cmvr-visual/backend/app/adapters/provider/transport.py
zhanghao 88cf14d794 feat: consolidate story studio and editable automatic production
Restructure backend and frontend modules; add story, library, and editor schema migrations.

Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews.

Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
2026-11-14 14:07:26 +08:00

110 lines
4.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""受限 HTTP 与按服务隔离的认证。"""
from __future__ import annotations
import asyncio
import json
import os
from pathlib import Path
import stat
from urllib.parse import urlsplit
import httpx
from app.domain.errors import MediaError as ProviderError
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .client import Provider
def _read_key(path):
descriptor = None
try:
path = Path(path)
if not path.is_absolute() or path.is_symlink():
raise ValueError
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
info = os.fstat(descriptor)
if not stat.S_ISREG(info.st_mode) or (os.name == "posix" and info.st_mode & 0o022):
raise ValueError
raw = os.read(descriptor, 4097)
value = raw.decode("utf-8").strip()
if not value or len(raw) > 4096 or "\n" in value or "\r" in value:
raise ValueError
return value
except (OSError, ValueError, UnicodeError):
raise ProviderError("provider_not_configured", "模型服务认证配置不可用。", True) from None
finally:
if descriptor is not None:
os.close(descriptor)
def _url(base, suffix):
if not isinstance(base, str) or not base:
raise ProviderError("capability_unavailable", "此能力尚未配置。")
parsed = urlsplit(base)
if (
parsed.scheme not in {"http", "https"}
or not parsed.hostname
or parsed.username
or parsed.password
or parsed.query
or parsed.fragment
):
raise ProviderError("provider_not_configured", "模型服务地址配置无效。", True)
return base.rstrip("/") + suffix
def _headers(provider: Provider, family="inference"):
# 各服务只读自己的认证信息,Qwen/TTS 不继承 GPU 推理服务的密钥。
key = getattr(provider.settings, family + "_api_key", "") or ""
if family == "inference" and getattr(provider.settings, "inference_api_key_file", None):
key = _read_key(provider.settings.inference_api_key_file)
if (
not isinstance(key, str)
or len(key) > 4096
or any(not 32 <= ord(char) <= 126 for char in key)
):
raise ProviderError("provider_not_configured", "模型服务认证配置不可用。", True)
return {"Authorization": "Bearer " + key} if key else {}
def _http_error(status):
if status in {400, 413, 415, 422}:
return ProviderError("upstream_rejected", "模型服务拒绝了任务输入或参数。")
if status == 404:
return ProviderError("upstream_not_found", "模型服务未找到请求的任务或结果。", True)
if status == 409:
return ProviderError("upstream_conflict", "模型任务或幂等请求发生冲突。")
return ProviderError("upstream_unavailable", "模型服务暂时不可用。", True)
async def _json(provider: Provider, method, url, *, payload=None, headers=None, timeout=None):
seconds = float(provider.settings.request_timeout_seconds if timeout is None else timeout)
options = {} if timeout is None else {"timeout": httpx.Timeout(seconds)}
try:
async with asyncio.timeout(seconds + 1):
async with provider.client.stream(
method, url, json=payload, headers=headers, **options
) as response:
if not 200 <= response.status_code < 300:
raise provider._http_error(response.status_code)
data, size = [], 0
async for chunk in response.aiter_bytes():
size += len(chunk)
if size > 2 * 1024 * 1024:
raise ProviderError(
"invalid_upstream_response", "模型服务响应超出限制。", True
)
data.append(chunk)
value = json.loads(b"".join(data))
if not isinstance(value, dict):
raise ValueError
return value
except (httpx.HTTPError, asyncio.TimeoutError):
raise ProviderError("upstream_unavailable", "模型服务连接失败或响应超时。", True) from None
except (ValueError, UnicodeError, RecursionError):
raise ProviderError("invalid_upstream_response", "模型服务返回了无效响应。", True) from None