From 396535f1751b48919a13a931d2230cfd0113eaa7 Mon Sep 17 00:00:00 2001
From: Eviee Py <evieepy@gmail.com>
Date: Thu, 25 Jul 2024 12:24:35 +1000
Subject: [PATCH] Handle cancelled redis connection checks.

---
 starlette_plus/redis.py | 26 ++++++++++++++++++--------
 1 file changed, 18 insertions(+), 8 deletions(-)

diff --git a/starlette_plus/redis.py b/starlette_plus/redis.py
index cec0c41..6413bc0 100644
--- a/starlette_plus/redis.py
+++ b/starlette_plus/redis.py
@@ -52,11 +52,21 @@ async def ping(self) -> bool:
         return self._could_connect
 
     async def _health_task(self) -> None:
-        while True:
-            previous = self.could_connect
-            await self.ping()
-
-            if not previous and self.could_connect:
-                logger.info("Redis connection has been (re)established: %s", self.url)
-
-            await asyncio.sleep(5)
+        try:
+            while True:
+                previous = self.could_connect
+                await self.ping()
+
+                if not previous and self.could_connect:
+                    logger.info("Redis connection has been (re)established: %s", self.url)
+
+                await asyncio.sleep(5)
+        except asyncio.CancelledError:
+            logger.warning(
+                'Redis connection: "%s" health check was cancelled. Safe to ignore on shutdown. '
+                "If this was not intentional, all middleware relying on this connection will now be in-memory.",
+                self.url,
+            )
+            self._could_connect = False
+        finally:
+            await self.pool.aclose()