4949
5050_RATE_LIMIT_RE = re .compile (rb"blocked for (\d+) seconds" , re .IGNORECASE )
5151_RATE_LIMIT_WAIT_LOG = "Rate limited (429) for %s seconds; waiting it out"
52- _UNPARSABLE_INITIAL_WAIT_SECONDS = 5
5352_UNPARSABLE_COOLDOWN_BASE_SECONDS = 60
5453_UNPARSABLE_COOLDOWN_MAX_SECONDS = 600
5554_INCOMPLETE_MENU_CACHE_TTL_SECONDS = 3600
@@ -76,20 +75,6 @@ def _parse_retry_after_seconds(headers: Any) -> Optional[int]:
7675 return None
7776
7877
79- def _rate_limit_wait_seconds (content : bytes ) -> int :
80- """Effective wait for a 429: parsed duration + 1s margin, else 5s."""
81- parsed = _parse_block_seconds (content )
82- if parsed is None :
83- _LOGGER .warning (
84- "Rate limited (429) without parsable block duration; "
85- "falling back to %ss wait" ,
86- _UNPARSABLE_INITIAL_WAIT_SECONDS ,
87- )
88- return _UNPARSABLE_INITIAL_WAIT_SECONDS
89- _LOGGER .warning (_RATE_LIMIT_WAIT_LOG , parsed + 1 )
90- return parsed + 1
91-
92-
9378def _raise_unless_http_500 (error : ConnectionException ) -> None :
9479 """Re-raise ConnectionException unless its status code is HTTP 500."""
9580 if error .args [:1 ] != (500 ,):
@@ -147,6 +132,11 @@ def _menu_items_path(api_url: str, gw_id: str, menu_items_query: str) -> str:
147132class ConnectionException (Exception ):
148133 """When can not connect to Ariston cloud"""
149134
135+ def __init__ (self , * args : Any , retry_after : Optional [float ] = None ) -> None :
136+ """Initialize the connection exception with optional rate-limit delay."""
137+ super ().__init__ (* args )
138+ self .retry_after = retry_after
139+
150140
151141class AristonAPI :
152142 """Ariston API class"""
@@ -182,8 +172,18 @@ def __init__(
182172 # Sync (requests) R2 web-app session; created lazily on first use.
183173 self .__r2_requests_session : Optional [requests .Session ] = None
184174
185- def _bump_rate_limit_cooldown (self ) -> None :
175+ def _rate_limit_exception (self , payload : Any ) -> ConnectionException :
176+ """Build a 429 ConnectionException carrying the remaining block delay."""
177+ remaining = self ._blocked_until - time .time ()
178+ return ConnectionException (
179+ 429 ,
180+ payload ,
181+ retry_after = remaining if remaining > 0 else None ,
182+ )
183+
184+ def _bump_rate_limit_cooldown (self , now : Optional [float ] = None ) -> None :
186185 """Advance unparsable-429 streak and extend the shared block window."""
186+ current_time = time .time () if now is None else now
187187 self ._rate_limit_streak += 1
188188 cooldown = min (
189189 _UNPARSABLE_COOLDOWN_MAX_SECONDS ,
@@ -196,30 +196,29 @@ def _bump_rate_limit_cooldown(self) -> None:
196196 self ._rate_limit_streak ,
197197 cooldown ,
198198 )
199- self ._blocked_until = max (self ._blocked_until , time . time () + cooldown )
199+ self ._blocked_until = max (self ._blocked_until , current_time + cooldown )
200200
201201 def _prepare_rate_limit_retry (
202- self , content : bytes , headers : Any , is_retry : bool
202+ self , content : bytes , headers : Any , is_rate_limit_retry : bool
203203 ) -> Optional [tuple [int , int ]]:
204204 """Update rate-limit state and return the wait and epoch for a retry."""
205205 now = time .time ()
206206 parsed = _parse_block_seconds (content )
207207 if parsed is None :
208208 parsed = _parse_retry_after_seconds (headers )
209209
210- if parsed is not None :
211- wait_seconds = parsed + 1
212- _LOGGER .warning (_RATE_LIMIT_WAIT_LOG , wait_seconds )
213- elif self ._rate_limit_retry_in_flight and not is_retry :
214- return None
215- elif is_retry or self ._rate_limit_streak :
216- self ._bump_rate_limit_cooldown ()
210+ if parsed is None :
211+ if not is_rate_limit_retry and (
212+ self ._rate_limit_retry_in_flight or now < self ._blocked_until
213+ ):
214+ return None
215+ self ._bump_rate_limit_cooldown (now )
217216 return None
218- else :
219- wait_seconds = _rate_limit_wait_seconds (content )
220217
218+ wait_seconds = parsed + 1
219+ _LOGGER .warning (_RATE_LIMIT_WAIT_LOG , wait_seconds )
221220 self ._blocked_until = max (self ._blocked_until , now + wait_seconds )
222- if is_retry or self ._rate_limit_retry_in_flight :
221+ if is_rate_limit_retry or self ._rate_limit_retry_in_flight :
223222 return None
224223
225224 return (math .ceil (self ._blocked_until - now ), self ._rate_limit_retry_epoch )
@@ -258,6 +257,8 @@ def connect(self) -> bool:
258257
259258 return True
260259
260+ except ConnectionException :
261+ raise
261262 except Exception as error :
262263 raise ConnectionException () from error
263264
@@ -782,12 +783,12 @@ def __request(
782783 params : Optional [dict [str , Any ]] = None ,
783784 body : Any = None ,
784785 is_retry : bool = False ,
786+ rate_limit_retry : bool = False ,
785787 ) -> Optional [dict [str , Any ]]:
786788 """Request with requests"""
787- if not is_retry and time .time () < self ._blocked_until :
788- raise ConnectionException (
789- 429 ,
790- "Rate limited; skipping request until the block window ends" ,
789+ if not rate_limit_retry and time .time () < self ._blocked_until :
790+ raise self ._rate_limit_exception (
791+ "Rate limited; skipping request until the block window ends"
791792 )
792793 headers : dict [str , Any ] = {
793794 "User-Agent" : self .__user_agent ,
@@ -815,15 +816,16 @@ def __request(
815816 return None
816817 case 429 :
817818 return self .__handle_rate_limit (
818- response , is_retry , method , path , params , body
819+ response , rate_limit_retry , method , path , params , body
819820 )
820821 case _:
821822 if not is_retry :
822823 time .sleep (5 )
823824 return self .__request (method , path , params , body , True )
824825 raise ConnectionException (response .status_code )
825826
826- self ._rate_limit_streak = 0
827+ if time .time () >= self ._blocked_until :
828+ self ._rate_limit_streak = 0
827829 if len (response .content ) > 0 :
828830 json = response .json ()
829831 _LOGGER .debug ("Response %s" , json )
@@ -838,7 +840,7 @@ def _post(self, path: str, body: Any) -> Any:
838840 def __handle_rate_limit (
839841 self ,
840842 response ,
841- is_retry : bool ,
843+ is_rate_limit_retry : bool ,
842844 method : str ,
843845 path : str ,
844846 params : Optional [dict [str , Any ]],
@@ -847,16 +849,18 @@ def __handle_rate_limit(
847849 """Sleep out the 429 block window, retry once, per-instance deadline."""
848850 content = response .content
849851 headers = getattr (response , "headers" , None )
850- retry_plan = self ._prepare_rate_limit_retry (content , headers , is_retry )
852+ retry_plan = self ._prepare_rate_limit_retry (
853+ content , headers , is_rate_limit_retry
854+ )
851855 if retry_plan is not None :
852856 wait_seconds , epoch = retry_plan
853857 time .sleep (wait_seconds )
854858 if self ._claim_rate_limit_retry (epoch ):
855859 try :
856- return self .__request (method , path , params , body , True )
860+ return self .__request (method , path , params , body , True , True )
857861 finally :
858862 self ._rate_limit_retry_in_flight = False
859- raise ConnectionException ( response . status_code , content .decode ())
863+ raise self . _rate_limit_exception ( content .decode ())
860864
861865 def _get (self , path : str , params : Optional [dict [str , Any ]] = None ) -> Any :
862866 """GET request"""
@@ -991,6 +995,8 @@ async def async_connect(self) -> bool:
991995
992996 return True
993997
998+ except ConnectionException :
999+ raise
9941000 except Exception as error :
9951001 raise ConnectionException () from error
9961002
@@ -1749,12 +1755,12 @@ async def __async_request(
17491755 body : Any = None ,
17501756 is_retry : bool = False ,
17511757 timeout_seconds : int = 30 ,
1758+ rate_limit_retry : bool = False ,
17521759 ) -> Optional [dict [str , Any ]]:
17531760 """Async request with aiohttp"""
1754- if not is_retry and time .time () < self ._blocked_until :
1755- raise ConnectionException (
1756- 429 ,
1757- "Rate limited; skipping request until the block window ends" ,
1761+ if not rate_limit_retry and time .time () < self ._blocked_until :
1762+ raise self ._rate_limit_exception (
1763+ "Rate limited; skipping request until the block window ends"
17581764 )
17591765 headers : dict [str , Any ] = {
17601766 "User-Agent" : self .__user_agent ,
@@ -1791,7 +1797,13 @@ async def __async_request(
17911797 return None
17921798 case 429 :
17931799 return await self .__async_handle_rate_limit (
1794- response , is_retry , method , path , params , body , timeout_seconds
1800+ response ,
1801+ rate_limit_retry ,
1802+ method ,
1803+ path ,
1804+ params ,
1805+ body ,
1806+ timeout_seconds ,
17951807 )
17961808 case _:
17971809 if not is_retry :
@@ -1801,7 +1813,8 @@ async def __async_request(
18011813 )
18021814 raise ConnectionException (response .status )
18031815
1804- self ._rate_limit_streak = 0
1816+ if time .time () >= self ._blocked_until :
1817+ self ._rate_limit_streak = 0
18051818 if response .content_length and response .content_length > 0 :
18061819 json = await response .json ()
18071820 _LOGGER .debug ("Response %s" , json )
@@ -1820,7 +1833,7 @@ async def _async_post(
18201833 async def __async_handle_rate_limit (
18211834 self ,
18221835 response ,
1823- is_retry : bool ,
1836+ is_rate_limit_retry : bool ,
18241837 method : str ,
18251838 path : str ,
18261839 params : Optional [dict [str , Any ]],
@@ -1830,18 +1843,20 @@ async def __async_handle_rate_limit(
18301843 """Sleep out the 429 block window, retry once, share the deadline."""
18311844 content = await response .content .read ()
18321845 headers = getattr (response , "headers" , None )
1833- retry_plan = self ._prepare_rate_limit_retry (content , headers , is_retry )
1846+ retry_plan = self ._prepare_rate_limit_retry (
1847+ content , headers , is_rate_limit_retry
1848+ )
18341849 if retry_plan is not None :
18351850 wait_seconds , epoch = retry_plan
18361851 await asyncio .sleep (wait_seconds )
18371852 if self ._claim_rate_limit_retry (epoch ):
18381853 try :
18391854 return await self .__async_request (
1840- method , path , params , body , True , timeout_seconds
1855+ method , path , params , body , True , timeout_seconds , True
18411856 )
18421857 finally :
18431858 self ._rate_limit_retry_in_flight = False
1844- raise ConnectionException ( response . status , content )
1859+ raise self . _rate_limit_exception ( content )
18451860
18461861 async def _async_get (
18471862 self , path : str , params : Optional [dict [str , Any ]] = None
0 commit comments