Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
106 lines
5.1 KiB
Python
106 lines
5.1 KiB
Python
import asyncio
|
|
import json
|
|
import time
|
|
|
|
import aiohttp
|
|
from multidict import CIMultiDict
|
|
|
|
from gateway_providers import ProviderError, response_effort, safe_to_retry
|
|
|
|
MAX_REJECTION = 65536
|
|
|
|
|
|
def outcome_status(result, fallback):
|
|
"""Downstream status the success handler actually produced.
|
|
|
|
A 200 from upstream can still become an identity, payload, or validation
|
|
refusal downstream. Accounting must follow the bytes that left the gateway,
|
|
not the upstream status line, or a broken route is recorded as healthy.
|
|
Partial or broken streams remain visible only when the handler raises; a
|
|
prepared 2xx stream that ends short is not observable here.
|
|
"""
|
|
status = getattr(result, "status", None)
|
|
return status if type(status) is int and 100 <= status <= 599 else fallback
|
|
|
|
|
|
async def relay_selected(request, session, target, *, headers, body, registry, newapi_db,
|
|
raw_key, model, success, failure, retry_budget=30):
|
|
pinned = request.headers.get("X-Iishko-Provider") or None
|
|
try:
|
|
payload = json.loads(body) if body else {}
|
|
effort = response_effort(payload)
|
|
header_effort = request.headers.get("X-Iishko-Effort")
|
|
if header_effort and header_effort != effort:
|
|
raise ProviderError(400, "effort_requires_request_field", "Specify effort in the model request body; headers do not rewrite generation parameters.")
|
|
except (ValueError, TypeError, UnicodeDecodeError) as error:
|
|
if isinstance(error, ProviderError):
|
|
raise
|
|
raise ProviderError(400, "invalid_request", "Provider routing requires a JSON generation request.") from error
|
|
attempted = []
|
|
started = time.monotonic()
|
|
for attempt in range(2):
|
|
selection = asyncio.create_task(asyncio.to_thread(
|
|
registry.choose, newapi_db, raw_key, model,
|
|
pinned=pinned, effort=effort, exclude=tuple(attempted)))
|
|
try:
|
|
choice = await asyncio.shield(selection)
|
|
except asyncio.CancelledError:
|
|
def release_late(future):
|
|
try:
|
|
late_choice = future.result()
|
|
except (Exception, asyncio.CancelledError):
|
|
return
|
|
registry.abandon(late_choice)
|
|
selection.add_done_callback(release_late)
|
|
raise
|
|
attempted.append(choice.id)
|
|
finished = False
|
|
success_started = False
|
|
outgoing = CIMultiDict((k, v) for k, v in headers.items() if k.lower() not in (
|
|
"x-iishko-provider", "x-iishko-effort", "x-api-key", "api-key", "x-new-api-channel-id", "x-channel-id"))
|
|
try:
|
|
outgoing["Authorization"] = registry.pinned_authorization(raw_key, choice)
|
|
outgoing["Accept-Encoding"] = "identity"
|
|
async with session.request(request.method, target, headers=outgoing, data=body,
|
|
allow_redirects=False, auto_decompress=False,
|
|
skip_auto_headers={"Accept-Encoding"}) as response:
|
|
request["iishko_provider"] = choice.id
|
|
if response.status >= 400:
|
|
raw = bytearray()
|
|
async for chunk in response.content.iter_chunked(16384):
|
|
raw.extend(chunk)
|
|
if len(raw) > MAX_REJECTION:
|
|
raw = bytearray()
|
|
break
|
|
registry.complete(choice, response.status, retry_after=response.headers.get("Retry-After", 0))
|
|
finished = True
|
|
can_retry = (not pinned and attempt == 0 and time.monotonic() - started < retry_budget
|
|
and safe_to_retry(response.status, raw))
|
|
if can_retry:
|
|
continue
|
|
return await failure(response.status, bytes(raw), response.headers)
|
|
success_started = True
|
|
result = await success(response)
|
|
# [OUTCOME 2610] The route is credited with what the caller got,
|
|
# not with the upstream 200. No replay is possible after this
|
|
# point, and the lease is released exactly once below.
|
|
registry.complete(choice, outcome_status(result, response.status))
|
|
finished = True
|
|
return result
|
|
except asyncio.CancelledError:
|
|
raise
|
|
except (aiohttp.ClientError, asyncio.TimeoutError, ConnectionResetError) as error:
|
|
# The provider may already have accepted/billed the generation.
|
|
# Never replay an ambiguous connection failure on a reserve.
|
|
registry.complete(choice, 504 if isinstance(error, asyncio.TimeoutError) else 502)
|
|
finished = True
|
|
if success_started:
|
|
if request.transport is not None:
|
|
request.transport.close()
|
|
raise
|
|
return await failure(504 if isinstance(error, asyncio.TimeoutError) else 503, b"", {})
|
|
finally:
|
|
if not finished:
|
|
registry.abandon(choice)
|
|
raise ProviderError(503, "no_healthy_provider", "No healthy same-model provider is available.")
|