Skip to content

Commit 433fd62

Browse files
committed
feat: add asynchronous health check functions for API availability
- Implemented `check_api_health` to verify API accessibility with retries and timeout handling. - Added `wait_for_api` to wait until the API becomes available within a specified time frame. - Enhanced error handling and logging for connection attempts.
1 parent 3285d70 commit 433fd62

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

services/utils.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import httpx
22
import config
3+
import asyncio
34

45

56
def get_httpx_client_kwargs():
@@ -59,3 +60,61 @@ def find_in_list_by_field(lst, field, element):
5960
return item
6061

6162
return None
63+
64+
65+
# ========== Health Check для локального API ==========
66+
67+
async def check_api_health(url: str, max_retries: int = 3, timeout: float = 5.0) -> bool:
68+
"""
69+
Проверка доступности API
70+
71+
Args:
72+
url: Base URL API (например, http://localhost:8000)
73+
max_retries: Количество попыток
74+
timeout: Таймаут на каждую попытку
75+
76+
Returns:
77+
bool: True если API доступен, False иначе
78+
"""
79+
health_endpoint = f"{url}/health" # Предполагаем что есть /health endpoint
80+
81+
for attempt in range(max_retries):
82+
try:
83+
response = await async_get(health_endpoint, timeout=timeout)
84+
if response.status_code == 200:
85+
print(f"[Health Check] ✅ API доступен: {url}")
86+
return True
87+
except httpx.ConnectError:
88+
print(f"[Health Check] ❌ Попытка {attempt + 1}/{max_retries}: Не удалось подключиться к {url}")
89+
except httpx.TimeoutException:
90+
print(f"[Health Check] ❌ Попытка {attempt + 1}/{max_retries}: Таймаут при подключении к {url}")
91+
except Exception as e:
92+
print(f"[Health Check] ❌ Попытка {attempt + 1}/{max_retries}: {type(e).__name__}: {str(e)}")
93+
94+
if attempt < max_retries - 1:
95+
await asyncio.sleep(2) # Пауза перед следующей попыткой
96+
97+
print(f"[Health Check] ❌ API недоступен после {max_retries} попыток: {url}")
98+
return False
99+
100+
101+
async def wait_for_api(url: str, max_wait_time: int = 60) -> bool:
102+
"""
103+
Ждет пока API станет доступным
104+
105+
Args:
106+
url: Base URL API
107+
max_wait_time: Максимальное время ожидания в секундах
108+
109+
Returns:
110+
bool: True если API стал доступен, False если истекло время
111+
"""
112+
print(f"[Health Check] Ожидание доступности API: {url}")
113+
start_time = asyncio.get_event_loop().time()
114+
115+
while (asyncio.get_event_loop().time() - start_time) < max_wait_time:
116+
if await check_api_health(url, max_retries=1, timeout=3.0):
117+
return True
118+
await asyncio.sleep(5) # Проверяем каждые 5 секунд
119+
120+
return False

0 commit comments

Comments
 (0)