From 0026eaa2ca7bd094db1ebabc5d39b1bba05516c7 Mon Sep 17 00:00:00 2001 From: Jonathan Laliberte Date: Thu, 10 Oct 2024 16:55:00 -0400 Subject: [PATCH] #171 - Use exponential backoff when logging into Unifi API (#172) --- unifi_protect_backup/unifi_protect_backup_core.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/unifi_protect_backup/unifi_protect_backup_core.py b/unifi_protect_backup/unifi_protect_backup_core.py index f703795..24fd246 100644 --- a/unifi_protect_backup/unifi_protect_backup_core.py +++ b/unifi_protect_backup/unifi_protect_backup_core.py @@ -197,18 +197,23 @@ class UnifiProtectBackup: # Start the uiprotect connection by calling `update` logger.info("Connecting to Unifi Protect...") - for attempts in range(10): + delay = 5 # Start with a 5 second delay + max_delay = 3600 # 1 hour in seconds + + for attempts in range(20): try: await self._protect.update() break except Exception as e: logger.warning( - f"Failed to connect to UniFi Protect, retrying in {attempts}s...", + f"Failed to connect to UniFi Protect, retrying in {delay}s...", exc_info=e, ) - await asyncio.sleep(attempts) + await asyncio.sleep(delay) + delay = min(max_delay, delay * 2) # Double the delay but do not exceed max_delay else: - raise ConnectionError("Failed to connect to UniFi Protect after 10 attempts") + raise ConnectionError("Failed to connect to UniFi Protect after 20 attempts") + # Add a lock to the protect client that can be used to prevent code accessing the client when it has # lost connection