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
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Document center namespace: ``client.doc.documents``, one method per Open API operation.
|
|
2
|
+
|
|
3
|
+
Documents (labels, customs documents, proof of delivery, carrier manifest
|
|
4
|
+
forms, handover sheets, ...) belong to a parent record: ``ref_type`` is
|
|
5
|
+
``waybill`` (``ref`` = shipment ID ``shp_…``), ``manifest`` (manifest batch
|
|
6
|
+
number) or ``handover`` (handover number). Parameters are sent as given; the
|
|
7
|
+
SDK does not filter or reorder documents. Every operation is a GET and is
|
|
8
|
+
retried automatically on network error / 429 / 5xx.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import TYPE_CHECKING, Sequence
|
|
13
|
+
|
|
14
|
+
from .tms import _segment, _with_query
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from ..client import ApiResponse, BinaryResponse, FlowabbitClient
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _csv(value: str | Sequence[str] | None) -> str | None:
|
|
21
|
+
"""A comma-separated parameter: a string is sent as it is, a sequence is
|
|
22
|
+
joined with ``,`` in the given order, ``None`` leaves the parameter out."""
|
|
23
|
+
if value is None or isinstance(value, str):
|
|
24
|
+
return value
|
|
25
|
+
return ",".join(value)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class DocumentsResource:
|
|
29
|
+
def __init__(self, client: "FlowabbitClient") -> None:
|
|
30
|
+
self._client = client
|
|
31
|
+
|
|
32
|
+
def list(self, ref_type: str, ref: str) -> "ApiResponse":
|
|
33
|
+
"""GET /doc/documents: the active documents of one parent record that
|
|
34
|
+
you can see, each with its ``download_path``."""
|
|
35
|
+
return self._client._request(
|
|
36
|
+
method="GET", path=_with_query("/doc/documents", {"ref_type": ref_type, "ref": ref})
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
def get(self, document_id: str) -> "ApiResponse":
|
|
40
|
+
"""GET /doc/documents/{id}: one document (any status)."""
|
|
41
|
+
return self._client._request(method="GET", path=f"/doc/documents/{_segment('document_id', document_id)}")
|
|
42
|
+
|
|
43
|
+
def download(self, document_id: str) -> "BinaryResponse":
|
|
44
|
+
"""GET /doc/documents/{id}/file: the document file.
|
|
45
|
+
|
|
46
|
+
A stored file answers 302 with a short-lived signed link; the SDK
|
|
47
|
+
follows it without the ``Authorization`` header. A handover sheet is
|
|
48
|
+
rendered on demand and returned as PDF directly.
|
|
49
|
+
"""
|
|
50
|
+
return self._client._download(path=f"/doc/documents/{_segment('document_id', document_id)}/file")
|
|
51
|
+
|
|
52
|
+
def merged(
|
|
53
|
+
self,
|
|
54
|
+
ref_type: str,
|
|
55
|
+
ref: str,
|
|
56
|
+
*,
|
|
57
|
+
types: str | Sequence[str] | None = None,
|
|
58
|
+
sources: str | Sequence[str] | None = None,
|
|
59
|
+
print_media: str | None = None,
|
|
60
|
+
document_ids: str | Sequence[str] | None = None,
|
|
61
|
+
) -> "BinaryResponse":
|
|
62
|
+
"""GET /doc/documents/merged: one PDF merging documents of the parent
|
|
63
|
+
record page by page.
|
|
64
|
+
|
|
65
|
+
By default only active carrier-side documents are merged (``sources``
|
|
66
|
+
defaults to ``carrier`` on the server); pass ``sources`` (``carrier``,
|
|
67
|
+
``customer``) or ``document_ids`` to include documents you uploaded.
|
|
68
|
+
``document_ids`` (at most 50, no duplicates) is merged in the given
|
|
69
|
+
order and makes the server ignore ``types``, ``sources`` and
|
|
70
|
+
``print_media``. List parameters may be a comma-separated string or a
|
|
71
|
+
sequence (joined with ``,`` in order).
|
|
72
|
+
"""
|
|
73
|
+
query = {
|
|
74
|
+
"ref_type": ref_type,
|
|
75
|
+
"ref": ref,
|
|
76
|
+
"types": _csv(types),
|
|
77
|
+
"sources": _csv(sources),
|
|
78
|
+
"print_media": print_media,
|
|
79
|
+
"document_ids": _csv(document_ids),
|
|
80
|
+
}
|
|
81
|
+
return self._client._download(path=_with_query("/doc/documents/merged", query))
|
|
82
|
+
|
|
83
|
+
def types(self) -> "ApiResponse":
|
|
84
|
+
"""GET /doc/document-types: the document types you may receive (open
|
|
85
|
+
enum: ignore types you do not know)."""
|
|
86
|
+
return self._client._request(method="GET", path="/doc/document-types")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class DocResource:
|
|
90
|
+
def __init__(self, client: "FlowabbitClient") -> None:
|
|
91
|
+
self._client = client
|
|
92
|
+
self.documents = DocumentsResource(client)
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""TMS resource namespaces: ``client.tms.origins / rates / shipments / trackers /
|
|
2
|
+
manifests / handovers``, one method per Open API operation.
|
|
3
|
+
|
|
4
|
+
Request bodies are plain dicts and responses are ``ApiResponse`` (parsed JSON).
|
|
5
|
+
Labels, carrier forms and handover sheets are documents: list and download
|
|
6
|
+
them with ``client.doc.documents``. Automatic retries (network error / 429 /
|
|
7
|
+
5xx) apply to GET operations and to the POST operations whose replay cannot
|
|
8
|
+
duplicate an effect; each method's docstring says which case it is.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import TYPE_CHECKING, Any, Mapping
|
|
13
|
+
from urllib.parse import quote
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from ..client import ApiResponse, FlowabbitClient
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _segment(name: str, value: str) -> str:
|
|
20
|
+
"""One path parameter, percent-encoded (only RFC 3986 unreserved
|
|
21
|
+
characters stay as they are). Every path parameter is required."""
|
|
22
|
+
if not isinstance(value, str) or value == "":
|
|
23
|
+
raise ValueError(f"{name} is required")
|
|
24
|
+
if value in (".", ".."):
|
|
25
|
+
raise ValueError(f"{name} must not be '.' or '..'")
|
|
26
|
+
return quote(value, safe="")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _with_query(path: str, query: Mapping[str, Any] | None) -> str:
|
|
30
|
+
"""``path`` plus the query string: keys sorted, ``None`` values left out,
|
|
31
|
+
booleans as ``true`` / ``false``, keys and values percent-encoded."""
|
|
32
|
+
if not query:
|
|
33
|
+
return path
|
|
34
|
+
parts = []
|
|
35
|
+
for key in sorted(query):
|
|
36
|
+
value = query[key]
|
|
37
|
+
if value is None:
|
|
38
|
+
continue
|
|
39
|
+
if isinstance(value, bool):
|
|
40
|
+
text = "true" if value else "false"
|
|
41
|
+
else:
|
|
42
|
+
text = str(value)
|
|
43
|
+
parts.append(f"{quote(str(key), safe='')}={quote(text, safe='')}")
|
|
44
|
+
return f"{path}?{'&'.join(parts)}" if parts else path
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def all_entries_have_reference_no(body: Any) -> bool:
|
|
48
|
+
"""True when ``body["shipments"]`` is a non-empty list and every entry
|
|
49
|
+
carries a ``reference_no`` that is non-blank after trimming.
|
|
50
|
+
|
|
51
|
+
The server keeps ``reference_no`` unique per customer among active
|
|
52
|
+
shipments, so replaying such a request cannot create a second shipment:
|
|
53
|
+
an entry that was already created comes back as
|
|
54
|
+
``SHIPMENT_REFERENCE_EXISTS`` with the existing ``shipment_id``.
|
|
55
|
+
"""
|
|
56
|
+
if not isinstance(body, dict):
|
|
57
|
+
return False
|
|
58
|
+
entries = body.get("shipments")
|
|
59
|
+
if not isinstance(entries, list) or not entries:
|
|
60
|
+
return False
|
|
61
|
+
for entry in entries:
|
|
62
|
+
if not isinstance(entry, dict):
|
|
63
|
+
return False
|
|
64
|
+
ref = entry.get("reference_no")
|
|
65
|
+
if not isinstance(ref, str) or not ref.strip():
|
|
66
|
+
return False
|
|
67
|
+
return True
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ShipmentsResource:
|
|
71
|
+
def __init__(self, client: "FlowabbitClient") -> None:
|
|
72
|
+
self._client = client
|
|
73
|
+
|
|
74
|
+
def create(self, body: dict[str, Any]) -> "ApiResponse":
|
|
75
|
+
"""POST /tms/shipments.
|
|
76
|
+
|
|
77
|
+
Every entry in ``body["shipments"]`` must carry ``reference_no`` (your
|
|
78
|
+
own order number). The customer is taken from the OAuth token; do not
|
|
79
|
+
send ``customer_id``.
|
|
80
|
+
|
|
81
|
+
Retries on network errors / 429 / 5xx happen only when every entry has
|
|
82
|
+
a non-blank ``reference_no``. A replayed entry that the server already
|
|
83
|
+
created comes back as ``SHIPMENT_REFERENCE_EXISTS`` with the existing
|
|
84
|
+
``shipment_id``; treat it as "already created" when that id is the one
|
|
85
|
+
you expect.
|
|
86
|
+
"""
|
|
87
|
+
return self._client._request(
|
|
88
|
+
method="POST",
|
|
89
|
+
path="/tms/shipments",
|
|
90
|
+
body=body,
|
|
91
|
+
replay_safe=all_entries_have_reference_no(body),
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
def modify(self, body: dict[str, Any]) -> "ApiResponse":
|
|
95
|
+
"""POST /tms/shipments/modify.
|
|
96
|
+
|
|
97
|
+
Replace a shipment that has no label yet, located by its ``reference_no``;
|
|
98
|
+
``body`` is one create entry with a new ``selected_rate_id``. The old
|
|
99
|
+
charge is refunded and the new quote charged. A shipment that already
|
|
100
|
+
has a label returns ``SHIPMENT_HAS_LABEL`` (cancel it, then create it
|
|
101
|
+
again with the same ``reference_no``).
|
|
102
|
+
|
|
103
|
+
Never retried automatically: a lost response may hide a modify that
|
|
104
|
+
succeeded, and its quote is single-use; re-quote or read the shipment
|
|
105
|
+
before trying again.
|
|
106
|
+
"""
|
|
107
|
+
return self._client._request(
|
|
108
|
+
method="POST",
|
|
109
|
+
path="/tms/shipments/modify",
|
|
110
|
+
body=body,
|
|
111
|
+
replay_safe=False,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
def query(self, body: dict[str, Any]) -> "ApiResponse":
|
|
115
|
+
"""POST /tms/shipments/query: look shipments up by ``shipment_ids`` or
|
|
116
|
+
``reference_nos``. Read-only, so it is retried like a GET."""
|
|
117
|
+
return self._client._request(method="POST", path="/tms/shipments/query", body=body, replay_safe=True)
|
|
118
|
+
|
|
119
|
+
def get(self, shipment_id: str) -> "ApiResponse":
|
|
120
|
+
"""GET /tms/shipments/{id}."""
|
|
121
|
+
return self._client._request(method="GET", path=f"/tms/shipments/{_segment('shipment_id', shipment_id)}")
|
|
122
|
+
|
|
123
|
+
def cancel(self, shipment_id: str) -> "ApiResponse":
|
|
124
|
+
"""POST /tms/shipments/{id}/cancel.
|
|
125
|
+
|
|
126
|
+
Retried on network errors / 429 / 5xx: cancelling a shipment that is
|
|
127
|
+
already cancelled, voided or being cancelled returns its current
|
|
128
|
+
status instead of acting again.
|
|
129
|
+
"""
|
|
130
|
+
return self._client._request(
|
|
131
|
+
method="POST",
|
|
132
|
+
path=f"/tms/shipments/{_segment('shipment_id', shipment_id)}/cancel",
|
|
133
|
+
replay_safe=True,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class OriginsResource:
|
|
138
|
+
def __init__(self, client: "FlowabbitClient") -> None:
|
|
139
|
+
self._client = client
|
|
140
|
+
|
|
141
|
+
def list(self) -> "ApiResponse":
|
|
142
|
+
"""GET /tms/origins: the ship-from origins available to you."""
|
|
143
|
+
return self._client._request(method="GET", path="/tms/origins")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class RatesResource:
|
|
147
|
+
def __init__(self, client: "FlowabbitClient") -> None:
|
|
148
|
+
self._client = client
|
|
149
|
+
|
|
150
|
+
def list(self, body: dict[str, Any]) -> "ApiResponse":
|
|
151
|
+
"""POST /tms/rates: quote ``body["requests"]``. A quote charges nothing,
|
|
152
|
+
so it is retried like a GET; a retry may return new ``rate_id`` values."""
|
|
153
|
+
return self._client._request(method="POST", path="/tms/rates", body=body, replay_safe=True)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class TrackersResource:
|
|
157
|
+
def __init__(self, client: "FlowabbitClient") -> None:
|
|
158
|
+
self._client = client
|
|
159
|
+
|
|
160
|
+
def query(self, body: dict[str, Any]) -> "ApiResponse":
|
|
161
|
+
"""POST /tms/trackers/query: tracking by ``shipment_ids`` or
|
|
162
|
+
``tracking_nos``. Read-only, so it is retried like a GET."""
|
|
163
|
+
return self._client._request(method="POST", path="/tms/trackers/query", body=body, replay_safe=True)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class ManifestsResource:
|
|
167
|
+
def __init__(self, client: "FlowabbitClient") -> None:
|
|
168
|
+
self._client = client
|
|
169
|
+
|
|
170
|
+
def request(self, body: dict[str, Any]) -> "ApiResponse":
|
|
171
|
+
"""POST /tms/shipments/manifest: manifest ``body["shipment_ids"]``.
|
|
172
|
+
|
|
173
|
+
The request as a whole succeeds; each shipment gets its own result
|
|
174
|
+
(``manifested`` / ``scheduled`` with a ``manifest_no``,
|
|
175
|
+
``not_required``, or ``not_eligible`` with a reason). Retried on
|
|
176
|
+
network errors / 429 / 5xx: a shipment that is already manifested or
|
|
177
|
+
scheduled comes back with its existing ``manifest_no``.
|
|
178
|
+
"""
|
|
179
|
+
return self._client._request(method="POST", path="/tms/shipments/manifest", body=body, replay_safe=True)
|
|
180
|
+
|
|
181
|
+
def list(self, query: Mapping[str, Any] | None = None) -> "ApiResponse":
|
|
182
|
+
"""GET /tms/manifests. ``query`` keys: ``status``, ``manifest_no``,
|
|
183
|
+
``page`` (from 1), ``page_size`` (1-100)."""
|
|
184
|
+
return self._client._request(method="GET", path=_with_query("/tms/manifests", query))
|
|
185
|
+
|
|
186
|
+
def get(self, manifest_no: str) -> "ApiResponse":
|
|
187
|
+
"""GET /tms/manifests/{manifest_no}."""
|
|
188
|
+
return self._client._request(method="GET", path=f"/tms/manifests/{_segment('manifest_no', manifest_no)}")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class HandoversResource:
|
|
192
|
+
def __init__(self, client: "FlowabbitClient") -> None:
|
|
193
|
+
self._client = client
|
|
194
|
+
|
|
195
|
+
def create(self, body: dict[str, Any]) -> "ApiResponse":
|
|
196
|
+
"""POST /tms/handovers: hand over ``body["shipment_ids"]``.
|
|
197
|
+
|
|
198
|
+
The request as a whole succeeds; each shipment gets its own result.
|
|
199
|
+
Retried on network errors / 429 / 5xx: a shipment that is already in a
|
|
200
|
+
handover record comes back as ``already_handed_over`` with that
|
|
201
|
+
record's ``handover_no``.
|
|
202
|
+
"""
|
|
203
|
+
return self._client._request(method="POST", path="/tms/handovers", body=body, replay_safe=True)
|
|
204
|
+
|
|
205
|
+
def list(self, query: Mapping[str, Any] | None = None) -> "ApiResponse":
|
|
206
|
+
"""GET /tms/handovers. ``query`` keys: ``status``, ``handover_no``,
|
|
207
|
+
``page`` (from 1), ``page_size`` (1-100)."""
|
|
208
|
+
return self._client._request(method="GET", path=_with_query("/tms/handovers", query))
|
|
209
|
+
|
|
210
|
+
def get(self, handover_no: str) -> "ApiResponse":
|
|
211
|
+
"""GET /tms/handovers/{handover_no}."""
|
|
212
|
+
return self._client._request(method="GET", path=f"/tms/handovers/{_segment('handover_no', handover_no)}")
|
|
213
|
+
|
|
214
|
+
def find_by_document(self, document_no: str) -> "ApiResponse":
|
|
215
|
+
"""GET /tms/handovers/by-document/{document_no}: the records listing a
|
|
216
|
+
carrier form number, handover number or manifest number."""
|
|
217
|
+
return self._client._request(
|
|
218
|
+
method="GET", path=f"/tms/handovers/by-document/{_segment('document_no', document_no)}"
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
def remove_items(self, handover_no: str, body: dict[str, Any]) -> "ApiResponse":
|
|
222
|
+
"""POST /tms/handovers/{handover_no}/items/remove: remove
|
|
223
|
+
``body["shipment_ids"]`` from the record, with ``body["reason"]``.
|
|
224
|
+
|
|
225
|
+
Never retried automatically: replaying a removal that succeeded
|
|
226
|
+
returns ``TMS_HANDOVER_ITEM_NOT_REVOCABLE``; read the record with
|
|
227
|
+
``get`` before trying again.
|
|
228
|
+
"""
|
|
229
|
+
return self._client._request(
|
|
230
|
+
method="POST",
|
|
231
|
+
path=f"/tms/handovers/{_segment('handover_no', handover_no)}/items/remove",
|
|
232
|
+
body=body,
|
|
233
|
+
replay_safe=False,
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
class TmsResource:
|
|
238
|
+
def __init__(self, client: "FlowabbitClient") -> None:
|
|
239
|
+
self._client = client
|
|
240
|
+
self.origins = OriginsResource(client)
|
|
241
|
+
self.rates = RatesResource(client)
|
|
242
|
+
self.shipments = ShipmentsResource(client)
|
|
243
|
+
self.trackers = TrackersResource(client)
|
|
244
|
+
self.manifests = ManifestsResource(client)
|
|
245
|
+
self.handovers = HandoversResource(client)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Runtime helpers — token manager, retry policy, rate-limit parsing, webhook
|
|
2
|
+
verifier and the typed error model.
|
|
3
|
+
|
|
4
|
+
Importable surface:
|
|
5
|
+
from flowabbit.runtime import (
|
|
6
|
+
TokenManager,
|
|
7
|
+
AccessToken,
|
|
8
|
+
RetryPolicy,
|
|
9
|
+
WebhookVerifier,
|
|
10
|
+
WebhookEvent,
|
|
11
|
+
RateLimitInfo,
|
|
12
|
+
from_headers,
|
|
13
|
+
from_response,
|
|
14
|
+
FlowabbitError,
|
|
15
|
+
FlowabbitNetworkError,
|
|
16
|
+
FlowabbitOAuthError,
|
|
17
|
+
FlowabbitApiError,
|
|
18
|
+
FlowabbitAuthError,
|
|
19
|
+
FlowabbitValidationError,
|
|
20
|
+
FlowabbitRateLimitError,
|
|
21
|
+
FlowabbitServerError,
|
|
22
|
+
FlowabbitWebhookDuplicateEventError,
|
|
23
|
+
FlowabbitWebhookSignatureError,
|
|
24
|
+
FlowabbitBatchEntryError,
|
|
25
|
+
)
|
|
26
|
+
"""
|
|
27
|
+
from .errors import (
|
|
28
|
+
FlowabbitApiError,
|
|
29
|
+
FlowabbitAuthError,
|
|
30
|
+
FlowabbitBatchEntryError,
|
|
31
|
+
FlowabbitError,
|
|
32
|
+
FlowabbitNetworkError,
|
|
33
|
+
FlowabbitOAuthError,
|
|
34
|
+
FlowabbitRateLimitError,
|
|
35
|
+
FlowabbitServerError,
|
|
36
|
+
FlowabbitValidationError,
|
|
37
|
+
FlowabbitWebhookDuplicateEventError,
|
|
38
|
+
FlowabbitWebhookSignatureError,
|
|
39
|
+
from_response,
|
|
40
|
+
)
|
|
41
|
+
from .rate_limit import RateLimitInfo, from_headers
|
|
42
|
+
from .retry import RetryPolicy
|
|
43
|
+
from .token_manager import AccessToken, TokenManager
|
|
44
|
+
from .webhook_verifier import WebhookEvent, WebhookVerifier
|
|
45
|
+
|
|
46
|
+
__all__ = [
|
|
47
|
+
"AccessToken",
|
|
48
|
+
"FlowabbitApiError",
|
|
49
|
+
"FlowabbitAuthError",
|
|
50
|
+
"FlowabbitBatchEntryError",
|
|
51
|
+
"FlowabbitError",
|
|
52
|
+
"FlowabbitNetworkError",
|
|
53
|
+
"FlowabbitOAuthError",
|
|
54
|
+
"FlowabbitRateLimitError",
|
|
55
|
+
"FlowabbitServerError",
|
|
56
|
+
"FlowabbitValidationError",
|
|
57
|
+
"FlowabbitWebhookDuplicateEventError",
|
|
58
|
+
"FlowabbitWebhookSignatureError",
|
|
59
|
+
"RateLimitInfo",
|
|
60
|
+
"RetryPolicy",
|
|
61
|
+
"TokenManager",
|
|
62
|
+
"WebhookEvent",
|
|
63
|
+
"WebhookVerifier",
|
|
64
|
+
"from_headers",
|
|
65
|
+
"from_response",
|
|
66
|
+
]
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Typed errors — 5 HTTP status classes + error_code string switch.
|
|
2
|
+
|
|
3
|
+
There is no subclass per error_code; callers switch on ``err.error_code``.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class FlowabbitError(Exception):
|
|
11
|
+
"""Root of all Flowabbit SDK errors."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class FlowabbitNetworkError(FlowabbitError):
|
|
15
|
+
"""connect / read timeout / DNS / TCP reset — no HTTP response received."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, message: str, cause: BaseException | None = None) -> None:
|
|
18
|
+
super().__init__(message)
|
|
19
|
+
self.cause = cause
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class FlowabbitOAuthError(FlowabbitError):
|
|
23
|
+
"""OAuth2 token endpoint failure (RFC 6749 §5.2 OAuthTokenError schema)."""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
error: str,
|
|
28
|
+
error_description: str | None = None,
|
|
29
|
+
http_status: int | None = None,
|
|
30
|
+
raw_response: Any | None = None,
|
|
31
|
+
) -> None:
|
|
32
|
+
super().__init__(f"OAuth error: {error}" + (f" — {error_description}" if error_description else ""))
|
|
33
|
+
self.error = error
|
|
34
|
+
self.error_description = error_description
|
|
35
|
+
self.http_status = http_status
|
|
36
|
+
self.raw_response = raw_response
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class FlowabbitApiError(FlowabbitError):
|
|
40
|
+
"""Business endpoint error (Problem Details body: code / detail / request_id)."""
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
*,
|
|
45
|
+
error_code: str,
|
|
46
|
+
message: str,
|
|
47
|
+
request_id: str = "",
|
|
48
|
+
http_status: int,
|
|
49
|
+
raw_response: Any | None = None,
|
|
50
|
+
) -> None:
|
|
51
|
+
super().__init__(f"[{http_status} {error_code}] {message}")
|
|
52
|
+
self.error_code = error_code
|
|
53
|
+
self.message = message
|
|
54
|
+
self.request_id = request_id
|
|
55
|
+
self.http_status = http_status
|
|
56
|
+
self.raw_response = raw_response
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class FlowabbitValidationError(FlowabbitApiError):
|
|
60
|
+
"""4xx other than 401/403/429 — request shape / validation failure."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class FlowabbitAuthError(FlowabbitApiError):
|
|
64
|
+
"""401 / 403 — auth failed or scope insufficient."""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class FlowabbitRateLimitError(FlowabbitApiError):
|
|
68
|
+
"""429 — rate limit exceeded."""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class FlowabbitServerError(FlowabbitApiError):
|
|
72
|
+
"""5xx — server-side failure."""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class FlowabbitWebhookSignatureError(FlowabbitError):
|
|
76
|
+
"""Webhook signature verification failed (bad HMAC, skew, missing header).
|
|
77
|
+
|
|
78
|
+
This exception is **only** raised when the inbound webhook
|
|
79
|
+
cannot be authenticated — bad signature, timestamp out of skew, missing
|
|
80
|
+
required header. Duplicate-event detection raises
|
|
81
|
+
:class:`FlowabbitWebhookDuplicateEventError` instead (separate type so
|
|
82
|
+
callers don't conflate normal idempotent dedup with auth failure).
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class FlowabbitWebhookDuplicateEventError(FlowabbitError):
|
|
87
|
+
"""Webhook event already processed (reported by ``dedup_hook``).
|
|
88
|
+
|
|
89
|
+
Duplicate delivery is normal idempotent behaviour, not an
|
|
90
|
+
auth or signature failure. Callers should typically log + ACK 200 and move
|
|
91
|
+
on. Does **not** inherit from :class:`FlowabbitWebhookSignatureError`.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
def __init__(self, *, event_id: str, event_type: str, timestamp: int) -> None:
|
|
95
|
+
super().__init__(f"duplicate webhook event: {event_id} ({event_type})")
|
|
96
|
+
self.event_id = event_id
|
|
97
|
+
self.event_type = event_type
|
|
98
|
+
self.timestamp = timestamp
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def from_response(
|
|
102
|
+
*,
|
|
103
|
+
http_status: int,
|
|
104
|
+
body: dict[str, Any] | None,
|
|
105
|
+
raw_response: Any | None = None,
|
|
106
|
+
) -> FlowabbitApiError:
|
|
107
|
+
"""Map (http_status, Problem Details body) to a typed exception class.
|
|
108
|
+
|
|
109
|
+
5 HTTP status classes only. Callers should switch on ``err.error_code``
|
|
110
|
+
(see the error directory in the API documentation).
|
|
111
|
+
"""
|
|
112
|
+
body = body or {}
|
|
113
|
+
# Problem Details wire: code / detail / request_id. Legacy fields and the
|
|
114
|
+
# OAuth token-endpoint fields (error, error_description) are not read here;
|
|
115
|
+
# token errors have their own adapter in TokenManager.
|
|
116
|
+
error_code = body.get("code")
|
|
117
|
+
if not isinstance(error_code, str) or not error_code:
|
|
118
|
+
error_code = "unknown_error"
|
|
119
|
+
message = body.get("detail")
|
|
120
|
+
if not isinstance(message, str):
|
|
121
|
+
message = ""
|
|
122
|
+
request_id = body.get("request_id")
|
|
123
|
+
if not isinstance(request_id, str):
|
|
124
|
+
request_id = ""
|
|
125
|
+
|
|
126
|
+
kwargs = dict(
|
|
127
|
+
error_code=error_code,
|
|
128
|
+
message=message,
|
|
129
|
+
request_id=request_id,
|
|
130
|
+
http_status=http_status,
|
|
131
|
+
raw_response=raw_response,
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
if http_status in (401, 403):
|
|
135
|
+
return FlowabbitAuthError(**kwargs)
|
|
136
|
+
if http_status == 429:
|
|
137
|
+
return FlowabbitRateLimitError(**kwargs)
|
|
138
|
+
if 400 <= http_status < 500:
|
|
139
|
+
return FlowabbitValidationError(**kwargs)
|
|
140
|
+
if 500 <= http_status < 600:
|
|
141
|
+
return FlowabbitServerError(**kwargs)
|
|
142
|
+
return FlowabbitApiError(**kwargs)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class FlowabbitBatchEntryError:
|
|
146
|
+
"""Batch entry-level error (OpenAPI ``V1EntryError`` schema).
|
|
147
|
+
|
|
148
|
+
NOT raised — returned as a result field. Iterate batch results and check
|
|
149
|
+
``isinstance(item, FlowabbitBatchEntryError)``.
|
|
150
|
+
|
|
151
|
+
The "Batch" prefix distinguishes entry-level errors from per-request
|
|
152
|
+
errors; the PHP, Java and Go SDKs use the same name.
|
|
153
|
+
"""
|
|
154
|
+
|
|
155
|
+
__slots__ = ("error_code", "message", "request_id", "index")
|
|
156
|
+
|
|
157
|
+
def __init__(self, *, error_code: str, message: str, request_id: str = "", index: int = -1) -> None:
|
|
158
|
+
self.error_code = error_code
|
|
159
|
+
self.message = message
|
|
160
|
+
self.request_id = request_id
|
|
161
|
+
self.index = index
|
|
162
|
+
|
|
163
|
+
def __repr__(self) -> str:
|
|
164
|
+
return f"FlowabbitBatchEntryError(index={self.index}, error_code={self.error_code!r})"
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""RateLimit accessor — RFC 9333 RateLimit-* + legacy X-RateLimit-* compatibility.
|
|
2
|
+
|
|
3
|
+
Response headers are exposed as a typed struct on the
|
|
4
|
+
returned ApiResponse; SDK does NOT actively throttle (RetryPolicy handles 429).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Mapping
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class RateLimitInfo:
|
|
14
|
+
"""Parsed rate-limit metadata. Any field may be ``None`` if header missing."""
|
|
15
|
+
|
|
16
|
+
limit: int | None = None
|
|
17
|
+
remaining: int | None = None
|
|
18
|
+
reset: int | None = None
|
|
19
|
+
policy: str | None = None
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def present(self) -> bool:
|
|
23
|
+
"""True if at least one RateLimit-* header was parsed."""
|
|
24
|
+
return any(v is not None for v in (self.limit, self.remaining, self.reset, self.policy))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _ci_get(headers: Mapping[str, str], name: str) -> str | None:
|
|
28
|
+
"""Case-insensitive header lookup. Works with dict / requests.Response.headers."""
|
|
29
|
+
if hasattr(headers, "get"):
|
|
30
|
+
v = headers.get(name)
|
|
31
|
+
if v is not None:
|
|
32
|
+
return v
|
|
33
|
+
v = headers.get(name.lower())
|
|
34
|
+
if v is not None:
|
|
35
|
+
return v
|
|
36
|
+
for k, val in headers.items():
|
|
37
|
+
if k.lower() == name.lower():
|
|
38
|
+
return val
|
|
39
|
+
return None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _to_int(v: str | None) -> int | None:
|
|
43
|
+
if v is None:
|
|
44
|
+
return None
|
|
45
|
+
try:
|
|
46
|
+
return int(str(v).strip())
|
|
47
|
+
except (ValueError, TypeError):
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def from_headers(headers: Mapping[str, str]) -> RateLimitInfo:
|
|
52
|
+
"""Parse RateLimit-* (RFC 9333) with X-RateLimit-* legacy fallback per field.
|
|
53
|
+
|
|
54
|
+
Any subset of fields may be absent (the server sends them only when it has
|
|
55
|
+
a quota decision for the request). SDK clients must use Optional.
|
|
56
|
+
"""
|
|
57
|
+
limit = _to_int(_ci_get(headers, "RateLimit-Limit")) or _to_int(_ci_get(headers, "X-RateLimit-Limit"))
|
|
58
|
+
remaining = _to_int(_ci_get(headers, "RateLimit-Remaining")) or _to_int(_ci_get(headers, "X-RateLimit-Remaining"))
|
|
59
|
+
reset = _to_int(_ci_get(headers, "RateLimit-Reset")) or _to_int(_ci_get(headers, "X-RateLimit-Reset"))
|
|
60
|
+
policy = _ci_get(headers, "RateLimit-Policy") or _ci_get(headers, "X-RateLimit-Policy")
|
|
61
|
+
return RateLimitInfo(limit=limit, remaining=remaining, reset=reset, policy=policy)
|