64 lines
2.1 KiB
Python
64 lines
2.1 KiB
Python
import tomllib
|
|
from pathlib import Path
|
|
from fastapi import APIRouter, HTTPException
|
|
import socket
|
|
|
|
from bd import Settings
|
|
from redis_db import get_redis_client
|
|
|
|
# Создаем базовый router для FastAPI
|
|
router = APIRouter(tags=["base"])
|
|
|
|
def get_version():
|
|
"""Получить версию из pyproject.toml"""
|
|
try:
|
|
pyproject_path = Path(__file__).parent.parent / "pyproject.toml"
|
|
with open(pyproject_path, "rb") as f:
|
|
pyproject = tomllib.load(f)
|
|
return pyproject["project"]["version"]
|
|
except:
|
|
return "0.1.0"
|
|
|
|
@router.get("/")
|
|
async def root():
|
|
return {"message": "API is running"}
|
|
|
|
@router.get("/health")
|
|
async def health():
|
|
return {"status": "ok"}
|
|
|
|
@router.get("/version")
|
|
async def version():
|
|
return {"version": get_version()}
|
|
|
|
|
|
@router.get("/health/db")
|
|
async def health_db():
|
|
"""Проверка доступности БД по TCP (host:port)"""
|
|
settings = Settings()
|
|
host = settings.DB_HOST
|
|
port = settings.DB_PORT
|
|
try:
|
|
# Пробуем открыть TCP-соединение к хосту:порту
|
|
with socket.create_connection((host, port), timeout=3):
|
|
return {"status": "ok", "db": "reachable", "host": host, "port": port}
|
|
except Exception as e:
|
|
raise HTTPException(status_code=503, detail=f"db unreachable: {e}")
|
|
|
|
|
|
@router.get("/health/redis")
|
|
async def health_redis():
|
|
"""Проверка подключения к Redis через ping()"""
|
|
client = get_redis_client()
|
|
try:
|
|
if client.ping():
|
|
# Получаем параметры соединения для удобства в ответе
|
|
conn_kwargs = getattr(client, "connection_pool", None)
|
|
info = {}
|
|
if conn_kwargs:
|
|
info = conn_kwargs.connection_kwargs if hasattr(conn_kwargs, 'connection_kwargs') else {}
|
|
return {"status": "ok", "redis": "reachable", "info": info}
|
|
else:
|
|
raise HTTPException(status_code=503, detail="redis ping failed")
|
|
except Exception as e:
|
|
raise HTTPException(status_code=503, detail=f"redis unreachable: {e}") |