Files
VoiceStudio/backend/core/api_activity.py
debpalash 3a528c1b42 fix(api-activity): label server cancellation honestly; tighten tests
A server-side CancelledError no longer reads as a client disconnect;
the transport still flags real disconnects. Annotates the activity
API, pairs each keepalive test with its own content type, asserts the
context reset inside each request task, and replaces a polling sleep
with an event.
2026-12-01 06:31:17 +05:30

350 lines
15 KiB
Python

"""Bounded, content-free activity for local speech API requests."""
from __future__ import annotations
import asyncio
from collections import deque
from collections.abc import Awaitable, Callable
from contextvars import ContextVar
from functools import wraps
import json
import logging
import re
import threading
import time
from typing import TypeVar
import uuid
from starlette.types import ASGIApp, Receive, Scope, Send
from starlette.requests import ClientDisconnect
from starlette.responses import Response
T = TypeVar("T")
STAGES = frozenset({"received", "queued", "loading_model", "generating", "encoding", "streaming"})
ERROR_CODES = frozenset({"http_error", "internal_error", "client_disconnected", "stream_error"})
_CURRENT = ContextVar("speech_api_activity", default=None)
_IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9._/-]{0,159}\Z")
logger = logging.getLogger("omnivoice.api_activity")
def _identifier(value: object) -> str | None:
# Only explicitly supplied model/engine identifiers, never filesystem paths.
if isinstance(value, str) and _IDENTIFIER.fullmatch(value) and ".." not in value:
return value
return None
class RequestActivityStore:
"""Keep active requests separate so a burst cannot evict ongoing work."""
def __init__(self, limit: int = 200, max_active: int = 128):
self.limit = max(1, min(int(limit), 1000))
self.max_active = max(1, min(int(max_active), 1000))
self._active = {}
self._recent = deque(maxlen=self.limit)
self._lock = threading.Lock()
self._dropped = 0
def start(self, method: str, path: str, source: str) -> str | None:
with self._lock:
if len(self._active) >= self.max_active:
self._dropped += 1
return None
identity = uuid.uuid4().hex
self._active[identity] = {
"id": identity, "method": method, "path": path, "source": source,
"status": "running", "stage": "received", "engine": None, "model": None,
"started_at": time.time(), "finished_at": None, "elapsed_ms": 0,
"http_status": None, "response_bytes": 0, "error_code": None,
"_started": time.monotonic(),
}
return identity
def update(
self, identity: str, *, stage: str | None = None, engine: str | None = None,
model: str | None = None, http_status: int | None = None, response_bytes: int | None = None,
) -> None:
with self._lock:
record = self._active.get(identity)
if record is None:
return
if isinstance(stage, str) and stage in STAGES:
record["stage"] = stage
if isinstance(http_status, int) and 100 <= http_status <= 599:
record["http_status"] = http_status
if isinstance(response_bytes, int) and response_bytes >= 0:
record["response_bytes"] = response_bytes
for key, value in (("engine", engine), ("model", model)):
if _identifier(value) is not None:
record[key] = value
def mark_error(self, identity: str, code: str = "stream_error") -> None:
with self._lock:
if identity in self._active and code in ERROR_CODES:
self._active[identity]["error_code"] = code
def finish(
self, identity: str, *, status: str = "completed", http_status: int | None = None,
response_bytes: int = 0, error_code: str | None = None,
) -> dict | None:
with self._lock:
record = self._active.pop(identity, None)
if record is None:
return None
if error_code in ERROR_CODES:
record["error_code"] = error_code
if status == "completed" and record["error_code"]:
status = "failed"
record.update(
status=status, stage=status, http_status=http_status,
response_bytes=max(0, int(response_bytes)), finished_at=time.time(),
elapsed_ms=round((time.monotonic() - record.pop("_started")) * 1000),
)
if len(self._recent) == self.limit:
self._dropped += 1
self._recent.append(record)
return dict(record)
def snapshot(self) -> dict:
with self._lock:
records = [dict(record) for record in self._recent]
now = time.monotonic()
for record in self._active.values():
public = dict(record)
public["elapsed_ms"] = round((now - public.pop("_started")) * 1000)
records.append(public)
records.sort(key=lambda item: item["started_at"], reverse=True)
return {"requests": records, "dropped": self._dropped, "limit": self.limit}
def error_response(self, identity: str, http_status: int, response_bytes: int = 0) -> None:
"""Correlate an error produced by Starlette's outer error boundary."""
with self._lock:
for record in reversed(self._recent):
if record["id"] != identity:
continue
record["http_status"] = http_status
record["response_bytes"] += max(0, int(response_bytes))
if http_status == 499:
record.update(status="cancelled", stage="cancelled", error_code="client_disconnected")
break
def clear_finished(self) -> int:
with self._lock:
count = len(self._recent)
self._recent.clear()
self._dropped = 0
return count
store = RequestActivityStore()
def update_current(*, stage: str | None = None, engine: str | None = None, model: str | None = None) -> None:
current = _CURRENT.get()
if current is not None:
activity_store, identity = current
activity_store.update(identity, stage=stage, engine=engine, model=model)
def mark_error_current(code: str = "stream_error") -> None:
current = _CURRENT.get()
if current is not None:
current[0].mark_error(current[1], code)
def bind(function: Callable[..., T]) -> Callable[..., T]:
"""Carry only activity identity into an executor; leave other contexts alone."""
current = _CURRENT.get()
if current is None:
return function
@wraps(function)
def wrapped(*args, **kwargs):
token = _CURRENT.set(current)
try:
return function(*args, **kwargs)
finally:
_CURRENT.reset(token)
return wrapped
def track_error_response(handler: Callable[..., Awaitable[Response]]) -> Callable[..., Awaitable[Response]]:
"""Preserve error-handler responses and their request correlation header."""
@wraps(handler)
async def wrapped(request, exc):
response = await handler(request, exc)
current = request.scope.get("_voicestudio_api_activity")
if current is not None and not request.scope.get("_voicestudio_api_response_started"):
activity_store, identity = current
response.headers["X-VoiceStudio-Request-ID"] = identity
exposed = response.headers.get("Access-Control-Expose-Headers", "")
names = [name.strip() for name in exposed.split(",") if name.strip()]
if not any(name.lower() == "x-voicestudio-request-id" for name in names):
names.append("X-VoiceStudio-Request-ID")
response.headers["Access-Control-Expose-Headers"] = ", ".join(names)
activity_store.error_response(identity, response.status_code, len(getattr(response, "body", b"")))
logger.info("API error response %s: HTTP %s", identity, response.status_code)
return response
return wrapped
def _tracked_path(scope: Scope) -> tuple[str, str] | None:
if scope.get("type") != "http" or scope.get("method") != "POST":
return None
path = scope.get("path", "")
root = scope.get("root_path", "")
if root and path.startswith(root + "/"):
# Behind a root prefix the router matches the route-relative path.
path = path[len(root):]
if path in {"/v1/audio/speech", "/v1/audio/transcriptions", "/v1/audio/translations"}:
return path, "openai"
if path in {"/generate", "/generate/stream"}:
return path, "native"
for prefix in ("/elevenlabs/v1/text-to-speech/", "/v1/text-to-speech/"):
if path.startswith(prefix):
pieces = path[len(prefix):].split("/")
tail = tuple(pieces[1:])
if pieces[0] and tail in {(), ("stream",), ("with-timestamps",), ("stream", "with-timestamps")}:
suffix = "/" + "/".join(tail) if tail else ""
return prefix + "{voice_id}" + suffix, "elevenlabs"
return None
def _is_keepalive(body: bytes) -> bool:
"""Blank NDJSON lines and SSE comments keep a framed text stream open.
Binary audio chunks are never checked: their bytes can look like either.
"""
return not body.strip() or body.lstrip().startswith(b":")
class _SseFailureDetector:
"""Inspect bounded SSE lines for coarse error signals, retaining no payload."""
def __init__(self):
self.pending = bytearray()
self.oversized = False
self.failed = False
def feed(self, chunk: bytes) -> None:
for part in chunk.splitlines(keepends=True):
ended = part.endswith((b"\n", b"\r"))
if not self.oversized:
if len(self.pending) + len(part) > 16384:
self.pending.clear()
self.oversized = True
else:
self.pending.extend(part)
if not ended:
continue
if not self.oversized:
line = bytes(self.pending).strip()
if line.startswith(b"event:") and line[6:].strip() == b"error":
self.failed = True
elif line.startswith(b"data:") or line.startswith(b"{"):
try:
value = json.loads(line[5:].strip() if line.startswith(b"data:") else line)
except (ValueError, UnicodeError, RecursionError):
value = None
if isinstance(value, dict) and (value.get("type") == "error" or value.get("type") == "speech.audio.error" or bool(value.get("error"))):
self.failed = True
self.pending.clear()
self.oversized = False
class ApiActivityMiddleware:
"""Observe the full ASGI response without consuming or retaining request data."""
def __init__(self, app: ASGIApp, activity_store: RequestActivityStore = store) -> None:
self.app = app
self.store = activity_store
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
tracked = _tracked_path(scope)
if tracked is None:
await self.app(scope, receive, send)
return
identity = self.store.start("POST", *tracked)
if identity is None:
await self.app(scope, receive, send)
return
logger.info("API request %s POST %s: received", identity, tracked[0])
token = _CURRENT.set((self.store, identity))
scope["_voicestudio_api_activity"] = (self.store, identity)
http_status = None
response_bytes = 0
complete = False
disconnected = False
streaming = False
detector = _SseFailureDetector()
outcome, error = "failed", "internal_error"
async def observed_receive():
nonlocal disconnected
message = await receive()
if message["type"] == "http.disconnect":
disconnected = True
return message
async def observed_send(message):
nonlocal http_status, response_bytes, complete, streaming, disconnected
if message["type"] == "http.response.start":
headers = [(k, v) for k, v in message.get("headers", []) if k.lower() != b"x-voicestudio-request-id"]
headers.append((b"x-voicestudio-request-id", identity.encode("ascii")))
streaming = any(
k.lower() == b"content-type" and any(
mime in v.lower() for mime in (b"text/event-stream", b"application/x-ndjson", b"application/ndjson")
) for k, v in headers
)
message = {**message, "headers": headers}
try:
await send(message)
except OSError:
disconnected = True
raise
if message["type"] == "http.response.start":
# Only a start the transport accepted gives the request a status.
http_status = message["status"]
scope["_voicestudio_api_response_started"] = True
self.store.update(identity, http_status=http_status)
if message["type"] == "http.response.body":
body = message.get("body", b"")
response_bytes += len(body)
self.store.update(identity, response_bytes=response_bytes)
if streaming:
detector.feed(body)
if not message.get("more_body", False):
complete = True
elif body and not (streaming and _is_keepalive(body)):
self.store.update(identity, stage="streaming")
try:
await self.app(scope, observed_receive, observed_send)
if detector.failed:
outcome, error = "failed", "stream_error"
elif http_status is not None and http_status >= 400:
outcome, error = "failed", "http_error"
elif complete:
outcome, error = "completed", None
else:
outcome, error = "failed", "internal_error"
except asyncio.CancelledError:
# Server-side cancellation (shutdown, a timeout) is not a client
# disconnect; the transport flags a real disconnect below.
outcome, error = "cancelled", None
raise
except ClientDisconnect:
outcome, error = "cancelled", "client_disconnected"
raise
finally:
if disconnected and not complete:
outcome, error = "cancelled", "client_disconnected"
try:
result = self.store.finish(identity, status=outcome, http_status=http_status,
response_bytes=response_bytes, error_code=error)
if result is not None:
logger.info("API request %s POST %s: %s (HTTP %s, %d ms)",
identity, tracked[0], result["status"], http_status, result["elapsed_ms"])
finally:
_CURRENT.reset(token)