""" services/queue.py ───────────────── Async inference queue that serialises all ONNX synthesis calls onto a single background worker thread, preventing: - Concurrent ONNX calls that would cause memory spikes - Blocking the FastAPI event loop during CPU-heavy inference Architecture: ┌─────────────────────────────────┐ │ FastAPI event loop (async) │ │ POST /synthesize │ │ └─ enqueue_synthesis() │ ← puts a Future onto the queue │ └─ await future │ ← suspends without blocking the loop └──────────────┬──────────────────┘ │ asyncio.Queue (bounded) ┌──────────────▼──────────────────┐ │ ThreadPoolExecutor (1 thread) │ │ _worker_loop() │ ← pulls jobs, runs ONNX inference │ └─ core.tts_engine.synthesize() └─────────────────────────────────┘ The queue is bounded (settings.queue_max_size). If full, new requests immediately receive a 503 Service Unavailable response — preventing runaway memory usage under load spikes. """ import asyncio import logging from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field from typing import Any, Callable from core.config import get_settings from core.tts_engine import synthesize as _synthesize_sync logger = logging.getLogger(__name__) # ── Job dataclass ────────────────────────────────────────────────────────────── @dataclass class SynthesisJob: func: Callable args: tuple kwargs: dict future: asyncio.Future = field(default_factory=asyncio.Future) # ── Queue worker ─────────────────────────────────────────────────────────────── _queue: asyncio.Queue | None = None _executor: ThreadPoolExecutor | None = None _worker_task: asyncio.Task | None = None async def _worker_loop() -> None: """ Continuously pulls SynthesisJobs from the queue and executes them on the thread-pool executor (one thread → one ONNX job at a time). """ loop = asyncio.get_running_loop() logger.info("Synthesis queue worker started.") while True: try: job: SynthesisJob = await _queue.get() if job.future.cancelled(): _queue.task_done() continue try: wav_bytes: bytes = await loop.run_in_executor( _executor, lambda: job.func(*job.args, **job.kwargs) ) if not job.future.cancelled(): job.future.set_result(wav_bytes) except Exception as exc: if not job.future.cancelled(): job.future.set_exception(exc) finally: _queue.task_done() except asyncio.CancelledError: logger.info("Synthesis queue worker shutting down.") break except Exception: logger.exception("Unexpected error in queue worker loop — continuing.") # ── Public lifecycle API ─────────────────────────────────────────────────────── def start_queue() -> None: """ Initialise the queue and launch the background worker. Must be called once inside a running asyncio event loop (e.g. from a FastAPI lifespan startup handler). """ global _queue, _executor, _worker_task settings = get_settings() _queue = asyncio.Queue(maxsize=settings.queue_max_size) # Single-threaded executor — ONNX inference is not thread-safe on some models _executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="onnx_worker") _worker_task = asyncio.create_task(_worker_loop()) logger.info( "Synthesis queue initialised (max_size=%d, timeout=%ds).", settings.queue_max_size, settings.queue_timeout_seconds, ) async def stop_queue() -> None: """ Gracefully shut down the queue worker. Called from the FastAPI lifespan shutdown handler. """ global _worker_task, _executor if _worker_task: _worker_task.cancel() try: await _worker_task except asyncio.CancelledError: pass if _executor: _executor.shutdown(wait=False) logger.info("Synthesis queue stopped.") async def enqueue_job(func: Callable, *args, **kwargs) -> bytes: """ Submit a generic synthesis job to the queue and await its result. Returns: WAV audio bytes. Raises: asyncio.QueueFull or asyncio.TimeoutError """ if _queue is None: raise RuntimeError("Synthesis queue has not been started.") settings = get_settings() loop = asyncio.get_running_loop() future: asyncio.Future[bytes] = loop.create_future() job = SynthesisJob( func=func, args=args, kwargs=kwargs, future=future, ) try: _queue.put_nowait(job) except asyncio.QueueFull as exc: raise asyncio.QueueFull( "Synthesis queue is at capacity. Please retry shortly." ) from exc return await asyncio.wait_for(future, timeout=settings.queue_timeout_seconds) async def enqueue_synthesis( template: str, variables: dict[str, str], voice_key: str, speed: float, ) -> bytes: """Legacy helper for the main synthesize endpoint.""" return await enqueue_job(_synthesize_sync, template, variables, voice_key, speed) def queue_stats() -> dict[str, Any]: """Return diagnostic statistics for the /health endpoint.""" if _queue is None: return {"status": "not_started"} return { "status": "running", "queue_size": _queue.qsize(), "queue_max_size": _queue.maxsize, }