Coverage for dj/api/health.py: 100%

23 statements  

« prev     ^ index     » next       coverage.py v7.2.3, created at 2023-04-17 20:05 -0700

1""" 

2Application healthchecks. 

3""" 

4 

5import enum 

6from typing import List 

7 

8from fastapi import APIRouter, Depends 

9from sqlalchemy import select 

10from sqlmodel import Session, SQLModel 

11 

12from dj.utils import get_session 

13 

14router = APIRouter() 

15 

16 

17class HealthcheckStatus(str, enum.Enum): 

18 """ 

19 Possible health statuses. 

20 """ 

21 

22 OK = "ok" 

23 FAILED = "failed" 

24 

25 

26class HealthCheck(SQLModel): 

27 """ 

28 A healthcheck response. 

29 """ 

30 

31 name: str 

32 status: HealthcheckStatus 

33 

34 

35async def database_health(session: Session) -> HealthcheckStatus: 

36 """ 

37 The status of the database. 

38 """ 

39 try: 

40 result = session.execute(select(1)).one() 

41 health_status = ( 

42 HealthcheckStatus.OK if result == (1,) else HealthcheckStatus.FAILED 

43 ) 

44 return health_status 

45 except Exception: # pylint: disable=broad-except 

46 return HealthcheckStatus.FAILED 

47 

48 

49@router.get("/health/", response_model=List[HealthCheck]) 

50async def health_check(session: Session = Depends(get_session)) -> List[HealthCheck]: 

51 """ 

52 Healthcheck for services. 

53 """ 

54 return [ 

55 HealthCheck( 

56 name="database", 

57 status=await database_health(session), 

58 ), 

59 ]