"""Concurrency guard for server-side /detect requests.""" from __future__ import annotations import asyncio import os from typing import Any, Callable, TypeVar MAX_CONCURRENT = int(os.environ.get("DETECT_MAX_CONCURRENT", "20")) DETECT_TIMEOUT_SEC = float(os.environ.get("DETECT_TIMEOUT_SEC", "60")) DETECT_TIMEOUT_MAX_SEC = float(os.environ.get("DETECT_TIMEOUT_MAX_SEC", "180")) def estimate_detect_timeout_sec(payload_bytes: int) -> float: """Scale timeout for large uploads — dense pipe bundles need more CPU time.""" mb = payload_bytes / (1024 * 1024) return min(max(DETECT_TIMEOUT_SEC, DETECT_TIMEOUT_SEC + mb * 25), DETECT_TIMEOUT_MAX_SEC) T = TypeVar("T") class DetectBusyError(Exception): """Raised when all detection slots are already in use.""" class DetectTimeoutError(Exception): """Raised when detection exceeds the configured time limit.""" def __init__(self, timeout_sec: float) -> None: self.timeout_sec = timeout_sec super().__init__() class DetectConcurrencyLimiter: def __init__(self, max_concurrent: int, timeout_sec: float) -> None: self.max_concurrent = max_concurrent self.timeout_sec = timeout_sec self._active = 0 self._lock = asyncio.Lock() async def status(self) -> dict[str, Any]: async with self._lock: active = self._active return { "current_requests": active, "max_concurrent": self.max_concurrent, "timeout_sec": self.timeout_sec, "timeout_max_sec": DETECT_TIMEOUT_MAX_SEC, "slots_available": max(0, self.max_concurrent - active), } async def run( self, func: Callable[..., T], *args: Any, timeout_sec: float | None = None, **kwargs: Any, ) -> T: deadline = timeout_sec if timeout_sec is not None else self.timeout_sec async with self._lock: if self._active >= self.max_concurrent: raise DetectBusyError() self._active += 1 try: return await asyncio.wait_for( asyncio.to_thread(func, *args, **kwargs), timeout=deadline, ) except asyncio.TimeoutError as exc: raise DetectTimeoutError(deadline) from exc finally: async with self._lock: self._active -= 1 limiter = DetectConcurrencyLimiter(MAX_CONCURRENT, DETECT_TIMEOUT_SEC)