refactor DB health-check

This commit is contained in:
David Rodenkirchen 2024-09-03 17:33:37 +02:00
parent 1ca7db6427
commit eb7d94d46c
3 changed files with 26 additions and 8 deletions

View File

@ -4,12 +4,18 @@ from typing import * # type: ignore
from rio import Component, event, Spacer, Card, Container, Column, Row, TextStyle, Color, Text
from src.ez_lan_manager import ConfigurationService
from src.ez_lan_manager import ConfigurationService, DatabaseService
from src.ez_lan_manager.components.DesktopNavigation import DesktopNavigation
class BasePage(Component):
content: Component
@event.periodic(5)
async def check_db_conn(self) -> None:
is_healthy = await self.session[DatabaseService].is_healthy()
if not is_healthy:
self.session.navigate_to("./db-error")
@event.on_window_size_change
async def on_window_size_change(self):
await self.force_refresh()

View File

@ -15,12 +15,12 @@ class DbErrorPage(Component):
async def on_window_size_change(self) -> None:
await self.force_refresh()
# @event.on_mount
# async def retry_db_connect(self) -> None:
# await self.session.set_title(f"{self.session[ConfigurationService].get_lan_info().name} - Fehler")
# while not self.session[DatabaseService].is_connected:
# await sleep(2)
# self.session.navigate_to("./")
@event.on_mount
async def retry_db_connect(self) -> None:
await self.session.set_title(f"{self.session[ConfigurationService].get_lan_info().name} - Fehler")
while not await self.session[DatabaseService].is_healthy():
await sleep(2)
self.session.navigate_to("./")
def build(self) -> Component:
content = Card(

View File

@ -29,6 +29,17 @@ class DatabaseService:
self._database_config = database_config
self._connection_pool: Optional[aiomysql.Pool] = None
async def is_healthy(self) -> bool:
try:
async with self._connection_pool.acquire() as conn:
async with conn.cursor() as _:
return True
except aiomysql.OperationalError:
return False
except Exception as e:
logger.error(f"Failed to acquire a connection: {e}")
return False
async def init_db_pool(self) -> bool:
logger.info(
f"Connecting to database '{self._database_config.db_name}' on "
@ -42,7 +53,7 @@ class DatabaseService:
password=self._database_config.db_password,
db=self._database_config.db_name,
minsize=1,
maxsize=20
maxsize=40
)
except aiomysql.OperationalError:
return False
@ -215,6 +226,7 @@ class DatabaseService:
except aiomysql.InterfaceError:
pool_init_result = await self.init_db_pool()
if not pool_init_result:
print(self._connection_pool)
raise NoDatabaseConnectionError
return await self.get_news(dt_start, dt_end)
except Exception as e: