Spaces:
Sleeping

crowncode-backend / app /services /tool_gate.py
Rthur2003's picture
feat: backend API routes servisleri ve tests için commend data processing dreams ve remix features eklendi
a427438
Raw History Blame Contribute Delete
2.21 kB
"""Keeps the Creator Studio and ML Toolkit audio work off the event loop.
Remixing, mixing, converting and tagging audio are CPU-bound librosa calls. Run
inline in an async handler they freeze the whole server (health checks, AURIS
polling, other downloads) until they finish. They go to a worker thread
instead, and at most TOOLS_CPU_SLOTS of them run at once so two visitors'
jobs don't starve each other and the AURIS analysis on the same CPU.
"""
from __future__ import annotations
import asyncio
import os
from contextlib import asynccontextmanager
from typing import Any, AsyncIterator, Callable, Optional, TypeVar
from fastapi import HTTPException, status
from starlette.concurrency import run_in_threadpool
T = TypeVar("T")
TOOL_SLOTS = max(1, int(os.getenv("TOOLS_CPU_SLOTS", "1")))
# Jobs allowed to wait for a slot; past that the visitor is told to come back.
MAX_WAITING = max(1, int(os.getenv("TOOLS_MAX_WAITING", "6")))
_semaphore: Optional[asyncio.Semaphore] = None
_semaphore_loop: Optional[asyncio.AbstractEventLoop] = None
_waiting = 0
def waiting() -> int:
return _waiting
@asynccontextmanager
async def tool_slot() -> AsyncIterator[None]:
global _semaphore, _semaphore_loop, _waiting
loop = asyncio.get_running_loop()
if _semaphore is None or _semaphore_loop is not loop:
# One per event loop: a semaphore must not be shared across loops (tests start several).
_semaphore, _semaphore_loop, _waiting = asyncio.Semaphore(TOOL_SLOTS), loop, 0
if _waiting >= MAX_WAITING:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail={"code": "server_busy", "message": "Too many audio jobs are waiting. Try again in a minute."},
headers={"Retry-After": "30"},
)
_waiting += 1
try:
await _semaphore.acquire()
finally:
_waiting -= 1
try:
yield
finally:
_semaphore.release()
async def run_blocking(fn: Callable[..., T], *args: Any, **kwargs: Any) -> T:
"""Run a CPU-bound function in a worker thread, waiting for a free slot first."""
async with tool_slot():
return await run_in_threadpool(fn, *args, **kwargs)