File size: 2,473 Bytes
a34f575
 
 
 
 
 
 
 
d16c4ed
 
 
 
 
 
 
 
a34f575
 
 
 
 
 
 
 
 
 
 
d16c4ed
 
 
 
a34f575
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d16c4ed
a34f575
 
 
d16c4ed
 
 
 
 
 
 
 
a34f575
1337f5b
 
a34f575
 
 
 
 
d16c4ed
a34f575
 
d16c4ed
a34f575
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""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)