44
55import builtins
66import json
7+ import random
8+ import time
9+ import uuid
710from pathlib import Path
8- from typing import Any , IO , Sequence , Union
11+ from typing import Any , Callable , IO , Sequence , Union
912
1013import requests
1114from requests import Response
2528
2629DEFAULT_BASE_URL = "http://localhost:8080/api/v1"
2730DEFAULT_TIMEOUT = 30
31+ DEFAULT_MAX_RETRY_DELAY = 60.0
2832
2933ImageInput = 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
3251def _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 )
0 commit comments