|
| 1 | +import asyncio |
| 2 | +import os |
| 3 | +import platform |
| 4 | +import signal |
| 5 | +from fastapi import APIRouter |
| 6 | +from pydantic import BaseModel |
| 7 | +from app.logging.setup_logging import get_logger |
| 8 | + |
| 9 | +logger = get_logger(__name__) |
| 10 | + |
| 11 | +router = APIRouter(tags=["Shutdown"]) |
| 12 | + |
| 13 | + |
| 14 | +class ShutdownResponse(BaseModel): |
| 15 | + """Response model for shutdown endpoint.""" |
| 16 | + |
| 17 | + status: str |
| 18 | + message: str |
| 19 | + |
| 20 | + |
| 21 | +async def _delayed_shutdown(delay: float = 0.5): |
| 22 | + """ |
| 23 | + Shutdown the server after a short delay to allow the response to be sent. |
| 24 | + |
| 25 | + Args: |
| 26 | + delay: Seconds to wait before signaling shutdown |
| 27 | + """ |
| 28 | + await asyncio.sleep(delay) |
| 29 | + logger.info("Backend shutdown initiated, exiting process...") |
| 30 | + |
| 31 | + if platform.system() == "Windows": |
| 32 | + # Windows: SIGTERM doesn't work reliably with uvicorn subprocesses |
| 33 | + os._exit(0) |
| 34 | + else: |
| 35 | + # Unix (Linux/macOS): SIGTERM allows cleanup handlers to run |
| 36 | + os.kill(os.getpid(), signal.SIGTERM) |
| 37 | + |
| 38 | + |
| 39 | +@router.post("/shutdown", response_model=ShutdownResponse) |
| 40 | +async def shutdown(): |
| 41 | + """ |
| 42 | + Gracefully shutdown the PictoPy backend. |
| 43 | + |
| 44 | + This endpoint schedules backend server termination after response is sent. |
| 45 | + The frontend is responsible for shutting down the sync service separately. |
| 46 | + |
| 47 | + Returns: |
| 48 | + ShutdownResponse with status and message |
| 49 | + """ |
| 50 | + logger.info("Shutdown request received for PictoPy backend") |
| 51 | + |
| 52 | + # Define callback to handle potential exceptions in the background task |
| 53 | + def _handle_shutdown_exception(task: asyncio.Task): |
| 54 | + try: |
| 55 | + task.result() |
| 56 | + except Exception as e: |
| 57 | + logger.error(f"Shutdown task failed: {e}") |
| 58 | + |
| 59 | + # Schedule backend shutdown after response is sent |
| 60 | + shutdown_task = asyncio.create_task(_delayed_shutdown()) |
| 61 | + shutdown_task.add_done_callback(_handle_shutdown_exception) |
| 62 | + |
| 63 | + return ShutdownResponse( |
| 64 | + status="shutting_down", |
| 65 | + message="PictoPy backend shutdown initiated.", |
| 66 | + ) |
0 commit comments