From 55ff7ecbbc4e497fc0f12b748f21004dd4c731fb Mon Sep 17 00:00:00 2001 From: vladsaveliev Date: Tue, 26 Mar 2024 22:20:42 +0100 Subject: [PATCH] Add health endpoint --- app/db.py | 7 ++++--- app/main.py | 16 +++++++++++++++- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/app/db.py b/app/db.py index a99f9bc..42b6ff2 100644 --- a/app/db.py +++ b/app/db.py @@ -78,11 +78,11 @@ def get_visit_stats( statement = select(VisitStats) if start: # Ignore type because Visit.called_at can be None for default value - statement.where(VisitStats.start >= start) # type: ignore + statement = statement.where(VisitStats.start >= start) # type: ignore if end: - statement.where(VisitStats.end <= end) # type: ignore + statement = statement.where(VisitStats.end <= end) # type: ignore if limit: - statement.limit(limit) + statement = statement.limit(limit) statement.order_by(VisitStats.start.desc()) # type: ignore return session.exec(statement).all() @@ -129,3 +129,4 @@ def insert_download_stats(df: pd.DataFrame) -> pd.DataFrame: session.add(new_entry) session.commit() return df + diff --git a/app/main.py b/app/main.py index f049922..30a4262 100644 --- a/app/main.py +++ b/app/main.py @@ -1,5 +1,4 @@ import logging -from logzio.handler import LogzioHandler from typing import List, Dict, Optional @@ -126,6 +125,21 @@ async def version( return models.VersionResponse(latest_release=app.latest_release) +@app.get("/health") +async def health(): + """ + Health check endpoint. Checks if the visits table contains records + in the past 10 minutes. + """ + try: + visits = db.get_visit_stats(start=datetime.datetime.now() - datetime.timedelta(minutes=10)) + except Exception as e: + raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) + if not visits: + raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="No recent visits found") + return PlainTextResponse(content=str(len(visits))) + + def _log_visit( timestamp: str, version_multiqc: str = "",