2026-08-04 18:55:54 +00:00
|
|
|
import time
|
|
|
|
|
from datetime import datetime, timezone
|
|
|
|
|
|
2026-08-06 16:03:48 +00:00
|
|
|
from fastapi import APIRouter, Depends
|
|
|
|
|
from sqlalchemy import text
|
|
|
|
|
from sqlalchemy.orm import Session
|
2026-08-04 18:55:54 +00:00
|
|
|
|
2026-08-06 16:03:48 +00:00
|
|
|
from app.database import get_db
|
2026-08-04 18:55:54 +00:00
|
|
|
from app.schemas import HealthCheck, HealthResponse
|
|
|
|
|
|
|
|
|
|
router = APIRouter(tags=['health'])
|
|
|
|
|
START_TIME = time.time()
|
|
|
|
|
|
|
|
|
|
|
2026-08-06 16:03:48 +00:00
|
|
|
def build_health(db: Session) -> HealthResponse:
|
|
|
|
|
db_check: HealthCheck
|
|
|
|
|
try:
|
|
|
|
|
t0 = time.perf_counter()
|
|
|
|
|
db.execute(text("SELECT 1"))
|
|
|
|
|
latency_ms = round((time.perf_counter() - t0) * 1000, 2)
|
|
|
|
|
db_check = HealthCheck(status='pass', latency_ms=latency_ms, detail='sqlite ok')
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
db_check = HealthCheck(status='fail', detail=str(exc))
|
|
|
|
|
overall = 'pass' if db_check.status == 'pass' else 'fail'
|
2026-08-04 18:55:54 +00:00
|
|
|
return HealthResponse(
|
2026-08-06 16:03:48 +00:00
|
|
|
status=overall,
|
2026-08-04 18:55:54 +00:00
|
|
|
service='netmapper-backend',
|
|
|
|
|
version='0.1.0',
|
|
|
|
|
time=datetime.now(timezone.utc),
|
|
|
|
|
uptime_s=round(time.time() - START_TIME, 2),
|
2026-08-06 16:03:48 +00:00
|
|
|
checks={'db': db_check},
|
2026-08-04 18:55:54 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.get('/live', response_model=HealthResponse)
|
2026-08-06 16:03:48 +00:00
|
|
|
def live(db: Session = Depends(get_db)) -> HealthResponse:
|
|
|
|
|
return build_health(db)
|
2026-08-04 18:55:54 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.get('/ready', response_model=HealthResponse)
|
2026-08-06 16:03:48 +00:00
|
|
|
def ready(db: Session = Depends(get_db)) -> HealthResponse:
|
|
|
|
|
return build_health(db)
|
2026-08-04 18:55:54 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.get('/health', response_model=HealthResponse)
|
2026-08-06 16:03:48 +00:00
|
|
|
def health(db: Session = Depends(get_db)) -> HealthResponse:
|
|
|
|
|
return build_health(db)
|