Skip to content

Commit 08bcedd

Browse files
authored
Add idempotency keys, Retry-After and opt-in retries (#6)
Enrolment, synchronous batch and asynchronous batch calls take an idempotency key, sent as the Idempotency-Key header, and a generator returns a random UUID v4 for it. The API replays the first outcome for an identical repeat, so a retry after a lost response cannot enrol twice. The typed API error now carries retryAfter, the seconds from a Retry-After header. Retries are off by default. When enabled with a maximum number of retries: 429 and 503 wait for Retry-After (capped, default 60 s) or an exponential backoff with jitter; network errors and other 5xx are retried only for GET, PATCH and DELETE and for keyed requests; other 4xx are never retried. Enrolment and batch calls generate one key per call when retries are on and none was given, and send it on every attempt.
1 parent 45df1d4 commit 08bcedd

5 files changed

Lines changed: 333 additions & 7 deletions

File tree

‎README.md‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,47 @@ except LiveXFaceNetworkError as e:
119119
print(f"Network error: {e}")
120120
```
121121

122+
`LiveXFaceApiError` carries `status_code`, `code`, the message (`str(e)`),
123+
`request_id`, `details` (a dict, or `None`) and `retry_after`: the seconds from
124+
the response's `Retry-After` header on a 429 or 503, or `None` when it had none.
125+
126+
## Idempotent Requests
127+
128+
`register`, `batch_register` and `batch_register_async` accept an
129+
`idempotency_key`, sent as the `Idempotency-Key` header. The API remembers the
130+
answer to a keyed request for 24 hours: sending the same request with the same
131+
key again returns that stored answer, with the header `Idempotent-Replayed: true`,
132+
instead of enrolling the faces a second time. So a call that timed out or lost
133+
its connection can be repeated without creating duplicates.
134+
135+
- The same key with a different request is answered 422 `IDEMPOTENCY_KEY_MISMATCH`.
136+
- The same key while the first request is still running is answered 409 `IDEMPOTENCY_KEY_IN_USE`.
137+
- 429 and 5xx answers are not remembered, so a retry with the same key runs the request again.
138+
- Other 4xx answers are remembered: after fixing the request, send it with a new key.
139+
140+
`new_idempotency_key()` returns a random key (a UUID v4).
141+
142+
## Production Retries
143+
144+
Retries are off by default. `max_retries` turns them on (the number of attempts
145+
after the first): a 429 or 503 is retried after its `Retry-After`, capped at
146+
`max_retry_delay`, or after an exponential backoff with jitter when it gives
147+
none. A network error or another 5xx is retried only for reads, deletions and
148+
calls that carry an idempotency key; other 4xx are never retried. Enrolment and
149+
batch calls send one key on every attempt, generating it when you give none.
150+
151+
```python
152+
from livexface import LiveXFace, LiveXFaceApiError, new_idempotency_key
153+
154+
client = LiveXFace(api_key="lxf_live_xxxx", max_retries=3)
155+
156+
key = new_idempotency_key() # store it with your record to retry safely later
157+
try:
158+
face = client.faces.register("collection-uuid", open("alice.jpg", "rb"), "user_123", idempotency_key=key)
159+
except LiveXFaceApiError as e:
160+
print(f"[{e.code}] {e.status_code}: {e} (request {e.request_id}, retry after {e.retry_after}s)")
161+
```
162+
122163
## Image Input Types
123164

124165
The SDK accepts images as:
@@ -133,3 +174,5 @@ The SDK accepts images as:
133174
| `api_key` | **required** | Your API key (`lxf_live_xxx`) |
134175
| `base_url` | `http://localhost:8080/api/v1` | Base URL of the LiveXFace server |
135176
| `timeout` | `30` | Request timeout in seconds |
177+
| `max_retries` | `0` | Retries after the first attempt; 0 turns retries off |
178+
| `max_retry_delay` | `60` | Longest wait between attempts, in seconds |

‎livexface/__init__.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""LiveXFace Python SDK — Face Recognition as a Service."""
22

3-
from .client import LiveXFace
3+
from .client import LiveXFace, new_idempotency_key
44
from .exceptions import LiveXFaceApiError, LiveXFaceNetworkError
55
from .types import (
66
Face,
@@ -21,6 +21,7 @@
2121
__version__ = "0.1.0"
2222
__all__ = [
2323
"LiveXFace",
24+
"new_idempotency_key",
2425
"LiveXFaceApiError",
2526
"LiveXFaceNetworkError",
2627
"Face",

‎livexface/client.py‎

Lines changed: 93 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,11 @@
44

55
import builtins
66
import json
7+
import random
8+
import time
9+
import uuid
710
from pathlib import Path
8-
from typing import Any, IO, Sequence, Union
11+
from typing import Any, Callable, IO, Sequence, Union
912

1013
import requests
1114
from requests import Response
@@ -25,9 +28,25 @@
2528

2629
DEFAULT_BASE_URL = "http://localhost:8080/api/v1"
2730
DEFAULT_TIMEOUT = 30
31+
DEFAULT_MAX_RETRY_DELAY = 60.0
2832

2933
ImageInput = Union[bytes, str, Path, IO[bytes]]
3034

35+
# Repeating these is harmless, so a network error or a 5xx may be retried.
36+
_SAFE_METHODS = frozenset({"GET", "PATCH", "DELETE"})
37+
38+
39+
def new_idempotency_key() -> str:
40+
"""Return a random key (UUID v4) for the ``idempotency_key`` argument."""
41+
return str(uuid.uuid4())
42+
43+
44+
def _retry_after(resp: Response) -> int | None:
45+
value = resp.headers.get("Retry-After")
46+
if isinstance(value, str) and value.strip().isdecimal():
47+
return int(value)
48+
return None
49+
3150

3251
def _to_bytes_tuple(src: ImageInput, filename: str = "image.jpg") -> tuple[str, bytes, str]:
3352
"""Convert an image source to a (filename, bytes, content_type) tuple for requests."""
@@ -70,16 +89,57 @@ def __init__(
7089
api_key: str,
7190
base_url: str = DEFAULT_BASE_URL,
7291
timeout: int = DEFAULT_TIMEOUT,
92+
max_retries: int = 0,
93+
max_retry_delay: float = DEFAULT_MAX_RETRY_DELAY,
94+
sleep: Callable[[float], None] = time.sleep,
7395
) -> None:
96+
"""
97+
:param max_retries: Retries after the first attempt; 0 (the default)
98+
turns retries off. A 429 or 503 is retried after its
99+
``Retry-After`` (or an exponential backoff with jitter); a network
100+
error or another 5xx only for GET, PATCH and DELETE calls and for
101+
calls that carry an idempotency key. Other 4xx are never retried.
102+
:param max_retry_delay: Upper bound, in seconds, of one wait between
103+
attempts.
104+
:param sleep: Called with the delay before each retry; tests replace it.
105+
"""
74106
self.api_key = api_key
75107
self.base_url = base_url.rstrip("/")
76108
self.timeout = timeout
109+
self.max_retries = max_retries
110+
self.max_retry_delay = max_retry_delay
111+
self._sleep = sleep
77112
self._session = requests.Session()
78113
self._session.headers.update({"X-API-Key": api_key})
79114

80115
self.faces = FacesResource(self)
81116

82-
def _request(self, method: str, endpoint: str, **kwargs: Any) -> Any:
117+
def _request(
118+
self, method: str, endpoint: str, idempotency_key: str | None = None, **kwargs: Any
119+
) -> Any:
120+
if idempotency_key:
121+
kwargs["headers"] = {"Idempotency-Key": idempotency_key}
122+
# A keyed request is safe to repeat: the API replays the first answer.
123+
safe = method in _SAFE_METHODS or bool(idempotency_key)
124+
attempt = 0
125+
while True:
126+
try:
127+
return self._send(method, endpoint, **kwargs)
128+
except LiveXFaceApiError as exc:
129+
retryable = exc.status_code in (429, 503) or (exc.status_code >= 500 and safe)
130+
if not retryable or attempt >= self.max_retries:
131+
raise
132+
wait: float | None = exc.retry_after
133+
except LiveXFaceNetworkError:
134+
if not safe or attempt >= self.max_retries:
135+
raise
136+
wait = None
137+
if wait is None:
138+
wait = random.uniform(0, 0.5 * 2**attempt)
139+
self._sleep(min(wait, self.max_retry_delay))
140+
attempt += 1
141+
142+
def _send(self, method: str, endpoint: str, **kwargs: Any) -> Any:
83143
url = f"{self.base_url}{endpoint}"
84144
try:
85145
resp: Response = self._session.request(
@@ -102,7 +162,10 @@ def _request(self, method: str, endpoint: str, **kwargs: Any) -> Any:
102162
# envelope; report the HTTP status rather than a parse failure.
103163
if not resp.ok:
104164
raise LiveXFaceApiError(
105-
f"HTTP_{resp.status_code}", f"Request failed with HTTP {resp.status_code}", resp.status_code
165+
f"HTTP_{resp.status_code}",
166+
f"Request failed with HTTP {resp.status_code}",
167+
resp.status_code,
168+
retry_after=_retry_after(resp),
106169
) from exc
107170
raise LiveXFaceApiError("PARSE_ERROR", "Failed to parse response body", resp.status_code) from exc
108171

@@ -114,6 +177,7 @@ def _request(self, method: str, endpoint: str, **kwargs: Any) -> Any:
114177
status_code=resp.status_code,
115178
request_id=parsed.get("requestId"),
116179
details=err.get("details"),
180+
retry_after=_retry_after(resp),
117181
)
118182

119183
return parsed.get("data")
@@ -125,19 +189,30 @@ class FacesResource:
125189
def __init__(self, client: LiveXFace) -> None:
126190
self._c = client
127191

192+
def _key(self, idempotency_key: str | None) -> str | None:
193+
# With retries on, every attempt of one call must carry the same key,
194+
# so a call without one gets its own.
195+
if idempotency_key is None and self._c.max_retries > 0:
196+
return new_idempotency_key()
197+
return idempotency_key
198+
128199
def register(
129200
self,
130201
collection_id: str,
131202
image: ImageInput,
132203
external_id: str,
133204
metadata: dict[str, Any] | None = None,
134205
liveness_token: str | None = None,
206+
idempotency_key: str | None = None,
135207
) -> Face:
136208
"""Register a face in a collection.
137209
138210
:param liveness_token: Token from a passed :meth:`active_liveness`
139211
check. Required when the collection requires liveness on enrolment;
140212
single-use, valid for 5 minutes, and bound to the collection.
213+
:param idempotency_key: Sent as ``Idempotency-Key``; repeating the call
214+
with the same key within 24 hours replays the first answer instead
215+
of enrolling again. See :func:`new_idempotency_key`.
141216
"""
142217
fname, fbytes, ftype = _to_bytes_tuple(image)
143218
files = {"image": (fname, fbytes, ftype)}
@@ -146,7 +221,13 @@ def register(
146221
data["metadata"] = json.dumps(metadata)
147222
if liveness_token:
148223
data["liveness_token"] = liveness_token
149-
resp = self._c._request("POST", f"/collections/{collection_id}/faces", files=files, data=data)
224+
resp = self._c._request(
225+
"POST",
226+
f"/collections/{collection_id}/faces",
227+
idempotency_key=self._key(idempotency_key),
228+
files=files,
229+
data=data,
230+
)
150231
return Face.from_dict(resp)
151232

152233
def list(
@@ -293,13 +374,15 @@ def batch_register(
293374
self,
294375
collection_id: str,
295376
items: builtins.list[dict[str, Any]],
377+
idempotency_key: str | None = None,
296378
) -> BatchResponse:
297379
"""
298380
Batch register up to 20 faces in a single request.
299381
300382
Each item must have ``image`` (ImageInput) and ``external_id`` (str).
301383
Optional ``metadata`` dict and ``liveness_token`` (str, from
302-
:meth:`active_liveness`) are also supported.
384+
:meth:`active_liveness`) are also supported. ``idempotency_key`` works
385+
as in :meth:`register`.
303386
304387
Example::
305388
@@ -323,6 +406,7 @@ def batch_register(
323406
resp = self._c._request(
324407
"POST",
325408
f"/collections/{collection_id}/faces/batch",
409+
idempotency_key=self._key(idempotency_key),
326410
files=files,
327411
data={"entries": json.dumps(entries)},
328412
)
@@ -351,6 +435,7 @@ def batch_register_async(
351435
self,
352436
collection_id: str,
353437
items: builtins.list[dict[str, Any]],
438+
idempotency_key: str | None = None,
354439
) -> BatchJob:
355440
"""
356441
Submit up to 100 faces for asynchronous registration. Returns a job
@@ -359,7 +444,8 @@ def batch_register_async(
359444
360445
Each item must have ``image`` (ImageInput) and ``external_id`` (str).
361446
Optional ``metadata`` dict and ``liveness_token`` (str, from
362-
:meth:`active_liveness`) are also supported.
447+
:meth:`active_liveness`) are also supported. ``idempotency_key`` works
448+
as in :meth:`register`.
363449
"""
364450
files: dict[str, Any] = {}
365451
entries: builtins.list[dict[str, Any]] = []
@@ -376,6 +462,7 @@ def batch_register_async(
376462
resp = self._c._request(
377463
"POST",
378464
f"/collections/{collection_id}/faces/batch-async",
465+
idempotency_key=self._key(idempotency_key),
379466
files=files,
380467
data={"entries": json.dumps(entries)},
381468
)

‎livexface/exceptions.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ def __init__(
1313
status_code: int,
1414
request_id: str | None = None,
1515
details: dict[str, Any] | None = None,
16+
retry_after: int | None = None,
1617
) -> None:
1718
super().__init__(message)
1819
self.code = code
@@ -21,6 +22,9 @@ def __init__(
2122
# Machine-readable context when the API sends it, e.g. faceCount and
2223
# faces for MULTIPLE_FACES.
2324
self.details = details
25+
# Seconds from the response's Retry-After header (429, 503), or None
26+
# when it had none.
27+
self.retry_after = retry_after
2428

2529
def __repr__(self) -> str:
2630
return f"LiveXFaceApiError(code={self.code!r}, status_code={self.status_code}, message={str(self)!r})"

0 commit comments

Comments
 (0)