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,173 @@
|
|
|
1
|
+
"""Retry policy — RFC 9333 RateLimit-Reset > Retry-After > exponential backoff.
|
|
2
|
+
|
|
3
|
+
Retry only idempotent methods (GET/HEAD/DELETE/OPTIONS) or a POST the caller
|
|
4
|
+
marks ``replay_safe``. ``POST /tms/shipments`` is replay-safe when every entry
|
|
5
|
+
carries a non-blank ``reference_no``: the server keeps it unique per customer,
|
|
6
|
+
so a replay cannot create a second shipment. Network error + 429 + 5xx are
|
|
7
|
+
retryable. Max retries defaults to 3.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import email.utils
|
|
12
|
+
import random
|
|
13
|
+
import time
|
|
14
|
+
from typing import Mapping
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
_IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "DELETE", "OPTIONS"})
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class RetryPolicy:
|
|
21
|
+
"""Retry decisions + backoff calculation for replay-safe requests.
|
|
22
|
+
|
|
23
|
+
Semantics (shared by the Python, Go, PHP and Java SDKs):
|
|
24
|
+
``max_retries`` is the **retry count**, NOT the total attempt count.
|
|
25
|
+
Total attempts = ``max_retries + 1``.
|
|
26
|
+
|
|
27
|
+
============ =========== =====================
|
|
28
|
+
max_retries retries total attempts
|
|
29
|
+
============ =========== =====================
|
|
30
|
+
0 0 1
|
|
31
|
+
1 1 2
|
|
32
|
+
3 (default) 3 4
|
|
33
|
+
N N N + 1
|
|
34
|
+
============ =========== =====================
|
|
35
|
+
|
|
36
|
+
Cross-language alignment (PHP / Java / Go must keep this exact semantic):
|
|
37
|
+
- PHP ``int $maxRetries``
|
|
38
|
+
- Java ``int maxRetries``
|
|
39
|
+
- Go ``MaxRetries int``
|
|
40
|
+
|
|
41
|
+
See ``tests/test_retry.py::test_max_retries_boundary_total_attempts`` for
|
|
42
|
+
the regression test that locks the boundary.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
*,
|
|
48
|
+
max_retries: int = 3,
|
|
49
|
+
initial_backoff_seconds: float = 0.5,
|
|
50
|
+
max_backoff_seconds: float = 30.0,
|
|
51
|
+
respect_retry_after: bool = True,
|
|
52
|
+
respect_rate_limit_reset: bool = True,
|
|
53
|
+
jitter: bool = True,
|
|
54
|
+
) -> None:
|
|
55
|
+
if max_retries < 0:
|
|
56
|
+
raise ValueError("max_retries must be >= 0")
|
|
57
|
+
if initial_backoff_seconds <= 0:
|
|
58
|
+
raise ValueError("initial_backoff_seconds must be > 0")
|
|
59
|
+
if max_backoff_seconds < initial_backoff_seconds:
|
|
60
|
+
raise ValueError("max_backoff_seconds must be >= initial_backoff_seconds")
|
|
61
|
+
self.max_retries = max_retries
|
|
62
|
+
self.initial_backoff_seconds = initial_backoff_seconds
|
|
63
|
+
self.max_backoff_seconds = max_backoff_seconds
|
|
64
|
+
self.respect_retry_after = respect_retry_after
|
|
65
|
+
self.respect_rate_limit_reset = respect_rate_limit_reset
|
|
66
|
+
self.jitter = jitter
|
|
67
|
+
|
|
68
|
+
def should_retry(
|
|
69
|
+
self,
|
|
70
|
+
*,
|
|
71
|
+
attempt: int,
|
|
72
|
+
method: str,
|
|
73
|
+
replay_safe: bool,
|
|
74
|
+
status_code: int | None,
|
|
75
|
+
network_error: bool,
|
|
76
|
+
) -> bool:
|
|
77
|
+
"""Decide whether to retry after a failed attempt.
|
|
78
|
+
|
|
79
|
+
``attempt`` is the 1-based index of the attempt that **just failed**.
|
|
80
|
+
Returns False once ``attempt > max_retries`` — i.e. once we have
|
|
81
|
+
already made ``max_retries + 1`` total attempts (1 initial + N retries).
|
|
82
|
+
|
|
83
|
+
Example with ``max_retries=3``:
|
|
84
|
+
- after attempt 1 fails: should_retry(attempt=1) → True (retry → attempt 2)
|
|
85
|
+
- after attempt 2 fails: should_retry(attempt=2) → True (retry → attempt 3)
|
|
86
|
+
- after attempt 3 fails: should_retry(attempt=3) → True (retry → attempt 4)
|
|
87
|
+
- after attempt 4 fails: should_retry(attempt=4) → False (stop, raise)
|
|
88
|
+
|
|
89
|
+
Total business calls = 4, retries = 3.
|
|
90
|
+
|
|
91
|
+
``replay_safe`` lets a non-idempotent method (POST) retry; the caller
|
|
92
|
+
sets it only when a replay cannot duplicate side effects.
|
|
93
|
+
"""
|
|
94
|
+
if attempt > self.max_retries:
|
|
95
|
+
return False
|
|
96
|
+
method_upper = method.upper()
|
|
97
|
+
retryable_method = method_upper in _IDEMPOTENT_METHODS or replay_safe
|
|
98
|
+
if not retryable_method:
|
|
99
|
+
return False
|
|
100
|
+
if network_error:
|
|
101
|
+
return True
|
|
102
|
+
if status_code is None:
|
|
103
|
+
return False
|
|
104
|
+
if status_code == 429:
|
|
105
|
+
return True
|
|
106
|
+
if 500 <= status_code < 600:
|
|
107
|
+
return True
|
|
108
|
+
return False
|
|
109
|
+
|
|
110
|
+
def next_delay_seconds(
|
|
111
|
+
self,
|
|
112
|
+
*,
|
|
113
|
+
attempt: int,
|
|
114
|
+
headers: Mapping[str, str] | None = None,
|
|
115
|
+
now: float | None = None,
|
|
116
|
+
) -> float:
|
|
117
|
+
"""Compute sleep before next attempt.
|
|
118
|
+
|
|
119
|
+
Priority: Retry-After > RateLimit-Reset > exponential backoff + jitter.
|
|
120
|
+
Cap to max_backoff_seconds. ``attempt`` is 1-based for the attempt that
|
|
121
|
+
just failed (so next sleep is for attempt+1).
|
|
122
|
+
"""
|
|
123
|
+
if headers is not None and self.respect_retry_after:
|
|
124
|
+
retry_after = _parse_retry_after(_ci_get(headers, "Retry-After"), now=now)
|
|
125
|
+
if retry_after is not None:
|
|
126
|
+
return _clamp(retry_after, self.max_backoff_seconds)
|
|
127
|
+
if headers is not None and self.respect_rate_limit_reset:
|
|
128
|
+
reset = _parse_int(_ci_get(headers, "RateLimit-Reset")) or _parse_int(
|
|
129
|
+
_ci_get(headers, "X-RateLimit-Reset")
|
|
130
|
+
)
|
|
131
|
+
if reset is not None and reset > 0:
|
|
132
|
+
return _clamp(float(reset), self.max_backoff_seconds)
|
|
133
|
+
base = self.initial_backoff_seconds * (2 ** max(0, attempt - 1))
|
|
134
|
+
base = min(base, self.max_backoff_seconds)
|
|
135
|
+
if self.jitter:
|
|
136
|
+
base = base * (0.5 + random.random() * 0.5)
|
|
137
|
+
return _clamp(base, self.max_backoff_seconds)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _clamp(v: float, ceiling: float) -> float:
|
|
141
|
+
return max(0.0, min(v, ceiling))
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _ci_get(headers: Mapping[str, str], name: str) -> str | None:
|
|
145
|
+
for k, val in headers.items():
|
|
146
|
+
if k.lower() == name.lower():
|
|
147
|
+
return val
|
|
148
|
+
return None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _parse_int(v: str | None) -> int | None:
|
|
152
|
+
if v is None:
|
|
153
|
+
return None
|
|
154
|
+
try:
|
|
155
|
+
return int(str(v).strip())
|
|
156
|
+
except (ValueError, TypeError):
|
|
157
|
+
return None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _parse_retry_after(v: str | None, *, now: float | None = None) -> float | None:
|
|
161
|
+
"""RFC 7231 Retry-After: either seconds (delta) or HTTP-date (absolute)."""
|
|
162
|
+
if v is None:
|
|
163
|
+
return None
|
|
164
|
+
s = str(v).strip()
|
|
165
|
+
if s.isdigit():
|
|
166
|
+
return float(s)
|
|
167
|
+
try:
|
|
168
|
+
dt = email.utils.parsedate_to_datetime(s)
|
|
169
|
+
target = dt.timestamp()
|
|
170
|
+
ref = now if now is not None else time.time()
|
|
171
|
+
return max(0.0, target - ref)
|
|
172
|
+
except (TypeError, ValueError):
|
|
173
|
+
return None
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""OAuth2 client_credentials token manager — lazy fetch, in-memory cache, 401 refresh.
|
|
2
|
+
|
|
3
|
+
client_credentials only, no refresh_token, no
|
|
4
|
+
explicit scope arg (server returns all authorized scopes). In-memory cache;
|
|
5
|
+
multi-instance clients each fetch independently — distributed cache is the
|
|
6
|
+
client's responsibility, not the SDK's.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import time
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from typing import TYPE_CHECKING
|
|
14
|
+
|
|
15
|
+
from .errors import FlowabbitOAuthError
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from ..http_client import HttpClient
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class AccessToken:
|
|
23
|
+
value: str
|
|
24
|
+
expires_at: float # epoch seconds
|
|
25
|
+
token_type: str = "Bearer"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TokenManager:
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
*,
|
|
32
|
+
client_id: str,
|
|
33
|
+
client_secret: str,
|
|
34
|
+
token_url: str,
|
|
35
|
+
http_client: "HttpClient",
|
|
36
|
+
cache_lifetime_buffer_seconds: float = 60.0,
|
|
37
|
+
clock: object = time,
|
|
38
|
+
) -> None:
|
|
39
|
+
if not client_id or not client_secret:
|
|
40
|
+
raise ValueError("client_id and client_secret are required")
|
|
41
|
+
if not token_url:
|
|
42
|
+
raise ValueError("token_url is required")
|
|
43
|
+
self._client_id = client_id
|
|
44
|
+
self._client_secret = client_secret
|
|
45
|
+
self._token_url = token_url
|
|
46
|
+
self._http = http_client
|
|
47
|
+
self._buffer = cache_lifetime_buffer_seconds
|
|
48
|
+
self._clock = clock
|
|
49
|
+
self._cached: AccessToken | None = None
|
|
50
|
+
|
|
51
|
+
def fetch(self) -> AccessToken:
|
|
52
|
+
"""Return a valid access token, fetching from the server if cache is stale."""
|
|
53
|
+
now = self._clock.time()
|
|
54
|
+
if self._cached is not None and self._cached.expires_at - self._buffer > now:
|
|
55
|
+
return self._cached
|
|
56
|
+
token = self._do_fetch()
|
|
57
|
+
self._cached = token
|
|
58
|
+
return token
|
|
59
|
+
|
|
60
|
+
def invalidate(self) -> None:
|
|
61
|
+
"""Drop the cached token. Next ``fetch()`` will re-request from the server."""
|
|
62
|
+
self._cached = None
|
|
63
|
+
|
|
64
|
+
def _do_fetch(self) -> AccessToken:
|
|
65
|
+
body = f"grant_type=client_credentials&client_id={self._client_id}&client_secret={self._client_secret}"
|
|
66
|
+
resp = self._http.request(
|
|
67
|
+
method="POST",
|
|
68
|
+
url=self._token_url,
|
|
69
|
+
headers={
|
|
70
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
71
|
+
"Accept": "application/json",
|
|
72
|
+
},
|
|
73
|
+
body=body.encode("utf-8"),
|
|
74
|
+
)
|
|
75
|
+
try:
|
|
76
|
+
payload = json.loads(resp.body.decode("utf-8")) if resp.body else {}
|
|
77
|
+
except (ValueError, UnicodeDecodeError) as exc:
|
|
78
|
+
raise FlowabbitOAuthError(
|
|
79
|
+
error="invalid_response",
|
|
80
|
+
error_description=f"token endpoint returned non-JSON body: {exc}",
|
|
81
|
+
http_status=resp.status,
|
|
82
|
+
raw_response=resp,
|
|
83
|
+
) from exc
|
|
84
|
+
|
|
85
|
+
if resp.status >= 400 or "access_token" not in payload:
|
|
86
|
+
raise FlowabbitOAuthError(
|
|
87
|
+
error=str(payload.get("error", "token_request_failed")),
|
|
88
|
+
error_description=payload.get("error_description"),
|
|
89
|
+
http_status=resp.status,
|
|
90
|
+
raw_response=payload,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
expires_in = payload.get("expires_in", 3600)
|
|
94
|
+
try:
|
|
95
|
+
expires_in = float(expires_in)
|
|
96
|
+
except (TypeError, ValueError):
|
|
97
|
+
expires_in = 3600.0
|
|
98
|
+
return AccessToken(
|
|
99
|
+
value=str(payload["access_token"]),
|
|
100
|
+
expires_at=self._clock.time() + expires_in,
|
|
101
|
+
token_type=str(payload.get("token_type", "Bearer")),
|
|
102
|
+
)
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Webhook verifier — Standard Webhooks signatures, ±5min skew, optional dedup hook.
|
|
2
|
+
|
|
3
|
+
The SDK is **stateless**. event_id 30-day dedup
|
|
4
|
+
is the client's responsibility — pass a ``dedup_hook(event_id) -> bool`` callable
|
|
5
|
+
that returns True when the event was already processed (caller should skip).
|
|
6
|
+
|
|
7
|
+
Deliveries follow the Standard Webhooks specification (https://www.standardwebhooks.com).
|
|
8
|
+
Headers (lookup is case-insensitive):
|
|
9
|
+
- webhook-id : event id, stable across retries (dedup key)
|
|
10
|
+
- webhook-timestamp : unix seconds at delivery time
|
|
11
|
+
- webhook-signature : space-separated ``v1,<base64>`` signatures; each is
|
|
12
|
+
HMAC-SHA256 over ``{webhook-id}.{webhook-timestamp}.{raw body}``
|
|
13
|
+
keyed with the base64-decoded secret after ``whsec_``.
|
|
14
|
+
During a secret rotation both secrets sign; any match passes.
|
|
15
|
+
- X-Flowabbit-Event : event type for routing before verification (not signed);
|
|
16
|
+
the verified event type is taken from the signed body.
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import base64
|
|
21
|
+
import binascii
|
|
22
|
+
import hashlib
|
|
23
|
+
import hmac
|
|
24
|
+
import json
|
|
25
|
+
import time
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from typing import Callable, Mapping
|
|
28
|
+
|
|
29
|
+
from .errors import FlowabbitWebhookDuplicateEventError, FlowabbitWebhookSignatureError
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class WebhookEvent:
|
|
34
|
+
event_id: str
|
|
35
|
+
event_type: str
|
|
36
|
+
timestamp: int
|
|
37
|
+
raw_body: bytes
|
|
38
|
+
# ``payload`` is intentionally typed as ``object`` rather than a TypedDict
|
|
39
|
+
# union of the WebhookEvent*Payload variants, so new event types and
|
|
40
|
+
# fields never break decoding.
|
|
41
|
+
payload: object
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
_HEADER_ID = "webhook-id"
|
|
45
|
+
_HEADER_TS = "webhook-timestamp"
|
|
46
|
+
_HEADER_SIG = "webhook-signature"
|
|
47
|
+
_SECRET_PREFIX = "whsec_"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _decode_secret(secret: str) -> bytes:
|
|
51
|
+
if not isinstance(secret, str) or not secret.startswith(_SECRET_PREFIX):
|
|
52
|
+
raise ValueError("secret must be whsec_<base64>")
|
|
53
|
+
try:
|
|
54
|
+
key = base64.b64decode(secret[len(_SECRET_PREFIX):], validate=True)
|
|
55
|
+
except (binascii.Error, ValueError) as exc:
|
|
56
|
+
raise ValueError("secret must be whsec_<base64>") from exc
|
|
57
|
+
if not 24 <= len(key) <= 64:
|
|
58
|
+
raise ValueError("secret must decode to 24-64 bytes")
|
|
59
|
+
return key
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class WebhookVerifier:
|
|
63
|
+
def __init__(
|
|
64
|
+
self,
|
|
65
|
+
*,
|
|
66
|
+
secret: str,
|
|
67
|
+
skew_seconds: int = 300,
|
|
68
|
+
dedup_hook: Callable[[str], bool] | None = None,
|
|
69
|
+
clock: object = time,
|
|
70
|
+
) -> None:
|
|
71
|
+
if not secret:
|
|
72
|
+
raise ValueError("secret is required")
|
|
73
|
+
if skew_seconds < 0:
|
|
74
|
+
raise ValueError("skew_seconds must be >= 0")
|
|
75
|
+
self._key = _decode_secret(secret)
|
|
76
|
+
self._skew = skew_seconds
|
|
77
|
+
self._dedup_hook = dedup_hook
|
|
78
|
+
self._clock = clock
|
|
79
|
+
|
|
80
|
+
def verify(self, *, headers: Mapping[str, str], raw_body: bytes) -> WebhookEvent:
|
|
81
|
+
"""Verify signature + skew, optionally call dedup_hook.
|
|
82
|
+
|
|
83
|
+
Raises ``FlowabbitWebhookSignatureError`` on a missing header, a bad
|
|
84
|
+
signature, a timestamp out of skew, or a signed body without ``event_type``;
|
|
85
|
+
``FlowabbitWebhookDuplicateEventError`` when ``dedup_hook`` returns True.
|
|
86
|
+
"""
|
|
87
|
+
event_id = _ci_get(headers, _HEADER_ID)
|
|
88
|
+
ts_str = _ci_get(headers, _HEADER_TS)
|
|
89
|
+
signature = _ci_get(headers, _HEADER_SIG)
|
|
90
|
+
for label, value in ((_HEADER_ID, event_id), (_HEADER_TS, ts_str), (_HEADER_SIG, signature)):
|
|
91
|
+
if value is None or value == "":
|
|
92
|
+
raise FlowabbitWebhookSignatureError(f"missing header: {label}")
|
|
93
|
+
|
|
94
|
+
try:
|
|
95
|
+
timestamp = int(ts_str)
|
|
96
|
+
except (TypeError, ValueError) as exc:
|
|
97
|
+
raise FlowabbitWebhookSignatureError(f"invalid timestamp: {ts_str!r}") from exc
|
|
98
|
+
|
|
99
|
+
now = int(self._clock.time())
|
|
100
|
+
if abs(now - timestamp) > self._skew:
|
|
101
|
+
raise FlowabbitWebhookSignatureError(
|
|
102
|
+
f"timestamp skew exceeds {self._skew}s (server={now} delivery={timestamp})"
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
mac = hmac.new(self._key, f"{event_id}.{timestamp}.".encode("utf-8"), hashlib.sha256)
|
|
106
|
+
mac.update(raw_body)
|
|
107
|
+
expected = "v1," + base64.b64encode(mac.digest()).decode("ascii")
|
|
108
|
+
if not any(hmac.compare_digest(expected, candidate) for candidate in signature.split(" ")):
|
|
109
|
+
raise FlowabbitWebhookSignatureError("signature mismatch")
|
|
110
|
+
|
|
111
|
+
try:
|
|
112
|
+
payload: object = json.loads(raw_body.decode("utf-8")) if raw_body else None
|
|
113
|
+
except (ValueError, UnicodeDecodeError):
|
|
114
|
+
payload = None
|
|
115
|
+
event_type = payload.get("event_type") if isinstance(payload, dict) else None
|
|
116
|
+
if not isinstance(event_type, str) or not event_type:
|
|
117
|
+
raise FlowabbitWebhookSignatureError("signed body has no event_type")
|
|
118
|
+
|
|
119
|
+
if self._dedup_hook is not None and self._dedup_hook(event_id):
|
|
120
|
+
# Duplicate ≠ signature failure. Raise a distinct exception
|
|
121
|
+
# so callers can ACK 200 silently instead of treating it as auth error.
|
|
122
|
+
raise FlowabbitWebhookDuplicateEventError(
|
|
123
|
+
event_id=event_id,
|
|
124
|
+
event_type=event_type,
|
|
125
|
+
timestamp=timestamp,
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
return WebhookEvent(
|
|
129
|
+
event_id=event_id,
|
|
130
|
+
event_type=event_type,
|
|
131
|
+
timestamp=timestamp,
|
|
132
|
+
raw_body=raw_body,
|
|
133
|
+
payload=payload,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _ci_get(headers: Mapping[str, str], name: str) -> str | None:
|
|
138
|
+
for k, val in headers.items():
|
|
139
|
+
if k.lower() == name.lower():
|
|
140
|
+
return val
|
|
141
|
+
return None
|