flowabbit 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.
- flowabbit/__init__.py +51 -0
- flowabbit/client.py +471 -0
- flowabbit/http_client.py +87 -0
- flowabbit/resources/__init__.py +1 -0
- flowabbit/resources/bms.py +29 -0
- flowabbit/resources/doc.py +92 -0
- flowabbit/resources/tms.py +245 -0
- flowabbit/runtime/__init__.py +66 -0
- flowabbit/runtime/errors.py +164 -0
- flowabbit/runtime/rate_limit.py +61 -0
- flowabbit/runtime/retry.py +173 -0
- flowabbit/runtime/token_manager.py +102 -0
- flowabbit/runtime/webhook_verifier.py +141 -0
- flowabbit-1.0.0.dist-info/METADATA +330 -0
- flowabbit-1.0.0.dist-info/RECORD +18 -0
- flowabbit-1.0.0.dist-info/WHEEL +5 -0
- flowabbit-1.0.0.dist-info/licenses/LICENSE +201 -0
- flowabbit-1.0.0.dist-info/top_level.txt +1 -0
flowabbit/__init__.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Flowabbit Python SDK. See README.md."""
|
|
2
|
+
from .client import ApiResponse, BinaryResponse, FlowabbitClient, SDK_VERSION
|
|
3
|
+
from .http_client import HttpClient, HttpResponse, UrllibHttpClient
|
|
4
|
+
from .runtime import (
|
|
5
|
+
AccessToken,
|
|
6
|
+
FlowabbitApiError,
|
|
7
|
+
FlowabbitAuthError,
|
|
8
|
+
FlowabbitBatchEntryError,
|
|
9
|
+
FlowabbitError,
|
|
10
|
+
FlowabbitNetworkError,
|
|
11
|
+
FlowabbitOAuthError,
|
|
12
|
+
FlowabbitRateLimitError,
|
|
13
|
+
FlowabbitServerError,
|
|
14
|
+
FlowabbitValidationError,
|
|
15
|
+
FlowabbitWebhookDuplicateEventError,
|
|
16
|
+
FlowabbitWebhookSignatureError,
|
|
17
|
+
RateLimitInfo,
|
|
18
|
+
RetryPolicy,
|
|
19
|
+
TokenManager,
|
|
20
|
+
WebhookEvent,
|
|
21
|
+
WebhookVerifier,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
__version__ = SDK_VERSION
|
|
25
|
+
__all__ = [
|
|
26
|
+
"AccessToken",
|
|
27
|
+
"ApiResponse",
|
|
28
|
+
"BinaryResponse",
|
|
29
|
+
"FlowabbitApiError",
|
|
30
|
+
"FlowabbitAuthError",
|
|
31
|
+
"FlowabbitBatchEntryError",
|
|
32
|
+
"FlowabbitClient",
|
|
33
|
+
"FlowabbitError",
|
|
34
|
+
"FlowabbitNetworkError",
|
|
35
|
+
"FlowabbitOAuthError",
|
|
36
|
+
"FlowabbitRateLimitError",
|
|
37
|
+
"FlowabbitServerError",
|
|
38
|
+
"FlowabbitValidationError",
|
|
39
|
+
"FlowabbitWebhookDuplicateEventError",
|
|
40
|
+
"FlowabbitWebhookSignatureError",
|
|
41
|
+
"HttpClient",
|
|
42
|
+
"HttpResponse",
|
|
43
|
+
"RateLimitInfo",
|
|
44
|
+
"RetryPolicy",
|
|
45
|
+
"SDK_VERSION",
|
|
46
|
+
"TokenManager",
|
|
47
|
+
"UrllibHttpClient",
|
|
48
|
+
"WebhookEvent",
|
|
49
|
+
"WebhookVerifier",
|
|
50
|
+
"__version__",
|
|
51
|
+
]
|
flowabbit/client.py
ADDED
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
"""FlowabbitClient — entry class wiring the runtime helpers + resource namespaces.
|
|
2
|
+
|
|
3
|
+
Every Open API operation has a method: ``client.me()`` plus the ``client.tms``
|
|
4
|
+
namespaces (origins, rates, shipments, trackers, manifests, handovers), the
|
|
5
|
+
``client.bms`` namespace (accounts) and the ``client.doc`` namespace
|
|
6
|
+
(documents). The
|
|
7
|
+
OAuth token operation is handled by ``TokenManager``.
|
|
8
|
+
``RequestSigner`` is **deliberately not surfaced** (no public placeholder).
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
import time
|
|
14
|
+
from typing import Any, Mapping
|
|
15
|
+
from urllib.parse import unquote, urljoin, urlsplit
|
|
16
|
+
|
|
17
|
+
from .http_client import HttpClient, HttpResponse, UrllibHttpClient
|
|
18
|
+
from .runtime.errors import (
|
|
19
|
+
FlowabbitApiError,
|
|
20
|
+
FlowabbitError,
|
|
21
|
+
FlowabbitNetworkError,
|
|
22
|
+
from_response,
|
|
23
|
+
)
|
|
24
|
+
from .runtime.rate_limit import RateLimitInfo, from_headers as _rate_from_headers
|
|
25
|
+
from .runtime.retry import RetryPolicy
|
|
26
|
+
from .runtime.token_manager import TokenManager
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# Path prefix of every Open API operation, the token endpoint included.
|
|
30
|
+
# ``base_url`` is only the domain the customer uses (there is no default
|
|
31
|
+
# domain); request URLs are ``base_url + API_PREFIX + <operation path>``.
|
|
32
|
+
API_PREFIX = "/api/v1"
|
|
33
|
+
SDK_VERSION = "1.0.0"
|
|
34
|
+
|
|
35
|
+
# A download may answer with a redirect to a short-lived signed storage link.
|
|
36
|
+
_REDIRECT_STATUSES = (301, 302, 303, 307, 308)
|
|
37
|
+
_MAX_REDIRECTS = 5
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _domain_origin(base_url: str) -> str:
|
|
41
|
+
"""``base_url`` without trailing ``/``; it must be a domain only
|
|
42
|
+
(``https://example.com``), because the SDK adds ``API_PREFIX`` itself."""
|
|
43
|
+
origin = base_url.rstrip("/")
|
|
44
|
+
parts = urlsplit(origin)
|
|
45
|
+
if (
|
|
46
|
+
parts.scheme not in ("http", "https")
|
|
47
|
+
or not parts.netloc
|
|
48
|
+
or parts.path
|
|
49
|
+
or parts.query
|
|
50
|
+
or parts.fragment
|
|
51
|
+
):
|
|
52
|
+
raise ValueError(
|
|
53
|
+
f"base_url must be the domain only, such as https://example.com, "
|
|
54
|
+
f"without a path (the SDK adds {API_PREFIX}); got {base_url!r}"
|
|
55
|
+
)
|
|
56
|
+
return origin
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ApiResponse.data typing:
|
|
60
|
+
# data is the **parsed JSON body** — raw map / list / null.
|
|
61
|
+
#
|
|
62
|
+
# Cross-language alignment:
|
|
63
|
+
# Python dict[str, Any] | list[Any] | None
|
|
64
|
+
# Java Map<String, Object> | List<Object> | null (or JsonNode)
|
|
65
|
+
# Go map[string]any | []any | nil
|
|
66
|
+
# PHP array | null
|
|
67
|
+
ApiResponseData = dict[str, Any] | list[Any] | None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ApiResponse:
|
|
71
|
+
"""Wrapper exposing ``data`` (parsed JSON) and ``rate_limit`` info.
|
|
72
|
+
|
|
73
|
+
``data`` is the **untyped** parsed JSON body — either a ``dict`` (object
|
|
74
|
+
response), a ``list`` (array response), or ``None`` (204 / empty body).
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
__slots__ = ("data", "rate_limit", "request_id", "http_status", "raw")
|
|
78
|
+
|
|
79
|
+
def __init__(
|
|
80
|
+
self,
|
|
81
|
+
*,
|
|
82
|
+
data: ApiResponseData,
|
|
83
|
+
rate_limit: RateLimitInfo,
|
|
84
|
+
request_id: str,
|
|
85
|
+
http_status: int,
|
|
86
|
+
raw: HttpResponse,
|
|
87
|
+
) -> None:
|
|
88
|
+
self.data: ApiResponseData = data
|
|
89
|
+
self.rate_limit = rate_limit
|
|
90
|
+
self.request_id = request_id
|
|
91
|
+
self.http_status = http_status
|
|
92
|
+
self.raw = raw
|
|
93
|
+
|
|
94
|
+
def __repr__(self) -> str:
|
|
95
|
+
return (
|
|
96
|
+
f"ApiResponse(http_status={self.http_status}, "
|
|
97
|
+
f"rate_limit={self.rate_limit}, request_id={self.request_id!r})"
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class BinaryResponse:
|
|
102
|
+
"""A downloaded file (a document file or a merged PDF).
|
|
103
|
+
|
|
104
|
+
``content`` is the response body as bytes, never parsed as JSON;
|
|
105
|
+
``content_type`` is the ``Content-Type`` header ("" when absent);
|
|
106
|
+
``filename`` comes from ``Content-Disposition`` when the server sends one
|
|
107
|
+
(``None`` otherwise) and is the server's suggestion only: sanitize it
|
|
108
|
+
before using it as a local path. When the API redirected to a signed
|
|
109
|
+
storage link, the headers (and ``raw``) are those of the storage response.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
__slots__ = ("content", "content_type", "filename", "rate_limit", "request_id", "http_status", "raw")
|
|
113
|
+
|
|
114
|
+
def __init__(
|
|
115
|
+
self,
|
|
116
|
+
*,
|
|
117
|
+
content: bytes,
|
|
118
|
+
content_type: str,
|
|
119
|
+
filename: str | None,
|
|
120
|
+
rate_limit: RateLimitInfo,
|
|
121
|
+
request_id: str,
|
|
122
|
+
http_status: int,
|
|
123
|
+
raw: HttpResponse,
|
|
124
|
+
) -> None:
|
|
125
|
+
self.content = content
|
|
126
|
+
self.content_type = content_type
|
|
127
|
+
self.filename = filename
|
|
128
|
+
self.rate_limit = rate_limit
|
|
129
|
+
self.request_id = request_id
|
|
130
|
+
self.http_status = http_status
|
|
131
|
+
self.raw = raw
|
|
132
|
+
|
|
133
|
+
def __repr__(self) -> str:
|
|
134
|
+
return (
|
|
135
|
+
f"BinaryResponse(http_status={self.http_status}, content_type={self.content_type!r}, "
|
|
136
|
+
f"bytes={len(self.content)}, request_id={self.request_id!r})"
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class FlowabbitClient:
|
|
141
|
+
def __init__(
|
|
142
|
+
self,
|
|
143
|
+
*,
|
|
144
|
+
client_id: str,
|
|
145
|
+
client_secret: str,
|
|
146
|
+
base_url: str,
|
|
147
|
+
timeout_seconds: float = 30.0,
|
|
148
|
+
max_retries: int = 3,
|
|
149
|
+
user_agent_extra: str = "",
|
|
150
|
+
http_client: HttpClient | None = None,
|
|
151
|
+
retry_policy: RetryPolicy | None = None,
|
|
152
|
+
token_manager: TokenManager | None = None,
|
|
153
|
+
clock: object = time,
|
|
154
|
+
) -> None:
|
|
155
|
+
# base_url is required (no default). It is the domain the
|
|
156
|
+
# customer calls the API on; failing to pass it raises here rather
|
|
157
|
+
# than letting the SDK fan out requests to a guessed host.
|
|
158
|
+
if not client_id or not client_secret:
|
|
159
|
+
raise ValueError("client_id and client_secret are required")
|
|
160
|
+
if not base_url:
|
|
161
|
+
raise ValueError("base_url is required (no default placeholder)")
|
|
162
|
+
self._base_url = _domain_origin(base_url)
|
|
163
|
+
self._timeout = timeout_seconds
|
|
164
|
+
self._http: HttpClient = http_client or UrllibHttpClient(default_timeout_seconds=timeout_seconds)
|
|
165
|
+
self._retry = retry_policy or RetryPolicy(max_retries=max_retries)
|
|
166
|
+
self._token_manager = token_manager or TokenManager(
|
|
167
|
+
client_id=client_id,
|
|
168
|
+
client_secret=client_secret,
|
|
169
|
+
token_url=self._build_url("/oauth/token"),
|
|
170
|
+
http_client=self._http,
|
|
171
|
+
clock=clock,
|
|
172
|
+
)
|
|
173
|
+
self._user_agent = self._build_user_agent(user_agent_extra)
|
|
174
|
+
self._clock = clock
|
|
175
|
+
|
|
176
|
+
from .resources.bms import BmsResource
|
|
177
|
+
from .resources.doc import DocResource
|
|
178
|
+
from .resources.tms import TmsResource
|
|
179
|
+
|
|
180
|
+
self.tms = TmsResource(self)
|
|
181
|
+
self.bms = BmsResource(self)
|
|
182
|
+
self.doc = DocResource(self)
|
|
183
|
+
|
|
184
|
+
@staticmethod
|
|
185
|
+
def _build_user_agent(extra: str) -> str:
|
|
186
|
+
ua = f"flowabbit-sdk-python/{SDK_VERSION}"
|
|
187
|
+
return f"{ua} {extra}".strip() if extra else ua
|
|
188
|
+
|
|
189
|
+
@property
|
|
190
|
+
def token_manager(self) -> TokenManager:
|
|
191
|
+
return self._token_manager
|
|
192
|
+
|
|
193
|
+
@property
|
|
194
|
+
def retry_policy(self) -> RetryPolicy:
|
|
195
|
+
return self._retry
|
|
196
|
+
|
|
197
|
+
def me(self) -> ApiResponse:
|
|
198
|
+
"""GET /me: the client, App, customer and scopes behind the credentials."""
|
|
199
|
+
return self._request(method="GET", path="/me")
|
|
200
|
+
|
|
201
|
+
def _build_url(self, path: str) -> str:
|
|
202
|
+
if path.startswith("http://") or path.startswith("https://"):
|
|
203
|
+
return path
|
|
204
|
+
if not path.startswith("/"):
|
|
205
|
+
path = "/" + path
|
|
206
|
+
return f"{self._base_url}{API_PREFIX}{path}"
|
|
207
|
+
|
|
208
|
+
def _request(
|
|
209
|
+
self,
|
|
210
|
+
*,
|
|
211
|
+
method: str,
|
|
212
|
+
path: str,
|
|
213
|
+
body: Any = None,
|
|
214
|
+
replay_safe: bool = False,
|
|
215
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
216
|
+
) -> ApiResponse:
|
|
217
|
+
resp = self._send(
|
|
218
|
+
method=method,
|
|
219
|
+
path=path,
|
|
220
|
+
body=body,
|
|
221
|
+
replay_safe=replay_safe,
|
|
222
|
+
accept="application/json",
|
|
223
|
+
extra_headers=extra_headers,
|
|
224
|
+
)
|
|
225
|
+
return self._build_response(resp)
|
|
226
|
+
|
|
227
|
+
def _download(self, *, path: str) -> BinaryResponse:
|
|
228
|
+
"""GET a file; the body is returned as bytes and never parsed as JSON.
|
|
229
|
+
Errors still come back as Problem Details and map to the typed errors.
|
|
230
|
+
|
|
231
|
+
A redirect (a short-lived signed storage link in ``Location``) is
|
|
232
|
+
followed here, without the ``Authorization`` header: the access token
|
|
233
|
+
is only ever sent to the API domain."""
|
|
234
|
+
resp = self._send(
|
|
235
|
+
method="GET",
|
|
236
|
+
path=path,
|
|
237
|
+
body=None,
|
|
238
|
+
replay_safe=False,
|
|
239
|
+
accept="*/*",
|
|
240
|
+
extra_headers=None,
|
|
241
|
+
follow_redirects=True,
|
|
242
|
+
)
|
|
243
|
+
return self._build_binary_response(resp)
|
|
244
|
+
|
|
245
|
+
def _follow_redirects(self, resp: HttpResponse, url: str) -> HttpResponse:
|
|
246
|
+
"""GET each ``Location`` in turn without ``Authorization`` (at most
|
|
247
|
+
``_MAX_REDIRECTS`` hops; a further redirect is returned as it is)."""
|
|
248
|
+
for _ in range(_MAX_REDIRECTS):
|
|
249
|
+
location = _header(resp.headers, "Location")
|
|
250
|
+
if resp.status not in _REDIRECT_STATUSES or not location:
|
|
251
|
+
return resp
|
|
252
|
+
url = urljoin(url, location)
|
|
253
|
+
resp = self._http.request(
|
|
254
|
+
method="GET",
|
|
255
|
+
url=url,
|
|
256
|
+
headers={"Accept": "*/*", "User-Agent": self._user_agent},
|
|
257
|
+
body=None,
|
|
258
|
+
timeout_seconds=self._timeout,
|
|
259
|
+
)
|
|
260
|
+
return resp
|
|
261
|
+
|
|
262
|
+
def _send(
|
|
263
|
+
self,
|
|
264
|
+
*,
|
|
265
|
+
method: str,
|
|
266
|
+
path: str,
|
|
267
|
+
body: Any,
|
|
268
|
+
replay_safe: bool,
|
|
269
|
+
accept: str,
|
|
270
|
+
extra_headers: Mapping[str, str] | None,
|
|
271
|
+
follow_redirects: bool = False,
|
|
272
|
+
) -> HttpResponse:
|
|
273
|
+
import json
|
|
274
|
+
|
|
275
|
+
method_upper = method.upper()
|
|
276
|
+
url = self._build_url(path)
|
|
277
|
+
body_bytes = json.dumps(body).encode("utf-8") if body is not None else None
|
|
278
|
+
|
|
279
|
+
attempt = 0
|
|
280
|
+
last_exc: BaseException | None = None
|
|
281
|
+
while True:
|
|
282
|
+
attempt += 1
|
|
283
|
+
token = self._token_manager.fetch()
|
|
284
|
+
headers: dict[str, str] = {
|
|
285
|
+
"Authorization": f"{token.token_type} {token.value}",
|
|
286
|
+
"Accept": accept,
|
|
287
|
+
"User-Agent": self._user_agent,
|
|
288
|
+
}
|
|
289
|
+
if body_bytes is not None:
|
|
290
|
+
headers["Content-Type"] = "application/json"
|
|
291
|
+
if extra_headers:
|
|
292
|
+
for k, v in extra_headers.items():
|
|
293
|
+
headers[k] = v
|
|
294
|
+
|
|
295
|
+
redirected = False
|
|
296
|
+
try:
|
|
297
|
+
resp = self._http.request(
|
|
298
|
+
method=method_upper,
|
|
299
|
+
url=url,
|
|
300
|
+
headers=headers,
|
|
301
|
+
body=body_bytes,
|
|
302
|
+
timeout_seconds=self._timeout,
|
|
303
|
+
)
|
|
304
|
+
if follow_redirects and resp.status in _REDIRECT_STATUSES:
|
|
305
|
+
redirected = True
|
|
306
|
+
resp = self._follow_redirects(resp, url)
|
|
307
|
+
network_error = False
|
|
308
|
+
status: int | None = resp.status
|
|
309
|
+
except FlowabbitNetworkError as exc:
|
|
310
|
+
last_exc = exc
|
|
311
|
+
resp = None # type: ignore[assignment]
|
|
312
|
+
network_error = True
|
|
313
|
+
status = None
|
|
314
|
+
|
|
315
|
+
# A 401 from the storage link is not about the access token.
|
|
316
|
+
if status == 401 and attempt == 1 and not redirected:
|
|
317
|
+
self._token_manager.invalidate()
|
|
318
|
+
continue
|
|
319
|
+
|
|
320
|
+
if status is not None and 200 <= status < 300:
|
|
321
|
+
return resp
|
|
322
|
+
|
|
323
|
+
if not self._retry.should_retry(
|
|
324
|
+
attempt=attempt,
|
|
325
|
+
method=method_upper,
|
|
326
|
+
replay_safe=replay_safe,
|
|
327
|
+
status_code=status,
|
|
328
|
+
network_error=network_error,
|
|
329
|
+
):
|
|
330
|
+
if network_error:
|
|
331
|
+
raise last_exc if last_exc else FlowabbitNetworkError("network error (no detail)")
|
|
332
|
+
assert resp is not None
|
|
333
|
+
self._raise_api_error(resp)
|
|
334
|
+
|
|
335
|
+
delay = self._retry.next_delay_seconds(
|
|
336
|
+
attempt=attempt,
|
|
337
|
+
headers=resp.headers if resp is not None else None,
|
|
338
|
+
)
|
|
339
|
+
self._sleep(delay)
|
|
340
|
+
|
|
341
|
+
def _sleep(self, seconds: float) -> None:
|
|
342
|
+
if seconds <= 0:
|
|
343
|
+
return
|
|
344
|
+
try:
|
|
345
|
+
self._clock.sleep(seconds) # type: ignore[attr-defined]
|
|
346
|
+
except AttributeError:
|
|
347
|
+
time.sleep(seconds)
|
|
348
|
+
|
|
349
|
+
@staticmethod
|
|
350
|
+
def _build_response(resp: HttpResponse) -> ApiResponse:
|
|
351
|
+
data: Any = None
|
|
352
|
+
if resp.body:
|
|
353
|
+
try:
|
|
354
|
+
data = resp.json()
|
|
355
|
+
except ValueError:
|
|
356
|
+
data = None
|
|
357
|
+
return ApiResponse(
|
|
358
|
+
data=data,
|
|
359
|
+
rate_limit=_rate_from_headers(resp.headers),
|
|
360
|
+
request_id=_header(resp.headers, "X-Request-Id") or "",
|
|
361
|
+
http_status=resp.status,
|
|
362
|
+
raw=resp,
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
@staticmethod
|
|
366
|
+
def _build_binary_response(resp: HttpResponse) -> BinaryResponse:
|
|
367
|
+
return BinaryResponse(
|
|
368
|
+
content=resp.body,
|
|
369
|
+
content_type=_header(resp.headers, "Content-Type") or "",
|
|
370
|
+
filename=_disposition_filename(_header(resp.headers, "Content-Disposition")),
|
|
371
|
+
rate_limit=_rate_from_headers(resp.headers),
|
|
372
|
+
request_id=_header(resp.headers, "X-Request-Id") or "",
|
|
373
|
+
http_status=resp.status,
|
|
374
|
+
raw=resp,
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
@staticmethod
|
|
378
|
+
def _raise_api_error(resp: HttpResponse) -> None:
|
|
379
|
+
try:
|
|
380
|
+
body = resp.json() if resp.body else None
|
|
381
|
+
except ValueError:
|
|
382
|
+
body = None
|
|
383
|
+
if not isinstance(body, dict):
|
|
384
|
+
# Not a business response: no code or message is derived from it;
|
|
385
|
+
# the raw response stays attached.
|
|
386
|
+
body = None
|
|
387
|
+
raise from_response(http_status=resp.status, body=body, raw_response=resp)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _header(headers: Mapping[str, str], name: str) -> str | None:
|
|
391
|
+
for k, v in headers.items():
|
|
392
|
+
if k.lower() == name.lower():
|
|
393
|
+
return v
|
|
394
|
+
return None
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
# Visible ASCII with well-formed %XX escapes (the RFC 8187 value-chars).
|
|
398
|
+
_PERCENT_ENCODED = re.compile(r"(?:[\x21-\x24\x26-\x7e]|%[0-9A-Fa-f]{2})*")
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _disposition_filename(value: str | None) -> str | None:
|
|
402
|
+
"""File name from a ``Content-Disposition`` header (RFC 6266): a UTF-8
|
|
403
|
+
``filename*`` (RFC 8187) wins over ``filename``; None when neither is given."""
|
|
404
|
+
if not value:
|
|
405
|
+
return None
|
|
406
|
+
plain: str | None = None
|
|
407
|
+
extended: str | None = None
|
|
408
|
+
for name, param in _disposition_params(value):
|
|
409
|
+
if name == "filename*":
|
|
410
|
+
parts = param.split("'", 2)
|
|
411
|
+
extended = None
|
|
412
|
+
if len(parts) == 3 and parts[0].lower() == "utf-8" and _PERCENT_ENCODED.fullmatch(parts[2]):
|
|
413
|
+
try:
|
|
414
|
+
extended = unquote(parts[2], encoding="utf-8", errors="strict")
|
|
415
|
+
except UnicodeDecodeError:
|
|
416
|
+
extended = None
|
|
417
|
+
elif name == "filename":
|
|
418
|
+
plain = param
|
|
419
|
+
return extended or plain or None
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _disposition_params(value: str) -> list[tuple[str, str]]:
|
|
423
|
+
"""``name=value`` parameters after the disposition type; names lowercased,
|
|
424
|
+
quoted values unquoted (backslash escapes honoured)."""
|
|
425
|
+
i = value.find(";")
|
|
426
|
+
if i < 0:
|
|
427
|
+
return []
|
|
428
|
+
n = len(value)
|
|
429
|
+
out: list[tuple[str, str]] = []
|
|
430
|
+
i += 1
|
|
431
|
+
while i < n:
|
|
432
|
+
while i < n and value[i] in " \t;":
|
|
433
|
+
i += 1
|
|
434
|
+
start = i
|
|
435
|
+
while i < n and value[i] not in "=;":
|
|
436
|
+
i += 1
|
|
437
|
+
name = value[start:i].strip().lower()
|
|
438
|
+
if i >= n or value[i] == ";":
|
|
439
|
+
continue
|
|
440
|
+
i += 1
|
|
441
|
+
while i < n and value[i] in " \t":
|
|
442
|
+
i += 1
|
|
443
|
+
if i < n and value[i] == '"':
|
|
444
|
+
i += 1
|
|
445
|
+
chars: list[str] = []
|
|
446
|
+
while i < n and value[i] != '"':
|
|
447
|
+
if value[i] == "\\" and i + 1 < n:
|
|
448
|
+
i += 1
|
|
449
|
+
chars.append(value[i])
|
|
450
|
+
i += 1
|
|
451
|
+
param = "".join(chars)
|
|
452
|
+
while i < n and value[i] != ";":
|
|
453
|
+
i += 1
|
|
454
|
+
else:
|
|
455
|
+
start = i
|
|
456
|
+
while i < n and value[i] != ";":
|
|
457
|
+
i += 1
|
|
458
|
+
param = value[start:i].strip()
|
|
459
|
+
if name:
|
|
460
|
+
out.append((name, param))
|
|
461
|
+
return out
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
__all__ = [
|
|
465
|
+
"ApiResponse",
|
|
466
|
+
"BinaryResponse",
|
|
467
|
+
"FlowabbitClient",
|
|
468
|
+
"FlowabbitError",
|
|
469
|
+
"FlowabbitApiError",
|
|
470
|
+
"SDK_VERSION",
|
|
471
|
+
]
|
flowabbit/http_client.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""HttpClient Protocol — pluggable HTTP transport so tests can inject a fake.
|
|
2
|
+
|
|
3
|
+
The SDK intentionally does NOT take a hard dependency on ``requests`` /
|
|
4
|
+
``httpx``. The default implementation uses ``urllib.request`` (stdlib).
|
|
5
|
+
Clients may pass any object that satisfies the ``HttpClient`` Protocol.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json as _json
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.request
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Mapping, Protocol
|
|
14
|
+
|
|
15
|
+
from .runtime.errors import FlowabbitNetworkError
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class HttpResponse:
|
|
20
|
+
status: int
|
|
21
|
+
headers: Mapping[str, str] = field(default_factory=dict)
|
|
22
|
+
body: bytes = b""
|
|
23
|
+
|
|
24
|
+
def json(self) -> object:
|
|
25
|
+
if not self.body:
|
|
26
|
+
return None
|
|
27
|
+
return _json.loads(self.body.decode("utf-8"))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class HttpClient(Protocol):
|
|
31
|
+
def request(
|
|
32
|
+
self,
|
|
33
|
+
*,
|
|
34
|
+
method: str,
|
|
35
|
+
url: str,
|
|
36
|
+
headers: Mapping[str, str],
|
|
37
|
+
body: bytes | None = None,
|
|
38
|
+
timeout_seconds: float | None = None,
|
|
39
|
+
) -> HttpResponse: ...
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
43
|
+
"""Never follow a redirect: the 3xx response is returned as it is.
|
|
44
|
+
|
|
45
|
+
``urlopen`` follows redirects by default and copies every request header,
|
|
46
|
+
``Authorization`` included, to the next URL. A document download answers
|
|
47
|
+
302 with a signed storage link that must be fetched without the access
|
|
48
|
+
token, so the client follows it itself (``FlowabbitClient._download``).
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D102, ANN001
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class UrllibHttpClient:
|
|
56
|
+
"""Stdlib-only HTTP client (the default); clients can swap in requests/httpx.
|
|
57
|
+
|
|
58
|
+
Redirects are never followed automatically (same as the Go / Java / PHP
|
|
59
|
+
transports); a 3xx comes back as an ``HttpResponse``.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def __init__(self, *, default_timeout_seconds: float = 30.0) -> None:
|
|
63
|
+
self._default_timeout = default_timeout_seconds
|
|
64
|
+
self._opener = urllib.request.build_opener(_NoRedirect())
|
|
65
|
+
|
|
66
|
+
def request(
|
|
67
|
+
self,
|
|
68
|
+
*,
|
|
69
|
+
method: str,
|
|
70
|
+
url: str,
|
|
71
|
+
headers: Mapping[str, str],
|
|
72
|
+
body: bytes | None = None,
|
|
73
|
+
timeout_seconds: float | None = None,
|
|
74
|
+
) -> HttpResponse:
|
|
75
|
+
req = urllib.request.Request(url=url, data=body, method=method.upper())
|
|
76
|
+
for k, v in headers.items():
|
|
77
|
+
req.add_header(k, v)
|
|
78
|
+
timeout = timeout_seconds if timeout_seconds is not None else self._default_timeout
|
|
79
|
+
try:
|
|
80
|
+
with self._opener.open(req, timeout=timeout) as resp: # noqa: S310
|
|
81
|
+
resp_headers = {k: v for k, v in resp.headers.items()}
|
|
82
|
+
return HttpResponse(status=resp.status, headers=resp_headers, body=resp.read())
|
|
83
|
+
except urllib.error.HTTPError as exc:
|
|
84
|
+
resp_headers = {k: v for k, v in exc.headers.items()} if exc.headers else {}
|
|
85
|
+
return HttpResponse(status=exc.code, headers=resp_headers, body=exc.read() or b"")
|
|
86
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError) as exc:
|
|
87
|
+
raise FlowabbitNetworkError(f"network error: {exc}", cause=exc) from exc
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Resource namespaces wired into FlowabbitClient (tms, bms, doc)."""
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""BMS resource namespaces: ``client.bms.accounts``, one method per Open API operation.
|
|
2
|
+
|
|
3
|
+
Responses are ``ApiResponse`` (parsed JSON). The read is a GET and is retried
|
|
4
|
+
automatically on network error / 429 / 5xx.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
|
|
10
|
+
from .tms import _with_query
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from ..client import ApiResponse, FlowabbitClient
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class AccountsResource:
|
|
17
|
+
def __init__(self, client: "FlowabbitClient") -> None:
|
|
18
|
+
self._client = client
|
|
19
|
+
|
|
20
|
+
def list(self, currency: str | None = None) -> "ApiResponse":
|
|
21
|
+
"""GET /bms/accounts: your wallets, one per currency; ``currency`` (ISO 4217,
|
|
22
|
+
upper case, e.g. ``USD``) narrows the list to that currency."""
|
|
23
|
+
return self._client._request(method="GET", path=_with_query("/bms/accounts", {"currency": currency}))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class BmsResource:
|
|
27
|
+
def __init__(self, client: "FlowabbitClient") -> None:
|
|
28
|
+
self._client = client
|
|
29
|
+
self.accounts = AccountsResource(client)
|