Khunndev Cursor commited on
Commit
a34f575
·
1 Parent(s): ffdf130

Limit server detect to 20 concurrent requests with 10s timeout.

Browse files
Files changed (3) hide show
  1. Dockerfile +1 -1
  2. detect_limiter.py +62 -0
  3. main.py +19 -2
Dockerfile CHANGED
@@ -17,7 +17,7 @@ RUN apt-get update \
17
  && rm -rf /var/lib/apt/lists/*
18
  COPY requirements-server.txt .
19
  RUN pip install --no-cache-dir -r requirements-server.txt
20
- COPY main.py detect.py ./
21
  COPY --from=frontend-build /frontend/dist ./static
22
  RUN useradd -m appuser && chown -R appuser:appuser /app
23
  USER appuser
 
17
  && rm -rf /var/lib/apt/lists/*
18
  COPY requirements-server.txt .
19
  RUN pip install --no-cache-dir -r requirements-server.txt
20
+ COPY main.py detect.py detect_limiter.py ./
21
  COPY --from=frontend-build /frontend/dist ./static
22
  RUN useradd -m appuser && chown -R appuser:appuser /app
23
  USER appuser
detect_limiter.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Concurrency guard for server-side /detect requests."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import os
6
+ from typing import Any, Callable, TypeVar
7
+
8
+ MAX_CONCURRENT = int(os.environ.get("DETECT_MAX_CONCURRENT", "20"))
9
+ DETECT_TIMEOUT_SEC = float(os.environ.get("DETECT_TIMEOUT_SEC", "10"))
10
+
11
+ T = TypeVar("T")
12
+
13
+
14
+ class DetectBusyError(Exception):
15
+ """Raised when all detection slots are already in use."""
16
+
17
+
18
+ class DetectTimeoutError(Exception):
19
+ """Raised when detection exceeds the configured time limit."""
20
+
21
+
22
+ class DetectConcurrencyLimiter:
23
+ def __init__(self, max_concurrent: int, timeout_sec: float) -> None:
24
+ self.max_concurrent = max_concurrent
25
+ self.timeout_sec = timeout_sec
26
+ self._sem = asyncio.Semaphore(max_concurrent)
27
+ self._active = 0
28
+ self._lock = asyncio.Lock()
29
+
30
+ async def status(self) -> dict[str, Any]:
31
+ async with self._lock:
32
+ active = self._active
33
+ return {
34
+ "current_requests": active,
35
+ "max_concurrent": self.max_concurrent,
36
+ "timeout_sec": self.timeout_sec,
37
+ "slots_available": max(0, self.max_concurrent - active),
38
+ }
39
+
40
+ async def run(self, func: Callable[..., T], *args: Any, **kwargs: Any) -> T:
41
+ try:
42
+ await asyncio.wait_for(self._sem.acquire(), timeout=0)
43
+ except asyncio.TimeoutError as exc:
44
+ raise DetectBusyError() from exc
45
+
46
+ async with self._lock:
47
+ self._active += 1
48
+
49
+ try:
50
+ return await asyncio.wait_for(
51
+ asyncio.to_thread(func, *args, **kwargs),
52
+ timeout=self.timeout_sec,
53
+ )
54
+ except asyncio.TimeoutError as exc:
55
+ raise DetectTimeoutError() from exc
56
+ finally:
57
+ async with self._lock:
58
+ self._active -= 1
59
+ self._sem.release()
60
+
61
+
62
+ limiter = DetectConcurrencyLimiter(MAX_CONCURRENT, DETECT_TIMEOUT_SEC)
main.py CHANGED
@@ -7,6 +7,7 @@ from starlette.middleware.base import BaseHTTPMiddleware
7
  from starlette.requests import Request
8
 
9
  import detect
 
10
 
11
  APP_VERSION = "1.0.0"
12
  STATIC_PATH = Path(__file__).resolve().parent / "static"
@@ -41,14 +42,15 @@ app.add_middleware(
41
  @app.get("/health")
42
  async def health_check():
43
  model_path = STATIC_PATH / "models" / "countmodel.onnx"
 
44
  return JSONResponse(
45
  {
46
  "status": "ok",
47
  "version": APP_VERSION,
48
  "mode": "static-pwa",
49
  "model_present": model_path.is_file(),
50
- # tells the client whether the server-side detection fallback is usable
51
  "server_detect": detect.is_available(),
 
52
  }
53
  )
54
 
@@ -71,12 +73,27 @@ async def detect_endpoint(
71
  raise HTTPException(status_code=413, detail="Image too large")
72
 
73
  try:
74
- result = detect.detect_bytes(
 
75
  data,
76
  use_tiling=True if tiling else None,
77
  auto_tile=auto_tile,
78
  filter_outliers_flag=outliers,
79
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  except ValueError as exc:
81
  raise HTTPException(status_code=400, detail=str(exc))
82
  except Exception as exc: # noqa: BLE001 - surface a clean 500 to the client
 
7
  from starlette.requests import Request
8
 
9
  import detect
10
+ from detect_limiter import DetectBusyError, DetectTimeoutError, limiter
11
 
12
  APP_VERSION = "1.0.0"
13
  STATIC_PATH = Path(__file__).resolve().parent / "static"
 
42
  @app.get("/health")
43
  async def health_check():
44
  model_path = STATIC_PATH / "models" / "countmodel.onnx"
45
+ queue = await limiter.status()
46
  return JSONResponse(
47
  {
48
  "status": "ok",
49
  "version": APP_VERSION,
50
  "mode": "static-pwa",
51
  "model_present": model_path.is_file(),
 
52
  "server_detect": detect.is_available(),
53
+ "queue": queue,
54
  }
55
  )
56
 
 
73
  raise HTTPException(status_code=413, detail="Image too large")
74
 
75
  try:
76
+ result = await limiter.run(
77
+ detect.detect_bytes,
78
  data,
79
  use_tiling=True if tiling else None,
80
  auto_tile=auto_tile,
81
  filter_outliers_flag=outliers,
82
  )
83
+ except DetectBusyError:
84
+ queue = await limiter.status()
85
+ raise HTTPException(
86
+ status_code=429,
87
+ detail={
88
+ "message": "Server is busy. Try again in a few seconds.",
89
+ "queue": queue,
90
+ },
91
+ )
92
+ except DetectTimeoutError:
93
+ raise HTTPException(
94
+ status_code=504,
95
+ detail=f"Detection timed out after {limiter.timeout_sec:.0f}s",
96
+ )
97
  except ValueError as exc:
98
  raise HTTPException(status_code=400, detail=str(exc))
99
  except Exception as exc: # noqa: BLE001 - surface a clean 500 to the client