Download app/services/health.py from binhugg2/api: direct link, hf CLI and curl.
- Browser
- Download file 4.06 kB
-
https://huggingface.co/spaces/binhugg2/api/resolve/main/app/services/health.py
- Command line
-
hf download hf://spaces/binhugg2/api/app/services/health.py
-
curl -L -o health.py https://huggingface.co/spaces/binhugg2/api/resolve/main/app/services/health.py
4.06 kB
| import asyncio | |
| import logging | |
| import time | |
| from datetime import datetime, timezone | |
| import httpx | |
| from sqlalchemy import select, update | |
| from app.database import async_session | |
| from app.models.source_site import SourceSite | |
| from app.models.source_health import SourceHealth | |
| logger = logging.getLogger("health") | |
| async def check_source(source: SourceSite) -> dict: | |
| """对单个源站发起健康检查,返回检查结果""" | |
| start = time.monotonic() | |
| error_msg = None | |
| is_success = False | |
| try: | |
| async with httpx.AsyncClient(timeout=10, follow_redirects=True) as client: | |
| resp = await client.get(source.base_url, params={"ac": "list", "pg": "1"}) | |
| resp.raise_for_status() | |
| data = resp.json() | |
| # 验证返回格式是否符合预期 | |
| if "list" in data or "class" in data or "total" in data: | |
| is_success = True | |
| else: | |
| error_msg = "响应格式不符合预期" | |
| except httpx.TimeoutException: | |
| error_msg = "连接超时" | |
| except httpx.HTTPStatusError as e: | |
| error_msg = f"HTTP {e.response.status_code}" | |
| except Exception as e: | |
| error_msg = str(e)[:200] | |
| response_time_ms = int((time.monotonic() - start) * 1000) | |
| return { | |
| "source_id": source.id, | |
| "is_success": is_success, | |
| "response_time_ms": response_time_ms, | |
| "error_message": error_msg, | |
| } | |
| async def run_health_checks() -> list[dict]: | |
| """对所有启用的源站执行健康检查""" | |
| async with async_session() as db: | |
| result = await db.execute( | |
| select(SourceSite).where(SourceSite.is_active == True).order_by(SourceSite.sort_order) | |
| ) | |
| sources = result.scalars().all() | |
| if not sources: | |
| return [] | |
| # 并发检查,最多 5 个并发 | |
| semaphore = asyncio.Semaphore(5) | |
| async def check_with_semaphore(source): | |
| async with semaphore: | |
| return await check_source(source) | |
| results = await asyncio.gather(*[check_with_semaphore(s) for s in sources]) | |
| # 批量写入检查结果 | |
| async with async_session() as db: | |
| now = datetime.now(timezone.utc) | |
| for r in results: | |
| record = SourceHealth( | |
| source_id=r["source_id"], | |
| check_type="api", | |
| is_success=r["is_success"], | |
| response_time_ms=r["response_time_ms"], | |
| error_message=r["error_message"], | |
| checked_at=now, | |
| ) | |
| db.add(record) | |
| # 同步更新 source_site 的最后健康状态 | |
| await db.execute( | |
| update(SourceSite) | |
| .where(SourceSite.id == r["source_id"]) | |
| .values(last_sync_status="healthy" if r["is_success"] else "unhealthy") | |
| ) | |
| await db.commit() | |
| logger.info(f"Health check completed: {len(results)} sources checked, " | |
| f"{sum(1 for r in results if r['is_success'])} healthy") | |
| return list(results) | |
| async def get_latest_health(db, source_ids: list[int] | None = None) -> dict[int, dict]: | |
| """获取每个源站最新的健康检查记录""" | |
| from sqlalchemy import func | |
| # 子查询:每个 source_id 的最新 checked_at | |
| subq = ( | |
| select(SourceHealth.source_id, func.max(SourceHealth.checked_at).label("latest")) | |
| .group_by(SourceHealth.source_id) | |
| .subquery() | |
| ) | |
| query = ( | |
| select(SourceHealth) | |
| .join(subq, (SourceHealth.source_id == subq.c.source_id) & | |
| (SourceHealth.checked_at == subq.c.latest)) | |
| ) | |
| if source_ids: | |
| query = query.where(SourceHealth.source_id.in_(source_ids)) | |
| result = await db.execute(query) | |
| records = result.scalars().all() | |
| return { | |
| r.source_id: { | |
| "is_success": r.is_success, | |
| "response_time_ms": r.response_time_ms, | |
| "error_message": r.error_message, | |
| "checked_at": str(r.checked_at) if r.checked_at else None, | |
| } | |
| for r in records | |
| } | |