mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-23 08:00:49 +00:00
refactor: migrate to multi-provider gateway architecture
Rebuild the backend as the frozen gateway workspace with a single PostgreSQL schema, provider-owned OpenAI and xAI boundaries, and mirrored domain tests. Restore the admin product contracts for accounts, model catalogs, usage observability, billing details, and provider-scoped settings without compatibility shims. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
+1
-1
@@ -1,5 +1,5 @@
|
||||
# Rust
|
||||
/backend/target/
|
||||
/backend/**/target/
|
||||
*.profraw
|
||||
*.profdata
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
# Codex Proxy RS
|
||||
|
||||
**基于 Rust 的高性能 Codex 多账号网关代理**
|
||||
**基于 Rust 的多 Provider 透明 AI 网关**
|
||||
|
||||
[](https://github.com/zyycn/codex-proxy-rs/actions/workflows/ci.yml)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
@@ -23,13 +23,12 @@
|
||||
|
||||
| 领域 | 实现 |
|
||||
| -------- | ------------------------------------------------ |
|
||||
| 协议 | Responses HTTP、SSE、官方 WebSocket |
|
||||
| 传输 | 会话级 WebSocket 池、共享 HTTP/2 后备 |
|
||||
| 调度 | 智能调度、额度优先、轮询、粘滞 |
|
||||
| 故障处理 | 额度、认证、封禁、模型与传输故障切换 |
|
||||
| 身份 | 账号身份隔离、稳定 installation ID、会话拓扑透传 |
|
||||
| 管理 | 账号、客户端 Key、模型别名、运行设置与在线更新 |
|
||||
| 遥测 | Token、费用、缓存、TTFT、延迟与错误 |
|
||||
| 协议 | OpenAI Responses JSON/SSE 与模型目录 |
|
||||
| Provider | Codex OAuth、xAI/Grok OAuth session |
|
||||
| 路由 | Provider instance、能力过滤、显式 fallback 与多 credential |
|
||||
| 延续 | Provider 原生 continuation 与加密 portable transcript |
|
||||
| 管理 | Client Key、Provider、模型、Route、Target、价格与 OAuth |
|
||||
| 计量 | Request/Attempt usage、版本价格、预算、聚合与恢复 |
|
||||
|
||||
## 快速开始
|
||||
|
||||
@@ -84,9 +83,12 @@ curl -i http://127.0.0.1:8080/healthz
|
||||
### 3. 初始化
|
||||
|
||||
1. 使用 `admin@cpr.local` 与初始密码登录。
|
||||
2. 添加 Codex 账号并执行连接测试。
|
||||
3. 创建 `sk_...` 客户端 Key。
|
||||
4. 复制 Codex CLI 配置,或导入 CCSwitch。
|
||||
2. 创建 Provider instance,并通过 OAuth 导入 Codex 或 xAI credential。
|
||||
3. 配置 Provider model、对外 Route/Target;严格预算场景同时发布价格版本。
|
||||
4. 创建 `sk_...` 客户端 Key,并设置模型 allowlist、速率、并发和预算策略。
|
||||
|
||||
> [!IMPORTANT]
|
||||
> xAI 使用 OAuth session,不支持把 xAI API Key 作为上游 credential。
|
||||
|
||||
> [!NOTE]
|
||||
> `admin.default_password` 只在首次创建管理员时生效。
|
||||
@@ -120,12 +122,9 @@ curl http://127.0.0.1:8080/v1/responses \
|
||||
|
||||
| 路由 | 用途 |
|
||||
| --------------------------- | ------------------- |
|
||||
| `POST /v1/responses` | JSON 或 SSE |
|
||||
| `GET /v1/responses` | Responses WebSocket |
|
||||
| `POST /v1/responses/review` | Review |
|
||||
| `GET /v1/models` | 模型列表 |
|
||||
| `GET /v1/models/catalog` | 模型目录 |
|
||||
| `GET /v1/models/{model_id}` | 模型详情 |
|
||||
| `POST /v1/responses` | JSON 或 SSE 透明代理 |
|
||||
| `GET /v1/models` | 启用的公开模型列表 |
|
||||
| `GET /v1/models/{model_id}` | 公开模型详情 |
|
||||
|
||||
所有 `/v1/*` 路由都需要客户端 API Key。
|
||||
|
||||
@@ -156,5 +155,7 @@ upgrade 与真实客户端 IP;不要暴露 PostgreSQL 或 Redis。
|
||||
|
||||
- [部署](deploy/README.md)
|
||||
- [架构](docs/architecture.md)
|
||||
- [多 Provider 目标架构](docs/multi-provider-architecture.md)
|
||||
- [终态数据模型](docs/multi-provider-database.md)
|
||||
- [Release](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
- [容器镜像](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
|
||||
|
||||
Generated
+607
-22
@@ -113,6 +113,28 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-stream"
|
||||
version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476"
|
||||
dependencies = [
|
||||
"async-stream-impl",
|
||||
"futures-core",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-stream-impl"
|
||||
version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-trait"
|
||||
version = "0.1.89"
|
||||
@@ -152,6 +174,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
|
||||
dependencies = [
|
||||
"axum-core",
|
||||
"base64",
|
||||
"bytes",
|
||||
"form_urlencoded",
|
||||
"futures-util",
|
||||
@@ -170,8 +193,10 @@ dependencies = [
|
||||
"serde_json",
|
||||
"serde_path_to_error",
|
||||
"serde_urlencoded",
|
||||
"sha1 0.10.7",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-tungstenite 0.29.0",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
@@ -206,6 +231,12 @@ dependencies = [
|
||||
"fastrand",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base16ct"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
@@ -361,20 +392,20 @@ dependencies = [
|
||||
"config",
|
||||
"flate2",
|
||||
"futures",
|
||||
"gateway-api",
|
||||
"gateway-core",
|
||||
"gateway-protocol",
|
||||
"gateway-store",
|
||||
"hex",
|
||||
"hmac",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"indexmap",
|
||||
"hmac 0.13.0",
|
||||
"ipnet",
|
||||
"provider-openai",
|
||||
"provider-xai",
|
||||
"rand 0.10.2",
|
||||
"rand_core 0.6.4",
|
||||
"redis",
|
||||
"reqwest",
|
||||
"roxmltree",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"rustls-pki-types",
|
||||
"ring",
|
||||
"secrecy",
|
||||
"semver",
|
||||
"serde",
|
||||
@@ -387,17 +418,17 @@ dependencies = [
|
||||
"tempfile",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tokio-tungstenite",
|
||||
"tokio-tungstenite 0.29.0",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-http",
|
||||
"tracing",
|
||||
"tracing-appender",
|
||||
"tracing-subscriber",
|
||||
"tungstenite",
|
||||
"url",
|
||||
"uuid",
|
||||
"wiremock",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -455,6 +486,12 @@ dependencies = [
|
||||
"yaml-rust2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.10.2"
|
||||
@@ -572,6 +609,18 @@ version = "0.8.22"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
|
||||
|
||||
[[package]]
|
||||
name = "crypto-bigint"
|
||||
version = "0.5.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"rand_core 0.6.4",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
@@ -600,6 +649,33 @@ dependencies = [
|
||||
"cmov",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek"
|
||||
version = "4.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"curve25519-dalek-derive",
|
||||
"digest 0.10.7",
|
||||
"fiat-crypto",
|
||||
"rustc_version",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek-derive"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "data-encoding"
|
||||
version = "2.11.0"
|
||||
@@ -624,6 +700,17 @@ version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b"
|
||||
|
||||
[[package]]
|
||||
name = "der"
|
||||
version = "0.7.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid 0.9.6",
|
||||
"pem-rfc7468",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.8"
|
||||
@@ -637,6 +724,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer 0.10.4",
|
||||
"const-oid 0.9.6",
|
||||
"crypto-common 0.1.7",
|
||||
"subtle",
|
||||
]
|
||||
@@ -648,7 +736,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer 0.12.1",
|
||||
"const-oid",
|
||||
"const-oid 0.10.2",
|
||||
"crypto-common 0.2.2",
|
||||
"ctutils",
|
||||
]
|
||||
@@ -679,6 +767,44 @@ version = "0.15.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
|
||||
|
||||
[[package]]
|
||||
name = "ecdsa"
|
||||
version = "0.16.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
|
||||
dependencies = [
|
||||
"der",
|
||||
"digest 0.10.7",
|
||||
"elliptic-curve",
|
||||
"rfc6979",
|
||||
"signature",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519"
|
||||
version = "2.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
|
||||
dependencies = [
|
||||
"pkcs8",
|
||||
"signature",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519-dalek"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
|
||||
dependencies = [
|
||||
"curve25519-dalek",
|
||||
"ed25519",
|
||||
"serde",
|
||||
"sha2 0.10.9",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.16.0"
|
||||
@@ -688,6 +814,27 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "elliptic-curve"
|
||||
version = "0.13.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
|
||||
dependencies = [
|
||||
"base16ct",
|
||||
"crypto-bigint",
|
||||
"digest 0.10.7",
|
||||
"ff",
|
||||
"generic-array",
|
||||
"group",
|
||||
"hkdf 0.12.4",
|
||||
"pem-rfc7468",
|
||||
"pkcs8",
|
||||
"rand_core 0.6.4",
|
||||
"sec1",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "encoding_rs"
|
||||
version = "0.8.35"
|
||||
@@ -750,6 +897,22 @@ version = "2.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
|
||||
|
||||
[[package]]
|
||||
name = "ff"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393"
|
||||
dependencies = [
|
||||
"rand_core 0.6.4",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||
|
||||
[[package]]
|
||||
name = "filetime"
|
||||
version = "0.2.29"
|
||||
@@ -891,6 +1054,12 @@ version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
|
||||
|
||||
[[package]]
|
||||
name = "futures-timer"
|
||||
version = "3.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968"
|
||||
|
||||
[[package]]
|
||||
name = "futures-util"
|
||||
version = "0.3.32"
|
||||
@@ -908,6 +1077,71 @@ dependencies = [
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gateway-api"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64",
|
||||
"chrono",
|
||||
"futures",
|
||||
"gateway-core",
|
||||
"gateway-protocol",
|
||||
"rand_core 0.6.4",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"subtle",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gateway-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"chrono",
|
||||
"futures",
|
||||
"futures-timer",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gateway-protocol"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gateway-store"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"chrono",
|
||||
"futures",
|
||||
"gateway-core",
|
||||
"hex",
|
||||
"redis",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.11.0",
|
||||
"sqlx",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
@@ -916,6 +1150,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -957,6 +1192,17 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "group"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"
|
||||
dependencies = [
|
||||
"ff",
|
||||
"rand_core 0.6.4",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "h2"
|
||||
version = "0.4.15"
|
||||
@@ -1044,13 +1290,31 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hkdf"
|
||||
version = "0.12.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
|
||||
dependencies = [
|
||||
"hmac 0.12.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hkdf"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
|
||||
dependencies = [
|
||||
"hmac",
|
||||
"hmac 0.13.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1318,8 +1582,6 @@ checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown 0.17.1",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1355,11 +1617,35 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonwebtoken"
|
||||
version = "10.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0529410abe238729a60b108898784df8984c87f6054c9c4fcacc47e4803c1ce1"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"ed25519-dalek",
|
||||
"getrandom 0.2.17",
|
||||
"hmac 0.12.1",
|
||||
"js-sys",
|
||||
"p256",
|
||||
"p384",
|
||||
"rand 0.8.7",
|
||||
"rsa",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"signature",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||
dependencies = [
|
||||
"spin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
@@ -1367,6 +1653,12 @@ version = "0.2.186"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
|
||||
|
||||
[[package]]
|
||||
name = "libm"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "libsqlite3-sys"
|
||||
version = "0.37.0"
|
||||
@@ -1493,12 +1785,47 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint-dig"
|
||||
version = "0.8.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
"libm",
|
||||
"num-integer",
|
||||
"num-iter",
|
||||
"num-traits",
|
||||
"rand 0.8.7",
|
||||
"smallvec",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-iter"
|
||||
version = "0.1.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -1506,6 +1833,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1530,6 +1858,30 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
|
||||
|
||||
[[package]]
|
||||
name = "p256"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b"
|
||||
dependencies = [
|
||||
"ecdsa",
|
||||
"elliptic-curve",
|
||||
"primeorder",
|
||||
"sha2 0.10.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "p384"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6"
|
||||
dependencies = [
|
||||
"ecdsa",
|
||||
"elliptic-curve",
|
||||
"primeorder",
|
||||
"sha2 0.10.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking"
|
||||
version = "2.2.1"
|
||||
@@ -1576,6 +1928,15 @@ version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"
|
||||
|
||||
[[package]]
|
||||
name = "pem-rfc7468"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
@@ -1588,6 +1949,27 @@ version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "pkcs1"
|
||||
version = "0.7.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
|
||||
dependencies = [
|
||||
"der",
|
||||
"pkcs8",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
|
||||
dependencies = [
|
||||
"der",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.33"
|
||||
@@ -1618,6 +2000,15 @@ dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "primeorder"
|
||||
version = "0.13.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"
|
||||
dependencies = [
|
||||
"elliptic-curve",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.106"
|
||||
@@ -1627,6 +2018,72 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "provider-openai"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"async-stream",
|
||||
"async-trait",
|
||||
"base64",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"cookie",
|
||||
"futures",
|
||||
"gateway-core",
|
||||
"gateway-protocol",
|
||||
"getrandom 0.3.4",
|
||||
"hex",
|
||||
"jsonwebtoken",
|
||||
"reqwest",
|
||||
"rsa",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"rustls-pki-types",
|
||||
"secrecy",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.11.0",
|
||||
"subtle",
|
||||
"tempfile",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tokio-tungstenite 0.28.0",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
"tungstenite 0.27.0",
|
||||
"url",
|
||||
"uuid",
|
||||
"wiremock",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "provider-xai"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"async-stream",
|
||||
"async-trait",
|
||||
"base64",
|
||||
"chrono",
|
||||
"futures",
|
||||
"gateway-core",
|
||||
"gateway-protocol",
|
||||
"getrandom 0.3.4",
|
||||
"jsonwebtoken",
|
||||
"p256",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.11.0",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"url",
|
||||
"uuid",
|
||||
"wiremock",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "psl-types"
|
||||
version = "2.0.11"
|
||||
@@ -1720,13 +2177,24 @@ version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.8.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rand_chacha 0.3.1",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_chacha 0.9.0",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
@@ -1741,6 +2209,16 @@ dependencies = [
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
@@ -1893,6 +2371,16 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rfc6979"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"
|
||||
dependencies = [
|
||||
"hmac 0.12.1",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
@@ -1908,12 +2396,23 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "roxmltree"
|
||||
version = "0.21.1"
|
||||
name = "rsa"
|
||||
version = "0.9.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb"
|
||||
checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"const-oid 0.9.6",
|
||||
"digest 0.10.7",
|
||||
"num-bigint-dig",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
"pkcs1",
|
||||
"pkcs8",
|
||||
"rand_core 0.6.4",
|
||||
"signature",
|
||||
"spki",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1922,6 +2421,15 @@ version = "2.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
|
||||
dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.4"
|
||||
@@ -2009,6 +2517,20 @@ version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "sec1"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
|
||||
dependencies = [
|
||||
"base16ct",
|
||||
"der",
|
||||
"generic-array",
|
||||
"pkcs8",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "secrecy"
|
||||
version = "0.10.3"
|
||||
@@ -2190,6 +2712,16 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
||||
dependencies = [
|
||||
"digest 0.10.7",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.9"
|
||||
@@ -2230,6 +2762,16 @@ dependencies = [
|
||||
"lock_api",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"der",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sqlx"
|
||||
version = "0.9.0"
|
||||
@@ -2314,6 +2856,7 @@ dependencies = [
|
||||
"sqlx-postgres",
|
||||
"sqlx-sqlite",
|
||||
"syn",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"url",
|
||||
]
|
||||
@@ -2363,8 +2906,8 @@ dependencies = [
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"hex",
|
||||
"hkdf",
|
||||
"hmac",
|
||||
"hkdf 0.13.0",
|
||||
"hmac 0.13.0",
|
||||
"itoa",
|
||||
"log",
|
||||
"md-5",
|
||||
@@ -2634,7 +3177,19 @@ dependencies = [
|
||||
"rustls-pki-types",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tungstenite",
|
||||
"tungstenite 0.27.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-tungstenite"
|
||||
version = "0.29.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"log",
|
||||
"tokio",
|
||||
"tungstenite 0.29.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2822,6 +3377,22 @@ dependencies = [
|
||||
"utf-8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tungstenite"
|
||||
version = "0.29.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"data-encoding",
|
||||
"http",
|
||||
"httparse",
|
||||
"log",
|
||||
"rand 0.9.4",
|
||||
"sha1 0.10.7",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
@@ -3329,6 +3900,20 @@ name = "zeroize"
|
||||
version = "1.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
|
||||
dependencies = [
|
||||
"zeroize_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zeroize_derive"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerotrie"
|
||||
|
||||
+16
-62
@@ -1,73 +1,27 @@
|
||||
[package]
|
||||
name = "codex-proxy-rs"
|
||||
[workspace]
|
||||
members = [
|
||||
"apps/gateway",
|
||||
"crates/gateway-api",
|
||||
"crates/gateway-core",
|
||||
"crates/gateway-protocol",
|
||||
"crates/gateway-store",
|
||||
"crates/providers/openai",
|
||||
"crates/providers/xai",
|
||||
]
|
||||
resolver = "3"
|
||||
|
||||
[workspace.package]
|
||||
version = "0.0.0"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
publish = false
|
||||
rust-version = "1.97"
|
||||
|
||||
[dependencies]
|
||||
argon2 = "0.5.3"
|
||||
async-trait = "0.1.89"
|
||||
axum = { version = "0.8.9", default-features = false, features = ["http1", "json", "query", "tokio", "tracing"] }
|
||||
base64 = "0.22.1"
|
||||
bytes = "1.11.1"
|
||||
chrono = { version = "0.4.45", features = ["serde", "clock"] }
|
||||
config = { version = "0.15.23", default-features = false, features = ["yaml"] }
|
||||
flate2 = "1.1.9"
|
||||
futures = "0.3.32"
|
||||
hex = "0.4.3"
|
||||
hmac = "0.13.0"
|
||||
hyper = { version = "1.10.1", features = ["http1", "server"] }
|
||||
hyper-util = { version = "0.1.20", features = ["tokio"] }
|
||||
indexmap = { version = "2.0", features = ["serde"] }
|
||||
ipnet = "2.12.0"
|
||||
rand = "0.10.1"
|
||||
# Enables password_hash::rand_core::OsRng for argon2 0.5.
|
||||
rand_core = { version = "0.6.4", features = ["getrandom"] }
|
||||
redis = { version = "1.3.0", default-features = false, features = ["tokio-comp", "connection-manager", "script"] }
|
||||
roxmltree = "0.21.1"
|
||||
# Pinned to the Codex Desktop 26.707.41301 HTTP stack; re-audit a newer Desktop before upgrading.
|
||||
reqwest = { version = "=0.12.28", default-features = false, features = ["json", "stream", "cookies", "rustls-tls-native-roots", "gzip", "brotli", "zstd", "deflate", "http2"] }
|
||||
rustls = { version = "=0.23.42", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
rustls-native-certs = "0.8.4"
|
||||
rustls-pki-types = "1.14.1"
|
||||
secrecy = { version = "0.10.3", features = ["serde"] }
|
||||
semver = "1.0.27"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = { version = "1.0.150", features = ["preserve_order"] }
|
||||
sha2 = "0.11.0"
|
||||
sqlx = { version = "0.9.0", default-features = false, features = ["runtime-tokio", "tls-rustls", "postgres", "chrono", "json"] }
|
||||
subtle = "2.6.1"
|
||||
tar = "0.4.44"
|
||||
thiserror = "2.0.18"
|
||||
tokio = { version = "1.52.3", default-features = false, features = ["macros", "rt-multi-thread", "signal", "fs", "time", "sync", "net"] }
|
||||
tokio-util = { version = "0.7.18", features = ["rt"] }
|
||||
tokio-tungstenite = { version = "0.28.0", features = ["proxy", "rustls-tls-native-roots"] }
|
||||
tower = { version = "0.5.3", features = ["util"] }
|
||||
tower-http = { version = "0.6.11", features = ["trace", "cors", "request-id", "timeout", "fs"] }
|
||||
tracing = "0.1.44"
|
||||
tracing-appender = "0.2.5"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] }
|
||||
tungstenite = { version = "0.27.0", features = ["deflate", "proxy"] }
|
||||
url = "2.5.8"
|
||||
uuid = { version = "1.23.3", features = ["v4", "v7", "serde"] }
|
||||
|
||||
[dev-dependencies]
|
||||
sqlx = { version = "0.9.0", default-features = false, features = ["derive"] }
|
||||
syn = { version = "2.0.118", features = ["full", "visit"] }
|
||||
tempfile = "3.27.0"
|
||||
tokio = { version = "1.52.3", default-features = false, features = ["test-util"] }
|
||||
wiremock = "0.6.5"
|
||||
|
||||
[patch.crates-io]
|
||||
tokio-tungstenite = { git = "https://github.com/openai-oss-forks/tokio-tungstenite", rev = "0e5b2d73aa18dd9f0a50ee9ff199d5aef7594186" }
|
||||
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "4fffad30fe373adbdcffab9545e9e9bf4f2fc19f" }
|
||||
|
||||
[lints.rust]
|
||||
[workspace.lints.rust]
|
||||
warnings = "deny"
|
||||
unsafe_code = "forbid"
|
||||
|
||||
[lints.clippy]
|
||||
[workspace.lints.clippy]
|
||||
all = { level = "deny", priority = 10 }
|
||||
redundant_clone = { level = "deny", priority = 9 }
|
||||
large_enum_variant = { level = "warn", priority = 8 }
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
[package]
|
||||
name = "codex-proxy-rs"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
rust-version.workspace = true
|
||||
autotests = false
|
||||
|
||||
[lib]
|
||||
path = "src/bootstrap.rs"
|
||||
|
||||
[[test]]
|
||||
name = "main"
|
||||
path = "tests/main.rs"
|
||||
|
||||
[dependencies]
|
||||
argon2 = "0.5.3"
|
||||
async-trait = "0.1.89"
|
||||
axum = { version = "0.8.9", default-features = false, features = ["http1", "json", "query", "tokio", "tracing", "ws"] }
|
||||
base64 = "0.22.1"
|
||||
bytes = "1.11.1"
|
||||
chrono = { version = "0.4.45", features = ["serde", "clock"] }
|
||||
config = { version = "0.15.23", default-features = false, features = ["yaml"] }
|
||||
flate2 = "1.1.9"
|
||||
futures = "0.3.32"
|
||||
gateway-api = { path = "../../crates/gateway-api" }
|
||||
gateway-core = { path = "../../crates/gateway-core" }
|
||||
gateway-protocol = { path = "../../crates/gateway-protocol" }
|
||||
gateway-store = { path = "../../crates/gateway-store" }
|
||||
provider-openai = { path = "../../crates/providers/openai" }
|
||||
provider-xai = { path = "../../crates/providers/xai" }
|
||||
hex = "0.4.3"
|
||||
hmac = "0.13.0"
|
||||
ipnet = "2.12.0"
|
||||
rand = "0.10.1"
|
||||
# Enables password_hash::rand_core::OsRng for argon2 0.5.
|
||||
rand_core = { version = "0.6.4", features = ["getrandom"] }
|
||||
redis = { version = "1.3.0", default-features = false, features = ["tokio-comp", "connection-manager", "script"] }
|
||||
ring = "0.17.14"
|
||||
# Pinned to the Codex Desktop 26.707.41301 HTTP stack; re-audit a newer Desktop before upgrading.
|
||||
reqwest = { version = "=0.12.28", default-features = false, features = ["json", "stream", "cookies", "rustls-tls-native-roots", "gzip", "brotli", "zstd", "deflate", "http2"] }
|
||||
secrecy = { version = "0.10.3", features = ["serde"] }
|
||||
semver = "1.0.27"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = { version = "1.0.150", features = ["preserve_order"] }
|
||||
sha2 = "0.11.0"
|
||||
sqlx = { version = "0.9.0", default-features = false, features = ["runtime-tokio", "tls-rustls", "postgres", "chrono", "json"] }
|
||||
subtle = "2.6.1"
|
||||
tar = "0.4.44"
|
||||
thiserror = "2.0.18"
|
||||
tokio = { version = "1.52.3", default-features = false, features = ["macros", "rt-multi-thread", "signal", "fs", "time", "sync", "net"] }
|
||||
tokio-util = { version = "0.7.18", features = ["rt"] }
|
||||
tower = { version = "0.5.3", features = ["util"] }
|
||||
tower-http = { version = "0.6.11", features = ["trace", "cors", "request-id", "timeout", "fs"] }
|
||||
tracing = "0.1.44"
|
||||
tracing-appender = "0.2.5"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] }
|
||||
url = "2.5.8"
|
||||
uuid = { version = "1.23.3", features = ["v4", "v7", "serde"] }
|
||||
zeroize = { version = "1.8.2", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
sqlx = { version = "0.9.0", default-features = false, features = ["derive"] }
|
||||
syn = { version = "2.0.118", features = ["full", "visit"] }
|
||||
tempfile = "3.27.0"
|
||||
tokio = { version = "1.52.3", default-features = false, features = ["test-util"] }
|
||||
tokio-tungstenite = "0.29.0"
|
||||
wiremock = "0.6.5"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::{env, fs};
|
||||
|
||||
const RELEASE_VERSION_FILE: &str = "../release/version.yaml";
|
||||
const RELEASE_VERSION_FILE: &str = "../../../release/version.yaml";
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed={RELEASE_VERSION_FILE}");
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,34 @@
|
||||
use std::{env, error::Error, io};
|
||||
|
||||
use codex_proxy_rs::{BootstrapConfig, run};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let mut arguments = env::args_os().skip(1);
|
||||
match arguments.next().as_deref().and_then(|value| value.to_str()) {
|
||||
None | Some("serve") => {
|
||||
reject_extra_arguments(arguments)?;
|
||||
let config = BootstrapConfig::load()?;
|
||||
runtime()?.block_on(run(config))
|
||||
}
|
||||
Some(command) => {
|
||||
Err(invalid_cli(&format!("unknown command {command:?}; expected serve")).into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn runtime() -> Result<tokio::runtime::Runtime, io::Error> {
|
||||
tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
}
|
||||
|
||||
fn reject_extra_arguments(mut arguments: impl Iterator) -> Result<(), io::Error> {
|
||||
if arguments.next().is_some() {
|
||||
return Err(invalid_cli("unexpected extra command arguments"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn invalid_cli(message: &str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidInput, message)
|
||||
}
|
||||
@@ -0,0 +1,894 @@
|
||||
//! 后台任务注册、leader lease、监督、退避、健康状态与优雅关闭。
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fmt;
|
||||
use std::num::NonZeroU64;
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use futures::FutureExt as _;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// 冻结架构允许出现的六类后台任务组。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum WorkerKind {
|
||||
OAuthRefresh,
|
||||
QuotaCatalogHealth,
|
||||
NativeClaimRecovery,
|
||||
StaleModelRequestRecovery,
|
||||
Retention,
|
||||
OpsFlush,
|
||||
}
|
||||
|
||||
impl WorkerKind {
|
||||
pub const ALL: [Self; 6] = [
|
||||
Self::OAuthRefresh,
|
||||
Self::QuotaCatalogHealth,
|
||||
Self::NativeClaimRecovery,
|
||||
Self::StaleModelRequestRecovery,
|
||||
Self::Retention,
|
||||
Self::OpsFlush,
|
||||
];
|
||||
|
||||
#[must_use]
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::OAuthRefresh => "oauth_refresh",
|
||||
Self::QuotaCatalogHealth => "quota_catalog_health",
|
||||
Self::NativeClaimRecovery => "native_claim_recovery",
|
||||
Self::StaleModelRequestRecovery => "stale_model_request_recovery",
|
||||
Self::Retention => "retention",
|
||||
Self::OpsFlush => "ops_flush",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for WorkerKind {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// 同类任务中的真实 owner 标识;一个任务组可以组合多个 owner。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct WorkerId {
|
||||
kind: WorkerKind,
|
||||
owner: String,
|
||||
}
|
||||
|
||||
impl WorkerId {
|
||||
pub fn new(kind: WorkerKind, owner: impl Into<String>) -> Result<Self, WorkerRegistryError> {
|
||||
let owner = owner.into();
|
||||
if !valid_owner(&owner) {
|
||||
return Err(WorkerRegistryError::InvalidOwner(owner));
|
||||
}
|
||||
Ok(Self { kind, owner })
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn kind(&self) -> WorkerKind {
|
||||
self.kind
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn owner(&self) -> &str {
|
||||
&self.owner
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for WorkerId {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(formatter, "{}:{}", self.kind, self.owner)
|
||||
}
|
||||
}
|
||||
|
||||
/// Final DB 明确不存在对应状态时允许使用的两种终态。
|
||||
///
|
||||
/// 该枚举刻意不提供通用字符串分支,避免把缺少 owner 的真实任务伪装成禁用。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum WorkerDisabledReason {
|
||||
NoPersistentNativeClaimState,
|
||||
NoBufferedOpsEvents,
|
||||
}
|
||||
|
||||
impl WorkerDisabledReason {
|
||||
#[must_use]
|
||||
pub const fn kind(self) -> WorkerKind {
|
||||
match self {
|
||||
Self::NoPersistentNativeClaimState => WorkerKind::NativeClaimRecovery,
|
||||
Self::NoBufferedOpsEvents => WorkerKind::OpsFlush,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::NoPersistentNativeClaimState => {
|
||||
"native continuation has no persistent claim state"
|
||||
}
|
||||
Self::NoBufferedOpsEvents => "ops events have no flush buffer",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for WorkerDisabledReason {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// 正整数 fencing token。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct WorkerFencingToken(NonZeroU64);
|
||||
|
||||
impl WorkerFencingToken {
|
||||
#[must_use]
|
||||
pub const fn new(value: NonZeroU64) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn get(self) -> u64 {
|
||||
self.0.get()
|
||||
}
|
||||
}
|
||||
|
||||
/// 一次 leader lease 申请;resource 由任务 kind 与 owner 共同确定。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct WorkerLeaseRequest {
|
||||
worker: WorkerId,
|
||||
ttl: Duration,
|
||||
}
|
||||
|
||||
impl WorkerLeaseRequest {
|
||||
#[must_use]
|
||||
pub const fn worker(&self) -> &WorkerId {
|
||||
&self.worker
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn ttl(&self) -> Duration {
|
||||
self.ttl
|
||||
}
|
||||
}
|
||||
|
||||
/// Leader lease guard 暴露 fencing token 与续租操作,并在 Drop 时释放。
|
||||
#[async_trait]
|
||||
pub trait WorkerLeaderLeaseGuard: Send + Sync + 'static {
|
||||
fn fencing_token(&self) -> WorkerFencingToken;
|
||||
|
||||
async fn renew(&mut self) -> Result<(), WorkerLeaseError>;
|
||||
}
|
||||
|
||||
/// Leader lease 的稳定获取结果。
|
||||
pub enum WorkerLeaseAcquisition {
|
||||
Acquired(Box<dyn WorkerLeaderLeaseGuard>),
|
||||
Busy { retry_after: Option<Duration> },
|
||||
}
|
||||
|
||||
impl fmt::Debug for WorkerLeaseAcquisition {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Acquired(_) => formatter.write_str("Acquired([LEASE_GUARD])"),
|
||||
Self::Busy { retry_after } => formatter
|
||||
.debug_struct("Busy")
|
||||
.field("retry_after", retry_after)
|
||||
.finish(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 多实例 worker leader lease 的 App 抽象端口。
|
||||
#[async_trait]
|
||||
pub trait WorkerLeaderLeasePort: Send + Sync + 'static {
|
||||
async fn try_acquire(
|
||||
&self,
|
||||
request: WorkerLeaseRequest,
|
||||
) -> Result<WorkerLeaseAcquisition, WorkerLeaseError>;
|
||||
}
|
||||
|
||||
/// 不暴露 Redis 原文或资源标识的 lease 错误。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("{message}")]
|
||||
pub struct WorkerLeaseError {
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl WorkerLeaseError {
|
||||
#[must_use]
|
||||
pub fn safe(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn as_safe_str(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
}
|
||||
|
||||
/// 任务算法收到的单周期上下文。
|
||||
#[derive(Clone)]
|
||||
pub struct WorkerCycleContext {
|
||||
worker: WorkerId,
|
||||
fencing_token: WorkerFencingToken,
|
||||
cancellation: CancellationToken,
|
||||
}
|
||||
|
||||
impl WorkerCycleContext {
|
||||
#[must_use]
|
||||
pub const fn worker(&self) -> &WorkerId {
|
||||
&self.worker
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn fencing_token(&self) -> WorkerFencingToken {
|
||||
self.fencing_token
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn is_cancelled(&self) -> bool {
|
||||
self.cancellation.is_cancelled()
|
||||
}
|
||||
|
||||
pub async fn cancelled(&self) {
|
||||
self.cancellation.cancelled().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// 任务算法的外层端口。实现必须位于对应 Store 或 Provider owner。
|
||||
#[async_trait]
|
||||
pub trait WorkerTask: Send + Sync + 'static {
|
||||
async fn run_cycle(&self, context: WorkerCycleContext) -> Result<(), WorkerTaskError>;
|
||||
}
|
||||
|
||||
/// 不暴露 Provider 原文或存储细节的后台任务错误。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("{message}")]
|
||||
pub struct WorkerTaskError {
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl WorkerTaskError {
|
||||
#[must_use]
|
||||
pub fn safe(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn as_safe_str(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
}
|
||||
|
||||
/// 单个 owner 任务的固定监督策略。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct WorkerSchedule {
|
||||
interval: Duration,
|
||||
initial_backoff: Duration,
|
||||
maximum_backoff: Duration,
|
||||
leader_lease_ttl: Duration,
|
||||
leader_lease_renewal_interval: Duration,
|
||||
}
|
||||
|
||||
impl WorkerSchedule {
|
||||
/// 所有时长都必须大于零,且最大退避不能小于初始退避。
|
||||
pub fn new(
|
||||
interval: Duration,
|
||||
initial_backoff: Duration,
|
||||
maximum_backoff: Duration,
|
||||
leader_lease_ttl: Duration,
|
||||
) -> Result<Self, WorkerRegistryError> {
|
||||
let Some(leader_lease_renewal_interval) = leader_lease_ttl.checked_div(3) else {
|
||||
return Err(WorkerRegistryError::InvalidSchedule);
|
||||
};
|
||||
if interval.is_zero()
|
||||
|| initial_backoff.is_zero()
|
||||
|| maximum_backoff < initial_backoff
|
||||
|| leader_lease_ttl.is_zero()
|
||||
|| leader_lease_renewal_interval.is_zero()
|
||||
{
|
||||
return Err(WorkerRegistryError::InvalidSchedule);
|
||||
}
|
||||
Ok(Self {
|
||||
interval,
|
||||
initial_backoff,
|
||||
maximum_backoff,
|
||||
leader_lease_ttl,
|
||||
leader_lease_renewal_interval,
|
||||
})
|
||||
}
|
||||
|
||||
fn success_freshness(self) -> Duration {
|
||||
self.interval
|
||||
.saturating_mul(2)
|
||||
.saturating_add(self.maximum_backoff)
|
||||
}
|
||||
}
|
||||
|
||||
struct WorkerRegistration {
|
||||
id: WorkerId,
|
||||
task: Arc<dyn WorkerTask>,
|
||||
schedule: WorkerSchedule,
|
||||
}
|
||||
|
||||
/// 六类终态 worker 的唯一注册表。
|
||||
#[derive(Default)]
|
||||
pub struct WorkerRegistry {
|
||||
registrations: BTreeMap<WorkerId, WorkerRegistration>,
|
||||
disabled: BTreeMap<WorkerKind, WorkerDisabledReason>,
|
||||
}
|
||||
|
||||
impl WorkerRegistry {
|
||||
#[must_use]
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
registrations: BTreeMap::new(),
|
||||
disabled: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 注册一个真实 Store/Provider-owned 周期任务。
|
||||
pub fn register(
|
||||
&mut self,
|
||||
kind: WorkerKind,
|
||||
owner: impl Into<String>,
|
||||
task: Arc<dyn WorkerTask>,
|
||||
schedule: WorkerSchedule,
|
||||
) -> Result<(), WorkerRegistryError> {
|
||||
if self.disabled.contains_key(&kind) {
|
||||
return Err(WorkerRegistryError::KindDisabled(kind));
|
||||
}
|
||||
let id = WorkerId::new(kind, owner)?;
|
||||
if self.registrations.contains_key(&id) {
|
||||
return Err(WorkerRegistryError::Duplicate(id));
|
||||
}
|
||||
self.registrations
|
||||
.insert(id.clone(), WorkerRegistration { id, task, schedule });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 声明 Final DB 不存在相应可恢复或可 flush 状态。
|
||||
pub fn disable(&mut self, reason: WorkerDisabledReason) -> Result<(), WorkerRegistryError> {
|
||||
let kind = reason.kind();
|
||||
if self
|
||||
.registrations
|
||||
.keys()
|
||||
.any(|registered| registered.kind() == kind)
|
||||
{
|
||||
return Err(WorkerRegistryError::KindHasTasks(kind));
|
||||
}
|
||||
if self.disabled.insert(kind, reason).is_some() {
|
||||
return Err(WorkerRegistryError::DuplicateDisabled(kind));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 校验六类 worker 都有真实 owner 或合法终态后启动监督器。
|
||||
pub fn start(
|
||||
self,
|
||||
leader_leases: Arc<dyn WorkerLeaderLeasePort>,
|
||||
) -> Result<WorkerSupervisor, WorkerRegistryError> {
|
||||
let active_kinds = self
|
||||
.registrations
|
||||
.keys()
|
||||
.map(WorkerId::kind)
|
||||
.collect::<BTreeSet<_>>();
|
||||
let missing = WorkerKind::ALL
|
||||
.into_iter()
|
||||
.filter(|kind| !active_kinds.contains(kind) && !self.disabled.contains_key(kind))
|
||||
.collect::<Vec<_>>();
|
||||
if !missing.is_empty() {
|
||||
return Err(WorkerRegistryError::Missing(missing));
|
||||
}
|
||||
|
||||
let cancellation = CancellationToken::new();
|
||||
let health = WorkerHealthRegistry::new(&self.registrations, &self.disabled);
|
||||
let active_ids = self.registrations.keys().cloned().collect::<Vec<_>>();
|
||||
let handles = self
|
||||
.registrations
|
||||
.into_values()
|
||||
.map(|registration| {
|
||||
let id = registration.id.clone();
|
||||
let handle = spawn_worker(
|
||||
registration,
|
||||
Arc::clone(&leader_leases),
|
||||
cancellation.child_token(),
|
||||
health.clone(),
|
||||
);
|
||||
(id, handle)
|
||||
})
|
||||
.collect();
|
||||
Ok(WorkerSupervisor {
|
||||
cancellation,
|
||||
health,
|
||||
active_ids,
|
||||
handles,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 注册或启动监督器失败。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum WorkerRegistryError {
|
||||
#[error("worker schedule is invalid")]
|
||||
InvalidSchedule,
|
||||
#[error("worker owner is invalid: {0}")]
|
||||
InvalidOwner(String),
|
||||
#[error("worker `{0}` was registered more than once")]
|
||||
Duplicate(WorkerId),
|
||||
#[error("worker kind `{0}` is already disabled")]
|
||||
KindDisabled(WorkerKind),
|
||||
#[error("worker kind `{0}` already has real tasks")]
|
||||
KindHasTasks(WorkerKind),
|
||||
#[error("worker kind `{0}` was disabled more than once")]
|
||||
DuplicateDisabled(WorkerKind),
|
||||
#[error("required workers are missing: {0:?}")]
|
||||
Missing(Vec<WorkerKind>),
|
||||
}
|
||||
|
||||
/// 一个 owner 任务的运行状态。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum WorkerRuntimeState {
|
||||
Starting,
|
||||
AcquiringLease,
|
||||
Standby,
|
||||
Running,
|
||||
Idle,
|
||||
BackingOff,
|
||||
Stopped,
|
||||
Disabled(WorkerDisabledReason),
|
||||
}
|
||||
|
||||
/// 健康快照中的稳定 key。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum WorkerHealthKey {
|
||||
Task(WorkerId),
|
||||
Disabled(WorkerKind),
|
||||
}
|
||||
|
||||
/// 一个任务或终态 worker kind 的监督状态。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct WorkerHealth {
|
||||
pub state: WorkerRuntimeState,
|
||||
pub consecutive_failures: u32,
|
||||
pub completed_cycles: u64,
|
||||
pub last_fencing_token: Option<WorkerFencingToken>,
|
||||
pub last_success_at: Option<SystemTime>,
|
||||
pub last_failure_at: Option<SystemTime>,
|
||||
pub last_error: Option<String>,
|
||||
success_freshness: Duration,
|
||||
}
|
||||
|
||||
impl WorkerHealth {
|
||||
fn active(schedule: WorkerSchedule) -> Self {
|
||||
Self {
|
||||
state: WorkerRuntimeState::Starting,
|
||||
consecutive_failures: 0,
|
||||
completed_cycles: 0,
|
||||
last_fencing_token: None,
|
||||
last_success_at: None,
|
||||
last_failure_at: None,
|
||||
last_error: None,
|
||||
success_freshness: schedule.success_freshness(),
|
||||
}
|
||||
}
|
||||
|
||||
const fn disabled(reason: WorkerDisabledReason) -> Self {
|
||||
Self {
|
||||
state: WorkerRuntimeState::Disabled(reason),
|
||||
consecutive_failures: 0,
|
||||
completed_cycles: 0,
|
||||
last_fencing_token: None,
|
||||
last_success_at: None,
|
||||
last_failure_at: None,
|
||||
last_error: None,
|
||||
success_freshness: Duration::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_healthy(&self, now: SystemTime) -> bool {
|
||||
match self.state {
|
||||
WorkerRuntimeState::Disabled(_) | WorkerRuntimeState::Standby => true,
|
||||
WorkerRuntimeState::AcquiringLease
|
||||
| WorkerRuntimeState::Running
|
||||
| WorkerRuntimeState::Idle => {
|
||||
self.consecutive_failures == 0
|
||||
&& self.last_success_at.is_some_and(|last_success| {
|
||||
now.duration_since(last_success)
|
||||
.is_ok_and(|age| age <= self.success_freshness)
|
||||
})
|
||||
}
|
||||
WorkerRuntimeState::Starting
|
||||
| WorkerRuntimeState::BackingOff
|
||||
| WorkerRuntimeState::Stopped => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 可供健康检查读取的 worker 状态快照。
|
||||
#[derive(Clone)]
|
||||
pub struct WorkerHealthRegistry {
|
||||
states: Arc<Mutex<BTreeMap<WorkerHealthKey, WorkerHealth>>>,
|
||||
}
|
||||
|
||||
impl WorkerHealthRegistry {
|
||||
fn new(
|
||||
registrations: &BTreeMap<WorkerId, WorkerRegistration>,
|
||||
disabled: &BTreeMap<WorkerKind, WorkerDisabledReason>,
|
||||
) -> Self {
|
||||
let mut states = registrations
|
||||
.values()
|
||||
.map(|registration| {
|
||||
(
|
||||
WorkerHealthKey::Task(registration.id.clone()),
|
||||
WorkerHealth::active(registration.schedule),
|
||||
)
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
states.extend(disabled.iter().map(|(kind, reason)| {
|
||||
(
|
||||
WorkerHealthKey::Disabled(*kind),
|
||||
WorkerHealth::disabled(*reason),
|
||||
)
|
||||
}));
|
||||
Self {
|
||||
states: Arc::new(Mutex::new(states)),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn snapshot(&self) -> BTreeMap<WorkerHealthKey, WorkerHealth> {
|
||||
lock_unpoisoned(&self.states).clone()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn all_healthy(&self) -> bool {
|
||||
let now = SystemTime::now();
|
||||
lock_unpoisoned(&self.states)
|
||||
.values()
|
||||
.all(|health| health.is_healthy(now))
|
||||
}
|
||||
|
||||
fn update_task(&self, id: &WorkerId, update: impl FnOnce(&mut WorkerHealth)) {
|
||||
if let Some(state) =
|
||||
lock_unpoisoned(&self.states).get_mut(&WorkerHealthKey::Task(id.clone()))
|
||||
{
|
||||
update(state);
|
||||
}
|
||||
}
|
||||
|
||||
fn acquiring_lease(&self, id: &WorkerId) {
|
||||
self.update_task(id, |state| {
|
||||
state.state = WorkerRuntimeState::AcquiringLease;
|
||||
});
|
||||
}
|
||||
|
||||
fn standby(&self, id: &WorkerId) {
|
||||
self.update_task(id, |state| {
|
||||
state.state = WorkerRuntimeState::Standby;
|
||||
state.consecutive_failures = 0;
|
||||
state.last_error = None;
|
||||
});
|
||||
}
|
||||
|
||||
fn running(&self, id: &WorkerId, fencing_token: WorkerFencingToken) {
|
||||
self.update_task(id, |state| {
|
||||
state.state = WorkerRuntimeState::Running;
|
||||
state.last_fencing_token = Some(fencing_token);
|
||||
});
|
||||
}
|
||||
|
||||
fn succeeded(&self, id: &WorkerId) {
|
||||
self.update_task(id, |state| {
|
||||
state.state = WorkerRuntimeState::Idle;
|
||||
state.consecutive_failures = 0;
|
||||
state.completed_cycles = state.completed_cycles.saturating_add(1);
|
||||
state.last_success_at = Some(SystemTime::now());
|
||||
state.last_error = None;
|
||||
});
|
||||
}
|
||||
|
||||
fn failed(&self, id: &WorkerId, error: String) -> u32 {
|
||||
let mut failures = 0;
|
||||
self.update_task(id, |state| {
|
||||
state.state = WorkerRuntimeState::BackingOff;
|
||||
state.consecutive_failures = state.consecutive_failures.saturating_add(1);
|
||||
state.last_failure_at = Some(SystemTime::now());
|
||||
state.last_error = Some(error);
|
||||
failures = state.consecutive_failures;
|
||||
});
|
||||
failures
|
||||
}
|
||||
|
||||
fn stopped(&self, id: &WorkerId) {
|
||||
self.update_task(id, |state| {
|
||||
state.state = WorkerRuntimeState::Stopped;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 所有后台任务的统一 shutdown/join 句柄。
|
||||
pub struct WorkerSupervisor {
|
||||
cancellation: CancellationToken,
|
||||
health: WorkerHealthRegistry,
|
||||
active_ids: Vec<WorkerId>,
|
||||
handles: Vec<(WorkerId, JoinHandle<()>)>,
|
||||
}
|
||||
|
||||
impl WorkerSupervisor {
|
||||
#[must_use]
|
||||
pub const fn health(&self) -> &WorkerHealthRegistry {
|
||||
&self.health
|
||||
}
|
||||
|
||||
/// 先协作取消;超时后强制 abort,并等待 guard 完成 Drop。
|
||||
pub async fn shutdown(mut self, timeout: Duration) {
|
||||
self.cancellation.cancel();
|
||||
let mut handles = std::mem::take(&mut self.handles);
|
||||
let completed = tokio::time::timeout(timeout, async {
|
||||
for (_, handle) in &mut handles {
|
||||
let _ = handle.await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.is_ok();
|
||||
if !completed {
|
||||
for (_, handle) in &handles {
|
||||
handle.abort();
|
||||
}
|
||||
for (_, handle) in handles {
|
||||
let _ = handle.await;
|
||||
}
|
||||
}
|
||||
for id in &self.active_ids {
|
||||
self.health.stopped(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WorkerSupervisor {
|
||||
fn drop(&mut self) {
|
||||
self.cancellation.cancel();
|
||||
for (_, handle) in &self.handles {
|
||||
handle.abort();
|
||||
}
|
||||
for id in &self.active_ids {
|
||||
self.health.stopped(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_worker(
|
||||
registration: WorkerRegistration,
|
||||
leader_leases: Arc<dyn WorkerLeaderLeasePort>,
|
||||
cancellation: CancellationToken,
|
||||
health: WorkerHealthRegistry,
|
||||
) -> JoinHandle<()> {
|
||||
tokio::spawn(async move {
|
||||
supervise_worker(registration, leader_leases, cancellation, &health).await;
|
||||
})
|
||||
}
|
||||
|
||||
async fn supervise_worker(
|
||||
registration: WorkerRegistration,
|
||||
leader_leases: Arc<dyn WorkerLeaderLeasePort>,
|
||||
cancellation: CancellationToken,
|
||||
health: &WorkerHealthRegistry,
|
||||
) {
|
||||
let WorkerRegistration { id, task, schedule } = registration;
|
||||
let mut backoff = schedule.initial_backoff;
|
||||
|
||||
loop {
|
||||
health.acquiring_lease(&id);
|
||||
let request = WorkerLeaseRequest {
|
||||
worker: id.clone(),
|
||||
ttl: schedule.leader_lease_ttl,
|
||||
};
|
||||
let acquisition = AssertUnwindSafe(leader_leases.try_acquire(request)).catch_unwind();
|
||||
tokio::pin!(acquisition);
|
||||
let acquisition = tokio::select! {
|
||||
() = cancellation.cancelled() => break,
|
||||
acquisition = &mut acquisition => acquisition,
|
||||
};
|
||||
|
||||
let delay = match acquisition {
|
||||
Ok(Ok(WorkerLeaseAcquisition::Acquired(guard))) => {
|
||||
match run_leased_cycle(
|
||||
&id,
|
||||
&task,
|
||||
guard,
|
||||
schedule.leader_lease_renewal_interval,
|
||||
&cancellation,
|
||||
health,
|
||||
)
|
||||
.await
|
||||
{
|
||||
LeasedCycleOutcome::Completed(TaskCycleOutcome::Succeeded) => {
|
||||
health.succeeded(&id);
|
||||
backoff = schedule.initial_backoff;
|
||||
schedule.interval
|
||||
}
|
||||
LeasedCycleOutcome::Completed(TaskCycleOutcome::Failed(error)) => {
|
||||
let failures = health.failed(&id, error.as_safe_str().to_owned());
|
||||
tracing::warn!(
|
||||
worker = %id,
|
||||
failures,
|
||||
"后台任务周期执行失败"
|
||||
);
|
||||
take_backoff(&mut backoff, schedule.maximum_backoff)
|
||||
}
|
||||
LeasedCycleOutcome::Completed(TaskCycleOutcome::Panicked) => {
|
||||
let failures = health.failed(&id, "worker panicked".to_owned());
|
||||
tracing::error!(worker = %id, failures, "后台任务发生 panic");
|
||||
take_backoff(&mut backoff, schedule.maximum_backoff)
|
||||
}
|
||||
LeasedCycleOutcome::LeaseLost(error) => {
|
||||
let failures = health.failed(&id, error);
|
||||
tracing::warn!(worker = %id, failures, "后台任务 leader lease 已失效");
|
||||
take_backoff(&mut backoff, schedule.maximum_backoff)
|
||||
}
|
||||
LeasedCycleOutcome::ShuttingDown => break,
|
||||
}
|
||||
}
|
||||
Ok(Ok(WorkerLeaseAcquisition::Busy { retry_after })) => {
|
||||
health.standby(&id);
|
||||
retry_after
|
||||
.filter(|delay| !delay.is_zero())
|
||||
.unwrap_or(schedule.interval)
|
||||
.min(schedule.maximum_backoff)
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
let failures = health.failed(&id, error.as_safe_str().to_owned());
|
||||
tracing::warn!(worker = %id, failures, "后台任务 leader lease 获取失败");
|
||||
take_backoff(&mut backoff, schedule.maximum_backoff)
|
||||
}
|
||||
Err(_) => {
|
||||
let failures = health.failed(&id, "leader lease port panicked".to_owned());
|
||||
tracing::error!(worker = %id, failures, "后台任务 leader lease 端口发生 panic");
|
||||
take_backoff(&mut backoff, schedule.maximum_backoff)
|
||||
}
|
||||
};
|
||||
|
||||
tokio::select! {
|
||||
() = cancellation.cancelled() => break,
|
||||
() = tokio::time::sleep(delay) => {}
|
||||
}
|
||||
}
|
||||
health.stopped(&id);
|
||||
}
|
||||
|
||||
enum TaskCycleOutcome {
|
||||
Succeeded,
|
||||
Failed(WorkerTaskError),
|
||||
Panicked,
|
||||
}
|
||||
|
||||
enum LeasedCycleOutcome {
|
||||
Completed(TaskCycleOutcome),
|
||||
LeaseLost(String),
|
||||
ShuttingDown,
|
||||
}
|
||||
|
||||
async fn run_leased_cycle(
|
||||
id: &WorkerId,
|
||||
task: &Arc<dyn WorkerTask>,
|
||||
mut guard: Box<dyn WorkerLeaderLeaseGuard>,
|
||||
renewal_interval: Duration,
|
||||
cancellation: &CancellationToken,
|
||||
health: &WorkerHealthRegistry,
|
||||
) -> LeasedCycleOutcome {
|
||||
let fencing_token = match std::panic::catch_unwind(AssertUnwindSafe(|| guard.fencing_token())) {
|
||||
Ok(fencing_token) => fencing_token,
|
||||
Err(_) => return LeasedCycleOutcome::LeaseLost("leader lease guard panicked".to_owned()),
|
||||
};
|
||||
health.running(id, fencing_token);
|
||||
let cycle_cancellation = cancellation.child_token();
|
||||
let context = WorkerCycleContext {
|
||||
worker: id.clone(),
|
||||
fencing_token,
|
||||
cancellation: cycle_cancellation.clone(),
|
||||
};
|
||||
let cycle = run_task_cycle(task, context);
|
||||
tokio::pin!(cycle);
|
||||
let renewal_sleep = tokio::time::sleep(renewal_interval);
|
||||
tokio::pin!(renewal_sleep);
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
outcome = &mut cycle => return LeasedCycleOutcome::Completed(outcome),
|
||||
() = cancellation.cancelled() => {
|
||||
cycle_cancellation.cancel();
|
||||
let _ = cycle.await;
|
||||
return LeasedCycleOutcome::ShuttingDown;
|
||||
}
|
||||
() = &mut renewal_sleep => {
|
||||
let renewal = AssertUnwindSafe(guard.renew()).catch_unwind();
|
||||
tokio::pin!(renewal);
|
||||
let renewal_timeout = tokio::time::sleep(renewal_interval);
|
||||
tokio::pin!(renewal_timeout);
|
||||
let renewal = tokio::select! {
|
||||
biased;
|
||||
outcome = &mut cycle => {
|
||||
return LeasedCycleOutcome::Completed(outcome);
|
||||
}
|
||||
() = cancellation.cancelled() => {
|
||||
cycle_cancellation.cancel();
|
||||
let _ = cycle.await;
|
||||
return LeasedCycleOutcome::ShuttingDown;
|
||||
}
|
||||
renewal = &mut renewal => Some(renewal),
|
||||
() = &mut renewal_timeout => None,
|
||||
};
|
||||
match renewal {
|
||||
Some(Ok(Ok(()))) => {
|
||||
renewal_sleep
|
||||
.as_mut()
|
||||
.reset(tokio::time::Instant::now() + renewal_interval);
|
||||
}
|
||||
Some(Ok(Err(error))) => {
|
||||
cycle_cancellation.cancel();
|
||||
return LeasedCycleOutcome::LeaseLost(error.as_safe_str().to_owned());
|
||||
}
|
||||
Some(Err(_)) => {
|
||||
cycle_cancellation.cancel();
|
||||
return LeasedCycleOutcome::LeaseLost(
|
||||
"leader lease renewal panicked".to_owned(),
|
||||
);
|
||||
}
|
||||
None => {
|
||||
cycle_cancellation.cancel();
|
||||
return LeasedCycleOutcome::LeaseLost(
|
||||
"leader lease renewal timed out".to_owned(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_task_cycle(
|
||||
task: &Arc<dyn WorkerTask>,
|
||||
context: WorkerCycleContext,
|
||||
) -> TaskCycleOutcome {
|
||||
match AssertUnwindSafe(task.run_cycle(context))
|
||||
.catch_unwind()
|
||||
.await
|
||||
{
|
||||
Ok(Ok(())) => TaskCycleOutcome::Succeeded,
|
||||
Ok(Err(error)) => TaskCycleOutcome::Failed(error),
|
||||
Err(_) => TaskCycleOutcome::Panicked,
|
||||
}
|
||||
}
|
||||
|
||||
fn take_backoff(backoff: &mut Duration, maximum: Duration) -> Duration {
|
||||
let delay = *backoff;
|
||||
*backoff = backoff.checked_mul(2).unwrap_or(maximum).min(maximum);
|
||||
delay
|
||||
}
|
||||
|
||||
fn valid_owner(owner: &str) -> bool {
|
||||
!owner.is_empty()
|
||||
&& owner.len() <= 64
|
||||
&& owner.bytes().all(|byte| {
|
||||
byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"-_.".contains(&byte)
|
||||
})
|
||||
&& owner
|
||||
.as_bytes()
|
||||
.first()
|
||||
.is_some_and(u8::is_ascii_alphanumeric)
|
||||
}
|
||||
|
||||
fn lock_unpoisoned<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
mutex
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,152 @@
|
||||
mod bootstrap;
|
||||
mod workers;
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use syn::{Attribute, Item, Meta};
|
||||
|
||||
#[test]
|
||||
fn app_tree_is_exactly_the_frozen_six_rust_files() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
assert_eq!(
|
||||
rust_files(&root.join("src")),
|
||||
BTreeSet::from([
|
||||
PathBuf::from("bootstrap.rs"),
|
||||
PathBuf::from("main.rs"),
|
||||
PathBuf::from("workers.rs"),
|
||||
]),
|
||||
);
|
||||
assert_eq!(
|
||||
rust_files(&root.join("tests")),
|
||||
BTreeSet::from([
|
||||
PathBuf::from("bootstrap.rs"),
|
||||
PathBuf::from("main.rs"),
|
||||
PathBuf::from("workers.rs"),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cargo_library_root_is_bootstrap() {
|
||||
let manifest = fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml"))
|
||||
.expect("read app Cargo.toml");
|
||||
let normalized = manifest.split_whitespace().collect::<String>();
|
||||
assert!(normalized.contains("[lib]path=\"src/bootstrap.rs\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_files_have_no_hidden_modules_or_test_hooks() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
|
||||
for relative in ["bootstrap.rs", "main.rs", "workers.rs"] {
|
||||
let path = root.join(relative);
|
||||
let source = fs::read_to_string(&path).expect("read production source");
|
||||
assert!(
|
||||
!source.contains("include!("),
|
||||
"{} uses include!",
|
||||
path.display()
|
||||
);
|
||||
let syntax = syn::parse_file(&source).expect("parse production source");
|
||||
for item in &syntax.items {
|
||||
if let Item::Mod(module) = item {
|
||||
assert!(
|
||||
module.content.is_none(),
|
||||
"{} has an inline module",
|
||||
path.display()
|
||||
);
|
||||
assert!(
|
||||
!module.attrs.iter().any(is_path_or_test_cfg),
|
||||
"{} has a hidden module hook",
|
||||
path.display(),
|
||||
);
|
||||
}
|
||||
for attribute in item_attrs(item) {
|
||||
assert!(
|
||||
!is_path_or_test_cfg(attribute),
|
||||
"{} has a production test/path hook",
|
||||
path.display(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bootstrap_and_workers_do_not_own_storage_or_provider_wire_algorithms() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
|
||||
let bootstrap = fs::read_to_string(root.join("bootstrap.rs")).expect("read bootstrap");
|
||||
let workers = fs::read_to_string(root.join("workers.rs")).expect("read workers");
|
||||
for forbidden in [
|
||||
"sqlx::query",
|
||||
"sqlx::query_as",
|
||||
"redis::Script",
|
||||
"redis.call(",
|
||||
"access_token\"",
|
||||
"refresh_token\"",
|
||||
] {
|
||||
assert!(
|
||||
!bootstrap.contains(forbidden),
|
||||
"bootstrap owns `{forbidden}`"
|
||||
);
|
||||
assert!(!workers.contains(forbidden), "workers owns `{forbidden}`");
|
||||
}
|
||||
}
|
||||
|
||||
fn rust_files(root: &Path) -> BTreeSet<PathBuf> {
|
||||
let mut result = BTreeSet::new();
|
||||
collect_rust_files(root, root, &mut result);
|
||||
result
|
||||
}
|
||||
|
||||
fn collect_rust_files(root: &Path, current: &Path, result: &mut BTreeSet<PathBuf>) {
|
||||
for entry in fs::read_dir(current).expect("read app tree") {
|
||||
let path = entry.expect("read app tree entry").path();
|
||||
if path.is_dir() {
|
||||
collect_rust_files(root, &path, result);
|
||||
} else if path.extension().is_some_and(|extension| extension == "rs") {
|
||||
result.insert(
|
||||
path.strip_prefix(root)
|
||||
.expect("relative app path")
|
||||
.to_path_buf(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_path_or_test_cfg(attribute: &Attribute) -> bool {
|
||||
if attribute.path().is_ident("path") {
|
||||
return true;
|
||||
}
|
||||
if !attribute.path().is_ident("cfg") && !attribute.path().is_ident("cfg_attr") {
|
||||
return false;
|
||||
}
|
||||
let Meta::List(list) = &attribute.meta else {
|
||||
return false;
|
||||
};
|
||||
list.tokens
|
||||
.to_string()
|
||||
.split(|character: char| !character.is_ascii_alphanumeric() && character != '_')
|
||||
.any(|segment| segment == "test" || segment.starts_with("test_"))
|
||||
}
|
||||
|
||||
fn item_attrs(item: &Item) -> &[Attribute] {
|
||||
match item {
|
||||
Item::Const(item) => &item.attrs,
|
||||
Item::Enum(item) => &item.attrs,
|
||||
Item::ExternCrate(item) => &item.attrs,
|
||||
Item::Fn(item) => &item.attrs,
|
||||
Item::ForeignMod(item) => &item.attrs,
|
||||
Item::Impl(item) => &item.attrs,
|
||||
Item::Macro(item) => &item.attrs,
|
||||
Item::Mod(item) => &item.attrs,
|
||||
Item::Static(item) => &item.attrs,
|
||||
Item::Struct(item) => &item.attrs,
|
||||
Item::Trait(item) => &item.attrs,
|
||||
Item::TraitAlias(item) => &item.attrs,
|
||||
Item::Type(item) => &item.attrs,
|
||||
Item::Union(item) => &item.attrs,
|
||||
Item::Use(item) => &item.attrs,
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,853 @@
|
||||
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
||||
use std::future::pending;
|
||||
use std::num::NonZeroU64;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use codex_proxy_rs::workers::{
|
||||
WorkerCycleContext, WorkerDisabledReason, WorkerFencingToken, WorkerHealthKey, WorkerId,
|
||||
WorkerKind, WorkerLeaderLeaseGuard, WorkerLeaderLeasePort, WorkerLeaseAcquisition,
|
||||
WorkerLeaseError, WorkerLeaseRequest, WorkerRegistry, WorkerRegistryError, WorkerRuntimeState,
|
||||
WorkerSchedule, WorkerTask, WorkerTaskError,
|
||||
};
|
||||
use tokio::sync::Notify;
|
||||
|
||||
const ACTIVE_KINDS: [WorkerKind; 4] = [
|
||||
WorkerKind::OAuthRefresh,
|
||||
WorkerKind::QuotaCatalogHealth,
|
||||
WorkerKind::StaleModelRequestRecovery,
|
||||
WorkerKind::Retention,
|
||||
];
|
||||
|
||||
struct CountingTask {
|
||||
runs: AtomicUsize,
|
||||
fail_until: usize,
|
||||
fences: Mutex<Vec<u64>>,
|
||||
}
|
||||
|
||||
impl CountingTask {
|
||||
fn new(fail_until: usize) -> Self {
|
||||
Self {
|
||||
runs: AtomicUsize::new(0),
|
||||
fail_until,
|
||||
fences: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl WorkerTask for CountingTask {
|
||||
async fn run_cycle(&self, context: WorkerCycleContext) -> Result<(), WorkerTaskError> {
|
||||
lock_unpoisoned(&self.fences).push(context.fencing_token().get());
|
||||
let run = self.runs.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
if run <= self.fail_until {
|
||||
Err(WorkerTaskError::safe("expected test failure"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PanicOnceTask {
|
||||
runs: AtomicUsize,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl WorkerTask for PanicOnceTask {
|
||||
async fn run_cycle(&self, _context: WorkerCycleContext) -> Result<(), WorkerTaskError> {
|
||||
if self.runs.fetch_add(1, Ordering::SeqCst) == 0 {
|
||||
panic!("expected isolated worker panic");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct CancellationTask {
|
||||
entered: AtomicUsize,
|
||||
observed: AtomicUsize,
|
||||
notification: Notify,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl WorkerTask for CancellationTask {
|
||||
async fn run_cycle(&self, context: WorkerCycleContext) -> Result<(), WorkerTaskError> {
|
||||
self.entered.fetch_add(1, Ordering::SeqCst);
|
||||
self.notification.notify_one();
|
||||
context.cancelled().await;
|
||||
self.observed.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct HungTask {
|
||||
entered: AtomicBool,
|
||||
notification: Notify,
|
||||
}
|
||||
|
||||
struct SucceedsThenHangsTask {
|
||||
runs: AtomicUsize,
|
||||
second_cycle: Notify,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl WorkerTask for SucceedsThenHangsTask {
|
||||
async fn run_cycle(&self, _context: WorkerCycleContext) -> Result<(), WorkerTaskError> {
|
||||
if self.runs.fetch_add(1, Ordering::SeqCst) == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
self.second_cycle.notify_one();
|
||||
pending::<()>().await;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl WorkerTask for HungTask {
|
||||
async fn run_cycle(&self, _context: WorkerCycleContext) -> Result<(), WorkerTaskError> {
|
||||
self.entered.store(true, Ordering::SeqCst);
|
||||
self.notification.notify_one();
|
||||
pending::<()>().await;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct LeaseAwareTask {
|
||||
entered: Notify,
|
||||
release: Notify,
|
||||
completed: AtomicBool,
|
||||
saw_live_guard: AtomicBool,
|
||||
expected_worker: WorkerId,
|
||||
active_guards: Arc<Mutex<BTreeSet<WorkerId>>>,
|
||||
fence: AtomicU64,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl WorkerTask for LeaseAwareTask {
|
||||
async fn run_cycle(&self, context: WorkerCycleContext) -> Result<(), WorkerTaskError> {
|
||||
self.saw_live_guard.store(
|
||||
lock_unpoisoned(&self.active_guards).contains(context.worker()),
|
||||
Ordering::SeqCst,
|
||||
);
|
||||
if context.worker() != &self.expected_worker {
|
||||
return Err(WorkerTaskError::safe("unexpected worker identity"));
|
||||
}
|
||||
self.fence
|
||||
.store(context.fencing_token().get(), Ordering::SeqCst);
|
||||
self.entered.notify_one();
|
||||
self.release.notified().await;
|
||||
self.completed.store(true, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct ConcurrentCycleTask {
|
||||
starts: AtomicUsize,
|
||||
active: AtomicUsize,
|
||||
maximum_active: AtomicUsize,
|
||||
}
|
||||
|
||||
struct ActiveCycle<'a> {
|
||||
active: &'a AtomicUsize,
|
||||
}
|
||||
|
||||
impl Drop for ActiveCycle<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.active.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl WorkerTask for ConcurrentCycleTask {
|
||||
async fn run_cycle(&self, context: WorkerCycleContext) -> Result<(), WorkerTaskError> {
|
||||
self.starts.fetch_add(1, Ordering::SeqCst);
|
||||
let active = self.active.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
self.maximum_active.fetch_max(active, Ordering::SeqCst);
|
||||
let _active_cycle = ActiveCycle {
|
||||
active: &self.active,
|
||||
};
|
||||
context.cancelled().await;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum LeaseStep {
|
||||
Acquired,
|
||||
Busy(Option<Duration>),
|
||||
Error,
|
||||
Panic,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum RenewStep {
|
||||
Success,
|
||||
Error,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FakeLeasePort {
|
||||
scripts: Mutex<BTreeMap<WorkerId, VecDeque<LeaseStep>>>,
|
||||
renew_scripts: Arc<Mutex<BTreeMap<WorkerId, VecDeque<RenewStep>>>>,
|
||||
requests: Mutex<Vec<WorkerLeaseRequest>>,
|
||||
renewals: Arc<Mutex<Vec<WorkerId>>>,
|
||||
active_guards: Arc<Mutex<BTreeSet<WorkerId>>>,
|
||||
next_fence: AtomicU64,
|
||||
}
|
||||
|
||||
impl FakeLeasePort {
|
||||
fn script(&self, worker: WorkerId, steps: impl IntoIterator<Item = LeaseStep>) {
|
||||
lock_unpoisoned(&self.scripts).insert(worker, steps.into_iter().collect());
|
||||
}
|
||||
|
||||
fn renew_script(&self, worker: WorkerId, steps: impl IntoIterator<Item = RenewStep>) {
|
||||
lock_unpoisoned(&self.renew_scripts).insert(worker, steps.into_iter().collect());
|
||||
}
|
||||
|
||||
fn requests(&self) -> Vec<WorkerLeaseRequest> {
|
||||
lock_unpoisoned(&self.requests).clone()
|
||||
}
|
||||
|
||||
fn renewal_count(&self, worker: &WorkerId) -> usize {
|
||||
lock_unpoisoned(&self.renewals)
|
||||
.iter()
|
||||
.filter(|renewed| *renewed == worker)
|
||||
.count()
|
||||
}
|
||||
}
|
||||
|
||||
struct FakeLeaseGuard {
|
||||
worker: WorkerId,
|
||||
fencing_token: WorkerFencingToken,
|
||||
active_guards: Arc<Mutex<BTreeSet<WorkerId>>>,
|
||||
renew_scripts: Arc<Mutex<BTreeMap<WorkerId, VecDeque<RenewStep>>>>,
|
||||
renewals: Arc<Mutex<Vec<WorkerId>>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl WorkerLeaderLeaseGuard for FakeLeaseGuard {
|
||||
fn fencing_token(&self) -> WorkerFencingToken {
|
||||
self.fencing_token
|
||||
}
|
||||
|
||||
async fn renew(&mut self) -> Result<(), WorkerLeaseError> {
|
||||
lock_unpoisoned(&self.renewals).push(self.worker.clone());
|
||||
match lock_unpoisoned(&self.renew_scripts)
|
||||
.get_mut(&self.worker)
|
||||
.and_then(VecDeque::pop_front)
|
||||
.unwrap_or(RenewStep::Success)
|
||||
{
|
||||
RenewStep::Success => Ok(()),
|
||||
RenewStep::Error => Err(WorkerLeaseError::safe("expected renewal failure")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FakeLeaseGuard {
|
||||
fn drop(&mut self) {
|
||||
lock_unpoisoned(&self.active_guards).remove(&self.worker);
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl WorkerLeaderLeasePort for FakeLeasePort {
|
||||
async fn try_acquire(
|
||||
&self,
|
||||
request: WorkerLeaseRequest,
|
||||
) -> Result<WorkerLeaseAcquisition, WorkerLeaseError> {
|
||||
lock_unpoisoned(&self.requests).push(request.clone());
|
||||
let step = lock_unpoisoned(&self.scripts)
|
||||
.get_mut(request.worker())
|
||||
.and_then(VecDeque::pop_front)
|
||||
.unwrap_or(LeaseStep::Acquired);
|
||||
match step {
|
||||
LeaseStep::Acquired => {
|
||||
let fence = self.next_fence.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
lock_unpoisoned(&self.active_guards).insert(request.worker().clone());
|
||||
Ok(WorkerLeaseAcquisition::Acquired(Box::new(FakeLeaseGuard {
|
||||
worker: request.worker().clone(),
|
||||
fencing_token: WorkerFencingToken::new(
|
||||
NonZeroU64::new(fence).expect("positive test fencing token"),
|
||||
),
|
||||
active_guards: Arc::clone(&self.active_guards),
|
||||
renew_scripts: Arc::clone(&self.renew_scripts),
|
||||
renewals: Arc::clone(&self.renewals),
|
||||
})))
|
||||
}
|
||||
LeaseStep::Busy(retry_after) => Ok(WorkerLeaseAcquisition::Busy { retry_after }),
|
||||
LeaseStep::Error => Err(WorkerLeaseError::safe("expected lease failure")),
|
||||
LeaseStep::Panic => panic!("expected isolated lease port panic"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schedule_rejects_every_invalid_duration_boundary() {
|
||||
let valid = Duration::from_millis(1);
|
||||
for values in [
|
||||
(Duration::ZERO, valid, valid, valid),
|
||||
(valid, Duration::ZERO, valid, valid),
|
||||
(valid, valid, Duration::ZERO, valid),
|
||||
(valid, valid, valid, Duration::ZERO),
|
||||
(valid, valid, valid, Duration::from_nanos(2)),
|
||||
(
|
||||
valid,
|
||||
Duration::from_millis(2),
|
||||
Duration::from_millis(1),
|
||||
valid,
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
WorkerSchedule::new(values.0, values.1, values.2, values.3),
|
||||
Err(WorkerRegistryError::InvalidSchedule),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_owner_rejects_empty_unsafe_or_oversized_names() {
|
||||
for owner in [
|
||||
String::new(),
|
||||
"Codex".to_owned(),
|
||||
"provider/codex".to_owned(),
|
||||
"x".repeat(65),
|
||||
] {
|
||||
assert!(matches!(
|
||||
WorkerId::new(WorkerKind::OAuthRefresh, owner),
|
||||
Err(WorkerRegistryError::InvalidOwner(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_composes_multiple_owners_but_rejects_duplicate_identity() {
|
||||
let mut registry = WorkerRegistry::new();
|
||||
let task = Arc::new(CountingTask::new(0));
|
||||
registry
|
||||
.register(
|
||||
WorkerKind::OAuthRefresh,
|
||||
"openai",
|
||||
task.clone(),
|
||||
test_schedule(),
|
||||
)
|
||||
.expect("first owner registration");
|
||||
registry
|
||||
.register(
|
||||
WorkerKind::OAuthRefresh,
|
||||
"xai",
|
||||
task.clone(),
|
||||
test_schedule(),
|
||||
)
|
||||
.expect("second owner registration");
|
||||
assert!(matches!(
|
||||
registry.register(
|
||||
WorkerKind::OAuthRefresh,
|
||||
"openai",
|
||||
task,
|
||||
test_schedule(),
|
||||
),
|
||||
Err(WorkerRegistryError::Duplicate(id)) if id.owner() == "openai"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_database_fact_reasons_can_disable_the_two_nonexistent_workers() {
|
||||
let task = Arc::new(CountingTask::new(0));
|
||||
let mut disabled = WorkerRegistry::new();
|
||||
disabled
|
||||
.disable(WorkerDisabledReason::NoPersistentNativeClaimState)
|
||||
.expect("native claim terminal fact");
|
||||
assert_eq!(
|
||||
disabled.register(
|
||||
WorkerKind::NativeClaimRecovery,
|
||||
"store",
|
||||
task.clone(),
|
||||
test_schedule(),
|
||||
),
|
||||
Err(WorkerRegistryError::KindDisabled(
|
||||
WorkerKind::NativeClaimRecovery
|
||||
)),
|
||||
);
|
||||
|
||||
let mut active = WorkerRegistry::new();
|
||||
active
|
||||
.register(WorkerKind::OpsFlush, "store", task, test_schedule())
|
||||
.expect("real owner registration");
|
||||
assert_eq!(
|
||||
active.disable(WorkerDisabledReason::NoBufferedOpsEvents),
|
||||
Err(WorkerRegistryError::KindHasTasks(WorkerKind::OpsFlush)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_refuses_start_when_any_real_owner_kind_is_missing() {
|
||||
let task = Arc::new(CountingTask::new(0));
|
||||
let mut registry = WorkerRegistry::new();
|
||||
for kind in ACTIVE_KINDS
|
||||
.into_iter()
|
||||
.filter(|kind| *kind != WorkerKind::Retention)
|
||||
{
|
||||
registry
|
||||
.register(kind, kind.as_str(), task.clone(), test_schedule())
|
||||
.expect("unique active worker");
|
||||
}
|
||||
disable_nonexistent_workers(&mut registry);
|
||||
let lease_port: Arc<dyn WorkerLeaderLeasePort> = Arc::new(FakeLeasePort::default());
|
||||
assert!(matches!(
|
||||
registry.start(lease_port),
|
||||
Err(WorkerRegistryError::Missing(missing)) if missing == vec![WorkerKind::Retention]
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabled_database_facts_never_execute_or_acquire_a_lease() {
|
||||
let task = Arc::new(CountingTask::new(0));
|
||||
let lease_port = Arc::new(FakeLeasePort::default());
|
||||
let supervisor = complete_registry(task)
|
||||
.start(lease_port.clone())
|
||||
.expect("complete registry starts");
|
||||
|
||||
wait_until(|| lease_port.requests().len() >= ACTIVE_KINDS.len()).await;
|
||||
assert!(lease_port.requests().iter().all(|request| {
|
||||
!matches!(
|
||||
request.worker().kind(),
|
||||
WorkerKind::NativeClaimRecovery | WorkerKind::OpsFlush
|
||||
)
|
||||
}));
|
||||
let snapshot = supervisor.health().snapshot();
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.get(&WorkerHealthKey::Disabled(WorkerKind::NativeClaimRecovery))
|
||||
.map(|health| health.state),
|
||||
Some(WorkerRuntimeState::Disabled(
|
||||
WorkerDisabledReason::NoPersistentNativeClaimState
|
||||
)),
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.get(&WorkerHealthKey::Disabled(WorkerKind::OpsFlush))
|
||||
.map(|health| health.state),
|
||||
Some(WorkerRuntimeState::Disabled(
|
||||
WorkerDisabledReason::NoBufferedOpsEvents
|
||||
)),
|
||||
);
|
||||
assert!(supervisor.health().all_healthy());
|
||||
supervisor.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn one_kind_runs_all_registered_owner_tasks() {
|
||||
let common = Arc::new(CountingTask::new(0));
|
||||
let second_oauth_owner = Arc::new(CountingTask::new(0));
|
||||
let mut registry = complete_registry(common);
|
||||
registry
|
||||
.register(
|
||||
WorkerKind::OAuthRefresh,
|
||||
"xai",
|
||||
second_oauth_owner.clone(),
|
||||
test_schedule(),
|
||||
)
|
||||
.expect("second OAuth owner");
|
||||
let supervisor = registry
|
||||
.start(Arc::new(FakeLeasePort::default()))
|
||||
.expect("complete registry starts");
|
||||
|
||||
wait_until(|| second_oauth_owner.runs.load(Ordering::SeqCst) >= 1).await;
|
||||
assert_eq!(
|
||||
supervisor
|
||||
.health()
|
||||
.snapshot()
|
||||
.keys()
|
||||
.filter(|key| matches!(key, WorkerHealthKey::Task(id) if id.kind() == WorkerKind::OAuthRefresh))
|
||||
.count(),
|
||||
2,
|
||||
);
|
||||
supervisor.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn leader_guard_lives_through_cycle_and_fence_reaches_owner() {
|
||||
let expected_worker =
|
||||
WorkerId::new(WorkerKind::OAuthRefresh, "openai").expect("valid expected worker identity");
|
||||
let lease_port = Arc::new(FakeLeasePort::default());
|
||||
let lease_task = Arc::new(LeaseAwareTask {
|
||||
entered: Notify::new(),
|
||||
release: Notify::new(),
|
||||
completed: AtomicBool::new(false),
|
||||
saw_live_guard: AtomicBool::new(false),
|
||||
expected_worker: expected_worker.clone(),
|
||||
active_guards: Arc::clone(&lease_port.active_guards),
|
||||
fence: AtomicU64::new(0),
|
||||
});
|
||||
let other = Arc::new(CountingTask::new(0));
|
||||
let mut registry = WorkerRegistry::new();
|
||||
registry
|
||||
.register(
|
||||
WorkerKind::OAuthRefresh,
|
||||
"openai",
|
||||
lease_task.clone(),
|
||||
long_interval_schedule(),
|
||||
)
|
||||
.expect("lease-aware worker");
|
||||
for kind in ACTIVE_KINDS
|
||||
.into_iter()
|
||||
.filter(|kind| *kind != WorkerKind::OAuthRefresh)
|
||||
{
|
||||
registry
|
||||
.register(kind, kind.as_str(), other.clone(), long_interval_schedule())
|
||||
.expect("other active worker");
|
||||
}
|
||||
disable_nonexistent_workers(&mut registry);
|
||||
let supervisor = registry
|
||||
.start(lease_port.clone())
|
||||
.expect("complete registry starts");
|
||||
|
||||
lease_task.entered.notified().await;
|
||||
assert!(lease_task.saw_live_guard.load(Ordering::SeqCst));
|
||||
assert!(
|
||||
lock_unpoisoned(&lease_port.active_guards).contains(&expected_worker),
|
||||
"guard must remain alive while owner task is running"
|
||||
);
|
||||
lease_task.release.notify_one();
|
||||
wait_until(|| lease_task.completed.load(Ordering::SeqCst)).await;
|
||||
wait_until(|| !lock_unpoisoned(&lease_port.active_guards).contains(&expected_worker)).await;
|
||||
assert!(lease_task.fence.load(Ordering::SeqCst) > 0);
|
||||
let request = lease_port
|
||||
.requests()
|
||||
.into_iter()
|
||||
.find(|request| request.worker() == &expected_worker)
|
||||
.expect("leader lease request recorded");
|
||||
assert_eq!(request.ttl(), Duration::from_secs(30));
|
||||
supervisor.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn long_cycle_renews_leader_lease_before_ttl() {
|
||||
let expected_worker = target_worker();
|
||||
let lease_port = Arc::new(FakeLeasePort::default());
|
||||
let lease_task = Arc::new(LeaseAwareTask {
|
||||
entered: Notify::new(),
|
||||
release: Notify::new(),
|
||||
completed: AtomicBool::new(false),
|
||||
saw_live_guard: AtomicBool::new(false),
|
||||
expected_worker: expected_worker.clone(),
|
||||
active_guards: Arc::clone(&lease_port.active_guards),
|
||||
fence: AtomicU64::new(0),
|
||||
});
|
||||
let supervisor = registry_with_target(lease_task.clone(), renewal_schedule())
|
||||
.start(lease_port.clone())
|
||||
.expect("complete registry starts");
|
||||
|
||||
lease_task.entered.notified().await;
|
||||
tokio::time::advance(Duration::from_millis(10)).await;
|
||||
yield_until(|| lease_port.renewal_count(&expected_worker) >= 1).await;
|
||||
assert!(lock_unpoisoned(&lease_port.active_guards).contains(&expected_worker));
|
||||
lease_task.release.notify_one();
|
||||
yield_until(|| lease_task.completed.load(Ordering::SeqCst)).await;
|
||||
supervisor.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn renewal_failure_cancels_old_cycle_before_another_leader_cycle_starts() {
|
||||
let task = Arc::new(ConcurrentCycleTask {
|
||||
starts: AtomicUsize::new(0),
|
||||
active: AtomicUsize::new(0),
|
||||
maximum_active: AtomicUsize::new(0),
|
||||
});
|
||||
let lease_port = Arc::new(FakeLeasePort::default());
|
||||
lease_port.renew_script(target_worker(), [RenewStep::Error]);
|
||||
let supervisor = registry_with_target(task.clone(), renewal_schedule())
|
||||
.start(lease_port)
|
||||
.expect("complete registry starts");
|
||||
|
||||
yield_until(|| task.starts.load(Ordering::SeqCst) == 1).await;
|
||||
tokio::time::advance(Duration::from_millis(10)).await;
|
||||
yield_until(|| task.active.load(Ordering::SeqCst) == 0).await;
|
||||
assert_eq!(
|
||||
task_health(&supervisor.health().snapshot(), target_worker()).state,
|
||||
WorkerRuntimeState::BackingOff,
|
||||
);
|
||||
tokio::time::advance(Duration::from_millis(5)).await;
|
||||
yield_until(|| task.starts.load(Ordering::SeqCst) == 2).await;
|
||||
assert_eq!(task.maximum_active.load(Ordering::SeqCst), 1);
|
||||
supervisor.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn supervisor_uses_exponential_backoff_and_recovers_health() {
|
||||
let recovering = Arc::new(CountingTask::new(2));
|
||||
let supervisor = registry_with_target(recovering.clone(), backoff_schedule())
|
||||
.start(Arc::new(FakeLeasePort::default()))
|
||||
.expect("complete registry starts");
|
||||
|
||||
yield_until(|| recovering.runs.load(Ordering::SeqCst) == 1).await;
|
||||
tokio::time::advance(Duration::from_millis(9)).await;
|
||||
yield_many().await;
|
||||
assert_eq!(recovering.runs.load(Ordering::SeqCst), 1);
|
||||
tokio::time::advance(Duration::from_millis(1)).await;
|
||||
yield_until(|| recovering.runs.load(Ordering::SeqCst) == 2).await;
|
||||
tokio::time::advance(Duration::from_millis(19)).await;
|
||||
yield_many().await;
|
||||
assert_eq!(recovering.runs.load(Ordering::SeqCst), 2);
|
||||
tokio::time::advance(Duration::from_millis(1)).await;
|
||||
yield_until(|| recovering.runs.load(Ordering::SeqCst) == 3).await;
|
||||
|
||||
let health = task_health(&supervisor.health().snapshot(), target_worker());
|
||||
assert_eq!(health.consecutive_failures, 0);
|
||||
assert_eq!(health.completed_cycles, 1);
|
||||
supervisor.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn task_and_lease_port_panics_are_isolated_and_retried() {
|
||||
let panic_task = Arc::new(PanicOnceTask {
|
||||
runs: AtomicUsize::new(0),
|
||||
});
|
||||
let lease_port = Arc::new(FakeLeasePort::default());
|
||||
let quota_worker = WorkerId::new(WorkerKind::QuotaCatalogHealth, "quota_catalog_health")
|
||||
.expect("valid quota worker");
|
||||
lease_port.script(
|
||||
quota_worker,
|
||||
[LeaseStep::Error, LeaseStep::Panic, LeaseStep::Acquired],
|
||||
);
|
||||
let supervisor = registry_with_target(panic_task.clone(), backoff_schedule())
|
||||
.start(lease_port)
|
||||
.expect("complete registry starts");
|
||||
|
||||
yield_until(|| panic_task.runs.load(Ordering::SeqCst) == 1).await;
|
||||
tokio::time::advance(Duration::from_millis(10)).await;
|
||||
yield_until(|| panic_task.runs.load(Ordering::SeqCst) == 2).await;
|
||||
tokio::time::advance(Duration::from_millis(20)).await;
|
||||
yield_many().await;
|
||||
assert!(panic_task.runs.load(Ordering::SeqCst) >= 2);
|
||||
let health = task_health(&supervisor.health().snapshot(), target_worker());
|
||||
assert_eq!(health.consecutive_failures, 0);
|
||||
supervisor.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn lease_busy_is_healthy_standby_and_retries_without_running_owner() {
|
||||
let task = Arc::new(CountingTask::new(0));
|
||||
let lease_port = Arc::new(FakeLeasePort::default());
|
||||
lease_port.script(
|
||||
target_worker(),
|
||||
[
|
||||
LeaseStep::Busy(Some(Duration::from_millis(7))),
|
||||
LeaseStep::Acquired,
|
||||
],
|
||||
);
|
||||
let supervisor = registry_with_target(task.clone(), backoff_schedule())
|
||||
.start(lease_port)
|
||||
.expect("complete registry starts");
|
||||
|
||||
yield_until(|| {
|
||||
task_health(&supervisor.health().snapshot(), target_worker()).state
|
||||
== WorkerRuntimeState::Standby
|
||||
})
|
||||
.await;
|
||||
assert_eq!(task.runs.load(Ordering::SeqCst), 0);
|
||||
assert!(supervisor.health().all_healthy());
|
||||
tokio::time::advance(Duration::from_millis(7)).await;
|
||||
yield_until(|| task.runs.load(Ordering::SeqCst) == 1).await;
|
||||
supervisor.shutdown(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cooperative_shutdown_propagates_cancel_before_dropping_all_guards() {
|
||||
let task = Arc::new(CancellationTask {
|
||||
entered: AtomicUsize::new(0),
|
||||
observed: AtomicUsize::new(0),
|
||||
notification: Notify::new(),
|
||||
});
|
||||
let lease_port = Arc::new(FakeLeasePort::default());
|
||||
let supervisor = complete_registry(task.clone())
|
||||
.start(lease_port.clone())
|
||||
.expect("complete registry starts");
|
||||
|
||||
wait_until(|| task.entered.load(Ordering::SeqCst) == ACTIVE_KINDS.len()).await;
|
||||
let health = supervisor.health().clone();
|
||||
supervisor.shutdown(Duration::from_secs(1)).await;
|
||||
assert_eq!(task.observed.load(Ordering::SeqCst), ACTIVE_KINDS.len());
|
||||
assert!(lock_unpoisoned(&lease_port.active_guards).is_empty());
|
||||
assert!(health.snapshot().iter().all(|(key, value)| {
|
||||
matches!(key, WorkerHealthKey::Disabled(_)) || value.state == WorkerRuntimeState::Stopped
|
||||
}));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_timeout_aborts_uncooperative_task_and_drops_guard() {
|
||||
let hung = Arc::new(HungTask {
|
||||
entered: AtomicBool::new(false),
|
||||
notification: Notify::new(),
|
||||
});
|
||||
let lease_port = Arc::new(FakeLeasePort::default());
|
||||
let supervisor = registry_with_target(hung.clone(), long_interval_schedule())
|
||||
.start(lease_port.clone())
|
||||
.expect("complete registry starts");
|
||||
|
||||
hung.notification.notified().await;
|
||||
assert!(hung.entered.load(Ordering::SeqCst));
|
||||
assert!(
|
||||
!supervisor.health().all_healthy(),
|
||||
"a running worker without one successful cycle is not healthy"
|
||||
);
|
||||
let health = supervisor.health().clone();
|
||||
supervisor.shutdown(Duration::from_millis(10)).await;
|
||||
assert!(lock_unpoisoned(&lease_port.active_guards).is_empty());
|
||||
assert_eq!(
|
||||
task_health(&health.snapshot(), target_worker()).state,
|
||||
WorkerRuntimeState::Stopped,
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn running_worker_becomes_unhealthy_when_last_success_is_stale() {
|
||||
let task = Arc::new(SucceedsThenHangsTask {
|
||||
runs: AtomicUsize::new(0),
|
||||
second_cycle: Notify::new(),
|
||||
});
|
||||
let schedule = WorkerSchedule::new(
|
||||
Duration::from_millis(10),
|
||||
Duration::from_millis(5),
|
||||
Duration::from_millis(10),
|
||||
Duration::from_secs(30),
|
||||
)
|
||||
.expect("freshness schedule");
|
||||
let supervisor = registry_with_target(task.clone(), schedule)
|
||||
.start(Arc::new(FakeLeasePort::default()))
|
||||
.expect("complete registry starts");
|
||||
|
||||
task.second_cycle.notified().await;
|
||||
assert_eq!(task.runs.load(Ordering::SeqCst), 2);
|
||||
tokio::time::sleep(Duration::from_millis(40)).await;
|
||||
assert!(
|
||||
!supervisor.health().all_healthy(),
|
||||
"running cannot mask an expired last-success timestamp"
|
||||
);
|
||||
supervisor.shutdown(Duration::from_millis(10)).await;
|
||||
}
|
||||
|
||||
fn complete_registry(task: Arc<dyn WorkerTask>) -> WorkerRegistry {
|
||||
let mut registry = WorkerRegistry::new();
|
||||
for kind in ACTIVE_KINDS {
|
||||
registry
|
||||
.register(kind, kind.as_str(), task.clone(), test_schedule())
|
||||
.expect("unique real worker registration");
|
||||
}
|
||||
disable_nonexistent_workers(&mut registry);
|
||||
registry
|
||||
}
|
||||
|
||||
fn registry_with_target(target: Arc<dyn WorkerTask>, schedule: WorkerSchedule) -> WorkerRegistry {
|
||||
let other = Arc::new(CountingTask::new(0));
|
||||
let mut registry = WorkerRegistry::new();
|
||||
registry
|
||||
.register(WorkerKind::OAuthRefresh, "openai", target, schedule)
|
||||
.expect("target worker registration");
|
||||
for kind in ACTIVE_KINDS
|
||||
.into_iter()
|
||||
.filter(|kind| *kind != WorkerKind::OAuthRefresh)
|
||||
{
|
||||
registry
|
||||
.register(kind, kind.as_str(), other.clone(), schedule)
|
||||
.expect("other worker registration");
|
||||
}
|
||||
disable_nonexistent_workers(&mut registry);
|
||||
registry
|
||||
}
|
||||
|
||||
fn disable_nonexistent_workers(registry: &mut WorkerRegistry) {
|
||||
registry
|
||||
.disable(WorkerDisabledReason::NoPersistentNativeClaimState)
|
||||
.expect("native claim has no persistent state");
|
||||
registry
|
||||
.disable(WorkerDisabledReason::NoBufferedOpsEvents)
|
||||
.expect("ops events have no buffer");
|
||||
}
|
||||
|
||||
fn target_worker() -> WorkerId {
|
||||
WorkerId::new(WorkerKind::OAuthRefresh, "openai").expect("valid target worker")
|
||||
}
|
||||
|
||||
fn task_health(
|
||||
snapshot: &BTreeMap<WorkerHealthKey, codex_proxy_rs::workers::WorkerHealth>,
|
||||
id: WorkerId,
|
||||
) -> codex_proxy_rs::workers::WorkerHealth {
|
||||
snapshot
|
||||
.get(&WorkerHealthKey::Task(id))
|
||||
.expect("worker health exists")
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn test_schedule() -> WorkerSchedule {
|
||||
WorkerSchedule::new(
|
||||
Duration::from_millis(20),
|
||||
Duration::from_millis(5),
|
||||
Duration::from_millis(20),
|
||||
Duration::from_secs(30),
|
||||
)
|
||||
.expect("valid test schedule")
|
||||
}
|
||||
|
||||
fn long_interval_schedule() -> WorkerSchedule {
|
||||
WorkerSchedule::new(
|
||||
Duration::from_secs(60),
|
||||
Duration::from_millis(5),
|
||||
Duration::from_millis(20),
|
||||
Duration::from_secs(30),
|
||||
)
|
||||
.expect("valid long-interval schedule")
|
||||
}
|
||||
|
||||
fn backoff_schedule() -> WorkerSchedule {
|
||||
WorkerSchedule::new(
|
||||
Duration::from_secs(60),
|
||||
Duration::from_millis(10),
|
||||
Duration::from_millis(20),
|
||||
Duration::from_secs(30),
|
||||
)
|
||||
.expect("valid backoff schedule")
|
||||
}
|
||||
|
||||
fn renewal_schedule() -> WorkerSchedule {
|
||||
WorkerSchedule::new(
|
||||
Duration::from_secs(60),
|
||||
Duration::from_millis(5),
|
||||
Duration::from_millis(20),
|
||||
Duration::from_millis(30),
|
||||
)
|
||||
.expect("valid renewal schedule")
|
||||
}
|
||||
|
||||
async fn wait_until(mut condition: impl FnMut() -> bool) {
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while !condition() {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("worker test timeout");
|
||||
}
|
||||
|
||||
async fn yield_until(mut condition: impl FnMut() -> bool) {
|
||||
for _ in 0..100 {
|
||||
if condition() {
|
||||
return;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
assert!(condition(), "condition did not become true after yielding");
|
||||
}
|
||||
|
||||
async fn yield_many() {
|
||||
for _ in 0..20 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
}
|
||||
|
||||
fn lock_unpoisoned<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
mutex
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "gateway-api"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
publish = false
|
||||
rust-version = "1.97"
|
||||
autotests = false
|
||||
|
||||
[[test]]
|
||||
name = "main"
|
||||
path = "tests/main.rs"
|
||||
|
||||
[dependencies]
|
||||
argon2 = "0.5.3"
|
||||
async-trait = "0.1.89"
|
||||
axum = { version = "0.8.9", default-features = false, features = ["json", "query", "ws"] }
|
||||
base64 = "0.22.1"
|
||||
chrono = { version = "0.4.45", features = ["serde"] }
|
||||
futures = "0.3.32"
|
||||
gateway-core = { path = "../gateway-core" }
|
||||
gateway-protocol = { path = "../gateway-protocol" }
|
||||
rand_core = { version = "0.6.4", features = ["getrandom"] }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = "1.0.150"
|
||||
thiserror = "2.0.18"
|
||||
tokio = { version = "1.52.3", default-features = false, features = ["macros"] }
|
||||
tracing = "0.1.44"
|
||||
subtle = "2.6.1"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.52.3", default-features = false, features = ["macros", "rt"] }
|
||||
tower = { version = "0.5.3", features = ["util"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,761 @@
|
||||
//! 管理端账号目录、查询校验与安全响应 wire。
|
||||
|
||||
use std::{fmt, pin::Pin};
|
||||
|
||||
use futures::Stream;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use gateway_core::routing::ProviderKind;
|
||||
|
||||
use crate::admin::WireValidationError;
|
||||
|
||||
const DEFAULT_PAGE_SIZE: u32 = 50;
|
||||
const MAX_PAGE_SIZE: u32 = 200;
|
||||
const MAX_SEARCH_BYTES: usize = 256;
|
||||
|
||||
/// 账号列表查询参数。
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ListQuery {
|
||||
pub page: Option<u32>,
|
||||
pub page_size: Option<u32>,
|
||||
pub provider: Option<String>,
|
||||
pub search: Option<String>,
|
||||
pub status: Option<String>,
|
||||
pub sort_by: Option<String>,
|
||||
pub sort_direction: Option<String>,
|
||||
}
|
||||
|
||||
impl ListQuery {
|
||||
/// 解析并校验全部 wire 字段。
|
||||
pub fn validate(self) -> Result<ValidatedListQuery, WireValidationError> {
|
||||
let page = self.page.unwrap_or(1);
|
||||
if page == 0 {
|
||||
return Err(WireValidationError::new("page"));
|
||||
}
|
||||
let page_size = self.page_size.unwrap_or(DEFAULT_PAGE_SIZE);
|
||||
if page_size == 0 || page_size > MAX_PAGE_SIZE {
|
||||
return Err(WireValidationError::new("pageSize"));
|
||||
}
|
||||
let provider = ProviderFilter::parse(self.provider.as_deref().unwrap_or("all"))
|
||||
.ok_or_else(|| WireValidationError::new("provider"))?;
|
||||
let search = self
|
||||
.search
|
||||
.map(|value| value.trim().to_owned())
|
||||
.filter(|value| !value.is_empty());
|
||||
if search.as_deref().is_some_and(|value| {
|
||||
value.len() > MAX_SEARCH_BYTES || value.chars().any(char::is_control)
|
||||
}) {
|
||||
return Err(WireValidationError::new("search"));
|
||||
}
|
||||
let status = match self.status.as_deref().map(str::trim) {
|
||||
None | Some("") => None,
|
||||
Some(value) => Some(
|
||||
AccountStatus::parse(value).ok_or_else(|| WireValidationError::new("status"))?,
|
||||
),
|
||||
};
|
||||
let sort = match (self.sort_by.as_deref(), self.sort_direction.as_deref()) {
|
||||
(None, None) => None,
|
||||
(Some(field), Some(direction)) => Some(AccountSort {
|
||||
field: SortField::parse(field).ok_or_else(|| WireValidationError::new("sortBy"))?,
|
||||
direction: SortDirection::parse(direction)
|
||||
.ok_or_else(|| WireValidationError::new("sortDirection"))?,
|
||||
}),
|
||||
_ => return Err(WireValidationError::new("sort")),
|
||||
};
|
||||
Ok(ValidatedListQuery {
|
||||
page,
|
||||
page_size,
|
||||
provider,
|
||||
search,
|
||||
status,
|
||||
sort,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 已校验的账号查询。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ValidatedListQuery {
|
||||
pub page: u32,
|
||||
pub page_size: u32,
|
||||
pub provider: ProviderFilter,
|
||||
pub search: Option<String>,
|
||||
pub status: Option<AccountStatus>,
|
||||
pub sort: Option<AccountSort>,
|
||||
}
|
||||
|
||||
/// Provider 过滤值。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ProviderFilter {
|
||||
All,
|
||||
Provider(ProviderKind),
|
||||
}
|
||||
|
||||
impl ProviderFilter {
|
||||
fn parse(value: &str) -> Option<Self> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() || value.eq_ignore_ascii_case("all") {
|
||||
return Some(Self::All);
|
||||
}
|
||||
ProviderKind::new(value.to_owned()).ok().map(Self::Provider)
|
||||
}
|
||||
}
|
||||
|
||||
/// 账号状态过滤值。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AccountStatus {
|
||||
Active,
|
||||
Expired,
|
||||
QuotaExhausted,
|
||||
Disabled,
|
||||
Banned,
|
||||
}
|
||||
|
||||
impl AccountStatus {
|
||||
fn parse(value: &str) -> Option<Self> {
|
||||
match value.trim().to_ascii_lowercase().as_str() {
|
||||
"active" => Some(Self::Active),
|
||||
"expired" => Some(Self::Expired),
|
||||
"quota_exhausted" => Some(Self::QuotaExhausted),
|
||||
"disabled" => Some(Self::Disabled),
|
||||
"banned" => Some(Self::Banned),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 账号排序字段。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SortField {
|
||||
Email,
|
||||
Status,
|
||||
PlanType,
|
||||
Usage,
|
||||
LastUsedAt,
|
||||
ExpiresAt,
|
||||
}
|
||||
|
||||
impl SortField {
|
||||
fn parse(value: &str) -> Option<Self> {
|
||||
match value.trim() {
|
||||
"email" => Some(Self::Email),
|
||||
"status" => Some(Self::Status),
|
||||
"planType" => Some(Self::PlanType),
|
||||
"usage" => Some(Self::Usage),
|
||||
"lastUsedAt" => Some(Self::LastUsedAt),
|
||||
"expiresAt" => Some(Self::ExpiresAt),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 账号排序方向。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SortDirection {
|
||||
Asc,
|
||||
Desc,
|
||||
}
|
||||
|
||||
impl SortDirection {
|
||||
fn parse(value: &str) -> Option<Self> {
|
||||
match value.trim().to_ascii_lowercase().as_str() {
|
||||
"asc" => Some(Self::Asc),
|
||||
"desc" => Some(Self::Desc),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 已校验的排序组合。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct AccountSort {
|
||||
pub field: SortField,
|
||||
pub direction: SortDirection,
|
||||
}
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::admin::PageMeta;
|
||||
|
||||
/// 账号列表响应数据。
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountPageData {
|
||||
pub config_revision: u64,
|
||||
pub items: Vec<AccountView>,
|
||||
pub page: PageMeta,
|
||||
pub summary: AccountSummaryView,
|
||||
}
|
||||
|
||||
/// 账号概览计数。
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountSummaryView {
|
||||
pub total: u64,
|
||||
pub active: u64,
|
||||
pub quota_exhausted: u64,
|
||||
pub attention: u64,
|
||||
}
|
||||
|
||||
/// 一条安全账号视图。
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountView {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub provider: String,
|
||||
pub provider_instance_id: String,
|
||||
pub provider_instance_name: String,
|
||||
pub resource_ref: String,
|
||||
pub email: Option<String>,
|
||||
pub account_id: Option<String>,
|
||||
pub user_id: Option<String>,
|
||||
pub label: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
pub has_refresh_token: bool,
|
||||
pub status: String,
|
||||
pub display_status: String,
|
||||
pub token_refreshing: bool,
|
||||
pub availability: String,
|
||||
pub enabled: bool,
|
||||
pub credential_revision: u64,
|
||||
pub state_revision: Option<u64>,
|
||||
pub access_token_expires_at: Option<String>,
|
||||
pub access_token_expires_at_display: Option<String>,
|
||||
pub refresh_token_expires_at: Option<String>,
|
||||
pub next_refresh_at: Option<String>,
|
||||
pub added_at: String,
|
||||
pub added_at_display: String,
|
||||
pub updated_at: String,
|
||||
pub updated_at_display: String,
|
||||
pub quota: AccountQuotaView,
|
||||
pub usage: AccountUsageView,
|
||||
}
|
||||
|
||||
/// Provider quota 安全视图。
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountQuotaView {
|
||||
pub refreshed_at_display: String,
|
||||
pub windows: Vec<AccountQuotaWindowView>,
|
||||
}
|
||||
|
||||
/// 一个 quota 时间窗口。
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountQuotaWindowView {
|
||||
pub key: String,
|
||||
pub group: String,
|
||||
pub window_seconds: Option<u64>,
|
||||
pub label_display: String,
|
||||
pub used_percent: Option<f64>,
|
||||
pub used_percent_display: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub local_usage: Option<serde_json::Value>,
|
||||
pub reset_at_display: String,
|
||||
}
|
||||
|
||||
/// 账号观测用量。
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountUsageView {
|
||||
pub request_count: Option<u64>,
|
||||
pub request_count_display: String,
|
||||
pub input_tokens: Option<u64>,
|
||||
pub input_tokens_display: String,
|
||||
pub output_tokens: Option<u64>,
|
||||
pub output_tokens_display: String,
|
||||
pub cached_tokens: Option<u64>,
|
||||
pub cached_tokens_display: String,
|
||||
pub total_tokens: Option<u64>,
|
||||
pub total_tokens_display: String,
|
||||
pub created_tokens: Option<u64>,
|
||||
pub created_tokens_display: String,
|
||||
pub read_tokens: Option<u64>,
|
||||
pub read_tokens_display: String,
|
||||
pub last_used_at: Option<String>,
|
||||
pub last_used_at_display: String,
|
||||
pub cost_estimate_status: String,
|
||||
pub known_cost_count: Option<u64>,
|
||||
pub partial_cost_count: Option<u64>,
|
||||
pub unknown_cost_count: Option<u64>,
|
||||
pub costs: Vec<CurrencyCostView>,
|
||||
pub models: Vec<ModelUsageView>,
|
||||
}
|
||||
|
||||
/// 凭据在单个上游模型上的观测用量。
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ModelUsageView {
|
||||
pub model: String,
|
||||
pub request_count: u64,
|
||||
pub request_count_display: String,
|
||||
pub success_rate: Option<f64>,
|
||||
pub success_rate_display: String,
|
||||
pub input_tokens: Option<u64>,
|
||||
pub input_tokens_display: String,
|
||||
pub output_tokens: Option<u64>,
|
||||
pub output_tokens_display: String,
|
||||
pub cached_tokens: Option<u64>,
|
||||
pub cached_tokens_display: String,
|
||||
pub total_tokens: Option<u64>,
|
||||
pub total_tokens_display: String,
|
||||
pub billing_amount_usd: Option<String>,
|
||||
pub billing_amount_usd_display: String,
|
||||
pub cost_estimate_status: String,
|
||||
pub known_cost_count: u64,
|
||||
pub partial_cost_count: u64,
|
||||
pub unknown_cost_count: u64,
|
||||
pub costs: Vec<CurrencyCostView>,
|
||||
pub last_used_at: String,
|
||||
pub last_used_at_display: String,
|
||||
}
|
||||
|
||||
/// 单一货币的可查询成本。
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CurrencyCostView {
|
||||
pub currency: String,
|
||||
pub estimated_amount: String,
|
||||
pub estimated_amount_display: String,
|
||||
}
|
||||
|
||||
/// 账号详情类 GET 的固定 ID query。
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AccountIdQuery {
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
impl AccountIdQuery {
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_account_id(&self.id)
|
||||
}
|
||||
}
|
||||
|
||||
/// 敏感导出的固定 query;IDs 使用逗号分隔,禁止隐式导出全部账号。
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AccountExportQuery {
|
||||
pub ids: String,
|
||||
pub confirm: String,
|
||||
}
|
||||
|
||||
impl AccountExportQuery {
|
||||
pub fn into_ids(self) -> Result<Vec<String>, WireValidationError> {
|
||||
if self.confirm != "export_sensitive_accounts" {
|
||||
return Err(WireValidationError::new("confirm"));
|
||||
}
|
||||
let ids = self
|
||||
.ids
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
.collect::<Vec<_>>();
|
||||
if ids.is_empty() || ids.len() > 200 || ids.iter().any(|id| require_account_id(id).is_err())
|
||||
{
|
||||
return Err(WireValidationError::new("ids"));
|
||||
}
|
||||
let unique = ids.iter().collect::<std::collections::BTreeSet<_>>();
|
||||
if unique.len() != ids.len() {
|
||||
return Err(WireValidationError::new("ids"));
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
}
|
||||
|
||||
/// 账号运行期动作。
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AccountActionRequest {
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
impl AccountActionRequest {
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_account_id(&self.id)
|
||||
}
|
||||
}
|
||||
|
||||
/// 手工 OAuth 刷新会变更持久 credential,因此必须携带配置 CAS revision。
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AccountRefreshRequest {
|
||||
pub id: String,
|
||||
pub expected_config_revision: u64,
|
||||
}
|
||||
|
||||
impl AccountRefreshRequest {
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_account_id(&self.id)?;
|
||||
if self.expected_config_revision == 0 {
|
||||
return Err(WireValidationError::new("expectedConfigRevision"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 连接测试 query;测试仍经唯一 Core/Provider 模型请求路径执行。
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AccountTestQuery {
|
||||
pub id: String,
|
||||
pub model_id: String,
|
||||
}
|
||||
|
||||
impl AccountTestQuery {
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_account_id(&self.id)?;
|
||||
if self.model_id.trim().is_empty() || self.model_id.chars().any(char::is_control) {
|
||||
return Err(WireValidationError::new("modelId"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct AccountModelView {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct AccountModelsData {
|
||||
pub models: Vec<AccountModelView>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountRefreshData {
|
||||
pub config_revision: u64,
|
||||
pub account: AccountView,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct AccountQuotaData {
|
||||
pub account: AccountView,
|
||||
}
|
||||
|
||||
/// Provider-owned 明文导出文档;Debug 永远不输出内部 JSON。
|
||||
#[derive(Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct AccountExportData(Value);
|
||||
|
||||
impl AccountExportData {
|
||||
#[must_use]
|
||||
pub const fn new(value: Value) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for AccountExportData {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str("AccountExportData(<redacted>)")
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AccountConnectionTestEvent {
|
||||
pub data: Value,
|
||||
}
|
||||
|
||||
impl AccountConnectionTestEvent {
|
||||
#[must_use]
|
||||
pub fn started(model: impl Into<String>) -> Self {
|
||||
Self {
|
||||
data: serde_json::json!({
|
||||
"type": "test_start",
|
||||
"model": model.into(),
|
||||
"text": "正在连接上游 Responses"
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn request(payload: Value) -> Self {
|
||||
Self {
|
||||
data: serde_json::json!({ "type": "request", "payload": payload }),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn content(text: impl Into<String>) -> Self {
|
||||
Self {
|
||||
data: serde_json::json!({ "type": "content", "text": text.into() }),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn completed(account_status: impl Into<String>) -> Self {
|
||||
Self {
|
||||
data: serde_json::json!({
|
||||
"type": "test_complete",
|
||||
"success": true,
|
||||
"accountStatus": account_status.into()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn failed(error: impl Into<String>, account_status: impl Into<String>) -> Self {
|
||||
Self {
|
||||
data: serde_json::json!({
|
||||
"type": "error",
|
||||
"error": error.into(),
|
||||
"accountStatus": account_status.into()
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type AccountConnectionTestEventStream =
|
||||
Pin<Box<dyn Stream<Item = AccountConnectionTestEvent> + Send + 'static>>;
|
||||
|
||||
fn require_account_id(value: &str) -> Result<(), WireValidationError> {
|
||||
if value.trim().is_empty()
|
||||
|| value.len() > 128
|
||||
|| value.chars().any(char::is_control)
|
||||
|| !value.starts_with("acct_")
|
||||
{
|
||||
return Err(WireValidationError::new("id"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
use async_trait::async_trait;
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Query, State},
|
||||
http::{HeaderValue, StatusCode, header::CACHE_CONTROL},
|
||||
response::{
|
||||
IntoResponse, Response,
|
||||
sse::{Event, KeepAlive, Sse},
|
||||
},
|
||||
routing::{get, post},
|
||||
};
|
||||
use futures::StreamExt as _;
|
||||
use std::convert::Infallible;
|
||||
|
||||
use super::{
|
||||
AdminAuth, AdminEnvelope, AdminError, AdminResponse, AdminServiceError, AdminServiceErrorKind,
|
||||
AdminSessionState,
|
||||
};
|
||||
|
||||
/// 统一账号目录应用端口。
|
||||
#[async_trait]
|
||||
pub trait AccountAdminService: Send + Sync {
|
||||
async fn list(&self, query: ValidatedListQuery) -> Result<AccountPageData, AdminServiceError>;
|
||||
async fn export(
|
||||
&self,
|
||||
context: &super::AdminRequestContext,
|
||||
ids: Vec<String>,
|
||||
) -> Result<AccountExportData, AdminServiceError>;
|
||||
async fn refresh(
|
||||
&self,
|
||||
context: &super::AdminRequestContext,
|
||||
request: AccountRefreshRequest,
|
||||
) -> Result<AccountRefreshData, AdminServiceError>;
|
||||
async fn quota(&self, id: String) -> Result<AccountQuotaData, AdminServiceError>;
|
||||
async fn refresh_quota(&self, id: String) -> Result<AccountQuotaData, AdminServiceError>;
|
||||
async fn models(&self, id: String) -> Result<AccountModelsData, AdminServiceError>;
|
||||
async fn refresh_models(&self, id: String) -> Result<AccountModelsData, AdminServiceError>;
|
||||
async fn test_connection(
|
||||
&self,
|
||||
id: String,
|
||||
model_id: String,
|
||||
) -> Result<AccountConnectionTestEventStream, AdminServiceError>;
|
||||
}
|
||||
|
||||
/// 账号目录 HTTP module 所需最小 state。
|
||||
pub trait AccountAdminState: AdminSessionState {
|
||||
fn account_admin_service(&self) -> &dyn AccountAdminService;
|
||||
}
|
||||
|
||||
/// 构造固定 GET 账号目录路由。
|
||||
pub fn router<S>() -> Router<S>
|
||||
where
|
||||
S: AccountAdminState + Clone + Send + Sync + 'static,
|
||||
{
|
||||
Router::new()
|
||||
.route("/api/admin/accounts", get(list_accounts::<S>))
|
||||
.route("/api/admin/accounts/export", get(export_accounts::<S>))
|
||||
.route("/api/admin/accounts/refresh", post(refresh_account::<S>))
|
||||
.route("/api/admin/accounts/quota", get(account_quota::<S>))
|
||||
.route(
|
||||
"/api/admin/accounts/quota/refresh",
|
||||
post(refresh_account_quota::<S>),
|
||||
)
|
||||
.route("/api/admin/accounts/models", get(account_models::<S>))
|
||||
.route(
|
||||
"/api/admin/accounts/models/refresh",
|
||||
post(refresh_account_models::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/accounts/test",
|
||||
get(test_account_connection::<S>),
|
||||
)
|
||||
}
|
||||
|
||||
async fn list_accounts<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Query(query): Query<ListQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: AccountAdminState + Send + Sync,
|
||||
{
|
||||
let query = query
|
||||
.validate()
|
||||
.map_err(|error| AdminError::bad_request(format!("Invalid {}", error.field())))?;
|
||||
let data = state
|
||||
.account_admin_service()
|
||||
.list(query)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)))
|
||||
}
|
||||
|
||||
async fn export_accounts<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Query(query): Query<AccountExportQuery>,
|
||||
) -> Result<Response, AdminError>
|
||||
where
|
||||
S: AccountAdminState + Send + Sync,
|
||||
{
|
||||
let ids = query.into_ids().map_err(map_wire_error)?;
|
||||
let data = state
|
||||
.account_admin_service()
|
||||
.export(auth.context(), ids)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
let mut response = AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)).into_response();
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn refresh_account<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Json(request): Json<AccountRefreshRequest>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: AccountAdminState + Send + Sync,
|
||||
{
|
||||
request.validate().map_err(map_wire_error)?;
|
||||
let data = state
|
||||
.account_admin_service()
|
||||
.refresh(auth.context(), request)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)))
|
||||
}
|
||||
|
||||
async fn account_quota<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Query(query): Query<AccountIdQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: AccountAdminState + Send + Sync,
|
||||
{
|
||||
query.validate().map_err(map_wire_error)?;
|
||||
let data = state
|
||||
.account_admin_service()
|
||||
.quota(query.id)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)))
|
||||
}
|
||||
|
||||
async fn refresh_account_quota<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Json(request): Json<AccountActionRequest>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: AccountAdminState + Send + Sync,
|
||||
{
|
||||
request.validate().map_err(map_wire_error)?;
|
||||
let data = state
|
||||
.account_admin_service()
|
||||
.refresh_quota(request.id)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)))
|
||||
}
|
||||
|
||||
async fn account_models<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Query(query): Query<AccountIdQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: AccountAdminState + Send + Sync,
|
||||
{
|
||||
query.validate().map_err(map_wire_error)?;
|
||||
let data = state
|
||||
.account_admin_service()
|
||||
.models(query.id)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)))
|
||||
}
|
||||
|
||||
async fn refresh_account_models<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Json(request): Json<AccountActionRequest>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: AccountAdminState + Send + Sync,
|
||||
{
|
||||
request.validate().map_err(map_wire_error)?;
|
||||
let data = state
|
||||
.account_admin_service()
|
||||
.refresh_models(request.id)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)))
|
||||
}
|
||||
|
||||
async fn test_account_connection<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Query(query): Query<AccountTestQuery>,
|
||||
) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, AdminError>
|
||||
where
|
||||
S: AccountAdminState + Send + Sync,
|
||||
{
|
||||
query.validate().map_err(map_wire_error)?;
|
||||
let stream = state
|
||||
.account_admin_service()
|
||||
.test_connection(query.id, query.model_id)
|
||||
.await
|
||||
.map_err(map_service_error)?
|
||||
.map(|event| {
|
||||
let data = serde_json::to_string(&event.data).unwrap_or_else(|_| "{}".to_owned());
|
||||
Ok(Event::default().data(data))
|
||||
});
|
||||
Ok(Sse::new(stream).keep_alive(KeepAlive::default()))
|
||||
}
|
||||
|
||||
fn map_wire_error(error: WireValidationError) -> AdminError {
|
||||
AdminError::bad_request(format!("Invalid {}", error.field()))
|
||||
}
|
||||
|
||||
fn map_service_error(error: AdminServiceError) -> AdminError {
|
||||
match error.kind() {
|
||||
AdminServiceErrorKind::Invalid => AdminError::bad_request(error.to_string()),
|
||||
AdminServiceErrorKind::NotFound => AdminError::not_found(error.to_string()),
|
||||
AdminServiceErrorKind::Conflict => AdminError::conflict(error.to_string()),
|
||||
AdminServiceErrorKind::Unavailable => {
|
||||
AdminError::service_unavailable("Account directory unavailable")
|
||||
}
|
||||
AdminServiceErrorKind::Internal => AdminError::internal(error.to_string()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,717 @@
|
||||
//! 管理员登录、会话、principal 与认证服务端口。
|
||||
|
||||
use std::{fmt, sync::Arc};
|
||||
|
||||
use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier, password_hash::SaltString};
|
||||
use async_trait::async_trait;
|
||||
use axum::{
|
||||
Extension, Json, Router,
|
||||
extract::{FromRequestParts, State},
|
||||
http::{HeaderMap, HeaderValue, StatusCode, header::SET_COOKIE, request::Parts},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use rand_core::{OsRng, RngCore};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use subtle::ConstantTimeEq as _;
|
||||
|
||||
use super::{AdminEnvelope, AdminError, AdminResponse};
|
||||
|
||||
/// 管理端服务错误分类。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AdminServiceErrorKind {
|
||||
Invalid,
|
||||
NotFound,
|
||||
Conflict,
|
||||
Unavailable,
|
||||
Internal,
|
||||
}
|
||||
|
||||
/// 管理端服务错误。
|
||||
#[derive(Debug, Clone, thiserror::Error)]
|
||||
#[error("{message}")]
|
||||
pub struct AdminServiceError {
|
||||
kind: AdminServiceErrorKind,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl AdminServiceError {
|
||||
#[must_use]
|
||||
pub fn new(kind: AdminServiceErrorKind, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn invalid(message: impl Into<String>) -> Self {
|
||||
Self::new(AdminServiceErrorKind::Invalid, message)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn not_found(message: impl Into<String>) -> Self {
|
||||
Self::new(AdminServiceErrorKind::NotFound, message)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn conflict(message: impl Into<String>) -> Self {
|
||||
Self::new(AdminServiceErrorKind::Conflict, message)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn unavailable(message: impl Into<String>) -> Self {
|
||||
Self::new(AdminServiceErrorKind::Unavailable, message)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn internal(message: impl Into<String>) -> Self {
|
||||
Self::new(AdminServiceErrorKind::Internal, message)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn kind(&self) -> AdminServiceErrorKind {
|
||||
self.kind
|
||||
}
|
||||
}
|
||||
|
||||
/// 已认证的管理端主体。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AdminPrincipal {
|
||||
Session { admin_user_id: String },
|
||||
ApiKey,
|
||||
}
|
||||
|
||||
/// 传给应用服务的安全请求上下文。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AdminRequestContext {
|
||||
principal: AdminPrincipal,
|
||||
request_id: String,
|
||||
}
|
||||
|
||||
impl AdminRequestContext {
|
||||
#[must_use]
|
||||
pub fn new(principal: AdminPrincipal, request_id: impl Into<String>) -> Self {
|
||||
Self {
|
||||
principal,
|
||||
request_id: request_id.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn principal(&self) -> &AdminPrincipal {
|
||||
&self.principal
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn admin_user_id(&self) -> Option<&str> {
|
||||
match &self.principal {
|
||||
AdminPrincipal::Session { admin_user_id } => Some(admin_user_id),
|
||||
AdminPrincipal::ApiKey => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn request_id(&self) -> &str {
|
||||
&self.request_id
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn is_api_key(&self) -> bool {
|
||||
matches!(self.principal, AdminPrincipal::ApiKey)
|
||||
}
|
||||
}
|
||||
|
||||
const REQUEST_ID_HEADER: &str = "x-request-id";
|
||||
|
||||
#[async_trait]
|
||||
pub trait AdminSessionResolver: Send + Sync {
|
||||
async fn resolve_admin_user_id(
|
||||
&self,
|
||||
session_id: Option<&str>,
|
||||
) -> Result<Option<String>, AdminServiceError>;
|
||||
|
||||
async fn verify_admin_api_key(&self, _key: &str) -> Result<bool, AdminServiceError> {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait AdminSessionState {
|
||||
fn admin_session_resolver(&self) -> &dyn AdminSessionResolver;
|
||||
}
|
||||
|
||||
/// 已通过管理员会话或部署级管理 API Key 鉴权的请求。
|
||||
pub struct AdminAuth {
|
||||
context: AdminRequestContext,
|
||||
}
|
||||
|
||||
impl AdminAuth {
|
||||
#[must_use]
|
||||
pub fn context(&self) -> &AdminRequestContext {
|
||||
&self.context
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn into_context(self) -> AdminRequestContext {
|
||||
self.context
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> FromRequestParts<S> for AdminAuth
|
||||
where
|
||||
S: AdminSessionState + Send + Sync,
|
||||
{
|
||||
type Rejection = AdminError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
|
||||
let principal = require_admin_auth(state, &parts.headers).await?;
|
||||
let request_id = parts
|
||||
.headers
|
||||
.get(REQUEST_ID_HEADER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(|| AdminError::internal("Missing admin request context"))?;
|
||||
Ok(Self {
|
||||
context: AdminRequestContext::new(principal, request_id),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn require_admin_session<S>(state: &S, headers: &HeaderMap) -> Result<String, AdminError>
|
||||
where
|
||||
S: AdminSessionState + Send + Sync,
|
||||
{
|
||||
match state
|
||||
.admin_session_resolver()
|
||||
.resolve_admin_user_id(admin_session_cookie(headers).as_deref())
|
||||
.await
|
||||
{
|
||||
Ok(Some(admin_user_id)) => Ok(admin_user_id),
|
||||
Ok(None) => Err(AdminError::admin_session_required()),
|
||||
Err(_) => Err(AdminError::internal("Failed to validate admin session")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn require_admin_auth<S>(state: &S, headers: &HeaderMap) -> Result<AdminPrincipal, AdminError>
|
||||
where
|
||||
S: AdminSessionState + Send + Sync,
|
||||
{
|
||||
if let Some(api_key) = admin_api_key_header(headers) {
|
||||
return match state
|
||||
.admin_session_resolver()
|
||||
.verify_admin_api_key(&api_key)
|
||||
.await
|
||||
{
|
||||
Ok(true) => Ok(AdminPrincipal::ApiKey),
|
||||
Ok(false) => Err(AdminError::invalid_admin_api_key()),
|
||||
Err(_) => Err(AdminError::internal("Failed to validate admin API key")),
|
||||
};
|
||||
}
|
||||
|
||||
require_admin_session(state, headers)
|
||||
.await
|
||||
.map(|admin_user_id| AdminPrincipal::Session { admin_user_id })
|
||||
}
|
||||
|
||||
fn admin_api_key_header(headers: &HeaderMap) -> Option<String> {
|
||||
let value = headers.get("x-api-key")?.to_str().ok()?.trim();
|
||||
(!value.is_empty()).then(|| value.to_owned())
|
||||
}
|
||||
|
||||
const ADMIN_SESSION_COOKIE: &str = "cpr_admin_session";
|
||||
const ADMIN_SESSION_COOKIE_ATTRS: &str = "Path=/; Secure; HttpOnly; SameSite=Lax";
|
||||
|
||||
/// 管理员登录请求;密码不得进入 `Debug`。
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AdminLoginRequest {
|
||||
username: Option<String>,
|
||||
password: String,
|
||||
}
|
||||
|
||||
impl AdminLoginRequest {
|
||||
/// 取出认证服务所需字段。
|
||||
#[must_use]
|
||||
pub fn into_parts(self) -> (Option<String>, String) {
|
||||
(self.username, self.password)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for AdminLoginRequest {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter
|
||||
.debug_struct("AdminLoginRequest")
|
||||
.field("username", &self.username)
|
||||
.field("password", &"[REDACTED]")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// 登录成功响应。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AdminLoginData {
|
||||
expires_at: String,
|
||||
}
|
||||
|
||||
impl AdminLoginData {
|
||||
/// 构造登录成功响应。
|
||||
#[must_use]
|
||||
pub fn new(expires_at: String) -> Self {
|
||||
Self { expires_at }
|
||||
}
|
||||
}
|
||||
|
||||
/// 管理员会话状态响应。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AdminSessionStatusData {
|
||||
authenticated: bool,
|
||||
}
|
||||
|
||||
impl AdminSessionStatusData {
|
||||
/// 构造会话状态响应。
|
||||
#[must_use]
|
||||
pub const fn new(authenticated: bool) -> Self {
|
||||
Self { authenticated }
|
||||
}
|
||||
}
|
||||
|
||||
/// 登出成功响应。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
pub struct AdminLogoutData {
|
||||
message: &'static str,
|
||||
}
|
||||
|
||||
impl AdminLogoutData {
|
||||
/// 构造稳定登出响应。
|
||||
#[must_use]
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
message: "Logged out successfully",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AdminLogoutData {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// 请求上下文解析出的客户端登录来源。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AdminLoginSource(String);
|
||||
|
||||
impl AdminLoginSource {
|
||||
#[must_use]
|
||||
pub fn new(value: impl Into<String>) -> Self {
|
||||
Self(value.into())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// 登录成功后由应用层返回的 session 事实。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AdminLoginSession {
|
||||
pub session_id: String,
|
||||
pub expires_at: String,
|
||||
}
|
||||
|
||||
/// 登录特有的低基数失败分类。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AdminLoginError {
|
||||
InvalidCredentials,
|
||||
Throttled,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
/// 管理员认证应用端口。
|
||||
#[async_trait]
|
||||
pub trait AdminAuthService: Send + Sync {
|
||||
async fn login(
|
||||
&self,
|
||||
source: &str,
|
||||
username: Option<String>,
|
||||
password: String,
|
||||
) -> Result<AdminLoginSession, AdminLoginError>;
|
||||
|
||||
async fn validate(&self, session_id: Option<String>) -> Result<bool, AdminServiceError>;
|
||||
|
||||
async fn logout(&self, session_id: String) -> Result<(), AdminServiceError>;
|
||||
}
|
||||
|
||||
/// 认证 HTTP module 的最小 state。
|
||||
pub trait AdminAuthState {
|
||||
fn admin_auth_service(&self) -> &dyn AdminAuthService;
|
||||
}
|
||||
|
||||
/// 构造固定 GET/POST 管理员认证路由。
|
||||
pub fn router<S>() -> Router<S>
|
||||
where
|
||||
S: AdminAuthState + Clone + Send + Sync + 'static,
|
||||
{
|
||||
Router::new()
|
||||
.route("/api/admin/login", post(login::<S>))
|
||||
.route("/api/admin/auth/status", get(session_status::<S>))
|
||||
.route("/api/admin/logout", post(logout::<S>))
|
||||
}
|
||||
|
||||
async fn login<S>(
|
||||
State(state): State<S>,
|
||||
source: Option<Extension<AdminLoginSource>>,
|
||||
Json(payload): Json<AdminLoginRequest>,
|
||||
) -> Result<Response, AdminError>
|
||||
where
|
||||
S: AdminAuthState + Send + Sync,
|
||||
{
|
||||
let source = source
|
||||
.as_ref()
|
||||
.map_or("unknown", |Extension(source)| source.as_str());
|
||||
let (username, password) = payload.into_parts();
|
||||
let session = state
|
||||
.admin_auth_service()
|
||||
.login(source, username, password)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
AdminLoginError::InvalidCredentials => AdminError::invalid_admin_credentials(),
|
||||
AdminLoginError::Throttled => AdminError::too_many_login_attempts(),
|
||||
AdminLoginError::Unavailable => AdminError::internal("Failed to create admin session"),
|
||||
})?;
|
||||
let mut response = AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(AdminLoginData::new(session.expires_at)),
|
||||
)
|
||||
.into_response();
|
||||
let cookie = format!(
|
||||
"{ADMIN_SESSION_COOKIE}={}; {ADMIN_SESSION_COOKIE_ATTRS}",
|
||||
session.session_id
|
||||
);
|
||||
response.headers_mut().insert(
|
||||
SET_COOKIE,
|
||||
HeaderValue::from_str(&cookie)
|
||||
.map_err(|_| AdminError::internal("Failed to create admin session cookie"))?,
|
||||
);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn session_status<S>(
|
||||
State(state): State<S>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: AdminAuthState + Send + Sync,
|
||||
{
|
||||
let authenticated = state
|
||||
.admin_auth_service()
|
||||
.validate(admin_session_cookie(&headers))
|
||||
.await
|
||||
.map_err(|_| AdminError::internal("Failed to validate admin session"))?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(AdminSessionStatusData::new(authenticated)),
|
||||
))
|
||||
}
|
||||
|
||||
async fn logout<S>(State(state): State<S>, headers: HeaderMap) -> Result<Response, AdminError>
|
||||
where
|
||||
S: AdminAuthState + Send + Sync,
|
||||
{
|
||||
if let Some(session_id) = admin_session_cookie(&headers) {
|
||||
let _ = state.admin_auth_service().logout(session_id).await;
|
||||
}
|
||||
let mut response =
|
||||
AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(AdminLogoutData::new()))
|
||||
.into_response();
|
||||
let cookie = format!("{ADMIN_SESSION_COOKIE}=; {ADMIN_SESSION_COOKIE_ATTRS}; Max-Age=0");
|
||||
response.headers_mut().insert(
|
||||
SET_COOKIE,
|
||||
HeaderValue::from_str(&cookie)
|
||||
.map_err(|_| AdminError::internal("Failed to clear admin session cookie"))?,
|
||||
);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
fn admin_session_cookie(headers: &HeaderMap) -> Option<String> {
|
||||
let cookie = headers.get("cookie")?.to_str().ok()?;
|
||||
cookie.split(';').find_map(|part| {
|
||||
let (name, value) = part.trim().split_once('=')?;
|
||||
(name == ADMIN_SESSION_COOKIE).then(|| value.to_owned())
|
||||
})
|
||||
}
|
||||
|
||||
const LOGIN_FAILURE_LIMIT: u32 = 5;
|
||||
const LOGIN_FAILURE_WINDOW_SECONDS: u64 = 15 * 60;
|
||||
|
||||
/// 认证领域需要的外层持久端口;API crate 不知道 PostgreSQL 或 runtime settings。
|
||||
#[async_trait]
|
||||
pub trait AdminAuthBackend: Send + Sync {
|
||||
async fn password_hash(&self, admin_user_id: &str)
|
||||
-> Result<Option<String>, AdminServiceError>;
|
||||
async fn store_password_hash(
|
||||
&self,
|
||||
admin_user_id: &str,
|
||||
password_hash: &str,
|
||||
) -> Result<(), AdminServiceError>;
|
||||
async fn admin_api_key(&self) -> Result<Option<String>, AdminServiceError>;
|
||||
async fn load_admin_session(
|
||||
&self,
|
||||
session_id: &str,
|
||||
) -> Result<Option<AdminBackendSession>, AdminServiceError>;
|
||||
async fn store_admin_session(
|
||||
&self,
|
||||
session_id: &str,
|
||||
session: &AdminBackendSession,
|
||||
) -> Result<(), AdminServiceError>;
|
||||
async fn delete_admin_session(
|
||||
&self,
|
||||
session_id: &str,
|
||||
) -> Result<Option<AdminBackendSession>, AdminServiceError>;
|
||||
async fn login_source_is_throttled(
|
||||
&self,
|
||||
source: &str,
|
||||
failure_limit: u32,
|
||||
window_seconds: u64,
|
||||
) -> Result<bool, AdminServiceError>;
|
||||
async fn record_login_failure(
|
||||
&self,
|
||||
source: &str,
|
||||
failure_limit: u32,
|
||||
window_seconds: u64,
|
||||
) -> Result<bool, AdminServiceError>;
|
||||
async fn clear_login_failures(&self, source: &str) -> Result<(), AdminServiceError>;
|
||||
async fn append_auth_audit(&self, event: AdminAuthAuditEvent) -> Result<(), AdminServiceError>;
|
||||
}
|
||||
|
||||
/// 登录与登出的最小安全审计事实。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AdminAuthAuditEvent {
|
||||
pub admin_user_id: String,
|
||||
pub action: &'static str,
|
||||
pub occurred_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// Redis session owner 与认证领域交换的非秘密会话事实。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AdminBackendSession {
|
||||
pub admin_user_id: String,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// 冻结管理端使用的默认认证领域实现。
|
||||
pub struct DefaultAdminAuthService {
|
||||
default_admin_user_id: String,
|
||||
session_ttl: Duration,
|
||||
backend: Arc<dyn AdminAuthBackend>,
|
||||
}
|
||||
|
||||
impl DefaultAdminAuthService {
|
||||
#[must_use]
|
||||
pub fn new(
|
||||
default_admin_user_id: String,
|
||||
session_ttl_minutes: u64,
|
||||
backend: Arc<dyn AdminAuthBackend>,
|
||||
) -> Self {
|
||||
let minutes = i64::try_from(session_ttl_minutes).unwrap_or(i64::MAX);
|
||||
Self {
|
||||
default_admin_user_id,
|
||||
session_ttl: Duration::minutes(minutes.max(1)),
|
||||
backend,
|
||||
}
|
||||
}
|
||||
|
||||
/// 空库第一次启动时创建唯一默认管理员;已有用户绝不覆盖密码。
|
||||
pub async fn ensure_default_admin(&self, password: &str) -> Result<bool, AdminServiceError> {
|
||||
if self
|
||||
.backend
|
||||
.password_hash(&self.default_admin_user_id)
|
||||
.await?
|
||||
.is_some()
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let hash = hash_admin_password(password)?;
|
||||
self.backend
|
||||
.store_password_hash(&self.default_admin_user_id, &hash)
|
||||
.await?;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AdminSessionResolver for DefaultAdminAuthService {
|
||||
async fn resolve_admin_user_id(
|
||||
&self,
|
||||
session_id: Option<&str>,
|
||||
) -> Result<Option<String>, AdminServiceError> {
|
||||
let Some(session_id) = session_id else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(self
|
||||
.backend
|
||||
.load_admin_session(session_id)
|
||||
.await?
|
||||
.filter(|session| session.expires_at > Utc::now())
|
||||
.map(|session| session.admin_user_id))
|
||||
}
|
||||
|
||||
async fn verify_admin_api_key(&self, key: &str) -> Result<bool, AdminServiceError> {
|
||||
if !valid_admin_api_key_shape(key) {
|
||||
return Ok(false);
|
||||
}
|
||||
let stored = self.backend.admin_api_key().await?;
|
||||
Ok(stored.as_deref().is_some_and(|stored| {
|
||||
key.len() == stored.len() && bool::from(key.as_bytes().ct_eq(stored.as_bytes()))
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AdminAuthService for DefaultAdminAuthService {
|
||||
async fn login(
|
||||
&self,
|
||||
source: &str,
|
||||
username: Option<String>,
|
||||
password: String,
|
||||
) -> Result<AdminLoginSession, AdminLoginError> {
|
||||
let source = normalized_login_source(source);
|
||||
if self
|
||||
.backend
|
||||
.login_source_is_throttled(source, LOGIN_FAILURE_LIMIT, LOGIN_FAILURE_WINDOW_SECONDS)
|
||||
.await
|
||||
.map_err(|_| AdminLoginError::Unavailable)?
|
||||
{
|
||||
return Err(AdminLoginError::Throttled);
|
||||
}
|
||||
if username.as_deref().unwrap_or(&self.default_admin_user_id) != self.default_admin_user_id
|
||||
{
|
||||
let throttled = self
|
||||
.backend
|
||||
.record_login_failure(source, LOGIN_FAILURE_LIMIT, LOGIN_FAILURE_WINDOW_SECONDS)
|
||||
.await
|
||||
.map_err(|_| AdminLoginError::Unavailable)?;
|
||||
return Err(if throttled {
|
||||
AdminLoginError::Throttled
|
||||
} else {
|
||||
AdminLoginError::InvalidCredentials
|
||||
});
|
||||
}
|
||||
let hash = self
|
||||
.backend
|
||||
.password_hash(&self.default_admin_user_id)
|
||||
.await
|
||||
.map_err(|_| AdminLoginError::Unavailable)?
|
||||
.ok_or(AdminLoginError::InvalidCredentials)?;
|
||||
if !verify_admin_password(&password, &hash).map_err(|_| AdminLoginError::Unavailable)? {
|
||||
let throttled = self
|
||||
.backend
|
||||
.record_login_failure(source, LOGIN_FAILURE_LIMIT, LOGIN_FAILURE_WINDOW_SECONDS)
|
||||
.await
|
||||
.map_err(|_| AdminLoginError::Unavailable)?;
|
||||
return Err(if throttled {
|
||||
AdminLoginError::Throttled
|
||||
} else {
|
||||
AdminLoginError::InvalidCredentials
|
||||
});
|
||||
}
|
||||
|
||||
self.backend
|
||||
.clear_login_failures(source)
|
||||
.await
|
||||
.map_err(|_| AdminLoginError::Unavailable)?;
|
||||
let session_id = random_session_token();
|
||||
let expires_at = Utc::now() + self.session_ttl;
|
||||
self.backend
|
||||
.store_admin_session(
|
||||
&session_id,
|
||||
&AdminBackendSession {
|
||||
admin_user_id: self.default_admin_user_id.clone(),
|
||||
expires_at,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|_| AdminLoginError::Unavailable)?;
|
||||
if self
|
||||
.backend
|
||||
.append_auth_audit(AdminAuthAuditEvent {
|
||||
admin_user_id: self.default_admin_user_id.clone(),
|
||||
action: "admin.login",
|
||||
occurred_at: Utc::now(),
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
let _ = self.backend.delete_admin_session(&session_id).await;
|
||||
return Err(AdminLoginError::Unavailable);
|
||||
}
|
||||
Ok(AdminLoginSession {
|
||||
session_id,
|
||||
expires_at: expires_at.to_rfc3339(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn validate(&self, session_id: Option<String>) -> Result<bool, AdminServiceError> {
|
||||
let Some(session_id) = session_id else {
|
||||
return Ok(false);
|
||||
};
|
||||
Ok(self
|
||||
.backend
|
||||
.load_admin_session(&session_id)
|
||||
.await?
|
||||
.is_some_and(|session| session.expires_at > Utc::now()))
|
||||
}
|
||||
|
||||
async fn logout(&self, session_id: String) -> Result<(), AdminServiceError> {
|
||||
let session = self.backend.delete_admin_session(&session_id).await?;
|
||||
if let Some(session) = session {
|
||||
self.backend
|
||||
.append_auth_audit(AdminAuthAuditEvent {
|
||||
admin_user_id: session.admin_user_id,
|
||||
action: "admin.logout",
|
||||
occurred_at: Utc::now(),
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn hash_admin_password(password: &str) -> Result<String, AdminServiceError> {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
Argon2::default()
|
||||
.hash_password(password.as_bytes(), &salt)
|
||||
.map(|hash| hash.to_string())
|
||||
.map_err(|_| AdminServiceError::internal("Failed to hash admin password"))
|
||||
}
|
||||
|
||||
fn verify_admin_password(password: &str, encoded: &str) -> Result<bool, AdminServiceError> {
|
||||
let hash = PasswordHash::new(encoded)
|
||||
.map_err(|_| AdminServiceError::internal("Stored admin password hash is invalid"))?;
|
||||
Ok(Argon2::default()
|
||||
.verify_password(password.as_bytes(), &hash)
|
||||
.is_ok())
|
||||
}
|
||||
|
||||
fn random_session_token() -> String {
|
||||
let mut bytes = [0_u8; 32];
|
||||
OsRng.fill_bytes(&mut bytes);
|
||||
format!("session_{}", URL_SAFE_NO_PAD.encode(bytes))
|
||||
}
|
||||
|
||||
fn valid_admin_api_key_shape(value: &str) -> bool {
|
||||
value.len() == 70
|
||||
&& value.starts_with("admin-")
|
||||
&& value[6..].bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
fn normalized_login_source(source: &str) -> &str {
|
||||
let source = source.trim();
|
||||
if source.is_empty() { "unknown" } else { source }
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
//! Provider instance 管理边界。
|
||||
|
||||
use async_trait::async_trait;
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Query, State},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
routing::{get, post},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use gateway_core::routing::ProviderInstanceId;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{
|
||||
AdminAuth, AdminEnvelope, AdminError, AdminRequestContext, AdminResponse, AdminServiceError,
|
||||
AdminServiceErrorKind, AdminSessionState, WireValidationError,
|
||||
};
|
||||
|
||||
const DEFAULT_PAGE_SIZE: u16 = 50;
|
||||
const MAX_PAGE_SIZE: u16 = 200;
|
||||
const MAX_CURSOR_BYTES: usize = 1024;
|
||||
const MAX_TEXT_BYTES: usize = 2048;
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CatalogListQuery {
|
||||
pub cursor: Option<String>,
|
||||
pub limit: Option<u16>,
|
||||
}
|
||||
|
||||
impl CatalogListQuery {
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
validate_cursor(self.cursor.as_deref())?;
|
||||
validate_limit(self.limit)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn page_size(&self) -> u16 {
|
||||
self.limit.unwrap_or(DEFAULT_PAGE_SIZE)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CatalogIdQuery {
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
impl CatalogIdQuery {
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_id(&self.id, "id")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CatalogMutationData {
|
||||
pub config_revision: u64,
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CreateProviderInstanceRequest {
|
||||
pub id: String,
|
||||
pub expected_config_revision: u64,
|
||||
pub provider_kind: String,
|
||||
pub name: String,
|
||||
pub base_url: String,
|
||||
}
|
||||
|
||||
impl CreateProviderInstanceRequest {
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_provider_instance_id(&self.id, "id")?;
|
||||
require_revision(self.expected_config_revision)?;
|
||||
require_provider_kind(&self.provider_kind)?;
|
||||
require_text(&self.name, "name")?;
|
||||
require_text(&self.base_url, "baseUrl")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateProviderInstanceRequest {
|
||||
pub id: String,
|
||||
pub expected_config_revision: u64,
|
||||
pub name: String,
|
||||
pub base_url: String,
|
||||
}
|
||||
|
||||
impl UpdateProviderInstanceRequest {
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_provider_instance_id(&self.id, "id")?;
|
||||
require_revision(self.expected_config_revision)?;
|
||||
require_text(&self.name, "name")?;
|
||||
require_text(&self.base_url, "baseUrl")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CatalogRevisionRequest {
|
||||
pub id: String,
|
||||
pub expected_config_revision: u64,
|
||||
}
|
||||
|
||||
impl CatalogRevisionRequest {
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_id(&self.id, "id")?;
|
||||
require_revision(self.expected_config_revision)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProviderInstanceView {
|
||||
pub id: String,
|
||||
pub provider_kind: String,
|
||||
pub name: String,
|
||||
pub base_url: String,
|
||||
pub enabled: bool,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProviderInstanceListData {
|
||||
pub config_revision: u64,
|
||||
pub items: Vec<ProviderInstanceView>,
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProviderInstanceDetailData {
|
||||
pub config_revision: u64,
|
||||
pub item: ProviderInstanceView,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait CatalogAdminService: Send + Sync {
|
||||
async fn list_provider_instances(
|
||||
&self,
|
||||
query: CatalogListQuery,
|
||||
) -> Result<ProviderInstanceListData, AdminServiceError>;
|
||||
async fn provider_instance(
|
||||
&self,
|
||||
id: String,
|
||||
) -> Result<ProviderInstanceDetailData, AdminServiceError>;
|
||||
async fn create_provider_instance(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: CreateProviderInstanceRequest,
|
||||
) -> Result<CatalogMutationData, AdminServiceError>;
|
||||
async fn update_provider_instance(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: UpdateProviderInstanceRequest,
|
||||
) -> Result<CatalogMutationData, AdminServiceError>;
|
||||
async fn enable_provider_instance(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: CatalogRevisionRequest,
|
||||
) -> Result<CatalogMutationData, AdminServiceError>;
|
||||
async fn disable_provider_instance(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: CatalogRevisionRequest,
|
||||
) -> Result<CatalogMutationData, AdminServiceError>;
|
||||
async fn delete_provider_instance(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: CatalogRevisionRequest,
|
||||
) -> Result<CatalogMutationData, AdminServiceError>;
|
||||
}
|
||||
|
||||
pub trait CatalogAdminState: AdminSessionState {
|
||||
fn catalog_admin_service(&self) -> &dyn CatalogAdminService;
|
||||
}
|
||||
|
||||
pub fn router<S>() -> Router<S>
|
||||
where
|
||||
S: CatalogAdminState + Clone + Send + Sync + 'static,
|
||||
{
|
||||
Router::new()
|
||||
.route(
|
||||
"/api/admin/provider-instances",
|
||||
get(list_provider_instances::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/provider-instances/detail",
|
||||
get(provider_instance::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/provider-instances/create",
|
||||
post(create_provider_instance::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/provider-instances/update",
|
||||
post(update_provider_instance::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/provider-instances/enable",
|
||||
post(enable_provider_instance::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/provider-instances/disable",
|
||||
post(disable_provider_instance::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/provider-instances/delete",
|
||||
post(delete_provider_instance::<S>),
|
||||
)
|
||||
}
|
||||
|
||||
macro_rules! get_handler {
|
||||
($name:ident, $query:ty, $method:ident) => {
|
||||
async fn $name<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Query(query): Query<$query>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: CatalogAdminState + Send + Sync,
|
||||
{
|
||||
query.validate().map_err(map_wire_error)?;
|
||||
let data = state
|
||||
.catalog_admin_service()
|
||||
.$method(query)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! get_id_handler {
|
||||
($name:ident, $method:ident) => {
|
||||
async fn $name<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Query(query): Query<CatalogIdQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: CatalogAdminState + Send + Sync,
|
||||
{
|
||||
query.validate().map_err(map_wire_error)?;
|
||||
let data = state
|
||||
.catalog_admin_service()
|
||||
.$method(query.id)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! post_handler {
|
||||
($name:ident, $request:ty, $method:ident, $status:expr) => {
|
||||
async fn $name<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Json(request): Json<$request>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: CatalogAdminState + Send + Sync,
|
||||
{
|
||||
request.validate().map_err(map_wire_error)?;
|
||||
let data = state
|
||||
.catalog_admin_service()
|
||||
.$method(auth.context(), request)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new($status, AdminEnvelope::ok(data)))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
get_handler!(
|
||||
list_provider_instances,
|
||||
CatalogListQuery,
|
||||
list_provider_instances
|
||||
);
|
||||
get_id_handler!(provider_instance, provider_instance);
|
||||
post_handler!(
|
||||
create_provider_instance,
|
||||
CreateProviderInstanceRequest,
|
||||
create_provider_instance,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
post_handler!(
|
||||
update_provider_instance,
|
||||
UpdateProviderInstanceRequest,
|
||||
update_provider_instance,
|
||||
StatusCode::OK
|
||||
);
|
||||
post_handler!(
|
||||
enable_provider_instance,
|
||||
CatalogRevisionRequest,
|
||||
enable_provider_instance,
|
||||
StatusCode::OK
|
||||
);
|
||||
post_handler!(
|
||||
disable_provider_instance,
|
||||
CatalogRevisionRequest,
|
||||
disable_provider_instance,
|
||||
StatusCode::OK
|
||||
);
|
||||
post_handler!(
|
||||
delete_provider_instance,
|
||||
CatalogRevisionRequest,
|
||||
delete_provider_instance,
|
||||
StatusCode::OK
|
||||
);
|
||||
|
||||
fn require_revision(value: u64) -> Result<(), WireValidationError> {
|
||||
if value == 0 || i64::try_from(value).is_err() {
|
||||
return Err(WireValidationError::new("expectedConfigRevision"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_id(value: &str, field: &'static str) -> Result<(), WireValidationError> {
|
||||
require_text(value, field)?;
|
||||
if value.starts_with("__")
|
||||
|| !value
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':'))
|
||||
{
|
||||
return Err(WireValidationError::new(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_provider_instance_id(
|
||||
value: &str,
|
||||
field: &'static str,
|
||||
) -> Result<(), WireValidationError> {
|
||||
ProviderInstanceId::new(value).map_or_else(|_| Err(WireValidationError::new(field)), |_| Ok(()))
|
||||
}
|
||||
|
||||
fn require_text(value: &str, field: &'static str) -> Result<(), WireValidationError> {
|
||||
if value.trim().is_empty()
|
||||
|| value.len() > MAX_TEXT_BYTES
|
||||
|| value.chars().any(char::is_control)
|
||||
{
|
||||
return Err(WireValidationError::new(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_provider_kind(value: &str) -> Result<(), WireValidationError> {
|
||||
if matches!(value, "openai" | "xai") {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(WireValidationError::new("providerKind"))
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_cursor(cursor: Option<&str>) -> Result<(), WireValidationError> {
|
||||
if cursor.is_some_and(|value| value.is_empty() || value.len() > MAX_CURSOR_BYTES) {
|
||||
Err(WireValidationError::new("cursor"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_limit(limit: Option<u16>) -> Result<(), WireValidationError> {
|
||||
if limit.is_some_and(|value| value == 0 || value > MAX_PAGE_SIZE) {
|
||||
Err(WireValidationError::new("limit"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn map_wire_error(error: WireValidationError) -> AdminError {
|
||||
AdminError::bad_request(format!("Invalid field: {}", error.field()))
|
||||
}
|
||||
|
||||
fn map_service_error(error: AdminServiceError) -> AdminError {
|
||||
match error.kind() {
|
||||
AdminServiceErrorKind::Invalid => AdminError::bad_request(error.to_string()),
|
||||
AdminServiceErrorKind::NotFound => AdminError::not_found(error.to_string()),
|
||||
AdminServiceErrorKind::Conflict => AdminError::conflict(error.to_string()),
|
||||
AdminServiceErrorKind::Unavailable => {
|
||||
AdminError::service_unavailable("Catalog unavailable")
|
||||
}
|
||||
AdminServiceErrorKind::Internal => AdminError::internal(error.to_string()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,788 @@
|
||||
//! Client API Key 管理 wire contract。
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Query, State},
|
||||
http::{HeaderValue, StatusCode, header::CACHE_CONTROL},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
|
||||
use super::{
|
||||
AdminAuth, AdminEnvelope, AdminError, AdminRequestContext, AdminResponse, AdminServiceError,
|
||||
AdminServiceErrorKind, AdminSessionState, WireValidationError,
|
||||
};
|
||||
|
||||
const MAX_CURSOR_BYTES: usize = 512;
|
||||
const MAX_SEARCH_BYTES: usize = 256;
|
||||
|
||||
/// Client Key 列表查询。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ListClientKeysQuery {
|
||||
cursor: Option<String>,
|
||||
limit: Option<u16>,
|
||||
search: Option<String>,
|
||||
sort_by: Option<String>,
|
||||
sort_direction: Option<String>,
|
||||
}
|
||||
|
||||
impl ListClientKeysQuery {
|
||||
/// 校验游标与页大小的 wire 边界并取出字段。
|
||||
pub fn into_parts(self) -> Result<ListClientKeysFields, WireValidationError> {
|
||||
if self
|
||||
.cursor
|
||||
.as_deref()
|
||||
.is_some_and(|cursor| cursor.is_empty() || cursor.len() > MAX_CURSOR_BYTES)
|
||||
{
|
||||
return Err(WireValidationError::new("cursor"));
|
||||
}
|
||||
if self.limit == Some(0) {
|
||||
return Err(WireValidationError::new("limit"));
|
||||
}
|
||||
let search = self.search.map(|search| search.trim().to_owned());
|
||||
if search.as_deref().is_some_and(|search| {
|
||||
search.len() > MAX_SEARCH_BYTES
|
||||
|| search.chars().any(char::is_control)
|
||||
|| contains_client_key_material(search)
|
||||
}) {
|
||||
return Err(WireValidationError::new("search"));
|
||||
}
|
||||
let sort = ClientKeySort::parse(
|
||||
self.sort_by.as_deref().unwrap_or("createdAt"),
|
||||
self.sort_direction.as_deref().unwrap_or("desc"),
|
||||
)?;
|
||||
Ok(ListClientKeysFields {
|
||||
cursor: self.cursor,
|
||||
limit: self.limit,
|
||||
search: search.filter(|search| !search.is_empty()),
|
||||
sort,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Client Key 数据库排序字段。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ClientKeySortField {
|
||||
Name,
|
||||
Enabled,
|
||||
CreatedAt,
|
||||
LastUsedAt,
|
||||
}
|
||||
|
||||
/// Client Key 数据库排序方向。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ClientKeySortDirection {
|
||||
Asc,
|
||||
Desc,
|
||||
}
|
||||
|
||||
/// 已校验且会写入自描述游标的排序组合。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ClientKeySort {
|
||||
pub field: ClientKeySortField,
|
||||
pub direction: ClientKeySortDirection,
|
||||
}
|
||||
|
||||
impl ClientKeySort {
|
||||
fn parse(field: &str, direction: &str) -> Result<Self, WireValidationError> {
|
||||
let field = match field {
|
||||
"name" => ClientKeySortField::Name,
|
||||
"enabled" => ClientKeySortField::Enabled,
|
||||
"createdAt" => ClientKeySortField::CreatedAt,
|
||||
"lastUsedAt" => ClientKeySortField::LastUsedAt,
|
||||
_ => return Err(WireValidationError::new("sortBy")),
|
||||
};
|
||||
let direction = match direction {
|
||||
"asc" => ClientKeySortDirection::Asc,
|
||||
"desc" => ClientKeySortDirection::Desc,
|
||||
_ => return Err(WireValidationError::new("sortDirection")),
|
||||
};
|
||||
Ok(Self { field, direction })
|
||||
}
|
||||
}
|
||||
|
||||
/// 已校验的 Client Key 列表查询字段。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ListClientKeysFields {
|
||||
pub cursor: Option<String>,
|
||||
pub limit: Option<u16>,
|
||||
pub search: Option<String>,
|
||||
pub sort: ClientKeySort,
|
||||
}
|
||||
|
||||
/// 创建 Client Key 请求。
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CreateClientKeyRequest {
|
||||
expected_config_revision: u64,
|
||||
name: String,
|
||||
label: Option<String>,
|
||||
provider_kind: String,
|
||||
max_concurrency: u64,
|
||||
requests_per_minute: u64,
|
||||
tokens_per_minute: u64,
|
||||
}
|
||||
|
||||
impl CreateClientKeyRequest {
|
||||
/// 校验请求并转换为应用层可消费字段。
|
||||
pub fn into_fields(self) -> Result<CreateClientKeyFields, WireValidationError> {
|
||||
validate_revision(self.expected_config_revision)?;
|
||||
validate_required_text(&self.name, "name")?;
|
||||
validate_optional_text(self.label.as_deref(), "label")?;
|
||||
validate_provider_kind(&self.provider_kind)?;
|
||||
validate_limit(self.max_concurrency, "maxConcurrency")?;
|
||||
validate_limit(self.requests_per_minute, "requestsPerMinute")?;
|
||||
validate_limit(self.tokens_per_minute, "tokensPerMinute")?;
|
||||
Ok(CreateClientKeyFields {
|
||||
expected_config_revision: self.expected_config_revision,
|
||||
name: self.name,
|
||||
label: self.label,
|
||||
provider_kind: self.provider_kind,
|
||||
max_concurrency: self.max_concurrency,
|
||||
requests_per_minute: self.requests_per_minute,
|
||||
tokens_per_minute: self.tokens_per_minute,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 已校验的 Client Key 创建字段。
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CreateClientKeyFields {
|
||||
pub expected_config_revision: u64,
|
||||
pub name: String,
|
||||
pub label: Option<String>,
|
||||
pub provider_kind: String,
|
||||
pub max_concurrency: u64,
|
||||
pub requests_per_minute: u64,
|
||||
pub tokens_per_minute: u64,
|
||||
}
|
||||
|
||||
/// 更新 Client Key 请求。
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateClientKeyRequest {
|
||||
id: String,
|
||||
expected_config_revision: u64,
|
||||
name: String,
|
||||
label: Option<String>,
|
||||
provider_kind: String,
|
||||
max_concurrency: u64,
|
||||
requests_per_minute: u64,
|
||||
tokens_per_minute: u64,
|
||||
}
|
||||
|
||||
impl UpdateClientKeyRequest {
|
||||
/// 校验请求并转换为应用层可消费字段。
|
||||
pub fn into_fields(self) -> Result<UpdateClientKeyFields, WireValidationError> {
|
||||
validate_required_text(&self.id, "id")?;
|
||||
validate_revision(self.expected_config_revision)?;
|
||||
validate_required_text(&self.name, "name")?;
|
||||
validate_optional_text(self.label.as_deref(), "label")?;
|
||||
validate_provider_kind(&self.provider_kind)?;
|
||||
validate_limit(self.max_concurrency, "maxConcurrency")?;
|
||||
validate_limit(self.requests_per_minute, "requestsPerMinute")?;
|
||||
validate_limit(self.tokens_per_minute, "tokensPerMinute")?;
|
||||
Ok(UpdateClientKeyFields {
|
||||
id: self.id,
|
||||
expected_config_revision: self.expected_config_revision,
|
||||
name: self.name,
|
||||
label: self.label,
|
||||
provider_kind: self.provider_kind,
|
||||
max_concurrency: self.max_concurrency,
|
||||
requests_per_minute: self.requests_per_minute,
|
||||
tokens_per_minute: self.tokens_per_minute,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 已校验的 Client Key 更新字段。
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct UpdateClientKeyFields {
|
||||
pub id: String,
|
||||
pub expected_config_revision: u64,
|
||||
pub name: String,
|
||||
pub label: Option<String>,
|
||||
pub provider_kind: String,
|
||||
pub max_concurrency: u64,
|
||||
pub requests_per_minute: u64,
|
||||
pub tokens_per_minute: u64,
|
||||
}
|
||||
|
||||
/// 只携带 ID 与配置 revision 的 Client Key mutation 请求。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ClientKeyRevisionRequest {
|
||||
id: String,
|
||||
expected_config_revision: u64,
|
||||
}
|
||||
|
||||
/// 读取一次完整 Key 的 ID query。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ClientKeyIdQuery {
|
||||
id: String,
|
||||
}
|
||||
|
||||
impl ClientKeyIdQuery {
|
||||
pub fn into_id(self) -> Result<String, WireValidationError> {
|
||||
validate_required_text(&self.id, "id")?;
|
||||
Ok(self.id)
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientKeyRevisionRequest {
|
||||
/// 校验请求并取出 ID 与 revision。
|
||||
pub fn into_parts(self) -> Result<(String, u64), WireValidationError> {
|
||||
validate_required_text(&self.id, "id")?;
|
||||
validate_revision(self.expected_config_revision)?;
|
||||
Ok((self.id, self.expected_config_revision))
|
||||
}
|
||||
}
|
||||
|
||||
/// 不含完整 Key 的管理端安全视图。
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ClientKeyView {
|
||||
id: String,
|
||||
name: String,
|
||||
label: Option<String>,
|
||||
provider_kind: String,
|
||||
prefix: String,
|
||||
enabled: bool,
|
||||
max_concurrency: u64,
|
||||
requests_per_minute: u64,
|
||||
tokens_per_minute: u64,
|
||||
created_at: DateTime<Utc>,
|
||||
updated_at: DateTime<Utc>,
|
||||
last_used_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
impl ClientKeyView {
|
||||
/// 从应用层已经读取的安全字段构造视图。
|
||||
#[must_use]
|
||||
pub fn new(fields: ClientKeyViewFields) -> Self {
|
||||
Self {
|
||||
id: fields.id,
|
||||
name: fields.name,
|
||||
label: fields.label,
|
||||
provider_kind: fields.provider_kind,
|
||||
prefix: fields.prefix,
|
||||
enabled: fields.enabled,
|
||||
max_concurrency: fields.max_concurrency,
|
||||
requests_per_minute: fields.requests_per_minute,
|
||||
tokens_per_minute: fields.tokens_per_minute,
|
||||
created_at: fields.created_at,
|
||||
updated_at: fields.updated_at,
|
||||
last_used_at: fields.last_used_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Client Key 安全视图的应用层输入字段。
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ClientKeyViewFields {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub label: Option<String>,
|
||||
pub provider_kind: String,
|
||||
pub prefix: String,
|
||||
pub enabled: bool,
|
||||
pub max_concurrency: u64,
|
||||
pub requests_per_minute: u64,
|
||||
pub tokens_per_minute: u64,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
pub last_used_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
/// Client Key 列表响应数据。
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ClientKeyListData {
|
||||
config_revision: u64,
|
||||
items: Vec<ClientKeyView>,
|
||||
next_cursor: Option<String>,
|
||||
total: u64,
|
||||
}
|
||||
|
||||
impl ClientKeyListData {
|
||||
/// 构造 Client Key 列表响应。
|
||||
#[must_use]
|
||||
pub fn new(
|
||||
config_revision: u64,
|
||||
items: Vec<ClientKeyView>,
|
||||
next_cursor: Option<String>,
|
||||
total: u64,
|
||||
) -> Self {
|
||||
Self {
|
||||
config_revision,
|
||||
items,
|
||||
next_cursor,
|
||||
total,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Client Key 创建响应;完整值只允许出现在本次序列化结果中。
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CreatedClientKeyData {
|
||||
config_revision: u64,
|
||||
id: String,
|
||||
prefix: String,
|
||||
plaintext_key: String,
|
||||
}
|
||||
|
||||
impl CreatedClientKeyData {
|
||||
/// 构造一次性创建响应。
|
||||
#[must_use]
|
||||
pub fn new(config_revision: u64, id: String, prefix: String, plaintext_key: String) -> Self {
|
||||
Self {
|
||||
config_revision,
|
||||
id,
|
||||
prefix,
|
||||
plaintext_key,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for CreatedClientKeyData {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter
|
||||
.debug_struct("CreatedClientKeyData")
|
||||
.field("config_revision", &self.config_revision)
|
||||
.field("id", &self.id)
|
||||
.field("prefix", &self.prefix)
|
||||
.field("plaintext_key", &"[REDACTED]")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// 仅由显式 reveal 返回一次的完整明文 Key。
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RevealedClientKeyData {
|
||||
id: String,
|
||||
plaintext_key: String,
|
||||
}
|
||||
|
||||
impl RevealedClientKeyData {
|
||||
#[must_use]
|
||||
pub fn new(id: String, plaintext_key: String) -> Self {
|
||||
Self { id, plaintext_key }
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for RevealedClientKeyData {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter
|
||||
.debug_struct("RevealedClientKeyData")
|
||||
.field("id", &self.id)
|
||||
.field("plaintext_key", &"[REDACTED]")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Client Key mutation 响应数据。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MutatedClientKeyData {
|
||||
config_revision: u64,
|
||||
id: String,
|
||||
}
|
||||
|
||||
impl MutatedClientKeyData {
|
||||
/// 构造 mutation 响应。
|
||||
#[must_use]
|
||||
pub fn new(config_revision: u64, id: String) -> Self {
|
||||
Self {
|
||||
config_revision,
|
||||
id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 解码后的 Client Key 游标字段。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientKeyCursorData {
|
||||
pub sort: ClientKeySort,
|
||||
pub value: ClientKeyCursorValue,
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
/// 游标中与排序字段严格对应的最后一行值。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", content = "value", rename_all = "camelCase")]
|
||||
pub enum ClientKeyCursorValue {
|
||||
Name(String),
|
||||
Enabled(bool),
|
||||
CreatedAt(DateTime<Utc>),
|
||||
LastUsedAt(Option<DateTime<Utc>>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct CursorWire {
|
||||
sort: ClientKeySort,
|
||||
value: ClientKeyCursorValue,
|
||||
id: String,
|
||||
}
|
||||
|
||||
/// 把 owner 游标编码为不透明 wire 值。
|
||||
pub fn encode_client_key_cursor(
|
||||
cursor: &ClientKeyCursorData,
|
||||
) -> Result<String, WireValidationError> {
|
||||
validate_client_key_cursor(cursor)?;
|
||||
let bytes = serde_json::to_vec(&CursorWire {
|
||||
sort: cursor.sort,
|
||||
value: cursor.value.clone(),
|
||||
id: cursor.id.clone(),
|
||||
})
|
||||
.map_err(|_| WireValidationError::new("cursor"))?;
|
||||
Ok(URL_SAFE_NO_PAD.encode(bytes))
|
||||
}
|
||||
|
||||
/// 解码并严格校验 Client Key 游标。
|
||||
pub fn decode_client_key_cursor(encoded: &str) -> Result<ClientKeyCursorData, WireValidationError> {
|
||||
if encoded.is_empty() || encoded.len() > MAX_CURSOR_BYTES {
|
||||
return Err(WireValidationError::new("cursor"));
|
||||
}
|
||||
let bytes = URL_SAFE_NO_PAD
|
||||
.decode(encoded)
|
||||
.map_err(|_| WireValidationError::new("cursor"))?;
|
||||
let cursor: CursorWire =
|
||||
serde_json::from_slice(&bytes).map_err(|_| WireValidationError::new("cursor"))?;
|
||||
let cursor = ClientKeyCursorData {
|
||||
sort: cursor.sort,
|
||||
value: cursor.value,
|
||||
id: cursor.id,
|
||||
};
|
||||
validate_client_key_cursor(&cursor)?;
|
||||
Ok(cursor)
|
||||
}
|
||||
|
||||
fn validate_client_key_cursor(cursor: &ClientKeyCursorData) -> Result<(), WireValidationError> {
|
||||
validate_required_text(&cursor.id, "cursor")?;
|
||||
let matching = matches!(
|
||||
(cursor.sort.field, &cursor.value),
|
||||
(ClientKeySortField::Name, ClientKeyCursorValue::Name(value)) if !value.trim().is_empty()
|
||||
) || matches!(
|
||||
(cursor.sort.field, &cursor.value),
|
||||
(
|
||||
ClientKeySortField::Enabled,
|
||||
ClientKeyCursorValue::Enabled(_)
|
||||
) | (
|
||||
ClientKeySortField::CreatedAt,
|
||||
ClientKeyCursorValue::CreatedAt(_)
|
||||
) | (
|
||||
ClientKeySortField::LastUsedAt,
|
||||
ClientKeyCursorValue::LastUsedAt(_)
|
||||
)
|
||||
);
|
||||
if matching {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(WireValidationError::new("cursor"))
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_revision(value: u64) -> Result<(), WireValidationError> {
|
||||
if value == 0 {
|
||||
return Err(WireValidationError::new("expectedConfigRevision"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_limit(value: u64, field: &'static str) -> Result<(), WireValidationError> {
|
||||
if i64::try_from(value).is_err() {
|
||||
return Err(WireValidationError::new(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_required_text(value: &str, field: &'static str) -> Result<(), WireValidationError> {
|
||||
if value.trim().is_empty() {
|
||||
return Err(WireValidationError::new(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_provider_kind(value: &str) -> Result<(), WireValidationError> {
|
||||
let valid = !value.is_empty()
|
||||
&& value.len() <= 64
|
||||
&& value.bytes().enumerate().all(|(index, byte)| {
|
||||
byte.is_ascii_lowercase()
|
||||
|| byte.is_ascii_digit()
|
||||
|| (byte == b'-' && index > 0 && index + 1 < value.len())
|
||||
})
|
||||
&& !value.starts_with('-')
|
||||
&& !value.ends_with('-');
|
||||
if valid {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(WireValidationError::new("providerKind"))
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_optional_text(
|
||||
value: Option<&str>,
|
||||
field: &'static str,
|
||||
) -> Result<(), WireValidationError> {
|
||||
if value.is_some_and(|value| value.trim().is_empty()) {
|
||||
return Err(WireValidationError::new(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn contains_client_key_material(value: &str) -> bool {
|
||||
value.as_bytes().windows(46).any(|window| {
|
||||
&window[..3] == b"sk_"
|
||||
&& window[3..]
|
||||
.iter()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
|
||||
})
|
||||
}
|
||||
|
||||
/// Client API Key 管理应用端口。
|
||||
#[async_trait]
|
||||
pub trait ClientKeyAdminService: Send + Sync {
|
||||
async fn list(
|
||||
&self,
|
||||
query: ListClientKeysFields,
|
||||
) -> Result<ClientKeyListData, AdminServiceError>;
|
||||
|
||||
async fn create(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
fields: CreateClientKeyFields,
|
||||
) -> Result<CreatedClientKeyData, AdminServiceError>;
|
||||
|
||||
async fn reveal(&self, id: String) -> Result<RevealedClientKeyData, AdminServiceError>;
|
||||
|
||||
async fn update(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
fields: UpdateClientKeyFields,
|
||||
) -> Result<MutatedClientKeyData, AdminServiceError>;
|
||||
|
||||
async fn disable(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
id: String,
|
||||
expected_config_revision: u64,
|
||||
) -> Result<MutatedClientKeyData, AdminServiceError>;
|
||||
|
||||
async fn enable(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
id: String,
|
||||
expected_config_revision: u64,
|
||||
) -> Result<MutatedClientKeyData, AdminServiceError>;
|
||||
|
||||
async fn delete(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
id: String,
|
||||
expected_config_revision: u64,
|
||||
) -> Result<MutatedClientKeyData, AdminServiceError>;
|
||||
}
|
||||
|
||||
/// Client API Key HTTP module 所需最小 state。
|
||||
pub trait ClientKeyAdminState: AdminSessionState {
|
||||
fn client_key_admin_service(&self) -> &dyn ClientKeyAdminService;
|
||||
}
|
||||
|
||||
/// 构造固定 GET/POST 且 ID 仅位于 query/body 的 Client API Key 路由。
|
||||
pub fn router<S>() -> Router<S>
|
||||
where
|
||||
S: ClientKeyAdminState + Clone + Send + Sync + 'static,
|
||||
{
|
||||
Router::new()
|
||||
.route(
|
||||
"/api/admin/client-keys",
|
||||
get(list_client_keys::<S>).post(create_client_key::<S>),
|
||||
)
|
||||
.route("/api/admin/client-keys/reveal", get(reveal_client_key::<S>))
|
||||
.route(
|
||||
"/api/admin/client-keys/update",
|
||||
post(update_client_key::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/client-keys/disable",
|
||||
post(disable_client_key::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/client-keys/enable",
|
||||
post(enable_client_key::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/client-keys/delete",
|
||||
post(delete_client_key::<S>),
|
||||
)
|
||||
}
|
||||
|
||||
async fn list_client_keys<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Query(query): Query<ListClientKeysQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: ClientKeyAdminState + Send + Sync,
|
||||
{
|
||||
let fields = query.into_parts().map_err(map_wire_error)?;
|
||||
let data = state
|
||||
.client_key_admin_service()
|
||||
.list(fields)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)))
|
||||
}
|
||||
|
||||
async fn create_client_key<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Json(payload): Json<CreateClientKeyRequest>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: ClientKeyAdminState + Send + Sync,
|
||||
{
|
||||
let fields = payload.into_fields().map_err(map_wire_error)?;
|
||||
let data = state
|
||||
.client_key_admin_service()
|
||||
.create(auth.context(), fields)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::CREATED,
|
||||
AdminEnvelope::ok(data),
|
||||
))
|
||||
}
|
||||
|
||||
async fn reveal_client_key<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Query(query): Query<ClientKeyIdQuery>,
|
||||
) -> Result<Response, AdminError>
|
||||
where
|
||||
S: ClientKeyAdminState + Send + Sync,
|
||||
{
|
||||
let id = query.into_id().map_err(map_wire_error)?;
|
||||
let data = state
|
||||
.client_key_admin_service()
|
||||
.reveal(id)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
let mut response = AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)).into_response();
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn update_client_key<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Json(payload): Json<UpdateClientKeyRequest>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: ClientKeyAdminState + Send + Sync,
|
||||
{
|
||||
let fields = payload.into_fields().map_err(map_wire_error)?;
|
||||
mutation_response(
|
||||
state
|
||||
.client_key_admin_service()
|
||||
.update(auth.context(), fields)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
|
||||
async fn disable_client_key<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Json(payload): Json<ClientKeyRevisionRequest>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: ClientKeyAdminState + Send + Sync,
|
||||
{
|
||||
let (id, revision) = payload.into_parts().map_err(map_wire_error)?;
|
||||
mutation_response(
|
||||
state
|
||||
.client_key_admin_service()
|
||||
.disable(auth.context(), id, revision)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
|
||||
async fn enable_client_key<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Json(payload): Json<ClientKeyRevisionRequest>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: ClientKeyAdminState + Send + Sync,
|
||||
{
|
||||
let (id, revision) = payload.into_parts().map_err(map_wire_error)?;
|
||||
mutation_response(
|
||||
state
|
||||
.client_key_admin_service()
|
||||
.enable(auth.context(), id, revision)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
|
||||
async fn delete_client_key<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Json(payload): Json<ClientKeyRevisionRequest>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: ClientKeyAdminState + Send + Sync,
|
||||
{
|
||||
let (id, revision) = payload.into_parts().map_err(map_wire_error)?;
|
||||
mutation_response(
|
||||
state
|
||||
.client_key_admin_service()
|
||||
.delete(auth.context(), id, revision)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
|
||||
fn mutation_response(
|
||||
result: Result<MutatedClientKeyData, AdminServiceError>,
|
||||
) -> Result<AdminResponse<AdminEnvelope<MutatedClientKeyData>>, AdminError> {
|
||||
let data = result.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)))
|
||||
}
|
||||
|
||||
fn map_wire_error(error: WireValidationError) -> AdminError {
|
||||
match error.field() {
|
||||
"cursor" => AdminError::bad_request("Invalid client key cursor"),
|
||||
"expectedConfigRevision" => {
|
||||
AdminError::bad_request("expectedConfigRevision must be positive")
|
||||
}
|
||||
_ => AdminError::bad_request("Invalid client API key request"),
|
||||
}
|
||||
}
|
||||
|
||||
fn map_service_error(error: AdminServiceError) -> AdminError {
|
||||
match error.kind() {
|
||||
AdminServiceErrorKind::Invalid => AdminError::bad_request(error.to_string()),
|
||||
AdminServiceErrorKind::NotFound => AdminError::not_found(error.to_string()),
|
||||
AdminServiceErrorKind::Conflict => AdminError::conflict(error.to_string()),
|
||||
AdminServiceErrorKind::Unavailable => {
|
||||
AdminError::service_unavailable("Configuration repository unavailable")
|
||||
}
|
||||
AdminServiceErrorKind::Internal => AdminError::internal(error.to_string()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! 管理端 HTTP adapter、wire contract 与固定路由。
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
http::{HeaderValue, header},
|
||||
middleware,
|
||||
response::Response,
|
||||
};
|
||||
|
||||
pub mod accounts;
|
||||
pub mod auth;
|
||||
pub mod catalog;
|
||||
pub mod client_keys;
|
||||
pub mod observability;
|
||||
pub mod openai;
|
||||
pub mod settings;
|
||||
pub mod system;
|
||||
pub mod wire;
|
||||
pub mod xai;
|
||||
|
||||
pub use auth::{
|
||||
AdminAuth, AdminPrincipal, AdminRequestContext, AdminServiceError, AdminServiceErrorKind,
|
||||
AdminSessionResolver, AdminSessionState,
|
||||
};
|
||||
pub use settings::{
|
||||
AdminApiKeyStatus, DeletedAdminApiKey, ProviderModelMappings, RegeneratedAdminApiKey,
|
||||
RuntimeSettingsView, UpdateRuntimeSettingsRequest,
|
||||
};
|
||||
pub use wire::{
|
||||
ADMIN_OK_CODE, ADMIN_OK_MESSAGE, AdminEnvelope, AdminError, AdminErrorBody, AdminErrorCode,
|
||||
AdminPageData, AdminResponse, PageMeta, WireValidationError,
|
||||
};
|
||||
|
||||
use accounts::AccountAdminState;
|
||||
use auth::AdminAuthState;
|
||||
use catalog::CatalogAdminState;
|
||||
use client_keys::ClientKeyAdminState;
|
||||
use observability::ObservabilityAdminState;
|
||||
use openai::CodexAdminState;
|
||||
use settings::AdminSettingsState;
|
||||
use system::SystemAdminState;
|
||||
use xai::XaiAdminState;
|
||||
|
||||
/// 构造完整且固定的 `/api/admin` 路由。
|
||||
pub fn router<S>() -> Router<S>
|
||||
where
|
||||
S: AccountAdminState
|
||||
+ AdminAuthState
|
||||
+ CatalogAdminState
|
||||
+ ClientKeyAdminState
|
||||
+ CodexAdminState
|
||||
+ ObservabilityAdminState
|
||||
+ AdminSettingsState
|
||||
+ SystemAdminState
|
||||
+ XaiAdminState
|
||||
+ Clone
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
{
|
||||
Router::new()
|
||||
.merge(accounts::router::<S>())
|
||||
.merge(auth::router::<S>())
|
||||
.merge(catalog::router::<S>())
|
||||
.merge(client_keys::router::<S>())
|
||||
.merge(openai::router::<S>())
|
||||
.merge(observability::router::<S>())
|
||||
.merge(settings::router::<S>())
|
||||
.merge(system::router::<S>())
|
||||
.merge(xai::router::<S>())
|
||||
.layer(middleware::map_response(no_store))
|
||||
}
|
||||
|
||||
async fn no_store(mut response: Response) -> Response {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||
response
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,558 @@
|
||||
//! Codex OAuth credential 管理端 wire contract。
|
||||
|
||||
use async_trait::async_trait;
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Query, State},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
routing::{get, post},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::admin::{
|
||||
AdminAuth, AdminEnvelope, AdminError, AdminRequestContext, AdminResponse, AdminServiceError,
|
||||
AdminServiceErrorKind, AdminSessionState, WireValidationError,
|
||||
};
|
||||
|
||||
pub const DEFAULT_PAGE_SIZE: u16 = 50;
|
||||
pub const MAX_PAGE_SIZE: u16 = 200;
|
||||
const MAX_ID_BYTES: usize = 256;
|
||||
const MAX_NAME_BYTES: usize = 512;
|
||||
const MAX_CURSOR_BYTES: usize = 1_024;
|
||||
const MAX_IMPORT_DOCUMENT_BYTES: usize = 64 * 1_024 * 1_024;
|
||||
const MAX_ACCESS_TOKEN_BYTES: usize = 16 * 1_024;
|
||||
const MAX_REFRESH_TOKEN_BYTES: usize = 64 * 1_024;
|
||||
const MAX_CALLBACK_URL_BYTES: usize = 16 * 1_024;
|
||||
|
||||
/// Codex credential 列表查询。
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ListCredentialsQuery {
|
||||
pub provider_instance_id: Option<String>,
|
||||
pub availability: Option<String>,
|
||||
pub enabled: Option<bool>,
|
||||
pub cursor: Option<String>,
|
||||
pub limit: Option<u16>,
|
||||
}
|
||||
|
||||
impl ListCredentialsQuery {
|
||||
/// 校验筛选与游标边界。
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
if let Some(provider_instance_id) = self.provider_instance_id.as_deref() {
|
||||
require_id(provider_instance_id, "providerInstanceId")?;
|
||||
}
|
||||
if self.availability.as_deref().is_some_and(|value| {
|
||||
!matches!(
|
||||
value,
|
||||
"unknown" | "ready" | "cooldown" | "exhausted" | "invalid"
|
||||
)
|
||||
}) {
|
||||
return Err(WireValidationError::new("availability"));
|
||||
}
|
||||
if self
|
||||
.cursor
|
||||
.as_deref()
|
||||
.is_some_and(|value| value.is_empty() || value.len() > MAX_CURSOR_BYTES)
|
||||
{
|
||||
return Err(WireValidationError::new("cursor"));
|
||||
}
|
||||
if self
|
||||
.limit
|
||||
.is_some_and(|limit| limit == 0 || limit > MAX_PAGE_SIZE)
|
||||
{
|
||||
return Err(WireValidationError::new("limit"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Codex credential 详情查询。
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CredentialDetailsQuery {
|
||||
pub credential_id: String,
|
||||
}
|
||||
|
||||
impl CredentialDetailsQuery {
|
||||
/// 校验 credential ID。
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_id(&self.credential_id, "credentialId")
|
||||
}
|
||||
}
|
||||
|
||||
/// OpenAI Provider-owned 账号导入文档。
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ImportCredentialsDocumentRequest {
|
||||
pub expected_config_revision: u64,
|
||||
pub provider_instance_id: String,
|
||||
pub document: Value,
|
||||
}
|
||||
|
||||
impl ImportCredentialsDocumentRequest {
|
||||
/// Wire 只约束文档大小;结构识别与 token 验证完全归 Provider。
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_positive(self.expected_config_revision, "expectedConfigRevision")?;
|
||||
require_id(&self.provider_instance_id, "providerInstanceId")?;
|
||||
if !self.document.is_object()
|
||||
|| serde_json::to_vec(&self.document)
|
||||
.map_or(true, |encoded| encoded.len() > MAX_IMPORT_DOCUMENT_BYTES)
|
||||
{
|
||||
return Err(WireValidationError::new("document"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 启动 Codex Authorization Code + PKCE;可创建新账号或绑定既有账号重新授权。
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct StartOAuthAuthorizationRequest {
|
||||
pub expected_config_revision: u64,
|
||||
pub provider_instance_id: String,
|
||||
pub name: String,
|
||||
pub credential_id: Option<String>,
|
||||
pub expected_credential_revision: Option<u64>,
|
||||
}
|
||||
|
||||
impl StartOAuthAuthorizationRequest {
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_positive(self.expected_config_revision, "expectedConfigRevision")?;
|
||||
require_id(&self.provider_instance_id, "providerInstanceId")?;
|
||||
require_text(&self.name, MAX_NAME_BYTES, "name")?;
|
||||
match (
|
||||
self.credential_id.as_deref(),
|
||||
self.expected_credential_revision,
|
||||
) {
|
||||
(None, None) => {}
|
||||
(Some(credential_id), Some(revision)) => {
|
||||
require_id(credential_id, "credentialId")?;
|
||||
require_positive(revision, "expectedCredentialRevision")?;
|
||||
}
|
||||
_ => return Err(WireValidationError::new("reauthorization")),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 完成 Codex Authorization Code flow;flow ID 与 callback 都放在 POST body。
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CompleteOAuthAuthorizationRequest {
|
||||
pub flow_id: String,
|
||||
pub callback_url: String,
|
||||
}
|
||||
|
||||
impl CompleteOAuthAuthorizationRequest {
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
use base64::Engine as _;
|
||||
|
||||
if !base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(&self.flow_id)
|
||||
.is_ok_and(|decoded| decoded.len() == 32)
|
||||
{
|
||||
return Err(WireValidationError::new("flowId"));
|
||||
}
|
||||
if self.callback_url.is_empty()
|
||||
|| self.callback_url.len() > MAX_CALLBACK_URL_BYTES
|
||||
|| self.callback_url.chars().any(char::is_control)
|
||||
{
|
||||
return Err(WireValidationError::new("callbackUrl"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Codex OAuth token 轮换请求。
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct RotateCredentialRequest {
|
||||
pub credential_id: String,
|
||||
pub expected_config_revision: u64,
|
||||
pub expected_credential_revision: u64,
|
||||
pub access_token: String,
|
||||
pub refresh_token: Option<String>,
|
||||
}
|
||||
|
||||
impl RotateCredentialRequest {
|
||||
/// 校验 ID、revision 与 OAuth material 的 wire 形状。
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_id(&self.credential_id, "credentialId")?;
|
||||
require_positive(self.expected_config_revision, "expectedConfigRevision")?;
|
||||
require_positive(
|
||||
self.expected_credential_revision,
|
||||
"expectedCredentialRevision",
|
||||
)?;
|
||||
validate_oauth_material(&self.access_token, self.refresh_token.as_deref())
|
||||
}
|
||||
}
|
||||
|
||||
/// Codex credential 生命周期 mutation 请求。
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CredentialMutationRequest {
|
||||
pub credential_id: String,
|
||||
pub expected_config_revision: u64,
|
||||
}
|
||||
|
||||
impl CredentialMutationRequest {
|
||||
/// 校验 ID 与配置 revision。
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_id(&self.credential_id, "credentialId")?;
|
||||
require_positive(self.expected_config_revision, "expectedConfigRevision")
|
||||
}
|
||||
}
|
||||
|
||||
/// 列表游标的 JSON 形状;HTTP 组合层负责 base64url 编解码。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CredentialCursorWire {
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub credential_id: String,
|
||||
}
|
||||
|
||||
/// Admin API 可安全返回的 Codex credential 视图。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CodexCredentialView {
|
||||
pub id: String,
|
||||
pub provider_instance_id: String,
|
||||
pub name: String,
|
||||
pub email: Option<String>,
|
||||
pub upstream_user_id: String,
|
||||
pub upstream_account_id: Option<String>,
|
||||
pub enabled: bool,
|
||||
pub credential_revision: i64,
|
||||
pub has_refresh_token: bool,
|
||||
pub availability: String,
|
||||
pub availability_reason: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
pub access_token_expires_at: DateTime<Utc>,
|
||||
pub next_refresh_at: Option<DateTime<Utc>>,
|
||||
pub cooldown_until: Option<DateTime<Utc>>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// Codex credential 列表响应数据。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CodexCredentialListData {
|
||||
pub config_revision: u64,
|
||||
pub items: Vec<CodexCredentialView>,
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
/// Codex credential 详情响应数据。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CodexCredentialDetailsData {
|
||||
pub config_revision: u64,
|
||||
pub credential: CodexCredentialView,
|
||||
}
|
||||
|
||||
/// 已提交的结构配置 mutation 响应数据。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CodexCredentialMutationData {
|
||||
pub config_revision: u64,
|
||||
pub credential_id: String,
|
||||
}
|
||||
|
||||
/// Provider 正式文档一次原子导入的结果。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CodexCredentialsDocumentImportData {
|
||||
pub config_revision: u64,
|
||||
pub credential_ids: Vec<String>,
|
||||
}
|
||||
|
||||
/// Authorization Code + PKCE 启动响应。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CodexOAuthAuthorizationStartedData {
|
||||
pub flow_id: String,
|
||||
pub authorization_url: String,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// 已提交的 token 轮换响应数据。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CodexCredentialRotationData {
|
||||
pub credential_id: String,
|
||||
pub credential_revision: i64,
|
||||
}
|
||||
|
||||
fn validate_oauth_material(
|
||||
access_token: &str,
|
||||
refresh_token: Option<&str>,
|
||||
) -> Result<(), WireValidationError> {
|
||||
if access_token.len() > MAX_ACCESS_TOKEN_BYTES
|
||||
|| !valid_visible_ascii(access_token)
|
||||
|| !valid_compact_jwt_shape(access_token)
|
||||
{
|
||||
return Err(WireValidationError::new("accessToken"));
|
||||
}
|
||||
if refresh_token.is_some_and(|token| {
|
||||
token.len() > MAX_REFRESH_TOKEN_BYTES
|
||||
|| !valid_visible_ascii(token)
|
||||
|| token == access_token
|
||||
}) {
|
||||
return Err(WireValidationError::new("refreshToken"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn valid_compact_jwt_shape(value: &str) -> bool {
|
||||
let mut segments = value.split('.');
|
||||
matches!(
|
||||
(segments.next(), segments.next(), segments.next(), segments.next()),
|
||||
(Some(header), Some(payload), Some(signature), None)
|
||||
if !header.is_empty() && !payload.is_empty() && !signature.is_empty()
|
||||
)
|
||||
}
|
||||
|
||||
fn valid_visible_ascii(value: &str) -> bool {
|
||||
!value.is_empty() && value.bytes().all(|byte| (0x21..=0x7e).contains(&byte))
|
||||
}
|
||||
|
||||
fn require_id(value: &str, field: &'static str) -> Result<(), WireValidationError> {
|
||||
require_text(value, MAX_ID_BYTES, field)?;
|
||||
if value.starts_with("__") {
|
||||
return Err(WireValidationError::new(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_text(
|
||||
value: &str,
|
||||
max_bytes: usize,
|
||||
field: &'static str,
|
||||
) -> Result<(), WireValidationError> {
|
||||
if value.trim().is_empty() || value.len() > max_bytes || value.chars().any(char::is_control) {
|
||||
return Err(WireValidationError::new(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_positive(value: u64, field: &'static str) -> Result<(), WireValidationError> {
|
||||
if value == 0 || i64::try_from(value).is_err() {
|
||||
return Err(WireValidationError::new(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Codex OAuth credential 管理应用端口。
|
||||
#[async_trait]
|
||||
pub trait CodexAdminService: Send + Sync {
|
||||
async fn list(
|
||||
&self,
|
||||
query: ListCredentialsQuery,
|
||||
) -> Result<CodexCredentialListData, AdminServiceError>;
|
||||
async fn details(
|
||||
&self,
|
||||
credential_id: String,
|
||||
) -> Result<CodexCredentialDetailsData, AdminServiceError>;
|
||||
async fn import_document(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: ImportCredentialsDocumentRequest,
|
||||
) -> Result<CodexCredentialsDocumentImportData, AdminServiceError>;
|
||||
async fn start_authorization(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: StartOAuthAuthorizationRequest,
|
||||
) -> Result<CodexOAuthAuthorizationStartedData, AdminServiceError>;
|
||||
async fn complete_authorization(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: CompleteOAuthAuthorizationRequest,
|
||||
) -> Result<CodexCredentialMutationData, AdminServiceError>;
|
||||
async fn rotate(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: RotateCredentialRequest,
|
||||
) -> Result<CodexCredentialRotationData, AdminServiceError>;
|
||||
async fn enable(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: CredentialMutationRequest,
|
||||
) -> Result<CodexCredentialMutationData, AdminServiceError>;
|
||||
async fn disable(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: CredentialMutationRequest,
|
||||
) -> Result<CodexCredentialMutationData, AdminServiceError>;
|
||||
async fn delete(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: CredentialMutationRequest,
|
||||
) -> Result<CodexCredentialMutationData, AdminServiceError>;
|
||||
}
|
||||
|
||||
/// Codex HTTP module 所需最小 state。
|
||||
pub trait CodexAdminState: AdminSessionState {
|
||||
fn codex_admin_service(&self) -> &dyn CodexAdminService;
|
||||
}
|
||||
|
||||
/// 构造固定 GET/POST Codex credential 管理路由。
|
||||
pub fn router<S>() -> Router<S>
|
||||
where
|
||||
S: CodexAdminState + Clone + Send + Sync + 'static,
|
||||
{
|
||||
Router::new()
|
||||
.route("/api/admin/openai/credentials", get(list_credentials::<S>))
|
||||
.route("/api/admin/openai/credential", get(credential_details::<S>))
|
||||
.route(
|
||||
"/api/admin/openai/credentials/import-document",
|
||||
post(import_credentials_document::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/openai/oauth/authorization/start",
|
||||
post(start_oauth_authorization::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/openai/oauth/authorization/complete",
|
||||
post(complete_oauth_authorization::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/openai/credentials/rotate",
|
||||
post(rotate_credential::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/openai/credentials/enable",
|
||||
post(enable_credential::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/openai/credentials/disable",
|
||||
post(disable_credential::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/openai/credentials/delete",
|
||||
post(delete_credential::<S>),
|
||||
)
|
||||
}
|
||||
|
||||
async fn list_credentials<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Query(query): Query<ListCredentialsQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: CodexAdminState + Send + Sync,
|
||||
{
|
||||
query.validate().map_err(map_wire_error)?;
|
||||
ok(
|
||||
StatusCode::OK,
|
||||
state.codex_admin_service().list(query).await,
|
||||
)
|
||||
}
|
||||
|
||||
async fn credential_details<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Query(query): Query<CredentialDetailsQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: CodexAdminState + Send + Sync,
|
||||
{
|
||||
query.validate().map_err(map_wire_error)?;
|
||||
ok(
|
||||
StatusCode::OK,
|
||||
state
|
||||
.codex_admin_service()
|
||||
.details(query.credential_id)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
|
||||
macro_rules! codex_post_handler {
|
||||
($name:ident, $request:ty, $method:ident, $status:expr) => {
|
||||
async fn $name<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Json(request): Json<$request>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: CodexAdminState + Send + Sync,
|
||||
{
|
||||
request.validate().map_err(map_wire_error)?;
|
||||
ok(
|
||||
$status,
|
||||
state
|
||||
.codex_admin_service()
|
||||
.$method(auth.context(), request)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
codex_post_handler!(
|
||||
import_credentials_document,
|
||||
ImportCredentialsDocumentRequest,
|
||||
import_document,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
codex_post_handler!(
|
||||
start_oauth_authorization,
|
||||
StartOAuthAuthorizationRequest,
|
||||
start_authorization,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
codex_post_handler!(
|
||||
complete_oauth_authorization,
|
||||
CompleteOAuthAuthorizationRequest,
|
||||
complete_authorization,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
codex_post_handler!(
|
||||
rotate_credential,
|
||||
RotateCredentialRequest,
|
||||
rotate,
|
||||
StatusCode::OK
|
||||
);
|
||||
codex_post_handler!(
|
||||
enable_credential,
|
||||
CredentialMutationRequest,
|
||||
enable,
|
||||
StatusCode::OK
|
||||
);
|
||||
codex_post_handler!(
|
||||
disable_credential,
|
||||
CredentialMutationRequest,
|
||||
disable,
|
||||
StatusCode::OK
|
||||
);
|
||||
codex_post_handler!(
|
||||
delete_credential,
|
||||
CredentialMutationRequest,
|
||||
delete,
|
||||
StatusCode::OK
|
||||
);
|
||||
|
||||
fn ok<T: Serialize>(
|
||||
status: StatusCode,
|
||||
result: Result<T, AdminServiceError>,
|
||||
) -> Result<AdminResponse<AdminEnvelope<T>>, AdminError> {
|
||||
let data = result.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(status, AdminEnvelope::ok(data)))
|
||||
}
|
||||
|
||||
fn map_wire_error(error: WireValidationError) -> AdminError {
|
||||
AdminError::bad_request(format!("Invalid Codex credential field: {}", error.field()))
|
||||
}
|
||||
|
||||
fn map_service_error(error: AdminServiceError) -> AdminError {
|
||||
match error.kind() {
|
||||
AdminServiceErrorKind::Invalid => AdminError::bad_request(error.to_string()),
|
||||
AdminServiceErrorKind::NotFound => AdminError::not_found(error.to_string()),
|
||||
AdminServiceErrorKind::Conflict => AdminError::conflict(error.to_string()),
|
||||
AdminServiceErrorKind::Unavailable => AdminError::service_unavailable(error.to_string()),
|
||||
AdminServiceErrorKind::Internal => AdminError::internal(error.to_string()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
//! Runtime settings、旧设置页聚合投影与明文 Admin API Key wire。
|
||||
|
||||
use std::{collections::BTreeMap, fmt};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::State,
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
routing::{get, post},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{
|
||||
AdminAuth, AdminEnvelope, AdminError, AdminRequestContext, AdminResponse, AdminServiceError,
|
||||
AdminServiceErrorKind, AdminSessionState, WireValidationError,
|
||||
};
|
||||
|
||||
/// 按 Provider 分组的精确模型映射:Provider → 客户端模型 → 上游模型。
|
||||
pub type ProviderModelMappings = BTreeMap<String, BTreeMap<String, String>>;
|
||||
|
||||
/// 运行配置投影与设置页字段的聚合响应。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuntimeSettingsView {
|
||||
pub config_revision: u64,
|
||||
pub provider_model_mappings: ProviderModelMappings,
|
||||
pub refresh_margin_seconds: u64,
|
||||
pub refresh_concurrency: u64,
|
||||
pub max_concurrent_per_account: u64,
|
||||
pub request_interval_ms: u64,
|
||||
pub rotation_strategy: String,
|
||||
pub usage_retention_days: u64,
|
||||
pub ops_event_retention_days: u64,
|
||||
pub audit_retention_days: u64,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// 原子替换全局运行参数的请求。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateRuntimeSettingsRequest {
|
||||
pub expected_config_revision: u64,
|
||||
pub provider_model_mappings: ProviderModelMappings,
|
||||
pub refresh_margin_seconds: u64,
|
||||
pub refresh_concurrency: u64,
|
||||
pub max_concurrent_per_account: u64,
|
||||
pub request_interval_ms: u64,
|
||||
pub rotation_strategy: String,
|
||||
pub usage_retention_days: u64,
|
||||
pub ops_event_retention_days: u64,
|
||||
pub audit_retention_days: u64,
|
||||
}
|
||||
|
||||
impl UpdateRuntimeSettingsRequest {
|
||||
/// 校验公共运行参数。
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
if self.expected_config_revision == 0 {
|
||||
return Err(WireValidationError::new("expectedConfigRevision"));
|
||||
}
|
||||
validate_provider_model_mappings(&self.provider_model_mappings)?;
|
||||
for (value, field) in [
|
||||
(self.refresh_margin_seconds, "refreshMarginSeconds"),
|
||||
(self.refresh_concurrency, "refreshConcurrency"),
|
||||
(self.max_concurrent_per_account, "maxConcurrentPerAccount"),
|
||||
(self.usage_retention_days, "usageRetentionDays"),
|
||||
(self.ops_event_retention_days, "opsEventRetentionDays"),
|
||||
(self.audit_retention_days, "auditRetentionDays"),
|
||||
] {
|
||||
require_positive_i64(value, field)?;
|
||||
}
|
||||
if i64::try_from(self.request_interval_ms).is_err() {
|
||||
return Err(WireValidationError::new("requestIntervalMs"));
|
||||
}
|
||||
if !matches!(
|
||||
self.rotation_strategy.as_str(),
|
||||
"smart" | "quota_reset_priority" | "round_robin" | "sticky"
|
||||
) {
|
||||
return Err(WireValidationError::new("rotationStrategy"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 管理 API Key 状态;状态读取不回显完整值。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AdminApiKeyStatus {
|
||||
pub exists: bool,
|
||||
}
|
||||
|
||||
/// 管理 API Key 重新生成响应。
|
||||
#[derive(Serialize)]
|
||||
pub struct RegeneratedAdminApiKey {
|
||||
pub key: String,
|
||||
}
|
||||
|
||||
impl fmt::Debug for RegeneratedAdminApiKey {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter
|
||||
.debug_struct("RegeneratedAdminApiKey")
|
||||
.field("key", &"[REDACTED]")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// 管理 API Key 删除响应。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
pub struct DeletedAdminApiKey {
|
||||
pub message: &'static str,
|
||||
}
|
||||
|
||||
impl Default for DeletedAdminApiKey {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
message: "Admin API key deleted",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 设置页聚合和明文 Admin API Key 管理应用端口。
|
||||
#[async_trait]
|
||||
pub trait AdminSettingsService: Send + Sync {
|
||||
async fn load(&self) -> Result<RuntimeSettingsView, AdminServiceError>;
|
||||
|
||||
async fn replace(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: UpdateRuntimeSettingsRequest,
|
||||
) -> Result<RuntimeSettingsView, AdminServiceError>;
|
||||
|
||||
async fn admin_api_key_exists(&self) -> Result<bool, AdminServiceError>;
|
||||
|
||||
async fn regenerate_admin_api_key(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
) -> Result<String, AdminServiceError>;
|
||||
|
||||
async fn delete_admin_api_key(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
) -> Result<(), AdminServiceError>;
|
||||
}
|
||||
|
||||
/// 设置 HTTP module 所需最小 state。
|
||||
pub trait AdminSettingsState: AdminSessionState {
|
||||
fn admin_settings_service(&self) -> &dyn AdminSettingsService;
|
||||
}
|
||||
|
||||
/// 构造固定 GET/POST 设置路由。
|
||||
pub fn router<S>() -> Router<S>
|
||||
where
|
||||
S: AdminSettingsState + Clone + Send + Sync + 'static,
|
||||
{
|
||||
Router::new()
|
||||
.route(
|
||||
"/api/admin/settings",
|
||||
get(settings::<S>).post(update_settings::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/settings/admin-api-key",
|
||||
get(admin_api_key_status::<S>).post(delete_admin_api_key::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/settings/admin-api-key/regenerate",
|
||||
post(regenerate_admin_api_key::<S>),
|
||||
)
|
||||
}
|
||||
|
||||
async fn settings<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: AdminSettingsState + Send + Sync,
|
||||
{
|
||||
let data = state
|
||||
.admin_settings_service()
|
||||
.load()
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)))
|
||||
}
|
||||
|
||||
async fn update_settings<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Json(request): Json<UpdateRuntimeSettingsRequest>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: AdminSettingsState + Send + Sync,
|
||||
{
|
||||
request.validate().map_err(map_wire_error)?;
|
||||
let data = state
|
||||
.admin_settings_service()
|
||||
.replace(auth.context(), request)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)))
|
||||
}
|
||||
|
||||
async fn admin_api_key_status<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: AdminSettingsState + Send + Sync,
|
||||
{
|
||||
let exists = state
|
||||
.admin_settings_service()
|
||||
.admin_api_key_exists()
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(AdminApiKeyStatus { exists }),
|
||||
))
|
||||
}
|
||||
|
||||
async fn regenerate_admin_api_key<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: AdminSettingsState + Send + Sync,
|
||||
{
|
||||
let key = state
|
||||
.admin_settings_service()
|
||||
.regenerate_admin_api_key(auth.context())
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(RegeneratedAdminApiKey { key }),
|
||||
))
|
||||
}
|
||||
|
||||
async fn delete_admin_api_key<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: AdminSettingsState + Send + Sync,
|
||||
{
|
||||
state
|
||||
.admin_settings_service()
|
||||
.delete_admin_api_key(auth.context())
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(DeletedAdminApiKey::default()),
|
||||
))
|
||||
}
|
||||
|
||||
fn require_positive_i64(value: u64, field: &'static str) -> Result<(), WireValidationError> {
|
||||
if value == 0 || i64::try_from(value).is_err() {
|
||||
return Err(WireValidationError::new(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_provider_model_mappings(
|
||||
mappings: &ProviderModelMappings,
|
||||
) -> Result<(), WireValidationError> {
|
||||
if mappings.len() > 32 {
|
||||
return Err(WireValidationError::new("providerModelMappings"));
|
||||
}
|
||||
for (provider, entries) in mappings {
|
||||
if !valid_slug(provider, 64) || entries.len() > 512 {
|
||||
return Err(WireValidationError::new("providerModelMappings"));
|
||||
}
|
||||
for (requested, upstream) in entries {
|
||||
if !valid_model_name(requested, 256) || !valid_model_name(upstream, 256) {
|
||||
return Err(WireValidationError::new("providerModelMappings"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn valid_slug(value: &str, max_len: usize) -> bool {
|
||||
!value.is_empty()
|
||||
&& value.len() <= max_len
|
||||
&& !value.starts_with('-')
|
||||
&& !value.ends_with('-')
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
|
||||
}
|
||||
|
||||
fn valid_model_name(value: &str, max_len: usize) -> bool {
|
||||
!value.is_empty()
|
||||
&& value.len() <= max_len
|
||||
&& !value.bytes().any(|byte| byte.is_ascii_control())
|
||||
}
|
||||
|
||||
fn map_wire_error(error: WireValidationError) -> AdminError {
|
||||
AdminError::bad_request(format!("Invalid field: {}", error.field()))
|
||||
}
|
||||
|
||||
fn map_service_error(error: AdminServiceError) -> AdminError {
|
||||
match error.kind() {
|
||||
AdminServiceErrorKind::Invalid => AdminError::bad_request(error.to_string()),
|
||||
AdminServiceErrorKind::NotFound => AdminError::not_found(error.to_string()),
|
||||
AdminServiceErrorKind::Conflict => AdminError::conflict(error.to_string()),
|
||||
AdminServiceErrorKind::Unavailable => {
|
||||
AdminError::service_unavailable("Settings repository unavailable")
|
||||
}
|
||||
AdminServiceErrorKind::Internal => AdminError::internal(error.to_string()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
//! 系统管理接口的查询与请求 wire contract。
|
||||
//!
|
||||
//! 这里不依赖更新服务或进程控制;应用层通过窄端口提供系统操作事实。
|
||||
|
||||
use std::{convert::Infallible, pin::Pin};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Query, State},
|
||||
http::StatusCode,
|
||||
response::{
|
||||
IntoResponse,
|
||||
sse::{Event, KeepAlive, Sse},
|
||||
},
|
||||
routing::{get, post},
|
||||
};
|
||||
use futures::{Stream, StreamExt};
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{AdminAuth, AdminEnvelope, AdminError, AdminResponse, AdminSessionState};
|
||||
|
||||
/// 更新详情查询参数。
|
||||
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateDetailQuery {
|
||||
refresh: Option<bool>,
|
||||
}
|
||||
|
||||
impl UpdateDetailQuery {
|
||||
/// 是否强制从发布源刷新。
|
||||
#[must_use]
|
||||
pub fn refresh(&self) -> bool {
|
||||
self.refresh.unwrap_or(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// 执行更新请求。
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateRequest {
|
||||
target_version: String,
|
||||
}
|
||||
|
||||
impl UpdateRequest {
|
||||
/// 取出确认的目标版本原值,由更新领域负责版本规范化和校验。
|
||||
#[must_use]
|
||||
pub fn into_target_version(self) -> String {
|
||||
self.target_version
|
||||
}
|
||||
}
|
||||
|
||||
/// 一条已经脱敏的更新事件。
|
||||
pub struct SystemUpdateEvent {
|
||||
pub id: String,
|
||||
pub data: Value,
|
||||
}
|
||||
|
||||
/// 每个 SSE 订阅独占的更新事件流。
|
||||
pub type SystemUpdateEventStream = Pin<Box<dyn Stream<Item = SystemUpdateEvent> + Send + 'static>>;
|
||||
|
||||
/// 系统操作失败分类。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SystemAdminErrorKind {
|
||||
Invalid,
|
||||
Conflict,
|
||||
BadGateway,
|
||||
Internal,
|
||||
}
|
||||
|
||||
/// 系统操作安全错误。
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("{message}")]
|
||||
pub struct SystemAdminError {
|
||||
kind: SystemAdminErrorKind,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl SystemAdminError {
|
||||
#[must_use]
|
||||
pub fn new(kind: SystemAdminErrorKind, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn kind(&self) -> SystemAdminErrorKind {
|
||||
self.kind
|
||||
}
|
||||
}
|
||||
|
||||
/// 系统版本、更新与进程控制应用端口。
|
||||
#[async_trait]
|
||||
pub trait SystemAdminService: Send + Sync {
|
||||
async fn version(&self) -> Result<Value, SystemAdminError>;
|
||||
async fn update_detail(&self, refresh: bool) -> Result<Value, SystemAdminError>;
|
||||
fn update_events(&self) -> SystemUpdateEventStream;
|
||||
async fn perform_update(
|
||||
&self,
|
||||
target_version: Option<String>,
|
||||
) -> Result<Value, SystemAdminError>;
|
||||
async fn update_status(&self) -> Result<Value, SystemAdminError>;
|
||||
async fn rollback(&self) -> Result<Value, SystemAdminError>;
|
||||
async fn restart(&self) -> Result<Value, SystemAdminError>;
|
||||
}
|
||||
|
||||
/// 系统管理 HTTP module 所需最小 state。
|
||||
pub trait SystemAdminState: AdminSessionState {
|
||||
fn system_admin_service(&self) -> &dyn SystemAdminService;
|
||||
}
|
||||
|
||||
/// 构造固定 GET/POST 系统管理路由。
|
||||
pub fn router<S>() -> Router<S>
|
||||
where
|
||||
S: SystemAdminState + Clone + Send + Sync + 'static,
|
||||
{
|
||||
Router::new()
|
||||
.route("/api/admin/system/version", get(version::<S>))
|
||||
.route("/api/admin/system/update-detail", get(update_detail::<S>))
|
||||
.route(
|
||||
"/api/admin/system/update-events",
|
||||
get(update_event_stream::<S>),
|
||||
)
|
||||
.route("/api/admin/system/update", post(perform_update::<S>))
|
||||
.route("/api/admin/system/update-status", get(update_status::<S>))
|
||||
.route("/api/admin/system/rollback", post(rollback::<S>))
|
||||
.route("/api/admin/system/restart", post(restart::<S>))
|
||||
}
|
||||
|
||||
async fn version<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SystemAdminState + Send + Sync,
|
||||
{
|
||||
value_response(state.system_admin_service().version().await)
|
||||
}
|
||||
|
||||
async fn update_detail<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Query(query): Query<UpdateDetailQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SystemAdminState + Send + Sync,
|
||||
{
|
||||
value_response(
|
||||
state
|
||||
.system_admin_service()
|
||||
.update_detail(query.refresh())
|
||||
.await,
|
||||
)
|
||||
}
|
||||
|
||||
async fn update_event_stream<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, AdminError>
|
||||
where
|
||||
S: SystemAdminState + Send + Sync,
|
||||
{
|
||||
let stream = state.system_admin_service().update_events().map(|message| {
|
||||
let data = serde_json::to_string(&message.data).unwrap_or_else(|_| "{}".to_owned());
|
||||
Ok(Event::default().event("update").id(message.id).data(data))
|
||||
});
|
||||
Ok(Sse::new(stream).keep_alive(KeepAlive::default()))
|
||||
}
|
||||
|
||||
async fn perform_update<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
payload: Option<Json<UpdateRequest>>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SystemAdminState + Send + Sync,
|
||||
{
|
||||
value_response(
|
||||
state
|
||||
.system_admin_service()
|
||||
.perform_update(payload.map(|Json(value)| value.into_target_version()))
|
||||
.await,
|
||||
)
|
||||
}
|
||||
|
||||
async fn update_status<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SystemAdminState + Send + Sync,
|
||||
{
|
||||
value_response(state.system_admin_service().update_status().await)
|
||||
}
|
||||
|
||||
async fn rollback<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SystemAdminState + Send + Sync,
|
||||
{
|
||||
value_response(state.system_admin_service().rollback().await)
|
||||
}
|
||||
|
||||
async fn restart<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: SystemAdminState + Send + Sync,
|
||||
{
|
||||
value_response(state.system_admin_service().restart().await)
|
||||
}
|
||||
|
||||
fn value_response(
|
||||
result: Result<Value, SystemAdminError>,
|
||||
) -> Result<AdminResponse<AdminEnvelope<Value>>, AdminError> {
|
||||
let data = result.map_err(map_system_error)?;
|
||||
Ok(AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data)))
|
||||
}
|
||||
|
||||
fn map_system_error(error: SystemAdminError) -> AdminError {
|
||||
match error.kind() {
|
||||
SystemAdminErrorKind::Invalid => AdminError::bad_request(error.to_string()),
|
||||
SystemAdminErrorKind::Conflict => AdminError::conflict(error.to_string()),
|
||||
SystemAdminErrorKind::BadGateway => AdminError::bad_gateway(error.to_string()),
|
||||
SystemAdminErrorKind::Internal => AdminError::internal(error.to_string()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
//! 管理端公共 wire、响应信封与脱敏错误。
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// 管理端 wire 字段校验错误;只携带稳定字段名,不回显输入值。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct WireValidationError {
|
||||
field: &'static str,
|
||||
}
|
||||
|
||||
impl WireValidationError {
|
||||
/// 构造字段校验错误。
|
||||
#[must_use]
|
||||
pub const fn new(field: &'static str) -> Self {
|
||||
Self { field }
|
||||
}
|
||||
|
||||
/// 返回未通过校验的字段名。
|
||||
#[must_use]
|
||||
pub const fn field(self) -> &'static str {
|
||||
self.field
|
||||
}
|
||||
}
|
||||
|
||||
/// 成功响应的稳定业务码。
|
||||
pub const ADMIN_OK_CODE: u32 = 200;
|
||||
|
||||
/// 成功响应的稳定消息。
|
||||
pub const ADMIN_OK_MESSAGE: &str = "OK";
|
||||
|
||||
/// 页码分页元数据。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PageMeta {
|
||||
page: u32,
|
||||
page_size: u32,
|
||||
total: u64,
|
||||
total_pages: u32,
|
||||
}
|
||||
|
||||
impl PageMeta {
|
||||
/// 由分页 owner 已经校验并计算的事实构造 wire metadata。
|
||||
#[must_use]
|
||||
pub const fn new(page: u32, page_size: u32, total: u64, total_pages: u32) -> Self {
|
||||
Self {
|
||||
page,
|
||||
page_size,
|
||||
total,
|
||||
total_pages,
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前页,从 1 开始。
|
||||
#[must_use]
|
||||
pub const fn page(self) -> u32 {
|
||||
self.page
|
||||
}
|
||||
|
||||
/// 每页数量。
|
||||
#[must_use]
|
||||
pub const fn page_size(self) -> u32 {
|
||||
self.page_size
|
||||
}
|
||||
|
||||
/// 全部记录数量。
|
||||
#[must_use]
|
||||
pub const fn total(self) -> u64 {
|
||||
self.total
|
||||
}
|
||||
|
||||
/// 总页数。
|
||||
#[must_use]
|
||||
pub const fn total_pages(self) -> u32 {
|
||||
self.total_pages
|
||||
}
|
||||
}
|
||||
|
||||
/// 管理端稳定业务错误码。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct AdminErrorCode(u32);
|
||||
|
||||
impl AdminErrorCode {
|
||||
/// JSON 解析失败。
|
||||
pub const MALFORMED_JSON: Self = Self(40000);
|
||||
/// 请求参数或状态不合法。
|
||||
pub const BAD_REQUEST: Self = Self(40001);
|
||||
/// 时间范围不合法。
|
||||
pub const INVALID_TIME_RANGE: Self = Self(40002);
|
||||
/// 模型来源不合法。
|
||||
pub const INVALID_MODEL_SOURCE: Self = Self(40003);
|
||||
/// 缺少管理员会话。
|
||||
pub const SESSION_REQUIRED: Self = Self(40101);
|
||||
/// 管理员登录凭据错误。
|
||||
pub const INVALID_CREDENTIALS: Self = Self(40102);
|
||||
/// 管理 API Key 错误。
|
||||
pub const INVALID_API_KEY: Self = Self(40103);
|
||||
/// 资源不存在。
|
||||
pub const NOT_FOUND: Self = Self(40401);
|
||||
/// 配置 revision 或资源状态冲突。
|
||||
pub const CONFLICT: Self = Self(40901);
|
||||
/// 管理员登录尝试过多。
|
||||
pub const TOO_MANY_LOGIN_ATTEMPTS: Self = Self(42901);
|
||||
/// 设置持久化失败。
|
||||
pub const SETTINGS_PERSIST: Self = Self(50000);
|
||||
/// 未分类内部错误。
|
||||
pub const INTERNAL: Self = Self(50001);
|
||||
/// 用量记录的账号投影失败。
|
||||
pub const USAGE_RECORD_ACCOUNTS: Self = Self(50002);
|
||||
/// 上游网关失败。
|
||||
pub const BAD_GATEWAY: Self = Self(50201);
|
||||
/// 依赖的服务暂不可用。
|
||||
pub const SERVICE_UNAVAILABLE: Self = Self(50301);
|
||||
|
||||
/// 返回用于 JSON wire contract 的数值。
|
||||
#[must_use]
|
||||
pub const fn value(self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// 管理端错误响应正文。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AdminErrorBody {
|
||||
code: AdminErrorCode,
|
||||
message: String,
|
||||
data: (),
|
||||
}
|
||||
|
||||
impl AdminErrorBody {
|
||||
/// 构造不携带业务数据的管理端错误正文。
|
||||
#[must_use]
|
||||
pub fn new(code: AdminErrorCode, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
code,
|
||||
message: message.into(),
|
||||
data: (),
|
||||
}
|
||||
}
|
||||
|
||||
/// 稳定业务错误码。
|
||||
#[must_use]
|
||||
pub const fn code(&self) -> AdminErrorCode {
|
||||
self.code
|
||||
}
|
||||
|
||||
/// 安全的客户端错误消息。
|
||||
#[must_use]
|
||||
pub fn message(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
}
|
||||
|
||||
/// 管理端 HTTP 错误。
|
||||
pub struct AdminError {
|
||||
status: StatusCode,
|
||||
body: AdminErrorBody,
|
||||
}
|
||||
|
||||
impl AdminError {
|
||||
fn new(status: StatusCode, code: AdminErrorCode, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
status,
|
||||
body: AdminErrorBody::new(code, message),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bad_request(message: impl Into<String>) -> Self {
|
||||
Self::new(
|
||||
StatusCode::BAD_REQUEST,
|
||||
AdminErrorCode::BAD_REQUEST,
|
||||
message,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn admin_session_required() -> Self {
|
||||
Self::new(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
AdminErrorCode::SESSION_REQUIRED,
|
||||
"Admin session required",
|
||||
)
|
||||
}
|
||||
|
||||
pub fn invalid_admin_credentials() -> Self {
|
||||
Self::new(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
AdminErrorCode::INVALID_CREDENTIALS,
|
||||
"Invalid admin credentials",
|
||||
)
|
||||
}
|
||||
|
||||
pub fn invalid_admin_api_key() -> Self {
|
||||
Self::new(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
AdminErrorCode::INVALID_API_KEY,
|
||||
"Invalid admin API key",
|
||||
)
|
||||
}
|
||||
|
||||
pub fn too_many_login_attempts() -> Self {
|
||||
Self::new(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
AdminErrorCode::TOO_MANY_LOGIN_ATTEMPTS,
|
||||
"Too many admin login attempts",
|
||||
)
|
||||
}
|
||||
|
||||
pub fn conflict(message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::CONFLICT, AdminErrorCode::CONFLICT, message)
|
||||
}
|
||||
|
||||
pub fn not_found(message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::NOT_FOUND, AdminErrorCode::NOT_FOUND, message)
|
||||
}
|
||||
|
||||
pub fn internal(message: impl Into<String>) -> Self {
|
||||
Self::new(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
AdminErrorCode::INTERNAL,
|
||||
message,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn bad_gateway(message: impl Into<String>) -> Self {
|
||||
Self::new(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
AdminErrorCode::BAD_GATEWAY,
|
||||
message,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn service_unavailable(message: impl Into<String>) -> Self {
|
||||
Self::new(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
AdminErrorCode::SERVICE_UNAVAILABLE,
|
||||
message,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for AdminError {
|
||||
fn into_response(self) -> Response {
|
||||
(self.status, Json(self.body)).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for AdminError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.body.message())
|
||||
}
|
||||
}
|
||||
|
||||
/// 带独立 HTTP 状态的管理端响应。
|
||||
pub struct AdminResponse<T: Serialize> {
|
||||
status: StatusCode,
|
||||
body: T,
|
||||
}
|
||||
|
||||
impl<T: Serialize> AdminResponse<T> {
|
||||
#[must_use]
|
||||
pub fn new(status: StatusCode, body: T) -> Self {
|
||||
Self { status, body }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Serialize> IntoResponse for AdminResponse<T> {
|
||||
fn into_response(self) -> Response {
|
||||
(self.status, Json(self.body)).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
/// 管理端响应信封。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AdminEnvelope<T> {
|
||||
code: u32,
|
||||
message: String,
|
||||
data: T,
|
||||
}
|
||||
|
||||
impl<T> AdminEnvelope<T> {
|
||||
/// 构造稳定的成功响应。
|
||||
#[must_use]
|
||||
pub fn ok(data: T) -> Self {
|
||||
Self {
|
||||
code: ADMIN_OK_CODE,
|
||||
message: ADMIN_OK_MESSAGE.to_owned(),
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
/// 稳定业务码。
|
||||
#[must_use]
|
||||
pub const fn code(&self) -> u32 {
|
||||
self.code
|
||||
}
|
||||
|
||||
/// 稳定业务消息。
|
||||
#[must_use]
|
||||
pub fn message(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
|
||||
/// 响应数据。
|
||||
#[must_use]
|
||||
pub const fn data(&self) -> &T {
|
||||
&self.data
|
||||
}
|
||||
|
||||
/// 取出响应数据。
|
||||
#[must_use]
|
||||
pub fn into_data(self) -> T {
|
||||
self.data
|
||||
}
|
||||
}
|
||||
|
||||
/// 页码分页响应数据。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AdminPageData<T> {
|
||||
items: Vec<T>,
|
||||
page: PageMeta,
|
||||
}
|
||||
|
||||
impl<T> AdminPageData<T> {
|
||||
/// 组合查询 owner 返回的当前页数据与分页事实。
|
||||
#[must_use]
|
||||
pub const fn new(items: Vec<T>, page: PageMeta) -> Self {
|
||||
Self { items, page }
|
||||
}
|
||||
|
||||
/// 当前页记录。
|
||||
#[must_use]
|
||||
pub fn items(&self) -> &[T] {
|
||||
&self.items
|
||||
}
|
||||
|
||||
/// 分页元数据。
|
||||
#[must_use]
|
||||
pub const fn page(&self) -> PageMeta {
|
||||
self.page
|
||||
}
|
||||
|
||||
/// 拆分分页数据。
|
||||
#[must_use]
|
||||
pub fn into_parts(self) -> (Vec<T>, PageMeta) {
|
||||
(self.items, self.page)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
//! xAI 管理端 wire contract。
|
||||
|
||||
use async_trait::async_trait;
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Query, State},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
routing::{get, post},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::admin::{
|
||||
AdminAuth, AdminEnvelope, AdminError, AdminRequestContext, AdminResponse, AdminServiceError,
|
||||
AdminServiceErrorKind, AdminSessionState, WireValidationError,
|
||||
};
|
||||
|
||||
const MAX_IMPORT_DOCUMENT_BYTES: usize = 64 * 1024 * 1024;
|
||||
|
||||
/// xAI Provider-owned 正式导入文档;API 不解释文档内部字段。
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct XaiCredentialImportDocumentRequest {
|
||||
pub expected_config_revision: u64,
|
||||
pub provider_instance_id: String,
|
||||
pub document: Value,
|
||||
}
|
||||
|
||||
impl XaiCredentialImportDocumentRequest {
|
||||
/// 只校验公共 revision、instance 和请求体边界;Provider 负责全部格式语义。
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_positive(self.expected_config_revision, "expectedConfigRevision")?;
|
||||
require_id(&self.provider_instance_id, "providerInstanceId")?;
|
||||
if !self.document.is_object()
|
||||
|| serde_json::to_vec(&self.document)
|
||||
.map_or(true, |encoded| encoded.len() > MAX_IMPORT_DOCUMENT_BYTES)
|
||||
{
|
||||
return Err(WireValidationError::new("document"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 批量导入成功响应;不包含任何 token、subject、邮箱或 client ID。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct XaiCredentialImportData {
|
||||
pub config_revision: u64,
|
||||
pub imported_count: usize,
|
||||
pub credential_ids: Vec<String>,
|
||||
}
|
||||
|
||||
impl XaiCredentialImportData {
|
||||
#[must_use]
|
||||
pub fn new(config_revision: u64, credential_ids: Vec<String>) -> Self {
|
||||
Self {
|
||||
config_revision,
|
||||
imported_count: credential_ids.len(),
|
||||
credential_ids,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_ID_BYTES: usize = 256;
|
||||
const MAX_NAME_BYTES: usize = 512;
|
||||
const MAX_CALLBACK_FIELD_BYTES: usize = 64 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ListCredentialsQuery {
|
||||
pub provider_instance_id: Option<String>,
|
||||
}
|
||||
|
||||
impl ListCredentialsQuery {
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
if let Some(id) = self.provider_instance_id.as_deref() {
|
||||
require_id(id, "providerInstanceId")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct NewCredentialRequest {
|
||||
pub expected_config_revision: u64,
|
||||
pub provider_instance_id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl NewCredentialRequest {
|
||||
fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_positive(self.expected_config_revision, "expectedConfigRevision")?;
|
||||
require_id(&self.provider_instance_id, "providerInstanceId")?;
|
||||
require_text(&self.name, MAX_NAME_BYTES, "name")?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct StartAuthorizationRequest {
|
||||
#[serde(flatten)]
|
||||
pub credential: NewCredentialRequest,
|
||||
}
|
||||
|
||||
impl StartAuthorizationRequest {
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
self.credential.validate()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CompleteAuthorizationRequest {
|
||||
pub flow_id: String,
|
||||
pub callback_url: String,
|
||||
}
|
||||
|
||||
impl CompleteAuthorizationRequest {
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_id(&self.flow_id, "flowId")?;
|
||||
require_text(&self.callback_url, MAX_CALLBACK_FIELD_BYTES, "callbackUrl")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CredentialMutationRequest {
|
||||
pub credential_id: String,
|
||||
pub expected_config_revision: u64,
|
||||
}
|
||||
|
||||
impl CredentialMutationRequest {
|
||||
pub fn validate(&self) -> Result<(), WireValidationError> {
|
||||
require_id(&self.credential_id, "credentialId")?;
|
||||
require_positive(self.expected_config_revision, "expectedConfigRevision")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AuthorizationStartData {
|
||||
pub flow_id: String,
|
||||
pub authorization_url: String,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// Authorization Code flow 启动的应用端结果。
|
||||
///
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AuthorizationStartResult {
|
||||
pub flow_id: String,
|
||||
pub authorization_url: String,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// xAI OAuth credential 的安全管理视图。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct XaiCredentialViewData {
|
||||
pub id: String,
|
||||
pub provider_instance_id: String,
|
||||
pub name: String,
|
||||
pub email: Option<String>,
|
||||
pub upstream_user_id: String,
|
||||
pub upstream_account_id: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
pub enabled: bool,
|
||||
pub credential_revision: i64,
|
||||
pub has_refresh_token: bool,
|
||||
pub availability: String,
|
||||
pub availability_reason: Option<String>,
|
||||
pub access_token_expires_at: DateTime<Utc>,
|
||||
pub next_refresh_at: Option<DateTime<Utc>>,
|
||||
pub cooldown_until: Option<DateTime<Utc>>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// xAI OAuth credential 列表响应。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct XaiCredentialListData {
|
||||
pub config_revision: u64,
|
||||
pub items: Vec<XaiCredentialViewData>,
|
||||
}
|
||||
|
||||
/// Credential 生命周期 mutation 响应。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct XaiCredentialMutationData {
|
||||
pub config_revision: u64,
|
||||
pub credential_id: String,
|
||||
}
|
||||
|
||||
/// xAI OAuth credential 管理应用端口。
|
||||
#[async_trait]
|
||||
pub trait XaiAdminService: Send + Sync {
|
||||
async fn list(
|
||||
&self,
|
||||
query: ListCredentialsQuery,
|
||||
) -> Result<XaiCredentialListData, AdminServiceError>;
|
||||
async fn import_document(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: XaiCredentialImportDocumentRequest,
|
||||
) -> Result<XaiCredentialImportData, AdminServiceError>;
|
||||
async fn start_authorization(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: StartAuthorizationRequest,
|
||||
) -> Result<AuthorizationStartResult, AdminServiceError>;
|
||||
async fn complete_authorization(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: CompleteAuthorizationRequest,
|
||||
) -> Result<XaiCredentialMutationData, AdminServiceError>;
|
||||
async fn disable(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: CredentialMutationRequest,
|
||||
) -> Result<XaiCredentialMutationData, AdminServiceError>;
|
||||
async fn enable(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: CredentialMutationRequest,
|
||||
) -> Result<XaiCredentialMutationData, AdminServiceError>;
|
||||
async fn delete(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: CredentialMutationRequest,
|
||||
) -> Result<XaiCredentialMutationData, AdminServiceError>;
|
||||
}
|
||||
|
||||
/// xAI HTTP module 所需最小 state。
|
||||
pub trait XaiAdminState: AdminSessionState {
|
||||
fn xai_admin_service(&self) -> &dyn XaiAdminService;
|
||||
}
|
||||
|
||||
/// 构造固定 GET/POST xAI OAuth 管理路由。
|
||||
pub fn router<S>() -> Router<S>
|
||||
where
|
||||
S: XaiAdminState + Clone + Send + Sync + 'static,
|
||||
{
|
||||
Router::new()
|
||||
.route("/api/admin/xai/credentials", get(list_credentials::<S>))
|
||||
.route(
|
||||
"/api/admin/xai/credentials/import-document",
|
||||
post(import_credentials_document::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/xai/oauth/authorization/start",
|
||||
post(start_authorization_code_flow::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/xai/oauth/authorization/complete",
|
||||
post(complete_authorization_code_flow::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/xai/credentials/disable",
|
||||
post(disable_credential::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/xai/credentials/enable",
|
||||
post(enable_credential::<S>),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/xai/credentials/delete",
|
||||
post(delete_credential::<S>),
|
||||
)
|
||||
}
|
||||
|
||||
async fn list_credentials<S>(
|
||||
_auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Query(query): Query<ListCredentialsQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: XaiAdminState + Send + Sync,
|
||||
{
|
||||
query.validate().map_err(map_wire_error)?;
|
||||
ok(StatusCode::OK, state.xai_admin_service().list(query).await)
|
||||
}
|
||||
|
||||
macro_rules! xai_post_handler {
|
||||
($name:ident, $request:ty, $method:ident, $status:expr) => {
|
||||
async fn $name<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Json(request): Json<$request>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: XaiAdminState + Send + Sync,
|
||||
{
|
||||
request.validate().map_err(map_wire_error)?;
|
||||
ok(
|
||||
$status,
|
||||
state
|
||||
.xai_admin_service()
|
||||
.$method(auth.context(), request)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
xai_post_handler!(
|
||||
import_credentials_document,
|
||||
XaiCredentialImportDocumentRequest,
|
||||
import_document,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
async fn start_authorization_code_flow<S>(
|
||||
auth: AdminAuth,
|
||||
State(state): State<S>,
|
||||
Json(request): Json<StartAuthorizationRequest>,
|
||||
) -> Result<impl IntoResponse, AdminError>
|
||||
where
|
||||
S: XaiAdminState + Send + Sync,
|
||||
{
|
||||
request.validate().map_err(map_wire_error)?;
|
||||
let started = state
|
||||
.xai_admin_service()
|
||||
.start_authorization(auth.context(), request)
|
||||
.await
|
||||
.map_err(map_service_error)?;
|
||||
require_id(&started.flow_id, "flowId").map_err(map_wire_error)?;
|
||||
let data = AuthorizationStartData {
|
||||
authorization_url: started.authorization_url,
|
||||
flow_id: started.flow_id,
|
||||
expires_at: started.expires_at,
|
||||
};
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::CREATED,
|
||||
AdminEnvelope::ok(data),
|
||||
))
|
||||
}
|
||||
xai_post_handler!(
|
||||
complete_authorization_code_flow,
|
||||
CompleteAuthorizationRequest,
|
||||
complete_authorization,
|
||||
StatusCode::CREATED
|
||||
);
|
||||
xai_post_handler!(
|
||||
disable_credential,
|
||||
CredentialMutationRequest,
|
||||
disable,
|
||||
StatusCode::OK
|
||||
);
|
||||
xai_post_handler!(
|
||||
enable_credential,
|
||||
CredentialMutationRequest,
|
||||
enable,
|
||||
StatusCode::OK
|
||||
);
|
||||
xai_post_handler!(
|
||||
delete_credential,
|
||||
CredentialMutationRequest,
|
||||
delete,
|
||||
StatusCode::OK
|
||||
);
|
||||
|
||||
fn ok<T: Serialize>(
|
||||
status: StatusCode,
|
||||
result: Result<T, AdminServiceError>,
|
||||
) -> Result<AdminResponse<AdminEnvelope<T>>, AdminError> {
|
||||
let data = result.map_err(map_service_error)?;
|
||||
Ok(AdminResponse::new(status, AdminEnvelope::ok(data)))
|
||||
}
|
||||
|
||||
fn map_wire_error(error: WireValidationError) -> AdminError {
|
||||
AdminError::bad_request(format!("Invalid xAI OAuth field: {}", error.field()))
|
||||
}
|
||||
|
||||
fn map_service_error(error: AdminServiceError) -> AdminError {
|
||||
match error.kind() {
|
||||
AdminServiceErrorKind::Invalid => AdminError::bad_request(error.to_string()),
|
||||
AdminServiceErrorKind::NotFound => AdminError::not_found(error.to_string()),
|
||||
AdminServiceErrorKind::Conflict => AdminError::conflict(error.to_string()),
|
||||
AdminServiceErrorKind::Unavailable => AdminError::bad_gateway(error.to_string()),
|
||||
AdminServiceErrorKind::Internal => AdminError::internal(error.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn require_id(value: &str, field: &'static str) -> Result<(), WireValidationError> {
|
||||
require_text(value, MAX_ID_BYTES, field)?;
|
||||
if value.starts_with("__")
|
||||
|| !value
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':'))
|
||||
{
|
||||
return Err(WireValidationError::new(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_text(
|
||||
value: &str,
|
||||
max_bytes: usize,
|
||||
field: &'static str,
|
||||
) -> Result<(), WireValidationError> {
|
||||
if value.trim().is_empty() || value.len() > max_bytes || value.chars().any(char::is_control) {
|
||||
return Err(WireValidationError::new(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_positive(value: u64, field: &'static str) -> Result<(), WireValidationError> {
|
||||
if value == 0 || i64::try_from(value).is_err() {
|
||||
return Err(WireValidationError::new(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! 客户端协议 adapter。
|
||||
//!
|
||||
//! 本 crate 只负责把外部 wire contract 转换为 [`gateway_core`] 的稳定
|
||||
//! operation/event contract。它不执行路由、Provider 调用、重试或持久化。
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod admin;
|
||||
pub mod openai;
|
||||
@@ -0,0 +1,100 @@
|
||||
//! OpenAI 客户端协议的 Bearer API key 认证。
|
||||
|
||||
use axum::{
|
||||
http::{HeaderMap, header::AUTHORIZATION},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
|
||||
use super::{
|
||||
error::{missing_client_api_key_response, runtime_unavailable_response},
|
||||
service::OpenAiClientService,
|
||||
};
|
||||
|
||||
/// Client API key 鉴权失败原因。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ClientApiKeyAuthError {
|
||||
/// 缺失 Authorization 头。
|
||||
MissingAuthorization,
|
||||
/// Authorization 头不是合法的 Bearer token。
|
||||
MalformedAuthorization,
|
||||
/// Bearer token 不是 client API key 格式。
|
||||
InvalidKeyFormat,
|
||||
/// Key 不存在、已禁用或 wire 格式无效。
|
||||
InvalidKey,
|
||||
/// RuntimeSnapshot 一致性保护暂停接收新请求。
|
||||
RuntimeUnavailable,
|
||||
}
|
||||
|
||||
impl ClientApiKeyAuthError {
|
||||
/// 返回可用于日志和指标的稳定失败原因。
|
||||
#[must_use]
|
||||
pub const fn reason(self) -> &'static str {
|
||||
match self {
|
||||
Self::MissingAuthorization => "missing_authorization",
|
||||
Self::MalformedAuthorization => "malformed_authorization",
|
||||
Self::InvalidKeyFormat => "invalid_key_format",
|
||||
Self::InvalidKey => "invalid_key",
|
||||
Self::RuntimeUnavailable => "runtime_unavailable",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 从请求头提取 Bearer Client API key。
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Header 缺失、Bearer 语法错误或不是网关 Client Key 前缀时返回稳定错误。
|
||||
pub fn bearer_client_api_key(headers: &HeaderMap) -> Result<&str, ClientApiKeyAuthError> {
|
||||
let raw = headers
|
||||
.get(AUTHORIZATION)
|
||||
.ok_or(ClientApiKeyAuthError::MissingAuthorization)?
|
||||
.to_str()
|
||||
.map_err(|_| ClientApiKeyAuthError::MalformedAuthorization)?;
|
||||
let token = raw
|
||||
.strip_prefix("Bearer ")
|
||||
.ok_or(ClientApiKeyAuthError::MalformedAuthorization)?
|
||||
.trim();
|
||||
if token.is_empty() {
|
||||
return Err(ClientApiKeyAuthError::MalformedAuthorization);
|
||||
}
|
||||
if !token.starts_with("sk_") {
|
||||
return Err(ClientApiKeyAuthError::InvalidKeyFormat);
|
||||
}
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
pub(crate) fn authenticate_client<S>(
|
||||
service: &S,
|
||||
headers: &HeaderMap,
|
||||
) -> Result<S::Client, ClientApiKeyAuthError>
|
||||
where
|
||||
S: OpenAiClientService,
|
||||
{
|
||||
bearer_client_api_key(headers).and_then(|key| service.authenticate(key))
|
||||
}
|
||||
|
||||
pub(crate) fn authentication_error_response(error: ClientApiKeyAuthError) -> Response {
|
||||
log_client_api_key_auth_failure(error);
|
||||
if error == ClientApiKeyAuthError::RuntimeUnavailable {
|
||||
runtime_unavailable_response().into_response()
|
||||
} else {
|
||||
missing_client_api_key_response().into_response()
|
||||
}
|
||||
}
|
||||
|
||||
fn log_client_api_key_auth_failure(error: ClientApiKeyAuthError) {
|
||||
match error {
|
||||
ClientApiKeyAuthError::RuntimeUnavailable => {
|
||||
tracing::warn!(
|
||||
auth_failure = error.reason(),
|
||||
"Client API key authorization failed"
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
tracing::info!(
|
||||
auth_failure = error.reason(),
|
||||
"Client API key authorization failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
//! OpenAI 客户端协议的稳定错误响应。
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use gateway_core::{
|
||||
engine::{EngineError, UpstreamSendState},
|
||||
error::{GatewayError, GatewayErrorKind, ProviderErrorKind},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::responses::ProtocolErrorBody;
|
||||
|
||||
/// OpenAI 风格错误响应。
|
||||
pub fn openai_error_response(
|
||||
status: StatusCode,
|
||||
message: &str,
|
||||
error_type: &str,
|
||||
code: &str,
|
||||
) -> (StatusCode, Json<Value>) {
|
||||
(
|
||||
status,
|
||||
Json(json!({
|
||||
"error": {
|
||||
"message": message,
|
||||
"type": error_type,
|
||||
"code": code
|
||||
}
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
/// 严格协议 decoder/encoder 返回的安全错误 body。
|
||||
pub fn protocol_error_response(status: StatusCode, body: ProtocolErrorBody) -> Response {
|
||||
(status, Json(body.into_value())).into_response()
|
||||
}
|
||||
|
||||
/// 下游 Client API Key 无效。
|
||||
pub fn missing_client_api_key_response() -> (StatusCode, Json<Value>) {
|
||||
openai_error_response(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"Missing or invalid API key",
|
||||
"invalid_request_error",
|
||||
"invalid_api_key",
|
||||
)
|
||||
}
|
||||
|
||||
/// RuntimeSnapshot 当前不允许接收新的配置依赖请求。
|
||||
pub fn runtime_unavailable_response() -> (StatusCode, Json<Value>) {
|
||||
openai_error_response(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"Gateway runtime configuration is temporarily unavailable",
|
||||
"server_error",
|
||||
"runtime_configuration_unavailable",
|
||||
)
|
||||
}
|
||||
|
||||
/// 对外模型不存在。
|
||||
pub fn model_not_found_response() -> (StatusCode, Json<Value>) {
|
||||
openai_error_response(
|
||||
StatusCode::NOT_FOUND,
|
||||
"The requested model does not exist or is not available",
|
||||
"invalid_request_error",
|
||||
"model_not_found",
|
||||
)
|
||||
}
|
||||
|
||||
/// 将 core Engine 错误收敛为稳定 Gateway 分类。
|
||||
#[must_use]
|
||||
pub fn gateway_error_from_engine(error: &EngineError) -> GatewayError {
|
||||
match error {
|
||||
EngineError::Provider(error)
|
||||
if error.kind() == ProviderErrorKind::Unavailable
|
||||
&& error.send_state() == UpstreamSendState::NotSent =>
|
||||
{
|
||||
GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"no upstream Provider instance or account is currently available",
|
||||
)
|
||||
}
|
||||
EngineError::Provider(error) => GatewayError::from_provider(error),
|
||||
EngineError::Cancelled => {
|
||||
GatewayError::new(GatewayErrorKind::Cancelled, "request was cancelled")
|
||||
}
|
||||
EngineError::Deadline => {
|
||||
GatewayError::new(GatewayErrorKind::Timeout, "gateway request timed out")
|
||||
}
|
||||
EngineError::ProviderNotRegistered { .. } | EngineError::EmptyRoutingPlan => {
|
||||
GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"no upstream Provider instance or account is currently available",
|
||||
)
|
||||
}
|
||||
EngineError::Store(_)
|
||||
| EngineError::ProviderMetadataMismatch
|
||||
| EngineError::ContinuationPinMismatch
|
||||
| EngineError::RequiredAccountMismatch
|
||||
| EngineError::DownstreamCommitRequired
|
||||
| EngineError::InvalidDeliveryState => {
|
||||
GatewayError::new(GatewayErrorKind::Internal, "gateway execution failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gateway 错误的 OpenAI HTTP 表达。
|
||||
pub fn gateway_error_response(error: &GatewayError) -> Response {
|
||||
let (status, error_type, code) = gateway_error_contract(error.kind());
|
||||
openai_error_response(status, error.safe_message(), error_type, code).into_response()
|
||||
}
|
||||
|
||||
/// Gateway 错误稳定映射,供 HTTP、SSE 和 WebSocket 共用。
|
||||
#[must_use]
|
||||
pub const fn gateway_error_contract(
|
||||
kind: GatewayErrorKind,
|
||||
) -> (StatusCode, &'static str, &'static str) {
|
||||
match kind {
|
||||
GatewayErrorKind::InvalidRequest => (
|
||||
StatusCode::BAD_REQUEST,
|
||||
"invalid_request_error",
|
||||
"invalid_request",
|
||||
),
|
||||
GatewayErrorKind::Unsupported => (
|
||||
StatusCode::BAD_REQUEST,
|
||||
"invalid_request_error",
|
||||
"unsupported_capability",
|
||||
),
|
||||
GatewayErrorKind::Unauthorized => (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"invalid_request_error",
|
||||
"invalid_api_key",
|
||||
),
|
||||
GatewayErrorKind::PolicyDenied => (
|
||||
StatusCode::FORBIDDEN,
|
||||
"invalid_request_error",
|
||||
"policy_denied",
|
||||
),
|
||||
GatewayErrorKind::ModelNotFound => (
|
||||
StatusCode::NOT_FOUND,
|
||||
"invalid_request_error",
|
||||
"model_not_found",
|
||||
),
|
||||
GatewayErrorKind::NoAvailableProvider => (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"server_error",
|
||||
"no_available_provider",
|
||||
),
|
||||
GatewayErrorKind::RateLimited => (
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"rate_limit_error",
|
||||
"rate_limit_exceeded",
|
||||
),
|
||||
GatewayErrorKind::UpstreamUnavailable => (
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"server_error",
|
||||
"upstream_unavailable",
|
||||
),
|
||||
GatewayErrorKind::Timeout => (
|
||||
StatusCode::GATEWAY_TIMEOUT,
|
||||
"server_error",
|
||||
"request_timeout",
|
||||
),
|
||||
GatewayErrorKind::Cancelled => (
|
||||
StatusCode::REQUEST_TIMEOUT,
|
||||
"server_error",
|
||||
"request_cancelled",
|
||||
),
|
||||
GatewayErrorKind::Internal => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"server_error",
|
||||
"internal_error",
|
||||
),
|
||||
_ => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"server_error",
|
||||
"internal_error",
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//! OpenAI 客户端协议 adapter。
|
||||
|
||||
pub mod auth;
|
||||
pub mod error;
|
||||
pub mod models;
|
||||
pub mod responses;
|
||||
pub mod router;
|
||||
pub mod service;
|
||||
|
||||
pub use router::router;
|
||||
pub use service::{
|
||||
ConnectionTask, DeliveryEvent, OpenAiApiState, OpenAiClientService, ResponseExecutionSession,
|
||||
ResponsesTransport, StartedResponse,
|
||||
};
|
||||
@@ -0,0 +1,81 @@
|
||||
//! OpenAI 模型目录 HTTP adapter。
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use gateway_core::routing::PublicModelId;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{
|
||||
auth::{authenticate_client, authentication_error_response},
|
||||
error::model_not_found_response,
|
||||
service::{OpenAiApiState, OpenAiClientService},
|
||||
};
|
||||
|
||||
const MODEL_CREATED_TIMESTAMP: i64 = 1_700_000_000;
|
||||
|
||||
/// `GET /v1/models`。
|
||||
pub async fn models<S>(State(state): State<S>, headers: HeaderMap) -> Response
|
||||
where
|
||||
S: OpenAiApiState,
|
||||
{
|
||||
let service = state.openai_client_api();
|
||||
let client = match authenticate_client(&service, &headers) {
|
||||
Ok(client) => client,
|
||||
Err(error) => return authentication_error_response(error),
|
||||
};
|
||||
let data = service
|
||||
.public_models(&client)
|
||||
.into_iter()
|
||||
.map(|model| openai_model_json(&model))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(json!({
|
||||
"object": "list",
|
||||
"data": data,
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// `GET /v1/models/{model_id}`。
|
||||
pub async fn model_detail<S>(
|
||||
State(state): State<S>,
|
||||
headers: HeaderMap,
|
||||
Path(model_id): Path<String>,
|
||||
) -> Response
|
||||
where
|
||||
S: OpenAiApiState,
|
||||
{
|
||||
let service = state.openai_client_api();
|
||||
let client = match authenticate_client(&service, &headers) {
|
||||
Ok(client) => client,
|
||||
Err(error) => return authentication_error_response(error),
|
||||
};
|
||||
let Ok(public_model) = PublicModelId::new(model_id) else {
|
||||
return model_not_found_response().into_response();
|
||||
};
|
||||
if !service.contains_public_model(&client, &public_model) {
|
||||
return model_not_found_response().into_response();
|
||||
}
|
||||
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(openai_model_json(public_model.as_str())),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
fn openai_model_json(id: &str) -> Value {
|
||||
json!({
|
||||
"id": id,
|
||||
"object": "model",
|
||||
"created": MODEL_CREATED_TIMESTAMP,
|
||||
"owned_by": "gateway",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
//! OpenAI Responses adapter 的稳定错误 contract。
|
||||
|
||||
use gateway_core::event::EventSequenceError;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
use thiserror::Error;
|
||||
|
||||
/// OpenAI 风格的协议错误 JSON。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
pub struct ProtocolErrorBody {
|
||||
/// 错误对象。
|
||||
pub error: ProtocolError,
|
||||
}
|
||||
|
||||
/// 不包含请求正文或 prompt 的错误对象。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
pub struct ProtocolError {
|
||||
/// OpenAI 错误类别。
|
||||
#[serde(rename = "type")]
|
||||
pub kind: &'static str,
|
||||
/// 稳定机器码。
|
||||
pub code: &'static str,
|
||||
/// 安全的可读信息。
|
||||
pub message: String,
|
||||
/// 出错字段;不包含字段值。
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub param: Option<String>,
|
||||
}
|
||||
|
||||
impl ProtocolErrorBody {
|
||||
/// 序列化为 JSON value。
|
||||
#[must_use]
|
||||
pub fn into_value(self) -> Value {
|
||||
serde_json::json!({ "error": self.error })
|
||||
}
|
||||
}
|
||||
|
||||
/// Responses 请求解码错误。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Error)]
|
||||
pub enum RequestDecodeError {
|
||||
/// 请求不是合法 JSON。
|
||||
#[error("request body must be valid JSON")]
|
||||
MalformedJson,
|
||||
/// 顶层不是 object。
|
||||
#[error("request body must be a JSON object")]
|
||||
ExpectedObject,
|
||||
/// 缺少必填字段。
|
||||
#[error("required field `{field}` is missing")]
|
||||
MissingField {
|
||||
/// 字段路径。
|
||||
field: String,
|
||||
},
|
||||
/// 字段类型错误。
|
||||
#[error("field `{field}` has an invalid type; expected {expected}")]
|
||||
InvalidType {
|
||||
/// 字段路径。
|
||||
field: String,
|
||||
/// 安全的期望类型。
|
||||
expected: &'static str,
|
||||
},
|
||||
/// 字段为空。
|
||||
#[error("field `{field}` must not be empty")]
|
||||
EmptyField {
|
||||
/// 字段路径。
|
||||
field: String,
|
||||
},
|
||||
/// 字段值不满足稳定约束。
|
||||
#[error("field `{field}` has an invalid value")]
|
||||
InvalidValue {
|
||||
/// 字段路径;不保存原始值。
|
||||
field: String,
|
||||
},
|
||||
/// 未知字段。
|
||||
#[error("unknown field `{field}`")]
|
||||
UnknownField {
|
||||
/// 字段路径;不保存字段值。
|
||||
field: String,
|
||||
},
|
||||
/// 已知但尚未实现的语义。
|
||||
#[error("field `{field}` is not supported by this gateway")]
|
||||
UnsupportedField {
|
||||
/// 字段路径。
|
||||
field: String,
|
||||
},
|
||||
/// Provider options 版本不受支持。
|
||||
#[error("unsupported provider_options version")]
|
||||
UnsupportedProviderOptionsVersion,
|
||||
/// Core operation 拒绝规范化后的字段。
|
||||
#[error("field `{field}` violates the canonical operation contract")]
|
||||
CanonicalContract {
|
||||
/// 字段路径。
|
||||
field: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl RequestDecodeError {
|
||||
/// 转换为 OpenAI 风格且不泄露正文的错误 payload。
|
||||
#[must_use]
|
||||
pub fn protocol_body(&self) -> ProtocolErrorBody {
|
||||
let (code, message, param) = match self {
|
||||
Self::MalformedJson => (
|
||||
"invalid_json",
|
||||
"Request body must be valid JSON.".to_owned(),
|
||||
None,
|
||||
),
|
||||
Self::ExpectedObject => (
|
||||
"invalid_request_body",
|
||||
"Request body must be a JSON object.".to_owned(),
|
||||
None,
|
||||
),
|
||||
Self::MissingField { field } => (
|
||||
"missing_required_parameter",
|
||||
format!("Required parameter `{field}` is missing."),
|
||||
Some(field.clone()),
|
||||
),
|
||||
Self::InvalidType { field, expected } => (
|
||||
"invalid_type",
|
||||
format!("Parameter `{field}` must be {expected}."),
|
||||
Some(field.clone()),
|
||||
),
|
||||
Self::EmptyField { field } => (
|
||||
"invalid_value",
|
||||
format!("Parameter `{field}` must not be empty."),
|
||||
Some(field.clone()),
|
||||
),
|
||||
Self::InvalidValue { field } | Self::CanonicalContract { field } => (
|
||||
"invalid_value",
|
||||
format!("Parameter `{field}` has an invalid value."),
|
||||
Some(field.clone()),
|
||||
),
|
||||
Self::UnknownField { field } => (
|
||||
"unknown_parameter",
|
||||
format!("Unknown parameter `{field}`."),
|
||||
Some(field.clone()),
|
||||
),
|
||||
Self::UnsupportedField { field } => (
|
||||
"unsupported_parameter",
|
||||
format!("Parameter `{field}` is not supported by this gateway."),
|
||||
Some(field.clone()),
|
||||
),
|
||||
Self::UnsupportedProviderOptionsVersion => (
|
||||
"unsupported_provider_options_version",
|
||||
"The provider_options version is not supported.".to_owned(),
|
||||
Some("provider_options.version".to_owned()),
|
||||
),
|
||||
};
|
||||
ProtocolErrorBody {
|
||||
error: ProtocolError {
|
||||
kind: "invalid_request_error",
|
||||
code,
|
||||
message,
|
||||
param,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonical event 到 OpenAI Responses 的编码错误。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Error)]
|
||||
pub enum ResponseEncodeError {
|
||||
/// Core canonical 顺序错误。
|
||||
#[error("canonical event sequence is invalid: {0}")]
|
||||
Sequence(#[from] EventSequenceError),
|
||||
/// Core 新增了当前 adapter 尚未声明的事件语义。
|
||||
#[error("canonical event is not supported by this OpenAI Responses adapter")]
|
||||
UnsupportedEvent,
|
||||
/// `Started` 与 `Completed` 元数据不一致。
|
||||
#[error("response metadata changed during canonical stream")]
|
||||
MetadataChanged,
|
||||
/// 同一 stream 重复报告 usage。
|
||||
#[error("canonical stream contains more than one Usage event")]
|
||||
DuplicateUsage,
|
||||
/// 当前 OpenAI Responses adapter 无法表达该 canonical 内容类别。
|
||||
#[error("canonical content kind `{kind}` is not supported by OpenAI Responses")]
|
||||
UnsupportedContentKind {
|
||||
/// 安全类别名。
|
||||
kind: &'static str,
|
||||
},
|
||||
/// Usage 缺少 OpenAI Responses 所需的基础 token 事实。
|
||||
#[error("canonical Usage is missing required token totals")]
|
||||
IncompleteUsage,
|
||||
/// Tool call 在结束时仍缺少名称。
|
||||
#[error("tool call at content index {index} has no name")]
|
||||
MissingToolName {
|
||||
/// Canonical content index。
|
||||
index: u32,
|
||||
},
|
||||
/// Tool call ID 或名称在增量中发生变化。
|
||||
#[error("tool call identity changed at content index {index}")]
|
||||
ToolIdentityChanged {
|
||||
/// Canonical content index。
|
||||
index: u32,
|
||||
},
|
||||
/// Collector 已终结。
|
||||
#[error("responses collector has already completed")]
|
||||
AlreadyCompleted,
|
||||
/// Adapter 自身生成的 event framing 无法还原为 WebSocket event JSON。
|
||||
#[error("responses event encoder produced an invalid internal framing")]
|
||||
InvalidEventEncoding,
|
||||
}
|
||||
|
||||
impl ResponseEncodeError {
|
||||
/// 转换为不包含生成内容的 OpenAI 风格错误 payload。
|
||||
#[must_use]
|
||||
pub fn protocol_body(&self) -> ProtocolErrorBody {
|
||||
ProtocolErrorBody {
|
||||
error: ProtocolError {
|
||||
kind: "server_error",
|
||||
code: "invalid_canonical_response",
|
||||
message: "The gateway could not encode the canonical response.".to_owned(),
|
||||
param: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
//! OpenAI Responses HTTP 与 SSE adapter。
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::convert::Infallible;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
|
||||
use axum::{
|
||||
body::{Body, Bytes},
|
||||
extract::{Extension, State, connect_info::ConnectInfo},
|
||||
http::{
|
||||
HeaderMap, HeaderValue, StatusCode,
|
||||
header::{CACHE_CONTROL, CONTENT_TYPE, USER_AGENT},
|
||||
},
|
||||
response::Response,
|
||||
};
|
||||
use futures::stream;
|
||||
use gateway_core::engine::CommitRequirement;
|
||||
use gateway_core::error::{GatewayError, GatewayErrorKind};
|
||||
use gateway_core::event::GatewayEvent;
|
||||
use gateway_protocol::openai::sse::{DONE_SSE_FRAME, response_failed_sse_event};
|
||||
|
||||
use crate::openai::{
|
||||
auth::{authenticate_client, authentication_error_response},
|
||||
error::{
|
||||
gateway_error_contract, gateway_error_from_engine, gateway_error_response,
|
||||
protocol_error_response,
|
||||
},
|
||||
service::{OpenAiApiState, OpenAiClientService, ResponseExecutionSession, ResponsesTransport},
|
||||
};
|
||||
|
||||
use super::{ProtocolErrorBody, ResponseEncodeError, ResponsesCollector, decode_request};
|
||||
|
||||
/// `POST /v1/responses`。
|
||||
pub async fn responses<S>(
|
||||
State(state): State<S>,
|
||||
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response
|
||||
where
|
||||
S: OpenAiApiState,
|
||||
{
|
||||
let service = state.openai_client_api();
|
||||
let client = match authenticate_client(&service, &headers) {
|
||||
Ok(client) => client,
|
||||
Err(error) => return authentication_error_response(error),
|
||||
};
|
||||
let decoded = match decode_request(&body) {
|
||||
Ok(decoded) => decoded,
|
||||
Err(error) => {
|
||||
return protocol_error_response(StatusCode::BAD_REQUEST, error.protocol_body());
|
||||
}
|
||||
};
|
||||
let (client_ip, user_agent) = request_client_context(
|
||||
&headers,
|
||||
connect_info.map(|Extension(ConnectInfo(address))| address),
|
||||
);
|
||||
let decoded = decoded.with_client_context(client_ip, user_agent);
|
||||
let started = match service
|
||||
.start_response(client, decoded, ResponsesTransport::Http)
|
||||
.await
|
||||
{
|
||||
Ok(started) => started,
|
||||
Err(error) => return gateway_error_response(&error),
|
||||
};
|
||||
let (session, created_at, streaming) = started.into_parts();
|
||||
if streaming {
|
||||
stream_execution_response(session, created_at).await
|
||||
} else {
|
||||
collect_execution_response(session, created_at).await
|
||||
}
|
||||
}
|
||||
|
||||
/// 从 socket 与标准转发头提取旧 Usage 页面使用的诊断事实。
|
||||
pub(super) fn request_client_context(
|
||||
headers: &HeaderMap,
|
||||
peer_address: Option<SocketAddr>,
|
||||
) -> (Option<IpAddr>, Option<String>) {
|
||||
let client_ip = ["cf-connecting-ip", "x-real-ip"]
|
||||
.into_iter()
|
||||
.find_map(|name| header_ip(headers, name))
|
||||
.or_else(|| forwarded_client_ip(headers))
|
||||
.or_else(|| peer_address.map(|address| address.ip()));
|
||||
let user_agent = headers
|
||||
.get(USER_AGENT)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned);
|
||||
(client_ip, user_agent)
|
||||
}
|
||||
|
||||
fn header_ip(headers: &HeaderMap, name: &str) -> Option<IpAddr> {
|
||||
headers
|
||||
.get(name)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::trim)
|
||||
.and_then(|value| value.parse().ok())
|
||||
}
|
||||
|
||||
fn forwarded_client_ip(headers: &HeaderMap) -> Option<IpAddr> {
|
||||
let addresses = headers
|
||||
.get("x-forwarded-for")?
|
||||
.to_str()
|
||||
.ok()?
|
||||
.split(',')
|
||||
.filter_map(|value| value.trim().parse::<IpAddr>().ok())
|
||||
.collect::<Vec<_>>();
|
||||
addresses
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|address| !is_private_or_loopback(*address))
|
||||
.or_else(|| addresses.first().copied())
|
||||
}
|
||||
|
||||
const fn is_private_or_loopback(address: IpAddr) -> bool {
|
||||
match address {
|
||||
IpAddr::V4(address) => address.is_private() || address.is_loopback(),
|
||||
IpAddr::V6(address) => address.is_unique_local() || address.is_loopback(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 编码完整 canonical event 集合,并在完整 JSON 成功后提交下游。
|
||||
pub async fn collect_execution_response<S>(session: S, created_at: u64) -> Response
|
||||
where
|
||||
S: ResponseExecutionSession,
|
||||
{
|
||||
let mut execution = PendingExecution::new(session);
|
||||
let Some(session) = execution.session_mut() else {
|
||||
return internal_gateway_response("gateway response session is unavailable");
|
||||
};
|
||||
let events = match session.collect_uncommitted().await {
|
||||
Ok(events) => events,
|
||||
Err(error) => {
|
||||
let response = gateway_error_response(&gateway_error_from_engine(&error));
|
||||
return execution.record_response_status(response).await;
|
||||
}
|
||||
};
|
||||
|
||||
let encoded = match encode_collected_events(created_at, &events) {
|
||||
Ok(encoded) => encoded,
|
||||
Err(error) => {
|
||||
let response =
|
||||
protocol_error_response(StatusCode::INTERNAL_SERVER_ERROR, error.protocol_body());
|
||||
let response = execution.record_response_status(response).await;
|
||||
execution.cancel_and_finalize().await;
|
||||
return response;
|
||||
}
|
||||
};
|
||||
let response = json_body_response(encoded);
|
||||
|
||||
let Some(session) = execution.session_mut() else {
|
||||
return internal_gateway_response("gateway response session is unavailable");
|
||||
};
|
||||
if let Err(error) = session
|
||||
.commit_downstream(Some(StatusCode::OK.as_u16()))
|
||||
.await
|
||||
{
|
||||
execution.cancel_and_finalize().await;
|
||||
let response = gateway_error_response(&gateway_error_from_engine(&error));
|
||||
return execution.record_response_status(response).await;
|
||||
}
|
||||
if !session.is_finalized() {
|
||||
execution.cancel_and_finalize().await;
|
||||
return internal_gateway_response("gateway response was not finalized after commit");
|
||||
}
|
||||
execution.disarm();
|
||||
response
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum BufferedResponseEncodeError {
|
||||
Canonical(ResponseEncodeError),
|
||||
Json,
|
||||
}
|
||||
|
||||
impl BufferedResponseEncodeError {
|
||||
fn protocol_body(&self) -> ProtocolErrorBody {
|
||||
match self {
|
||||
Self::Canonical(error) => error.protocol_body(),
|
||||
Self::Json => ResponseEncodeError::UnsupportedEvent.protocol_body(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_collected_events(
|
||||
created_at: u64,
|
||||
events: &[GatewayEvent],
|
||||
) -> Result<Vec<u8>, BufferedResponseEncodeError> {
|
||||
let mut collector = ResponsesCollector::new(created_at);
|
||||
for event in events {
|
||||
collector
|
||||
.push(event)
|
||||
.map_err(BufferedResponseEncodeError::Canonical)?;
|
||||
}
|
||||
let response = collector
|
||||
.finish()
|
||||
.map_err(BufferedResponseEncodeError::Canonical)?;
|
||||
serde_json::to_vec(&response).map_err(|_| BufferedResponseEncodeError::Json)
|
||||
}
|
||||
|
||||
fn json_body_response(encoded: Vec<u8>) -> Response {
|
||||
let mut response = Response::new(Body::from(encoded));
|
||||
*response.status_mut() = StatusCode::OK;
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
response
|
||||
}
|
||||
|
||||
/// 编码首个 SSE frame 后提交下游,再持续驱动同一执行会话。
|
||||
pub async fn stream_execution_response<S>(session: S, created_at: u64) -> Response
|
||||
where
|
||||
S: ResponseExecutionSession,
|
||||
{
|
||||
let mut execution = PendingExecution::new(session);
|
||||
let Some(session) = execution.session_mut() else {
|
||||
return internal_gateway_response("gateway response session is unavailable");
|
||||
};
|
||||
let first = match session.next_delivery_event().await {
|
||||
Ok(Some(event)) => event,
|
||||
Ok(None) => {
|
||||
let response = gateway_error_response(&GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"gateway response ended before its first event",
|
||||
));
|
||||
let response = execution.record_response_status(response).await;
|
||||
execution.cancel_and_finalize().await;
|
||||
return response;
|
||||
}
|
||||
Err(error) => {
|
||||
let response = gateway_error_response(&gateway_error_from_engine(&error));
|
||||
return execution.record_response_status(response).await;
|
||||
}
|
||||
};
|
||||
let (first_event, first_requirement) = first.into_parts();
|
||||
if first_requirement != CommitRequirement::CommitBeforeDelivery {
|
||||
let response = internal_gateway_response("gateway first event did not require commit");
|
||||
let response = execution.record_response_status(response).await;
|
||||
execution.cancel_and_finalize().await;
|
||||
return response;
|
||||
}
|
||||
let mut collector = ResponsesCollector::new(created_at);
|
||||
let frames = match collector.push(&first_event) {
|
||||
Ok(frames) => frames,
|
||||
Err(error) => {
|
||||
let response =
|
||||
protocol_error_response(StatusCode::INTERNAL_SERVER_ERROR, error.protocol_body());
|
||||
let response = execution.record_response_status(response).await;
|
||||
execution.cancel_and_finalize().await;
|
||||
return response;
|
||||
}
|
||||
};
|
||||
if frames.is_empty() {
|
||||
let response = internal_gateway_response("gateway first event encoded no SSE frame");
|
||||
let response = execution.record_response_status(response).await;
|
||||
execution.cancel_and_finalize().await;
|
||||
return response;
|
||||
}
|
||||
let Some(session) = execution.session_mut() else {
|
||||
return internal_gateway_response("gateway response session is unavailable");
|
||||
};
|
||||
if let Err(error) = session
|
||||
.commit_downstream(Some(StatusCode::OK.as_u16()))
|
||||
.await
|
||||
{
|
||||
execution.cancel_and_finalize().await;
|
||||
let response = gateway_error_response(&gateway_error_from_engine(&error));
|
||||
return execution.record_response_status(response).await;
|
||||
}
|
||||
let Some(session) = execution.into_session() else {
|
||||
return internal_gateway_response("gateway response session is unavailable");
|
||||
};
|
||||
let state = ResponsesStreamState::new(session, collector, frames);
|
||||
let body = Body::from_stream(stream::unfold(state, |mut state| async move {
|
||||
loop {
|
||||
if let Some(chunk) = state.pending.pop_front() {
|
||||
return Some((Ok::<Bytes, Infallible>(chunk), state));
|
||||
}
|
||||
if state.output_finished {
|
||||
return None;
|
||||
}
|
||||
state.advance().await;
|
||||
}
|
||||
}));
|
||||
event_stream_response(body)
|
||||
}
|
||||
|
||||
fn event_stream_response(body: Body) -> Response {
|
||||
let mut response = Response::new(body);
|
||||
*response.status_mut() = StatusCode::OK;
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(CONTENT_TYPE, HeaderValue::from_static("text/event-stream"));
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(CACHE_CONTROL, HeaderValue::from_static("no-cache"));
|
||||
response
|
||||
}
|
||||
|
||||
fn internal_gateway_response(message: &'static str) -> Response {
|
||||
gateway_error_response(&GatewayError::new(GatewayErrorKind::Internal, message))
|
||||
}
|
||||
|
||||
pub(super) struct PendingExecution<S>
|
||||
where
|
||||
S: ResponseExecutionSession,
|
||||
{
|
||||
session: Option<S>,
|
||||
}
|
||||
|
||||
impl<S> PendingExecution<S>
|
||||
where
|
||||
S: ResponseExecutionSession,
|
||||
{
|
||||
pub(super) fn new(session: S) -> Self {
|
||||
Self {
|
||||
session: Some(session),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn session_mut(&mut self) -> Option<&mut S> {
|
||||
self.session.as_mut()
|
||||
}
|
||||
|
||||
async fn cancel_and_finalize(&mut self) {
|
||||
if let Some(session) = self.session.as_mut() {
|
||||
session.cancel();
|
||||
if !session.is_finalized() {
|
||||
let _ = session.next_delivery_event().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn record_response_status(&mut self, response: Response) -> Response {
|
||||
let Some(session) = self.session.as_mut() else {
|
||||
return internal_gateway_response("gateway response session is unavailable");
|
||||
};
|
||||
if session
|
||||
.record_client_status(response.status().as_u16())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return internal_gateway_response("gateway client status could not be persisted");
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
pub(super) fn disarm(&mut self) {
|
||||
self.session = None;
|
||||
}
|
||||
|
||||
fn into_session(mut self) -> Option<S> {
|
||||
self.session.take()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Drop for PendingExecution<S>
|
||||
where
|
||||
S: ResponseExecutionSession,
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
let Some(session) = self.session.take() else {
|
||||
return;
|
||||
};
|
||||
if session.is_finalized() {
|
||||
return;
|
||||
}
|
||||
session.cancel();
|
||||
session.detach_finalize();
|
||||
}
|
||||
}
|
||||
|
||||
struct ResponsesStreamState<S>
|
||||
where
|
||||
S: ResponseExecutionSession,
|
||||
{
|
||||
session: Option<S>,
|
||||
collector: ResponsesCollector,
|
||||
pending: VecDeque<Bytes>,
|
||||
output_finished: bool,
|
||||
execution_terminal: bool,
|
||||
}
|
||||
|
||||
impl<S> ResponsesStreamState<S>
|
||||
where
|
||||
S: ResponseExecutionSession,
|
||||
{
|
||||
fn new(session: S, collector: ResponsesCollector, initial_frames: Vec<String>) -> Self {
|
||||
Self {
|
||||
session: Some(session),
|
||||
collector,
|
||||
pending: initial_frames.into_iter().map(Bytes::from).collect(),
|
||||
output_finished: false,
|
||||
execution_terminal: false,
|
||||
}
|
||||
}
|
||||
|
||||
async fn advance(&mut self) {
|
||||
let next = match self.session.as_mut() {
|
||||
Some(session) => session.next_delivery_event().await,
|
||||
None => {
|
||||
self.finish_with_gateway_error(GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"gateway response session is unavailable",
|
||||
));
|
||||
return;
|
||||
}
|
||||
};
|
||||
match next {
|
||||
Ok(Some(event)) => {
|
||||
let (event, requirement) = event.into_parts();
|
||||
if requirement != CommitRequirement::AlreadyCommitted {
|
||||
self.cancel_execution().await;
|
||||
self.finish_with_gateway_error(GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"gateway requested another downstream commit",
|
||||
));
|
||||
} else {
|
||||
self.push_event(event).await;
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
self.execution_terminal = self
|
||||
.session
|
||||
.as_ref()
|
||||
.is_some_and(ResponseExecutionSession::is_finalized);
|
||||
self.finish_with_gateway_error(GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"gateway response ended without a terminal event",
|
||||
));
|
||||
}
|
||||
Err(error) => {
|
||||
self.execution_terminal = self
|
||||
.session
|
||||
.as_ref()
|
||||
.is_some_and(ResponseExecutionSession::is_finalized);
|
||||
self.finish_with_gateway_error(gateway_error_from_engine(&error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn push_event(&mut self, event: GatewayEvent) {
|
||||
let completed = matches!(event, GatewayEvent::Completed(_));
|
||||
match self.collector.push(&event) {
|
||||
Ok(frames) => {
|
||||
if completed {
|
||||
self.finish_completed(frames).await;
|
||||
} else {
|
||||
self.pending.extend(frames.into_iter().map(Bytes::from));
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
self.cancel_execution().await;
|
||||
self.finish_with_encode_error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn finish_completed(&mut self, frames: Vec<String>) {
|
||||
let next = match self.session.as_mut() {
|
||||
Some(session) => session.next_delivery_event().await,
|
||||
None => {
|
||||
self.finish_with_gateway_error(GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"gateway response session is unavailable",
|
||||
));
|
||||
return;
|
||||
}
|
||||
};
|
||||
match next {
|
||||
Ok(None)
|
||||
if self
|
||||
.session
|
||||
.as_ref()
|
||||
.is_some_and(ResponseExecutionSession::is_finalized) =>
|
||||
{
|
||||
self.pending.extend(frames.into_iter().map(Bytes::from));
|
||||
self.execution_terminal = true;
|
||||
self.pending
|
||||
.push_back(Bytes::from_static(DONE_SSE_FRAME.as_bytes()));
|
||||
self.output_finished = true;
|
||||
}
|
||||
Ok(None) => {
|
||||
self.cancel_execution().await;
|
||||
self.finish_with_gateway_error(GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"gateway response was not finalized after its terminal event",
|
||||
));
|
||||
}
|
||||
Ok(Some(_)) => {
|
||||
self.cancel_execution().await;
|
||||
self.finish_with_gateway_error(GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"gateway response continued after its terminal event",
|
||||
));
|
||||
}
|
||||
Err(error) => {
|
||||
self.execution_terminal = self
|
||||
.session
|
||||
.as_ref()
|
||||
.is_some_and(ResponseExecutionSession::is_finalized);
|
||||
self.finish_with_gateway_error(gateway_error_from_engine(&error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn cancel_execution(&mut self) {
|
||||
if let Some(session) = self.session.as_mut() {
|
||||
session.cancel();
|
||||
if !session.is_finalized() {
|
||||
let _ = session.next_delivery_event().await;
|
||||
}
|
||||
self.execution_terminal = session.is_finalized();
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_with_gateway_error(&mut self, error: GatewayError) {
|
||||
let (_, error_type, code) = gateway_error_contract(error.kind());
|
||||
self.pending
|
||||
.push_back(Bytes::from(response_failed_sse_event(
|
||||
error_type,
|
||||
code,
|
||||
error.safe_message(),
|
||||
)));
|
||||
self.pending
|
||||
.push_back(Bytes::from_static(DONE_SSE_FRAME.as_bytes()));
|
||||
self.output_finished = true;
|
||||
}
|
||||
|
||||
fn finish_with_encode_error(&mut self, error: ResponseEncodeError) {
|
||||
let protocol = error.protocol_body().error;
|
||||
self.pending
|
||||
.push_back(Bytes::from(response_failed_sse_event(
|
||||
protocol.kind,
|
||||
protocol.code,
|
||||
&protocol.message,
|
||||
)));
|
||||
self.pending
|
||||
.push_back(Bytes::from_static(DONE_SSE_FRAME.as_bytes()));
|
||||
self.output_finished = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Drop for ResponsesStreamState<S>
|
||||
where
|
||||
S: ResponseExecutionSession,
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
if self.execution_terminal {
|
||||
return;
|
||||
}
|
||||
let Some(session) = self.session.take() else {
|
||||
return;
|
||||
};
|
||||
session.cancel();
|
||||
// Body drop 后由应用 runtime 继续状态机清理,HTTP body 生命周期不等待它。
|
||||
session.detach_finalize();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//! OpenAI Responses 的请求 decoder 与 canonical event encoder。
|
||||
//!
|
||||
//! 这里的“透明”指已声明语义逐项映射,而不是原始 JSON/SSE passthrough。
|
||||
//! 未实现语义会返回稳定的 typed error,不能静默删除。
|
||||
|
||||
mod error;
|
||||
mod http;
|
||||
mod request;
|
||||
mod response;
|
||||
mod websocket;
|
||||
|
||||
pub use error::{ProtocolErrorBody, RequestDecodeError, ResponseEncodeError};
|
||||
pub use http::{collect_execution_response, responses, stream_execution_response};
|
||||
pub use request::{
|
||||
ContinuationIntent, DecodedResponsesRequest, PROVIDER_OPTIONS_VERSION,
|
||||
ResponsesRequestMetadata, decode_request,
|
||||
};
|
||||
pub use response::{CollectedResponses, ResponsesCollector};
|
||||
pub use websocket::{
|
||||
ResponseCreateFrameError, ResponsesWebSocketAdapter, decode_response_create,
|
||||
responses_websocket,
|
||||
};
|
||||
@@ -0,0 +1,840 @@
|
||||
//! OpenAI Responses JSON 到 canonical operation 的严格解码。
|
||||
|
||||
use std::{fmt, net::IpAddr};
|
||||
|
||||
use gateway_core::operation::{
|
||||
ContentPart, ContinuationMode, GenerateRequest, ImageSource, JsonSchemaFormat, Message,
|
||||
MessageRole, Operation, OutputFormat, ProviderOptions, ReasoningEffort, ReasoningRequirement,
|
||||
ReasoningSummary, ResponsePersistence, ToolDefinition,
|
||||
};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use super::error::RequestDecodeError;
|
||||
|
||||
/// Gateway 扩展 `provider_options` 的唯一受支持版本。
|
||||
pub const PROVIDER_OPTIONS_VERSION: &str = "v1";
|
||||
|
||||
const TOP_LEVEL_FIELDS: &[&str] = &[
|
||||
"input",
|
||||
"instructions",
|
||||
"max_output_tokens",
|
||||
"model",
|
||||
"previous_response_id",
|
||||
"provider_options",
|
||||
"reasoning",
|
||||
"store",
|
||||
"stream",
|
||||
"text",
|
||||
"tools",
|
||||
];
|
||||
|
||||
const KNOWN_UNSUPPORTED_TOP_LEVEL_FIELDS: &[&str] = &[
|
||||
"background",
|
||||
"conversation",
|
||||
"context_management",
|
||||
"include",
|
||||
"max_tool_calls",
|
||||
"metadata",
|
||||
"moderation",
|
||||
"parallel_tool_calls",
|
||||
"prompt",
|
||||
"prompt_cache_key",
|
||||
"prompt_cache_options",
|
||||
"prompt_cache_retention",
|
||||
"safety_identifier",
|
||||
"service_tier",
|
||||
"stream_options",
|
||||
"temperature",
|
||||
"tool_choice",
|
||||
"top_logprobs",
|
||||
"top_p",
|
||||
"truncation",
|
||||
"user",
|
||||
];
|
||||
|
||||
/// 客户端声明的 continuation 意图。
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub enum ContinuationIntent {
|
||||
/// 不使用先前响应。
|
||||
None,
|
||||
/// 使用当前调用方可见的 OpenAI response ID。
|
||||
///
|
||||
/// History owner 必须在认证后把它解析为调用方隔离的 binding;不得直接
|
||||
/// 作为 Provider handle 使用。
|
||||
PreviousResponseId(String),
|
||||
}
|
||||
|
||||
impl ContinuationIntent {
|
||||
/// 返回是否请求了对话延续。
|
||||
#[must_use]
|
||||
pub const fn is_continuation(&self) -> bool {
|
||||
matches!(self, Self::PreviousResponseId(_))
|
||||
}
|
||||
|
||||
/// 返回待 history owner 解析的 response ID。
|
||||
#[must_use]
|
||||
pub fn previous_response_id(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::None => None,
|
||||
Self::PreviousResponseId(value) => Some(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ContinuationIntent {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::None => formatter.write_str("None"),
|
||||
Self::PreviousResponseId(_) => formatter.write_str("PreviousResponseId(<redacted>)"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handler、Router 和 history owner 使用的请求元数据。
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct ResponsesRequestMetadata {
|
||||
requested_model: String,
|
||||
public_model: String,
|
||||
stream: bool,
|
||||
store: bool,
|
||||
continuation: ContinuationIntent,
|
||||
client_ip: Option<IpAddr>,
|
||||
user_agent: Option<String>,
|
||||
}
|
||||
|
||||
impl ResponsesRequestMetadata {
|
||||
/// 返回客户端原始模型名。
|
||||
#[must_use]
|
||||
pub fn requested_model(&self) -> &str {
|
||||
&self.requested_model
|
||||
}
|
||||
|
||||
/// 返回协议层公开模型候选。
|
||||
///
|
||||
/// Decoder 阶段它与 `requested_model` 相同;Router 冻结 Route Plan 后必须
|
||||
/// 以实际解析出的 public model 构造 logical request 事实。
|
||||
#[must_use]
|
||||
pub fn public_model(&self) -> &str {
|
||||
&self.public_model
|
||||
}
|
||||
|
||||
/// 返回客户端是否请求 SSE。
|
||||
#[must_use]
|
||||
pub const fn stream(&self) -> bool {
|
||||
self.stream
|
||||
}
|
||||
|
||||
/// 返回客户端 storage intent。
|
||||
#[must_use]
|
||||
pub const fn store(&self) -> bool {
|
||||
self.store
|
||||
}
|
||||
|
||||
/// 返回 continuation intent。
|
||||
#[must_use]
|
||||
pub const fn continuation(&self) -> &ContinuationIntent {
|
||||
&self.continuation
|
||||
}
|
||||
|
||||
/// 返回从 HTTP 连接边界解析出的客户端地址。
|
||||
#[must_use]
|
||||
pub const fn client_ip(&self) -> Option<IpAddr> {
|
||||
self.client_ip
|
||||
}
|
||||
|
||||
/// 返回经过 UTF-8 校验和空白归一化的 User-Agent。
|
||||
#[must_use]
|
||||
pub fn user_agent(&self) -> Option<&str> {
|
||||
self.user_agent.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ResponsesRequestMetadata {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter
|
||||
.debug_struct("ResponsesRequestMetadata")
|
||||
.field("requested_model", &self.requested_model)
|
||||
.field("public_model", &self.public_model)
|
||||
.field("stream", &self.stream)
|
||||
.field("store", &self.store)
|
||||
.field("continuation", &self.continuation)
|
||||
.field("client_ip", &self.client_ip)
|
||||
.field("has_user_agent", &self.user_agent.is_some())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// 一次成功解码的 Responses 请求。
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct DecodedResponsesRequest {
|
||||
operation: Operation,
|
||||
metadata: ResponsesRequestMetadata,
|
||||
}
|
||||
|
||||
impl DecodedResponsesRequest {
|
||||
/// 返回协议无关 operation。
|
||||
#[must_use]
|
||||
pub const fn operation(&self) -> &Operation {
|
||||
&self.operation
|
||||
}
|
||||
|
||||
/// 返回 handler 元数据。
|
||||
#[must_use]
|
||||
pub const fn metadata(&self) -> &ResponsesRequestMetadata {
|
||||
&self.metadata
|
||||
}
|
||||
|
||||
/// 拆分为 operation 与元数据。
|
||||
#[must_use]
|
||||
pub fn into_parts(self) -> (Operation, ResponsesRequestMetadata) {
|
||||
(self.operation, self.metadata)
|
||||
}
|
||||
|
||||
/// 附着只由 HTTP/WebSocket 连接边界提供的诊断事实。
|
||||
#[must_use]
|
||||
pub fn with_client_context(
|
||||
mut self,
|
||||
client_ip: Option<IpAddr>,
|
||||
user_agent: Option<String>,
|
||||
) -> Self {
|
||||
self.metadata.client_ip = client_ip;
|
||||
self.metadata.user_agent = user_agent;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for DecodedResponsesRequest {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter
|
||||
.debug_struct("DecodedResponsesRequest")
|
||||
.field("operation", &self.operation)
|
||||
.field("metadata", &self.metadata)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// 严格解码 OpenAI Responses JSON object。
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// JSON 非法、字段类型错误、出现未知字段或出现已知但未实现的语义时返回
|
||||
/// [`RequestDecodeError`]。错误及其 `Debug` 不保存原始 body 或 prompt。
|
||||
pub fn decode_request(body: &[u8]) -> Result<DecodedResponsesRequest, RequestDecodeError> {
|
||||
// UTF-8 wire bytes 是 Provider 无关且不会低估 byte-level token 数量的保守上界;
|
||||
// continuation owner 后续还要把恢复历史的 estimate 加入同一 canonical 事实。
|
||||
let input_token_estimate =
|
||||
u64::try_from(body.len()).map_err(|_| RequestDecodeError::InvalidValue {
|
||||
field: "input".to_owned(),
|
||||
})?;
|
||||
let value =
|
||||
serde_json::from_slice::<Value>(body).map_err(|_| RequestDecodeError::MalformedJson)?;
|
||||
let object = value
|
||||
.as_object()
|
||||
.ok_or(RequestDecodeError::ExpectedObject)?;
|
||||
reject_top_level_fields(object)?;
|
||||
|
||||
let model = required_non_empty_string(object, "model", "model")?.to_owned();
|
||||
if model.len() > 256 || model.chars().any(char::is_control) {
|
||||
return Err(RequestDecodeError::InvalidValue {
|
||||
field: "model".to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
let mut messages = Vec::new();
|
||||
if let Some(instructions) = optional_non_empty_string(object, "instructions", "instructions")? {
|
||||
messages.push(canonical_message(
|
||||
MessageRole::Developer,
|
||||
vec![ContentPart::Text(instructions.to_owned())],
|
||||
"instructions",
|
||||
)?);
|
||||
}
|
||||
let input = object
|
||||
.get("input")
|
||||
.ok_or_else(|| RequestDecodeError::MissingField {
|
||||
field: "input".to_owned(),
|
||||
})?;
|
||||
messages.extend(parse_input(input)?);
|
||||
|
||||
let mut request = GenerateRequest::new(messages)
|
||||
.map_err(|_| RequestDecodeError::CanonicalContract {
|
||||
field: "input".to_owned(),
|
||||
})?
|
||||
.with_estimated_context_tokens(input_token_estimate);
|
||||
|
||||
if let Some(tools) = object.get("tools") {
|
||||
request = request.with_tools(parse_tools(tools)?);
|
||||
}
|
||||
if let Some(text) = object.get("text") {
|
||||
request = request.with_output_format(parse_text_format(text)?);
|
||||
}
|
||||
if let Some(reasoning) = object.get("reasoning")
|
||||
&& let Some(reasoning) = parse_reasoning(reasoning)?
|
||||
{
|
||||
request = request.with_reasoning(reasoning);
|
||||
}
|
||||
if let Some(tokens) = optional_u64(object, "max_output_tokens", "max_output_tokens")? {
|
||||
if tokens == 0 {
|
||||
return Err(RequestDecodeError::InvalidValue {
|
||||
field: "max_output_tokens".to_owned(),
|
||||
});
|
||||
}
|
||||
request = request.with_max_output_tokens(tokens);
|
||||
}
|
||||
|
||||
let continuation =
|
||||
match optional_non_empty_string(object, "previous_response_id", "previous_response_id")? {
|
||||
Some(response_id) => {
|
||||
validate_response_id(response_id)?;
|
||||
request = request.with_continuation(ContinuationMode::Native);
|
||||
ContinuationIntent::PreviousResponseId(response_id.to_owned())
|
||||
}
|
||||
None => ContinuationIntent::None,
|
||||
};
|
||||
|
||||
if let Some(options) = object.get("provider_options") {
|
||||
request = request.with_provider_options(parse_provider_options(options)?);
|
||||
}
|
||||
|
||||
let stream = optional_bool(object, "stream", "stream")?.unwrap_or(false);
|
||||
let store = optional_bool(object, "store", "store")?.unwrap_or(true);
|
||||
request = request.with_response_persistence(if store {
|
||||
ResponsePersistence::Store
|
||||
} else {
|
||||
ResponsePersistence::DoNotStore
|
||||
});
|
||||
Ok(DecodedResponsesRequest {
|
||||
operation: Operation::Generate(request),
|
||||
metadata: ResponsesRequestMetadata {
|
||||
requested_model: model.clone(),
|
||||
public_model: model,
|
||||
stream,
|
||||
store,
|
||||
continuation,
|
||||
client_ip: None,
|
||||
user_agent: None,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn reject_top_level_fields(object: &Map<String, Value>) -> Result<(), RequestDecodeError> {
|
||||
for field in object.keys() {
|
||||
if TOP_LEVEL_FIELDS.contains(&field.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if KNOWN_UNSUPPORTED_TOP_LEVEL_FIELDS.contains(&field.as_str()) {
|
||||
return Err(RequestDecodeError::UnsupportedField {
|
||||
field: field.clone(),
|
||||
});
|
||||
}
|
||||
return Err(RequestDecodeError::UnknownField {
|
||||
field: field.clone(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_input(value: &Value) -> Result<Vec<Message>, RequestDecodeError> {
|
||||
match value {
|
||||
Value::String(text) => {
|
||||
require_non_empty(text, "input")?;
|
||||
Ok(vec![canonical_message(
|
||||
MessageRole::User,
|
||||
vec![ContentPart::Text(text.clone())],
|
||||
"input",
|
||||
)?])
|
||||
}
|
||||
Value::Array(items) if items.is_empty() => Err(RequestDecodeError::EmptyField {
|
||||
field: "input".to_owned(),
|
||||
}),
|
||||
Value::Array(items) => items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, item)| parse_input_item(item, index))
|
||||
.collect(),
|
||||
_ => Err(RequestDecodeError::InvalidType {
|
||||
field: "input".to_owned(),
|
||||
expected: "a string or array",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_input_item(value: &Value, index: usize) -> Result<Message, RequestDecodeError> {
|
||||
let path = format!("input[{index}]");
|
||||
let object = required_object(value, &path)?;
|
||||
match object.get("type").and_then(Value::as_str) {
|
||||
Some("function_call_output") => parse_function_call_output(object, &path),
|
||||
Some("message") | None => parse_message(object, &path),
|
||||
Some(_) => Err(RequestDecodeError::UnsupportedField {
|
||||
field: format!("{path}.type"),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_message(object: &Map<String, Value>, path: &str) -> Result<Message, RequestDecodeError> {
|
||||
reject_nested_fields(object, &["content", "role", "type"], &[], path)?;
|
||||
if let Some(kind) = object.get("type") {
|
||||
require_exact_string(kind, "message", &format!("{path}.type"))?;
|
||||
}
|
||||
let role_path = format!("{path}.role");
|
||||
let role = match required_string_value(object, "role", &role_path)? {
|
||||
"system" => MessageRole::System,
|
||||
"developer" => MessageRole::Developer,
|
||||
"user" => MessageRole::User,
|
||||
"assistant" => MessageRole::Assistant,
|
||||
_ => {
|
||||
return Err(RequestDecodeError::InvalidValue { field: role_path });
|
||||
}
|
||||
};
|
||||
let content_path = format!("{path}.content");
|
||||
let content = object
|
||||
.get("content")
|
||||
.ok_or_else(|| RequestDecodeError::MissingField {
|
||||
field: content_path.clone(),
|
||||
})?;
|
||||
let parts = parse_message_content(content, role, &content_path)?;
|
||||
canonical_message(role, parts, &content_path)
|
||||
}
|
||||
|
||||
fn parse_message_content(
|
||||
value: &Value,
|
||||
role: MessageRole,
|
||||
path: &str,
|
||||
) -> Result<Vec<ContentPart>, RequestDecodeError> {
|
||||
match value {
|
||||
Value::String(text) => {
|
||||
require_non_empty(text, path)?;
|
||||
Ok(vec![ContentPart::Text(text.clone())])
|
||||
}
|
||||
Value::Array(parts) if parts.is_empty() => Err(RequestDecodeError::EmptyField {
|
||||
field: path.to_owned(),
|
||||
}),
|
||||
Value::Array(parts) => parts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, part)| parse_content_part(part, role, &format!("{path}[{index}]")))
|
||||
.collect(),
|
||||
_ => Err(RequestDecodeError::InvalidType {
|
||||
field: path.to_owned(),
|
||||
expected: "a string or array",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_content_part(
|
||||
value: &Value,
|
||||
role: MessageRole,
|
||||
path: &str,
|
||||
) -> Result<ContentPart, RequestDecodeError> {
|
||||
let object = required_object(value, path)?;
|
||||
let type_path = format!("{path}.type");
|
||||
match required_string_value(object, "type", &type_path)? {
|
||||
"input_text" => {
|
||||
reject_nested_fields(object, &["text", "type"], &[], path)?;
|
||||
let text = required_non_empty_string(object, "text", &format!("{path}.text"))?;
|
||||
Ok(ContentPart::Text(text.to_owned()))
|
||||
}
|
||||
"output_text" if role == MessageRole::Assistant => {
|
||||
reject_nested_fields(
|
||||
object,
|
||||
&["text", "type"],
|
||||
&["annotations", "logprobs"],
|
||||
path,
|
||||
)?;
|
||||
let text = required_non_empty_string(object, "text", &format!("{path}.text"))?;
|
||||
Ok(ContentPart::Text(text.to_owned()))
|
||||
}
|
||||
"output_text" => Err(RequestDecodeError::InvalidValue { field: type_path }),
|
||||
"input_image" => parse_input_image(object, path),
|
||||
_ => Err(RequestDecodeError::UnsupportedField { field: type_path }),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_input_image(
|
||||
object: &Map<String, Value>,
|
||||
path: &str,
|
||||
) -> Result<ContentPart, RequestDecodeError> {
|
||||
reject_nested_fields(object, &["image_url", "type"], &["detail", "file_id"], path)?;
|
||||
let url_path = format!("{path}.image_url");
|
||||
let url = required_non_empty_string(object, "image_url", &url_path)?;
|
||||
if url.len() > 8 * 1024 || !(url.starts_with("https://") || url.starts_with("http://")) {
|
||||
return Err(RequestDecodeError::InvalidValue { field: url_path });
|
||||
}
|
||||
Ok(ContentPart::Image(ImageSource::Url(url.to_owned())))
|
||||
}
|
||||
|
||||
fn parse_function_call_output(
|
||||
object: &Map<String, Value>,
|
||||
path: &str,
|
||||
) -> Result<Message, RequestDecodeError> {
|
||||
reject_nested_fields(object, &["call_id", "output", "type"], &[], path)?;
|
||||
let call_id = required_non_empty_string(object, "call_id", &format!("{path}.call_id"))?;
|
||||
let output = required_string_value(object, "output", &format!("{path}.output"))?;
|
||||
canonical_message(
|
||||
MessageRole::User,
|
||||
vec![ContentPart::ToolResult {
|
||||
call_id: call_id.to_owned(),
|
||||
output: output.to_owned(),
|
||||
}],
|
||||
path,
|
||||
)
|
||||
}
|
||||
|
||||
fn parse_tools(value: &Value) -> Result<Vec<ToolDefinition>, RequestDecodeError> {
|
||||
let tools = value
|
||||
.as_array()
|
||||
.ok_or_else(|| RequestDecodeError::InvalidType {
|
||||
field: "tools".to_owned(),
|
||||
expected: "an array",
|
||||
})?;
|
||||
if tools.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
tools
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, tool)| parse_tool(tool, index))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn parse_tool(value: &Value, index: usize) -> Result<ToolDefinition, RequestDecodeError> {
|
||||
let path = format!("tools[{index}]");
|
||||
let object = required_object(value, &path)?;
|
||||
reject_nested_fields(
|
||||
object,
|
||||
&["description", "name", "parameters", "strict", "type"],
|
||||
&[],
|
||||
&path,
|
||||
)?;
|
||||
require_exact_string(
|
||||
object
|
||||
.get("type")
|
||||
.ok_or_else(|| RequestDecodeError::MissingField {
|
||||
field: format!("{path}.type"),
|
||||
})?,
|
||||
"function",
|
||||
&format!("{path}.type"),
|
||||
)?;
|
||||
let name = required_non_empty_string(object, "name", &format!("{path}.name"))?;
|
||||
let description =
|
||||
optional_non_empty_string(object, "description", &format!("{path}.description"))?
|
||||
.map(ToOwned::to_owned);
|
||||
let parameters_path = format!("{path}.parameters");
|
||||
let parameters = object
|
||||
.get("parameters")
|
||||
.ok_or_else(|| RequestDecodeError::MissingField {
|
||||
field: parameters_path.clone(),
|
||||
})?
|
||||
.as_object()
|
||||
.ok_or(RequestDecodeError::InvalidType {
|
||||
field: parameters_path,
|
||||
expected: "a JSON object",
|
||||
})?
|
||||
.clone();
|
||||
let strict = optional_bool(object, "strict", &format!("{path}.strict"))?.unwrap_or(false);
|
||||
ToolDefinition::new(name, description, parameters)
|
||||
.map(|tool| tool.with_strict(strict))
|
||||
.map_err(|_| RequestDecodeError::CanonicalContract {
|
||||
field: format!("{path}.name"),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_text_format(value: &Value) -> Result<OutputFormat, RequestDecodeError> {
|
||||
let object = required_object(value, "text")?;
|
||||
reject_nested_fields(object, &["format"], &["verbosity"], "text")?;
|
||||
let Some(format) = object.get("format") else {
|
||||
return Ok(OutputFormat::Text);
|
||||
};
|
||||
let format = required_object(format, "text.format")?;
|
||||
let format_type = required_string_value(format, "type", "text.format.type")?;
|
||||
match format_type {
|
||||
"text" => {
|
||||
reject_nested_fields(format, &["type"], &[], "text.format")?;
|
||||
Ok(OutputFormat::Text)
|
||||
}
|
||||
"json_object" => {
|
||||
reject_nested_fields(format, &["type"], &[], "text.format")?;
|
||||
Ok(OutputFormat::JsonObject)
|
||||
}
|
||||
"json_schema" => parse_json_schema_format(format),
|
||||
_ => Err(RequestDecodeError::UnsupportedField {
|
||||
field: "text.format.type".to_owned(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_json_schema_format(
|
||||
object: &Map<String, Value>,
|
||||
) -> Result<OutputFormat, RequestDecodeError> {
|
||||
reject_nested_fields(
|
||||
object,
|
||||
&["description", "name", "schema", "strict", "type"],
|
||||
&[],
|
||||
"text.format",
|
||||
)?;
|
||||
let name = required_non_empty_string(object, "name", "text.format.name")?;
|
||||
let description = optional_non_empty_string(object, "description", "text.format.description")?
|
||||
.map(ToOwned::to_owned);
|
||||
let schema = object
|
||||
.get("schema")
|
||||
.ok_or_else(|| RequestDecodeError::MissingField {
|
||||
field: "text.format.schema".to_owned(),
|
||||
})?
|
||||
.as_object()
|
||||
.ok_or_else(|| RequestDecodeError::InvalidType {
|
||||
field: "text.format.schema".to_owned(),
|
||||
expected: "a JSON object",
|
||||
})?
|
||||
.clone();
|
||||
let strict = optional_bool(object, "strict", "text.format.strict")?.unwrap_or(false);
|
||||
JsonSchemaFormat::new(name, description, schema, strict)
|
||||
.map(OutputFormat::JsonSchema)
|
||||
.map_err(|_| RequestDecodeError::CanonicalContract {
|
||||
field: "text.format.name".to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_reasoning(value: &Value) -> Result<Option<ReasoningRequirement>, RequestDecodeError> {
|
||||
let object = required_object(value, "reasoning")?;
|
||||
reject_nested_fields(object, &["effort", "summary"], &[], "reasoning")?;
|
||||
let effort = match object.get("effort") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(value)) => Some(match value.as_str() {
|
||||
"minimal" => ReasoningEffort::Minimal,
|
||||
"low" => ReasoningEffort::Low,
|
||||
"medium" => ReasoningEffort::Medium,
|
||||
"high" => ReasoningEffort::High,
|
||||
"xhigh" => ReasoningEffort::ExtraHigh,
|
||||
_ => {
|
||||
return Err(RequestDecodeError::InvalidValue {
|
||||
field: "reasoning.effort".to_owned(),
|
||||
});
|
||||
}
|
||||
}),
|
||||
Some(_) => {
|
||||
return Err(RequestDecodeError::InvalidType {
|
||||
field: "reasoning.effort".to_owned(),
|
||||
expected: "a string",
|
||||
});
|
||||
}
|
||||
};
|
||||
let summary = match object.get("summary") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(value)) => Some(match value.as_str() {
|
||||
"auto" => ReasoningSummary::Auto,
|
||||
"concise" => ReasoningSummary::Concise,
|
||||
"detailed" => ReasoningSummary::Detailed,
|
||||
"none" => ReasoningSummary::None,
|
||||
_ => {
|
||||
return Err(RequestDecodeError::InvalidValue {
|
||||
field: "reasoning.summary".to_owned(),
|
||||
});
|
||||
}
|
||||
}),
|
||||
Some(_) => {
|
||||
return Err(RequestDecodeError::InvalidType {
|
||||
field: "reasoning.summary".to_owned(),
|
||||
expected: "a string",
|
||||
});
|
||||
}
|
||||
};
|
||||
Ok((effort.is_some() || summary.is_some()).then_some(ReasoningRequirement { effort, summary }))
|
||||
}
|
||||
|
||||
fn parse_provider_options(value: &Value) -> Result<ProviderOptions, RequestDecodeError> {
|
||||
let object = required_object(value, "provider_options")?;
|
||||
reject_nested_fields(object, &["providers", "version"], &[], "provider_options")?;
|
||||
let version = required_string_value(object, "version", "provider_options.version")?;
|
||||
if version != PROVIDER_OPTIONS_VERSION {
|
||||
return Err(RequestDecodeError::UnsupportedProviderOptionsVersion);
|
||||
}
|
||||
let providers = object
|
||||
.get("providers")
|
||||
.ok_or_else(|| RequestDecodeError::MissingField {
|
||||
field: "provider_options.providers".to_owned(),
|
||||
})?
|
||||
.as_object()
|
||||
.ok_or_else(|| RequestDecodeError::InvalidType {
|
||||
field: "provider_options.providers".to_owned(),
|
||||
expected: "a JSON object",
|
||||
})?;
|
||||
let mut options = ProviderOptions::new();
|
||||
for (provider, value) in providers {
|
||||
let provider_options =
|
||||
value
|
||||
.as_object()
|
||||
.ok_or_else(|| RequestDecodeError::InvalidType {
|
||||
field: format!("provider_options.providers.{provider}"),
|
||||
expected: "a JSON object",
|
||||
})?;
|
||||
options
|
||||
.insert(provider.clone(), provider_options.clone())
|
||||
.map_err(|_| RequestDecodeError::CanonicalContract {
|
||||
field: format!("provider_options.providers.{provider}"),
|
||||
})?;
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
fn validate_response_id(response_id: &str) -> Result<(), RequestDecodeError> {
|
||||
if response_id.len() > 256
|
||||
|| !response_id.starts_with("resp_")
|
||||
|| response_id.chars().any(char::is_control)
|
||||
{
|
||||
return Err(RequestDecodeError::InvalidValue {
|
||||
field: "previous_response_id".to_owned(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn canonical_message(
|
||||
role: MessageRole,
|
||||
parts: Vec<ContentPart>,
|
||||
field: &str,
|
||||
) -> Result<Message, RequestDecodeError> {
|
||||
Message::new(role, parts).map_err(|_| RequestDecodeError::CanonicalContract {
|
||||
field: field.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
fn reject_nested_fields(
|
||||
object: &Map<String, Value>,
|
||||
supported: &[&str],
|
||||
known_unsupported: &[&str],
|
||||
path: &str,
|
||||
) -> Result<(), RequestDecodeError> {
|
||||
for field in object.keys() {
|
||||
if supported.contains(&field.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let field_path = format!("{path}.{field}");
|
||||
if known_unsupported.contains(&field.as_str()) {
|
||||
return Err(RequestDecodeError::UnsupportedField { field: field_path });
|
||||
}
|
||||
return Err(RequestDecodeError::UnknownField { field: field_path });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn required_object<'a>(
|
||||
value: &'a Value,
|
||||
field: &str,
|
||||
) -> Result<&'a Map<String, Value>, RequestDecodeError> {
|
||||
value
|
||||
.as_object()
|
||||
.ok_or_else(|| RequestDecodeError::InvalidType {
|
||||
field: field.to_owned(),
|
||||
expected: "a JSON object",
|
||||
})
|
||||
}
|
||||
|
||||
fn required_string_value<'a>(
|
||||
object: &'a Map<String, Value>,
|
||||
key: &str,
|
||||
field: &str,
|
||||
) -> Result<&'a str, RequestDecodeError> {
|
||||
object
|
||||
.get(key)
|
||||
.ok_or_else(|| RequestDecodeError::MissingField {
|
||||
field: field.to_owned(),
|
||||
})?
|
||||
.as_str()
|
||||
.ok_or_else(|| RequestDecodeError::InvalidType {
|
||||
field: field.to_owned(),
|
||||
expected: "a string",
|
||||
})
|
||||
}
|
||||
|
||||
fn required_non_empty_string<'a>(
|
||||
object: &'a Map<String, Value>,
|
||||
key: &str,
|
||||
field: &str,
|
||||
) -> Result<&'a str, RequestDecodeError> {
|
||||
let value = required_string_value(object, key, field)?;
|
||||
require_non_empty(value, field)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn optional_non_empty_string<'a>(
|
||||
object: &'a Map<String, Value>,
|
||||
key: &str,
|
||||
field: &str,
|
||||
) -> Result<Option<&'a str>, RequestDecodeError> {
|
||||
match object.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(value)) => {
|
||||
require_non_empty(value, field)?;
|
||||
Ok(Some(value))
|
||||
}
|
||||
Some(_) => Err(RequestDecodeError::InvalidType {
|
||||
field: field.to_owned(),
|
||||
expected: "a string",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn optional_bool(
|
||||
object: &Map<String, Value>,
|
||||
key: &str,
|
||||
field: &str,
|
||||
) -> Result<Option<bool>, RequestDecodeError> {
|
||||
match object.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::Bool(value)) => Ok(Some(*value)),
|
||||
Some(_) => Err(RequestDecodeError::InvalidType {
|
||||
field: field.to_owned(),
|
||||
expected: "a boolean",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn optional_u64(
|
||||
object: &Map<String, Value>,
|
||||
key: &str,
|
||||
field: &str,
|
||||
) -> Result<Option<u64>, RequestDecodeError> {
|
||||
match object.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::Number(value)) => {
|
||||
value
|
||||
.as_u64()
|
||||
.map(Some)
|
||||
.ok_or_else(|| RequestDecodeError::InvalidType {
|
||||
field: field.to_owned(),
|
||||
expected: "a non-negative integer",
|
||||
})
|
||||
}
|
||||
Some(_) => Err(RequestDecodeError::InvalidType {
|
||||
field: field.to_owned(),
|
||||
expected: "a non-negative integer",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn require_non_empty(value: &str, field: &str) -> Result<(), RequestDecodeError> {
|
||||
if value.is_empty() {
|
||||
return Err(RequestDecodeError::EmptyField {
|
||||
field: field.to_owned(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_exact_string(
|
||||
value: &Value,
|
||||
expected: &'static str,
|
||||
field: &str,
|
||||
) -> Result<(), RequestDecodeError> {
|
||||
let actual = value
|
||||
.as_str()
|
||||
.ok_or_else(|| RequestDecodeError::InvalidType {
|
||||
field: field.to_owned(),
|
||||
expected: "a string",
|
||||
})?;
|
||||
if actual != expected {
|
||||
return Err(RequestDecodeError::UnsupportedField {
|
||||
field: field.to_owned(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,806 @@
|
||||
//! Canonical event 到 OpenAI Responses SSE/JSON 的单一状态机。
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use gateway_core::accounting::Usage;
|
||||
use gateway_core::event::{
|
||||
ContentItem, ContentKind, EventSequenceValidator, FinishReason, GatewayEvent, ReasoningDelta,
|
||||
ResponseMeta, TextDelta, ToolCallDelta,
|
||||
};
|
||||
use gateway_protocol::openai::sse::encode_sse_event;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::error::ResponseEncodeError;
|
||||
|
||||
/// 同一 canonical event 流生成的两种 Responses 表达。
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CollectedResponses {
|
||||
response: Value,
|
||||
sse_frames: Vec<String>,
|
||||
}
|
||||
|
||||
impl CollectedResponses {
|
||||
/// 返回非流式 Responses JSON。
|
||||
#[must_use]
|
||||
pub const fn response(&self) -> &Value {
|
||||
&self.response
|
||||
}
|
||||
|
||||
/// 返回按事件边界编码的 SSE frame。
|
||||
#[must_use]
|
||||
pub fn sse_frames(&self) -> &[String] {
|
||||
&self.sse_frames
|
||||
}
|
||||
|
||||
/// 拆分两种表达。
|
||||
#[must_use]
|
||||
pub fn into_parts(self) -> (Value, Vec<String>) {
|
||||
(self.response, self.sse_frames)
|
||||
}
|
||||
}
|
||||
|
||||
/// OpenAI Responses event collector。
|
||||
///
|
||||
/// Collector 只做协议编码;它不拥有 commit、retry 或 Provider 生命周期。
|
||||
#[derive(Debug)]
|
||||
pub struct ResponsesCollector {
|
||||
validator: EventSequenceValidator,
|
||||
created_at: u64,
|
||||
started: Option<ResponseMeta>,
|
||||
usage: Option<Usage>,
|
||||
output_positions: BTreeMap<u32, usize>,
|
||||
output: Vec<OutputState>,
|
||||
final_response: Option<Value>,
|
||||
}
|
||||
|
||||
impl ResponsesCollector {
|
||||
/// 创建 collector。`created_at` 是 logical request 冻结的 Unix 秒时间戳。
|
||||
#[must_use]
|
||||
pub fn new(created_at: u64) -> Self {
|
||||
Self {
|
||||
validator: EventSequenceValidator::new(),
|
||||
created_at,
|
||||
started: None,
|
||||
usage: None,
|
||||
output_positions: BTreeMap::new(),
|
||||
output: Vec::new(),
|
||||
final_response: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 消费一个 canonical event,并返回本次新产生的 SSE frames。
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 事件乱序、元数据变化、重复 usage 或出现 OpenAI Responses 无法表达的
|
||||
/// canonical 语义时返回 [`ResponseEncodeError`]。
|
||||
pub fn push(&mut self, event: &GatewayEvent) -> Result<Vec<String>, ResponseEncodeError> {
|
||||
if self.final_response.is_some() {
|
||||
return Err(ResponseEncodeError::AlreadyCompleted);
|
||||
}
|
||||
self.validator.observe(event)?;
|
||||
|
||||
match event {
|
||||
GatewayEvent::Started(meta) => self.started(meta),
|
||||
GatewayEvent::ContentAdded(item) => self.content_added(item),
|
||||
GatewayEvent::TextDelta(delta) => self.text_delta(delta),
|
||||
GatewayEvent::ReasoningDelta(delta) => self.reasoning_delta(delta),
|
||||
GatewayEvent::ToolCallDelta(delta) => self.tool_call_delta(delta),
|
||||
GatewayEvent::Usage(usage) => self.observe_usage(usage),
|
||||
GatewayEvent::CalculatedCost(_) | GatewayEvent::ProviderCost(_) => Ok(Vec::new()),
|
||||
GatewayEvent::Completed(meta) => self.completed(meta),
|
||||
_ => Err(ResponseEncodeError::UnsupportedEvent),
|
||||
}
|
||||
}
|
||||
|
||||
/// 消费一个 canonical event,并返回 Responses WebSocket 文本消息。
|
||||
///
|
||||
/// WebSocket 与 SSE 共用同一状态机和事件 JSON;这里只移除 SSE framing,
|
||||
/// 避免两个下游 transport 各自维护一套协议投影。
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 继承 [`Self::push`] 的 canonical 编码错误;内部 SSE framing 若不满足编码器
|
||||
/// 自身的不变量则返回 [`ResponseEncodeError::InvalidEventEncoding`]。
|
||||
pub fn push_websocket_events(
|
||||
&mut self,
|
||||
event: &GatewayEvent,
|
||||
) -> Result<Vec<String>, ResponseEncodeError> {
|
||||
self.push(event)?
|
||||
.into_iter()
|
||||
.map(|frame| {
|
||||
frame
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("data: "))
|
||||
.map(ToOwned::to_owned)
|
||||
.ok_or(ResponseEncodeError::InvalidEventEncoding)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 校验终态并返回非流式 JSON。
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Stream 未正常完成时返回事件顺序错误。
|
||||
pub fn finish(self) -> Result<Value, ResponseEncodeError> {
|
||||
self.validator.finish()?;
|
||||
self.final_response
|
||||
.ok_or_else(|| gateway_core::event::EventSequenceError::MissingCompleted.into())
|
||||
}
|
||||
|
||||
/// 一次性收集完整事件序列,同时保留 stateful collector 的相同实现路径。
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 任意事件无法编码或序列不完整时返回错误。
|
||||
pub fn collect<'a>(
|
||||
created_at: u64,
|
||||
events: impl IntoIterator<Item = &'a GatewayEvent>,
|
||||
) -> Result<CollectedResponses, ResponseEncodeError> {
|
||||
let mut collector = Self::new(created_at);
|
||||
let mut sse_frames = Vec::new();
|
||||
for event in events {
|
||||
sse_frames.extend(collector.push(event)?);
|
||||
}
|
||||
let response = collector.finish()?;
|
||||
Ok(CollectedResponses {
|
||||
response,
|
||||
sse_frames,
|
||||
})
|
||||
}
|
||||
|
||||
fn started(&mut self, meta: &ResponseMeta) -> Result<Vec<String>, ResponseEncodeError> {
|
||||
self.started = Some(meta.clone());
|
||||
let response = response_base(
|
||||
meta,
|
||||
self.created_at,
|
||||
"in_progress",
|
||||
Value::Null,
|
||||
Vec::new(),
|
||||
Value::Null,
|
||||
);
|
||||
Ok(vec![sse_frame(
|
||||
"response.created",
|
||||
json!({
|
||||
"type": "response.created",
|
||||
"response": response,
|
||||
}),
|
||||
)])
|
||||
}
|
||||
|
||||
fn content_added(&mut self, item: &ContentItem) -> Result<Vec<String>, ResponseEncodeError> {
|
||||
let started = self
|
||||
.started
|
||||
.as_ref()
|
||||
.ok_or(gateway_core::event::EventSequenceError::MissingStarted)?;
|
||||
let output_index = self.output.len();
|
||||
let id = deterministic_output_id(started.response_id(), item.index(), item.kind());
|
||||
let state = match item.kind() {
|
||||
ContentKind::Text => OutputState::Text {
|
||||
id,
|
||||
text: String::new(),
|
||||
},
|
||||
ContentKind::Reasoning => OutputState::Reasoning {
|
||||
id,
|
||||
text: String::new(),
|
||||
},
|
||||
ContentKind::ToolCall => OutputState::ToolCall {
|
||||
canonical_index: item.index(),
|
||||
id,
|
||||
call_id: None,
|
||||
name: None,
|
||||
arguments: String::new(),
|
||||
published: false,
|
||||
},
|
||||
ContentKind::Image => {
|
||||
return Err(ResponseEncodeError::UnsupportedContentKind { kind: "image" });
|
||||
}
|
||||
ContentKind::Audio => {
|
||||
return Err(ResponseEncodeError::UnsupportedContentKind { kind: "audio" });
|
||||
}
|
||||
_ => {
|
||||
return Err(ResponseEncodeError::UnsupportedContentKind { kind: "unknown" });
|
||||
}
|
||||
};
|
||||
self.output_positions.insert(item.index(), output_index);
|
||||
let frames = state.added_frames(output_index);
|
||||
self.output.push(state);
|
||||
Ok(frames)
|
||||
}
|
||||
|
||||
fn text_delta(&mut self, delta: &TextDelta) -> Result<Vec<String>, ResponseEncodeError> {
|
||||
let output_index = self.position(delta.content_index)?;
|
||||
let OutputState::Text { id, text, .. } = &mut self.output[output_index] else {
|
||||
return Err(
|
||||
gateway_core::event::EventSequenceError::InvalidDeltaTarget {
|
||||
index: delta.content_index,
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
};
|
||||
text.push_str(&delta.text);
|
||||
Ok(vec![sse_frame(
|
||||
"response.output_text.delta",
|
||||
json!({
|
||||
"type": "response.output_text.delta",
|
||||
"item_id": id,
|
||||
"output_index": output_index,
|
||||
"content_index": 0,
|
||||
"delta": &delta.text,
|
||||
}),
|
||||
)])
|
||||
}
|
||||
|
||||
fn reasoning_delta(
|
||||
&mut self,
|
||||
delta: &ReasoningDelta,
|
||||
) -> Result<Vec<String>, ResponseEncodeError> {
|
||||
let output_index = self.position(delta.content_index)?;
|
||||
let OutputState::Reasoning { id, text, .. } = &mut self.output[output_index] else {
|
||||
return Err(
|
||||
gateway_core::event::EventSequenceError::InvalidDeltaTarget {
|
||||
index: delta.content_index,
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
};
|
||||
text.push_str(&delta.text);
|
||||
Ok(vec![sse_frame(
|
||||
"response.reasoning_summary_text.delta",
|
||||
json!({
|
||||
"type": "response.reasoning_summary_text.delta",
|
||||
"item_id": id,
|
||||
"output_index": output_index,
|
||||
"summary_index": 0,
|
||||
"delta": &delta.text,
|
||||
}),
|
||||
)])
|
||||
}
|
||||
|
||||
fn tool_call_delta(
|
||||
&mut self,
|
||||
delta: &ToolCallDelta,
|
||||
) -> Result<Vec<String>, ResponseEncodeError> {
|
||||
let output_index = self.position(delta.content_index)?;
|
||||
let OutputState::ToolCall {
|
||||
canonical_index,
|
||||
id,
|
||||
call_id,
|
||||
name,
|
||||
arguments,
|
||||
published,
|
||||
} = &mut self.output[output_index]
|
||||
else {
|
||||
return Err(
|
||||
gateway_core::event::EventSequenceError::InvalidDeltaTarget {
|
||||
index: delta.content_index,
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
};
|
||||
if delta.call_id.is_empty() {
|
||||
return Err(ResponseEncodeError::ToolIdentityChanged {
|
||||
index: *canonical_index,
|
||||
});
|
||||
}
|
||||
match call_id {
|
||||
Some(existing) if existing != &delta.call_id => {
|
||||
return Err(ResponseEncodeError::ToolIdentityChanged {
|
||||
index: *canonical_index,
|
||||
});
|
||||
}
|
||||
None => *call_id = Some(delta.call_id.clone()),
|
||||
Some(_) => {}
|
||||
}
|
||||
if let Some(delta_name) = &delta.name {
|
||||
if delta_name.is_empty() {
|
||||
return Err(ResponseEncodeError::MissingToolName {
|
||||
index: *canonical_index,
|
||||
});
|
||||
}
|
||||
match name {
|
||||
Some(existing) if existing != delta_name => {
|
||||
return Err(ResponseEncodeError::ToolIdentityChanged {
|
||||
index: *canonical_index,
|
||||
});
|
||||
}
|
||||
None => *name = Some(delta_name.clone()),
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
let mut frames = Vec::new();
|
||||
if !*published && name.is_some() {
|
||||
frames.push(sse_frame(
|
||||
"response.output_item.added",
|
||||
json!({
|
||||
"type": "response.output_item.added",
|
||||
"output_index": output_index,
|
||||
"item": tool_item(id, call_id.as_deref(), name.as_deref(), "", "in_progress"),
|
||||
}),
|
||||
));
|
||||
*published = true;
|
||||
if !arguments.is_empty() {
|
||||
frames.push(tool_arguments_delta_frame(id, output_index, arguments));
|
||||
}
|
||||
}
|
||||
arguments.push_str(&delta.arguments_delta);
|
||||
if *published && !delta.arguments_delta.is_empty() {
|
||||
frames.push(tool_arguments_delta_frame(
|
||||
id,
|
||||
output_index,
|
||||
&delta.arguments_delta,
|
||||
));
|
||||
}
|
||||
Ok(frames)
|
||||
}
|
||||
|
||||
fn observe_usage(&mut self, usage: &Usage) -> Result<Vec<String>, ResponseEncodeError> {
|
||||
if self.usage.is_some() {
|
||||
return Err(ResponseEncodeError::DuplicateUsage);
|
||||
}
|
||||
if usage.input_tokens.is_none()
|
||||
|| usage.output_tokens.is_none()
|
||||
|| usage.total_tokens.is_none()
|
||||
{
|
||||
return Err(ResponseEncodeError::IncompleteUsage);
|
||||
}
|
||||
self.usage = Some(usage.clone());
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
fn completed(&mut self, meta: &ResponseMeta) -> Result<Vec<String>, ResponseEncodeError> {
|
||||
let started = self
|
||||
.started
|
||||
.as_ref()
|
||||
.ok_or(gateway_core::event::EventSequenceError::MissingStarted)?;
|
||||
if started.response_id() != meta.response_id() || started.model() != meta.model() {
|
||||
return Err(ResponseEncodeError::MetadataChanged);
|
||||
}
|
||||
|
||||
let mut frames = Vec::new();
|
||||
for (output_index, state) in self.output.iter().enumerate() {
|
||||
frames.extend(state.done_frames(output_index)?);
|
||||
}
|
||||
let output = self
|
||||
.output
|
||||
.iter()
|
||||
.map(OutputState::completed_item)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let (status, terminal_event, incomplete_details) = terminal_status(meta.finish_reason());
|
||||
let usage = self.usage.as_ref().map_or(Ok(Value::Null), usage_json)?;
|
||||
let response = response_base(
|
||||
meta,
|
||||
self.created_at,
|
||||
status,
|
||||
incomplete_details,
|
||||
output,
|
||||
usage,
|
||||
);
|
||||
frames.push(sse_frame(
|
||||
terminal_event,
|
||||
json!({
|
||||
"type": terminal_event,
|
||||
"response": &response,
|
||||
}),
|
||||
));
|
||||
self.final_response = Some(response);
|
||||
Ok(frames)
|
||||
}
|
||||
|
||||
fn position(&self, canonical_index: u32) -> Result<usize, ResponseEncodeError> {
|
||||
self.output_positions
|
||||
.get(&canonical_index)
|
||||
.copied()
|
||||
.ok_or_else(|| {
|
||||
gateway_core::event::EventSequenceError::InvalidDeltaTarget {
|
||||
index: canonical_index,
|
||||
}
|
||||
.into()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum OutputState {
|
||||
Text {
|
||||
id: String,
|
||||
text: String,
|
||||
},
|
||||
Reasoning {
|
||||
id: String,
|
||||
text: String,
|
||||
},
|
||||
ToolCall {
|
||||
canonical_index: u32,
|
||||
id: String,
|
||||
call_id: Option<String>,
|
||||
name: Option<String>,
|
||||
arguments: String,
|
||||
published: bool,
|
||||
},
|
||||
}
|
||||
|
||||
impl OutputState {
|
||||
fn added_frames(&self, output_index: usize) -> Vec<String> {
|
||||
match self {
|
||||
Self::Text { id, .. } => vec![
|
||||
sse_frame(
|
||||
"response.output_item.added",
|
||||
json!({
|
||||
"type": "response.output_item.added",
|
||||
"output_index": output_index,
|
||||
"item": message_item(id, "in_progress", Vec::new()),
|
||||
}),
|
||||
),
|
||||
sse_frame(
|
||||
"response.content_part.added",
|
||||
json!({
|
||||
"type": "response.content_part.added",
|
||||
"item_id": id,
|
||||
"output_index": output_index,
|
||||
"content_index": 0,
|
||||
"part": output_text_part(""),
|
||||
}),
|
||||
),
|
||||
],
|
||||
Self::Reasoning { id, .. } => vec![
|
||||
sse_frame(
|
||||
"response.output_item.added",
|
||||
json!({
|
||||
"type": "response.output_item.added",
|
||||
"output_index": output_index,
|
||||
"item": reasoning_item_with_summary(id, Vec::new()),
|
||||
}),
|
||||
),
|
||||
sse_frame(
|
||||
"response.reasoning_summary_part.added",
|
||||
json!({
|
||||
"type": "response.reasoning_summary_part.added",
|
||||
"item_id": id,
|
||||
"output_index": output_index,
|
||||
"summary_index": 0,
|
||||
"part": summary_text_part(""),
|
||||
}),
|
||||
),
|
||||
],
|
||||
Self::ToolCall { .. } => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn done_frames(&self, output_index: usize) -> Result<Vec<String>, ResponseEncodeError> {
|
||||
match self {
|
||||
Self::Text { id, text, .. } => Ok(vec![
|
||||
sse_frame(
|
||||
"response.output_text.done",
|
||||
json!({
|
||||
"type": "response.output_text.done",
|
||||
"item_id": id,
|
||||
"output_index": output_index,
|
||||
"content_index": 0,
|
||||
"text": text,
|
||||
}),
|
||||
),
|
||||
sse_frame(
|
||||
"response.content_part.done",
|
||||
json!({
|
||||
"type": "response.content_part.done",
|
||||
"item_id": id,
|
||||
"output_index": output_index,
|
||||
"content_index": 0,
|
||||
"part": output_text_part(text),
|
||||
}),
|
||||
),
|
||||
sse_frame(
|
||||
"response.output_item.done",
|
||||
json!({
|
||||
"type": "response.output_item.done",
|
||||
"output_index": output_index,
|
||||
"item": text_item(id, text, "completed"),
|
||||
}),
|
||||
),
|
||||
]),
|
||||
Self::Reasoning { id, text, .. } => Ok(vec![
|
||||
sse_frame(
|
||||
"response.reasoning_summary_text.done",
|
||||
json!({
|
||||
"type": "response.reasoning_summary_text.done",
|
||||
"item_id": id,
|
||||
"output_index": output_index,
|
||||
"summary_index": 0,
|
||||
"text": text,
|
||||
}),
|
||||
),
|
||||
sse_frame(
|
||||
"response.reasoning_summary_part.done",
|
||||
json!({
|
||||
"type": "response.reasoning_summary_part.done",
|
||||
"item_id": id,
|
||||
"output_index": output_index,
|
||||
"summary_index": 0,
|
||||
"part": summary_text_part(text),
|
||||
}),
|
||||
),
|
||||
sse_frame(
|
||||
"response.output_item.done",
|
||||
json!({
|
||||
"type": "response.output_item.done",
|
||||
"output_index": output_index,
|
||||
"item": reasoning_item(id, text),
|
||||
}),
|
||||
),
|
||||
]),
|
||||
Self::ToolCall {
|
||||
canonical_index,
|
||||
id,
|
||||
call_id,
|
||||
name,
|
||||
arguments,
|
||||
published,
|
||||
} => {
|
||||
let name = name
|
||||
.as_deref()
|
||||
.ok_or(ResponseEncodeError::MissingToolName {
|
||||
index: *canonical_index,
|
||||
})?;
|
||||
let call_id =
|
||||
call_id
|
||||
.as_deref()
|
||||
.ok_or(ResponseEncodeError::ToolIdentityChanged {
|
||||
index: *canonical_index,
|
||||
})?;
|
||||
let mut frames = Vec::new();
|
||||
if !published {
|
||||
frames.push(sse_frame(
|
||||
"response.output_item.added",
|
||||
json!({
|
||||
"type": "response.output_item.added",
|
||||
"output_index": output_index,
|
||||
"item": tool_item(id, Some(call_id), Some(name), "", "in_progress"),
|
||||
}),
|
||||
));
|
||||
if !arguments.is_empty() {
|
||||
frames.push(tool_arguments_delta_frame(id, output_index, arguments));
|
||||
}
|
||||
}
|
||||
frames.push(sse_frame(
|
||||
"response.function_call_arguments.done",
|
||||
json!({
|
||||
"type": "response.function_call_arguments.done",
|
||||
"item_id": id,
|
||||
"output_index": output_index,
|
||||
"arguments": arguments,
|
||||
}),
|
||||
));
|
||||
frames.push(sse_frame(
|
||||
"response.output_item.done",
|
||||
json!({
|
||||
"type": "response.output_item.done",
|
||||
"output_index": output_index,
|
||||
"item": tool_item(
|
||||
id,
|
||||
Some(call_id),
|
||||
Some(name),
|
||||
arguments,
|
||||
"completed",
|
||||
),
|
||||
}),
|
||||
));
|
||||
Ok(frames)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn completed_item(&self) -> Result<Value, ResponseEncodeError> {
|
||||
match self {
|
||||
Self::Text { id, text, .. } => Ok(text_item(id, text, "completed")),
|
||||
Self::Reasoning { id, text, .. } => Ok(reasoning_item(id, text)),
|
||||
Self::ToolCall {
|
||||
canonical_index,
|
||||
id,
|
||||
call_id,
|
||||
name,
|
||||
arguments,
|
||||
..
|
||||
} => Ok(tool_item(
|
||||
id,
|
||||
Some(
|
||||
call_id
|
||||
.as_deref()
|
||||
.ok_or(ResponseEncodeError::ToolIdentityChanged {
|
||||
index: *canonical_index,
|
||||
})?,
|
||||
),
|
||||
Some(
|
||||
name.as_deref()
|
||||
.ok_or(ResponseEncodeError::MissingToolName {
|
||||
index: *canonical_index,
|
||||
})?,
|
||||
),
|
||||
arguments,
|
||||
"completed",
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn terminal_status(finish_reason: Option<FinishReason>) -> (&'static str, &'static str, Value) {
|
||||
match finish_reason {
|
||||
Some(FinishReason::Length) => (
|
||||
"incomplete",
|
||||
"response.incomplete",
|
||||
json!({ "reason": "max_output_tokens" }),
|
||||
),
|
||||
Some(FinishReason::ContentFilter) => (
|
||||
"incomplete",
|
||||
"response.incomplete",
|
||||
json!({ "reason": "content_filter" }),
|
||||
),
|
||||
_ => ("completed", "response.completed", Value::Null),
|
||||
}
|
||||
}
|
||||
|
||||
fn response_base(
|
||||
meta: &ResponseMeta,
|
||||
created_at: u64,
|
||||
status: &str,
|
||||
incomplete_details: Value,
|
||||
output: Vec<Value>,
|
||||
usage: Value,
|
||||
) -> Value {
|
||||
json!({
|
||||
"id": meta.response_id(),
|
||||
"object": "response",
|
||||
"created_at": created_at,
|
||||
"status": status,
|
||||
"error": null,
|
||||
"incomplete_details": incomplete_details,
|
||||
"model": meta.model(),
|
||||
"output": output,
|
||||
"usage": usage,
|
||||
})
|
||||
}
|
||||
|
||||
fn usage_json(usage: &Usage) -> Result<Value, ResponseEncodeError> {
|
||||
let input_tokens = usage
|
||||
.input_tokens
|
||||
.ok_or(ResponseEncodeError::IncompleteUsage)?;
|
||||
let output_tokens = usage
|
||||
.output_tokens
|
||||
.ok_or(ResponseEncodeError::IncompleteUsage)?;
|
||||
let total_tokens = usage
|
||||
.total_tokens
|
||||
.ok_or(ResponseEncodeError::IncompleteUsage)?;
|
||||
let mut object = Map::new();
|
||||
object.insert("input_tokens".to_owned(), json!(input_tokens));
|
||||
object.insert("output_tokens".to_owned(), json!(output_tokens));
|
||||
object.insert("total_tokens".to_owned(), json!(total_tokens));
|
||||
let mut input_details = Map::new();
|
||||
if let Some(cached_tokens) = usage.cached_tokens {
|
||||
input_details.insert("cached_tokens".to_owned(), json!(cached_tokens));
|
||||
}
|
||||
if let Some(cache_write_tokens) = usage.cache_write_tokens {
|
||||
input_details.insert("cache_write_tokens".to_owned(), json!(cache_write_tokens));
|
||||
}
|
||||
if !input_details.is_empty() {
|
||||
object.insert(
|
||||
"input_tokens_details".to_owned(),
|
||||
Value::Object(input_details),
|
||||
);
|
||||
}
|
||||
if let Some(reasoning_tokens) = usage.reasoning_tokens {
|
||||
object.insert(
|
||||
"output_tokens_details".to_owned(),
|
||||
json!({ "reasoning_tokens": reasoning_tokens }),
|
||||
);
|
||||
}
|
||||
Ok(Value::Object(object))
|
||||
}
|
||||
|
||||
fn text_item(id: &str, text: &str, status: &str) -> Value {
|
||||
message_item(id, status, vec![output_text_part(text)])
|
||||
}
|
||||
|
||||
fn message_item(id: &str, status: &str, content: Vec<Value>) -> Value {
|
||||
json!({
|
||||
"id": id,
|
||||
"type": "message",
|
||||
"status": status,
|
||||
"role": "assistant",
|
||||
"content": content,
|
||||
})
|
||||
}
|
||||
|
||||
fn output_text_part(text: &str) -> Value {
|
||||
json!({
|
||||
"type": "output_text",
|
||||
"text": text,
|
||||
"annotations": [],
|
||||
})
|
||||
}
|
||||
|
||||
fn reasoning_item(id: &str, text: &str) -> Value {
|
||||
reasoning_item_with_summary(id, vec![summary_text_part(text)])
|
||||
}
|
||||
|
||||
fn reasoning_item_with_summary(id: &str, summary: Vec<Value>) -> Value {
|
||||
json!({
|
||||
"id": id,
|
||||
"type": "reasoning",
|
||||
"summary": summary,
|
||||
})
|
||||
}
|
||||
|
||||
fn summary_text_part(text: &str) -> Value {
|
||||
json!({
|
||||
"type": "summary_text",
|
||||
"text": text,
|
||||
})
|
||||
}
|
||||
|
||||
fn tool_item(
|
||||
id: &str,
|
||||
call_id: Option<&str>,
|
||||
name: Option<&str>,
|
||||
arguments: &str,
|
||||
status: &str,
|
||||
) -> Value {
|
||||
json!({
|
||||
"id": id,
|
||||
"type": "function_call",
|
||||
"status": status,
|
||||
"call_id": call_id,
|
||||
"name": name,
|
||||
"arguments": arguments,
|
||||
})
|
||||
}
|
||||
|
||||
fn tool_arguments_delta_frame(id: &str, output_index: usize, delta: &str) -> String {
|
||||
sse_frame(
|
||||
"response.function_call_arguments.delta",
|
||||
json!({
|
||||
"type": "response.function_call_arguments.delta",
|
||||
"item_id": id,
|
||||
"output_index": output_index,
|
||||
"delta": delta,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn sse_frame(event: &str, payload: Value) -> String {
|
||||
encode_sse_event(event, &payload.to_string())
|
||||
}
|
||||
|
||||
fn deterministic_output_id(response_id: &str, index: u32, kind: ContentKind) -> String {
|
||||
let prefix = match kind {
|
||||
ContentKind::Text => "msg",
|
||||
ContentKind::Reasoning => "rs",
|
||||
ContentKind::ToolCall => "fc",
|
||||
ContentKind::Image => "img",
|
||||
ContentKind::Audio => "audio",
|
||||
_ => "item",
|
||||
};
|
||||
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
|
||||
for byte in response_id
|
||||
.bytes()
|
||||
.chain(index.to_be_bytes())
|
||||
.chain(kind_tag(kind))
|
||||
{
|
||||
hash ^= u64::from(byte);
|
||||
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
format!("{prefix}_{hash:016x}")
|
||||
}
|
||||
|
||||
fn kind_tag(kind: ContentKind) -> [u8; 1] {
|
||||
let tag = match kind {
|
||||
ContentKind::Text => 1,
|
||||
ContentKind::Reasoning => 2,
|
||||
ContentKind::ToolCall => 3,
|
||||
ContentKind::Image => 4,
|
||||
ContentKind::Audio => 5,
|
||||
_ => u8::MAX,
|
||||
};
|
||||
[tag]
|
||||
}
|
||||
@@ -0,0 +1,605 @@
|
||||
//! OpenAI Responses WebSocket adapter。
|
||||
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
|
||||
use axum::{
|
||||
extract::{
|
||||
Extension, State,
|
||||
connect_info::ConnectInfo,
|
||||
ws::{CloseFrame, Message, WebSocket, WebSocketUpgrade, close_code},
|
||||
},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use futures::StreamExt;
|
||||
use gateway_core::engine::{CommitRequirement, EngineError};
|
||||
use gateway_core::error::{GatewayError, GatewayErrorKind};
|
||||
use gateway_core::event::GatewayEvent;
|
||||
use serde_json::{Map, Value, json};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::openai::{
|
||||
auth::{authenticate_client, authentication_error_response},
|
||||
error::{gateway_error_contract, gateway_error_from_engine, runtime_unavailable_response},
|
||||
router::MAX_CLIENT_REQUEST_BODY_BYTES,
|
||||
service::{
|
||||
DeliveryEvent, OpenAiApiState, OpenAiClientService, ResponseExecutionSession,
|
||||
ResponsesTransport, StartedResponse,
|
||||
},
|
||||
};
|
||||
|
||||
use super::{
|
||||
DecodedResponsesRequest, ProtocolErrorBody, RequestDecodeError, ResponsesCollector,
|
||||
decode_request,
|
||||
http::{PendingExecution, request_client_context},
|
||||
};
|
||||
|
||||
const ACTIVE_RESPONSE_VIOLATION: &str = "Only one response.create may be active per connection";
|
||||
const TEXT_FRAMES_ONLY: &str = "Responses WebSocket accepts text frames only";
|
||||
|
||||
/// 将已认证的 `GET /v1/responses` 升级为 Responses WebSocket。
|
||||
pub async fn responses_websocket<S>(
|
||||
State(state): State<S>,
|
||||
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
|
||||
headers: HeaderMap,
|
||||
websocket: WebSocketUpgrade,
|
||||
) -> Response
|
||||
where
|
||||
S: OpenAiApiState,
|
||||
{
|
||||
let service = state.openai_client_api();
|
||||
let client = match authenticate_client(&service, &headers) {
|
||||
Ok(client) => client,
|
||||
Err(error) => return authentication_error_response(error),
|
||||
};
|
||||
let (client_ip, user_agent) = request_client_context(
|
||||
&headers,
|
||||
connect_info.map(|Extension(ConnectInfo(address))| address),
|
||||
);
|
||||
ResponsesWebSocketAdapter::new(service)
|
||||
.upgrade_with_client_context(websocket, client, client_ip, user_agent)
|
||||
}
|
||||
|
||||
/// 已鉴权 Responses WebSocket 升级边界。
|
||||
#[derive(Clone)]
|
||||
pub struct ResponsesWebSocketAdapter<S> {
|
||||
service: S,
|
||||
}
|
||||
|
||||
impl<S> ResponsesWebSocketAdapter<S>
|
||||
where
|
||||
S: OpenAiClientService,
|
||||
{
|
||||
/// 绑定应用提供的唯一 OpenAI 客户端服务端口。
|
||||
#[must_use]
|
||||
pub const fn new(service: S) -> Self {
|
||||
Self { service }
|
||||
}
|
||||
|
||||
/// 升级一个已认证的请求;明文 API key 不进入长连接 session。
|
||||
#[must_use]
|
||||
pub fn upgrade(&self, websocket: WebSocketUpgrade, client: S::Client) -> Response {
|
||||
self.upgrade_with_client_context(websocket, client, None, None)
|
||||
}
|
||||
|
||||
fn upgrade_with_client_context(
|
||||
&self,
|
||||
websocket: WebSocketUpgrade,
|
||||
client: S::Client,
|
||||
client_ip: Option<IpAddr>,
|
||||
user_agent: Option<String>,
|
||||
) -> Response {
|
||||
if self.service.is_shutting_down() {
|
||||
return runtime_unavailable_response().into_response();
|
||||
}
|
||||
let session = ResponsesWebSocketSession {
|
||||
service: self.service.clone(),
|
||||
client,
|
||||
connection_id: self.service.next_connection_id(),
|
||||
client_ip,
|
||||
user_agent,
|
||||
};
|
||||
let lifecycle = self.service.clone();
|
||||
websocket
|
||||
.max_message_size(MAX_CLIENT_REQUEST_BODY_BYTES)
|
||||
.max_frame_size(MAX_CLIENT_REQUEST_BODY_BYTES)
|
||||
.on_upgrade(move |socket| async move {
|
||||
lifecycle.spawn_connection(Box::pin(serve_responses_websocket(socket, session)));
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ResponsesWebSocketSession<S>
|
||||
where
|
||||
S: OpenAiClientService,
|
||||
{
|
||||
service: S,
|
||||
client: S::Client,
|
||||
connection_id: String,
|
||||
client_ip: Option<IpAddr>,
|
||||
user_agent: Option<String>,
|
||||
}
|
||||
|
||||
async fn serve_responses_websocket<S>(mut socket: WebSocket, session: ResponsesWebSocketSession<S>)
|
||||
where
|
||||
S: OpenAiClientService,
|
||||
{
|
||||
tracing::info!(
|
||||
websocket_connection_id = %session.connection_id,
|
||||
"Responses WebSocket connected"
|
||||
);
|
||||
let mut request_count = 0_u64;
|
||||
|
||||
while let Some(message) = socket.next().await {
|
||||
let payload = match message {
|
||||
Ok(Message::Text(payload)) => payload,
|
||||
Ok(Message::Ping(_) | Message::Pong(_)) => continue,
|
||||
Ok(Message::Close(_)) => break,
|
||||
Ok(Message::Binary(_)) => {
|
||||
close_for_protocol_violation(&mut socket, TEXT_FRAMES_ONLY).await;
|
||||
break;
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::info!(
|
||||
websocket_connection_id = %session.connection_id,
|
||||
error = %error,
|
||||
"Responses WebSocket receive failed"
|
||||
);
|
||||
break;
|
||||
}
|
||||
};
|
||||
request_count = request_count.saturating_add(1);
|
||||
let correlation_id = session.service.next_request_id();
|
||||
let decoded = match decode_response_create(payload.as_str()) {
|
||||
Ok(decoded) => {
|
||||
decoded.with_client_context(session.client_ip, session.user_agent.clone())
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::info!(
|
||||
websocket_connection_id = %session.connection_id,
|
||||
request_id = %correlation_id,
|
||||
error = %error,
|
||||
"Responses WebSocket request rejected"
|
||||
);
|
||||
if send_protocol_error(
|
||||
&mut socket,
|
||||
StatusCode::BAD_REQUEST,
|
||||
error.protocol_body(),
|
||||
&correlation_id,
|
||||
)
|
||||
.await
|
||||
== ForwardOutcome::Disconnect
|
||||
{
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let started = match session
|
||||
.service
|
||||
.start_response(
|
||||
session.client.clone(),
|
||||
decoded,
|
||||
ResponsesTransport::WebSocket,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(started) => started,
|
||||
Err(error) => {
|
||||
if send_gateway_error(&mut socket, &error, &correlation_id).await
|
||||
== ForwardOutcome::Disconnect
|
||||
{
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if forward_execution(&mut socket, started).await == ForwardOutcome::Disconnect {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
websocket_connection_id = %session.connection_id,
|
||||
request_count,
|
||||
"Responses WebSocket disconnected"
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum ForwardOutcome {
|
||||
Continue,
|
||||
Disconnect,
|
||||
}
|
||||
|
||||
async fn forward_execution<S>(socket: &mut WebSocket, started: StartedResponse<S>) -> ForwardOutcome
|
||||
where
|
||||
S: ResponseExecutionSession,
|
||||
{
|
||||
let request_id = started.request_id().to_owned();
|
||||
let (session, created_at, streaming) = started.into_parts();
|
||||
let mut execution = PendingExecution::new(session);
|
||||
if !streaming {
|
||||
let error = GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"WebSocket execution was not initialized as a stream",
|
||||
);
|
||||
return send_gateway_error(socket, &error, &request_id).await;
|
||||
}
|
||||
let first = loop {
|
||||
match next_active_input(socket, &mut execution).await {
|
||||
ActiveInput::Event(Ok(Some(event))) => break event,
|
||||
ActiveInput::Event(Ok(None)) => {
|
||||
let error = GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"gateway response ended before its first event",
|
||||
);
|
||||
return send_gateway_error(socket, &error, &request_id).await;
|
||||
}
|
||||
ActiveInput::Event(Err(error)) => {
|
||||
let error = gateway_error_from_engine(&error);
|
||||
return send_gateway_error(socket, &error, &request_id).await;
|
||||
}
|
||||
ActiveInput::Control => continue,
|
||||
ActiveInput::Disconnect => return ForwardOutcome::Disconnect,
|
||||
ActiveInput::ProtocolViolation => {
|
||||
close_for_protocol_violation(socket, ACTIVE_RESPONSE_VIOLATION).await;
|
||||
return ForwardOutcome::Disconnect;
|
||||
}
|
||||
}
|
||||
};
|
||||
let (first, requirement) = first.into_parts();
|
||||
if requirement != CommitRequirement::CommitBeforeDelivery {
|
||||
let error = GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"gateway first event did not require commit",
|
||||
);
|
||||
return send_gateway_error(socket, &error, &request_id).await;
|
||||
}
|
||||
let mut collector = ResponsesCollector::new(created_at);
|
||||
let first_messages = match collector.push_websocket_events(&first) {
|
||||
Ok(messages) if !messages.is_empty() => messages,
|
||||
Ok(_) => {
|
||||
let error = GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"gateway first event encoded no WebSocket message",
|
||||
);
|
||||
return send_gateway_error(socket, &error, &request_id).await;
|
||||
}
|
||||
Err(error) => {
|
||||
return send_protocol_error(
|
||||
socket,
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
error.protocol_body(),
|
||||
&request_id,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
};
|
||||
let Some(response_session) = execution.session_mut() else {
|
||||
return ForwardOutcome::Disconnect;
|
||||
};
|
||||
if let Err(error) = response_session.commit_downstream(None).await {
|
||||
let error = gateway_error_from_engine(&error);
|
||||
return send_gateway_error(socket, &error, &request_id).await;
|
||||
}
|
||||
if !send_text(socket, response_metadata_event(&request_id)).await
|
||||
|| !send_messages(socket, first_messages).await
|
||||
{
|
||||
return ForwardOutcome::Disconnect;
|
||||
}
|
||||
|
||||
loop {
|
||||
match next_active_input(socket, &mut execution).await {
|
||||
ActiveInput::Event(Ok(Some(delivery))) => {
|
||||
let (event, requirement) = delivery.into_parts();
|
||||
if requirement != CommitRequirement::AlreadyCommitted {
|
||||
let error = GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"gateway requested another downstream commit",
|
||||
);
|
||||
return send_gateway_error(socket, &error, &request_id).await;
|
||||
}
|
||||
let terminal = matches!(event, GatewayEvent::Completed(_));
|
||||
let messages = match collector.push_websocket_events(&event) {
|
||||
Ok(messages) => messages,
|
||||
Err(error) => {
|
||||
return send_protocol_error(
|
||||
socket,
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
error.protocol_body(),
|
||||
&request_id,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
};
|
||||
if terminal {
|
||||
if collector.finish().is_err() {
|
||||
let error = GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"gateway terminal event did not finish the response encoder",
|
||||
);
|
||||
return send_gateway_error(socket, &error, &request_id).await;
|
||||
}
|
||||
loop {
|
||||
match next_active_input(socket, &mut execution).await {
|
||||
ActiveInput::Event(Ok(None))
|
||||
if execution
|
||||
.session_mut()
|
||||
.is_some_and(|session| session.is_finalized()) =>
|
||||
{
|
||||
break;
|
||||
}
|
||||
ActiveInput::Event(Ok(None)) => {
|
||||
let error = GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"gateway response was not finalized after its terminal event",
|
||||
);
|
||||
return send_gateway_error(socket, &error, &request_id).await;
|
||||
}
|
||||
ActiveInput::Event(Ok(Some(_))) => {
|
||||
let error = GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"gateway response continued after its terminal event",
|
||||
);
|
||||
return send_gateway_error(socket, &error, &request_id).await;
|
||||
}
|
||||
ActiveInput::Event(Err(error)) => {
|
||||
let error = gateway_error_from_engine(&error);
|
||||
return send_gateway_error(socket, &error, &request_id).await;
|
||||
}
|
||||
ActiveInput::Control => {}
|
||||
ActiveInput::Disconnect => return ForwardOutcome::Disconnect,
|
||||
ActiveInput::ProtocolViolation => {
|
||||
close_for_protocol_violation(socket, ACTIVE_RESPONSE_VIOLATION)
|
||||
.await;
|
||||
return ForwardOutcome::Disconnect;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !send_messages(socket, messages).await {
|
||||
return ForwardOutcome::Disconnect;
|
||||
}
|
||||
execution.disarm();
|
||||
return ForwardOutcome::Continue;
|
||||
}
|
||||
if !send_messages(socket, messages).await {
|
||||
return ForwardOutcome::Disconnect;
|
||||
}
|
||||
}
|
||||
ActiveInput::Event(Ok(None)) => {
|
||||
let error = GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"gateway response ended without a terminal event",
|
||||
);
|
||||
return send_gateway_error(socket, &error, &request_id).await;
|
||||
}
|
||||
ActiveInput::Event(Err(error)) => {
|
||||
let error = gateway_error_from_engine(&error);
|
||||
return send_gateway_error(socket, &error, &request_id).await;
|
||||
}
|
||||
ActiveInput::Control => {}
|
||||
ActiveInput::Disconnect => return ForwardOutcome::Disconnect,
|
||||
ActiveInput::ProtocolViolation => {
|
||||
close_for_protocol_violation(socket, ACTIVE_RESPONSE_VIOLATION).await;
|
||||
return ForwardOutcome::Disconnect;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum ActiveInput {
|
||||
Event(Result<Option<DeliveryEvent>, EngineError>),
|
||||
Control,
|
||||
Disconnect,
|
||||
ProtocolViolation,
|
||||
}
|
||||
|
||||
async fn next_active_input<S>(
|
||||
socket: &mut WebSocket,
|
||||
execution: &mut PendingExecution<S>,
|
||||
) -> ActiveInput
|
||||
where
|
||||
S: ResponseExecutionSession,
|
||||
{
|
||||
let Some(session) = execution.session_mut() else {
|
||||
return ActiveInput::Disconnect;
|
||||
};
|
||||
tokio::select! {
|
||||
event = session.next_delivery_event() => ActiveInput::Event(event),
|
||||
message = socket.next() => match message {
|
||||
Some(Ok(Message::Ping(_) | Message::Pong(_))) => ActiveInput::Control,
|
||||
Some(Ok(Message::Close(_))) | None | Some(Err(_)) => ActiveInput::Disconnect,
|
||||
Some(Ok(Message::Text(_) | Message::Binary(_))) => ActiveInput::ProtocolViolation,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// 解码一个官方 `response.create` 文本帧。
|
||||
///
|
||||
/// 缺省 `stream` 等价于 WebSocket 固有的流式语义;显式 `false` 会被拒绝。
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 帧不是合法 JSON object、消息类型错误、显式关闭 stream,或 Responses 请求
|
||||
/// 无法映射到 canonical operation 时返回不包含正文内容的稳定错误。
|
||||
pub fn decode_response_create(
|
||||
payload: &str,
|
||||
) -> Result<DecodedResponsesRequest, ResponseCreateFrameError> {
|
||||
let Value::Object(mut body) = serde_json::from_str::<Value>(payload)
|
||||
.map_err(|_| ResponseCreateFrameError::InvalidJson)?
|
||||
else {
|
||||
return Err(ResponseCreateFrameError::ExpectedObject);
|
||||
};
|
||||
match body.remove("type") {
|
||||
Some(Value::String(message_type)) if message_type == "response.create" => {}
|
||||
_ => return Err(ResponseCreateFrameError::UnsupportedType),
|
||||
}
|
||||
match body.get("stream") {
|
||||
Some(Value::Bool(true)) => {}
|
||||
Some(Value::Bool(false)) => return Err(ResponseCreateFrameError::StreamingRequired),
|
||||
Some(_) => {
|
||||
return Err(ResponseCreateFrameError::Request(
|
||||
RequestDecodeError::InvalidType {
|
||||
field: "stream".to_owned(),
|
||||
expected: "a boolean",
|
||||
},
|
||||
));
|
||||
}
|
||||
None => {
|
||||
body.insert("stream".to_owned(), Value::Bool(true));
|
||||
}
|
||||
}
|
||||
let encoded = serde_json::to_vec(&Value::Object(body))
|
||||
.map_err(|_| ResponseCreateFrameError::InvalidJson)?;
|
||||
decode_request(&encoded).map_err(ResponseCreateFrameError::Request)
|
||||
}
|
||||
|
||||
/// `response.create` 帧的稳定安全错误。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Error)]
|
||||
pub enum ResponseCreateFrameError {
|
||||
/// 文本不是合法 JSON。
|
||||
#[error("response.create frame must be valid JSON")]
|
||||
InvalidJson,
|
||||
/// 顶层不是 object。
|
||||
#[error("response.create frame must be a JSON object")]
|
||||
ExpectedObject,
|
||||
/// `type` 缺失或不是 `response.create`。
|
||||
#[error("unsupported Responses WebSocket message type")]
|
||||
UnsupportedType,
|
||||
/// WebSocket 请求显式声明 `stream=false`。
|
||||
#[error("Responses WebSocket requests require stream=true")]
|
||||
StreamingRequired,
|
||||
/// 内层 Responses 请求无法映射到 canonical operation。
|
||||
#[error(transparent)]
|
||||
Request(RequestDecodeError),
|
||||
}
|
||||
|
||||
impl ResponseCreateFrameError {
|
||||
fn protocol_body(&self) -> ProtocolErrorBody {
|
||||
match self {
|
||||
Self::Request(error) => error.protocol_body(),
|
||||
Self::InvalidJson => RequestDecodeError::MalformedJson.protocol_body(),
|
||||
Self::ExpectedObject => RequestDecodeError::ExpectedObject.protocol_body(),
|
||||
Self::UnsupportedType => RequestDecodeError::InvalidValue {
|
||||
field: "type".to_owned(),
|
||||
}
|
||||
.protocol_body(),
|
||||
Self::StreamingRequired => RequestDecodeError::InvalidValue {
|
||||
field: "stream".to_owned(),
|
||||
}
|
||||
.protocol_body(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn response_metadata_event(request_id: &str) -> String {
|
||||
json!({
|
||||
"type": "response.metadata",
|
||||
"headers": {"x-request-id": request_id},
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
async fn send_gateway_error(
|
||||
socket: &mut WebSocket,
|
||||
error: &GatewayError,
|
||||
request_id: &str,
|
||||
) -> ForwardOutcome {
|
||||
let (status, error_type, code) = gateway_error_contract(error.kind());
|
||||
if send_error_event(
|
||||
socket,
|
||||
status,
|
||||
error_type,
|
||||
code,
|
||||
error.safe_message(),
|
||||
None,
|
||||
request_id,
|
||||
)
|
||||
.await
|
||||
{
|
||||
ForwardOutcome::Continue
|
||||
} else {
|
||||
ForwardOutcome::Disconnect
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_protocol_error(
|
||||
socket: &mut WebSocket,
|
||||
status: StatusCode,
|
||||
body: ProtocolErrorBody,
|
||||
request_id: &str,
|
||||
) -> ForwardOutcome {
|
||||
let error = body.error;
|
||||
if send_error_event(
|
||||
socket,
|
||||
status,
|
||||
error.kind,
|
||||
error.code,
|
||||
&error.message,
|
||||
error.param.as_deref(),
|
||||
request_id,
|
||||
)
|
||||
.await
|
||||
{
|
||||
ForwardOutcome::Continue
|
||||
} else {
|
||||
ForwardOutcome::Disconnect
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_error_event(
|
||||
socket: &mut WebSocket,
|
||||
status: StatusCode,
|
||||
error_type: &str,
|
||||
code: &str,
|
||||
message: &str,
|
||||
param: Option<&str>,
|
||||
request_id: &str,
|
||||
) -> bool {
|
||||
let mut error = Map::new();
|
||||
error.insert("type".to_owned(), Value::String(error_type.to_owned()));
|
||||
error.insert("code".to_owned(), Value::String(code.to_owned()));
|
||||
error.insert("message".to_owned(), Value::String(message.to_owned()));
|
||||
if let Some(param) = param {
|
||||
error.insert("param".to_owned(), Value::String(param.to_owned()));
|
||||
}
|
||||
send_text(
|
||||
socket,
|
||||
json!({
|
||||
"type": "error",
|
||||
"status": status.as_u16(),
|
||||
"error": error,
|
||||
"request_id": request_id,
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn send_messages(socket: &mut WebSocket, messages: Vec<String>) -> bool {
|
||||
for message in messages {
|
||||
if !send_text(socket, message).await {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
async fn send_text(socket: &mut WebSocket, payload: String) -> bool {
|
||||
if let Err(error) = socket.send(Message::Text(payload.into())).await {
|
||||
tracing::info!(error = %error, "Responses WebSocket send failed");
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
async fn close_for_protocol_violation(socket: &mut WebSocket, reason: &'static str) {
|
||||
let _ = socket
|
||||
.send(Message::Close(Some(CloseFrame {
|
||||
code: close_code::POLICY,
|
||||
reason: reason.into(),
|
||||
})))
|
||||
.await;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
//! OpenAI 客户端协议路由。
|
||||
|
||||
use axum::{Router, extract::DefaultBodyLimit, routing::get};
|
||||
|
||||
use super::{
|
||||
models::{model_detail, models},
|
||||
responses::{responses, responses_websocket},
|
||||
service::OpenAiApiState,
|
||||
};
|
||||
|
||||
/// OpenAI 请求正文上限。
|
||||
pub const MAX_CLIENT_REQUEST_BODY_BYTES: usize = 16 * 1024 * 1024;
|
||||
|
||||
/// 构造 OpenAI 客户端协议路由。
|
||||
pub fn router<S>() -> Router<S>
|
||||
where
|
||||
S: OpenAiApiState,
|
||||
{
|
||||
Router::new()
|
||||
.route(
|
||||
"/v1/responses",
|
||||
get(responses_websocket::<S>).post(responses::<S>),
|
||||
)
|
||||
.route("/v1/models", get(models::<S>))
|
||||
// 官方 OpenAI 模型详情合同使用 path ID;它不属于 Admin API 约束。
|
||||
.route("/v1/models/{model_id}", get(model_detail::<S>))
|
||||
.layer(DefaultBodyLimit::max(MAX_CLIENT_REQUEST_BODY_BYTES))
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//! OpenAI HTTP adapter 与应用组合根之间的窄端口。
|
||||
|
||||
use std::{future::Future, pin::Pin};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use gateway_core::{
|
||||
engine::{CommitRequirement, EngineError},
|
||||
error::GatewayError,
|
||||
event::GatewayEvent,
|
||||
routing::PublicModelId,
|
||||
};
|
||||
|
||||
use super::{auth::ClientApiKeyAuthError, responses::DecodedResponsesRequest};
|
||||
|
||||
/// 由应用生命周期控制器接管的长连接任务。
|
||||
pub type ConnectionTask = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
|
||||
|
||||
/// Responses 请求使用的下游传输。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ResponsesTransport {
|
||||
/// 普通 HTTP 或 HTTP SSE。
|
||||
Http,
|
||||
/// OpenAI Responses WebSocket。
|
||||
WebSocket,
|
||||
}
|
||||
|
||||
/// 一条带下游提交边界的 canonical delivery event。
|
||||
pub struct DeliveryEvent {
|
||||
event: GatewayEvent,
|
||||
commit_requirement: CommitRequirement,
|
||||
}
|
||||
|
||||
impl DeliveryEvent {
|
||||
/// 绑定 canonical event 与 Engine 已冻结的提交要求。
|
||||
#[must_use]
|
||||
pub const fn new(event: GatewayEvent, commit_requirement: CommitRequirement) -> Self {
|
||||
Self {
|
||||
event,
|
||||
commit_requirement,
|
||||
}
|
||||
}
|
||||
|
||||
/// 拆分 canonical event 与提交要求。
|
||||
#[must_use]
|
||||
pub fn into_parts(self) -> (GatewayEvent, CommitRequirement) {
|
||||
(self.event, self.commit_requirement)
|
||||
}
|
||||
}
|
||||
|
||||
/// OpenAI response delivery 只依赖的执行会话端口。
|
||||
#[async_trait]
|
||||
pub trait ResponseExecutionSession: Send + 'static {
|
||||
/// 读取下一条带提交语义的 canonical event。
|
||||
async fn next_delivery_event(&mut self) -> Result<Option<DeliveryEvent>, EngineError>;
|
||||
|
||||
/// 在提交下游前收集完整 canonical event 序列。
|
||||
async fn collect_uncommitted(&mut self) -> Result<Vec<GatewayEvent>, EngineError>;
|
||||
|
||||
/// 原子提交下游 delivery 边界。
|
||||
async fn commit_downstream(
|
||||
&mut self,
|
||||
client_status_code: Option<u16>,
|
||||
) -> Result<(), EngineError>;
|
||||
|
||||
/// 首字节前失败已经终结后,补写协议 adapter 实际返回的 HTTP 状态。
|
||||
async fn record_client_status(&mut self, client_status_code: u16) -> Result<(), EngineError>;
|
||||
|
||||
/// 返回执行事实是否已经终结。
|
||||
fn is_finalized(&self) -> bool;
|
||||
|
||||
/// 触发请求取消;不得等待清理完成。
|
||||
fn cancel(&self);
|
||||
|
||||
/// 将未完成会话交给应用 runtime 做脱离 HTTP 生命周期的最终清理。
|
||||
fn detach_finalize(self);
|
||||
}
|
||||
|
||||
/// 已完成认证、请求装配和 logical-request 持久化的执行结果。
|
||||
pub struct StartedResponse<S> {
|
||||
request_id: String,
|
||||
session: S,
|
||||
created_at_unix_seconds: u64,
|
||||
streaming: bool,
|
||||
}
|
||||
|
||||
impl<S> StartedResponse<S> {
|
||||
/// 构造协议 adapter 可消费的执行事实。
|
||||
#[must_use]
|
||||
pub fn new(
|
||||
request_id: String,
|
||||
session: S,
|
||||
created_at_unix_seconds: u64,
|
||||
streaming: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
request_id,
|
||||
session,
|
||||
created_at_unix_seconds,
|
||||
streaming,
|
||||
}
|
||||
}
|
||||
|
||||
/// 返回 logical request ID。
|
||||
#[must_use]
|
||||
pub fn request_id(&self) -> &str {
|
||||
&self.request_id
|
||||
}
|
||||
|
||||
/// 拆分 handler 编码所需的冻结事实。
|
||||
#[must_use]
|
||||
pub fn into_parts(self) -> (S, u64, bool) {
|
||||
(self.session, self.created_at_unix_seconds, self.streaming)
|
||||
}
|
||||
}
|
||||
|
||||
/// OpenAI 客户端协议所需的应用服务端口。
|
||||
#[async_trait]
|
||||
pub trait OpenAiClientService: Clone + Send + Sync + 'static {
|
||||
/// 应用内部的已认证调用方快照。
|
||||
type Client: Clone + Send + Sync + 'static;
|
||||
/// 应用数据面执行会话。
|
||||
type Session: ResponseExecutionSession;
|
||||
|
||||
/// 用明文下游 API key 冻结一次认证快照。
|
||||
fn authenticate(&self, plaintext: &str) -> Result<Self::Client, ClientApiKeyAuthError>;
|
||||
|
||||
/// 返回当前调用方可见的全部公开模型。
|
||||
fn public_models(&self, client: &Self::Client) -> Vec<String>;
|
||||
|
||||
/// 判断调用方是否可访问一个已验证语法的公开模型。
|
||||
fn contains_public_model(&self, client: &Self::Client, model: &PublicModelId) -> bool;
|
||||
|
||||
/// 启动唯一数据面执行路径。
|
||||
async fn start_response(
|
||||
&self,
|
||||
client: Self::Client,
|
||||
request: DecodedResponsesRequest,
|
||||
transport: ResponsesTransport,
|
||||
) -> Result<StartedResponse<Self::Session>, GatewayError>;
|
||||
|
||||
/// 返回进程是否已停止接收新的长连接。
|
||||
fn is_shutting_down(&self) -> bool;
|
||||
|
||||
/// 把长连接任务注册到应用生命周期控制器。
|
||||
fn spawn_connection(&self, task: ConnectionTask);
|
||||
|
||||
/// 分配仅用于诊断的连接 ID。
|
||||
fn next_connection_id(&self) -> String;
|
||||
|
||||
/// 分配在数据面启动前使用的安全请求关联 ID。
|
||||
fn next_request_id(&self) -> String;
|
||||
}
|
||||
|
||||
/// Axum state 向协议 router 暴露的唯一组合入口。
|
||||
pub trait OpenAiApiState: Clone + Send + Sync + 'static {
|
||||
/// 每个请求获取的轻量服务 adapter。
|
||||
type Service: OpenAiClientService;
|
||||
|
||||
/// 返回绑定同一应用服务集合的 OpenAI adapter。
|
||||
fn openai_client_api(&self) -> Self::Service;
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
mod query {
|
||||
use gateway_api::admin::accounts::{
|
||||
AccountStatus, ListQuery, ProviderFilter, SortDirection, SortField,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn account_query_should_parse_provider_status_and_sort_once() {
|
||||
let query: ListQuery = serde_json::from_value(json!({
|
||||
"page": 3,
|
||||
"pageSize": 20,
|
||||
"provider": "xai",
|
||||
"search": " operator ",
|
||||
"status": "active",
|
||||
"sortBy": "lastUsedAt",
|
||||
"sortDirection": "desc"
|
||||
}))
|
||||
.expect("deserialize account query");
|
||||
let query = query.validate().expect("validate account query");
|
||||
assert_eq!(query.page, 3);
|
||||
assert_eq!(query.page_size, 20);
|
||||
assert!(matches!(
|
||||
query.provider,
|
||||
ProviderFilter::Provider(ref provider) if provider.as_str() == "xai"
|
||||
));
|
||||
assert_eq!(query.search.as_deref(), Some("operator"));
|
||||
assert_eq!(query.status, Some(AccountStatus::Active));
|
||||
assert_eq!(query.sort.expect("sort").field, SortField::LastUsedAt);
|
||||
assert_eq!(
|
||||
query.sort.expect("copy sort").direction,
|
||||
SortDirection::Desc
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_query_should_reject_unbounded_page_size() {
|
||||
let query: ListQuery =
|
||||
serde_json::from_value(json!({"pageSize": 201})).expect("deserialize account query");
|
||||
assert_eq!(
|
||||
query.validate().expect_err("reject page size").field(),
|
||||
"pageSize"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_query_should_reject_incomplete_sort() {
|
||||
let query: ListQuery =
|
||||
serde_json::from_value(json!({"sortBy": "usage"})).expect("deserialize account query");
|
||||
assert_eq!(query.validate().expect_err("reject sort").field(), "sort");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_query_should_reject_unknown_fields() {
|
||||
assert!(serde_json::from_value::<ListQuery>(json!({"id": "cred_1"})).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
mod response {
|
||||
use gateway_api::admin::accounts::AccountUsageView;
|
||||
|
||||
#[test]
|
||||
fn account_usage_view_should_keep_unobserved_numbers_null() {
|
||||
let view = AccountUsageView {
|
||||
request_count: None,
|
||||
request_count_display: "-".to_owned(),
|
||||
input_tokens: None,
|
||||
input_tokens_display: "-".to_owned(),
|
||||
output_tokens: None,
|
||||
output_tokens_display: "-".to_owned(),
|
||||
cached_tokens: None,
|
||||
cached_tokens_display: "-".to_owned(),
|
||||
total_tokens: None,
|
||||
total_tokens_display: "-".to_owned(),
|
||||
created_tokens: None,
|
||||
created_tokens_display: "-".to_owned(),
|
||||
read_tokens: None,
|
||||
read_tokens_display: "-".to_owned(),
|
||||
last_used_at: None,
|
||||
last_used_at_display: "-".to_owned(),
|
||||
cost_estimate_status: "unknown".to_owned(),
|
||||
known_cost_count: None,
|
||||
partial_cost_count: None,
|
||||
unknown_cost_count: None,
|
||||
costs: Vec::new(),
|
||||
models: Vec::new(),
|
||||
};
|
||||
let value = serde_json::to_value(view).expect("serialize account usage");
|
||||
assert!(value["inputTokens"].is_null());
|
||||
assert!(value["totalTokens"].is_null());
|
||||
assert_eq!(value["createdTokensDisplay"], "-");
|
||||
}
|
||||
}
|
||||
|
||||
mod actions {
|
||||
use gateway_api::admin::accounts::{
|
||||
AccountActionRequest, AccountConnectionTestEvent, AccountExportData, AccountExportQuery,
|
||||
AccountIdQuery, AccountRefreshRequest, AccountTestQuery,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn export_should_require_explicit_unique_ids_and_confirmation() {
|
||||
let valid: AccountExportQuery = serde_json::from_value(json!({
|
||||
"ids": "acct_1,acct_2",
|
||||
"confirm": "export_sensitive_accounts"
|
||||
}))
|
||||
.expect("decode export query");
|
||||
assert_eq!(
|
||||
valid.into_ids().expect("valid export"),
|
||||
["acct_1".to_owned(), "acct_2".to_owned()]
|
||||
);
|
||||
|
||||
for query in [
|
||||
json!({ "ids": "", "confirm": "export_sensitive_accounts" }),
|
||||
json!({ "ids": "acct_1,acct_1", "confirm": "export_sensitive_accounts" }),
|
||||
json!({ "ids": "acct_1", "confirm": "yes" }),
|
||||
] {
|
||||
assert!(
|
||||
serde_json::from_value::<AccountExportQuery>(query)
|
||||
.expect("decode invalid export query")
|
||||
.into_ids()
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_actions_should_require_frozen_account_ids_and_revision() {
|
||||
let id: AccountIdQuery =
|
||||
serde_json::from_value(json!({ "id": "acct_1" })).expect("decode ID query");
|
||||
assert!(id.validate().is_ok());
|
||||
let action: AccountActionRequest =
|
||||
serde_json::from_value(json!({ "id": "legacy-id" })).expect("decode action");
|
||||
assert_eq!(action.validate().unwrap_err().field(), "id");
|
||||
let refresh: AccountRefreshRequest = serde_json::from_value(json!({
|
||||
"id": "acct_1",
|
||||
"expectedConfigRevision": 0
|
||||
}))
|
||||
.expect("decode refresh");
|
||||
assert_eq!(
|
||||
refresh.validate().unwrap_err().field(),
|
||||
"expectedConfigRevision"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connection_test_should_require_model_in_query() {
|
||||
let query: AccountTestQuery = serde_json::from_value(json!({
|
||||
"id": "acct_1",
|
||||
"modelId": " "
|
||||
}))
|
||||
.expect("decode connection test query");
|
||||
assert_eq!(query.validate().unwrap_err().field(), "modelId");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connection_test_events_should_preserve_the_existing_frontend_contract() {
|
||||
let events = [
|
||||
AccountConnectionTestEvent::started("grok-4.5"),
|
||||
AccountConnectionTestEvent::request(json!({ "model": "grok-4.5" })),
|
||||
AccountConnectionTestEvent::content("OK"),
|
||||
AccountConnectionTestEvent::completed("active"),
|
||||
AccountConnectionTestEvent::failed("upstream unavailable", "active"),
|
||||
]
|
||||
.map(|event| event.data);
|
||||
|
||||
assert_eq!(
|
||||
events,
|
||||
[
|
||||
json!({ "type": "test_start", "model": "grok-4.5", "text": "正在连接上游 Responses" }),
|
||||
json!({ "type": "request", "payload": { "model": "grok-4.5" } }),
|
||||
json!({ "type": "content", "text": "OK" }),
|
||||
json!({ "type": "test_complete", "success": true, "accountStatus": "active" }),
|
||||
json!({ "type": "error", "error": "upstream unavailable", "accountStatus": "active" }),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_export_document_should_serialize_but_never_debug_secret() {
|
||||
let secret = "provider-refresh-token-must-not-enter-debug";
|
||||
let document = AccountExportData::new(json!({ "refresh_token": secret }));
|
||||
assert!(!format!("{document:?}").contains(secret));
|
||||
assert_eq!(
|
||||
serde_json::to_value(document).expect("serialize export"),
|
||||
json!({ "refresh_token": secret })
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use gateway_api::admin::AdminServiceError;
|
||||
use gateway_api::admin::auth::{
|
||||
AdminAuthAuditEvent, AdminAuthBackend, AdminAuthService, AdminBackendSession, AdminLoginData,
|
||||
AdminLoginError, AdminLoginRequest, AdminLogoutData, AdminSessionResolver,
|
||||
AdminSessionStatusData, DefaultAdminAuthService,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn login_request_should_deny_unknown_fields_and_redact_password_debug() {
|
||||
let password = "admin-password-must-not-leak";
|
||||
let request = serde_json::from_value::<AdminLoginRequest>(json!({
|
||||
"username": "admin@example.invalid",
|
||||
"password": password
|
||||
}))
|
||||
.expect("deserialize login request");
|
||||
|
||||
assert!(!format!("{request:?}").contains(password));
|
||||
let (username, parsed_password) = request.into_parts();
|
||||
assert_eq!(username.as_deref(), Some("admin@example.invalid"));
|
||||
assert_eq!(parsed_password, password);
|
||||
assert!(
|
||||
serde_json::from_value::<AdminLoginRequest>(json!({
|
||||
"password": password,
|
||||
"rememberMe": true
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auth_responses_should_keep_stable_wire_shapes() {
|
||||
assert_eq!(
|
||||
serde_json::to_value(AdminLoginData::new("2026-07-18T08:00:00+08:00".to_owned()))
|
||||
.expect("serialize login"),
|
||||
json!({ "expiresAt": "2026-07-18T08:00:00+08:00" })
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(AdminSessionStatusData::new(true)).expect("serialize status"),
|
||||
json!({ "authenticated": true })
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(AdminLogoutData::new()).expect("serialize logout"),
|
||||
json!({ "message": "Logged out successfully" })
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MemoryAuthBackend {
|
||||
password_hash: Mutex<Option<String>>,
|
||||
admin_api_key: Mutex<Option<String>>,
|
||||
sessions: Mutex<BTreeMap<String, AdminBackendSession>>,
|
||||
login_failures: Mutex<BTreeMap<String, u32>>,
|
||||
audits: Mutex<Vec<AdminAuthAuditEvent>>,
|
||||
fail_audit: AtomicBool,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AdminAuthBackend for MemoryAuthBackend {
|
||||
async fn password_hash(
|
||||
&self,
|
||||
_admin_user_id: &str,
|
||||
) -> Result<Option<String>, AdminServiceError> {
|
||||
Ok(self.password_hash.lock().expect("password lock").clone())
|
||||
}
|
||||
|
||||
async fn store_password_hash(
|
||||
&self,
|
||||
_admin_user_id: &str,
|
||||
password_hash: &str,
|
||||
) -> Result<(), AdminServiceError> {
|
||||
*self.password_hash.lock().expect("password lock") = Some(password_hash.to_owned());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn admin_api_key(&self) -> Result<Option<String>, AdminServiceError> {
|
||||
Ok(self.admin_api_key.lock().expect("API key lock").clone())
|
||||
}
|
||||
|
||||
async fn load_admin_session(
|
||||
&self,
|
||||
session_id: &str,
|
||||
) -> Result<Option<AdminBackendSession>, AdminServiceError> {
|
||||
Ok(self
|
||||
.sessions
|
||||
.lock()
|
||||
.expect("session lock")
|
||||
.get(session_id)
|
||||
.cloned())
|
||||
}
|
||||
|
||||
async fn store_admin_session(
|
||||
&self,
|
||||
session_id: &str,
|
||||
session: &AdminBackendSession,
|
||||
) -> Result<(), AdminServiceError> {
|
||||
self.sessions
|
||||
.lock()
|
||||
.expect("session lock")
|
||||
.insert(session_id.to_owned(), session.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn delete_admin_session(
|
||||
&self,
|
||||
session_id: &str,
|
||||
) -> Result<Option<AdminBackendSession>, AdminServiceError> {
|
||||
Ok(self
|
||||
.sessions
|
||||
.lock()
|
||||
.expect("session lock")
|
||||
.remove(session_id))
|
||||
}
|
||||
|
||||
async fn login_source_is_throttled(
|
||||
&self,
|
||||
source: &str,
|
||||
failure_limit: u32,
|
||||
_window_seconds: u64,
|
||||
) -> Result<bool, AdminServiceError> {
|
||||
Ok(self
|
||||
.login_failures
|
||||
.lock()
|
||||
.expect("failure lock")
|
||||
.get(source)
|
||||
.is_some_and(|count| *count >= failure_limit))
|
||||
}
|
||||
|
||||
async fn record_login_failure(
|
||||
&self,
|
||||
source: &str,
|
||||
failure_limit: u32,
|
||||
_window_seconds: u64,
|
||||
) -> Result<bool, AdminServiceError> {
|
||||
let mut failures = self.login_failures.lock().expect("failure lock");
|
||||
let count = failures.entry(source.to_owned()).or_default();
|
||||
*count = count.saturating_add(1);
|
||||
Ok(*count >= failure_limit)
|
||||
}
|
||||
|
||||
async fn clear_login_failures(&self, source: &str) -> Result<(), AdminServiceError> {
|
||||
self.login_failures
|
||||
.lock()
|
||||
.expect("failure lock")
|
||||
.remove(source);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn append_auth_audit(&self, event: AdminAuthAuditEvent) -> Result<(), AdminServiceError> {
|
||||
if self.fail_audit.load(Ordering::SeqCst) {
|
||||
return Err(AdminServiceError::unavailable("audit unavailable"));
|
||||
}
|
||||
self.audits.lock().expect("audit lock").push(event);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn default_auth_service_should_initialize_login_validate_and_logout() {
|
||||
let backend = Arc::new(MemoryAuthBackend::default());
|
||||
let service = DefaultAdminAuthService::new("admin_1".to_owned(), 60, backend.clone());
|
||||
assert!(
|
||||
service
|
||||
.ensure_default_admin("strong-admin-password")
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
assert!(
|
||||
!service
|
||||
.ensure_default_admin("different-password")
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
|
||||
let session = service
|
||||
.login(
|
||||
"127.0.0.1",
|
||||
Some("admin_1".to_owned()),
|
||||
"strong-admin-password".to_owned(),
|
||||
)
|
||||
.await
|
||||
.expect("login succeeds");
|
||||
assert!(
|
||||
service
|
||||
.validate(Some(session.session_id.clone()))
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
service
|
||||
.resolve_admin_user_id(Some(&session.session_id))
|
||||
.await
|
||||
.unwrap()
|
||||
.as_deref(),
|
||||
Some("admin_1"),
|
||||
);
|
||||
service.logout(session.session_id.clone()).await.unwrap();
|
||||
assert!(!service.validate(Some(session.session_id)).await.unwrap());
|
||||
assert_eq!(backend.audits.lock().expect("audit lock").len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn default_auth_service_should_throttle_repeated_invalid_identity() {
|
||||
let backend = Arc::new(MemoryAuthBackend::default());
|
||||
let service = DefaultAdminAuthService::new("admin_1".to_owned(), 60, backend.clone());
|
||||
for attempt in 1..=5 {
|
||||
let error = service
|
||||
.login(
|
||||
"shared-source",
|
||||
Some("wrong-user".to_owned()),
|
||||
"wrong-password".to_owned(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
if attempt < 5 {
|
||||
assert_eq!(error, AdminLoginError::InvalidCredentials);
|
||||
} else {
|
||||
assert_eq!(error, AdminLoginError::Throttled);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
service
|
||||
.login("shared-source", None, "anything".to_owned())
|
||||
.await
|
||||
.unwrap_err(),
|
||||
AdminLoginError::Throttled,
|
||||
);
|
||||
assert!(backend.sessions.lock().expect("session lock").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn default_auth_service_should_verify_only_full_plaintext_admin_key() {
|
||||
let backend = Arc::new(MemoryAuthBackend::default());
|
||||
let key = format!("admin-{}", "a".repeat(64));
|
||||
*backend.admin_api_key.lock().expect("API key lock") = Some(key.clone());
|
||||
let service = DefaultAdminAuthService::new("admin_1".to_owned(), 60, backend);
|
||||
|
||||
assert!(service.verify_admin_api_key(&key).await.unwrap());
|
||||
assert!(!service.verify_admin_api_key("admin-short").await.unwrap());
|
||||
assert!(
|
||||
!service
|
||||
.verify_admin_api_key(&format!("admin-{}", "b".repeat(64)))
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn audit_failure_should_revoke_new_session_before_returning_it() {
|
||||
let backend = Arc::new(MemoryAuthBackend::default());
|
||||
let service = DefaultAdminAuthService::new("admin_1".to_owned(), 60, backend.clone());
|
||||
service
|
||||
.ensure_default_admin("strong-admin-password")
|
||||
.await
|
||||
.unwrap();
|
||||
backend.fail_audit.store(true, Ordering::SeqCst);
|
||||
|
||||
assert_eq!(
|
||||
service
|
||||
.login("source", None, "strong-admin-password".to_owned())
|
||||
.await
|
||||
.unwrap_err(),
|
||||
AdminLoginError::Unavailable,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
use chrono::Utc;
|
||||
use gateway_api::admin::catalog::{
|
||||
CatalogListQuery, CreateProviderInstanceRequest, ProviderInstanceView,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
fn provider_request(provider_kind: &str) -> CreateProviderInstanceRequest {
|
||||
serde_json::from_value(json!({
|
||||
"id": format!("inst_{provider_kind}"),
|
||||
"expectedConfigRevision": 1,
|
||||
"providerKind": provider_kind,
|
||||
"name": provider_kind,
|
||||
"baseUrl": "https://example.invalid"
|
||||
}))
|
||||
.expect("decode provider instance")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_instance_should_accept_openai_platform() {
|
||||
assert!(provider_request("openai").validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_instance_should_accept_xai_platform() {
|
||||
assert!(provider_request("xai").validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_instance_should_reject_removed_scheduling_fields() {
|
||||
let result = serde_json::from_value::<CreateProviderInstanceRequest>(json!({
|
||||
"id": "inst_openai",
|
||||
"expectedConfigRevision": 1,
|
||||
"providerKind": "openai",
|
||||
"name": "OpenAI",
|
||||
"baseUrl": "https://chatgpt.com",
|
||||
"maxConcurrency": 3
|
||||
}));
|
||||
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_instance_should_reject_removed_model_routing_fields() {
|
||||
let result = serde_json::from_value::<CreateProviderInstanceRequest>(json!({
|
||||
"id": "inst_openai",
|
||||
"expectedConfigRevision": 1,
|
||||
"providerKind": "openai",
|
||||
"name": "OpenAI",
|
||||
"baseUrl": "https://chatgpt.com",
|
||||
"upstreamModelId": "gpt-5.4"
|
||||
}));
|
||||
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_instance_should_reject_unknown_provider_kind() {
|
||||
let request = provider_request("unknown");
|
||||
|
||||
assert_eq!(request.validate().unwrap_err().field(), "providerKind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_instance_should_reject_id_without_core_prefix() {
|
||||
let request: CreateProviderInstanceRequest = serde_json::from_value(json!({
|
||||
"id": "codex-official",
|
||||
"expectedConfigRevision": 1,
|
||||
"providerKind": "openai",
|
||||
"name": "Codex",
|
||||
"baseUrl": "https://chatgpt.com/backend-api"
|
||||
}))
|
||||
.expect("decode provider instance");
|
||||
|
||||
assert_eq!(request.validate().unwrap_err().field(), "id");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_instance_should_require_positive_revision() {
|
||||
let mut request = provider_request("openai");
|
||||
request.expected_config_revision = 0;
|
||||
|
||||
assert_eq!(
|
||||
request.validate().unwrap_err().field(),
|
||||
"expectedConfigRevision"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_page_size_should_remain_bounded() {
|
||||
let query = CatalogListQuery {
|
||||
cursor: None,
|
||||
limit: Some(201),
|
||||
};
|
||||
|
||||
assert_eq!(query.validate().unwrap_err().field(), "limit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_instance_view_should_not_emit_provider_config_json() {
|
||||
let value = serde_json::to_value(ProviderInstanceView {
|
||||
id: "inst_openai".into(),
|
||||
provider_kind: "openai".into(),
|
||||
name: "Codex".into(),
|
||||
base_url: "https://chatgpt.com".into(),
|
||||
enabled: true,
|
||||
created_at: Utc::now(),
|
||||
updated_at: Utc::now(),
|
||||
})
|
||||
.expect("serialize provider instance");
|
||||
|
||||
assert!(value.get("configJson").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_instance_view_should_emit_platform_explicitly() {
|
||||
let value = serde_json::to_value(ProviderInstanceView {
|
||||
id: "inst_xai".into(),
|
||||
provider_kind: "xai".into(),
|
||||
name: "xAI".into(),
|
||||
base_url: "https://grok.com".into(),
|
||||
enabled: true,
|
||||
created_at: Utc::now(),
|
||||
updated_at: Utc::now(),
|
||||
})
|
||||
.expect("serialize provider instance");
|
||||
|
||||
assert_eq!(value["providerKind"], "xai");
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
use chrono::{DateTime, TimeZone as _, Utc};
|
||||
use gateway_api::admin::client_keys::{
|
||||
self, ClientKeyAdminService, ClientKeyAdminState, ClientKeyCursorData, ClientKeyCursorValue,
|
||||
ClientKeyListData, ClientKeyRevisionRequest, ClientKeySort, ClientKeySortDirection,
|
||||
ClientKeySortField, ClientKeyView, ClientKeyViewFields, CreateClientKeyFields,
|
||||
CreateClientKeyRequest, CreatedClientKeyData, ListClientKeysFields, ListClientKeysQuery,
|
||||
MutatedClientKeyData, RevealedClientKeyData, UpdateClientKeyFields, UpdateClientKeyRequest,
|
||||
decode_client_key_cursor, encode_client_key_cursor,
|
||||
};
|
||||
use gateway_api::admin::{
|
||||
AdminRequestContext, AdminServiceError, AdminSessionResolver, AdminSessionState,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn client_key_queries_should_reject_unknown_zero_and_oversized_fields() {
|
||||
let unknown = serde_json::from_value::<ListClientKeysQuery>(json!({ "other": true }));
|
||||
let zero = serde_json::from_value::<ListClientKeysQuery>(json!({ "limit": 0 }))
|
||||
.expect("deserialize zero limit");
|
||||
let oversized = serde_json::from_value::<ListClientKeysQuery>(json!({
|
||||
"cursor": "a".repeat(513)
|
||||
}))
|
||||
.expect("deserialize oversized cursor");
|
||||
let oversized_search = serde_json::from_value::<ListClientKeysQuery>(json!({
|
||||
"search": "a".repeat(257)
|
||||
}))
|
||||
.expect("deserialize oversized search");
|
||||
let secret_search = serde_json::from_value::<ListClientKeysQuery>(json!({
|
||||
"search": format!("sk_{}", "a".repeat(43))
|
||||
}))
|
||||
.expect("deserialize secret search");
|
||||
let invalid_sort = serde_json::from_value::<ListClientKeysQuery>(json!({
|
||||
"sortBy": "plaintextKey",
|
||||
"sortDirection": "asc"
|
||||
}))
|
||||
.expect("deserialize invalid sort");
|
||||
|
||||
assert!(unknown.is_err());
|
||||
assert_eq!(
|
||||
zero.into_parts().expect_err("reject zero limit").field(),
|
||||
"limit"
|
||||
);
|
||||
assert_eq!(
|
||||
oversized
|
||||
.into_parts()
|
||||
.expect_err("reject oversized cursor")
|
||||
.field(),
|
||||
"cursor"
|
||||
);
|
||||
assert_eq!(
|
||||
oversized_search
|
||||
.into_parts()
|
||||
.expect_err("reject oversized search")
|
||||
.field(),
|
||||
"search"
|
||||
);
|
||||
assert_eq!(
|
||||
secret_search
|
||||
.into_parts()
|
||||
.expect_err("reject full key in search")
|
||||
.field(),
|
||||
"search"
|
||||
);
|
||||
assert_eq!(
|
||||
invalid_sort
|
||||
.into_parts()
|
||||
.expect_err("reject invalid sort")
|
||||
.field(),
|
||||
"sortBy"
|
||||
);
|
||||
let sorted = serde_json::from_value::<ListClientKeysQuery>(json!({
|
||||
"sortBy": "lastUsedAt",
|
||||
"sortDirection": "asc"
|
||||
}))
|
||||
.expect("deserialize valid sort")
|
||||
.into_parts()
|
||||
.expect("validate sort");
|
||||
assert_eq!(
|
||||
sorted.sort,
|
||||
ClientKeySort {
|
||||
field: ClientKeySortField::LastUsedAt,
|
||||
direction: ClientKeySortDirection::Asc,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_value::<ListClientKeysQuery>(json!({ "search": " " }))
|
||||
.expect("deserialize blank search")
|
||||
.into_parts()
|
||||
.expect("normalize blank search")
|
||||
.search,
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_key_mutations_should_validate_revision_text_limits_and_unknown_fields() {
|
||||
let valid = serde_json::from_value::<CreateClientKeyRequest>(json!({
|
||||
"expectedConfigRevision": 7,
|
||||
"name": "terminal key",
|
||||
"label": "production",
|
||||
"providerKind": "openai",
|
||||
"maxConcurrency": 2,
|
||||
"requestsPerMinute": 60,
|
||||
"tokensPerMinute": 100000
|
||||
}))
|
||||
.expect("deserialize create")
|
||||
.into_fields()
|
||||
.expect("validate create");
|
||||
assert_eq!(valid.expected_config_revision, 7);
|
||||
|
||||
for (payload, field) in [
|
||||
(
|
||||
json!({
|
||||
"expectedConfigRevision": 0,
|
||||
"name": "key",
|
||||
"providerKind": "openai",
|
||||
"maxConcurrency": 0,
|
||||
"requestsPerMinute": 0,
|
||||
"tokensPerMinute": 0
|
||||
}),
|
||||
"expectedConfigRevision",
|
||||
),
|
||||
(
|
||||
json!({
|
||||
"expectedConfigRevision": 1,
|
||||
"name": " ",
|
||||
"providerKind": "openai",
|
||||
"maxConcurrency": 0,
|
||||
"requestsPerMinute": 0,
|
||||
"tokensPerMinute": 0
|
||||
}),
|
||||
"name",
|
||||
),
|
||||
(
|
||||
json!({
|
||||
"expectedConfigRevision": 1,
|
||||
"name": "key",
|
||||
"providerKind": "openai",
|
||||
"maxConcurrency": u64::MAX,
|
||||
"requestsPerMinute": 0,
|
||||
"tokensPerMinute": 0
|
||||
}),
|
||||
"maxConcurrency",
|
||||
),
|
||||
] {
|
||||
let request = serde_json::from_value::<CreateClientKeyRequest>(payload)
|
||||
.expect("deserialize invalid create shape");
|
||||
assert_eq!(
|
||||
request
|
||||
.into_fields()
|
||||
.expect_err("reject invalid create")
|
||||
.field(),
|
||||
field
|
||||
);
|
||||
}
|
||||
|
||||
assert!(
|
||||
serde_json::from_value::<UpdateClientKeyRequest>(json!({
|
||||
"id": "key_1",
|
||||
"expectedConfigRevision": 1,
|
||||
"name": "key",
|
||||
"providerKind": "openai",
|
||||
"maxConcurrency": 0,
|
||||
"requestsPerMinute": 0,
|
||||
"tokensPerMinute": 0,
|
||||
"plaintextKey": "must-not-be-accepted"
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
let revision = serde_json::from_value::<ClientKeyRevisionRequest>(json!({
|
||||
"id": "key_1",
|
||||
"expectedConfigRevision": 3
|
||||
}))
|
||||
.expect("deserialize revision mutation")
|
||||
.into_parts()
|
||||
.expect("validate revision mutation");
|
||||
assert_eq!(revision, ("key_1".to_owned(), 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_key_cursor_should_round_trip_and_reject_noncanonical_input() {
|
||||
let created_at = Utc
|
||||
.with_ymd_and_hms(2026, 7, 18, 8, 0, 0)
|
||||
.single()
|
||||
.expect("valid time");
|
||||
let cursor = ClientKeyCursorData {
|
||||
sort: ClientKeySort {
|
||||
field: ClientKeySortField::CreatedAt,
|
||||
direction: ClientKeySortDirection::Desc,
|
||||
},
|
||||
value: ClientKeyCursorValue::CreatedAt(created_at),
|
||||
id: "key_cursor".to_owned(),
|
||||
};
|
||||
let encoded = encode_client_key_cursor(&cursor).expect("encode cursor");
|
||||
let decoded = decode_client_key_cursor(&encoded).expect("decode cursor");
|
||||
|
||||
assert_eq!(decoded, cursor);
|
||||
assert!(!encoded.contains("key_cursor"));
|
||||
for invalid in ["", "not-base64!", "e30"] {
|
||||
assert!(decode_client_key_cursor(invalid).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_key_responses_should_keep_shape_and_redact_creation_debug() {
|
||||
let created_at = Utc
|
||||
.with_ymd_and_hms(2026, 7, 18, 8, 0, 0)
|
||||
.single()
|
||||
.expect("valid time");
|
||||
let view = ClientKeyView::new(ClientKeyViewFields {
|
||||
id: "key_visible".to_owned(),
|
||||
name: "visible".to_owned(),
|
||||
label: None,
|
||||
provider_kind: "openai".to_owned(),
|
||||
prefix: "sk_visible12".to_owned(),
|
||||
enabled: true,
|
||||
max_concurrency: 2,
|
||||
requests_per_minute: 60,
|
||||
tokens_per_minute: 100_000,
|
||||
created_at,
|
||||
updated_at: created_at,
|
||||
last_used_at: Some(created_at),
|
||||
});
|
||||
let list = serde_json::to_value(ClientKeyListData::new(9, vec![view], None, 1))
|
||||
.expect("serialize list");
|
||||
assert_eq!(list["configRevision"], 9);
|
||||
assert_eq!(list["total"], 1);
|
||||
assert_eq!(list["items"][0]["id"], "key_visible");
|
||||
assert_eq!(list["items"][0]["providerKind"], "openai");
|
||||
assert_eq!(list["items"][0]["maxConcurrency"], 2);
|
||||
assert_eq!(list["items"][0]["requestsPerMinute"], 60);
|
||||
assert_eq!(list["items"][0]["tokensPerMinute"], 100_000);
|
||||
assert!(list["items"][0].get("policyJson").is_none());
|
||||
assert_eq!(
|
||||
DateTime::parse_from_rfc3339(
|
||||
list["items"][0]["lastUsedAt"]
|
||||
.as_str()
|
||||
.expect("serialized last-used timestamp")
|
||||
)
|
||||
.expect("parse serialized last-used timestamp"),
|
||||
created_at.fixed_offset()
|
||||
);
|
||||
assert!(list["items"][0].get("plaintextKey").is_none());
|
||||
|
||||
let plaintext = format!("sk_{}", "a".repeat(43));
|
||||
let created = CreatedClientKeyData::new(
|
||||
10,
|
||||
"key_created".to_owned(),
|
||||
"sk_aaaaaaaaa".to_owned(),
|
||||
plaintext.clone(),
|
||||
);
|
||||
assert!(!format!("{created:?}").contains(&plaintext));
|
||||
let value = serde_json::to_value(created).expect("serialize created key");
|
||||
assert_eq!(value["plaintextKey"], plaintext);
|
||||
let revealed = RevealedClientKeyData::new("key_created".to_owned(), plaintext.clone());
|
||||
assert!(!format!("{revealed:?}").contains(&plaintext));
|
||||
assert_eq!(
|
||||
serde_json::to_value(revealed).expect("serialize revealed key"),
|
||||
json!({ "id": "key_created", "plaintextKey": plaintext })
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(MutatedClientKeyData::new(11, "key_created".to_owned()))
|
||||
.expect("serialize mutation"),
|
||||
json!({ "configRevision": 11, "id": "key_created" })
|
||||
);
|
||||
}
|
||||
|
||||
struct RevealService;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl AdminSessionResolver for RevealService {
|
||||
async fn resolve_admin_user_id(
|
||||
&self,
|
||||
session_id: Option<&str>,
|
||||
) -> Result<Option<String>, AdminServiceError> {
|
||||
Ok((session_id == Some("valid-session")).then(|| "admin_1".to_owned()))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ClientKeyAdminService for RevealService {
|
||||
async fn list(
|
||||
&self,
|
||||
_query: ListClientKeysFields,
|
||||
) -> Result<ClientKeyListData, AdminServiceError> {
|
||||
Err(AdminServiceError::internal("unused test operation"))
|
||||
}
|
||||
|
||||
async fn create(
|
||||
&self,
|
||||
_context: &AdminRequestContext,
|
||||
_fields: CreateClientKeyFields,
|
||||
) -> Result<CreatedClientKeyData, AdminServiceError> {
|
||||
Err(AdminServiceError::internal("unused test operation"))
|
||||
}
|
||||
|
||||
async fn reveal(&self, id: String) -> Result<RevealedClientKeyData, AdminServiceError> {
|
||||
Ok(RevealedClientKeyData::new(
|
||||
id,
|
||||
format!("sk_{}", "a".repeat(43)),
|
||||
))
|
||||
}
|
||||
|
||||
async fn update(
|
||||
&self,
|
||||
_context: &AdminRequestContext,
|
||||
_fields: UpdateClientKeyFields,
|
||||
) -> Result<MutatedClientKeyData, AdminServiceError> {
|
||||
Err(AdminServiceError::internal("unused test operation"))
|
||||
}
|
||||
|
||||
async fn disable(
|
||||
&self,
|
||||
_context: &AdminRequestContext,
|
||||
_id: String,
|
||||
_expected_config_revision: u64,
|
||||
) -> Result<MutatedClientKeyData, AdminServiceError> {
|
||||
Err(AdminServiceError::internal("unused test operation"))
|
||||
}
|
||||
|
||||
async fn enable(
|
||||
&self,
|
||||
_context: &AdminRequestContext,
|
||||
_id: String,
|
||||
_expected_config_revision: u64,
|
||||
) -> Result<MutatedClientKeyData, AdminServiceError> {
|
||||
Err(AdminServiceError::internal("unused test operation"))
|
||||
}
|
||||
|
||||
async fn delete(
|
||||
&self,
|
||||
_context: &AdminRequestContext,
|
||||
_id: String,
|
||||
_expected_config_revision: u64,
|
||||
) -> Result<MutatedClientKeyData, AdminServiceError> {
|
||||
Err(AdminServiceError::internal("unused test operation"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct RevealState(std::sync::Arc<RevealService>);
|
||||
|
||||
impl AdminSessionState for RevealState {
|
||||
fn admin_session_resolver(&self) -> &dyn AdminSessionResolver {
|
||||
self.0.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientKeyAdminState for RevealState {
|
||||
fn client_key_admin_service(&self) -> &dyn ClientKeyAdminService {
|
||||
self.0.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reveal_route_should_use_query_id_and_no_store_response() {
|
||||
use axum::{
|
||||
body::{Body, to_bytes},
|
||||
http::{Request, StatusCode, header},
|
||||
};
|
||||
use tower::ServiceExt as _;
|
||||
|
||||
let state = RevealState(std::sync::Arc::new(RevealService));
|
||||
let response = client_keys::router::<RevealState>()
|
||||
.with_state(state)
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/admin/client-keys/reveal?id=key_1")
|
||||
.header(header::COOKIE, "cpr_admin_session=valid-session")
|
||||
.header("x-request-id", "req_reveal")
|
||||
.body(Body::empty())
|
||||
.expect("reveal request"),
|
||||
)
|
||||
.await
|
||||
.expect("reveal response");
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get(header::CACHE_CONTROL)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
Some("no-store")
|
||||
);
|
||||
let body = to_bytes(response.into_body(), 4096)
|
||||
.await
|
||||
.expect("reveal body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("reveal JSON");
|
||||
assert_eq!(value["data"]["id"], "key_1");
|
||||
assert_eq!(
|
||||
value["data"]["plaintextKey"],
|
||||
format!("sk_{}", "a".repeat(43))
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
mod accounts;
|
||||
mod auth;
|
||||
mod catalog;
|
||||
mod client_keys;
|
||||
mod observability;
|
||||
mod openai;
|
||||
mod settings;
|
||||
mod system;
|
||||
mod wire;
|
||||
mod xai;
|
||||
@@ -0,0 +1,183 @@
|
||||
mod query {
|
||||
use gateway_api::admin::observability::{
|
||||
DashboardQuery, DiagnosticDimension, DiagnosticsQuery, OpsQuery, TrendKind, UsageQuery,
|
||||
parse_attempt_index, parse_datetime, parse_status,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn dashboard_query_should_parse_terminal_trend_kinds() {
|
||||
let query: DashboardQuery = serde_json::from_value(json!({"kind": "errors"})).unwrap();
|
||||
assert_eq!(query.trend_kind().unwrap(), TrendKind::Errors);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dashboard_query_should_reject_unknown_trend_kind() {
|
||||
let query: DashboardQuery = serde_json::from_value(json!({"kind": "secret"})).unwrap();
|
||||
assert_eq!(query.trend_kind().unwrap_err().field(), "kind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_query_should_bound_page_size_and_cursor() {
|
||||
let query: UsageQuery = serde_json::from_value(json!({
|
||||
"page": 2,
|
||||
"pageSize": 100,
|
||||
"cursor": "opaque"
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(query.validate_page().unwrap(), (2, 100));
|
||||
assert!(query.validate_cursor().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_query_should_reject_zero_page() {
|
||||
let query: UsageQuery = serde_json::from_value(json!({"page": 0})).unwrap();
|
||||
assert_eq!(query.validate_page().unwrap_err().field(), "page");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ops_query_should_reject_page_size_above_terminal_limit() {
|
||||
let query: OpsQuery = serde_json::from_value(json!({"pageSize": 101})).unwrap();
|
||||
assert_eq!(query.validate_page().unwrap_err().field(), "pageSize");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostics_query_should_keep_wire_dimension_name() {
|
||||
let query: DiagnosticsQuery =
|
||||
serde_json::from_value(json!({"dimension": "failure_class"})).unwrap();
|
||||
assert_eq!(query.dimension().unwrap(), DiagnosticDimension::Failure);
|
||||
assert_eq!(DiagnosticDimension::Failure.display_name(), "failureClass");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_query_parsers_should_reject_out_of_range_values_without_echoing_input() {
|
||||
assert_eq!(parse_status(Some(99)).unwrap_err().field(), "statusCode");
|
||||
assert_eq!(
|
||||
parse_attempt_index(Some(0)).unwrap_err().field(),
|
||||
"attemptIndex"
|
||||
);
|
||||
assert_eq!(
|
||||
parse_datetime(Some("not-a-time")).unwrap_err().field(),
|
||||
"timeRange"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
mod response {
|
||||
use chrono::{TimeZone, Utc};
|
||||
use gateway_api::admin::observability::{
|
||||
BillingView, CostCoverageView, CursorWire, PageData, PageMeta, TokenDetailsView, TrendData,
|
||||
TrendKind, TrendPointView, TrendSummaryView,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn usage_page_should_keep_terminal_camel_case_shape() {
|
||||
let data = PageData {
|
||||
items: vec![json!({"id": "request_1"})],
|
||||
page: PageMeta::new(1, 50, 1, 1),
|
||||
next_cursor: Some("cursor".to_owned()),
|
||||
};
|
||||
let value = serde_json::to_value(data).unwrap();
|
||||
assert_eq!(value["page"]["pageSize"], 50);
|
||||
assert_eq!(value["nextCursor"], "cursor");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trend_wire_should_serialize_kind_and_values_without_store_types() {
|
||||
let now = Utc.timestamp_opt(0, 0).single().unwrap();
|
||||
let data = TrendData {
|
||||
kind: TrendKind::Usage,
|
||||
points: vec![TrendPointView {
|
||||
time: "08:00".to_owned(),
|
||||
bucket: now,
|
||||
label: "01-01 08:00".to_owned(),
|
||||
requests: "1".to_owned(),
|
||||
requests_value: 1,
|
||||
input_tokens: "2".to_owned(),
|
||||
input_tokens_value: 2,
|
||||
output_tokens: "3".to_owned(),
|
||||
output_tokens_value: 3,
|
||||
cached_tokens: "0".to_owned(),
|
||||
cached_tokens_value: 0,
|
||||
cache_hit_rate_value: 0.0,
|
||||
tokens_value: 5,
|
||||
errors: "0".to_owned(),
|
||||
errors_value: 0,
|
||||
latency: "1 ms".to_owned(),
|
||||
latency_value: Some(1),
|
||||
first_token_latency: "1 ms".to_owned(),
|
||||
first_token_latency_value: Some(1),
|
||||
max_latency: "1 ms".to_owned(),
|
||||
max_latency_value: Some(1),
|
||||
min_latency: "1 ms".to_owned(),
|
||||
min_latency_value: Some(1),
|
||||
success_rate: "100.0%".to_owned(),
|
||||
success_rate_value: Some(100.0),
|
||||
}],
|
||||
summary: vec![TrendSummaryView {
|
||||
label: "输入".to_owned(),
|
||||
value: "2".to_owned(),
|
||||
ratio: None,
|
||||
}],
|
||||
};
|
||||
let value = serde_json::to_value(data).unwrap();
|
||||
assert_eq!(value["kind"], "usage");
|
||||
assert_eq!(value["points"][0]["requestsValue"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sensitive_response_views_do_not_require_debug_or_add_secret_fields() {
|
||||
let coverage = CostCoverageView {
|
||||
known: 1,
|
||||
partial: 0,
|
||||
unknown: 0,
|
||||
not_billable: 0,
|
||||
};
|
||||
let token_details = TokenDetailsView {
|
||||
input_tokens: Some(1),
|
||||
output_tokens: Some(2),
|
||||
cached_tokens: None,
|
||||
cache_write_tokens: None,
|
||||
reasoning_tokens: None,
|
||||
total_tokens: Some(3),
|
||||
input_tokens_display: "1".to_owned(),
|
||||
output_tokens_display: "2".to_owned(),
|
||||
cached_tokens_display: "-".to_owned(),
|
||||
cache_write_tokens_display: "-".to_owned(),
|
||||
reasoning_tokens_display: "-".to_owned(),
|
||||
total_tokens_display: "3".to_owned(),
|
||||
};
|
||||
let cursor = CursorWire {
|
||||
observed_at: Utc.timestamp_opt(0, 0).single().unwrap(),
|
||||
stable_id: "request_1".to_owned(),
|
||||
};
|
||||
let value = serde_json::to_value((&coverage, &token_details, &cursor)).unwrap();
|
||||
assert!(value.to_string().contains("known"));
|
||||
assert!(!value.to_string().contains("secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn billing_view_should_preserve_the_original_detail_contract() {
|
||||
let value = serde_json::to_value(BillingView {
|
||||
input_amount_display: "$0.03".to_owned(),
|
||||
output_amount_display: "$0.00".to_owned(),
|
||||
cache_read_amount_display: "$0.14".to_owned(),
|
||||
cache_write_amount_display: "$0.00".to_owned(),
|
||||
standard_amount_display: "$0.17".to_owned(),
|
||||
total_amount_display: "$0.17".to_owned(),
|
||||
input_price_display: "$10.0000 / 1M Token".to_owned(),
|
||||
output_price_display: "$60.0000 / 1M Token".to_owned(),
|
||||
cache_read_price_display: "$1.0000 / 1M Token".to_owned(),
|
||||
cache_write_price_display: "$12.5000 / 1M Token".to_owned(),
|
||||
service_tier_display: "Fast".to_owned(),
|
||||
multiplier_display: "1.00x".to_owned(),
|
||||
})
|
||||
.expect("billing view");
|
||||
|
||||
assert_eq!(value["inputAmountDisplay"], "$0.03");
|
||||
assert_eq!(value["cacheReadPriceDisplay"], "$1.0000 / 1M Token");
|
||||
assert_eq!(value["serviceTierDisplay"], "Fast");
|
||||
assert_eq!(value["multiplierDisplay"], "1.00x");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
use gateway_api::admin::openai::{
|
||||
CompleteOAuthAuthorizationRequest, CredentialDetailsQuery, CredentialMutationRequest,
|
||||
ImportCredentialsDocumentRequest, ListCredentialsQuery, RotateCredentialRequest,
|
||||
StartOAuthAuthorizationRequest,
|
||||
};
|
||||
|
||||
fn compact_jwt() -> String {
|
||||
"header.payload.signature".to_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_import_accepts_provider_owned_object() {
|
||||
let request: ImportCredentialsDocumentRequest = serde_json::from_value(serde_json::json!({
|
||||
"expectedConfigRevision": 7,
|
||||
"providerInstanceId": "inst_openai",
|
||||
"document": {"accounts": [{"token": compact_jwt()}]}
|
||||
}))
|
||||
.expect("deserialize Provider import document");
|
||||
|
||||
assert_eq!(request.validate(), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_import_rejects_unknown_outer_fields() {
|
||||
let result = serde_json::from_value::<ImportCredentialsDocumentRequest>(serde_json::json!({
|
||||
"expectedConfigRevision": 7,
|
||||
"providerInstanceId": "inst_openai",
|
||||
"document": {"accounts": []},
|
||||
"maxConcurrency": 2
|
||||
}));
|
||||
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_import_rejects_non_object_document() {
|
||||
let array: ImportCredentialsDocumentRequest = serde_json::from_value(serde_json::json!({
|
||||
"expectedConfigRevision": 7,
|
||||
"providerInstanceId": "inst_openai",
|
||||
"document": []
|
||||
}))
|
||||
.expect("deserialize array document");
|
||||
|
||||
assert_eq!(array.validate().unwrap_err().field(), "document");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_import_keeps_provider_document_opaque_to_api() {
|
||||
let request: ImportCredentialsDocumentRequest = serde_json::from_value(serde_json::json!({
|
||||
"expectedConfigRevision": 7,
|
||||
"providerInstanceId": "inst_openai",
|
||||
"document": {
|
||||
"providerOwnedUnknownField": {"nested": [1, 2, 3]},
|
||||
"accounts": [{"credentials": {"access_token": "provider-validates-this"}}]
|
||||
}
|
||||
}))
|
||||
.expect("deserialize opaque Provider document");
|
||||
|
||||
assert_eq!(request.validate(), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_query_should_validate_status_pagination_and_reserved_ids() {
|
||||
let valid: ListCredentialsQuery = serde_json::from_value(serde_json::json!({
|
||||
"providerInstanceId": "inst_openai",
|
||||
"availability": "cooldown",
|
||||
"enabled": false,
|
||||
"cursor": "cursor",
|
||||
"limit": 200
|
||||
}))
|
||||
.expect("deserialize list query");
|
||||
let invalid_status: ListCredentialsQuery = serde_json::from_value(serde_json::json!({
|
||||
"availability": "refreshing"
|
||||
}))
|
||||
.expect("deserialize invalid status query");
|
||||
let invalid_limit: ListCredentialsQuery = serde_json::from_value(serde_json::json!({
|
||||
"limit": 201
|
||||
}))
|
||||
.expect("deserialize invalid page size query");
|
||||
|
||||
assert_eq!(valid.validate(), Ok(()));
|
||||
assert_eq!(
|
||||
invalid_status.validate().unwrap_err().field(),
|
||||
"availability"
|
||||
);
|
||||
assert_eq!(invalid_limit.validate().unwrap_err().field(), "limit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detail_and_mutation_should_reject_missing_invalid_or_overflowing_identity() {
|
||||
let detail = CredentialDetailsQuery {
|
||||
credential_id: "__reserved__".to_owned(),
|
||||
};
|
||||
let mutation = CredentialMutationRequest {
|
||||
credential_id: "cred_codex".to_owned(),
|
||||
expected_config_revision: 0,
|
||||
};
|
||||
let rotation: RotateCredentialRequest = serde_json::from_value(serde_json::json!({
|
||||
"credentialId": "cred_codex",
|
||||
"expectedConfigRevision": 1,
|
||||
"expectedCredentialRevision": u64::MAX,
|
||||
"accessToken": compact_jwt()
|
||||
}))
|
||||
.expect("deserialize overflowing revision");
|
||||
|
||||
assert_eq!(detail.validate().unwrap_err().field(), "credentialId");
|
||||
assert_eq!(
|
||||
mutation.validate().unwrap_err().field(),
|
||||
"expectedConfigRevision"
|
||||
);
|
||||
assert_eq!(
|
||||
rotation.validate().unwrap_err().field(),
|
||||
"expectedCredentialRevision"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oauth_wire_should_keep_flow_id_and_callback_in_post_body_only() {
|
||||
let start: StartOAuthAuthorizationRequest = serde_json::from_value(serde_json::json!({
|
||||
"expectedConfigRevision": 7,
|
||||
"providerInstanceId": "inst_openai",
|
||||
"name": "OAuth browser flow",
|
||||
"credentialId": "acct_existing",
|
||||
"expectedCredentialRevision": 9
|
||||
}))
|
||||
.expect("start wire");
|
||||
let complete: CompleteOAuthAuthorizationRequest = serde_json::from_value(serde_json::json!({
|
||||
"flowId": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
|
||||
"callbackUrl": "http://localhost:1455/auth/callback?code=code&state=state"
|
||||
}))
|
||||
.expect("complete wire");
|
||||
let client_state =
|
||||
serde_json::from_value::<StartOAuthAuthorizationRequest>(serde_json::json!({
|
||||
"expectedConfigRevision": 7,
|
||||
"providerInstanceId": "inst_openai",
|
||||
"name": "OAuth browser flow",
|
||||
"state": "client-controlled"
|
||||
}))
|
||||
.expect_err("state must remain server-side");
|
||||
|
||||
assert_eq!(start.validate(), Ok(()));
|
||||
assert_eq!(complete.validate(), Ok(()));
|
||||
assert!(client_state.to_string().contains("unknown field `state`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oauth_reauthorization_requires_account_and_revision_together() {
|
||||
let missing_revision: StartOAuthAuthorizationRequest =
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"expectedConfigRevision": 7,
|
||||
"providerInstanceId": "inst_openai",
|
||||
"name": "OAuth browser flow",
|
||||
"credentialId": "acct_existing"
|
||||
}))
|
||||
.expect("deserialize incomplete reauthorization");
|
||||
|
||||
assert_eq!(
|
||||
missing_revision.validate().unwrap_err().field(),
|
||||
"reauthorization"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use axum::{
|
||||
Router,
|
||||
body::{Body, to_bytes},
|
||||
http::{Method, Request, StatusCode, header},
|
||||
};
|
||||
use chrono::Utc;
|
||||
use gateway_api::admin::{
|
||||
AdminRequestContext, AdminServiceError, AdminSessionResolver, AdminSessionState,
|
||||
RuntimeSettingsView, UpdateRuntimeSettingsRequest,
|
||||
settings::{self, AdminSettingsService, AdminSettingsState},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use tower::ServiceExt;
|
||||
|
||||
struct FakeSettings {
|
||||
settings: Mutex<RuntimeSettingsView>,
|
||||
key_exists: Mutex<bool>,
|
||||
}
|
||||
|
||||
impl Default for FakeSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
settings: Mutex::new(runtime_settings()),
|
||||
key_exists: Mutex::new(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AdminSessionResolver for FakeSettings {
|
||||
async fn resolve_admin_user_id(
|
||||
&self,
|
||||
session_id: Option<&str>,
|
||||
) -> Result<Option<String>, AdminServiceError> {
|
||||
Ok((session_id == Some("valid-session")).then(|| "admin_1".to_owned()))
|
||||
}
|
||||
|
||||
async fn verify_admin_api_key(&self, key: &str) -> Result<bool, AdminServiceError> {
|
||||
Ok(key == "admin-valid-test-key")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AdminSettingsService for FakeSettings {
|
||||
async fn load(&self) -> Result<RuntimeSettingsView, AdminServiceError> {
|
||||
Ok(self.settings.lock().expect("settings state").clone())
|
||||
}
|
||||
|
||||
async fn replace(
|
||||
&self,
|
||||
context: &AdminRequestContext,
|
||||
request: UpdateRuntimeSettingsRequest,
|
||||
) -> Result<RuntimeSettingsView, AdminServiceError> {
|
||||
assert_eq!(context.admin_user_id(), Some("admin_1"));
|
||||
let settings = RuntimeSettingsView {
|
||||
config_revision: request.expected_config_revision + 1,
|
||||
provider_model_mappings: request.provider_model_mappings,
|
||||
refresh_margin_seconds: request.refresh_margin_seconds,
|
||||
refresh_concurrency: request.refresh_concurrency,
|
||||
max_concurrent_per_account: request.max_concurrent_per_account,
|
||||
request_interval_ms: request.request_interval_ms,
|
||||
rotation_strategy: request.rotation_strategy,
|
||||
usage_retention_days: request.usage_retention_days,
|
||||
ops_event_retention_days: request.ops_event_retention_days,
|
||||
audit_retention_days: request.audit_retention_days,
|
||||
updated_at: Utc::now(),
|
||||
};
|
||||
*self.settings.lock().expect("settings state") = settings.clone();
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
async fn admin_api_key_exists(&self) -> Result<bool, AdminServiceError> {
|
||||
Ok(*self.key_exists.lock().expect("key state"))
|
||||
}
|
||||
|
||||
async fn regenerate_admin_api_key(
|
||||
&self,
|
||||
_context: &AdminRequestContext,
|
||||
) -> Result<String, AdminServiceError> {
|
||||
*self.key_exists.lock().expect("key state") = true;
|
||||
Ok("admin-generated-secret-once".to_owned())
|
||||
}
|
||||
|
||||
async fn delete_admin_api_key(
|
||||
&self,
|
||||
_context: &AdminRequestContext,
|
||||
) -> Result<(), AdminServiceError> {
|
||||
*self.key_exists.lock().expect("key state") = false;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestState(Arc<FakeSettings>);
|
||||
|
||||
impl AdminSessionState for TestState {
|
||||
fn admin_session_resolver(&self) -> &dyn AdminSessionResolver {
|
||||
self.0.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl AdminSettingsState for TestState {
|
||||
fn admin_settings_service(&self) -> &dyn AdminSettingsService {
|
||||
self.0.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
fn app(settings: Arc<FakeSettings>) -> Router {
|
||||
settings::router::<TestState>().with_state(TestState(settings))
|
||||
}
|
||||
|
||||
fn request(method: Method, path: &str, body: Option<Value>) -> Request<Body> {
|
||||
let mut builder = Request::builder()
|
||||
.method(method)
|
||||
.uri(path)
|
||||
.header(header::COOKIE, "cpr_admin_session=valid-session")
|
||||
.header("x-request-id", "req_admin_settings");
|
||||
let body = if let Some(value) = body {
|
||||
builder = builder.header(header::CONTENT_TYPE, "application/json");
|
||||
Body::from(value.to_string())
|
||||
} else {
|
||||
Body::empty()
|
||||
};
|
||||
builder.body(body).expect("build settings request")
|
||||
}
|
||||
|
||||
async fn response_json(response: axum::response::Response) -> Value {
|
||||
let bytes = to_bytes(response.into_body(), 1024 * 1024)
|
||||
.await
|
||||
.expect("read response body");
|
||||
serde_json::from_slice(&bytes).expect("parse response JSON")
|
||||
}
|
||||
|
||||
fn runtime_settings() -> RuntimeSettingsView {
|
||||
RuntimeSettingsView {
|
||||
config_revision: 7,
|
||||
provider_model_mappings: BTreeMap::from([
|
||||
(
|
||||
"openai".to_owned(),
|
||||
BTreeMap::from([("coding-default".to_owned(), "gpt-5.4".to_owned())]),
|
||||
),
|
||||
(
|
||||
"xai".to_owned(),
|
||||
BTreeMap::from([("grok-latest".to_owned(), "grok-4.5".to_owned())]),
|
||||
),
|
||||
]),
|
||||
refresh_margin_seconds: 3600,
|
||||
refresh_concurrency: 2,
|
||||
max_concurrent_per_account: 3,
|
||||
request_interval_ms: 50,
|
||||
rotation_strategy: "smart".into(),
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 90,
|
||||
updated_at: Utc::now(),
|
||||
}
|
||||
}
|
||||
|
||||
fn update_body() -> Value {
|
||||
json!({
|
||||
"expectedConfigRevision": 7,
|
||||
"providerModelMappings": {
|
||||
"openai": { "gpt-5.4": "gpt-5.5" },
|
||||
"xai": { "grok-latest": "grok-4.5" }
|
||||
},
|
||||
"refreshMarginSeconds": 1800,
|
||||
"refreshConcurrency": 4,
|
||||
"maxConcurrentPerAccount": 5,
|
||||
"requestIntervalMs": 25,
|
||||
"rotationStrategy": "round_robin",
|
||||
"usageRetentionDays": 32,
|
||||
"opsEventRetentionDays": 31,
|
||||
"auditRetentionDays": 91
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_request_should_reject_unknown_rotation_strategy() {
|
||||
let mut body = update_body();
|
||||
body["rotationStrategy"] = json!("random");
|
||||
let request: UpdateRuntimeSettingsRequest =
|
||||
serde_json::from_value(body).expect("decode settings");
|
||||
|
||||
assert_eq!(request.validate().unwrap_err().field(), "rotationStrategy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_request_should_require_positive_revision() {
|
||||
let mut body = update_body();
|
||||
body["expectedConfigRevision"] = json!(0);
|
||||
let request: UpdateRuntimeSettingsRequest =
|
||||
serde_json::from_value(body).expect("decode settings");
|
||||
assert_eq!(
|
||||
request.validate().unwrap_err().field(),
|
||||
"expectedConfigRevision"
|
||||
);
|
||||
|
||||
let mut missing = update_body();
|
||||
missing
|
||||
.as_object_mut()
|
||||
.expect("settings object")
|
||||
.remove("expectedConfigRevision");
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(missing).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_request_should_reject_removed_bucket_retention() {
|
||||
let mut body = update_body();
|
||||
body["bucketRetentionDays"] = json!(365);
|
||||
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(body).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settings_get_should_preserve_provider_scoped_model_mappings() {
|
||||
let response = app(Arc::new(FakeSettings::default()))
|
||||
.oneshot(request(Method::GET, "/api/admin/settings", None))
|
||||
.await
|
||||
.expect("settings response");
|
||||
let data = response_json(response).await["data"].clone();
|
||||
|
||||
assert_eq!(
|
||||
(
|
||||
data["providerModelMappings"]["openai"]["coding-default"].as_str(),
|
||||
data["providerModelMappings"]["xai"]["grok-latest"].as_str(),
|
||||
data["rotationStrategy"].as_str()
|
||||
),
|
||||
(Some("gpt-5.4"), Some("grok-4.5"), Some("smart"))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settings_post_should_replace_provider_scoped_model_mappings() {
|
||||
let response = app(Arc::new(FakeSettings::default()))
|
||||
.oneshot(request(
|
||||
Method::POST,
|
||||
"/api/admin/settings",
|
||||
Some(update_body()),
|
||||
))
|
||||
.await
|
||||
.expect("settings update response");
|
||||
let data = response_json(response).await["data"].clone();
|
||||
|
||||
assert_eq!(data["configRevision"], 8);
|
||||
assert_eq!(
|
||||
data["providerModelMappings"]["openai"]["gpt-5.4"],
|
||||
"gpt-5.5"
|
||||
);
|
||||
assert_eq!(
|
||||
data["providerModelMappings"]["xai"]["grok-latest"],
|
||||
"grok-4.5"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_request_should_reject_invalid_provider_mapping_slug() {
|
||||
let mut body = update_body();
|
||||
body["providerModelMappings"] = json!({
|
||||
"OpenAI": { "gpt-5.4": "gpt-5.5" }
|
||||
});
|
||||
let request: UpdateRuntimeSettingsRequest =
|
||||
serde_json::from_value(body).expect("decode settings");
|
||||
|
||||
assert_eq!(
|
||||
request.validate().unwrap_err().field(),
|
||||
"providerModelMappings"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settings_should_require_admin_auth() {
|
||||
let response = app(Arc::new(FakeSettings::default()))
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/admin/settings")
|
||||
.header("x-request-id", "req_unauthorized")
|
||||
.body(Body::empty())
|
||||
.expect("unauthorized request"),
|
||||
)
|
||||
.await
|
||||
.expect("unauthorized response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn admin_key_should_return_secret_only_on_regenerate() {
|
||||
let response = app(Arc::new(FakeSettings::default()))
|
||||
.oneshot(request(
|
||||
Method::POST,
|
||||
"/api/admin/settings/admin-api-key/regenerate",
|
||||
None,
|
||||
))
|
||||
.await
|
||||
.expect("regenerate response");
|
||||
let data = response_json(response).await["data"].clone();
|
||||
|
||||
assert_eq!(data["key"], "admin-generated-secret-once");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn admin_key_delete_should_use_fixed_post_path() {
|
||||
let settings = Arc::new(FakeSettings::default());
|
||||
*settings.key_exists.lock().expect("key state") = true;
|
||||
let response = app(settings)
|
||||
.oneshot(request(
|
||||
Method::POST,
|
||||
"/api/admin/settings/admin-api-key",
|
||||
None,
|
||||
))
|
||||
.await
|
||||
.expect("delete response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settings_should_accept_admin_api_key_header() {
|
||||
let response = app(Arc::new(FakeSettings::default()))
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/api/admin/settings")
|
||||
.header("x-api-key", "admin-valid-test-key")
|
||||
.header("x-request-id", "req_api_key")
|
||||
.body(Body::empty())
|
||||
.expect("api key request"),
|
||||
)
|
||||
.await
|
||||
.expect("api key response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
use gateway_api::admin::system::{UpdateDetailQuery, UpdateRequest};
|
||||
|
||||
#[test]
|
||||
fn update_detail_query_should_default_to_no_refresh_and_reject_unknown_fields() {
|
||||
let query: UpdateDetailQuery = serde_json::from_str("{}").expect("empty query object");
|
||||
assert!(!query.refresh());
|
||||
assert!(serde_json::from_str::<UpdateDetailQuery>(r#"{"refresh":true,"extra":1}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_request_should_preserve_target_version_for_domain_validation() {
|
||||
let request: UpdateRequest =
|
||||
serde_json::from_str(r#"{"targetVersion":"v0.2.0"}"#).expect("update request");
|
||||
assert_eq!(request.into_target_version(), "v0.2.0");
|
||||
assert!(
|
||||
serde_json::from_str::<UpdateRequest>(r#"{"targetVersion":"v0.2.0","extra":1}"#).is_err()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
mod common {
|
||||
use gateway_api::admin::PageMeta;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn page_meta_should_keep_the_existing_camel_case_wire_shape() {
|
||||
let value = serde_json::to_value(PageMeta::new(2, 10, 21, 3))
|
||||
.expect("page metadata should serialize");
|
||||
|
||||
assert_eq!(
|
||||
value,
|
||||
json!({
|
||||
"page": 2,
|
||||
"pageSize": 10,
|
||||
"total": 21,
|
||||
"totalPages": 3
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
mod error {
|
||||
use gateway_api::admin::{AdminErrorBody, AdminErrorCode};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn error_codes_should_keep_all_published_numeric_values() {
|
||||
let actual = [
|
||||
AdminErrorCode::MALFORMED_JSON,
|
||||
AdminErrorCode::BAD_REQUEST,
|
||||
AdminErrorCode::INVALID_TIME_RANGE,
|
||||
AdminErrorCode::INVALID_MODEL_SOURCE,
|
||||
AdminErrorCode::SESSION_REQUIRED,
|
||||
AdminErrorCode::INVALID_CREDENTIALS,
|
||||
AdminErrorCode::INVALID_API_KEY,
|
||||
AdminErrorCode::NOT_FOUND,
|
||||
AdminErrorCode::CONFLICT,
|
||||
AdminErrorCode::TOO_MANY_LOGIN_ATTEMPTS,
|
||||
AdminErrorCode::SETTINGS_PERSIST,
|
||||
AdminErrorCode::INTERNAL,
|
||||
AdminErrorCode::USAGE_RECORD_ACCOUNTS,
|
||||
AdminErrorCode::BAD_GATEWAY,
|
||||
AdminErrorCode::SERVICE_UNAVAILABLE,
|
||||
]
|
||||
.map(AdminErrorCode::value);
|
||||
|
||||
assert_eq!(
|
||||
actual,
|
||||
[
|
||||
40000, 40001, 40002, 40003, 40101, 40102, 40103, 40401, 40901, 42901, 50000, 50001,
|
||||
50002, 50201, 50301,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_admin_api_key_should_keep_code_and_null_data() {
|
||||
let value = serde_json::to_value(AdminErrorBody::new(
|
||||
AdminErrorCode::INVALID_API_KEY,
|
||||
"Invalid admin API key",
|
||||
))
|
||||
.expect("admin error body should serialize");
|
||||
|
||||
assert_eq!(
|
||||
value,
|
||||
json!({
|
||||
"code": 40103,
|
||||
"message": "Invalid admin API key",
|
||||
"data": null
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
mod response {
|
||||
use axum::{
|
||||
body::to_bytes,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use gateway_api::admin::{AdminEnvelope, AdminError, AdminPageData, AdminResponse, PageMeta};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn success_envelope_should_keep_the_existing_wire_shape() {
|
||||
let value = serde_json::to_value(AdminEnvelope::ok(json!({ "id": "resource_1" })))
|
||||
.expect("admin success envelope should serialize");
|
||||
|
||||
assert_eq!(
|
||||
value,
|
||||
json!({
|
||||
"code": 200,
|
||||
"message": "OK",
|
||||
"data": { "id": "resource_1" }
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_envelope_should_keep_items_and_page_nested_under_data() {
|
||||
let data = AdminPageData::new(
|
||||
vec![json!({ "id": "resource_1" })],
|
||||
PageMeta::new(2, 10, 21, 3),
|
||||
);
|
||||
let value = serde_json::to_value(AdminEnvelope::ok(data))
|
||||
.expect("admin page envelope should serialize");
|
||||
|
||||
assert_eq!(
|
||||
value,
|
||||
json!({
|
||||
"code": 200,
|
||||
"message": "OK",
|
||||
"data": {
|
||||
"items": [{ "id": "resource_1" }],
|
||||
"page": {
|
||||
"page": 2,
|
||||
"pageSize": 10,
|
||||
"total": 21,
|
||||
"totalPages": 3
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async fn response_json(response: Response) -> serde_json::Value {
|
||||
let body = to_bytes(response.into_body(), 1024 * 1024)
|
||||
.await
|
||||
.expect("read admin response body");
|
||||
serde_json::from_slice(&body).expect("parse admin response body")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn admin_response_should_keep_http_status_independent_from_envelope_code() {
|
||||
let response: Response = AdminResponse::new(
|
||||
StatusCode::CREATED,
|
||||
AdminEnvelope::ok(json!({ "id": "resource_created" })),
|
||||
)
|
||||
.into_response();
|
||||
let status = response.status();
|
||||
let body = response_json(response).await;
|
||||
|
||||
assert_eq!(
|
||||
(status, body["code"].as_u64()),
|
||||
(StatusCode::CREATED, Some(200))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_admin_api_key_should_keep_its_published_wire_contract() {
|
||||
let response = AdminError::invalid_admin_api_key().into_response();
|
||||
let status = response.status();
|
||||
let body = response_json(response).await;
|
||||
|
||||
assert_eq!(
|
||||
(status, body),
|
||||
(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
json!({
|
||||
"code": 40103,
|
||||
"message": "Invalid admin API key",
|
||||
"data": null
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn admin_error_variants_should_use_stable_http_and_null_data_contract() {
|
||||
let cases = [
|
||||
(
|
||||
AdminError::bad_request("bad input"),
|
||||
StatusCode::BAD_REQUEST,
|
||||
40001,
|
||||
),
|
||||
(
|
||||
AdminError::admin_session_required(),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
40101,
|
||||
),
|
||||
(
|
||||
AdminError::invalid_admin_credentials(),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
40102,
|
||||
),
|
||||
(
|
||||
AdminError::too_many_login_attempts(),
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
42901,
|
||||
),
|
||||
(
|
||||
AdminError::conflict("conflict"),
|
||||
StatusCode::CONFLICT,
|
||||
40901,
|
||||
),
|
||||
(
|
||||
AdminError::not_found("missing"),
|
||||
StatusCode::NOT_FOUND,
|
||||
40401,
|
||||
),
|
||||
(
|
||||
AdminError::internal("internal"),
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
50001,
|
||||
),
|
||||
(
|
||||
AdminError::bad_gateway("upstream"),
|
||||
StatusCode::BAD_GATEWAY,
|
||||
50201,
|
||||
),
|
||||
(
|
||||
AdminError::service_unavailable("storage"),
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
50301,
|
||||
),
|
||||
];
|
||||
|
||||
for (error, expected_status, expected_code) in cases {
|
||||
let response = error.into_response();
|
||||
let status = response.status();
|
||||
let body = response_json(response).await;
|
||||
|
||||
assert_eq!(status, expected_status);
|
||||
assert_eq!(body["code"], expected_code);
|
||||
assert!(body["message"].is_string());
|
||||
assert!(body["data"].is_null());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
use chrono::{TimeZone, Utc};
|
||||
use gateway_api::admin::xai::{
|
||||
AuthorizationStartData, CompleteAuthorizationRequest, NewCredentialRequest,
|
||||
StartAuthorizationRequest, XaiCredentialImportData, XaiCredentialImportDocumentRequest,
|
||||
XaiCredentialListData, XaiCredentialViewData,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn valid_request() -> Value {
|
||||
json!({
|
||||
"expectedConfigRevision": 7,
|
||||
"providerInstanceId": "inst_xai",
|
||||
"document": {
|
||||
"type": "oauth-account-bundle",
|
||||
"version": 1,
|
||||
"exported_at": "2026-07-18T02:47:01Z",
|
||||
"proxies": [],
|
||||
"accounts": [{
|
||||
"name": "Grok OAuth",
|
||||
"platform": "grok",
|
||||
"type": "oauth",
|
||||
"credentials": {
|
||||
"access_token": "access-token-secret",
|
||||
"refresh_token": "refresh-token-secret",
|
||||
"token_type": "Bearer",
|
||||
"expires_at": "2026-07-18T06:47:01Z",
|
||||
"email": "ignored@example.com",
|
||||
"base_url": "https://cli-chat-proxy.grok.com/v1",
|
||||
"id_token": "header.payload.signature",
|
||||
"client_id": "official-client",
|
||||
"scope": "openid offline_access grok-cli:access api:access"
|
||||
},
|
||||
"extra": {"email": "also-ignored@example.com"},
|
||||
"concurrency": 1,
|
||||
"priority": 0
|
||||
}]
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_document_accepts_opaque_provider_owned_shape() {
|
||||
let request: XaiCredentialImportDocumentRequest =
|
||||
serde_json::from_value(valid_request()).expect("deserialize Provider document");
|
||||
|
||||
request
|
||||
.validate()
|
||||
.expect("validate Provider document boundary");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_document_keeps_inner_schema_owned_by_provider() {
|
||||
let mut request = valid_request();
|
||||
request["document"]["accounts"][0]["credentials"]["provider_future_field"] =
|
||||
json!({"nested": true});
|
||||
|
||||
let request = serde_json::from_value::<XaiCredentialImportDocumentRequest>(request)
|
||||
.expect("API must not decode Provider fields");
|
||||
|
||||
assert_eq!(request.validate(), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_document_rejects_unknown_outer_field() {
|
||||
let mut request = valid_request();
|
||||
request["schemaVersion"] = json!(1);
|
||||
let error = serde_json::from_value::<XaiCredentialImportDocumentRequest>(request)
|
||||
.err()
|
||||
.expect("unknown API field must fail");
|
||||
|
||||
assert!(error.to_string().contains("unknown field `schemaVersion`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_document_rejects_non_object_document() {
|
||||
let mut request = valid_request();
|
||||
request["document"] = json!([]);
|
||||
let request: XaiCredentialImportDocumentRequest =
|
||||
serde_json::from_value(request).expect("deserialize generic JSON");
|
||||
|
||||
assert_eq!(request.validate().unwrap_err().field(), "document");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_response_should_never_contain_identity_or_secret_fields() {
|
||||
let response = XaiCredentialImportData::new(8, vec!["cred_xai_safe".to_owned()]);
|
||||
let rendered = serde_json::to_string(&response).expect("serialize response");
|
||||
|
||||
assert_eq!(
|
||||
rendered,
|
||||
r#"{"configRevision":8,"importedCount":1,"credentialIds":["cred_xai_safe"]}"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_list_wire_should_expose_only_safe_view_fields() {
|
||||
let timestamp = Utc
|
||||
.with_ymd_and_hms(2026, 7, 18, 3, 0, 0)
|
||||
.single()
|
||||
.expect("valid fixture timestamp");
|
||||
let response = XaiCredentialListData {
|
||||
config_revision: 8,
|
||||
items: vec![XaiCredentialViewData {
|
||||
id: "cred_xai_safe".to_owned(),
|
||||
provider_instance_id: "inst_xai".to_owned(),
|
||||
name: "Grok OAuth".to_owned(),
|
||||
email: Some("verified@example.com".to_owned()),
|
||||
upstream_user_id: "subject_xai".to_owned(),
|
||||
upstream_account_id: None,
|
||||
plan_type: Some("pro".to_owned()),
|
||||
enabled: true,
|
||||
credential_revision: 2,
|
||||
has_refresh_token: true,
|
||||
availability: "ready".to_owned(),
|
||||
availability_reason: None,
|
||||
access_token_expires_at: timestamp,
|
||||
next_refresh_at: Some(timestamp),
|
||||
cooldown_until: None,
|
||||
created_at: timestamp,
|
||||
updated_at: timestamp,
|
||||
}],
|
||||
};
|
||||
let rendered = serde_json::to_string(&response).expect("serialize typed list response");
|
||||
|
||||
assert!(rendered.contains("credentialRevision"));
|
||||
assert!(rendered.contains("accessTokenExpiresAt"));
|
||||
for forbidden in [
|
||||
"\"accessToken\":",
|
||||
"\"refreshToken\":",
|
||||
"\"idToken\":",
|
||||
"\"subject\":",
|
||||
] {
|
||||
assert!(!rendered.contains(forbidden), "wire leaked {forbidden}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authorization_start_wire_contains_only_browser_flow_fields() {
|
||||
let response = AuthorizationStartData {
|
||||
flow_id: "flow_xai_safe".to_owned(),
|
||||
authorization_url: "https://auth.x.ai/oauth2/auth?state=redacted".to_owned(),
|
||||
expires_at: Utc::now(),
|
||||
};
|
||||
let rendered = serde_json::to_string(&response).expect("serialize authorization response");
|
||||
|
||||
assert!(rendered.contains("authorizationUrl"));
|
||||
assert!(!rendered.contains("codeVerifier"));
|
||||
assert!(!rendered.contains("nonce"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authorization_requests_require_server_owned_flow_and_full_callback_url() {
|
||||
let start = StartAuthorizationRequest {
|
||||
credential: NewCredentialRequest {
|
||||
expected_config_revision: 7,
|
||||
provider_instance_id: "inst_xai".to_owned(),
|
||||
name: "xAI OAuth".to_owned(),
|
||||
},
|
||||
};
|
||||
start.validate().expect("authorization start is valid");
|
||||
|
||||
let complete: CompleteAuthorizationRequest = serde_json::from_value(json!({
|
||||
"flowId": "flow_xai_safe",
|
||||
"callbackUrl": "http://127.0.0.1:56121/callback?code=redacted&state=redacted"
|
||||
}))
|
||||
.expect("deserialize callback completion");
|
||||
complete.validate().expect("callback completion is valid");
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
use std::{fs, path::Path};
|
||||
|
||||
#[test]
|
||||
fn manifest_should_depend_only_on_core_protocol_and_http_adapter_layers() {
|
||||
let manifest = include_str!("../Cargo.toml");
|
||||
let forbidden = [
|
||||
"codex-proxy-rs",
|
||||
"gateway-store",
|
||||
"provider-",
|
||||
"redis",
|
||||
"reqwest",
|
||||
"sqlx",
|
||||
];
|
||||
|
||||
assert!(
|
||||
forbidden
|
||||
.iter()
|
||||
.all(|dependency| !manifest.contains(dependency)),
|
||||
"gateway-api manifest contains an infrastructure/provider dependency"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_should_include_gateway_api() {
|
||||
let workspace = include_str!("../../../Cargo.toml");
|
||||
|
||||
assert!(workspace.contains("\"crates/gateway-api\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_tree_should_match_frozen_machine_manifest() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
let mut actual = rust_files(&root.join("src"));
|
||||
actual.sort();
|
||||
let mut expected = vec![
|
||||
"src/admin/accounts.rs",
|
||||
"src/admin/auth.rs",
|
||||
"src/admin/catalog.rs",
|
||||
"src/admin/client_keys.rs",
|
||||
"src/admin/openai.rs",
|
||||
"src/admin/mod.rs",
|
||||
"src/admin/observability.rs",
|
||||
"src/admin/settings.rs",
|
||||
"src/admin/system.rs",
|
||||
"src/admin/wire.rs",
|
||||
"src/admin/xai.rs",
|
||||
"src/lib.rs",
|
||||
"src/openai/auth.rs",
|
||||
"src/openai/error.rs",
|
||||
"src/openai/mod.rs",
|
||||
"src/openai/models.rs",
|
||||
"src/openai/responses/error.rs",
|
||||
"src/openai/responses/http.rs",
|
||||
"src/openai/responses/mod.rs",
|
||||
"src/openai/responses/request.rs",
|
||||
"src/openai/responses/response.rs",
|
||||
"src/openai/responses/websocket.rs",
|
||||
"src/openai/router.rs",
|
||||
"src/openai/service.rs",
|
||||
];
|
||||
expected.sort_unstable();
|
||||
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tree_should_match_frozen_rust_mirror() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
let mut actual = rust_files(&root.join("tests"));
|
||||
actual.sort();
|
||||
let mut expected = vec![
|
||||
"tests/admin/accounts.rs",
|
||||
"tests/admin/auth.rs",
|
||||
"tests/admin/catalog.rs",
|
||||
"tests/admin/client_keys.rs",
|
||||
"tests/admin/openai.rs",
|
||||
"tests/admin/mod.rs",
|
||||
"tests/admin/observability.rs",
|
||||
"tests/admin/settings.rs",
|
||||
"tests/admin/system.rs",
|
||||
"tests/admin/wire.rs",
|
||||
"tests/admin/xai.rs",
|
||||
"tests/architecture.rs",
|
||||
"tests/main.rs",
|
||||
"tests/openai/auth.rs",
|
||||
"tests/openai/error.rs",
|
||||
"tests/openai/mod.rs",
|
||||
"tests/openai/models.rs",
|
||||
"tests/openai/responses/http.rs",
|
||||
"tests/openai/responses/mod.rs",
|
||||
"tests/openai/responses/websocket.rs",
|
||||
"tests/openai/router.rs",
|
||||
];
|
||||
expected.sort_unstable();
|
||||
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frozen_openai_fixture_set_should_be_complete() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/openai/responses/fixtures");
|
||||
let files = all_files(&root);
|
||||
|
||||
assert_eq!(files.len(), 69);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admin_routes_should_use_only_get_post_and_static_paths() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/admin");
|
||||
let mut combined = String::new();
|
||||
for path in all_files(&root) {
|
||||
if path.extension().and_then(|value| value.to_str()) == Some("rs") {
|
||||
combined.push_str(&fs::read_to_string(path).expect("read admin source"));
|
||||
}
|
||||
}
|
||||
|
||||
assert!(
|
||||
!combined.contains("routing::put")
|
||||
&& !combined.contains("routing::patch")
|
||||
&& !combined.contains("routing::delete")
|
||||
&& !combined.contains("/:id")
|
||||
&& !combined.contains("/{id}")
|
||||
);
|
||||
}
|
||||
|
||||
fn rust_files(root: &Path) -> Vec<String> {
|
||||
let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
all_files(root)
|
||||
.into_iter()
|
||||
.filter(|path| path.extension().and_then(|value| value.to_str()) == Some("rs"))
|
||||
.map(|path| {
|
||||
path.strip_prefix(manifest)
|
||||
.expect("path below manifest")
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn all_files(root: &Path) -> Vec<std::path::PathBuf> {
|
||||
let mut files = Vec::new();
|
||||
let mut pending = vec![root.to_path_buf()];
|
||||
while let Some(path) = pending.pop() {
|
||||
for entry in fs::read_dir(path).expect("read architecture directory") {
|
||||
let path = entry.expect("read architecture entry").path();
|
||||
if path.is_dir() {
|
||||
pending.push(path);
|
||||
} else {
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
files
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
mod admin;
|
||||
mod architecture;
|
||||
mod openai;
|
||||
@@ -0,0 +1,90 @@
|
||||
use axum::http::{HeaderMap, HeaderValue, header::AUTHORIZATION};
|
||||
|
||||
use gateway_api::openai::auth::{ClientApiKeyAuthError, bearer_client_api_key};
|
||||
|
||||
#[test]
|
||||
fn bearer_client_api_key_should_reject_missing_authorization() {
|
||||
assert_eq!(
|
||||
bearer_client_api_key(&HeaderMap::new()),
|
||||
Err(ClientApiKeyAuthError::MissingAuthorization)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bearer_client_api_key_should_reject_non_utf8_authorization() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_bytes(&[0xff]).expect("opaque header value"),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
bearer_client_api_key(&headers),
|
||||
Err(ClientApiKeyAuthError::MalformedAuthorization)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bearer_client_api_key_should_require_exact_bearer_scheme() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(AUTHORIZATION, HeaderValue::from_static("bearer sk_client"));
|
||||
|
||||
assert_eq!(
|
||||
bearer_client_api_key(&headers),
|
||||
Err(ClientApiKeyAuthError::MalformedAuthorization)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bearer_client_api_key_should_reject_empty_bearer_token() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer "));
|
||||
|
||||
assert_eq!(
|
||||
bearer_client_api_key(&headers),
|
||||
Err(ClientApiKeyAuthError::MalformedAuthorization)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bearer_client_api_key_should_reject_non_gateway_key_prefix() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer xai-secret"));
|
||||
|
||||
assert_eq!(
|
||||
bearer_client_api_key(&headers),
|
||||
Err(ClientApiKeyAuthError::InvalidKeyFormat)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bearer_client_api_key_should_return_trimmed_gateway_key() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer sk_client_secret "),
|
||||
);
|
||||
|
||||
assert_eq!(bearer_client_api_key(&headers), Ok("sk_client_secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_auth_failure_reasons_should_be_stable_and_secret_free() {
|
||||
assert_eq!(
|
||||
[
|
||||
ClientApiKeyAuthError::MissingAuthorization,
|
||||
ClientApiKeyAuthError::MalformedAuthorization,
|
||||
ClientApiKeyAuthError::InvalidKeyFormat,
|
||||
ClientApiKeyAuthError::InvalidKey,
|
||||
ClientApiKeyAuthError::RuntimeUnavailable,
|
||||
]
|
||||
.map(ClientApiKeyAuthError::reason),
|
||||
[
|
||||
"missing_authorization",
|
||||
"malformed_authorization",
|
||||
"invalid_key_format",
|
||||
"invalid_key",
|
||||
"runtime_unavailable",
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
use axum::http::StatusCode;
|
||||
use gateway_core::engine::{EngineError, UpstreamSendState};
|
||||
use gateway_core::error::{
|
||||
GatewayError, GatewayErrorKind, ProviderError, ProviderErrorKind, StoreError, StoreErrorKind,
|
||||
};
|
||||
|
||||
use gateway_api::openai::error::{
|
||||
gateway_error_contract, gateway_error_from_engine, openai_error_response,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn invalid_request_error_should_map_to_openai_bad_request() {
|
||||
assert_eq!(
|
||||
gateway_error_contract(GatewayErrorKind::InvalidRequest),
|
||||
(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"invalid_request_error",
|
||||
"invalid_request",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_error_should_map_to_openai_bad_request() {
|
||||
assert_eq!(
|
||||
gateway_error_contract(GatewayErrorKind::Unsupported),
|
||||
(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"invalid_request_error",
|
||||
"unsupported_capability",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_not_found_error_should_map_to_openai_model_not_found() {
|
||||
assert_eq!(
|
||||
gateway_error_contract(GatewayErrorKind::ModelNotFound),
|
||||
(
|
||||
StatusCode::NOT_FOUND,
|
||||
"invalid_request_error",
|
||||
"model_not_found",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_available_provider_error_should_map_to_service_unavailable() {
|
||||
assert_eq!(
|
||||
gateway_error_contract(GatewayErrorKind::NoAvailableProvider),
|
||||
(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"server_error",
|
||||
"no_available_provider",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rate_limited_error_should_map_to_openai_retryable_status() {
|
||||
assert_eq!(
|
||||
gateway_error_contract(GatewayErrorKind::RateLimited),
|
||||
(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"rate_limit_error",
|
||||
"rate_limit_exceeded",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upstream_unavailable_error_should_map_to_bad_gateway() {
|
||||
assert_eq!(
|
||||
gateway_error_contract(GatewayErrorKind::UpstreamUnavailable),
|
||||
(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"server_error",
|
||||
"upstream_unavailable",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timeout_error_should_map_to_gateway_timeout() {
|
||||
assert_eq!(
|
||||
gateway_error_contract(GatewayErrorKind::Timeout),
|
||||
(
|
||||
StatusCode::GATEWAY_TIMEOUT,
|
||||
"server_error",
|
||||
"request_timeout",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_error_should_not_be_misclassified_as_upstream_failure() {
|
||||
assert_eq!(
|
||||
gateway_error_contract(GatewayErrorKind::Cancelled),
|
||||
(
|
||||
StatusCode::REQUEST_TIMEOUT,
|
||||
"server_error",
|
||||
"request_cancelled",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_provider_error_should_preserve_retry_classification() {
|
||||
let error = EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::RateLimited,
|
||||
UpstreamSendState::Sent,
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
gateway_error_from_engine(&error).kind(),
|
||||
GatewayErrorKind::RateLimited
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
|
||||
let error = EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::Unavailable,
|
||||
UpstreamSendState::NotSent,
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
gateway_error_from_engine(&error),
|
||||
GatewayError::new(
|
||||
GatewayErrorKind::NoAvailableProvider,
|
||||
"no upstream Provider instance or account is currently available"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sent_provider_unavailability_should_remain_bad_gateway() {
|
||||
let error = EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::Unavailable,
|
||||
UpstreamSendState::Sent,
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
gateway_error_from_engine(&error).kind(),
|
||||
GatewayErrorKind::UpstreamUnavailable
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_provider_invalid_request_should_remain_a_client_request_error() {
|
||||
let error = EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::InvalidRequest,
|
||||
UpstreamSendState::Sent,
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
gateway_error_from_engine(&error).kind(),
|
||||
GatewayErrorKind::InvalidRequest
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_provider_unsupported_capability_should_remain_unsupported() {
|
||||
let error = EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::Unsupported,
|
||||
UpstreamSendState::NotSent,
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
gateway_error_from_engine(&error).kind(),
|
||||
GatewayErrorKind::Unsupported
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_provider_credential_failures_should_not_impersonate_client_auth_failures() {
|
||||
for kind in [
|
||||
ProviderErrorKind::Unauthorized,
|
||||
ProviderErrorKind::PermissionDenied,
|
||||
] {
|
||||
let error = EngineError::Provider(ProviderError::new(kind, UpstreamSendState::Sent));
|
||||
let mapped = gateway_error_from_engine(&error);
|
||||
|
||||
assert_eq!(mapped.kind(), GatewayErrorKind::UpstreamUnavailable);
|
||||
assert_eq!(
|
||||
mapped.safe_message(),
|
||||
"upstream authentication resource is unavailable"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_provider_quota_exhaustion_should_use_the_retryable_capacity_contract() {
|
||||
let error = EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::QuotaExhausted,
|
||||
UpstreamSendState::Sent,
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
gateway_error_from_engine(&error).kind(),
|
||||
GatewayErrorKind::RateLimited
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_provider_timeout_and_cancellation_should_remain_distinct() {
|
||||
let timeout = EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::Timeout,
|
||||
UpstreamSendState::Ambiguous,
|
||||
));
|
||||
let cancelled = EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::Cancelled,
|
||||
UpstreamSendState::Sent,
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
(
|
||||
gateway_error_from_engine(&timeout).kind(),
|
||||
gateway_error_from_engine(&cancelled).kind(),
|
||||
),
|
||||
(GatewayErrorKind::Timeout, GatewayErrorKind::Cancelled)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_provider_runtime_failures_should_collapse_to_safe_unavailability() {
|
||||
for kind in [
|
||||
ProviderErrorKind::Transport,
|
||||
ProviderErrorKind::Protocol,
|
||||
ProviderErrorKind::Unavailable,
|
||||
ProviderErrorKind::ProcessTerminated,
|
||||
] {
|
||||
let error = EngineError::Provider(ProviderError::new(kind, UpstreamSendState::Ambiguous));
|
||||
|
||||
assert_eq!(
|
||||
gateway_error_from_engine(&error),
|
||||
GatewayError::new(
|
||||
GatewayErrorKind::UpstreamUnavailable,
|
||||
"upstream service is unavailable"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_store_error_should_collapse_to_safe_internal_error() {
|
||||
let error = EngineError::Store(StoreError::new(StoreErrorKind::Unavailable));
|
||||
|
||||
assert_eq!(
|
||||
gateway_error_from_engine(&error),
|
||||
GatewayError::new(GatewayErrorKind::Internal, "gateway execution failed")
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn openai_error_response_should_preserve_only_safe_contract_fields() {
|
||||
let (status, body) = openai_error_response(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"upstream service is unavailable",
|
||||
"server_error",
|
||||
"upstream_unavailable",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
(status, body.0),
|
||||
(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
serde_json::json!({
|
||||
"error": {
|
||||
"message": "upstream service is unavailable",
|
||||
"type": "server_error",
|
||||
"code": "upstream_unavailable"
|
||||
}
|
||||
}),
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
mod auth;
|
||||
mod error;
|
||||
mod models;
|
||||
mod responses;
|
||||
mod router;
|
||||
@@ -0,0 +1,183 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use axum::{
|
||||
body::{Body, to_bytes},
|
||||
http::{Request, StatusCode, header::AUTHORIZATION},
|
||||
};
|
||||
use gateway_api::openai::{
|
||||
ConnectionTask, DeliveryEvent, OpenAiApiState, OpenAiClientService, ResponseExecutionSession,
|
||||
ResponsesTransport, StartedResponse, auth::ClientApiKeyAuthError,
|
||||
responses::DecodedResponsesRequest,
|
||||
};
|
||||
use gateway_core::{
|
||||
engine::EngineError,
|
||||
error::{GatewayError, GatewayErrorKind},
|
||||
event::GatewayEvent,
|
||||
routing::PublicModelId,
|
||||
};
|
||||
use tower::ServiceExt;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ModelsState;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ModelsService;
|
||||
|
||||
struct UnusedSession;
|
||||
|
||||
#[async_trait]
|
||||
impl ResponseExecutionSession for UnusedSession {
|
||||
async fn next_delivery_event(&mut self) -> Result<Option<DeliveryEvent>, EngineError> {
|
||||
unreachable!("models endpoints do not start an execution")
|
||||
}
|
||||
|
||||
async fn collect_uncommitted(&mut self) -> Result<Vec<GatewayEvent>, EngineError> {
|
||||
unreachable!("models endpoints do not start an execution")
|
||||
}
|
||||
|
||||
async fn commit_downstream(
|
||||
&mut self,
|
||||
_client_status_code: Option<u16>,
|
||||
) -> Result<(), EngineError> {
|
||||
unreachable!("models endpoints do not start an execution")
|
||||
}
|
||||
|
||||
async fn record_client_status(&mut self, _client_status_code: u16) -> Result<(), EngineError> {
|
||||
unreachable!("models endpoints do not start an execution")
|
||||
}
|
||||
|
||||
fn is_finalized(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn cancel(&self) {}
|
||||
|
||||
fn detach_finalize(self) {}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl OpenAiClientService for ModelsService {
|
||||
type Client = ();
|
||||
type Session = UnusedSession;
|
||||
|
||||
fn authenticate(&self, plaintext: &str) -> Result<Self::Client, ClientApiKeyAuthError> {
|
||||
if plaintext == "sk_models_test" {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ClientApiKeyAuthError::InvalidKey)
|
||||
}
|
||||
}
|
||||
|
||||
fn public_models(&self, _client: &Self::Client) -> Vec<String> {
|
||||
vec!["model-a".to_owned(), "model-b".to_owned()]
|
||||
}
|
||||
|
||||
fn contains_public_model(&self, _client: &Self::Client, model: &PublicModelId) -> bool {
|
||||
BTreeSet::from(["model-a", "model-b"]).contains(model.as_str())
|
||||
}
|
||||
|
||||
async fn start_response(
|
||||
&self,
|
||||
_client: Self::Client,
|
||||
_request: DecodedResponsesRequest,
|
||||
_transport: ResponsesTransport,
|
||||
) -> Result<StartedResponse<Self::Session>, GatewayError> {
|
||||
Err(GatewayError::new(
|
||||
GatewayErrorKind::Internal,
|
||||
"models test must not start a response",
|
||||
))
|
||||
}
|
||||
|
||||
fn is_shutting_down(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn spawn_connection(&self, task: ConnectionTask) {
|
||||
drop(task);
|
||||
}
|
||||
|
||||
fn next_connection_id(&self) -> String {
|
||||
"ws_models_test".to_owned()
|
||||
}
|
||||
|
||||
fn next_request_id(&self) -> String {
|
||||
"req_models_test".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl OpenAiApiState for ModelsState {
|
||||
type Service = ModelsService;
|
||||
|
||||
fn openai_client_api(&self) -> Self::Service {
|
||||
ModelsService
|
||||
}
|
||||
}
|
||||
|
||||
fn authorized_request(path: &str) -> Request<Body> {
|
||||
Request::get(path)
|
||||
.header(AUTHORIZATION, "Bearer sk_models_test")
|
||||
.body(Body::empty())
|
||||
.expect("build models request")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn models_should_encode_the_service_visible_catalog() {
|
||||
let response = gateway_api::openai::router::<ModelsState>()
|
||||
.with_state(ModelsState)
|
||||
.oneshot(authorized_request("/v1/models"))
|
||||
.await
|
||||
.expect("list models response");
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read models body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("models JSON");
|
||||
|
||||
assert_eq!(
|
||||
value,
|
||||
serde_json::json!({
|
||||
"object": "list",
|
||||
"data": [
|
||||
{"id":"model-a","object":"model","created":1700000000_i64,"owned_by":"gateway"},
|
||||
{"id":"model-b","object":"model","created":1700000000_i64,"owned_by":"gateway"}
|
||||
]
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_detail_should_keep_the_official_path_id_contract() {
|
||||
let response = gateway_api::openai::router::<ModelsState>()
|
||||
.with_state(ModelsState)
|
||||
.oneshot(authorized_request("/v1/models/model-a"))
|
||||
.await
|
||||
.expect("model detail response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_detail_should_hide_unknown_models() {
|
||||
let response = gateway_api::openai::router::<ModelsState>()
|
||||
.with_state(ModelsState)
|
||||
.oneshot(authorized_request("/v1/models/model-private"))
|
||||
.await
|
||||
.expect("unknown model response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn models_should_require_a_valid_bearer_client_key() {
|
||||
let response = gateway_api::openai::router::<ModelsState>()
|
||||
.with_state(ModelsState)
|
||||
.oneshot(
|
||||
Request::get("/v1/models")
|
||||
.body(Body::empty())
|
||||
.expect("build unauthenticated request"),
|
||||
)
|
||||
.await
|
||||
.expect("unauthenticated models response");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
event: response.completed
|
||||
data: {}
|
||||
|
||||
data: [DONE]
|
||||
|
||||
event: response.completed
|
||||
data: {}
|
||||
|
||||
data: [DONE]
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user