tring-sdk 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.
- tring_sdk/__init__.py +77 -0
- tring_sdk/_client.py +569 -0
- tring_sdk/_errors.py +83 -0
- tring_sdk/_generated/__init__.py +4 -0
- tring_sdk/_generated/methods.py +1653 -0
- tring_sdk/_generated/operations.py +1056 -0
- tring_sdk/_generated/types.py +4232 -0
- tring_sdk/_helpers.py +132 -0
- tring_sdk/_version.py +6 -0
- tring_sdk/_webhooks.py +127 -0
- tring_sdk/py.typed +0 -0
- tring_sdk-0.1.0.dist-info/METADATA +71 -0
- tring_sdk-0.1.0.dist-info/RECORD +15 -0
- tring_sdk-0.1.0.dist-info/WHEEL +4 -0
- tring_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
tring_sdk/__init__.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Official Python SDK of the Tring API: Israeli receipts and invoices.
|
|
2
|
+
|
|
3
|
+
from tring_sdk import Tring
|
|
4
|
+
tring = Tring() # reads TRING_API_KEY; sandbox keys start with kbl_test_
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from ._client import AsyncTring, Tring
|
|
8
|
+
from ._errors import (
|
|
9
|
+
TringApiError,
|
|
10
|
+
TringApprovalDeclinedError,
|
|
11
|
+
TringConfigError,
|
|
12
|
+
TringConnectionError,
|
|
13
|
+
TringError,
|
|
14
|
+
TringOutcomeUnknownError,
|
|
15
|
+
TringSignatureError,
|
|
16
|
+
is_tring_api_error,
|
|
17
|
+
)
|
|
18
|
+
from ._generated import types
|
|
19
|
+
from ._generated.operations import OPERATIONS, SPEC_HASH, SPEC_VERSION, WEBHOOK_EVENT_TYPES
|
|
20
|
+
from ._helpers import (
|
|
21
|
+
DocType,
|
|
22
|
+
PaymentMethod,
|
|
23
|
+
amount,
|
|
24
|
+
file_media_type,
|
|
25
|
+
idempotency_key,
|
|
26
|
+
is_valid_idempotency_key,
|
|
27
|
+
key_environment,
|
|
28
|
+
public_key_part,
|
|
29
|
+
quantity,
|
|
30
|
+
redact_keys,
|
|
31
|
+
today_in_israel,
|
|
32
|
+
)
|
|
33
|
+
from ._version import PRODUCTION_BASE_URL, SANDBOX_BASE_URL, __version__
|
|
34
|
+
from ._webhooks import (
|
|
35
|
+
DEFAULT_SIGNATURE_SCHEME,
|
|
36
|
+
SignatureScheme,
|
|
37
|
+
construct_webhook_event,
|
|
38
|
+
sign_webhook_payload,
|
|
39
|
+
verify_webhook_signature,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"Tring",
|
|
44
|
+
"AsyncTring",
|
|
45
|
+
"TringError",
|
|
46
|
+
"TringApiError",
|
|
47
|
+
"TringConfigError",
|
|
48
|
+
"TringConnectionError",
|
|
49
|
+
"TringOutcomeUnknownError",
|
|
50
|
+
"TringApprovalDeclinedError",
|
|
51
|
+
"TringSignatureError",
|
|
52
|
+
"is_tring_api_error",
|
|
53
|
+
"DocType",
|
|
54
|
+
"PaymentMethod",
|
|
55
|
+
"amount",
|
|
56
|
+
"quantity",
|
|
57
|
+
"today_in_israel",
|
|
58
|
+
"idempotency_key",
|
|
59
|
+
"file_media_type",
|
|
60
|
+
"is_valid_idempotency_key",
|
|
61
|
+
"key_environment",
|
|
62
|
+
"public_key_part",
|
|
63
|
+
"redact_keys",
|
|
64
|
+
"verify_webhook_signature",
|
|
65
|
+
"construct_webhook_event",
|
|
66
|
+
"sign_webhook_payload",
|
|
67
|
+
"SignatureScheme",
|
|
68
|
+
"DEFAULT_SIGNATURE_SCHEME",
|
|
69
|
+
"OPERATIONS",
|
|
70
|
+
"WEBHOOK_EVENT_TYPES",
|
|
71
|
+
"SPEC_VERSION",
|
|
72
|
+
"SPEC_HASH",
|
|
73
|
+
"SANDBOX_BASE_URL",
|
|
74
|
+
"PRODUCTION_BASE_URL",
|
|
75
|
+
"types",
|
|
76
|
+
"__version__",
|
|
77
|
+
]
|
tring_sdk/_client.py
ADDED
|
@@ -0,0 +1,569 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import platform
|
|
4
|
+
import random
|
|
5
|
+
import time
|
|
6
|
+
from typing import (
|
|
7
|
+
Any,
|
|
8
|
+
AsyncIterator,
|
|
9
|
+
Awaitable,
|
|
10
|
+
Callable,
|
|
11
|
+
Dict,
|
|
12
|
+
Iterator,
|
|
13
|
+
List,
|
|
14
|
+
Mapping,
|
|
15
|
+
Optional,
|
|
16
|
+
Tuple,
|
|
17
|
+
TypeVar,
|
|
18
|
+
Union,
|
|
19
|
+
)
|
|
20
|
+
from urllib.parse import quote
|
|
21
|
+
|
|
22
|
+
import httpx
|
|
23
|
+
|
|
24
|
+
from ._errors import (
|
|
25
|
+
TringApiError,
|
|
26
|
+
TringApprovalDeclinedError,
|
|
27
|
+
TringConfigError,
|
|
28
|
+
TringConnectionError,
|
|
29
|
+
TringOutcomeUnknownError,
|
|
30
|
+
)
|
|
31
|
+
from ._generated import types as T
|
|
32
|
+
from ._generated.methods import AsyncGeneratedOperations, GeneratedOperations
|
|
33
|
+
from ._generated.operations import OPERATIONS, Operation
|
|
34
|
+
from ._helpers import file_media_type, is_valid_idempotency_key, key_environment, public_key_part
|
|
35
|
+
from ._version import PRODUCTION_BASE_URL, SANDBOX_BASE_URL, __version__
|
|
36
|
+
|
|
37
|
+
Item = TypeVar("Item")
|
|
38
|
+
Page = Mapping[str, Any]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class _Settings:
|
|
42
|
+
"""What a sync and an async client share: configuration, building a request, reading an answer."""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
api_key: Optional[str],
|
|
47
|
+
base_url: Optional[str],
|
|
48
|
+
timeout: float,
|
|
49
|
+
max_retries: int,
|
|
50
|
+
confirm_max_retries: int,
|
|
51
|
+
retry_base_delay: float,
|
|
52
|
+
max_retry_delay: float,
|
|
53
|
+
app_info: Optional[str],
|
|
54
|
+
) -> None:
|
|
55
|
+
key = api_key if api_key is not None else os.environ.get("TRING_API_KEY")
|
|
56
|
+
if not key:
|
|
57
|
+
raise TringConfigError(
|
|
58
|
+
"No API key: pass api_key= or set TRING_API_KEY. Sandbox keys start with kbl_test_."
|
|
59
|
+
)
|
|
60
|
+
if any(c.isspace() for c in key):
|
|
61
|
+
raise TringConfigError("The API key holds whitespace; copy it again without spaces or line breaks.")
|
|
62
|
+
self.environment = key_environment(key)
|
|
63
|
+
url = base_url or os.environ.get("TRING_BASE_URL")
|
|
64
|
+
if not url:
|
|
65
|
+
if self.environment == "sandbox":
|
|
66
|
+
url = SANDBOX_BASE_URL
|
|
67
|
+
elif self.environment == "production":
|
|
68
|
+
url = PRODUCTION_BASE_URL
|
|
69
|
+
else:
|
|
70
|
+
raise TringConfigError("Unknown key prefix; pass base_url= for this deployment.")
|
|
71
|
+
url = url.rstrip("/")
|
|
72
|
+
if self.environment == "sandbox" and url == PRODUCTION_BASE_URL:
|
|
73
|
+
raise TringConfigError(f"A sandbox key ({public_key_part(key)}) does not work against production ({url}).")
|
|
74
|
+
if self.environment == "production" and url == SANDBOX_BASE_URL:
|
|
75
|
+
raise TringConfigError(f"A production key ({public_key_part(key)}) does not work against the sandbox ({url}).")
|
|
76
|
+
self.base_url = url
|
|
77
|
+
self._api_key = key
|
|
78
|
+
self.timeout = timeout
|
|
79
|
+
self.max_retries = max_retries
|
|
80
|
+
self.confirm_max_retries = confirm_max_retries
|
|
81
|
+
self.retry_base_delay = retry_base_delay
|
|
82
|
+
self.max_retry_delay = max_retry_delay
|
|
83
|
+
self.user_agent = f"tring-python/{__version__} python/{platform.python_version()}" + (
|
|
84
|
+
f" {app_info}" if app_info else ""
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def key_id(self) -> str:
|
|
89
|
+
return public_key_part(self._api_key)
|
|
90
|
+
|
|
91
|
+
def build(
|
|
92
|
+
self,
|
|
93
|
+
operation_id: str,
|
|
94
|
+
path: Optional[Mapping[str, str]],
|
|
95
|
+
query: Optional[Mapping[str, Any]],
|
|
96
|
+
body: Any,
|
|
97
|
+
idempotency_key: Optional[str],
|
|
98
|
+
content_type: Optional[str] = None,
|
|
99
|
+
) -> Tuple[Operation, str, Dict[str, str], Dict[str, str], Optional[bytes]]:
|
|
100
|
+
op = OPERATIONS.get(operation_id)
|
|
101
|
+
if op is None:
|
|
102
|
+
raise TringConfigError(f"Unknown operation {operation_id}")
|
|
103
|
+
url_path = op.path
|
|
104
|
+
for name in op.path_params:
|
|
105
|
+
v = (path or {}).get(name)
|
|
106
|
+
if not isinstance(v, str) or not v:
|
|
107
|
+
raise TringConfigError(f"{operation_id}: {name} is required")
|
|
108
|
+
url_path = url_path.replace("{" + name + "}", quote(v, safe=""))
|
|
109
|
+
params: Dict[str, str] = {}
|
|
110
|
+
wire_names = set(op.query.values())
|
|
111
|
+
for k, v in (query or {}).items():
|
|
112
|
+
if v is None:
|
|
113
|
+
continue
|
|
114
|
+
if k not in wire_names:
|
|
115
|
+
raise TringConfigError(f"{operation_id}: unknown query parameter {k}")
|
|
116
|
+
params[k] = str(v).lower() if isinstance(v, bool) else str(v)
|
|
117
|
+
headers = {
|
|
118
|
+
"Authorization": f"Bearer {self._api_key}",
|
|
119
|
+
"Accept": "*/*" if op.response == "binary" else "application/json",
|
|
120
|
+
"User-Agent": self.user_agent,
|
|
121
|
+
}
|
|
122
|
+
if op.idempotency_key:
|
|
123
|
+
if idempotency_key is None:
|
|
124
|
+
if op.idempotency_key == "required":
|
|
125
|
+
raise TringConfigError(
|
|
126
|
+
f"{operation_id} needs idempotency_key=: one key per document, made from your order number "
|
|
127
|
+
'(for example "order-1001-receipt") and stored with the order before the first call.'
|
|
128
|
+
)
|
|
129
|
+
elif not is_valid_idempotency_key(idempotency_key):
|
|
130
|
+
raise TringConfigError("An Idempotency-Key is 1 to 255 printable ASCII characters with no spaces.")
|
|
131
|
+
else:
|
|
132
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
133
|
+
content: Optional[bytes] = None
|
|
134
|
+
if body is not None and op.body_kind == "binary":
|
|
135
|
+
content, sent_name = _file_bytes(operation_id, body)
|
|
136
|
+
media_type = content_type or file_media_type(content)
|
|
137
|
+
accepted = ", ".join(op.body_media_types)
|
|
138
|
+
if not media_type:
|
|
139
|
+
raise TringConfigError(
|
|
140
|
+
f"{operation_id}: the first bytes of the file are not those of {accepted}; "
|
|
141
|
+
"pass content_type= if it is one of them."
|
|
142
|
+
)
|
|
143
|
+
if media_type not in op.body_media_types:
|
|
144
|
+
raise TringConfigError(f"{operation_id} takes {accepted}, not {media_type}.")
|
|
145
|
+
if op.body_max_bytes is not None and len(content) > op.body_max_bytes:
|
|
146
|
+
raise TringConfigError(
|
|
147
|
+
f"{operation_id}: the file is {len(content)} bytes; the API takes at most "
|
|
148
|
+
f"{op.body_max_bytes} (PAYLOAD_TOO_LARGE)."
|
|
149
|
+
)
|
|
150
|
+
headers["Content-Type"] = media_type
|
|
151
|
+
# A path or an open file carries its own name: it names the stored file unless the call named it.
|
|
152
|
+
if sent_name and "fileName" in wire_names and "fileName" not in params:
|
|
153
|
+
params["fileName"] = sent_name
|
|
154
|
+
elif body is not None:
|
|
155
|
+
content = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
|
156
|
+
headers["Content-Type"] = "application/json"
|
|
157
|
+
elif op.body == "required":
|
|
158
|
+
raise TringConfigError(f"{operation_id}: a body is required")
|
|
159
|
+
return op, self.base_url + url_path, params, headers, content
|
|
160
|
+
|
|
161
|
+
def retries(self, op: Operation, max_retries: Optional[int]) -> int:
|
|
162
|
+
if max_retries is not None:
|
|
163
|
+
return max_retries
|
|
164
|
+
return self.confirm_max_retries if op.retry == "confirm" else self.max_retries
|
|
165
|
+
|
|
166
|
+
def backoff(self, attempt: int, retry_after: Optional[float]) -> float:
|
|
167
|
+
if retry_after is not None:
|
|
168
|
+
return float(min(retry_after, self.max_retry_delay))
|
|
169
|
+
base: float = min(self.retry_base_delay * (2.0**attempt), 8.0)
|
|
170
|
+
return base * (0.75 + random.random() * 0.5)
|
|
171
|
+
|
|
172
|
+
def read(self, operation_id: str, op: Operation, res: httpx.Response) -> Tuple[str, Any, Optional[float]]:
|
|
173
|
+
"""("ok", value) | ("retry-ambiguous" | "retry" | "final" | "final-ambiguous", error)."""
|
|
174
|
+
retry_after: Optional[float] = None
|
|
175
|
+
ra = res.headers.get("retry-after")
|
|
176
|
+
if ra and ra.isdigit():
|
|
177
|
+
retry_after = float(ra)
|
|
178
|
+
if res.is_success:
|
|
179
|
+
if op.response == "binary":
|
|
180
|
+
return "ok", res.content, None
|
|
181
|
+
if op.response == "empty" or res.status_code == 204:
|
|
182
|
+
return "ok", None, None
|
|
183
|
+
return "ok", res.json(), None
|
|
184
|
+
err_body: Any = None
|
|
185
|
+
try:
|
|
186
|
+
err_body = res.json().get("error")
|
|
187
|
+
except Exception:
|
|
188
|
+
err_body = None
|
|
189
|
+
method = op.method
|
|
190
|
+
if not isinstance(err_body, dict) or not isinstance(err_body.get("code"), str):
|
|
191
|
+
if res.status_code >= 500:
|
|
192
|
+
e: Exception = TringConnectionError(
|
|
193
|
+
operation_id,
|
|
194
|
+
method != "GET",
|
|
195
|
+
f"{res.status_code} without an answer of the API from {method} {op.path}",
|
|
196
|
+
)
|
|
197
|
+
return ("retry-ambiguous" if op.retry != "unsafe" else "final-ambiguous"), e, retry_after
|
|
198
|
+
return (
|
|
199
|
+
"final",
|
|
200
|
+
TringApiError(
|
|
201
|
+
status=res.status_code,
|
|
202
|
+
code=f"HTTP_{res.status_code}",
|
|
203
|
+
message=res.text[:200],
|
|
204
|
+
operation_id=operation_id,
|
|
205
|
+
),
|
|
206
|
+
retry_after,
|
|
207
|
+
)
|
|
208
|
+
code = err_body["code"]
|
|
209
|
+
error = TringApiError(
|
|
210
|
+
status=res.status_code,
|
|
211
|
+
code=code,
|
|
212
|
+
message=str(err_body.get("message", "")),
|
|
213
|
+
details=err_body.get("details") or {},
|
|
214
|
+
issues=err_body.get("issues") or [],
|
|
215
|
+
request_id=err_body.get("requestId") or res.headers.get("x-request-id"),
|
|
216
|
+
retry_after=retry_after,
|
|
217
|
+
operation_id=operation_id,
|
|
218
|
+
)
|
|
219
|
+
decision = _classify(res.status_code, code, error.details, op.retry)
|
|
220
|
+
if decision == "final":
|
|
221
|
+
return "final", error, retry_after
|
|
222
|
+
if decision == "ambiguous":
|
|
223
|
+
return "retry-ambiguous", error, retry_after
|
|
224
|
+
return "retry", error, retry_after
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _file_bytes(operation_id: str, body: Any) -> Tuple[bytes, Optional[str]]:
|
|
228
|
+
"""The bytes of a file given as bytes, a path, or a file opened in binary mode; and its name, when known."""
|
|
229
|
+
if isinstance(body, (bytes, bytearray, memoryview)):
|
|
230
|
+
return bytes(body), None
|
|
231
|
+
if isinstance(body, (str, os.PathLike)):
|
|
232
|
+
path = os.fspath(body)
|
|
233
|
+
with open(path, "rb") as f:
|
|
234
|
+
return f.read(), os.path.basename(path) or None
|
|
235
|
+
read = getattr(body, "read", None)
|
|
236
|
+
if callable(read):
|
|
237
|
+
data = read()
|
|
238
|
+
if not isinstance(data, (bytes, bytearray)):
|
|
239
|
+
raise TringConfigError(f"{operation_id}: open the file in binary mode (\"rb\").")
|
|
240
|
+
name = getattr(body, "name", None)
|
|
241
|
+
return bytes(data), (os.path.basename(name) or None) if isinstance(name, str) else None
|
|
242
|
+
raise TringConfigError(
|
|
243
|
+
f"{operation_id} takes the file itself: bytes, a path, or a file opened in binary mode, "
|
|
244
|
+
f"not {type(body).__name__}."
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _classify(status: int, code: str, details: Mapping[str, Any], policy: str) -> str:
|
|
249
|
+
if status == 429 and code == "RATE_LIMITED":
|
|
250
|
+
return "refused"
|
|
251
|
+
if status == 503 and code == "UNAVAILABLE":
|
|
252
|
+
return "refused"
|
|
253
|
+
if policy == "unsafe":
|
|
254
|
+
return "final"
|
|
255
|
+
if code == "OUTCOME_UNKNOWN":
|
|
256
|
+
return "ambiguous"
|
|
257
|
+
if code == "ISSUE_TIMEOUT":
|
|
258
|
+
return "transient"
|
|
259
|
+
if code == "RENDER_FAILED" and details.get("reason") in ("render-timeout", "browser-unavailable"):
|
|
260
|
+
return "transient"
|
|
261
|
+
if policy == "safe" and status in (502, 503, 504) and code != "AUTHORITY_NOT_CONFIGURED":
|
|
262
|
+
return "transient"
|
|
263
|
+
return "final"
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _finish(op: Operation, path: Optional[Mapping[str, str]], last: Tuple[str, Exception]) -> Exception:
|
|
267
|
+
kind, error = last
|
|
268
|
+
if op.retry == "confirm" and kind == "ambiguous":
|
|
269
|
+
out = TringOutcomeUnknownError((path or {}).get("draftId", ""))
|
|
270
|
+
out.__cause__ = error
|
|
271
|
+
return out
|
|
272
|
+
return error
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
class Tring(GeneratedOperations):
|
|
276
|
+
"""The Tring API client.
|
|
277
|
+
|
|
278
|
+
>>> tring = Tring() # reads TRING_API_KEY
|
|
279
|
+
>>> prepared = tring.prepare_draft(issuer_id, body, idempotency_key="order-1001-receipt")
|
|
280
|
+
>>> issued = tring.confirm_draft(prepared["draft"]["id"])
|
|
281
|
+
|
|
282
|
+
Every operation of the API is a method named by its operationId in snake_case. Reads and idempotent
|
|
283
|
+
requests are sent again when the answer is lost; a confirm is sent again until its outcome is known.
|
|
284
|
+
"""
|
|
285
|
+
|
|
286
|
+
def __init__(
|
|
287
|
+
self,
|
|
288
|
+
api_key: Optional[str] = None,
|
|
289
|
+
*,
|
|
290
|
+
base_url: Optional[str] = None,
|
|
291
|
+
timeout: float = 60.0,
|
|
292
|
+
max_retries: int = 2,
|
|
293
|
+
confirm_max_retries: int = 8,
|
|
294
|
+
retry_base_delay: float = 0.5,
|
|
295
|
+
max_retry_delay: float = 30.0,
|
|
296
|
+
app_info: Optional[str] = None,
|
|
297
|
+
http_client: Optional[httpx.Client] = None,
|
|
298
|
+
) -> None:
|
|
299
|
+
self._s = _Settings(
|
|
300
|
+
api_key, base_url, timeout, max_retries, confirm_max_retries, retry_base_delay, max_retry_delay, app_info
|
|
301
|
+
)
|
|
302
|
+
self._http = http_client or httpx.Client()
|
|
303
|
+
self._own_http = http_client is None
|
|
304
|
+
|
|
305
|
+
@property
|
|
306
|
+
def base_url(self) -> str:
|
|
307
|
+
return self._s.base_url
|
|
308
|
+
|
|
309
|
+
@property
|
|
310
|
+
def environment(self) -> str:
|
|
311
|
+
return self._s.environment
|
|
312
|
+
|
|
313
|
+
@property
|
|
314
|
+
def key_id(self) -> str:
|
|
315
|
+
"""The public part of the key in use, safe to log."""
|
|
316
|
+
return self._s.key_id
|
|
317
|
+
|
|
318
|
+
def __repr__(self) -> str:
|
|
319
|
+
return f"Tring(base_url={self.base_url!r}, environment={self.environment!r}, key_id={self.key_id!r})"
|
|
320
|
+
|
|
321
|
+
def close(self) -> None:
|
|
322
|
+
if self._own_http:
|
|
323
|
+
self._http.close()
|
|
324
|
+
|
|
325
|
+
def __enter__(self) -> "Tring":
|
|
326
|
+
return self
|
|
327
|
+
|
|
328
|
+
def __exit__(self, *exc: Any) -> None:
|
|
329
|
+
self.close()
|
|
330
|
+
|
|
331
|
+
def request(
|
|
332
|
+
self,
|
|
333
|
+
operation_id: str,
|
|
334
|
+
*,
|
|
335
|
+
path: Optional[Mapping[str, str]] = None,
|
|
336
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
337
|
+
body: Any = None,
|
|
338
|
+
idempotency_key: Optional[str] = None,
|
|
339
|
+
timeout: Optional[float] = None,
|
|
340
|
+
max_retries: Optional[int] = None,
|
|
341
|
+
content_type: Optional[str] = None,
|
|
342
|
+
) -> Any:
|
|
343
|
+
"""Calls any operation by its operationId (camelCase, as in openapi.json); query names as on the wire."""
|
|
344
|
+
return self._call(
|
|
345
|
+
operation_id,
|
|
346
|
+
path=dict(path or {}),
|
|
347
|
+
query=dict(query or {}),
|
|
348
|
+
body=body,
|
|
349
|
+
idempotency_key=idempotency_key,
|
|
350
|
+
timeout=timeout,
|
|
351
|
+
max_retries=max_retries,
|
|
352
|
+
content_type=content_type,
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
def issue(
|
|
356
|
+
self,
|
|
357
|
+
issuer_id: str,
|
|
358
|
+
body: T.PrepareRequest,
|
|
359
|
+
*,
|
|
360
|
+
idempotency_key: str,
|
|
361
|
+
approve: Optional[Callable[[T.Draft], bool]] = None,
|
|
362
|
+
) -> T.Document:
|
|
363
|
+
"""Prepares and confirms a document.
|
|
364
|
+
|
|
365
|
+
``approve`` is called with the draft before it is confirmed; return False to stop (nothing is
|
|
366
|
+
issued, TringApprovalDeclinedError is raised). When the key was already used for this request and
|
|
367
|
+
the draft became a document, that document is returned and nothing is issued again.
|
|
368
|
+
"""
|
|
369
|
+
prepared = self.prepare_draft(issuer_id, body, idempotency_key=idempotency_key)
|
|
370
|
+
if prepared["outcome"] == "document" and "document" in prepared:
|
|
371
|
+
return prepared["document"]
|
|
372
|
+
draft = prepared["draft"]
|
|
373
|
+
if approve is not None and not approve(draft):
|
|
374
|
+
raise TringApprovalDeclinedError(draft["id"])
|
|
375
|
+
return self.confirm_draft(draft["id"])["document"]
|
|
376
|
+
|
|
377
|
+
def paginate(self, fetch_page: Callable[[Optional[str]], Page]) -> Iterator[Any]:
|
|
378
|
+
"""Walks every page: ``for d in tring.paginate(lambda c: tring.list_documents(id, cursor=c))``."""
|
|
379
|
+
cursor: Optional[str] = None
|
|
380
|
+
while True:
|
|
381
|
+
page = fetch_page(cursor)
|
|
382
|
+
yield from page["items"]
|
|
383
|
+
cursor = page.get("nextCursor")
|
|
384
|
+
if not cursor:
|
|
385
|
+
return
|
|
386
|
+
|
|
387
|
+
def _call(
|
|
388
|
+
self,
|
|
389
|
+
operation_id: str,
|
|
390
|
+
*,
|
|
391
|
+
path: Dict[str, str],
|
|
392
|
+
query: Dict[str, Any],
|
|
393
|
+
body: Any,
|
|
394
|
+
idempotency_key: Optional[str],
|
|
395
|
+
timeout: Optional[float],
|
|
396
|
+
max_retries: Optional[int],
|
|
397
|
+
content_type: Optional[str] = None,
|
|
398
|
+
) -> Any:
|
|
399
|
+
op, url, params, headers, content = self._s.build(operation_id, path, query, body, idempotency_key, content_type)
|
|
400
|
+
retries = self._s.retries(op, max_retries)
|
|
401
|
+
last: Tuple[str, Exception] = ("answer", TringConfigError("no attempt"))
|
|
402
|
+
for attempt in range(retries + 1):
|
|
403
|
+
try:
|
|
404
|
+
res = self._http.request(
|
|
405
|
+
op.method, url, params=params, headers=headers, content=content, timeout=timeout or self._s.timeout
|
|
406
|
+
)
|
|
407
|
+
except httpx.TransportError as exc:
|
|
408
|
+
last = (
|
|
409
|
+
"ambiguous",
|
|
410
|
+
TringConnectionError(operation_id, op.method != "GET", f"No answer from {op.method} {op.path}: {exc}"),
|
|
411
|
+
)
|
|
412
|
+
if op.retry != "unsafe" and attempt < retries:
|
|
413
|
+
time.sleep(self._s.backoff(attempt, None))
|
|
414
|
+
continue
|
|
415
|
+
break
|
|
416
|
+
kind, value, retry_after = self._s.read(operation_id, op, res)
|
|
417
|
+
if kind == "ok":
|
|
418
|
+
return value
|
|
419
|
+
last = ("ambiguous" if kind.endswith("ambiguous") else "answer", value)
|
|
420
|
+
if kind in ("retry", "retry-ambiguous") and attempt < retries:
|
|
421
|
+
time.sleep(self._s.backoff(attempt, retry_after))
|
|
422
|
+
continue
|
|
423
|
+
break
|
|
424
|
+
raise _finish(op, path, last)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
class AsyncTring(AsyncGeneratedOperations):
|
|
428
|
+
"""The asynchronous Tring API client. Same methods as Tring, awaited."""
|
|
429
|
+
|
|
430
|
+
def __init__(
|
|
431
|
+
self,
|
|
432
|
+
api_key: Optional[str] = None,
|
|
433
|
+
*,
|
|
434
|
+
base_url: Optional[str] = None,
|
|
435
|
+
timeout: float = 60.0,
|
|
436
|
+
max_retries: int = 2,
|
|
437
|
+
confirm_max_retries: int = 8,
|
|
438
|
+
retry_base_delay: float = 0.5,
|
|
439
|
+
max_retry_delay: float = 30.0,
|
|
440
|
+
app_info: Optional[str] = None,
|
|
441
|
+
http_client: Optional[httpx.AsyncClient] = None,
|
|
442
|
+
) -> None:
|
|
443
|
+
self._s = _Settings(
|
|
444
|
+
api_key, base_url, timeout, max_retries, confirm_max_retries, retry_base_delay, max_retry_delay, app_info
|
|
445
|
+
)
|
|
446
|
+
self._http = http_client or httpx.AsyncClient()
|
|
447
|
+
self._own_http = http_client is None
|
|
448
|
+
|
|
449
|
+
@property
|
|
450
|
+
def base_url(self) -> str:
|
|
451
|
+
return self._s.base_url
|
|
452
|
+
|
|
453
|
+
@property
|
|
454
|
+
def environment(self) -> str:
|
|
455
|
+
return self._s.environment
|
|
456
|
+
|
|
457
|
+
@property
|
|
458
|
+
def key_id(self) -> str:
|
|
459
|
+
return self._s.key_id
|
|
460
|
+
|
|
461
|
+
def __repr__(self) -> str:
|
|
462
|
+
return f"AsyncTring(base_url={self.base_url!r}, environment={self.environment!r}, key_id={self.key_id!r})"
|
|
463
|
+
|
|
464
|
+
async def aclose(self) -> None:
|
|
465
|
+
if self._own_http:
|
|
466
|
+
await self._http.aclose()
|
|
467
|
+
|
|
468
|
+
async def __aenter__(self) -> "AsyncTring":
|
|
469
|
+
return self
|
|
470
|
+
|
|
471
|
+
async def __aexit__(self, *exc: Any) -> None:
|
|
472
|
+
await self.aclose()
|
|
473
|
+
|
|
474
|
+
async def request(
|
|
475
|
+
self,
|
|
476
|
+
operation_id: str,
|
|
477
|
+
*,
|
|
478
|
+
path: Optional[Mapping[str, str]] = None,
|
|
479
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
480
|
+
body: Any = None,
|
|
481
|
+
idempotency_key: Optional[str] = None,
|
|
482
|
+
timeout: Optional[float] = None,
|
|
483
|
+
max_retries: Optional[int] = None,
|
|
484
|
+
content_type: Optional[str] = None,
|
|
485
|
+
) -> Any:
|
|
486
|
+
return await self._call(
|
|
487
|
+
operation_id,
|
|
488
|
+
path=dict(path or {}),
|
|
489
|
+
query=dict(query or {}),
|
|
490
|
+
body=body,
|
|
491
|
+
idempotency_key=idempotency_key,
|
|
492
|
+
timeout=timeout,
|
|
493
|
+
max_retries=max_retries,
|
|
494
|
+
content_type=content_type,
|
|
495
|
+
)
|
|
496
|
+
|
|
497
|
+
async def issue(
|
|
498
|
+
self,
|
|
499
|
+
issuer_id: str,
|
|
500
|
+
body: T.PrepareRequest,
|
|
501
|
+
*,
|
|
502
|
+
idempotency_key: str,
|
|
503
|
+
approve: Optional[Callable[[T.Draft], Union[bool, Awaitable[bool]]]] = None,
|
|
504
|
+
) -> T.Document:
|
|
505
|
+
prepared = await self.prepare_draft(issuer_id, body, idempotency_key=idempotency_key)
|
|
506
|
+
if prepared["outcome"] == "document" and "document" in prepared:
|
|
507
|
+
return prepared["document"]
|
|
508
|
+
draft = prepared["draft"]
|
|
509
|
+
if approve is not None:
|
|
510
|
+
ok = approve(draft)
|
|
511
|
+
if not isinstance(ok, bool):
|
|
512
|
+
ok = await ok
|
|
513
|
+
if not ok:
|
|
514
|
+
raise TringApprovalDeclinedError(draft["id"])
|
|
515
|
+
return (await self.confirm_draft(draft["id"]))["document"]
|
|
516
|
+
|
|
517
|
+
async def paginate(self, fetch_page: Callable[[Optional[str]], Awaitable[Page]]) -> AsyncIterator[Any]:
|
|
518
|
+
cursor: Optional[str] = None
|
|
519
|
+
while True:
|
|
520
|
+
page = await fetch_page(cursor)
|
|
521
|
+
for item in page["items"]:
|
|
522
|
+
yield item
|
|
523
|
+
cursor = page.get("nextCursor")
|
|
524
|
+
if not cursor:
|
|
525
|
+
return
|
|
526
|
+
|
|
527
|
+
async def _call(
|
|
528
|
+
self,
|
|
529
|
+
operation_id: str,
|
|
530
|
+
*,
|
|
531
|
+
path: Dict[str, str],
|
|
532
|
+
query: Dict[str, Any],
|
|
533
|
+
body: Any,
|
|
534
|
+
idempotency_key: Optional[str],
|
|
535
|
+
timeout: Optional[float],
|
|
536
|
+
max_retries: Optional[int],
|
|
537
|
+
content_type: Optional[str] = None,
|
|
538
|
+
) -> Any:
|
|
539
|
+
import anyio
|
|
540
|
+
|
|
541
|
+
op, url, params, headers, content = self._s.build(operation_id, path, query, body, idempotency_key, content_type)
|
|
542
|
+
retries = self._s.retries(op, max_retries)
|
|
543
|
+
last: Tuple[str, Exception] = ("answer", TringConfigError("no attempt"))
|
|
544
|
+
for attempt in range(retries + 1):
|
|
545
|
+
try:
|
|
546
|
+
res = await self._http.request(
|
|
547
|
+
op.method, url, params=params, headers=headers, content=content, timeout=timeout or self._s.timeout
|
|
548
|
+
)
|
|
549
|
+
except httpx.TransportError as exc:
|
|
550
|
+
last = (
|
|
551
|
+
"ambiguous",
|
|
552
|
+
TringConnectionError(operation_id, op.method != "GET", f"No answer from {op.method} {op.path}: {exc}"),
|
|
553
|
+
)
|
|
554
|
+
if op.retry != "unsafe" and attempt < retries:
|
|
555
|
+
await anyio.sleep(self._s.backoff(attempt, None))
|
|
556
|
+
continue
|
|
557
|
+
break
|
|
558
|
+
kind, value, retry_after = self._s.read(operation_id, op, res)
|
|
559
|
+
if kind == "ok":
|
|
560
|
+
return value
|
|
561
|
+
last = ("ambiguous" if kind.endswith("ambiguous") else "answer", value)
|
|
562
|
+
if kind in ("retry", "retry-ambiguous") and attempt < retries:
|
|
563
|
+
await anyio.sleep(self._s.backoff(attempt, retry_after))
|
|
564
|
+
continue
|
|
565
|
+
break
|
|
566
|
+
raise _finish(op, path, last)
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
__all__: List[str] = ["Tring", "AsyncTring"]
|