Skip to content

Commit

Permalink
Tweak retry on usage to try more times and with bigger gaps between r…
Browse files Browse the repository at this point in the history
…etries. Caller can change settings or disable.
  • Loading branch information
magico13 committed Mar 3, 2024
1 parent a9708a9 commit 714d193
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
5 changes: 1 addition & 4 deletions pyemvue/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def __init__(
self.read_timeout = read_timeout
self.token_updater = token_updater
self.max_retry_attempts = max(max_retry_attempts, 1)
self.initial_retry_delay = max(initial_retry_delay, 0)
self.initial_retry_delay = max(initial_retry_delay, 0.5)
self.max_retry_delay = max(max_retry_delay, 0)
self.pool_wellknown_jwks = None

Expand Down Expand Up @@ -98,9 +98,6 @@ def request(self, method: str, path: str, **kwargs) -> requests.Response:
self.initial_retry_delay * (2 ** (attempts - 1)),
self.max_retry_delay,
)
print(
f"Server error {response.status_code}, retrying in {delay} seconds"
)
time.sleep(delay)
continue

Expand Down
19 changes: 15 additions & 4 deletions pyemvue/pyemvue.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,9 @@ def get_device_list_usage(
instant: Optional[datetime.datetime],
scale=Scale.SECOND.value,
unit=Unit.KWH.value,
max_retry_attempts: int = 5,
initial_retry_delay: float = 2.0,
max_retry_delay: float = 30.0,
) -> "dict[int, VueUsageDevice]":
"""Returns a nested dictionary of VueUsageDevice and VueDeviceChannelUsage with the total usage of the devices over the specified scale. Note that you may need to scale this to get a rate (1MIN in kw = 60*result)"""
if not instant:
Expand All @@ -119,14 +122,19 @@ def get_device_list_usage(
url = API_DEVICES_USAGE.format(
deviceGids=gids, instant=_format_time(instant), scale=scale, unit=unit
)
max_attempts = 3
attempts = 0
success = False
max_retry_attempts = max(max_retry_attempts, 1)
initial_retry_delay = max(initial_retry_delay, 0.5)
max_retry_delay = max(max_retry_delay, 0)

while attempts < max_attempts and not success:
while attempts < max_retry_attempts and not success:
if attempts > 0:
# if we're retrying, wait a bit before trying again
delay = 2**attempts
# if we're retrying, wait a bit before trying again using an exponential backoff
delay = min(
initial_retry_delay * (2 ** (attempts - 1)),
max_retry_delay,
)
time.sleep(delay)
attempts += 1
response = self.auth.request("get", url)
Expand All @@ -153,6 +161,9 @@ def get_device_list_usage(
success = False
else:
success = False

# if we still haven't fully succeeded, return the data we did manage to get

if response:
response.raise_for_status()
return devices
Expand Down

0 comments on commit 714d193

Please sign in to comment.