|
9 | 9 | from sqlalchemy import text |
10 | 10 | from infrastructure.queue.celery_app import celery_app |
11 | 11 |
|
12 | | -# Create the container at startup to wire everything |
13 | | -container = get_container() |
| 12 | +import asyncio |
| 13 | +import httpx |
| 14 | +import logging |
| 15 | +from config import settings |
14 | 16 |
|
| 17 | +container = get_container() |
| 18 | +logger = logging.getLogger(__name__) |
15 | 19 |
|
16 | 20 | @asynccontextmanager |
17 | 21 | async def lifespan(app: FastAPI): |
18 | 22 | # Any necessary init happens via Dependency Injector singletons if needed |
| 23 | + |
| 24 | + async def poll_inference_api(): |
| 25 | + consecutive_failures = 0 |
| 26 | + current_state = "online" |
| 27 | + |
| 28 | + while True: |
| 29 | + try: |
| 30 | + async with httpx.AsyncClient() as client: |
| 31 | + response = await client.get(f"{settings.INFERENCE_API_URL.rstrip('/')}/health", timeout=5.0) |
| 32 | + response.raise_for_status() |
| 33 | + |
| 34 | + consecutive_failures = 0 |
| 35 | + if current_state == "offline": |
| 36 | + logger.info("Poller: Inference API is back online! Resuming Celery queue...") |
| 37 | + await asyncio.to_thread(celery_app.control.add_consumer, 'celery', reply=True) |
| 38 | + current_state = "online" |
| 39 | + |
| 40 | + except Exception as e: |
| 41 | + consecutive_failures += 1 |
| 42 | + if consecutive_failures >= 3 and current_state == "online": |
| 43 | + logger.warning(f"Poller: Inference API health check failed {consecutive_failures} times! Pausing Celery queue...") |
| 44 | + await asyncio.to_thread(celery_app.control.cancel_consumer, 'celery', reply=True) |
| 45 | + current_state = "offline" |
| 46 | + |
| 47 | + # Wait 10 seconds before next ping |
| 48 | + await asyncio.sleep(10) |
| 49 | + |
| 50 | + # Start the background task |
| 51 | + task = asyncio.create_task(poll_inference_api()) |
| 52 | + |
19 | 53 | yield |
20 | | - |
| 54 | + |
| 55 | + # Clean up on shutdown |
| 56 | + task.cancel() |
21 | 57 |
|
22 | 58 | app = FastAPI( |
23 | 59 | title="Eventsnap Main API (Orchestrator) - Clean", |
|
0 commit comments