"""Transparent successful API replies; bounded, neutral errors, no fake completions.""" import asyncio import json import logging import math import secrets import time import zlib from email.utils import parsedate_to_datetime from weakref import WeakKeyDictionary import aiohttp from aiohttp import web from multidict import CIMultiDict from gateway_errors import HOP_HEADERS, key_from_headers, public_error, public_json_dumps from model_identity import ModelIdentityError, check_response_model LOG = logging.getLogger("gateway_proxy") MAX_ERROR_BODY = 65536 MAX_JSON_BODY = 40 * 1024 * 1024 MAX_SSE_FRAME = 65536 API_REQUEST_DEADLINE = 860.0 # Provider prefill for a large POST can spend minutes before response headers. # That wait is not a stalled body stream: allow a longer preheader read budget # and re-apply the original socket idle budget only after headers arrive. PREFILL_SOCK_READ = 180.0 PREFILL_MIN_BODY = 64 * 1024 BUSY_MAX_RETRIES = 2 BUSY_BACKOFF_BASE = 0.25 BUSY_MAX_RETRY_AFTER = 2.0 BUSY_MAX_BACKOFF = 4.0 BUSY_MAX_WAITERS = 32 BUSY_MAX_MODEL_WAITERS = 4 BUSY_MAX_REPLAY_BODY = 1024 * 1024 _BUSY_PATHS = frozenset(("/v1/chat/completions", "/v1/completions", "/v1/responses", "/v1/messages")) _BUSY_WAITERS = WeakKeyDictionary() class _BusyWaiters: """Single-loop recovery work, not generation/connection leases or an auth queue.""" def __init__(self): self.total = 0 self.models = {} def enter(self, model): count = self.models.get(model, 0) if self.total >= BUSY_MAX_WAITERS or count >= BUSY_MAX_MODEL_WAITERS: return False self.total += 1 self.models[model] = count + 1 return True def leave(self, model): count = self.models[model] - 1 if count: self.models[model] = count else: del self.models[model] self.total -= 1 def _unique_error_object(pairs): result = {} for key, value in pairs: if key in result: raise ValueError("ambiguous error envelope") result[key] = value return result def _explicit_busy_rejection(raw, headers): """A complete provider capacity envelope only; HTTP 429/text alone is not proof.""" if (not raw or "json" not in headers.get("Content-Type", "").lower() or headers.get("Content-Encoding", "").lower() not in ("", "identity")): return False try: obj = json.loads(raw, object_pairs_hook=_unique_error_object) except (ValueError, UnicodeDecodeError, RecursionError): return False if (not isinstance(obj, dict) or set(obj) - {"error", "request_id", "gateway_request_id", "status", "success"}): return False # Never replay choices, usage, output, partials or unknown envelopes. error = obj.get("error") if (not isinstance(error, dict) or error.get("retryable", True) is not True or set(error) - {"message", "type", "code", "param", "status", "retryable", "request_id", "gateway_request_id"} or not isinstance(error.get("message", ""), str) or obj.get("success", False) is not False): return False if any(node.get("status", 429) != 429 for node in (obj, error)): return False code, kind = error.get("code"), error.get("type") if not all(value is None or isinstance(value, str) for value in (code, kind, error.get("param"))): return False # Explicit provider origin is required: new-api's own rate_limit_error and # generic rate_limit_exceeded envelopes are not authenticated admission proof. provider_code = code in ("upstream_busy", "upstream_rate_limited", "upstream_rate_limit_exceeded") provider_kind = kind in ("upstream_error", "overloaded_error", "server_overloaded") capacity_code = code in (None, "", "rate_limit_exceeded", "too_many_requests", "overloaded", "overloaded_error", "server_overloaded") if not (provider_code or (provider_kind and capacity_code)): return False text = json.dumps(error, ensure_ascii=False).lower() return not any(marker in text for marker in ( "quota", "billing", "balance", "credit", "auth", "api_key", "api key", "permission", "forbidden", "access_denied", "rank", "daily", "per_day", "user_rate", "key_rate", "token_rate", "rate_limit_user", "rate_limit_key", "this key", "your key", "this user", "your account", "account_limit", "额度", "余额", "权限", "认证", "封禁", "дневн", "баланс", "ранг", "заблок", )) def _busy_delay(headers, attempt): delay = BUSY_BACKOFF_BASE * (2 ** attempt) * (0.8 + secrets.randbelow(401) / 1000) hints = headers.getall("Retry-After", []) if hasattr(headers, "getall") else ( [headers["Retry-After"]] if "Retry-After" in headers else []) if len(hints) > 1: return None if hints: hint = hints[0].strip() if not hint or len(hint) > 128: return None try: if hint.isascii() and hint.isdigit(): seconds = float(hint) else: date = parsedate_to_datetime(hint) if date.tzinfo is None: return None seconds = max(0.0, date.timestamp() - time.time()) except (ValueError, TypeError, OverflowError, OSError): return None if not math.isfinite(seconds) or seconds > BUSY_MAX_RETRY_AFTER: return None # Do not retry earlier than an upstream hint exceeding our cap. delay = max(delay, seconds) return min(delay, BUSY_MAX_RETRY_AFTER) def _finite_positive(value): return isinstance(value, (int, float)) and math.isfinite(value) and value > 0 def _extended_prefill(request, body): """Large text-generation POST: provider prefill may outlast socket idle.""" return (request.method == "POST" and request.path.rstrip("/") in _BUSY_PATHS and isinstance(body, (bytes, bytearray, memoryview)) and len(body) >= PREFILL_MIN_BODY) def _prefill_timeout(timeout): """Longer preheader read budget; never inflate a caller's explicit total.""" sock_read = timeout.sock_read if not _finite_positive(sock_read) or sock_read >= PREFILL_SOCK_READ: return timeout budget = PREFILL_SOCK_READ if _finite_positive(timeout.total): budget = min(budget, timeout.total) if budget <= sock_read: return timeout return aiohttp.ClientTimeout( total=timeout.total, connect=timeout.connect, sock_connect=timeout.sock_connect, sock_read=budget, ceil_threshold=timeout.ceil_threshold) async def relay_api_request(request, session, url, *, headers, body, requested_model=None, json_to_sse=False, sse_include_usage=False, balance_lookup=None): """Exact dispatch after existing gates; replay only a definitive pre-generation 429. No pre-auth queue, route/model substitution, replay of ambiguous failures or renewed timeout. Recovery work is bounded independently of upstream leases. A large generation POST gets a longer preheader read budget, while its body still has to produce a chunk within the inherited socket idle timeout. """ loop = asyncio.get_running_loop() original_timeout = session.timeout extended = _extended_prefill(request, body) dispatch_timeout = _prefill_timeout(original_timeout) if extended else original_timeout body_idle_timeout = None if dispatch_timeout is not original_timeout and _finite_positive(original_timeout.sock_read): body_idle_timeout = original_timeout.sock_read budget = API_REQUEST_DEADLINE for seconds in (dispatch_timeout.total, dispatch_timeout.sock_read): if _finite_positive(seconds): budget = min(budget, seconds) deadline = loop.time() + budget recoverable = (request.method == "POST" and request.path.rstrip("/") in _BUSY_PATHS and isinstance(body, bytes) and 0 < len(body) <= BUSY_MAX_REPLAY_BODY and isinstance(requested_model, str) and 0 < len(requested_model) <= 128 and not any(ord(char) < 32 for char in requested_model) and bool(key_from_headers(headers))) attempts, waited, pool = 0, 0.0, None rejection = None try: while True: remaining = deadline - loop.time() if remaining <= 0: if rejection is not None: return rejection raise asyncio.TimeoutError() # Preserve the healthy first attempt's existing timeout exactly. # Only replays get a total timeout shortened to the original deadline. timeout = dispatch_timeout if attempts == 0 else aiohttp.ClientTimeout( total=remaining, connect=original_timeout.connect, sock_connect=original_timeout.sock_connect, sock_read=dispatch_timeout.sock_read, ceil_threshold=math.inf) async with session.request( request.method, url, headers=headers, data=body, allow_redirects=False, auto_decompress=False, skip_auto_headers={"Accept-Encoding"}, timeout=timeout) as upstream: raw = None if recoverable and upstream.status == 429: raw = await _read_bounded(upstream, MAX_ERROR_BODY, idle=body_idle_timeout) safe_busy = (raw is not None and _explicit_busy_rejection(raw, upstream.headers)) user_balance = None if upstream.status >= 400 and not safe_busy and balance_lookup is not None: auth = headers.get("Authorization", "") key = auth[7:].strip() if auth[:7].lower() == "bearer " else "" user_balance = await asyncio.to_thread(balance_lookup, key) if not safe_busy: if pool is not None: pool.leave(requested_model) pool = None return await relay_api( request, upstream, user_balance=user_balance, requested_model=requested_model, json_to_sse=json_to_sse, sse_include_usage=sse_include_usage, body_idle_timeout=body_idle_timeout, error_body=raw if raw is not None else ( b"" if recoverable and upstream.status == 429 else None)) rejection = await relay_api( request, upstream, requested_model=requested_model, body_idle_timeout=body_idle_timeout, error_body=raw) delay = _busy_delay(upstream.headers, attempts) # The fully read rejection and its context/connection are released # BEFORE reserving bounded recovery work or sleeping. transport = request.transport if (attempts >= BUSY_MAX_RETRIES or delay is None or waited + delay > BUSY_MAX_BACKOFF or loop.time() + delay + 0.05 >= deadline or transport is None or transport.is_closing()): return rejection if pool is None: candidate = _BUSY_WAITERS.get(loop) if candidate is None: candidate = _BusyWaiters() _BUSY_WAITERS[loop] = candidate if not candidate.enter(requested_model): return rejection pool = candidate LOG.info("api_busy_retry attempt=%s delay=%.3f path=%s", attempts + 1, delay, request.path) await asyncio.sleep(delay) waited += delay # Handler cancellation always unwinds the finally below. A browser # disconnect need not cancel aiohttp handlers, so check it as well. if (request.transport is None or request.transport.is_closing() or loop.time() + 0.05 >= deadline): return rejection attempts += 1 finally: if pool is not None: pool.leave(requested_model) def _decode(raw, encoding): if not encoding or encoding == "identity": return raw if encoding not in ("gzip", "deflate"): return b"" try: decoder = zlib.decompressobj(47 if encoding == "gzip" else zlib.MAX_WBITS) body = decoder.decompress(raw, MAX_JSON_BODY + 1) return body if (len(body) <= MAX_JSON_BODY and decoder.eof and not decoder.unconsumed_tail) else b"" except zlib.error: return b"" async def _bounded_chunks(content, idle): """Yield upstream chunks; an idle stream aborts at the caller's body budget.""" if idle is None: async for chunk in content.iter_chunked(8192): yield chunk return iterator = content.iter_chunked(8192).__aiter__() while True: try: chunk = await asyncio.wait_for(iterator.__anext__(), idle) except StopAsyncIteration: return yield chunk async def _read_bounded(upstream, limit, idle=None): body = bytearray() async for chunk in _bounded_chunks(upstream.content, idle): if len(body) + len(chunk) > limit: return None body.extend(chunk) return bytes(body) def _identity_error(): return {"error": {"message": "Выбранная модель сейчас недоступна. Повтори позже.", "type": "upstream_error", "code": "model_identity_mismatch", "retryable": False}} def _failure(code, retryable=True): return {"error": {"message": "Выбранная модель сейчас недоступна. Повтори позже.", "type": "upstream_error", "code": code, "retryable": retryable}} def _sse_error(payload): return b"event: error\ndata: " + json.dumps(payload, ensure_ascii=False).encode(), True def _incomplete_sse_frame(request_id): payload = _failure("upstream_stream_incomplete", False) payload["error"]["message"] = ( "Поток ответа оборвался. Полученный текст может быть неполным. " "Автоматический повтор не выполнялся.") payload["error"]["gateway_request_id"] = request_id frame, _ = _sse_error(payload) return frame + b"\n\n" def safe_sse_frame(frame, path, requested_model=None, user_balance=None): """Inspect bounded JSON data frames; valid successful frames are byte-exact.""" if len(frame) > MAX_SSE_FRAME: return _sse_error(_failure("upstream_frame_too_large", False)) data = [line[5:].strip() for line in frame.splitlines() if line.startswith((b"data:", b"data "))] if not data: return frame, False if b"\n".join(data).strip() == b"[DONE]": return frame, True try: obj = json.loads(b"\n".join(data)) except (ValueError, UnicodeDecodeError): return _sse_error(_failure("upstream_unparseable_response", False)) if not isinstance(obj, dict): return _sse_error(_failure("upstream_unparseable_response", False)) if obj.get("error"): error = obj["error"] status = error.get("status", 502) if isinstance(error, dict) else 502 try: status = int(status) except (ValueError, TypeError): status = 502 _, payload = public_error(status if 400 <= status <= 599 else 502, json.dumps(obj).encode(), path, from_upstream=True, user_balance=user_balance) else: try: if requested_model: check_response_model(requested_model, obj.get("message", obj)) except ModelIdentityError: payload = _identity_error() else: return frame, False return _sse_error(payload) def _json_to_sse_chunks(obj, include_usage): """Map a validated non-stream completion to chat.completion.chunk frames. Nothing is invented: id/created/model/fingerprint/usage and every message field are copied verbatim from the upstream object; only the chunk framing (object type, finish_reason staging, positional tool_call indexes) is protocol-required shape. Returns None when choices are not complete successful completions — the caller must fail HTTP instead of streaming. """ choices = obj.get("choices") if not isinstance(choices, list) or not choices: return None base = {k: v for k, v in obj.items() if k not in ("choices", "usage")} base["object"] = "chat.completion.chunk" chunks = [] for position, choice in enumerate(choices): if not isinstance(choice, dict): return None message = choice.get("message") if not isinstance(message, dict) or not isinstance(choice.get("finish_reason"), str): return None index = choice.get("index") if not isinstance(index, int) or isinstance(index, bool): index = position delta = dict(message) if delta.get("tool_calls") is not None: if not isinstance(delta["tool_calls"], list): return None indexed = [] for tool_position, tool_call in enumerate(delta["tool_calls"]): if not isinstance(tool_call, dict): return None tool_call = dict(tool_call) if not isinstance(tool_call.get("index"), int) or isinstance(tool_call.get("index"), bool): tool_call["index"] = tool_position indexed.append(tool_call) delta["tool_calls"] = indexed if delta: chunks.append(dict(base, choices=[{"index": index, "delta": delta, "finish_reason": None}])) finish = dict(base, choices=[{"index": index, "delta": {}, "finish_reason": choice["finish_reason"]}]) if choice.get("logprobs") is not None: finish["choices"][0]["logprobs"] = choice["logprobs"] chunks.append(finish) if include_usage and obj.get("usage") is not None: chunks.append(dict(base, choices=[], usage=obj["usage"])) return chunks async def relay_api(request, upstream, *, user_balance=None, requested_model=None, json_to_sse=False, sse_include_usage=False, body_idle_timeout=None, error_body=None): excluded = HOP_HEADERS | {name.strip().lower() for name in upstream.headers.get("Connection", "").split(",")} headers = CIMultiDict((name, value) for name, value in upstream.headers.items() if name.lower() not in excluded) request_id = secrets.token_hex(16) headers["X-Request-ID"] = request_id ctype = headers.get("Content-Type", "").lower() encoding = headers.get("Content-Encoding", "").lower() if upstream.status >= 400: raw = await _read_bounded(upstream, MAX_ERROR_BODY, idle=body_idle_timeout) if error_body is None else error_body raw = _decode(raw or b"", encoding) if len(raw) > MAX_ERROR_BODY: raw = b"" status, payload = public_error(upstream.status, raw, request.path, user_balance=user_balance, from_upstream=True, api_key=key_from_headers(request.headers)) payload["error"]["gateway_request_id"] = request_id safe_headers = {"X-Request-ID": request_id, "Cache-Control": "no-store"} retry_after = headers.get("Retry-After", "") if retry_after.isdigit() and len(retry_after) <= 8: safe_headers["Retry-After"] = retry_after LOG.warning("api_error status=%s upstream_status=%s code=%s model=%s path=%s request_id=%s", status, upstream.status, payload["error"]["code"], requested_model, request.path, request_id) return web.json_response(payload, status=status, headers=safe_headers, dumps=public_json_dumps) if json_to_sse: # [OPUS-SSE 2026-10-23] owner-approved JSON->SSE adapter, exact model only. # Identity is proven on the real non-stream JSON before any SSE byte # leaves the gateway; every failure below is a plain HTTP JSON error. if not 200 <= upstream.status < 300 or "json" not in ctype: return web.json_response(_failure("upstream_unexpected_stream"), status=502, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) raw = await _read_bounded(upstream, MAX_JSON_BODY, idle=body_idle_timeout) if raw is None: return web.json_response(_failure("upstream_response_too_large", False), status=502, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) decoded = _decode(raw, encoding) try: obj = json.loads(decoded) except (ValueError, UnicodeDecodeError): obj = None if not isinstance(obj, dict): return web.json_response(_failure("upstream_unparseable_response"), status=502, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) if obj.get("error"): error = obj["error"] status = error.get("status", 502) if isinstance(error, dict) else 502 try: status = int(status) except (ValueError, TypeError): status = 502 status, payload = public_error(status if 400 <= status <= 599 else 502, decoded, request.path, user_balance=user_balance, from_upstream=True, api_key=key_from_headers(request.headers)) return web.json_response(payload, status=status, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) try: if not isinstance(obj.get("model"), str): raise ModelIdentityError() check_response_model(requested_model, obj) except ModelIdentityError: return web.json_response(_identity_error(), status=503, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) chunks = _json_to_sse_chunks(obj, sse_include_usage) if chunks is None: LOG.warning("opus_sse_incomplete request_id=%s path=%s", request_id, request.path) return web.json_response(_failure("upstream_incomplete_response"), status=502, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) stream_body = b"".join(b"data: " + json.dumps(chunk, ensure_ascii=False).encode("utf-8") + b"\n\n" for chunk in chunks) + b"data: [DONE]\n\n" sse_headers = CIMultiDict((name, value) for name, value in headers.items() if name.lower() not in ("content-type", "content-encoding", "content-length")) sse_headers["Content-Type"] = "text/event-stream" sse_headers["X-Gateway-Stream-Mode"] = "buffered-json" LOG.info("opus_json_to_sse request_id=%s status=%s choices=%d usage=%s", request_id, upstream.status, len(obj.get("choices", [])), sse_include_usage) return web.Response(status=upstream.status, body=stream_body, headers=sse_headers) if "text/event-stream" in ctype and encoding not in ("", "identity"): return web.json_response(_failure("upstream_encoding_unsupported"), status=502, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) if requested_model and "json" in ctype: raw = await _read_bounded(upstream, MAX_JSON_BODY, idle=body_idle_timeout) if raw is None: return web.json_response(_failure("upstream_response_too_large", False), status=502, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) try: obj = json.loads(_decode(raw, encoding)) check_response_model(requested_model, obj) if isinstance(obj, dict) and obj.get("error"): error = obj["error"] status = error.get("status", 502) if isinstance(error, dict) else 502 try: status = int(status) except (ValueError, TypeError): status = 502 status, payload = public_error(status if 400 <= status <= 599 else 502, _decode(raw, encoding), request.path, user_balance=user_balance, from_upstream=True, api_key=key_from_headers(request.headers)) return web.json_response(payload, status=status, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) except ModelIdentityError: return web.json_response(_identity_error(), status=503, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) except (ValueError, UnicodeDecodeError): return web.json_response(_failure("upstream_unparseable_response"), status=502, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) return web.Response(status=upstream.status, body=raw, headers=headers) response = web.StreamResponse(status=upstream.status, reason=upstream.reason, headers=headers) chat_sse = ("text/event-stream" in ctype and request.path.rstrip("/") in ("/v1/chat/completions", "/v1/completions")) stream_started = time.monotonic() # Count accepted data bytes only; incomplete-stream error frames are excluded. _forwarded = 0 try: await response.prepare(request) buffered = b"" async for chunk in _bounded_chunks(upstream.content, body_idle_timeout): if "text/event-stream" not in ctype: await response.write(chunk) _forwarded += len(chunk) continue buffered += chunk while b"\n\n" in buffered or b"\r\n\r\n" in buffered: choices = [(buffered.find(sep), sep) for sep in (b"\n\n", b"\r\n\r\n") if sep in buffered] index, sep = min(choices, key=lambda pair: pair[0]) frame, buffered = buffered[:index], buffered[index + len(sep):] frame, terminal = safe_sse_frame(frame, request.path, requested_model, user_balance) await response.write(frame + sep) _forwarded += len(frame) + len(sep) if terminal: await response.write_eof() return response if len(buffered) > MAX_SSE_FRAME: frame, _ = _sse_error(_failure("upstream_frame_too_large", False)) await response.write(frame + b"\n\n") _forwarded += len(frame) + 2 await response.write_eof() return response if buffered: frame, terminal = safe_sse_frame(buffered, request.path, requested_model, user_balance) await response.write(frame) _forwarded += len(frame) if terminal: await response.write_eof() return response if chat_sse: await response.write(b"\n\n") _forwarded += 2 if chat_sse: LOG.warning("api_stream_incomplete request_id=%s duration_ms=%d reason=eof", request_id, int((time.monotonic() - stream_started) * 1000)) await response.write(_incomplete_sse_frame(request_id)) await response.write_eof() except (aiohttp.ClientError, asyncio.TimeoutError, ConnectionResetError) as exc: # Class and counters only: never exception text, payload, model, auth or user. LOG.warning("api_stream_aborted type=%s elapsed=%.3f prepared=%s forwarded=%d " "status=%s request_id=%s", type(exc).__name__, time.monotonic() - stream_started, response.prepared, _forwarded, upstream.status, request_id) transport = request.transport if chat_sse and response.prepared and transport is not None and not transport.is_closing(): LOG.warning("api_stream_incomplete request_id=%s duration_ms=%d reason=%s", request_id, int((time.monotonic() - stream_started) * 1000), type(exc).__name__) try: await response.write(_incomplete_sse_frame(request_id)) await response.write_eof() return response except (aiohttp.ClientError, asyncio.TimeoutError, ConnectionResetError): pass # The downstream has also gone away; close rather than replay. response.force_close() if request.transport is not None: request.transport.close() return response