From 401bffb5f3656b11168c09a9910294d1a1aa0c6e Mon Sep 17 00:00:00 2001 From: Dan Kelley Date: Wed, 16 Feb 2022 21:05:08 -0500 Subject: [PATCH] retry 401s from the envoy Because there can be enough time between when _is_enphase_token_expired() is called and when the subsequent http request to the envoy happens, the token freshness check can pass but the envoy will still see an expired token. This results in a 401 from the envoy, which raises an exception. This change looks for these 401s and attempts to refresh the token twice before giving up. --- envoy_reader/envoy_reader.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/envoy_reader/envoy_reader.py b/envoy_reader/envoy_reader.py index 13186ef..7509389 100644 --- a/envoy_reader/envoy_reader.py +++ b/envoy_reader/envoy_reader.py @@ -164,6 +164,13 @@ async def _async_fetch_with_retry(self, url, **kwargs): resp = await client.get( url, headers=self._authorization_header, timeout=30, **kwargs ) + if resp.status_code == 401 and attempt < 2: + _LOGGER.debug( + "Received 401 from Envoy; refreshing token, attempt %s of 2", + attempt+1, + ) + await self._getEnphaseToken() + continue _LOGGER.debug("Fetched from %s: %s: %s", url, resp, resp.text) return resp except httpx.TransportError: