Skip to content

Commit 21372fc

Browse files
committed
ensure connection stronger
1 parent 8eeed13 commit 21372fc

1 file changed

Lines changed: 48 additions & 9 deletions

File tree

subvortex/core/database/database.py

Lines changed: 48 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ async def get_client(self):
3636
btul.logging.info(
3737
"Created new Redis client for event loop", prefix=self.settings.logging_name
3838
)
39+
3940
return client
4041

4142
async def is_connection_alive(self) -> bool:
@@ -51,14 +52,52 @@ async def is_connection_alive(self) -> bool:
5152
return False
5253

5354
async def ensure_connection(self):
54-
client = await self.get_client()
55-
56-
if not await self.is_connection_alive():
57-
btul.logging.warning(
58-
"Redis ping failed, but client will be reused",
59-
prefix=self.settings.logging_name,
60-
)
61-
# You may optionally recreate here if needed
55+
retry_delay = 1.0 # Start with 1 second
56+
attempt = 0
57+
58+
while True:
59+
attempt += 1
60+
61+
if await self.is_connection_alive():
62+
# Connection is working
63+
if attempt > 1:
64+
btul.logging.info(
65+
f"✅ Redis connection restored after {attempt - 1} attempts",
66+
prefix=self.settings.logging_name,
67+
)
68+
return
69+
70+
# Connection failed
71+
if attempt == 1:
72+
btul.logging.warning(
73+
"🔄 Redis connection lost, will keep trying until restored...",
74+
prefix=self.settings.logging_name,
75+
)
76+
77+
# Remove broken client from cache
78+
loop = self._get_loop()
79+
if loop in self._clients:
80+
try:
81+
await self._clients[loop].close()
82+
except:
83+
pass # Ignore errors when closing broken client
84+
del self._clients[loop]
85+
86+
# Log every 10 attempts to avoid spam
87+
if attempt % 10 == 0:
88+
btul.logging.warning(
89+
f"🔄 Redis still unreachable after {attempt} attempts, continuing...",
90+
prefix=self.settings.logging_name,
91+
)
92+
else:
93+
btul.logging.debug(
94+
f"🔄 Redis reconnection attempt {attempt} failed, retrying in {retry_delay}s...",
95+
prefix=self.settings.logging_name,
96+
)
97+
98+
await asyncio.sleep(retry_delay)
99+
# Exponential backoff with cap
100+
retry_delay = min(retry_delay * 1.2, 30.0) # Cap at 30 seconds
62101

63102
async def wait_until_ready(self, name: str):
64103
await self.ensure_connection()
@@ -108,7 +147,7 @@ async def wait_until_ready(self, name: str):
108147

109148
async def _get_migration_status(self, model_name: str):
110149
await self.ensure_connection()
111-
150+
112151
client = await self.get_client()
113152

114153
latest = None

0 commit comments

Comments
 (0)