mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 16:02:12 +00:00
Merge branch 'main' into fix/build-grok45-capability-compat
This commit is contained in:
109 files changed
+10227
-925
No files matched your search
@@ -138,7 +138,7 @@ The Gateway routes requests through the Provider Registry. Account Sync refreshe
|
||||
| Routing | Model discovery, Provider pinning, sticky sessions, quota/concurrency guards, and bounded failover |
|
||||
| Sessions | Stored responses, compact, prompt-cache affinity, and optional reasoning replay |
|
||||
| Media | Image generation/editing, video jobs, local archiving, and URL/Base64/SSE output |
|
||||
| Egress | HTTP/SOCKS/Resin, subscriptions, probes, proxy pools, allocation, fallback, and FlareSolverr |
|
||||
| Egress | HTTP/SOCKS/Resin and Trojan/VLESS/Shadowsocks/VMess tunnels, subscriptions, probes, proxy pools, allocation, fallback, and FlareSolverr |
|
||||
| Operations | Dashboard, model routes, client keys, audits, runtime settings, and media libraries |
|
||||
|
||||
### Provider boundaries
|
||||
@@ -147,9 +147,9 @@ The Gateway routes requests through the Provider Registry. Account Sync refreshe
|
||||
| :-- | :-- | :-- | :-- |
|
||||
| Grok Build | OAuth / Device OAuth | Discovered per account | Responses, Chat, Messages, compact, stored responses, paid-account video |
|
||||
| Grok Web | SSO | Built-in, filtered by tier | Responses, Chat, Messages, stored responses, images, image editing, video |
|
||||
| Grok Console | SSO | Built-in | Stateless Responses, Chat, Messages, images, image editing, video |
|
||||
| Grok Console | SSO | Built-in | Stateless Responses, Chat, Messages, images, image editing, video, TTS, STT, Realtime |
|
||||
|
||||
Each Provider keeps its own credentials, quota, health, cooldown, concurrency, and model capabilities. Failover stays within the selected Provider.
|
||||
Each Provider keeps its own credentials, quota, health, cooldown, concurrency, and model capabilities. Account retries stay within one route; when one public model ID intentionally aggregates multiple routes, the gateway may select another schedulable route without mixing Provider state.
|
||||
|
||||
## Quick start
|
||||
|
||||
@@ -258,13 +258,13 @@ Web uses a built-in catalog filtered by account tier; higher tiers inherit lower
|
||||
| `grok-chat-expert` | Conversation | Super | Chat Completions, Responses, Messages |
|
||||
| `grok-chat-heavy` | Conversation | Heavy | Chat Completions, Responses, Messages |
|
||||
| `grok-imagine-image-lite` | Image | Basic | Images Generations |
|
||||
| `grok-imagine-image-quality-lite` | Image | Super | Images Generations |
|
||||
| `grok-imagine-image-quality-lite` | Image | Basic | Images Generations |
|
||||
| `grok-imagine-image-edit` | Image Edit | Super | Images Edits |
|
||||
| `grok-imagine-video` | Video | Super | Videos |
|
||||
|
||||
### Grok Console
|
||||
|
||||
Console uses the catalog built into the current release. Conversation forwarding is stateless, while image and video models use the standard xAI resource APIs.
|
||||
Console uses the catalog built into the current release. Conversation forwarding is stateless, while image, video, and voice use the standard xAI resource APIs.
|
||||
|
||||
| Model | Type | Gateway surfaces |
|
||||
| :-- | :-- | :-- |
|
||||
@@ -276,7 +276,11 @@ Console uses the catalog built into the current release. Conversation forwarding
|
||||
| `grok-build-0.1` | Conversation | Chat Completions, Responses, Messages |
|
||||
| `grok-imagine-image` | Image, Image Edit | Images Generations, Images Edits |
|
||||
| `grok-imagine-image-quality` | Image, Image Edit | Images Generations, Images Edits |
|
||||
| `grok-imagine-image-2.0` | Image, Image Edit | Images Generations, Images Edits |
|
||||
| `grok-imagine-video` | Video | Videos |
|
||||
| `grok-imagine-video-1.5` | Video | Video generation, including Free Console accounts |
|
||||
| `grok-voice-latest`, `grok-voice-think-fast-2.0`, `grok-voice-think-fast-1.0` | Voice | TTS and Realtime WebSocket proxy |
|
||||
| `grok-stt` | Voice | STT and OpenAI-compatible audio transcriptions |
|
||||
|
||||
Generation and editing capabilities for the same Console image model are grouped into one logical model row; no separate `-edit` model copy is required.
|
||||
|
||||
@@ -309,10 +313,15 @@ Authorization: Bearer g2a_xxx_xxx
|
||||
| `POST` | `/v1/messages` | Anthropic Messages JSON/SSE |
|
||||
| `POST` | `/v1/images/generations`, `/v1/images/edits` | Generate or edit images |
|
||||
| `POST`, `GET` | `/v1/videos/*` | Create and inspect video jobs |
|
||||
| `POST` | `/v1/tts`, `/v1/audio/speech`, `/v1/audio/tasks` | Synthesize speech |
|
||||
| `POST` | `/v1/stt`, `/v1/audio/transcriptions` | Transcribe audio |
|
||||
| `GET` | `/v1/stt`, `/v1/realtime` | Proxy voice WebSocket sessions |
|
||||
| `GET` | `/v1/media/images/{asset_id}`, `/v1/media/videos/{asset_id}` | Read archived media |
|
||||
|
||||
Stored responses and compact depend on the selected Provider. The signed-in admin console provides live examples at `/docs`; Swagger is available only when `server.swaggerEnabled: true`.
|
||||
|
||||
`/v1/audio/transcriptions` supports `json` (default), `verbose_json`, and `text`. Video edit/extension routes must resolve to Console `grok-imagine-video`; custom public model names remain supported. Monetary billing is applied only when the gateway can reliably measure the official pricing unit: TTS is reserved and settled from its input character count, while REST and streaming STT are settled from the actual audio duration returned by a successful response. Because STT duration is known only after completion, concurrent requests may briefly take a billing-limited key beyond its spend limit. Realtime, video edits/extensions, and custom routes without a recognized official price are currently audited as unpriced; they remain callable and do not consume the spend limit.
|
||||
|
||||
Client keys support model allowlists and optional RPM, concurrency, spend, and expiry limits.
|
||||
|
||||
```bash
|
||||
@@ -330,7 +339,8 @@ curl http://127.0.0.1:8000/v1/responses \
|
||||
|
||||
Egress nodes are scoped to Build, Web, Console, or Web assets. The admin console supports:
|
||||
|
||||
- HTTP, HTTPS, SOCKS4/4A, SOCKS5/5H, and Resin
|
||||
- HTTP, HTTPS, SOCKS4/4A, SOCKS5/5H, Resin, Trojan, VLESS, Shadowsocks, and VMess
|
||||
- TCP, WebSocket, and TLS tunnel transports; unsupported variants are rejected during import
|
||||
- Subscription and text/Base64 import
|
||||
- Batch probes, filtering, deletion, assignment, and balancing
|
||||
- Fallback per scope: none, direct, or a fixed node
|
||||
@@ -338,6 +348,8 @@ Egress nodes are scoped to Build, Web, Console, or Web assets. The admin console
|
||||
- Immediate recovery probes after fixed-proxy transport failures, with per-node coalescing and bounded waiting for fast retry
|
||||
- Optional [Egress Quality Guard](./tools/egress-quality-guard/README.md) for active per-node model probes, guarded quarantine, and recovery; enable it with the built-in `quality-guard` Compose profile
|
||||
|
||||
Hysteria and TUIC are not supported yet. FlareSolverr accepts only HTTP/SOCKS proxy URLs, so automatic clearance refresh cannot use a tunnel share URL directly.
|
||||
|
||||
To enable the guard, add a `qualityGuard` section to `config.yaml`, then start
|
||||
the profile. The main service creates and reuses a non-exportable system probe
|
||||
identity automatically:
|
||||
|
||||
+18
-6
@@ -139,7 +139,7 @@ flowchart LR
|
||||
| 路由 | 模型发现、Provider 限定、会话粘滞、额度/并发门禁和有界切换 |
|
||||
| 会话 | stored response、compact、Prompt Cache 亲和与可选 reasoning replay |
|
||||
| 媒体 | 图片生成与编辑、视频任务、本地归档及 URL/Base64/SSE 输出 |
|
||||
| 出口 | HTTP/SOCKS/Resin、订阅、探测、代理池、调配、回退与 FlareSolverr |
|
||||
| 出口 | HTTP/SOCKS/Resin 与 Trojan/VLESS/Shadowsocks/VMess 隧道、订阅、探测、代理池、调配、回退与 FlareSolverr |
|
||||
| 运维 | Dashboard、模型路由、客户端密钥、审计、运行设置和媒体库 |
|
||||
|
||||
### Provider 边界
|
||||
@@ -148,9 +148,9 @@ flowchart LR
|
||||
| :-- | :-- | :-- | :-- |
|
||||
| Grok Build | OAuth / 设备授权 | 按账号动态发现 | Responses、Chat、Messages、compact、stored response、付费账号视频 |
|
||||
| Grok Web | SSO | 内置并按等级过滤 | Responses、Chat、Messages、stored response、图片、图片编辑、视频 |
|
||||
| Grok Console | SSO | 内置 | 无状态 Responses、Chat、Messages、图片、图片编辑、视频 |
|
||||
| Grok Console | SSO | 内置 | 无状态 Responses、Chat、Messages、图片、图片编辑、视频、TTS、STT、Realtime |
|
||||
|
||||
三个 Provider 独立维护凭据、额度、健康、冷却、并发与模型能力。故障切换不会跨 Provider 混用账号状态。
|
||||
三个 Provider 独立维护凭据、额度、健康、冷却、并发与模型能力。单条路由的账号重试始终留在当前 Provider;当同一对外模型名主动聚合了多条路由时,网关可选择另一条可调度路由,但不会跨 Provider 混用账号状态。
|
||||
|
||||
## 快速部署
|
||||
|
||||
@@ -259,13 +259,13 @@ Web 使用内置目录并按账号等级过滤;更高等级继承低等级模
|
||||
| `grok-chat-expert` | 对话 | Super | Chat Completions、Responses、Messages |
|
||||
| `grok-chat-heavy` | 对话 | Heavy | Chat Completions、Responses、Messages |
|
||||
| `grok-imagine-image-lite` | 图像 | Basic | Images Generations |
|
||||
| `grok-imagine-image-quality-lite` | 图像 | Super | Images Generations |
|
||||
| `grok-imagine-image-quality-lite` | 图像 | Basic | Images Generations |
|
||||
| `grok-imagine-image-edit` | 图像编辑 | Super | Images Edits |
|
||||
| `grok-imagine-video` | 视频 | Super | Videos |
|
||||
|
||||
### Grok Console
|
||||
|
||||
Console 使用当前版本内置目录。对话为无状态转发;图片和视频使用 xAI 标准资源接口。
|
||||
Console 使用当前版本内置目录。对话为无状态转发;图片、视频和语音使用 xAI 标准资源接口。
|
||||
|
||||
| 模型 | 类型 | 网关接口能力 |
|
||||
| :-- | :-- | :-- |
|
||||
@@ -277,7 +277,11 @@ Console 使用当前版本内置目录。对话为无状态转发;图片和视
|
||||
| `grok-build-0.1` | 对话 | Chat Completions、Responses、Messages |
|
||||
| `grok-imagine-image` | 图像、图像编辑 | Images Generations、Images Edits |
|
||||
| `grok-imagine-image-quality` | 图像、图像编辑 | Images Generations、Images Edits |
|
||||
| `grok-imagine-image-2.0` | 图像、图像编辑 | Images Generations、Images Edits |
|
||||
| `grok-imagine-video` | 视频 | Videos |
|
||||
| `grok-imagine-video-1.5` | 视频 | 视频生成,包括 Free Console 账号 |
|
||||
| `grok-voice-latest`、`grok-voice-think-fast-2.0`、`grok-voice-think-fast-1.0` | 语音 | TTS 和 Realtime WebSocket 代理 |
|
||||
| `grok-stt` | 语音 | STT 和 OpenAI 兼容的音频转录 |
|
||||
|
||||
同一个 Console 图片模型的生成与编辑能力会聚合展示为一条逻辑模型,不需要创建 `-edit` 模型副本。
|
||||
|
||||
@@ -310,10 +314,15 @@ Authorization: Bearer g2a_xxx_xxx
|
||||
| `POST` | `/v1/messages` | Anthropic Messages JSON/SSE |
|
||||
| `POST` | `/v1/images/generations`、`/v1/images/edits` | 生成或编辑图片 |
|
||||
| `POST`、`GET` | `/v1/videos/*` | 创建和查询视频任务 |
|
||||
| `POST` | `/v1/tts`、`/v1/audio/speech`、`/v1/audio/tasks` | 语音合成 |
|
||||
| `POST` | `/v1/stt`、`/v1/audio/transcriptions` | 音频转录 |
|
||||
| `GET` | `/v1/stt`、`/v1/realtime` | 代理语音 WebSocket 会话 |
|
||||
| `GET` | `/v1/media/images/{asset_id}`、`/v1/media/videos/{asset_id}` | 读取归档媒体 |
|
||||
|
||||
stored response 和 compact 取决于最终 Provider。登录管理端后可在 `/docs` 查看当前模型与调用示例;仅在 `server.swaggerEnabled: true` 时提供 Swagger。
|
||||
|
||||
`/v1/audio/transcriptions` 支持 `json`(默认)、`verbose_json` 和 `text`。视频编辑与延长按实际路由校验 Console `grok-imagine-video`,对外模型名仍可自定义。金额计费以网关能够可靠测量的官方计价单位为准:TTS 按输入字符数预留并结算,REST 与流式 STT 按成功响应返回的实际音频时长结算。STT 时长只能在请求完成后获得,因此并发中的请求可能使有限额 Key 短暂超过金额上限。Realtime、视频编辑与延长,以及未收录官方定价的自定义路由当前记录为“未计费”,保持可调用且不消耗金额额度。
|
||||
|
||||
客户端密钥支持模型白名单,以及可选的 RPM、并发、用量和截止日期限制。
|
||||
|
||||
```bash
|
||||
@@ -331,7 +340,8 @@ curl http://127.0.0.1:8000/v1/responses \
|
||||
|
||||
出口节点按 Build、Web、Console 或 Web 资源隔离。管理端支持:
|
||||
|
||||
- HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H 与 Resin
|
||||
- HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H、Resin、Trojan、VLESS、Shadowsocks 与 VMess
|
||||
- 隧道协议支持 TCP、WebSocket 和 TLS,未实现的传输形态会在导入时拒绝
|
||||
- 订阅和文本/Base64 导入
|
||||
- 批量探测、筛选、删除、分配与均衡
|
||||
- 按作用域配置无回退、直连或固定节点
|
||||
@@ -339,6 +349,8 @@ curl http://127.0.0.1:8000/v1/responses \
|
||||
- 固定代理传输失败后立即复测;同节点复测自动合并,后续绑定请求限时等待并在恢复后快速重试
|
||||
- 可选的[出口质量守护程序](./tools/egress-quality-guard/README.zh-CN.md),支持逐节点模型探测、防误杀隔离和自动恢复;通过内置的 `quality-guard` Compose profile 按需启用
|
||||
|
||||
Hysteria 与 TUIC 暂未支持。FlareSolverr 仅接受 HTTP/SOCKS 代理地址,因此自动刷新 Clearance 暂不能直接使用隧道分享链接。
|
||||
|
||||
首次启用时只需在 `config.yaml` 中增加 `qualityGuard` 并启动 profile。主程序会自动创建并稳定复用不可导出的系统探测身份:
|
||||
|
||||
```yaml
|
||||
|
||||
@@ -497,6 +497,102 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/v1/videos/edits": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Videos"
|
||||
],
|
||||
"summary": "创建异步视频编辑任务",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "请求",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpserver.SwaggerVideoGenerationRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/v1/videos/extensions": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Videos"
|
||||
],
|
||||
"summary": "创建异步视频延长任务",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "请求",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpserver.SwaggerVideoGenerationRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/v1/videos/generations": {
|
||||
"post": {
|
||||
"security": [
|
||||
@@ -754,6 +850,15 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"httpserver.SwaggerVideoAudioInput": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"voice_id": {
|
||||
"type": "string",
|
||||
"example": "eve"
|
||||
}
|
||||
}
|
||||
},
|
||||
"httpserver.SwaggerVideoGenerationRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -765,6 +870,9 @@ const docTemplate = `{
|
||||
"type": "integer",
|
||||
"example": 8
|
||||
},
|
||||
"image": {
|
||||
"$ref": "#/definitions/httpserver.SwaggerVideoMediaInput"
|
||||
},
|
||||
"model": {
|
||||
"type": "string",
|
||||
"example": "grok-imagine-video"
|
||||
@@ -773,9 +881,37 @@ const docTemplate = `{
|
||||
"type": "string",
|
||||
"example": "A cinematic tracking shot in the rain"
|
||||
},
|
||||
"reference_audios": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/httpserver.SwaggerVideoAudioInput"
|
||||
}
|
||||
},
|
||||
"reference_images": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/httpserver.SwaggerVideoMediaInput"
|
||||
}
|
||||
},
|
||||
"resolution": {
|
||||
"type": "string",
|
||||
"example": "720p"
|
||||
},
|
||||
"video": {
|
||||
"$ref": "#/definitions/httpserver.SwaggerVideoMediaInput"
|
||||
}
|
||||
}
|
||||
},
|
||||
"httpserver.SwaggerVideoMediaInput": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"file_id": {
|
||||
"type": "string",
|
||||
"example": "file_123"
|
||||
},
|
||||
"url": {
|
||||
"type": "string",
|
||||
"example": "https://example.com/input.png"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -490,6 +490,102 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/v1/videos/edits": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Videos"
|
||||
],
|
||||
"summary": "创建异步视频编辑任务",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "请求",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpserver.SwaggerVideoGenerationRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/v1/videos/extensions": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Videos"
|
||||
],
|
||||
"summary": "创建异步视频延长任务",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "请求",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/httpserver.SwaggerVideoGenerationRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/v1/videos/generations": {
|
||||
"post": {
|
||||
"security": [
|
||||
@@ -747,6 +843,15 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"httpserver.SwaggerVideoAudioInput": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"voice_id": {
|
||||
"type": "string",
|
||||
"example": "eve"
|
||||
}
|
||||
}
|
||||
},
|
||||
"httpserver.SwaggerVideoGenerationRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -758,6 +863,9 @@
|
||||
"type": "integer",
|
||||
"example": 8
|
||||
},
|
||||
"image": {
|
||||
"$ref": "#/definitions/httpserver.SwaggerVideoMediaInput"
|
||||
},
|
||||
"model": {
|
||||
"type": "string",
|
||||
"example": "grok-imagine-video"
|
||||
@@ -766,9 +874,37 @@
|
||||
"type": "string",
|
||||
"example": "A cinematic tracking shot in the rain"
|
||||
},
|
||||
"reference_audios": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/httpserver.SwaggerVideoAudioInput"
|
||||
}
|
||||
},
|
||||
"reference_images": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/httpserver.SwaggerVideoMediaInput"
|
||||
}
|
||||
},
|
||||
"resolution": {
|
||||
"type": "string",
|
||||
"example": "720p"
|
||||
},
|
||||
"video": {
|
||||
"$ref": "#/definitions/httpserver.SwaggerVideoMediaInput"
|
||||
}
|
||||
}
|
||||
},
|
||||
"httpserver.SwaggerVideoMediaInput": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"file_id": {
|
||||
"type": "string",
|
||||
"example": "file_123"
|
||||
},
|
||||
"url": {
|
||||
"type": "string",
|
||||
"example": "https://example.com/input.png"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,6 +118,12 @@ definitions:
|
||||
example: false
|
||||
type: boolean
|
||||
type: object
|
||||
httpserver.SwaggerVideoAudioInput:
|
||||
properties:
|
||||
voice_id:
|
||||
example: eve
|
||||
type: string
|
||||
type: object
|
||||
httpserver.SwaggerVideoGenerationRequest:
|
||||
properties:
|
||||
aspect_ratio:
|
||||
@@ -126,15 +132,36 @@ definitions:
|
||||
duration:
|
||||
example: 8
|
||||
type: integer
|
||||
image:
|
||||
$ref: '#/definitions/httpserver.SwaggerVideoMediaInput'
|
||||
model:
|
||||
example: grok-imagine-video
|
||||
type: string
|
||||
prompt:
|
||||
example: A cinematic tracking shot in the rain
|
||||
type: string
|
||||
reference_audios:
|
||||
items:
|
||||
$ref: '#/definitions/httpserver.SwaggerVideoAudioInput'
|
||||
type: array
|
||||
reference_images:
|
||||
items:
|
||||
$ref: '#/definitions/httpserver.SwaggerVideoMediaInput'
|
||||
type: array
|
||||
resolution:
|
||||
example: 720p
|
||||
type: string
|
||||
video:
|
||||
$ref: '#/definitions/httpserver.SwaggerVideoMediaInput'
|
||||
type: object
|
||||
httpserver.SwaggerVideoMediaInput:
|
||||
properties:
|
||||
file_id:
|
||||
example: file_123
|
||||
type: string
|
||||
url:
|
||||
example: https://example.com/input.png
|
||||
type: string
|
||||
type: object
|
||||
info:
|
||||
contact: {}
|
||||
@@ -475,6 +502,66 @@ paths:
|
||||
summary: 查询异步视频任务
|
||||
tags:
|
||||
- Videos
|
||||
/v1/videos/edits:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- description: 请求
|
||||
in: body
|
||||
name: request
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/httpserver.SwaggerVideoGenerationRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties:
|
||||
type: string
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: 创建异步视频编辑任务
|
||||
tags:
|
||||
- Videos
|
||||
/v1/videos/extensions:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- description: 请求
|
||||
in: body
|
||||
name: request
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/httpserver.SwaggerVideoGenerationRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties:
|
||||
type: string
|
||||
type: object
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: 创建异步视频延长任务
|
||||
tags:
|
||||
- Videos
|
||||
/v1/videos/generations:
|
||||
post:
|
||||
consumes:
|
||||
|
||||
@@ -3,15 +3,19 @@ module github.com/chenyme/grok2api/backend
|
||||
go 1.26
|
||||
|
||||
require (
|
||||
github.com/Asutorufa/yuhaiin v0.3.8
|
||||
github.com/bdandy/go-socks4 v1.2.3
|
||||
github.com/bogdanfinn/fhttp v0.6.8
|
||||
github.com/bogdanfinn/tls-client v1.15.1
|
||||
github.com/bogdanfinn/websocket v1.5.5-barnius
|
||||
github.com/coder/websocket v1.8.14
|
||||
github.com/gin-gonic/gin v1.12.0
|
||||
github.com/glebarez/sqlite v1.11.0
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/redis/go-redis/v9 v9.21.0
|
||||
github.com/shadowsocks/go-shadowsocks2 v0.1.5
|
||||
github.com/swaggo/files v1.0.1
|
||||
github.com/swaggo/gin-swagger v1.6.1
|
||||
github.com/swaggo/swag v1.16.6
|
||||
@@ -30,6 +34,7 @@ require (
|
||||
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
|
||||
github.com/andybalholm/brotli v1.2.0 // indirect
|
||||
github.com/bdandy/go-errors v1.2.2 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/bogdanfinn/quic-go-utls v1.0.9-utls // indirect
|
||||
github.com/bogdanfinn/utls v1.7.7-barnius // indirect
|
||||
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||
@@ -65,21 +70,30 @@ require (
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/prometheus/client_golang v1.20.5 // indirect
|
||||
github.com/prometheus/client_model v0.6.1 // indirect
|
||||
github.com/prometheus/common v0.55.0 // indirect
|
||||
github.com/prometheus/procfs v0.15.1 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/quic-go/quic-go v0.59.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 // indirect
|
||||
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.1 // indirect
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
golang.org/x/arch v0.22.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20241204233417-43b7b7cde48d // indirect
|
||||
golang.org/x/mod v0.37.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
golang.org/x/time v0.9.0 // indirect
|
||||
golang.org/x/tools v0.47.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gvisor.dev/gvisor v0.0.0-20241220022509-4690b2e35d70 // indirect
|
||||
modernc.org/libc v1.22.5 // indirect
|
||||
modernc.org/mathutil v1.5.0 // indirect
|
||||
modernc.org/memory v1.5.0 // indirect
|
||||
|
||||
+34
-2
@@ -1,3 +1,5 @@
|
||||
github.com/Asutorufa/yuhaiin v0.3.8 h1:HrEqvXNVYUviL2+Zu01AxRJiPayZa7lZvoYQlvgMkgc=
|
||||
github.com/Asutorufa/yuhaiin v0.3.8/go.mod h1:fLEwJOwgPumPQvGgJNJn392c63GyAaP4QCkZTj6LRyo=
|
||||
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
|
||||
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
|
||||
github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=
|
||||
@@ -10,6 +12,8 @@ github.com/bdandy/go-errors v1.2.2 h1:WdFv/oukjTJCLa79UfkGmwX7ZxONAihKu4V0mLIs11
|
||||
github.com/bdandy/go-errors v1.2.2/go.mod h1:NkYHl4Fey9oRRdbB1CoC6e84tuqQHiqrOcZpqFEkBxM=
|
||||
github.com/bdandy/go-socks4 v1.2.3 h1:Q6Y2heY1GRjCtHbmlKfnwrKVU/k81LS8mRGLRlmDlic=
|
||||
github.com/bdandy/go-socks4 v1.2.3/go.mod h1:98kiVFgpdogR8aIGLWLvjDVZ8XcKPsSI/ypGrO+bqHI=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/bogdanfinn/fhttp v0.6.8 h1:LiQyHOY3i0QoxxNB7nq27/nGNNbtPj0fuBPozhR7Ws4=
|
||||
github.com/bogdanfinn/fhttp v0.6.8/go.mod h1:A+EKDzMx2hb4IUbMx4TlkoHnaJEiLl8r/1Ss1Y+5e5M=
|
||||
github.com/bogdanfinn/quic-go-utls v1.0.9-utls h1:tV6eDEiRbRCcepALSzxR94JUVD3N3ACIiRLgyc2Ep8s=
|
||||
@@ -34,6 +38,8 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=
|
||||
github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
@@ -79,10 +85,12 @@ github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArs
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
|
||||
github.com/google/pprof v0.0.0-20240910150728-a0b0bb1d4134 h1:c5FlPPgxOn7kJz3VoPLkQYQXGBS3EklQ4Zfi57uOuqQ=
|
||||
github.com/google/pprof v0.0.0-20240910150728-a0b0bb1d4134/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
@@ -125,11 +133,21 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y=
|
||||
github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE=
|
||||
github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
|
||||
github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
|
||||
github.com/prometheus/common v0.55.0 h1:KEi6DK7lXW/m7Ig5i47x0vRzuBsHuvJdi5ee6Y3G1dc=
|
||||
github.com/prometheus/common v0.55.0/go.mod h1:2SECS4xJG1kd8XF9IcM1gMX6510RAEL65zxzNImwdc8=
|
||||
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
|
||||
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
|
||||
@@ -139,8 +157,12 @@ github.com/redis/go-redis/v9 v9.21.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3b
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 h1:f/FNXud6gA3MNr8meMVVGxhp+QBTqY91tM8HjEuMjGg=
|
||||
github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3/go.mod h1:HgjTstvQsPGkxUsCd2KWxErBblirPizecHcpD3ffK+s=
|
||||
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||
github.com/shadowsocks/go-shadowsocks2 v0.1.5 h1:PDSQv9y2S85Fl7VBeOMF9StzeXZyK1HakRm86CUbr28=
|
||||
github.com/shadowsocks/go-shadowsocks2 v0.1.5/go.mod h1:AGGpIoek4HRno4xzyFiAtLHkOpcoznZEkAccaI/rplM=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
@@ -180,12 +202,16 @@ go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
|
||||
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
|
||||
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/exp v0.0.0-20241204233417-43b7b7cde48d h1:0olWaB5pg3+oychR51GUVCEsGkeCU/2JxjBgIo4f3M0=
|
||||
golang.org/x/exp v0.0.0-20241204233417-43b7b7cde48d/go.mod h1:qj5a5QZpwLU2NLQudwIN5koi3beDhSAlJwa67PuM98c=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
|
||||
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM=
|
||||
@@ -199,6 +225,7 @@ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJ
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -209,6 +236,7 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
@@ -219,6 +247,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY=
|
||||
golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
@@ -245,6 +275,8 @@ gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
|
||||
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
|
||||
gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
|
||||
gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||
gvisor.dev/gvisor v0.0.0-20241220022509-4690b2e35d70 h1:YAGAbMnGNRna7ajnsDuRjV1o/Mc2LDwEliRemNFDVF4=
|
||||
gvisor.dev/gvisor v0.0.0-20241220022509-4690b2e35d70/go.mod h1:5DMfjtclAbTIjbXqO1qCe2K5GKKxWz2JHvCChuTcJEM=
|
||||
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
|
||||
modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=
|
||||
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
|
||||
|
||||
@@ -32,12 +32,23 @@ func TestConsoleRoutesUseStableProviderNamespace(t *testing.T) {
|
||||
if seen["Console/grok-4.3"] == nil {
|
||||
t.Fatal("canonical Console/grok-4.3 route is missing")
|
||||
}
|
||||
for _, modelID := range []string{"Console/grok-imagine-image-quality", "Console/grok-imagine-image"} {
|
||||
for _, modelID := range []string{"Console/grok-imagine-image", "Console/grok-imagine-image-quality", "Console/grok-imagine-image-2.0"} {
|
||||
if !seen[modelID]["image"] || !seen[modelID]["image_edit"] {
|
||||
t.Fatalf("Console image route capabilities for %s = %#v", modelID, seen[modelID])
|
||||
}
|
||||
}
|
||||
for _, modelID := range []string{"Console/grok-voice-latest", "Console/grok-voice-think-fast-2.0", "Console/grok-voice-think-fast-1.0"} {
|
||||
if !seen[modelID]["realtime"] || !seen[modelID]["tts"] {
|
||||
t.Fatalf("Console voice route capabilities for %s = %#v", modelID, seen[modelID])
|
||||
}
|
||||
}
|
||||
if !seen["Console/grok-stt"]["stt"] {
|
||||
t.Fatal("Console STT route is missing")
|
||||
}
|
||||
if !seen["Console/grok-imagine-video"]["video"] {
|
||||
t.Fatal("Console video route is missing")
|
||||
}
|
||||
if !seen["Console/grok-imagine-video-1.5"]["video"] {
|
||||
t.Fatal("Console video 1.5 route is missing")
|
||||
}
|
||||
}
|
||||
@@ -24,10 +24,12 @@ func TestWebQuotaRefreshDeduplicatesPerMode(t *testing.T) {
|
||||
service.QueueQuotaRefresh(43, "console")
|
||||
service.QueueQuotaRefresh(43, "console_image")
|
||||
service.QueueQuotaRefresh(43, "console_video")
|
||||
service.QueueQuotaRefresh(44, accountdomain.QuotaModeWebImagePro)
|
||||
service.QueueQuotaRefresh(44, accountdomain.QuotaModeWebVideo720p)
|
||||
|
||||
service.quotaRefreshMu.Lock()
|
||||
defer service.quotaRefreshMu.Unlock()
|
||||
if len(service.quotaRefreshes) != 5 {
|
||||
if len(service.quotaRefreshes) != 6 {
|
||||
t.Fatalf("refresh states = %#v", service.quotaRefreshes)
|
||||
}
|
||||
if service.quotaRefreshes["42:fast"].generation != 2 || !service.quotaRefreshes["42:fast"].queued {
|
||||
@@ -44,7 +46,10 @@ func TestWebQuotaRefreshDeduplicatesPerMode(t *testing.T) {
|
||||
t.Fatalf("Console %s refresh state is invalid: %#v", mode, state)
|
||||
}
|
||||
}
|
||||
if len(service.quotaRefreshQueue) != 5 {
|
||||
if state := service.quotaRefreshes["44:"+accountdomain.QuotaGroupWebImagine]; state == nil || state.generation != 2 || !state.queued {
|
||||
t.Fatalf("Imagine group refresh state is invalid: %#v", state)
|
||||
}
|
||||
if len(service.quotaRefreshQueue) != 6 {
|
||||
t.Fatalf("queued refreshes = %d", len(service.quotaRefreshQueue))
|
||||
}
|
||||
}
|
||||
@@ -354,6 +359,58 @@ func TestRefreshQuotaModeDoesNotTriggerFullProviderSyncForAutoTier(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshWebImagineQuotaModeAtomicallyReplacesGroup(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "imagine-quota-group.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.Close() })
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accounts := relational.NewAccountRepository(database)
|
||||
credential, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
Provider: accountdomain.ProviderWeb, AuthType: accountdomain.AuthTypeSSO,
|
||||
Name: "web-imagine", SourceKey: "web-imagine", EncryptedAccessToken: "encrypted",
|
||||
Enabled: true, AuthStatus: accountdomain.AuthStatusActive,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
if err := accounts.SaveQuotaWindows(ctx, credential.ID, accountdomain.WebTierSuper, now, []accountdomain.QuotaWindow{
|
||||
{AccountID: credential.ID, Mode: "weekly", Remaining: 90, Total: 100, UpdatedAt: now},
|
||||
{AccountID: credential.ID, Mode: accountdomain.QuotaModeWebImagePro, Remaining: 4, UpdatedAt: now},
|
||||
{AccountID: credential.ID, Mode: accountdomain.QuotaModeWebVideo720p, Remaining: 1, UpdatedAt: now},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
adapter := &imagineQuotaGroupAdapter{}
|
||||
service := NewService(accounts, nil, nil, nil, provider.NewRegistry(adapter), nil, nil)
|
||||
window, err := service.RefreshQuotaMode(ctx, credential.ID, accountdomain.QuotaModeWebImagePro)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if window.Remaining != 3 || adapter.calls.Load() != 1 {
|
||||
t.Fatalf("window = %#v, calls = %d", window, adapter.calls.Load())
|
||||
}
|
||||
stored, err := accounts.GetQuotaWindows(ctx, []uint64{credential.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
byMode := make(map[string]accountdomain.QuotaWindow)
|
||||
for _, current := range stored[credential.ID] {
|
||||
byMode[current.Mode] = current
|
||||
}
|
||||
if byMode["weekly"].Remaining != 90 || byMode[accountdomain.QuotaModeWebImagePro].Remaining != 3 {
|
||||
t.Fatalf("stored = %#v", stored[credential.ID])
|
||||
}
|
||||
if _, exists := byMode[accountdomain.QuotaModeWebVideo720p]; exists {
|
||||
t.Fatalf("stale video_720p window survived group replacement: %#v", stored[credential.ID])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshConsoleQuotaModePersistsCompleteUsageSnapshot(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "console-quota-mode.db"))
|
||||
@@ -839,6 +896,36 @@ type quotaCountingAdapter struct {
|
||||
modeRelease chan struct{}
|
||||
}
|
||||
|
||||
type imagineQuotaGroupAdapter struct {
|
||||
calls atomic.Int64
|
||||
}
|
||||
|
||||
func (a *imagineQuotaGroupAdapter) Provider() accountdomain.Provider {
|
||||
return accountdomain.ProviderWeb
|
||||
}
|
||||
|
||||
func (a *imagineQuotaGroupAdapter) Definition() provider.Definition {
|
||||
return provider.Definition{
|
||||
Provider: accountdomain.ProviderWeb, ModelNamespace: accountdomain.ProviderWeb.ModelNamespace(),
|
||||
Quota: provider.QuotaRemoteWindow, Credential: provider.CredentialSurface{AuthType: accountdomain.AuthTypeSSO},
|
||||
}
|
||||
}
|
||||
|
||||
func (a *imagineQuotaGroupAdapter) SyncQuotaGroup(_ context.Context, credential accountdomain.Credential, group string) (provider.QuotaGroupSnapshot, error) {
|
||||
a.calls.Add(1)
|
||||
if group != accountdomain.QuotaGroupWebImagine {
|
||||
return provider.QuotaGroupSnapshot{}, errors.New("unexpected group")
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
return provider.QuotaGroupSnapshot{
|
||||
Group: group, Modes: accountdomain.WebImagineQuotaModes(), SyncedAt: now,
|
||||
Windows: []accountdomain.QuotaWindow{{
|
||||
AccountID: credential.ID, Mode: accountdomain.QuotaModeWebImagePro, Remaining: 3,
|
||||
WindowSeconds: 86400, SyncedAt: &now, Source: accountdomain.QuotaSourceUpstream, UpdatedAt: now,
|
||||
}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
type consoleQuotaSnapshotAdapter struct {
|
||||
fullCalls atomic.Int64
|
||||
modeCalls atomic.Int64
|
||||
|
||||
@@ -134,6 +134,7 @@ type quotaRefreshRequest struct {
|
||||
type quotaRefreshResult struct {
|
||||
Credential accountdomain.Credential
|
||||
Windows []accountdomain.QuotaWindow
|
||||
Modes []string
|
||||
}
|
||||
|
||||
type QuotaRefreshStats struct {
|
||||
@@ -2833,6 +2834,9 @@ func (s *Service) RefreshQuotaMode(ctx context.Context, id uint64, mode string)
|
||||
mode = strings.TrimSpace(mode)
|
||||
key := quotaSyncKey(id, mode)
|
||||
result, err, _ := s.quotaSyncs.Do(key, func() (any, error) {
|
||||
if isWebImagineQuotaMode(mode) {
|
||||
return s.refreshQuotaGroup(ctx, id, accountdomain.QuotaGroupWebImagine)
|
||||
}
|
||||
return s.refreshQuotaMode(ctx, id, mode)
|
||||
})
|
||||
if err != nil {
|
||||
@@ -2842,19 +2846,26 @@ func (s *Service) RefreshQuotaMode(ctx context.Context, id uint64, mode string)
|
||||
if !ok {
|
||||
return accountdomain.QuotaWindow{}, fmt.Errorf("Provider 模式额度同步返回类型无效")
|
||||
}
|
||||
if len(refreshed.Modes) > 0 {
|
||||
if err := s.reconcileQuotaGroupWindows(ctx, refreshed.Credential.Provider, id, refreshed.Modes, refreshed.Windows); err != nil {
|
||||
return accountdomain.QuotaWindow{}, err
|
||||
}
|
||||
}
|
||||
window, ok := quotaWindowByMode(refreshed.Windows, mode)
|
||||
if !ok {
|
||||
return accountdomain.QuotaWindow{}, fmt.Errorf("Provider usage 响应缺少 %s 额度", mode)
|
||||
}
|
||||
if refreshed.Credential.Provider == accountdomain.ProviderConsole {
|
||||
if len(refreshed.Modes) == 0 && refreshed.Credential.Provider == accountdomain.ProviderConsole {
|
||||
// One Console request refreshes all three authoritative windows. Reconcile
|
||||
// every matching recovery event so externally consumed media quota cannot
|
||||
// remain unscheduled merely because a different kind triggered the refresh.
|
||||
if err := s.reconcileQuotaRecoveryWindows(ctx, refreshed.Credential.Provider, id, refreshed.Windows); err != nil {
|
||||
return window, err
|
||||
}
|
||||
} else if err := s.reconcileQuotaRecoveryWindow(ctx, refreshed.Credential.Provider, id, window); err != nil {
|
||||
return window, err
|
||||
} else if len(refreshed.Modes) == 0 {
|
||||
if err := s.reconcileQuotaRecoveryWindow(ctx, refreshed.Credential.Provider, id, window); err != nil {
|
||||
return window, err
|
||||
}
|
||||
}
|
||||
return window, nil
|
||||
}
|
||||
@@ -2866,6 +2877,9 @@ func (s *Service) ProbeQuotaMode(ctx context.Context, id uint64, mode string) (a
|
||||
mode = strings.TrimSpace(mode)
|
||||
key := quotaSyncKey(id, mode)
|
||||
result, err, _ := s.quotaSyncs.Do(key, func() (any, error) {
|
||||
if isWebImagineQuotaMode(mode) {
|
||||
return s.refreshQuotaGroup(ctx, id, accountdomain.QuotaGroupWebImagine)
|
||||
}
|
||||
return s.refreshQuotaMode(ctx, id, mode)
|
||||
})
|
||||
if err != nil {
|
||||
@@ -2882,6 +2896,34 @@ func (s *Service) ProbeQuotaMode(ctx context.Context, id uint64, mode string) (a
|
||||
return window, nil
|
||||
}
|
||||
|
||||
func (s *Service) refreshQuotaGroup(ctx context.Context, id uint64, group string) (quotaRefreshResult, error) {
|
||||
value, err := s.accounts.Get(ctx, id)
|
||||
if err != nil {
|
||||
return quotaRefreshResult{}, mapRepositoryError(err)
|
||||
}
|
||||
adapter, ok := s.providers.QuotaGroup(value.Provider)
|
||||
if !ok {
|
||||
return quotaRefreshResult{}, fmt.Errorf("%s quota group Provider 未注册", value.Provider)
|
||||
}
|
||||
snapshot, err := adapter.SyncQuotaGroup(ctx, value, group)
|
||||
if err != nil {
|
||||
if errors.Is(err, provider.ErrUnauthorized) {
|
||||
err = errors.Join(err, s.markSSOCredentialRejected(ctx, value, fmt.Sprintf("%s SSO credential rejected", value.Provider)))
|
||||
}
|
||||
return quotaRefreshResult{}, err
|
||||
}
|
||||
if snapshot.Group != group || len(snapshot.Modes) == 0 {
|
||||
return quotaRefreshResult{}, fmt.Errorf("Provider quota group %s 返回无效快照", group)
|
||||
}
|
||||
if snapshot.SyncedAt.IsZero() {
|
||||
snapshot.SyncedAt = s.now()
|
||||
}
|
||||
if err := s.accounts.ReplaceQuotaWindowGroup(ctx, id, snapshot.SyncedAt, snapshot.Modes, snapshot.Windows); err != nil {
|
||||
return quotaRefreshResult{}, err
|
||||
}
|
||||
return quotaRefreshResult{Credential: value, Windows: snapshot.Windows, Modes: snapshot.Modes}, nil
|
||||
}
|
||||
|
||||
func (s *Service) refreshQuotaMode(ctx context.Context, id uint64, mode string) (quotaRefreshResult, error) {
|
||||
value, err := s.accounts.Get(ctx, id)
|
||||
if err != nil {
|
||||
@@ -2949,6 +2991,9 @@ func quotaSyncKey(accountID uint64, mode string) string {
|
||||
if isConsoleUsageQuotaMode(mode) {
|
||||
return "all:" + strconv.FormatUint(accountID, 10)
|
||||
}
|
||||
if isWebImagineQuotaMode(mode) || mode == accountdomain.QuotaGroupWebImagine {
|
||||
return accountdomain.QuotaGroupWebImagine + ":" + strconv.FormatUint(accountID, 10)
|
||||
}
|
||||
return mode + ":" + strconv.FormatUint(accountID, 10)
|
||||
}
|
||||
|
||||
@@ -2970,6 +3015,27 @@ func (s *Service) reconcileQuotaRecoveryWindows(ctx context.Context, providerVal
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) reconcileQuotaGroupWindows(ctx context.Context, providerValue accountdomain.Provider, accountID uint64, modes []string, windows []accountdomain.QuotaWindow) error {
|
||||
byMode := make(map[string]accountdomain.QuotaWindow, len(windows))
|
||||
for _, window := range windows {
|
||||
byMode[window.Mode] = window
|
||||
}
|
||||
for _, mode := range modes {
|
||||
if window, ok := byMode[mode]; ok {
|
||||
if err := s.reconcileQuotaRecoveryWindow(ctx, providerValue, accountID, window); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if s.quotaQueue != nil {
|
||||
if err := s.quotaQueue.CancelQuotaRecovery(ctx, accountID, mode); err != nil {
|
||||
return fmt.Errorf("取消额度恢复事件: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) reconcileQuotaRecoveryWindow(ctx context.Context, providerValue accountdomain.Provider, accountID uint64, window accountdomain.QuotaWindow) error {
|
||||
if s.quotaQueue == nil || !quotaWindowControlsRouting(providerValue, window.Mode) {
|
||||
return nil
|
||||
@@ -3012,7 +3078,10 @@ func quotaRecoveryDueAt(window accountdomain.QuotaWindow, now time.Time, exhaust
|
||||
// QueueQuotaRefresh asynchronously refreshes the remote quota window after a successful request.
|
||||
func (s *Service) QueueQuotaRefresh(id uint64, mode string) {
|
||||
mode = strings.TrimSpace(mode)
|
||||
if id == 0 || (!isConsoleUsageQuotaMode(mode) && mode != "weekly" && !isWebChatQuotaMode(mode)) {
|
||||
if isWebImagineQuotaMode(mode) {
|
||||
mode = accountdomain.QuotaGroupWebImagine
|
||||
}
|
||||
if id == 0 || (!isConsoleUsageQuotaMode(mode) && mode != "weekly" && mode != accountdomain.QuotaGroupWebImagine && !isWebChatQuotaMode(mode)) {
|
||||
return
|
||||
}
|
||||
key := strconv.FormatUint(id, 10) + ":" + mode
|
||||
@@ -3181,9 +3250,10 @@ func (s *Service) runQuotaRefresh(parent context.Context, request quotaRefreshRe
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
} else if request.mode != accountdomain.QuotaGroupWebImagine {
|
||||
// Weekly remains a Grok Web capability. Console never inherits this
|
||||
// legacy mode and always refreshes its authoritative /usage snapshot.
|
||||
// Imagine 配额组走 /rest/media/imagine/quota_info,不可被改刷 weekly。
|
||||
for _, window := range windows[request.accountID] {
|
||||
if window.Mode == "weekly" {
|
||||
refreshMode = "weekly"
|
||||
@@ -3206,7 +3276,15 @@ func (s *Service) runQuotaRefresh(parent context.Context, request quotaRefreshRe
|
||||
}
|
||||
if !skipUpstream && refreshErr == nil && acquired {
|
||||
if err := s.syncPool.Do(ctx, func(workCtx context.Context) error {
|
||||
_, refreshErr = s.RefreshQuotaMode(workCtx, request.accountID, refreshMode)
|
||||
if refreshMode == accountdomain.QuotaGroupWebImagine {
|
||||
var refreshed quotaRefreshResult
|
||||
refreshed, refreshErr = s.refreshQuotaGroup(workCtx, request.accountID, refreshMode)
|
||||
if refreshErr == nil {
|
||||
refreshErr = s.reconcileQuotaGroupWindows(workCtx, refreshed.Credential.Provider, request.accountID, refreshed.Modes, refreshed.Windows)
|
||||
}
|
||||
} else {
|
||||
_, refreshErr = s.RefreshQuotaMode(workCtx, request.accountID, refreshMode)
|
||||
}
|
||||
return refreshErr
|
||||
}); err != nil {
|
||||
refreshErr = err
|
||||
@@ -3460,6 +3538,10 @@ func isConsoleUsageQuotaMode(mode string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
func isWebImagineQuotaMode(mode string) bool {
|
||||
return accountdomain.IsWebImagineQuotaMode(mode)
|
||||
}
|
||||
|
||||
func quotaWindowControlsRouting(providerValue accountdomain.Provider, mode string) bool {
|
||||
return providerValue != accountdomain.ProviderConsole || isConsoleUsageQuotaMode(mode)
|
||||
}
|
||||
|
||||
@@ -304,7 +304,7 @@ func (s *Service) RunMaintenance(ctx context.Context) error {
|
||||
resultErr = errors.Join(resultErr, err)
|
||||
} else {
|
||||
for _, source := range sources {
|
||||
if _, syncErr := s.syncSourceWithConfig(ctx, operations, source, config); syncErr != nil {
|
||||
if _, syncErr := s.syncSource(ctx, operations, source); syncErr != nil {
|
||||
resultErr = errors.Join(resultErr, syncErr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +58,8 @@ type SubscriptionSourceInput struct {
|
||||
Enabled bool
|
||||
URL *string
|
||||
ClearURL bool
|
||||
ProxyURL *string
|
||||
ClearProxyURL bool
|
||||
RefreshIntervalSeconds *int
|
||||
DefaultAccountCapacity *int
|
||||
}
|
||||
@@ -90,12 +92,7 @@ type OperationsConfigInput struct {
|
||||
AutoAssignEnabled bool
|
||||
AutoBalanceEnabled bool
|
||||
AssignmentIntervalSeconds int
|
||||
// SubscriptionProxyURL updates the optional proxy used when fetching remote
|
||||
// subscription sources and must be non-empty when supplied. The explicit
|
||||
// ClearSubscriptionProxy flag clears it; nil leaves the secret unchanged.
|
||||
SubscriptionProxyURL *string
|
||||
ClearSubscriptionProxy bool
|
||||
Fallbacks map[domain.Scope]FallbackConfigInput
|
||||
Fallbacks map[domain.Scope]FallbackConfigInput
|
||||
}
|
||||
|
||||
type FallbackConfigInput struct {
|
||||
@@ -413,31 +410,10 @@ func (s *Service) UpdateOperationsConfig(ctx context.Context, input OperationsCo
|
||||
return domain.OperationsConfig{}, err
|
||||
}
|
||||
}
|
||||
subscriptionProxyURL := current.EncryptedSubscriptionProxyURL
|
||||
if input.ClearSubscriptionProxy {
|
||||
subscriptionProxyURL = ""
|
||||
} else if input.SubscriptionProxyURL != nil {
|
||||
normalized, normalizeErr := NormalizeProxyURL(*input.SubscriptionProxyURL)
|
||||
if normalizeErr != nil {
|
||||
return domain.OperationsConfig{}, fmt.Errorf("%w: 订阅拉取代理地址无效: %v", ErrInvalidInput, normalizeErr)
|
||||
}
|
||||
if normalized == "" {
|
||||
return domain.OperationsConfig{}, fmt.Errorf("%w: 订阅拉取代理地址不能为空;如需清除请显式指定 clearSubscriptionProxy", ErrInvalidInput)
|
||||
}
|
||||
if strings.Contains(normalized, ProxyAccountPlaceholder) {
|
||||
return domain.OperationsConfig{}, fmt.Errorf("%w: 订阅拉取代理不能使用账号占位符", ErrInvalidInput)
|
||||
}
|
||||
encrypted, encryptErr := s.cipher.Encrypt(normalized)
|
||||
if encryptErr != nil {
|
||||
return domain.OperationsConfig{}, encryptErr
|
||||
}
|
||||
subscriptionProxyURL = encrypted
|
||||
}
|
||||
saved, err := operations.SaveEgressOperationsConfig(ctx, domain.OperationsConfig{
|
||||
ProbeProvider: probeProvider, ProbeIntervalSeconds: input.ProbeIntervalSeconds, AutoAssignEnabled: input.AutoAssignEnabled,
|
||||
AutoBalanceEnabled: input.AutoBalanceEnabled, AssignmentIntervalSeconds: input.AssignmentIntervalSeconds,
|
||||
EncryptedSubscriptionProxyURL: subscriptionProxyURL,
|
||||
Fallbacks: fallbacks, UpdatedAt: time.Now().UTC(),
|
||||
Fallbacks: fallbacks, UpdatedAt: time.Now().UTC(),
|
||||
})
|
||||
if errors.Is(err, repository.ErrEgressFallbackInUse) {
|
||||
return domain.OperationsConfig{}, fmt.Errorf("%w: 固定回退节点必须保持启用且可用", ErrInvalidInput)
|
||||
@@ -553,7 +529,26 @@ func (s *Service) applySourceInput(value domain.SubscriptionSource, input Subscr
|
||||
if create && value.EncryptedURL == "" {
|
||||
return domain.SubscriptionSource{}, fmt.Errorf("%w: 必须提供订阅地址", ErrInvalidInput)
|
||||
}
|
||||
if create || input.URL != nil || input.ClearURL {
|
||||
if input.ClearProxyURL {
|
||||
value.EncryptedProxyURL = ""
|
||||
} else if input.ProxyURL != nil {
|
||||
proxyURL, err := NormalizeProxyURL(*input.ProxyURL)
|
||||
if err != nil {
|
||||
return domain.SubscriptionSource{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
|
||||
}
|
||||
if proxyURL == "" {
|
||||
return domain.SubscriptionSource{}, fmt.Errorf("%w: 订阅代理地址不能为空", ErrInvalidInput)
|
||||
}
|
||||
if strings.Contains(proxyURL, ProxyAccountPlaceholder) {
|
||||
return domain.SubscriptionSource{}, fmt.Errorf("%w: 订阅代理地址不能包含账号占位符", ErrInvalidInput)
|
||||
}
|
||||
encryptedProxyURL, err := s.cipher.Encrypt(proxyURL)
|
||||
if err != nil {
|
||||
return domain.SubscriptionSource{}, err
|
||||
}
|
||||
value.EncryptedProxyURL = encryptedProxyURL
|
||||
}
|
||||
if create || input.URL != nil || input.ClearURL || input.ProxyURL != nil || input.ClearProxyURL {
|
||||
value.NextSyncAt = nil
|
||||
value.LastSyncError = ""
|
||||
}
|
||||
@@ -563,6 +558,7 @@ func (s *Service) applySourceInput(value domain.SubscriptionSource, input Subscr
|
||||
func publicSource(value domain.SubscriptionSource) domain.PublicSubscriptionSource {
|
||||
return domain.PublicSubscriptionSource{
|
||||
ID: value.ID, Name: value.Name, Scope: value.Scope, Enabled: value.Enabled, URLConfigured: value.EncryptedURL != "",
|
||||
ProxyConfigured: value.EncryptedProxyURL != "",
|
||||
RefreshIntervalSeconds: value.RefreshIntervalSeconds, DefaultAccountCapacity: value.DefaultAccountCapacity,
|
||||
LastSyncedAt: value.LastSyncedAt, NextSyncAt: value.NextSyncAt, LastSyncImported: value.LastSyncImported, LastSyncError: value.LastSyncError,
|
||||
CreatedAt: value.CreatedAt, UpdatedAt: value.UpdatedAt,
|
||||
|
||||
@@ -1,153 +0,0 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
domain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
)
|
||||
|
||||
type operationsConfigRepositoryStub struct {
|
||||
OperationsRepository
|
||||
config domain.OperationsConfig
|
||||
getErr error
|
||||
saved domain.OperationsConfig
|
||||
saveCalls int
|
||||
syncUpdates int
|
||||
}
|
||||
|
||||
func (r *operationsConfigRepositoryStub) GetEgressOperationsConfig(context.Context) (domain.OperationsConfig, error) {
|
||||
if r.getErr != nil {
|
||||
return domain.OperationsConfig{}, r.getErr
|
||||
}
|
||||
return r.config, nil
|
||||
}
|
||||
|
||||
func (r *operationsConfigRepositoryStub) SaveEgressOperationsConfig(_ context.Context, value domain.OperationsConfig) (domain.OperationsConfig, error) {
|
||||
r.saved = value
|
||||
r.config = value
|
||||
r.saveCalls++
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *operationsConfigRepositoryStub) UpdateEgressSourceSync(context.Context, uint64, time.Time, time.Time, int, string) error {
|
||||
r.syncUpdates++
|
||||
return nil
|
||||
}
|
||||
|
||||
func testOperationsConfigInput() OperationsConfigInput {
|
||||
return OperationsConfigInput{
|
||||
ProbeProvider: domain.ProbeProviderCloudflare,
|
||||
ProbeIntervalSeconds: 900,
|
||||
AssignmentIntervalSeconds: 300,
|
||||
}
|
||||
}
|
||||
|
||||
func testEgressCipher(t *testing.T) *security.Cipher {
|
||||
t.Helper()
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return cipher
|
||||
}
|
||||
|
||||
func TestUpdateOperationsConfigUsesExplicitSubscriptionProxyTriState(t *testing.T) {
|
||||
cipher := testEgressCipher(t)
|
||||
existing, err := cipher.Encrypt("socks5h://old.example:1080")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Run("omitted preserves existing secret", func(t *testing.T) {
|
||||
repository := &operationsConfigRepositoryStub{config: domain.DefaultOperationsConfig()}
|
||||
repository.config.EncryptedSubscriptionProxyURL = existing
|
||||
service := &Service{operations: repository, cipher: cipher}
|
||||
if _, err := service.UpdateOperationsConfig(context.Background(), testOperationsConfigInput()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if repository.saved.EncryptedSubscriptionProxyURL != existing {
|
||||
t.Fatal("omitted subscription proxy did not preserve the existing secret")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty value requires explicit clear", func(t *testing.T) {
|
||||
repository := &operationsConfigRepositoryStub{config: domain.DefaultOperationsConfig()}
|
||||
repository.config.EncryptedSubscriptionProxyURL = existing
|
||||
service := &Service{operations: repository, cipher: cipher}
|
||||
input := testOperationsConfigInput()
|
||||
empty := ""
|
||||
input.SubscriptionProxyURL = &empty
|
||||
_, err := service.UpdateOperationsConfig(context.Background(), input)
|
||||
if !errors.Is(err, ErrInvalidInput) || repository.saveCalls != 0 {
|
||||
t.Fatalf("empty proxy error=%v saveCalls=%d", err, repository.saveCalls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("clear removes existing secret", func(t *testing.T) {
|
||||
repository := &operationsConfigRepositoryStub{config: domain.DefaultOperationsConfig()}
|
||||
repository.config.EncryptedSubscriptionProxyURL = existing
|
||||
service := &Service{operations: repository, cipher: cipher}
|
||||
input := testOperationsConfigInput()
|
||||
input.ClearSubscriptionProxy = true
|
||||
if _, err := service.UpdateOperationsConfig(context.Background(), input); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if repository.saved.EncryptedSubscriptionProxyURL != "" {
|
||||
t.Fatal("explicit clear preserved the subscription proxy")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("new value is encrypted", func(t *testing.T) {
|
||||
repository := &operationsConfigRepositoryStub{config: domain.DefaultOperationsConfig()}
|
||||
service := &Service{operations: repository, cipher: cipher}
|
||||
input := testOperationsConfigInput()
|
||||
proxyURL := "socks5h://user:secret@new.example:1080"
|
||||
input.SubscriptionProxyURL = &proxyURL
|
||||
if _, err := service.UpdateOperationsConfig(context.Background(), input); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if repository.saved.EncryptedSubscriptionProxyURL == "" || repository.saved.EncryptedSubscriptionProxyURL == proxyURL {
|
||||
t.Fatal("new subscription proxy was not encrypted")
|
||||
}
|
||||
decrypted, err := cipher.Decrypt(repository.saved.EncryptedSubscriptionProxyURL)
|
||||
if err != nil || decrypted != proxyURL {
|
||||
t.Fatalf("decrypted proxy=%q err=%v", decrypted, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("account placeholder is rejected", func(t *testing.T) {
|
||||
repository := &operationsConfigRepositoryStub{config: domain.DefaultOperationsConfig()}
|
||||
service := &Service{operations: repository, cipher: cipher}
|
||||
input := testOperationsConfigInput()
|
||||
proxyURL := "socks5h://Default.{account}:secret@proxy.example:1080"
|
||||
input.SubscriptionProxyURL = &proxyURL
|
||||
_, err := service.UpdateOperationsConfig(context.Background(), input)
|
||||
if !errors.Is(err, ErrInvalidInput) || repository.saveCalls != 0 {
|
||||
t.Fatalf("placeholder proxy error=%v saveCalls=%d", err, repository.saveCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSyncSourceFailsClosedWhenOperationsConfigCannotBeRead(t *testing.T) {
|
||||
repository := &operationsConfigRepositoryStub{getErr: errors.New("database unavailable")}
|
||||
service := &Service{operations: repository, cipher: testEgressCipher(t)}
|
||||
_, err := service.syncSource(context.Background(), repository, domain.SubscriptionSource{ID: 7, RefreshIntervalSeconds: 900})
|
||||
if !errors.Is(err, ErrSubscriptionSync) {
|
||||
t.Fatalf("sync error=%v", err)
|
||||
}
|
||||
if repository.syncUpdates != 1 {
|
||||
t.Fatalf("failure status updates=%d", repository.syncUpdates)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscriptionFetchProxyRejectsCorruptConfiguredSecret(t *testing.T) {
|
||||
service := &Service{cipher: testEgressCipher(t)}
|
||||
_, err := service.subscriptionFetchProxy(domain.OperationsConfig{EncryptedSubscriptionProxyURL: "not-ciphertext"})
|
||||
if err == nil {
|
||||
t.Fatal("corrupt configured subscription proxy was accepted")
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
domain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
)
|
||||
|
||||
@@ -851,13 +852,27 @@ func NormalizeProxyURL(value string) (string, error) {
|
||||
}
|
||||
parseValue := strings.ReplaceAll(value, ProxyAccountPlaceholder, proxyAccountSentinel)
|
||||
parsed, err := url.Parse(parseValue)
|
||||
if err != nil || parsed.Host == "" || parsed.Hostname() == "" {
|
||||
if err != nil {
|
||||
return "", errors.New("代理地址格式无效")
|
||||
}
|
||||
switch strings.ToLower(parsed.Scheme) {
|
||||
scheme := strings.ToLower(parsed.Scheme)
|
||||
if tunnelproxy.IsSupportedScheme(scheme) {
|
||||
if hasAccountPlaceholder {
|
||||
return "", errors.New("隧道代理不支持 {account} 占位符")
|
||||
}
|
||||
normalized, normalizeErr := tunnelproxy.Normalize(value)
|
||||
if normalizeErr != nil {
|
||||
return "", normalizeErr
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
if parsed.Host == "" || parsed.Hostname() == "" {
|
||||
return "", errors.New("代理地址格式无效")
|
||||
}
|
||||
switch scheme {
|
||||
case "http", "https", "socks4", "socks4a", "socks5", "socks5h":
|
||||
default:
|
||||
return "", errors.New("代理地址协议必须是 HTTP、HTTPS、SOCKS4 或 SOCKS5")
|
||||
return "", errors.New("代理地址协议必须是 HTTP、HTTPS、SOCKS4、SOCKS5、Trojan、VLESS、SS 或 VMess")
|
||||
}
|
||||
if parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") {
|
||||
return "", errors.New("代理地址不能包含路径、查询参数或片段")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -21,23 +22,48 @@ func TestSanitizeCloudflareCookiesDropsControlsAndNonCloudflareValues(t *testing
|
||||
}
|
||||
|
||||
func TestNormalizeProxyURLValidatesStructure(t *testing.T) {
|
||||
vmess := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(`{"v":"2","ps":"node","add":"proxy.example","port":"443","id":"123e4567-e89b-12d3-a456-426614174000","aid":"0","scy":"auto","net":"ws","tls":"tls","sni":"edge.example","host":"edge.example","path":"/ws"}`))
|
||||
for _, raw := range []string{
|
||||
"http://user:password@127.0.0.1:8080", "https://proxy.example:8443",
|
||||
"socks4://127.0.0.1:1080", "socks4a://proxy.example:1080",
|
||||
"socks5://user:password@127.0.0.1:1080", "socks5h://user:password@proxy.example:1080",
|
||||
"trojan://password@proxy.example:443?security=tls&sni=edge.example#remark",
|
||||
"vless://123e4567-e89b-12d3-a456-426614174000@proxy.example:443?encryption=none&security=tls&sni=edge.example#remark",
|
||||
"ss://YWVzLTEyOC1nY206c2VjcmV0@proxy.example:8388#remark",
|
||||
vmess,
|
||||
} {
|
||||
value, err := NormalizeProxyURL(raw)
|
||||
if err != nil || value == "" {
|
||||
t.Fatalf("valid proxy %q = %q, err = %v", raw, value, err)
|
||||
}
|
||||
}
|
||||
for _, invalid := range []string{"file:///tmp/proxy", "https://", "http://proxy.example/path", "http://proxy.example\r\nX-Leak: yes"} {
|
||||
for _, invalid := range []string{
|
||||
"file:///tmp/proxy", "https://", "http://proxy.example/path", "http://proxy.example\r\nX-Leak: yes",
|
||||
"vless://uuid@127.0.0.1:443?encryption=none&flow=xtls-rprx-vision#remark",
|
||||
"ss://base64#remark", "vmess://base64#remark", "hysteria://127.0.0.1:443",
|
||||
"hysteria2://127.0.0.1:443", "tuic://user:pass@127.0.0.1:443", "tuicv5://user:pass@127.0.0.1:443",
|
||||
} {
|
||||
if _, err := NormalizeProxyURL(invalid); err == nil {
|
||||
t.Fatalf("invalid proxy accepted: %q", invalid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeProxyURLStripsTunnelRemarks(t *testing.T) {
|
||||
base := "trojan://password@proxy.example:443?security=tls&sni=edge.example"
|
||||
one, err := NormalizeProxyURL(base + "#one")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
two, err := NormalizeProxyURL(base + "#two")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if one != two || strings.Contains(one, "#") {
|
||||
t.Fatalf("normalized tunnel identities = %q and %q", one, two)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeProxyURLAllowsAccountPlaceholderOnlyInUsername(t *testing.T) {
|
||||
value, err := NormalizeProxyURL("socks5h://Default.{account}:token@resin:2260")
|
||||
if err != nil {
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"unicode/utf8"
|
||||
|
||||
_ "github.com/bdandy/go-socks4"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy"
|
||||
xproxy "golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
@@ -163,8 +164,14 @@ func subscriptionTransport(viaProxy string) (*http.Transport, error) {
|
||||
return nil, fmt.Errorf("创建订阅拉取 SOCKS 代理: %w", err)
|
||||
}
|
||||
transport.DialContext = subscriptionProxyDialContext(dialer)
|
||||
case "trojan", "vless", "ss", "vmess":
|
||||
dialer, err := tunnelproxy.NewDialer(viaProxy)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建订阅拉取隧道代理: %w", err)
|
||||
}
|
||||
transport.DialContext = dialer.DialContext
|
||||
default:
|
||||
return nil, errors.New("订阅拉取代理协议必须是 HTTP、HTTPS、SOCKS4 或 SOCKS5")
|
||||
return nil, errors.New("订阅拉取代理协议不受支持")
|
||||
}
|
||||
return transport, nil
|
||||
}
|
||||
@@ -361,7 +368,7 @@ func parseProxySubscription(value string) ([]subscriptionEntry, int, error) {
|
||||
return entries, decodedSkipped, nil
|
||||
}
|
||||
}
|
||||
return nil, skipped, errors.New("订阅中没有可用的 HTTP 或 SOCKS 代理")
|
||||
return nil, skipped, errors.New("订阅中没有可用的代理节点")
|
||||
}
|
||||
|
||||
func parseProxyLines(value string) ([]subscriptionEntry, int) {
|
||||
|
||||
@@ -4,12 +4,42 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
domain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
)
|
||||
|
||||
type subscriptionSyncRepositoryStub struct {
|
||||
OperationsRepository
|
||||
mu sync.Mutex
|
||||
nodes map[uint64][]domain.Node
|
||||
}
|
||||
|
||||
func (r *subscriptionSyncRepositoryStub) UpsertEgressNodesFromSource(_ context.Context, sourceID uint64, nodes []domain.Node) (int, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.nodes[sourceID] = append([]domain.Node(nil), nodes...)
|
||||
return len(nodes), nil
|
||||
}
|
||||
|
||||
func (r *subscriptionSyncRepositoryStub) UpdateEgressSourceSync(context.Context, uint64, time.Time, time.Time, int, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *subscriptionSyncRepositoryStub) nodesFor(sourceID uint64) []domain.Node {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return append([]domain.Node(nil), r.nodes[sourceID]...)
|
||||
}
|
||||
|
||||
func TestParseProxySubscriptionAcceptsPlainAndBase64Lists(t *testing.T) {
|
||||
plain, skipped, err := parseProxySubscription(strings.Join([]string{
|
||||
"# proxy list",
|
||||
@@ -46,6 +76,30 @@ func TestParseProxySubscriptionRejectsNoUsableEntries(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseProxySubscriptionImportsSupportedTunnelSchemes(t *testing.T) {
|
||||
vmess := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(`{"v":"2","ps":"node","add":"proxy.example","port":"443","id":"123e4567-e89b-12d3-a456-426614174000","aid":"0","scy":"auto","net":"tcp"}`))
|
||||
entries, skipped, err := parseProxySubscription(strings.Join([]string{
|
||||
"http://proxy.example:8080",
|
||||
"trojan://password@proxy.example:443#remark",
|
||||
"vless://123e4567-e89b-12d3-a456-426614174000@proxy.example:443?encryption=none#remark",
|
||||
"ss://YWVzLTEyOC1nY206c2VjcmV0@proxy.example:8388#remark",
|
||||
vmess,
|
||||
"hysteria2://proxy.example:443",
|
||||
"tuic://user:pass@proxy.example:443",
|
||||
}, "\n"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 5 || skipped != 2 || entries[0].ProxyURL != "http://proxy.example:8080" {
|
||||
t.Fatalf("entries=%#v skipped=%d", entries, skipped)
|
||||
}
|
||||
for _, entry := range entries[1:] {
|
||||
if strings.Contains(entry.ProxyURL, "#") {
|
||||
t.Fatalf("subscription remark was retained: %q", entry.ProxyURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsPublicAddressRejectsNonPublicRanges(t *testing.T) {
|
||||
for _, raw := range []string{
|
||||
"0.0.0.1", "10.0.0.1", "100.64.0.1", "127.0.0.1", "169.254.10.1",
|
||||
@@ -118,3 +172,78 @@ func TestSubscriptionTransportSupportsConfiguredProxyProtocols(t *testing.T) {
|
||||
transport.CloseIdleConnections()
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscriptionFetchProxyRejectsCorruptSourceSecret(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := &Service{cipher: cipher}
|
||||
if _, err := service.subscriptionFetchProxy(domain.SubscriptionSource{EncryptedProxyURL: "not-ciphertext"}); err == nil {
|
||||
t.Fatal("corrupt per-source subscription proxy was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncSourceUsesItsOwnFetchProxy(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
type proxyFixture struct {
|
||||
hits atomic.Int32
|
||||
server *httptest.Server
|
||||
nodeProxy string
|
||||
}
|
||||
newProxy := func(nodeProxy string) *proxyFixture {
|
||||
fixture := &proxyFixture{nodeProxy: nodeProxy}
|
||||
fixture.server = httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
||||
fixture.hits.Add(1)
|
||||
if request.URL.Host != "1.1.1.1" {
|
||||
response.WriteHeader(http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
_, _ = response.Write([]byte(fixture.nodeProxy + "\n"))
|
||||
}))
|
||||
t.Cleanup(fixture.server.Close)
|
||||
return fixture
|
||||
}
|
||||
firstProxy := newProxy("socks5h://first-node.example:1080")
|
||||
secondProxy := newProxy("http://second-node.example:8080")
|
||||
|
||||
encryptedSourceURL, err := cipher.Encrypt("http://1.1.1.1/subscription")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repository := &subscriptionSyncRepositoryStub{nodes: make(map[uint64][]domain.Node)}
|
||||
service := &Service{cipher: cipher}
|
||||
for id, fixture := range map[uint64]*proxyFixture{1: firstProxy, 2: secondProxy} {
|
||||
encryptedProxyURL, encryptErr := cipher.Encrypt(fixture.server.URL)
|
||||
if encryptErr != nil {
|
||||
t.Fatal(encryptErr)
|
||||
}
|
||||
_, syncErr := service.syncSource(context.Background(), repository, domain.SubscriptionSource{
|
||||
ID: id, Name: "source", Scope: domain.ScopeBuild, Enabled: true,
|
||||
EncryptedURL: encryptedSourceURL, EncryptedProxyURL: encryptedProxyURL, RefreshIntervalSeconds: 900,
|
||||
})
|
||||
if syncErr != nil {
|
||||
t.Fatalf("sync source %d: %v", id, syncErr)
|
||||
}
|
||||
}
|
||||
|
||||
if firstProxy.hits.Load() != 1 || secondProxy.hits.Load() != 1 {
|
||||
t.Fatalf("proxy hits: first=%d second=%d", firstProxy.hits.Load(), secondProxy.hits.Load())
|
||||
}
|
||||
for id, expected := range map[uint64]string{1: firstProxy.nodeProxy, 2: secondProxy.nodeProxy} {
|
||||
nodes := repository.nodesFor(id)
|
||||
if len(nodes) != 1 {
|
||||
t.Fatalf("source %d imported %d nodes", id, len(nodes))
|
||||
}
|
||||
actual, decryptErr := cipher.Decrypt(nodes[0].EncryptedProxyURL)
|
||||
if decryptErr != nil {
|
||||
t.Fatal(decryptErr)
|
||||
}
|
||||
if actual != expected {
|
||||
t.Fatalf("source %d imported proxy %q, want %q", id, actual, expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,17 +13,6 @@ import (
|
||||
var ErrSubscriptionSync = errors.New("代理订阅同步失败")
|
||||
|
||||
func (s *Service) syncSource(ctx context.Context, operations OperationsRepository, source domain.SubscriptionSource) (ImportResult, error) {
|
||||
config, err := operations.GetEgressOperationsConfig(ctx)
|
||||
if err != nil {
|
||||
now := time.Now().UTC()
|
||||
nextSyncAt := sourceNextSyncAt(source, now)
|
||||
_ = operations.UpdateEgressSourceSync(context.WithoutCancel(ctx), source.ID, now, nextSyncAt, 0, "订阅拉取或解析失败")
|
||||
return ImportResult{}, ErrSubscriptionSync
|
||||
}
|
||||
return s.syncSourceWithConfig(ctx, operations, source, config)
|
||||
}
|
||||
|
||||
func (s *Service) syncSourceWithConfig(ctx context.Context, operations OperationsRepository, source domain.SubscriptionSource, config domain.OperationsConfig) (ImportResult, error) {
|
||||
now := time.Now().UTC()
|
||||
nextSyncAt := sourceNextSyncAt(source, now)
|
||||
recordFailure := func() {
|
||||
@@ -40,7 +29,7 @@ func (s *Service) syncSourceWithConfig(ctx context.Context, operations Operation
|
||||
recordFailure()
|
||||
return ImportResult{}, ErrSubscriptionSync
|
||||
}
|
||||
fetchProxy, err := s.subscriptionFetchProxy(config)
|
||||
fetchProxy, err := s.subscriptionFetchProxy(source)
|
||||
if err != nil {
|
||||
recordFailure()
|
||||
return ImportResult{}, ErrSubscriptionSync
|
||||
@@ -93,8 +82,8 @@ func sourceNextSyncAt(source domain.SubscriptionSource, now time.Time) time.Time
|
||||
return now.Add(time.Duration(source.RefreshIntervalSeconds) * time.Second)
|
||||
}
|
||||
|
||||
func (s *Service) subscriptionFetchProxy(config domain.OperationsConfig) (string, error) {
|
||||
encrypted := strings.TrimSpace(config.EncryptedSubscriptionProxyURL)
|
||||
func (s *Service) subscriptionFetchProxy(source domain.SubscriptionSource) (string, error) {
|
||||
encrypted := strings.TrimSpace(source.EncryptedProxyURL)
|
||||
if encrypted == "" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ type ImageGenerationInput struct {
|
||||
Size string
|
||||
AspectRatio string
|
||||
Resolution string
|
||||
Quality string
|
||||
ResponseFormat string
|
||||
Streaming bool
|
||||
PartialImages int
|
||||
@@ -42,6 +43,7 @@ type ImageEditInput struct {
|
||||
Size string
|
||||
AspectRatio string
|
||||
Resolution string
|
||||
Quality string
|
||||
ResponseFormat string
|
||||
Streaming bool
|
||||
PartialImages int
|
||||
@@ -63,10 +65,10 @@ func (s *Service) GenerateImage(ctx context.Context, input ImageGenerationInput)
|
||||
}
|
||||
return adapter.GenerateImage(executionCtx, provider.ImageGenerationRequest{
|
||||
Credential: credential, Model: upstream, Prompt: input.Prompt, Count: input.Count,
|
||||
Size: input.Size, AspectRatio: input.AspectRatio, Resolution: input.Resolution,
|
||||
Size: input.Size, AspectRatio: input.AspectRatio, Resolution: input.Resolution, Quality: input.Quality,
|
||||
ResponseFormat: input.ResponseFormat, Streaming: input.Streaming, PartialImages: input.PartialImages,
|
||||
})
|
||||
}, input.Streaming, input.Resolution, input.Count, 0)
|
||||
}, input.Streaming, input.Resolution, input.Quality, input.Count, 0)
|
||||
}
|
||||
|
||||
// EditImage 选择支持图片编辑的路由和账号,并返回可统一审计的上游响应。
|
||||
@@ -82,10 +84,10 @@ func (s *Service) EditImage(ctx context.Context, input ImageEditInput) (*Result,
|
||||
return adapter.EditImage(executionCtx, provider.ImageEditRequest{
|
||||
Credential: credential, Model: upstream, Prompt: input.Prompt,
|
||||
ImageURLs: input.ImageURLs, Count: input.Count, Size: input.Size, AspectRatio: input.AspectRatio,
|
||||
Resolution: input.Resolution, ResponseFormat: input.ResponseFormat,
|
||||
Resolution: input.Resolution, Quality: input.Quality, ResponseFormat: input.ResponseFormat,
|
||||
Streaming: input.Streaming, PartialImages: input.PartialImages,
|
||||
})
|
||||
}, input.Streaming, input.Resolution, input.Count, len(input.ImageURLs))
|
||||
}, input.Streaming, input.Resolution, input.Quality, input.Count, len(input.ImageURLs))
|
||||
}
|
||||
|
||||
func (s *Service) executeImage(
|
||||
@@ -99,6 +101,7 @@ func (s *Service) executeImage(
|
||||
execute imageExecution,
|
||||
streaming bool,
|
||||
resolution string,
|
||||
quality string,
|
||||
requestedCount int,
|
||||
inputImageCount int,
|
||||
) (*Result, error) {
|
||||
@@ -109,9 +112,16 @@ func (s *Service) executeImage(
|
||||
if err != nil {
|
||||
return nil, ErrModelNotFound
|
||||
}
|
||||
route, err := s.selectMediaRoute(routes, key, capability, supports)
|
||||
route, preselectedSession, err := s.selectSchedulableMediaRoute(ctx, routes, key, capability, true, supports)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
// Preserve the established failure-audit path when every eligible target
|
||||
// is currently unschedulable. The request loop will reproduce the
|
||||
// selection error for the representative route after auditBase exists.
|
||||
route, err = s.selectMediaRoute(routes, key, capability, supports)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
preselectedSession = nil
|
||||
}
|
||||
externalModel := modeldomain.ExternalPublicID(route.Provider, route.PublicID)
|
||||
auditBase := audit.Record{
|
||||
@@ -148,9 +158,9 @@ func (s *Service) executeImage(
|
||||
var priced bool
|
||||
switch operation {
|
||||
case audit.OperationImage:
|
||||
reservation, priced = audit.EstimateOfficialImageCost(pricingModel, resolution, requestedCount)
|
||||
reservation, priced = audit.EstimateOfficialImageCost(pricingModel, resolution, quality, requestedCount)
|
||||
case audit.OperationImageEdit:
|
||||
reservation, priced = audit.EstimateOfficialImageEditCost(pricingModel, resolution, requestedCount, inputImageCount)
|
||||
reservation, priced = audit.EstimateOfficialImageEditCost(pricingModel, resolution, quality, requestedCount, inputImageCount)
|
||||
}
|
||||
reserved := false
|
||||
if priced {
|
||||
@@ -166,9 +176,10 @@ func (s *Service) executeImage(
|
||||
}
|
||||
}()
|
||||
quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel)
|
||||
quotaRefreshGroup := s.providers.QuotaRefreshGroup(route.Provider, route.UpstreamModel)
|
||||
attemptPolicy := newRoutingAttemptPolicy(int(s.maxAttempts.Load()))
|
||||
excluded := make(map[uint64]bool)
|
||||
var selection *selectionSession
|
||||
selection := preselectedSession
|
||||
var lease *accountLease
|
||||
var credential accountdomain.Credential
|
||||
var response *provider.Response
|
||||
@@ -284,9 +295,9 @@ func (s *Service) executeImage(
|
||||
var priced bool
|
||||
switch operation {
|
||||
case audit.OperationImage:
|
||||
pricing, priced = audit.EstimateOfficialImageCost(pricingModel, resolution, requestedCount)
|
||||
pricing, priced = audit.EstimateOfficialImageCost(pricingModel, resolution, quality, requestedCount)
|
||||
case audit.OperationImageEdit:
|
||||
pricing, priced = audit.EstimateOfficialImageEditCost(pricingModel, resolution, requestedCount, inputImageCount)
|
||||
pricing, priced = audit.EstimateOfficialImageEditCost(pricingModel, resolution, quality, requestedCount, inputImageCount)
|
||||
}
|
||||
if priced {
|
||||
record.EstimatedCostInUSDTicks = pricing.CostInUSDTicks
|
||||
@@ -295,22 +306,28 @@ func (s *Service) executeImage(
|
||||
}
|
||||
}
|
||||
quotaKind, _ := s.providers.QuotaKind(route.Provider)
|
||||
if successful && quotaKind == provider.QuotaRemoteWindow && effectiveQuotaMode != "" {
|
||||
if effectiveQuotaMode != "weekly" {
|
||||
refreshMode := effectiveQuotaMode
|
||||
decrementMode := effectiveQuotaMode
|
||||
if quotaRefreshGroup != "" {
|
||||
refreshMode = quotaRefreshGroup
|
||||
decrementMode = quotaMode
|
||||
}
|
||||
if successful && quotaKind == provider.QuotaRemoteWindow && refreshMode != "" {
|
||||
if decrementMode != "" && decrementMode != "weekly" {
|
||||
units := max(1, response.QuotaUnits)
|
||||
var updated bool
|
||||
err := budget.run("quota_decrement", finalizationQuotaBudget, func(stageCtx context.Context) error {
|
||||
var decrementErr error
|
||||
updated, decrementErr = s.accounts.DecrementWebQuota(stageCtx, accountID, effectiveQuotaMode, units)
|
||||
updated, decrementErr = s.accounts.DecrementWebQuota(stageCtx, accountID, decrementMode, units)
|
||||
return decrementErr
|
||||
})
|
||||
if err != nil {
|
||||
s.logger.Warn("web_quota_decrement_failed", "account_id", accountID, "mode", effectiveQuotaMode, "units", units, "error", err)
|
||||
s.logger.Warn("web_quota_decrement_failed", "account_id", accountID, "mode", decrementMode, "units", units, "error", err)
|
||||
} else if updated {
|
||||
s.selector.ConsumeQuota(route.Provider, accountID, effectiveQuotaMode, units)
|
||||
s.selector.ConsumeQuota(route.Provider, accountID, decrementMode, units)
|
||||
}
|
||||
}
|
||||
s.accounts.QueueQuotaRefresh(accountID, effectiveQuotaMode)
|
||||
s.accounts.QueueQuotaRefresh(accountID, refreshMode)
|
||||
}
|
||||
if err := budget.run("audit", finalizationAuditBudget, func(stageCtx context.Context) error {
|
||||
return s.audits.Create(stageCtx, record)
|
||||
|
||||
@@ -44,6 +44,7 @@ var (
|
||||
ErrConversationUnsupported = errors.New("目标模型不支持当前对话协议")
|
||||
ErrVideoInputTooLarge = errors.New("视频参考图片编码后总输入超过 32 MiB")
|
||||
ErrVideoInputUnavailable = errors.New("视频临时输入不存在或已过期")
|
||||
ErrVideoOperationUnsupported = errors.New("视频编辑/延长仅支持路由到 Console grok-imagine-video")
|
||||
ErrLedgerUnavailable = errors.New("计费账本暂不可用")
|
||||
)
|
||||
|
||||
@@ -160,8 +161,8 @@ type routeResolver interface {
|
||||
type videoAssetStore interface {
|
||||
SaveVideo(ctx context.Context, jobID, contentType string, body io.Reader) (mediadomain.Asset, error)
|
||||
OpenVideo(ctx context.Context, id string) (mediadomain.Asset, io.ReadCloser, error)
|
||||
OpenInputImage(ctx context.Context, id string) (mediadomain.Asset, io.ReadCloser, error)
|
||||
ReleaseInputImages(ctx context.Context, references []string) error
|
||||
OpenInputAsset(ctx context.Context, id string) (mediadomain.Asset, io.ReadCloser, error)
|
||||
ReleaseInputAssets(ctx context.Context, references []string) error
|
||||
}
|
||||
|
||||
type accountModelSyncer interface {
|
||||
@@ -686,10 +687,19 @@ func routeTargetSeed(input Input) string {
|
||||
|
||||
// selectMediaRoute selects a same-name route that satisfies media capability, key permissions, and Provider support.
|
||||
func (s *Service) selectMediaRoute(routes []modeldomain.Route, key clientkey.Key, capability modeldomain.Capability, providerSupported func(accountdomain.Provider) bool) (modeldomain.Route, error) {
|
||||
eligible, fallback, err := s.eligibleMediaRoutes(routes, key, capability, providerSupported)
|
||||
if err != nil {
|
||||
return fallback, err
|
||||
}
|
||||
return eligible[0], nil
|
||||
}
|
||||
|
||||
func (s *Service) eligibleMediaRoutes(routes []modeldomain.Route, key clientkey.Key, capability modeldomain.Capability, providerSupported func(accountdomain.Provider) bool) ([]modeldomain.Route, modeldomain.Route, error) {
|
||||
if len(routes) == 0 {
|
||||
return modeldomain.Route{}, ErrModelNotFound
|
||||
return nil, modeldomain.Route{}, ErrModelNotFound
|
||||
}
|
||||
fallback := routes[0]
|
||||
eligible := make([]modeldomain.Route, 0, len(routes))
|
||||
accountScope := key.AccountScope()
|
||||
capabilityMatched := false
|
||||
scopeMatched := false
|
||||
@@ -709,19 +719,68 @@ func (s *Service) selectMediaRoute(routes []modeldomain.Route, key clientkey.Key
|
||||
}
|
||||
allowed = true
|
||||
if providerSupported(route.Provider) {
|
||||
return route, nil
|
||||
eligible = append(eligible, route)
|
||||
}
|
||||
}
|
||||
if len(eligible) > 0 {
|
||||
return eligible, fallback, nil
|
||||
}
|
||||
if !capabilityMatched {
|
||||
return fallback, ErrModelNotFound
|
||||
return nil, fallback, ErrModelNotFound
|
||||
}
|
||||
if !scopeMatched {
|
||||
return fallback, &SelectionUnavailableError{Reason: SelectionNoAccounts, Scope: accountScope}
|
||||
return nil, fallback, &SelectionUnavailableError{Reason: SelectionNoAccounts, Scope: accountScope}
|
||||
}
|
||||
if !allowed {
|
||||
return fallback, clientkeyapp.ErrModelNotAllowed
|
||||
return nil, fallback, clientkeyapp.ErrModelNotAllowed
|
||||
}
|
||||
return fallback, ErrNoAvailableAccount
|
||||
return nil, fallback, ErrNoAvailableAccount
|
||||
}
|
||||
|
||||
// selectSchedulableMediaRoute resolves a concrete same-name media target and
|
||||
// its immutable account plan together. A cooling or exhausted first target
|
||||
// therefore cannot hide a healthy target from another Provider.
|
||||
func (s *Service) selectSchedulableMediaRoute(ctx context.Context, routes []modeldomain.Route, key clientkey.Key, capability modeldomain.Capability, consumesQuota bool, providerSupported func(accountdomain.Provider) bool) (modeldomain.Route, *selectionSession, error) {
|
||||
return s.selectSchedulableMediaRouteWithQuotaMode(ctx, routes, key, capability, consumesQuota, providerSupported, nil)
|
||||
}
|
||||
|
||||
func (s *Service) selectSchedulableMediaRouteWithQuotaMode(ctx context.Context, routes []modeldomain.Route, key clientkey.Key, capability modeldomain.Capability, consumesQuota bool, providerSupported func(accountdomain.Provider) bool, resolveQuotaMode func(modeldomain.Route) string) (modeldomain.Route, *selectionSession, error) {
|
||||
eligible, fallback, err := s.eligibleMediaRoutes(routes, key, capability, providerSupported)
|
||||
if err != nil {
|
||||
return fallback, nil, err
|
||||
}
|
||||
var firstSelectionErr error
|
||||
for _, route := range eligible {
|
||||
quotaMode := ""
|
||||
if consumesQuota {
|
||||
if resolveQuotaMode != nil {
|
||||
quotaMode = resolveQuotaMode(route)
|
||||
} else {
|
||||
quotaMode = s.providers.QuotaMode(route.Provider, route.UpstreamModel)
|
||||
}
|
||||
}
|
||||
session, selectionErr := s.selector.beginSelectionSessionForKey(
|
||||
ctx,
|
||||
route.Provider,
|
||||
route.ID,
|
||||
route.UpstreamModel,
|
||||
quotaMode,
|
||||
"",
|
||||
nil,
|
||||
false,
|
||||
key.AccountScope(),
|
||||
)
|
||||
if selectionErr == nil {
|
||||
return route, session, nil
|
||||
}
|
||||
if firstSelectionErr == nil {
|
||||
firstSelectionErr = selectionErr
|
||||
}
|
||||
}
|
||||
if firstSelectionErr == nil {
|
||||
firstSelectionErr = ErrNoAvailableAccount
|
||||
}
|
||||
return eligible[0], nil, firstSelectionErr
|
||||
}
|
||||
|
||||
func (s *Service) createResponseAt(ctx context.Context, input Input, path string) (*Result, error) {
|
||||
@@ -1294,7 +1353,7 @@ attemptLoop:
|
||||
record.ReasoningTokens = usage.ReasoningTokens
|
||||
record.TotalTokens = usage.TotalTokens
|
||||
record.CostInUSDTicks = usage.CostInUSDTicks
|
||||
imagePricing, imagePriced := audit.EstimateOfficialImageCost(pricingModel, "", response.QuotaUnits)
|
||||
imagePricing, imagePriced := audit.EstimateOfficialImageCost(pricingModel, "", "", response.QuotaUnits)
|
||||
if imagePriced {
|
||||
record.MediaOutputImages = int64(max(0, response.QuotaUnits))
|
||||
}
|
||||
|
||||
@@ -51,6 +51,79 @@ func TestQueueAccountModelSyncDeduplicatesConcurrentETagRefresh(t *testing.T) {
|
||||
close(resolver.release)
|
||||
}
|
||||
|
||||
func TestVoiceWebSocketAuditOutcomeUsesLogicalSuccessStatus(t *testing.T) {
|
||||
if status, code := voiceWebSocketAuditOutcome(VoiceWebSocketOutcome{}); status != http.StatusOK || code != "" {
|
||||
t.Fatalf("successful outcome = status %d code %q", status, code)
|
||||
}
|
||||
if status, code := voiceWebSocketAuditOutcome(VoiceWebSocketOutcome{ErrorCode: " upstream_stream_interrupted "}); status != http.StatusBadGateway || code != "upstream_stream_interrupted" {
|
||||
t.Fatalf("failed outcome = status %d code %q", status, code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamingSTTPricingUsesCompletedDuration(t *testing.T) {
|
||||
result, ok := audit.EstimateOfficialSTTCost(3.45, true)
|
||||
if !ok || result.Model != "grok-stt-streaming" || result.CostInUSDTicks != 1_916_667 {
|
||||
t.Fatalf("streaming STT pricing = %#v, ok = %t", result, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVoiceErrorResponseDoesNotExposeUnclassifiedErrors(t *testing.T) {
|
||||
response, err := voiceErrorResponse(testVoiceStatusError{status: http.StatusBadGateway, message: "access_token=secret"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, readErr := io.ReadAll(response.Body)
|
||||
response.Body.Close()
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
if strings.Contains(string(body), "access_token") || strings.Contains(string(body), "secret") {
|
||||
t.Fatalf("unclassified provider error leaked through public response: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
type testVoiceStatusError struct {
|
||||
status int
|
||||
message string
|
||||
}
|
||||
|
||||
func (e testVoiceStatusError) Error() string { return e.message }
|
||||
func (e testVoiceStatusError) HTTPStatusCode() int { return e.status }
|
||||
|
||||
func TestFormatSTTResponseHonorsOpenAIFormats(t *testing.T) {
|
||||
speaker := 2
|
||||
result := provider.STTResult{
|
||||
Text: "hello", Language: "en", Duration: 1.25,
|
||||
Words: []provider.STTWord{{Text: "hello", Start: 0.1, End: 0.8, Speaker: &speaker}},
|
||||
RawJSON: []byte(`{"text":"native","provider_field":true}`),
|
||||
}
|
||||
for _, test := range []struct {
|
||||
format string
|
||||
contentType string
|
||||
contains []string
|
||||
}{
|
||||
{format: "text", contentType: "text/plain; charset=utf-8", contains: []string{"hello"}},
|
||||
{format: "json", contentType: "application/json", contains: []string{`"text":"hello"`}},
|
||||
{format: "verbose_json", contentType: "application/json", contains: []string{`"task":"transcribe"`, `"word":"hello"`, `"speaker":2`}},
|
||||
{format: "", contentType: "application/json", contains: []string{`"provider_field":true`}},
|
||||
} {
|
||||
response := formatSTTResponse(result, test.format)
|
||||
body, err := io.ReadAll(response.Body)
|
||||
response.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Header.Get("Content-Type") != test.contentType {
|
||||
t.Fatalf("format %q content type = %q", test.format, response.Header.Get("Content-Type"))
|
||||
}
|
||||
for _, expected := range test.contains {
|
||||
if !strings.Contains(string(body), expected) {
|
||||
t.Fatalf("format %q body %q missing %q", test.format, body, expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type etagSyncResolver struct {
|
||||
calls atomic.Int64
|
||||
started chan uint64
|
||||
@@ -972,6 +1045,293 @@ func TestSelectMediaRouteSkipsSameNamedConversationRoute(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectSchedulableMediaRouteSkipsUnavailableFirstTarget(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "media-route-failover.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accountRepo := relational.NewAccountRepository(database)
|
||||
modelRepo := relational.NewModelRepository(database)
|
||||
now := time.Now().UTC()
|
||||
coolingUntil := now.Add(time.Hour)
|
||||
buildAccount, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderBuild, AuthType: account.AuthTypeOAuth,
|
||||
Name: "cooling-build", SourceKey: "cooling-build", EncryptedAccessToken: "build-token",
|
||||
Enabled: true, AuthStatus: account.AuthStatusActive, MaxConcurrent: 1, CooldownUntil: &coolingUntil,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
webAccount, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderWeb, AuthType: account.AuthTypeSSO, WebTier: account.WebTierSuper,
|
||||
Name: "healthy-web", SourceKey: "healthy-web", EncryptedAccessToken: "web-token",
|
||||
Enabled: true, AuthStatus: account.AuthStatusActive, MaxConcurrent: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const publicModel = "shared-media-target"
|
||||
routeInputs := []modeldomain.Route{
|
||||
{PublicID: publicModel, Provider: account.ProviderBuild, UpstreamModel: "build-image-target", Capability: modeldomain.CapabilityImage, Enabled: true},
|
||||
{PublicID: publicModel, Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image", Capability: modeldomain.CapabilityImage, Enabled: true},
|
||||
}
|
||||
if err := modelRepo.UpsertRoutes(ctx, routeInputs); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := modelRepo.ReplaceAccountCapabilities(ctx, buildAccount.ID, []string{"build-image-target"}, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := modelRepo.ReplaceAccountCapabilities(ctx, webAccount.ID, []string{"grok-imagine-image"}, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
routes, err := modelRepo.GetByPublicIDCandidates(ctx, publicModel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry := provider.NewRegistry(&credentialFailureImageAdapter{}, &webImageStreamAdapter{})
|
||||
sticky := memory.NewStickyStore()
|
||||
selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute)
|
||||
service := &Service{
|
||||
clientKeys: clientkeyapp.NewService(nil, nil, nil, 60, 4, nil),
|
||||
providers: registry,
|
||||
selector: selector,
|
||||
}
|
||||
selected, selection, err := service.selectSchedulableMediaRoute(ctx, routes, clientkey.Key{}, modeldomain.CapabilityImage, true, func(providerValue account.Provider) bool {
|
||||
_, ok := registry.ImageGeneration(providerValue)
|
||||
return ok
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if selected.Provider != account.ProviderWeb || selection == nil {
|
||||
t.Fatalf("selected route = %#v, selection = %#v", selected, selection)
|
||||
}
|
||||
lease, err := selection.Acquire(ctx, nil, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if lease.Credential.ID != webAccount.ID {
|
||||
t.Fatalf("selected account = %d, want %d", lease.Credential.ID, webAccount.ID)
|
||||
}
|
||||
lease.Release()
|
||||
|
||||
// Non-consuming metadata calls (for example voice listing) must not inherit
|
||||
// the Provider quota mode from route probing. Otherwise an account with an
|
||||
// exhausted inference window cannot serve a request that consumes no quota.
|
||||
if err := accountRepo.SaveQuotaWindows(ctx, webAccount.ID, account.WebTierSuper, now, []account.QuotaWindow{{
|
||||
AccountID: webAccount.ID, Mode: "fast", Remaining: 0, Total: 10, WindowSeconds: 3600,
|
||||
Source: account.QuotaSourceUpstream, SyncedAt: &now,
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
quotaSelector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), registry, time.Hour, time.Second, time.Minute)
|
||||
service.selector = quotaSelector
|
||||
if _, _, err := service.selectSchedulableMediaRoute(ctx, routes, clientkey.Key{}, modeldomain.CapabilityImage, true, func(providerValue account.Provider) bool {
|
||||
_, ok := registry.ImageGeneration(providerValue)
|
||||
return ok
|
||||
}); err == nil {
|
||||
t.Fatal("quota-consuming selection unexpectedly accepted an exhausted account")
|
||||
}
|
||||
selected, selection, err = service.selectSchedulableMediaRoute(ctx, routes, clientkey.Key{}, modeldomain.CapabilityImage, false, func(providerValue account.Provider) bool {
|
||||
_, ok := registry.ImageGeneration(providerValue)
|
||||
return ok
|
||||
})
|
||||
if err != nil || selected.Provider != account.ProviderWeb || selection == nil {
|
||||
t.Fatalf("non-consuming route = %#v, selection = %#v, err = %v", selected, selection, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnpricedVoiceRemainsAvailableToFiniteClientKey(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "voice-billing-policy.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accountRepo := relational.NewAccountRepository(database)
|
||||
modelRepo := relational.NewModelRepository(database)
|
||||
auditRepo := relational.NewAuditRepository(database)
|
||||
credential, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderConsole, AuthType: account.AuthTypeSSO,
|
||||
Name: "console-voice", SourceKey: "console-voice", EncryptedAccessToken: "console-token",
|
||||
Enabled: true, AuthStatus: account.AuthStatusActive, MaxConcurrent: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const voiceModel = "voice-billing-policy"
|
||||
if err := modelRepo.UpsertRoutes(ctx, []modeldomain.Route{{
|
||||
PublicID: voiceModel, Provider: account.ProviderConsole, UpstreamModel: voiceModel,
|
||||
Capability: modeldomain.CapabilityTTS, Enabled: true,
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{voiceModel}, time.Now().UTC()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry := provider.NewRegistry(statelessConsoleAdapter{})
|
||||
sticky := memory.NewStickyStore()
|
||||
selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute)
|
||||
accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil)
|
||||
service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(nil, nil, nil, 60, 4, nil), registry, selector, nil, 1)
|
||||
executed := false
|
||||
result, err := service.executeVoice(ctx, "req-voice-billing", clientkey.Key{ID: 1, BillingLimitUSDTicks: 1}, voiceModel, audit.OperationTTS, modeldomain.CapabilityTTS, true, audit.PricingResult{}, func(account.Provider) bool {
|
||||
return true
|
||||
}, func(context.Context, account.Provider, account.Credential, string) (voiceExecutionResult, error) {
|
||||
executed = true
|
||||
return voiceExecutionResult{response: jsonVoiceResponse(http.StatusOK, map[string]any{"ok": true})}, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !executed {
|
||||
t.Fatal("unpriced voice request did not reach the provider")
|
||||
}
|
||||
result.Finalize(Usage{}, "", "")
|
||||
_ = result.Body.Close()
|
||||
}
|
||||
|
||||
func TestVoicePricingSettlesTTSAndRESTSTTUsage(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "voice-pricing.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
accountRepo := relational.NewAccountRepository(database)
|
||||
modelRepo := relational.NewModelRepository(database)
|
||||
auditRepo := relational.NewAuditRepository(database)
|
||||
keyRepo := relational.NewClientKeyRepository(database)
|
||||
credential, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderConsole, AuthType: account.AuthTypeSSO,
|
||||
Name: "console-priced-voice", SourceKey: "console-priced-voice", EncryptedAccessToken: "console-token",
|
||||
Enabled: true, AuthStatus: account.AuthStatusActive, MaxConcurrent: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const (
|
||||
ttsModel = "voice-priced-tts"
|
||||
sttModel = "voice-priced-stt"
|
||||
)
|
||||
if err := modelRepo.UpsertRoutes(ctx, []modeldomain.Route{
|
||||
{PublicID: ttsModel, Provider: account.ProviderConsole, UpstreamModel: ttsModel, Capability: modeldomain.CapabilityTTS, Enabled: true},
|
||||
{PublicID: sttModel, Provider: account.ProviderConsole, UpstreamModel: sttModel, Capability: modeldomain.CapabilitySTT, Enabled: true},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{ttsModel, sttModel}, time.Now().UTC()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
limitedKey, err := keyRepo.Create(ctx, clientkey.Key{
|
||||
Name: "voice-priced-key", Prefix: "voice-priced", SecretHash: strings.Repeat("a", 64), EncryptedSecret: "encrypted",
|
||||
Enabled: true, BillingLimitUSDTicks: 10_000_000_000,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
registry := provider.NewRegistry(statelessConsoleAdapter{})
|
||||
sticky := memory.NewStickyStore()
|
||||
selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute)
|
||||
accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil)
|
||||
clientKeyService := clientkeyapp.NewService(keyRepo, nil, nil, 60, 4, nil)
|
||||
service := NewService(modelRepo, auditRepo, accountService, clientKeyService, registry, selector, nil, 1)
|
||||
|
||||
ttsPricing, ok := audit.EstimateOfficialTTSCost("Hello 世界")
|
||||
if !ok {
|
||||
t.Fatal("TTS pricing unavailable")
|
||||
}
|
||||
ttsResult, err := service.executeVoice(ctx, "req-priced-tts", limitedKey, ttsModel, audit.OperationTTS, modeldomain.CapabilityTTS, true, ttsPricing, func(account.Provider) bool {
|
||||
return true
|
||||
}, func(context.Context, account.Provider, account.Credential, string) (voiceExecutionResult, error) {
|
||||
return voiceExecutionResult{response: jsonVoiceResponse(http.StatusOK, map[string]any{"ok": true}), pricing: ttsPricing}, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ttsResult.Finalize(Usage{}, "", "")
|
||||
_ = ttsResult.Body.Close()
|
||||
|
||||
settledKey, err := keyRepo.Get(ctx, limitedKey.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if settledKey.BilledUsageUSDTicks != ttsPricing.CostInUSDTicks || settledKey.ReservedUsageUSDTicks != 0 {
|
||||
t.Fatalf("TTS billing = billed %d reserved %d, want billed %d reserved 0", settledKey.BilledUsageUSDTicks, settledKey.ReservedUsageUSDTicks, ttsPricing.CostInUSDTicks)
|
||||
}
|
||||
|
||||
sttPricing, ok := audit.EstimateOfficialSTTCost(3.45, false)
|
||||
if !ok {
|
||||
t.Fatal("STT pricing unavailable")
|
||||
}
|
||||
sttResult, err := service.executeVoice(ctx, "req-priced-stt", limitedKey, sttModel, audit.OperationSTT, modeldomain.CapabilitySTT, true, audit.PricingResult{}, func(account.Provider) bool {
|
||||
return true
|
||||
}, func(context.Context, account.Provider, account.Credential, string) (voiceExecutionResult, error) {
|
||||
return voiceExecutionResult{response: jsonVoiceResponse(http.StatusOK, map[string]any{"text": "hello"}), pricing: sttPricing}, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sttResult.Finalize(Usage{}, "", "")
|
||||
_ = sttResult.Body.Close()
|
||||
|
||||
settledKey, err = keyRepo.Get(ctx, limitedKey.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantBilled := ttsPricing.CostInUSDTicks + sttPricing.CostInUSDTicks
|
||||
if settledKey.BilledUsageUSDTicks != wantBilled || settledKey.ReservedUsageUSDTicks != 0 {
|
||||
t.Fatalf("voice billing = billed %d reserved %d, want billed %d reserved 0", settledKey.BilledUsageUSDTicks, settledKey.ReservedUsageUSDTicks, wantBilled)
|
||||
}
|
||||
audits, total, err := auditRepo.List(ctx, 0, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if total != 2 || len(audits) != 2 {
|
||||
t.Fatalf("voice audits = %d/%d, want 2/2", len(audits), total)
|
||||
}
|
||||
if audits[0].RequestID != "req-priced-stt" || audits[0].PricingModel != sttPricing.Model || audits[0].EstimatedCostInUSDTicks != sttPricing.CostInUSDTicks {
|
||||
t.Fatalf("STT audit = %#v", audits[0])
|
||||
}
|
||||
if audits[1].RequestID != "req-priced-tts" || audits[1].PricingModel != ttsPricing.Model || audits[1].EstimatedCostInUSDTicks != ttsPricing.CostInUSDTicks {
|
||||
t.Fatalf("TTS audit = %#v", audits[1])
|
||||
}
|
||||
|
||||
cappedKey, err := keyRepo.Create(ctx, clientkey.Key{
|
||||
Name: "voice-capped-key", Prefix: "voice-capped", SecretHash: strings.Repeat("b", 64), EncryptedSecret: "encrypted",
|
||||
Enabled: true, BillingLimitUSDTicks: ttsPricing.CostInUSDTicks - 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
executed := false
|
||||
_, err = service.executeVoice(ctx, "req-capped-tts", cappedKey, ttsModel, audit.OperationTTS, modeldomain.CapabilityTTS, true, ttsPricing, func(account.Provider) bool {
|
||||
return true
|
||||
}, func(context.Context, account.Provider, account.Credential, string) (voiceExecutionResult, error) {
|
||||
executed = true
|
||||
return voiceExecutionResult{response: jsonVoiceResponse(http.StatusOK, map[string]any{"ok": true}), pricing: ttsPricing}, nil
|
||||
})
|
||||
if !errors.Is(err, clientkeyapp.ErrBillingLimit) {
|
||||
t.Fatalf("capped TTS error = %v, want billing limit", err)
|
||||
}
|
||||
if executed {
|
||||
t.Fatal("TTS reached upstream after exact reservation exceeded the key limit")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateImageReturnsWhenEveryCredentialRefreshFails(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "image-credential-failure.db"))
|
||||
|
||||
@@ -40,27 +40,97 @@ func VideoInputFileReference(fileID string) string {
|
||||
}
|
||||
|
||||
type VideoInput struct {
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
Prompt string
|
||||
Duration int
|
||||
AspectRatio string
|
||||
Resolution string
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
// Operation defaults to generate when empty.
|
||||
Operation provider.VideoOperation
|
||||
Prompt string
|
||||
Duration int
|
||||
AspectRatio string
|
||||
Resolution string
|
||||
// ImageURL is the optional first-frame image (official "image").
|
||||
ImageURL string
|
||||
// ReferenceURLs are style/content references (official "reference_images").
|
||||
ReferenceURLs []string
|
||||
// ReferenceAudios are preset voice_ids for reference-to-video.
|
||||
ReferenceAudios []string
|
||||
// VideoURL is required for edit/extend (official "video").
|
||||
VideoURL string
|
||||
}
|
||||
|
||||
func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job, error) {
|
||||
if s.mediaJobs == nil || s.mediaQueue == nil {
|
||||
return media.Job{}, fmt.Errorf("视频任务服务未配置")
|
||||
}
|
||||
if len(input.Prompt) > 100000 || (len(input.Prompt) == 0 && len(input.ReferenceURLs) == 0) {
|
||||
return media.Job{}, fmt.Errorf("文本生视频必须提供 prompt;图片生视频可以省略 prompt")
|
||||
operation := input.Operation
|
||||
if operation == "" {
|
||||
operation = provider.VideoOperationGenerate
|
||||
}
|
||||
if err := s.validateVideoInputReferences(ctx, input.ReferenceURLs); err != nil {
|
||||
switch operation {
|
||||
case provider.VideoOperationGenerate, provider.VideoOperationEdit, provider.VideoOperationExtend:
|
||||
default:
|
||||
return media.Job{}, fmt.Errorf("不支持的视频操作")
|
||||
}
|
||||
if len(input.Prompt) > 100000 {
|
||||
return media.Job{}, fmt.Errorf("prompt 过长")
|
||||
}
|
||||
if operation == provider.VideoOperationGenerate {
|
||||
hasImage := strings.TrimSpace(input.ImageURL) != ""
|
||||
hasRefs := len(input.ReferenceURLs) > 0
|
||||
hasRefAudio := len(input.ReferenceAudios) > 0
|
||||
if hasImage && (hasRefs || hasRefAudio) {
|
||||
return media.Job{}, fmt.Errorf("image 不能与 reference_images/reference_audios 同时使用")
|
||||
}
|
||||
if hasRefs || hasRefAudio {
|
||||
if len(input.Prompt) == 0 {
|
||||
return media.Job{}, fmt.Errorf("参考图/参考音频视频必须提供 prompt")
|
||||
}
|
||||
if resolution := strings.ToLower(strings.TrimSpace(input.Resolution)); resolution == "1080p" {
|
||||
return media.Job{}, fmt.Errorf("参考图视频 resolution 最高 720p")
|
||||
}
|
||||
}
|
||||
if len(input.Prompt) == 0 && !hasImage && !hasRefs && !hasRefAudio {
|
||||
return media.Job{}, fmt.Errorf("文本生视频必须提供 prompt;图片生视频可以省略 prompt")
|
||||
}
|
||||
if strings.TrimSpace(input.VideoURL) != "" {
|
||||
return media.Job{}, fmt.Errorf("视频生成不支持 video 输入")
|
||||
}
|
||||
if err := validateVideoReferenceAudios(input.ReferenceAudios); err != nil {
|
||||
return media.Job{}, err
|
||||
}
|
||||
} else {
|
||||
if strings.TrimSpace(input.Prompt) == "" {
|
||||
return media.Job{}, fmt.Errorf("视频编辑/延长必须提供 prompt")
|
||||
}
|
||||
if strings.TrimSpace(input.VideoURL) == "" {
|
||||
return media.Job{}, fmt.Errorf("视频编辑/延长必须提供 video")
|
||||
}
|
||||
if strings.TrimSpace(input.ImageURL) != "" || len(input.ReferenceURLs) > 0 || len(input.ReferenceAudios) > 0 {
|
||||
return media.Job{}, fmt.Errorf("视频编辑/延长不支持 image、reference_images 或 reference_audios")
|
||||
}
|
||||
if operation == provider.VideoOperationEdit && input.Duration != 0 {
|
||||
return media.Job{}, fmt.Errorf("视频编辑不支持 duration")
|
||||
}
|
||||
if operation == provider.VideoOperationExtend {
|
||||
if input.Duration == 0 {
|
||||
input.Duration = 6
|
||||
}
|
||||
if input.Duration < 2 || input.Duration > 10 {
|
||||
return media.Job{}, fmt.Errorf("视频延长 duration 必须在 2 到 10 秒之间")
|
||||
}
|
||||
}
|
||||
}
|
||||
allRefs := videoInputReferences(input.ImageURL, input.ReferenceURLs)
|
||||
if err := s.validateVideoInputReferences(ctx, allRefs, "image"); err != nil {
|
||||
return media.Job{}, err
|
||||
}
|
||||
inputJSON, err := encodeVideoInput(input.ReferenceURLs)
|
||||
if videoURL := strings.TrimSpace(input.VideoURL); videoURL != "" {
|
||||
if err := s.validateVideoInputReferences(ctx, []string{videoURL}, "video"); err != nil {
|
||||
return media.Job{}, err
|
||||
}
|
||||
}
|
||||
inputJSON, err := encodeVideoInputFull(operation, input.ImageURL, input.ReferenceURLs, input.ReferenceAudios, input.VideoURL)
|
||||
if err != nil {
|
||||
return media.Job{}, err
|
||||
}
|
||||
@@ -68,19 +138,28 @@ func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job,
|
||||
if err != nil {
|
||||
return media.Job{}, ErrModelNotFound
|
||||
}
|
||||
route, err := s.selectMediaRoute(routes, input.ClientKey, model.CapabilityVideo, func(providerValue account.Provider) bool {
|
||||
routes, err = routesForVideoOperation(routes, operation)
|
||||
if err != nil {
|
||||
return media.Job{}, err
|
||||
}
|
||||
route, selection, err := s.selectSchedulableMediaRouteWithQuotaMode(ctx, routes, input.ClientKey, model.CapabilityVideo, true, func(providerValue account.Provider) bool {
|
||||
_, ok := s.providers.Videos(providerValue)
|
||||
return ok
|
||||
}, func(route model.Route) string {
|
||||
return videoQuotaMode(route.Provider, s.providers.QuotaMode(route.Provider, route.UpstreamModel), input.Resolution)
|
||||
})
|
||||
if err != nil {
|
||||
return media.Job{}, err
|
||||
}
|
||||
if err := validateVideoRouteParameters(operation, route.UpstreamModel, input.Resolution, len(input.ReferenceURLs) > 0); err != nil {
|
||||
return media.Job{}, err
|
||||
}
|
||||
if err := s.checkLedgerReady(); err != nil {
|
||||
return media.Job{}, err
|
||||
}
|
||||
pricing, priced := resolveVideoPricing(operation, route.UpstreamModel, input.Resolution, input.Duration, len(allRefs))
|
||||
externalModel := model.ExternalPublicID(route.Provider, route.PublicID)
|
||||
quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel)
|
||||
lease, err := s.selector.AcquireForKey(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", nil, false, input.ClientKey.AccountScope())
|
||||
lease, err := selection.Acquire(ctx, nil, false)
|
||||
if err != nil {
|
||||
return media.Job{}, fmt.Errorf("%w: %w", ErrNoAvailableAccount, err)
|
||||
}
|
||||
@@ -95,12 +174,12 @@ func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job,
|
||||
ID: "video_" + token, RequestID: input.RequestID,
|
||||
ClientKeyID: input.ClientKey.ID, ClientKeyName: input.ClientKey.Name,
|
||||
AccountID: accountID, AccountName: lease.Credential.Name,
|
||||
Provider: string(route.Provider), Model: externalModel, ModelRouteID: route.ID, UpstreamModel: model.DisplayUpstreamModel(route.Provider, route.UpstreamModel), Prompt: input.Prompt,
|
||||
Provider: string(route.Provider), Model: externalModel, ModelRouteID: route.ID, UpstreamModel: model.DisplayUpstreamModel(route.Provider, route.UpstreamModel), Operation: operation, Prompt: input.Prompt,
|
||||
Seconds: input.Duration, Size: input.AspectRatio, Quality: input.Resolution,
|
||||
Status: media.StatusQueued, Progress: 0, InputJSON: inputJSON, InputImageCount: len(input.ReferenceURLs), CreatedAt: now, UpdatedAt: now,
|
||||
Status: media.StatusQueued, Progress: 0, InputJSON: inputJSON, InputImageCount: len(allRefs), CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
reserved := false
|
||||
if pricing, ok := audit.EstimateOfficialVideoCost(externalModel, input.Resolution, input.Duration); ok {
|
||||
if priced {
|
||||
reserved, err = s.clientKeys.ReserveBilling(ctx, input.ClientKey, "video_usage_"+job.ID, pricing.CostInUSDTicks, mediaBillingReservationTTL)
|
||||
if err != nil {
|
||||
return media.Job{}, err
|
||||
@@ -118,6 +197,42 @@ func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job,
|
||||
return job, nil
|
||||
}
|
||||
|
||||
func validateVideoRouteParameters(operation provider.VideoOperation, upstreamModel, resolution string, hasReferences bool) error {
|
||||
if operation != provider.VideoOperationGenerate || !strings.EqualFold(strings.TrimSpace(resolution), "1080p") {
|
||||
return nil
|
||||
}
|
||||
if strings.TrimSpace(upstreamModel) != "grok-imagine-video-1.5" {
|
||||
return fmt.Errorf("%w: %s 不支持 1080p", ErrVideoOperationUnsupported, upstreamModel)
|
||||
}
|
||||
if hasReferences {
|
||||
return fmt.Errorf("%w: reference_images 模式最高支持 720p", ErrVideoOperationUnsupported)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func routesForVideoOperation(routes []model.Route, operation provider.VideoOperation) ([]model.Route, error) {
|
||||
if operation == provider.VideoOperationGenerate {
|
||||
return routes, nil
|
||||
}
|
||||
compatible := make([]model.Route, 0, len(routes))
|
||||
for _, candidate := range routes {
|
||||
if candidate.Provider == account.ProviderConsole && strings.TrimSpace(candidate.UpstreamModel) == "grok-imagine-video" {
|
||||
compatible = append(compatible, candidate)
|
||||
}
|
||||
}
|
||||
if len(compatible) == 0 {
|
||||
return nil, ErrVideoOperationUnsupported
|
||||
}
|
||||
return compatible, nil
|
||||
}
|
||||
|
||||
func resolveVideoPricing(operation provider.VideoOperation, upstreamModel, resolution string, duration, inputImages int) (audit.PricingResult, bool) {
|
||||
if operation == provider.VideoOperationGenerate {
|
||||
return audit.EstimateOfficialVideoCost(upstreamModel, resolution, duration, inputImages)
|
||||
}
|
||||
return audit.PricingResult{}, false
|
||||
}
|
||||
|
||||
func (s *Service) GetVideo(ctx context.Context, id string, key clientkey.Key) (media.Job, error) {
|
||||
if s.mediaJobs == nil {
|
||||
return media.Job{}, ErrResponseNotFound
|
||||
@@ -311,7 +426,8 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model
|
||||
defer releaseInputSlot()
|
||||
// 视频任务创建时已持久化账号归属;恢复只能重新获取原账号,禁止因后续
|
||||
// 轮询或结果处理失败切换到其他账号。
|
||||
quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel)
|
||||
quotaMode := videoQuotaMode(route.Provider, s.providers.QuotaMode(route.Provider, route.UpstreamModel), job.Quality)
|
||||
quotaRefreshGroup := s.providers.QuotaRefreshGroup(route.Provider, route.UpstreamModel)
|
||||
lease, err := s.selector.AcquirePinned(ctx, route.Provider, job.AccountID, route.ID, route.UpstreamModel, quotaMode, true)
|
||||
if err != nil {
|
||||
if parent.Err() != nil {
|
||||
@@ -333,15 +449,30 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model
|
||||
s.failVideoJob(parent, job, "provider_unavailable", ErrNoAvailableAccount)
|
||||
return
|
||||
}
|
||||
referenceURLs, err := s.resolveVideoInputReferences(ctx, inputReferences)
|
||||
operation := provider.VideoOperation(job.Operation)
|
||||
if operation == "" {
|
||||
operation = decodeVideoOperation(job.InputJSON)
|
||||
}
|
||||
imageURL, referenceURLs, referenceAudios, videoURL, err := s.resolveVideoJobInputs(ctx, operation, job.InputJSON)
|
||||
if err != nil {
|
||||
s.failVideoJob(parent, job, "input_unavailable", err)
|
||||
return
|
||||
}
|
||||
lastProgress := job.Progress
|
||||
duration := job.Seconds
|
||||
aspectRatio := job.Size
|
||||
resolution := job.Quality
|
||||
switch operation {
|
||||
case provider.VideoOperationEdit:
|
||||
duration, aspectRatio, resolution = 0, "", ""
|
||||
case provider.VideoOperationExtend:
|
||||
aspectRatio, resolution = "", ""
|
||||
}
|
||||
result, err := adapter.GenerateVideo(ctx, provider.VideoRequest{
|
||||
Credential: lease.Credential, Billing: lease.Billing, JobID: job.ID, Prompt: job.Prompt, Duration: job.Seconds, AspectRatio: job.Size, Resolution: job.Quality,
|
||||
ReferenceURLs: referenceURLs,
|
||||
Credential: lease.Credential, Billing: lease.Billing, JobID: job.ID, Model: route.UpstreamModel,
|
||||
Operation: operation,
|
||||
Prompt: job.Prompt, Duration: duration, AspectRatio: aspectRatio, Resolution: resolution,
|
||||
ImageURL: imageURL, ReferenceURLs: referenceURLs, ReferenceAudios: referenceAudios, VideoURL: videoURL,
|
||||
Progress: func(value int) {
|
||||
value = min(99, max(1, value))
|
||||
if value-lastProgress < 5 {
|
||||
@@ -433,26 +564,42 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model
|
||||
return
|
||||
}
|
||||
s.selector.MarkSuccess(context.Background(), lease.Credential)
|
||||
if lease.QuotaMode != "" && lease.QuotaMode != "weekly" {
|
||||
refreshMode := lease.QuotaMode
|
||||
decrementMode := lease.QuotaMode
|
||||
if quotaRefreshGroup != "" {
|
||||
refreshMode = quotaRefreshGroup
|
||||
decrementMode = quotaMode
|
||||
}
|
||||
if decrementMode != "" && decrementMode != "weekly" {
|
||||
quotaCtx, quotaCancel := context.WithTimeout(context.Background(), accountStateWriteTimeout)
|
||||
updated, quotaErr := s.accounts.DecrementQuota(quotaCtx, job.AccountID, lease.QuotaMode, 1)
|
||||
updated, quotaErr := s.accounts.DecrementQuota(quotaCtx, job.AccountID, decrementMode, 1)
|
||||
quotaCancel()
|
||||
if quotaErr != nil {
|
||||
s.logger.Warn("video_quota_decrement_failed", "provider", route.Provider, "account_id", job.AccountID, "mode", lease.QuotaMode, "error", quotaErr)
|
||||
s.logger.Warn("video_quota_decrement_failed", "provider", route.Provider, "account_id", job.AccountID, "mode", decrementMode, "error", quotaErr)
|
||||
} else if updated {
|
||||
s.selector.ConsumeQuota(route.Provider, job.AccountID, lease.QuotaMode, 1)
|
||||
s.selector.ConsumeQuota(route.Provider, job.AccountID, decrementMode, 1)
|
||||
}
|
||||
}
|
||||
if err := s.recordVideoAudit(context.Background(), job, time.Since(startedAt).Milliseconds()); err != nil {
|
||||
s.logger.Error("video_usage_record_failed", "job_id", job.ID, "event_id", "video_usage_"+job.ID, "error", err)
|
||||
}
|
||||
if quotaKind, _ := s.providers.QuotaKind(route.Provider); quotaKind == provider.QuotaRemoteWindow && lease.QuotaMode != "" {
|
||||
s.accounts.QueueQuotaRefresh(job.AccountID, lease.QuotaMode)
|
||||
if quotaKind, _ := s.providers.QuotaKind(route.Provider); quotaKind == provider.QuotaRemoteWindow && refreshMode != "" {
|
||||
s.accounts.QueueQuotaRefresh(job.AccountID, refreshMode)
|
||||
}
|
||||
// 输入回收放在账号状态、计费和审计收尾之后,存储抖动不得延迟关键终态逻辑。
|
||||
s.releaseVideoInputs(job)
|
||||
}
|
||||
|
||||
func videoQuotaMode(providerValue account.Provider, catalogMode, resolution string) string {
|
||||
if providerValue == account.ProviderWeb && catalogMode == account.QuotaModeWebVideo {
|
||||
resolution = strings.ToLower(strings.TrimSpace(resolution))
|
||||
if resolution == "" || resolution == "720p" {
|
||||
return account.QuotaModeWebVideo720p
|
||||
}
|
||||
}
|
||||
return catalogMode
|
||||
}
|
||||
|
||||
func (s *Service) acquireVideoInputSlot(ctx context.Context, references []string) (func(), error) {
|
||||
hasLocalInput := false
|
||||
for _, reference := range references {
|
||||
@@ -473,7 +620,7 @@ func (s *Service) acquireVideoInputSlot(ctx context.Context, references []string
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) validateVideoInputReferences(ctx context.Context, references []string) error {
|
||||
func (s *Service) validateVideoInputReferences(ctx context.Context, references []string, expectedKind string) error {
|
||||
estimatedBytes := videoInputJSONBaseBytes
|
||||
for _, reference := range references {
|
||||
fileID, local := media.ParseInputReference(reference)
|
||||
@@ -486,11 +633,14 @@ func (s *Service) validateVideoInputReferences(ctx context.Context, references [
|
||||
if s.mediaAssets == nil || !local {
|
||||
return ErrVideoInputUnavailable
|
||||
}
|
||||
asset, body, err := s.mediaAssets.OpenInputImage(ctx, fileID)
|
||||
asset, body, err := s.mediaAssets.OpenInputAsset(ctx, fileID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrVideoInputUnavailable, err)
|
||||
}
|
||||
_ = body.Close()
|
||||
if asset.Kind != expectedKind {
|
||||
return fmt.Errorf("%w: file_id 必须引用%s", ErrVideoInputUnavailable, expectedKind)
|
||||
}
|
||||
if !addVideoReferenceBytes(&estimatedBytes, materializedVideoReferenceBytes(asset.MIMEType, asset.SizeBytes)) {
|
||||
return ErrVideoInputTooLarge
|
||||
}
|
||||
@@ -498,7 +648,38 @@ func (s *Service) validateVideoInputReferences(ctx context.Context, references [
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) resolveVideoInputReferences(ctx context.Context, references []string) ([]string, error) {
|
||||
func (s *Service) resolveVideoInputParts(ctx context.Context, inputJSON string) (string, []string, error) {
|
||||
imageURL, referenceURLs := decodeVideoInputParts(inputJSON)
|
||||
all := videoInputReferences(imageURL, referenceURLs)
|
||||
resolved, err := s.resolveVideoInputReferences(ctx, all, "image")
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
// Map resolved URLs back while preserving empty/non-empty slots by original order.
|
||||
next := 0
|
||||
take := func(original string) string {
|
||||
original = strings.TrimSpace(original)
|
||||
if original == "" {
|
||||
return ""
|
||||
}
|
||||
if next >= len(resolved) {
|
||||
return original
|
||||
}
|
||||
value := resolved[next]
|
||||
next++
|
||||
return value
|
||||
}
|
||||
outImage := take(imageURL)
|
||||
outRefs := make([]string, 0, len(referenceURLs))
|
||||
for _, raw := range referenceURLs {
|
||||
if value := take(raw); value != "" {
|
||||
outRefs = append(outRefs, value)
|
||||
}
|
||||
}
|
||||
return outImage, outRefs, nil
|
||||
}
|
||||
|
||||
func (s *Service) resolveVideoInputReferences(ctx context.Context, references []string, expectedKind string) ([]string, error) {
|
||||
resolved := make([]string, 0, len(references))
|
||||
estimatedBytes := videoInputJSONBaseBytes
|
||||
for _, reference := range references {
|
||||
@@ -513,10 +694,14 @@ func (s *Service) resolveVideoInputReferences(ctx context.Context, references []
|
||||
if s.mediaAssets == nil || !local {
|
||||
return nil, ErrVideoInputUnavailable
|
||||
}
|
||||
asset, body, err := s.mediaAssets.OpenInputImage(ctx, fileID)
|
||||
asset, body, err := s.mediaAssets.OpenInputAsset(ctx, fileID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrVideoInputUnavailable, err)
|
||||
}
|
||||
if asset.Kind != expectedKind {
|
||||
_ = body.Close()
|
||||
return nil, fmt.Errorf("%w: file_id 必须引用%s", ErrVideoInputUnavailable, expectedKind)
|
||||
}
|
||||
data, readErr := io.ReadAll(io.LimitReader(body, media.MaxInputJSONBytes+1))
|
||||
closeErr := body.Close()
|
||||
if readErr != nil {
|
||||
@@ -649,10 +834,14 @@ func (s *Service) recordVideoAudit(ctx context.Context, job media.Job, durationM
|
||||
MediaInputImages: int64(job.InputImageCount),
|
||||
DurationMS: durationMS, CreatedAt: createdAt,
|
||||
}
|
||||
if job.Status == media.StatusCompleted {
|
||||
if job.Status == media.StatusCompleted && job.Seconds > 0 {
|
||||
record.MediaOutputSeconds = int64(max(0, job.Seconds))
|
||||
}
|
||||
if pricing, ok := audit.EstimateOfficialVideoCost(job.Model, job.Quality, job.Seconds); ok && job.Status == media.StatusCompleted {
|
||||
operation := provider.VideoOperation(job.Operation)
|
||||
if operation == "" {
|
||||
operation = provider.VideoOperationGenerate
|
||||
}
|
||||
if pricing, ok := audit.EstimateOfficialVideoCost(job.UpstreamModel, job.Quality, job.Seconds, job.InputImageCount); ok && job.Status == media.StatusCompleted && operation == provider.VideoOperationGenerate {
|
||||
record.EstimatedCostInUSDTicks = pricing.CostInUSDTicks
|
||||
record.PricingModel = pricing.Model
|
||||
record.PricingVersion = audit.OfficialPricingAsOf
|
||||
@@ -671,8 +860,44 @@ func (s *Service) recordVideoAudit(ctx context.Context, job media.Job, durationM
|
||||
return s.mediaJobs.MarkMediaJobUsageRecorded(markCtx, job.ID, time.Now().UTC())
|
||||
}
|
||||
|
||||
func encodeVideoInput(referenceURLs []string) (string, error) {
|
||||
data, err := json.Marshal(map[string][]string{"image_urls": referenceURLs})
|
||||
func encodeVideoInput(imageURL string, referenceURLs []string) (string, error) {
|
||||
return encodeVideoInputFull(provider.VideoOperationGenerate, imageURL, referenceURLs, nil, "")
|
||||
}
|
||||
|
||||
func encodeVideoInputFull(operation provider.VideoOperation, imageURL string, referenceURLs []string, referenceAudios []string, videoURL string) (string, error) {
|
||||
payload := map[string]any{}
|
||||
if operation == "" {
|
||||
operation = provider.VideoOperationGenerate
|
||||
}
|
||||
if operation != provider.VideoOperationGenerate {
|
||||
payload["operation"] = string(operation)
|
||||
}
|
||||
if value := strings.TrimSpace(imageURL); value != "" {
|
||||
payload["image_url"] = value
|
||||
}
|
||||
refs := make([]string, 0, len(referenceURLs))
|
||||
for _, raw := range referenceURLs {
|
||||
if value := strings.TrimSpace(raw); value != "" {
|
||||
refs = append(refs, value)
|
||||
}
|
||||
}
|
||||
if len(refs) > 0 {
|
||||
payload["reference_urls"] = refs
|
||||
}
|
||||
audios := normalizeVideoReferenceAudios(referenceAudios)
|
||||
if len(audios) > 0 {
|
||||
payload["reference_audios"] = audios
|
||||
}
|
||||
if value := strings.TrimSpace(videoURL); value != "" {
|
||||
payload["video_url"] = value
|
||||
}
|
||||
// Keep a combined image_urls field for older readers/tools that only
|
||||
// understand the pre-split shape. New workers prefer image_url/reference_urls.
|
||||
combined := videoInputReferences(imageURL, referenceURLs)
|
||||
if len(combined) > 0 {
|
||||
payload["image_urls"] = combined
|
||||
}
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("编码视频输入: %w", err)
|
||||
}
|
||||
@@ -683,9 +908,133 @@ func encodeVideoInput(referenceURLs []string) (string, error) {
|
||||
}
|
||||
|
||||
func decodeVideoInput(value string) []string {
|
||||
var input map[string][]string
|
||||
imageURL, refs, videoURL := decodeVideoInputFull(value)
|
||||
values := videoInputReferences(imageURL, refs)
|
||||
if v := strings.TrimSpace(videoURL); v != "" {
|
||||
values = append(values, v)
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func decodeVideoInputParts(value string) (string, []string) {
|
||||
imageURL, refs, _ := decodeVideoInputFull(value)
|
||||
return imageURL, refs
|
||||
}
|
||||
|
||||
func decodeVideoInputFull(value string) (string, []string, string) {
|
||||
imageURL, refs, _, videoURL := decodeVideoInputDetailed(value)
|
||||
return imageURL, refs, videoURL
|
||||
}
|
||||
|
||||
func decodeVideoInputDetailed(value string) (string, []string, []string, string) {
|
||||
var input struct {
|
||||
Operation string `json:"operation"`
|
||||
ImageURL string `json:"image_url"`
|
||||
ReferenceURLs []string `json:"reference_urls"`
|
||||
ReferenceAudios []string `json:"reference_audios"`
|
||||
ImageURLs []string `json:"image_urls"`
|
||||
VideoURL string `json:"video_url"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(value), &input)
|
||||
return input["image_urls"]
|
||||
videoURL := strings.TrimSpace(input.VideoURL)
|
||||
audios := normalizeVideoReferenceAudios(input.ReferenceAudios)
|
||||
if strings.TrimSpace(input.ImageURL) != "" || len(input.ReferenceURLs) > 0 || len(audios) > 0 || videoURL != "" || strings.TrimSpace(input.Operation) != "" {
|
||||
refs := make([]string, 0, len(input.ReferenceURLs))
|
||||
for _, raw := range input.ReferenceURLs {
|
||||
if v := strings.TrimSpace(raw); v != "" {
|
||||
refs = append(refs, v)
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(input.ImageURL), refs, audios, videoURL
|
||||
}
|
||||
// Legacy jobs stored a flat image_urls list. Preserve historical mapping:
|
||||
// one URL was treated as the first-frame image; multiple URLs were references.
|
||||
legacy := make([]string, 0, len(input.ImageURLs))
|
||||
for _, raw := range input.ImageURLs {
|
||||
if v := strings.TrimSpace(raw); v != "" {
|
||||
legacy = append(legacy, v)
|
||||
}
|
||||
}
|
||||
switch len(legacy) {
|
||||
case 0:
|
||||
return "", nil, nil, ""
|
||||
case 1:
|
||||
return legacy[0], nil, nil, ""
|
||||
default:
|
||||
return "", legacy, nil, ""
|
||||
}
|
||||
}
|
||||
|
||||
func decodeVideoOperation(value string) provider.VideoOperation {
|
||||
var input struct {
|
||||
Operation string `json:"operation"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(value), &input)
|
||||
switch provider.VideoOperation(strings.TrimSpace(input.Operation)) {
|
||||
case provider.VideoOperationEdit:
|
||||
return provider.VideoOperationEdit
|
||||
case provider.VideoOperationExtend:
|
||||
return provider.VideoOperationExtend
|
||||
default:
|
||||
return provider.VideoOperationGenerate
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) resolveVideoJobInputs(ctx context.Context, operation provider.VideoOperation, inputJSON string) (string, []string, []string, string, error) {
|
||||
_, _, referenceAudios, videoURL := decodeVideoInputDetailed(inputJSON)
|
||||
resolvedImage, resolvedRefs, err := s.resolveVideoInputParts(ctx, inputJSON)
|
||||
if err != nil {
|
||||
return "", nil, nil, "", err
|
||||
}
|
||||
if strings.TrimSpace(videoURL) == "" {
|
||||
return resolvedImage, resolvedRefs, referenceAudios, "", nil
|
||||
}
|
||||
if operation == provider.VideoOperationGenerate {
|
||||
return "", nil, nil, "", ErrVideoInputUnavailable
|
||||
}
|
||||
resolvedVideos, err := s.resolveVideoInputReferences(ctx, []string{videoURL}, "video")
|
||||
if err != nil {
|
||||
return "", nil, nil, "", err
|
||||
}
|
||||
if len(resolvedVideos) == 0 {
|
||||
return "", nil, nil, "", ErrVideoInputUnavailable
|
||||
}
|
||||
return resolvedImage, resolvedRefs, referenceAudios, resolvedVideos[0], nil
|
||||
}
|
||||
|
||||
func validateVideoReferenceAudios(values []string) error {
|
||||
if len(values) > 3 {
|
||||
return fmt.Errorf("reference_audios 最多 3 个")
|
||||
}
|
||||
for _, raw := range values {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return fmt.Errorf("reference_audios.voice_id 不能为空")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeVideoReferenceAudios(values []string) []string {
|
||||
out := make([]string, 0, len(values))
|
||||
for _, raw := range values {
|
||||
if value := strings.TrimSpace(raw); value != "" {
|
||||
out = append(out, value)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func videoInputReferences(imageURL string, referenceURLs []string) []string {
|
||||
values := make([]string, 0, 1+len(referenceURLs))
|
||||
if v := strings.TrimSpace(imageURL); v != "" {
|
||||
values = append(values, v)
|
||||
}
|
||||
for _, raw := range referenceURLs {
|
||||
if v := strings.TrimSpace(raw); v != "" {
|
||||
values = append(values, v)
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func (s *Service) failVideoJob(ctx context.Context, job media.Job, code string, err error) {
|
||||
@@ -716,7 +1065,7 @@ func (s *Service) releaseVideoInputs(job media.Job) {
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := s.mediaAssets.ReleaseInputImages(ctx, references); err != nil {
|
||||
if err := s.mediaAssets.ReleaseInputAssets(ctx, references); err != nil {
|
||||
logger := s.logger
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
|
||||
@@ -16,16 +16,35 @@ import (
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/audit"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/media"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
)
|
||||
|
||||
func TestVideoQuotaModeUsesWeb720pProduct(t *testing.T) {
|
||||
tests := []struct {
|
||||
provider account.Provider
|
||||
resolution string
|
||||
want string
|
||||
}{
|
||||
{account.ProviderWeb, "", account.QuotaModeWebVideo720p},
|
||||
{account.ProviderWeb, "720p", account.QuotaModeWebVideo720p},
|
||||
{account.ProviderWeb, "480p", account.QuotaModeWebVideo},
|
||||
{account.ProviderConsole, "720p", account.QuotaModeWebVideo},
|
||||
}
|
||||
for _, test := range tests {
|
||||
if got := videoQuotaMode(test.provider, account.QuotaModeWebVideo, test.resolution); got != test.want {
|
||||
t.Fatalf("videoQuotaMode(%s, %q) = %q, want %q", test.provider, test.resolution, got, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoverVideoJobsRetriesUsageWithoutRegeneratingVideo(t *testing.T) {
|
||||
completedAt := time.Now().UTC()
|
||||
repository := &videoUsageRepository{job: media.Job{
|
||||
ID: "video_usage_recovery", RequestID: "request-usage-recovery",
|
||||
ClientKeyID: 1, ClientKeyName: "client", AccountID: 2, AccountName: "account",
|
||||
Provider: "grok_web", Model: "grok-imagine-video", ModelRouteID: 3, UpstreamModel: "video",
|
||||
Provider: "grok_web", Model: "custom-video", ModelRouteID: 3, UpstreamModel: "Web/grok-imagine-video",
|
||||
Seconds: 8, Quality: "720p", Status: media.StatusCompleted, InputImageCount: 2, CreatedAt: completedAt.Add(-time.Minute), CompletedAt: &completedAt,
|
||||
}}
|
||||
recorder := &durableVideoAuditRecorder{failures: 1}
|
||||
@@ -47,18 +66,135 @@ func TestRecoverVideoJobsRetriesUsageWithoutRegeneratingVideo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeVideoInputEnforcesPersistedLimit(t *testing.T) {
|
||||
overhead := len(`{"image_urls":[""]}`)
|
||||
atLimit := strings.Repeat("A", media.MaxInputJSONBytes-overhead)
|
||||
encoded, err := encodeVideoInput([]string{atLimit})
|
||||
if err != nil || len(encoded) != media.MaxInputJSONBytes {
|
||||
t.Fatalf("encoded len=%d err=%v", len(encoded), err)
|
||||
func TestVideoEditRouteUsesResolvedUpstreamInsteadOfPublicName(t *testing.T) {
|
||||
routes := []model.Route{
|
||||
{ID: 1, PublicID: "grok-imagine-video", Provider: account.ProviderBuild, UpstreamModel: "grok-imagine-video"},
|
||||
{ID: 2, PublicID: "company-video-editor", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-video"},
|
||||
{ID: 3, PublicID: "company-video-editor", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-video-1.5"},
|
||||
}
|
||||
if _, err := encodeVideoInput([]string{atLimit + "A"}); !errors.Is(err, ErrVideoInputTooLarge) {
|
||||
compatible, err := routesForVideoOperation(routes, provider.VideoOperationEdit)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(compatible) != 1 || compatible[0].ID != 2 {
|
||||
t.Fatalf("compatible routes = %#v", compatible)
|
||||
}
|
||||
if _, err := routesForVideoOperation(routes[:1], provider.VideoOperationExtend); !errors.Is(err, ErrVideoOperationUnsupported) {
|
||||
t.Fatalf("unsupported route error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVideoPricingLeavesUnmeasurableOperationsUnpriced(t *testing.T) {
|
||||
pricing, priced := resolveVideoPricing(provider.VideoOperationGenerate, "Console/grok-imagine-video", "720p", 6, 1)
|
||||
if !priced || pricing.CostInUSDTicks <= 0 {
|
||||
t.Fatalf("priced generation = %#v, priced=%v", pricing, priced)
|
||||
}
|
||||
if pricing, priced := resolveVideoPricing(provider.VideoOperationGenerate, "Console/grok-imagine-video", "", 6, 0); priced || pricing.CostInUSDTicks != 0 {
|
||||
t.Fatalf("generation without resolution = %#v, priced=%v", pricing, priced)
|
||||
}
|
||||
if pricing, priced := resolveVideoPricing(provider.VideoOperationExtend, "Console/grok-imagine-video", "", 6, 0); priced || pricing.CostInUSDTicks != 0 {
|
||||
t.Fatalf("extension without measurable input duration = %#v, priced=%v", pricing, priced)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVideo1080pValidationUsesResolvedUpstreamModel(t *testing.T) {
|
||||
if err := validateVideoRouteParameters(provider.VideoOperationGenerate, "grok-imagine-video-1.5", "1080P", false); err != nil {
|
||||
t.Fatalf("1.5 text/image 1080p rejected: %v", err)
|
||||
}
|
||||
if err := validateVideoRouteParameters(provider.VideoOperationGenerate, "grok-imagine-video", "1080p", false); !errors.Is(err, ErrVideoOperationUnsupported) {
|
||||
t.Fatalf("legacy 1080p error = %v", err)
|
||||
}
|
||||
if err := validateVideoRouteParameters(provider.VideoOperationGenerate, "grok-imagine-video-1.5", "1080p", true); !errors.Is(err, ErrVideoOperationUnsupported) {
|
||||
t.Fatalf("reference 1080p error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeVideoInputEnforcesPersistedLimit(t *testing.T) {
|
||||
// image_url and combined image_urls both store the same value, so the URL is counted twice.
|
||||
base := `{"image_url":"","image_urls":[""]}`
|
||||
overhead := len(base)
|
||||
urlLen := (media.MaxInputJSONBytes - overhead) / 2
|
||||
atLimit := strings.Repeat("A", urlLen)
|
||||
encoded, err := encodeVideoInput(atLimit, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("encode at limit: %v", err)
|
||||
}
|
||||
if len(encoded) > media.MaxInputJSONBytes {
|
||||
t.Fatalf("encoded len=%d exceeds limit", len(encoded))
|
||||
}
|
||||
if _, err := encodeVideoInput(atLimit+"AA", nil); !errors.Is(err, ErrVideoInputTooLarge) {
|
||||
t.Fatalf("oversized input error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeDecodeVideoInputPreservesImageAndReferences(t *testing.T) {
|
||||
encoded, err := encodeVideoInput("https://example.com/first.png", []string{"https://example.com/ref.png"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
imageURL, refs := decodeVideoInputParts(encoded)
|
||||
if imageURL != "https://example.com/first.png" || len(refs) != 1 || refs[0] != "https://example.com/ref.png" {
|
||||
t.Fatalf("decoded split = %q %#v from %s", imageURL, refs, encoded)
|
||||
}
|
||||
|
||||
encoded, err = encodeVideoInput("", []string{"https://example.com/ref-only.png"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
imageURL, refs = decodeVideoInputParts(encoded)
|
||||
if imageURL != "" || len(refs) != 1 || refs[0] != "https://example.com/ref-only.png" {
|
||||
t.Fatalf("single reference decoded = %q %#v from %s", imageURL, refs, encoded)
|
||||
}
|
||||
|
||||
imageURL, refs = decodeVideoInputParts(`{"image_urls":["https://legacy/one.png"]}`)
|
||||
if imageURL != "https://legacy/one.png" || len(refs) != 0 {
|
||||
t.Fatalf("legacy single = %q %#v", imageURL, refs)
|
||||
}
|
||||
imageURL, refs = decodeVideoInputParts(`{"image_urls":["https://legacy/a.png","https://legacy/b.png"]}`)
|
||||
if imageURL != "" || len(refs) != 2 || refs[0] != "https://legacy/a.png" || refs[1] != "https://legacy/b.png" {
|
||||
t.Fatalf("legacy multi = %q %#v", imageURL, refs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeDecodeVideoInputPreservesOperationAndReferenceAudio(t *testing.T) {
|
||||
encoded, err := encodeVideoInputFull(
|
||||
provider.VideoOperationGenerate,
|
||||
"",
|
||||
[]string{"https://example.com/ref.png"},
|
||||
[]string{"eve", " ara "},
|
||||
"",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
imageURL, refs, audios, videoURL := decodeVideoInputDetailed(encoded)
|
||||
if imageURL != "" || videoURL != "" || len(refs) != 1 || refs[0] != "https://example.com/ref.png" || len(audios) != 2 || audios[0] != "eve" || audios[1] != "ara" {
|
||||
t.Fatalf("decoded reference input = image %q refs %#v audios %#v video %q from %s", imageURL, refs, audios, videoURL, encoded)
|
||||
}
|
||||
if operation := decodeVideoOperation(encoded); operation != provider.VideoOperationGenerate {
|
||||
t.Fatalf("generation operation = %q", operation)
|
||||
}
|
||||
|
||||
encoded, err = encodeVideoInputFull(provider.VideoOperationExtend, "", nil, nil, media.InputReference("source-video"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if operation := decodeVideoOperation(encoded); operation != provider.VideoOperationExtend {
|
||||
t.Fatalf("extension operation = %q from %s", operation, encoded)
|
||||
}
|
||||
_, _, _, videoURL = decodeVideoInputDetailed(encoded)
|
||||
if videoURL != media.InputReference("source-video") {
|
||||
t.Fatalf("extension video = %q", videoURL)
|
||||
}
|
||||
|
||||
if err := validateVideoReferenceAudios([]string{"eve", ""}); err == nil {
|
||||
t.Fatal("blank reference voice was accepted")
|
||||
}
|
||||
if err := validateVideoReferenceAudios([]string{"a", "b", "c", "d"}); err == nil {
|
||||
t.Fatal("too many reference voices were accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoverVideoJobsRecordsFailedAuditWithEgress(t *testing.T) {
|
||||
completedAt := time.Now().UTC()
|
||||
nodeID := uint64(42)
|
||||
@@ -181,10 +317,13 @@ func TestResolveVideoInputFileReferenceToDataURI(t *testing.T) {
|
||||
store := &videoAssetStoreStub{inputID: inputID, inputData: raw}
|
||||
service := &Service{mediaAssets: store}
|
||||
reference := VideoInputFileReference(inputID)
|
||||
if err := service.validateVideoInputReferences(context.Background(), []string{reference}); err != nil {
|
||||
if err := service.validateVideoInputReferences(context.Background(), []string{reference}, "image"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resolved, err := service.resolveVideoInputReferences(context.Background(), []string{"https://example.com/a.png", reference})
|
||||
if err := service.validateVideoInputReferences(context.Background(), []string{reference}, "video"); !errors.Is(err, ErrVideoInputUnavailable) {
|
||||
t.Fatalf("image accepted as video input: %v", err)
|
||||
}
|
||||
resolved, err := service.resolveVideoInputReferences(context.Background(), []string{"https://example.com/a.png", reference}, "image")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -192,11 +331,11 @@ func TestResolveVideoInputFileReferenceToDataURI(t *testing.T) {
|
||||
if len(resolved) != 2 || resolved[0] != "https://example.com/a.png" || resolved[1] != want {
|
||||
t.Fatalf("resolved=%#v", resolved)
|
||||
}
|
||||
if err := service.validateVideoInputReferences(context.Background(), []string{VideoInputFileReference("missing")}); !errors.Is(err, ErrVideoInputUnavailable) {
|
||||
if err := service.validateVideoInputReferences(context.Background(), []string{VideoInputFileReference("missing")}, "image"); !errors.Is(err, ErrVideoInputUnavailable) {
|
||||
t.Fatalf("missing input error=%v", err)
|
||||
}
|
||||
store.inputSize = 20 << 20
|
||||
if err := service.validateVideoInputReferences(context.Background(), []string{reference, reference}); !errors.Is(err, ErrVideoInputTooLarge) {
|
||||
if err := service.validateVideoInputReferences(context.Background(), []string{reference, reference}, "image"); !errors.Is(err, ErrVideoInputTooLarge) {
|
||||
t.Fatalf("aggregate local input error=%v", err)
|
||||
}
|
||||
}
|
||||
@@ -257,6 +396,8 @@ type videoAssetStoreStub struct {
|
||||
inputID string
|
||||
inputData []byte
|
||||
inputSize int64
|
||||
inputKind string
|
||||
inputMIME string
|
||||
}
|
||||
|
||||
func (s *videoAssetStoreStub) SaveVideo(_ context.Context, jobID, contentType string, body io.Reader) (media.Asset, error) {
|
||||
@@ -278,7 +419,7 @@ func (*videoAssetStoreStub) OpenVideo(context.Context, string) (media.Asset, io.
|
||||
return media.Asset{}, nil, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (s *videoAssetStoreStub) OpenInputImage(_ context.Context, id string) (media.Asset, io.ReadCloser, error) {
|
||||
func (s *videoAssetStoreStub) OpenInputAsset(_ context.Context, id string) (media.Asset, io.ReadCloser, error) {
|
||||
if id != s.inputID || len(s.inputData) == 0 {
|
||||
return media.Asset{}, nil, errors.New("not implemented")
|
||||
}
|
||||
@@ -286,10 +427,18 @@ func (s *videoAssetStoreStub) OpenInputImage(_ context.Context, id string) (medi
|
||||
if size <= 0 {
|
||||
size = int64(len(s.inputData))
|
||||
}
|
||||
return media.Asset{ID: id, Kind: "image", MIMEType: "image/png", SizeBytes: size}, io.NopCloser(bytes.NewReader(s.inputData)), nil
|
||||
kind := s.inputKind
|
||||
if kind == "" {
|
||||
kind = "image"
|
||||
}
|
||||
mimeType := s.inputMIME
|
||||
if mimeType == "" {
|
||||
mimeType = "image/png"
|
||||
}
|
||||
return media.Asset{ID: id, Kind: kind, MIMEType: mimeType, SizeBytes: size}, io.NopCloser(bytes.NewReader(s.inputData)), nil
|
||||
}
|
||||
|
||||
func (*videoAssetStoreStub) ReleaseInputImages(context.Context, []string) error { return nil }
|
||||
func (*videoAssetStoreStub) ReleaseInputAssets(context.Context, []string) error { return nil }
|
||||
|
||||
type durableVideoAuditRecorder struct {
|
||||
failures int
|
||||
|
||||
@@ -0,0 +1,543 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/audit"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/clientkey"
|
||||
modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
)
|
||||
|
||||
type TTSInput struct {
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
Text string
|
||||
VoiceID string
|
||||
Language string
|
||||
OutputFormat provider.TTSOutputFormat
|
||||
Speed float64
|
||||
OptimizeStreamingLatency int
|
||||
TextNormalization bool
|
||||
WithTimestamps bool
|
||||
}
|
||||
|
||||
type STTInput struct {
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
FileName string
|
||||
FileMIME string
|
||||
FileData []byte
|
||||
URL string
|
||||
AudioFormat string
|
||||
SampleRate string
|
||||
Language string
|
||||
Format bool
|
||||
Multichannel bool
|
||||
Channels int
|
||||
Diarize bool
|
||||
KeyTerms []string
|
||||
FillerWords bool
|
||||
VADThreshold *float64
|
||||
// ResponseFormat is empty for the native Console-compatible response, or an
|
||||
// OpenAI-compatible format normalized by the HTTP transport.
|
||||
ResponseFormat string
|
||||
}
|
||||
|
||||
type VoiceListInput struct {
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
}
|
||||
|
||||
type VoiceIDInput struct {
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
VoiceID string
|
||||
}
|
||||
|
||||
type voiceProviderSupport func(accountdomain.Provider) bool
|
||||
|
||||
type voiceExecutionResult struct {
|
||||
response *provider.Response
|
||||
pricing audit.PricingResult
|
||||
}
|
||||
|
||||
func (s *Service) SynthesizeSpeech(ctx context.Context, input TTSInput) (*Result, error) {
|
||||
reservation, _ := audit.EstimateOfficialTTSCost(input.Text)
|
||||
return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationTTS, modeldomain.CapabilityTTS, true, reservation, func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.TTS(providerValue)
|
||||
return ok
|
||||
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, upstream string) (voiceExecutionResult, error) {
|
||||
adapter, ok := s.providers.TTS(providerValue)
|
||||
if !ok {
|
||||
return voiceExecutionResult{}, ErrNoAvailableAccount
|
||||
}
|
||||
result, err := adapter.SynthesizeSpeech(executionCtx, provider.TTSRequest{
|
||||
Credential: credential, Model: upstream, Text: input.Text, VoiceID: input.VoiceID, Language: input.Language,
|
||||
OutputFormat: input.OutputFormat, Speed: input.Speed, OptimizeStreamingLatency: input.OptimizeStreamingLatency,
|
||||
TextNormalization: input.TextNormalization, WithTimestamps: input.WithTimestamps,
|
||||
})
|
||||
if err != nil {
|
||||
return voiceExecutionResult{}, err
|
||||
}
|
||||
if result.JSONEnvelope || input.WithTimestamps {
|
||||
payload := map[string]any{
|
||||
"audio": firstNonEmpty(result.Base64Audio, base64.StdEncoding.EncodeToString(result.Audio)),
|
||||
"content_type": firstNonEmpty(result.ContentType, "audio/mpeg"),
|
||||
"duration": result.Duration,
|
||||
}
|
||||
if result.Timestamps != nil {
|
||||
times := make([]map[string]any, 0, len(result.Timestamps.GraphTimes))
|
||||
for _, item := range result.Timestamps.GraphTimes {
|
||||
times = append(times, map[string]any{"start": item.Start, "end": item.End})
|
||||
}
|
||||
payload["audio_timestamps"] = map[string]any{"graph_chars": result.Timestamps.GraphChars, "graph_times": times}
|
||||
}
|
||||
return voiceExecutionResult{response: jsonVoiceResponse(http.StatusOK, payload), pricing: reservation}, nil
|
||||
}
|
||||
header := http.Header{}
|
||||
header.Set("Content-Type", firstNonEmpty(result.ContentType, "audio/mpeg"))
|
||||
header.Set("Content-Length", fmt.Sprintf("%d", len(result.Audio)))
|
||||
return voiceExecutionResult{response: &provider.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Status: fmt.Sprintf("%d %s", http.StatusOK, http.StatusText(http.StatusOK)),
|
||||
Header: header,
|
||||
Body: io.NopCloser(bytes.NewReader(result.Audio)),
|
||||
QuotaUnits: 1,
|
||||
}, pricing: reservation}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) ListTTSVoices(ctx context.Context, input VoiceListInput) (*Result, error) {
|
||||
return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationTTS, modeldomain.CapabilityTTS, false, audit.PricingResult{}, func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.TTS(providerValue)
|
||||
return ok
|
||||
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (voiceExecutionResult, error) {
|
||||
adapter, ok := s.providers.TTS(providerValue)
|
||||
if !ok {
|
||||
return voiceExecutionResult{}, ErrNoAvailableAccount
|
||||
}
|
||||
voices, err := adapter.ListTTSVoices(executionCtx, credential)
|
||||
if err != nil {
|
||||
return voiceExecutionResult{}, err
|
||||
}
|
||||
items := make([]map[string]any, 0, len(voices))
|
||||
for _, voice := range voices {
|
||||
item := map[string]any{"voice_id": voice.VoiceID, "name": voice.Name}
|
||||
if voice.Language != "" {
|
||||
item["language"] = voice.Language
|
||||
} else {
|
||||
item["language"] = nil
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
response := jsonVoiceResponse(http.StatusOK, map[string]any{"voices": items})
|
||||
response.QuotaUnits = 0
|
||||
return voiceExecutionResult{response: response}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) GetTTSVoice(ctx context.Context, input VoiceIDInput) (*Result, error) {
|
||||
return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationTTS, modeldomain.CapabilityTTS, false, audit.PricingResult{}, func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.TTS(providerValue)
|
||||
return ok
|
||||
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (voiceExecutionResult, error) {
|
||||
adapter, ok := s.providers.TTS(providerValue)
|
||||
if !ok {
|
||||
return voiceExecutionResult{}, ErrNoAvailableAccount
|
||||
}
|
||||
voice, err := adapter.GetTTSVoice(executionCtx, credential, input.VoiceID)
|
||||
if err != nil {
|
||||
return voiceExecutionResult{}, err
|
||||
}
|
||||
payload := map[string]any{"voice_id": voice.VoiceID, "name": voice.Name}
|
||||
if voice.Language != "" {
|
||||
payload["language"] = voice.Language
|
||||
} else {
|
||||
payload["language"] = nil
|
||||
}
|
||||
response := jsonVoiceResponse(http.StatusOK, payload)
|
||||
response.QuotaUnits = 0
|
||||
return voiceExecutionResult{response: response}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) TranscribeSpeech(ctx context.Context, input STTInput) (*Result, error) {
|
||||
return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationSTT, modeldomain.CapabilitySTT, true, audit.PricingResult{}, func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.STT(providerValue)
|
||||
return ok
|
||||
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, upstream string) (voiceExecutionResult, error) {
|
||||
adapter, ok := s.providers.STT(providerValue)
|
||||
if !ok {
|
||||
return voiceExecutionResult{}, ErrNoAvailableAccount
|
||||
}
|
||||
result, err := adapter.TranscribeSpeech(executionCtx, provider.STTRequest{
|
||||
Credential: credential, Model: upstream, FileName: input.FileName, FileMIME: input.FileMIME, FileData: input.FileData,
|
||||
URL: input.URL, AudioFormat: input.AudioFormat, SampleRate: input.SampleRate, Language: input.Language, Format: input.Format,
|
||||
Multichannel: input.Multichannel, Channels: input.Channels, Diarize: input.Diarize, KeyTerms: input.KeyTerms,
|
||||
FillerWords: input.FillerWords, VADThreshold: input.VADThreshold,
|
||||
})
|
||||
if err != nil {
|
||||
return voiceExecutionResult{}, err
|
||||
}
|
||||
pricing, _ := audit.EstimateOfficialSTTCost(result.Duration, false)
|
||||
return voiceExecutionResult{response: formatSTTResponse(result, input.ResponseFormat), pricing: pricing}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func formatSTTResponse(result provider.STTResult, responseFormat string) *provider.Response {
|
||||
switch responseFormat {
|
||||
case "text":
|
||||
data := []byte(result.Text)
|
||||
header := http.Header{}
|
||||
header.Set("Content-Type", "text/plain; charset=utf-8")
|
||||
header.Set("Content-Length", strconv.Itoa(len(data)))
|
||||
return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(data)), QuotaUnits: 1}
|
||||
case "json":
|
||||
return jsonVoiceResponse(http.StatusOK, map[string]any{"text": result.Text})
|
||||
case "verbose_json":
|
||||
payload := map[string]any{"task": "transcribe", "text": result.Text, "language": result.Language, "duration": result.Duration}
|
||||
if len(result.Words) > 0 {
|
||||
words := make([]map[string]any, 0, len(result.Words))
|
||||
for _, word := range result.Words {
|
||||
item := map[string]any{"word": word.Text, "start": word.Start, "end": word.End}
|
||||
if word.Speaker != nil {
|
||||
item["speaker"] = *word.Speaker
|
||||
}
|
||||
words = append(words, item)
|
||||
}
|
||||
payload["words"] = words
|
||||
}
|
||||
return jsonVoiceResponse(http.StatusOK, payload)
|
||||
}
|
||||
if len(result.RawJSON) > 0 {
|
||||
header := http.Header{}
|
||||
header.Set("Content-Type", "application/json")
|
||||
header.Set("Content-Length", strconv.Itoa(len(result.RawJSON)))
|
||||
return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(result.RawJSON)), QuotaUnits: 1}
|
||||
}
|
||||
payload := map[string]any{"text": result.Text, "language": result.Language, "duration": result.Duration}
|
||||
if len(result.Words) > 0 {
|
||||
words := make([]map[string]any, 0, len(result.Words))
|
||||
for _, word := range result.Words {
|
||||
item := map[string]any{"text": word.Text, "start": word.Start, "end": word.End}
|
||||
if word.Speaker != nil {
|
||||
item["speaker"] = *word.Speaker
|
||||
}
|
||||
words = append(words, item)
|
||||
}
|
||||
payload["words"] = words
|
||||
}
|
||||
if len(result.Channels) > 0 {
|
||||
channels := make([]map[string]any, 0, len(result.Channels))
|
||||
for _, channel := range result.Channels {
|
||||
item := map[string]any{"index": channel.Index, "text": channel.Text}
|
||||
if len(channel.Words) > 0 {
|
||||
words := make([]map[string]any, 0, len(channel.Words))
|
||||
for _, word := range channel.Words {
|
||||
wordItem := map[string]any{"text": word.Text, "start": word.Start, "end": word.End}
|
||||
if word.Speaker != nil {
|
||||
wordItem["speaker"] = *word.Speaker
|
||||
}
|
||||
words = append(words, wordItem)
|
||||
}
|
||||
item["words"] = words
|
||||
}
|
||||
channels = append(channels, item)
|
||||
}
|
||||
payload["channels"] = channels
|
||||
}
|
||||
return jsonVoiceResponse(http.StatusOK, payload)
|
||||
}
|
||||
|
||||
func (s *Service) executeVoice(
|
||||
ctx context.Context,
|
||||
requestID string,
|
||||
key clientkey.Key,
|
||||
publicModel string,
|
||||
operation audit.Operation,
|
||||
capability modeldomain.Capability,
|
||||
consumesQuota bool,
|
||||
reservation audit.PricingResult,
|
||||
supports voiceProviderSupport,
|
||||
execute func(context.Context, accountdomain.Provider, accountdomain.Credential, string) (voiceExecutionResult, error),
|
||||
) (*Result, error) {
|
||||
ctx, egressTrace := infraegress.WithTrace(ctx)
|
||||
startedAt := time.Now()
|
||||
eventID := newAuditEventID()
|
||||
routes, err := s.models.GetByPublicIDCandidates(ctx, publicModel)
|
||||
if err != nil {
|
||||
return nil, ErrModelNotFound
|
||||
}
|
||||
route, preselectedSession, err := s.selectSchedulableMediaRoute(ctx, routes, key, capability, consumesQuota, supports)
|
||||
if err != nil {
|
||||
// Keep selection failures observable in request audits when no same-name
|
||||
// target is schedulable; capability/scope failures still return directly.
|
||||
route, err = s.selectMediaRoute(routes, key, capability, supports)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
preselectedSession = nil
|
||||
}
|
||||
externalModel := modeldomain.ExternalPublicID(route.Provider, route.PublicID)
|
||||
auditBase := audit.Record{
|
||||
EventID: eventID, RequestID: requestID, ClientKeyID: key.ID, ClientKeyName: key.Name,
|
||||
ModelRouteID: route.ID, ModelPublicID: externalModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel),
|
||||
Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone,
|
||||
}
|
||||
if err := s.checkLedgerReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if reservation.CostInUSDTicks > 0 {
|
||||
if _, err := s.clientKeys.ReserveBilling(ctx, key, eventID, reservation.CostInUSDTicks, mediaBillingReservationTTL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
writeFailureAudit := func(statusCode int, errorCode string, credential *accountdomain.Credential) {
|
||||
record := auditBase
|
||||
record.StatusCode = statusCode
|
||||
record.ErrorCode = errorCode
|
||||
record.DurationMS = time.Since(startedAt).Milliseconds()
|
||||
record.CreatedAt = time.Now().UTC()
|
||||
if credential != nil {
|
||||
accountID := credential.ID
|
||||
record.AccountID = &accountID
|
||||
record.AccountName = credential.Name
|
||||
}
|
||||
applyAuditEgress(&record, egressTrace, route.Provider)
|
||||
persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout)
|
||||
defer cancel()
|
||||
if auditErr := s.audits.Create(persistCtx, record); auditErr != nil {
|
||||
s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", requestID, "error", auditErr)
|
||||
}
|
||||
}
|
||||
quotaMode := ""
|
||||
if consumesQuota {
|
||||
quotaMode = s.providers.QuotaMode(route.Provider, route.UpstreamModel)
|
||||
}
|
||||
attemptPolicy := newRoutingAttemptPolicy(int(s.maxAttempts.Load()))
|
||||
excluded := make(map[uint64]bool)
|
||||
selection := preselectedSession
|
||||
var lease *accountLease
|
||||
var credential accountdomain.Credential
|
||||
var response *provider.Response
|
||||
var completedPricing audit.PricingResult
|
||||
var responseRequestScoped bool
|
||||
var lastCredentialFailure *accountdomain.Credential
|
||||
var lastCredentialError error
|
||||
for attempt := 0; attemptPolicy.allows(attempt); attempt++ {
|
||||
if selection == nil {
|
||||
selection, err = s.selector.beginSelectionSessionForKey(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", excluded, false, key.AccountScope())
|
||||
}
|
||||
if err == nil {
|
||||
lease, err = selection.Acquire(ctx, excluded, false)
|
||||
}
|
||||
if err != nil {
|
||||
errorCode := "upstream_unavailable"
|
||||
var selectionFailure *SelectionUnavailableError
|
||||
if errors.As(err, &selectionFailure) {
|
||||
errorCode = selectionFailure.Code()
|
||||
}
|
||||
writeFailureAudit(http.StatusServiceUnavailable, errorCode, lastCredentialFailure)
|
||||
return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, err)
|
||||
}
|
||||
excluded[lease.Credential.ID] = true
|
||||
credential, err = s.accounts.EnsureCredential(ctx, lease.Credential, false)
|
||||
if err != nil {
|
||||
failedCredential := lease.Credential
|
||||
lastCredentialFailure = &failedCredential
|
||||
lastCredentialError = err
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
lease.markSelectorUpstreamStarted()
|
||||
responseRequestScoped = false
|
||||
execution, executionErr := execute(ctx, route.Provider, credential, route.UpstreamModel)
|
||||
response, completedPricing, err = execution.response, execution.pricing, executionErr
|
||||
if err != nil {
|
||||
if _, ok := provider.ErrorHTTPStatus(err); ok {
|
||||
responseRequestScoped = provider.IsRequestScopedError(err)
|
||||
response, err = voiceErrorResponse(err)
|
||||
} else if isSSOCredentialRejected(err, credential) {
|
||||
s.markSSOCredentialRejected(ctx, credential, fmt.Sprintf("%s SSO credential rejected", credential.Provider))
|
||||
failedCredential := credential
|
||||
lastCredentialFailure = &failedCredential
|
||||
lastCredentialError = provider.ErrUnauthorized
|
||||
lease.Release()
|
||||
continue
|
||||
} else {
|
||||
failure := newTransportUpstreamFailure(err, credential.ID, credential.Name)
|
||||
lastCredentialError = failure
|
||||
if ctx.Err() == nil && isRetryableTransportFailure(credential.Provider, err) && attemptPolicy.hasNext(attempt) {
|
||||
// Transport failures are normally tied to the selected egress. Retry the
|
||||
// same account after the adapter has invalidated/rebuilt that transport,
|
||||
// without cooling an otherwise healthy credential.
|
||||
delete(excluded, credential.ID)
|
||||
if selection != nil {
|
||||
selection.RetryAccount(credential.ID)
|
||||
}
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
lease.Release()
|
||||
writeFailureAudit(failure.HTTPStatus, failure.AuditCode(), &credential)
|
||||
return nil, failure
|
||||
}
|
||||
if err != nil {
|
||||
lease.Release()
|
||||
writeFailureAudit(http.StatusBadGateway, "upstream_unavailable", &credential)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if response.StatusCode == http.StatusUnauthorized && credential.AuthType == accountdomain.AuthTypeSSO {
|
||||
_, _ = readRetryableBody(response.Body)
|
||||
s.markSSOCredentialRejected(ctx, credential, fmt.Sprintf("%s SSO credential rejected", credential.Provider))
|
||||
failedCredential := credential
|
||||
lastCredentialFailure = &failedCredential
|
||||
lastCredentialError = provider.ErrUnauthorized
|
||||
response = nil
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
if s.providers.RetryForbiddenAsEgress(credential.Provider) && response.StatusCode == http.StatusForbidden && !responseRequestScoped && attempt == 0 && attemptPolicy.hasNext(attempt) {
|
||||
_, _ = readRetryableBody(response.Body)
|
||||
delete(excluded, credential.ID)
|
||||
if selection != nil {
|
||||
selection.RetryAccount(credential.ID)
|
||||
}
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
if response.StatusCode == http.StatusPaymentRequired || response.StatusCode == http.StatusTooManyRequests {
|
||||
retryAfter := parseRetryAfter(response.Header.Get("Retry-After"), time.Now().UTC())
|
||||
if quotaKind, _ := s.providers.QuotaKind(credential.Provider); quotaKind == provider.QuotaRemoteWindow && lease.QuotaMode != "" {
|
||||
exhausted, reconcileErr := s.accounts.ReconcileRateLimit(ctx, credential.ID, lease.QuotaMode, retryAfter)
|
||||
s.selector.MarkQuotaStateChanged(credential.Provider, credential.ID)
|
||||
if reconcileErr != nil || !exhausted {
|
||||
s.selector.MarkFailure(ctx, credential, response.StatusCode, retryAfter)
|
||||
}
|
||||
} else {
|
||||
s.selector.MarkFailure(ctx, credential, response.StatusCode, retryAfter)
|
||||
}
|
||||
if attemptPolicy.hasNext(attempt) {
|
||||
_, _ = readRetryableBody(response.Body)
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
}
|
||||
if response.StatusCode >= http.StatusInternalServerError && attemptPolicy.hasNext(attempt) {
|
||||
_, _ = readRetryableBody(response.Body)
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
if response == nil {
|
||||
writeFailureAudit(http.StatusServiceUnavailable, "upstream_unavailable", lastCredentialFailure)
|
||||
if lastCredentialError == nil {
|
||||
lastCredentialError = ErrNoAvailableAccount
|
||||
}
|
||||
return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, lastCredentialError)
|
||||
}
|
||||
accountID := credential.ID
|
||||
var once sync.Once
|
||||
finalize := func(_ Usage, _ string, errorCode string) {
|
||||
once.Do(func() {
|
||||
successful := auditRequestSucceeded(response.StatusCode, errorCode)
|
||||
lease.completeSelectorObservation(successful)
|
||||
lease.Release()
|
||||
budget := newFinalizationBudget(string(operation), string(route.Provider))
|
||||
record := auditBase
|
||||
record.AccountID, record.AccountName, record.StatusCode = &accountID, credential.Name, response.StatusCode
|
||||
record.ErrorCode = errorCode
|
||||
record.DurationMS, record.CreatedAt = time.Since(startedAt).Milliseconds(), time.Now().UTC()
|
||||
applyAuditEgress(&record, egressTrace, route.Provider)
|
||||
if successful && completedPricing.CostInUSDTicks > 0 {
|
||||
record.EstimatedCostInUSDTicks = completedPricing.CostInUSDTicks
|
||||
record.PricingModel = completedPricing.Model
|
||||
record.PricingVersion = audit.OfficialPricingAsOf
|
||||
}
|
||||
if successful && response.QuotaUnits > 0 && quotaMode != "" && quotaMode != "weekly" {
|
||||
units := response.QuotaUnits
|
||||
var updated bool
|
||||
err := budget.run("quota_decrement", finalizationQuotaBudget, func(stageCtx context.Context) error {
|
||||
var decrementErr error
|
||||
updated, decrementErr = s.accounts.DecrementQuota(stageCtx, accountID, quotaMode, units)
|
||||
return decrementErr
|
||||
})
|
||||
if err != nil {
|
||||
s.logger.Warn("voice_quota_decrement_failed", "provider", route.Provider, "account_id", accountID, "mode", quotaMode, "units", units, "error", err)
|
||||
} else if updated {
|
||||
s.selector.ConsumeQuota(route.Provider, accountID, quotaMode, units)
|
||||
}
|
||||
}
|
||||
if successful && response.QuotaUnits > 0 && quotaMode != "" {
|
||||
if quotaKind, _ := s.providers.QuotaKind(route.Provider); quotaKind == provider.QuotaRemoteWindow {
|
||||
s.accounts.QueueQuotaRefresh(accountID, quotaMode)
|
||||
}
|
||||
}
|
||||
if err := budget.run("audit", finalizationAuditBudget, func(stageCtx context.Context) error {
|
||||
return s.audits.Create(stageCtx, record)
|
||||
}); err != nil {
|
||||
s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", requestID, "error", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
return &Result{StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, Body: &finalizingBody{ReadCloser: response.Body, finalize: func() { finalize(Usage{}, "", "stream_closed") }}, Finalize: finalize}, nil
|
||||
}
|
||||
|
||||
func jsonVoiceResponse(status int, value any) *provider.Response {
|
||||
data, _ := json.Marshal(value)
|
||||
header := http.Header{}
|
||||
header.Set("Content-Type", "application/json")
|
||||
header.Set("Content-Length", fmt.Sprintf("%d", len(data)))
|
||||
return &provider.Response{
|
||||
StatusCode: status,
|
||||
Status: fmt.Sprintf("%d %s", status, http.StatusText(status)),
|
||||
Header: header,
|
||||
Body: io.NopCloser(bytes.NewReader(data)),
|
||||
QuotaUnits: 1,
|
||||
}
|
||||
}
|
||||
|
||||
func voiceErrorResponse(err error) (*provider.Response, error) {
|
||||
if status, ok := provider.ErrorHTTPStatus(err); ok {
|
||||
message, safe := provider.ErrorPublicMessage(err)
|
||||
if !safe {
|
||||
message = "上游语音服务返回错误"
|
||||
}
|
||||
response := jsonVoiceResponse(status, map[string]any{"error": map[string]any{"type": "upstream_error", "message": message}})
|
||||
if retryAfter := provider.ErrorRetryAfter(err); retryAfter > 0 {
|
||||
seconds := max(int64(1), int64((retryAfter+time.Second-1)/time.Second))
|
||||
response.Header.Set("Retry-After", strconv.FormatInt(seconds, 10))
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/audit"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/clientkey"
|
||||
modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
)
|
||||
|
||||
type VoiceWebSocketInput struct {
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
// Path is one of /realtime or /stt.
|
||||
Path string
|
||||
}
|
||||
|
||||
type VoiceWebSocketSession struct {
|
||||
Conn provider.VoiceWebSocketConn
|
||||
Finalize func(VoiceWebSocketOutcome)
|
||||
RequestID string
|
||||
PublicModel string
|
||||
Provider accountdomain.Provider
|
||||
AccountID uint64
|
||||
AccountName string
|
||||
Operation audit.Operation
|
||||
Capability modeldomain.Capability
|
||||
}
|
||||
|
||||
type VoiceWebSocketOutcome struct {
|
||||
ErrorCode string
|
||||
UpstreamFailed bool
|
||||
AudioDurationSeconds float64
|
||||
}
|
||||
|
||||
// OpenVoiceWebSocket selects a Console account and dials the upstream voice websocket.
|
||||
func (s *Service) OpenVoiceWebSocket(ctx context.Context, input VoiceWebSocketInput) (*VoiceWebSocketSession, error) {
|
||||
pathValue := strings.TrimSpace(input.Path)
|
||||
capability, operation, defaultModel, err := voiceWebSocketRoute(pathValue)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
publicModel := strings.TrimSpace(input.PublicModel)
|
||||
if publicModel == "" {
|
||||
publicModel = defaultModel
|
||||
}
|
||||
|
||||
ctx, egressTrace := infraegress.WithTrace(ctx)
|
||||
startedAt := time.Now()
|
||||
eventID := newAuditEventID()
|
||||
|
||||
routes, err := s.models.GetByPublicIDCandidates(ctx, publicModel)
|
||||
if err != nil {
|
||||
return nil, ErrModelNotFound
|
||||
}
|
||||
supportsVoiceWebSocket := func(providerValue accountdomain.Provider) bool {
|
||||
_, ok := s.providers.VoiceWebSocket(providerValue)
|
||||
return ok
|
||||
}
|
||||
route, preselectedSession, err := s.selectSchedulableMediaRoute(ctx, routes, input.ClientKey, capability, true, supportsVoiceWebSocket)
|
||||
if err != nil {
|
||||
// Preserve selection-failure audits when every eligible target is cooling
|
||||
// or exhausted. The regular request loop will reproduce the error.
|
||||
route, err = s.selectMediaRoute(routes, input.ClientKey, capability, supportsVoiceWebSocket)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
preselectedSession = nil
|
||||
}
|
||||
externalModel := modeldomain.ExternalPublicID(route.Provider, route.PublicID)
|
||||
auditBase := audit.Record{
|
||||
EventID: eventID, RequestID: input.RequestID, ClientKeyID: input.ClientKey.ID, ClientKeyName: input.ClientKey.Name,
|
||||
ModelRouteID: route.ID, ModelPublicID: externalModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel),
|
||||
Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone, Streaming: true,
|
||||
}
|
||||
if err := s.checkLedgerReady(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel)
|
||||
attemptPolicy := newRoutingAttemptPolicy(int(s.maxAttempts.Load()))
|
||||
excluded := make(map[uint64]bool)
|
||||
selection := preselectedSession
|
||||
var lease *accountLease
|
||||
var credential accountdomain.Credential
|
||||
var lastCredentialFailure *accountdomain.Credential
|
||||
var lastErr error
|
||||
|
||||
writeFailureAudit := func(statusCode int, errorCode string, cred *accountdomain.Credential) {
|
||||
record := auditBase
|
||||
record.StatusCode = statusCode
|
||||
record.ErrorCode = errorCode
|
||||
record.DurationMS = time.Since(startedAt).Milliseconds()
|
||||
record.CreatedAt = time.Now().UTC()
|
||||
if cred != nil {
|
||||
accountID := cred.ID
|
||||
record.AccountID = &accountID
|
||||
record.AccountName = cred.Name
|
||||
}
|
||||
applyAuditEgress(&record, egressTrace, route.Provider)
|
||||
persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout)
|
||||
defer cancel()
|
||||
if auditErr := s.audits.Create(persistCtx, record); auditErr != nil {
|
||||
s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", input.RequestID, "error", auditErr)
|
||||
}
|
||||
}
|
||||
|
||||
for attempt := 0; attemptPolicy.allows(attempt); attempt++ {
|
||||
if selection == nil {
|
||||
selection, err = s.selector.beginSelectionSessionForKey(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", excluded, false, input.ClientKey.AccountScope())
|
||||
}
|
||||
if err == nil {
|
||||
lease, err = selection.Acquire(ctx, excluded, false)
|
||||
}
|
||||
if err != nil {
|
||||
errorCode := "upstream_unavailable"
|
||||
var selectionFailure *SelectionUnavailableError
|
||||
if errors.As(err, &selectionFailure) {
|
||||
errorCode = selectionFailure.Code()
|
||||
}
|
||||
writeFailureAudit(http.StatusServiceUnavailable, errorCode, lastCredentialFailure)
|
||||
return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, err)
|
||||
}
|
||||
excluded[lease.Credential.ID] = true
|
||||
credential, err = s.accounts.EnsureCredential(ctx, lease.Credential, false)
|
||||
if err != nil {
|
||||
failed := lease.Credential
|
||||
lastCredentialFailure = &failed
|
||||
lastErr = err
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
adapter, ok := s.providers.VoiceWebSocket(route.Provider)
|
||||
if !ok {
|
||||
lease.Release()
|
||||
writeFailureAudit(http.StatusBadGateway, "upstream_unavailable", &credential)
|
||||
return nil, ErrNoAvailableAccount
|
||||
}
|
||||
lease.markSelectorUpstreamStarted()
|
||||
conn, cleanup, dialErr := adapter.DialVoiceWebSocket(ctx, provider.VoiceWebSocketRequest{
|
||||
Credential: credential,
|
||||
Path: pathValue,
|
||||
Model: route.UpstreamModel,
|
||||
})
|
||||
if dialErr != nil {
|
||||
if cleanup != nil {
|
||||
cleanup()
|
||||
}
|
||||
if status, ok := provider.ErrorHTTPStatus(dialErr); ok {
|
||||
failure := newHTTPUpstreamFailure(status, nil, credential.ID, credential.Name)
|
||||
failure.RequestScopedForbidden = provider.IsRequestScopedError(dialErr)
|
||||
failure.RetryAfter = provider.ErrorRetryAfter(dialErr)
|
||||
failure.Cause = dialErr
|
||||
lastErr = failure
|
||||
switch {
|
||||
case status == http.StatusUnauthorized && credential.AuthType == accountdomain.AuthTypeSSO:
|
||||
s.markSSOCredentialRejected(ctx, credential, fmt.Sprintf("%s SSO credential rejected", credential.Provider))
|
||||
failed := credential
|
||||
lastCredentialFailure = &failed
|
||||
lease.Release()
|
||||
continue
|
||||
case status == http.StatusForbidden && s.providers.RetryForbiddenAsEgress(credential.Provider) && !failure.RequestScopedForbidden && attempt == 0 && attemptPolicy.hasNext(attempt):
|
||||
delete(excluded, credential.ID)
|
||||
if selection != nil {
|
||||
selection.RetryAccount(credential.ID)
|
||||
}
|
||||
lease.Release()
|
||||
continue
|
||||
case status == http.StatusPaymentRequired || status == http.StatusTooManyRequests:
|
||||
if quotaKind, _ := s.providers.QuotaKind(credential.Provider); quotaKind == provider.QuotaRemoteWindow && lease.QuotaMode != "" {
|
||||
exhausted, reconcileErr := s.accounts.ReconcileRateLimit(ctx, credential.ID, lease.QuotaMode, failure.RetryAfter)
|
||||
s.selector.MarkQuotaStateChanged(credential.Provider, credential.ID)
|
||||
if reconcileErr != nil || !exhausted {
|
||||
s.selector.MarkFailure(ctx, credential, status, failure.RetryAfter)
|
||||
}
|
||||
} else {
|
||||
s.selector.MarkFailure(ctx, credential, status, failure.RetryAfter)
|
||||
}
|
||||
if attemptPolicy.hasNext(attempt) {
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
case status >= http.StatusInternalServerError && attemptPolicy.hasNext(attempt):
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
lease.Release()
|
||||
writeFailureAudit(failure.HTTPStatus, failure.AuditCode(), &credential)
|
||||
return nil, failure
|
||||
}
|
||||
|
||||
lastErr = dialErr
|
||||
if isSSOCredentialRejected(dialErr, credential) {
|
||||
s.markSSOCredentialRejected(ctx, credential, fmt.Sprintf("%s SSO credential rejected", credential.Provider))
|
||||
failed := credential
|
||||
lastCredentialFailure = &failed
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
failure := newTransportUpstreamFailure(dialErr, credential.ID, credential.Name)
|
||||
lastErr = failure
|
||||
if ctx.Err() == nil && isRetryableTransportFailure(credential.Provider, dialErr) && attempt == 0 && attemptPolicy.hasNext(attempt) {
|
||||
delete(excluded, credential.ID)
|
||||
if selection != nil {
|
||||
selection.RetryAccount(credential.ID)
|
||||
}
|
||||
lease.Release()
|
||||
continue
|
||||
}
|
||||
lease.Release()
|
||||
writeFailureAudit(failure.HTTPStatus, failure.AuditCode(), &credential)
|
||||
return nil, failure
|
||||
}
|
||||
|
||||
// Keep the account lease until the websocket finishes so scheduling stays consistent.
|
||||
accountLeaseRef := lease
|
||||
accountCredential := credential
|
||||
var finalizeOnce sync.Once
|
||||
finalize := func(outcome VoiceWebSocketOutcome) {
|
||||
finalizeOnce.Do(func() {
|
||||
if cleanup != nil {
|
||||
cleanup()
|
||||
}
|
||||
successful := strings.TrimSpace(outcome.ErrorCode) == ""
|
||||
accountLeaseRef.completeSelectorObservation(!outcome.UpstreamFailed)
|
||||
accountLeaseRef.Release()
|
||||
|
||||
budget := newFinalizationBudget(string(operation), string(route.Provider))
|
||||
accountID := accountCredential.ID
|
||||
if successful && quotaMode != "" && quotaMode != "weekly" {
|
||||
var updated bool
|
||||
err := budget.run("quota_decrement", finalizationQuotaBudget, func(stageCtx context.Context) error {
|
||||
var decrementErr error
|
||||
updated, decrementErr = s.accounts.DecrementQuota(stageCtx, accountID, quotaMode, 1)
|
||||
return decrementErr
|
||||
})
|
||||
if err != nil {
|
||||
s.logger.Warn("voice_quota_decrement_failed", "provider", route.Provider, "account_id", accountID, "mode", quotaMode, "units", 1, "error", err)
|
||||
} else if updated {
|
||||
s.selector.ConsumeQuota(route.Provider, accountID, quotaMode, 1)
|
||||
}
|
||||
}
|
||||
if successful && quotaMode != "" {
|
||||
if quotaKind, _ := s.providers.QuotaKind(route.Provider); quotaKind == provider.QuotaRemoteWindow {
|
||||
s.accounts.QueueQuotaRefresh(accountID, quotaMode)
|
||||
}
|
||||
}
|
||||
|
||||
record := auditBase
|
||||
record.StatusCode, record.ErrorCode = voiceWebSocketAuditOutcome(outcome)
|
||||
record.DurationMS = time.Since(startedAt).Milliseconds()
|
||||
record.CreatedAt = time.Now().UTC()
|
||||
record.AccountID = &accountID
|
||||
record.AccountName = accountCredential.Name
|
||||
applyAuditEgress(&record, egressTrace, route.Provider)
|
||||
if successful && operation == audit.OperationSTT {
|
||||
if pricing, priced := audit.EstimateOfficialSTTCost(outcome.AudioDurationSeconds, true); priced {
|
||||
record.EstimatedCostInUSDTicks = pricing.CostInUSDTicks
|
||||
record.PricingModel = pricing.Model
|
||||
record.PricingVersion = audit.OfficialPricingAsOf
|
||||
}
|
||||
}
|
||||
if auditErr := budget.run("audit", finalizationAuditBudget, func(stageCtx context.Context) error {
|
||||
return s.audits.Create(stageCtx, record)
|
||||
}); auditErr != nil {
|
||||
s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", input.RequestID, "error", auditErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
return &VoiceWebSocketSession{
|
||||
Conn: conn, Finalize: finalize, RequestID: input.RequestID, PublicModel: externalModel,
|
||||
Provider: route.Provider, AccountID: credential.ID, AccountName: credential.Name,
|
||||
Operation: operation, Capability: capability,
|
||||
}, nil
|
||||
}
|
||||
if lastErr != nil {
|
||||
return nil, lastErr
|
||||
}
|
||||
return nil, ErrNoAvailableAccount
|
||||
}
|
||||
|
||||
func voiceWebSocketAuditOutcome(outcome VoiceWebSocketOutcome) (int, string) {
|
||||
errorCode := strings.TrimSpace(outcome.ErrorCode)
|
||||
if errorCode == "" {
|
||||
// Audits store the logical request outcome. The transport handshake remains
|
||||
// HTTP 101, while successful request accounting uses the common 2xx predicate.
|
||||
return http.StatusOK, ""
|
||||
}
|
||||
return http.StatusBadGateway, errorCode
|
||||
}
|
||||
|
||||
func voiceWebSocketRoute(pathValue string) (modeldomain.Capability, audit.Operation, string, error) {
|
||||
switch strings.TrimSpace(pathValue) {
|
||||
case "/realtime":
|
||||
return modeldomain.CapabilityRealtime, audit.OperationRealtime, "grok-voice-latest", nil
|
||||
case "/stt":
|
||||
return modeldomain.CapabilitySTT, audit.OperationSTT, "grok-stt", nil
|
||||
default:
|
||||
return "", "", "", errors.New("不支持的 voice websocket path")
|
||||
}
|
||||
}
|
||||
@@ -28,12 +28,12 @@ var (
|
||||
ErrActiveVideoSelection = errors.New("排队中或生成中的视频任务不能删除")
|
||||
ErrInvalidFilter = errors.New("媒体筛选条件无效")
|
||||
ErrMediaJobsUnavailable = errors.New("视频任务仓储未配置")
|
||||
ErrInputImageNotFound = errors.New("临时输入图片不存在或已过期")
|
||||
ErrInputAssetNotFound = errors.New("临时输入资产不存在或已过期")
|
||||
ErrMediaCapacity = errors.New("媒体存储容量不足")
|
||||
)
|
||||
|
||||
// InputImageTTL 是临时输入的硬保留上限;无论任务状态如何,超过后都可回收。
|
||||
const InputImageTTL = 24 * time.Hour
|
||||
// InputAssetTTL 是临时输入的硬保留上限;无论任务状态如何,超过后都可回收。
|
||||
const InputAssetTTL = 24 * time.Hour
|
||||
|
||||
// Service 负责图片/视频校验、文件落盘和元数据持久化的一致性收口。
|
||||
type Service struct {
|
||||
@@ -112,7 +112,8 @@ func (s *Service) SaveImage(ctx context.Context, data []byte) (mediadomain.Asset
|
||||
// SaveInputImage 保存不会进入图库、不会公开读取并会自动过期的视频输入图片。
|
||||
func (s *Service) SaveInputImage(ctx context.Context, data []byte) (mediadomain.Asset, error) {
|
||||
cfg := s.runtimeConfig()
|
||||
if len(data) == 0 || int64(len(data)) > cfg.MaxImageBytes {
|
||||
inputLimit := min(cfg.MaxImageBytes, int64(mediadomain.MaxInputAssetBytes))
|
||||
if len(data) == 0 || inputLimit <= 0 || int64(len(data)) > inputLimit {
|
||||
return mediadomain.Asset{}, ErrInvalidImage
|
||||
}
|
||||
s.inputSaveMu.Lock()
|
||||
@@ -132,7 +133,7 @@ func (s *Service) SaveInputImage(ctx context.Context, data []byte) (mediadomain.
|
||||
}
|
||||
return mediadomain.Asset{}, ErrMediaCapacity
|
||||
}
|
||||
expiresAt := time.Now().UTC().Add(InputImageTTL)
|
||||
expiresAt := time.Now().UTC().Add(InputAssetTTL)
|
||||
return s.saveImage(ctx, data, &expiresAt, mediadomain.InputAssetIDPrefix)
|
||||
}
|
||||
|
||||
@@ -172,28 +173,28 @@ func (s *Service) saveImage(ctx context.Context, data []byte, expiresAt *time.Ti
|
||||
return asset, nil
|
||||
}
|
||||
|
||||
// OpenInputImage 读取未过期的临时输入;它从不通过公开图片路由暴露。
|
||||
func (s *Service) OpenInputImage(ctx context.Context, id string) (mediadomain.Asset, io.ReadCloser, error) {
|
||||
// OpenInputAsset 读取未过期的临时输入;它从不通过公开媒体路由暴露。
|
||||
func (s *Service) OpenInputAsset(ctx context.Context, id string) (mediadomain.Asset, io.ReadCloser, error) {
|
||||
id = strings.TrimSpace(id)
|
||||
if !mediadomain.IsInputAssetID(id) {
|
||||
return mediadomain.Asset{}, nil, ErrInputImageNotFound
|
||||
return mediadomain.Asset{}, nil, ErrInputAssetNotFound
|
||||
}
|
||||
asset, err := s.assets.GetMediaAsset(ctx, id)
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return mediadomain.Asset{}, nil, ErrInputImageNotFound
|
||||
return mediadomain.Asset{}, nil, ErrInputAssetNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return mediadomain.Asset{}, nil, err
|
||||
}
|
||||
if asset.Kind != "image" || asset.ExpiresAt == nil {
|
||||
return mediadomain.Asset{}, nil, ErrInputImageNotFound
|
||||
if (asset.Kind != "image" && asset.Kind != "video") || asset.ExpiresAt == nil {
|
||||
return mediadomain.Asset{}, nil, ErrInputAssetNotFound
|
||||
}
|
||||
if !asset.ExpiresAt.After(time.Now().UTC()) {
|
||||
return mediadomain.Asset{}, nil, ErrInputImageNotFound
|
||||
return mediadomain.Asset{}, nil, ErrInputAssetNotFound
|
||||
}
|
||||
body, err := s.objects.Open(ctx, asset.StorageKey)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return mediadomain.Asset{}, nil, ErrInputImageNotFound
|
||||
return mediadomain.Asset{}, nil, ErrInputAssetNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return mediadomain.Asset{}, nil, err
|
||||
@@ -201,8 +202,8 @@ func (s *Service) OpenInputImage(ctx context.Context, id string) (mediadomain.As
|
||||
return asset, body, nil
|
||||
}
|
||||
|
||||
// ReleaseInputImages 在任务进入终态后立即回收不再被其他活动任务引用的临时输入。
|
||||
func (s *Service) ReleaseInputImages(ctx context.Context, references []string) error {
|
||||
// ReleaseInputAssets 在任务进入终态后立即回收不再被其他活动任务引用的临时输入。
|
||||
func (s *Service) ReleaseInputAssets(ctx context.Context, references []string) error {
|
||||
seen := make(map[string]struct{}, len(references))
|
||||
for _, reference := range references {
|
||||
id, ok := mediadomain.ParseInputReference(reference)
|
||||
@@ -227,7 +228,7 @@ func (s *Service) ReleaseInputImages(ctx context.Context, references []string) e
|
||||
if getErr != nil {
|
||||
return getErr
|
||||
}
|
||||
if asset.ExpiresAt == nil || asset.Kind != "image" {
|
||||
if asset.ExpiresAt == nil || (asset.Kind != "image" && asset.Kind != "video") {
|
||||
continue
|
||||
}
|
||||
if deleteErr := s.objects.Delete(ctx, asset.StorageKey); deleteErr != nil && !errors.Is(deleteErr, os.ErrNotExist) {
|
||||
|
||||
@@ -98,7 +98,7 @@ func TestTransientInputIsHiddenReadableAndExpires(t *testing.T) {
|
||||
if _, _, openErr := service.OpenImage(ctx, input.ID); !errors.Is(openErr, ErrAssetNotFound) {
|
||||
t.Fatalf("public open error=%v", openErr)
|
||||
}
|
||||
stored, body, err := service.OpenInputImage(ctx, input.ID)
|
||||
stored, body, err := service.OpenInputAsset(ctx, input.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -165,10 +165,10 @@ func TestTransientInputIsHiddenReadableAndExpires(t *testing.T) {
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := service.OpenInputImage(ctx, activeInputID); !errors.Is(err, ErrInputImageNotFound) {
|
||||
if _, _, err := service.OpenInputAsset(ctx, activeInputID); !errors.Is(err, ErrInputAssetNotFound) {
|
||||
t.Fatalf("open active expired input error=%v", err)
|
||||
}
|
||||
if err := service.ReleaseInputImages(ctx, []string{mediadomain.InputReference(activeInputID)}); err != nil {
|
||||
if err := service.ReleaseInputAssets(ctx, []string{mediadomain.InputReference(activeInputID)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := assets.GetMediaAsset(ctx, activeInputID); err != nil {
|
||||
@@ -180,7 +180,7 @@ func TestTransientInputIsHiddenReadableAndExpires(t *testing.T) {
|
||||
if _, err := assets.GetMediaAsset(ctx, activeInputID); !errors.Is(err, repository.ErrNotFound) {
|
||||
t.Fatalf("active expired input metadata error=%v", err)
|
||||
}
|
||||
if err := service.ReleaseInputImages(ctx, []string{mediadomain.InputReference(input.ID)}); err != nil {
|
||||
if err := service.ReleaseInputAssets(ctx, []string{mediadomain.InputReference(input.ID)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := assets.GetMediaAsset(ctx, input.ID); !errors.Is(err, repository.ErrNotFound) {
|
||||
@@ -215,6 +215,18 @@ func TestSaveInputImageReservesCleanupHeadroom(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveInputImageEnforcesSharedInputAssetLimit(t *testing.T) {
|
||||
service := NewService(nil, nil, nil, nil, Config{
|
||||
MaxImageBytes: mediadomain.MaxInputAssetBytes * 2,
|
||||
MaxTotalBytes: mediadomain.MaxInputAssetBytes * 4,
|
||||
})
|
||||
data := make([]byte, mediadomain.MaxInputAssetBytes+1)
|
||||
copy(data, []byte("\x89PNG\r\n\x1a\n"))
|
||||
if _, err := service.SaveInputImage(context.Background(), data); !errors.Is(err, ErrInvalidImage) {
|
||||
t.Fatalf("SaveInputImage oversized error = %v, want ErrInvalidImage", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminDeleteVideoJobsRemovesTerminalJobAssetAndTicket(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "media-video-delete.db"))
|
||||
|
||||
@@ -198,7 +198,7 @@ func (s *Service) ReceiveVideoUpload(ctx context.Context, rawToken string, conte
|
||||
}
|
||||
}()
|
||||
|
||||
asset, err := s.commitStagedVideo(ctx, staged, now)
|
||||
asset, err := s.commitStagedVideo(ctx, staged, now, nil)
|
||||
if err != nil {
|
||||
return mediadomain.Asset{}, err
|
||||
}
|
||||
@@ -240,7 +240,7 @@ func (s *Service) SaveVideo(ctx context.Context, jobID, contentType string, body
|
||||
return mediadomain.Asset{}, err
|
||||
}
|
||||
defer func() { _ = s.objects.AbortVideoUpload(context.WithoutCancel(ctx), staged.TempPath) }()
|
||||
asset, err := s.commitStagedVideo(ctx, staged, time.Now().UTC())
|
||||
asset, err := s.commitStagedVideo(ctx, staged, time.Now().UTC(), nil)
|
||||
if err == nil {
|
||||
saved = true
|
||||
}
|
||||
@@ -294,13 +294,54 @@ func (s *Service) stageVideo(ctx context.Context, id, mimeType string, body io.R
|
||||
return stagedVideo{ID: id, TempPath: tempPath, StorageKey: storageKey, MIMEType: mimeType, SizeBytes: written, SHA256: hex.EncodeToString(hasher.Sum(nil))}, nil
|
||||
}
|
||||
|
||||
func (s *Service) commitStagedVideo(ctx context.Context, staged stagedVideo, createdAt time.Time) (mediadomain.Asset, error) {
|
||||
// SaveInputVideo stores a private, expiring video input for edit/extension jobs.
|
||||
func (s *Service) SaveInputVideo(ctx context.Context, contentType string, body io.Reader) (mediadomain.Asset, error) {
|
||||
mimeType := normalizeVideoMIME(contentType)
|
||||
if mimeType == "" {
|
||||
mimeType = "video/mp4"
|
||||
}
|
||||
if !supportedVideoMIME(mimeType) {
|
||||
return mediadomain.Asset{}, fmt.Errorf("%w: Content-Type 无效", ErrInvalidVideoUpload)
|
||||
}
|
||||
id, err := newAssetID(mediadomain.InputAssetIDPrefix)
|
||||
if err != nil {
|
||||
return mediadomain.Asset{}, err
|
||||
}
|
||||
staged, err := s.stageVideo(ctx, id, mimeType, body, mediadomain.MaxInputAssetBytes)
|
||||
if err != nil {
|
||||
return mediadomain.Asset{}, err
|
||||
}
|
||||
defer func() { _ = s.objects.AbortVideoUpload(context.WithoutCancel(ctx), staged.TempPath) }()
|
||||
|
||||
s.inputSaveMu.Lock()
|
||||
defer s.inputSaveMu.Unlock()
|
||||
cfg := s.runtimeConfig()
|
||||
total, err := s.assets.TotalMediaAssetBytes(ctx)
|
||||
if err != nil {
|
||||
return mediadomain.Asset{}, err
|
||||
}
|
||||
capacityLimit := cleanupThresholdBytes(cfg)
|
||||
if capacityLimit <= 0 || capacityLimit > cfg.MaxTotalBytes {
|
||||
capacityLimit = cfg.MaxTotalBytes
|
||||
}
|
||||
if staged.SizeBytes > capacityLimit || total > capacityLimit-staged.SizeBytes {
|
||||
select {
|
||||
case s.cleanupSignal <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
return mediadomain.Asset{}, ErrMediaCapacity
|
||||
}
|
||||
expiresAt := time.Now().UTC().Add(InputAssetTTL)
|
||||
return s.commitStagedVideo(ctx, staged, time.Now().UTC(), &expiresAt)
|
||||
}
|
||||
|
||||
func (s *Service) commitStagedVideo(ctx context.Context, staged stagedVideo, createdAt time.Time, expiresAt *time.Time) (mediadomain.Asset, error) {
|
||||
if err := s.objects.CommitVideoUpload(ctx, staged.TempPath, staged.StorageKey); err != nil {
|
||||
return mediadomain.Asset{}, err
|
||||
}
|
||||
asset := mediadomain.Asset{
|
||||
ID: staged.ID, Kind: "video", StorageKey: staged.StorageKey, MIMEType: staged.MIMEType,
|
||||
SizeBytes: staged.SizeBytes, SHA256: staged.SHA256, CreatedAt: createdAt,
|
||||
SizeBytes: staged.SizeBytes, SHA256: staged.SHA256, ExpiresAt: expiresAt, CreatedAt: createdAt,
|
||||
}
|
||||
if err := s.assets.CreateMediaAsset(ctx, asset); err != nil {
|
||||
_ = s.objects.Delete(context.WithoutCancel(ctx), staged.StorageKey)
|
||||
@@ -324,7 +365,7 @@ func (s *Service) OpenVideo(ctx context.Context, id string) (mediadomain.Asset,
|
||||
if err != nil {
|
||||
return mediadomain.Asset{}, nil, err
|
||||
}
|
||||
if asset.Kind != "video" {
|
||||
if asset.Kind != "video" || asset.ExpiresAt != nil {
|
||||
return mediadomain.Asset{}, nil, ErrAssetNotFound
|
||||
}
|
||||
body, err := s.objects.Open(ctx, asset.StorageKey)
|
||||
|
||||
@@ -96,6 +96,36 @@ func TestSaveVideoArchivesProviderResultWithoutUploadTicket(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveInputVideoIsPrivateExpiringAsset(t *testing.T) {
|
||||
database, objects, _, cleanup := openUploadTestDeps(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
service := NewService(
|
||||
relational.NewMediaAssetRepository(database), relational.NewMediaJobRepository(database), objects, nil,
|
||||
Config{MaxImageBytes: mediadomain.MaxInputAssetBytes, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: time.Minute},
|
||||
)
|
||||
payload := append([]byte{0x00, 0x00, 0x00, 0x18, 'f', 't', 'y', 'p', 'i', 's', 'o', 'm'}, bytes.Repeat([]byte{0x04}, 64)...)
|
||||
asset, err := service.SaveInputVideo(ctx, "video/mp4", bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !mediadomain.IsInputAssetID(asset.ID) || asset.Kind != "video" || asset.ExpiresAt == nil || !asset.ExpiresAt.After(time.Now().UTC()) {
|
||||
t.Fatalf("input asset = %#v", asset)
|
||||
}
|
||||
stored, body, err := service.OpenInputAsset(ctx, asset.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer body.Close()
|
||||
raw, err := io.ReadAll(body)
|
||||
if err != nil || !bytes.Equal(raw, payload) || stored.ExpiresAt == nil {
|
||||
t.Fatalf("stored = %#v size=%d err=%v", stored, len(raw), err)
|
||||
}
|
||||
if _, _, err := service.OpenVideo(ctx, asset.ID); !errors.Is(err, ErrAssetNotFound) {
|
||||
t.Fatalf("temporary video unexpectedly public: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type bindingTicketRepository struct {
|
||||
repository.MediaUploadTicketRepository
|
||||
jobID string
|
||||
|
||||
@@ -153,9 +153,15 @@ func endpointCapabilitiesForDefinition(routes []modeldomain.Route, definition pr
|
||||
available["image_edit"] = definition.Media.ImageEdit
|
||||
case modeldomain.CapabilityVideo:
|
||||
available["video"] = definition.Media.VideoGeneration
|
||||
case modeldomain.CapabilityTTS:
|
||||
available["tts"] = definition.Media.TTS
|
||||
case modeldomain.CapabilitySTT:
|
||||
available["stt"] = definition.Media.STT
|
||||
case modeldomain.CapabilityRealtime:
|
||||
available["realtime"] = definition.Media.Realtime
|
||||
}
|
||||
}
|
||||
order := []string{"completions", "responses", "messages", "image", "image_edit", "video"}
|
||||
order := []string{"completions", "responses", "messages", "image", "image_edit", "video", "tts", "stt", "realtime"}
|
||||
result := make([]string, 0, len(order))
|
||||
for _, capability := range order {
|
||||
if available[capability] {
|
||||
|
||||
@@ -269,6 +269,27 @@ const (
|
||||
QuotaSourceUpstream QuotaSource = "upstream"
|
||||
)
|
||||
|
||||
const (
|
||||
QuotaModeWebImagePro = "image_pro"
|
||||
QuotaModeWebImageEdit = "image_edit"
|
||||
QuotaModeWebVideo = "video"
|
||||
QuotaModeWebVideo720p = "video_720p"
|
||||
QuotaGroupWebImagine = "web_imagine"
|
||||
)
|
||||
|
||||
func WebImagineQuotaModes() []string {
|
||||
return []string{QuotaModeWebImagePro, QuotaModeWebImageEdit, QuotaModeWebVideo, QuotaModeWebVideo720p}
|
||||
}
|
||||
|
||||
func IsWebImagineQuotaMode(mode string) bool {
|
||||
switch mode {
|
||||
case QuotaModeWebImagePro, QuotaModeWebImageEdit, QuotaModeWebVideo, QuotaModeWebVideo720p:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// QuotaWindow 表示 Provider 单个模式的额度窗口。
|
||||
type QuotaWindow struct {
|
||||
AccountID uint64
|
||||
|
||||
@@ -12,6 +12,10 @@ const (
|
||||
OperationImage Operation = "image"
|
||||
OperationImageEdit Operation = "image_edit"
|
||||
OperationVideo Operation = "video"
|
||||
OperationTTS Operation = "tts"
|
||||
OperationSTT Operation = "stt"
|
||||
OperationRealtime Operation = "realtime"
|
||||
OperationVoice Operation = "voice"
|
||||
)
|
||||
|
||||
type UsageSource string
|
||||
|
||||
@@ -2,13 +2,48 @@ package audit
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"math"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const officialTTSCharacterTicks int64 = 150_000
|
||||
|
||||
// EstimateOfficialTTSCost prices unary TTS from the exact Unicode character
|
||||
// count accepted by the upstream request. xAI publishes $15 per 1M characters.
|
||||
func EstimateOfficialTTSCost(text string) (PricingResult, bool) {
|
||||
characters := utf8.RuneCountInString(text)
|
||||
if characters <= 0 {
|
||||
return PricingResult{}, false
|
||||
}
|
||||
return PricingResult{
|
||||
Model: "grok-voice-tts",
|
||||
CostInUSDTicks: int64(characters) * officialTTSCharacterTicks,
|
||||
}, true
|
||||
}
|
||||
|
||||
// EstimateOfficialSTTCost prices a completed STT request from the duration
|
||||
// reported by xAI. REST costs $0.10/hour and streaming costs $0.20/hour.
|
||||
func EstimateOfficialSTTCost(durationSeconds float64, streaming bool) (PricingResult, bool) {
|
||||
if durationSeconds <= 0 || math.IsNaN(durationSeconds) || math.IsInf(durationSeconds, 0) {
|
||||
return PricingResult{}, false
|
||||
}
|
||||
hourlyTicks := int64(1_000_000_000)
|
||||
model := "grok-stt-rest"
|
||||
if streaming {
|
||||
hourlyTicks = 2_000_000_000
|
||||
model = "grok-stt-streaming"
|
||||
}
|
||||
// Round upward to one USD tick so a positive billable duration never
|
||||
// disappears through integer truncation.
|
||||
cost := int64(math.Ceil(durationSeconds * float64(hourlyTicks) / 3600))
|
||||
return PricingResult{Model: model, CostInUSDTicks: max(int64(1), cost)}, true
|
||||
}
|
||||
|
||||
const (
|
||||
OfficialPricingSource = "https://docs.x.ai/developers/pricing"
|
||||
OfficialPricingAsOf = "2026-07-14"
|
||||
OfficialPricingAsOf = "2026-08-13"
|
||||
officialImageEditInputTicks int64 = 100_000_000
|
||||
officialLiteImageInputTicks int64 = 20_000_000
|
||||
)
|
||||
@@ -81,6 +116,7 @@ type tokenPriceRule struct {
|
||||
|
||||
var officialTokenPriceRules = []tokenPriceRule{
|
||||
{Pattern: regexp.MustCompile(`^grok-(?:build-0\.1|code-fast(?:-1)?|composer-2\.5-fast)(?:-[a-z0-9.]+)*$`), CanonicalModel: "grok-build-0.1"},
|
||||
{Pattern: regexp.MustCompile(`^grok-4\.6(?:-[a-z0-9.]+)*$`), CanonicalModel: "grok-4.6"},
|
||||
{Pattern: regexp.MustCompile(`^grok-4\.5(?:-[a-z0-9.]+)*$`), CanonicalModel: "grok-4.5"},
|
||||
{Pattern: regexp.MustCompile(`^grok-4\.3(?:-[a-z0-9.]+)*$`), CanonicalModel: "grok-4.3"},
|
||||
{Pattern: regexp.MustCompile(`^grok-4\.20-multi-agent(?:-[a-z0-9.]+)*$`), CanonicalModel: "grok-4.20-multi-agent-0309"},
|
||||
@@ -100,6 +136,8 @@ func buildOfficialTokenPrices() map[string]tokenPrice {
|
||||
}
|
||||
register("grok-build-0.1", tokenPrice{InputTicks: 10000, CachedInputTicks: 2000, OutputTicks: 20000, LongContextTokens: 200000, LongInputTicks: 20000, LongCachedTicks: 4000, LongOutputTicks: 40000},
|
||||
"grok-code-fast-1", "grok-code-fast", "grok-code-fast-1-0825", "grok-composer-2.5-fast")
|
||||
register("grok-4.6", tokenPrice{InputTicks: 20000, CachedInputTicks: 5000, OutputTicks: 60000, LongContextTokens: 200000, LongInputTicks: 40000, LongCachedTicks: 10000, LongOutputTicks: 120000},
|
||||
"grok-4.6-latest")
|
||||
register("grok-4.5", tokenPrice{InputTicks: 20000, CachedInputTicks: 3000, OutputTicks: 60000, LongContextTokens: 200000, LongInputTicks: 40000, LongCachedTicks: 6000, LongOutputTicks: 120000},
|
||||
"grok-4.5-latest", "grok-build-latest")
|
||||
standard := tokenPrice{InputTicks: 12500, CachedInputTicks: 2000, OutputTicks: 25000, LongContextTokens: 200000, LongInputTicks: 25000, LongCachedTicks: 4000, LongOutputTicks: 50000}
|
||||
@@ -229,15 +267,36 @@ func estimateJSONTokens(value any) int64 {
|
||||
}
|
||||
|
||||
// EstimateOfficialImageCost 按客户端请求的 n 计算 Grok Imagine 图片费用。
|
||||
func EstimateOfficialImageCost(model, resolution string, count int) (PricingResult, bool) {
|
||||
func EstimateOfficialImageCost(model, resolution, quality string, count int) (PricingResult, bool) {
|
||||
if count <= 0 {
|
||||
return PricingResult{}, false
|
||||
}
|
||||
model = normalizePricingModel(model)
|
||||
quality = strings.ToLower(strings.TrimSpace(quality))
|
||||
if model == "grok-imagine-image" {
|
||||
if quality != "" {
|
||||
return PricingResult{}, false
|
||||
}
|
||||
return PricingResult{Model: "grok-imagine-image", CostInUSDTicks: int64(count) * 200_000_000}, true
|
||||
}
|
||||
if model != "grok-imagine-image-quality" {
|
||||
if model == "grok-imagine-image-2.0" {
|
||||
resolution = strings.ToLower(strings.TrimSpace(resolution))
|
||||
if resolution == "" {
|
||||
resolution = "1k"
|
||||
}
|
||||
if quality == "" {
|
||||
quality = "medium"
|
||||
}
|
||||
outputTicks, ok := officialImage20OutputTicks(resolution, quality)
|
||||
if !ok {
|
||||
return PricingResult{}, false
|
||||
}
|
||||
return PricingResult{
|
||||
Model: "grok-imagine-image-2.0-" + quality + "-" + resolution,
|
||||
CostInUSDTicks: int64(count) * outputTicks,
|
||||
}, true
|
||||
}
|
||||
if model != "grok-imagine-image-quality" || quality != "" {
|
||||
return PricingResult{}, false
|
||||
}
|
||||
resolution = strings.ToLower(strings.TrimSpace(resolution))
|
||||
@@ -260,12 +319,13 @@ func EstimateOfficialImageCost(model, resolution string, count int) (PricingResu
|
||||
}
|
||||
|
||||
// EstimateOfficialImageEditCost 按输出图片数量计费,并叠加每张输入图片的处理费用。
|
||||
func EstimateOfficialImageEditCost(model, resolution string, outputCount, inputCount int) (PricingResult, bool) {
|
||||
func EstimateOfficialImageEditCost(model, resolution, quality string, outputCount, inputCount int) (PricingResult, bool) {
|
||||
model = normalizePricingModel(model)
|
||||
if outputCount <= 0 || inputCount <= 0 {
|
||||
return PricingResult{}, false
|
||||
}
|
||||
resolution = strings.ToLower(strings.TrimSpace(resolution))
|
||||
quality = strings.ToLower(strings.TrimSpace(quality))
|
||||
if resolution == "" {
|
||||
resolution = "1k"
|
||||
}
|
||||
@@ -274,10 +334,29 @@ func EstimateOfficialImageEditCost(model, resolution string, outputCount, inputC
|
||||
var outputTicks int64
|
||||
switch model {
|
||||
case "grok-imagine-image-edit":
|
||||
if quality != "" {
|
||||
return PricingResult{}, false
|
||||
}
|
||||
pricingModel = "grok-imagine-image-edit-" + resolution
|
||||
case "grok-imagine-image-2.0":
|
||||
if quality == "" {
|
||||
quality = "medium"
|
||||
}
|
||||
var ok bool
|
||||
outputTicks, ok = officialImage20OutputTicks(resolution, quality)
|
||||
if !ok {
|
||||
return PricingResult{}, false
|
||||
}
|
||||
pricingModel = "grok-imagine-image-2.0-edit-" + quality + "-" + resolution
|
||||
case "grok-imagine-image-quality":
|
||||
if quality != "" {
|
||||
return PricingResult{}, false
|
||||
}
|
||||
pricingModel = "grok-imagine-image-quality-edit-" + resolution
|
||||
case "grok-imagine-image":
|
||||
if quality != "" {
|
||||
return PricingResult{}, false
|
||||
}
|
||||
pricingModel = "grok-imagine-image-edit-lite-" + resolution
|
||||
inputTicks = officialLiteImageInputTicks
|
||||
outputTicks = 200_000_000
|
||||
@@ -300,10 +379,23 @@ func EstimateOfficialImageEditCost(model, resolution string, outputCount, inputC
|
||||
}, true
|
||||
}
|
||||
|
||||
func officialImage20OutputTicks(resolution, quality string) (int64, bool) {
|
||||
switch resolution + "/" + quality {
|
||||
case "1k/low":
|
||||
return 400_000_000, true
|
||||
case "2k/low", "1k/medium":
|
||||
return 600_000_000, true
|
||||
case "2k/medium":
|
||||
return 800_000_000, true
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
// EstimateOfficialVideoCost 按请求视频时长和分辨率计算费用。
|
||||
// 仅精确支持 grok-imagine-video 与 grok-imagine-video-1.5(可带来源前缀);未知后缀拒绝。
|
||||
func EstimateOfficialVideoCost(model, resolution string, seconds int) (PricingResult, bool) {
|
||||
if seconds <= 0 {
|
||||
func EstimateOfficialVideoCost(model, resolution string, seconds, inputImages int) (PricingResult, bool) {
|
||||
if seconds <= 0 || inputImages < 0 {
|
||||
return PricingResult{}, false
|
||||
}
|
||||
baseModel, ok := officialVideoPricingModel(model)
|
||||
@@ -311,18 +403,34 @@ func EstimateOfficialVideoCost(model, resolution string, seconds int) (PricingRe
|
||||
return PricingResult{}, false
|
||||
}
|
||||
resolution = strings.ToLower(strings.TrimSpace(resolution))
|
||||
var ticksPerSecond int64
|
||||
switch resolution {
|
||||
case "480p":
|
||||
ticksPerSecond = 800_000_000
|
||||
case "720p":
|
||||
ticksPerSecond = 1_400_000_000
|
||||
default:
|
||||
return PricingResult{}, false
|
||||
var ticksPerSecond, ticksPerInputImage int64
|
||||
switch baseModel {
|
||||
case "grok-imagine-video":
|
||||
ticksPerInputImage = officialLiteImageInputTicks
|
||||
switch resolution {
|
||||
case "480p":
|
||||
ticksPerSecond = 500_000_000
|
||||
case "720p":
|
||||
ticksPerSecond = 700_000_000
|
||||
default:
|
||||
return PricingResult{}, false
|
||||
}
|
||||
case "grok-imagine-video-1.5":
|
||||
ticksPerInputImage = officialImageEditInputTicks
|
||||
switch resolution {
|
||||
case "480p":
|
||||
ticksPerSecond = 800_000_000
|
||||
case "720p":
|
||||
ticksPerSecond = 1_400_000_000
|
||||
case "1080p":
|
||||
ticksPerSecond = 2_500_000_000
|
||||
default:
|
||||
return PricingResult{}, false
|
||||
}
|
||||
}
|
||||
return PricingResult{
|
||||
Model: baseModel + "-" + resolution,
|
||||
CostInUSDTicks: int64(seconds) * ticksPerSecond,
|
||||
CostInUSDTicks: int64(seconds)*ticksPerSecond + int64(inputImages)*ticksPerInputImage,
|
||||
}, true
|
||||
}
|
||||
|
||||
@@ -331,36 +439,80 @@ func ReconstructOfficialCost(model string, inputTokens, cachedInputTokens, outpu
|
||||
normalized := normalizePricingModel(model)
|
||||
switch normalized {
|
||||
case "grok-imagine-image":
|
||||
return reconstructImageCost(normalized, "", outputImages)
|
||||
return reconstructImageCost(normalized, "", "", outputImages)
|
||||
case "grok-imagine-image-2.0":
|
||||
// Records written before the quality-aware pricing revision stored the
|
||||
// former flat $0.04 estimate under this identifier. Preserve an exact
|
||||
// reconstruction for those immutable audit rows.
|
||||
return reconstructLegacyImage20Cost(normalized, outputImages, 400_000_000)
|
||||
case "grok-imagine-image-2.0-low-1k":
|
||||
return reconstructImageCost("grok-imagine-image-2.0", "1k", "low", outputImages)
|
||||
case "grok-imagine-image-2.0-low-2k":
|
||||
return reconstructImageCost("grok-imagine-image-2.0", "2k", "low", outputImages)
|
||||
case "grok-imagine-image-2.0-medium-1k":
|
||||
return reconstructImageCost("grok-imagine-image-2.0", "1k", "medium", outputImages)
|
||||
case "grok-imagine-image-2.0-medium-2k":
|
||||
return reconstructImageCost("grok-imagine-image-2.0", "2k", "medium", outputImages)
|
||||
case "grok-imagine-image-quality-1k":
|
||||
return reconstructImageCost("grok-imagine-image-quality", "1k", outputImages)
|
||||
return reconstructImageCost("grok-imagine-image-quality", "1k", "", outputImages)
|
||||
case "grok-imagine-image-quality-2k":
|
||||
return reconstructImageCost("grok-imagine-image-quality", "2k", outputImages)
|
||||
return reconstructImageCost("grok-imagine-image-quality", "2k", "", outputImages)
|
||||
case "grok-imagine-image-edit-1k":
|
||||
return reconstructImageEditCost("grok-imagine-image-edit", "1k", inputImages, outputImages)
|
||||
return reconstructImageEditCost("grok-imagine-image-edit", "1k", "", inputImages, outputImages)
|
||||
case "grok-imagine-image-edit-2k":
|
||||
return reconstructImageEditCost("grok-imagine-image-edit", "2k", inputImages, outputImages)
|
||||
return reconstructImageEditCost("grok-imagine-image-edit", "2k", "", inputImages, outputImages)
|
||||
case "grok-imagine-image-2.0-edit-low-1k":
|
||||
return reconstructImageEditCost("grok-imagine-image-2.0", "1k", "low", inputImages, outputImages)
|
||||
case "grok-imagine-image-2.0-edit-low-2k":
|
||||
return reconstructImageEditCost("grok-imagine-image-2.0", "2k", "low", inputImages, outputImages)
|
||||
case "grok-imagine-image-2.0-edit-medium-1k":
|
||||
return reconstructImageEditCost("grok-imagine-image-2.0", "1k", "medium", inputImages, outputImages)
|
||||
case "grok-imagine-image-2.0-edit-medium-2k":
|
||||
return reconstructImageEditCost("grok-imagine-image-2.0", "2k", "medium", inputImages, outputImages)
|
||||
case "grok-imagine-image-2.0-edit-1k", "grok-imagine-image-2.0-edit-2k":
|
||||
return reconstructLegacyImage20EditCost(normalized, inputImages, outputImages)
|
||||
case "grok-imagine-image-quality-edit-1k":
|
||||
return reconstructImageEditCost("grok-imagine-image-quality", "1k", inputImages, outputImages)
|
||||
return reconstructImageEditCost("grok-imagine-image-quality", "1k", "", inputImages, outputImages)
|
||||
case "grok-imagine-image-quality-edit-2k":
|
||||
return reconstructImageEditCost("grok-imagine-image-quality", "2k", inputImages, outputImages)
|
||||
return reconstructImageEditCost("grok-imagine-image-quality", "2k", "", inputImages, outputImages)
|
||||
case "grok-imagine-image-edit-lite-1k":
|
||||
return reconstructImageEditCost("grok-imagine-image", "1k", inputImages, outputImages)
|
||||
return reconstructImageEditCost("grok-imagine-image", "1k", "", inputImages, outputImages)
|
||||
case "grok-imagine-image-edit-lite-2k":
|
||||
return reconstructImageEditCost("grok-imagine-image", "2k", inputImages, outputImages)
|
||||
return reconstructImageEditCost("grok-imagine-image", "2k", "", inputImages, outputImages)
|
||||
case "grok-imagine-video-480p":
|
||||
return reconstructVideoCost("grok-imagine-video", "480p", outputSeconds)
|
||||
return reconstructVideoCost("grok-imagine-video", "480p", inputImages, outputSeconds)
|
||||
case "grok-imagine-video-720p":
|
||||
return reconstructVideoCost("grok-imagine-video", "720p", outputSeconds)
|
||||
return reconstructVideoCost("grok-imagine-video", "720p", inputImages, outputSeconds)
|
||||
case "grok-imagine-video-1.5-480p":
|
||||
return reconstructVideoCost("grok-imagine-video-1.5", "480p", outputSeconds)
|
||||
return reconstructVideoCost("grok-imagine-video-1.5", "480p", inputImages, outputSeconds)
|
||||
case "grok-imagine-video-1.5-720p":
|
||||
return reconstructVideoCost("grok-imagine-video-1.5", "720p", outputSeconds)
|
||||
return reconstructVideoCost("grok-imagine-video-1.5", "720p", inputImages, outputSeconds)
|
||||
case "grok-imagine-video-1.5-1080p":
|
||||
return reconstructVideoCost("grok-imagine-video-1.5", "1080p", inputImages, outputSeconds)
|
||||
default:
|
||||
return reconstructTextCost(normalized, inputTokens, cachedInputTokens, outputTokens, contextInputTokens)
|
||||
}
|
||||
}
|
||||
|
||||
func reconstructLegacyImage20Cost(model string, outputCount, outputTicks int64) (PricingBreakdown, bool) {
|
||||
if outputCount <= 0 {
|
||||
return PricingBreakdown{}, false
|
||||
}
|
||||
return newPricingBreakdown(model, PricingTierMedia,
|
||||
newPricingComponent(PricingComponentOutputImage, PricingUnitImage, outputCount, outputTicks),
|
||||
), true
|
||||
}
|
||||
|
||||
func reconstructLegacyImage20EditCost(model string, inputCount, outputCount int64) (PricingBreakdown, bool) {
|
||||
if inputCount <= 0 || outputCount <= 0 {
|
||||
return PricingBreakdown{}, false
|
||||
}
|
||||
return newPricingBreakdown(model, PricingTierMedia,
|
||||
newPricingComponent(PricingComponentOutputImage, PricingUnitImage, outputCount, 400_000_000),
|
||||
newPricingComponent(PricingComponentInputImage, PricingUnitImage, inputCount, officialImageEditInputTicks),
|
||||
), true
|
||||
}
|
||||
|
||||
func reconstructTextCost(model string, inputTokens, cachedInputTokens, outputTokens, contextInputTokens int64) (PricingBreakdown, bool) {
|
||||
price, ok := resolveOfficialTokenPrice(model)
|
||||
if !ok {
|
||||
@@ -384,11 +536,11 @@ func reconstructTextCost(model string, inputTokens, cachedInputTokens, outputTok
|
||||
), true
|
||||
}
|
||||
|
||||
func reconstructImageCost(model, resolution string, count int64) (PricingBreakdown, bool) {
|
||||
func reconstructImageCost(model, resolution, quality string, count int64) (PricingBreakdown, bool) {
|
||||
if count <= 0 || int64(int(count)) != count {
|
||||
return PricingBreakdown{}, false
|
||||
}
|
||||
result, ok := EstimateOfficialImageCost(model, resolution, int(count))
|
||||
result, ok := EstimateOfficialImageCost(model, resolution, quality, int(count))
|
||||
if !ok {
|
||||
return PricingBreakdown{}, false
|
||||
}
|
||||
@@ -397,11 +549,11 @@ func reconstructImageCost(model, resolution string, count int64) (PricingBreakdo
|
||||
), true
|
||||
}
|
||||
|
||||
func reconstructImageEditCost(model, resolution string, inputCount, outputCount int64) (PricingBreakdown, bool) {
|
||||
func reconstructImageEditCost(model, resolution, quality string, inputCount, outputCount int64) (PricingBreakdown, bool) {
|
||||
if inputCount <= 0 || outputCount <= 0 || int64(int(inputCount)) != inputCount || int64(int(outputCount)) != outputCount {
|
||||
return PricingBreakdown{}, false
|
||||
}
|
||||
result, ok := EstimateOfficialImageEditCost(model, resolution, int(outputCount), int(inputCount))
|
||||
result, ok := EstimateOfficialImageEditCost(model, resolution, quality, int(outputCount), int(inputCount))
|
||||
if !ok {
|
||||
return PricingBreakdown{}, false
|
||||
}
|
||||
@@ -419,16 +571,25 @@ func reconstructImageEditCost(model, resolution string, inputCount, outputCount
|
||||
), true
|
||||
}
|
||||
|
||||
func reconstructVideoCost(model, resolution string, seconds int64) (PricingBreakdown, bool) {
|
||||
if seconds <= 0 || int64(int(seconds)) != seconds {
|
||||
func reconstructVideoCost(model, resolution string, inputImages, seconds int64) (PricingBreakdown, bool) {
|
||||
if seconds <= 0 || inputImages < 0 || int64(int(seconds)) != seconds || int64(int(inputImages)) != inputImages {
|
||||
return PricingBreakdown{}, false
|
||||
}
|
||||
result, ok := EstimateOfficialVideoCost(model, resolution, int(seconds))
|
||||
result, ok := EstimateOfficialVideoCost(model, resolution, int(seconds), int(inputImages))
|
||||
if !ok {
|
||||
return PricingBreakdown{}, false
|
||||
}
|
||||
inputTicks := officialLiteImageInputTicks
|
||||
if normalizePricingModel(model) == "grok-imagine-video-1.5" {
|
||||
inputTicks = officialImageEditInputTicks
|
||||
}
|
||||
outputCost := result.CostInUSDTicks - inputImages*inputTicks
|
||||
if outputCost < 0 || outputCost%seconds != 0 {
|
||||
return PricingBreakdown{}, false
|
||||
}
|
||||
return newPricingBreakdown(result.Model, PricingTierMedia,
|
||||
newPricingComponent(PricingComponentOutputSecond, PricingUnitSecond, seconds, result.CostInUSDTicks/seconds),
|
||||
newPricingComponent(PricingComponentOutputSecond, PricingUnitSecond, seconds, outputCost/seconds),
|
||||
newPricingComponent(PricingComponentInputImage, PricingUnitImage, inputImages, inputTicks),
|
||||
), true
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ func TestEstimateOfficialCostMatchesControlledModelFamilies(t *testing.T) {
|
||||
canonical string
|
||||
}{
|
||||
{model: "Build/grok-build-0.1", canonical: "grok-build-0.1"},
|
||||
{model: "Console/grok-4.6-latest", canonical: "grok-4.6"},
|
||||
{model: "grok_build/grok-code-fast-1-0825", canonical: "grok-build-0.1"},
|
||||
{model: "Console/grok-4.3-high", canonical: "grok-4.3"},
|
||||
{model: "Web/grok-4.5-2026-07-14", canonical: "grok-4.5"},
|
||||
@@ -53,6 +54,7 @@ func TestOfficialPricingMatchesPublishedTokenRates(t *testing.T) {
|
||||
inputCost, cachedCost, outputCost int64
|
||||
}{
|
||||
{model: "grok-build-0.1", inputCost: 10_000_000_000, cachedCost: 2_000_000_000, outputCost: 20_000_000_000},
|
||||
{model: "grok-4.6", inputCost: 20_000_000_000, cachedCost: 5_000_000_000, outputCost: 60_000_000_000},
|
||||
{model: "grok-4.5", inputCost: 20_000_000_000, cachedCost: 3_000_000_000, outputCost: 60_000_000_000},
|
||||
{model: "grok-4.3", inputCost: 12_500_000_000, cachedCost: 2_000_000_000, outputCost: 25_000_000_000},
|
||||
{model: "grok-4.20-multi-agent-0309", inputCost: 12_500_000_000, cachedCost: 2_000_000_000, outputCost: 25_000_000_000},
|
||||
@@ -74,13 +76,13 @@ func TestOfficialPricingMatchesPublishedTokenRates(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestMediaPricingAcceptsProviderPrefixes(t *testing.T) {
|
||||
if result, ok := EstimateOfficialImageCost("Web/grok-imagine-image", "1k", 1); !ok || result.CostInUSDTicks != 200_000_000 {
|
||||
if result, ok := EstimateOfficialImageCost("Web/grok-imagine-image", "1k", "", 1); !ok || result.CostInUSDTicks != 200_000_000 {
|
||||
t.Fatalf("prefixed image price = %#v, %v", result, ok)
|
||||
}
|
||||
if result, ok := EstimateOfficialImageEditCost("grok_web/grok-imagine-image-edit", "1k", 1, 1); !ok || result.CostInUSDTicks != 600_000_000 {
|
||||
if result, ok := EstimateOfficialImageEditCost("grok_web/grok-imagine-image-edit", "1k", "", 1, 1); !ok || result.CostInUSDTicks != 600_000_000 {
|
||||
t.Fatalf("prefixed image edit price = %#v, %v", result, ok)
|
||||
}
|
||||
if result, ok := EstimateOfficialVideoCost("Web/grok-imagine-video", "480p", 1); !ok || result.CostInUSDTicks != 800_000_000 {
|
||||
if result, ok := EstimateOfficialVideoCost("Web/grok-imagine-video", "480p", 1, 0); !ok || result.CostInUSDTicks != 500_000_000 {
|
||||
t.Fatalf("prefixed video price = %#v, %v", result, ok)
|
||||
}
|
||||
}
|
||||
@@ -100,71 +102,124 @@ func TestEstimateOfficialTextReservationUsesOutputLimitAndIgnoresInlineMediaByte
|
||||
}
|
||||
|
||||
func TestEstimateOfficialImageCost(t *testing.T) {
|
||||
result, ok := EstimateOfficialImageCost("grok-imagine-image-quality", "1k", 2)
|
||||
result, ok := EstimateOfficialImageCost("grok-imagine-image-quality", "1k", "", 2)
|
||||
if !ok || result.Model != "grok-imagine-image-quality-1k" || result.CostInUSDTicks != 1_000_000_000 {
|
||||
t.Fatalf("1k result = %#v, ok = %v", result, ok)
|
||||
}
|
||||
result, ok = EstimateOfficialImageCost("grok-imagine-image-quality", "2k", 3)
|
||||
result, ok = EstimateOfficialImageCost("grok-imagine-image-quality", "2k", "", 3)
|
||||
if !ok || result.Model != "grok-imagine-image-quality-2k" || result.CostInUSDTicks != 2_100_000_000 {
|
||||
t.Fatalf("2k result = %#v, ok = %v", result, ok)
|
||||
}
|
||||
result, ok = EstimateOfficialImageCost("grok-imagine-image", "2k", 4)
|
||||
result, ok = EstimateOfficialImageCost("grok-imagine-image", "2k", "", 4)
|
||||
if !ok || result.Model != "grok-imagine-image" || result.CostInUSDTicks != 800_000_000 {
|
||||
t.Fatalf("Lite result = %#v, ok = %v", result, ok)
|
||||
}
|
||||
result, ok = EstimateOfficialImageCost("Console/grok-imagine-image-2.0", "2k", "", 2)
|
||||
if !ok || result.Model != "grok-imagine-image-2.0-medium-2k" || result.CostInUSDTicks != 1_600_000_000 {
|
||||
t.Fatalf("2.0 default-medium result = %#v, ok = %v", result, ok)
|
||||
}
|
||||
result, ok = EstimateOfficialImageCost("Console/grok-imagine-image-2.0", "2k", "low", 2)
|
||||
if !ok || result.Model != "grok-imagine-image-2.0-low-2k" || result.CostInUSDTicks != 1_200_000_000 {
|
||||
t.Fatalf("2.0 low result = %#v, ok = %v", result, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImage20PricingMatchesPublishedResolutionAndQualityRates(t *testing.T) {
|
||||
tests := []struct {
|
||||
resolution string
|
||||
quality string
|
||||
wantTicks int64
|
||||
}{
|
||||
{resolution: "1k", quality: "low", wantTicks: 400_000_000},
|
||||
{resolution: "2k", quality: "low", wantTicks: 600_000_000},
|
||||
{resolution: "1k", quality: "medium", wantTicks: 600_000_000},
|
||||
{resolution: "2k", quality: "medium", wantTicks: 800_000_000},
|
||||
}
|
||||
for _, test := range tests {
|
||||
result, ok := EstimateOfficialImageCost("grok-imagine-image-2.0", test.resolution, test.quality, 1)
|
||||
if !ok || result.CostInUSDTicks != test.wantTicks {
|
||||
t.Fatalf("Image 2.0 %s/%s = %#v, ok=%v", test.resolution, test.quality, result, ok)
|
||||
}
|
||||
}
|
||||
if _, ok := EstimateOfficialImageCost("grok-imagine-image-2.0", "1k", "high", 1); ok {
|
||||
t.Fatal("unsupported Image 2.0 quality was priced")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEstimateOfficialImageEditCost(t *testing.T) {
|
||||
result, ok := EstimateOfficialImageEditCost("grok-imagine-image-edit", "1k", 2, 1)
|
||||
result, ok := EstimateOfficialImageEditCost("grok-imagine-image-edit", "1k", "", 2, 1)
|
||||
if !ok || result.Model != "grok-imagine-image-edit-1k" || result.CostInUSDTicks != 1_100_000_000 {
|
||||
t.Fatalf("1k edit result = %#v, ok = %v", result, ok)
|
||||
}
|
||||
result, ok = EstimateOfficialImageEditCost("grok-imagine-image-edit", "2K", 3, 4)
|
||||
result, ok = EstimateOfficialImageEditCost("grok-imagine-image-edit", "2K", "", 3, 4)
|
||||
if !ok || result.Model != "grok-imagine-image-edit-2k" || result.CostInUSDTicks != 2_500_000_000 {
|
||||
t.Fatalf("2k edit result = %#v, ok = %v", result, ok)
|
||||
}
|
||||
if result, ok = EstimateOfficialImageEditCost("grok-imagine-image-edit", "4k", 1, 1); ok || result.CostInUSDTicks != 0 {
|
||||
if result, ok = EstimateOfficialImageEditCost("grok-imagine-image-edit", "4k", "", 1, 1); ok || result.CostInUSDTicks != 0 {
|
||||
t.Fatalf("unknown edit resolution = %#v, ok = %v", result, ok)
|
||||
}
|
||||
result, ok = EstimateOfficialImageEditCost("Console/grok-imagine-image-quality", "2k", 1, 2)
|
||||
result, ok = EstimateOfficialImageEditCost("Console/grok-imagine-image-quality", "2k", "", 1, 2)
|
||||
if !ok || result.Model != "grok-imagine-image-quality-edit-2k" || result.CostInUSDTicks != 900_000_000 {
|
||||
t.Fatalf("Console quality edit price = %#v, ok = %v", result, ok)
|
||||
}
|
||||
result, ok = EstimateOfficialImageEditCost("Console/grok-imagine-image", "1k", 1, 2)
|
||||
result, ok = EstimateOfficialImageEditCost("Console/grok-imagine-image", "1k", "", 1, 2)
|
||||
if !ok || result.Model != "grok-imagine-image-edit-lite-1k" || result.CostInUSDTicks != 240_000_000 {
|
||||
t.Fatalf("Console lite edit price = %#v, ok = %v", result, ok)
|
||||
}
|
||||
result, ok = EstimateOfficialImageEditCost("Console/grok-imagine-image-2.0", "2k", "medium", 2, 1)
|
||||
if !ok || result.Model != "grok-imagine-image-2.0-edit-medium-2k" || result.CostInUSDTicks != 1_700_000_000 {
|
||||
t.Fatalf("Console 2.0 edit price = %#v, ok = %v", result, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEstimateOfficialVideoCost(t *testing.T) {
|
||||
result, ok := EstimateOfficialVideoCost("grok-imagine-video", "480p", 10)
|
||||
if !ok || result.Model != "grok-imagine-video-480p" || result.CostInUSDTicks != 8_000_000_000 {
|
||||
result, ok := EstimateOfficialVideoCost("grok-imagine-video", "480p", 10, 0)
|
||||
if !ok || result.Model != "grok-imagine-video-480p" || result.CostInUSDTicks != 5_000_000_000 {
|
||||
t.Fatalf("480p video result = %#v, ok = %v", result, ok)
|
||||
}
|
||||
result, ok = EstimateOfficialVideoCost("grok-imagine-video", "720P", 6)
|
||||
if !ok || result.Model != "grok-imagine-video-720p" || result.CostInUSDTicks != 8_400_000_000 {
|
||||
result, ok = EstimateOfficialVideoCost("grok-imagine-video", "720P", 6, 2)
|
||||
if !ok || result.Model != "grok-imagine-video-720p" || result.CostInUSDTicks != 4_240_000_000 {
|
||||
t.Fatalf("720p video result = %#v, ok = %v", result, ok)
|
||||
}
|
||||
if result, ok = EstimateOfficialVideoCost("grok-imagine-video", "1080p", 10); ok || result.CostInUSDTicks != 0 {
|
||||
if result, ok = EstimateOfficialVideoCost("grok-imagine-video", "1080p", 10, 0); ok || result.CostInUSDTicks != 0 {
|
||||
t.Fatalf("unpriced video resolution = %#v, ok = %v", result, ok)
|
||||
}
|
||||
|
||||
result, ok = EstimateOfficialVideoCost("grok-imagine-video-1.5", "720p", 6)
|
||||
result, ok = EstimateOfficialVideoCost("grok-imagine-video-1.5", "720p", 6, 0)
|
||||
if !ok || result.Model != "grok-imagine-video-1.5-720p" || result.CostInUSDTicks != 8_400_000_000 {
|
||||
t.Fatalf("1.5 720p video result = %#v, ok = %v", result, ok)
|
||||
}
|
||||
result, ok = EstimateOfficialVideoCost("Build/grok-imagine-video-1.5", "480p", 1)
|
||||
if !ok || result.Model != "grok-imagine-video-1.5-480p" || result.CostInUSDTicks != 800_000_000 {
|
||||
result, ok = EstimateOfficialVideoCost("Build/grok-imagine-video-1.5", "480p", 1, 1)
|
||||
if !ok || result.Model != "grok-imagine-video-1.5-480p" || result.CostInUSDTicks != 900_000_000 {
|
||||
t.Fatalf("prefixed 1.5 video result = %#v, ok = %v", result, ok)
|
||||
}
|
||||
if result, ok = EstimateOfficialVideoCost("grok-imagine-video-1.5-fast", "720p", 6); ok || result.CostInUSDTicks != 0 {
|
||||
result, ok = EstimateOfficialVideoCost("grok-imagine-video-1.5", "1080p", 6, 0)
|
||||
if !ok || result.Model != "grok-imagine-video-1.5-1080p" || result.CostInUSDTicks != 15_000_000_000 {
|
||||
t.Fatalf("1.5 1080p video result = %#v, ok = %v", result, ok)
|
||||
}
|
||||
if result, ok = EstimateOfficialVideoCost("grok-imagine-video-1.5-fast", "720p", 6, 0); ok || result.CostInUSDTicks != 0 {
|
||||
t.Fatalf("unknown 1.5 suffix was priced = %#v, ok = %v", result, ok)
|
||||
}
|
||||
if result, ok = EstimateOfficialVideoCost("grok-imagine-video-2.0", "720p", 6); ok || result.CostInUSDTicks != 0 {
|
||||
if result, ok = EstimateOfficialVideoCost("grok-imagine-video-2.0", "720p", 6, 0); ok || result.CostInUSDTicks != 0 {
|
||||
t.Fatalf("unknown video model was priced = %#v, ok = %v", result, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEstimateOfficialVoiceCosts(t *testing.T) {
|
||||
if result, ok := EstimateOfficialTTSCost("Hello 世界"); !ok || result.Model != "grok-voice-tts" || result.CostInUSDTicks != 8*150_000 {
|
||||
t.Fatalf("tts pricing = %#v, ok=%v", result, ok)
|
||||
}
|
||||
if result, ok := EstimateOfficialSTTCost(3600, false); !ok || result.Model != "grok-stt-rest" || result.CostInUSDTicks != 1_000_000_000 {
|
||||
t.Fatalf("rest stt pricing = %#v, ok=%v", result, ok)
|
||||
}
|
||||
if result, ok := EstimateOfficialSTTCost(3.45, true); !ok || result.Model != "grok-stt-streaming" || result.CostInUSDTicks != 1_916_667 {
|
||||
t.Fatalf("streaming stt pricing = %#v, ok=%v", result, ok)
|
||||
}
|
||||
if _, ok := EstimateOfficialSTTCost(0, false); ok {
|
||||
t.Fatal("zero-duration STT must remain unpriced")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconstructOfficialCostReturnsExactStoredFormulaInputs(t *testing.T) {
|
||||
textResult, ok := ReconstructOfficialCost("grok-build-0.1", 100, 20, 50, 100, 0, 0, 0)
|
||||
if !ok || textResult.Tier != PricingTierStandard || textResult.CostInUSDTicks != 1_840_000 || len(textResult.Components) != 3 {
|
||||
@@ -179,7 +234,11 @@ func TestReconstructOfficialCostReturnsExactStoredFormulaInputs(t *testing.T) {
|
||||
t.Fatalf("image reconstruction = %#v, %v", imageResult, ok)
|
||||
}
|
||||
videoResult, ok := ReconstructOfficialCost("grok-imagine-video-1.5-720p", 0, 0, 0, 0, 1, 0, 6)
|
||||
if !ok || videoResult.CostInUSDTicks != 8_400_000_000 || videoResult.Components[0].Unit != PricingUnitSecond {
|
||||
if !ok || videoResult.CostInUSDTicks != 8_500_000_000 || len(videoResult.Components) != 2 || videoResult.Components[0].Unit != PricingUnitSecond || videoResult.Components[1].Kind != PricingComponentInputImage {
|
||||
t.Fatalf("video reconstruction = %#v, %v", videoResult, ok)
|
||||
}
|
||||
legacyImage20, ok := ReconstructOfficialCost("grok-imagine-image-2.0", 0, 0, 0, 0, 0, 2, 0)
|
||||
if !ok || legacyImage20.CostInUSDTicks != 800_000_000 {
|
||||
t.Fatalf("legacy Image 2.0 reconstruction = %#v, %v", legacyImage20, ok)
|
||||
}
|
||||
}
|
||||
@@ -131,6 +131,7 @@ type SubscriptionSource struct {
|
||||
Scope Scope
|
||||
Enabled bool
|
||||
EncryptedURL string
|
||||
EncryptedProxyURL string
|
||||
RefreshIntervalSeconds int
|
||||
DefaultAccountCapacity int
|
||||
LastSyncedAt *time.Time
|
||||
@@ -147,6 +148,7 @@ type PublicSubscriptionSource struct {
|
||||
Scope Scope
|
||||
Enabled bool
|
||||
URLConfigured bool
|
||||
ProxyConfigured bool
|
||||
RefreshIntervalSeconds int
|
||||
DefaultAccountCapacity int
|
||||
LastSyncedAt *time.Time
|
||||
@@ -218,11 +220,8 @@ type OperationsConfig struct {
|
||||
AutoAssignEnabled bool
|
||||
AutoBalanceEnabled bool
|
||||
AssignmentIntervalSeconds int
|
||||
// EncryptedSubscriptionProxyURL is the optional proxy used only when
|
||||
// fetching remote proxy subscription sources. It is write-only at rest.
|
||||
EncryptedSubscriptionProxyURL string
|
||||
Fallbacks map[Scope]FallbackConfig
|
||||
UpdatedAt time.Time
|
||||
Fallbacks map[Scope]FallbackConfig
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
func DefaultOperationsConfig() OperationsConfig {
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
// InputAssetIDPrefix 标识不会公开展示、带生命周期的视频输入资产。
|
||||
// InputAssetIDPrefix 标识不会公开展示、带生命周期的视频任务输入资产。
|
||||
InputAssetIDPrefix = "input_"
|
||||
// InputReferencePrefix 标识 media_jobs.input_json 中的本地临时输入引用。
|
||||
InputReferencePrefix = "grok2api-input:"
|
||||
|
||||
@@ -18,6 +18,17 @@ const MaxInputJSONBytes = 32 << 20
|
||||
// MaxInputImages is the maximum number of reference images accepted for a video job.
|
||||
const MaxInputImages = 8
|
||||
|
||||
// MaxInputAssetBytes limits each temporary image or video input to 20 MiB.
|
||||
const MaxInputAssetBytes = 20 << 20
|
||||
|
||||
type VideoOperation string
|
||||
|
||||
const (
|
||||
VideoOperationGenerate VideoOperation = "generate"
|
||||
VideoOperationEdit VideoOperation = "edit"
|
||||
VideoOperationExtend VideoOperation = "extend"
|
||||
)
|
||||
|
||||
// Job 表示可跨进程重启恢复的异步视频任务。
|
||||
type Job struct {
|
||||
ID string
|
||||
@@ -34,6 +45,7 @@ type Job struct {
|
||||
Model string
|
||||
ModelRouteID uint64
|
||||
UpstreamModel string
|
||||
Operation VideoOperation
|
||||
Prompt string
|
||||
Seconds int
|
||||
Size string
|
||||
|
||||
@@ -22,6 +22,9 @@ const (
|
||||
CapabilityImage Capability = "image"
|
||||
CapabilityImageEdit Capability = "image_edit"
|
||||
CapabilityVideo Capability = "video"
|
||||
CapabilityTTS Capability = "tts"
|
||||
CapabilitySTT Capability = "stt"
|
||||
CapabilityRealtime Capability = "realtime"
|
||||
)
|
||||
|
||||
// Capabilities returns every persisted route capability. Callers use this as
|
||||
@@ -33,6 +36,9 @@ func Capabilities() []Capability {
|
||||
CapabilityImage,
|
||||
CapabilityImageEdit,
|
||||
CapabilityVideo,
|
||||
CapabilityTTS,
|
||||
CapabilitySTT,
|
||||
CapabilityRealtime,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
_ "github.com/bdandy/go-socks4"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy"
|
||||
xproxy "golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
@@ -58,6 +59,12 @@ func newBuildClientWithOptions(proxyURL string, responseHeaderTimeout time.Durat
|
||||
return nil, fmt.Errorf("创建 Grok Build SOCKS 代理: %w", err)
|
||||
}
|
||||
transport.DialContext = dialContext(dialer)
|
||||
case "trojan", "vless", "ss", "vmess":
|
||||
dialer, err := tunnelproxy.NewDialer(proxyURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建 Grok Build 隧道代理: %w", err)
|
||||
}
|
||||
transport.DialContext = dialer.DialContext
|
||||
default:
|
||||
return nil, fmt.Errorf("Grok Build 不支持代理协议 %q", parsed.Scheme)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
application "github.com/chenyme/grok2api/backend/internal/application/egress"
|
||||
neterrorpkg "github.com/chenyme/grok2api/backend/internal/pkg/neterror"
|
||||
)
|
||||
|
||||
@@ -123,6 +125,39 @@ func TestNewBuildClientRejectsUnsupportedProxyScheme(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatedProxySchemesCreateBuildAndBrowserClients(t *testing.T) {
|
||||
vmess := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(`{"v":"2","add":"proxy.example","port":"443","id":"123e4567-e89b-12d3-a456-426614174000","aid":"0","scy":"auto","net":"tcp"}`))
|
||||
for _, raw := range []string{
|
||||
"http://user:password@127.0.0.1:8080",
|
||||
"https://proxy.example:8443",
|
||||
"socks4://127.0.0.1:1080",
|
||||
"socks4a://proxy.example:1080",
|
||||
"socks5://user:password@127.0.0.1:1080",
|
||||
"socks5h://user:password@proxy.example:1080",
|
||||
"trojan://password@proxy.example:443?security=tls&sni=edge.example",
|
||||
"vless://123e4567-e89b-12d3-a456-426614174000@proxy.example:443?encryption=none&security=tls&sni=edge.example",
|
||||
"ss://YWVzLTEyOC1nY206c2VjcmV0@proxy.example:8388",
|
||||
vmess,
|
||||
} {
|
||||
t.Run(raw, func(t *testing.T) {
|
||||
normalized, err := application.NormalizeProxyURL(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
build, err := newBuildClient(normalized, 5*time.Minute)
|
||||
if err != nil {
|
||||
t.Fatalf("build client: %v", err)
|
||||
}
|
||||
build.CloseIdleConnections()
|
||||
browser, err := newBrowserClient(normalized, DefaultUserAgent)
|
||||
if err != nil {
|
||||
t.Fatalf("browser client: %v", err)
|
||||
}
|
||||
browser.CloseIdleConnections()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildClientRoutesThroughSOCKS5HWithRemoteDNS(t *testing.T) {
|
||||
target := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.Header.Get("User-Agent") != "grok-shell/0.2.102 (linux; x86_64)" {
|
||||
|
||||
@@ -14,12 +14,14 @@ import (
|
||||
"time"
|
||||
|
||||
application "github.com/chenyme/grok2api/backend/internal/application/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy"
|
||||
)
|
||||
|
||||
const maxFlareSolverrResponseBytes = 2 << 20
|
||||
|
||||
var (
|
||||
proxyCredentialPattern = regexp.MustCompile(`(?i)\b(https?|socks4a?|socks5h?)://[^\s/@:]+:[^\s/@]+@`)
|
||||
tunnelCredentialPattern = regexp.MustCompile(`(?i)\b(?:trojan|vless)://[^\s/@]+@|\b(?:ss|vmess)://[^\s,;]+`)
|
||||
bearerCredentialPattern = regexp.MustCompile(`(?i)\bbearer\s+[a-z0-9._~+/=-]+`)
|
||||
namedCredentialPattern = regexp.MustCompile(`(?i)\b(token|password|passwd|authorization|cookie)\s*[:=]\s*[^\s,;]+`)
|
||||
)
|
||||
@@ -44,6 +46,9 @@ type clearanceSolver interface {
|
||||
type flaresolverrSolver struct{}
|
||||
|
||||
func (flaresolverrSolver) Solve(ctx context.Context, cfg ClearanceConfig, proxyURL string) (clearanceSolution, error) {
|
||||
if parsedProxy, parseErr := url.Parse(proxyURL); parseErr == nil && tunnelproxy.IsSupportedScheme(parsedProxy.Scheme) {
|
||||
return clearanceSolution{}, errors.New("FlareSolverr 暂不支持 Trojan、VLESS、SS 或 VMess 隧道代理")
|
||||
}
|
||||
endpoint, err := flaresolverrEndpoint(cfg.FlareSolverrURL)
|
||||
if err != nil {
|
||||
return clearanceSolution{}, err
|
||||
@@ -139,6 +144,7 @@ func sanitizeFlareSolverrMessage(value string) string {
|
||||
}
|
||||
return candidate[:separator+3] + "***:***@"
|
||||
})
|
||||
value = tunnelCredentialPattern.ReplaceAllString(value, "[redacted tunnel proxy]")
|
||||
value = bearerCredentialPattern.ReplaceAllString(value, "Bearer [redacted]")
|
||||
value = namedCredentialPattern.ReplaceAllString(value, "$1=[redacted]")
|
||||
characters := []rune(value)
|
||||
|
||||
@@ -60,6 +60,13 @@ func TestFlareSolverrSolveAcceptsNoChallengeWithoutCloudflareCookies(t *testing.
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlareSolverrSolveRejectsTunnelProxy(t *testing.T) {
|
||||
_, err := (flaresolverrSolver{}).Solve(context.Background(), ClearanceConfig{}, "trojan://secret@proxy.example:443")
|
||||
if err == nil || !strings.Contains(err.Error(), "FlareSolverr") {
|
||||
t.Fatalf("tunnel proxy error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlareSolverrEndpointAcceptsBaseAndV1Path(t *testing.T) {
|
||||
for input, expected := range map[string]string{
|
||||
"http://flaresolverr:8191": "http://flaresolverr:8191/v1",
|
||||
@@ -74,8 +81,8 @@ func TestFlareSolverrEndpointAcceptsBaseAndV1Path(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSanitizeFlareSolverrMessageRedactsCredentials(t *testing.T) {
|
||||
message := sanitizeFlareSolverrMessage("proxy socks5h://user:secret@resin:2260 failed; token=abc123 Authorization: Bearer.SECRET cookie=sso-value")
|
||||
for _, secret := range []string{"user", "secret", "abc123", "Bearer.SECRET", "sso-value"} {
|
||||
message := sanitizeFlareSolverrMessage("proxy socks5h://user:secret@resin:2260 and trojan://tunnel-secret@proxy.example:443 and vmess://base64-secret failed; token=abc123 Authorization: Bearer.SECRET cookie=sso-value")
|
||||
for _, secret := range []string{"user", "secret", "tunnel-secret", "base64-secret", "abc123", "Bearer.SECRET", "sso-value"} {
|
||||
if strings.Contains(message, secret) {
|
||||
t.Fatalf("sanitized message leaked %q: %q", secret, message)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy"
|
||||
xproxy "golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
@@ -81,6 +82,12 @@ func newPinnedHTTPSClient(proxyURL, serverName string, tlsConfig *tls.Config) (*
|
||||
return nil, fmt.Errorf("创建固定地址 SOCKS 代理: %w", err)
|
||||
}
|
||||
transport.DialContext = dialContext(dialer)
|
||||
case "trojan", "vless", "ss", "vmess":
|
||||
dialer, err := tunnelproxy.NewDialer(proxyURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建固定地址隧道代理: %w", err)
|
||||
}
|
||||
transport.DialContext = dialer.DialContext
|
||||
default:
|
||||
return nil, fmt.Errorf("固定地址请求不支持代理协议 %q", parsed.Scheme)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -15,6 +16,7 @@ import (
|
||||
tlsclient "github.com/bogdanfinn/tls-client"
|
||||
"github.com/bogdanfinn/tls-client/profiles"
|
||||
"github.com/bogdanfinn/websocket"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy"
|
||||
)
|
||||
|
||||
type browserClient struct{ inner tlsclient.HttpClient }
|
||||
@@ -62,7 +64,19 @@ func newBrowserClient(proxyURL, userAgent string) (*browserClient, error) {
|
||||
tlsclient.WithNotFollowRedirects(),
|
||||
}
|
||||
if proxyURL != "" {
|
||||
options = append(options, tlsclient.WithProxyUrl(proxyURL))
|
||||
parsed, err := url.Parse(proxyURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析浏览器出口代理: %w", err)
|
||||
}
|
||||
if tunnelproxy.IsSupportedScheme(parsed.Scheme) {
|
||||
dialer, err := tunnelproxy.NewDialer(proxyURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("创建浏览器隧道代理: %w", err)
|
||||
}
|
||||
options = append(options, tlsclient.WithDialContext(dialer.DialContext))
|
||||
} else {
|
||||
options = append(options, tlsclient.WithProxyUrl(proxyURL))
|
||||
}
|
||||
}
|
||||
client, err := tlsclient.NewHttpClient(tlsclient.NewNoopLogger(), options...)
|
||||
if err != nil {
|
||||
|
||||
@@ -642,7 +642,10 @@ func (r *AccountRepository) getRoutingQuotaWindows(ctx context.Context, provider
|
||||
return result, nil
|
||||
}
|
||||
modes := make([]string, 0, 2)
|
||||
if provider == account.ProviderWeb {
|
||||
// Paid Web chat routes are governed by the shared weekly pool. Imagine
|
||||
// products have independent authoritative windows and must not be hidden by
|
||||
// a weekly row merely because the same account also has paid chat access.
|
||||
if provider == account.ProviderWeb && !account.IsWebImagineQuotaMode(quotaMode) {
|
||||
modes = append(modes, "weekly")
|
||||
}
|
||||
if quotaMode != "" {
|
||||
@@ -2305,7 +2308,7 @@ func (r *AccountRepository) GetQuotaWindows(ctx context.Context, accountIDs []ui
|
||||
}
|
||||
|
||||
func (r *AccountRepository) SaveQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow) error {
|
||||
err := r.saveQuotaWindows(ctx, accountID, tier, syncedAt, values, false)
|
||||
err := r.saveQuotaWindows(ctx, accountID, tier, syncedAt, values, false, nil)
|
||||
if err == nil {
|
||||
r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountQuotaChanged, AccountID: accountID})
|
||||
}
|
||||
@@ -2313,14 +2316,48 @@ func (r *AccountRepository) SaveQuotaWindows(ctx context.Context, accountID uint
|
||||
}
|
||||
|
||||
func (r *AccountRepository) ReplaceQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow) error {
|
||||
err := r.saveQuotaWindows(ctx, accountID, tier, syncedAt, values, true)
|
||||
err := r.saveQuotaWindows(ctx, accountID, tier, syncedAt, values, true, nil)
|
||||
if err == nil {
|
||||
r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountQuotaChanged, AccountID: accountID})
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *AccountRepository) saveQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow, replace bool) error {
|
||||
func (r *AccountRepository) ReplaceQuotaWindowGroup(ctx context.Context, accountID uint64, syncedAt time.Time, modes []string, values []account.QuotaWindow) error {
|
||||
allowed := make(map[string]struct{}, len(modes))
|
||||
cleanModes := make([]string, 0, len(modes))
|
||||
for _, mode := range modes {
|
||||
mode = strings.TrimSpace(mode)
|
||||
if mode == "" {
|
||||
return repository.ErrConflict
|
||||
}
|
||||
if _, exists := allowed[mode]; !exists {
|
||||
allowed[mode] = struct{}{}
|
||||
cleanModes = append(cleanModes, mode)
|
||||
}
|
||||
}
|
||||
if accountID == 0 || len(cleanModes) == 0 {
|
||||
return repository.ErrConflict
|
||||
}
|
||||
seen := make(map[string]struct{}, len(values))
|
||||
for _, value := range values {
|
||||
mode := strings.TrimSpace(value.Mode)
|
||||
if _, ok := allowed[mode]; !ok {
|
||||
return repository.ErrConflict
|
||||
}
|
||||
if _, duplicate := seen[mode]; duplicate {
|
||||
return repository.ErrConflict
|
||||
}
|
||||
seen[mode] = struct{}{}
|
||||
}
|
||||
err := r.saveQuotaWindows(ctx, accountID, "", syncedAt, values, false, cleanModes)
|
||||
if err == nil {
|
||||
r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountQuotaChanged, AccountID: accountID})
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *AccountRepository) saveQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow, replace bool, replaceModes []string) error {
|
||||
return r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if tier != "" {
|
||||
profile := webAccountProfileModel{AccountID: accountID, Tier: string(tier), SyncedAt: &syncedAt}
|
||||
@@ -2332,6 +2369,10 @@ func (r *AccountRepository) saveQuotaWindows(ctx context.Context, accountID uint
|
||||
if err := tx.Where("account_id = ?", accountID).Delete("aWindowModel{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
} else if len(replaceModes) > 0 {
|
||||
if err := tx.Where("account_id = ? AND mode IN ?", accountID, replaceModes).Delete("aWindowModel{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, value := range values {
|
||||
serializedBreakdown := make([]quotaBreakdownJSON, 0, len(value.Breakdown))
|
||||
|
||||
@@ -101,7 +101,7 @@ func validatePreparedAudit(value preparedAudit) error {
|
||||
if !auditStringAllowed(row.Provider, "grok_build", "grok_web", "grok_console") {
|
||||
return errors.New("provider is invalid")
|
||||
}
|
||||
if !auditStringAllowed(row.Operation, "responses", "compaction", "chat", "messages", "image", "image_edit", "video") {
|
||||
if !auditStringAllowed(row.Operation, "responses", "compaction", "chat", "messages", "image", "image_edit", "video", "tts", "stt", "realtime", "voice") {
|
||||
return errors.New("operation is invalid")
|
||||
}
|
||||
if !auditStringAllowed(row.UsageSource, "upstream", "estimated", "none") {
|
||||
|
||||
@@ -790,16 +790,17 @@ func TestEgressOperationsStoresSubscriptionURLEncrypted(t *testing.T) {
|
||||
cipher := egressOperationsCipher(t)
|
||||
service := egressapp.NewService(nodes, cipher, "test-browser", accounts)
|
||||
url := "https://subscription.example/proxies?token=subscription-token"
|
||||
proxyURL := "socks5h://proxy-user:proxy-secret@proxy.example:1080"
|
||||
interval := 900
|
||||
capacity := 3
|
||||
created, err := service.CreateSource(ctx, egressapp.SubscriptionSourceInput{
|
||||
Name: "source", Scope: egress.ScopeBuild, Enabled: true, URL: &url,
|
||||
Name: "source", Scope: egress.ScopeBuild, Enabled: true, URL: &url, ProxyURL: &proxyURL,
|
||||
RefreshIntervalSeconds: &interval, DefaultAccountCapacity: &capacity,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !created.URLConfigured || created.DefaultAccountCapacity != capacity {
|
||||
if !created.URLConfigured || !created.ProxyConfigured || created.DefaultAccountCapacity != capacity {
|
||||
t.Fatalf("public source = %#v", created)
|
||||
}
|
||||
stored, err := nodes.GetEgressSource(ctx, created.ID)
|
||||
@@ -809,6 +810,79 @@ func TestEgressOperationsStoresSubscriptionURLEncrypted(t *testing.T) {
|
||||
if stored.EncryptedURL == url || strings.Contains(stored.EncryptedURL, "subscription-token") {
|
||||
t.Fatalf("subscription URL stored in plaintext: %q", stored.EncryptedURL)
|
||||
}
|
||||
if stored.EncryptedProxyURL == proxyURL || strings.Contains(stored.EncryptedProxyURL, "proxy-secret") {
|
||||
t.Fatalf("subscription proxy URL stored in plaintext: %q", stored.EncryptedProxyURL)
|
||||
}
|
||||
originalEncryptedProxyURL := stored.EncryptedProxyURL
|
||||
|
||||
updated, err := service.UpdateSource(ctx, created.ID, egressapp.SubscriptionSourceInput{
|
||||
Name: created.Name, Scope: created.Scope, Enabled: created.Enabled,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !updated.ProxyConfigured {
|
||||
t.Fatal("omitted proxy update cleared the configured proxy")
|
||||
}
|
||||
stored, err = nodes.GetEgressSource(ctx, created.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored.EncryptedProxyURL != originalEncryptedProxyURL {
|
||||
t.Fatal("omitted proxy update replaced the encrypted proxy")
|
||||
}
|
||||
|
||||
replacementProxyURL := "http://replacement-user:replacement-secret@proxy.example:8080"
|
||||
updated, err = service.UpdateSource(ctx, created.ID, egressapp.SubscriptionSourceInput{
|
||||
Name: created.Name, Scope: created.Scope, Enabled: created.Enabled, ProxyURL: &replacementProxyURL,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored, err = nodes.GetEgressSource(ctx, created.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decryptedProxyURL, err := cipher.Decrypt(stored.EncryptedProxyURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if decryptedProxyURL != replacementProxyURL || !updated.ProxyConfigured {
|
||||
t.Fatalf("replacement proxy = %q, public source = %#v", decryptedProxyURL, updated)
|
||||
}
|
||||
|
||||
for _, invalidProxyURL := range []string{"", "socks5h://Default.{account}:secret@proxy.example:1080"} {
|
||||
_, updateErr := service.UpdateSource(ctx, created.ID, egressapp.SubscriptionSourceInput{
|
||||
Name: created.Name, Scope: created.Scope, Enabled: created.Enabled, ProxyURL: &invalidProxyURL,
|
||||
})
|
||||
if !errors.Is(updateErr, egressapp.ErrInvalidInput) {
|
||||
t.Fatalf("invalid proxy %q error = %v", invalidProxyURL, updateErr)
|
||||
}
|
||||
}
|
||||
stored, err = nodes.GetEgressSource(ctx, created.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored.EncryptedProxyURL == "" {
|
||||
t.Fatal("invalid proxy update modified the configured proxy")
|
||||
}
|
||||
|
||||
updated, err = service.UpdateSource(ctx, created.ID, egressapp.SubscriptionSourceInput{
|
||||
Name: created.Name, Scope: created.Scope, Enabled: created.Enabled, ClearProxyURL: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if updated.ProxyConfigured {
|
||||
t.Fatal("cleared subscription proxy remains publicly configured")
|
||||
}
|
||||
stored, err = nodes.GetEgressSource(ctx, created.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored.EncryptedProxyURL != "" {
|
||||
t.Fatal("cleared subscription proxy remains encrypted at rest")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEgressOperationsSubscriptionImportCountsOnlyNewNodes(t *testing.T) {
|
||||
|
||||
@@ -468,9 +468,14 @@ func (r *EgressRepository) SaveEgressOperationsConfig(ctx context.Context, value
|
||||
row := fromEgressOperationsConfigDomain(value)
|
||||
row.ID = 1
|
||||
err := r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if _, err := lockEgressOperationsConfig(tx); err != nil {
|
||||
locked, err := lockEgressOperationsConfig(tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// This schema-only marker is deliberately outside the domain settings.
|
||||
// Preserve it across ordinary configuration updates so the legacy proxy
|
||||
// migration cannot run again and overwrite an intentionally direct source.
|
||||
row.SubscriptionProxyMigrationCompleted = locked.SubscriptionProxyMigrationCompleted
|
||||
if err := validateLockedEgressFallbackNodes(tx, row); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -823,7 +828,7 @@ func probeFamilyFromRow(status string, testedAt *time.Time, latencyMS int, exitI
|
||||
|
||||
func toEgressSubscriptionSourceDomain(row egressSubscriptionSourceModel) egress.SubscriptionSource {
|
||||
return egress.SubscriptionSource{
|
||||
ID: row.ID, Name: row.Name, Scope: egress.Scope(row.Scope), Enabled: row.Enabled, EncryptedURL: row.EncryptedURL,
|
||||
ID: row.ID, Name: row.Name, Scope: egress.Scope(row.Scope), Enabled: row.Enabled, EncryptedURL: row.EncryptedURL, EncryptedProxyURL: row.EncryptedProxyURL,
|
||||
RefreshIntervalSeconds: row.RefreshIntervalSeconds, DefaultAccountCapacity: row.DefaultAccountCapacity,
|
||||
LastSyncedAt: row.LastSyncedAt, NextSyncAt: row.NextSyncAt, LastSyncImported: row.LastSyncImported, LastSyncError: row.LastSyncError,
|
||||
CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt,
|
||||
@@ -832,7 +837,7 @@ func toEgressSubscriptionSourceDomain(row egressSubscriptionSourceModel) egress.
|
||||
|
||||
func fromEgressSubscriptionSourceDomain(value egress.SubscriptionSource) egressSubscriptionSourceModel {
|
||||
return egressSubscriptionSourceModel{
|
||||
ID: value.ID, Name: value.Name, Scope: string(value.Scope), Enabled: value.Enabled, EncryptedURL: value.EncryptedURL,
|
||||
ID: value.ID, Name: value.Name, Scope: string(value.Scope), Enabled: value.Enabled, EncryptedURL: value.EncryptedURL, EncryptedProxyURL: value.EncryptedProxyURL,
|
||||
RefreshIntervalSeconds: value.RefreshIntervalSeconds, DefaultAccountCapacity: value.DefaultAccountCapacity,
|
||||
LastSyncedAt: value.LastSyncedAt, NextSyncAt: value.NextSyncAt, LastSyncImported: value.LastSyncImported, LastSyncError: value.LastSyncError,
|
||||
CreatedAt: value.CreatedAt, UpdatedAt: value.UpdatedAt,
|
||||
@@ -843,8 +848,7 @@ func toEgressOperationsConfigDomain(row egressOperationsConfigModel) egress.Oper
|
||||
return egress.OperationsConfig{
|
||||
ProbeProvider: egress.ProbeProvider(row.ProbeProvider).Normalized(),
|
||||
ProbeIntervalSeconds: row.ProbeIntervalSeconds, AutoAssignEnabled: row.AutoAssignEnabled, AutoBalanceEnabled: row.AutoBalanceEnabled,
|
||||
AssignmentIntervalSeconds: row.AssignmentIntervalSeconds,
|
||||
EncryptedSubscriptionProxyURL: row.EncryptedSubscriptionProxyURL,
|
||||
AssignmentIntervalSeconds: row.AssignmentIntervalSeconds,
|
||||
Fallbacks: map[egress.Scope]egress.FallbackConfig{
|
||||
egress.ScopeBuild: {Mode: egress.FallbackMode(row.BuildFallbackMode).Normalized(), NodeID: row.BuildFallbackNodeID},
|
||||
egress.ScopeWeb: {Mode: egress.FallbackMode(row.WebFallbackMode).Normalized(), NodeID: row.WebFallbackNodeID},
|
||||
@@ -865,8 +869,7 @@ func fromEgressOperationsConfigDomain(value egress.OperationsConfig) egressOpera
|
||||
return egressOperationsConfigModel{
|
||||
ID: 1, ProbeProvider: string(value.ProbeProvider.Normalized()), ProbeIntervalSeconds: value.ProbeIntervalSeconds, AutoAssignEnabled: value.AutoAssignEnabled,
|
||||
AutoBalanceEnabled: value.AutoBalanceEnabled, AssignmentIntervalSeconds: value.AssignmentIntervalSeconds,
|
||||
EncryptedSubscriptionProxyURL: value.EncryptedSubscriptionProxyURL,
|
||||
BuildFallbackMode: string(buildFallback.Mode), BuildFallbackNodeID: buildFallback.NodeID,
|
||||
BuildFallbackMode: string(buildFallback.Mode), BuildFallbackNodeID: buildFallback.NodeID,
|
||||
WebFallbackMode: string(webFallback.Mode), WebFallbackNodeID: webFallback.NodeID,
|
||||
ConsoleFallbackMode: string(consoleFallback.Mode), ConsoleFallbackNodeID: consoleFallback.NodeID,
|
||||
WebAssetFallbackMode: string(webAssetFallback.Mode), WebAssetFallbackNodeID: webAssetFallback.NodeID,
|
||||
|
||||
@@ -129,7 +129,7 @@ func (r *MediaAssetRepository) ExpireMediaInputIfUnreferenced(ctx context.Contex
|
||||
activeReference := r.db.db.Model(&mediaJobModel{}).Select("1").
|
||||
Where("status IN ? AND input_json LIKE ?", []string{string(media.StatusQueued), string(media.StatusInProgress)}, referencePattern)
|
||||
result := r.db.db.WithContext(ctx).Model(&mediaAssetModel{}).
|
||||
Where("id = ? AND kind = ? AND expires_at IS NOT NULL", id, "image").
|
||||
Where("id = ? AND kind IN ? AND expires_at IS NOT NULL", id, []string{"image", "video"}).
|
||||
Where("NOT EXISTS (?)", activeReference).
|
||||
Update("expires_at", expiresAt)
|
||||
return result.RowsAffected > 0, result.Error
|
||||
@@ -483,12 +483,16 @@ func (r *MediaJobRepository) TryClaimMediaJob(ctx context.Context, id string, no
|
||||
}
|
||||
|
||||
func mediaJobFromDomain(value media.Job) *mediaJobModel {
|
||||
operation := value.Operation
|
||||
if operation == "" {
|
||||
operation = media.VideoOperationGenerate
|
||||
}
|
||||
return &mediaJobModel{
|
||||
ID: value.ID, RequestID: value.RequestID, ClientKeyID: value.ClientKeyID, ClientKeyName: value.ClientKeyName,
|
||||
AccountID: mediaJobAccountID(value.AccountID), AccountName: value.AccountName,
|
||||
EgressNodeID: value.EgressNodeID, EgressNodeName: value.EgressNodeName, EgressScope: value.EgressScope, EgressMode: value.EgressMode,
|
||||
Provider: value.Provider,
|
||||
Model: value.Model, ModelRouteID: value.ModelRouteID, UpstreamModel: value.UpstreamModel,
|
||||
Model: value.Model, ModelRouteID: value.ModelRouteID, UpstreamModel: value.UpstreamModel, Operation: string(operation),
|
||||
Prompt: value.Prompt, Seconds: value.Seconds, Size: value.Size, Quality: value.Quality,
|
||||
Status: string(value.Status), Progress: value.Progress, InputJSON: value.InputJSON, InputImageCount: mediaJobInputImageCount(value.InputImageCount), UpstreamURL: value.UpstreamURL,
|
||||
ResultAssetID: value.ResultAssetID, ContentType: value.ContentType, ErrorCode: value.ErrorCode, ErrorMessage: value.ErrorMessage,
|
||||
@@ -506,12 +510,16 @@ func mediaJobToDomain(row mediaJobModel) media.Job {
|
||||
if row.InputImageCount != nil {
|
||||
inputImageCount = *row.InputImageCount
|
||||
}
|
||||
operation := media.VideoOperation(row.Operation)
|
||||
if operation == "" {
|
||||
operation = media.VideoOperationGenerate
|
||||
}
|
||||
return media.Job{
|
||||
ID: row.ID, RequestID: row.RequestID, ClientKeyID: row.ClientKeyID, ClientKeyName: row.ClientKeyName,
|
||||
AccountID: accountID, AccountName: row.AccountName,
|
||||
EgressNodeID: row.EgressNodeID, EgressNodeName: row.EgressNodeName, EgressScope: row.EgressScope, EgressMode: row.EgressMode,
|
||||
Provider: row.Provider,
|
||||
Model: row.Model, ModelRouteID: row.ModelRouteID, UpstreamModel: row.UpstreamModel,
|
||||
Model: row.Model, ModelRouteID: row.ModelRouteID, UpstreamModel: row.UpstreamModel, Operation: operation,
|
||||
Prompt: row.Prompt, Seconds: row.Seconds, Size: row.Size, Quality: row.Quality,
|
||||
Status: media.Status(row.Status), Progress: row.Progress, InputJSON: row.InputJSON, InputImageCount: inputImageCount, UpstreamURL: row.UpstreamURL,
|
||||
ResultAssetID: row.ResultAssetID, ContentType: row.ContentType, ErrorCode: row.ErrorCode, ErrorMessage: row.ErrorMessage,
|
||||
|
||||
+100
-12
@@ -556,13 +556,15 @@ func TestReplaceProviderRoutesCanRenameUpstreamModels(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplaceProviderRoutesRenamesWebImagePublicIDs(t *testing.T) {
|
||||
func TestReplaceProviderRoutesRestoresWebImageLitePublicIDs(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
repo := NewModelRepository(database)
|
||||
if err := repo.UpsertRoutes(ctx, []model.Route{
|
||||
{PublicID: "grok-imagine-image", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImage, Enabled: true},
|
||||
{PublicID: "grok-imagine-image-quality", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImage, Enabled: true},
|
||||
{PublicID: "grok-imagine-image-2.0", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImage, Enabled: true},
|
||||
{PublicID: "grok-imagine-image-2.0", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImageEdit, Enabled: true},
|
||||
{PublicID: "grok-imagine-image-quality-2.0", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImage, Enabled: true},
|
||||
{PublicID: "grok-imagine-image-quality-2.0", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImageEdit, Enabled: true},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -570,6 +572,18 @@ func TestReplaceProviderRoutesRenamesWebImagePublicIDs(t *testing.T) {
|
||||
if err := database.db.WithContext(ctx).Where("provider = ?", account.ProviderWeb).Order("upstream_model ASC").Find(&before).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, route := range before {
|
||||
if route.Capability != string(model.CapabilityImage) {
|
||||
continue
|
||||
}
|
||||
alias := "Web/grok-imagine-image-lite"
|
||||
if route.UpstreamModel == "grok-imagine-image-quality" {
|
||||
alias = "Web/grok-imagine-image-quality-lite"
|
||||
}
|
||||
if err := database.db.WithContext(ctx).Create(&modelRouteAliasModel{Alias: alias, ModelRouteID: route.ID}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := repo.ReplaceProviderRoutes(ctx, account.ProviderWeb, []model.Route{
|
||||
{PublicID: "grok-imagine-image-lite", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImage, Enabled: true},
|
||||
{PublicID: "grok-imagine-image-quality-lite", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImage, Enabled: true},
|
||||
@@ -580,25 +594,99 @@ func TestReplaceProviderRoutesRenamesWebImagePublicIDs(t *testing.T) {
|
||||
if err := database.db.WithContext(ctx).Where("provider = ?", account.ProviderWeb).Order("upstream_model ASC").Find(&after).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(after) != 2 || after[0].PublicID != "Web/grok-imagine-image-lite" || after[1].PublicID != "Web/grok-imagine-image-quality-lite" {
|
||||
if len(after) != 2 {
|
||||
t.Fatalf("renamed routes = %#v", after)
|
||||
}
|
||||
beforeIDs := make(map[string]uint64, len(before))
|
||||
for _, route := range before {
|
||||
beforeIDs[route.UpstreamModel] = route.ID
|
||||
beforeIDs[route.UpstreamModel+"|"+route.Capability] = route.ID
|
||||
}
|
||||
for _, route := range after {
|
||||
if beforeIDs[route.UpstreamModel] != route.ID {
|
||||
wantPublicID := "Web/grok-imagine-image-lite"
|
||||
if route.UpstreamModel == "grok-imagine-image-quality" {
|
||||
wantPublicID = "Web/grok-imagine-image-quality-lite"
|
||||
}
|
||||
if route.Capability != string(model.CapabilityImage) || route.PublicID != wantPublicID || beforeIDs[route.UpstreamModel+"|"+route.Capability] != route.ID {
|
||||
t.Fatalf("route ID changed for %s: before=%#v after=%#v", route.UpstreamModel, before, after)
|
||||
}
|
||||
}
|
||||
for oldPublicID, upstreamModel := range map[string]string{
|
||||
"grok-imagine-image": "grok-imagine-image",
|
||||
"grok-imagine-image-quality": "grok-imagine-image-quality",
|
||||
} {
|
||||
compatibilityAliases := map[string]string{
|
||||
"grok-imagine-image-2.0": "Web/grok-imagine-image-lite",
|
||||
"grok-imagine-image-quality-2.0": "Web/grok-imagine-image-quality-lite",
|
||||
}
|
||||
for oldPublicID, wantPublicID := range compatibilityAliases {
|
||||
route, err := repo.GetByPublicIDIncludingDisabled(ctx, oldPublicID)
|
||||
if err != nil || route.UpstreamModel != upstreamModel || route.ID != beforeIDs[upstreamModel] {
|
||||
t.Fatalf("legacy alias %s resolved as %#v, err=%v", oldPublicID, route, err)
|
||||
if err != nil || route.PublicID != wantPublicID || route.Capability != model.CapabilityImage {
|
||||
t.Fatalf("Web compatibility alias %s resolved as %#v, err=%v", oldPublicID, route, err)
|
||||
}
|
||||
}
|
||||
var promotedAliasCount int64
|
||||
if err := database.db.WithContext(ctx).Model(&modelRouteAliasModel{}).
|
||||
Where("alias IN ?", []string{"Web/grok-imagine-image-lite", "Web/grok-imagine-image-quality-lite"}).
|
||||
Count(&promotedAliasCount).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if promotedAliasCount != 0 {
|
||||
t.Fatalf("promoted aliases remain: %d", promotedAliasCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplaceProviderRoutesRestoresThreeConsoleImageModels(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
repo := NewModelRepository(database)
|
||||
legacyCatalog := []model.Route{
|
||||
{PublicID: "grok-imagine-image-quality-2.0", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImage, Enabled: true},
|
||||
{PublicID: "grok-imagine-image-quality-2.0", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImageEdit, Enabled: true},
|
||||
{PublicID: "grok-imagine-image-2.0", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImage, Enabled: true},
|
||||
{PublicID: "grok-imagine-image-2.0", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImageEdit, Enabled: true},
|
||||
}
|
||||
if err := repo.UpsertRoutes(ctx, legacyCatalog); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var before []modelRouteModel
|
||||
if err := database.db.WithContext(ctx).Where("provider = ?", account.ProviderConsole).Find(&before).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
beforeIDs := make(map[string]uint64, len(before))
|
||||
for _, route := range before {
|
||||
beforeIDs[route.UpstreamModel+"|"+route.Capability] = route.ID
|
||||
}
|
||||
desiredCatalog := []model.Route{
|
||||
// Legacy and quality must be reconciled before the new 2.0 route so the
|
||||
// rows created by the temporary two-model catalog retain their IDs.
|
||||
{PublicID: "grok-imagine-image", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImage, Enabled: true},
|
||||
{PublicID: "grok-imagine-image", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImageEdit, Enabled: true},
|
||||
{PublicID: "grok-imagine-image-quality", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImage, Enabled: true},
|
||||
{PublicID: "grok-imagine-image-quality", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImageEdit, Enabled: true},
|
||||
{PublicID: "grok-imagine-image-2.0", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image-2.0", Capability: model.CapabilityImage, Enabled: true},
|
||||
{PublicID: "grok-imagine-image-2.0", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image-2.0", Capability: model.CapabilityImageEdit, Enabled: true},
|
||||
}
|
||||
for range 2 {
|
||||
if err := repo.ReplaceProviderRoutes(ctx, account.ProviderConsole, desiredCatalog); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var after []modelRouteModel
|
||||
if err := database.db.WithContext(ctx).Where("provider = ? AND upstream_model LIKE ?", account.ProviderConsole, "grok-imagine-image%").Order("id ASC").Find(&after).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(after) != 6 {
|
||||
t.Fatalf("Console image routes = %#v", after)
|
||||
}
|
||||
seen := make(map[string]map[string]bool)
|
||||
for _, route := range after {
|
||||
if seen[route.PublicID] == nil {
|
||||
seen[route.PublicID] = make(map[string]bool)
|
||||
}
|
||||
seen[route.PublicID][route.Capability] = true
|
||||
if route.UpstreamModel != "grok-imagine-image-2.0" && beforeIDs[route.UpstreamModel+"|"+route.Capability] != route.ID {
|
||||
t.Fatalf("existing Console route ID changed: before=%#v after=%#v", before, after)
|
||||
}
|
||||
}
|
||||
for _, publicID := range []string{"Console/grok-imagine-image", "Console/grok-imagine-image-quality", "Console/grok-imagine-image-2.0"} {
|
||||
if !seen[publicID][string(model.CapabilityImage)] || !seen[publicID][string(model.CapabilityImageEdit)] {
|
||||
t.Fatalf("Console image capabilities for %s = %#v", publicID, seen[publicID])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -747,13 +747,17 @@ func discoveredRouteDefaults(provider account.Provider, upstreamModel string) (s
|
||||
return upstreamModel, model.CapabilityResponses
|
||||
case account.ProviderConsole:
|
||||
switch upstreamModel {
|
||||
case "grok-imagine-image", "grok-imagine-image-quality":
|
||||
case "grok-imagine-image", "grok-imagine-image-quality", "grok-imagine-image-2.0":
|
||||
// The catalog also registers image_edit for the same public model.
|
||||
// Discovery only needs one existing managed capability to remain
|
||||
// idempotent and must never synthesize a Responses route.
|
||||
return upstreamModel, model.CapabilityImage
|
||||
case "grok-imagine-video":
|
||||
case "grok-imagine-video", "grok-imagine-video-1.5":
|
||||
return upstreamModel, model.CapabilityVideo
|
||||
case "grok-voice-latest", "grok-voice-think-fast-2.0", "grok-voice-think-fast-1.0":
|
||||
return upstreamModel, model.CapabilityRealtime
|
||||
case "grok-stt":
|
||||
return upstreamModel, model.CapabilitySTT
|
||||
default:
|
||||
return upstreamModel, model.CapabilityResponses
|
||||
}
|
||||
@@ -882,6 +886,40 @@ func (r *ModelRepository) ReplaceProviderRoutes(ctx context.Context, provider ac
|
||||
return err
|
||||
}
|
||||
}
|
||||
// A catalog name may have multiple capability rows. When a previous
|
||||
// catalog rename preserved that name as an alias to one member, restoring
|
||||
// it must promote the alias back to the formal group name before every
|
||||
// matched capability row is validated. Aliases owned by another group
|
||||
// remain conflicts and are never reclaimed.
|
||||
matchedIDsByPublicID := make(map[string]map[uint64]struct{}, len(values))
|
||||
for index, value := range values {
|
||||
row, ok := matched[index]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
ids := matchedIDsByPublicID[value.PublicID]
|
||||
if ids == nil {
|
||||
ids = make(map[uint64]struct{})
|
||||
matchedIDsByPublicID[value.PublicID] = ids
|
||||
}
|
||||
ids[row.ID] = struct{}{}
|
||||
}
|
||||
for publicID, routeIDs := range matchedIDsByPublicID {
|
||||
var alias modelRouteAliasModel
|
||||
err := tx.Where("alias = ?", publicID).First(&alias).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, owned := routeIDs[alias.ModelRouteID]; !owned {
|
||||
return fmt.Errorf("%w: 模型公开 ID %q 已被路由 %d 保留为兼容名称", repository.ErrConflict, publicID, alias.ModelRouteID)
|
||||
}
|
||||
if err := tx.Delete(&modelRouteAliasModel{}, "alias = ?", publicID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for index, value := range values {
|
||||
routeID := uint64(0)
|
||||
if row, ok := matched[index]; ok {
|
||||
|
||||
@@ -185,7 +185,7 @@ type modelRouteModel struct {
|
||||
PublicID string `gorm:"size:255;index:idx_model_routes_public_id_lookup;not null;check:chk_model_routes_public_id,length(trim(public_id)) BETWEEN 1 AND 255"`
|
||||
Provider string `gorm:"size:32;index:idx_model_routes_provider_upstream;not null;check:chk_model_routes_provider,provider IN ('grok_build','grok_web','grok_console')"`
|
||||
UpstreamModel string `gorm:"size:255;index:idx_model_routes_provider_upstream;not null;check:chk_model_routes_upstream_model,length(trim(upstream_model)) BETWEEN 1 AND 255"`
|
||||
Capability string `gorm:"size:32;not null;check:chk_model_routes_capability,capability IN ('responses','chat','image','image_edit','video')"`
|
||||
Capability string `gorm:"size:32;not null;check:chk_model_routes_capability,capability IN ('responses','chat','image','image_edit','video','tts','stt','realtime')"`
|
||||
Origin string `gorm:"size:32;not null;default:discovered;check:chk_model_routes_origin,origin IN ('catalog','discovered','manual')"`
|
||||
Enabled bool `gorm:"not null"`
|
||||
CreatedAt time.Time `gorm:"not null"`
|
||||
@@ -297,7 +297,7 @@ type requestAuditModel struct {
|
||||
ModelPublicID string `gorm:"size:255;check:chk_request_audits_model_public_id,length(model_public_id) <= 255"`
|
||||
ModelUpstreamModel string `gorm:"size:255;check:chk_request_audits_model_upstream_model,length(model_upstream_model) <= 255"`
|
||||
Provider string `gorm:"size:32;not null;check:chk_request_audits_provider,provider IN ('grok_build','grok_web','grok_console')"`
|
||||
Operation string `gorm:"size:32;not null;check:chk_request_audits_operation,operation IN ('responses','compaction','chat','messages','image','image_edit','video')"`
|
||||
Operation string `gorm:"size:32;not null;check:chk_request_audits_operation,operation IN ('responses','compaction','chat','messages','image','image_edit','video','tts','stt','realtime','voice')"`
|
||||
UsageSource string `gorm:"size:16;not null;check:chk_request_audits_usage_source,usage_source IN ('upstream','estimated','none')"`
|
||||
AccountID *uint64 `gorm:"check:chk_request_audits_account_id,account_id IS NULL OR account_id > 0"`
|
||||
AccountName string `gorm:"size:160;check:chk_request_audits_account_name,length(account_name) <= 160"`
|
||||
@@ -404,10 +404,11 @@ type mediaJobModel struct {
|
||||
Model string `gorm:"size:255;not null;check:chk_media_jobs_model,length(trim(model)) BETWEEN 1 AND 255"`
|
||||
ModelRouteID uint64 `gorm:"not null;check:chk_media_jobs_model_route_id,model_route_id > 0"`
|
||||
UpstreamModel string `gorm:"size:255;not null;check:chk_media_jobs_upstream_model,length(trim(upstream_model)) BETWEEN 1 AND 255"`
|
||||
Operation string `gorm:"size:16;not null;default:'generate';check:chk_media_jobs_operation,operation IN ('generate','edit','extend')"`
|
||||
Prompt string `gorm:"type:text;not null;check:chk_media_jobs_prompt,length(prompt) BETWEEN 0 AND 100000"`
|
||||
Seconds int `gorm:"not null;check:chk_media_jobs_seconds,seconds BETWEEN 1 AND 15"`
|
||||
Size string `gorm:"size:32;not null;check:chk_media_jobs_size,length(trim(size)) BETWEEN 1 AND 32"`
|
||||
Quality string `gorm:"size:32;not null;check:chk_media_jobs_quality,length(trim(quality)) BETWEEN 1 AND 32"`
|
||||
Seconds int `gorm:"not null;check:chk_media_jobs_seconds,seconds BETWEEN 0 AND 15"`
|
||||
Size string `gorm:"size:32;not null;default:'';check:chk_media_jobs_size,length(trim(size)) BETWEEN 0 AND 32"`
|
||||
Quality string `gorm:"size:32;not null;default:'';check:chk_media_jobs_quality,length(trim(quality)) BETWEEN 0 AND 32"`
|
||||
Status string `gorm:"size:32;not null;check:chk_media_jobs_status,status IN ('queued','in_progress','completed','failed')"`
|
||||
Progress int `gorm:"not null;check:chk_media_jobs_progress,progress BETWEEN 0 AND 100"`
|
||||
// InputJSON limit 33554432 must stay equal to media.MaxInputJSONBytes (GORM tags require literals).
|
||||
@@ -477,6 +478,7 @@ type egressSubscriptionSourceModel struct {
|
||||
Scope string `gorm:"size:32;not null;check:chk_egress_subscription_sources_scope,scope IN ('grok_build','grok_web','grok_console','grok_web_asset','grok_console_asset')"`
|
||||
Enabled bool `gorm:"not null;default:true"`
|
||||
EncryptedURL string `gorm:"type:text;not null;default:'';check:chk_egress_subscription_sources_url,length(encrypted_url) <= 65536"`
|
||||
EncryptedProxyURL string `gorm:"type:text;not null;default:'';check:chk_egress_subscription_sources_proxy_url,length(encrypted_proxy_url) <= 65536"`
|
||||
RefreshIntervalSeconds int `gorm:"not null;default:900;check:chk_egress_subscription_sources_refresh,refresh_interval_seconds BETWEEN 60 AND 86400"`
|
||||
DefaultAccountCapacity int `gorm:"not null;default:0;check:chk_egress_subscription_sources_capacity,default_account_capacity BETWEEN 0 AND 100000"`
|
||||
LastSyncedAt *time.Time
|
||||
@@ -532,24 +534,24 @@ type egressNodeModel struct {
|
||||
func (egressNodeModel) TableName() string { return "egress_nodes" }
|
||||
|
||||
type egressOperationsConfigModel struct {
|
||||
ID uint64 `gorm:"primaryKey;check:chk_egress_operations_config_id,id = 1"`
|
||||
ProbeProvider string `gorm:"size:16;not null;default:cloudflare;check:chk_egress_operations_config_probe_provider,probe_provider IN ('ipinfo','cloudflare')"`
|
||||
ProbeIntervalSeconds int `gorm:"not null;default:900;check:chk_egress_operations_config_probe_interval,probe_interval_seconds BETWEEN 60 AND 86400"`
|
||||
AutoAssignEnabled bool `gorm:"not null;default:false"`
|
||||
AutoBalanceEnabled bool `gorm:"not null;default:false"`
|
||||
AssignmentIntervalSeconds int `gorm:"not null;default:300;check:chk_egress_operations_config_assignment_interval,assignment_interval_seconds BETWEEN 60 AND 86400"`
|
||||
EncryptedSubscriptionProxyURL string `gorm:"type:text;not null;default:'';check:chk_egress_operations_config_subscription_proxy,length(encrypted_subscription_proxy_url) <= 65536"`
|
||||
BuildFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
BuildFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
WebFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
WebFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
ConsoleFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
ConsoleFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
WebAssetFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
WebAssetFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
ConsoleAssetFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
ConsoleAssetFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
UpdatedAt time.Time `gorm:"not null"`
|
||||
ID uint64 `gorm:"primaryKey;check:chk_egress_operations_config_id,id = 1"`
|
||||
ProbeProvider string `gorm:"size:16;not null;default:cloudflare;check:chk_egress_operations_config_probe_provider,probe_provider IN ('ipinfo','cloudflare')"`
|
||||
ProbeIntervalSeconds int `gorm:"not null;default:900;check:chk_egress_operations_config_probe_interval,probe_interval_seconds BETWEEN 60 AND 86400"`
|
||||
AutoAssignEnabled bool `gorm:"not null;default:false"`
|
||||
AutoBalanceEnabled bool `gorm:"not null;default:false"`
|
||||
AssignmentIntervalSeconds int `gorm:"not null;default:300;check:chk_egress_operations_config_assignment_interval,assignment_interval_seconds BETWEEN 60 AND 86400"`
|
||||
SubscriptionProxyMigrationCompleted bool `gorm:"not null;default:false"`
|
||||
BuildFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
BuildFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
WebFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
WebFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
ConsoleFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
ConsoleFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
WebAssetFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
WebAssetFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
ConsoleAssetFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
ConsoleAssetFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
UpdatedAt time.Time `gorm:"not null"`
|
||||
}
|
||||
|
||||
func (egressOperationsConfigModel) TableName() string { return "egress_operations_config" }
|
||||
@@ -256,6 +256,47 @@ func TestAccountRepositoryDecrementsQuotaByAmountAtomically(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountRepositoryReplacesQuotaGroupWithoutTouchingOtherModes(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := NewAccountRepository(openTestDatabase(t))
|
||||
value, _, err := repo.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderWeb, AuthType: account.AuthTypeSSO, Name: "quota-group", SourceKey: "quota-group",
|
||||
EncryptedAccessToken: testEncryptedToken, AuthStatus: account.AuthStatusActive,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
initial := []account.QuotaWindow{
|
||||
{AccountID: value.ID, Mode: "weekly", Remaining: 90, Total: 100, UpdatedAt: now},
|
||||
{AccountID: value.ID, Mode: account.QuotaModeWebImagePro, Remaining: 4, UpdatedAt: now},
|
||||
{AccountID: value.ID, Mode: account.QuotaModeWebVideo720p, Remaining: 1, UpdatedAt: now},
|
||||
}
|
||||
if err := repo.SaveQuotaWindows(ctx, value.ID, account.WebTierSuper, now, initial); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updatedAt := now.Add(time.Minute)
|
||||
if err := repo.ReplaceQuotaWindowGroup(ctx, value.ID, updatedAt, account.WebImagineQuotaModes(), []account.QuotaWindow{
|
||||
{AccountID: value.ID, Mode: account.QuotaModeWebImagePro, Remaining: 3, UpdatedAt: updatedAt},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
windows, err := repo.GetQuotaWindows(ctx, []uint64{value.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
byMode := make(map[string]account.QuotaWindow)
|
||||
for _, window := range windows[value.ID] {
|
||||
byMode[window.Mode] = window
|
||||
}
|
||||
if byMode["weekly"].Remaining != 90 || byMode[account.QuotaModeWebImagePro].Remaining != 3 {
|
||||
t.Fatalf("windows = %#v", windows[value.ID])
|
||||
}
|
||||
if _, exists := byMode[account.QuotaModeWebVideo720p]; exists {
|
||||
t.Fatalf("explicitly unavailable group mode was preserved: %#v", windows[value.ID])
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountRepositorySummarizesOperationalStates(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
|
||||
@@ -44,6 +44,9 @@ func TestRoutingProjectionLeavesSecretsAndLargeJSONOutOfCandidateLoad(t *testing
|
||||
AccountID: created.ID, Mode: "weekly", Remaining: 10, Total: 20, UsagePercent: 50,
|
||||
Breakdown: []account.QuotaBreakdown{{ProductCode: account.QuotaProductChat, UsagePercent: 50}},
|
||||
WindowSeconds: 3600, ResetAt: &resetAt, SyncedAt: &now, Source: account.QuotaSourceUpstream,
|
||||
}, {
|
||||
AccountID: created.ID, Mode: account.QuotaModeWebImagePro, Remaining: 3,
|
||||
WindowSeconds: 86400, SyncedAt: &now, Source: account.QuotaSourceUpstream,
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -62,6 +65,13 @@ func TestRoutingProjectionLeavesSecretsAndLargeJSONOutOfCandidateLoad(t *testing
|
||||
if bases[0].QuotaWindow == nil || bases[0].QuotaWindow.Remaining != 10 || len(bases[0].QuotaWindow.Breakdown) != 0 {
|
||||
t.Fatalf("routing quota = %#v, want scalar quota without breakdown", bases[0].QuotaWindow)
|
||||
}
|
||||
imagineBases, err := accounts.ListRoutingAccountBases(ctx, account.ProviderWeb, account.QuotaModeWebImagePro)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(imagineBases) != 1 || imagineBases[0].QuotaWindow == nil || imagineBases[0].QuotaWindow.Mode != account.QuotaModeWebImagePro || imagineBases[0].QuotaWindow.Remaining != 3 {
|
||||
t.Fatalf("Imagine routing quota = %#v", imagineBases)
|
||||
}
|
||||
|
||||
candidates, err := accounts.ListRoutingCandidates(ctx, account.ProviderWeb, 0, "grok-test", "")
|
||||
if err != nil {
|
||||
@@ -94,8 +104,8 @@ func TestRoutingProjectionLeavesSecretsAndLargeJSONOutOfCandidateLoad(t *testing
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(windows[created.ID]) != 1 || len(windows[created.ID][0].Breakdown) != 1 {
|
||||
t.Fatalf("management quota windows = %#v, want breakdown", windows)
|
||||
if len(windows[created.ID]) != 2 {
|
||||
t.Fatalf("management quota windows = %#v, want two modes", windows)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/media"
|
||||
settingsdomain "github.com/chenyme/grok2api/backend/internal/domain/settings"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
const mediaJobInputMetadataPendingIndex = "CREATE INDEX IF NOT EXISTS idx_media_jobs_input_metadata_pending ON media_jobs(id) WHERE input_image_count IS NULL"
|
||||
@@ -129,6 +130,7 @@ func (d *Database) initializeSchema(ctx context.Context) error {
|
||||
hadProviderScope := hadClientKeys && db.Migrator().HasColumn(&clientKeyModel{}, "ProviderScopeMask")
|
||||
hadTierScope := hadClientKeys && db.Migrator().HasColumn(&clientKeyModel{}, "TierScopeMask")
|
||||
hadLegacyAccountPool := hadClientKeys && db.Migrator().HasColumn("client_keys", "account_pool")
|
||||
hadGlobalSubscriptionProxy := db.Migrator().HasTable("egress_operations_config") && db.Migrator().HasColumn("egress_operations_config", "encrypted_subscription_proxy_url")
|
||||
// all 作用域会让 Build 与 Web 共用 UA、健康度和冷却状态,升级时直接移除旧节点。
|
||||
if db.Migrator().HasTable(&egressNodeModel{}) {
|
||||
if err := db.Where("scope = ?", "all").Delete(&egressNodeModel{}).Error; err != nil {
|
||||
@@ -149,6 +151,11 @@ func (d *Database) initializeSchema(ctx context.Context) error {
|
||||
if migrateErr != nil {
|
||||
return fmt.Errorf("初始化数据库表: %w", migrateErr)
|
||||
}
|
||||
if hadGlobalSubscriptionProxy {
|
||||
if err := d.migratePerSourceSubscriptionProxy(ctx); err != nil {
|
||||
return fmt.Errorf("迁移代理订阅拉取代理: %w", err)
|
||||
}
|
||||
}
|
||||
if err := d.migrateClientKeyAccountScopes(ctx, hadLegacyAccountPool, !hadProviderScope, !hadTierScope); err != nil {
|
||||
return fmt.Errorf("迁移客户端 Key 调用范围: %w", err)
|
||||
}
|
||||
@@ -167,9 +174,15 @@ func (d *Database) initializeSchema(ctx context.Context) error {
|
||||
if err := d.ensureAuditOperationConstraints(ctx); err != nil {
|
||||
return fmt.Errorf("迁移请求审计操作约束: %w", err)
|
||||
}
|
||||
if err := d.ensureModelRouteCapabilityConstraints(ctx); err != nil {
|
||||
return fmt.Errorf("迁移模型路由能力约束: %w", err)
|
||||
}
|
||||
if err := d.ensureMediaJobConstraints(ctx); err != nil {
|
||||
return fmt.Errorf("迁移 media job 数据库约束: %w", err)
|
||||
}
|
||||
if err := d.migrateMediaJobOperations(ctx); err != nil {
|
||||
return fmt.Errorf("迁移 media job 操作类型: %w", err)
|
||||
}
|
||||
if err := d.ensureMediaJobInputConstraint(ctx); err != nil {
|
||||
return fmt.Errorf("迁移 media job 输入长度约束: %w", err)
|
||||
}
|
||||
@@ -216,6 +229,43 @@ func (d *Database) initializeSchema(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Database) migratePerSourceSubscriptionProxy(ctx context.Context) error {
|
||||
return d.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var legacy struct {
|
||||
EncryptedProxyURL string `gorm:"column:encrypted_subscription_proxy_url"`
|
||||
MigrationCompleted bool `gorm:"column:subscription_proxy_migration_completed"`
|
||||
}
|
||||
err := tx.Table("egress_operations_config").
|
||||
Select("encrypted_subscription_proxy_url", "subscription_proxy_migration_completed").
|
||||
Where("id = ?", 1).
|
||||
Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Take(&legacy).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if legacy.MigrationCompleted {
|
||||
return nil
|
||||
}
|
||||
if strings.TrimSpace(legacy.EncryptedProxyURL) != "" {
|
||||
if err := tx.Model(&egressSubscriptionSourceModel{}).Where("encrypted_proxy_url = ''").Updates(map[string]any{
|
||||
"encrypted_proxy_url": legacy.EncryptedProxyURL,
|
||||
"next_sync_at": nil,
|
||||
"last_sync_error": "",
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Keep the encrypted legacy value for still-running old replicas and a
|
||||
// rollback window. The marker prevents subsequent startups from applying
|
||||
// it to sources that were later configured for direct fetching.
|
||||
return tx.Table("egress_operations_config").Where("id = ?", 1).
|
||||
Update("subscription_proxy_migration_completed", true).Error
|
||||
})
|
||||
}
|
||||
|
||||
// migrateClientKeyAccountScopes translates the short-lived account_pool
|
||||
// representation only when the corresponding scope columns are first added.
|
||||
func (d *Database) migrateClientKeyAccountScopes(ctx context.Context, hadLegacyAccountPool, providerScopeAdded, tierScopeAdded bool) error {
|
||||
@@ -386,11 +436,19 @@ func (d *Database) ensureEgressAssetScopeConstraints(ctx context.Context) error
|
||||
}
|
||||
|
||||
// ensureAuditOperationConstraints upgrades existing databases so Codex remote
|
||||
// compaction can be recorded separately from ordinary Responses requests.
|
||||
// compaction and Console voice operations can be recorded separately.
|
||||
func (d *Database) ensureAuditOperationConstraints(ctx context.Context) error {
|
||||
return d.ensureNamedConstraints(ctx, []consoleConstraint{
|
||||
{model: &requestAuditModel{}, table: "request_audits", name: "chk_request_audits_operation"},
|
||||
}, "compaction")
|
||||
}, "tts")
|
||||
}
|
||||
|
||||
// ensureModelRouteCapabilityConstraints upgrades existing databases so Console
|
||||
// TTS/STT/Realtime routes can be managed alongside image and video.
|
||||
func (d *Database) ensureModelRouteCapabilityConstraints(ctx context.Context) error {
|
||||
return d.ensureNamedConstraints(ctx, []consoleConstraint{
|
||||
{model: &modelRouteModel{}, table: "model_routes", name: "chk_model_routes_capability"},
|
||||
}, "tts")
|
||||
}
|
||||
|
||||
// ensureMediaJobConstraints 将历史仅允许 grok_web 的 media job CHECK 升级到支持 Build 与 Console 视频。
|
||||
@@ -401,9 +459,43 @@ func (d *Database) ensureMediaJobConstraints(ctx context.Context) error {
|
||||
}, "grok_console"); err != nil {
|
||||
return err
|
||||
}
|
||||
return d.ensureNamedConstraints(ctx, []consoleConstraint{
|
||||
if err := d.ensureNamedConstraints(ctx, []consoleConstraint{
|
||||
{model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_egress_scope"},
|
||||
}, "grok_console")
|
||||
}, "grok_console"); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, constraint := range []consoleConstraint{
|
||||
{model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_operation"},
|
||||
{model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_seconds"},
|
||||
{model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_size"},
|
||||
{model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_quality"},
|
||||
} {
|
||||
marker := "0"
|
||||
if constraint.name == "chk_media_jobs_operation" {
|
||||
marker = "extend"
|
||||
}
|
||||
if err := d.ensureNamedConstraints(ctx, []consoleConstraint{constraint}, marker); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// migrateMediaJobOperations preserves queued and in-progress edit/extension
|
||||
// jobs created before media_jobs.operation existed. Those releases persisted
|
||||
// the operation only in the compact JSON metadata; AutoMigrate necessarily
|
||||
// fills the new non-null column with "generate", which must not change the
|
||||
// request semantics when a job is recovered after an upgrade.
|
||||
func (d *Database) migrateMediaJobOperations(ctx context.Context) error {
|
||||
editPattern := `%"operation":"edit"%`
|
||||
extendPattern := `%"operation":"extend"%`
|
||||
return d.db.WithContext(ctx).Exec(
|
||||
`UPDATE media_jobs
|
||||
SET operation = CASE WHEN input_json LIKE ? THEN ? ELSE ? END
|
||||
WHERE operation = ? AND (input_json LIKE ? OR input_json LIKE ?)`,
|
||||
editPattern, media.VideoOperationEdit, media.VideoOperationExtend,
|
||||
media.VideoOperationGenerate, editPattern, extendPattern,
|
||||
).Error
|
||||
}
|
||||
|
||||
// ensureMediaJobInputConstraint 允许异步视频任务持久化 Base64 首图。
|
||||
|
||||
@@ -61,6 +61,28 @@ func TestMediaJobModelTagsAllowAllVideoProvidersAndPrimaryScopes(t *testing.T) {
|
||||
!strings.Contains(countTag, "IS NULL OR input_image_count BETWEEN 0 AND "+maxImages) {
|
||||
t.Fatalf("input_image_count tag = %q, want max %s", countTag, maxImages)
|
||||
}
|
||||
operationField, ok := modelType.FieldByName("Operation")
|
||||
if !ok {
|
||||
t.Fatal("Operation field missing")
|
||||
}
|
||||
operationTag := operationField.Tag.Get("gorm")
|
||||
if !strings.Contains(operationTag, "chk_media_jobs_operation") ||
|
||||
!strings.Contains(operationTag, "'generate','edit','extend'") {
|
||||
t.Fatalf("operation tag = %q", operationTag)
|
||||
}
|
||||
for fieldName, expected := range map[string]string{
|
||||
"Seconds": "seconds BETWEEN 0 AND 15",
|
||||
"Size": "length(trim(size)) BETWEEN 0 AND 32",
|
||||
"Quality": "length(trim(quality)) BETWEEN 0 AND 32",
|
||||
} {
|
||||
field, exists := modelType.FieldByName(fieldName)
|
||||
if !exists {
|
||||
t.Fatalf("%s field missing", fieldName)
|
||||
}
|
||||
if tag := field.Tag.Get("gorm"); !strings.Contains(tag, expected) {
|
||||
t.Fatalf("%s tag = %q, want %q", fieldName, tag, expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaJobInputMetadataPendingIndexExists(t *testing.T) {
|
||||
@@ -95,6 +117,61 @@ func TestMediaJobInputMetadataPendingIndexExists(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitializeSchemaBackfillsLegacyMediaJobOperations(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
accountValue, _, err := NewAccountRepository(database).UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
Provider: accountdomain.ProviderConsole, AuthType: accountdomain.AuthTypeSSO,
|
||||
Name: "legacy-video-operation", SourceKey: "legacy-video-operation",
|
||||
EncryptedAccessToken: testEncryptedToken, AuthStatus: accountdomain.AuthStatusActive,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := clientKeyModel{Name: "legacy-video-operation", Prefix: "legacy-video-operation", SecretHash: testSecretHash, EncryptedSecret: testEncryptedToken, Enabled: true, RPMLimit: 60, MaxConcurrent: 4}
|
||||
if err := database.db.WithContext(ctx).Create(&key).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
jobs := NewMediaJobRepository(database)
|
||||
for index, operation := range []mediadomain.VideoOperation{mediadomain.VideoOperationEdit, mediadomain.VideoOperationExtend} {
|
||||
job := testMediaJob(fmt.Sprintf("video_legacy_operation_%d", index), accountValue.ID, key.ID, mediadomain.StatusQueued, now)
|
||||
job.Operation = mediadomain.VideoOperationGenerate
|
||||
job.InputJSON = fmt.Sprintf(`{"operation":%q,"video_url":"https://example.com/source.mp4"}`, operation)
|
||||
if err := jobs.CreateMediaJob(ctx, job); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
generate := testMediaJob("video_legitimate_generate", accountValue.ID, key.ID, mediadomain.StatusQueued, now)
|
||||
generate.InputJSON = `{}`
|
||||
if err := jobs.CreateMediaJob(ctx, generate); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for index, want := range []string{"edit", "extend"} {
|
||||
var row mediaJobModel
|
||||
if err := database.db.WithContext(ctx).Where("id = ?", fmt.Sprintf("video_legacy_operation_%d", index)).First(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if row.Operation != want {
|
||||
t.Fatalf("legacy operation = %q, want %q", row.Operation, want)
|
||||
}
|
||||
}
|
||||
var generateRow mediaJobModel
|
||||
if err := database.db.WithContext(ctx).Where("id = ?", generate.ID).First(&generateRow).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if generateRow.Operation != "generate" {
|
||||
t.Fatalf("generate operation = %q", generateRow.Operation)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitializeSchemaUpgradesOnlyPreviousMediaJobInputConstraint(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "previous-media-input.db"))
|
||||
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
package relational
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
)
|
||||
|
||||
type legacyOperationsConfigWithSubscriptionProxy struct {
|
||||
ID uint64 `gorm:"primaryKey"`
|
||||
ProbeProvider string `gorm:"size:16;not null;default:cloudflare"`
|
||||
ProbeIntervalSeconds int `gorm:"not null;default:900"`
|
||||
AutoAssignEnabled bool `gorm:"not null;default:false"`
|
||||
AutoBalanceEnabled bool `gorm:"not null;default:false"`
|
||||
AssignmentIntervalSeconds int `gorm:"not null;default:300"`
|
||||
EncryptedSubscriptionProxyURL string `gorm:"type:text;not null;default:''"`
|
||||
BuildFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
BuildFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
WebFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
WebFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
ConsoleFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
ConsoleFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
WebAssetFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
WebAssetFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
ConsoleAssetFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
ConsoleAssetFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
UpdatedAt time.Time `gorm:"not null"`
|
||||
}
|
||||
|
||||
func (legacyOperationsConfigWithSubscriptionProxy) TableName() string {
|
||||
return "egress_operations_config"
|
||||
}
|
||||
|
||||
type legacySubscriptionSourceWithoutProxy struct {
|
||||
ID uint64 `gorm:"primaryKey"`
|
||||
Name string `gorm:"size:160;not null"`
|
||||
Scope string `gorm:"size:32;not null"`
|
||||
Enabled bool `gorm:"not null;default:true"`
|
||||
EncryptedURL string `gorm:"type:text;not null;default:''"`
|
||||
RefreshIntervalSeconds int `gorm:"not null;default:900"`
|
||||
DefaultAccountCapacity int `gorm:"not null;default:0"`
|
||||
LastSyncedAt *time.Time
|
||||
NextSyncAt *time.Time
|
||||
LastSyncImported int `gorm:"not null;default:0"`
|
||||
LastSyncError string `gorm:"size:512;not null;default:''"`
|
||||
CreatedAt time.Time `gorm:"not null"`
|
||||
UpdatedAt time.Time `gorm:"not null"`
|
||||
}
|
||||
|
||||
func (legacySubscriptionSourceWithoutProxy) TableName() string {
|
||||
return "egress_subscription_sources"
|
||||
}
|
||||
|
||||
func TestSchemaMigratesGlobalSubscriptionProxyToEverySource(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "subscription-proxy-upgrade.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.Close() })
|
||||
|
||||
if err := database.db.AutoMigrate(&legacyOperationsConfigWithSubscriptionProxy{}, &legacySubscriptionSourceWithoutProxy{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const encryptedProxy = "encrypted-global-subscription-proxy"
|
||||
if err := database.db.Create(&legacyOperationsConfigWithSubscriptionProxy{ID: 1, EncryptedSubscriptionProxyURL: encryptedProxy}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, source := range []legacySubscriptionSourceWithoutProxy{
|
||||
{ID: 1, Name: "domestic", Scope: "grok_build", Enabled: true},
|
||||
{ID: 2, Name: "overseas", Scope: "grok_web", Enabled: true},
|
||||
} {
|
||||
if err := database.db.Create(&source).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var sources []egressSubscriptionSourceModel
|
||||
if err := database.db.Order("id").Find(&sources).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(sources) != 2 {
|
||||
t.Fatalf("migrated sources = %d", len(sources))
|
||||
}
|
||||
for _, source := range sources {
|
||||
if source.EncryptedProxyURL != encryptedProxy || source.NextSyncAt != nil {
|
||||
t.Fatalf("migrated source = %#v", source)
|
||||
}
|
||||
}
|
||||
var current egressOperationsConfigModel
|
||||
if err := database.db.First(¤t, 1).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !current.SubscriptionProxyMigrationCompleted {
|
||||
t.Fatal("subscription proxy migration was not marked complete")
|
||||
}
|
||||
repository := NewEgressRepository(database)
|
||||
if _, err := repository.SaveEgressOperationsConfig(ctx, egressdomain.DefaultOperationsConfig()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := database.db.First(¤t, 1).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !current.SubscriptionProxyMigrationCompleted {
|
||||
t.Fatal("ordinary operations update reset the subscription proxy migration marker")
|
||||
}
|
||||
var legacy legacyOperationsConfigWithSubscriptionProxy
|
||||
if err := database.db.First(&legacy, 1).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if legacy.EncryptedSubscriptionProxyURL != encryptedProxy {
|
||||
t.Fatal("legacy global subscription proxy was not retained for rollback")
|
||||
}
|
||||
|
||||
// Sources created after the one-time migration must remain direct. Keeping
|
||||
// the legacy ciphertext for rollback must not cause it to be copied again.
|
||||
direct := legacySubscriptionSourceWithoutProxy{ID: 3, Name: "direct", Scope: "grok_console", Enabled: true}
|
||||
if err := database.db.Create(&direct).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatalf("repeated migration failed: %v", err)
|
||||
}
|
||||
var directAfterRestart egressSubscriptionSourceModel
|
||||
if err := database.db.First(&directAfterRestart, direct.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if directAfterRestart.EncryptedProxyURL != "" {
|
||||
t.Fatal("repeated migration applied the legacy proxy to a new direct source")
|
||||
}
|
||||
}
|
||||
@@ -669,7 +669,7 @@ func TestGenerateVideoFallbackInjectsUploadURL(t *testing.T) {
|
||||
})
|
||||
result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: account.Credential{ID: 15, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted, BuildSuperEntitled: true},
|
||||
JobID: "video_job_1", Prompt: "waves", Duration: 6, Resolution: "720p", ReferenceURLs: []string{"https://cdn.example.com/first.png"},
|
||||
JobID: "video_job_1", Prompt: "waves", Duration: 6, Resolution: "720p", ImageURL: "https://cdn.example.com/first.png",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -750,7 +750,7 @@ func TestGenerateVideoAutoBotFlaggedUsesXAIDirectly(t *testing.T) {
|
||||
})
|
||||
result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: account.Credential{ID: 116, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted, BuildRouteMode: account.BuildRouteAuto, BuildSuperEntitled: true},
|
||||
JobID: "video_bot", Prompt: "waves", Duration: 6, Resolution: "720p", ReferenceURLs: []string{"https://cdn.example.com/bot.png"},
|
||||
JobID: "video_bot", Prompt: "waves", Duration: 6, Resolution: "720p", ImageURL: "https://cdn.example.com/bot.png",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media"
|
||||
infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
)
|
||||
@@ -21,7 +22,9 @@ import (
|
||||
const (
|
||||
buildVideoModel = "grok-imagine-video-1.5"
|
||||
xaiVideoModel = "grok-imagine-video-1.5-preview"
|
||||
buildVideoMaxImages = 1
|
||||
// Align with the gateway ceiling and official xAI video inputs:
|
||||
// image = first frame; reference_images = style/content references (may be length 1).
|
||||
buildVideoMaxImages = mediadomain.MaxInputImages
|
||||
buildVideoPollEvery = 2 * time.Second
|
||||
buildVideoMaxBodySize = 2 << 20
|
||||
buildVideoErrorSummaryLimit = 256
|
||||
@@ -148,13 +151,13 @@ func boundDiagnosticText(value string, limit int) string {
|
||||
}
|
||||
|
||||
// GenerateVideo 通过 Build OAuth 创建并轮询视频任务;对外仍使用 grok-imagine-video-1.5,
|
||||
// 发往 XAI 时仅在出站协议层转换为官方 preview 模型与 image.url 结构。
|
||||
// 最多 1 张首图;多于 1 张在调用上游前失败,不静默截断。
|
||||
// 发往 XAI 时仅在出站协议层转换为官方 preview 模型与 image/reference_images 结构。
|
||||
// image = 首帧;reference_images = 参考图(即使只有 1 张也不升格为 image)。超过网关上限时失败,不静默截断。
|
||||
// 显式模式优先;auto 下仅已确认 Super 且 bot_flag_source/bfs 为 1 或 2 默认使用 XAI。
|
||||
// 其他 auto Super 账号仅在当次 Build 创建返回 403 后探测 XAI。
|
||||
func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoRequest) (provider.VideoResult, error) {
|
||||
if len(request.ReferenceURLs) > buildVideoMaxImages {
|
||||
return provider.VideoResult{}, fmt.Errorf("Build grok-imagine-video-1.5 最多支持 1 张首图,当前为 %d 张", len(request.ReferenceURLs))
|
||||
if total := buildVideoImageCount(request); total > buildVideoMaxImages {
|
||||
return provider.VideoResult{}, fmt.Errorf("Build grok-imagine-video-1.5 最多支持 %d 张输入图,当前为 %d 张", buildVideoMaxImages, total)
|
||||
}
|
||||
accessToken, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken)
|
||||
if err != nil {
|
||||
@@ -291,16 +294,52 @@ func videoCreatePayload(request provider.VideoRequest, uploadURL string, profile
|
||||
if resolution := strings.TrimSpace(request.Resolution); resolution != "" {
|
||||
payload["resolution"] = resolution
|
||||
}
|
||||
if len(request.ReferenceURLs) == 1 {
|
||||
imageURL := strings.TrimSpace(request.ReferenceURLs[0])
|
||||
if imageURL == "" {
|
||||
return nil, fmt.Errorf("视频首图 URL 不能为空")
|
||||
}
|
||||
if imageURL := strings.TrimSpace(request.ImageURL); imageURL != "" {
|
||||
payload["image"] = map[string]any{profile.imageURLField: imageURL}
|
||||
}
|
||||
if strings.TrimSpace(request.ImageURL) != "" && (len(request.ReferenceURLs) > 0 || len(request.ReferenceAudios) > 0) {
|
||||
return nil, fmt.Errorf("image 不能与 reference_images/reference_audios 同时使用")
|
||||
}
|
||||
if len(request.ReferenceURLs) > 0 {
|
||||
references := make([]map[string]any, 0, len(request.ReferenceURLs))
|
||||
for _, rawURL := range request.ReferenceURLs {
|
||||
refURL := strings.TrimSpace(rawURL)
|
||||
if refURL == "" {
|
||||
return nil, fmt.Errorf("视频参考图 URL 不能为空")
|
||||
}
|
||||
references = append(references, map[string]any{profile.imageURLField: refURL})
|
||||
}
|
||||
// A single reference must stay in reference_images; do not coerce to image.
|
||||
payload["reference_images"] = references
|
||||
}
|
||||
if len(request.ReferenceAudios) > 0 {
|
||||
if len(request.ReferenceAudios) > 3 {
|
||||
return nil, fmt.Errorf("reference_audios 最多 3 个")
|
||||
}
|
||||
audios := make([]map[string]any, 0, len(request.ReferenceAudios))
|
||||
for _, raw := range request.ReferenceAudios {
|
||||
voiceID := strings.TrimSpace(raw)
|
||||
if voiceID == "" {
|
||||
return nil, fmt.Errorf("reference_audios.voice_id 不能为空")
|
||||
}
|
||||
audios = append(audios, map[string]any{"voice_id": voiceID})
|
||||
}
|
||||
payload["reference_audios"] = audios
|
||||
}
|
||||
hasReferenceMode := len(request.ReferenceURLs) > 0 || len(request.ReferenceAudios) > 0
|
||||
if hasReferenceMode {
|
||||
if strings.TrimSpace(request.Prompt) == "" {
|
||||
return nil, fmt.Errorf("参考图/参考音频视频必须提供 prompt")
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(request.Resolution), "1080p") {
|
||||
return nil, fmt.Errorf("参考图视频 resolution 最高 720p")
|
||||
}
|
||||
}
|
||||
if _, hasPrompt := payload["prompt"]; !hasPrompt {
|
||||
if _, hasImage := payload["image"]; !hasImage {
|
||||
return nil, fmt.Errorf("文本生视频必须提供 prompt;图片生视频可以省略 prompt")
|
||||
if !hasReferenceMode {
|
||||
return nil, fmt.Errorf("文本生视频必须提供 prompt;图片生视频可以省略 prompt")
|
||||
}
|
||||
}
|
||||
}
|
||||
if uploadURL = strings.TrimSpace(uploadURL); uploadURL != "" {
|
||||
@@ -555,3 +594,16 @@ func numberAsInt(value any) (int, bool) {
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func buildVideoImageCount(request provider.VideoRequest) int {
|
||||
count := 0
|
||||
if strings.TrimSpace(request.ImageURL) != "" {
|
||||
count++
|
||||
}
|
||||
for _, raw := range request.ReferenceURLs {
|
||||
if strings.TrimSpace(raw) != "" {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
@@ -38,7 +38,7 @@ func TestBuildVideoCreatePayloadNoImageAndSingleR2URL(t *testing.T) {
|
||||
|
||||
withImage, err := videoCreatePayload(provider.VideoRequest{
|
||||
Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p",
|
||||
ReferenceURLs: []string{"https://cdn.example.com/r2/first.png"},
|
||||
ImageURL: "https://cdn.example.com/r2/first.png",
|
||||
}, "", buildVideoRequestProfile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -47,10 +47,28 @@ func TestBuildVideoCreatePayloadNoImageAndSingleR2URL(t *testing.T) {
|
||||
if !ok || image["image_url"] != "https://cdn.example.com/r2/first.png" {
|
||||
t.Fatalf("image payload = %#v", withImage)
|
||||
}
|
||||
if _, exists := withImage["reference_images"]; exists {
|
||||
t.Fatalf("first-frame payload must not include reference_images: %#v", withImage)
|
||||
}
|
||||
if withImage["model"] != buildVideoModel || withImage["resolution"] != "720p" || withImage["aspect_ratio"] != "16:9" {
|
||||
t.Fatalf("single-image payload = %#v", withImage)
|
||||
}
|
||||
|
||||
withSingleReference, err := videoCreatePayload(provider.VideoRequest{
|
||||
Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p",
|
||||
ReferenceURLs: []string{"https://cdn.example.com/r2/ref-only.png"},
|
||||
}, "", buildVideoRequestProfile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, exists := withSingleReference["image"]; exists {
|
||||
t.Fatalf("single reference must not coerce to image: %#v", withSingleReference)
|
||||
}
|
||||
singleRefs, ok := withSingleReference["reference_images"].([]map[string]any)
|
||||
if !ok || len(singleRefs) != 1 || singleRefs[0]["image_url"] != "https://cdn.example.com/r2/ref-only.png" {
|
||||
t.Fatalf("single reference payload = %#v", withSingleReference)
|
||||
}
|
||||
|
||||
withUpload, err := videoCreatePayload(provider.VideoRequest{Prompt: "x", Duration: 6}, "https://api.example/v1/media/uploads/tok", buildVideoRequestProfile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -63,11 +81,11 @@ func TestBuildVideoCreatePayloadNoImageAndSingleR2URL(t *testing.T) {
|
||||
|
||||
func TestBuildVideoCreatePayloadImageOnlyEmptyPrompt(t *testing.T) {
|
||||
payload, err := videoCreatePayload(provider.VideoRequest{
|
||||
Prompt: " ",
|
||||
Duration: 6,
|
||||
AspectRatio: "16:9",
|
||||
Resolution: "720p",
|
||||
ReferenceURLs: []string{"https://r2.example.com/first.png"},
|
||||
Prompt: " ",
|
||||
Duration: 6,
|
||||
AspectRatio: "16:9",
|
||||
Resolution: "720p",
|
||||
ImageURL: "https://r2.example.com/first.png",
|
||||
}, "", buildVideoRequestProfile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -83,11 +101,11 @@ func TestBuildVideoCreatePayloadImageOnlyEmptyPrompt(t *testing.T) {
|
||||
|
||||
func TestXAIVideoCreatePayloadMatchesOfficialSchema(t *testing.T) {
|
||||
payload, err := videoCreatePayload(provider.VideoRequest{
|
||||
Prompt: "animate",
|
||||
Duration: 6,
|
||||
AspectRatio: "16:9",
|
||||
Resolution: "720p",
|
||||
ReferenceURLs: []string{"https://cdn.example.com/r2/first.png"},
|
||||
Prompt: "animate",
|
||||
Duration: 6,
|
||||
AspectRatio: "16:9",
|
||||
Resolution: "720p",
|
||||
ImageURL: "https://cdn.example.com/r2/first.png",
|
||||
}, "https://api.example/v1/media/uploads/tok", xaiVideoRequestProfile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -108,23 +126,109 @@ func TestXAIVideoCreatePayloadMatchesOfficialSchema(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateVideoRejectsTwoImagesBeforeUpstream(t *testing.T) {
|
||||
adapter, encrypted := newTestBuildVideoAdapter(t)
|
||||
var hits atomic.Int32
|
||||
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
|
||||
hits.Add(1)
|
||||
t.Fatalf("two-image request must not reach upstream: %s %s", request.Method, request.URL)
|
||||
return nil, nil
|
||||
})
|
||||
_, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: account.Credential{ID: 1, EncryptedAccessToken: encrypted},
|
||||
Prompt: "animate",
|
||||
func TestBuildVideoCreatePayloadMapsMultipleReferences(t *testing.T) {
|
||||
payload, err := videoCreatePayload(provider.VideoRequest{
|
||||
Prompt: "animate",
|
||||
Duration: 6,
|
||||
AspectRatio: "16:9",
|
||||
Resolution: "720p",
|
||||
ReferenceURLs: []string{
|
||||
"https://cdn.example.com/one.png",
|
||||
"https://cdn.example.com/two.png",
|
||||
"https://cdn.example.com/three.png",
|
||||
},
|
||||
}, "", buildVideoRequestProfile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, exists := payload["image"]; exists {
|
||||
t.Fatalf("multi-reference payload must not include image: %#v", payload)
|
||||
}
|
||||
references, ok := payload["reference_images"].([]map[string]any)
|
||||
if !ok || len(references) != 3 {
|
||||
t.Fatalf("reference_images = %#v", payload["reference_images"])
|
||||
}
|
||||
if references[0]["image_url"] != "https://cdn.example.com/one.png" || references[2]["image_url"] != "https://cdn.example.com/three.png" {
|
||||
t.Fatalf("reference_images = %#v", references)
|
||||
}
|
||||
|
||||
xaiPayload, err := videoCreatePayload(provider.VideoRequest{
|
||||
Prompt: "animate",
|
||||
ReferenceURLs: []string{
|
||||
"https://cdn.example.com/one.png",
|
||||
"https://cdn.example.com/two.png",
|
||||
},
|
||||
}, "https://api.example/v1/media/uploads/tok", xaiVideoRequestProfile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xaiReferences, ok := xaiPayload["reference_images"].([]map[string]any)
|
||||
if !ok || len(xaiReferences) != 2 || xaiReferences[0]["url"] != "https://cdn.example.com/one.png" {
|
||||
t.Fatalf("xai reference_images = %#v", xaiPayload["reference_images"])
|
||||
}
|
||||
if _, exists := xaiPayload["image"]; exists {
|
||||
t.Fatalf("xai multi-reference payload must not include image: %#v", xaiPayload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildVideoCreatePayloadRejectsImageWithReferences(t *testing.T) {
|
||||
_, err := videoCreatePayload(provider.VideoRequest{
|
||||
Prompt: "animate",
|
||||
Duration: 6,
|
||||
AspectRatio: "16:9",
|
||||
Resolution: "720p",
|
||||
ImageURL: "https://cdn.example.com/first-frame.png",
|
||||
ReferenceURLs: []string{"https://cdn.example.com/ref.png"},
|
||||
}, "", buildVideoRequestProfile)
|
||||
if err == nil {
|
||||
t.Fatal("expected image+reference_images combination to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildVideoCreatePayloadReferenceAudios(t *testing.T) {
|
||||
payload, err := videoCreatePayload(provider.VideoRequest{
|
||||
Prompt: "speak",
|
||||
Duration: 8,
|
||||
AspectRatio: "9:16",
|
||||
Resolution: "720p",
|
||||
ReferenceURLs: []string{"https://cdn.example.com/person.png"},
|
||||
ReferenceAudios: []string{"eve"},
|
||||
}, "", buildVideoRequestProfile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, exists := payload["image"]; exists {
|
||||
t.Fatalf("image = %#v", payload["image"])
|
||||
}
|
||||
references, ok := payload["reference_images"].([]map[string]any)
|
||||
if !ok || len(references) != 1 || references[0]["image_url"] != "https://cdn.example.com/person.png" {
|
||||
t.Fatalf("reference_images = %#v", payload["reference_images"])
|
||||
}
|
||||
audios, ok := payload["reference_audios"].([]map[string]any)
|
||||
if !ok || len(audios) != 1 || audios[0]["voice_id"] != "eve" {
|
||||
t.Fatalf("reference_audios = %#v", payload["reference_audios"])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func TestGenerateVideoRejectsTooManyImagesBeforeUpstream(t *testing.T) {
|
||||
adapter, encrypted := newTestBuildVideoAdapter(t)
|
||||
var hits atomic.Int32
|
||||
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
|
||||
hits.Add(1)
|
||||
t.Fatalf("oversized reference request must not reach upstream: %s %s", request.Method, request.URL)
|
||||
return nil, nil
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "最多支持 1 张首图") {
|
||||
references := make([]string, buildVideoMaxImages+1)
|
||||
for i := range references {
|
||||
references[i] = "https://cdn.example.com/" + strings.Repeat("x", i+1) + ".png"
|
||||
}
|
||||
_, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: account.Credential{ID: 1, EncryptedAccessToken: encrypted},
|
||||
Prompt: "animate",
|
||||
ReferenceURLs: references,
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "最多支持") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
if hits.Load() != 0 {
|
||||
@@ -132,6 +236,66 @@ func TestGenerateVideoRejectsTwoImagesBeforeUpstream(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateVideoPostsReferenceImagesAndPollsUntilReady(t *testing.T) {
|
||||
adapter, encrypted := newTestBuildVideoAdapter(t)
|
||||
var createBody map[string]any
|
||||
var pollCount atomic.Int32
|
||||
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
|
||||
if identity := infraegress.AccountFromContext(request.Context()); identity != "grok_build_9" {
|
||||
t.Fatalf("egress account identity = %q", identity)
|
||||
}
|
||||
switch {
|
||||
case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations":
|
||||
if request.Header.Get("Authorization") != "Bearer access-token" {
|
||||
t.Fatalf("missing auth header: %#v", request.Header)
|
||||
}
|
||||
if err := json.NewDecoder(request.Body).Decode(&createBody); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return jsonResponse(http.StatusOK, `{"request_id":"vid_ref_123","status":"queued"}`, request), nil
|
||||
case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/vid_ref_123":
|
||||
count := pollCount.Add(1)
|
||||
if count == 1 {
|
||||
return jsonResponse(http.StatusOK, `{"status":"processing","progress":40}`, request), nil
|
||||
}
|
||||
return jsonResponse(http.StatusOK, `{"status":"completed","progress":100,"video":{"url":"https://assets.grok.com/videos/ref.mp4"}}`, request), nil
|
||||
default:
|
||||
t.Fatalf("unexpected request %s %s", request.Method, request.URL)
|
||||
return nil, nil
|
||||
}
|
||||
})
|
||||
|
||||
result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: account.Credential{ID: 9, UserID: "user-1", EncryptedAccessToken: encrypted},
|
||||
Prompt: "animate knife",
|
||||
Duration: 6,
|
||||
AspectRatio: "16:9",
|
||||
Resolution: "720p",
|
||||
ReferenceURLs: []string{
|
||||
"https://r2.example.com/first.png",
|
||||
"https://r2.example.com/second.png",
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.URL != "https://assets.grok.com/videos/ref.mp4" || result.ContentType != "video/mp4" {
|
||||
t.Fatalf("result = %#v", result)
|
||||
}
|
||||
if _, exists := createBody["image"]; exists {
|
||||
t.Fatalf("create body unexpectedly includes image: %#v", createBody)
|
||||
}
|
||||
references, ok := createBody["reference_images"].([]any)
|
||||
if !ok || len(references) != 2 {
|
||||
t.Fatalf("create body reference_images = %#v", createBody["reference_images"])
|
||||
}
|
||||
first, _ := references[0].(map[string]any)
|
||||
second, _ := references[1].(map[string]any)
|
||||
if first["image_url"] != "https://r2.example.com/first.png" || second["image_url"] != "https://r2.example.com/second.png" {
|
||||
t.Fatalf("create body = %#v", createBody)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateVideoPostsSingleImageAndPollsUntilReady(t *testing.T) {
|
||||
adapter, encrypted := newTestBuildVideoAdapter(t)
|
||||
var createBody map[string]any
|
||||
@@ -169,12 +333,12 @@ func TestGenerateVideoPostsSingleImageAndPollsUntilReady(t *testing.T) {
|
||||
|
||||
var progressValues []int
|
||||
result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: account.Credential{ID: 9, UserID: "user-1", EncryptedAccessToken: encrypted},
|
||||
Prompt: "animate knife",
|
||||
Duration: 6,
|
||||
AspectRatio: "16:9",
|
||||
Resolution: "720p",
|
||||
ReferenceURLs: []string{"https://r2.example.com/first.png"},
|
||||
Credential: account.Credential{ID: 9, UserID: "user-1", EncryptedAccessToken: encrypted},
|
||||
Prompt: "animate knife",
|
||||
Duration: 6,
|
||||
AspectRatio: "16:9",
|
||||
Resolution: "720p",
|
||||
ImageURL: "https://r2.example.com/first.png",
|
||||
Progress: func(value int) {
|
||||
progressValues = append(progressValues, value)
|
||||
},
|
||||
|
||||
@@ -78,6 +78,9 @@ func (a *Adapter) QuotaMode(upstreamModel string) string {
|
||||
if ResolveMedia(upstreamModel, modeldomain.CapabilityVideo) {
|
||||
return QuotaModeVideo
|
||||
}
|
||||
if ResolveMedia(upstreamModel, modeldomain.CapabilityTTS) || ResolveMedia(upstreamModel, modeldomain.CapabilitySTT) || ResolveMedia(upstreamModel, modeldomain.CapabilityRealtime) {
|
||||
return QuotaMode
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
|
||||
@@ -35,15 +35,28 @@ var mediaCatalog = []struct {
|
||||
UpstreamModel string
|
||||
Capabilities []modeldomain.Capability
|
||||
}{
|
||||
{PublicID: "grok-imagine-image-quality", UpstreamModel: "grok-imagine-image-quality", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}},
|
||||
// Keep the three official Console image products distinct. The legacy and
|
||||
// quality routes intentionally precede 2.0 so catalog reconciliation can
|
||||
// restore stable route IDs created before 2.0 was introduced.
|
||||
{PublicID: "grok-imagine-image", UpstreamModel: "grok-imagine-image", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}},
|
||||
{PublicID: "grok-imagine-image-quality", UpstreamModel: "grok-imagine-image-quality", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}},
|
||||
{PublicID: "grok-imagine-image-2.0", UpstreamModel: "grok-imagine-image-2.0", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}},
|
||||
{PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", Capabilities: []modeldomain.Capability{modeldomain.CapabilityVideo}},
|
||||
// Free Console accounts can use the 1.5 video model on the official Console media API.
|
||||
{PublicID: "grok-imagine-video-1.5", UpstreamModel: "grok-imagine-video-1.5", Capabilities: []modeldomain.Capability{modeldomain.CapabilityVideo}},
|
||||
{PublicID: "grok-voice-latest", UpstreamModel: "grok-voice-latest", Capabilities: []modeldomain.Capability{modeldomain.CapabilityRealtime, modeldomain.CapabilityTTS}},
|
||||
{PublicID: "grok-voice-think-fast-2.0", UpstreamModel: "grok-voice-think-fast-2.0", Capabilities: []modeldomain.Capability{modeldomain.CapabilityRealtime, modeldomain.CapabilityTTS}},
|
||||
{PublicID: "grok-voice-think-fast-1.0", UpstreamModel: "grok-voice-think-fast-1.0", Capabilities: []modeldomain.Capability{modeldomain.CapabilityRealtime, modeldomain.CapabilityTTS}},
|
||||
{PublicID: "grok-stt", UpstreamModel: "grok-stt", Capabilities: []modeldomain.Capability{modeldomain.CapabilitySTT}},
|
||||
}
|
||||
|
||||
// Effort-suffixed aliases only include levels each Provider/model combination
|
||||
// actually supports (see domain/model.SupportedReasoningEffortsForProvider).
|
||||
// No blanket none/low/medium/high/xhigh/max template.
|
||||
var aliases = []provider.ModelAlias{
|
||||
// Compatibility for the temporary PR catalog name. The official quality
|
||||
// model itself remains a first-class route.
|
||||
consoleAlias("grok-imagine-image-quality-2.0", "grok-imagine-image-quality", "grok-imagine-image-quality", ""),
|
||||
consoleAlias("grok-4.3-console", "grok-4.3", "grok-4.3", ""),
|
||||
consoleAlias("grok-4.20-0309-reasoning-console", "grok-4.20-0309-reasoning", "grok-4.20-0309-reasoning", ""),
|
||||
consoleAlias("grok-4.20-0309-non-reasoning-console", "grok-4.20-0309-non-reasoning", "grok-4.20-0309-non-reasoning", ""),
|
||||
|
||||
@@ -21,6 +21,9 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
fhttp "github.com/bogdanfinn/fhttp"
|
||||
fhttptest "github.com/bogdanfinn/fhttp/httptest"
|
||||
"github.com/bogdanfinn/websocket"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media"
|
||||
@@ -47,11 +50,21 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) {
|
||||
{publicID: "Console/grok-4.20-multi-agent-0309", capability: modeldomain.CapabilityResponses}: "grok-4.20-multi-agent-0309",
|
||||
{publicID: "Console/grok-4.5", capability: modeldomain.CapabilityResponses}: "grok-4.5",
|
||||
{publicID: "Console/grok-build-0.1", capability: modeldomain.CapabilityResponses}: "grok-build-0.1",
|
||||
{publicID: "Console/grok-imagine-image-quality", capability: modeldomain.CapabilityImage}: "grok-imagine-image-quality",
|
||||
{publicID: "Console/grok-imagine-image-quality", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image-quality",
|
||||
{publicID: "Console/grok-imagine-image", capability: modeldomain.CapabilityImage}: "grok-imagine-image",
|
||||
{publicID: "Console/grok-imagine-image", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image",
|
||||
{publicID: "Console/grok-imagine-image-quality", capability: modeldomain.CapabilityImage}: "grok-imagine-image-quality",
|
||||
{publicID: "Console/grok-imagine-image-quality", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image-quality",
|
||||
{publicID: "Console/grok-imagine-image-2.0", capability: modeldomain.CapabilityImage}: "grok-imagine-image-2.0",
|
||||
{publicID: "Console/grok-imagine-image-2.0", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image-2.0",
|
||||
{publicID: "Console/grok-imagine-video", capability: modeldomain.CapabilityVideo}: "grok-imagine-video",
|
||||
{publicID: "Console/grok-imagine-video-1.5", capability: modeldomain.CapabilityVideo}: "grok-imagine-video-1.5",
|
||||
{publicID: "Console/grok-voice-latest", capability: modeldomain.CapabilityRealtime}: "grok-voice-latest",
|
||||
{publicID: "Console/grok-voice-latest", capability: modeldomain.CapabilityTTS}: "grok-voice-latest",
|
||||
{publicID: "Console/grok-voice-think-fast-2.0", capability: modeldomain.CapabilityRealtime}: "grok-voice-think-fast-2.0",
|
||||
{publicID: "Console/grok-voice-think-fast-2.0", capability: modeldomain.CapabilityTTS}: "grok-voice-think-fast-2.0",
|
||||
{publicID: "Console/grok-voice-think-fast-1.0", capability: modeldomain.CapabilityRealtime}: "grok-voice-think-fast-1.0",
|
||||
{publicID: "Console/grok-voice-think-fast-1.0", capability: modeldomain.CapabilityTTS}: "grok-voice-think-fast-1.0",
|
||||
{publicID: "Console/grok-stt", capability: modeldomain.CapabilitySTT}: "grok-stt",
|
||||
}
|
||||
routes := Routes()
|
||||
if len(routes) != len(expected) {
|
||||
@@ -66,14 +79,15 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) {
|
||||
}
|
||||
}
|
||||
aliases := Aliases()
|
||||
if len(aliases) != 13 {
|
||||
t.Fatalf("aliases = %d, want 13", len(aliases))
|
||||
if len(aliases) != 14 {
|
||||
t.Fatalf("aliases = %d, want 14", len(aliases))
|
||||
}
|
||||
registry := provider.NewRegistry(NewAdapter(Config{}, nil, nil, nil))
|
||||
if registry.SupportsStoredResponses(account.ProviderConsole) {
|
||||
t.Fatal("console must not advertise stored Responses support")
|
||||
}
|
||||
for _, name := range []string{
|
||||
"grok-imagine-image-quality-2.0",
|
||||
"grok-4.3-console", "grok-4.20-0309-reasoning-console",
|
||||
"grok-4.20-0309-non-reasoning-console", "grok-4.20-multi-agent-console", "grok-build-console",
|
||||
"grok-4.3-low", "grok-4.3-medium", "grok-4.3-high",
|
||||
@@ -90,8 +104,9 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) {
|
||||
}
|
||||
adapter := NewAdapter(Config{}, nil, nil, nil)
|
||||
for model, want := range map[string]string{
|
||||
"grok-4.5": QuotaMode, "grok-imagine-image-quality": QuotaModeImage,
|
||||
"grok-imagine-image": QuotaModeImage, "grok-imagine-video": QuotaModeVideo,
|
||||
"grok-4.5": QuotaMode, "grok-imagine-image-quality": QuotaModeImage, "grok-imagine-image-2.0": QuotaModeImage,
|
||||
"grok-imagine-image": QuotaModeImage, "grok-imagine-video": QuotaModeVideo, "grok-imagine-video-1.5": QuotaModeVideo,
|
||||
"grok-voice-latest": QuotaMode, "grok-voice-think-fast-2.0": QuotaMode, "grok-voice-think-fast-1.0": QuotaMode, "grok-stt": QuotaMode,
|
||||
} {
|
||||
if got := adapter.QuotaMode(model); got != want {
|
||||
t.Fatalf("QuotaMode(%q) = %q, want %q", model, got, want)
|
||||
@@ -99,6 +114,142 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVoiceErrorIsSanitizedAndPreservesRetryMetadata(t *testing.T) {
|
||||
response := &http.Response{
|
||||
StatusCode: http.StatusTooManyRequests,
|
||||
Header: http.Header{"Retry-After": {"17"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":{"message":"Authorization: Bearer secret-token"}}`)),
|
||||
}
|
||||
err := consoleVoiceResponseError(response)
|
||||
if err == nil {
|
||||
t.Fatal("expected voice upstream error")
|
||||
}
|
||||
if strings.Contains(strings.ToLower(err.Error()), "authorization") || strings.Contains(err.Error(), "secret-token") {
|
||||
t.Fatalf("voice error exposed sensitive upstream body: %q", err)
|
||||
}
|
||||
if status, ok := provider.ErrorHTTPStatus(err); !ok || status != http.StatusTooManyRequests {
|
||||
t.Fatalf("status = %d, ok = %v", status, ok)
|
||||
}
|
||||
if retryAfter := provider.ErrorRetryAfter(err); retryAfter != 17*time.Second {
|
||||
t.Fatalf("retry after = %s", retryAfter)
|
||||
}
|
||||
if message, ok := provider.ErrorPublicMessage(err); !ok || strings.Contains(message, "secret-token") {
|
||||
t.Fatalf("public message = %q, ok = %v", message, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVoiceErrorSanitizesCredentialAliases(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{"error":{"message":"access_token=secret"}}`,
|
||||
`{"error":{"message":"refresh-token=secret"}}`,
|
||||
`{"error":{"message":"api_key=secret"}}`,
|
||||
`{"error":{"message":"Bearer secret"}}`,
|
||||
`{"error":{"message":"cf_clearance=secret"}}`,
|
||||
} {
|
||||
err := newConsoleMediaUpstreamError(http.StatusBadGateway, []byte(body), 0)
|
||||
message, ok := provider.ErrorPublicMessage(err)
|
||||
if !ok || message == "" || strings.Contains(strings.ToLower(message), "secret") {
|
||||
t.Fatalf("body %q produced public message %q, ok = %v", body, message, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVoiceDPoPRejectionIsRequestScoped(t *testing.T) {
|
||||
err := newConsoleMediaUpstreamError(http.StatusForbidden, []byte(`{"error":{"code":"unauthorized:dpop-required"}}`), 0)
|
||||
if !provider.IsRequestScopedError(err) {
|
||||
t.Fatalf("DPoP rejection was not request-scoped: %v", err)
|
||||
}
|
||||
if strings.Contains(strings.ToLower(err.Error()), "authorization") {
|
||||
t.Fatalf("DPoP error exposed authorization details: %q", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVoiceWebSocketProofEndpointUsesHTTPUpgradeURI(t *testing.T) {
|
||||
got, err := voiceWebSocketProofEndpoint("wss://console.x.ai/v1/realtime?model=grok-voice-latest")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != "https://console.x.ai/v1/realtime?model=grok-voice-latest" {
|
||||
t.Fatalf("proof endpoint = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVoiceWebSocketRefreshesDPoPOnceAfterUnauthorized(t *testing.T) {
|
||||
var tokenRequests atomic.Int32
|
||||
var websocketRequests atomic.Int32
|
||||
server := fhttptest.NewServer(fhttp.HandlerFunc(func(writer fhttp.ResponseWriter, request *fhttp.Request) {
|
||||
switch request.URL.Path {
|
||||
case "/v1/dpop/token":
|
||||
tokenRequests.Add(1)
|
||||
var payload struct {
|
||||
JWK dpopJWK `json:"jwk"`
|
||||
}
|
||||
if err := json.NewDecoder(request.Body).Decode(&payload); err != nil {
|
||||
t.Errorf("decode DPoP token request: %v", err)
|
||||
writer.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
thumbprint, err := dpopJWKThumbprint(payload.JWK)
|
||||
if err != nil {
|
||||
t.Errorf("DPoP thumbprint: %v", err)
|
||||
writer.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
header, _ := json.Marshal(map[string]any{"alg": "HS256", "typ": "JWT"})
|
||||
claims, _ := json.Marshal(map[string]any{
|
||||
"sub": "test-user", "iat": time.Now().UTC().Unix(), "exp": time.Now().UTC().Add(5 * time.Minute).Unix(),
|
||||
"cnf": map[string]any{"jkt": thumbprint}, "token_use": "dpop-bound",
|
||||
})
|
||||
accessToken := base64.RawURLEncoding.EncodeToString(header) + "." + base64.RawURLEncoding.EncodeToString(claims) + ".dGVzdA"
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(writer).Encode(map[string]any{"access_token": accessToken, "token_type": "DPoP", "expires_in": 300})
|
||||
case "/v1/realtime":
|
||||
current := websocketRequests.Add(1)
|
||||
proof, _, err := jwt.NewParser().ParseUnverified(request.Header.Get("DPoP"), jwt.MapClaims{})
|
||||
if err != nil {
|
||||
t.Errorf("parse DPoP proof: %v", err)
|
||||
writer.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
claims := proof.Claims.(jwt.MapClaims)
|
||||
wantHTU := "http://" + request.Host + request.URL.EscapedPath()
|
||||
if claims["htu"] != wantHTU || claims["htm"] != http.MethodGet {
|
||||
t.Errorf("websocket DPoP binding = %#v, want htu=%q", claims, wantHTU)
|
||||
}
|
||||
if current == 1 {
|
||||
writer.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
connection, err := (&websocket.Upgrader{CheckOrigin: func(*fhttp.Request) bool { return true }}).Upgrade(writer, request, nil)
|
||||
if err != nil {
|
||||
t.Errorf("upgrade voice websocket: %v", err)
|
||||
return
|
||||
}
|
||||
_ = connection.Close()
|
||||
default:
|
||||
fhttp.NotFound(writer, request)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
adapter, credential := newConsoleTestAdapter(t, server.URL)
|
||||
connection, cleanup, err := adapter.DialVoiceWebSocket(context.Background(), provider.VoiceWebSocketRequest{
|
||||
Credential: credential, Path: "/realtime", Model: "grok-voice-latest",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if connection != nil {
|
||||
_ = connection.Close()
|
||||
}
|
||||
if cleanup != nil {
|
||||
cleanup()
|
||||
}
|
||||
if tokenRequests.Load() != 2 || websocketRequests.Load() != 2 {
|
||||
t.Fatalf("requests token=%d websocket=%d", tokenRequests.Load(), websocketRequests.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncAccountIdentityUsesWebSessionWithConsoleCredential(t *testing.T) {
|
||||
t.Parallel()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
@@ -185,6 +336,140 @@ func TestNormalizeRequestAppliesConsoleContract(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRequestForwardsXSearchTimeRangeAndImageSearch(t *testing.T) {
|
||||
spec, ok := Resolve("grok-4.3")
|
||||
if !ok {
|
||||
t.Fatal("grok-4.3 missing")
|
||||
}
|
||||
|
||||
t.Run("forwards enable_image_search on web_search", func(t *testing.T) {
|
||||
body, err := normalizeRequest([]byte(`{
|
||||
"model":"grok-4.3",
|
||||
"tools":[{"type":"web_search","enable_image_search":true,"custom":true}]
|
||||
}`), spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tools, _ := payload["tools"].([]any)
|
||||
if len(tools) != 1 {
|
||||
t.Fatalf("tools = %#v", tools)
|
||||
}
|
||||
webSearch, _ := tools[0].(map[string]any)
|
||||
if webSearch["type"] != "web_search" || webSearch["enable_image_understanding"] != true {
|
||||
t.Fatalf("web_search defaults = %#v", webSearch)
|
||||
}
|
||||
if webSearch["enable_image_search"] != true {
|
||||
t.Fatalf("enable_image_search not forwarded: %#v", webSearch)
|
||||
}
|
||||
if webSearch["custom"] != nil {
|
||||
t.Fatalf("unknown field custom should be stripped: %#v", webSearch)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("omits enable_image_search when client does not set it", func(t *testing.T) {
|
||||
body, err := normalizeRequest([]byte(`{
|
||||
"model":"grok-4.3",
|
||||
"tools":[{"type":"web_search"}]
|
||||
}`), spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
webSearch, _ := payload["tools"].([]any)[0].(map[string]any)
|
||||
if _, exists := webSearch["enable_image_search"]; exists {
|
||||
t.Fatalf("enable_image_search should be absent by default: %#v", webSearch)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("forwards valid x_search from_date and to_date", func(t *testing.T) {
|
||||
body, err := normalizeRequest([]byte(`{
|
||||
"model":"grok-4.3",
|
||||
"tools":[{"type":"x_search","from_date":"2026-07-01","to_date":"2026-07-23","noise":1}]
|
||||
}`), spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xSearch, _ := payload["tools"].([]any)[0].(map[string]any)
|
||||
if xSearch["type"] != "x_search" || xSearch["enable_video_understanding"] != true {
|
||||
t.Fatalf("x_search defaults = %#v", xSearch)
|
||||
}
|
||||
if xSearch["from_date"] != "2026-07-01" || xSearch["to_date"] != "2026-07-23" {
|
||||
t.Fatalf("date bounds not forwarded: %#v", xSearch)
|
||||
}
|
||||
if xSearch["noise"] != nil {
|
||||
t.Fatalf("unknown field noise should be stripped: %#v", xSearch)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("drops invalid date formats", func(t *testing.T) {
|
||||
body, err := normalizeRequest([]byte(`{
|
||||
"model":"grok-4.3",
|
||||
"tools":[{"type":"x_search","from_date":"2026-7-01","to_date":"2026-02-30"}]
|
||||
}`), spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xSearch, _ := payload["tools"].([]any)[0].(map[string]any)
|
||||
if xSearch["from_date"] != nil || xSearch["to_date"] != nil {
|
||||
t.Fatalf("invalid dates should be dropped: %#v", xSearch)
|
||||
}
|
||||
if xSearch["type"] != "x_search" || xSearch["enable_video_understanding"] != true {
|
||||
t.Fatalf("x_search defaults should remain: %#v", xSearch)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("drops inverted date range", func(t *testing.T) {
|
||||
body, err := normalizeRequest([]byte(`{
|
||||
"model":"grok-4.3",
|
||||
"tools":[{"type":"x_search","from_date":"2026-07-24","to_date":"2026-07-23"}]
|
||||
}`), spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xSearch, _ := payload["tools"].([]any)[0].(map[string]any)
|
||||
if xSearch["from_date"] != nil || xSearch["to_date"] != nil {
|
||||
t.Fatalf("inverted range should drop both bounds: %#v", xSearch)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("keeps only from_date when to_date absent", func(t *testing.T) {
|
||||
body, err := normalizeRequest([]byte(`{
|
||||
"model":"grok-4.3",
|
||||
"tools":[{"type":"x_search","from_date":"2026-08-01"}]
|
||||
}`), spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xSearch, _ := payload["tools"].([]any)[0].(map[string]any)
|
||||
if xSearch["from_date"] != "2026-08-01" || xSearch["to_date"] != nil {
|
||||
t.Fatalf("single bound = %#v", xSearch)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNormalizeRequestDoesNotInjectToolsForConsoleCatalog(t *testing.T) {
|
||||
for _, spec := range catalog {
|
||||
t.Run(spec.PublicID, func(t *testing.T) {
|
||||
@@ -1228,6 +1513,43 @@ func TestConsoleImageEditForwardsMultipleImages(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleImage20ForwardsQualityAndRejectsItForLegacyModels(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if serveTestDPoPToken(t, writer, request) {
|
||||
return
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.NewDecoder(request.Body).Decode(&payload); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if payload["model"] != "grok-imagine-image-2.0" || payload["quality"] != "low" || payload["resolution"] != "2k" {
|
||||
t.Errorf("Image 2.0 payload = %#v", payload)
|
||||
}
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
_, _ = writer.Write([]byte(`{"data":[{"b64_json":"aW1hZ2U="}]}`))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
adapter, credential := newConsoleTestAdapter(t, server.URL)
|
||||
response, err := adapter.GenerateImage(context.Background(), provider.ImageGenerationRequest{
|
||||
Credential: credential, Model: "grok-imagine-image-2.0", Prompt: "draw", Count: 1,
|
||||
Resolution: "2k", Quality: "low", ResponseFormat: "b64_json",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = response.Body.Close()
|
||||
legacy, err := adapter.GenerateImage(context.Background(), provider.ImageGenerationRequest{
|
||||
Credential: credential, Model: "grok-imagine-image", Prompt: "draw", Count: 1, Quality: "low",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer legacy.Body.Close()
|
||||
if legacy.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("legacy quality response = %#v", legacy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideoCreatesAndPollsStandardResources(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if serveTestDPoPToken(t, writer, request) {
|
||||
@@ -1266,6 +1588,291 @@ func TestConsoleVideoCreatesAndPollsStandardResources(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideoPostsReferenceImages(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if serveTestDPoPToken(t, writer, request) {
|
||||
return
|
||||
}
|
||||
verifyTestDPoPProof(t, request)
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations":
|
||||
var payload map[string]any
|
||||
if err := json.NewDecoder(request.Body).Decode(&payload); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if _, exists := payload["image"]; exists {
|
||||
t.Errorf("multi-reference payload must not include image: %#v", payload)
|
||||
}
|
||||
references, ok := payload["reference_images"].([]any)
|
||||
if !ok || len(references) != 3 {
|
||||
t.Errorf("reference_images = %#v", payload["reference_images"])
|
||||
} else {
|
||||
first, _ := references[0].(map[string]any)
|
||||
third, _ := references[2].(map[string]any)
|
||||
if first["url"] != "https://example.com/a.png" || third["url"] != "https://example.com/c.png" {
|
||||
t.Errorf("reference_images = %#v", references)
|
||||
}
|
||||
}
|
||||
_, _ = writer.Write([]byte(`{"request_id":"upstream-video-ref-1"}`))
|
||||
case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-ref-1":
|
||||
_, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-ref.mp4"}}`))
|
||||
default:
|
||||
http.NotFound(writer, request)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
adapter, credential := newConsoleTestAdapter(t, server.URL)
|
||||
result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p",
|
||||
ReferenceURLs: []string{
|
||||
"https://example.com/a.png",
|
||||
"https://example.com/b.png",
|
||||
"https://example.com/c.png",
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.URL != "https://vidgen.x.ai/result-ref.mp4" || result.ContentType != "video/mp4" {
|
||||
t.Fatalf("video result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideoPostsSingleReferenceImage(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if serveTestDPoPToken(t, writer, request) {
|
||||
return
|
||||
}
|
||||
verifyTestDPoPProof(t, request)
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations":
|
||||
var payload map[string]any
|
||||
if err := json.NewDecoder(request.Body).Decode(&payload); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if _, exists := payload["image"]; exists {
|
||||
t.Errorf("single reference must not coerce to image: %#v", payload)
|
||||
}
|
||||
references, ok := payload["reference_images"].([]any)
|
||||
if !ok || len(references) != 1 {
|
||||
t.Errorf("reference_images = %#v", payload["reference_images"])
|
||||
} else {
|
||||
first, _ := references[0].(map[string]any)
|
||||
if first["url"] != "https://example.com/ref-only.png" {
|
||||
t.Errorf("reference_images = %#v", references)
|
||||
}
|
||||
}
|
||||
_, _ = writer.Write([]byte(`{"request_id":"upstream-video-ref-single"}`))
|
||||
case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-ref-single":
|
||||
_, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-ref-single.mp4"}}`))
|
||||
default:
|
||||
http.NotFound(writer, request)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
adapter, credential := newConsoleTestAdapter(t, server.URL)
|
||||
result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p",
|
||||
ReferenceURLs: []string{"https://example.com/ref-only.png"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.URL != "https://vidgen.x.ai/result-ref-single.mp4" {
|
||||
t.Fatalf("video result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideoRejectsImageWithReferences(t *testing.T) {
|
||||
adapter, credential := newConsoleTestAdapter(t, "https://console.example")
|
||||
_, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p",
|
||||
ImageURL: "https://example.com/first.png",
|
||||
ReferenceURLs: []string{"https://example.com/ref.png"},
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "不能与") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideoPostsReferenceAudios(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if serveTestDPoPToken(t, writer, request) {
|
||||
return
|
||||
}
|
||||
verifyTestDPoPProof(t, request)
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations":
|
||||
var payload map[string]any
|
||||
if err := json.NewDecoder(request.Body).Decode(&payload); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if _, exists := payload["image"]; exists {
|
||||
t.Errorf("image = %#v", payload["image"])
|
||||
}
|
||||
references, ok := payload["reference_images"].([]any)
|
||||
if !ok || len(references) != 1 {
|
||||
t.Errorf("reference_images = %#v", payload["reference_images"])
|
||||
} else {
|
||||
first, _ := references[0].(map[string]any)
|
||||
if first["url"] != "https://example.com/person.png" {
|
||||
t.Errorf("reference_images = %#v", references)
|
||||
}
|
||||
}
|
||||
audios, ok := payload["reference_audios"].([]any)
|
||||
if !ok || len(audios) != 1 {
|
||||
t.Errorf("reference_audios = %#v", payload["reference_audios"])
|
||||
} else if first, _ := audios[0].(map[string]any); first["voice_id"] != "eve" {
|
||||
t.Errorf("reference_audios = %#v", audios)
|
||||
}
|
||||
_, _ = writer.Write([]byte(`{"request_id":"upstream-video-ref-audio"}`))
|
||||
case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-ref-audio":
|
||||
_, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-ref-audio.mp4","duration":8}}`))
|
||||
default:
|
||||
http.NotFound(writer, request)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
adapter, credential := newConsoleTestAdapter(t, server.URL)
|
||||
result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Prompt: "speak", Duration: 8, AspectRatio: "9:16", Resolution: "720p",
|
||||
ReferenceURLs: []string{"https://example.com/person.png"},
|
||||
ReferenceAudios: []string{"eve"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.URL != "https://vidgen.x.ai/result-ref-audio.mp4" {
|
||||
t.Fatalf("video result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
// Measured upstream ceiling: 8 references answer 400 "Too many reference images:
|
||||
// 8. Maximum allowed is 7." on both grok-imagine-video and grok-imagine-video-1.5.
|
||||
func TestConsoleVideoRejectsTooManyReferenceImages(t *testing.T) {
|
||||
adapter, credential := newConsoleTestAdapter(t, "https://console.example")
|
||||
references := make([]string, consoleMaxVideoReferenceImages+1)
|
||||
for i := range references {
|
||||
references[i] = "https://example.com/" + strings.Repeat("x", i+1) + ".png"
|
||||
}
|
||||
_, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Prompt: "animate", Duration: 6, ReferenceURLs: references,
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "最多支持") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideoRejectsTooManyCombinedImages(t *testing.T) {
|
||||
adapter, credential := newConsoleTestAdapter(t, "https://console.example")
|
||||
references := make([]string, consoleMaxVideoReferenceImages)
|
||||
for i := range references {
|
||||
references[i] = "https://example.com/" + strings.Repeat("y", i+1) + ".png"
|
||||
}
|
||||
_, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Prompt: "animate", Duration: 6,
|
||||
ImageURL: "https://example.com/first.png", ReferenceURLs: references,
|
||||
})
|
||||
if err == nil || !(strings.Contains(err.Error(), "不能与") || strings.Contains(err.Error(), "最多支持")) {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Measured: grok-imagine-video with reference_images and duration=15 answers
|
||||
// 400 "Duration 15s exceeds the maximum allowed for reference-to-video, which is
|
||||
// 10s." The image field (image-to-video) and grok-imagine-video-1.5 both keep 15s.
|
||||
func TestConsoleVideoRejectsLongReferenceDurationOnBaseModel(t *testing.T) {
|
||||
adapter, credential := newConsoleTestAdapter(t, "https://console.example")
|
||||
_, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Prompt: "animate", Duration: 15,
|
||||
ReferenceURLs: []string{"https://example.com/ref.png"},
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "最长 10 秒") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The same 15s request must stay allowed for grok-imagine-video-1.5.
|
||||
func TestConsoleVideo15AllowsLongReferenceDuration(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if serveTestDPoPToken(t, writer, request) {
|
||||
return
|
||||
}
|
||||
verifyTestDPoPProof(t, request)
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations":
|
||||
_, _ = writer.Write([]byte(`{"request_id":"upstream-video-15s"}`))
|
||||
case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-15s":
|
||||
_, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-15s.mp4"}}`))
|
||||
default:
|
||||
http.NotFound(writer, request)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
adapter, credential := newConsoleTestAdapter(t, server.URL)
|
||||
result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Model: "grok-imagine-video-1.5", Prompt: "animate", Duration: 15,
|
||||
ReferenceURLs: []string{"https://example.com/ref.png"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.URL != "https://vidgen.x.ai/result-15s.mp4" {
|
||||
t.Fatalf("video result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideoUsesImagineVideo15Model(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if serveTestDPoPToken(t, writer, request) {
|
||||
return
|
||||
}
|
||||
verifyTestDPoPProof(t, request)
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations":
|
||||
var payload map[string]any
|
||||
if err := json.NewDecoder(request.Body).Decode(&payload); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if payload["model"] != "grok-imagine-video-1.5" || payload["resolution"] != "1080p" {
|
||||
t.Errorf("video payload = %#v", payload)
|
||||
}
|
||||
_, _ = writer.Write([]byte(`{"request_id":"upstream-video-15"}`))
|
||||
case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-15":
|
||||
_, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-15.mp4"}}`))
|
||||
default:
|
||||
http.NotFound(writer, request)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
adapter, credential := newConsoleTestAdapter(t, server.URL)
|
||||
result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Model: "grok-imagine-video-1.5", Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "1080p",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.URL != "https://vidgen.x.ai/result-15.mp4" {
|
||||
t.Fatalf("video result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideo15Rejects1080pReferenceMode(t *testing.T) {
|
||||
adapter, credential := newConsoleTestAdapter(t, "https://console.example")
|
||||
_, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Model: "grok-imagine-video-1.5", Prompt: "animate", Duration: 6, Resolution: "1080p",
|
||||
ReferenceURLs: []string{"https://example.com/reference.png"},
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "最高支持 720p") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseConsoleVideoStatusRejectsUnknownState(t *testing.T) {
|
||||
if _, _, err := parseConsoleVideoStatus([]byte(`{"status":"mystery"}`), nil); err == nil || !strings.Contains(err.Error(), "状态无效") {
|
||||
t.Fatalf("unknown status error = %v", err)
|
||||
@@ -1477,3 +2084,99 @@ func (r *recordingConsoleEgressRepository) UpdateCount() int {
|
||||
defer r.mu.Unlock()
|
||||
return r.updates
|
||||
}
|
||||
|
||||
func TestConsoleVideoEditPostsVideoAndPolls(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if serveTestDPoPToken(t, writer, request) {
|
||||
return
|
||||
}
|
||||
verifyTestDPoPProof(t, request)
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/edits":
|
||||
var payload map[string]any
|
||||
if err := json.NewDecoder(request.Body).Decode(&payload); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if payload["model"] != "grok-imagine-video" || payload["prompt"] != "add necklace" {
|
||||
t.Errorf("edit payload = %#v", payload)
|
||||
}
|
||||
if _, exists := payload["duration"]; exists {
|
||||
t.Errorf("edit payload must not include duration: %#v", payload)
|
||||
}
|
||||
video, ok := payload["video"].(map[string]any)
|
||||
if !ok || video["url"] != "https://example.com/source.mp4" {
|
||||
t.Errorf("edit video = %#v", payload["video"])
|
||||
}
|
||||
_, _ = writer.Write([]byte(`{"request_id":"upstream-video-edit-1"}`))
|
||||
case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-edit-1":
|
||||
_, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-edit.mp4"}}`))
|
||||
default:
|
||||
http.NotFound(writer, request)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
adapter, credential := newConsoleTestAdapter(t, server.URL)
|
||||
result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Model: "grok-imagine-video", Operation: provider.VideoOperationEdit,
|
||||
Prompt: "add necklace", VideoURL: "https://example.com/source.mp4",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.URL != "https://vidgen.x.ai/result-edit.mp4" {
|
||||
t.Fatalf("edit result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideoExtendPostsVideoAndPolls(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if serveTestDPoPToken(t, writer, request) {
|
||||
return
|
||||
}
|
||||
verifyTestDPoPProof(t, request)
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/extensions":
|
||||
var payload map[string]any
|
||||
if err := json.NewDecoder(request.Body).Decode(&payload); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if payload["model"] != "grok-imagine-video" || payload["duration"] != float64(4) || payload["prompt"] != "pan left" {
|
||||
t.Errorf("extend payload = %#v", payload)
|
||||
}
|
||||
video, ok := payload["video"].(map[string]any)
|
||||
if !ok || video["url"] != "https://example.com/source.mp4" {
|
||||
t.Errorf("extend video = %#v", payload["video"])
|
||||
}
|
||||
_, _ = writer.Write([]byte(`{"request_id":"upstream-video-extend-1"}`))
|
||||
case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-extend-1":
|
||||
_, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-extend.mp4"}}`))
|
||||
default:
|
||||
http.NotFound(writer, request)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
adapter, credential := newConsoleTestAdapter(t, server.URL)
|
||||
result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Model: "grok-imagine-video", Operation: provider.VideoOperationExtend,
|
||||
Prompt: "pan left", Duration: 4, VideoURL: "https://example.com/source.mp4",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.URL != "https://vidgen.x.ai/result-extend.mp4" {
|
||||
t.Fatalf("extend result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideoEditRejectsNonImagineVideoModel(t *testing.T) {
|
||||
adapter, credential := newConsoleTestAdapter(t, "http://127.0.0.1")
|
||||
_, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Model: "grok-imagine-video-1.5", Operation: provider.VideoOperationEdit,
|
||||
Prompt: "x", VideoURL: "https://example.com/source.mp4",
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "grok-imagine-video") {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,9 @@ func (a *Adapter) Definition() provider.Definition {
|
||||
modeldomain.CapabilityImage,
|
||||
modeldomain.CapabilityImageEdit,
|
||||
modeldomain.CapabilityVideo,
|
||||
modeldomain.CapabilityTTS,
|
||||
modeldomain.CapabilitySTT,
|
||||
modeldomain.CapabilityRealtime,
|
||||
},
|
||||
Quota: provider.QuotaRemoteWindow,
|
||||
Credential: provider.CredentialSurface{
|
||||
@@ -28,6 +31,7 @@ func (a *Adapter) Definition() provider.Definition {
|
||||
},
|
||||
Media: provider.MediaSurface{
|
||||
ImageGeneration: true, ImageEdit: true, VideoGeneration: true,
|
||||
TTS: true, STT: true, Realtime: true,
|
||||
},
|
||||
// Console shares the browser/clearance surface with Web. A 403 is
|
||||
// therefore normally an egress challenge, not proof that the SSO
|
||||
|
||||
@@ -292,6 +292,23 @@ func (a *Adapter) doDPoPRequest(
|
||||
method, endpoint string,
|
||||
body []byte,
|
||||
accept string,
|
||||
) (*http.Response, error) {
|
||||
contentType := ""
|
||||
if len(body) > 0 {
|
||||
contentType = "application/json"
|
||||
}
|
||||
return a.doDPoPRequestWithContentType(ctx, credential, ssoToken, lease, method, endpoint, body, contentType, accept)
|
||||
}
|
||||
|
||||
func (a *Adapter) doDPoPRequestWithContentType(
|
||||
ctx context.Context,
|
||||
credential account.Credential,
|
||||
ssoToken string,
|
||||
lease *infraegress.Lease,
|
||||
method, endpoint string,
|
||||
body []byte,
|
||||
contentType string,
|
||||
accept string,
|
||||
) (*http.Response, error) {
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
session, cacheKey, err := a.dpop.get(ctx, a, credential, ssoToken, lease)
|
||||
@@ -308,7 +325,10 @@ func (a *Adapter) doDPoPRequest(
|
||||
}
|
||||
applyBrowserHeaders(request, ssoToken, lease)
|
||||
if len(body) > 0 {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
if strings.TrimSpace(contentType) == "" {
|
||||
contentType = "application/json"
|
||||
}
|
||||
request.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
if strings.TrimSpace(accept) != "" {
|
||||
request.Header.Set("Accept", accept)
|
||||
|
||||
@@ -29,14 +29,31 @@ const (
|
||||
consoleMediaOutputAttempts = 3
|
||||
consoleVideoPollEvery = 2 * time.Second
|
||||
consoleMaxEditImages = 3
|
||||
consoleMaxVideoImages = 1
|
||||
// Upstream enforces the two video image inputs separately (measured against
|
||||
// console.x.ai on both grok-imagine-video and grok-imagine-video-1.5):
|
||||
// image = first frame, image-to-video, at most 1
|
||||
// reference_images = style/content references, reference-to-video, at most 7
|
||||
// 8 references answer 400 "Too many reference images: 8. Maximum allowed is 7."
|
||||
// The two are mutually exclusive below and their limits are never summed, so a
|
||||
// combined ceiling would accept payloads that upstream then rejects.
|
||||
consoleMaxVideoFirstFrames = 1
|
||||
consoleMaxVideoReferenceImages = 7
|
||||
)
|
||||
|
||||
type consoleMediaUpstreamError struct {
|
||||
status int
|
||||
summary string
|
||||
status int
|
||||
summary string
|
||||
retryAfter time.Duration
|
||||
requestScoped bool
|
||||
}
|
||||
|
||||
var (
|
||||
_ provider.HTTPStatusError = (*consoleMediaUpstreamError)(nil)
|
||||
_ provider.RetryAfterError = (*consoleMediaUpstreamError)(nil)
|
||||
_ provider.RequestScopedError = (*consoleMediaUpstreamError)(nil)
|
||||
_ provider.PublicMessageError = (*consoleMediaUpstreamError)(nil)
|
||||
)
|
||||
|
||||
func (e *consoleMediaUpstreamError) Error() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
@@ -51,6 +68,24 @@ func (e *consoleMediaUpstreamError) HTTPStatusCode() int {
|
||||
return e.status
|
||||
}
|
||||
|
||||
func (e *consoleMediaUpstreamError) RetryAfterDuration() time.Duration {
|
||||
if e == nil {
|
||||
return 0
|
||||
}
|
||||
return e.retryAfter
|
||||
}
|
||||
|
||||
func (e *consoleMediaUpstreamError) RequestScopedFailure() bool {
|
||||
return e != nil && e.requestScoped
|
||||
}
|
||||
|
||||
func (e *consoleMediaUpstreamError) PublicErrorMessage() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
return e.summary
|
||||
}
|
||||
|
||||
func (a *Adapter) GenerateImage(ctx context.Context, request provider.ImageGenerationRequest) (*provider.Response, error) {
|
||||
if !ResolveMedia(request.Model, modeldomain.CapabilityImage) {
|
||||
return invalidConsoleMediaRequest("模型不支持 Console 图片生成"), nil
|
||||
@@ -77,6 +112,10 @@ func (a *Adapter) GenerateImage(ctx context.Context, request provider.ImageGener
|
||||
if err != nil {
|
||||
return invalidConsoleMediaRequest(err.Error()), nil
|
||||
}
|
||||
quality, err := normalizeConsoleImageQuality(request.Model, request.Quality)
|
||||
if err != nil {
|
||||
return invalidConsoleMediaRequest(err.Error()), nil
|
||||
}
|
||||
payload := map[string]any{"model": request.Model, "prompt": request.Prompt, "n": count, "response_format": format}
|
||||
if ratio != "" {
|
||||
payload["aspect_ratio"] = ratio
|
||||
@@ -84,6 +123,9 @@ func (a *Adapter) GenerateImage(ctx context.Context, request provider.ImageGener
|
||||
if resolution != "" {
|
||||
payload["resolution"] = resolution
|
||||
}
|
||||
if quality != "" {
|
||||
payload["quality"] = quality
|
||||
}
|
||||
return a.forwardConsoleMedia(ctx, request.Credential, "/images/generations", payload, format, count)
|
||||
}
|
||||
|
||||
@@ -116,6 +158,10 @@ func (a *Adapter) EditImage(ctx context.Context, request provider.ImageEditReque
|
||||
if err != nil {
|
||||
return invalidConsoleMediaRequest(err.Error()), nil
|
||||
}
|
||||
quality, err := normalizeConsoleImageQuality(request.Model, request.Quality)
|
||||
if err != nil {
|
||||
return invalidConsoleMediaRequest(err.Error()), nil
|
||||
}
|
||||
images := make([]map[string]any, 0, len(request.ImageURLs))
|
||||
for _, rawURL := range request.ImageURLs {
|
||||
value := strings.TrimSpace(rawURL)
|
||||
@@ -136,6 +182,9 @@ func (a *Adapter) EditImage(ctx context.Context, request provider.ImageEditReque
|
||||
if resolution != "" {
|
||||
payload["resolution"] = resolution
|
||||
}
|
||||
if quality != "" {
|
||||
payload["quality"] = quality
|
||||
}
|
||||
return a.forwardConsoleMedia(ctx, request.Credential, "/images/edits", payload, format, count)
|
||||
}
|
||||
|
||||
@@ -394,40 +443,148 @@ func trustedConsoleImageHost(host string) bool {
|
||||
}
|
||||
|
||||
func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoRequest) (provider.VideoResult, error) {
|
||||
if !ResolveMedia("grok-imagine-video", modeldomain.CapabilityVideo) {
|
||||
return provider.VideoResult{}, errors.New("Console 视频模型未注册")
|
||||
modelName := strings.TrimSpace(request.Model)
|
||||
if modelName == "" {
|
||||
modelName = "grok-imagine-video"
|
||||
}
|
||||
if len(request.ReferenceURLs) > consoleMaxVideoImages {
|
||||
return provider.VideoResult{}, fmt.Errorf("Console grok-imagine-video 最多支持 1 张首图,当前为 %d 张", len(request.ReferenceURLs))
|
||||
if !ResolveMedia(modelName, modeldomain.CapabilityVideo) {
|
||||
return provider.VideoResult{}, fmt.Errorf("Console 视频模型未注册: %s", modelName)
|
||||
}
|
||||
if request.Duration < 1 || request.Duration > 15 {
|
||||
return provider.VideoResult{}, errors.New("duration 必须在 1 到 15 秒之间")
|
||||
operation := request.Operation
|
||||
if operation == "" {
|
||||
operation = provider.VideoOperationGenerate
|
||||
}
|
||||
if request.Resolution != "" && request.Resolution != "480p" && request.Resolution != "720p" {
|
||||
return provider.VideoResult{}, errors.New("grok-imagine-video 仅支持 480p 或 720p")
|
||||
switch operation {
|
||||
case provider.VideoOperationGenerate, provider.VideoOperationEdit, provider.VideoOperationExtend:
|
||||
default:
|
||||
return provider.VideoResult{}, fmt.Errorf("不支持的视频操作: %s", operation)
|
||||
}
|
||||
payload := map[string]any{
|
||||
"model": "grok-imagine-video", "duration": request.Duration,
|
||||
// Official video edit/extension docs and model catalog only expose VIDEO input on
|
||||
// grok-imagine-video. 1.5 is generation-oriented (TEXT/IMAGE/AUDIO) and is rejected here.
|
||||
if operation != provider.VideoOperationGenerate && modelName != "grok-imagine-video" {
|
||||
return provider.VideoResult{}, fmt.Errorf("%s 仅支持 grok-imagine-video", operation)
|
||||
}
|
||||
firstFrames, referenceImages := consoleVideoImageCounts(request)
|
||||
if firstFrames > consoleMaxVideoFirstFrames {
|
||||
return provider.VideoResult{}, fmt.Errorf("Console %s 最多支持 %d 张首帧图,当前为 %d 张", modelName, consoleMaxVideoFirstFrames, firstFrames)
|
||||
}
|
||||
if referenceImages > consoleMaxVideoReferenceImages {
|
||||
return provider.VideoResult{}, fmt.Errorf("Console %s 最多支持 %d 张参考图,当前为 %d 张", modelName, consoleMaxVideoReferenceImages, referenceImages)
|
||||
}
|
||||
if operation == provider.VideoOperationGenerate {
|
||||
if request.Duration < 1 || request.Duration > 15 {
|
||||
return provider.VideoResult{}, errors.New("duration 必须在 1 到 15 秒之间")
|
||||
}
|
||||
// reference-to-video on the base model caps at 10s upstream; measured:
|
||||
// grok-imagine-video + reference_images + duration=15
|
||||
// -> 400 "Duration 15s exceeds the maximum allowed for reference-to-video, which is 10s."
|
||||
// image-to-video (the image field) and grok-imagine-video-1.5 both keep 15s,
|
||||
// so the cap keys on reference_images plus the base model, not on duration alone.
|
||||
if modelName == "grok-imagine-video" && referenceImages > 0 && request.Duration > 10 {
|
||||
return provider.VideoResult{}, fmt.Errorf("%s 的参考图生视频最长 10 秒,当前为 %d 秒", modelName, request.Duration)
|
||||
}
|
||||
} else if operation == provider.VideoOperationExtend {
|
||||
// Official /v1/videos/extensions defaults to 6s and accepts 2-10s.
|
||||
if request.Duration == 0 {
|
||||
request.Duration = 6
|
||||
}
|
||||
if request.Duration < 2 || request.Duration > 10 {
|
||||
return provider.VideoResult{}, errors.New("视频延长 duration 必须在 2 到 10 秒之间")
|
||||
}
|
||||
} else if request.Duration != 0 {
|
||||
return provider.VideoResult{}, errors.New("视频编辑不支持 duration")
|
||||
}
|
||||
if request.Resolution == "1080p" {
|
||||
if modelName != "grok-imagine-video-1.5" {
|
||||
return provider.VideoResult{}, fmt.Errorf("%s 不支持 1080p", modelName)
|
||||
}
|
||||
if len(request.ReferenceURLs) > 0 {
|
||||
return provider.VideoResult{}, errors.New("reference_images 模式最高支持 720p")
|
||||
}
|
||||
} else if request.Resolution != "" && request.Resolution != "480p" && request.Resolution != "720p" {
|
||||
return provider.VideoResult{}, fmt.Errorf("%s 仅支持 480p、720p 或 1080p", modelName)
|
||||
}
|
||||
payload := map[string]any{"model": modelName}
|
||||
if operation == provider.VideoOperationGenerate || operation == provider.VideoOperationExtend {
|
||||
payload["duration"] = request.Duration
|
||||
}
|
||||
if prompt := strings.TrimSpace(request.Prompt); prompt != "" {
|
||||
payload["prompt"] = prompt
|
||||
}
|
||||
if ratio := strings.TrimSpace(request.AspectRatio); ratio != "" {
|
||||
payload["aspect_ratio"] = ratio
|
||||
}
|
||||
if resolution := strings.TrimSpace(request.Resolution); resolution != "" {
|
||||
payload["resolution"] = resolution
|
||||
}
|
||||
if len(request.ReferenceURLs) == 1 {
|
||||
value := strings.TrimSpace(request.ReferenceURLs[0])
|
||||
if !validConsoleMediaInputURL(value, "image") {
|
||||
return provider.VideoResult{}, errors.New("视频首图必须是 HTTPS URL 或 image data URL")
|
||||
if operation == provider.VideoOperationGenerate {
|
||||
if ratio := strings.TrimSpace(request.AspectRatio); ratio != "" {
|
||||
payload["aspect_ratio"] = ratio
|
||||
}
|
||||
payload["image"] = map[string]any{"url": value}
|
||||
}
|
||||
if _, hasPrompt := payload["prompt"]; !hasPrompt {
|
||||
if _, hasImage := payload["image"]; !hasImage {
|
||||
return provider.VideoResult{}, errors.New("文本生视频必须提供 prompt;图片生视频可以省略 prompt")
|
||||
if resolution := strings.TrimSpace(request.Resolution); resolution != "" {
|
||||
payload["resolution"] = resolution
|
||||
}
|
||||
if imageURL := strings.TrimSpace(request.ImageURL); imageURL != "" {
|
||||
if !validConsoleMediaInputURL(imageURL, "image") {
|
||||
return provider.VideoResult{}, errors.New("视频首图必须是 HTTPS URL 或 image data URL")
|
||||
}
|
||||
payload["image"] = map[string]any{"url": imageURL}
|
||||
}
|
||||
if strings.TrimSpace(request.ImageURL) != "" && (len(request.ReferenceURLs) > 0 || len(request.ReferenceAudios) > 0) {
|
||||
return provider.VideoResult{}, errors.New("image 不能与 reference_images/reference_audios 同时使用")
|
||||
}
|
||||
if len(request.ReferenceURLs) > 0 {
|
||||
references := make([]map[string]any, 0, len(request.ReferenceURLs))
|
||||
for _, rawURL := range request.ReferenceURLs {
|
||||
value := strings.TrimSpace(rawURL)
|
||||
if !validConsoleMediaInputURL(value, "image") {
|
||||
return provider.VideoResult{}, errors.New("每张视频参考图都必须是 HTTPS URL 或 image data URL")
|
||||
}
|
||||
references = append(references, map[string]any{"url": value})
|
||||
}
|
||||
// A single reference must stay in reference_images; do not coerce to image.
|
||||
payload["reference_images"] = references
|
||||
}
|
||||
if len(request.ReferenceAudios) > 0 {
|
||||
if len(request.ReferenceAudios) > 3 {
|
||||
return provider.VideoResult{}, errors.New("reference_audios 最多 3 个")
|
||||
}
|
||||
audios := make([]map[string]any, 0, len(request.ReferenceAudios))
|
||||
for _, raw := range request.ReferenceAudios {
|
||||
voiceID := strings.TrimSpace(raw)
|
||||
if voiceID == "" {
|
||||
return provider.VideoResult{}, errors.New("reference_audios.voice_id 不能为空")
|
||||
}
|
||||
audios = append(audios, map[string]any{"voice_id": voiceID})
|
||||
}
|
||||
payload["reference_audios"] = audios
|
||||
}
|
||||
hasReferenceMode := len(request.ReferenceURLs) > 0 || len(request.ReferenceAudios) > 0
|
||||
if hasReferenceMode {
|
||||
if strings.TrimSpace(request.Prompt) == "" {
|
||||
return provider.VideoResult{}, errors.New("参考图/参考音频视频必须提供 prompt")
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(request.Resolution), "1080p") {
|
||||
return provider.VideoResult{}, errors.New("参考图视频 resolution 最高 720p")
|
||||
}
|
||||
}
|
||||
if _, hasPrompt := payload["prompt"]; !hasPrompt {
|
||||
if _, hasImage := payload["image"]; !hasImage {
|
||||
if !hasReferenceMode {
|
||||
return provider.VideoResult{}, errors.New("文本生视频必须提供 prompt;图片生视频可以省略 prompt")
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
prompt := strings.TrimSpace(request.Prompt)
|
||||
if prompt == "" {
|
||||
return provider.VideoResult{}, errors.New("视频编辑/延长必须提供 prompt")
|
||||
}
|
||||
videoURL := strings.TrimSpace(request.VideoURL)
|
||||
if !validConsoleMediaInputURL(videoURL, "video") {
|
||||
return provider.VideoResult{}, errors.New("输入视频必须是 HTTPS URL 或 video data URL")
|
||||
}
|
||||
payload["prompt"] = prompt
|
||||
payload["video"] = map[string]any{"url": videoURL}
|
||||
if strings.TrimSpace(request.ImageURL) != "" || len(request.ReferenceURLs) > 0 || len(request.ReferenceAudios) > 0 {
|
||||
return provider.VideoResult{}, errors.New("视频编辑/延长不支持 image、reference_images 或 reference_audios")
|
||||
}
|
||||
if strings.TrimSpace(request.AspectRatio) != "" || strings.TrimSpace(request.Resolution) != "" {
|
||||
return provider.VideoResult{}, errors.New("视频编辑/延长不支持 aspect_ratio 或 resolution")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -445,7 +602,14 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque
|
||||
return provider.VideoResult{}, err
|
||||
}
|
||||
baseURL := a.config().BaseURL
|
||||
created, err := a.doConsoleVideoJSON(ctx, request.Credential, token, lease, http.MethodPost, consoleV1Endpoint(baseURL, "/videos/generations"), body)
|
||||
createPath := "/videos/generations"
|
||||
switch operation {
|
||||
case provider.VideoOperationEdit:
|
||||
createPath = "/videos/edits"
|
||||
case provider.VideoOperationExtend:
|
||||
createPath = "/videos/extensions"
|
||||
}
|
||||
created, err := a.doConsoleVideoJSON(ctx, request.Credential, token, lease, http.MethodPost, consoleV1Endpoint(baseURL, createPath), body)
|
||||
if err != nil {
|
||||
return provider.VideoResult{}, err
|
||||
}
|
||||
@@ -509,7 +673,7 @@ func (a *Adapter) doConsoleVideoJSON(ctx context.Context, credential account.Cre
|
||||
if !dpopRequired {
|
||||
a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil)
|
||||
}
|
||||
return nil, newConsoleMediaUpstreamError(response.StatusCode, data)
|
||||
return nil, newConsoleMediaUpstreamError(response.StatusCode, data, parseConsoleRetryAfterHeader(response.Header.Get("Retry-After"), time.Now().UTC()))
|
||||
}
|
||||
a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil)
|
||||
return data, nil
|
||||
@@ -603,6 +767,20 @@ func normalizeConsoleImageResolution(value string) (string, error) {
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func normalizeConsoleImageQuality(model, value string) (string, error) {
|
||||
value = strings.ToLower(strings.TrimSpace(value))
|
||||
if value == "" {
|
||||
return "", nil
|
||||
}
|
||||
if strings.TrimSpace(model) != "grok-imagine-image-2.0" {
|
||||
return "", errors.New("quality 仅支持 grok-imagine-image-2.0")
|
||||
}
|
||||
if value != "low" && value != "medium" {
|
||||
return "", errors.New("quality 必须是 low 或 medium")
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func resolveConsoleImageAspectRatio(aspectRatio, size string) (string, error) {
|
||||
value := strings.ToLower(strings.TrimSpace(aspectRatio))
|
||||
if value == "" {
|
||||
@@ -677,7 +855,7 @@ func parseConsoleVideoStatus(body []byte, progress func(int)) (provider.VideoRes
|
||||
}
|
||||
}
|
||||
|
||||
func newConsoleMediaUpstreamError(status int, body []byte) error {
|
||||
func newConsoleMediaUpstreamError(status int, body []byte, retryAfter time.Duration) error {
|
||||
message := ""
|
||||
var payload map[string]any
|
||||
if json.Unmarshal(body, &payload) == nil {
|
||||
@@ -685,22 +863,38 @@ func newConsoleMediaUpstreamError(status int, body []byte) error {
|
||||
if message == "" {
|
||||
message = safeConsoleMediaErrorValue(payload["message"])
|
||||
}
|
||||
if message == "" {
|
||||
message = safeConsoleMediaErrorValue(payload["detail"])
|
||||
}
|
||||
}
|
||||
summary := fmt.Sprintf("Console 媒体上游返回 %d", status)
|
||||
if message != "" {
|
||||
summary += ": " + message
|
||||
}
|
||||
return &consoleMediaUpstreamError{status: status, summary: summary}
|
||||
if retryAfter <= 0 {
|
||||
retryAfter = consoleRetryAfter(body)
|
||||
}
|
||||
return &consoleMediaUpstreamError{
|
||||
status: status, summary: summary, retryAfter: retryAfter,
|
||||
requestScoped: status == http.StatusForbidden && provider.IsDPoPProofRequiredBody(body),
|
||||
}
|
||||
}
|
||||
|
||||
func safeConsoleMediaErrorValue(value any) string {
|
||||
if object, ok := value.(map[string]any); ok {
|
||||
for _, key := range []string{"message", "code", "type"} {
|
||||
for _, key := range []string{"message", "msg", "code", "type", "detail", "error_description"} {
|
||||
raw, exists := object[key]
|
||||
if !exists || raw == nil {
|
||||
continue
|
||||
}
|
||||
if text := safeConsoleMediaText(fmt.Sprint(raw)); text != "" {
|
||||
if text := safeConsoleMediaErrorValue(raw); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
if values, ok := value.([]any); ok {
|
||||
for _, item := range values {
|
||||
if text := safeConsoleMediaErrorValue(item); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
@@ -708,13 +902,24 @@ func safeConsoleMediaErrorValue(value any) string {
|
||||
if text, ok := value.(string); ok {
|
||||
return safeConsoleMediaText(text)
|
||||
}
|
||||
switch value.(type) {
|
||||
case json.Number, float64, float32, int, int64, int32, uint, uint64, uint32, bool:
|
||||
return safeConsoleMediaText(fmt.Sprint(value))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func safeConsoleMediaText(value string) string {
|
||||
value = strings.Join(strings.Fields(value), " ")
|
||||
if strings.Contains(strings.ToLower(value), "authorization") || strings.Contains(strings.ToLower(value), "cookie") {
|
||||
return "上游拒绝请求"
|
||||
lower := strings.ToLower(value)
|
||||
for _, sensitive := range []string{
|
||||
"authorization", "cookie", "bearer ",
|
||||
"access_token", "access-token", "refresh_token", "refresh-token",
|
||||
"api_key", "api-key", "sso-rw", "cf_clearance",
|
||||
} {
|
||||
if strings.Contains(lower, sensitive) {
|
||||
return "上游拒绝请求"
|
||||
}
|
||||
}
|
||||
const limit = 160
|
||||
if len(value) <= limit {
|
||||
@@ -731,3 +936,15 @@ func trustedConsoleVideoHost(host string) bool {
|
||||
host = strings.ToLower(strings.TrimSpace(host))
|
||||
return host == "vidgen.x.ai" || strings.HasSuffix(host, ".vidgen.x.ai")
|
||||
}
|
||||
|
||||
func consoleVideoImageCounts(request provider.VideoRequest) (firstFrames int, referenceImages int) {
|
||||
if strings.TrimSpace(request.ImageURL) != "" {
|
||||
firstFrames++
|
||||
}
|
||||
for _, raw := range request.ReferenceURLs {
|
||||
if strings.TrimSpace(raw) != "" {
|
||||
referenceImages++
|
||||
}
|
||||
}
|
||||
return firstFrames, referenceImages
|
||||
}
|
||||
@@ -229,12 +229,39 @@ func normalizeConsoleTools(payload map[string]any) bool {
|
||||
if enabled, ok := tool["enable_image_understanding"].(bool); ok {
|
||||
clean["enable_image_understanding"] = enabled
|
||||
}
|
||||
// Forward the image-search toggle (enable_image_search) so clients
|
||||
// can explicitly enable/disable it; absent when not requested.
|
||||
if enabled, ok := tool["enable_image_search"].(bool); ok {
|
||||
clean["enable_image_search"] = enabled
|
||||
}
|
||||
result = append(result, clean)
|
||||
case "x_search":
|
||||
clean := map[string]any{"type": "x_search", "enable_video_understanding": true}
|
||||
if enabled, ok := tool["enable_video_understanding"].(bool); ok {
|
||||
clean["enable_video_understanding"] = enabled
|
||||
}
|
||||
// Forward the X-search time bounds (from_date/to_date, YYYY-MM-DD).
|
||||
// Invalid formats and empty strings are dropped; if from_date is
|
||||
// later than to_date both are dropped to avoid an upstream 400.
|
||||
for _, field := range []string{"from_date", "to_date"} {
|
||||
text, ok := tool[field].(string)
|
||||
if !ok || text == "" {
|
||||
continue
|
||||
}
|
||||
if date, err := time.Parse("2006-01-02", text); err == nil && date.Format("2006-01-02") == text {
|
||||
clean[field] = text
|
||||
}
|
||||
}
|
||||
from, hasFrom := clean["from_date"].(string)
|
||||
to, hasTo := clean["to_date"].(string)
|
||||
if hasFrom && hasTo {
|
||||
fromDate, _ := time.Parse("2006-01-02", from)
|
||||
toDate, _ := time.Parse("2006-01-02", to)
|
||||
if fromDate.After(toDate) {
|
||||
delete(clean, "from_date")
|
||||
delete(clean, "to_date")
|
||||
}
|
||||
}
|
||||
result = append(result, clean)
|
||||
case "function":
|
||||
name, _ := tool["name"].(string)
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
package console
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
)
|
||||
|
||||
const (
|
||||
consoleVoiceBodyLimit = 64 << 20
|
||||
consoleVoiceAudioLimit = 128 << 20
|
||||
)
|
||||
|
||||
func (a *Adapter) SynthesizeSpeech(ctx context.Context, request provider.TTSRequest) (provider.TTSResult, error) {
|
||||
text := strings.TrimSpace(request.Text)
|
||||
if text == "" {
|
||||
return provider.TTSResult{}, invalidConsoleVoiceError("text 不能为空")
|
||||
}
|
||||
if utf8.RuneCountInString(text) > 15000 {
|
||||
return provider.TTSResult{}, invalidConsoleVoiceError("text 最多 15000 个字符")
|
||||
}
|
||||
language := strings.TrimSpace(request.Language)
|
||||
if language == "" {
|
||||
return provider.TTSResult{}, invalidConsoleVoiceError("language 不能为空")
|
||||
}
|
||||
payload := map[string]any{"text": text, "language": language}
|
||||
if voiceID := strings.TrimSpace(request.VoiceID); voiceID != "" {
|
||||
payload["voice_id"] = voiceID
|
||||
}
|
||||
if format := normalizeTTSOutputFormat(request.OutputFormat); format != nil {
|
||||
payload["output_format"] = format
|
||||
}
|
||||
if request.Speed > 0 {
|
||||
payload["speed"] = request.Speed
|
||||
}
|
||||
if request.OptimizeStreamingLatency > 0 {
|
||||
payload["optimize_streaming_latency"] = strconv.Itoa(request.OptimizeStreamingLatency)
|
||||
}
|
||||
if request.TextNormalization {
|
||||
payload["text_normalization"] = true
|
||||
}
|
||||
if request.WithTimestamps {
|
||||
payload["with_timestamps"] = true
|
||||
}
|
||||
response, err := a.forwardConsoleVoice(ctx, request.Credential, http.MethodPost, "/tts", payload, "application/json", "*/*")
|
||||
if err != nil {
|
||||
return provider.TTSResult{}, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return provider.TTSResult{}, consoleVoiceResponseError(response)
|
||||
}
|
||||
contentType := strings.ToLower(strings.TrimSpace(response.Header.Get("Content-Type")))
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceAudioLimit+1))
|
||||
if err != nil {
|
||||
return provider.TTSResult{}, err
|
||||
}
|
||||
if len(data) > consoleVoiceAudioLimit {
|
||||
return provider.TTSResult{}, errors.New("Console TTS 响应超过安全上限")
|
||||
}
|
||||
if strings.Contains(contentType, "application/json") || request.WithTimestamps {
|
||||
var envelope struct {
|
||||
Audio string `json:"audio"`
|
||||
ContentType string `json:"content_type"`
|
||||
Duration float64 `json:"duration"`
|
||||
AudioTimestamps *struct {
|
||||
GraphChars []string `json:"graph_chars"`
|
||||
GraphTimes []struct {
|
||||
Start float64 `json:"start"`
|
||||
End float64 `json:"end"`
|
||||
} `json:"graph_times"`
|
||||
} `json:"audio_timestamps"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &envelope); err != nil {
|
||||
if !strings.Contains(contentType, "application/json") {
|
||||
return provider.TTSResult{Audio: data, ContentType: firstNonEmpty(contentType, "audio/mpeg")}, nil
|
||||
}
|
||||
return provider.TTSResult{}, fmt.Errorf("解析 Console TTS JSON 响应失败: %w", err)
|
||||
}
|
||||
audio, err := base64.StdEncoding.DecodeString(strings.TrimSpace(envelope.Audio))
|
||||
if err != nil {
|
||||
return provider.TTSResult{}, fmt.Errorf("解码 Console TTS audio 失败: %w", err)
|
||||
}
|
||||
result := provider.TTSResult{
|
||||
Audio: audio, ContentType: firstNonEmpty(envelope.ContentType, contentType, "audio/mpeg"),
|
||||
Duration: envelope.Duration, Base64Audio: envelope.Audio, JSONEnvelope: true,
|
||||
}
|
||||
if envelope.AudioTimestamps != nil {
|
||||
times := make([]provider.TTSTimestampSpan, 0, len(envelope.AudioTimestamps.GraphTimes))
|
||||
for _, item := range envelope.AudioTimestamps.GraphTimes {
|
||||
times = append(times, provider.TTSTimestampSpan{Start: item.Start, End: item.End})
|
||||
}
|
||||
result.Timestamps = &provider.TTSTimestamps{
|
||||
GraphChars: append([]string(nil), envelope.AudioTimestamps.GraphChars...),
|
||||
GraphTimes: times,
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
return provider.TTSResult{Audio: data, ContentType: firstNonEmpty(contentType, "audio/mpeg")}, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) ListTTSVoices(ctx context.Context, credential account.Credential) ([]provider.VoiceInfo, error) {
|
||||
response, err := a.forwardConsoleVoice(ctx, credential, http.MethodGet, "/tts/voices", nil, "", "application/json")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return nil, consoleVoiceResponseError(response)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var payload struct {
|
||||
Voices []struct {
|
||||
VoiceID string `json:"voice_id"`
|
||||
Name string `json:"name"`
|
||||
Language *string `json:"language"`
|
||||
} `json:"voices"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
return nil, fmt.Errorf("解析 Console TTS voices 失败: %w", err)
|
||||
}
|
||||
result := make([]provider.VoiceInfo, 0, len(payload.Voices))
|
||||
for _, item := range payload.Voices {
|
||||
language := ""
|
||||
if item.Language != nil {
|
||||
language = strings.TrimSpace(*item.Language)
|
||||
}
|
||||
result = append(result, provider.VoiceInfo{VoiceID: strings.TrimSpace(item.VoiceID), Name: strings.TrimSpace(item.Name), Language: language})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) GetTTSVoice(ctx context.Context, credential account.Credential, voiceID string) (provider.VoiceInfo, error) {
|
||||
voiceID = strings.TrimSpace(voiceID)
|
||||
if voiceID == "" {
|
||||
return provider.VoiceInfo{}, invalidConsoleVoiceError("voice_id 不能为空")
|
||||
}
|
||||
response, err := a.forwardConsoleVoice(ctx, credential, http.MethodGet, "/tts/voices/"+url.PathEscape(voiceID), nil, "", "application/json")
|
||||
if err != nil {
|
||||
return provider.VoiceInfo{}, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return provider.VoiceInfo{}, consoleVoiceResponseError(response)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1))
|
||||
if err != nil {
|
||||
return provider.VoiceInfo{}, err
|
||||
}
|
||||
var payload struct {
|
||||
VoiceID string `json:"voice_id"`
|
||||
Name string `json:"name"`
|
||||
Language *string `json:"language"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
return provider.VoiceInfo{}, fmt.Errorf("解析 Console TTS voice 失败: %w", err)
|
||||
}
|
||||
language := ""
|
||||
if payload.Language != nil {
|
||||
language = strings.TrimSpace(*payload.Language)
|
||||
}
|
||||
return provider.VoiceInfo{VoiceID: strings.TrimSpace(payload.VoiceID), Name: strings.TrimSpace(payload.Name), Language: language}, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) TranscribeSpeech(ctx context.Context, request provider.STTRequest) (provider.STTResult, error) {
|
||||
hasFile := len(request.FileData) > 0
|
||||
hasURL := strings.TrimSpace(request.URL) != ""
|
||||
if hasFile == hasURL {
|
||||
return provider.STTResult{}, invalidConsoleVoiceError("STT 必须提供 file 或 url 其中之一")
|
||||
}
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
writeField := func(name, value string) error {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
return writer.WriteField(name, value)
|
||||
}
|
||||
_ = writeField("audio_format", request.AudioFormat)
|
||||
_ = writeField("sample_rate", request.SampleRate)
|
||||
_ = writeField("language", request.Language)
|
||||
if request.Format {
|
||||
_ = writer.WriteField("format", "true")
|
||||
}
|
||||
if request.Multichannel {
|
||||
_ = writer.WriteField("multichannel", "true")
|
||||
}
|
||||
if request.Channels > 0 {
|
||||
_ = writer.WriteField("channels", strconv.Itoa(request.Channels))
|
||||
}
|
||||
if request.Diarize {
|
||||
_ = writer.WriteField("diarize", "true")
|
||||
}
|
||||
for _, term := range request.KeyTerms {
|
||||
_ = writeField("keyterm", term)
|
||||
}
|
||||
if request.FillerWords {
|
||||
_ = writer.WriteField("filler_words", "true")
|
||||
}
|
||||
if request.VADThreshold != nil {
|
||||
_ = writer.WriteField("vad_threshold", strconv.FormatFloat(*request.VADThreshold, 'f', -1, 64))
|
||||
}
|
||||
if modelName := strings.TrimSpace(request.Model); modelName != "" {
|
||||
_ = writer.WriteField("model", modelName)
|
||||
}
|
||||
if hasURL {
|
||||
_ = writer.WriteField("url", strings.TrimSpace(request.URL))
|
||||
}
|
||||
if hasFile {
|
||||
fileName := strings.TrimSpace(request.FileName)
|
||||
if fileName == "" {
|
||||
fileName = "audio.bin"
|
||||
}
|
||||
part, err := writer.CreateFormFile("file", path.Base(fileName))
|
||||
if err != nil {
|
||||
return provider.STTResult{}, err
|
||||
}
|
||||
if _, err := part.Write(request.FileData); err != nil {
|
||||
return provider.STTResult{}, err
|
||||
}
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
return provider.STTResult{}, err
|
||||
}
|
||||
response, err := a.forwardConsoleVoiceBytes(ctx, request.Credential, http.MethodPost, "/stt", body.Bytes(), writer.FormDataContentType(), "application/json")
|
||||
if err != nil {
|
||||
return provider.STTResult{}, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return provider.STTResult{}, consoleVoiceResponseError(response)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1))
|
||||
if err != nil {
|
||||
return provider.STTResult{}, err
|
||||
}
|
||||
result, err := parseSTTResult(data)
|
||||
if err != nil {
|
||||
return provider.STTResult{}, err
|
||||
}
|
||||
result.RawJSON = append([]byte(nil), data...)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) forwardConsoleVoice(ctx context.Context, credential account.Credential, method, pathValue string, payload any, contentType, accept string) (*http.Response, error) {
|
||||
var body []byte
|
||||
var err error
|
||||
if payload != nil {
|
||||
body, err = json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if contentType == "" {
|
||||
contentType = "application/json"
|
||||
}
|
||||
}
|
||||
return a.forwardConsoleVoiceBytes(ctx, credential, method, pathValue, body, contentType, accept)
|
||||
}
|
||||
|
||||
func (a *Adapter) forwardConsoleVoiceBytes(ctx context.Context, credential account.Credential, method, pathValue string, body []byte, contentType, accept string) (*http.Response, error) {
|
||||
if strings.HasPrefix(strings.ToLower(strings.TrimSpace(contentType)), "multipart/") {
|
||||
return a.forwardConsoleVoiceMultipart(ctx, credential, method, pathValue, body, contentType, accept)
|
||||
}
|
||||
token, err := a.cipher.Decrypt(credential.EncryptedAccessToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg := a.config()
|
||||
requestCtx, cancel := context.WithTimeout(ctx, time.Duration(cfg.TimeoutSeconds)*time.Second)
|
||||
lease, err := a.egress.AcquireCredential(requestCtx, egressdomain.ScopeConsole, credential)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
if accept == "" {
|
||||
accept = "*/*"
|
||||
}
|
||||
response, err := a.doDPoPRequestWithContentType(requestCtx, credential, token, lease, method, consoleV1Endpoint(cfg.BaseURL, pathValue), body, contentType, accept)
|
||||
if err != nil {
|
||||
a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, 0, err)
|
||||
lease.Release()
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
response.Body = &releaseBody{ReadCloser: response.Body, release: func() {
|
||||
a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil)
|
||||
lease.Release()
|
||||
cancel()
|
||||
}}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) forwardConsoleVoiceMultipart(ctx context.Context, credential account.Credential, method, pathValue string, body []byte, contentType, accept string) (*http.Response, error) {
|
||||
token, err := a.cipher.Decrypt(credential.EncryptedAccessToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg := a.config()
|
||||
requestCtx, cancel := context.WithTimeout(ctx, time.Duration(cfg.TimeoutSeconds)*time.Second)
|
||||
lease, err := a.egress.AcquireCredential(requestCtx, egressdomain.ScopeConsole, credential)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
if accept == "" {
|
||||
accept = "*/*"
|
||||
}
|
||||
response, err := a.doDPoPRequestWithContentType(requestCtx, credential, token, lease, method, consoleV1Endpoint(cfg.BaseURL, pathValue), body, contentType, accept)
|
||||
if err != nil {
|
||||
a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, 0, err)
|
||||
lease.Release()
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
response.Body = &releaseBody{ReadCloser: response.Body, release: func() {
|
||||
a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil)
|
||||
lease.Release()
|
||||
cancel()
|
||||
}}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func normalizeTTSOutputFormat(format provider.TTSOutputFormat) map[string]any {
|
||||
codec := strings.ToLower(strings.TrimSpace(format.Codec))
|
||||
if codec == "" && format.SampleRate == 0 && format.BitRate == 0 {
|
||||
return nil
|
||||
}
|
||||
if codec == "" {
|
||||
codec = "mp3"
|
||||
}
|
||||
result := map[string]any{"codec": codec}
|
||||
if format.SampleRate > 0 {
|
||||
result["sample_rate"] = format.SampleRate
|
||||
}
|
||||
if format.BitRate > 0 {
|
||||
result["bit_rate"] = format.BitRate
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func parseSTTResult(data []byte) (provider.STTResult, error) {
|
||||
var payload struct {
|
||||
Text string `json:"text"`
|
||||
Language string `json:"language"`
|
||||
Duration float64 `json:"duration"`
|
||||
Words []struct {
|
||||
Text string `json:"text"`
|
||||
Start float64 `json:"start"`
|
||||
End float64 `json:"end"`
|
||||
Speaker *int `json:"speaker"`
|
||||
} `json:"words"`
|
||||
Channels []struct {
|
||||
Index int `json:"index"`
|
||||
Text string `json:"text"`
|
||||
Words []struct {
|
||||
Text string `json:"text"`
|
||||
Start float64 `json:"start"`
|
||||
End float64 `json:"end"`
|
||||
Speaker *int `json:"speaker"`
|
||||
} `json:"words"`
|
||||
} `json:"channels"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
return provider.STTResult{}, fmt.Errorf("解析 Console STT 响应失败: %w", err)
|
||||
}
|
||||
result := provider.STTResult{Text: payload.Text, Language: payload.Language, Duration: payload.Duration}
|
||||
for _, word := range payload.Words {
|
||||
result.Words = append(result.Words, provider.STTWord{Text: word.Text, Start: word.Start, End: word.End, Speaker: word.Speaker})
|
||||
}
|
||||
for _, channel := range payload.Channels {
|
||||
item := provider.STTChannel{Index: channel.Index, Text: channel.Text}
|
||||
for _, word := range channel.Words {
|
||||
item.Words = append(item.Words, provider.STTWord{Text: word.Text, Start: word.Start, End: word.End, Speaker: word.Speaker})
|
||||
}
|
||||
result.Channels = append(result.Channels, item)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func consoleVoiceResponseError(response *http.Response) error {
|
||||
data, _, err := provider.ReadDiagnosticBody(response.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
retryAfter := parseConsoleRetryAfterHeader(response.Header.Get("Retry-After"), time.Now().UTC())
|
||||
return newConsoleMediaUpstreamError(response.StatusCode, data, retryAfter)
|
||||
}
|
||||
|
||||
func invalidConsoleVoiceError(message string) error {
|
||||
return &consoleMediaUpstreamError{status: http.StatusBadRequest, summary: message}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package console
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
fhttp "github.com/bogdanfinn/fhttp"
|
||||
"github.com/bogdanfinn/websocket"
|
||||
|
||||
egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
)
|
||||
|
||||
// DialVoiceWebSocket opens an authenticated Console websocket for realtime or STT streaming.
|
||||
func (a *Adapter) DialVoiceWebSocket(ctx context.Context, request provider.VoiceWebSocketRequest) (provider.VoiceWebSocketConn, func(), error) {
|
||||
pathValue := strings.TrimSpace(request.Path)
|
||||
if pathValue == "" || strings.Contains(pathValue, "://") || strings.Contains(pathValue, "..") {
|
||||
return nil, nil, invalidConsoleVoiceError("voice websocket path 无效")
|
||||
}
|
||||
if !strings.HasPrefix(pathValue, "/") {
|
||||
pathValue = "/" + pathValue
|
||||
}
|
||||
switch pathValue {
|
||||
case "/realtime", "/stt":
|
||||
default:
|
||||
return nil, nil, invalidConsoleVoiceError("不支持的 voice websocket path")
|
||||
}
|
||||
|
||||
token, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
requestCtx, cancel := context.WithCancel(ctx)
|
||||
lease, err := a.egress.AcquireCredential(requestCtx, egressdomain.ScopeConsole, request.Credential)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
cleanup := func() {
|
||||
lease.Release()
|
||||
cancel()
|
||||
}
|
||||
|
||||
endpoint, err := a.voiceWebSocketEndpoint(pathValue, request.Model)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
proofEndpoint, err := voiceWebSocketProofEndpoint(endpoint)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
session, cacheKey, sessionErr := a.dpop.get(requestCtx, a, request.Credential, token, lease)
|
||||
if sessionErr != nil {
|
||||
cleanup()
|
||||
return nil, nil, sessionErr
|
||||
}
|
||||
|
||||
// The websocket dialer needs wss://, while DPoP protects the underlying
|
||||
// HTTP Upgrade request and Console validates htu against https://. Signing
|
||||
// the websocket URI itself produces a valid JWT with the wrong htu and the
|
||||
// server rejects an otherwise healthy session with 401.
|
||||
httpReq, requestErr := http.NewRequestWithContext(requestCtx, http.MethodGet, proofEndpoint, nil)
|
||||
if requestErr != nil {
|
||||
cleanup()
|
||||
return nil, nil, requestErr
|
||||
}
|
||||
applyBrowserHeaders(httpReq, token, lease)
|
||||
httpReq.Header.Set("Accept", "*/*")
|
||||
httpReq.Header.Set("Sec-Fetch-Mode", "websocket")
|
||||
httpReq.Header.Set("Sec-Fetch-Dest", "empty")
|
||||
httpReq.Header.Set("Sec-Fetch-Site", "same-origin")
|
||||
httpReq.Header.Set("Cache-Control", "no-cache")
|
||||
httpReq.Header.Set("Pragma", "no-cache")
|
||||
if requestErr := applyDPoPAuthorization(httpReq, session); requestErr != nil {
|
||||
cleanup()
|
||||
return nil, nil, requestErr
|
||||
}
|
||||
|
||||
headers := fhttp.Header{}
|
||||
for key, values := range httpReq.Header {
|
||||
for _, value := range values {
|
||||
headers.Add(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
connection, response, dialErr := lease.DialWebSocket(requestCtx, endpoint, headers, 30*time.Second)
|
||||
if dialErr == nil {
|
||||
if response != nil && response.Body != nil {
|
||||
_ = response.Body.Close()
|
||||
}
|
||||
if connection == nil {
|
||||
cleanup()
|
||||
return nil, nil, errors.New("Console voice websocket 连接为空")
|
||||
}
|
||||
a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, http.StatusSwitchingProtocols, nil)
|
||||
return connection, cleanup, nil
|
||||
}
|
||||
if response == nil {
|
||||
a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, 0, dialErr)
|
||||
cleanup()
|
||||
return nil, nil, fmt.Errorf("拨号 Console voice websocket 失败: %w", dialErr)
|
||||
}
|
||||
status := response.StatusCode
|
||||
var body []byte
|
||||
if response.Body != nil {
|
||||
body, _, _ = provider.ReadDiagnosticBody(response.Body)
|
||||
_ = response.Body.Close()
|
||||
}
|
||||
if status == http.StatusUnauthorized {
|
||||
a.dpop.invalidate(cacheKey, session.accessToken)
|
||||
if attempt == 0 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
dpopRequired := status == http.StatusForbidden && provider.IsDPoPProofRequiredBody(body)
|
||||
if status == http.StatusForbidden && shouldInvalidateConsoleClearance(body) {
|
||||
lease.InvalidateClearance()
|
||||
}
|
||||
if !dpopRequired {
|
||||
a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, status, nil)
|
||||
}
|
||||
cleanup()
|
||||
retryAfter := parseConsoleRetryAfterHeader(response.Header.Get("Retry-After"), time.Now().UTC())
|
||||
return nil, nil, newConsoleMediaUpstreamError(status, body, retryAfter)
|
||||
}
|
||||
cleanup()
|
||||
return nil, nil, errors.New("Console voice websocket DPoP 重试状态无效")
|
||||
}
|
||||
|
||||
func (a *Adapter) voiceWebSocketEndpoint(pathValue, modelName string) (string, error) {
|
||||
base := strings.TrimRight(strings.TrimSpace(a.config().BaseURL), "/")
|
||||
if base == "" {
|
||||
return "", errors.New("Console BaseURL 未配置")
|
||||
}
|
||||
endpoint, err := url.Parse(consoleV1Endpoint(base, pathValue))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
switch strings.ToLower(endpoint.Scheme) {
|
||||
case "https":
|
||||
endpoint.Scheme = "wss"
|
||||
case "http":
|
||||
endpoint.Scheme = "ws"
|
||||
case "wss", "ws":
|
||||
default:
|
||||
return "", fmt.Errorf("不支持的 Console voice websocket scheme: %s", endpoint.Scheme)
|
||||
}
|
||||
values := endpoint.Query()
|
||||
if modelName = strings.TrimSpace(modelName); modelName != "" {
|
||||
values.Set("model", modelName)
|
||||
}
|
||||
endpoint.RawQuery = values.Encode()
|
||||
return endpoint.String(), nil
|
||||
}
|
||||
|
||||
func voiceWebSocketProofEndpoint(endpoint string) (string, error) {
|
||||
parsed, err := url.Parse(strings.TrimSpace(endpoint))
|
||||
if err != nil || parsed.Host == "" {
|
||||
return "", errors.New("Console voice websocket endpoint 无效")
|
||||
}
|
||||
switch strings.ToLower(parsed.Scheme) {
|
||||
case "wss":
|
||||
parsed.Scheme = "https"
|
||||
case "ws":
|
||||
parsed.Scheme = "http"
|
||||
case "https", "http":
|
||||
default:
|
||||
return "", fmt.Errorf("不支持的 Console voice websocket scheme: %s", parsed.Scheme)
|
||||
}
|
||||
return parsed.String(), nil
|
||||
}
|
||||
|
||||
// Ensure bogdanfinn websocket.Conn satisfies the provider contract at compile time.
|
||||
var _ provider.VoiceWebSocketConn = (*websocket.Conn)(nil)
|
||||
@@ -55,6 +55,9 @@ type MediaSurface struct {
|
||||
ImageGeneration bool
|
||||
ImageEdit bool
|
||||
VideoGeneration bool
|
||||
TTS bool
|
||||
STT bool
|
||||
Realtime bool
|
||||
}
|
||||
|
||||
// CredentialSurface 描述号池凭据的接入和维护方式。
|
||||
@@ -131,7 +134,7 @@ func (d Definition) Validate() error {
|
||||
capabilities := make(map[modeldomain.Capability]struct{}, len(d.ModelCapabilities))
|
||||
for _, capability := range d.ModelCapabilities {
|
||||
switch capability {
|
||||
case modeldomain.CapabilityResponses, modeldomain.CapabilityChat, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo:
|
||||
case modeldomain.CapabilityResponses, modeldomain.CapabilityChat, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo, modeldomain.CapabilityTTS, modeldomain.CapabilitySTT, modeldomain.CapabilityRealtime:
|
||||
default:
|
||||
return fmt.Errorf("Provider %s 声明了无效模型能力 %q", d.Provider, capability)
|
||||
}
|
||||
@@ -163,6 +166,9 @@ func (d Definition) Validate() error {
|
||||
{enabled: d.Media.ImageGeneration, capability: modeldomain.CapabilityImage, name: "图像生成"},
|
||||
{enabled: d.Media.ImageEdit, capability: modeldomain.CapabilityImageEdit, name: "图像编辑"},
|
||||
{enabled: d.Media.VideoGeneration, capability: modeldomain.CapabilityVideo, name: "视频生成"},
|
||||
{enabled: d.Media.TTS, capability: modeldomain.CapabilityTTS, name: "语音合成"},
|
||||
{enabled: d.Media.STT, capability: modeldomain.CapabilitySTT, name: "语音识别"},
|
||||
{enabled: d.Media.Realtime, capability: modeldomain.CapabilityRealtime, name: "实时语音"},
|
||||
}
|
||||
for _, item := range mediaCapabilities {
|
||||
_, declared := capabilities[item.capability]
|
||||
|
||||
@@ -62,10 +62,10 @@ func TestProductionProviderDefinitionsMatchImplementedCapabilities(t *testing.T)
|
||||
},
|
||||
{
|
||||
provider: account.ProviderConsole, catalog: provider.ModelCatalogStatic, quota: provider.QuotaRemoteWindow,
|
||||
capabilities: []modeldomain.Capability{modeldomain.CapabilityResponses, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo},
|
||||
capabilities: []modeldomain.Capability{modeldomain.CapabilityResponses, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo, modeldomain.CapabilityTTS, modeldomain.CapabilitySTT, modeldomain.CapabilityRealtime},
|
||||
credential: provider.CredentialSurface{AuthType: account.AuthTypeSSO, Import: true},
|
||||
conversation: provider.ConversationSurface{Responses: true, ChatCompletions: true, Messages: true},
|
||||
media: provider.MediaSurface{ImageGeneration: true, ImageEdit: true, VideoGeneration: true},
|
||||
media: provider.MediaSurface{ImageGeneration: true, ImageEdit: true, VideoGeneration: true, TTS: true, STT: true, Realtime: true},
|
||||
inference: provider.InferencePolicy{Usage: provider.UsageUpstream, RetryForbiddenAsEgress: true},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -30,6 +30,29 @@ type HTTPStatusError interface {
|
||||
HTTPStatusCode() int
|
||||
}
|
||||
|
||||
// RetryAfterError preserves a safe upstream retry delay when an adapter cannot
|
||||
// return a Response, for example when a WebSocket handshake is rejected.
|
||||
type RetryAfterError interface {
|
||||
error
|
||||
RetryAfterDuration() time.Duration
|
||||
}
|
||||
|
||||
// RequestScopedError marks an upstream rejection that retrying with another
|
||||
// account or egress cannot resolve.
|
||||
type RequestScopedError interface {
|
||||
error
|
||||
RequestScopedFailure() bool
|
||||
}
|
||||
|
||||
// PublicMessageError exposes a deliberately sanitized message that may cross
|
||||
// the public API boundary. Provider errors must opt in; arbitrary Error()
|
||||
// strings can contain upstream response bodies, tokens, cookies, or request
|
||||
// diagnostics and therefore are never returned to clients by default.
|
||||
type PublicMessageError interface {
|
||||
error
|
||||
PublicErrorMessage() string
|
||||
}
|
||||
|
||||
// ErrorHTTPStatus extracts the upstream HTTP status from a Provider error chain.
|
||||
func ErrorHTTPStatus(err error) (int, bool) {
|
||||
var statusError HTTPStatusError
|
||||
@@ -40,6 +63,33 @@ func ErrorHTTPStatus(err error) (int, bool) {
|
||||
return status, status > 0
|
||||
}
|
||||
|
||||
// ErrorRetryAfter extracts a positive retry delay from an error chain.
|
||||
func ErrorRetryAfter(err error) time.Duration {
|
||||
var retryError RetryAfterError
|
||||
if !errors.As(err, &retryError) {
|
||||
return 0
|
||||
}
|
||||
return max(0, retryError.RetryAfterDuration())
|
||||
}
|
||||
|
||||
// IsRequestScopedError reports whether the Provider has positively classified
|
||||
// the failure as request-scoped.
|
||||
func IsRequestScopedError(err error) bool {
|
||||
var requestError RequestScopedError
|
||||
return errors.As(err, &requestError) && requestError.RequestScopedFailure()
|
||||
}
|
||||
|
||||
// ErrorPublicMessage extracts a message that the Provider has explicitly
|
||||
// classified as safe for clients.
|
||||
func ErrorPublicMessage(err error) (string, bool) {
|
||||
var publicError PublicMessageError
|
||||
if !errors.As(err, &publicError) {
|
||||
return "", false
|
||||
}
|
||||
message := strings.TrimSpace(publicError.PublicErrorMessage())
|
||||
return message, message != ""
|
||||
}
|
||||
|
||||
// MediaPostProcessingStage identifies a local processing stage that failed after media generation.
|
||||
type MediaPostProcessingStage string
|
||||
|
||||
@@ -240,6 +290,17 @@ type QuotaSnapshot struct {
|
||||
SyncedAt time.Time
|
||||
}
|
||||
|
||||
// QuotaGroupSnapshot is an authoritative snapshot for a group of quota modes
|
||||
// returned by one upstream request. Modes lists the complete local scope so
|
||||
// callers can atomically remove products that the upstream explicitly reports
|
||||
// as unavailable without touching unrelated quota windows.
|
||||
type QuotaGroupSnapshot struct {
|
||||
Group string
|
||||
Modes []string
|
||||
Windows []account.QuotaWindow
|
||||
SyncedAt time.Time
|
||||
}
|
||||
|
||||
type ImageGenerationRequest struct {
|
||||
Credential account.Credential
|
||||
Model string
|
||||
@@ -248,6 +309,7 @@ type ImageGenerationRequest struct {
|
||||
Size string
|
||||
AspectRatio string
|
||||
Resolution string
|
||||
Quality string
|
||||
ResponseFormat string
|
||||
Streaming bool
|
||||
PartialImages int
|
||||
@@ -268,23 +330,47 @@ type ImageEditRequest struct {
|
||||
Size string
|
||||
AspectRatio string
|
||||
Resolution string
|
||||
Quality string
|
||||
ResponseFormat string
|
||||
Streaming bool
|
||||
PartialImages int
|
||||
}
|
||||
|
||||
// VideoOperation selects the official xAI video endpoint family.
|
||||
type VideoOperation = media.VideoOperation
|
||||
|
||||
const (
|
||||
VideoOperationGenerate = media.VideoOperationGenerate
|
||||
VideoOperationEdit = media.VideoOperationEdit
|
||||
VideoOperationExtend = media.VideoOperationExtend
|
||||
)
|
||||
|
||||
type VideoRequest struct {
|
||||
Credential account.Credential
|
||||
// Billing is used only to determine XAI eligibility in Build auto mode; nil means the account tier is unknown.
|
||||
Billing *account.Billing
|
||||
// JobID binds the local video job to XAI ZDR upload tickets and result assets.
|
||||
JobID string
|
||||
Prompt string
|
||||
Duration int
|
||||
AspectRatio string
|
||||
Resolution string
|
||||
JobID string
|
||||
// Model is the selected upstream video model when the Provider supports more than one.
|
||||
Model string
|
||||
// Operation defaults to generate when empty.
|
||||
Operation VideoOperation
|
||||
Prompt string
|
||||
Duration int
|
||||
AspectRatio string
|
||||
Resolution string
|
||||
// ImageURL is the optional first-frame image (official "image" field).
|
||||
ImageURL string
|
||||
// ReferenceURLs are style/content references (official "reference_images").
|
||||
// A single reference must stay in reference_images and must not be coerced to image.
|
||||
// Official docs forbid combining image with reference_images.
|
||||
ReferenceURLs []string
|
||||
Progress func(int)
|
||||
// ReferenceAudios are preset voice_ids for reference-to-video (official "reference_audios").
|
||||
// At most 3 entries; may be used alone or with reference_images.
|
||||
ReferenceAudios []string
|
||||
// VideoURL is required for edit/extend (official "video" field).
|
||||
VideoURL string
|
||||
Progress func(int)
|
||||
}
|
||||
|
||||
type VideoResult struct {
|
||||
@@ -294,6 +380,91 @@ type VideoResult struct {
|
||||
AssetID string
|
||||
}
|
||||
|
||||
type TTSOutputFormat struct {
|
||||
Codec string
|
||||
SampleRate int
|
||||
BitRate int
|
||||
}
|
||||
|
||||
type TTSRequest struct {
|
||||
Credential account.Credential
|
||||
Model string
|
||||
Text string
|
||||
VoiceID string
|
||||
Language string
|
||||
OutputFormat TTSOutputFormat
|
||||
Speed float64
|
||||
OptimizeStreamingLatency int
|
||||
TextNormalization bool
|
||||
WithTimestamps bool
|
||||
}
|
||||
|
||||
type TTSTimestampSpan struct {
|
||||
Start float64
|
||||
End float64
|
||||
}
|
||||
|
||||
type TTSTimestamps struct {
|
||||
GraphChars []string
|
||||
GraphTimes []TTSTimestampSpan
|
||||
}
|
||||
|
||||
type TTSResult struct {
|
||||
Audio []byte
|
||||
ContentType string
|
||||
Duration float64
|
||||
Base64Audio string
|
||||
Timestamps *TTSTimestamps
|
||||
JSONEnvelope bool
|
||||
}
|
||||
|
||||
type STTRequest struct {
|
||||
Credential account.Credential
|
||||
Model string
|
||||
FileName string
|
||||
FileMIME string
|
||||
FileData []byte
|
||||
URL string
|
||||
AudioFormat string
|
||||
SampleRate string
|
||||
Language string
|
||||
Format bool
|
||||
Multichannel bool
|
||||
Channels int
|
||||
Diarize bool
|
||||
KeyTerms []string
|
||||
FillerWords bool
|
||||
VADThreshold *float64
|
||||
}
|
||||
|
||||
type STTWord struct {
|
||||
Text string
|
||||
Start float64
|
||||
End float64
|
||||
Speaker *int
|
||||
}
|
||||
|
||||
type STTChannel struct {
|
||||
Index int
|
||||
Text string
|
||||
Words []STTWord
|
||||
}
|
||||
|
||||
type STTResult struct {
|
||||
Text string
|
||||
Language string
|
||||
Duration float64
|
||||
Words []STTWord
|
||||
Channels []STTChannel
|
||||
RawJSON []byte
|
||||
}
|
||||
|
||||
type VoiceInfo struct {
|
||||
VoiceID string
|
||||
Name string
|
||||
Language string
|
||||
}
|
||||
|
||||
// RefreshedCredential represents rotated credentials returned by an OAuth refresh.
|
||||
type RefreshedCredential struct {
|
||||
EncryptedAccessToken string
|
||||
@@ -387,6 +558,20 @@ type QuotaAdapter interface {
|
||||
SyncQuotaMode(ctx context.Context, credential account.Credential, mode string) (account.QuotaWindow, error)
|
||||
}
|
||||
|
||||
// QuotaGroupAdapter is optional. It is used when one upstream endpoint returns
|
||||
// several related quota products as one authoritative response.
|
||||
type QuotaGroupAdapter interface {
|
||||
Adapter
|
||||
SyncQuotaGroup(ctx context.Context, credential account.Credential, group string) (QuotaGroupSnapshot, error)
|
||||
}
|
||||
|
||||
// QuotaRefreshMetadataAdapter maps a model to an internal refresh group. The
|
||||
// group is scheduling metadata, not a routable quota mode.
|
||||
type QuotaRefreshMetadataAdapter interface {
|
||||
Adapter
|
||||
QuotaRefreshGroup(upstreamModel string) string
|
||||
}
|
||||
|
||||
// WebAccountSettingsAdapter defines upstream profile-setting capabilities for Grok Web SSO accounts.
|
||||
// This capability belongs only to the Web Provider; Build and Console must not emulate it through generic account logic.
|
||||
type WebAccountSettingsAdapter interface {
|
||||
@@ -426,6 +611,42 @@ type VideoContentDownloader interface {
|
||||
DownloadVideo(ctx context.Context, credential account.Credential, rawURL string) (io.ReadCloser, string, int64, error)
|
||||
}
|
||||
|
||||
// TTSAdapter synthesizes speech audio for text prompts.
|
||||
type TTSAdapter interface {
|
||||
Adapter
|
||||
SynthesizeSpeech(ctx context.Context, request TTSRequest) (TTSResult, error)
|
||||
ListTTSVoices(ctx context.Context, credential account.Credential) ([]VoiceInfo, error)
|
||||
GetTTSVoice(ctx context.Context, credential account.Credential, voiceID string) (VoiceInfo, error)
|
||||
}
|
||||
|
||||
// STTAdapter transcribes audio into text.
|
||||
type STTAdapter interface {
|
||||
Adapter
|
||||
TranscribeSpeech(ctx context.Context, request STTRequest) (STTResult, error)
|
||||
}
|
||||
|
||||
// VoiceWebSocketConn is a minimal duplex websocket used by voice streaming proxies.
|
||||
type VoiceWebSocketConn interface {
|
||||
ReadMessage() (messageType int, data []byte, err error)
|
||||
WriteMessage(messageType int, data []byte) error
|
||||
SetReadLimit(limit int64)
|
||||
Close() error
|
||||
}
|
||||
|
||||
// VoiceWebSocketRequest dials an upstream voice websocket with provider auth.
|
||||
type VoiceWebSocketRequest struct {
|
||||
Credential account.Credential
|
||||
// Path is a v1-relative path such as /realtime or /stt.
|
||||
Path string
|
||||
Model string
|
||||
}
|
||||
|
||||
// VoiceWebSocketAdapter dials official voice websocket endpoints with account auth.
|
||||
type VoiceWebSocketAdapter interface {
|
||||
Adapter
|
||||
DialVoiceWebSocket(ctx context.Context, request VoiceWebSocketRequest) (VoiceWebSocketConn, func(), error)
|
||||
}
|
||||
|
||||
type RoutingMetadataAdapter interface {
|
||||
Adapter
|
||||
QuotaMode(upstreamModel string) string
|
||||
@@ -607,6 +828,21 @@ func (r *Registry) Validate() error {
|
||||
return fmt.Errorf("Provider %s 声明视频能力但未实现适配器", value)
|
||||
}
|
||||
}
|
||||
if definition.Media.TTS {
|
||||
if _, ok := adapter.(TTSAdapter); !ok {
|
||||
return fmt.Errorf("Provider %s 声明语音合成能力但未实现适配器", value)
|
||||
}
|
||||
}
|
||||
if definition.Media.STT {
|
||||
if _, ok := adapter.(STTAdapter); !ok {
|
||||
return fmt.Errorf("Provider %s 声明语音识别能力但未实现适配器", value)
|
||||
}
|
||||
}
|
||||
if definition.Media.Realtime {
|
||||
if _, ok := adapter.(VoiceWebSocketAdapter); !ok {
|
||||
return fmt.Errorf("Provider %s 声明实时语音能力但未实现 WebSocket 适配器", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -749,6 +985,15 @@ func (r *Registry) Quota(value account.Provider) (QuotaAdapter, bool) {
|
||||
return result, ok
|
||||
}
|
||||
|
||||
func (r *Registry) QuotaGroup(value account.Provider) (QuotaGroupAdapter, bool) {
|
||||
adapter, ok := r.Get(value)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
result, ok := adapter.(QuotaGroupAdapter)
|
||||
return result, ok
|
||||
}
|
||||
|
||||
// WebAccountSettings returns the Grok Web-specific account profile settings capability.
|
||||
func (r *Registry) WebAccountSettings() (WebAccountSettingsAdapter, bool) {
|
||||
adapter, ok := r.Get(account.ProviderWeb)
|
||||
@@ -771,6 +1016,18 @@ func (r *Registry) QuotaMode(value account.Provider, upstreamModel string) strin
|
||||
return metadata.QuotaMode(upstreamModel)
|
||||
}
|
||||
|
||||
func (r *Registry) QuotaRefreshGroup(value account.Provider, upstreamModel string) string {
|
||||
adapter, ok := r.Get(value)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
metadata, ok := adapter.(QuotaRefreshMetadataAdapter)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return metadata.QuotaRefreshGroup(upstreamModel)
|
||||
}
|
||||
|
||||
func (r *Registry) TierOrder(value account.Provider, upstreamModel string) []account.WebTier {
|
||||
adapter, ok := r.Get(value)
|
||||
if !ok {
|
||||
@@ -827,6 +1084,33 @@ func (r *Registry) Videos(value account.Provider) (VideoAdapter, bool) {
|
||||
return result, ok
|
||||
}
|
||||
|
||||
func (r *Registry) TTS(value account.Provider) (TTSAdapter, bool) {
|
||||
adapter, ok := r.Get(value)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
result, ok := adapter.(TTSAdapter)
|
||||
return result, ok
|
||||
}
|
||||
|
||||
func (r *Registry) STT(value account.Provider) (STTAdapter, bool) {
|
||||
adapter, ok := r.Get(value)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
result, ok := adapter.(STTAdapter)
|
||||
return result, ok
|
||||
}
|
||||
|
||||
func (r *Registry) VoiceWebSocket(value account.Provider) (VoiceWebSocketAdapter, bool) {
|
||||
adapter, ok := r.Get(value)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
result, ok := adapter.(VoiceWebSocketAdapter)
|
||||
return result, ok
|
||||
}
|
||||
|
||||
// CredentialRejection 表示上游响应或错误是否构成「凭据被拒」的稳定判定。
|
||||
// 与网关 UpstreamFailure 的 CredentialRejected / PermanentAccountDenial / SpendingLimitBlocked 分类保持一致,
|
||||
// 供 account.Service 等非网关路径复用同一套失效收敛语义。
|
||||
|
||||
@@ -115,6 +115,13 @@ func (a *Adapter) QuotaMode(upstreamModel string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (a *Adapter) QuotaRefreshGroup(upstreamModel string) string {
|
||||
if spec, ok := Resolve(upstreamModel); ok && account.IsWebImagineQuotaMode(spec.Mode) {
|
||||
return account.QuotaGroupWebImagine
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (a *Adapter) TierOrder(upstreamModel string) []account.WebTier {
|
||||
spec, ok := Resolve(upstreamModel)
|
||||
if !ok {
|
||||
@@ -136,11 +143,15 @@ func (a *Adapter) PricingModel(upstreamModel string) string {
|
||||
if spec.Capability == modeldomain.CapabilityChat {
|
||||
return "grok-4.5"
|
||||
}
|
||||
// Public Web image names carry the -lite suffix to distinguish them from
|
||||
// Public Web image names use the -2.0 suffix to distinguish them from
|
||||
// Console routes. Billing continues to use the upstream xAI model name.
|
||||
if spec.Capability == modeldomain.CapabilityImage {
|
||||
return spec.UpstreamModel
|
||||
}
|
||||
// Dedicated Web edit upstream keeps a stable billing name.
|
||||
if spec.Capability == modeldomain.CapabilityImageEdit {
|
||||
return "grok-imagine-image-edit"
|
||||
}
|
||||
return spec.PublicID
|
||||
}
|
||||
return upstreamModel
|
||||
|
||||
@@ -19,10 +19,13 @@ var catalog = []ModelSpec{
|
||||
{PublicID: "grok-chat-auto", UpstreamModel: "grok-chat-auto", Capability: modeldomain.CapabilityChat, Mode: "auto", MinimumTier: account.WebTierSuper},
|
||||
{PublicID: "grok-chat-expert", UpstreamModel: "grok-chat-expert", Capability: modeldomain.CapabilityChat, Mode: "expert", MinimumTier: account.WebTierSuper},
|
||||
{PublicID: "grok-chat-heavy", UpstreamModel: "grok-chat-heavy", Capability: modeldomain.CapabilityChat, Mode: "heavy", MinimumTier: account.WebTierHeavy},
|
||||
// Web generation is exposed with a -lite suffix so it remains visibly
|
||||
// distinct from the Console resource API. Image editing is a separate
|
||||
// Super-only upstream model and must not be advertised on Basic routes.
|
||||
{PublicID: "grok-imagine-image-lite", UpstreamModel: "grok-imagine-image", ProtocolModel: "imagine-lite", Capability: modeldomain.CapabilityImage, Mode: "fast", MinimumTier: account.WebTierBasic},
|
||||
{PublicID: "grok-imagine-image-quality-lite", UpstreamModel: "grok-imagine-image-quality", ProtocolModel: "imagine", Capability: modeldomain.CapabilityImage, MinimumTier: account.WebTierSuper},
|
||||
{PublicID: "grok-imagine-image-edit", UpstreamModel: "imagine-image-edit", Capability: modeldomain.CapabilityImageEdit, MinimumTier: account.WebTierSuper},
|
||||
{PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", ProtocolModel: "imagine-video-gen", Capability: modeldomain.CapabilityVideo, MinimumTier: account.WebTierSuper},
|
||||
{PublicID: "grok-imagine-image-quality-lite", UpstreamModel: "grok-imagine-image-quality", ProtocolModel: "imagine", Capability: modeldomain.CapabilityImage, Mode: "image_pro", MinimumTier: account.WebTierBasic},
|
||||
{PublicID: "grok-imagine-image-edit", UpstreamModel: "imagine-image-edit", Capability: modeldomain.CapabilityImageEdit, Mode: "image_edit", MinimumTier: account.WebTierSuper},
|
||||
{PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", ProtocolModel: "imagine-video-gen", Capability: modeldomain.CapabilityVideo, Mode: "video", MinimumTier: account.WebTierSuper},
|
||||
}
|
||||
|
||||
func Catalog() []ModelSpec { return append([]ModelSpec(nil), catalog...) }
|
||||
|
||||
@@ -274,6 +274,9 @@ func numberAsInt(value any) (int, bool) {
|
||||
}
|
||||
|
||||
func (a *Adapter) GenerateImage(ctx context.Context, request provider.ImageGenerationRequest) (*provider.Response, error) {
|
||||
if strings.TrimSpace(request.Quality) != "" {
|
||||
return invalidImageRequest("Grok Web 图片模型不支持 quality")
|
||||
}
|
||||
count := request.Count
|
||||
if count <= 0 {
|
||||
count = 1
|
||||
@@ -675,6 +678,9 @@ func (a *Adapter) generateWSImage(ctx context.Context, request provider.ImageGen
|
||||
}
|
||||
|
||||
func (a *Adapter) EditImage(ctx context.Context, request provider.ImageEditRequest) (*provider.Response, error) {
|
||||
if strings.TrimSpace(request.Quality) != "" {
|
||||
return invalidImageRequest("Grok Web 图片模型不支持 quality")
|
||||
}
|
||||
if len(request.ImageURLs) == 0 || len(request.ImageURLs) > 8 {
|
||||
return jsonProviderResponse(http.StatusBadRequest, map[string]any{"error": map[string]any{"message": "image 数量必须在 1 到 8 之间", "type": "invalid_request_error"}}), nil
|
||||
}
|
||||
|
||||
@@ -37,34 +37,42 @@ import (
|
||||
|
||||
func TestCatalogMatchesSupportedSurface(t *testing.T) {
|
||||
values := Catalog()
|
||||
if len(values) != 8 {
|
||||
requiredModels := []string{"grok-chat-fast", "grok-chat-auto", "grok-chat-expert", "grok-chat-heavy", "grok-imagine-image-lite", "grok-imagine-image-quality-lite", "grok-imagine-image-edit", "grok-imagine-video"}
|
||||
if len(values) != len(requiredModels) {
|
||||
t.Fatalf("catalog size = %d", len(values))
|
||||
}
|
||||
publicIDs := make(map[string]struct{}, len(values))
|
||||
upstreamIDs := make(map[string]struct{}, len(values))
|
||||
routeKeys := make(map[string]struct{}, len(values))
|
||||
for _, value := range values {
|
||||
if _, exists := publicIDs[value.PublicID]; exists {
|
||||
t.Fatalf("duplicate public model: %s", value.PublicID)
|
||||
}
|
||||
if _, exists := upstreamIDs[value.UpstreamModel]; exists {
|
||||
t.Fatalf("duplicate route upstream model: %s", value.UpstreamModel)
|
||||
routeKey := value.PublicID + "|" + string(value.Capability)
|
||||
if _, exists := routeKeys[routeKey]; exists {
|
||||
t.Fatalf("duplicate public model capability: %s", routeKey)
|
||||
}
|
||||
routeKeys[routeKey] = struct{}{}
|
||||
publicIDs[value.PublicID] = struct{}{}
|
||||
upstreamIDs[value.UpstreamModel] = struct{}{}
|
||||
}
|
||||
for _, required := range []string{"grok-chat-fast", "grok-chat-auto", "grok-chat-expert", "grok-chat-heavy", "grok-imagine-image-lite", "grok-imagine-image-quality-lite", "grok-imagine-image-edit", "grok-imagine-video"} {
|
||||
for _, required := range requiredModels {
|
||||
if _, exists := publicIDs[required]; !exists {
|
||||
t.Fatalf("missing supported model: %s", required)
|
||||
}
|
||||
}
|
||||
for _, removed := range []string{"grok-imagine-image", "grok-imagine-image-quality", "grok-imagine-image-speed", "grok-imagine-image-pro"} {
|
||||
for _, required := range []string{
|
||||
"grok-imagine-image-lite|image",
|
||||
"grok-imagine-image-quality-lite|image",
|
||||
"grok-imagine-image-edit|image_edit",
|
||||
} {
|
||||
if _, exists := routeKeys[required]; !exists {
|
||||
t.Fatalf("missing supported route: %s", required)
|
||||
}
|
||||
}
|
||||
for _, removed := range []string{"grok-imagine-image", "grok-imagine-image-quality", "grok-imagine-image-2.0", "grok-imagine-image-quality-2.0", "grok-imagine-image-speed", "grok-imagine-image-pro"} {
|
||||
if _, exists := publicIDs[removed]; exists {
|
||||
t.Fatalf("obsolete image model remains: %s", removed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebImageLitePublicNamesPreserveGatewayModels(t *testing.T) {
|
||||
func TestWebImagePublicNamesPreserveGatewayModels(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"grok-imagine-image": "grok-imagine-image-lite",
|
||||
"grok-imagine-image-quality": "grok-imagine-image-quality-lite",
|
||||
@@ -74,10 +82,14 @@ func TestWebImageLitePublicNamesPreserveGatewayModels(t *testing.T) {
|
||||
if !ok {
|
||||
t.Fatalf("missing upstream model %s", upstreamModel)
|
||||
}
|
||||
if spec.PublicID != publicID || spec.UpstreamModel != upstreamModel {
|
||||
if spec.PublicID != publicID || spec.UpstreamModel != upstreamModel || spec.Capability != modeldomain.CapabilityImage {
|
||||
t.Fatalf("resolved %s as %#v", upstreamModel, spec)
|
||||
}
|
||||
}
|
||||
spec, ok := Resolve("imagine-image-edit")
|
||||
if !ok || spec.PublicID != "grok-imagine-image-edit" || spec.Capability != modeldomain.CapabilityImageEdit {
|
||||
t.Fatalf("edit upstream resolved as %#v ok=%v", spec, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMediaPostResponsePreservesStatusAndPostID(t *testing.T) {
|
||||
@@ -1014,7 +1026,7 @@ func TestWebMediaUpstreamDiagnosticLogsStageHeadersWithoutBodyPreview(t *testing
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatModelsUseLowestSufficientTierFirst(t *testing.T) {
|
||||
func TestModelsUseLowestSufficientTierFirst(t *testing.T) {
|
||||
adapter := &Adapter{}
|
||||
tests := []struct {
|
||||
model string
|
||||
@@ -1024,6 +1036,10 @@ func TestChatModelsUseLowestSufficientTierFirst(t *testing.T) {
|
||||
{model: "grok-chat-auto", want: []account.WebTier{account.WebTierSuper, account.WebTierHeavy}},
|
||||
{model: "grok-chat-expert", want: []account.WebTier{account.WebTierSuper, account.WebTierHeavy}},
|
||||
{model: "grok-chat-heavy", want: []account.WebTier{account.WebTierHeavy}},
|
||||
{model: "grok-imagine-image", want: []account.WebTier{account.WebTierBasic, account.WebTierSuper, account.WebTierHeavy}},
|
||||
{model: "grok-imagine-image-quality", want: []account.WebTier{account.WebTierBasic, account.WebTierSuper, account.WebTierHeavy}},
|
||||
{model: "imagine-image-edit", want: []account.WebTier{account.WebTierSuper, account.WebTierHeavy}},
|
||||
{model: "grok-imagine-video", want: []account.WebTier{account.WebTierSuper, account.WebTierHeavy}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
got := adapter.TierOrder(test.model)
|
||||
@@ -1047,12 +1063,27 @@ func TestOnlyChatModelsExposeRateLimitModes(t *testing.T) {
|
||||
}
|
||||
continue
|
||||
}
|
||||
if isImagineQuotaMode(spec.Mode) {
|
||||
continue
|
||||
}
|
||||
if spec.Mode != "" {
|
||||
t.Fatalf("media model %s must not expose chat quota mode %q", spec.PublicID, spec.Mode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaRefreshGroupSeparatesImagineEndpointFromLiteChatQuota(t *testing.T) {
|
||||
adapter := &Adapter{}
|
||||
if got := adapter.QuotaRefreshGroup("grok-imagine-image"); got != "" {
|
||||
t.Fatalf("lite refresh group = %q", got)
|
||||
}
|
||||
for _, model := range []string{"grok-imagine-image-quality", "imagine-image-edit", "grok-imagine-video"} {
|
||||
if got := adapter.QuotaRefreshGroup(model); got != account.QuotaGroupWebImagine {
|
||||
t.Fatalf("QuotaRefreshGroup(%q) = %q", model, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsumeUpstreamChatFixture(t *testing.T) {
|
||||
fixture := strings.Join([]string{
|
||||
`data: {"result":{"conversation":{"conversationId":"conv_1"}}}`,
|
||||
|
||||
@@ -21,37 +21,53 @@ import (
|
||||
const weeklyQuotaMode = "weekly"
|
||||
|
||||
func (a *Adapter) SyncQuota(ctx context.Context, credential account.Credential) (provider.QuotaSnapshot, error) {
|
||||
windows := make([]account.QuotaWindow, 0, 2)
|
||||
chatWindows := make([]account.QuotaWindow, 0, 2)
|
||||
autoWindow, autoErr := a.SyncQuotaMode(ctx, credential, "auto")
|
||||
if errors.Is(autoErr, provider.ErrUnauthorized) {
|
||||
return provider.QuotaSnapshot{}, autoErr
|
||||
}
|
||||
if autoErr == nil {
|
||||
windows = append(windows, autoWindow)
|
||||
chatWindows = append(chatWindows, autoWindow)
|
||||
}
|
||||
fastWindow, fastErr := a.SyncQuotaMode(ctx, credential, "fast")
|
||||
if errors.Is(fastErr, provider.ErrUnauthorized) {
|
||||
return provider.QuotaSnapshot{}, fastErr
|
||||
}
|
||||
if fastErr == nil {
|
||||
windows = append(windows, fastWindow)
|
||||
chatWindows = append(chatWindows, fastWindow)
|
||||
}
|
||||
if len(windows) > 0 {
|
||||
tier, _ := resolveWebTierFromQuota(credential.WebTier, windows, false)
|
||||
imagineSnapshot, imagineErr := a.SyncQuotaGroup(ctx, credential, account.QuotaGroupWebImagine)
|
||||
if imagineErr != nil {
|
||||
// A full refresh replaces every stored window. Never return a partial
|
||||
// snapshot, otherwise a transient Imagine failure would erase the last
|
||||
// known authoritative media quotas.
|
||||
return provider.QuotaSnapshot{}, imagineErr
|
||||
}
|
||||
if len(chatWindows) > 0 {
|
||||
tier, _ := resolveWebTierFromQuota(credential.WebTier, chatWindows, false)
|
||||
var windows []account.QuotaWindow
|
||||
// Basic/未知账号没有付费周池,避免为每次完整同步额外访问付费端点。
|
||||
// 只有模式额度已经确认付费等级时才读取 weekly 作为权威额度。
|
||||
if tier == account.WebTierSuper || tier == account.WebTierHeavy {
|
||||
if weekly, weeklyErr := a.syncWeeklyCredits(ctx, credential); weeklyErr == nil {
|
||||
windows = []account.QuotaWindow{weekly}
|
||||
// 周池覆盖 chat 模式窗口,但保留 imagine 窗口供前端展示与触顶判定。
|
||||
kept := make([]account.QuotaWindow, 0, 1+len(imagineSnapshot.Windows))
|
||||
kept = append(kept, weekly)
|
||||
kept = append(kept, imagineSnapshot.Windows...)
|
||||
windows = kept
|
||||
}
|
||||
}
|
||||
if windows == nil {
|
||||
windows = append(chatWindows, imagineSnapshot.Windows...)
|
||||
}
|
||||
return provider.QuotaSnapshot{Tier: tier, Windows: windows, SyncedAt: time.Now().UTC()}, nil
|
||||
}
|
||||
// 模式端点暂不可用时,仅已确认的付费账号允许用 weekly 兜底;
|
||||
// Basic/Auto 不能凭周额度探测提权,也不应制造无意义的付费端点流量。
|
||||
if credential.WebTier == account.WebTierSuper || credential.WebTier == account.WebTierHeavy {
|
||||
if weekly, weeklyErr := a.syncWeeklyCredits(ctx, credential); weeklyErr == nil {
|
||||
return provider.QuotaSnapshot{Tier: credential.WebTier, Windows: []account.QuotaWindow{weekly}, SyncedAt: time.Now().UTC()}, nil
|
||||
kept := append([]account.QuotaWindow{weekly}, imagineSnapshot.Windows...)
|
||||
return provider.QuotaSnapshot{Tier: credential.WebTier, Windows: kept, SyncedAt: time.Now().UTC()}, nil
|
||||
} else {
|
||||
return provider.QuotaSnapshot{}, weeklyErr
|
||||
}
|
||||
@@ -62,6 +78,141 @@ func (a *Adapter) SyncQuota(ctx context.Context, credential account.Credential)
|
||||
return provider.QuotaSnapshot{}, autoErr
|
||||
}
|
||||
|
||||
// SyncQuotaGroup refreshes the authoritative Web Imagine quota group. The
|
||||
// upstream endpoint returns every media product in one response, so callers
|
||||
// must persist the snapshot atomically instead of treating its fields as four
|
||||
// independent requests.
|
||||
func (a *Adapter) SyncQuotaGroup(ctx context.Context, credential account.Credential, group string) (provider.QuotaGroupSnapshot, error) {
|
||||
if group != account.QuotaGroupWebImagine {
|
||||
return provider.QuotaGroupSnapshot{}, fmt.Errorf("unsupported Web quota group %q", group)
|
||||
}
|
||||
cfg := a.config()
|
||||
token, err := a.cipher.Decrypt(credential.EncryptedAccessToken)
|
||||
if err != nil {
|
||||
return provider.QuotaGroupSnapshot{}, err
|
||||
}
|
||||
lease, err := a.egress.AcquireCredential(ctx, domainegress.ScopeWeb, credential)
|
||||
if err != nil {
|
||||
return provider.QuotaGroupSnapshot{}, err
|
||||
}
|
||||
defer lease.Release()
|
||||
endpoint := cfg.BaseURL + "/rest/media/imagine/quota_info"
|
||||
requestCtx, cancel := context.WithTimeout(ctx, time.Duration(cfg.QuotaTimeoutSeconds)*time.Second)
|
||||
defer cancel()
|
||||
request, err := http.NewRequestWithContext(requestCtx, http.MethodPost, endpoint, bytes.NewReader([]byte("{}")))
|
||||
if err != nil {
|
||||
return provider.QuotaGroupSnapshot{}, err
|
||||
}
|
||||
request.Header = buildHeaders(token, lease, "application/json")
|
||||
applyAppHeaders(request.Header, cfg.BaseURL, cfg.BaseURL+"/imagine")
|
||||
a.applySignedStatsig(requestCtx, request, token, lease)
|
||||
response, err := lease.DoDeferredForbidden(request)
|
||||
if err != nil {
|
||||
a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, err)
|
||||
return provider.QuotaGroupSnapshot{}, err
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(response.Body, 4<<20))
|
||||
_ = response.Body.Close()
|
||||
if err != nil {
|
||||
return provider.QuotaGroupSnapshot{}, err
|
||||
}
|
||||
if response.StatusCode == http.StatusUnauthorized {
|
||||
return provider.QuotaGroupSnapshot{}, provider.ErrUnauthorized
|
||||
}
|
||||
if response.StatusCode == http.StatusForbidden && provider.IsDefinitiveAccountBlockBody(body) {
|
||||
return provider.QuotaGroupSnapshot{}, fmt.Errorf("%w: account blocked", provider.ErrUnauthorized)
|
||||
}
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, response.StatusCode, nil)
|
||||
return provider.QuotaGroupSnapshot{}, fmt.Errorf("Grok Web Imagine 配额接口返回 %d", response.StatusCode)
|
||||
}
|
||||
a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, response.StatusCode, nil)
|
||||
now := time.Now().UTC()
|
||||
windows, err := decodeImagineQuotaSnapshot(body, credential.ID, now)
|
||||
if err != nil {
|
||||
return provider.QuotaGroupSnapshot{}, err
|
||||
}
|
||||
return provider.QuotaGroupSnapshot{
|
||||
Group: account.QuotaGroupWebImagine, Modes: account.WebImagineQuotaModes(), Windows: windows, SyncedAt: now,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type imagineQuotaProduct struct {
|
||||
Available *bool `json:"available"`
|
||||
RemainingQueries *int `json:"remainingQueries"`
|
||||
WindowSizeSeconds *int `json:"windowSizeSeconds"`
|
||||
NextAvailableAt *time.Time `json:"nextAvailableAt"`
|
||||
}
|
||||
|
||||
func isImagineQuotaMode(mode string) bool {
|
||||
return account.IsWebImagineQuotaMode(mode)
|
||||
}
|
||||
|
||||
func decodeImagineQuotaSnapshot(body []byte, accountID uint64, now time.Time) ([]account.QuotaWindow, error) {
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(body, &fields); err != nil {
|
||||
return nil, fmt.Errorf("解析 Grok Web Imagine 配额: %w", err)
|
||||
}
|
||||
products := []struct {
|
||||
field string
|
||||
mode string
|
||||
}{
|
||||
{"image", ""}, // lite uses the chat fast/weekly quota path.
|
||||
{"imagePro", account.QuotaModeWebImagePro},
|
||||
{"imageEdit", account.QuotaModeWebImageEdit},
|
||||
{"video", account.QuotaModeWebVideo},
|
||||
{"video720p", account.QuotaModeWebVideo720p},
|
||||
}
|
||||
windows := make([]account.QuotaWindow, 0, 4)
|
||||
for _, item := range products {
|
||||
raw, ok := fields[item.field]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Grok Web Imagine 配额响应缺少字段 %s", item.field)
|
||||
}
|
||||
if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
|
||||
continue
|
||||
}
|
||||
var product imagineQuotaProduct
|
||||
if err := json.Unmarshal(raw, &product); err != nil {
|
||||
return nil, fmt.Errorf("解析 Grok Web Imagine 配额字段 %s: %w", item.field, err)
|
||||
}
|
||||
if product.Available == nil {
|
||||
return nil, fmt.Errorf("Grok Web Imagine 配额字段 %s 结构不完整", item.field)
|
||||
}
|
||||
if item.mode == "" {
|
||||
continue
|
||||
}
|
||||
if *product.Available && (product.RemainingQueries == nil || product.WindowSizeSeconds == nil) {
|
||||
return nil, fmt.Errorf("Grok Web Imagine 配额字段 %s 结构不完整", item.field)
|
||||
}
|
||||
remaining := 0
|
||||
if product.RemainingQueries != nil {
|
||||
remaining = max(0, *product.RemainingQueries)
|
||||
}
|
||||
windowSeconds := 86400
|
||||
if product.WindowSizeSeconds != nil {
|
||||
windowSeconds = *product.WindowSizeSeconds
|
||||
}
|
||||
if windowSeconds <= 0 {
|
||||
return nil, fmt.Errorf("Grok Web Imagine 配额字段 %s 的 windowSizeSeconds 无效", item.field)
|
||||
}
|
||||
var resetAt *time.Time
|
||||
if product.NextAvailableAt != nil {
|
||||
value := product.NextAvailableAt.UTC()
|
||||
resetAt = &value
|
||||
} else if !*product.Available || remaining == 0 {
|
||||
value := now.Add(time.Duration(windowSeconds) * time.Second)
|
||||
resetAt = &value
|
||||
}
|
||||
windows = append(windows, account.QuotaWindow{
|
||||
AccountID: accountID, Mode: item.mode, Remaining: remaining, Total: 0,
|
||||
WindowSeconds: windowSeconds, ResetAt: resetAt, SyncedAt: &now,
|
||||
Source: account.QuotaSourceUpstream, UpdatedAt: now,
|
||||
})
|
||||
}
|
||||
return windows, nil
|
||||
}
|
||||
|
||||
func resolveWebTierFromQuota(current account.WebTier, windows []account.QuotaWindow, weeklyAvailable bool) (account.WebTier, bool) {
|
||||
if len(windows) > 0 {
|
||||
tier, known := inferWebTierFromQuota(windows)
|
||||
@@ -126,6 +277,18 @@ func (a *Adapter) SyncQuotaMode(ctx context.Context, credential account.Credenti
|
||||
if mode == weeklyQuotaMode {
|
||||
return a.syncWeeklyCredits(ctx, credential)
|
||||
}
|
||||
if account.IsWebImagineQuotaMode(mode) {
|
||||
snapshot, err := a.SyncQuotaGroup(ctx, credential, account.QuotaGroupWebImagine)
|
||||
if err != nil {
|
||||
return account.QuotaWindow{}, err
|
||||
}
|
||||
for _, w := range snapshot.Windows {
|
||||
if w.Mode == mode {
|
||||
return w, nil
|
||||
}
|
||||
}
|
||||
return account.QuotaWindow{}, fmt.Errorf("imagine 配额响应缺少 %s", mode)
|
||||
}
|
||||
cfg := a.config()
|
||||
token, err := a.cipher.Decrypt(credential.EncryptedAccessToken)
|
||||
if err != nil {
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"math"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -77,6 +78,8 @@ func TestSyncQuotaFetchesWeeklyOnlyAfterPaidTierIsConfirmed(t *testing.T) {
|
||||
var weeklyCalls atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
switch request.URL.Path {
|
||||
case "/rest/media/imagine/quota_info":
|
||||
writeEmptyImagineQuota(writer)
|
||||
case "/grok_api_v2.GrokBuildBilling/GetGrokCreditsConfig":
|
||||
weeklyCalls.Add(1)
|
||||
writer.Header().Set("Content-Type", "application/grpc-web+proto")
|
||||
@@ -386,6 +389,8 @@ func TestSyncQuotaCorrectsStoredSuperFromFreshWebQuota(t *testing.T) {
|
||||
var weeklyCalls atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
switch request.URL.Path {
|
||||
case "/rest/media/imagine/quota_info":
|
||||
writeEmptyImagineQuota(writer)
|
||||
case "/grok_api_v2.GrokBuildBilling/GetGrokCreditsConfig":
|
||||
weeklyCalls.Add(1)
|
||||
http.Error(writer, "not available", http.StatusNotFound)
|
||||
@@ -440,3 +445,63 @@ func TestSyncQuotaCorrectsStoredSuperFromFreshWebQuota(t *testing.T) {
|
||||
t.Fatalf("basic account probed weekly endpoint %d times", weeklyCalls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func writeEmptyImagineQuota(writer http.ResponseWriter) {
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
_, _ = writer.Write([]byte(`{"image":null,"imageEdit":null,"imagePro":null,"video":null,"video720p":null}`))
|
||||
}
|
||||
|
||||
func TestDecodeImagineQuotaSnapshotMatchesObservedProtocol(t *testing.T) {
|
||||
now := time.Date(2026, 8, 13, 8, 0, 0, 0, time.UTC)
|
||||
body := []byte(`{
|
||||
"image": null,
|
||||
"imageEdit": null,
|
||||
"imagePro": {"available":true,"remainingQueries":4,"windowSizeSeconds":86400},
|
||||
"video": null,
|
||||
"video720p": {"available":true,"remainingQueries":1,"windowSizeSeconds":86400}
|
||||
}`)
|
||||
windows, err := decodeImagineQuotaSnapshot(body, 42, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(windows) != 2 {
|
||||
t.Fatalf("windows = %#v", windows)
|
||||
}
|
||||
if windows[0].Mode != account.QuotaModeWebImagePro || windows[0].Remaining != 4 || windows[0].Total != 0 || windows[0].ResetAt != nil {
|
||||
t.Fatalf("image_pro = %#v", windows[0])
|
||||
}
|
||||
if windows[1].Mode != account.QuotaModeWebVideo720p || windows[1].Remaining != 1 || windows[1].Total != 0 || windows[1].ResetAt != nil {
|
||||
t.Fatalf("video_720p = %#v", windows[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeImagineQuotaSnapshotRequiresCompleteResponse(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
_, err := decodeImagineQuotaSnapshot([]byte(`{"image":null,"imageEdit":null,"imagePro":null,"video":null}`), 42, now)
|
||||
if err == nil || !strings.Contains(err.Error(), "video720p") {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeImagineQuotaSnapshotAcceptsExplicitUnavailableProduct(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
windows, err := decodeImagineQuotaSnapshot([]byte(`{
|
||||
"image":null,"imageEdit":{"available":false},"imagePro":null,"video":null,"video720p":null
|
||||
}`), 42, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(windows) != 1 || windows[0].Mode != account.QuotaModeWebImageEdit || windows[0].Remaining != 0 || windows[0].ResetAt == nil {
|
||||
t.Fatalf("windows = %#v", windows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeImagineQuotaSnapshotRejectsIncompleteAvailableProduct(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
_, err := decodeImagineQuotaSnapshot([]byte(`{
|
||||
"image":null,"imageEdit":null,"imagePro":{"available":true},"video":null,"video720p":null
|
||||
}`), 42, now)
|
||||
if err == nil || !strings.Contains(err.Error(), "imagePro") {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -219,8 +219,17 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque
|
||||
}
|
||||
defer lease.Release()
|
||||
parentID := ""
|
||||
references := make([]string, 0, len(request.ReferenceURLs))
|
||||
rawReferences := make([]string, 0, 1+len(request.ReferenceURLs))
|
||||
if imageURL := strings.TrimSpace(request.ImageURL); imageURL != "" {
|
||||
rawReferences = append(rawReferences, imageURL)
|
||||
}
|
||||
for _, rawReference := range request.ReferenceURLs {
|
||||
if value := strings.TrimSpace(rawReference); value != "" {
|
||||
rawReferences = append(rawReferences, value)
|
||||
}
|
||||
}
|
||||
references := make([]string, 0, len(rawReferences))
|
||||
for _, rawReference := range rawReferences {
|
||||
reference, referenceErr := a.prepareVideoReference(ctx, cfg, lease, token, rawReference)
|
||||
if referenceErr != nil {
|
||||
return provider.VideoResult{}, referenceErr
|
||||
|
||||
@@ -0,0 +1,745 @@
|
||||
package tunnelproxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Asutorufa/yuhaiin/pkg/net/netapi"
|
||||
"github.com/Asutorufa/yuhaiin/pkg/net/proxy/trojan"
|
||||
"github.com/Asutorufa/yuhaiin/pkg/net/proxy/vless"
|
||||
"github.com/Asutorufa/yuhaiin/pkg/net/proxy/vmess"
|
||||
"github.com/Asutorufa/yuhaiin/pkg/protos/node/protocol"
|
||||
"github.com/coder/websocket"
|
||||
"github.com/google/uuid"
|
||||
sscore "github.com/shadowsocks/go-shadowsocks2/core"
|
||||
"github.com/shadowsocks/go-shadowsocks2/socks"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Scheme string
|
||||
Server string
|
||||
Credential string
|
||||
Method string
|
||||
AlterID int
|
||||
Cipher string
|
||||
Transport string
|
||||
TLS bool
|
||||
ServerName string
|
||||
Insecure bool
|
||||
ALPN []string
|
||||
WebSocketHost string
|
||||
WebSocketPath string
|
||||
CanonicalProxyURL string
|
||||
}
|
||||
|
||||
const tunnelHandshakeTimeout = 10 * time.Second
|
||||
|
||||
func IsSupportedScheme(scheme string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(scheme)) {
|
||||
case "trojan", "vless", "ss", "vmess":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func Normalize(value string) (string, error) {
|
||||
config, err := Parse(value)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return config.CanonicalProxyURL, nil
|
||||
}
|
||||
|
||||
func Parse(value string) (Config, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if strings.IndexFunc(value, func(character rune) bool { return character < 0x20 || character == 0x7f }) >= 0 {
|
||||
return Config{}, errors.New("隧道代理地址包含控制字符")
|
||||
}
|
||||
scheme, _, ok := strings.Cut(value, "://")
|
||||
if !ok || !IsSupportedScheme(scheme) {
|
||||
return Config{}, errors.New("不支持的隧道代理协议")
|
||||
}
|
||||
switch strings.ToLower(scheme) {
|
||||
case "ss":
|
||||
return parseShadowsocks(value)
|
||||
case "vmess":
|
||||
return parseVMess(value)
|
||||
default:
|
||||
return parseUserInfoProxy(value)
|
||||
}
|
||||
}
|
||||
|
||||
func parseUserInfoProxy(value string) (Config, error) {
|
||||
parsed, err := url.Parse(value)
|
||||
if err != nil || parsed.Hostname() == "" || parsed.User == nil {
|
||||
return Config{}, errors.New("隧道代理地址格式无效")
|
||||
}
|
||||
scheme := strings.ToLower(parsed.Scheme)
|
||||
credential := parsed.User.Username()
|
||||
if credential == "" {
|
||||
return Config{}, errors.New("隧道代理凭据不能为空")
|
||||
}
|
||||
if _, hasPassword := parsed.User.Password(); hasPassword {
|
||||
return Config{}, errors.New("隧道代理凭据格式无效")
|
||||
}
|
||||
if parsed.Path != "" && parsed.Path != "/" {
|
||||
return Config{}, errors.New("隧道代理地址路径无效")
|
||||
}
|
||||
server, err := canonicalServer(parsed.Hostname(), parsed.Port())
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
query := parsed.Query()
|
||||
transport := strings.ToLower(firstNonEmpty(query.Get("type"), query.Get("network")))
|
||||
if transport == "" || transport == "none" {
|
||||
transport = "tcp"
|
||||
}
|
||||
if transport == "websocket" {
|
||||
transport = "ws"
|
||||
}
|
||||
if transport != "tcp" && transport != "ws" {
|
||||
return Config{}, fmt.Errorf("暂不支持 %s 传输", transport)
|
||||
}
|
||||
if flow := strings.TrimSpace(query.Get("flow")); flow != "" {
|
||||
return Config{}, fmt.Errorf("暂不支持 VLESS flow %q", flow)
|
||||
}
|
||||
if scheme == "vless" {
|
||||
parsedUUID, err := uuid.Parse(credential)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("VLESS UUID 无效")
|
||||
}
|
||||
credential = parsedUUID.String()
|
||||
if encryption := strings.ToLower(strings.TrimSpace(query.Get("encryption"))); encryption != "" && encryption != "none" {
|
||||
return Config{}, errors.New("VLESS encryption 必须为 none")
|
||||
}
|
||||
}
|
||||
security := strings.ToLower(strings.TrimSpace(query.Get("security")))
|
||||
tlsEnabled := scheme == "trojan"
|
||||
switch security {
|
||||
case "", "tls":
|
||||
if security == "tls" {
|
||||
tlsEnabled = true
|
||||
}
|
||||
case "none":
|
||||
tlsEnabled = false
|
||||
default:
|
||||
return Config{}, fmt.Errorf("暂不支持 %s security %q", strings.ToUpper(scheme), security)
|
||||
}
|
||||
if headerType := strings.ToLower(strings.TrimSpace(query.Get("headerType"))); headerType != "" && headerType != "none" {
|
||||
return Config{}, fmt.Errorf("暂不支持 %s headerType %q", strings.ToUpper(scheme), headerType)
|
||||
}
|
||||
insecure, err := queryBool(query, "allowInsecure", "insecure", "skip-cert-verify")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
serverName := firstNonEmpty(query.Get("sni"), query.Get("peer"), parsed.Hostname())
|
||||
wsHost := firstNonEmpty(query.Get("host"), serverName)
|
||||
if err := validateWebSocketHost(wsHost); transport == "ws" && err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
wsPath := query.Get("path")
|
||||
if wsPath == "" {
|
||||
wsPath = "/"
|
||||
} else if !strings.HasPrefix(wsPath, "/") {
|
||||
wsPath = "/" + wsPath
|
||||
}
|
||||
if transport == "tcp" && (query.Get("path") != "" || query.Get("host") != "") {
|
||||
return Config{}, errors.New("TCP 隧道不能包含 WebSocket host/path")
|
||||
}
|
||||
config := Config{
|
||||
Scheme: scheme, Server: server, Credential: credential, Transport: transport,
|
||||
TLS: tlsEnabled, ServerName: serverName, Insecure: insecure,
|
||||
ALPN: splitList(query.Get("alpn")), WebSocketHost: wsHost, WebSocketPath: wsPath,
|
||||
}
|
||||
config.CanonicalProxyURL = canonicalUserInfoProxyURL(config)
|
||||
if err := validateConfig(config); err != nil {
|
||||
return Config{}, fmt.Errorf("创建 %s 隧道配置: %w", strings.ToUpper(scheme), err)
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func canonicalUserInfoProxyURL(config Config) string {
|
||||
query := make(url.Values)
|
||||
query.Set("type", config.Transport)
|
||||
if config.TLS {
|
||||
query.Set("security", "tls")
|
||||
} else {
|
||||
query.Set("security", "none")
|
||||
}
|
||||
if config.Scheme == "vless" {
|
||||
query.Set("encryption", "none")
|
||||
}
|
||||
query.Set("sni", config.ServerName)
|
||||
if config.Insecure {
|
||||
query.Set("allowInsecure", "1")
|
||||
}
|
||||
if len(config.ALPN) != 0 {
|
||||
query.Set("alpn", strings.Join(config.ALPN, ","))
|
||||
}
|
||||
if config.Transport == "ws" {
|
||||
query.Set("host", config.WebSocketHost)
|
||||
query.Set("path", config.WebSocketPath)
|
||||
}
|
||||
return (&url.URL{
|
||||
Scheme: config.Scheme,
|
||||
User: url.User(config.Credential),
|
||||
Host: config.Server,
|
||||
RawQuery: query.Encode(),
|
||||
}).String()
|
||||
}
|
||||
|
||||
func parseShadowsocks(value string) (Config, error) {
|
||||
payload := value[len("ss://"):]
|
||||
if before, _, found := strings.Cut(payload, "#"); found {
|
||||
payload = before
|
||||
}
|
||||
if before, rawQuery, found := strings.Cut(payload, "?"); found {
|
||||
query, err := url.ParseQuery(rawQuery)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("Shadowsocks 查询参数无效")
|
||||
}
|
||||
if plugin := strings.TrimSpace(query.Get("plugin")); plugin != "" {
|
||||
return Config{}, errors.New("暂不支持 Shadowsocks plugin")
|
||||
}
|
||||
if len(query) != 0 {
|
||||
return Config{}, errors.New("Shadowsocks 查询参数无效")
|
||||
}
|
||||
payload = before
|
||||
}
|
||||
var userPart, serverPart string
|
||||
if separator := strings.LastIndex(payload, "@"); separator >= 0 {
|
||||
userPart, serverPart = payload[:separator], payload[separator+1:]
|
||||
decoded, err := url.PathUnescape(userPart)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("Shadowsocks 凭据无效")
|
||||
}
|
||||
if !strings.Contains(decoded, ":") {
|
||||
decoded, err = decodeBase64String(decoded)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("Shadowsocks 凭据不是有效的 Base64")
|
||||
}
|
||||
}
|
||||
userPart = decoded
|
||||
} else {
|
||||
decoded, err := decodeBase64String(payload)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("旧式 Shadowsocks 地址不是有效的 Base64")
|
||||
}
|
||||
separator := strings.LastIndex(decoded, "@")
|
||||
if separator < 0 {
|
||||
return Config{}, errors.New("旧式 Shadowsocks 地址格式无效")
|
||||
}
|
||||
userPart, serverPart = decoded[:separator], decoded[separator+1:]
|
||||
}
|
||||
method, password, ok := strings.Cut(userPart, ":")
|
||||
if !ok || strings.TrimSpace(method) == "" || password == "" {
|
||||
return Config{}, errors.New("Shadowsocks method/password 不能为空")
|
||||
}
|
||||
method = strings.ToLower(strings.TrimSpace(method))
|
||||
switch method {
|
||||
case "aes-128-gcm", "aes-256-gcm", "chacha20-ietf-poly1305":
|
||||
default:
|
||||
return Config{}, fmt.Errorf("暂不支持 Shadowsocks method %q", method)
|
||||
}
|
||||
serverURL, err := url.Parse("ss://" + serverPart)
|
||||
if err != nil || serverURL.User != nil || (serverURL.Path != "" && serverURL.Path != "/") || serverURL.RawQuery != "" || serverURL.Fragment != "" {
|
||||
return Config{}, errors.New("Shadowsocks 服务器地址无效")
|
||||
}
|
||||
server, err := canonicalServer(serverURL.Hostname(), serverURL.Port())
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
credential := method + ":" + password
|
||||
config := Config{
|
||||
Scheme: "ss", Server: server, Credential: password, Method: method, Transport: "tcp",
|
||||
CanonicalProxyURL: "ss://" + base64.RawURLEncoding.EncodeToString([]byte(credential)) + "@" + server,
|
||||
}
|
||||
if err := validateConfig(config); err != nil {
|
||||
return Config{}, fmt.Errorf("创建 Shadowsocks 隧道配置: %w", err)
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
type vmessShare struct {
|
||||
Version string `json:"v,omitempty"`
|
||||
Address string `json:"add"`
|
||||
Port string `json:"port"`
|
||||
UUID string `json:"id"`
|
||||
AlterID string `json:"aid"`
|
||||
Cipher string `json:"scy,omitempty"`
|
||||
Network string `json:"net"`
|
||||
TLS string `json:"tls,omitempty"`
|
||||
ServerName string `json:"sni,omitempty"`
|
||||
Host string `json:"host,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
AllowInsecure bool `json:"allowInsecure,omitempty"`
|
||||
}
|
||||
|
||||
func parseVMess(value string) (Config, error) {
|
||||
payload := value[len("vmess://"):]
|
||||
if before, _, found := strings.Cut(payload, "#"); found {
|
||||
payload = before
|
||||
}
|
||||
decoded, err := decodeBase64Bytes(payload)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("VMess 配置不是有效的 Base64")
|
||||
}
|
||||
var raw map[string]any
|
||||
if err := json.Unmarshal(decoded, &raw); err != nil {
|
||||
return Config{}, errors.New("VMess 配置不是有效的 JSON")
|
||||
}
|
||||
address := jsonString(raw, "add")
|
||||
port := jsonString(raw, "port")
|
||||
server, err := canonicalServer(address, port)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("VMess %w", err)
|
||||
}
|
||||
parsedUUID, err := uuid.Parse(jsonString(raw, "id"))
|
||||
if err != nil {
|
||||
return Config{}, errors.New("VMess UUID 无效")
|
||||
}
|
||||
userID := parsedUUID.String()
|
||||
alterID, err := strconv.Atoi(firstNonEmpty(jsonString(raw, "aid"), "0"))
|
||||
if err != nil || alterID < 0 || alterID > 65535 {
|
||||
return Config{}, errors.New("VMess alterId 无效")
|
||||
}
|
||||
cipher := strings.ToLower(firstNonEmpty(jsonString(raw, "scy"), jsonString(raw, "security"), "auto"))
|
||||
switch cipher {
|
||||
case "auto", "aes-128-gcm", "chacha20-poly1305", "none":
|
||||
default:
|
||||
return Config{}, fmt.Errorf("暂不支持 VMess cipher %q", cipher)
|
||||
}
|
||||
transport := strings.ToLower(firstNonEmpty(jsonString(raw, "net"), "tcp"))
|
||||
if transport == "websocket" {
|
||||
transport = "ws"
|
||||
}
|
||||
if transport != "tcp" && transport != "ws" {
|
||||
return Config{}, fmt.Errorf("暂不支持 VMess %s 传输", transport)
|
||||
}
|
||||
if headerType := strings.ToLower(jsonString(raw, "type")); headerType != "" && headerType != "none" {
|
||||
return Config{}, fmt.Errorf("暂不支持 VMess header type %q", headerType)
|
||||
}
|
||||
tlsMode := strings.ToLower(jsonString(raw, "tls"))
|
||||
if tlsMode != "" && tlsMode != "none" && tlsMode != "tls" {
|
||||
return Config{}, fmt.Errorf("暂不支持 VMess TLS 模式 %q", tlsMode)
|
||||
}
|
||||
tlsEnabled := tlsMode == "tls"
|
||||
serverName := firstNonEmpty(jsonString(raw, "sni"), address)
|
||||
host := firstNonEmpty(jsonString(raw, "host"), serverName)
|
||||
if err := validateWebSocketHost(host); transport == "ws" && err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
path := jsonString(raw, "path")
|
||||
if path == "" {
|
||||
path = "/"
|
||||
} else if !strings.HasPrefix(path, "/") {
|
||||
path = "/" + path
|
||||
}
|
||||
if transport == "tcp" && (jsonString(raw, "path") != "" || jsonString(raw, "host") != "") {
|
||||
return Config{}, errors.New("VMess TCP 隧道不能包含 WebSocket host/path")
|
||||
}
|
||||
insecure, err := jsonBool(raw, "allowInsecure")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
share := vmessShare{
|
||||
Version: "2", Address: address, Port: port, UUID: userID, AlterID: strconv.Itoa(alterID), Cipher: cipher,
|
||||
Network: transport, ServerName: serverName, AllowInsecure: insecure,
|
||||
}
|
||||
if transport == "ws" {
|
||||
share.Host = host
|
||||
share.Path = path
|
||||
}
|
||||
if tlsEnabled {
|
||||
share.TLS = "tls"
|
||||
}
|
||||
canonicalJSON, err := json.Marshal(share)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
config := Config{
|
||||
Scheme: "vmess", Server: server, Credential: userID, AlterID: alterID, Cipher: cipher,
|
||||
Transport: transport, TLS: tlsEnabled, ServerName: serverName, Insecure: insecure,
|
||||
WebSocketHost: host, WebSocketPath: path,
|
||||
CanonicalProxyURL: "vmess://" + base64.RawStdEncoding.EncodeToString(canonicalJSON),
|
||||
}
|
||||
if err := validateConfig(config); err != nil {
|
||||
return Config{}, fmt.Errorf("创建 VMess 隧道配置: %w", err)
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
type Dialer struct {
|
||||
proxy netapi.Proxy
|
||||
shadowsocksCipher sscore.StreamConnCipher
|
||||
server string
|
||||
}
|
||||
|
||||
func NewDialer(value string) (*Dialer, error) {
|
||||
config, err := Parse(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if config.Scheme == "ss" {
|
||||
cipher, err := sscore.PickCipher(config.Method, nil, config.Credential)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Dialer{shadowsocksCipher: cipher, server: config.Server}, nil
|
||||
}
|
||||
proxy, err := buildProxy(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Dialer{proxy: proxy}, nil
|
||||
}
|
||||
|
||||
func (d *Dialer) Dial(network, address string) (net.Conn, error) {
|
||||
return d.DialContext(context.Background(), network, address)
|
||||
}
|
||||
|
||||
func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
if d == nil || (d.proxy == nil && d.shadowsocksCipher == nil) {
|
||||
return nil, errors.New("隧道代理拨号器未初始化")
|
||||
}
|
||||
if !strings.HasPrefix(network, "tcp") {
|
||||
return nil, fmt.Errorf("隧道代理不支持网络 %q", network)
|
||||
}
|
||||
if d.shadowsocksCipher != nil {
|
||||
return d.dialShadowsocks(ctx, address)
|
||||
}
|
||||
target, err := netapi.ParseAddress(network, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.proxy.Conn(ctx, target)
|
||||
}
|
||||
|
||||
func (d *Dialer) dialShadowsocks(ctx context.Context, address string) (net.Conn, error) {
|
||||
target := socks.ParseAddr(address)
|
||||
if target == nil {
|
||||
return nil, errors.New("Shadowsocks 目标地址无效")
|
||||
}
|
||||
connection, err := newServerNetDialer().DialContext(ctx, "tcp", d.server)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
connection = d.shadowsocksCipher.StreamConn(connection)
|
||||
if _, err := connection.Write(target); err != nil {
|
||||
_ = connection.Close()
|
||||
return nil, fmt.Errorf("写入 Shadowsocks 目标地址: %w", err)
|
||||
}
|
||||
return connection, nil
|
||||
}
|
||||
|
||||
func validateConfig(config Config) error {
|
||||
if config.Scheme == "ss" {
|
||||
_, err := sscore.PickCipher(config.Method, nil, config.Credential)
|
||||
return err
|
||||
}
|
||||
_, err := buildProxy(config)
|
||||
return err
|
||||
}
|
||||
|
||||
func buildProxy(config Config) (netapi.Proxy, error) {
|
||||
var current netapi.Proxy = &serverDialer{address: config.Server}
|
||||
if config.Transport == "ws" {
|
||||
current = &websocketProxy{config: config, dialer: current}
|
||||
} else if config.TLS {
|
||||
current = &tlsProxy{config: config, dialer: current}
|
||||
}
|
||||
switch config.Scheme {
|
||||
case "trojan":
|
||||
protocolConfig := &protocol.Trojan{}
|
||||
protocolConfig.SetPassword(config.Credential)
|
||||
return trojan.NewClient(protocolConfig, current)
|
||||
case "vless":
|
||||
protocolConfig := &protocol.Vless{}
|
||||
protocolConfig.SetUuid(config.Credential)
|
||||
return newOwnedVLESSProxy(protocolConfig, current)
|
||||
case "vmess":
|
||||
protocolConfig := &protocol.Vmess{}
|
||||
protocolConfig.SetUuid(config.Credential)
|
||||
protocolConfig.SetAlterId(strconv.Itoa(config.AlterID))
|
||||
protocolConfig.SetSecurity(config.Cipher)
|
||||
return vmess.NewClient(protocolConfig, current)
|
||||
default:
|
||||
return nil, errors.New("不支持的隧道代理协议")
|
||||
}
|
||||
}
|
||||
|
||||
// ownedVLESSProxy closes the transport connection when the upstream VLESS
|
||||
// client fails while writing its initial request. yuhaiin's VLESS client does
|
||||
// not transfer the failed connection back to its caller, so ownership must be
|
||||
// retained at this boundary to prevent failed retries from leaking sockets.
|
||||
type ownedVLESSProxy struct {
|
||||
netapi.EmptyDispatch
|
||||
config *protocol.Vless
|
||||
dialer netapi.Proxy
|
||||
}
|
||||
|
||||
func newOwnedVLESSProxy(config *protocol.Vless, dialer netapi.Proxy) (netapi.Proxy, error) {
|
||||
if _, err := vless.NewClient(config, dialer); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ownedVLESSProxy{config: config, dialer: dialer}, nil
|
||||
}
|
||||
|
||||
func (p *ownedVLESSProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) {
|
||||
connection, err := p.dialer.Conn(ctx, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client, err := vless.NewClient(p.config, &singleConnectionProxy{connection: connection})
|
||||
if err != nil {
|
||||
_ = connection.Close()
|
||||
return nil, err
|
||||
}
|
||||
result, err := client.Conn(ctx, address)
|
||||
if err != nil {
|
||||
_ = connection.Close()
|
||||
return nil, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (p *ownedVLESSProxy) PacketConn(ctx context.Context, address netapi.Address) (net.PacketConn, error) {
|
||||
return nil, errors.New("VLESS 隧道不支持 UDP")
|
||||
}
|
||||
|
||||
type singleConnectionProxy struct {
|
||||
netapi.EmptyDispatch
|
||||
connection net.Conn
|
||||
}
|
||||
|
||||
func (p *singleConnectionProxy) Conn(context.Context, netapi.Address) (net.Conn, error) {
|
||||
if p.connection == nil {
|
||||
return nil, errors.New("VLESS 底层连接不可用")
|
||||
}
|
||||
connection := p.connection
|
||||
p.connection = nil
|
||||
return connection, nil
|
||||
}
|
||||
|
||||
func (p *singleConnectionProxy) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) {
|
||||
return nil, errors.New("VLESS 隧道不支持 UDP")
|
||||
}
|
||||
|
||||
type tlsProxy struct {
|
||||
netapi.EmptyDispatch
|
||||
config Config
|
||||
dialer netapi.Proxy
|
||||
}
|
||||
|
||||
func (p *tlsProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) {
|
||||
connection, err := p.dialer.Conn(ctx, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tlsConnection := tls.Client(connection, p.tlsConfig())
|
||||
handshakeCtx, cancel := newTunnelHandshakeContext(ctx)
|
||||
defer cancel()
|
||||
if err := tlsConnection.HandshakeContext(handshakeCtx); err != nil {
|
||||
_ = connection.Close()
|
||||
return nil, fmt.Errorf("隧道 TLS 握手: %w", err)
|
||||
}
|
||||
return tlsConnection, nil
|
||||
}
|
||||
|
||||
func (p *tlsProxy) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) {
|
||||
return nil, errors.New("TLS 隧道不支持 UDP")
|
||||
}
|
||||
|
||||
func (p *tlsProxy) tlsConfig() *tls.Config {
|
||||
return &tls.Config{
|
||||
MinVersion: tls.VersionTLS12, ServerName: p.config.ServerName,
|
||||
InsecureSkipVerify: p.config.Insecure, NextProtos: append([]string(nil), p.config.ALPN...),
|
||||
}
|
||||
}
|
||||
|
||||
type websocketProxy struct {
|
||||
netapi.EmptyDispatch
|
||||
config Config
|
||||
dialer netapi.Proxy
|
||||
}
|
||||
|
||||
func (p *websocketProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) {
|
||||
scheme := "ws"
|
||||
if p.config.TLS {
|
||||
scheme = "wss"
|
||||
}
|
||||
path, rawQuery, _ := strings.Cut(p.config.WebSocketPath, "?")
|
||||
endpoint := (&url.URL{Scheme: scheme, Host: p.config.WebSocketHost, Path: path, RawQuery: rawQuery}).String()
|
||||
transport := &http.Transport{
|
||||
Proxy: nil,
|
||||
DialContext: func(dialCtx context.Context, _, _ string) (net.Conn, error) {
|
||||
return p.dialer.Conn(dialCtx, address)
|
||||
},
|
||||
ForceAttemptHTTP2: false,
|
||||
TLSClientConfig: websocketTLSConfig(p.config),
|
||||
}
|
||||
handshakeCtx, cancel := newTunnelHandshakeContext(ctx)
|
||||
defer cancel()
|
||||
connection, _, err := websocket.Dial(handshakeCtx, endpoint, &websocket.DialOptions{
|
||||
HTTPClient: &http.Client{Transport: transport},
|
||||
Host: p.config.WebSocketHost,
|
||||
})
|
||||
if err != nil {
|
||||
transport.CloseIdleConnections()
|
||||
return nil, fmt.Errorf("隧道 WebSocket 握手: %w", err)
|
||||
}
|
||||
return websocket.NetConn(context.Background(), connection, websocket.MessageBinary), nil
|
||||
}
|
||||
|
||||
func (p *websocketProxy) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) {
|
||||
return nil, errors.New("WebSocket 隧道不支持 UDP")
|
||||
}
|
||||
|
||||
type serverDialer struct {
|
||||
netapi.EmptyDispatch
|
||||
address string
|
||||
}
|
||||
|
||||
func (d *serverDialer) Conn(ctx context.Context, _ netapi.Address) (net.Conn, error) {
|
||||
return newServerNetDialer().DialContext(ctx, "tcp", d.address)
|
||||
}
|
||||
|
||||
func newServerNetDialer() *net.Dialer {
|
||||
return &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}
|
||||
}
|
||||
|
||||
func newTunnelHandshakeContext(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(ctx, tunnelHandshakeTimeout)
|
||||
}
|
||||
|
||||
func websocketTLSConfig(config Config) *tls.Config {
|
||||
tlsConfig := (&tlsProxy{config: config}).tlsConfig()
|
||||
tlsConfig.NextProtos = []string{"http/1.1"}
|
||||
return tlsConfig
|
||||
}
|
||||
|
||||
func validateWebSocketHost(host string) error {
|
||||
parsed, err := url.Parse("http://" + strings.TrimSpace(host))
|
||||
if err != nil || parsed.Hostname() == "" || parsed.User != nil || parsed.Path != "" || parsed.RawQuery != "" || parsed.Fragment != "" {
|
||||
return errors.New("WebSocket host 无效")
|
||||
}
|
||||
if parsed.Port() != "" {
|
||||
if _, err := canonicalServer(parsed.Hostname(), parsed.Port()); err != nil {
|
||||
return errors.New("WebSocket host 无效")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *serverDialer) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) {
|
||||
return nil, errors.New("当前隧道代理不支持 UDP")
|
||||
}
|
||||
|
||||
func canonicalServer(host, port string) (string, error) {
|
||||
host = strings.TrimSpace(strings.Trim(host, "[]"))
|
||||
if host == "" {
|
||||
return "", errors.New("隧道代理服务器不能为空")
|
||||
}
|
||||
parsedPort, err := strconv.ParseUint(strings.TrimSpace(port), 10, 16)
|
||||
if err != nil || parsedPort == 0 {
|
||||
return "", errors.New("隧道代理端口无效")
|
||||
}
|
||||
return net.JoinHostPort(host, strconv.FormatUint(parsedPort, 10)), nil
|
||||
}
|
||||
|
||||
func decodeBase64String(value string) (string, error) {
|
||||
decoded, err := decodeBase64Bytes(value)
|
||||
return string(decoded), err
|
||||
}
|
||||
|
||||
func decodeBase64Bytes(value string) ([]byte, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
for _, encoding := range []*base64.Encoding{base64.RawStdEncoding, base64.StdEncoding, base64.RawURLEncoding, base64.URLEncoding} {
|
||||
if decoded, err := encoding.DecodeString(value); err == nil {
|
||||
return decoded, nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("invalid base64")
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func splitList(value string) []string {
|
||||
var result []string
|
||||
for item := range strings.SplitSeq(value, ",") {
|
||||
if item = strings.TrimSpace(item); item != "" {
|
||||
result = append(result, item)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func queryBool(query url.Values, names ...string) (bool, error) {
|
||||
for _, name := range names {
|
||||
if raw, ok := query[name]; ok && len(raw) != 0 {
|
||||
return parseBool(raw[0], name)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func jsonBool(value map[string]any, name string) (bool, error) {
|
||||
raw, ok := value[name]
|
||||
if !ok || raw == nil {
|
||||
return false, nil
|
||||
}
|
||||
switch typed := raw.(type) {
|
||||
case bool:
|
||||
return typed, nil
|
||||
case string:
|
||||
return parseBool(typed, name)
|
||||
case float64:
|
||||
return parseBool(strconv.FormatFloat(typed, 'f', -1, 64), name)
|
||||
default:
|
||||
return false, fmt.Errorf("%s 必须是布尔值", name)
|
||||
}
|
||||
}
|
||||
|
||||
func parseBool(value, name string) (bool, error) {
|
||||
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||
case "1", "true", "yes":
|
||||
return true, nil
|
||||
case "", "0", "false", "no":
|
||||
return false, nil
|
||||
default:
|
||||
return false, fmt.Errorf("%s 必须是布尔值", name)
|
||||
}
|
||||
}
|
||||
|
||||
func jsonString(value map[string]any, name string) string {
|
||||
raw, ok := value[name]
|
||||
if !ok || raw == nil {
|
||||
return ""
|
||||
}
|
||||
switch typed := raw.(type) {
|
||||
case string:
|
||||
return strings.TrimSpace(typed)
|
||||
case float64:
|
||||
return strconv.FormatFloat(typed, 'f', -1, 64)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package tunnelproxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Asutorufa/yuhaiin/pkg/net/netapi"
|
||||
"github.com/Asutorufa/yuhaiin/pkg/protos/node/protocol"
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
const testUUID = "123e4567-e89b-12d3-a456-426614174000"
|
||||
|
||||
func TestNormalizeStripsRemarksAndBuildsDialers(t *testing.T) {
|
||||
vmessJSON := fmt.Sprintf(`{"v":"2","ps":"node one","add":"proxy.example","port":"443","id":%q,"aid":"0","scy":"auto","net":"ws","tls":"tls","sni":"edge.example","host":"edge.example","path":"/ws"}`, testUUID)
|
||||
vmessURL := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(vmessJSON))
|
||||
tests := []struct {
|
||||
name string
|
||||
raw string
|
||||
}{
|
||||
{name: "trojan", raw: "trojan://secret@proxy.example:443?security=tls&sni=edge.example&type=ws&host=edge.example&path=%2Fws#one"},
|
||||
{name: "vless", raw: "vless://" + testUUID + "@proxy.example:443?encryption=none&security=tls&sni=edge.example&type=ws&host=edge.example&path=%2Fws#one"},
|
||||
{name: "shadowsocks", raw: "ss://" + base64.RawURLEncoding.EncodeToString([]byte("aes-128-gcm:secret")) + "@proxy.example:8388#one"},
|
||||
{name: "vmess", raw: vmessURL},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
normalized, err := Normalize(test.raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(normalized, "#") || strings.Contains(normalized, "node one") {
|
||||
t.Fatalf("remark leaked into normalized URL: %q", normalized)
|
||||
}
|
||||
if _, err := NewDialer(normalized); err != nil {
|
||||
t.Fatalf("construct dialer: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRemarksDoNotChangeIdentity(t *testing.T) {
|
||||
base := "trojan://secret@proxy.example:443?security=tls&sni=edge.example"
|
||||
one, err := Normalize(base + "#one")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
two, err := Normalize(base + "#two")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if one != two {
|
||||
t.Fatalf("remark changed identity: %q != %q", one, two)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeEquivalentShareLinksHaveOneIdentity(t *testing.T) {
|
||||
trojanOne, err := Normalize("trojan://secret@proxy.example:443?type=websocket&security=tls&sni=edge.example&host=edge.example&path=ws")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
trojanTwo, err := Normalize("trojan://secret@proxy.example:443?network=ws&peer=edge.example&host=edge.example&path=%2Fws")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if trojanOne != trojanTwo {
|
||||
t.Fatalf("equivalent Trojan links have different identities: %q != %q", trojanOne, trojanTwo)
|
||||
}
|
||||
|
||||
vmessOne := vmessTestURL(t, map[string]any{
|
||||
"v": "2", "add": "proxy.example", "port": "443", "id": testUUID,
|
||||
"aid": "0", "scy": "auto", "net": "ws", "tls": "tls",
|
||||
"sni": "edge.example", "host": "edge.example", "path": "ws",
|
||||
})
|
||||
vmessTwo := vmessTestURL(t, map[string]any{
|
||||
"v": "2", "add": "proxy.example", "port": "443", "id": testUUID,
|
||||
"aid": "0", "scy": "auto", "net": "ws", "tls": "tls",
|
||||
"sni": "edge.example", "host": "edge.example", "path": "/ws",
|
||||
})
|
||||
normalizedOne, err := Normalize(vmessOne)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
normalizedTwo, err := Normalize(vmessTwo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if normalizedOne != normalizedTwo {
|
||||
t.Fatalf("equivalent VMess links have different identities: %q != %q", normalizedOne, normalizedTwo)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnedVLESSProxyClosesConnectionWhenInitialWriteFails(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
if err := server.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tracked := &closeTrackingConn{Conn: client}
|
||||
config := &protocol.Vless{}
|
||||
config.SetUuid(testUUID)
|
||||
proxy, err := newOwnedVLESSProxy(config, &singleConnectionProxy{connection: tracked})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := proxy.Conn(context.Background(), netapi.ParseDomainPort("tcp", "target.example", 443)); err == nil {
|
||||
t.Fatal("VLESS initial write unexpectedly succeeded")
|
||||
}
|
||||
if !tracked.closed {
|
||||
t.Fatal("failed VLESS connection was not closed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTunnelHandshakeContextHasIndependentDeadline(t *testing.T) {
|
||||
ctx, cancel := newTunnelHandshakeContext(context.Background())
|
||||
defer cancel()
|
||||
deadline, ok := ctx.Deadline()
|
||||
if !ok {
|
||||
t.Fatal("tunnel handshake context has no deadline")
|
||||
}
|
||||
remaining := time.Until(deadline)
|
||||
if remaining <= 0 || remaining > tunnelHandshakeTimeout {
|
||||
t.Fatalf("tunnel handshake deadline remaining = %v", remaining)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeSupportsLegacyShadowsocks(t *testing.T) {
|
||||
raw := "ss://" + base64.RawStdEncoding.EncodeToString([]byte("chacha20-ietf-poly1305:secret@proxy.example:8388")) + "#legacy"
|
||||
normalized, err := Normalize(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(normalized, "ss://") || strings.Contains(normalized, "#") {
|
||||
t.Fatalf("normalized legacy URL = %q", normalized)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsUnsupportedOrMalformedLinks(t *testing.T) {
|
||||
for _, raw := range []string{
|
||||
"hysteria2://secret@proxy.example:443",
|
||||
"tuic://user:secret@proxy.example:443",
|
||||
"vless://not-a-uuid@proxy.example:443?encryption=none",
|
||||
"vless://" + testUUID + "@proxy.example:443?encryption=none&flow=xtls-rprx-vision",
|
||||
"trojan://secret@proxy.example:443?type=grpc",
|
||||
"trojan://secret@proxy.example:443/unexpected",
|
||||
"ss://" + base64.RawURLEncoding.EncodeToString([]byte("rc4-md5:secret")) + "@proxy.example:8388",
|
||||
"ss://" + base64.RawURLEncoding.EncodeToString([]byte("aes-128-gcm:secret")) + "@proxy.example:8388/unexpected",
|
||||
"vmess://not-base64",
|
||||
} {
|
||||
if _, err := Normalize(raw); err == nil {
|
||||
t.Fatalf("invalid tunnel accepted: %q", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebSocketTransportCarriesBinaryStream(t *testing.T) {
|
||||
handlerResult := make(chan error, 1)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.Host != "edge.example" || request.URL.Path != "/ws" {
|
||||
handlerResult <- fmt.Errorf("request host=%q path=%q", request.Host, request.URL.Path)
|
||||
return
|
||||
}
|
||||
connection, err := websocket.Accept(writer, request, nil)
|
||||
if err != nil {
|
||||
handlerResult <- err
|
||||
return
|
||||
}
|
||||
stream := websocket.NetConn(context.Background(), connection, websocket.MessageBinary)
|
||||
defer stream.Close()
|
||||
_, err = io.CopyN(stream, stream, 4)
|
||||
handlerResult <- err
|
||||
}))
|
||||
defer server.Close()
|
||||
serverAddress := strings.TrimPrefix(server.URL, "http://")
|
||||
proxy := &websocketProxy{
|
||||
config: Config{Server: serverAddress, WebSocketHost: "edge.example", WebSocketPath: "/ws"},
|
||||
dialer: &serverDialer{address: serverAddress},
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
connection, err := proxy.Conn(ctx, netapi.ParseDomainPort("tcp", "target.example", 443))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer connection.Close()
|
||||
if _, err := connection.Write([]byte("pong")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response := make([]byte, 4)
|
||||
if _, err := io.ReadFull(connection, response); err != nil || string(response) != "pong" {
|
||||
t.Fatalf("response=%q err=%v", response, err)
|
||||
}
|
||||
if err := <-handlerResult; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
type closeTrackingConn struct {
|
||||
net.Conn
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (c *closeTrackingConn) Close() error {
|
||||
c.closed = true
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
func vmessTestURL(t *testing.T, config map[string]any) string {
|
||||
t.Helper()
|
||||
payload, err := json.Marshal(config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return "vmess://" + base64.RawStdEncoding.EncodeToString(payload)
|
||||
}
|
||||
@@ -169,6 +169,7 @@ type AccountRepository interface {
|
||||
HasQuotaWindows(ctx context.Context, accountID uint64) (bool, error)
|
||||
GetQuotaWindows(ctx context.Context, accountIDs []uint64) (map[uint64][]account.QuotaWindow, error)
|
||||
ReplaceQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow) error
|
||||
ReplaceQuotaWindowGroup(ctx context.Context, accountID uint64, syncedAt time.Time, modes []string, values []account.QuotaWindow) error
|
||||
SaveQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow) error
|
||||
UpsertManyByIdentity(ctx context.Context, values []account.Credential) ([]AccountUpsertResult, error)
|
||||
DecrementQuotaWindow(ctx context.Context, accountID uint64, mode string, now time.Time) (bool, error)
|
||||
|
||||
@@ -800,6 +800,8 @@ type sourceRequest struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
URL *string `json:"url"`
|
||||
ClearURL bool `json:"clearUrl"`
|
||||
ProxyURL *string `json:"proxyURL"`
|
||||
ClearProxyURL bool `json:"clearProxyURL"`
|
||||
RefreshIntervalSeconds *int `json:"refreshIntervalSeconds"`
|
||||
DefaultAccountCapacity *int `json:"defaultAccountCapacity"`
|
||||
}
|
||||
@@ -810,6 +812,7 @@ type sourceResponse struct {
|
||||
Scope string `json:"scope"`
|
||||
Enabled bool `json:"enabled"`
|
||||
URLConfigured bool `json:"urlConfigured"`
|
||||
ProxyConfigured bool `json:"proxyConfigured"`
|
||||
RefreshIntervalSeconds int `json:"refreshIntervalSeconds"`
|
||||
DefaultAccountCapacity int `json:"defaultAccountCapacity"`
|
||||
LastSyncedAt *time.Time `json:"lastSyncedAt,omitempty"`
|
||||
@@ -835,8 +838,6 @@ type operationsConfigRequest struct {
|
||||
AutoAssignEnabled bool `json:"autoAssignEnabled"`
|
||||
AutoBalanceEnabled bool `json:"autoBalanceEnabled"`
|
||||
AssignmentIntervalSeconds int `json:"assignmentIntervalSeconds"`
|
||||
SubscriptionProxyURL *string `json:"subscriptionProxyURL,omitempty"`
|
||||
ClearSubscriptionProxy bool `json:"clearSubscriptionProxy,omitempty"`
|
||||
Fallbacks map[string]operationsFallbackRequest `json:"fallbacks"`
|
||||
}
|
||||
|
||||
@@ -846,14 +847,13 @@ type operationsFallbackRequest struct {
|
||||
}
|
||||
|
||||
type operationsConfigResponse struct {
|
||||
ProbeProvider string `json:"probeProvider"`
|
||||
ProbeIntervalSeconds int `json:"probeIntervalSeconds"`
|
||||
AutoAssignEnabled bool `json:"autoAssignEnabled"`
|
||||
AutoBalanceEnabled bool `json:"autoBalanceEnabled"`
|
||||
AssignmentIntervalSeconds int `json:"assignmentIntervalSeconds"`
|
||||
SubscriptionProxyConfigured bool `json:"subscriptionProxyConfigured"`
|
||||
Fallbacks map[string]operationsFallbackResponse `json:"fallbacks"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
ProbeProvider string `json:"probeProvider"`
|
||||
ProbeIntervalSeconds int `json:"probeIntervalSeconds"`
|
||||
AutoAssignEnabled bool `json:"autoAssignEnabled"`
|
||||
AutoBalanceEnabled bool `json:"autoBalanceEnabled"`
|
||||
AssignmentIntervalSeconds int `json:"assignmentIntervalSeconds"`
|
||||
Fallbacks map[string]operationsFallbackResponse `json:"fallbacks"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type operationsFallbackResponse struct {
|
||||
@@ -866,12 +866,6 @@ func (value operationsConfigRequest) input() (egressapp.OperationsConfigInput, e
|
||||
ProbeProvider: egressdomain.ProbeProvider(strings.TrimSpace(value.ProbeProvider)), ProbeIntervalSeconds: value.ProbeIntervalSeconds, AutoAssignEnabled: value.AutoAssignEnabled,
|
||||
AutoBalanceEnabled: value.AutoBalanceEnabled, AssignmentIntervalSeconds: value.AssignmentIntervalSeconds,
|
||||
}
|
||||
if value.SubscriptionProxyURL != nil {
|
||||
result.SubscriptionProxyURL = value.SubscriptionProxyURL
|
||||
}
|
||||
if value.ClearSubscriptionProxy {
|
||||
result.ClearSubscriptionProxy = true
|
||||
}
|
||||
if value.Fallbacks == nil {
|
||||
return result, nil
|
||||
}
|
||||
@@ -895,6 +889,7 @@ func (value operationsConfigRequest) input() (egressapp.OperationsConfigInput, e
|
||||
func (value sourceRequest) input() egressapp.SubscriptionSourceInput {
|
||||
return egressapp.SubscriptionSourceInput{
|
||||
Name: value.Name, Scope: egressdomain.Scope(value.Scope), Enabled: value.Enabled, URL: value.URL, ClearURL: value.ClearURL,
|
||||
ProxyURL: value.ProxyURL, ClearProxyURL: value.ClearProxyURL,
|
||||
RefreshIntervalSeconds: value.RefreshIntervalSeconds, DefaultAccountCapacity: value.DefaultAccountCapacity,
|
||||
}
|
||||
}
|
||||
@@ -902,6 +897,7 @@ func (value sourceRequest) input() egressapp.SubscriptionSourceInput {
|
||||
func newSourceResponse(value egressdomain.PublicSubscriptionSource) sourceResponse {
|
||||
return sourceResponse{
|
||||
ID: value.ID, Name: value.Name, Scope: string(value.Scope), Enabled: value.Enabled, URLConfigured: value.URLConfigured,
|
||||
ProxyConfigured: value.ProxyConfigured,
|
||||
RefreshIntervalSeconds: value.RefreshIntervalSeconds, DefaultAccountCapacity: value.DefaultAccountCapacity,
|
||||
LastSyncedAt: value.LastSyncedAt, NextSyncAt: value.NextSyncAt, LastSyncImported: value.LastSyncImported, LastSyncError: value.LastSyncError,
|
||||
}
|
||||
@@ -920,8 +916,7 @@ func newOperationsConfigResponse(value egressdomain.OperationsConfig) operations
|
||||
return operationsConfigResponse{
|
||||
ProbeProvider: string(value.ProbeProvider.Normalized()), ProbeIntervalSeconds: value.ProbeIntervalSeconds, AutoAssignEnabled: value.AutoAssignEnabled,
|
||||
AutoBalanceEnabled: value.AutoBalanceEnabled, AssignmentIntervalSeconds: value.AssignmentIntervalSeconds,
|
||||
SubscriptionProxyConfigured: value.EncryptedSubscriptionProxyURL != "",
|
||||
Fallbacks: fallbacks, UpdatedAt: value.UpdatedAt,
|
||||
Fallbacks: fallbacks, UpdatedAt: value.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -281,16 +281,3 @@ func TestOperationsConfigRequestRejectsInvalidFallbackNodeID(t *testing.T) {
|
||||
t.Fatalf("invalid node ID error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperationsConfigResponseReportsSubscriptionProxyWithoutExposingIt(t *testing.T) {
|
||||
response := newOperationsConfigResponse(egressdomain.OperationsConfig{
|
||||
ProbeProvider: egressdomain.ProbeProviderCloudflare,
|
||||
EncryptedSubscriptionProxyURL: "encrypted-secret-must-not-be-returned",
|
||||
})
|
||||
if !response.SubscriptionProxyConfigured {
|
||||
t.Fatal("configured subscription proxy was not reported")
|
||||
}
|
||||
if response.ProbeProvider != "cloudflare" {
|
||||
t.Fatalf("probe provider=%q", response.ProbeProvider)
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
clientkeydomain "github.com/chenyme/grok2api/backend/internal/domain/clientkey"
|
||||
mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media"
|
||||
modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/neterror"
|
||||
"github.com/chenyme/grok2api/backend/internal/transport/http/middleware"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -88,8 +89,20 @@ func (h *Handler) Register(router *gin.RouterGroup) {
|
||||
router.POST("/images/generations", h.generateImage)
|
||||
router.POST("/images/edits", h.editImage)
|
||||
router.POST("/videos/generations", h.generateVideo)
|
||||
router.POST("/videos/edits", h.editVideo)
|
||||
router.POST("/videos/extensions", h.extendVideo)
|
||||
router.GET("/videos/:requestId", h.getVideo)
|
||||
router.GET("/videos/:requestId/content", h.getVideoContent)
|
||||
router.POST("/tts", h.synthesizeSpeech)
|
||||
router.GET("/tts/voices", h.listTTSVoices)
|
||||
router.GET("/tts/voices/:voiceId", h.getTTSVoice)
|
||||
router.POST("/stt", h.transcribeSpeech)
|
||||
router.GET("/stt", h.proxySTTWebSocket)
|
||||
// OpenAI-compatible audio aliases for common client SDKs.
|
||||
router.POST("/audio/speech", h.synthesizeOpenAISpeech)
|
||||
router.POST("/audio/tasks", h.synthesizeOpenAIAudioTask)
|
||||
router.POST("/audio/transcriptions", h.transcribeOpenAIAudio)
|
||||
router.GET("/realtime", h.proxyRealtimeWebSocket)
|
||||
router.POST("/responses/compact", h.compactResponse)
|
||||
router.GET("/responses/:responseId", h.getResponse)
|
||||
router.DELETE("/responses/:responseId", h.deleteResponse)
|
||||
@@ -124,6 +137,7 @@ type imageGenerationRequest struct {
|
||||
Size string `json:"size"`
|
||||
AspectRatio string `json:"aspect_ratio"`
|
||||
Resolution string `json:"resolution"`
|
||||
Quality string `json:"quality"`
|
||||
ResponseFormat string `json:"response_format"`
|
||||
StorageOptions json.RawMessage `json:"storage_options"`
|
||||
Stream bool `json:"stream"`
|
||||
@@ -143,6 +157,7 @@ type imageEditJSONRequest struct {
|
||||
Size string `json:"size"`
|
||||
AspectRatio string `json:"aspect_ratio"`
|
||||
Resolution string `json:"resolution"`
|
||||
Quality string `json:"quality"`
|
||||
ResponseFormat string `json:"response_format"`
|
||||
StorageOptions json.RawMessage `json:"storage_options"`
|
||||
Stream bool `json:"stream"`
|
||||
@@ -154,6 +169,10 @@ type videoGenerationImage struct {
|
||||
FileID string `json:"file_id"`
|
||||
}
|
||||
|
||||
type videoGenerationAudio struct {
|
||||
VoiceID string `json:"voice_id"`
|
||||
}
|
||||
|
||||
type videoGenerationRequest struct {
|
||||
Model string `json:"model"`
|
||||
Prompt string `json:"prompt"`
|
||||
@@ -163,6 +182,8 @@ type videoGenerationRequest struct {
|
||||
Resolution string `json:"resolution"`
|
||||
Image *videoGenerationImage `json:"image"`
|
||||
ReferenceImages []videoGenerationImage `json:"reference_images"`
|
||||
ReferenceAudios []videoGenerationAudio `json:"reference_audios"`
|
||||
Video *videoGenerationImage `json:"video"`
|
||||
Output json.RawMessage `json:"output"`
|
||||
StorageOptions json.RawMessage `json:"storage_options"`
|
||||
}
|
||||
@@ -392,6 +413,11 @@ func (h *Handler) generateImage(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
quality := strings.ToLower(strings.TrimSpace(request.Quality))
|
||||
if quality != "" && quality != "low" && quality != "medium" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", "quality 必须是 low 或 medium")
|
||||
return
|
||||
}
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
@@ -399,7 +425,7 @@ func (h *Handler) generateImage(c *gin.Context) {
|
||||
result, err := h.gateway.GenerateImage(c.Request.Context(), gateway.ImageGenerationInput{
|
||||
RequestID: requestID, ClientKey: clientKey, PublicModel: request.Model, Prompt: request.Prompt,
|
||||
Count: count, Size: request.Size, AspectRatio: request.AspectRatio,
|
||||
Resolution: request.Resolution, ResponseFormat: request.ResponseFormat,
|
||||
Resolution: request.Resolution, Quality: quality, ResponseFormat: request.ResponseFormat,
|
||||
Streaming: request.Stream, PartialImages: partialImages,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -419,20 +445,30 @@ func (h *Handler) writeMediaResult(c *gin.Context, result *gateway.Result) {
|
||||
writeOpenAIError(c, http.StatusServiceUnavailable, clientCode, credentialErrorMessage(clientCode))
|
||||
return
|
||||
}
|
||||
if result.StatusCode < http.StatusOK || (result.StatusCode >= http.StatusMultipleChoices && result.StatusCode < http.StatusBadRequest) {
|
||||
errorCode = "invalid_upstream_status"
|
||||
writeOpenAIError(c, http.StatusBadGateway, "invalid_upstream_response", "上游媒体服务返回了不安全的重定向响应")
|
||||
return
|
||||
}
|
||||
contentType, safeContentType := normalizeMediaResponseContentType(result.Header.Get("Content-Type"))
|
||||
if !safeContentType {
|
||||
errorCode = "unsafe_media_content_type"
|
||||
writeOpenAIError(c, http.StatusBadGateway, "invalid_media_type", "上游媒体服务返回了不受支持的内容类型")
|
||||
return
|
||||
}
|
||||
contentLength, contentLengthErr := strconv.ParseInt(result.Header.Get("Content-Length"), 10, 64)
|
||||
if contentLengthErr == nil && contentLength > maxMediaResponseTransferBytes {
|
||||
errorCode = "response_too_large"
|
||||
writeOpenAIError(c, http.StatusBadGateway, "media_too_large", "上游媒体超过 2 GiB 安全上限")
|
||||
return
|
||||
}
|
||||
copyHeaders(c.Writer.Header(), result.Header)
|
||||
setSafeMediaResponseHeaders(c, result.Header)
|
||||
if contentLengthErr == nil && contentLength >= 0 {
|
||||
c.Header("Content-Length", strconv.FormatInt(contentLength, 10))
|
||||
} else {
|
||||
c.Header("Trailer", mediaTransferErrorTrailer)
|
||||
}
|
||||
c.Status(result.StatusCode)
|
||||
if err := copyMedia(responseDeadlineWriter{ResponseWriter: c.Writer}, result.Body, maxMediaResponseTransferBytes); err != nil {
|
||||
if err := writeMediaBody(c, result.Body, contentType, result.StatusCode, maxMediaResponseTransferBytes); err != nil {
|
||||
if errors.Is(err, errResponseTransferLimit) {
|
||||
errorCode = "response_too_large"
|
||||
} else {
|
||||
@@ -444,13 +480,39 @@ func (h *Handler) writeMediaResult(c *gin.Context, result *gateway.Result) {
|
||||
}
|
||||
}
|
||||
|
||||
type responseDeadlineWriter struct{ http.ResponseWriter }
|
||||
func normalizeMediaResponseContentType(value string) (string, bool) {
|
||||
mediaType, _, err := mime.ParseMediaType(strings.TrimSpace(value))
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
mediaType = strings.ToLower(mediaType)
|
||||
switch mediaType {
|
||||
case "application/json":
|
||||
return "application/json; charset=utf-8", true
|
||||
case "text/plain":
|
||||
return "text/plain; charset=utf-8", true
|
||||
case "application/ogg":
|
||||
return mediaType, true
|
||||
}
|
||||
if strings.HasPrefix(mediaType, "audio/") {
|
||||
switch mediaType {
|
||||
case "audio/aac", "audio/flac", "audio/l16", "audio/mpeg", "audio/mp3", "audio/ogg", "audio/opus", "audio/pcm", "audio/wav", "audio/webm", "audio/x-flac", "audio/x-wav":
|
||||
return mediaType, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func (w responseDeadlineWriter) Write(payload []byte) (int, error) {
|
||||
if err := setResponseWriteDeadline(w.ResponseWriter); err != nil {
|
||||
return 0, err
|
||||
func setSafeMediaResponseHeaders(c *gin.Context, upstream http.Header) {
|
||||
c.Header("Cache-Control", "private, no-store")
|
||||
c.Header("X-Content-Type-Options", "nosniff")
|
||||
c.Header("Content-Security-Policy", "default-src 'none'; sandbox")
|
||||
c.Header("Referrer-Policy", "no-referrer")
|
||||
for _, name := range []string{"Retry-After", "X-Request-Id"} {
|
||||
if value := strings.TrimSpace(upstream.Get(name)); value != "" {
|
||||
c.Header(name, value)
|
||||
}
|
||||
}
|
||||
return w.ResponseWriter.Write(payload)
|
||||
}
|
||||
|
||||
func setResponseWriteDeadline(writer http.ResponseWriter) error {
|
||||
@@ -461,7 +523,11 @@ func setResponseWriteDeadline(writer http.ResponseWriter) error {
|
||||
return err
|
||||
}
|
||||
|
||||
func copyMedia(writer io.Writer, source io.Reader, limit int64) error {
|
||||
// writeMediaBody binds the validated non-HTML content type before emitting the
|
||||
// response body, so no caller can stream media bytes without their MIME context.
|
||||
func writeMediaBody(c *gin.Context, source io.Reader, contentType string, statusCode int, limit int64) error {
|
||||
c.Header("Content-Type", contentType)
|
||||
c.Status(statusCode)
|
||||
buffer := make([]byte, 64<<10)
|
||||
var transferred int64
|
||||
for {
|
||||
@@ -475,7 +541,10 @@ func copyMedia(writer io.Writer, source io.Reader, limit int64) error {
|
||||
if int64(writeSize) > remaining {
|
||||
writeSize = int(remaining)
|
||||
}
|
||||
written, writeErr := writer.Write(buffer[:writeSize])
|
||||
if err := setResponseWriteDeadline(c.Writer); err != nil {
|
||||
return err
|
||||
}
|
||||
written, writeErr := c.Writer.Write(buffer[:writeSize])
|
||||
transferred += int64(written)
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
@@ -577,6 +646,11 @@ func (h *Handler) editImage(c *gin.Context) {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", "resolution 必须是 1k 或 2k")
|
||||
return
|
||||
}
|
||||
quality := strings.ToLower(strings.TrimSpace(request.Quality))
|
||||
if quality != "" && quality != "low" && quality != "medium" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", "quality 必须是 low 或 medium")
|
||||
return
|
||||
}
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
@@ -584,7 +658,7 @@ func (h *Handler) editImage(c *gin.Context) {
|
||||
result, err := h.gateway.EditImage(c.Request.Context(), gateway.ImageEditInput{
|
||||
RequestID: requestID, ClientKey: clientKey, PublicModel: model, Prompt: prompt,
|
||||
ImageURLs: imageURLs, Count: count, Size: size, AspectRatio: aspectRatio,
|
||||
Resolution: resolution, ResponseFormat: request.ResponseFormat,
|
||||
Resolution: resolution, Quality: quality, ResponseFormat: request.ResponseFormat,
|
||||
Streaming: request.Stream, PartialImages: partialImages,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -607,14 +681,32 @@ func requestIdentity(c *gin.Context) (clientkeydomain.Key, string, bool) {
|
||||
}
|
||||
|
||||
func (h *Handler) generateVideo(c *gin.Context) {
|
||||
h.handleVideoCreate(c, gatewayVideoOperationGenerate, "视频生成")
|
||||
}
|
||||
|
||||
func (h *Handler) editVideo(c *gin.Context) {
|
||||
h.handleVideoCreate(c, gatewayVideoOperationEdit, "视频编辑")
|
||||
}
|
||||
|
||||
func (h *Handler) extendVideo(c *gin.Context) {
|
||||
h.handleVideoCreate(c, gatewayVideoOperationExtend, "视频延长")
|
||||
}
|
||||
|
||||
const (
|
||||
gatewayVideoOperationGenerate = "generate"
|
||||
gatewayVideoOperationEdit = "edit"
|
||||
gatewayVideoOperationExtend = "extend"
|
||||
)
|
||||
|
||||
func (h *Handler) handleVideoCreate(c *gin.Context, operation, label string) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes)
|
||||
if !isJSONRequest(c) {
|
||||
writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "视频生成仅支持 application/json")
|
||||
writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", label+"仅支持 application/json")
|
||||
return
|
||||
}
|
||||
var request videoGenerationRequest
|
||||
if err := decodeSingleJSON(c.Request.Body, &request, true); err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "视频生成 JSON 请求无效: "+err.Error())
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", label+" JSON 请求无效: "+err.Error())
|
||||
return
|
||||
}
|
||||
if hasJSONValue(request.Output) {
|
||||
@@ -625,71 +717,179 @@ func (h *Handler) generateVideo(c *gin.Context) {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "unsupported_parameter", "当前兼容层暂不支持 storage_options")
|
||||
return
|
||||
}
|
||||
duration, err := parseVideoDuration(request.Duration)
|
||||
if err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
model := strings.TrimSpace(request.Model)
|
||||
prompt := strings.TrimSpace(request.Prompt)
|
||||
if model == "" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "视频生成缺少有效 model")
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", label+"缺少有效 model")
|
||||
return
|
||||
}
|
||||
aspectRatio := strings.TrimSpace(request.AspectRatio)
|
||||
if aspectRatio == "" {
|
||||
aspectRatio = "16:9"
|
||||
}
|
||||
if !validVideoAspectRatio(aspectRatio) {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "aspect_ratio 必须是 1:1、16:9、9:16、4:3、3:4、3:2 或 2:3")
|
||||
return
|
||||
}
|
||||
resolution := strings.ToLower(strings.TrimSpace(request.Resolution))
|
||||
if resolution == "" {
|
||||
resolution = "720p"
|
||||
}
|
||||
if resolution != "480p" && resolution != "720p" && resolution != "1080p" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "resolution 必须是 480p、720p 或 1080p")
|
||||
return
|
||||
}
|
||||
inputs := append([]videoGenerationImage(nil), request.ReferenceImages...)
|
||||
if request.Image != nil {
|
||||
inputs = append([]videoGenerationImage{*request.Image}, inputs...)
|
||||
}
|
||||
if len(inputs) > mediadomain.MaxInputImages {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", fmt.Sprintf("image 与 reference_images 合计不能超过 %d 张", mediadomain.MaxInputImages))
|
||||
return
|
||||
}
|
||||
referenceURLs := make([]string, 0, len(inputs))
|
||||
for _, input := range inputs {
|
||||
parseVideoImage := func(input videoGenerationImage, field string) (string, bool) {
|
||||
urlValue := strings.TrimSpace(input.URL)
|
||||
fileID := strings.TrimSpace(input.FileID)
|
||||
if (urlValue == "") == (fileID == "") {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "每个 image 必须且只能提供 url 或 file_id")
|
||||
return
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", field+" 必须且只能提供 url 或 file_id")
|
||||
return "", false
|
||||
}
|
||||
if fileID != "" {
|
||||
if !mediadomain.IsInputAssetID(fileID) {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "image.file_id 无效")
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", field+".file_id 无效")
|
||||
return "", false
|
||||
}
|
||||
return gateway.VideoInputFileReference(fileID), true
|
||||
}
|
||||
return urlValue, true
|
||||
}
|
||||
|
||||
duration := 0
|
||||
aspectRatio := ""
|
||||
resolution := ""
|
||||
imageURL := ""
|
||||
referenceURLs := []string{}
|
||||
referenceAudios := []string{}
|
||||
videoURL := ""
|
||||
|
||||
if operation == gatewayVideoOperationGenerate {
|
||||
var err error
|
||||
duration, err = parseVideoDuration(request.Duration)
|
||||
if err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
aspectRatio = strings.TrimSpace(request.AspectRatio)
|
||||
if aspectRatio == "" {
|
||||
aspectRatio = "16:9"
|
||||
}
|
||||
if !validVideoAspectRatio(aspectRatio) {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "aspect_ratio 必须是 1:1、16:9、9:16、4:3、3:4、3:2 或 2:3")
|
||||
return
|
||||
}
|
||||
resolution = strings.ToLower(strings.TrimSpace(request.Resolution))
|
||||
if resolution == "" {
|
||||
resolution = "720p"
|
||||
}
|
||||
if resolution != "480p" && resolution != "720p" && resolution != "1080p" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "resolution 必须是 480p、720p 或 1080p")
|
||||
return
|
||||
}
|
||||
if request.Image != nil {
|
||||
value, ok := parseVideoImage(*request.Image, "image")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
imageURL = value
|
||||
}
|
||||
referenceURLs = make([]string, 0, len(request.ReferenceImages))
|
||||
for _, input := range request.ReferenceImages {
|
||||
value, ok := parseVideoImage(input, "reference_images")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
referenceURLs = append(referenceURLs, value)
|
||||
}
|
||||
referenceAudios = make([]string, 0, len(request.ReferenceAudios))
|
||||
for i, input := range request.ReferenceAudios {
|
||||
voiceID := strings.TrimSpace(input.VoiceID)
|
||||
if voiceID == "" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", fmt.Sprintf("reference_audios[%d].voice_id 不能为空", i))
|
||||
return
|
||||
}
|
||||
referenceAudios = append(referenceAudios, voiceID)
|
||||
}
|
||||
if len(referenceAudios) > 3 {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "reference_audios 最多 3 个")
|
||||
return
|
||||
}
|
||||
if imageURL != "" && (len(referenceURLs) > 0 || len(referenceAudios) > 0) {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "image 不能与 reference_images/reference_audios 同时使用")
|
||||
return
|
||||
}
|
||||
if len(referenceURLs) > mediadomain.MaxInputImages {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", fmt.Sprintf("reference_images 不能超过 %d 张", mediadomain.MaxInputImages))
|
||||
return
|
||||
}
|
||||
hasReferenceMode := len(referenceURLs) > 0 || len(referenceAudios) > 0
|
||||
if hasReferenceMode {
|
||||
if prompt == "" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "参考图/参考音频视频必须提供 prompt")
|
||||
return
|
||||
}
|
||||
if resolution == "1080p" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "参考图视频 resolution 最高 720p")
|
||||
return
|
||||
}
|
||||
}
|
||||
if prompt == "" && imageURL == "" && !hasReferenceMode {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "文本生视频必须提供 prompt;图片生视频可以省略 prompt")
|
||||
return
|
||||
}
|
||||
if request.Video != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "视频生成不支持 video 输入")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if prompt == "" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", label+"必须提供 prompt")
|
||||
return
|
||||
}
|
||||
if request.Video == nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", label+"必须提供 video")
|
||||
return
|
||||
}
|
||||
value, ok := parseVideoImage(*request.Video, "video")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
videoURL = value
|
||||
if request.Image != nil || len(request.ReferenceImages) > 0 || len(request.ReferenceAudios) > 0 {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", label+"不支持 image、reference_images 或 reference_audios")
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(request.AspectRatio) != "" || strings.TrimSpace(request.Resolution) != "" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", label+"不支持 aspect_ratio 或 resolution")
|
||||
return
|
||||
}
|
||||
if operation == gatewayVideoOperationEdit {
|
||||
if hasJSONValue(request.Duration) {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "视频编辑不支持 duration")
|
||||
return
|
||||
}
|
||||
referenceURLs = append(referenceURLs, gateway.VideoInputFileReference(fileID))
|
||||
} else {
|
||||
referenceURLs = append(referenceURLs, urlValue)
|
||||
// extend: duration optional, default 6, range 2-10
|
||||
if hasJSONValue(request.Duration) {
|
||||
var err error
|
||||
duration, err = parseVideoDuration(request.Duration)
|
||||
if err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
} else {
|
||||
duration = 6
|
||||
}
|
||||
if duration < 2 || duration > 10 {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "视频延长 duration 必须在 2 到 10 秒之间")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if prompt == "" && len(referenceURLs) == 0 {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "文本生视频必须提供 prompt;图片生视频可以省略 prompt")
|
||||
return
|
||||
}
|
||||
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var op provider.VideoOperation
|
||||
switch operation {
|
||||
case gatewayVideoOperationEdit:
|
||||
op = provider.VideoOperationEdit
|
||||
case gatewayVideoOperationExtend:
|
||||
op = provider.VideoOperationExtend
|
||||
default:
|
||||
op = provider.VideoOperationGenerate
|
||||
}
|
||||
job, err := h.gateway.CreateVideo(c.Request.Context(), gateway.VideoInput{
|
||||
RequestID: requestID, ClientKey: clientKey, PublicModel: model,
|
||||
Prompt: prompt, Duration: duration, AspectRatio: aspectRatio, Resolution: resolution,
|
||||
ReferenceURLs: referenceURLs,
|
||||
Operation: op,
|
||||
Prompt: prompt, Duration: duration, AspectRatio: aspectRatio, Resolution: resolution,
|
||||
ImageURL: imageURL, ReferenceURLs: referenceURLs, ReferenceAudios: referenceAudios, VideoURL: videoURL,
|
||||
})
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
@@ -742,17 +942,22 @@ func writeVideoContent(c *gin.Context, body io.Reader, contentType string, size
|
||||
writeOpenAIError(c, http.StatusBadGateway, "media_too_large", "上游媒体超过 2 GiB 安全上限")
|
||||
return
|
||||
}
|
||||
c.Header("Content-Type", contentType)
|
||||
contentType, ok := normalizeVideoResponseContentType(contentType)
|
||||
if !ok {
|
||||
writeOpenAIError(c, http.StatusBadGateway, "invalid_media_type", "上游视频服务返回了不受支持的内容类型")
|
||||
return
|
||||
}
|
||||
c.Header("Content-Disposition", "inline")
|
||||
c.Header("Cache-Control", "private, no-store")
|
||||
c.Header("X-Content-Type-Options", "nosniff")
|
||||
c.Header("Content-Security-Policy", "default-src 'none'; sandbox")
|
||||
c.Header("Referrer-Policy", "no-referrer")
|
||||
if size >= 0 {
|
||||
c.Header("Content-Length", strconv.FormatInt(size, 10))
|
||||
} else {
|
||||
c.Header("Trailer", mediaTransferErrorTrailer)
|
||||
}
|
||||
c.Status(http.StatusOK)
|
||||
if err := copyMedia(responseDeadlineWriter{ResponseWriter: c.Writer}, body, maxMediaResponseTransferBytes); err != nil && size < 0 {
|
||||
if err := writeMediaBody(c, body, contentType, http.StatusOK, maxMediaResponseTransferBytes); err != nil && size < 0 {
|
||||
errorCode := "stream_interrupted"
|
||||
if errors.Is(err, errResponseTransferLimit) {
|
||||
errorCode = "response_too_large"
|
||||
@@ -761,6 +966,19 @@ func writeVideoContent(c *gin.Context, body io.Reader, contentType string, size
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeVideoResponseContentType(value string) (string, bool) {
|
||||
mediaType, _, err := mime.ParseMediaType(strings.TrimSpace(value))
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
switch strings.ToLower(mediaType) {
|
||||
case "video/mp4", "video/quicktime", "video/webm":
|
||||
return strings.ToLower(mediaType), true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
func parseVideoDuration(durationRaw json.RawMessage) (int, error) {
|
||||
duration, hasDuration, err := parseOptionalVideoInteger(durationRaw)
|
||||
if err != nil {
|
||||
@@ -834,9 +1052,17 @@ func videoGenerationResponse(job mediadomain.Job, contentURLs ...string) gin.H {
|
||||
if len(contentURLs) > 0 && contentURLs[0] != "" {
|
||||
videoURL = contentURLs[0]
|
||||
}
|
||||
video := gin.H{"url": videoURL, "respect_moderation": true}
|
||||
operation := job.Operation
|
||||
if operation == "" {
|
||||
operation = mediadomain.VideoOperationGenerate
|
||||
}
|
||||
if operation == mediadomain.VideoOperationGenerate && job.Seconds > 0 {
|
||||
video["duration"] = job.Seconds
|
||||
}
|
||||
return gin.H{
|
||||
"status": "done", "model": job.Model, "progress": 100,
|
||||
"video": gin.H{"url": videoURL, "duration": job.Seconds, "respect_moderation": true},
|
||||
"video": video,
|
||||
}
|
||||
case mediadomain.StatusFailed:
|
||||
return gin.H{
|
||||
@@ -1687,6 +1913,9 @@ func writeGatewayError(c *gin.Context, err error) {
|
||||
case errors.Is(err, gateway.ErrVideoInputTooLarge), errors.Is(err, gateway.ErrVideoInputUnavailable):
|
||||
status, code = http.StatusBadRequest, "invalid_request"
|
||||
message = err.Error()
|
||||
case errors.Is(err, gateway.ErrVideoOperationUnsupported):
|
||||
status, code = http.StatusBadRequest, "unsupported_model"
|
||||
message = err.Error()
|
||||
case errors.As(err, &upstreamFailure):
|
||||
if isSanitizedUpstreamAvailabilityFailure(upstreamFailure) {
|
||||
// Gateway mid-tier behavior: never expose upstream upgrade/billing prompts to clients.
|
||||
|
||||
@@ -344,6 +344,85 @@ func TestDirectUpstreamCredentialResponsesAreRewritten(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaResultRejectsActiveContentAndRedirects(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := NewHandler(nil, nil, 1<<20)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
status int
|
||||
contentType string
|
||||
headers http.Header
|
||||
}{
|
||||
{name: "html", status: http.StatusOK, contentType: "text/html; charset=utf-8"},
|
||||
{name: "svg", status: http.StatusOK, contentType: "image/svg+xml"},
|
||||
{name: "redirect", status: http.StatusFound, contentType: "text/plain", headers: http.Header{"Location": {"javascript:alert(1)"}}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
finalCode := ""
|
||||
header := make(http.Header)
|
||||
for name, values := range tc.headers {
|
||||
header[name] = append([]string(nil), values...)
|
||||
}
|
||||
header.Set("Content-Type", tc.contentType)
|
||||
result := &gateway.Result{
|
||||
StatusCode: tc.status,
|
||||
Header: header,
|
||||
Body: io.NopCloser(strings.NewReader(`<script id="must-not-reflect">alert(1)</script>`)),
|
||||
Finalize: func(_ gateway.Usage, _, code string) {
|
||||
finalCode = code
|
||||
},
|
||||
}
|
||||
router := gin.New()
|
||||
router.GET("/", func(c *gin.Context) { handler.writeMediaResult(c, result) })
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
if recorder.Code != http.StatusBadGateway || strings.Contains(recorder.Body.String(), "must-not-reflect") || recorder.Header().Get("Location") != "" || finalCode == "" {
|
||||
t.Fatalf("status=%d headers=%#v body=%s finalize=%q", recorder.Code, recorder.Header(), recorder.Body.String(), finalCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaResultPinsSafeResponseHeaders(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := NewHandler(nil, nil, 1<<20)
|
||||
result := &gateway.Result{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{
|
||||
"Content-Type": {"audio/mpeg; attacker=ignored"},
|
||||
"Content-Length": {"5"},
|
||||
"Set-Cookie": {"upstream=secret"},
|
||||
"Location": {"javascript:alert(1)"},
|
||||
"X-Request-Id": {"upstream-request"},
|
||||
},
|
||||
Body: io.NopCloser(strings.NewReader("audio")),
|
||||
Finalize: func(gateway.Usage, string, string) {},
|
||||
}
|
||||
router := gin.New()
|
||||
router.GET("/", func(c *gin.Context) { handler.writeMediaResult(c, result) })
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
if recorder.Code != http.StatusOK || recorder.Body.String() != "audio" {
|
||||
t.Fatalf("status=%d body=%q", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if recorder.Header().Get("Content-Type") != "audio/mpeg" || recorder.Header().Get("X-Content-Type-Options") != "nosniff" || recorder.Header().Get("Content-Security-Policy") == "" {
|
||||
t.Fatalf("safe headers = %#v", recorder.Header())
|
||||
}
|
||||
if recorder.Header().Get("Set-Cookie") != "" || recorder.Header().Get("Location") != "" || recorder.Header().Get("X-Request-Id") != "upstream-request" {
|
||||
t.Fatalf("unsafe or missing forwarded headers = %#v", recorder.Header())
|
||||
}
|
||||
}
|
||||
|
||||
func TestVideoContentRejectsUnsafeContentType(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
context, _ := gin.CreateTestContext(recorder)
|
||||
writeVideoContent(context, strings.NewReader(`<script id="must-not-reflect">alert(1)</script>`), "text/html", -1)
|
||||
if recorder.Code != http.StatusBadGateway || strings.Contains(recorder.Body.String(), "must-not-reflect") {
|
||||
t.Fatalf("status=%d headers=%#v body=%s", recorder.Code, recorder.Header(), recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessagesEndpointUsesAnthropicContract(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
@@ -428,6 +507,11 @@ func TestVideoGenerationResponseMatchesOfficialPollingShape(t *testing.T) {
|
||||
if done["status"] != "done" || done["progress"] != 100 || !ok || video["url"] != "https://assets.grok.com/video.mp4" || video["duration"] != 8 || video["respect_moderation"] != true {
|
||||
t.Fatalf("done response=%#v", done)
|
||||
}
|
||||
extended := videoGenerationResponse(mediadomain.Job{Operation: mediadomain.VideoOperationExtend, Status: mediadomain.StatusCompleted, Seconds: 6, UpstreamURL: "https://assets.grok.com/extended.mp4"})
|
||||
extendedVideo, ok := extended["video"].(gin.H)
|
||||
if !ok || extendedVideo["duration"] != nil {
|
||||
t.Fatalf("extended response exposes requested extension as output duration: %#v", extended)
|
||||
}
|
||||
failed := videoGenerationResponse(mediadomain.Job{Status: mediadomain.StatusFailed, ErrorCode: "account_unavailable", ErrorMessage: "try later"})
|
||||
errorValue, ok := failed["error"].(gin.H)
|
||||
if failed["status"] != "failed" || !ok || errorValue["code"] != "service_unavailable" || failed["model"] != nil || failed["progress"] != nil {
|
||||
@@ -447,6 +531,7 @@ func TestImageGenerationEndpointValidatesXAIContractBeforeRouting(t *testing.T)
|
||||
}{
|
||||
{name: "zero n", body: `{"model":"grok-imagine-image","prompt":"test","n":0}`, want: "n 必须在 1 到 10 之间"},
|
||||
{name: "large n", body: `{"model":"grok-imagine-image","prompt":"test","n":11}`, want: "n 必须在 1 到 10 之间"},
|
||||
{name: "invalid quality", body: `{"model":"grok-imagine-image-2.0","prompt":"test","quality":"high"}`, want: "quality 必须是 low 或 medium"},
|
||||
{name: "storage options", body: `{"model":"grok-imagine-image","prompt":"test","storage_options":{"filename":"test.jpg"}}`, want: "不支持 storage_options"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
@@ -505,6 +590,17 @@ func TestImageEditAcceptsOfficialJSONShape(t *testing.T) {
|
||||
t.Fatalf("invalid resolution status=%d body=%s", invalidResolutionRecorder.Code, invalidResolutionRecorder.Body.String())
|
||||
}
|
||||
|
||||
invalidQuality := httptest.NewRequest(http.MethodPost, "/v1/images/edits", strings.NewReader(`{
|
||||
"model":"grok-imagine-image-2.0","prompt":"test","quality":"high",
|
||||
"image":{"url":"https://example.com/input.png"}
|
||||
}`))
|
||||
invalidQuality.Header.Set("Content-Type", "application/json")
|
||||
invalidQualityRecorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(invalidQualityRecorder, invalidQuality)
|
||||
if invalidQualityRecorder.Code != http.StatusBadRequest || !strings.Contains(invalidQualityRecorder.Body.String(), "quality 必须是 low 或 medium") {
|
||||
t.Fatalf("invalid quality status=%d body=%s", invalidQualityRecorder.Code, invalidQualityRecorder.Body.String())
|
||||
}
|
||||
|
||||
validBatchCount := httptest.NewRequest(http.MethodPost, "/v1/images/edits", strings.NewReader(`{
|
||||
"model":"grok-imagine-image-quality","prompt":"test","n":2,
|
||||
"image":{"url":"https://example.com/input.png"}
|
||||
@@ -982,24 +1078,29 @@ func TestCopyJSONForwardsBodyBeyondMetadataInspectionLimit(t *testing.T) {
|
||||
|
||||
func TestCopyMediaRejectsUnknownLengthOverflowWithoutWritingPastLimit(t *testing.T) {
|
||||
payload := bytes.Repeat([]byte("v"), 33)
|
||||
var destination bytes.Buffer
|
||||
err := copyMedia(&destination, bytes.NewReader(payload), 32)
|
||||
recorder := httptest.NewRecorder()
|
||||
context, _ := gin.CreateTestContext(recorder)
|
||||
err := writeMediaBody(context, bytes.NewReader(payload), "video/mp4", http.StatusOK, 32)
|
||||
if !errors.Is(err, errResponseTransferLimit) {
|
||||
t.Fatalf("copy error = %v", err)
|
||||
}
|
||||
if destination.Len() != 32 {
|
||||
t.Fatalf("forwarded media size = %d", destination.Len())
|
||||
if recorder.Body.Len() != 32 {
|
||||
t.Fatalf("forwarded media size = %d", recorder.Body.Len())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyMediaAllowsExactLimit(t *testing.T) {
|
||||
payload := bytes.Repeat([]byte("v"), 32)
|
||||
var destination bytes.Buffer
|
||||
if err := copyMedia(&destination, bytes.NewReader(payload), 32); err != nil {
|
||||
recorder := httptest.NewRecorder()
|
||||
context, _ := gin.CreateTestContext(recorder)
|
||||
if err := writeMediaBody(context, bytes.NewReader(payload), "video/mp4", http.StatusOK, 32); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(destination.Bytes(), payload) {
|
||||
t.Fatalf("forwarded media = %q", destination.Bytes())
|
||||
if !bytes.Equal(recorder.Body.Bytes(), payload) {
|
||||
t.Fatalf("forwarded media = %q", recorder.Body.Bytes())
|
||||
}
|
||||
if recorder.Header().Get("Content-Type") != "video/mp4" {
|
||||
t.Fatalf("content type = %q", recorder.Header().Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1027,3 +1128,91 @@ func TestSelectionErrorResponseDistinguishesCoolingAndSaturation(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReferenceToVideoRequestValidation(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := &Handler{maxBodyBytes: 1 << 20}
|
||||
router := gin.New()
|
||||
handler.Register(router.Group("/v1"))
|
||||
|
||||
combined := httptest.NewRequest(http.MethodPost, "/v1/videos/generations", strings.NewReader(`{
|
||||
"model":"grok-imagine-video","prompt":"x",
|
||||
"image":{"url":"https://example.com/a.png"},
|
||||
"reference_images":[{"url":"https://example.com/b.png"}]
|
||||
}`))
|
||||
combined.Header.Set("Content-Type", "application/json")
|
||||
combinedRec := httptest.NewRecorder()
|
||||
router.ServeHTTP(combinedRec, combined)
|
||||
if combinedRec.Code != http.StatusBadRequest || !strings.Contains(combinedRec.Body.String(), "不能与") {
|
||||
t.Fatalf("combined image+refs status=%d body=%s", combinedRec.Code, combinedRec.Body.String())
|
||||
}
|
||||
|
||||
highRes := httptest.NewRequest(http.MethodPost, "/v1/videos/generations", strings.NewReader(`{
|
||||
"model":"grok-imagine-video","prompt":"x","resolution":"1080p",
|
||||
"reference_images":[{"url":"https://example.com/b.png"}]
|
||||
}`))
|
||||
highRes.Header.Set("Content-Type", "application/json")
|
||||
highResRec := httptest.NewRecorder()
|
||||
router.ServeHTTP(highResRec, highRes)
|
||||
if highResRec.Code != http.StatusBadRequest || !strings.Contains(highResRec.Body.String(), "720p") {
|
||||
t.Fatalf("r2v 1080p status=%d body=%s", highResRec.Code, highResRec.Body.String())
|
||||
}
|
||||
|
||||
tooManyAudio := httptest.NewRequest(http.MethodPost, "/v1/videos/generations", strings.NewReader(`{
|
||||
"model":"grok-imagine-video","prompt":"x","duration":8,"resolution":"720p",
|
||||
"reference_audios":[{"voice_id":"eve"},{"voice_id":"ara"},{"voice_id":"rex"},{"voice_id":"sal"}]
|
||||
}`))
|
||||
tooManyAudio.Header.Set("Content-Type", "application/json")
|
||||
tooManyAudioRec := httptest.NewRecorder()
|
||||
router.ServeHTTP(tooManyAudioRec, tooManyAudio)
|
||||
if tooManyAudioRec.Code != http.StatusBadRequest || !strings.Contains(tooManyAudioRec.Body.String(), "最多 3") {
|
||||
t.Fatalf("too many audios status=%d body=%s", tooManyAudioRec.Code, tooManyAudioRec.Body.String())
|
||||
}
|
||||
|
||||
valid := httptest.NewRequest(http.MethodPost, "/v1/videos/generations", strings.NewReader(`{
|
||||
"model":"grok-imagine-video","prompt":"The person speaks","duration":8,
|
||||
"aspect_ratio":"9:16","resolution":"720p",
|
||||
"reference_images":[{"url":"https://example.com/p.png"}],
|
||||
"reference_audios":[{"voice_id":"eve"}]
|
||||
}`))
|
||||
valid.Header.Set("Content-Type", "application/json")
|
||||
validRec := httptest.NewRecorder()
|
||||
router.ServeHTTP(validRec, valid)
|
||||
if validRec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("valid r2v status=%d body=%s", validRec.Code, validRec.Body.String())
|
||||
}
|
||||
}
|
||||
func TestEditAndExtendVideoRequestValidation(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := &Handler{maxBodyBytes: 1 << 20}
|
||||
router := gin.New()
|
||||
group := router.Group("/v1")
|
||||
handler.Register(group)
|
||||
|
||||
// Model compatibility is resolved from the selected upstream route, not the
|
||||
// caller-controlled public model name.
|
||||
rec := httptest.NewRecorder()
|
||||
context, _ := gin.CreateTestContext(rec)
|
||||
writeGatewayError(context, gateway.ErrVideoOperationUnsupported)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("unsupported video route status = %d body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// missing video on extend
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/videos/extensions", strings.NewReader(`{"model":"grok-imagine-video","prompt":"x","duration":4}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec = httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("extend missing video status = %d body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// invalid extend duration
|
||||
req = httptest.NewRequest(http.MethodPost, "/v1/videos/extensions", strings.NewReader(`{"model":"grok-imagine-video","prompt":"x","duration":15,"video":{"url":"https://example.com/a.mp4"}}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec = httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("extend bad duration status = %d body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package inference
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/application/gateway"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// OpenAI-compatible audio request shapes.
|
||||
// https://platform.openai.com/docs/api-reference/audio
|
||||
type openAISpeechRequest struct {
|
||||
Model string `json:"model"`
|
||||
Input string `json:"input"`
|
||||
Voice string `json:"voice"`
|
||||
ResponseFormat string `json:"response_format"`
|
||||
Speed *float64 `json:"speed"`
|
||||
// Optional Grok/Console extensions accepted without breaking OpenAI clients.
|
||||
Language string `json:"language"`
|
||||
VoiceID string `json:"voice_id"`
|
||||
OutputFormat json.RawMessage `json:"output_format"`
|
||||
OptimizeStreamingLatency json.RawMessage `json:"optimize_streaming_latency"`
|
||||
TextNormalization *bool `json:"text_normalization"`
|
||||
WithTimestamps *bool `json:"with_timestamps"`
|
||||
}
|
||||
|
||||
func (h *Handler) synthesizeOpenAISpeech(c *gin.Context) {
|
||||
h.handleOpenAISpeech(c)
|
||||
}
|
||||
|
||||
// synthesizeOpenAIAudioTask keeps a compatibility path used by some OpenAI-style
|
||||
// clients that post speech jobs to /v1/audio/tasks instead of /v1/audio/speech.
|
||||
// Behavior matches /audio/speech: raw audio by default, JSON only when requested.
|
||||
func (h *Handler) synthesizeOpenAIAudioTask(c *gin.Context) {
|
||||
h.handleOpenAISpeech(c)
|
||||
}
|
||||
|
||||
func (h *Handler) handleOpenAISpeech(c *gin.Context) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes)
|
||||
if !isJSONRequest(c) {
|
||||
writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "audio speech 仅支持 application/json")
|
||||
return
|
||||
}
|
||||
var request openAISpeechRequest
|
||||
if err := decodeSingleJSON(c.Request.Body, &request, false); err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "audio speech 请求无效")
|
||||
return
|
||||
}
|
||||
|
||||
text := strings.TrimSpace(request.Input)
|
||||
if text == "" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "input 不能为空")
|
||||
return
|
||||
}
|
||||
language := strings.TrimSpace(request.Language)
|
||||
if language == "" {
|
||||
// Console TTS requires language; default keeps OpenAI clients working.
|
||||
language = "en"
|
||||
}
|
||||
model := strings.TrimSpace(request.Model)
|
||||
if model == "" {
|
||||
model = "grok-voice-latest"
|
||||
}
|
||||
voiceID := firstNonEmpty(strings.TrimSpace(request.VoiceID), strings.TrimSpace(request.Voice))
|
||||
if mapped := mapOpenAIVoiceID(voiceID); mapped != "" {
|
||||
voiceID = mapped
|
||||
}
|
||||
|
||||
format, err := parseTTSOutputFormat(request.OutputFormat)
|
||||
if err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", err.Error())
|
||||
return
|
||||
}
|
||||
if format.Codec == "" {
|
||||
if codec := mapOpenAIResponseFormat(request.ResponseFormat); codec != "" {
|
||||
format.Codec = codec
|
||||
} else if strings.TrimSpace(request.ResponseFormat) != "" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "response_format 不受支持")
|
||||
return
|
||||
} else {
|
||||
format.Codec = "mp3"
|
||||
}
|
||||
}
|
||||
|
||||
speed, err := parseTTSSpeed(request.Speed)
|
||||
if err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", err.Error())
|
||||
return
|
||||
}
|
||||
optimize, err := parseOptimizeStreamingLatency(request.OptimizeStreamingLatency)
|
||||
if err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
input := gateway.TTSInput{
|
||||
RequestID: requestID,
|
||||
ClientKey: clientKey,
|
||||
PublicModel: model,
|
||||
Text: text,
|
||||
VoiceID: voiceID,
|
||||
Language: language,
|
||||
OutputFormat: format,
|
||||
Speed: speed,
|
||||
OptimizeStreamingLatency: optimize,
|
||||
}
|
||||
if request.TextNormalization != nil {
|
||||
input.TextNormalization = *request.TextNormalization
|
||||
}
|
||||
if request.WithTimestamps != nil {
|
||||
input.WithTimestamps = *request.WithTimestamps
|
||||
}
|
||||
|
||||
result, err := h.gateway.SynthesizeSpeech(c.Request.Context(), input)
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) transcribeOpenAIAudio(c *gin.Context) {
|
||||
h.transcribeSpeechRequest(c, true)
|
||||
}
|
||||
|
||||
func mapOpenAIResponseFormat(value string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||
case "", "mp3":
|
||||
return "mp3"
|
||||
case "opus", "ogg":
|
||||
return "opus"
|
||||
case "aac":
|
||||
return "aac"
|
||||
case "flac":
|
||||
return "flac"
|
||||
case "wav", "wave":
|
||||
return "wav"
|
||||
case "pcm", "pcm16":
|
||||
return "pcm"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// mapOpenAIVoiceID keeps common OpenAI voice names usable against Console voices.
|
||||
// Unknown values pass through so custom voice_id and built-in Grok ids still work.
|
||||
func mapOpenAIVoiceID(voice string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(voice)) {
|
||||
case "alloy", "verse":
|
||||
return "ara"
|
||||
case "echo", "ballad":
|
||||
return "eve"
|
||||
case "fable", "coral":
|
||||
return "sal"
|
||||
case "onyx", "ash":
|
||||
return "rex"
|
||||
case "nova", "sage":
|
||||
return "leo"
|
||||
case "shimmer", "marin":
|
||||
return "sia"
|
||||
default:
|
||||
return strings.TrimSpace(voice)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package inference
|
||||
|
||||
import (
|
||||
"math"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestStreamingSTTDurationAcceptsOnlyCompletedFiniteEvents(t *testing.T) {
|
||||
duration, ok := streamingSTTDuration([]byte(`{"type":"transcript.done","duration":3.45,"text":"hello"}`))
|
||||
if !ok || math.Abs(duration-3.45) > 1e-9 {
|
||||
t.Fatalf("completed duration = %v, ok = %t", duration, ok)
|
||||
}
|
||||
for _, payload := range [][]byte{
|
||||
[]byte(`{"type":"transcript.delta","duration":3.45}`),
|
||||
[]byte(`{"type":"transcript.done","duration":0}`),
|
||||
[]byte(`{"type":"transcript.done","duration":"3.45"}`),
|
||||
[]byte(`not-json`),
|
||||
} {
|
||||
if duration, ok := streamingSTTDuration(payload); ok || duration != 0 {
|
||||
t.Fatalf("invalid payload %q produced duration %v, ok = %t", payload, duration, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIAudioSpeechValidatesAndMapsFields(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
NewHandler(nil, nil, 1<<20).Register(router.Group("/v1"))
|
||||
|
||||
missingInput := httptest.NewRequest(http.MethodPost, "/v1/audio/speech", strings.NewReader(`{"model":"grok-voice-latest","voice":"alloy"}`))
|
||||
missingInput.Header.Set("Content-Type", "application/json")
|
||||
missingRecorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(missingRecorder, missingInput)
|
||||
if missingRecorder.Code != http.StatusBadRequest || !strings.Contains(missingRecorder.Body.String(), "input") {
|
||||
t.Fatalf("missing input status=%d body=%s", missingRecorder.Code, missingRecorder.Body.String())
|
||||
}
|
||||
|
||||
badFormat := httptest.NewRequest(http.MethodPost, "/v1/audio/speech", strings.NewReader(`{"model":"grok-voice-latest","input":"hi","response_format":"midi"}`))
|
||||
badFormat.Header.Set("Content-Type", "application/json")
|
||||
badFormatRecorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(badFormatRecorder, badFormat)
|
||||
if badFormatRecorder.Code != http.StatusBadRequest || !strings.Contains(badFormatRecorder.Body.String(), "response_format") {
|
||||
t.Fatalf("bad format status=%d body=%s", badFormatRecorder.Code, badFormatRecorder.Body.String())
|
||||
}
|
||||
|
||||
// Reach auth after successful mapping/validation.
|
||||
valid := httptest.NewRequest(http.MethodPost, "/v1/audio/speech", strings.NewReader(`{
|
||||
"model":"grok-voice-latest","input":"Hello from OpenAI clients.","voice":"alloy","response_format":"mp3","speed":1.0
|
||||
}`))
|
||||
valid.Header.Set("Content-Type", "application/json")
|
||||
validRecorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(validRecorder, valid)
|
||||
if validRecorder.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("valid openai speech status=%d body=%s", validRecorder.Code, validRecorder.Body.String())
|
||||
}
|
||||
|
||||
task := httptest.NewRequest(http.MethodPost, "/v1/audio/tasks", strings.NewReader(`{
|
||||
"model":"grok-voice-latest","input":"Hello from OpenAI clients.","voice":"nova"
|
||||
}`))
|
||||
task.Header.Set("Content-Type", "application/json")
|
||||
taskRecorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(taskRecorder, task)
|
||||
if taskRecorder.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("valid openai audio task status=%d body=%s", taskRecorder.Code, taskRecorder.Body.String())
|
||||
}
|
||||
|
||||
transcription := httptest.NewRequest(http.MethodPost, "/v1/audio/transcriptions", strings.NewReader(`{"model":"grok-stt","url":"https://example.com/a.wav"}`))
|
||||
transcription.Header.Set("Content-Type", "application/json")
|
||||
transcriptionRecorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(transcriptionRecorder, transcription)
|
||||
if transcriptionRecorder.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("openai transcription status=%d body=%s", transcriptionRecorder.Code, transcriptionRecorder.Body.String())
|
||||
}
|
||||
|
||||
badTranscriptionFormat := httptest.NewRequest(http.MethodPost, "/v1/audio/transcriptions", strings.NewReader(`{"model":"grok-stt","url":"https://example.com/a.wav","response_format":"srt"}`))
|
||||
badTranscriptionFormat.Header.Set("Content-Type", "application/json")
|
||||
badTranscriptionRecorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(badTranscriptionRecorder, badTranscriptionFormat)
|
||||
if badTranscriptionRecorder.Code != http.StatusBadRequest || !strings.Contains(badTranscriptionRecorder.Body.String(), "response_format") {
|
||||
t.Fatalf("bad transcription format status=%d body=%s", badTranscriptionRecorder.Code, badTranscriptionRecorder.Body.String())
|
||||
}
|
||||
|
||||
unsupportedPrompt := httptest.NewRequest(http.MethodPost, "/v1/audio/transcriptions", strings.NewReader(`{"model":"grok-stt","url":"https://example.com/a.wav","prompt":"special spelling"}`))
|
||||
unsupportedPrompt.Header.Set("Content-Type", "application/json")
|
||||
unsupportedPromptRecorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(unsupportedPromptRecorder, unsupportedPrompt)
|
||||
if unsupportedPromptRecorder.Code != http.StatusBadRequest || !strings.Contains(unsupportedPromptRecorder.Body.String(), "prompt") {
|
||||
t.Fatalf("unsupported prompt status=%d body=%s", unsupportedPromptRecorder.Code, unsupportedPromptRecorder.Body.String())
|
||||
}
|
||||
|
||||
translation := httptest.NewRequest(http.MethodPost, "/v1/audio/translations", strings.NewReader(`{"model":"grok-stt","url":"https://example.com/a.wav"}`))
|
||||
translation.Header.Set("Content-Type", "application/json")
|
||||
translationRecorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(translationRecorder, translation)
|
||||
if translationRecorder.Code != http.StatusNotFound {
|
||||
t.Fatalf("unsupported translation status=%d body=%s", translationRecorder.Code, translationRecorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestTTSOptionValidationIsSharedByNativeAndOpenAIHandlers(t *testing.T) {
|
||||
if _, err := parseTTSSpeed(float64Pointer(0.2)); err == nil {
|
||||
t.Fatal("invalid speed was accepted")
|
||||
}
|
||||
if _, err := parseOptimizeStreamingLatency([]byte(`2.5`)); err == nil {
|
||||
t.Fatal("fractional optimize_streaming_latency was accepted")
|
||||
}
|
||||
if _, err := parseOptimizeStreamingLatency([]byte(`"invalid"`)); err == nil {
|
||||
t.Fatal("invalid optimize_streaming_latency was accepted")
|
||||
}
|
||||
if _, err := parseTTSOutputFormat([]byte(`{"codec":"mp3","sample_rate":0}`)); err == nil {
|
||||
t.Fatal("invalid sample rate was accepted")
|
||||
}
|
||||
if value, err := parseOptimizeStreamingLatency([]byte(`"4"`)); err != nil || value != 4 {
|
||||
t.Fatalf("valid optimize_streaming_latency = %d, %v", value, err)
|
||||
}
|
||||
}
|
||||
|
||||
func float64Pointer(value float64) *float64 { return &value }
|
||||
|
||||
func TestMapOpenAIVoiceAndFormat(t *testing.T) {
|
||||
if got := mapOpenAIVoiceID("alloy"); got != "ara" {
|
||||
t.Fatalf("alloy map = %q", got)
|
||||
}
|
||||
if got := mapOpenAIVoiceID("custom_voice_123"); got != "custom_voice_123" {
|
||||
t.Fatalf("passthrough map = %q", got)
|
||||
}
|
||||
if got := mapOpenAIResponseFormat("wav"); got != "wav" {
|
||||
t.Fatalf("wav map = %q", got)
|
||||
}
|
||||
if got := mapOpenAIResponseFormat("midi"); got != "" {
|
||||
t.Fatalf("midi map = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
package inference
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/application/gateway"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
"github.com/chenyme/grok2api/backend/internal/transport/http/middleware"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type ttsRequest struct {
|
||||
Model string `json:"model"`
|
||||
Text string `json:"text"`
|
||||
VoiceID string `json:"voice_id"`
|
||||
Language string `json:"language"`
|
||||
OutputFormat json.RawMessage `json:"output_format"`
|
||||
Speed *float64 `json:"speed"`
|
||||
OptimizeStreamingLatency json.RawMessage `json:"optimize_streaming_latency"`
|
||||
TextNormalization *bool `json:"text_normalization"`
|
||||
WithTimestamps *bool `json:"with_timestamps"`
|
||||
}
|
||||
|
||||
func (h *Handler) synthesizeSpeech(c *gin.Context) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes)
|
||||
if !isJSONRequest(c) {
|
||||
writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "TTS 仅支持 application/json")
|
||||
return
|
||||
}
|
||||
var request ttsRequest
|
||||
if err := decodeSingleJSON(c.Request.Body, &request, false); err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "TTS 请求无效")
|
||||
return
|
||||
}
|
||||
text := strings.TrimSpace(request.Text)
|
||||
language := strings.TrimSpace(request.Language)
|
||||
if text == "" || language == "" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "TTS 缺少有效 text 或 language")
|
||||
return
|
||||
}
|
||||
model := strings.TrimSpace(request.Model)
|
||||
if model == "" {
|
||||
model = "grok-voice-latest"
|
||||
}
|
||||
format, err := parseTTSOutputFormat(request.OutputFormat)
|
||||
if err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", err.Error())
|
||||
return
|
||||
}
|
||||
speed, err := parseTTSSpeed(request.Speed)
|
||||
if err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", err.Error())
|
||||
return
|
||||
}
|
||||
optimize, err := parseOptimizeStreamingLatency(request.OptimizeStreamingLatency)
|
||||
if err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", err.Error())
|
||||
return
|
||||
}
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
input := gateway.TTSInput{
|
||||
RequestID: requestID, ClientKey: clientKey, PublicModel: model, Text: text, VoiceID: strings.TrimSpace(request.VoiceID),
|
||||
Language: language, OutputFormat: format, Speed: speed, OptimizeStreamingLatency: optimize,
|
||||
}
|
||||
if request.TextNormalization != nil {
|
||||
input.TextNormalization = *request.TextNormalization
|
||||
}
|
||||
if request.WithTimestamps != nil {
|
||||
input.WithTimestamps = *request.WithTimestamps
|
||||
}
|
||||
result, err := h.gateway.SynthesizeSpeech(c.Request.Context(), input)
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) listTTSVoices(c *gin.Context) {
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
model := strings.TrimSpace(c.Query("model"))
|
||||
if model == "" {
|
||||
model = "grok-voice-latest"
|
||||
}
|
||||
result, err := h.gateway.ListTTSVoices(c.Request.Context(), gateway.VoiceListInput{RequestID: requestID, ClientKey: clientKey, PublicModel: model})
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) getTTSVoice(c *gin.Context) {
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
model := strings.TrimSpace(c.Query("model"))
|
||||
if model == "" {
|
||||
model = "grok-voice-latest"
|
||||
}
|
||||
result, err := h.gateway.GetTTSVoice(c.Request.Context(), gateway.VoiceIDInput{
|
||||
RequestID: requestID, ClientKey: clientKey, PublicModel: model, VoiceID: c.Param("voiceId"),
|
||||
})
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) transcribeSpeech(c *gin.Context) {
|
||||
h.transcribeSpeechRequest(c, false)
|
||||
}
|
||||
|
||||
func (h *Handler) transcribeSpeechRequest(c *gin.Context, openAICompatible bool) {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes)
|
||||
contentType := strings.ToLower(strings.TrimSpace(c.GetHeader("Content-Type")))
|
||||
input := gateway.STTInput{PublicModel: "grok-stt"}
|
||||
unsupportedOpenAIParameter := ""
|
||||
if strings.HasPrefix(contentType, "multipart/form-data") {
|
||||
if err := c.Request.ParseMultipartForm(h.maxBodyBytes); err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "STT multipart 请求无效")
|
||||
return
|
||||
}
|
||||
form := c.Request.MultipartForm
|
||||
get := func(name string) string {
|
||||
if form == nil {
|
||||
return ""
|
||||
}
|
||||
values := form.Value[name]
|
||||
if len(values) == 0 {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(values[0])
|
||||
}
|
||||
if model := get("model"); model != "" {
|
||||
input.PublicModel = model
|
||||
}
|
||||
input.URL = get("url")
|
||||
input.AudioFormat = get("audio_format")
|
||||
input.SampleRate = firstNonEmpty(get("sample_rate"), get("sample_rate_hertz"))
|
||||
input.Language = get("language")
|
||||
if openAICompatible {
|
||||
input.ResponseFormat = get("response_format")
|
||||
if get("prompt") != "" {
|
||||
unsupportedOpenAIParameter = "prompt"
|
||||
}
|
||||
if temperature := get("temperature"); temperature != "" && temperature != "0" && temperature != "0.0" {
|
||||
unsupportedOpenAIParameter = "temperature"
|
||||
}
|
||||
if form != nil && len(form.Value["timestamp_granularities[]"]) > 0 {
|
||||
unsupportedOpenAIParameter = "timestamp_granularities[]"
|
||||
}
|
||||
}
|
||||
input.Format = parseTruthy(get("format"))
|
||||
input.Multichannel = parseTruthy(get("multichannel"))
|
||||
if channels := get("channels"); channels != "" {
|
||||
if value, err := strconv.Atoi(channels); err == nil {
|
||||
input.Channels = value
|
||||
}
|
||||
}
|
||||
input.Diarize = parseTruthy(get("diarize"))
|
||||
input.FillerWords = parseTruthy(get("filler_words"))
|
||||
if form != nil {
|
||||
input.KeyTerms = append([]string(nil), form.Value["keyterm"]...)
|
||||
}
|
||||
if threshold := get("vad_threshold"); threshold != "" {
|
||||
if value, err := strconv.ParseFloat(threshold, 64); err == nil {
|
||||
input.VADThreshold = &value
|
||||
}
|
||||
}
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err == nil {
|
||||
defer file.Close()
|
||||
data, readErr := io.ReadAll(io.LimitReader(file, h.maxBodyBytes+1))
|
||||
if readErr != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "读取音频文件失败")
|
||||
return
|
||||
}
|
||||
if int64(len(data)) > h.maxBodyBytes {
|
||||
writeOpenAIError(c, http.StatusRequestEntityTooLarge, "request_too_large", "音频文件超过限制")
|
||||
return
|
||||
}
|
||||
input.FileData = data
|
||||
if header != nil {
|
||||
input.FileName = header.Filename
|
||||
input.FileMIME = header.Header.Get("Content-Type")
|
||||
}
|
||||
}
|
||||
} else if isJSONRequest(c) {
|
||||
var payload struct {
|
||||
Model string `json:"model"`
|
||||
URL string `json:"url"`
|
||||
AudioFormat string `json:"audio_format"`
|
||||
SampleRate any `json:"sample_rate"`
|
||||
Language string `json:"language"`
|
||||
Format any `json:"format"`
|
||||
Multichannel any `json:"multichannel"`
|
||||
Channels any `json:"channels"`
|
||||
Diarize any `json:"diarize"`
|
||||
KeyTerms []string `json:"keyterm"`
|
||||
FillerWords any `json:"filler_words"`
|
||||
VADThreshold *float64 `json:"vad_threshold"`
|
||||
ResponseFormat string `json:"response_format"`
|
||||
Prompt string `json:"prompt"`
|
||||
Temperature *float64 `json:"temperature"`
|
||||
TimestampGranularities []string `json:"timestamp_granularities"`
|
||||
}
|
||||
if err := decodeSingleJSON(c.Request.Body, &payload, false); err != nil {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "STT JSON 请求无效")
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(payload.Model) != "" {
|
||||
input.PublicModel = strings.TrimSpace(payload.Model)
|
||||
}
|
||||
input.URL = strings.TrimSpace(payload.URL)
|
||||
input.AudioFormat = strings.TrimSpace(payload.AudioFormat)
|
||||
input.SampleRate = anyString(payload.SampleRate)
|
||||
input.Language = strings.TrimSpace(payload.Language)
|
||||
input.Format = anyTruthy(payload.Format)
|
||||
input.Multichannel = anyTruthy(payload.Multichannel)
|
||||
if channels := anyString(payload.Channels); channels != "" {
|
||||
if value, err := strconv.Atoi(channels); err == nil {
|
||||
input.Channels = value
|
||||
}
|
||||
}
|
||||
input.Diarize = anyTruthy(payload.Diarize)
|
||||
input.KeyTerms = payload.KeyTerms
|
||||
input.FillerWords = anyTruthy(payload.FillerWords)
|
||||
input.VADThreshold = payload.VADThreshold
|
||||
if openAICompatible {
|
||||
input.ResponseFormat = strings.TrimSpace(payload.ResponseFormat)
|
||||
if strings.TrimSpace(payload.Prompt) != "" {
|
||||
unsupportedOpenAIParameter = "prompt"
|
||||
}
|
||||
if payload.Temperature != nil && *payload.Temperature != 0 {
|
||||
unsupportedOpenAIParameter = "temperature"
|
||||
}
|
||||
if len(payload.TimestampGranularities) > 0 {
|
||||
unsupportedOpenAIParameter = "timestamp_granularities"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "STT 支持 multipart/form-data 或 application/json")
|
||||
return
|
||||
}
|
||||
if openAICompatible {
|
||||
if unsupportedOpenAIParameter != "" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "unsupported_parameter", unsupportedOpenAIParameter+" 暂不支持,不能无损转换到 Console STT")
|
||||
return
|
||||
}
|
||||
input.ResponseFormat = strings.ToLower(strings.TrimSpace(input.ResponseFormat))
|
||||
if input.ResponseFormat == "" {
|
||||
input.ResponseFormat = "json"
|
||||
}
|
||||
switch input.ResponseFormat {
|
||||
case "json", "verbose_json", "text":
|
||||
default:
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", "response_format 必须是 json、verbose_json 或 text")
|
||||
return
|
||||
}
|
||||
}
|
||||
if len(input.FileData) == 0 && strings.TrimSpace(input.URL) == "" {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "STT 必须提供 file 或 url")
|
||||
return
|
||||
}
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
input.ClientKey = clientKey
|
||||
input.RequestID = requestID
|
||||
result, err := h.gateway.TranscribeSpeech(c.Request.Context(), input)
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
h.writeMediaResult(c, result)
|
||||
}
|
||||
|
||||
func bytesTrim(value json.RawMessage) []byte {
|
||||
return []byte(strings.TrimSpace(string(value)))
|
||||
}
|
||||
|
||||
func parseTTSOutputFormat(value json.RawMessage) (provider.TTSOutputFormat, error) {
|
||||
format := provider.TTSOutputFormat{}
|
||||
if len(bytesTrim(value)) == 0 {
|
||||
return format, nil
|
||||
}
|
||||
var raw struct {
|
||||
Codec string `json:"codec"`
|
||||
SampleRate *int `json:"sample_rate"`
|
||||
BitRate *int `json:"bit_rate"`
|
||||
}
|
||||
if err := json.Unmarshal(value, &raw); err != nil {
|
||||
return format, errors.New("output_format 无效")
|
||||
}
|
||||
format.Codec = strings.ToLower(strings.TrimSpace(raw.Codec))
|
||||
if raw.SampleRate != nil {
|
||||
if *raw.SampleRate <= 0 {
|
||||
return provider.TTSOutputFormat{}, errors.New("output_format.sample_rate 必须大于 0")
|
||||
}
|
||||
format.SampleRate = *raw.SampleRate
|
||||
}
|
||||
if raw.BitRate != nil {
|
||||
if *raw.BitRate <= 0 {
|
||||
return provider.TTSOutputFormat{}, errors.New("output_format.bit_rate 必须大于 0")
|
||||
}
|
||||
format.BitRate = *raw.BitRate
|
||||
}
|
||||
return format, nil
|
||||
}
|
||||
|
||||
func parseTTSSpeed(value *float64) (float64, error) {
|
||||
if value == nil {
|
||||
return 0, nil
|
||||
}
|
||||
if math.IsNaN(*value) || math.IsInf(*value, 0) || *value < 0.25 || *value > 4 {
|
||||
return 0, errors.New("speed 必须在 0.25 到 4.0 之间")
|
||||
}
|
||||
return *value, nil
|
||||
}
|
||||
|
||||
func parseOptimizeStreamingLatency(value json.RawMessage) (int, error) {
|
||||
if len(bytesTrim(value)) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
var result int
|
||||
var asString string
|
||||
if json.Unmarshal(value, &asString) == nil {
|
||||
parsed, err := strconv.Atoi(strings.TrimSpace(asString))
|
||||
if err != nil {
|
||||
return 0, errors.New("optimize_streaming_latency 必须是 0 到 4 的整数")
|
||||
}
|
||||
result = parsed
|
||||
} else {
|
||||
var asNumber float64
|
||||
if json.Unmarshal(value, &asNumber) != nil || math.IsNaN(asNumber) || math.IsInf(asNumber, 0) || math.Trunc(asNumber) != asNumber {
|
||||
return 0, errors.New("optimize_streaming_latency 必须是 0 到 4 的整数")
|
||||
}
|
||||
result = int(asNumber)
|
||||
}
|
||||
if result < 0 || result > 4 {
|
||||
return 0, errors.New("optimize_streaming_latency 必须是 0 到 4 的整数")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func parseTruthy(value string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func anyTruthy(value any) bool {
|
||||
switch typed := value.(type) {
|
||||
case nil:
|
||||
return false
|
||||
case bool:
|
||||
return typed
|
||||
case string:
|
||||
return parseTruthy(typed)
|
||||
case float64:
|
||||
return typed != 0
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func anyString(value any) string {
|
||||
switch typed := value.(type) {
|
||||
case nil:
|
||||
return ""
|
||||
case string:
|
||||
return strings.TrimSpace(typed)
|
||||
case float64:
|
||||
return strconv.FormatInt(int64(typed), 10)
|
||||
case json.Number:
|
||||
return typed.String()
|
||||
default:
|
||||
return strings.TrimSpace(stringify(value))
|
||||
}
|
||||
}
|
||||
|
||||
func stringify(value any) string {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.Trim(string(data), `"`)
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// keep middleware import used for request identity compatibility in package docs.
|
||||
var _ = middleware.ClientKey
|
||||
@@ -0,0 +1,156 @@
|
||||
package inference
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
upstreamws "github.com/bogdanfinn/websocket"
|
||||
"github.com/chenyme/grok2api/backend/internal/application/gateway"
|
||||
"github.com/gin-gonic/gin"
|
||||
clientws "github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
const voiceWSMessageLimit = 16 << 20
|
||||
|
||||
var voiceWSUpgrader = clientws.Upgrader{
|
||||
ReadBufferSize: 32 << 10,
|
||||
WriteBufferSize: 32 << 10,
|
||||
CheckOrigin: func(*http.Request) bool {
|
||||
return true
|
||||
},
|
||||
EnableCompression: true,
|
||||
}
|
||||
|
||||
func (h *Handler) proxyRealtimeWebSocket(c *gin.Context) {
|
||||
h.proxyVoiceWebSocket(c, "/realtime")
|
||||
}
|
||||
|
||||
func (h *Handler) proxySTTWebSocket(c *gin.Context) {
|
||||
if !clientws.IsWebSocketUpgrade(c.Request) {
|
||||
writeOpenAIError(c, http.StatusMethodNotAllowed, "invalid_request", "STT 流式接口需要 WebSocket Upgrade")
|
||||
return
|
||||
}
|
||||
h.proxyVoiceWebSocket(c, "/stt")
|
||||
}
|
||||
|
||||
func (h *Handler) proxyVoiceWebSocket(c *gin.Context, pathValue string) {
|
||||
if !clientws.IsWebSocketUpgrade(c.Request) {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "请求不是有效的 WebSocket Upgrade")
|
||||
return
|
||||
}
|
||||
clientKey, requestID, ok := requestIdentity(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
model := strings.TrimSpace(c.Query("model"))
|
||||
session, err := h.gateway.OpenVoiceWebSocket(c.Request.Context(), gateway.VoiceWebSocketInput{
|
||||
RequestID: requestID, ClientKey: clientKey, PublicModel: model, Path: pathValue,
|
||||
})
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
clientConn, err := voiceWSUpgrader.Upgrade(c.Writer, c.Request, nil)
|
||||
if err != nil {
|
||||
session.Finalize(gateway.VoiceWebSocketOutcome{ErrorCode: "client_upgrade_failed"})
|
||||
return
|
||||
}
|
||||
clientConn.SetReadLimit(voiceWSMessageLimit)
|
||||
session.Conn.SetReadLimit(voiceWSMessageLimit)
|
||||
|
||||
var once sync.Once
|
||||
var outcomeMu sync.Mutex
|
||||
outcome := gateway.VoiceWebSocketOutcome{}
|
||||
closeAll := func() {
|
||||
once.Do(func() {
|
||||
_ = clientConn.Close()
|
||||
if session.Conn != nil {
|
||||
_ = session.Conn.Close()
|
||||
}
|
||||
outcomeMu.Lock()
|
||||
finalOutcome := outcome
|
||||
outcomeMu.Unlock()
|
||||
session.Finalize(finalOutcome)
|
||||
})
|
||||
}
|
||||
defer closeAll()
|
||||
|
||||
type pumpResult struct {
|
||||
upstreamSide bool
|
||||
result voiceWSPumpResult
|
||||
}
|
||||
errCh := make(chan pumpResult, 2)
|
||||
go func() {
|
||||
errCh <- pumpResult{result: proxyVoiceWSPump(func() (int, []byte, error) {
|
||||
return clientConn.ReadMessage()
|
||||
}, session.Conn.WriteMessage)}
|
||||
}()
|
||||
go func() {
|
||||
errCh <- pumpResult{upstreamSide: true, result: proxyVoiceWSPump(func() (int, []byte, error) {
|
||||
messageType, payload, readErr := session.Conn.ReadMessage()
|
||||
if readErr == nil && pathValue == "/stt" {
|
||||
if duration, ok := streamingSTTDuration(payload); ok {
|
||||
outcomeMu.Lock()
|
||||
outcome.AudioDurationSeconds = max(outcome.AudioDurationSeconds, duration)
|
||||
outcomeMu.Unlock()
|
||||
}
|
||||
}
|
||||
return messageType, payload, readErr
|
||||
}, clientConn.WriteMessage)}
|
||||
}()
|
||||
first := <-errCh
|
||||
if !isNormalVoiceWSClose(first.result.err) {
|
||||
outcomeMu.Lock()
|
||||
if (first.upstreamSide && !first.result.writeFailed) || (!first.upstreamSide && first.result.writeFailed) {
|
||||
outcome.ErrorCode = "upstream_stream_interrupted"
|
||||
outcome.UpstreamFailed = true
|
||||
} else {
|
||||
outcome.ErrorCode = "client_stream_interrupted"
|
||||
}
|
||||
outcomeMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func streamingSTTDuration(payload []byte) (float64, bool) {
|
||||
var event struct {
|
||||
Type string `json:"type"`
|
||||
Duration float64 `json:"duration"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &event); err != nil || strings.TrimSpace(event.Type) != "transcript.done" {
|
||||
return 0, false
|
||||
}
|
||||
if event.Duration <= 0 || math.IsNaN(event.Duration) || math.IsInf(event.Duration, 0) {
|
||||
return 0, false
|
||||
}
|
||||
return event.Duration, true
|
||||
}
|
||||
|
||||
type voiceWSPumpResult struct {
|
||||
err error
|
||||
writeFailed bool
|
||||
}
|
||||
|
||||
func proxyVoiceWSPump(read func() (int, []byte, error), write func(int, []byte) error) voiceWSPumpResult {
|
||||
for {
|
||||
messageType, payload, err := read()
|
||||
if err != nil {
|
||||
return voiceWSPumpResult{err: err}
|
||||
}
|
||||
if err := write(messageType, payload); err != nil {
|
||||
return voiceWSPumpResult{err: err, writeFailed: true}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isNormalVoiceWSClose(err error) bool {
|
||||
if err == nil || err == io.EOF {
|
||||
return true
|
||||
}
|
||||
return clientws.IsCloseError(err, clientws.CloseNormalClosure, clientws.CloseGoingAway) ||
|
||||
upstreamws.IsCloseError(err, upstreamws.CloseNormalClosure, upstreamws.CloseGoingAway)
|
||||
}
|
||||
@@ -38,7 +38,7 @@ func (h *Handler) RegisterAdmin(router *gin.RouterGroup) {
|
||||
router.DELETE("/media/images", h.deleteImages)
|
||||
router.GET("/media/images/stats", h.imageStats)
|
||||
router.POST("/media/inputs/import", h.importInputImageFromURL)
|
||||
router.POST("/media/inputs/upload", h.uploadInputImage)
|
||||
router.POST("/media/inputs/upload", h.uploadInputAsset)
|
||||
router.GET("/media/videos", h.listVideos)
|
||||
router.DELETE("/media/videos", h.deleteVideos)
|
||||
router.GET("/media/videos/stats", h.videoStats)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package media
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
@@ -15,6 +16,7 @@ import (
|
||||
"time"
|
||||
|
||||
mediaapp "github.com/chenyme/grok2api/backend/internal/application/media"
|
||||
mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media"
|
||||
"github.com/chenyme/grok2api/backend/internal/pkg/netguard"
|
||||
"github.com/chenyme/grok2api/backend/internal/shared/response"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -22,7 +24,7 @@ import (
|
||||
|
||||
const (
|
||||
// 20 MiB 为各 Provider 的共同安全输入上限,同时为全局 32 MiB multipart 请求上限保留编码开销。
|
||||
ingestMaxImageBytes = 20 << 20
|
||||
ingestMaxImageBytes = mediadomain.MaxInputAssetBytes
|
||||
// ingestFetchTimeout 是 URL 导入单次抓取的整体超时。
|
||||
ingestFetchTimeout = 20 * time.Second
|
||||
// ingestResolveTimeout 限制每个重定向目标的 DNS 解析时间。
|
||||
@@ -290,8 +292,8 @@ func (h *Handler) importInputImageFromURL(c *gin.Context) {
|
||||
h.saveIngestedImage(c, data)
|
||||
}
|
||||
|
||||
// uploadInputImage 接收管理员上传的本地图片文件(multipart 字段名 file),登记到临时输入区。
|
||||
func (h *Handler) uploadInputImage(c *gin.Context) {
|
||||
// uploadInputAsset 接收管理员上传的本地图片或视频(multipart 字段名 file),登记到临时输入区。
|
||||
func (h *Handler) uploadInputAsset(c *gin.Context) {
|
||||
if !h.acquireIngest(c) {
|
||||
return
|
||||
}
|
||||
@@ -300,14 +302,14 @@ func (h *Handler) uploadInputImage(c *gin.Context) {
|
||||
if err != nil {
|
||||
var maxBytesError *http.MaxBytesError
|
||||
if errors.As(err, &maxBytesError) {
|
||||
response.Error(c, http.StatusRequestEntityTooLarge, "imageTooLarge", "图片超过请求大小上限")
|
||||
response.Error(c, http.StatusRequestEntityTooLarge, "mediaTooLarge", "文件超过请求大小上限")
|
||||
return
|
||||
}
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", "缺少上传文件")
|
||||
return
|
||||
}
|
||||
if fileHeader.Size > ingestMaxImageBytes {
|
||||
response.Error(c, http.StatusRequestEntityTooLarge, "imageTooLarge", "图片超过大小上限")
|
||||
response.Error(c, http.StatusRequestEntityTooLarge, "mediaTooLarge", "文件超过大小上限")
|
||||
return
|
||||
}
|
||||
src, err := fileHeader.Open()
|
||||
@@ -322,10 +324,38 @@ func (h *Handler) uploadInputImage(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
if int64(len(data)) > ingestMaxImageBytes {
|
||||
response.Error(c, http.StatusRequestEntityTooLarge, "imageTooLarge", "图片超过大小上限")
|
||||
response.Error(c, http.StatusRequestEntityTooLarge, "mediaTooLarge", "文件超过大小上限")
|
||||
return
|
||||
}
|
||||
h.saveIngestedImage(c, data)
|
||||
declaredMIME := strings.ToLower(strings.TrimSpace(strings.Split(fileHeader.Header.Get("Content-Type"), ";")[0]))
|
||||
detectedMIME := strings.ToLower(http.DetectContentType(data))
|
||||
if strings.HasPrefix(detectedMIME, "image/") {
|
||||
h.saveIngestedImage(c, data)
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(declaredMIME, "video/") || strings.HasPrefix(detectedMIME, "video/") {
|
||||
contentType := declaredMIME
|
||||
if contentType == "" {
|
||||
contentType = detectedMIME
|
||||
}
|
||||
asset, saveErr := h.service.SaveInputVideo(c.Request.Context(), contentType, bytes.NewReader(data))
|
||||
if saveErr != nil {
|
||||
switch {
|
||||
case errors.Is(saveErr, mediaapp.ErrVideoUploadTooLarge):
|
||||
response.Error(c, http.StatusRequestEntityTooLarge, "mediaTooLarge", "视频超过大小上限")
|
||||
case errors.Is(saveErr, mediaapp.ErrInvalidVideoUpload):
|
||||
response.Error(c, http.StatusBadRequest, "invalidVideo", "视频内容无效或格式不支持(mp4/webm/quicktime)")
|
||||
case errors.Is(saveErr, mediaapp.ErrMediaCapacity):
|
||||
response.Error(c, http.StatusInsufficientStorage, "mediaCapacityExceeded", "媒体临时存储容量不足")
|
||||
default:
|
||||
response.Error(c, http.StatusInternalServerError, "mediaSaveVideoFailed", "保存视频失败")
|
||||
}
|
||||
return
|
||||
}
|
||||
h.writeInputAsset(c, asset)
|
||||
return
|
||||
}
|
||||
response.Error(c, http.StatusBadRequest, "invalidMedia", "仅支持图片或视频文件")
|
||||
}
|
||||
|
||||
// saveIngestedImage 收口两种临时输入路径:校验、落盘并登记 TTL,不进入图库。
|
||||
@@ -343,12 +373,16 @@ func (h *Handler) saveIngestedImage(c *gin.Context, data []byte) {
|
||||
response.Error(c, http.StatusInternalServerError, "mediaSaveImageFailed", "保存图片失败")
|
||||
return
|
||||
}
|
||||
h.writeInputAsset(c, asset)
|
||||
}
|
||||
|
||||
func (h *Handler) writeInputAsset(c *gin.Context, asset mediadomain.Asset) {
|
||||
expiresAt := ""
|
||||
if asset.ExpiresAt != nil {
|
||||
expiresAt = asset.ExpiresAt.Format(time.RFC3339)
|
||||
}
|
||||
response.Success(c, http.StatusCreated, gin.H{
|
||||
"fileId": asset.ID, "mimeType": asset.MIMEType, "sizeBytes": asset.SizeBytes, "expiresAt": expiresAt,
|
||||
"fileId": asset.ID, "kind": asset.Kind, "mimeType": asset.MIMEType, "sizeBytes": asset.SizeBytes, "expiresAt": expiresAt,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -357,7 +391,7 @@ func (h *Handler) acquireIngest(c *gin.Context) bool {
|
||||
case h.ingestSlots <- struct{}{}:
|
||||
return true
|
||||
default:
|
||||
response.Error(c, http.StatusServiceUnavailable, "mediaIngestBusy", "图片暂存并发已满,请稍后重试")
|
||||
response.Error(c, http.StatusServiceUnavailable, "mediaIngestBusy", "媒体暂存并发已满,请稍后重试")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,8 +94,22 @@ func inferenceBodyOperation(path string) string {
|
||||
return "image_generation"
|
||||
case "/v1/images/edits":
|
||||
return "image_edit"
|
||||
case "/v1/tts":
|
||||
return "tts"
|
||||
case "/v1/stt":
|
||||
return "stt"
|
||||
case "/v1/audio/speech", "/v1/audio/tasks":
|
||||
return "tts"
|
||||
case "/v1/audio/transcriptions":
|
||||
return "stt"
|
||||
case "/v1/realtime":
|
||||
return "realtime_websocket"
|
||||
case "/v1/videos/generations":
|
||||
return "video_generation"
|
||||
case "/v1/videos/edits":
|
||||
return "video_edit"
|
||||
case "/v1/videos/extensions":
|
||||
return "video_extension"
|
||||
default:
|
||||
return "other"
|
||||
}
|
||||
|
||||
@@ -63,12 +63,28 @@ type SwaggerImageEditRequest struct {
|
||||
}
|
||||
|
||||
// SwaggerVideoGenerationRequest 表示视频生成请求。
|
||||
// image 与 reference_images/reference_audios 互斥;参考图模式 resolution 最高 720p。
|
||||
type SwaggerVideoGenerationRequest struct {
|
||||
Model string `json:"model" example:"grok-imagine-video"`
|
||||
Prompt string `json:"prompt" example:"A cinematic tracking shot in the rain"`
|
||||
Duration int `json:"duration" example:"8"`
|
||||
AspectRatio string `json:"aspect_ratio,omitempty" example:"16:9"`
|
||||
Resolution string `json:"resolution,omitempty" example:"720p"`
|
||||
Model string `json:"model" example:"grok-imagine-video"`
|
||||
Prompt string `json:"prompt" example:"A cinematic tracking shot in the rain"`
|
||||
Duration int `json:"duration" example:"8"`
|
||||
AspectRatio string `json:"aspect_ratio,omitempty" example:"16:9"`
|
||||
Resolution string `json:"resolution,omitempty" example:"720p"`
|
||||
Image *SwaggerVideoMediaInput `json:"image,omitempty"`
|
||||
ReferenceImages []SwaggerVideoMediaInput `json:"reference_images,omitempty"`
|
||||
ReferenceAudios []SwaggerVideoAudioInput `json:"reference_audios,omitempty"`
|
||||
Video *SwaggerVideoMediaInput `json:"video,omitempty"`
|
||||
}
|
||||
|
||||
// SwaggerVideoMediaInput 表示视频相关的图片/视频输入。
|
||||
type SwaggerVideoMediaInput struct {
|
||||
URL string `json:"url,omitempty" example:"https://example.com/input.png"`
|
||||
FileID string `json:"file_id,omitempty" example:"file_123"`
|
||||
}
|
||||
|
||||
// SwaggerVideoAudioInput 表示参考音频(内置 voice_id)。
|
||||
type SwaggerVideoAudioInput struct {
|
||||
VoiceID string `json:"voice_id" example:"eve"`
|
||||
}
|
||||
|
||||
// swaggerHealth godoc
|
||||
@@ -217,6 +233,30 @@ func swaggerGetImage() {}
|
||||
// @Router /v1/videos/generations [post]
|
||||
func swaggerGenerateVideo() {}
|
||||
|
||||
// swaggerEditVideo godoc
|
||||
// @Summary 创建异步视频编辑任务
|
||||
// @Tags Videos
|
||||
// @Security BearerAuth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body SwaggerVideoGenerationRequest true "请求"
|
||||
// @Success 200 {object} map[string]string
|
||||
// @Failure 400 {object} map[string]any
|
||||
// @Router /v1/videos/edits [post]
|
||||
func swaggerEditVideo() {}
|
||||
|
||||
// swaggerExtendVideo godoc
|
||||
// @Summary 创建异步视频延长任务
|
||||
// @Tags Videos
|
||||
// @Security BearerAuth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body SwaggerVideoGenerationRequest true "请求"
|
||||
// @Success 200 {object} map[string]string
|
||||
// @Failure 400 {object} map[string]any
|
||||
// @Router /v1/videos/extensions [post]
|
||||
func swaggerExtendVideo() {}
|
||||
|
||||
// swaggerGetVideo godoc
|
||||
// @Summary 查询异步视频任务
|
||||
// @Tags Videos
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Box, ChevronDown, Eye, Image, KeyRound, Languages, LayoutDashboard, LogOut, Menu, MessageSquareText, Monitor, Moon, MoreHorizontal, Settings, ShieldCheck, Sparkles, Sun, Users, Video } from "lucide-react";
|
||||
import { AudioLines, Box, ChevronDown, Eye, Image, KeyRound, Languages, LayoutDashboard, LogOut, Menu, MessageSquareText, Monitor, Moon, MoreHorizontal, Settings, ShieldCheck, Sparkles, Sun, Users, Video } from "lucide-react";
|
||||
import { useTheme } from "next-themes";
|
||||
import { useState, type ReactNode } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
@@ -55,9 +55,24 @@ const documentation = [
|
||||
icon: Video,
|
||||
items: [
|
||||
{ href: "/docs/video/generations", label: "Video Generations", method: "POST" },
|
||||
{ href: "/docs/video/edits", label: "Video Edits", method: "POST" },
|
||||
{ href: "/docs/video/extensions", label: "Video Extensions", method: "POST" },
|
||||
{ href: "/docs/video/get", label: "Get Video", method: "GET" },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Voice",
|
||||
icon: AudioLines,
|
||||
items: [
|
||||
{ href: "/docs/voice/tts", label: "Text to Speech", method: "POST" },
|
||||
{ href: "/docs/voice/audio-speech", label: "OpenAI Speech", method: "POST" },
|
||||
{ href: "/docs/voice/audio-tasks", label: "OpenAI Audio Tasks", method: "POST" },
|
||||
{ href: "/docs/voice/audio-transcriptions", label: "OpenAI Transcriptions", method: "POST" },
|
||||
{ href: "/docs/voice/voices", label: "List Voices", method: "GET" },
|
||||
{ href: "/docs/voice/stt", label: "Speech to Text", method: "POST" },
|
||||
{ href: "/docs/voice/realtime", label: "Realtime WebSocket", method: "GET" },
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
|
||||
export function AppShell() {
|
||||
|
||||
@@ -21,7 +21,7 @@ const modelRouteValidator = hasShape({
|
||||
publicId: isString,
|
||||
provider: isOneOf("grok_build", "grok_web", "grok_console"),
|
||||
upstreamModel: isString,
|
||||
capability: isOneOf("responses", "chat", "image", "image_edit", "video"),
|
||||
capability: isOneOf("responses", "chat", "image", "image_edit", "video", "tts", "stt", "realtime"),
|
||||
origin: isOneOf("catalog", "discovered", "manual"),
|
||||
enabled: isBoolean,
|
||||
accountIds: isArrayOf(isString),
|
||||
@@ -35,7 +35,7 @@ const modelRouteValidator = hasShape({
|
||||
});
|
||||
const decodeModelRoute = createObjectDecoder<ModelRouteDTO>("model route", {
|
||||
id: isString, publicId: isString, provider: isOneOf("grok_build", "grok_web", "grok_console"), upstreamModel: isString,
|
||||
capability: isOneOf("responses", "chat", "image", "image_edit", "video"), origin: isOneOf("catalog", "discovered", "manual"),
|
||||
capability: isOneOf("responses", "chat", "image", "image_edit", "video", "tts", "stt", "realtime"), origin: isOneOf("catalog", "discovered", "manual"),
|
||||
enabled: isBoolean, accountIds: isArrayOf(isString), bindingMode: isBoolean, supportedAccounts: isNumber,
|
||||
syncedAccounts: isNumber, totalAccounts: isNumber, capabilityKnown: isBoolean, available: isBoolean, lastSyncedAt: isOptional(isString),
|
||||
});
|
||||
@@ -43,7 +43,7 @@ const decodeModelPage = createPaginatedDecoder<ModelRouteDTO>(modelRouteValidato
|
||||
const modelRouteGroupValidator = hasShape({
|
||||
key: isString,
|
||||
routes: (value) => Array.isArray(value) && value.length > 0 && value.every(modelRouteValidator),
|
||||
endpointCapabilities: isArrayOf(isOneOf("completions", "responses", "messages", "image", "image_edit", "video")),
|
||||
endpointCapabilities: isArrayOf(isOneOf("completions", "responses", "messages", "image", "image_edit", "video", "tts", "stt", "realtime")),
|
||||
});
|
||||
const decodeModelGroupPage = createPaginatedDecoder<ModelRouteGroupDTO>(modelRouteGroupValidator);
|
||||
const modelAccountValidator = hasShape({ id: isString, name: isString });
|
||||
|
||||
@@ -3,7 +3,7 @@ export type ModelRouteDTO = {
|
||||
publicId: string;
|
||||
provider: "grok_build" | "grok_web" | "grok_console";
|
||||
upstreamModel: string;
|
||||
capability: "responses" | "chat" | "image" | "image_edit" | "video";
|
||||
capability: "responses" | "chat" | "image" | "image_edit" | "video" | "tts" | "stt" | "realtime";
|
||||
origin: "catalog" | "discovered" | "manual";
|
||||
enabled: boolean;
|
||||
accountIds: string[];
|
||||
@@ -16,7 +16,7 @@ export type ModelRouteDTO = {
|
||||
lastSyncedAt?: string;
|
||||
};
|
||||
|
||||
export type ModelEndpointCapability = "completions" | "responses" | "messages" | "image" | "image_edit" | "video";
|
||||
export type ModelEndpointCapability = "completions" | "responses" | "messages" | "image" | "image_edit" | "video" | "tts" | "stt" | "realtime";
|
||||
|
||||
export type ModelRouteGroupDTO = {
|
||||
key: string;
|
||||
|
||||
@@ -103,6 +103,18 @@ function BuildQuota({ quota, billing, locale }: { quota: QuotaDTO; billing?: Bil
|
||||
|
||||
const visibleWebQuotaModes = ["auto", "fast", "expert", "heavy"] as const;
|
||||
|
||||
const imagineQuotaModes = [
|
||||
{ mode: "image_pro", labelKey: "imagineModeImagePro" as const },
|
||||
{ mode: "image_edit", labelKey: "imagineModeImageEdit" as const },
|
||||
{ mode: "video", labelKey: "imagineModeVideo" as const },
|
||||
{ mode: "video_720p", labelKey: "imagineModeVideo720p" as const },
|
||||
] as const;
|
||||
|
||||
function imagineWindowsOf(windows: WebQuotaWindow[]): WebQuotaWindow[] {
|
||||
const known: Set<string> = new Set(imagineQuotaModes.map((item) => item.mode));
|
||||
return windows.filter((window) => known.has(window.mode));
|
||||
}
|
||||
|
||||
export function ConsoleQuota({ windows, locale }: { windows: NonNullable<AccountDTO["quotaWindows"]>; locale: string }) {
|
||||
const { t } = useTranslation();
|
||||
if (windows.length === 0) return <span className="text-xs text-muted-foreground">{t("accounts.quotaNotSynced")}</span>;
|
||||
@@ -129,26 +141,85 @@ export function WebQuota({ windows, locale, tier }: { windows: NonNullable<Accou
|
||||
const { t } = useTranslation();
|
||||
if (windows.length === 0) return <span className="text-xs text-muted-foreground">{t("accounts.quotaNotSynced")}</span>;
|
||||
const windowsByMode = new Map(windows.map((window) => [window.mode, window]));
|
||||
const imagineWindows = imagineWindowsOf(windows);
|
||||
const weekly = windowsByMode.get("weekly");
|
||||
if (weekly) return <WeeklyWebQuota window={weekly} locale={locale} t={t} />;
|
||||
|
||||
const fast = windowsByMode.get("fast");
|
||||
if (tier === "basic" && fast) return <WebQuotaMode mode="Fast" window={fast} locale={locale} />;
|
||||
const mainBlock = (() => {
|
||||
if (weekly) return <WeeklyWebQuota window={weekly} locale={locale} t={t} />;
|
||||
const fast = windowsByMode.get("fast");
|
||||
if (tier === "basic" && fast) return <WebQuotaMode mode="Fast" window={fast} locale={locale} />;
|
||||
return (
|
||||
<div className="grid w-full min-w-0 grid-cols-4 divide-x divide-border/70">
|
||||
{visibleWebQuotaModes.map((mode) => {
|
||||
const window = windowsByMode.get(mode);
|
||||
if (!window) {
|
||||
return <div key={mode} className="min-w-0 px-2 first:pl-0 last:pr-0"><div className="flex items-center justify-between gap-1 text-[11px]"><span className="truncate capitalize text-muted-foreground">{mode}</span><span className="text-muted-foreground">-</span></div><div className="mt-1.5 h-1.5 rounded-full bg-muted" /></div>;
|
||||
}
|
||||
return <WebQuotaMode key={mode} mode={formatWebQuotaMode(mode)} window={window} locale={locale} compact />;
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
})();
|
||||
|
||||
if (imagineWindows.length === 0) return mainBlock;
|
||||
return (
|
||||
<div className="grid w-full min-w-0 grid-cols-4 divide-x divide-border/70">
|
||||
{visibleWebQuotaModes.map((mode) => {
|
||||
const window = windowsByMode.get(mode);
|
||||
if (!window) {
|
||||
return <div key={mode} className="min-w-0 px-2 first:pl-0 last:pr-0"><div className="flex items-center justify-between gap-1 text-[11px]"><span className="truncate capitalize text-muted-foreground">{mode}</span><span className="text-muted-foreground">-</span></div><div className="mt-1.5 h-1.5 rounded-full bg-muted" /></div>;
|
||||
}
|
||||
return <WebQuotaMode key={mode} mode={formatWebQuotaMode(mode)} window={window} locale={locale} compact />;
|
||||
})}
|
||||
<div className="w-full min-w-0 space-y-1.5">
|
||||
{mainBlock}
|
||||
<ImagineQuotaRow windows={imagineWindows} locale={locale} t={t} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type WebQuotaWindow = NonNullable<AccountDTO["quotaWindows"]>[number];
|
||||
|
||||
function imagineModeLabel(mode: string, t: TFunction): string {
|
||||
const entry = imagineQuotaModes.find((item) => item.mode === mode);
|
||||
return entry ? t(`accounts.${entry.labelKey}`) : mode;
|
||||
}
|
||||
|
||||
function ImagineQuotaRow({ windows, locale, t }: { windows: WebQuotaWindow[]; locale: string; t: TFunction }) {
|
||||
const windowsByMode = new Map(windows.map((window) => [window.mode, window]));
|
||||
const columns = imagineQuotaModes.filter((item) => windowsByMode.has(item.mode));
|
||||
if (columns.length === 0) return null;
|
||||
return (
|
||||
<div className="grid w-full min-w-0 divide-x divide-border/70" style={{ gridTemplateColumns: `repeat(${columns.length}, minmax(0, 1fr))` }}>
|
||||
{columns.map(({ mode }) => {
|
||||
const window = windowsByMode.get(mode)!;
|
||||
const exhausted = window.remaining <= 0;
|
||||
const hasTotal = window.total > 0;
|
||||
const used = hasTotal ? Math.max(0, window.total - window.remaining) : 0;
|
||||
const percent = hasTotal ? Math.max(0, Math.min(100, used / window.total * 100)) : 0;
|
||||
const label = imagineModeLabel(mode, t);
|
||||
return (
|
||||
<Tooltip key={mode}>
|
||||
<TooltipTrigger asChild>
|
||||
<button type="button" className="block w-full min-w-0 px-2 text-left first:pl-0 last:pr-0">
|
||||
<div className="flex items-center justify-between gap-1 text-[11px]">
|
||||
<span className={cn("truncate", exhausted ? "text-amber-600 dark:text-amber-400" : "text-muted-foreground")}>{label}</span>
|
||||
{exhausted ? (
|
||||
<span className="shrink-0 truncate text-amber-600 dark:text-amber-400">{t("accounts.imagineQuotaExhausted")}</span>
|
||||
) : hasTotal ? (
|
||||
<span className="shrink-0 tabular-nums text-muted-foreground">{formatNumber(window.remaining, locale, 0)}/{formatNumber(window.total, locale, 0)}</span>
|
||||
) : (
|
||||
<span className="shrink-0 tabular-nums text-muted-foreground">{t("accounts.imagineQuotaRemaining", { remaining: formatNumber(window.remaining, locale, 0) })}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-muted">
|
||||
{exhausted ? <div className="h-full w-full bg-amber-500" /> : hasTotal ? <div className="h-full bg-primary" style={{ width: `${percent}%` }} /> : null}
|
||||
</div>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div>{exhausted ? t("accounts.imagineQuotaExhausted") : t("accounts.imagineQuotaRemaining", { remaining: formatNumber(window.remaining, locale, 0) })}</div>
|
||||
<div className="text-muted-foreground">{window.resetAt ? t("accounts.quotaResetAt", { time: formatDateTime(window.resetAt, locale) }) : t("accounts.quotaResetUnknown")}</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WeeklyWebQuota({ window, locale, t }: { window: WebQuotaWindow; locale: string; t: TFunction }) {
|
||||
const usedPercent = Math.max(0, Math.min(100, window.usagePercent));
|
||||
const breakdown = (window.breakdown ?? []).filter((item) => item.usagePercent > 0);
|
||||
|
||||
@@ -32,7 +32,7 @@ export type AuditDTO = {
|
||||
modelPublicId?: string;
|
||||
modelUpstreamModel?: string;
|
||||
provider: "grok_build" | "grok_web" | "grok_console";
|
||||
operation: "responses" | "compaction" | "chat" | "messages" | "image" | "image_edit" | "video";
|
||||
operation: "responses" | "compaction" | "chat" | "messages" | "image" | "image_edit" | "video" | "tts" | "stt" | "realtime" | "voice";
|
||||
usageSource: "upstream" | "estimated" | "none";
|
||||
accountId?: string;
|
||||
accountName?: string;
|
||||
@@ -141,7 +141,7 @@ const auditBillingValidator = hasShape({
|
||||
const auditValidator = hasShape({
|
||||
id: isString, requestId: isString, clientKeyId: isString, clientKeyName: isOptional(isString), modelRouteId: isString,
|
||||
modelPublicId: isOptional(isString), modelUpstreamModel: isOptional(isString), provider: isOneOf("grok_build", "grok_web", "grok_console"),
|
||||
operation: isOneOf("responses", "compaction", "chat", "messages", "image", "image_edit", "video"), usageSource: isOneOf("upstream", "estimated", "none"),
|
||||
operation: isOneOf("responses", "compaction", "chat", "messages", "image", "image_edit", "video", "tts", "stt", "realtime", "voice"), usageSource: isOneOf("upstream", "estimated", "none"),
|
||||
accountId: isOptional(isString), accountName: isOptional(isString),
|
||||
egressNodeId: isOptional(isString), egressNodeName: isOptional(isString),
|
||||
egressScope: isOptional(isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset")), egressMode: isOptional(isOneOf("direct", "proxy")),
|
||||
|
||||
@@ -407,7 +407,7 @@ function EgressValue({ audit }: { audit: AuditDTO }) {
|
||||
function BillingValue({ audit }: { audit: AuditDTO }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const billing = audit.billing ?? fallbackBillingBreakdown(audit);
|
||||
const amount = billing ? formatUSDCost(billing.totalInUsdTicks, 2) : "-";
|
||||
const amount = billing ? formatUSDCost(billing.totalInUsdTicks, 2) : t("audits.unbilled");
|
||||
return (
|
||||
<div className="max-w-full text-left">
|
||||
{billing ? (
|
||||
@@ -417,7 +417,7 @@ function BillingValue({ audit }: { audit: AuditDTO }) {
|
||||
<BillingBreakdown billing={billing} locale={i18n.language} />
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : <span className="block text-xs text-muted-foreground">-</span>}
|
||||
) : <span className="block whitespace-nowrap text-xs text-muted-foreground">{amount}</span>}
|
||||
{audit.numServerSideToolsUsed > 0 ? (
|
||||
<span className="mt-0.5 block whitespace-nowrap text-[10px] text-muted-foreground">
|
||||
{t("audits.serverTools", { count: audit.numServerSideToolsUsed })}
|
||||
@@ -584,6 +584,16 @@ function UsageDetails({ audit, locale }: { audit: AuditDTO; locale: string }) {
|
||||
if (audit.operation === "video") {
|
||||
return <MediaUsage input={t("audits.imageCount", { count: audit.mediaInputImages })} output={t("audits.secondsCount", { count: audit.mediaOutputSeconds })} />;
|
||||
}
|
||||
if (audit.operation === "tts" || audit.operation === "stt" || audit.operation === "realtime" || audit.operation === "voice") {
|
||||
return (
|
||||
<div className="flex h-[52px] w-full items-center gap-2 rounded-md bg-muted/45 px-2.5 text-[11px]">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-medium">{t(`audits.operations.${audit.operation}`)}</p>
|
||||
<p className="truncate text-muted-foreground">{(audit.durationMs / 1000).toFixed(2)}s</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (audit.operation === "image" || audit.operation === "image_edit" || audit.mediaInputImages > 0 || audit.mediaOutputImages > 0) {
|
||||
return <MediaUsage input={t("audits.imageCount", { count: audit.mediaInputImages })} output={t("audits.imageCount", { count: audit.mediaOutputImages })} />;
|
||||
}
|
||||
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user