From 8208ab4c24373c2a413bb9e936fe6a5feab01b4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=AA=E5=BF=97=E9=B9=8F?= Date: Fri, 27 Nov 2026 06:22:15 +0000 Subject: [PATCH 1/2] [feat] provider: start a video gateway for H3 LoRA variants with the app ## summary - vLLM-Omni serves few-step MiniMax-H3 adapters such as Pika Flex Turbo from the base weights, and every request must carry the adapter's `lora` and its own step count. FastH3-Omni requests carry no `lora` and always ask for 8 steps, so those adapters could not be used. - Add `opendirector.video_gateway`: a YAML file lists model names, and a video creation request for a listed name is rewritten (served model name, forced and default fields, `extra_params`, `lora`) and sent to that entry's backend. Any other request reaches the default backend byte for byte. Job routes follow the backend that created the job. - `opendirector serve` and `opendirector dev` start the gateway when `.opendirector/video-gateway.yaml` exists in the data directory or `--video-gateway FILE` is given, and stop it with the application. An invalid file or a busy port stops the start before anything is spawned. - The model table is re-read when the file changes; a file that fails to load keeps the previous table. - Add bilingual guides and an example configuration. ## validation - pytest tests/test_video_gateway.py tests/test_launcher.py tests/test_cli.py - lint-imports - `opendirector serve` from this checkout with and without a configuration, with a broken one, and stopped with Ctrl+C - Real vLLM-Omni MiniMax-H3 Ref2VA server: FastH3-Omni style requests for a 4-step Pika LoRA name and a no-LoRA 20-step name both returned video with audio through the gateway Co-Authored-By: Claude Fable 5.2 --- docs/README.md | 1 + docs/guides/cli.md | 2 + docs/guides/user-guide.md | 2 + docs/guides/user-guide.zh-CN.md | 2 + docs/guides/video-gateway.md | 93 ++++++ docs/guides/video-gateway.zh-CN.md | 93 ++++++ packages/core/src/opendirector/cli.py | 15 +- packages/core/src/opendirector/launcher.py | 53 ++- .../core/src/opendirector/video_gateway.py | 311 ++++++++++++++++++ tests/test_video_gateway.py | 245 ++++++++++++++ .../video-gateway/video-gateway.example.yaml | 74 +++++ 11 files changed, 883 insertions(+), 8 deletions(-) create mode 100644 docs/guides/video-gateway.md create mode 100644 docs/guides/video-gateway.zh-CN.md create mode 100644 packages/core/src/opendirector/video_gateway.py create mode 100644 tests/test_video_gateway.py create mode 100644 tools/video-gateway/video-gateway.example.yaml diff --git a/docs/README.md b/docs/README.md index bbe67662c..77f505496 100644 --- a/docs/README.md +++ b/docs/README.md @@ -28,6 +28,7 @@ This directory is the entry point for the repository's shared documentation. The | [Business CLI](guides/cli.md) | Querying, editing, and generating through a terminal or Agent Shell | Commands, authorization, or receipt semantics change | | [DeepSeek Harness plugin](../plugins/deepseek-harness/README.md) | Installing the DSH bundle and editing an OpenDirector project from DSH | Plugin setup, tools, or creation workflows change | | [Video model capabilities](guides/video-model-capabilities.md) ([中文](guides/video-model-capabilities.zh-CN.md)) | Declaring output specifications supported by a service | Configuration fields or capability integration changes | +| [Video gateway](guides/video-gateway.md) ([中文](guides/video-gateway.zh-CN.md)) | Serving several H3 LoRA variants from one vLLM-Omni server through the gateway started with the application | Gateway configuration keys, startup, or rewrite behavior change | | [Model availability / 模型可用状态](guides/model-availability.md) | Optional runtime declarations, automatic checks, shared admission and API/CLI/Agent queries | Capability protocol, refresh, or acceptance rules change | | [OpenAI Images](guides/openai-images.md) | Wiring gpt-image as an optional image service, request shape and failures | Integration fields, capability scope, or the OpenAI interface change | | [Kling video](guides/kling-video.md) ([中文](guides/kling-video.zh-CN.md)) | Optional Kling 4.0 and Flash setup, model-specific inputs, and recovery limits | Kling inputs, model declarations, or recovery behavior change | diff --git a/docs/guides/cli.md b/docs/guides/cli.md index 3c6914137..08123d547 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -11,6 +11,8 @@ opendirector canvas --help opendirector canvas create-generation --help ``` +`serve` 和 `dev` 在数据目录存在 `.opendirector/video-gateway.yaml` 时一并启动[视频转发层](video-gateway.zh-CN.md),也可用 `--video-gateway FILE` 指定配置文件。 / `serve` and `dev` also start the [video gateway](video-gateway.md) when `.opendirector/video-gateway.yaml` exists in the data directory, or when `--video-gateway FILE` names a configuration. + 普通终端默认连接 `http://127.0.0.1:18000`。使用 `--url` 或 `OPENDIRECTOR_API_URL` 指定服务,使用 `--project` 或 `OPENDIRECTOR_PROJECT_ID` 选择工程。全局选项放在子命令前。 ```bash diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index dfef578da..ff852e324 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -47,6 +47,8 @@ example vLLM's 4096 default) rejects every request with HTTP 400. For vLLM-Omni video connections, enter fractional seconds directly, for example `6.583333`. The CLI accepts `opendirector video create --duration 6.583333` together with the other required options. Read `opendirector video create --help` and `opendirector model list` first; `inputRules.fractionalDuration` identifies support, and each output's duration list defines the allowed range. H3 can align output to its supported frame count, so inspect the actual result duration before assembling segments. +To use few-step H3 adapters such as Pika Flex Turbo, which need a LoRA and their own step count on every request, or to offer several such variants from one vLLM-Omni server, see the [video gateway](video-gateway.md) that starts with OpenDirector. + For detailed video settings, see [Video model capability configuration](video-model-capabilities.md). When no explicit output specification is provided, use **Auto** or **Service default duration**. Automatic region selection in images and video matting require a model with segmentation capabilities. Image generation and editing still require the corresponding generation or editing model. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index d26e3400d..00618c090 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -59,6 +59,8 @@ HTTP 400。 vLLM-Omni 视频连接支持直接输入小数秒,例如 `6.583333`。CLI 可使用 `opendirector video create --duration 6.583333` 并填写其余必需参数。先运行 `opendirector video create --help` 和 `opendirector model list`;`inputRules.fractionalDuration` 表示支持小数秒,各输出规格的时长列表定义允许范围。H3 可能按模型支持的帧数对齐,拼接分段前应核对结果的实际时长。 +使用 Pika Flex Turbo 等少步数 H3 适配器(每个请求都需要 LoRA 和对应的步数),或想用一个 vLLM-Omni 服务提供多个这样的变体时,参见随 OpenDirector 一起启动的[视频转发层](video-gateway.zh-CN.md)。 + ## 制作第一支短片 建议先完成一个镜头的生成与导出,再扩展到多段素材。 diff --git a/docs/guides/video-gateway.md b/docs/guides/video-gateway.md new file mode 100644 index 000000000..47ac7652d --- /dev/null +++ b/docs/guides/video-gateway.md @@ -0,0 +1,93 @@ +# Serve several H3 variants from one vLLM-Omni server + +[中文](video-gateway.zh-CN.md) + +The video gateway is a small local service that OpenDirector starts together with the application. It sits between OpenDirector and your self-hosted [vLLM-Omni](https://github.com/vllm-project/vllm-omni) video servers and lets one server appear as several models, each with its own step count and LoRA, chosen by model name. + +## When you need it + +vLLM-Omni serves few-step MiniMax-H3 adapters, such as Pika Flex Turbo, from the base weights. Each request must name the adapter in a `lora` field and use that adapter's step count and flow shift, or the server rejects it. OpenDirector's FastH3-Omni video requests carry no `lora` and always ask for 8 steps, so these adapters cannot be used directly. + +The gateway adds what the server needs to each request. You do not need it for FastH3 Omni or for base MiniMax-H3, which OpenDirector drives directly. + +## Configure it + +Create `.opendirector/video-gateway.yaml` in the OpenDirector data directory, beside `models.json`. Start from [`tools/video-gateway/video-gateway.example.yaml`](../../tools/video-gateway/video-gateway.example.yaml), which documents every key. + +```yaml +listen: + host: 127.0.0.1 + port: 8101 + +# Requests whose model is not listed below are forwarded here unchanged. +default_backend: http://127.0.0.1:8091 + +models: + Pika-Labs/Pika-H3-Flex-Turbo-4step: + backend: http://127.0.0.1:8091 + backend_model: MiniMaxAI/MiniMax-H3 + set: + num_inference_steps: 4 + guidance_scale: 1 + flow_shift: 12 + extra_params: + audio_flow_shift: 3 + lora: + name: pika-h3-flex-turbo-4step + path: /path/to/loras/pika_h3_flex_turbo_4step_ref2va.safetensors + scale: 1.0 +``` + +| Key | Meaning | +| --- | --- | +| `backend` | Base URL of the vLLM-Omni server that runs this model | +| `backend_model` | The name that server was started with (`--served-model-name`); defaults to the entry's name | +| `set` | Form fields forced to these values, replacing what the client sent | +| `defaults` | Form fields added only when the client did not send them | +| `extra_params` | Keys forced inside the request's `extra_params` JSON | +| `lora` | `{name, path, scale}` sent as the request's `lora`. `lora: null` removes one the client sent; leaving the key out passes the client's own through | + +`lora.path` is a path on the vLLM-Omni server, which may be another machine. The gateway sends it without checking it; the server reports a missing or mismatched file when a request arrives. Start that server with `--lora-backend peft` so that it accepts a per-request `lora`. + +Because OpenDirector always sends 8 steps, an entry whose weights need another step count must force it under `set`. + +## Start it + +`opendirector serve` starts the gateway whenever the configuration file exists, and stops it when the application stops: + +```text +Video gateway / 视频转发层: http://127.0.0.1:8101/v1 (.../.opendirector/video-gateway.yaml) +OpenDirector: http://127.0.0.1:8000 (Ctrl+C 退出) +``` + +To use a file somewhere else, pass it explicitly: `opendirector serve --video-gateway /path/to/video-gateway.yaml`. `opendirector dev` accepts the same option. Without a configuration, no gateway is started. + +An invalid file or a busy `listen.port` stops the start with a message that names the problem; nothing is left running. The gateway listens on `127.0.0.1` by default and adds no authentication, so keep it on the loopback address or behind your own access control. + +## Connect OpenDirector + +In **Settings → Model connections → Video → Add service**, select **vLLM-Omni video API**: + +- URL: the gateway, for example `http://127.0.0.1:8101/v1` +- Model ID: a name from `models` +- Request format: **FastH3-Omni (8 steps, multi-asset reference)** + +Add one model for each configured name. A model name that is not in the file still works through the gateway when the default backend serves it under that name. + +## What the gateway does to a request + +- A video creation request (`POST /v1/videos` or `POST /v1/videos/sync`) whose `model` is listed is rewritten as configured and sent to that entry's backend. Uploaded files are carried through unchanged. +- A request for any other model name goes to `default_backend` exactly as it arrived. +- Status queries, downloads and cancellation are relayed to the backend that created the job. +- `GET /v1/models` lists the configured names, then the default backend's own. +- Each rewrite is logged with the fields it changed, in the same terminal as the application. + +The model table is re-read when the file changes, so you can add a model or change a step count without a restart. A file that fails to load keeps the previous table and logs the reason. A changed `listen` address takes effect at the next start. + +## Limits + +- The gateway cannot make a server accept a name or an adapter it does not support: the backend still validates what it receives. +- Switching between LoRAs on one server takes extra time the first time each adapter is used. +- A request is held in memory while it is rewritten, up to 768 MiB. +- Only vLLM-Omni video creation is rewritten. Image, audio and chat services do not go through the gateway. +- `opendirector serve` and `opendirector dev` start the gateway; the desktop application does not. To run it on its own, for example beside the desktop application, use `python -m opendirector.video_gateway /path/to/video-gateway.yaml`. diff --git a/docs/guides/video-gateway.zh-CN.md b/docs/guides/video-gateway.zh-CN.md new file mode 100644 index 000000000..3204f70bb --- /dev/null +++ b/docs/guides/video-gateway.zh-CN.md @@ -0,0 +1,93 @@ +# 用一个 vLLM-Omni 服务提供多个 H3 变体 + +[English](video-gateway.md) + +视频转发层是一个随 OpenDirector 一起启动的本地小服务。它位于 OpenDirector 和自部署的 [vLLM-Omni](https://github.com/vllm-project/vllm-omni) 视频服务之间,让一个服务以多个模型的名义出现,每个模型有自己的步数和 LoRA,按模型名选择。 + +## 什么时候需要 + +vLLM-Omni 在原版权重上提供少步数的 MiniMax-H3 适配器,例如 Pika Flex Turbo。每个请求都必须在 `lora` 字段里指明适配器,并使用该适配器对应的步数和流偏移,否则服务会拒绝。OpenDirector 的 FastH3-Omni 视频请求不带 `lora`,步数固定为 8,所以无法直接使用这些适配器。 + +转发层为每个请求补上服务需要的内容。FastH3 Omni 和原版 MiniMax-H3 不需要它,OpenDirector 可以直接驱动。 + +## 配置 + +在 OpenDirector 数据目录中创建 `.opendirector/video-gateway.yaml`,与 `models.json` 放在一起。可以从 [`tools/video-gateway/video-gateway.example.yaml`](../../tools/video-gateway/video-gateway.example.yaml) 开始,其中说明了每个配置项。 + +```yaml +listen: + host: 127.0.0.1 + port: 8101 + +# 模型名不在下面列表中的请求,原样转发到这里。 +default_backend: http://127.0.0.1:8091 + +models: + Pika-Labs/Pika-H3-Flex-Turbo-4step: + backend: http://127.0.0.1:8091 + backend_model: MiniMaxAI/MiniMax-H3 + set: + num_inference_steps: 4 + guidance_scale: 1 + flow_shift: 12 + extra_params: + audio_flow_shift: 3 + lora: + name: pika-h3-flex-turbo-4step + path: /path/to/loras/pika_h3_flex_turbo_4step_ref2va.safetensors + scale: 1.0 +``` + +| 配置项 | 含义 | +| --- | --- | +| `backend` | 运行该模型的 vLLM-Omni 服务地址 | +| `backend_model` | 该服务启动时使用的名字(`--served-model-name`);默认与条目名相同 | +| `set` | 强制设为这些值的表单字段,覆盖客户端发送的值 | +| `defaults` | 仅在客户端未发送时才补上的表单字段 | +| `extra_params` | 强制写入请求 `extra_params` JSON 的键 | +| `lora` | 作为请求 `lora` 发送的 `{name, path, scale}`。`lora: null` 会去掉客户端发送的 `lora`;不写这一项则保留客户端自己的 | + +`lora.path` 是 vLLM-Omni 服务器上的路径,该服务器可能是另一台机器。转发层只发送这个路径,不做检查;文件缺失或不匹配时,由服务在收到请求时报告。该服务需以 `--lora-backend peft` 启动,才会接受请求里的 `lora`。 + +OpenDirector 发出的步数固定为 8,所以权重需要其他步数的条目必须在 `set` 里强制指定。 + +## 启动 + +只要配置文件存在,`opendirector serve` 就会一并启动转发层,并在应用退出时停止它: + +```text +Video gateway / 视频转发层: http://127.0.0.1:8101/v1 (.../.opendirector/video-gateway.yaml) +OpenDirector: http://127.0.0.1:8000 (Ctrl+C 退出) +``` + +配置文件放在别处时,可以显式指定:`opendirector serve --video-gateway /path/to/video-gateway.yaml`。`opendirector dev` 支持同一个选项。没有配置时不会启动转发层。 + +配置文件无效或 `listen.port` 被占用时,启动会停止并说明原因,不会留下任何进程。转发层默认监听 `127.0.0.1`,不做鉴权,请保持在本机回环地址上,或放在你自己的访问控制之后。 + +## 接入 OpenDirector + +在 **设置 → 模型接入 → 视频 → 添加服务** 中选择 **vLLM-Omni 视频接口**: + +- 地址:转发层,例如 `http://127.0.0.1:8101/v1` +- Model ID:`models` 里的一个名字 +- 请求格式:**FastH3-Omni(8 步、多素材参考)** + +每个配置的名字添加一个模型。不在配置文件里的模型名,只要默认后端以该名字提供服务,经过转发层同样可用。 + +## 转发层对请求做了什么 + +- 视频创建请求(`POST /v1/videos` 或 `POST /v1/videos/sync`)的 `model` 在配置里时,按配置改写后发给该条目的后端。上传的文件原样传递。 +- 其他模型名的请求原样转给 `default_backend`。 +- 状态查询、下载和取消会转给创建该任务的后端。 +- `GET /v1/models` 先列出配置里的名字,再列出默认后端自己的。 +- 每次改写都会记录改动了哪些字段,日志与应用在同一个终端里。 + +配置文件变化时会重新读取模型列表,因此添加模型或修改步数不需要重启。加载失败时继续使用上一份列表,并在日志里说明原因。修改 `listen` 地址在下次启动时生效。 + +## 限制 + +- 转发层不能让服务接受它不支持的模型名或适配器:后端仍会校验收到的请求。 +- 同一个服务上切换 LoRA,每个适配器第一次使用时会多花一些时间。 +- 改写请求时,请求体会完整读入内存,上限 768 MiB。 +- 只改写 vLLM-Omni 视频创建请求。图片、音频和对话服务不经过转发层。 +- `opendirector serve` 和 `opendirector dev` 会启动转发层,桌面应用不会。需要单独运行时(例如配合桌面应用),使用 `python -m opendirector.video_gateway /path/to/video-gateway.yaml`。 diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index e6188cac4..e474ab433 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -351,6 +351,11 @@ class LogLevel(str, Enum): PortOption = Annotated[int, typer.Option(min=1, max=65535, help="Local API port.")] WebPortOption = Annotated[int, typer.Option(min=1, max=65535, help="Vite development port.")] +VideoGatewayOption = Annotated[Path | None, typer.Option( + "--video-gateway", exists=True, dir_okay=False, readable=True, + help="Video gateway configuration to start with the application; defaults to .opendirector/video-gateway.yaml in the " + "data directory when that file exists. / 随应用启动的视频转发层配置;默认使用数据目录中已存在的 " + ".opendirector/video-gateway.yaml。")] @app.command("desktop", help="Open the desktop application installed with this terminal command. / 打开此终端命令所属的桌面应用。") @@ -362,15 +367,17 @@ def desktop(): @app.command("serve", help="Start the API and serve the built application.") -def serve(port: PortOption = 8000, web_port: WebPortOption = 5173, log_level: LogLevel = LogLevel.info): +def serve(port: PortOption = 8000, web_port: WebPortOption = 5173, log_level: LogLevel = LogLevel.info, + video_gateway: VideoGatewayOption = None): from opendirector.launcher import start - raise typer.Exit(start("serve", port, web_port, log_level.value)) + raise typer.Exit(start("serve", port, web_port, log_level.value, video_gateway)) @app.command("dev", help="Start the API and Vite development server.") -def dev(port: PortOption = 8000, web_port: WebPortOption = 5173, log_level: LogLevel = LogLevel.info): +def dev(port: PortOption = 8000, web_port: WebPortOption = 5173, log_level: LogLevel = LogLevel.info, + video_gateway: VideoGatewayOption = None): from opendirector.launcher import start - raise typer.Exit(start("dev", port, web_port, log_level.value)) + raise typer.Exit(start("dev", port, web_port, log_level.value, video_gateway)) def emit(value): diff --git a/packages/core/src/opendirector/launcher.py b/packages/core/src/opendirector/launcher.py index a8d9ca4f3..6d980a4ee 100644 --- a/packages/core/src/opendirector/launcher.py +++ b/packages/core/src/opendirector/launcher.py @@ -13,13 +13,14 @@ from opendirector.installation import SOURCE_ROOT, data_root, web_root ROOT = SOURCE_ROOT +VIDEO_GATEWAY_FILE = ".opendirector/video-gateway.yaml" # beside models.json -def port_in_use(port: int) -> bool: +def port_in_use(port: int, host: str = "127.0.0.1") -> bool: """True when something already accepts connections on the local port.""" - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe: + with socket.socket(socket.AF_INET6 if ":" in host else socket.AF_INET, socket.SOCK_STREAM) as probe: probe.settimeout(0.25) - return probe.connect_ex(("127.0.0.1", port)) == 0 + return probe.connect_ex((host, port)) == 0 def suggested_port(port: int) -> int | None: @@ -39,7 +40,33 @@ def require_free_port(port: int, flag: str) -> None: f"{alternative if alternative else '<端口>'} 指定其他端口。") -def start(mode: str = "serve", port: int = 8000, web_port: int = 5173, log_level: str = "info") -> int: +def video_gateway_config(explicit: Path | None, workspace: Path) -> Path | None: + """The video gateway runs only when it is configured: the given file, else the one beside the model settings.""" + if explicit is not None: + return explicit.expanduser().resolve() + default = workspace / VIDEO_GATEWAY_FILE + return default if default.is_file() else None + + +def video_gateway_listen(config: Path, api_port: int) -> tuple[str, int]: + """Check the configuration and its port before anything is spawned; returns where to reach the gateway.""" + from opendirector.video_gateway import ConfigError, load + try: + settings = load(config) + except ConfigError as error: + raise RuntimeError(f"Video gateway configuration is invalid / 视频转发层配置无效:{error}") from None + # A wildcard address is reached through the matching loopback one. + host = {"0.0.0.0": "127.0.0.1", "::": "::1"}.get(settings["host"], settings["host"]) + port = settings["port"] + if port == api_port or port_in_use(port, host): + raise RuntimeError( + f"Video gateway port {port} is already in use; close the program that holds it or change listen.port in {config}. / " + f"视频转发层端口 {port} 已被占用:请关闭占用该端口的程序,或修改 {config} 中的 listen.port。") + return host, port + + +def start(mode: str = "serve", port: int = 8000, web_port: int = 5173, log_level: str = "info", + video_gateway: Path | None = None) -> int: if not 1 <= port <= 65535 or not 1 <= web_port <= 65535: raise ValueError("端口必须在 1–65535 之间。") if mode not in {"serve", "dev"}: @@ -61,6 +88,13 @@ def start(mode: str = "serve", port: int = 8000, web_port: int = 5173, log_level require_free_port(port, "--port") if mode == "dev": require_free_port(web_port, "--web-port") + gateway_config = video_gateway_config(video_gateway, workspace) + gateway = None + if gateway_config: + gateway_host, gateway_port = video_gateway_listen(gateway_config, port) + gateway = subprocess.Popen([sys.executable, "-m", "opendirector.video_gateway", str(gateway_config), "--log-level", log_level], + cwd=workspace, env=environment) + processes.append(gateway) api = subprocess.Popen([sys.executable, "-m", "opendirector_api.server", "--port", str(port), "--log-level", log_level], cwd=workspace, env=environment) processes.append(api) opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) @@ -77,6 +111,17 @@ def start(mode: str = "serve", port: int = 8000, web_port: int = 5173, log_level time.sleep(0.1) else: raise RuntimeError("等待本地服务启动超时。") + if gateway: + for _ in range(300): + if gateway.poll() is not None: + raise RuntimeError("The video gateway failed to start; see the error output above. / 视频转发层启动失败,请查看上方错误输出。") + if port_in_use(gateway_port, gateway_host): + break + time.sleep(0.1) + else: + raise RuntimeError("Timed out waiting for the video gateway. / 等待视频转发层启动超时。") + address = f"[{gateway_host}]" if ":" in gateway_host else gateway_host + print(f"Video gateway / 视频转发层: http://{address}:{gateway_port}/v1 ({gateway_config})", flush=True) if mode == "dev": node = shutil.which("node") vite = ROOT / "node_modules/vite/bin/vite.js" diff --git a/packages/core/src/opendirector/video_gateway.py b/packages/core/src/opendirector/video_gateway.py new file mode 100644 index 000000000..d82ac8afc --- /dev/null +++ b/packages/core/src/opendirector/video_gateway.py @@ -0,0 +1,311 @@ +"""Config-driven gateway in front of vLLM-Omni video servers. + +A client names a model. When that name is listed in the YAML file, the gateway rewrites the request for +the server that really runs it: the served model name, forced or default form fields (step count, flow +shift, ...), keys inside `extra_params`, and the `lora` the weights need. Any other request is forwarded +to the default backend exactly as it arrived. + +`opendirector serve` starts this process when a configuration exists (see launcher.py). The format is +described in docs/guides/video-gateway.md and tools/video-gateway/video-gateway.example.yaml. +""" +import argparse +import json +import logging +import re +import sys +from pathlib import Path + +import httpx +import uvicorn +import yaml +from starlette.applications import Starlette +from starlette.background import BackgroundTask +from starlette.responses import JSONResponse, Response, StreamingResponse +from starlette.routing import Route + +log = logging.getLogger("opendirector.video_gateway") # not __name__: the module runs as __main__ +MAX_BODY = 768 * 1024 * 1024 +HOP = {"host", "connection", "transfer-encoding", "keep-alive", "content-length"} +CREATE = {"/v1/videos", "/v1/videos/sync"} +JOB = re.compile(r"^/v1/videos/(?!sync$)([^/]+)(/content)?$") + + +class ConfigError(ValueError): + pass + + +def load(path: Path) -> dict: + """Parse and check the model table; raises ConfigError with a message that names the entry.""" + try: + raw = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + except (OSError, UnicodeDecodeError, yaml.YAMLError) as error: + raise ConfigError(f"cannot read {path}: {error}") from None + if not isinstance(raw, dict): + raise ConfigError(f"{path} must be a mapping with `default_backend` and `models`") + models = raw.get("models") or {} + if not isinstance(models, dict): + raise ConfigError("`models` must be a mapping of model names") + default = raw.get("default_backend") + if not isinstance(default, str) or not default.startswith(("http://", "https://")): + raise ConfigError("`default_backend` must be the URL that unlisted models are forwarded to") + table = {} + for name, entry in models.items(): + if not isinstance(entry, dict) or not isinstance(entry.get("backend"), str): + raise ConfigError(f"model {name!r} needs a `backend` URL") + unknown = set(entry) - {"backend", "backend_model", "set", "defaults", "extra_params", "lora"} + if unknown: + raise ConfigError(f"model {name!r} has unknown keys: {', '.join(sorted(unknown))}") + for key in ("set", "defaults", "extra_params"): + if not isinstance(entry.get(key, {}), dict): + raise ConfigError(f"model {name!r}: `{key}` must be a mapping") + lora = entry.get("lora") + if lora is not None: + if not isinstance(lora, dict) or not {"name", "path"} <= set(lora): + raise ConfigError(f"model {name!r}: `lora` needs `name` and `path`") + # The path belongs to the vLLM-Omni server, which may be another machine: it is sent, not checked. + lora = {"name": str(lora["name"]), "path": str(lora["path"]), "scale": float(lora.get("scale", 1.0))} + table[str(name)] = { + "backend": entry["backend"].rstrip("/"), "backend_model": str(entry.get("backend_model", name)), + "set": {str(k): v for k, v in entry.get("set", {}).items()}, + "defaults": {str(k): v for k, v in entry.get("defaults", {}).items()}, + "extra_params": dict(entry.get("extra_params", {})), + "lora": lora, "strip_lora": "lora" in entry and entry["lora"] is None, + } + listen = raw.get("listen") or {} + port = listen.get("port", 8101) if isinstance(listen, dict) else None + if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535: + raise ConfigError("`listen.port` must be a port number between 1 and 65535") + return {"models": table, "default_backend": default.rstrip("/"), + "host": str(listen.get("host", "127.0.0.1")), "port": port} + + +def scalar(value) -> str: + """Form fields are text; keep booleans and numbers in the spelling the API reads.""" + return ("true" if value else "false") if isinstance(value, bool) else str(value) + + +def rewrite(entry: dict, fields: dict) -> tuple[dict, list[str]]: + """Apply one model entry to a request's text fields. Returns the new fields and what changed.""" + new, changes = dict(fields), [] + + def put(key, value, *, only_if_missing=False): + if only_if_missing and key in new: + return + if new.get(key) != value: + changes.append(f"{key}={value if len(value) < 60 else value[:57] + '...'}" + (f" (was {new[key]})" if key in new else "")) + new[key] = value + + put("model", entry["backend_model"]) + for key, value in entry["set"].items(): + put(key, scalar(value)) + for key, value in entry["defaults"].items(): + put(key, scalar(value), only_if_missing=True) + if entry["extra_params"]: + try: + extra = json.loads(new.get("extra_params") or "{}") + except ValueError: + extra = None + if not isinstance(extra, dict): + raise ValueError("extra_params is not a JSON object") + merged = {**extra, **entry["extra_params"]} + if merged != extra: + changes.append("extra_params += " + json.dumps({k: v for k, v in entry["extra_params"].items() if extra.get(k) != v})) + new["extra_params"] = json.dumps(merged) + if entry["lora"]: + put("lora", json.dumps(entry["lora"])) + elif entry["strip_lora"] and "lora" in new: + changes.append("lora removed") + del new["lora"] + return new, changes + + +# --- multipart/form-data: text fields are rewritten, file parts are carried through byte for byte ------------ + +def split_multipart(body: bytes, boundary: bytes): + """Return [(name, filename or None, header block, content)] for every part.""" + delimiter = b"--" + boundary + chunks = body.split(delimiter) + if len(chunks) < 3 or not chunks[-1].lstrip().startswith(b"--"): + raise ValueError("malformed multipart body") + parts = [] + for chunk in chunks[1:-1]: + chunk = chunk.removeprefix(b"\r\n").removesuffix(b"\r\n") + head, separator, content = chunk.partition(b"\r\n\r\n") + if not separator: + raise ValueError("malformed multipart part") + disposition = next((line for line in head.split(b"\r\n") if line.lower().startswith(b"content-disposition")), b"") + name = re.search(rb'[; ]name="([^"]*)"', disposition) + filename = re.search(rb'[; ]filename="([^"]*)"', disposition) + if not name: + raise ValueError("multipart part without a name") + parts.append((name.group(1).decode(), filename.group(1).decode() if filename else None, head, content)) + return parts + + +def join_multipart(parts, boundary: bytes) -> bytes: + out = bytearray() + for _, _, head, content in parts: + out += b"--" + boundary + b"\r\n" + head + b"\r\n\r\n" + content + b"\r\n" + return bytes(out + b"--" + boundary + b"--\r\n") + + +def text_part(name: str, value: str): + return name, None, f'Content-Disposition: form-data; name="{name}"'.encode(), value.encode() + + +class Gateway: + def __init__(self, path: Path): + self.path, self.stamp, self.config = path, None, None + self.jobs: dict[str, str] = {} # job id -> backend that owns it + self.client = httpx.AsyncClient(timeout=None) + self.reload(required=True) + + def reload(self, required=False): + """Pick up an edited file; a broken edit keeps serving the last good table.""" + try: + stamp = self.path.stat().st_mtime_ns + if stamp == self.stamp: + return + self.config, self.stamp = load(self.path), stamp + log.info("loaded %d models from %s: %s", len(self.config["models"]), self.path, ", ".join(self.config["models"])) + except (OSError, ConfigError) as error: + if required: + raise + if getattr(self, "_reported", None) != str(error): + log.error("keeping the previous configuration: %s", error) + self._reported = str(error) + + def backends(self): + """Every backend in use, the default one first.""" + return list(dict.fromkeys([self.config["default_backend"], *(entry["backend"] for entry in self.config["models"].values())])) + + @staticmethod + def error(status, message): + return JSONResponse({"error": {"message": message, "type": "gateway_error", "code": status}}, status_code=status) + + async def relay(self, request, backend, *, content=None, headers=None, remember=False): + headers = headers or {k: v for k, v in request.headers.items() if k.lower() not in HOP} + if content is None: + content = request.stream() + if "content-length" in request.headers: + headers["content-length"] = request.headers["content-length"] + upstream = self.client.build_request(request.method, backend + request.url.path, params=request.query_params, + headers=headers, content=content) + try: + response = await self.client.send(upstream, stream=True) + except httpx.HTTPError as error: + return self.error(502, f"backend {backend} is unreachable: {type(error).__name__}") + passed = {k: v for k, v in response.headers.items() if k.lower() not in HOP - {"content-length"}} + if remember: + # An async create answers with a small job document; note which backend owns the job. + data = await response.aread() + await response.aclose() + try: + job = json.loads(data).get("id") + if isinstance(job, str): + self.jobs[job] = backend + except (ValueError, AttributeError): + pass + kept = {k: v for k, v in passed.items() if k.lower() not in {"content-length", "content-encoding"}} + return Response(data, status_code=response.status_code, headers=kept) + return StreamingResponse(response.aiter_raw(), status_code=response.status_code, headers=passed, + background=BackgroundTask(response.aclose)) + + async def create(self, request): + content_type = request.headers.get("content-type", "") + body = bytearray() + async for chunk in request.stream(): + body += chunk + if len(body) > MAX_BODY: + return self.error(413, "request body is too large for the gateway") + body = bytes(body) + multipart = "multipart/form-data" in content_type and "boundary=" in content_type + try: + if multipart: + boundary = content_type.split("boundary=", 1)[1].split(";", 1)[0].strip().strip('"').encode() + parts = split_multipart(body, boundary) + fields = {name: content.decode() for name, filename, _, content in parts if filename is None} + else: + document = json.loads(body or b"{}") + fields = {key: value if isinstance(value, str) else json.dumps(value) for key, value in document.items()} + except (ValueError, UnicodeDecodeError, AttributeError): + # Not a body the gateway understands, so it cannot name a listed model: forward it as it is. + fields = {} + name = fields.get("model") + entry = self.config["models"].get(name) + headers = {k: v for k, v in request.headers.items() if k.lower() not in HOP} + remember = request.url.path.rstrip("/") == "/v1/videos" + if entry is None: + # Not a listed model: the default backend gets the request byte for byte. + log.info("%s %s -> %s: passed through unchanged", request.url.path, name, self.config["default_backend"]) + return await self.relay(request, self.config["default_backend"], content=body, headers=headers, remember=remember) + try: + new, changes = rewrite(entry, fields) + except ValueError as error: + return self.error(400, str(error)) + log.info("%s %s -> %s: %s", request.url.path, name, entry["backend"], "; ".join(changes) or "unchanged") + if multipart: + kept = [part for part in parts if part[1] is not None or part[0] in new] + rebuilt = [text_part(part[0], new[part[0]]) if part[1] is None else part for part in kept] + rebuilt += [text_part(key, value) for key, value in new.items() if key not in fields] + body = join_multipart(rebuilt, boundary) + else: + def typed(key): + # Untouched keys keep their original JSON type; rewritten ones are parsed back from text. + if key in fields and new[key] == fields[key]: + return document[key] + try: + return json.loads(new[key]) + except ValueError: + return new[key] + body = json.dumps({key: typed(key) for key in new}).encode() + return await self.relay(request, entry["backend"], content=body, headers=headers, remember=remember) + + async def handle(self, request): + self.reload() + path = request.url.path.rstrip("/") or "/" + if request.method == "POST" and path in CREATE: + return await self.create(request) + if request.method == "GET" and path == "/v1/models": + # The listed names, then whatever the default backend serves under its own names. + listed = [{"id": name, "object": "model", "owned_by": "gateway"} for name in self.config["models"]] + try: + native = (await self.client.get(self.config["default_backend"] + "/v1/models", timeout=5)).json().get("data", []) + except (httpx.HTTPError, ValueError, AttributeError): + native = [] + names = set(self.config["models"]) + return JSONResponse({"object": "list", "data": listed + [item for item in native if item.get("id") not in names]}) + job = JOB.match(path) + backends = self.backends() + if job and job.group(1) not in self.jobs and len(backends) > 1 and request.method == "GET": + # A job from before a restart: ask each backend until one knows it. + for backend in backends: + probe = await self.client.get(f"{backend}/v1/videos/{job.group(1)}") + if probe.status_code != 404: + self.jobs[job.group(1)] = backend + break + return await self.relay(request, self.jobs.get(job.group(1), backends[0]) if job else backends[0]) + + +def application(gateway: Gateway) -> Starlette: + return Starlette(routes=[Route("/{path:path}", gateway.handle, methods=["GET", "POST", "DELETE"])]) + + +def main() -> None: + parser = argparse.ArgumentParser(description="Run the OpenDirector video gateway") + parser.add_argument("config", type=Path, help="YAML file that lists the models") + parser.add_argument("--log-level", choices=("debug", "info", "warning", "error", "critical"), default="info") + args = parser.parse_args() + logging.basicConfig(level=args.log_level.upper(), format="%(asctime)s %(levelname)-7s %(name)s %(message)s", + datefmt="%Y-%m-%d %H:%M:%S") + logging.getLogger("httpx").setLevel(logging.WARNING) + try: + gateway = Gateway(args.config) + except (OSError, ConfigError) as error: + sys.exit(f"video gateway: {error}") + uvicorn.run(application(gateway), host=gateway.config["host"], port=gateway.config["port"], + log_level=args.log_level, log_config=None) + + +if __name__ == "__main__": + main() diff --git a/tests/test_video_gateway.py b/tests/test_video_gateway.py new file mode 100644 index 000000000..fb1982ed8 --- /dev/null +++ b/tests/test_video_gateway.py @@ -0,0 +1,245 @@ +"""The video gateway rewrites listed models and relays everything else untouched.""" +import json +import os +from pathlib import Path +import socket +import subprocess +import sys +import time + +import httpx +import pytest +from starlette.testclient import TestClient + +from opendirector import launcher +from opendirector import video_gateway as gateway + + +pytestmark = pytest.mark.cpu +ROOT = Path(__file__).resolve().parents[1] +EXAMPLE = ROOT / "tools/video-gateway/video-gateway.example.yaml" + + +def entry(**extra): + base = {"backend": "http://b", "backend_model": "served", "set": {}, "defaults": {}, "extra_params": {}, "lora": None, "strip_lora": False} + return {**base, **extra} + + +def free_port(): + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + return probe.getsockname()[1] + + +def test_rewrite_forces_set_fills_defaults_and_merges_extra_params(): + fields = {"model": "alias", "num_inference_steps": "8", "size": "832x480", "extra_params": '{"task": "ref2va", "audio_flow_shift": 5}'} + lora = {"name": "n", "path": "/p", "scale": 1.0} + new, changes = gateway.rewrite(entry(set={"num_inference_steps": 4, "flow_shift": 12}, defaults={"size": "1x1", "fps": 24}, + extra_params={"audio_flow_shift": 3}, lora=lora), fields) + assert new["model"] == "served" and new["num_inference_steps"] == "4" and new["flow_shift"] == "12" + assert new["size"] == "832x480" and new["fps"] == "24" # a default never replaces a sent value + assert json.loads(new["extra_params"]) == {"task": "ref2va", "audio_flow_shift": 3} + assert json.loads(new["lora"]) == lora + assert any(change.startswith("num_inference_steps=4 (was 8)") for change in changes) + + +def test_lora_is_stripped_only_when_the_entry_says_null(): + fields = {"model": "alias", "lora": '{"name": "client"}'} + assert "lora" not in gateway.rewrite(entry(strip_lora=True), fields)[0] + assert gateway.rewrite(entry(), fields)[0]["lora"] == '{"name": "client"}' + + +def test_multipart_round_trip_keeps_files_byte_for_byte(): + payload = bytes(range(256)) * 4 + b"\r\n--not-the-boundary\r\n" + request = httpx.Request("POST", "http://x/v1/videos", data={"model": "alias", "prompt": " 舞"}, + files=[("input_references", ("a.png", payload, "image/png")), ("input_references", ("b.png", b"second", "image/png"))]) + body = request.read() + boundary = request.headers["content-type"].split("boundary=")[1].encode() + parts = gateway.split_multipart(body, boundary) + assert [(name, filename) for name, filename, _, _ in parts] == [("model", None), ("prompt", None), ("input_references", "a.png"), ("input_references", "b.png")] + assert parts[2][3] == payload and parts[1][3].decode() == " 舞" + assert gateway.join_multipart(parts, boundary) == body + rebuilt = gateway.join_multipart([gateway.text_part("model", "served"), *parts[1:], gateway.text_part("lora", "{}")], boundary) + again = gateway.split_multipart(rebuilt, boundary) + assert again[0][3] == b"served" and again[2][3] == payload and again[-1][0] == "lora" + + +@pytest.mark.parametrize("text, message", [ + ("- not a mapping", "must be a mapping"), + ("models: {}", "`default_backend` must be the URL"), + ("default_backend: http://d\nlisten: {port: '8101'}", "`listen.port` must be a port number"), + ("default_backend: http://d\nmodels:\n a: {set: {}}", "'a' needs a `backend`"), + ("default_backend: http://d\nmodels:\n a: {backend: http://b, stepz: 4}", "unknown keys: stepz"), + ("default_backend: http://d\nmodels:\n a: {backend: http://b, lora: {name: n}}", "`lora` needs `name` and `path`"), +], ids=["not-a-mapping", "no-default-backend", "text-port", "no-backend", "unknown-key", "lora-without-path"]) +def test_config_errors_name_the_problem(tmp_path, text, message): + path = tmp_path / "video-gateway.yaml" + path.write_text(text) + with pytest.raises(gateway.ConfigError, match=message): + gateway.load(path) + + +def test_the_example_configuration_loads(): + config = gateway.load(EXAMPLE) + assert config["host"] == "127.0.0.1" and config["port"] == 8101 + assert config["models"]["Pika-Labs/Pika-H3-Flex-Turbo-4step"]["set"]["num_inference_steps"] == 4 + # The LoRA lives on the model server, so a path that is absent here is still accepted. + assert config["models"]["Pika-Labs/Pika-H3-Flex-Turbo-8step-HD"]["lora"]["path"].startswith("/path/to/") + assert config["models"]["MiniMaxAI/MiniMax-H3-Ref2VA"]["strip_lora"] + + +def served(tmp_path): + """A gateway with one listed model, its backends replaced by a recorder.""" + config = tmp_path / "video-gateway.yaml" + config.write_text("default_backend: http://default\nmodels:\n listed:\n backend: http://special\n backend_model: served\n" + " set: {num_inference_steps: 4}\n lora: {name: n, path: /server/adapter.safetensors}\n") + seen = [] + + def backend(request): + # Only creates carry a buffered body; polls are relayed as streams the recorder does not read. + seen.append((request.url.host, request.url.path, request.headers.get("content-type"), + request.content if request.method == "POST" else b"")) + document = {"data": [{"id": "native-model"}]} if request.url.path == "/v1/models" else {"id": "job-" + request.url.host} + # Real backends answer as streams, which is what the gateway relays. + return httpx.Response(200, headers={"content-type": "application/json"}, stream=httpx.ByteStream(json.dumps(document).encode())) + + app = gateway.Gateway(config) + app.client = httpx.AsyncClient(transport=httpx.MockTransport(backend)) + return TestClient(gateway.application(app)), seen, config + + +def test_an_unlisted_model_reaches_the_default_backend_byte_for_byte(tmp_path): + client, seen, _ = served(tmp_path) + request = httpx.Request("POST", "http://x/v1/videos", data={"model": "native-model", "num_inference_steps": "8", "lora": "{}"}, + files={"input_references": ("a.png", b"\x89PNG-bytes", "image/png")}) + body = request.read() + response = client.post("/v1/videos", content=body, headers={"content-type": request.headers["content-type"]}) + assert response.json() == {"id": "job-default"} + host, path, content_type, content = seen[-1] + assert (host, path) == ("default", "/v1/videos") and content == body and content_type == request.headers["content-type"] + # The job it created is polled on the same backend. + client.get("/v1/videos/job-default") + assert seen[-1][:2] == ("default", "/v1/videos/job-default") + + +def test_a_listed_model_is_rewritten_and_sent_to_its_own_backend(tmp_path): + client, seen, _ = served(tmp_path) + request = httpx.Request("POST", "http://x/v1/videos", data={"model": "listed", "num_inference_steps": "8"}, + files={"input_references": ("a.png", b"\x89PNG-bytes", "image/png")}) + client.post("/v1/videos", content=request.read(), headers={"content-type": request.headers["content-type"]}) + host, _, content_type, content = seen[-1] + parts = {name: body for name, _, _, body in gateway.split_multipart(content, content_type.split("boundary=")[1].encode())} + assert host == "special" and parts["model"] == b"served" and parts["num_inference_steps"] == b"4" + assert json.loads(parts["lora"]) == {"name": "n", "path": "/server/adapter.safetensors", "scale": 1.0} + assert parts["input_references"] == b"\x89PNG-bytes" + client.get("/v1/videos/job-special") + assert seen[-1][:2] == ("special", "/v1/videos/job-special") + + +def test_model_list_shows_listed_names_and_the_default_backends_own(tmp_path): + client, _, _ = served(tmp_path) + assert [item["id"] for item in client.get("/v1/models").json()["data"]] == ["listed", "native-model"] + + +def test_an_edited_file_is_picked_up_and_a_broken_edit_keeps_the_last_table(tmp_path): + client, _, config = served(tmp_path) + good = config.read_text() + + def rewrite(text): + # Step the timestamp explicitly: two writes can share one on a coarse filesystem clock. + stamp = config.stat().st_mtime_ns + 1_000_000_000 + config.write_text(text) + os.utime(config, ns=(stamp, stamp)) + + rewrite(good.replace("listed:", "renamed:")) + assert [item["id"] for item in client.get("/v1/models").json()["data"]] == ["renamed", "native-model"] + rewrite("models: [broken") + assert [item["id"] for item in client.get("/v1/models").json()["data"]] == ["renamed", "native-model"] + + +# --- started with OpenDirector ----------------------------------------------------------------------------- + +def test_the_gateway_is_configured_by_an_explicit_file_or_the_one_beside_the_model_settings(tmp_path): + assert launcher.video_gateway_config(None, tmp_path) is None + default = tmp_path / ".opendirector" / "video-gateway.yaml" + default.parent.mkdir() + default.write_text("default_backend: http://d\n") + assert launcher.video_gateway_config(None, tmp_path) == default + explicit = tmp_path / "other.yaml" + assert launcher.video_gateway_config(explicit, tmp_path) == explicit.resolve() + + +@pytest.fixture +def unspawned(tmp_path, monkeypatch): + """A launcher that may check its inputs but must not start a process.""" + web = tmp_path / "web" + web.mkdir() + (web / "index.html").write_text("") + monkeypatch.setattr(launcher, "web_root", lambda: web) + monkeypatch.setattr(launcher, "data_root", lambda: tmp_path / "data") + + def refuse(*args, **kwargs): + raise AssertionError("nothing may be spawned before the gateway configuration is accepted") + monkeypatch.setattr(launcher.subprocess, "Popen", refuse) + return tmp_path + + +def test_an_invalid_gateway_configuration_stops_the_start_before_anything_is_spawned(unspawned, capsys): + config = unspawned / "gateway.yaml" + config.write_text("models: {}\n") + assert launcher.start("serve", free_port(), video_gateway=config) == 1 + message = capsys.readouterr().err + assert "Video gateway configuration is invalid" in message and "视频转发层配置无效" in message + assert "`default_backend` must be the URL" in message + + +def test_a_bound_gateway_port_stops_the_start_and_names_the_setting(unspawned, capsys): + listener = socket.socket() + listener.bind(("127.0.0.1", 0)) + listener.listen() + try: + config = unspawned / "gateway.yaml" + config.write_text(f"default_backend: http://d\nlisten: {{port: {listener.getsockname()[1]}}}\n") + assert launcher.start("serve", free_port(), video_gateway=config) == 1 + finally: + listener.close() + message = capsys.readouterr().err + assert "listen.port" in message and "已被占用" in message and str(config) in message + + +def test_the_gateway_port_cannot_be_the_application_port(unspawned, capsys): + port = free_port() + config = unspawned / "gateway.yaml" + config.write_text(f"default_backend: http://d\nlisten: {{port: {port}}}\n") + assert launcher.start("serve", port, video_gateway=config) == 1 + assert "listen.port" in capsys.readouterr().err + + +def test_the_module_entry_point_serves_the_configured_models(tmp_path): + """The command the launcher runs, as a real process: it listens where the file says and answers.""" + port = free_port() + config = tmp_path / "video-gateway.yaml" + # Nothing listens on the default backend, so the list is the configured names alone. + config.write_text(f"listen: {{port: {port}}}\ndefault_backend: http://127.0.0.1:{free_port()}\n" + "models:\n listed: {backend: 'http://127.0.0.1:9'}\n") + process = subprocess.Popen([sys.executable, "-m", "opendirector.video_gateway", str(config)], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + deadline = time.monotonic() + 30 + while not launcher.port_in_use(port): + assert process.poll() is None, "the gateway exited before listening" + assert time.monotonic() < deadline, "the gateway did not start listening" + time.sleep(0.1) + with httpx.Client(trust_env=False) as client: + listed = client.get(f"http://127.0.0.1:{port}/v1/models", timeout=20).json() + assert [item["id"] for item in listed["data"]] == ["listed"] + finally: + process.terminate() + process.wait(timeout=10) + + +def test_the_module_entry_point_rejects_a_broken_configuration(tmp_path): + config = tmp_path / "video-gateway.yaml" + config.write_text("models: {}\n") + result = subprocess.run([sys.executable, "-m", "opendirector.video_gateway", str(config)], capture_output=True, text=True, timeout=60) + assert result.returncode != 0 and "`default_backend` must be the URL" in result.stderr diff --git a/tools/video-gateway/video-gateway.example.yaml b/tools/video-gateway/video-gateway.example.yaml new file mode 100644 index 000000000..fd5993205 --- /dev/null +++ b/tools/video-gateway/video-gateway.example.yaml @@ -0,0 +1,74 @@ +# Models offered by the OpenDirector video gateway. Copy this file to `.opendirector/video-gateway.yaml` +# in the OpenDirector data directory (beside models.json), or pass it with +# `opendirector serve --video-gateway `, and adjust it. +# See docs/guides/video-gateway.md. +# +# Each key under `models` is a model name a client may send. When a request's `model` is listed, the +# gateway rewrites the request as described and forwards it to that entry's `backend`. A request for any +# other model name goes to `default_backend` exactly as it arrived. +# The model table is re-read whenever the file changes; a file that fails to load keeps the previous +# version active. A changed `listen` address takes effect at the next start. +# +# backend base URL of the vLLM-Omni server that runs this model +# backend_model the name that server was started with (--served-model-name); defaults to the key +# set form fields forced to these values, replacing whatever the client sent +# defaults form fields added only when the client did not send them +# extra_params keys forced inside the request's extra_params JSON +# lora {name, path, scale} sent as the request's `lora`; `lora: null` strips any client-sent one; +# leaving the key out passes the client's own `lora` through +# +# `lora.path` is a path on the vLLM-Omni server, which may be another machine: the gateway sends it +# without checking it. Keep the released filename: the server reads the adapter's schedule from it. +# +# OpenDirector's FastH3-Omni requests always carry num_inference_steps=8 and guidance_scale=1, so an +# entry whose weights need another step count must force it under `set`. + +listen: + host: 127.0.0.1 + port: 8101 + +# Requests whose model is not listed below are forwarded here unchanged. +default_backend: http://127.0.0.1:8091 + +models: + # Pika Flex Turbo on base MiniMax-H3 Ref2VA, 8 steps. + Pika-Labs/Pika-H3-Flex-Turbo-8step-HD: + backend: http://127.0.0.1:8091 + backend_model: MiniMaxAI/MiniMax-H3 + set: + num_inference_steps: 8 + guidance_scale: 1 + flow_shift: 12 + extra_params: + audio_flow_shift: 3 + lora: + name: pika-h3-flex-turbo-8step-hd + path: /path/to/loras/pika_h3_flex_turbo_8step_hd_ref2va.safetensors + scale: 1.0 + + # The 4-step file of the same adapter on the same server: only the step count and the file differ. + Pika-Labs/Pika-H3-Flex-Turbo-4step: + backend: http://127.0.0.1:8091 + backend_model: MiniMaxAI/MiniMax-H3 + set: + num_inference_steps: 4 + guidance_scale: 1 + flow_shift: 12 + extra_params: + audio_flow_shift: 3 + lora: + name: pika-h3-flex-turbo-4step + path: /path/to/loras/pika_h3_flex_turbo_4step_ref2va.safetensors + scale: 1.0 + + # Base Ref2VA weights without an adapter, on their own longer schedule. + MiniMaxAI/MiniMax-H3-Ref2VA: + backend: http://127.0.0.1:8091 + backend_model: MiniMaxAI/MiniMax-H3 + set: + num_inference_steps: 20 + guidance_scale: 1 + flow_shift: 12 + extra_params: + audio_flow_shift: 3 + lora: null From 088956001fafa90a27e48b5884efdc0049968ac4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=AA=E5=BF=97=E9=B9=8F?= Date: Fri, 27 Nov 2026 07:36:10 +0000 Subject: [PATCH 2/2] [bugfix] provider: harden video gateway failure paths ## summary - Reach backends directly. The client followed proxy settings from the environment, so a loopback or LAN server was sent through HTTP_PROXY. - Report every mistake in the file as a configuration error: a non-numeric `lora.scale`, a `backend` without a scheme, an empty value under `set` or `defaults`, and non-text keys. A running gateway now keeps its previous table for these instead of answering 500. - Find the backend of a job the gateway did not see created, as after a restart, with the caller's credentials. Only a successful answer counts as ownership, a backend that is down is skipped, and the lookup also runs for cancellation. - Keep repeated text fields and per-part headers when a multipart request is rewritten, and rewrite urlencoded forms. - Send lists and mappings under `set` as JSON text. - In `opendirector dev`, reject a gateway port equal to the web port. ## validation - pytest tests/test_video_gateway.py tests/test_launcher.py tests/test_cli.py - lint-imports - Real vLLM-Omni MiniMax-H3 server with a dead proxy named in HTTP_PROXY and ALL_PROXY: both listed models returned video with audio Co-Authored-By: Claude Fable 5.2 --- docs/guides/video-gateway.md | 3 +- docs/guides/video-gateway.zh-CN.md | 3 +- packages/core/src/opendirector/launcher.py | 11 +- .../core/src/opendirector/video_gateway.py | 86 ++++++++++--- tests/test_video_gateway.py | 116 +++++++++++++++++- 5 files changed, 187 insertions(+), 32 deletions(-) diff --git a/docs/guides/video-gateway.md b/docs/guides/video-gateway.md index 47ac7652d..b78eff1a1 100644 --- a/docs/guides/video-gateway.md +++ b/docs/guides/video-gateway.md @@ -78,7 +78,8 @@ Add one model for each configured name. A model name that is not in the file sti - A video creation request (`POST /v1/videos` or `POST /v1/videos/sync`) whose `model` is listed is rewritten as configured and sent to that entry's backend. Uploaded files are carried through unchanged. - A request for any other model name goes to `default_backend` exactly as it arrived. -- Status queries, downloads and cancellation are relayed to the backend that created the job. +- Status queries, downloads and cancellation are relayed to the backend that created the job. After a gateway restart, the backend that answers for a job is looked up again with the caller's credentials. +- Backends are reached directly. Proxy settings in the environment, such as `HTTP_PROXY`, are not applied to them. - `GET /v1/models` lists the configured names, then the default backend's own. - Each rewrite is logged with the fields it changed, in the same terminal as the application. diff --git a/docs/guides/video-gateway.zh-CN.md b/docs/guides/video-gateway.zh-CN.md index 3204f70bb..8e2d8c8ee 100644 --- a/docs/guides/video-gateway.zh-CN.md +++ b/docs/guides/video-gateway.zh-CN.md @@ -78,7 +78,8 @@ OpenDirector: http://127.0.0.1:8000 (Ctrl+C 退出) - 视频创建请求(`POST /v1/videos` 或 `POST /v1/videos/sync`)的 `model` 在配置里时,按配置改写后发给该条目的后端。上传的文件原样传递。 - 其他模型名的请求原样转给 `default_backend`。 -- 状态查询、下载和取消会转给创建该任务的后端。 +- 状态查询、下载和取消会转给创建该任务的后端。转发层重启后,会带着调用方的凭证重新查找任务所在的后端。 +- 转发层直连后端,不使用环境变量里的代理设置(例如 `HTTP_PROXY`)。 - `GET /v1/models` 先列出配置里的名字,再列出默认后端自己的。 - 每次改写都会记录改动了哪些字段,日志与应用在同一个终端里。 diff --git a/packages/core/src/opendirector/launcher.py b/packages/core/src/opendirector/launcher.py index 6d980a4ee..888b73c88 100644 --- a/packages/core/src/opendirector/launcher.py +++ b/packages/core/src/opendirector/launcher.py @@ -48,8 +48,11 @@ def video_gateway_config(explicit: Path | None, workspace: Path) -> Path | None: return default if default.is_file() else None -def video_gateway_listen(config: Path, api_port: int) -> tuple[str, int]: - """Check the configuration and its port before anything is spawned; returns where to reach the gateway.""" +def video_gateway_listen(config: Path, taken: set[int]) -> tuple[str, int]: + """Check the configuration and its port before anything is spawned; returns where to reach the gateway. + + `taken` holds the ports this start is about to bind itself, which are still free when this runs. + """ from opendirector.video_gateway import ConfigError, load try: settings = load(config) @@ -58,7 +61,7 @@ def video_gateway_listen(config: Path, api_port: int) -> tuple[str, int]: # A wildcard address is reached through the matching loopback one. host = {"0.0.0.0": "127.0.0.1", "::": "::1"}.get(settings["host"], settings["host"]) port = settings["port"] - if port == api_port or port_in_use(port, host): + if port in taken or port_in_use(port, host): raise RuntimeError( f"Video gateway port {port} is already in use; close the program that holds it or change listen.port in {config}. / " f"视频转发层端口 {port} 已被占用:请关闭占用该端口的程序,或修改 {config} 中的 listen.port。") @@ -91,7 +94,7 @@ def start(mode: str = "serve", port: int = 8000, web_port: int = 5173, log_level gateway_config = video_gateway_config(video_gateway, workspace) gateway = None if gateway_config: - gateway_host, gateway_port = video_gateway_listen(gateway_config, port) + gateway_host, gateway_port = video_gateway_listen(gateway_config, {port, web_port} if mode == "dev" else {port}) gateway = subprocess.Popen([sys.executable, "-m", "opendirector.video_gateway", str(gateway_config), "--log-level", log_level], cwd=workspace, env=environment) processes.append(gateway) diff --git a/packages/core/src/opendirector/video_gateway.py b/packages/core/src/opendirector/video_gateway.py index d82ac8afc..046fd7377 100644 --- a/packages/core/src/opendirector/video_gateway.py +++ b/packages/core/src/opendirector/video_gateway.py @@ -14,6 +14,7 @@ import re import sys from pathlib import Path +from urllib.parse import parse_qsl, urlencode import httpx import uvicorn @@ -25,6 +26,7 @@ log = logging.getLogger("opendirector.video_gateway") # not __name__: the module runs as __main__ MAX_BODY = 768 * 1024 * 1024 +PROBE_TIMEOUT = 10 # seconds a backend gets to say whether it knows a job HOP = {"host", "connection", "transfer-encoding", "keep-alive", "content-length"} CREATE = {"/v1/videos", "/v1/videos/sync"} JOB = re.compile(r"^/v1/videos/(?!sync$)([^/]+)(/content)?$") @@ -34,6 +36,10 @@ class ConfigError(ValueError): pass +def is_url(value) -> bool: + return isinstance(value, str) and value.startswith(("http://", "https://")) + + def load(path: Path) -> dict: """Parse and check the model table; raises ConfigError with a message that names the entry.""" try: @@ -46,24 +52,31 @@ def load(path: Path) -> dict: if not isinstance(models, dict): raise ConfigError("`models` must be a mapping of model names") default = raw.get("default_backend") - if not isinstance(default, str) or not default.startswith(("http://", "https://")): + if not is_url(default): raise ConfigError("`default_backend` must be the URL that unlisted models are forwarded to") table = {} for name, entry in models.items(): - if not isinstance(entry, dict) or not isinstance(entry.get("backend"), str): - raise ConfigError(f"model {name!r} needs a `backend` URL") + if not isinstance(entry, dict) or not is_url(entry.get("backend")): + raise ConfigError(f"model {name!r} needs a `backend` URL that starts with http:// or https://") unknown = set(entry) - {"backend", "backend_model", "set", "defaults", "extra_params", "lora"} if unknown: - raise ConfigError(f"model {name!r} has unknown keys: {', '.join(sorted(unknown))}") + raise ConfigError(f"model {name!r} has unknown keys: {', '.join(sorted(map(str, unknown)))}") for key in ("set", "defaults", "extra_params"): if not isinstance(entry.get(key, {}), dict): raise ConfigError(f"model {name!r}: `{key}` must be a mapping") + for key in ("set", "defaults"): + empty = [str(field) for field, value in entry.get(key, {}).items() if value is None] + if empty: + raise ConfigError(f"model {name!r}: `{key}.{empty[0]}` has no value") lora = entry.get("lora") if lora is not None: if not isinstance(lora, dict) or not {"name", "path"} <= set(lora): raise ConfigError(f"model {name!r}: `lora` needs `name` and `path`") + scale = lora.get("scale", 1.0) + if not isinstance(scale, (int, float)) or isinstance(scale, bool): + raise ConfigError(f"model {name!r}: `lora.scale` must be a number") # The path belongs to the vLLM-Omni server, which may be another machine: it is sent, not checked. - lora = {"name": str(lora["name"]), "path": str(lora["path"]), "scale": float(lora.get("scale", 1.0))} + lora = {"name": str(lora["name"]), "path": str(lora["path"]), "scale": float(scale)} table[str(name)] = { "backend": entry["backend"].rstrip("/"), "backend_model": str(entry.get("backend_model", name)), "set": {str(k): v for k, v in entry.get("set", {}).items()}, @@ -80,8 +93,8 @@ def load(path: Path) -> dict: def scalar(value) -> str: - """Form fields are text; keep booleans and numbers in the spelling the API reads.""" - return ("true" if value else "false") if isinstance(value, bool) else str(value) + """Form fields are text; booleans, lists and mappings travel in the JSON spelling the API reads.""" + return json.dumps(value) if isinstance(value, (bool, dict, list)) else str(value) def rewrite(entry: dict, fields: dict) -> tuple[dict, list[str]]: @@ -154,10 +167,12 @@ def text_part(name: str, value: str): class Gateway: - def __init__(self, path: Path): + def __init__(self, path: Path, transport: httpx.AsyncBaseTransport | None = None): self.path, self.stamp, self.config = path, None, None self.jobs: dict[str, str] = {} # job id -> backend that owns it - self.client = httpx.AsyncClient(timeout=None) + # Backends are the user's own servers: like OpenDirector's self-hosted connections, reach them + # directly and never through a proxy named in the environment. + self.client = httpx.AsyncClient(timeout=None, trust_env=False, transport=transport) self.reload(required=True) def reload(self, required=False): @@ -220,35 +235,57 @@ async def create(self, request): return self.error(413, "request body is too large for the gateway") body = bytes(body) multipart = "multipart/form-data" in content_type and "boundary=" in content_type + urlencoded = "application/x-www-form-urlencoded" in content_type try: if multipart: boundary = content_type.split("boundary=", 1)[1].split(";", 1)[0].strip().strip('"').encode() parts = split_multipart(body, boundary) fields = {name: content.decode() for name, filename, _, content in parts if filename is None} + elif urlencoded: + pairs = parse_qsl(body.decode(), keep_blank_values=True, strict_parsing=bool(body)) + fields = dict(pairs) else: document = json.loads(body or b"{}") fields = {key: value if isinstance(value, str) else json.dumps(value) for key, value in document.items()} except (ValueError, UnicodeDecodeError, AttributeError): # Not a body the gateway understands, so it cannot name a listed model: forward it as it is. - fields = {} - name = fields.get("model") + fields = None + name = (fields or {}).get("model") entry = self.config["models"].get(name) headers = {k: v for k, v in request.headers.items() if k.lower() not in HOP} remember = request.url.path.rstrip("/") == "/v1/videos" if entry is None: # Not a listed model: the default backend gets the request byte for byte. - log.info("%s %s -> %s: passed through unchanged", request.url.path, name, self.config["default_backend"]) + log.info("%s %s -> %s: passed through unchanged", request.url.path, + "unreadable body" if fields is None else name, self.config["default_backend"]) return await self.relay(request, self.config["default_backend"], content=body, headers=headers, remember=remember) try: new, changes = rewrite(entry, fields) except ValueError as error: return self.error(400, str(error)) log.info("%s %s -> %s: %s", request.url.path, name, entry["backend"], "; ".join(changes) or "unchanged") + changed = {key for key in new if key in fields and new[key] != fields[key]} if multipart: - kept = [part for part in parts if part[1] is not None or part[0] in new] - rebuilt = [text_part(part[0], new[part[0]]) if part[1] is None else part for part in kept] + # Files and untouched text parts keep their own bytes; a changed field is written once. + rebuilt, written = [], set() + for part in parts: + key = part[0] + if part[1] is not None or key in new and key not in changed: + rebuilt.append(part) + elif key in changed and key not in written: + rebuilt.append(text_part(key, new[key])) + written.add(key) rebuilt += [text_part(key, value) for key, value in new.items() if key not in fields] body = join_multipart(rebuilt, boundary) + elif urlencoded: + kept, written = [], set() + for key, value in pairs: + if key in new and key not in changed: + kept.append((key, value)) + elif key in changed and key not in written: + kept.append((key, new[key])) + written.add(key) + body = urlencode(kept + [(key, value) for key, value in new.items() if key not in fields]).encode() else: def typed(key): # Untouched keys keep their original JSON type; rewritten ones are parsed back from text. @@ -276,15 +313,24 @@ async def handle(self, request): names = set(self.config["models"]) return JSONResponse({"object": "list", "data": listed + [item for item in native if item.get("id") not in names]}) job = JOB.match(path) + return await self.relay(request, await self.owner(job.group(1), request) if job else self.config["default_backend"]) + + async def owner(self, job: str, request) -> str: + """The backend that runs a job. One the gateway did not see created, as after a restart, is looked up.""" backends = self.backends() - if job and job.group(1) not in self.jobs and len(backends) > 1 and request.method == "GET": - # A job from before a restart: ask each backend until one knows it. + if job not in self.jobs and len(backends) > 1: + # Ask with the caller's own credentials. Only a backend that answers for the job owns it: an + # error or a refusal says nothing about where the job lives, and a backend that is down is skipped. + headers = {k: v for k, v in request.headers.items() if k.lower() not in HOP | {"content-type"}} for backend in backends: - probe = await self.client.get(f"{backend}/v1/videos/{job.group(1)}") - if probe.status_code != 404: - self.jobs[job.group(1)] = backend + try: + probe = await self.client.get(f"{backend}/v1/videos/{job}", headers=headers, timeout=PROBE_TIMEOUT) + except httpx.HTTPError: + continue + if probe.is_success: + self.jobs[job] = backend break - return await self.relay(request, self.jobs.get(job.group(1), backends[0]) if job else backends[0]) + return self.jobs.get(job, backends[0]) def application(gateway: Gateway) -> Starlette: diff --git a/tests/test_video_gateway.py b/tests/test_video_gateway.py index fb1982ed8..27eecff2d 100644 --- a/tests/test_video_gateway.py +++ b/tests/test_video_gateway.py @@ -6,6 +6,7 @@ import subprocess import sys import time +from urllib.parse import parse_qsl import httpx import pytest @@ -43,6 +44,11 @@ def test_rewrite_forces_set_fills_defaults_and_merges_extra_params(): assert any(change.startswith("num_inference_steps=4 (was 8)") for change in changes) +def test_structured_values_are_sent_as_json_text(): + new, _ = gateway.rewrite(entry(set={"enabled": True, "frame_indices": [0, 80], "options": {"tiled": False}}), {"model": "alias"}) + assert (new["enabled"], new["frame_indices"], new["options"]) == ("true", "[0, 80]", '{"tiled": false}') + + def test_lora_is_stripped_only_when_the_entry_says_null(): fields = {"model": "alias", "lora": '{"name": "client"}'} assert "lora" not in gateway.rewrite(entry(strip_lora=True), fields)[0] @@ -71,7 +77,13 @@ def test_multipart_round_trip_keeps_files_byte_for_byte(): ("default_backend: http://d\nmodels:\n a: {set: {}}", "'a' needs a `backend`"), ("default_backend: http://d\nmodels:\n a: {backend: http://b, stepz: 4}", "unknown keys: stepz"), ("default_backend: http://d\nmodels:\n a: {backend: http://b, lora: {name: n}}", "`lora` needs `name` and `path`"), -], ids=["not-a-mapping", "no-default-backend", "text-port", "no-backend", "unknown-key", "lora-without-path"]) + ("default_backend: http://d\nmodels:\n a: {backend: '127.0.0.1:8091'}", "'a' needs a `backend` URL that starts with http"), + ("default_backend: http://d\nmodels:\n a: {backend: http://b, 7: x}", "unknown keys: 7"), + ("default_backend: http://d\nmodels:\n a: {backend: http://b, lora: {name: n, path: p, scale: strong}}", "`lora.scale` must be a number"), + ("default_backend: http://d\nmodels:\n a: {backend: http://b, lora: {name: n, path: p, scale: }}", "`lora.scale` must be a number"), + ("default_backend: http://d\nmodels:\n a: {backend: http://b, set: {negative_prompt: }}", "`set.negative_prompt` has no value"), +], ids=["not-a-mapping", "no-default-backend", "text-port", "no-backend", "unknown-key", "lora-without-path", + "backend-without-scheme", "non-text-key", "text-scale", "empty-scale", "empty-set-value"]) def test_config_errors_name_the_problem(tmp_path, text, message): path = tmp_path / "video-gateway.yaml" path.write_text(text) @@ -103,9 +115,15 @@ def backend(request): # Real backends answer as streams, which is what the gateway relays. return httpx.Response(200, headers={"content-type": "application/json"}, stream=httpx.ByteStream(json.dumps(document).encode())) - app = gateway.Gateway(config) - app.client = httpx.AsyncClient(transport=httpx.MockTransport(backend)) - return TestClient(gateway.application(app)), seen, config + return TestClient(gateway.application(gateway.Gateway(config, httpx.MockTransport(backend)))), seen, config + + +def test_backends_are_reached_directly_whatever_proxy_the_environment_names(tmp_path, monkeypatch): + monkeypatch.setenv("HTTP_PROXY", "http://proxy.invalid:7890") + monkeypatch.setenv("ALL_PROXY", "http://proxy.invalid:7890") + config = tmp_path / "video-gateway.yaml" + config.write_text("default_backend: http://127.0.0.1:8091\n") + assert gateway.Gateway(config).client.trust_env is False def test_an_unlisted_model_reaches_the_default_backend_byte_for_byte(tmp_path): @@ -136,6 +154,82 @@ def test_a_listed_model_is_rewritten_and_sent_to_its_own_backend(tmp_path): assert seen[-1][:2] == ("special", "/v1/videos/job-special") +def test_repeated_and_typed_text_parts_survive_a_rewrite(tmp_path): + client, seen, _ = served(tmp_path) + boundary = b"edge" + typed = b'Content-Disposition: form-data; name="extra_params"\r\nContent-Type: application/json' + parts = [gateway.text_part("model", "listed"), gateway.text_part("tag", "one"), gateway.text_part("tag", "two"), + ("extra_params", None, typed, b'{"task": "ref2va"}'), gateway.text_part("num_inference_steps", "8"), + gateway.text_part("num_inference_steps", "8")] + client.post("/v1/videos", content=gateway.join_multipart(parts, boundary), headers={"content-type": "multipart/form-data; boundary=edge"}) + sent = gateway.split_multipart(seen[-1][3], boundary) + assert [(name, content) for name, _, _, content in sent if name == "tag"] == [("tag", b"one"), ("tag", b"two")] + assert [content for name, _, _, content in sent if name == "num_inference_steps"] == [b"4"] # a forced field is written once + assert next(head for name, _, head, _ in sent if name == "extra_params") == typed + + +def test_a_urlencoded_request_for_a_listed_model_is_rewritten(tmp_path): + client, seen, _ = served(tmp_path) + client.post("/v1/videos", content=b"model=listed&num_inference_steps=8&prompt=a+b%26c&tag=1&tag=2", + headers={"content-type": "application/x-www-form-urlencoded"}) + host, _, _, content = seen[-1] + sent = parse_qsl(content.decode()) + assert host == "special" and sent[:5] == [("model", "served"), ("num_inference_steps", "4"), ("prompt", "a b&c"), ("tag", "1"), ("tag", "2")] + assert json.loads(dict(sent)["lora"])["name"] == "n" + + +def test_a_body_the_gateway_cannot_read_goes_to_the_default_backend_untouched(tmp_path): + client, seen, _ = served(tmp_path) + body = b"\xff\xfe not a form" + client.post("/v1/videos", content=body, headers={"content-type": "application/octet-stream"}) + assert seen[-1][0] == "default" and seen[-1][3] == body + + +def restarted(tmp_path, default): + """A gateway that never saw `job-special` created; `default` answers for the default backend.""" + config = tmp_path / "video-gateway.yaml" + config.write_text("default_backend: http://default\nmodels:\n listed: {backend: http://special}\n") + seen = [] + + def backend(request): + seen.append((request.method, request.url.host, request.headers.get("authorization"))) + if request.url.host == "default": + return default(request) + if request.headers.get("authorization") != "Bearer key": + return httpx.Response(401, stream=httpx.ByteStream(b"{}")) + return httpx.Response(200, headers={"content-type": "application/json"}, stream=httpx.ByteStream(b'{"id": "job-special"}')) + + return TestClient(gateway.application(gateway.Gateway(config, httpx.MockTransport(backend)))), seen + + +def unreachable(request): + raise httpx.ConnectError("refused", request=request) + + +@pytest.mark.parametrize("default", [ + lambda request: httpx.Response(404, stream=httpx.ByteStream(b"{}")), + lambda request: httpx.Response(401, stream=httpx.ByteStream(b"{}")), + lambda request: httpx.Response(503, stream=httpx.ByteStream(b"{}")), + unreachable, +], ids=["unknown-there", "refused-there", "failing-there", "down"]) +@pytest.mark.parametrize("method", ["GET", "DELETE"]) +def test_after_a_restart_a_job_is_found_on_the_backend_that_answers_for_it(tmp_path, default, method): + client, seen = restarted(tmp_path, default) + response = client.request(method, "/v1/videos/job-special", headers={"authorization": "Bearer key"}) + assert response.status_code == 200 + # The lookup carries the caller's key, and the request itself lands on the owner. + assert seen[-1] == (method, "special", "Bearer key") and ("GET", "special", "Bearer key") in seen + seen.clear() + client.get("/v1/videos/job-special/content", headers={"authorization": "Bearer key"}) + assert seen == [("GET", "special", "Bearer key")] # remembered: no second lookup + + +def test_a_job_no_backend_knows_is_not_pinned_to_one(tmp_path): + client, seen = restarted(tmp_path, lambda request: httpx.Response(404, stream=httpx.ByteStream(b"{}"))) + assert client.get("/v1/videos/job-special").status_code == 404 # no key: the owner refuses the lookup + assert client.get("/v1/videos/job-special", headers={"authorization": "Bearer key"}).status_code == 200 + + def test_model_list_shows_listed_names_and_the_default_backends_own(tmp_path): client, _, _ = served(tmp_path) assert [item["id"] for item in client.get("/v1/models").json()["data"]] == ["listed", "native-model"] @@ -153,8 +247,9 @@ def rewrite(text): rewrite(good.replace("listed:", "renamed:")) assert [item["id"] for item in client.get("/v1/models").json()["data"]] == ["renamed", "native-model"] - rewrite("models: [broken") - assert [item["id"] for item in client.get("/v1/models").json()["data"]] == ["renamed", "native-model"] + for broken in ("models: [broken", good.replace("path: /server/adapter.safetensors", "path: p, scale: strong")): + rewrite(broken) + assert [item["id"] for item in client.get("/v1/models").json()["data"]] == ["renamed", "native-model"] # --- started with OpenDirector ----------------------------------------------------------------------------- @@ -215,6 +310,15 @@ def test_the_gateway_port_cannot_be_the_application_port(unspawned, capsys): assert "listen.port" in capsys.readouterr().err +def test_in_development_the_gateway_port_cannot_be_the_web_port(tmp_path): + web_port = free_port() + config = tmp_path / "gateway.yaml" + config.write_text(f"default_backend: http://d\nlisten: {{port: {web_port}}}\n") + with pytest.raises(RuntimeError, match="listen.port"): + launcher.video_gateway_listen(config, {free_port(), web_port}) + assert launcher.video_gateway_listen(config, {free_port()}) == ("127.0.0.1", web_port) + + def test_the_module_entry_point_serves_the_configured_models(tmp_path): """The command the launcher runs, as a real process: it listens where the file says and answers.""" port = free_port()