mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-07 08:05:32 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
096e48621a | ||
|
|
36828b1a7e | ||
|
|
05ec1a4d38 | ||
|
|
9808e5939c | ||
|
|
a58911c127 | ||
|
|
0b9e080f1b | ||
|
|
f218e31c72 | ||
|
|
83f2f55e4a | ||
|
|
0384e39289 | ||
|
|
9036288d69 | ||
|
|
77b18eec68 | ||
|
|
3f7d473bea | ||
|
|
99cf39c76d | ||
|
|
f4d0576e6b | ||
|
|
2d9510d9e3 | ||
|
|
36d6e26291 | ||
|
|
eff522f2b6 | ||
|
|
65a175d48c | ||
|
|
f1872df293 | ||
|
|
71d87c5ab9 | ||
|
|
e23689ae22 | ||
|
|
4e527feb38 | ||
|
|
537c749b73 | ||
|
|
28b89200f7 | ||
|
|
a8f5c5a54e | ||
|
|
d94bca33dd | ||
|
|
9b33e60df2 | ||
|
|
1e99c5037d | ||
|
|
26cf170f33 | ||
|
|
8d54171771 |
@@ -19,21 +19,24 @@ jobs:
|
||||
env:
|
||||
COMPOSE_PROJECT_NAME: cpr-ci-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
CPR_IMAGE: codex-proxy-rs:ci-${{ inputs.ref }}
|
||||
CPR_ADMIN_DEFAULT_PASSWORD: 'admin @:/?#%2F ci password'
|
||||
CPR_POSTGRES_PASSWORD: 'pg @:/?#%2F ci'
|
||||
CPR_REDIS_PASSWORD: 'redis @:/?#%2F ci'
|
||||
CPR_SMOKE_PORT: '18080'
|
||||
TRIVY_QUIET: 'true'
|
||||
TRIVY_SKIP_VERSION_CHECK: 'true'
|
||||
steps:
|
||||
- name: Define isolated runtime paths
|
||||
- name: Define isolated runtime values
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
admin_password="$(openssl rand -hex 24)"
|
||||
postgres_password="$(openssl rand -hex 24)"
|
||||
redis_password="$(openssl rand -hex 24)"
|
||||
echo "::add-mask::$admin_password"
|
||||
echo "::add-mask::$postgres_password"
|
||||
echo "::add-mask::$redis_password"
|
||||
{
|
||||
echo "CPR_CONFIG_FILE=$GITHUB_WORKSPACE/.runtime/ci-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT/config.yaml"
|
||||
echo "CPR_DATA_DIR=$GITHUB_WORKSPACE/.runtime/ci-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT/data"
|
||||
echo "CPR_LOG_DIR=$GITHUB_WORKSPACE/.runtime/ci-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT/logs"
|
||||
echo "DIAGNOSTICS_DIR=$RUNNER_TEMP/codex-proxy-rs-diagnostics"
|
||||
echo "CI_ADMIN_PASSWORD=$admin_password"
|
||||
echo "CI_POSTGRES_PASSWORD=$postgres_password"
|
||||
echo "CI_REDIS_PASSWORD=$redis_password"
|
||||
} >> "$GITHUB_ENV"
|
||||
|
||||
- name: Checkout
|
||||
@@ -94,19 +97,35 @@ jobs:
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
runtime_dir="$(dirname "$CPR_CONFIG_FILE")"
|
||||
mkdir -p "$runtime_dir" "$DIAGNOSTICS_DIR"
|
||||
sudo install -d -m 0770 -o "$(id -u)" -g 10001 "$CPR_DATA_DIR" "$CPR_LOG_DIR"
|
||||
cp deploy/config.example.yaml "$CPR_CONFIG_FILE"
|
||||
sudo chown "$(id -u):10001" "$CPR_CONFIG_FILE"
|
||||
chmod 0640 "$CPR_CONFIG_FILE"
|
||||
umask 0077
|
||||
# Bind roots hand off ownership to the image-specific database users.
|
||||
# Sticky directories keep that initialization compatible with user-namespaced runners.
|
||||
install -d -m 1777 .runtime/postgres .runtime/redis
|
||||
mkdir -p "$DIAGNOSTICS_DIR"
|
||||
sudo install -d -m 0770 -o "$(id -u)" -g 10001 \
|
||||
.runtime/data .runtime/logs
|
||||
ruby <<'RUBY'
|
||||
path = "deploy/config.example.yaml"
|
||||
content = File.read(path)
|
||||
replacements = {
|
||||
"password: &postgres_password ''" => "password: &postgres_password '#{ENV.fetch("CI_POSTGRES_PASSWORD")}'",
|
||||
"password: &redis_password ''" => "password: &redis_password '#{ENV.fetch("CI_REDIS_PASSWORD")}'",
|
||||
"default_password: ''" => "default_password: '#{ENV.fetch("CI_ADMIN_PASSWORD")}'",
|
||||
}
|
||||
replacements.each do |placeholder, configured|
|
||||
raise "missing config placeholder: #{placeholder}" unless content.sub!(placeholder, configured)
|
||||
end
|
||||
File.write("deploy/config.yaml", content)
|
||||
RUBY
|
||||
sudo chown "$(id -u):10001" deploy/config.yaml
|
||||
chmod 0640 deploy/config.yaml
|
||||
|
||||
- name: Validate Docker Compose
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker compose --project-name "$COMPOSE_PROJECT_NAME" \
|
||||
-f deploy/docker-compose.yml -f deploy/docker-compose.smoke.yml config --quiet
|
||||
-f deploy/compose.yaml config --quiet
|
||||
|
||||
- name: Configure Redis host memory overcommit
|
||||
shell: bash
|
||||
@@ -120,23 +139,25 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
compose=(docker compose --project-name "$COMPOSE_PROJECT_NAME" \
|
||||
-f deploy/docker-compose.yml -f deploy/docker-compose.smoke.yml)
|
||||
-f deploy/compose.yaml)
|
||||
"${compose[@]}" up -d --no-build --wait postgres redis
|
||||
"${compose[@]}" exec -T -e PGPASSWORD="$CPR_POSTGRES_PASSWORD" postgres \
|
||||
test "$("${compose[@]}" exec -T -e PGPASSWORD="$CI_POSTGRES_PASSWORD" postgres \
|
||||
psql -At -U codex_proxy -d codex_proxy -c "SHOW TimeZone;" | tr -d '\r')" = Asia/Shanghai
|
||||
"${compose[@]}" exec -T -e PGPASSWORD="$CI_POSTGRES_PASSWORD" postgres \
|
||||
psql -v ON_ERROR_STOP=1 -U codex_proxy -d codex_proxy -c \
|
||||
"CREATE TABLE cpr_ci_persistence_probe (value text PRIMARY KEY); INSERT INTO cpr_ci_persistence_probe VALUES ('persisted');"
|
||||
"${compose[@]}" exec -T -e REDISCLI_AUTH="$CPR_REDIS_PASSWORD" redis \
|
||||
"${compose[@]}" exec -T -e REDISCLI_AUTH="$CI_REDIS_PASSWORD" redis \
|
||||
redis-cli SET cpr:ci:persistence-probe persisted
|
||||
"${compose[@]}" up -d --no-build --wait --force-recreate postgres redis
|
||||
test "$("${compose[@]}" exec -T -e PGPASSWORD="$CPR_POSTGRES_PASSWORD" postgres \
|
||||
test "$("${compose[@]}" exec -T -e PGPASSWORD="$CI_POSTGRES_PASSWORD" postgres \
|
||||
psql -At -U codex_proxy -d codex_proxy -c \
|
||||
"SELECT value FROM cpr_ci_persistence_probe;")" = persisted
|
||||
test "$("${compose[@]}" exec -T -e REDISCLI_AUTH="$CPR_REDIS_PASSWORD" redis \
|
||||
test "$("${compose[@]}" exec -T -e REDISCLI_AUTH="$CI_REDIS_PASSWORD" redis \
|
||||
redis-cli --raw GET cpr:ci:persistence-probe | tr -d '\r')" = persisted
|
||||
"${compose[@]}" exec -T -e PGPASSWORD="$CPR_POSTGRES_PASSWORD" postgres \
|
||||
"${compose[@]}" exec -T -e PGPASSWORD="$CI_POSTGRES_PASSWORD" postgres \
|
||||
psql -v ON_ERROR_STOP=1 -U codex_proxy -d codex_proxy -c \
|
||||
"DROP TABLE cpr_ci_persistence_probe;"
|
||||
"${compose[@]}" exec -T -e REDISCLI_AUTH="$CPR_REDIS_PASSWORD" redis \
|
||||
"${compose[@]}" exec -T -e REDISCLI_AUTH="$CI_REDIS_PASSWORD" redis \
|
||||
redis-cli DEL cpr:ci:persistence-probe
|
||||
|
||||
- name: Start and verify application
|
||||
@@ -144,22 +165,24 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
compose=(docker compose --project-name "$COMPOSE_PROJECT_NAME" \
|
||||
-f deploy/docker-compose.yml -f deploy/docker-compose.smoke.yml)
|
||||
-f deploy/compose.yaml)
|
||||
"${compose[@]}" up -d --no-build --wait codex-proxy-rs
|
||||
status="$(curl --silent --show-error --output /dev/null --write-out '%{http_code}' \
|
||||
"http://127.0.0.1:${CPR_SMOKE_PORT}/healthz")"
|
||||
"http://127.0.0.1:8080/healthz")"
|
||||
test "$status" = 204
|
||||
test "$("${compose[@]}" exec -T codex-proxy-rs id -u | tr -d '\r')" = 10001
|
||||
test "$("${compose[@]}" exec -T codex-proxy-rs id -g | tr -d '\r')" = 10001
|
||||
test "$("${compose[@]}" exec -T codex-proxy-rs date +%z | tr -d '\r')" = +0800
|
||||
test "$("${compose[@]}" exec -T codex-proxy-rs cat /etc/timezone | tr -d '\r')" = Asia/Shanghai
|
||||
"${compose[@]}" exec -T codex-proxy-rs sh -c \
|
||||
'touch /app/data/.ci-write /app/logs/.ci-write && rm /app/data/.ci-write /app/logs/.ci-write'
|
||||
'touch /app/.runtime/data/.ci-write /app/.runtime/logs/.ci-write && rm /app/.runtime/data/.ci-write /app/.runtime/logs/.ci-write'
|
||||
|
||||
- name: Verify clean logs and graceful shutdown
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
compose=(docker compose --project-name "$COMPOSE_PROJECT_NAME" \
|
||||
-f deploy/docker-compose.yml -f deploy/docker-compose.smoke.yml)
|
||||
-f deploy/compose.yaml)
|
||||
"${compose[@]}" stop --timeout 30 codex-proxy-rs
|
||||
container_id="$("${compose[@]}" ps -a -q codex-proxy-rs)"
|
||||
test -n "$container_id"
|
||||
@@ -191,7 +214,7 @@ jobs:
|
||||
mkdir -p "$DIAGNOSTICS_DIR"
|
||||
raw_dir="$(mktemp -d)"
|
||||
compose=(docker compose --project-name "$COMPOSE_PROJECT_NAME" \
|
||||
-f deploy/docker-compose.yml -f deploy/docker-compose.smoke.yml)
|
||||
-f deploy/compose.yaml)
|
||||
"${compose[@]}" config > "$raw_dir/compose-config.yaml" 2>&1
|
||||
"${compose[@]}" ps -a > "$raw_dir/compose-ps.txt" 2>&1
|
||||
"${compose[@]}" logs --no-color --timestamps > "$raw_dir/compose.log" 2>&1
|
||||
@@ -203,9 +226,9 @@ jobs:
|
||||
raw_dir = ENV.fetch("RAW_DIR")
|
||||
output_dir = ENV.fetch("OUTPUT_DIR")
|
||||
secrets = [
|
||||
ENV.fetch("CPR_ADMIN_DEFAULT_PASSWORD"),
|
||||
ENV.fetch("CPR_POSTGRES_PASSWORD"),
|
||||
ENV.fetch("CPR_REDIS_PASSWORD"),
|
||||
ENV.fetch("CI_ADMIN_PASSWORD"),
|
||||
ENV.fetch("CI_POSTGRES_PASSWORD"),
|
||||
ENV.fetch("CI_REDIS_PASSWORD"),
|
||||
]
|
||||
encoded_secrets = secrets.map do |secret|
|
||||
secret.encode("UTF-8").bytes.map do |byte|
|
||||
@@ -239,6 +262,5 @@ jobs:
|
||||
shell: bash
|
||||
run: |
|
||||
docker compose --project-name "$COMPOSE_PROJECT_NAME" \
|
||||
-f deploy/docker-compose.yml -f deploy/docker-compose.smoke.yml \
|
||||
down --volumes --remove-orphans || true
|
||||
sudo rm -rf "$GITHUB_WORKSPACE/.runtime/ci-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT"
|
||||
-f deploy/compose.yaml down --remove-orphans || true
|
||||
sudo rm -rf "$GITHUB_WORKSPACE/.runtime" "$GITHUB_WORKSPACE/deploy/config.yaml"
|
||||
|
||||
@@ -24,7 +24,6 @@ jobs:
|
||||
CARGO_TERM_COLOR: always
|
||||
CPR_TEST_DATABASE_URL: postgres://codex_proxy:codex_proxy@127.0.0.1:5432/codex_proxy
|
||||
CPR_TEST_REDIS_URL: redis://127.0.0.1:6379
|
||||
RUSTFLAGS: -D warnings
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18-bookworm@sha256:d9c83446333daec3f0588cc709adb80c26090b7f9f0f7ec8d43c243385d79818
|
||||
@@ -56,7 +55,7 @@ jobs:
|
||||
ref: ${{ inputs.ref }}
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@eac0f66a48bc4b70a10b9acd4c4e930f835d95ff # 1.95
|
||||
uses: dtolnay/rust-toolchain@1a3a6d54512beeaffd394f8d516ca16f2c506a20 # 1.97
|
||||
with:
|
||||
components: rustfmt,clippy
|
||||
|
||||
@@ -71,7 +70,7 @@ jobs:
|
||||
|
||||
- name: Rust clippy
|
||||
working-directory: backend
|
||||
run: cargo clippy --all-targets --all-features --locked -- -D warnings
|
||||
run: cargo clippy --all-targets --all-features --locked
|
||||
|
||||
- name: Rust tests
|
||||
working-directory: backend
|
||||
|
||||
@@ -205,7 +205,7 @@ jobs:
|
||||
-v "$HOME/.cargo:/cargo" \
|
||||
-v "$PWD/..:/workspace" \
|
||||
-w /workspace/backend \
|
||||
rust:1.95-bookworm@sha256:6258907abe69656e41cd992e0b705cdcfabcbbe3db374f92ed2d47121282d4a1 \
|
||||
rust:1.97-bookworm@sha256:7d0723df719e7f213b69dc7c8c595985c3f4b060cfbee4f7bc0e347a86fe3b6a \
|
||||
cargo build --release --locked --target "${{ matrix.target }}" --bin codex-proxy-rs
|
||||
cp "target/${{ matrix.target }}/release/${{ matrix.binary }}" "../dist/binaries/${{ matrix.os }}-${{ matrix.arch }}/${{ matrix.binary }}"
|
||||
working-directory: backend
|
||||
@@ -239,7 +239,7 @@ jobs:
|
||||
ref: ${{ needs.release-info.outputs.git_sha }}
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@eac0f66a48bc4b70a10b9acd4c4e930f835d95ff # 1.95
|
||||
uses: dtolnay/rust-toolchain@1a3a6d54512beeaffd394f8d516ca16f2c506a20 # 1.97
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@eac0f66a48bc4b70a10b9acd4c4e930f835d95ff # 1.95
|
||||
uses: dtolnay/rust-toolchain@1a3a6d54512beeaffd394f8d516ca16f2c506a20 # 1.97
|
||||
|
||||
- name: Cache Rust
|
||||
uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1
|
||||
|
||||
+30
-32
@@ -1,43 +1,41 @@
|
||||
# Rust build output.
|
||||
# Rust
|
||||
/backend/target/
|
||||
/target/
|
||||
/dist/
|
||||
/package/
|
||||
/checksums.txt
|
||||
/codex-proxy-rs_*.tar.gz
|
||||
/codex-proxy-rs_*.zip
|
||||
*.profraw
|
||||
*.profdata
|
||||
|
||||
# Frontend dependencies and build output.
|
||||
# Frontend
|
||||
/frontend/node_modules/
|
||||
/frontend/dist/
|
||||
.pnpm-store
|
||||
/frontend/.vite/
|
||||
/.pnpm-store/
|
||||
/frontend/.pnpm-store/
|
||||
*.tsbuildinfo
|
||||
|
||||
# Application runtime state.
|
||||
*.runtime
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
# Release artifacts
|
||||
/dist/
|
||||
|
||||
# Runtime data
|
||||
/.runtime/
|
||||
*.log
|
||||
|
||||
# Local configuration.
|
||||
/local.yaml
|
||||
/local.yml
|
||||
/.env
|
||||
/config.yaml
|
||||
/backend/config.yaml
|
||||
/deploy/.env
|
||||
# Local configuration and secrets
|
||||
/deploy/config.yaml
|
||||
|
||||
# Local workspaces and tooling state.
|
||||
# Editors and operating systems
|
||||
/.idea/
|
||||
/.vscode/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# Local tools and worktrees
|
||||
/.codegraph/
|
||||
/.codex-ws-audit/
|
||||
/.agents/
|
||||
/.reasonix/
|
||||
/.worktrees/
|
||||
/worktrees/
|
||||
/.codex-ws-audit/
|
||||
/.codegraph/
|
||||
*.tmp
|
||||
*.swp
|
||||
*~
|
||||
*.codegraph
|
||||
/.agents/
|
||||
/.cargo/
|
||||
/.reasonix/
|
||||
*.tmp
|
||||
|
||||
@@ -1,123 +1,119 @@
|
||||
<div align="center">
|
||||
<h1>Codex Proxy RS</h1>
|
||||
<p>OpenAI Responses 兼容的 Codex 多账号网关</p>
|
||||
<p>
|
||||
<a href="https://www.rust-lang.org/"><img alt="Rust 1.95" src="https://img.shields.io/badge/Rust-1.95-000?style=flat-square&logo=rust" /></a>
|
||||
<a href="https://github.com/tokio-rs/axum"><img alt="Axum 0.8" src="https://img.shields.io/badge/Axum-0.8-2f7d95?style=flat-square" /></a>
|
||||
<a href="https://vuejs.org/"><img alt="Vue 3.5" src="https://img.shields.io/badge/Vue-3.5-42b883?style=flat-square&logo=vuedotjs&logoColor=white" /></a>
|
||||
<a href="https://vite.dev/"><img alt="Vite 8" src="https://img.shields.io/badge/Vite-8-646cff?style=flat-square&logo=vite&logoColor=white" /></a>
|
||||
<a href="https://www.postgresql.org/"><img alt="PostgreSQL 18" src="https://img.shields.io/badge/PostgreSQL-18-4169e1?style=flat-square&logo=postgresql&logoColor=white" /></a>
|
||||
<a href="https://redis.io/"><img alt="Redis 8" src="https://img.shields.io/badge/Redis-8-ff4438?style=flat-square&logo=redis&logoColor=white" /></a>
|
||||
<a href="https://opensource.org/license/mit"><img alt="MIT License" src="https://img.shields.io/badge/License-MIT-blue?style=flat-square" /></a>
|
||||
</p>
|
||||
<p>
|
||||
<a href="#快速部署">快速部署</a>
|
||||
·
|
||||
<a href="#客户端接入">客户端接入</a>
|
||||
·
|
||||
<a href="docs/architecture.md">架构说明</a>
|
||||
</p>
|
||||
|
||||
<img src="frontend/public/favicon.svg" alt="Codex Proxy RS" width="88" height="88" />
|
||||
|
||||
# Codex Proxy RS
|
||||
|
||||
**基于 Rust 的高性能 Codex 多账号网关代理**
|
||||
|
||||
[](https://github.com/zyycn/codex-proxy-rs/actions/workflows/ci.yml)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
[](https://www.rust-lang.org/)
|
||||
[](https://vuejs.org/)
|
||||
[](https://vite.dev/)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
|
||||
[](#开源许可)
|
||||
|
||||
[快速开始](#快速开始) · [首次使用](#首次使用) · [客户端接入](#客户端接入) · [常见问题](#常见问题) · [部署文档](deploy/README.md)
|
||||
|
||||
</div>
|
||||
|
||||
Codex Proxy RS 为多个 Codex 账号提供统一的 Responses API。客户端使用同一个服务地址和 API Key;账号调度、并发限制、额度检查、故障换号和会话续接都在服务端完成。
|
||||
> [!NOTE]
|
||||
> 当前兼容 OpenAI Responses API,不提供 `/v1/chat/completions`。
|
||||
|
||||
## 功能
|
||||
|
||||
- 兼容 `/v1/responses`、SSE 流式响应、Review、Compact 和模型查询。
|
||||
- 支持 HTTP/SSE 与 WebSocket 上游连接。
|
||||
- 提供 `smart`、额度重置优先、轮询和粘性四种账号调度策略。
|
||||
- 单个账号发生额度、认证、模型或传输故障时,继续使用账号池中的其他可用账号。
|
||||
- 使用会话亲和和受限历史重放处理 `previous_response_not_found` 与跨账号续接。
|
||||
- 为每个账号派生稳定且隔离的 installation、session、thread、turn 和 cache 标识。
|
||||
- 提供账号、API Key、模型映射、运行参数、用量、错误记录和系统更新管理界面。
|
||||
- 使用 PostgreSQL 保存权威业务数据,使用 Redis 保存会话、租约、模型快照和会话亲和数据。
|
||||
- 内置日志轮转、遥测保留期清理和 PostgreSQL/Redis 健康检查。
|
||||
- 支持 Responses HTTP、SSE 和官方 WebSocket 请求。
|
||||
- 提供智能调度、额度重置优先、轮询和粘滞四种账号策略。
|
||||
- 某个账号遇到额度、认证、模型或传输错误时,继续尝试其他账号。
|
||||
- 在网页中管理账号、客户端 Key、模型别名和运行参数。
|
||||
- 按请求、模型、账号或客户端 Key 查看 Token、费用、缓存、TTFT、延迟和错误。
|
||||
- 支持账号 OAuth、Token 导入以及 CPR、Sub2API、CLIProxyAPI JSON 导入。
|
||||
- 可直接生成 Codex CLI 配置,或通过 deeplink 导入 CCSwitch。
|
||||
|
||||
代理只补充账号凭据、上游请求头和账号作用域身份,并在必要时执行会话恢复;其余请求与响应尽量保持上游语义。
|
||||
## 快速开始
|
||||
|
||||
## 快速部署
|
||||
Docker Compose 是最简单的启动方式。开始前请安装 Docker Engine 和 Docker Compose Plugin。
|
||||
|
||||
需要 Docker Engine 和 Docker Compose Plugin。下面的 Compose 默认使用:
|
||||
|
||||
- 应用镜像:`ghcr.io/zyycn/codex-proxy-rs:latest`
|
||||
- PostgreSQL 18
|
||||
- Redis 8
|
||||
- 管理端地址:`http://127.0.0.1:8080`
|
||||
|
||||
### 1. 获取项目
|
||||
### 1. 准备配置
|
||||
|
||||
```bash
|
||||
git clone https://github.com/zyycn/codex-proxy-rs.git
|
||||
cd codex-proxy-rs
|
||||
```
|
||||
|
||||
### 2. 创建配置
|
||||
|
||||
```bash
|
||||
mkdir -p .runtime/data .runtime/logs
|
||||
cp deploy/config.example.yaml .runtime/config.yaml
|
||||
cp deploy/.env.example deploy/.env
|
||||
chmod 0600 deploy/.env
|
||||
install -d -m 0750 .runtime/postgres .runtime/redis
|
||||
cp deploy/config.example.yaml deploy/config.yaml
|
||||
sudo chown "$(id -u):10001" deploy/config.yaml
|
||||
chmod 0640 deploy/config.yaml
|
||||
```
|
||||
|
||||
编辑 `deploy/.env`:
|
||||
|
||||
```dotenv
|
||||
CPR_ADMIN_DEFAULT_PASSWORD='<管理员密码,至少 12 个字符>'
|
||||
CPR_POSTGRES_PASSWORD='<PostgreSQL 密码>'
|
||||
CPR_REDIS_PASSWORD='<Redis 密码>'
|
||||
```
|
||||
|
||||
`deploy/.env` 已被 Git 忽略。应用会安全地把 PostgreSQL 和 Redis 密码写入运行时连接 URL,不需要把真实密码填入 `.runtime/config.yaml`。
|
||||
|
||||
Linux 宿主机需要保证容器用户 `10001:10001` 可以读写数据和日志目录:
|
||||
分别执行三次以下命令生成密码:
|
||||
|
||||
```bash
|
||||
sudo chown -R "$(id -u):10001" .runtime/data .runtime/logs
|
||||
chmod 0770 .runtime/data .runtime/logs
|
||||
sudo chown "$(id -u):10001" .runtime/config.yaml
|
||||
chmod 0640 .runtime/config.yaml
|
||||
openssl rand -hex 24
|
||||
```
|
||||
|
||||
### 3. 启动
|
||||
把结果填入 `deploy/config.yaml` 的 `database.password`、`redis.password` 和
|
||||
`admin.default_password`。PostgreSQL 与 Redis 密码必须是 48 位十六进制字符;管理员密码
|
||||
至少 12 位且不能包含 `$`。
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 应用容器以非 root 用户 `10001:10001` 运行。Linux Bind Mount 会保留宿主机权限,因此需要允许容器用户组读取配置并写入数据和日志目录:
|
||||
>
|
||||
> ```bash
|
||||
> sudo chown -R "$(id -u):10001" .runtime/data .runtime/logs
|
||||
> chmod 0770 .runtime/data .runtime/logs
|
||||
> ```
|
||||
>
|
||||
> 配置文件通过 Compose `configs` 只读挂载;普通 Compose 会保留宿主机权限,因此由
|
||||
> 当前用户持有、仅向容器组开放读取权限。
|
||||
> macOS 和 Windows 的 Docker Desktop 通常也不需要调整数据目录权限。
|
||||
|
||||
### 2. 启动服务
|
||||
|
||||
```bash
|
||||
docker compose --env-file deploy/.env -f deploy/docker-compose.yml config
|
||||
docker compose --env-file deploy/.env -f deploy/docker-compose.yml pull
|
||||
docker compose --env-file deploy/.env -f deploy/docker-compose.yml up -d --no-build
|
||||
docker compose -f deploy/compose.yaml config --quiet
|
||||
docker compose -f deploy/compose.yaml pull
|
||||
docker compose -f deploy/compose.yaml up -d --no-build
|
||||
```
|
||||
|
||||
检查服务:
|
||||
启动后检查:
|
||||
|
||||
```bash
|
||||
docker compose --env-file deploy/.env -f deploy/docker-compose.yml ps
|
||||
docker compose -f deploy/compose.yaml ps
|
||||
curl -i http://127.0.0.1:8080/healthz
|
||||
```
|
||||
|
||||
`/healthz` 正常时返回 `204 No Content`。随后打开 <http://127.0.0.1:8080>:
|
||||
`/healthz` 返回 `204 No Content` 即表示服务正常。管理端地址为 <http://127.0.0.1:8080>。
|
||||
|
||||
- 用户名:`admin@cpr.local`
|
||||
- 密码:`deploy/.env` 中的 `CPR_ADMIN_DEFAULT_PASSWORD`
|
||||
## 首次使用
|
||||
|
||||
首次登录后导入账号,在“API 密钥”页面创建客户端 Key。
|
||||
1. 使用 `admin@cpr.local` 和 `x-cpr.admin.default_password` 中设置的密码登录。
|
||||
2. 打开“账号”,用 OAuth、Access/Refresh Token 或 JSON 文件添加账号。
|
||||
3. 点一次连接测试,能看到模型和额度即可。
|
||||
4. 打开“API 密钥”,创建一个 `sk_...` 客户端 Key。
|
||||
5. 点击“使用密钥”复制 Codex CLI 配置,或一键导入 CCSwitch。
|
||||
|
||||
### 本地构建镜像
|
||||
|
||||
需要验证当前源码时,不拉取 GHCR 镜像,直接构建:
|
||||
|
||||
```bash
|
||||
docker compose --env-file deploy/.env -f deploy/docker-compose.yml build codex-proxy-rs
|
||||
docker compose --env-file deploy/.env -f deploy/docker-compose.yml up -d
|
||||
```
|
||||
> [!TIP]
|
||||
> `admin.default_password` 只用于首次创建管理员。已有管理员后修改该字段不会重置登录密码。
|
||||
|
||||
## 客户端接入
|
||||
|
||||
OpenAI 兼容客户端填写:
|
||||
| 配置 | 值 |
|
||||
| -------- | ---------------------------------------- |
|
||||
| Base URL | `http://127.0.0.1:8080/v1` |
|
||||
| API Key | 管理端创建的 `sk_...` 客户端 Key |
|
||||
| 鉴权 | `Authorization: Bearer <client-api-key>` |
|
||||
|
||||
- Base URL:`http://127.0.0.1:8080/v1`
|
||||
- API Key:管理端创建的 `sk_...` 客户端 Key
|
||||
先查询当前可用模型:
|
||||
|
||||
Responses 请求示例:
|
||||
```bash
|
||||
curl http://127.0.0.1:8080/v1/models \
|
||||
-H 'Authorization: Bearer <client-api-key>'
|
||||
```
|
||||
|
||||
发送一个非流式 Responses 请求:
|
||||
|
||||
```bash
|
||||
curl http://127.0.0.1:8080/v1/responses \
|
||||
@@ -130,98 +126,90 @@ curl http://127.0.0.1:8080/v1/responses \
|
||||
}'
|
||||
```
|
||||
|
||||
可用接口:
|
||||
<details>
|
||||
<summary>查看全部客户端 API 路由</summary>
|
||||
|
||||
| 路由 | 说明 |
|
||||
| --- | --- |
|
||||
| `POST /v1/responses` | Responses 非流式或 SSE 流式请求 |
|
||||
| `POST /v1/responses/review` | Review 请求 |
|
||||
| `POST /v1/responses/compact` | Compact 请求 |
|
||||
| `GET /v1/models` | 模型列表 |
|
||||
| `GET /v1/models/catalog` | 模型目录 |
|
||||
| `GET /v1/models/{model_id}` | 模型详情 |
|
||||
| `GET /v1/models/{model_id}/info` | 模型运行信息 |
|
||||
| 路由 | 说明 |
|
||||
| -------------------------------- | ------------------------------- |
|
||||
| `POST /v1/responses` | Responses 非流式或 SSE 流式请求 |
|
||||
| `GET /v1/responses` | 官方 Responses WebSocket |
|
||||
| `POST /v1/responses/review` | Review 请求 |
|
||||
| `GET /v1/models` | OpenAI 格式的模型列表 |
|
||||
| `GET /v1/models/catalog` | 完整模型目录 |
|
||||
| `GET /v1/models/{model_id}` | 模型详情 |
|
||||
| `GET /v1/models/{model_id}/info` | 模型运行信息 |
|
||||
|
||||
Compose 默认只监听宿主机 `127.0.0.1`。需要从其他设备访问时,应在前面配置 HTTPS 反向代理,不要直接暴露 PostgreSQL 和 Redis 端口。
|
||||
所有 `/v1/*` 路由都需要客户端 API Key。
|
||||
|
||||
</details>
|
||||
|
||||
## 管理端
|
||||
|
||||
管理端提供以下页面:
|
||||
| 页面 | 内容 |
|
||||
| -------- | ---------------------------------------------------------------------- |
|
||||
| 概览 | 查看服务状态、请求趋势、Token、账号池容量、请求健康和最近调用 |
|
||||
| 账号 | 添加、导入、导出、测试、启停账号,以及刷新 Token 和额度 |
|
||||
| API 密钥 | 创建、复制、启停或删除 Key,生成 Codex CLI 配置并导入 CCSwitch |
|
||||
| 使用统计 | 按时间、模型、账号和客户端 Key 查看用量、费用、缓存、延迟和错误 |
|
||||
| 系统设置 | 配置模型别名、调度策略、单账号并发、请求间隔、刷新参数和管理员 API Key |
|
||||
| 系统更新 | 查看版本和发布说明;Release 版本可以在线更新并重启 |
|
||||
|
||||
- Dashboard:请求趋势、服务状态、账号概览和最近请求。
|
||||
- 账号:导入、导出、OAuth、连接测试、quota 和 token 刷新。
|
||||
- API 密钥:创建、停用、删除和客户端接入信息。
|
||||
- 用量:请求记录、token、延迟、模型分布和运维错误。
|
||||
- 设置:模型别名、账号调度策略、单账号并发、请求间隔和刷新参数。
|
||||
- 系统:版本检查、更新、重启和回滚。
|
||||
## 常用操作
|
||||
|
||||
管理端登录会话保存在 Redis,并按 `admin.session_ttl_minutes` 自动过期。
|
||||
|
||||
## 配置
|
||||
|
||||
启动配置位于 `.runtime/config.yaml`,模板见 [deploy/config.example.yaml](deploy/config.example.yaml)。
|
||||
|
||||
| 配置段 | 用途 |
|
||||
| --- | --- |
|
||||
| `server` | HTTP 监听地址和端口 |
|
||||
| `api` | Codex 上游地址 |
|
||||
| `database`、`redis` | PostgreSQL 与 Redis 连接 |
|
||||
| `quota` | quota 刷新周期和耗尽账号过滤 |
|
||||
| `tls` | 上游 HTTP 协议偏好 |
|
||||
| `ws_pool` | WebSocket 连接池与首事件超时 |
|
||||
| `fingerprint` | Codex Desktop 请求指纹 |
|
||||
| `admin` | 默认管理员和登录会话 TTL |
|
||||
| `logging` | 日志级别、目录、大小和保留期 |
|
||||
| `telemetry` | 请求事实记录开关 |
|
||||
|
||||
模型别名、调度策略、单账号并发、请求间隔和刷新参数由管理端保存到 PostgreSQL,可在运行中更新。请求事实、运维错误和聚合时间桶由后台任务按各自保留期自动清理。
|
||||
|
||||
## 数据与升级
|
||||
|
||||
| 数据 | 默认位置 |
|
||||
| --- | --- |
|
||||
| 账号、API Key、设置、用量和错误记录 | Compose 命名卷 `postgres-data` |
|
||||
| 管理会话、租约、模型快照和会话亲和 | Compose 命名卷 `redis-data` |
|
||||
| 身份派生密钥和更新状态 | `.runtime/data` |
|
||||
| 文件日志 | `.runtime/logs` |
|
||||
| 启动配置 | `.runtime/config.yaml` |
|
||||
| Docker 密钥 | `deploy/.env` |
|
||||
|
||||
普通升级只替换应用镜像:
|
||||
### 升级
|
||||
|
||||
```bash
|
||||
docker compose --env-file deploy/.env -f deploy/docker-compose.yml pull codex-proxy-rs
|
||||
docker compose --env-file deploy/.env -f deploy/docker-compose.yml up -d --no-build
|
||||
docker compose -f deploy/compose.yaml pull codex-proxy-rs
|
||||
docker compose -f deploy/compose.yaml up -d --no-build
|
||||
```
|
||||
|
||||
更新镜像不会删除数据库卷,但仍应在升级前备份 PostgreSQL 和 `.runtime/data`。
|
||||
|
||||
不要使用 `docker compose down -v` 做普通升级,该命令会删除 PostgreSQL 与 Redis 命名卷。
|
||||
|
||||
`.runtime/data/identity_hmac_secret` 必须长期保留。丢失该文件会改变全部账号的 installation ID 和账号作用域身份。
|
||||
|
||||
## 查看状态
|
||||
### 查看日志
|
||||
|
||||
```bash
|
||||
# 容器状态
|
||||
docker compose --env-file deploy/.env -f deploy/docker-compose.yml ps
|
||||
|
||||
# 应用日志
|
||||
docker compose --env-file deploy/.env -f deploy/docker-compose.yml logs -f codex-proxy-rs
|
||||
|
||||
# PostgreSQL 和 Redis 日志
|
||||
docker compose --env-file deploy/.env -f deploy/docker-compose.yml logs postgres redis
|
||||
|
||||
# 展开并检查最终 Compose 配置
|
||||
docker compose --env-file deploy/.env -f deploy/docker-compose.yml config
|
||||
docker compose -f deploy/compose.yaml logs -f codex-proxy-rs
|
||||
```
|
||||
|
||||
`/healthz` 返回 `503` 时,先检查 PostgreSQL 和 Redis 的健康状态。容器反复重启时,再检查 `.runtime/config.yaml`、`deploy/.env` 和 `.runtime/data`、`.runtime/logs` 的权限。
|
||||
### 从当前源码构建
|
||||
|
||||
## 架构
|
||||
```bash
|
||||
docker compose -f deploy/compose.yaml build codex-proxy-rs
|
||||
docker compose -f deploy/compose.yaml up -d
|
||||
```
|
||||
|
||||
模块边界、请求链路、换号条件、previous response 恢复、存储归属和后台任务见 [架构说明](docs/architecture.md)。
|
||||
> [!WARNING]
|
||||
> PostgreSQL、Redis、应用数据和文件日志都保存在仓库根目录 `.runtime/`。普通
|
||||
> `docker compose down` 不会删除这些绑定目录;删除 `.runtime/` 才会清除数据。升级前请备份
|
||||
> 整个目录,数据库备份中包含客户端凭据,应按敏感数据保管。
|
||||
|
||||
## License
|
||||
## 常见问题
|
||||
|
||||
MIT
|
||||
### `/healthz` 返回 `503`
|
||||
|
||||
检查 PostgreSQL 和 Redis 容器是否健康:
|
||||
|
||||
```bash
|
||||
docker compose -f deploy/compose.yaml ps
|
||||
docker compose -f deploy/compose.yaml logs postgres redis
|
||||
```
|
||||
|
||||
### 容器反复重启
|
||||
|
||||
检查 `deploy/config.yaml` 的三个密码是否填写完整,以及 `.runtime/data`、`.runtime/logs`
|
||||
的权限是否正确。
|
||||
|
||||
### 需要从其他设备访问
|
||||
|
||||
Compose 默认仅绑定 `127.0.0.1`。请在服务前配置 HTTPS 反向代理,并正确转发 WebSocket 升级和真实客户端 IP 请求头。不要直接暴露 PostgreSQL 或 Redis。
|
||||
|
||||
## 相关链接
|
||||
|
||||
- [发布版本](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
- [容器镜像](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
|
||||
- [详细部署说明](deploy/README.md)
|
||||
- [架构说明](docs/architecture.md)
|
||||
|
||||
Docker 镜像支持 Linux amd64/arm64。Release 压缩包另有 macOS arm64 和 Windows amd64 版本。
|
||||
|
||||
## 开源许可
|
||||
|
||||
Codex Proxy RS 基于 [MIT License](https://opensource.org/license/mit) 开源。
|
||||
|
||||
Generated
+14
-63
@@ -359,14 +359,14 @@ dependencies = [
|
||||
"bytes",
|
||||
"chrono",
|
||||
"config",
|
||||
"dirs",
|
||||
"flate2",
|
||||
"futures",
|
||||
"hex",
|
||||
"hmac 0.12.1",
|
||||
"hmac",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"indexmap",
|
||||
"ipnet",
|
||||
"percent-encoding",
|
||||
"rand 0.10.2",
|
||||
"rand_core 0.6.4",
|
||||
"redis",
|
||||
@@ -378,7 +378,7 @@ dependencies = [
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"sha2 0.11.0",
|
||||
"sqlx",
|
||||
"subtle",
|
||||
"tar",
|
||||
@@ -453,6 +453,12 @@ dependencies = [
|
||||
"yaml-rust2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
|
||||
|
||||
[[package]]
|
||||
name = "cookie"
|
||||
version = "0.18.1"
|
||||
@@ -640,31 +646,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer 0.12.1",
|
||||
"const-oid",
|
||||
"crypto-common 0.2.2",
|
||||
"ctutils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dirs"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
|
||||
dependencies = [
|
||||
"dirs-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dirs-sys"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "displaydoc"
|
||||
version = "0.2.6"
|
||||
@@ -1062,16 +1048,7 @@ version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
|
||||
dependencies = [
|
||||
"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",
|
||||
"hmac",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1388,22 +1365,12 @@ version = "0.2.186"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
|
||||
|
||||
[[package]]
|
||||
name = "libredox"
|
||||
version = "0.1.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libsqlite3-sys"
|
||||
version = "0.37.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1f111c8c41e7c61a49cd34e44c7619462967221a6443b0ec299e0ac30cfb9b1"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
@@ -1561,12 +1528,6 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
|
||||
|
||||
[[package]]
|
||||
name = "option-ext"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
|
||||
|
||||
[[package]]
|
||||
name = "parking"
|
||||
version = "2.2.1"
|
||||
@@ -1857,17 +1818,6 @@ dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_users"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"
|
||||
dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
"libredox",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.13.0"
|
||||
@@ -2054,6 +2004,7 @@ version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e891af845473308773346dc847b2c23ee78fe442e0472ac50e22a18a93d3ae5a"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
@@ -2402,7 +2353,7 @@ dependencies = [
|
||||
"futures-util",
|
||||
"hex",
|
||||
"hkdf",
|
||||
"hmac 0.13.0",
|
||||
"hmac",
|
||||
"itoa",
|
||||
"log",
|
||||
"md-5",
|
||||
|
||||
+9
-10
@@ -1,9 +1,9 @@
|
||||
[package]
|
||||
name = "codex-proxy-rs"
|
||||
edition = "2021"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
publish = false
|
||||
rust-version = "1.95"
|
||||
rust-version = "1.97"
|
||||
|
||||
[dependencies]
|
||||
argon2 = "0.5.3"
|
||||
@@ -13,14 +13,14 @@ 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"] }
|
||||
dirs = "6.0.0"
|
||||
flate2 = "1.1.9"
|
||||
futures = "0.3.32"
|
||||
hex = "0.4.3"
|
||||
hmac = "0.12.1"
|
||||
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"
|
||||
percent-encoding = "2.3.2"
|
||||
rand = "0.10.1"
|
||||
# Enables password_hash::rand_core::OsRng for argon2 0.5.
|
||||
rand_core = { version = "0.6.4", features = ["getrandom"] }
|
||||
@@ -30,12 +30,12 @@ reqwest = { version = "=0.12.28", default-features = false, features = ["json",
|
||||
rustls = { version = "=0.23.36", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
rustls-native-certs = "0.8.4"
|
||||
rustls-pki-types = "1.14.1"
|
||||
secrecy = "0.10.3"
|
||||
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.10.9"
|
||||
sqlx = { version = "0.9.0", default-features = false, features = ["runtime-tokio", "tls-rustls", "postgres", "sqlite-bundled", "chrono", "json"] }
|
||||
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"
|
||||
@@ -62,8 +62,7 @@ tokio-tungstenite = { git = "https://github.com/openai-oss-forks/tokio-tungsteni
|
||||
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "4fffad30fe373adbdcffab9545e9e9bf4f2fc19f" }
|
||||
|
||||
[lints.rust]
|
||||
future_incompatible = { level = "warn", priority = -1 }
|
||||
nonstandard_style = { level = "deny", priority = -1 }
|
||||
warnings = "deny"
|
||||
unsafe_code = "forbid"
|
||||
|
||||
[lints.clippy]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
[toolchain]
|
||||
channel = "1.95"
|
||||
channel = "1.97"
|
||||
components = ["clippy", "rustfmt"]
|
||||
profile = "minimal"
|
||||
components = ["rustfmt", "clippy"]
|
||||
|
||||
@@ -33,12 +33,12 @@ pub async fn health_check_accounts(
|
||||
"stagger_ms must be between 500 and 30000",
|
||||
));
|
||||
}
|
||||
if let Some(concurrency) = payload.concurrency {
|
||||
if !(1..=10).contains(&concurrency) {
|
||||
return Err(AdminError::bad_request(
|
||||
"concurrency must be between 1 and 10",
|
||||
));
|
||||
}
|
||||
if let Some(concurrency) = payload.concurrency
|
||||
&& !(1..=10).contains(&concurrency)
|
||||
{
|
||||
return Err(AdminError::bad_request(
|
||||
"concurrency must be between 1 and 10",
|
||||
));
|
||||
}
|
||||
match state
|
||||
.services
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
//! 账号管理 HTTP 处理器。
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
body::Body,
|
||||
extract::{Query, State},
|
||||
http::{
|
||||
header::{CACHE_CONTROL, CONNECTION, CONTENT_TYPE},
|
||||
StatusCode,
|
||||
header::{CACHE_CONTROL, CONNECTION, CONTENT_TYPE},
|
||||
},
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
@@ -17,30 +17,31 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
api::AppState,
|
||||
api::admin::{
|
||||
response::{
|
||||
parse_editable_update, AdminEnvelope, AdminError, AdminResponse, BatchDeleteData,
|
||||
EditableUpdateMessages, PageMeta, ADMIN_OK_CODE, ADMIN_OK_MESSAGE,
|
||||
ADMIN_OK_CODE, ADMIN_OK_MESSAGE, AdminEnvelope, AdminError, AdminResponse,
|
||||
BatchDeleteData, EditableUpdateMessages, PageMeta, parse_editable_update,
|
||||
},
|
||||
session::AdminAuth,
|
||||
},
|
||||
api::AppState,
|
||||
fleet::{
|
||||
account::AccountStatus,
|
||||
account::{AccountListSort, AccountSortField, AccountStatus},
|
||||
manage::{
|
||||
quota_view::{
|
||||
quota_data, AccountQuotaData, AccountQuotaUsageWindow, AccountQuotaWindowLocalUsage,
|
||||
},
|
||||
AccountHealthCheck, AccountManageError, AccountRefreshOutcome, AccountRefreshResult,
|
||||
AccountUpdate, ManagedAccount, OAuthExchangeInput,
|
||||
quota_view::{
|
||||
AccountQuotaData, AccountQuotaUsageWindow, AccountQuotaWindowLocalUsage, quota_data,
|
||||
},
|
||||
},
|
||||
refresh::token_refresh_status_eligible,
|
||||
},
|
||||
infra::{
|
||||
format::{
|
||||
format_cost, format_percent, format_plain_number, format_tokens, nonnegative_i64_to_u64,
|
||||
format_billing_amount, format_percent, format_plain_number, format_tokens,
|
||||
nonnegative_i64_to_u64,
|
||||
},
|
||||
json::{clamp_limit, clamp_page, total_pages},
|
||||
json::{SortDirection, clamp_limit, clamp_page, total_pages},
|
||||
time::{china_datetime, china_relative_time, china_rfc3339},
|
||||
},
|
||||
telemetry::{
|
||||
@@ -59,6 +60,9 @@ pub(crate) struct AccountsQuery {
|
||||
page: Option<u32>,
|
||||
page_size: Option<u32>,
|
||||
search: Option<String>,
|
||||
status: Option<String>,
|
||||
sort_by: Option<String>,
|
||||
sort_direction: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -282,8 +286,8 @@ struct AdminAccountModelUsageData {
|
||||
cached_tokens_display: String,
|
||||
total_tokens: u64,
|
||||
total_tokens_display: String,
|
||||
total_cost_usd: f64,
|
||||
total_cost_usd_display: String,
|
||||
billing_amount_usd: f64,
|
||||
billing_amount_usd_display: String,
|
||||
last_used_at: Option<String>,
|
||||
last_used_at_display: String,
|
||||
}
|
||||
@@ -304,7 +308,7 @@ struct AccountModelUsageRecord {
|
||||
input_tokens: i64,
|
||||
output_tokens: i64,
|
||||
cached_tokens: i64,
|
||||
total_cost_usd: f64,
|
||||
billing_amount_usd: f64,
|
||||
last_used_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
@@ -337,7 +341,7 @@ impl AccountListStats {
|
||||
struct AdminAccountSummaryData {
|
||||
total: u64,
|
||||
active: u64,
|
||||
high_usage: u64,
|
||||
quota_exhausted: u64,
|
||||
attention: u64,
|
||||
}
|
||||
|
||||
@@ -505,13 +509,15 @@ pub(crate) async fn accounts(
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
let page = clamp_page(params.page.unwrap_or(1));
|
||||
let page_size = clamp_limit(params.page_size.unwrap_or(50));
|
||||
let status = account_status_filter(params.status)?;
|
||||
let sort = account_list_sort(params.sort_by, params.sort_direction)?;
|
||||
let quota_by_account = quota_snapshots_by_account(&state).await;
|
||||
let summary = account_summary_data(&state, "a_by_account).await;
|
||||
let summary = account_summary_data(&state).await;
|
||||
|
||||
match state
|
||||
.services
|
||||
.admin_accounts
|
||||
.list_page(page, page_size, params.search)
|
||||
.list_page(page, page_size, params.search, status, sort)
|
||||
.await
|
||||
{
|
||||
Ok(page) => {
|
||||
|
||||
@@ -202,23 +202,16 @@ pub(super) fn apply_selected_quota_window_usage(
|
||||
usage
|
||||
}
|
||||
|
||||
pub(super) async fn account_summary_data(
|
||||
state: &AppState,
|
||||
quota_by_account: &HashMap<String, AccountQuotaData>,
|
||||
) -> AdminAccountSummaryData {
|
||||
pub(super) async fn account_summary_data(state: &AppState) -> AdminAccountSummaryData {
|
||||
let accounts = list_all_account_metadata(state).await;
|
||||
let total = accounts.len() as u64;
|
||||
let active = accounts
|
||||
.iter()
|
||||
.filter(|account| account.status == AccountStatus::Active)
|
||||
.count() as u64;
|
||||
let high_usage = accounts
|
||||
let quota_exhausted = accounts
|
||||
.iter()
|
||||
.filter(|account| {
|
||||
quota_by_account
|
||||
.get(&account.id)
|
||||
.is_some_and(account_quota_has_high_usage)
|
||||
})
|
||||
.filter(|account| account.status == AccountStatus::QuotaExhausted)
|
||||
.count() as u64;
|
||||
let attention = accounts
|
||||
.iter()
|
||||
@@ -228,7 +221,7 @@ pub(super) async fn account_summary_data(
|
||||
AdminAccountSummaryData {
|
||||
total,
|
||||
active,
|
||||
high_usage,
|
||||
quota_exhausted,
|
||||
attention,
|
||||
}
|
||||
}
|
||||
@@ -259,7 +252,7 @@ pub(super) async fn list_all_account_metadata(state: &AppState) -> Vec<ManagedAc
|
||||
let Ok(result) = state
|
||||
.services
|
||||
.admin_accounts
|
||||
.list_page(page, ACCOUNT_STATS_PAGE_LIMIT, None)
|
||||
.list_page(page, ACCOUNT_STATS_PAGE_LIMIT, None, None, None)
|
||||
.await
|
||||
else {
|
||||
return Vec::new();
|
||||
@@ -273,10 +266,6 @@ pub(super) async fn list_all_account_metadata(state: &AppState) -> Vec<ManagedAc
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn account_quota_has_high_usage(quota: &AccountQuotaData) -> bool {
|
||||
quota.has_high_usage()
|
||||
}
|
||||
|
||||
pub(super) fn account_summary_needs_attention(status: AccountStatus) -> bool {
|
||||
matches!(
|
||||
status,
|
||||
@@ -284,6 +273,47 @@ pub(super) fn account_summary_needs_attention(status: AccountStatus) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn account_status_filter(
|
||||
status: Option<String>,
|
||||
) -> Result<Option<AccountStatus>, AdminError> {
|
||||
let Some(status) = status.map(|value| value.trim().to_string()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if status.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
AccountStatus::parse(&status)
|
||||
.map(Some)
|
||||
.ok_or_else(|| AdminError::bad_request("Invalid account status"))
|
||||
}
|
||||
|
||||
pub(super) fn account_list_sort(
|
||||
sort_by: Option<String>,
|
||||
sort_direction: Option<String>,
|
||||
) -> Result<Option<AccountListSort>, AdminError> {
|
||||
let (sort_by, sort_direction) = match (sort_by, sort_direction) {
|
||||
(None, None) => return Ok(None),
|
||||
(Some(sort_by), Some(sort_direction)) => (sort_by, sort_direction),
|
||||
_ => {
|
||||
return Err(AdminError::bad_request(
|
||||
"Account sort field and direction must be provided together",
|
||||
));
|
||||
}
|
||||
};
|
||||
let field = match sort_by.trim() {
|
||||
"email" => AccountSortField::Email,
|
||||
"status" => AccountSortField::Status,
|
||||
"planType" => AccountSortField::PlanType,
|
||||
"usage" => AccountSortField::Usage,
|
||||
"lastUsedAt" => AccountSortField::LastUsedAt,
|
||||
"expiresAt" => AccountSortField::ExpiresAt,
|
||||
_ => return Err(AdminError::bad_request("Invalid account sort field")),
|
||||
};
|
||||
let direction = SortDirection::parse(&sort_direction)
|
||||
.ok_or_else(|| AdminError::bad_request("Invalid account sort direction"))?;
|
||||
Ok(Some(AccountListSort { field, direction }))
|
||||
}
|
||||
|
||||
pub(super) async fn list_current_window_model_usage(
|
||||
state: &AppState,
|
||||
usage_records: &[AccountUsageRecord],
|
||||
@@ -323,7 +353,7 @@ pub(super) async fn list_current_window_model_usage(
|
||||
let input_tokens = row.input_tokens;
|
||||
let output_tokens = row.output_tokens;
|
||||
let cached_tokens = row.cached_tokens;
|
||||
let total_cost_usd = billing::calculate_cost(
|
||||
let billing_amount_usd = billing::calculate_billing_amount(
|
||||
nonnegative_i64_to_u64(input_tokens),
|
||||
nonnegative_i64_to_u64(output_tokens),
|
||||
nonnegative_i64_to_u64(cached_tokens),
|
||||
@@ -342,7 +372,7 @@ pub(super) async fn list_current_window_model_usage(
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
cached_tokens: 0,
|
||||
total_cost_usd: 0.0,
|
||||
billing_amount_usd: 0.0,
|
||||
last_used_at: None,
|
||||
});
|
||||
record.request_count += request_count;
|
||||
@@ -350,7 +380,7 @@ pub(super) async fn list_current_window_model_usage(
|
||||
record.input_tokens += input_tokens;
|
||||
record.output_tokens += output_tokens;
|
||||
record.cached_tokens += cached_tokens;
|
||||
record.total_cost_usd += total_cost_usd;
|
||||
record.billing_amount_usd += billing_amount_usd;
|
||||
record.last_used_at = record.last_used_at.max(last_used_at);
|
||||
}
|
||||
let records = records_by_model.into_values().collect::<Vec<_>>();
|
||||
@@ -408,7 +438,7 @@ pub(super) fn model_usage_data(usage: AccountModelUsageRecord) -> AdminAccountMo
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let total_cost_usd = usage.total_cost_usd;
|
||||
let billing_amount_usd = usage.billing_amount_usd;
|
||||
|
||||
AdminAccountModelUsageData {
|
||||
model: usage.model,
|
||||
@@ -424,8 +454,8 @@ pub(super) fn model_usage_data(usage: AccountModelUsageRecord) -> AdminAccountMo
|
||||
cached_tokens_display: format_tokens(cached_tokens),
|
||||
total_tokens,
|
||||
total_tokens_display: format_tokens(total_tokens),
|
||||
total_cost_usd,
|
||||
total_cost_usd_display: format_cost(total_cost_usd),
|
||||
billing_amount_usd,
|
||||
billing_amount_usd_display: format_billing_amount(billing_amount_usd),
|
||||
last_used_at: usage.last_used_at.map(|value| china_rfc3339(&value)),
|
||||
last_used_at_display: china_relative_time(usage.last_used_at, Utc::now()),
|
||||
}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
//! 管理端认证路由。
|
||||
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::{header::SET_COOKIE, HeaderMap, HeaderValue, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
Extension, Json,
|
||||
extract::State,
|
||||
http::{HeaderMap, HeaderValue, StatusCode, header::SET_COOKIE},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
api::{
|
||||
AppState,
|
||||
admin::{
|
||||
response::{AdminEnvelope, AdminError, AdminResponse},
|
||||
session::{admin_session_cookie, ADMIN_SESSION_COOKIE},
|
||||
session::{ADMIN_SESSION_COOKIE, admin_session_cookie},
|
||||
},
|
||||
middleware::request_id::ClientIp,
|
||||
AppState,
|
||||
},
|
||||
auth::types::SessionError,
|
||||
infra::time::china_rfc3339,
|
||||
@@ -107,15 +107,14 @@ pub(crate) async fn logout(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Response, AdminError> {
|
||||
if let Some(session_id) = admin_session_cookie(&headers) {
|
||||
if let Err(error) = state
|
||||
if let Some(session_id) = admin_session_cookie(&headers)
|
||||
&& let Err(error) = state
|
||||
.services
|
||||
.admin_sessions
|
||||
.delete_session(&session_id)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %error, "failed to revoke admin session during logout");
|
||||
}
|
||||
{
|
||||
tracing::warn!(error = %error, "Failed to revoke admin session during logout");
|
||||
}
|
||||
|
||||
let mut response = AdminResponse::new(
|
||||
|
||||
@@ -12,15 +12,15 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
api::AppState,
|
||||
api::admin::{
|
||||
response::{AdminEnvelope, AdminError, AdminResponse},
|
||||
session::AdminAuth,
|
||||
usage_routes::{
|
||||
usage_cost_details, usage_record_models, usage_token_details,
|
||||
UsageRecordCostDetailsData, UsageRecordTokenDetailsData,
|
||||
UsageRecordBillingData, UsageRecordTokenDetailsData, usage_billing,
|
||||
usage_record_models, usage_token_details,
|
||||
},
|
||||
},
|
||||
api::AppState,
|
||||
fleet::{
|
||||
account::{Account, AccountStatus},
|
||||
pool::AccountCapacitySummary,
|
||||
@@ -36,13 +36,13 @@ use crate::{
|
||||
telemetry::{
|
||||
account_usage::query::AccountUsageTimeBucket,
|
||||
dashboard::{
|
||||
dashboard_cards, dashboard_health_timeline_data, dashboard_trend_data,
|
||||
DashboardAccountCounts, DashboardCardsData, DashboardHealthTimelineData,
|
||||
DashboardTrendData, DashboardTrendKind,
|
||||
DashboardTrendData, DashboardTrendKind, dashboard_cards,
|
||||
dashboard_health_timeline_data, dashboard_trend_data,
|
||||
},
|
||||
usage::{
|
||||
query::{UsageQueryFilter, UsageRecordAccountUsage},
|
||||
types::{metadata_string, UsageRecord},
|
||||
types::{UsageRecord, metadata_string},
|
||||
},
|
||||
},
|
||||
upstream::openai::fingerprint::Fingerprint,
|
||||
@@ -102,8 +102,12 @@ struct DashboardUsageRecordData {
|
||||
client_ip: Option<String>,
|
||||
user_agent: Option<String>,
|
||||
reasoning_effort: Option<String>,
|
||||
reasoning_preset: Option<String>,
|
||||
compact: bool,
|
||||
request_kind: Option<String>,
|
||||
subagent_kind: Option<String>,
|
||||
token_details: UsageRecordTokenDetailsData,
|
||||
cost_details: Option<UsageRecordCostDetailsData>,
|
||||
billing: Option<UsageRecordBillingData>,
|
||||
first_token_latency_ms_display: String,
|
||||
latency_ms_display: String,
|
||||
}
|
||||
@@ -201,12 +205,12 @@ pub(crate) async fn dashboard_summary(
|
||||
let capacity = state.services.account_pool.capacity_summary_now().await;
|
||||
let now = Utc::now();
|
||||
let today_filter = today_usage_record_filter(now);
|
||||
let lifetime_usage = state
|
||||
let retained_usage = state
|
||||
.services
|
||||
.usage
|
||||
.summary()
|
||||
.retained_totals()
|
||||
.await
|
||||
.map_err(|error| dashboard_data_error("account usage summary", &error))?;
|
||||
.map_err(|error| dashboard_data_error("retained usage summary", &error))?;
|
||||
let account_usage_records = state
|
||||
.services
|
||||
.usage_records
|
||||
@@ -252,7 +256,7 @@ pub(crate) async fn dashboard_summary(
|
||||
cards: dashboard_cards(
|
||||
dashboard_account_counts(&accounts),
|
||||
&time_buckets,
|
||||
&lifetime_usage,
|
||||
&retained_usage,
|
||||
),
|
||||
trend,
|
||||
health_timeline: dashboard_health_timeline_data(&time_buckets),
|
||||
@@ -415,7 +419,7 @@ async fn account_quota_used_percent_by_id(
|
||||
}
|
||||
|
||||
fn dashboard_data_error(source: &'static str, error: &impl std::fmt::Display) -> AdminError {
|
||||
tracing::error!(source, error = %error, "failed to load dashboard data");
|
||||
tracing::error!(source, error = %error, "Failed to load dashboard data");
|
||||
AdminError::internal("Failed to load dashboard data")
|
||||
}
|
||||
|
||||
@@ -514,8 +518,16 @@ fn dashboard_usage_record_data(
|
||||
let user_agent = metadata_string(&record.metadata, &["userAgent", "user_agent"]);
|
||||
let reasoning_effort =
|
||||
metadata_string(&record.metadata, &["reasoningEffort", "reasoning_effort"]);
|
||||
let reasoning_preset = metadata_string(&record.metadata, &["reasoningPreset"]);
|
||||
let compact = record
|
||||
.metadata
|
||||
.get("compact")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
let request_kind = metadata_string(&record.metadata, &["requestKind", "request_kind"]);
|
||||
let subagent_kind = metadata_string(&record.metadata, &["subagentKind", "subagent_kind"]);
|
||||
let token_details = usage_token_details(&record);
|
||||
let cost_details = usage_cost_details(&record, upstream_model.as_deref(), &token_details);
|
||||
let billing = usage_billing(&record, upstream_model.as_deref(), &token_details);
|
||||
let first_token_latency_ms = record.first_token_ms;
|
||||
|
||||
DashboardUsageRecordData {
|
||||
@@ -531,8 +543,12 @@ fn dashboard_usage_record_data(
|
||||
client_ip,
|
||||
user_agent,
|
||||
reasoning_effort,
|
||||
reasoning_preset,
|
||||
compact,
|
||||
request_kind,
|
||||
subagent_kind,
|
||||
token_details,
|
||||
cost_details,
|
||||
billing,
|
||||
first_token_latency_ms_display: format_duration_ms(first_token_latency_ms),
|
||||
latency_ms_display: format_duration_ms(record.latency_ms),
|
||||
}
|
||||
|
||||
@@ -1,26 +1,28 @@
|
||||
//! 管理端 v1 接口访问 Key 处理器(列表、创建、生命周期)。
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Query, State},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
Json,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
api::AppState,
|
||||
api::admin::response::{
|
||||
parse_editable_update, AdminEnvelope, AdminError, AdminPageEnvelope, AdminResponse,
|
||||
BatchDeleteData, EditableUpdateMessages,
|
||||
AdminEnvelope, AdminError, AdminPageEnvelope, AdminResponse, BatchDeleteData,
|
||||
EditableUpdateMessages, parse_editable_update,
|
||||
},
|
||||
api::admin::session::AdminAuth,
|
||||
api::AppState,
|
||||
infra::{
|
||||
json::{clamp_limit, clamp_page, NumberedPage},
|
||||
json::{NumberedPage, SortDirection, clamp_limit, clamp_page},
|
||||
time::{china_relative_time_str, china_rfc3339_str},
|
||||
},
|
||||
keys::types::{KeyManageError, ManagedClientApiKey},
|
||||
keys::types::{
|
||||
ClientApiKeyListSort, ClientApiKeySortField, KeyManageError, ManagedClientApiKey,
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -29,6 +31,8 @@ pub(crate) struct ApiKeysQuery {
|
||||
page: Option<u32>,
|
||||
page_size: Option<u32>,
|
||||
search: Option<String>,
|
||||
sort_by: Option<String>,
|
||||
sort_direction: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -120,10 +124,11 @@ pub(crate) async fn api_keys(
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
let page = clamp_page(query.page.unwrap_or(1));
|
||||
let page_size = clamp_limit(query.page_size.unwrap_or(50));
|
||||
let sort = client_api_key_list_sort(query.sort_by, query.sort_direction)?;
|
||||
match state
|
||||
.services
|
||||
.admin_client_keys
|
||||
.list_page(page, page_size, query.search)
|
||||
.list_page(page, page_size, query.search, sort)
|
||||
.await
|
||||
{
|
||||
Ok(page) => {
|
||||
@@ -142,6 +147,31 @@ pub(crate) async fn api_keys(
|
||||
}
|
||||
}
|
||||
|
||||
fn client_api_key_list_sort(
|
||||
sort_by: Option<String>,
|
||||
sort_direction: Option<String>,
|
||||
) -> Result<Option<ClientApiKeyListSort>, AdminError> {
|
||||
let (sort_by, sort_direction) = match (sort_by, sort_direction) {
|
||||
(None, None) => return Ok(None),
|
||||
(Some(sort_by), Some(sort_direction)) => (sort_by, sort_direction),
|
||||
_ => {
|
||||
return Err(AdminError::bad_request(
|
||||
"Client API key sort field and direction must be provided together",
|
||||
));
|
||||
}
|
||||
};
|
||||
let field = match sort_by.trim() {
|
||||
"name" => ClientApiKeySortField::Name,
|
||||
"enabled" => ClientApiKeySortField::Enabled,
|
||||
"createdAt" => ClientApiKeySortField::CreatedAt,
|
||||
"lastUsedAt" => ClientApiKeySortField::LastUsedAt,
|
||||
_ => return Err(AdminError::bad_request("Invalid client API key sort field")),
|
||||
};
|
||||
let direction = SortDirection::parse(&sort_direction)
|
||||
.ok_or_else(|| AdminError::bad_request("Invalid client API key sort direction"))?;
|
||||
Ok(Some(ClientApiKeyListSort { field, direction }))
|
||||
}
|
||||
|
||||
/// `POST /api/admin/keys`
|
||||
pub(crate) async fn create_api_key(
|
||||
State(state): State<AppState>,
|
||||
|
||||
@@ -8,13 +8,13 @@ use axum::{
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
api::AppState,
|
||||
api::admin::{
|
||||
response::{AdminError, AdminPageEnvelope, AdminResponse},
|
||||
session::AdminAuth,
|
||||
},
|
||||
api::AppState,
|
||||
infra::{
|
||||
json::{clamp_limit, clamp_page, NumberedPage},
|
||||
json::{NumberedPage, clamp_limit, clamp_page},
|
||||
time::china_datetime,
|
||||
},
|
||||
telemetry::{ops::query::OpsQueryError, ops::store::OpsErrorFilter, ops::types::OpsErrorLog},
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
//! 管理端响应封装与 From 转换。
|
||||
|
||||
use crate::infra::json::{total_pages, NumberedPage};
|
||||
use crate::infra::json::{NumberedPage, total_pages};
|
||||
use axum::{
|
||||
Json,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
@@ -16,7 +16,6 @@ const ADMIN_MALFORMED_JSON_CODE: u32 = 40000;
|
||||
const ADMIN_BAD_REQUEST_CODE: u32 = 40001;
|
||||
const ADMIN_INVALID_TIME_RANGE_CODE: u32 = 40002;
|
||||
const ADMIN_INVALID_MODEL_SOURCE_CODE: u32 = 40003;
|
||||
const ADMIN_INVALID_ENDPOINT_SOURCE_CODE: u32 = 40004;
|
||||
const ADMIN_SESSION_REQUIRED_CODE: u32 = 40101;
|
||||
const ADMIN_INVALID_CREDENTIALS_CODE: u32 = 40102;
|
||||
const ADMIN_INVALID_API_KEY_CODE: u32 = 40103;
|
||||
@@ -68,14 +67,6 @@ impl AdminError {
|
||||
)
|
||||
}
|
||||
|
||||
pub fn invalid_endpoint_source(message: impl Into<String>) -> Self {
|
||||
Self::new(
|
||||
StatusCode::BAD_REQUEST,
|
||||
ADMIN_INVALID_ENDPOINT_SOURCE_CODE,
|
||||
message,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn admin_session_required() -> Self {
|
||||
Self::new(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! 管理端路由。
|
||||
|
||||
use axum::{
|
||||
http::{header, HeaderValue},
|
||||
Router,
|
||||
http::{HeaderValue, header},
|
||||
middleware,
|
||||
response::Response,
|
||||
routing::{get, post},
|
||||
Router,
|
||||
};
|
||||
|
||||
use crate::api::AppState;
|
||||
@@ -30,7 +30,8 @@ use super::{
|
||||
},
|
||||
usage_routes::{
|
||||
clear_usage_records, usage_record_detail, usage_records,
|
||||
usage_records_endpoint_distribution, usage_records_latency_trend,
|
||||
usage_records_endpoint_distribution, usage_records_insights_diagnostics,
|
||||
usage_records_insights_overview, usage_records_latency_trend,
|
||||
usage_records_model_distribution, usage_records_summary, usage_records_token_trend,
|
||||
},
|
||||
};
|
||||
@@ -101,6 +102,14 @@ pub fn router() -> Router<AppState> {
|
||||
"/api/admin/usage/records/insights/latency-trend",
|
||||
get(usage_records_latency_trend),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/usage/records/insights/overview",
|
||||
get(usage_records_insights_overview),
|
||||
)
|
||||
.route(
|
||||
"/api/admin/usage/records/insights/diagnostics",
|
||||
get(usage_records_insights_diagnostics),
|
||||
)
|
||||
.route("/api/admin/usage/records/delete", post(clear_usage_records))
|
||||
.route("/api/admin/usage/records/detail", get(usage_record_detail))
|
||||
.route("/api/admin/ops/errors", get(ops_errors))
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
use axum::{
|
||||
extract::FromRequestParts,
|
||||
http::{request::Parts, HeaderMap},
|
||||
http::{HeaderMap, request::Parts},
|
||||
};
|
||||
|
||||
use crate::api::{admin::response::AdminError, AppState};
|
||||
use crate::api::{AppState, admin::response::AdminError};
|
||||
|
||||
pub(super) const ADMIN_SESSION_COOKIE: &str = "cpr_admin_session";
|
||||
|
||||
|
||||
@@ -6,11 +6,11 @@ use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::{
|
||||
api::AppState,
|
||||
api::admin::{
|
||||
response::{AdminEnvelope, AdminError, AdminResponse},
|
||||
session::AdminAuth,
|
||||
},
|
||||
api::AppState,
|
||||
settings::{SettingsError, SettingsPatch, SettingsSnapshot, SettingsValidationError},
|
||||
};
|
||||
|
||||
|
||||
@@ -6,24 +6,20 @@ use axum::{
|
||||
extract::{Json, Query, State},
|
||||
http::StatusCode,
|
||||
response::{
|
||||
sse::{Event, KeepAlive, Sse},
|
||||
IntoResponse,
|
||||
sse::{Event, KeepAlive, Sse},
|
||||
},
|
||||
};
|
||||
use futures::Stream;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::{
|
||||
api::AppState,
|
||||
api::admin::{
|
||||
response::{AdminEnvelope, AdminError, AdminResponse},
|
||||
session::AdminAuth,
|
||||
},
|
||||
api::AppState,
|
||||
update::{
|
||||
service::{self, RestartAction},
|
||||
state::operation_id,
|
||||
types::UpdateError,
|
||||
},
|
||||
update::{service::RestartAction, state::operation_id, types::UpdateError},
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -38,20 +34,30 @@ pub(crate) struct UpdateRequest {
|
||||
target_version: String,
|
||||
}
|
||||
|
||||
pub(crate) async fn version(_auth: AdminAuth) -> Result<impl IntoResponse, AdminError> {
|
||||
pub(crate) async fn version(
|
||||
State(state): State<AppState>,
|
||||
_auth: AdminAuth,
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(service::version_data().await),
|
||||
AdminEnvelope::ok(state.services.system_update.version_data().await),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn update_detail(
|
||||
State(state): State<AppState>,
|
||||
_auth: AdminAuth,
|
||||
Query(query): Query<UpdateDetailQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(service::update_detail(query.refresh.unwrap_or(false)).await),
|
||||
AdminEnvelope::ok(
|
||||
state
|
||||
.services
|
||||
.system_update
|
||||
.update_detail(query.refresh.unwrap_or(false))
|
||||
.await,
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -59,29 +65,25 @@ pub(crate) async fn update_event_stream(
|
||||
State(state): State<AppState>,
|
||||
_auth: AdminAuth,
|
||||
) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, AdminError> {
|
||||
let receiver = service::subscribe_update_events();
|
||||
let shutdown = state.services.process_control.subscribe_shutdown();
|
||||
let receiver = state.services.system_update.subscribe_update_events();
|
||||
let stream = futures::stream::unfold(
|
||||
(receiver, shutdown, false),
|
||||
|(mut receiver, mut shutdown, close_after_send)| async move {
|
||||
(receiver, false),
|
||||
|(mut receiver, close_after_send)| async move {
|
||||
if close_after_send {
|
||||
return None;
|
||||
}
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.recv() => return None,
|
||||
received = receiver.recv() => match received {
|
||||
Ok(message) => {
|
||||
let close_after_send = message.is_terminal();
|
||||
let id = message.id().to_string();
|
||||
let data = serde_json::to_string(&message)
|
||||
.unwrap_or_else(|_| "{}".to_string());
|
||||
let event = Event::default().event("update").id(id).data(data);
|
||||
return Some((Ok(event), (receiver, shutdown, close_after_send)));
|
||||
}
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => return None,
|
||||
match receiver.recv().await {
|
||||
Ok(message) => {
|
||||
let close_after_send = message.is_terminal();
|
||||
let id = message.id().to_string();
|
||||
let data =
|
||||
serde_json::to_string(&message).unwrap_or_else(|_| "{}".to_string());
|
||||
let event = Event::default().event("update").id(id).data(data);
|
||||
return Some((Ok(event), (receiver, close_after_send)));
|
||||
}
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => return None,
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -90,11 +92,15 @@ pub(crate) async fn update_event_stream(
|
||||
}
|
||||
|
||||
pub(crate) async fn perform_update(
|
||||
State(state): State<AppState>,
|
||||
_auth: AdminAuth,
|
||||
payload: Option<Json<UpdateRequest>>,
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
let target = payload.map(|Json(payload)| payload.target_version);
|
||||
let result = service::perform_update(target)
|
||||
let result = state
|
||||
.services
|
||||
.system_update
|
||||
.perform_update(target)
|
||||
.await
|
||||
.map_err(update_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
@@ -103,16 +109,31 @@ pub(crate) async fn perform_update(
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn update_status(_auth: AdminAuth) -> Result<impl IntoResponse, AdminError> {
|
||||
let status = service::update_status().map_err(update_error)?;
|
||||
pub(crate) async fn update_status(
|
||||
State(state): State<AppState>,
|
||||
_auth: AdminAuth,
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
let status = state
|
||||
.services
|
||||
.system_update
|
||||
.update_status()
|
||||
.map_err(update_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(status),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn rollback(_auth: AdminAuth) -> Result<impl IntoResponse, AdminError> {
|
||||
let operation_id = service::rollback().await.map_err(update_error)?;
|
||||
pub(crate) async fn rollback(
|
||||
State(state): State<AppState>,
|
||||
_auth: AdminAuth,
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
let operation_id = state
|
||||
.services
|
||||
.system_update
|
||||
.rollback()
|
||||
.await
|
||||
.map_err(update_error)?;
|
||||
Ok(AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(serde_json::json!({
|
||||
@@ -127,7 +148,11 @@ pub(crate) async fn restart(
|
||||
State(state): State<AppState>,
|
||||
_auth: AdminAuth,
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
let plan = service::restart_plan().map_err(update_error)?;
|
||||
let plan = state
|
||||
.services
|
||||
.system_update
|
||||
.restart_plan()
|
||||
.map_err(update_error)?;
|
||||
let message = plan.message;
|
||||
let process_control = state.services.process_control.clone();
|
||||
tokio::spawn(async move {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! 使用记录 HTTP 处理器。
|
||||
//! 使用统计与请求记录 HTTP 处理器。
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -8,28 +8,30 @@ use axum::{
|
||||
response::IntoResponse,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
api::AppState,
|
||||
api::admin::{
|
||||
response::{AdminEnvelope, AdminError, AdminPageEnvelope, AdminResponse},
|
||||
session::AdminAuth,
|
||||
},
|
||||
api::AppState,
|
||||
infra::{
|
||||
format::{
|
||||
format_compact_number, format_cost, format_duration_ms, format_duration_ms_f64,
|
||||
format_multiplier, format_number, format_percent, format_token_price, format_tokens,
|
||||
format_billing_amount, format_compact_number, format_duration_ms,
|
||||
format_duration_ms_f64, format_multiplier, format_number, format_percent,
|
||||
format_token_price, format_tokens,
|
||||
},
|
||||
json::{clamp_limit, clamp_page, NumberedPage},
|
||||
json::{NumberedPage, clamp_limit, clamp_page},
|
||||
time::china_datetime,
|
||||
},
|
||||
telemetry::{
|
||||
usage::insights::{UsageDiagnosticsDimension, default_time_range},
|
||||
usage::query::{
|
||||
usage_record_cost_details, UsageQueryError, UsageQueryFilter, UsageRecordBreakdown,
|
||||
UsageRecordEndpointSource, UsageRecordModelSource, UsageRecordSummary,
|
||||
UsageRecordTrendPoint,
|
||||
UsageQueryError, UsageQueryFilter, UsageRecordBreakdown, UsageRecordModelSource,
|
||||
UsageRecordSummary, UsageRecordTrendPoint, usage_record_billing,
|
||||
},
|
||||
usage::types::{metadata_string, UsageRecord},
|
||||
usage::types::{UsageRecord, metadata_string},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -63,6 +65,21 @@ pub(crate) struct UsageRecordDistributionQuery {
|
||||
source: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct UsageInsightsQuery {
|
||||
start_time: Option<String>,
|
||||
end_time: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct UsageDiagnosticsQuery {
|
||||
#[serde(flatten)]
|
||||
range: UsageInsightsQuery,
|
||||
dimension: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct UsageRecordDetailQuery {
|
||||
@@ -87,8 +104,12 @@ pub(crate) struct UsageRecordData {
|
||||
client_ip: Option<String>,
|
||||
user_agent: Option<String>,
|
||||
reasoning_effort: Option<String>,
|
||||
reasoning_preset: Option<String>,
|
||||
compact: bool,
|
||||
request_kind: Option<String>,
|
||||
subagent_kind: Option<String>,
|
||||
token_details: UsageRecordTokenDetailsData,
|
||||
cost_details: Option<UsageRecordCostDetailsData>,
|
||||
billing: Option<UsageRecordBillingData>,
|
||||
first_token_latency_ms: Option<i64>,
|
||||
first_token_latency_ms_display: String,
|
||||
latency_ms_display: String,
|
||||
@@ -111,23 +132,23 @@ pub(crate) struct UsageRecordTokenDetailsData {
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct UsageRecordCostDetailsData {
|
||||
input_cost: f64,
|
||||
output_cost: f64,
|
||||
cache_read_cost: f64,
|
||||
total_cost: f64,
|
||||
original_cost: f64,
|
||||
pub(crate) struct UsageRecordBillingData {
|
||||
input_amount: f64,
|
||||
output_amount: f64,
|
||||
cache_read_amount: f64,
|
||||
standard_amount: f64,
|
||||
total_amount: f64,
|
||||
input_price_per_mtoken: f64,
|
||||
output_price_per_mtoken: f64,
|
||||
cache_read_price_per_mtoken: f64,
|
||||
service_tier: Option<String>,
|
||||
service_tier_display: String,
|
||||
multiplier: f64,
|
||||
input_cost_display: String,
|
||||
output_cost_display: String,
|
||||
cache_read_cost_display: String,
|
||||
total_cost_display: String,
|
||||
original_cost_display: String,
|
||||
input_amount_display: String,
|
||||
output_amount_display: String,
|
||||
cache_read_amount_display: String,
|
||||
standard_amount_display: String,
|
||||
total_amount_display: String,
|
||||
input_price_display: String,
|
||||
output_price_display: String,
|
||||
cache_read_price_display: String,
|
||||
@@ -158,9 +179,9 @@ struct UsageRecordBreakdownData {
|
||||
total_tokens_value: u64,
|
||||
total_tokens_total: String,
|
||||
total_tokens_total_value: u64,
|
||||
cost: String,
|
||||
actual_cost: String,
|
||||
account_cost: String,
|
||||
standard_billing_amount: String,
|
||||
actual_billing_amount: String,
|
||||
account_billing_amount: String,
|
||||
average_latency_ms: String,
|
||||
}
|
||||
|
||||
@@ -178,8 +199,8 @@ struct UsageRecordTrendPointData {
|
||||
total_tokens_value: u64,
|
||||
cache_hit_rate: String,
|
||||
cache_hit_rate_value: f64,
|
||||
cost: String,
|
||||
actual_cost: String,
|
||||
standard_billing_amount: String,
|
||||
actual_billing_amount: String,
|
||||
average_latency_ms: String,
|
||||
average_latency_ms_value: Option<f64>,
|
||||
}
|
||||
@@ -264,14 +285,13 @@ pub(crate) async fn usage_records_model_distribution(
|
||||
pub(crate) async fn usage_records_endpoint_distribution(
|
||||
State(state): State<AppState>,
|
||||
_auth: AdminAuth,
|
||||
Query(query): Query<UsageRecordDistributionQuery>,
|
||||
Query(query): Query<UsageRecordsQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
let source = endpoint_source_from_query(query.source)?;
|
||||
let filter = filter_from_query(query.records)?;
|
||||
let filter = filter_from_query(query)?;
|
||||
match state
|
||||
.services
|
||||
.usage_records
|
||||
.endpoint_distribution(filter, source)
|
||||
.endpoint_distribution(filter)
|
||||
.await
|
||||
{
|
||||
Ok(items) => Ok(AdminResponse::new(
|
||||
@@ -300,6 +320,39 @@ pub(crate) async fn usage_records_latency_trend(
|
||||
usage_records_trend_response(state, query).await
|
||||
}
|
||||
|
||||
/// `GET /api/admin/usage/records/insights/overview`
|
||||
pub(crate) async fn usage_records_insights_overview(
|
||||
State(state): State<AppState>,
|
||||
_auth: AdminAuth,
|
||||
Query(query): Query<UsageInsightsQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
let (start, end) = insights_time_range(query)?;
|
||||
state
|
||||
.services
|
||||
.usage_records
|
||||
.insights_overview(start, end)
|
||||
.await
|
||||
.map(|insights| AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(insights)))
|
||||
.map_err(|error| log_error(&error))
|
||||
}
|
||||
|
||||
/// `GET /api/admin/usage/records/insights/diagnostics`
|
||||
pub(crate) async fn usage_records_insights_diagnostics(
|
||||
State(state): State<AppState>,
|
||||
_auth: AdminAuth,
|
||||
Query(query): Query<UsageDiagnosticsQuery>,
|
||||
) -> Result<impl IntoResponse, AdminError> {
|
||||
let dimension = diagnostics_dimension(query.dimension)?;
|
||||
let (start, end) = insights_time_range(query.range)?;
|
||||
state
|
||||
.services
|
||||
.usage_records
|
||||
.insights_diagnostics(start, end, dimension)
|
||||
.await
|
||||
.map(|insights| AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(insights)))
|
||||
.map_err(|error| log_error(&error))
|
||||
}
|
||||
|
||||
async fn usage_records_trend_response(
|
||||
state: AppState,
|
||||
query: UsageRecordsQuery,
|
||||
@@ -390,19 +443,6 @@ fn model_source_from_query(value: Option<String>) -> Result<UsageRecordModelSour
|
||||
}
|
||||
}
|
||||
|
||||
fn endpoint_source_from_query(
|
||||
value: Option<String>,
|
||||
) -> Result<UsageRecordEndpointSource, AdminError> {
|
||||
match non_empty(value).as_deref().unwrap_or("inbound") {
|
||||
"inbound" => Ok(UsageRecordEndpointSource::Inbound),
|
||||
"upstream" => Ok(UsageRecordEndpointSource::Upstream),
|
||||
"path" => Ok(UsageRecordEndpointSource::Path),
|
||||
_ => Err(AdminError::invalid_endpoint_source(
|
||||
"Invalid endpoint distribution source",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn optional_datetime(
|
||||
value: Option<String>,
|
||||
) -> Result<Option<chrono::DateTime<chrono::Utc>>, AdminError> {
|
||||
@@ -414,6 +454,25 @@ fn optional_datetime(
|
||||
.map_err(|_| AdminError::invalid_time_range("Invalid time range"))
|
||||
}
|
||||
|
||||
fn insights_time_range(
|
||||
query: UsageInsightsQuery,
|
||||
) -> Result<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>), AdminError> {
|
||||
let end = optional_datetime(query.end_time)?.unwrap_or_else(chrono::Utc::now);
|
||||
let start = optional_datetime(query.start_time)?.unwrap_or_else(|| default_time_range(end).0);
|
||||
if start >= end {
|
||||
return Err(AdminError::invalid_time_range(
|
||||
"Start time must be earlier than end time",
|
||||
));
|
||||
}
|
||||
Ok((start, end))
|
||||
}
|
||||
|
||||
fn diagnostics_dimension(value: Option<String>) -> Result<UsageDiagnosticsDimension, AdminError> {
|
||||
let value = non_empty(value).unwrap_or_else(|| "model".to_string());
|
||||
UsageDiagnosticsDimension::parse(&value)
|
||||
.ok_or_else(|| AdminError::bad_request("Invalid diagnostics dimension"))
|
||||
}
|
||||
|
||||
fn log_error(error: &UsageQueryError) -> AdminError {
|
||||
match error {
|
||||
UsageQueryError::List | UsageQueryError::Get | UsageQueryError::Clear => {
|
||||
@@ -452,8 +511,16 @@ fn usage_record_data(
|
||||
let user_agent = metadata_string(&record.metadata, &["userAgent", "user_agent"]);
|
||||
let reasoning_effort =
|
||||
metadata_string(&record.metadata, &["reasoningEffort", "reasoning_effort"]);
|
||||
let reasoning_preset = metadata_string(&record.metadata, &["reasoningPreset"]);
|
||||
let compact = record
|
||||
.metadata
|
||||
.get("compact")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
let request_kind = metadata_string(&record.metadata, &["requestKind", "request_kind"]);
|
||||
let subagent_kind = metadata_string(&record.metadata, &["subagentKind", "subagent_kind"]);
|
||||
let token_details = usage_token_details(&record);
|
||||
let cost_details = usage_cost_details(&record, upstream_model.as_deref(), &token_details);
|
||||
let billing = usage_billing(&record, upstream_model.as_deref(), &token_details);
|
||||
let first_token_latency_ms = record.first_token_ms;
|
||||
let first_token_latency_ms_display = format_duration_ms(first_token_latency_ms);
|
||||
let latency_ms_display = format_duration_ms(record.latency_ms);
|
||||
@@ -466,8 +533,12 @@ fn usage_record_data(
|
||||
client_ip,
|
||||
user_agent,
|
||||
reasoning_effort,
|
||||
reasoning_preset,
|
||||
compact,
|
||||
request_kind,
|
||||
subagent_kind,
|
||||
token_details,
|
||||
cost_details,
|
||||
billing,
|
||||
first_token_latency_ms,
|
||||
first_token_latency_ms_display,
|
||||
latency_ms_display,
|
||||
@@ -523,12 +594,12 @@ pub(crate) fn usage_token_details(record: &UsageRecord) -> UsageRecordTokenDetai
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn usage_cost_details(
|
||||
pub(crate) fn usage_billing(
|
||||
record: &UsageRecord,
|
||||
upstream_model: Option<&str>,
|
||||
tokens: &UsageRecordTokenDetailsData,
|
||||
) -> Option<UsageRecordCostDetailsData> {
|
||||
let cost = usage_record_cost_details(
|
||||
) -> Option<UsageRecordBillingData> {
|
||||
let billing = usage_record_billing(
|
||||
record,
|
||||
upstream_model,
|
||||
tokens.input_tokens,
|
||||
@@ -536,27 +607,27 @@ pub(crate) fn usage_cost_details(
|
||||
tokens.cached_tokens,
|
||||
)?;
|
||||
|
||||
Some(UsageRecordCostDetailsData {
|
||||
input_cost: cost.input_cost,
|
||||
output_cost: cost.output_cost,
|
||||
cache_read_cost: cost.cache_read_cost,
|
||||
total_cost: cost.total_cost,
|
||||
original_cost: cost.original_cost,
|
||||
input_price_per_mtoken: cost.input_price_per_mtoken,
|
||||
output_price_per_mtoken: cost.output_price_per_mtoken,
|
||||
cache_read_price_per_mtoken: cost.cache_read_price_per_mtoken,
|
||||
service_tier: cost.service_tier,
|
||||
service_tier_display: cost.service_tier_display,
|
||||
multiplier: cost.multiplier,
|
||||
input_cost_display: format_cost(cost.input_cost),
|
||||
output_cost_display: format_cost(cost.output_cost),
|
||||
cache_read_cost_display: format_cost(cost.cache_read_cost),
|
||||
total_cost_display: format_cost(cost.total_cost),
|
||||
original_cost_display: format_cost(cost.original_cost),
|
||||
input_price_display: format_token_price(cost.input_price_per_mtoken),
|
||||
output_price_display: format_token_price(cost.output_price_per_mtoken),
|
||||
cache_read_price_display: format_token_price(cost.cache_read_price_per_mtoken),
|
||||
multiplier_display: format_multiplier(cost.multiplier),
|
||||
Some(UsageRecordBillingData {
|
||||
input_amount: billing.input_amount,
|
||||
output_amount: billing.output_amount,
|
||||
cache_read_amount: billing.cache_read_amount,
|
||||
standard_amount: billing.standard_amount,
|
||||
total_amount: billing.total_amount,
|
||||
input_price_per_mtoken: billing.input_price_per_mtoken,
|
||||
output_price_per_mtoken: billing.output_price_per_mtoken,
|
||||
cache_read_price_per_mtoken: billing.cache_read_price_per_mtoken,
|
||||
service_tier: billing.service_tier,
|
||||
service_tier_display: billing.service_tier_display,
|
||||
multiplier: billing.multiplier,
|
||||
input_amount_display: format_billing_amount(billing.input_amount),
|
||||
output_amount_display: format_billing_amount(billing.output_amount),
|
||||
cache_read_amount_display: format_billing_amount(billing.cache_read_amount),
|
||||
standard_amount_display: format_billing_amount(billing.standard_amount),
|
||||
total_amount_display: format_billing_amount(billing.total_amount),
|
||||
input_price_display: format_token_price(billing.input_price_per_mtoken),
|
||||
output_price_display: format_token_price(billing.output_price_per_mtoken),
|
||||
cache_read_price_display: format_token_price(billing.cache_read_price_per_mtoken),
|
||||
multiplier_display: format_multiplier(billing.multiplier),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -592,9 +663,9 @@ impl UsageRecordBreakdownData {
|
||||
total_tokens_value: item.total_tokens,
|
||||
total_tokens_total: format_tokens(total_tokens_total),
|
||||
total_tokens_total_value: total_tokens_total,
|
||||
cost: format_cost(item.cost),
|
||||
actual_cost: format_cost(item.actual_cost),
|
||||
account_cost: format_cost(item.account_cost),
|
||||
standard_billing_amount: format_billing_amount(item.standard_billing_amount),
|
||||
actual_billing_amount: format_billing_amount(item.actual_billing_amount),
|
||||
account_billing_amount: format_billing_amount(item.account_billing_amount),
|
||||
average_latency_ms: format_duration_ms_f64(item.average_latency_ms),
|
||||
}
|
||||
}
|
||||
@@ -613,9 +684,9 @@ fn usage_record_breakdown_items(items: Vec<UsageRecordBreakdown>) -> Vec<UsageRe
|
||||
|
||||
impl From<UsageRecordTrendPoint> for UsageRecordTrendPointData {
|
||||
fn from(point: UsageRecordTrendPoint) -> Self {
|
||||
let prompt_tokens = point.input_tokens.saturating_add(point.cached_tokens);
|
||||
let cache_hit_rate_value = if prompt_tokens > 0 {
|
||||
(point.cached_tokens as f64 / prompt_tokens as f64 * 100.0).round()
|
||||
let cache_hit_rate_value = if point.input_tokens > 0 {
|
||||
(point.cached_tokens.min(point.input_tokens) as f64 / point.input_tokens as f64 * 100.0)
|
||||
.round()
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
@@ -631,8 +702,8 @@ impl From<UsageRecordTrendPoint> for UsageRecordTrendPointData {
|
||||
total_tokens_value: point.total_tokens,
|
||||
cache_hit_rate: format_percent(cache_hit_rate_value),
|
||||
cache_hit_rate_value,
|
||||
cost: format_cost(point.cost),
|
||||
actual_cost: format_cost(point.actual_cost),
|
||||
standard_billing_amount: format_billing_amount(point.standard_billing_amount),
|
||||
actual_billing_amount: format_billing_amount(point.actual_billing_amount),
|
||||
average_latency_ms: format_duration_ms_f64(point.average_latency_ms),
|
||||
average_latency_ms_value: point.average_latency_ms,
|
||||
}
|
||||
|
||||
@@ -4,10 +4,10 @@ use std::{
|
||||
};
|
||||
|
||||
use axum::{
|
||||
Json, Router,
|
||||
body::Body,
|
||||
http::{Request, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
Json, Router,
|
||||
};
|
||||
use serde_json::json;
|
||||
use tower::service_fn;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! 提供 Bearer token 提取与客户端 API key 校验。
|
||||
|
||||
use axum::http::{header::AUTHORIZATION, HeaderMap};
|
||||
use axum::http::{HeaderMap, header::AUTHORIZATION};
|
||||
|
||||
use crate::api::AppState;
|
||||
|
||||
@@ -93,13 +93,13 @@ fn log_client_api_key_auth_failure(error: &ClientApiKeyAuthError) {
|
||||
tracing::warn!(
|
||||
auth_failure = error.reason(),
|
||||
error = %message,
|
||||
"client api key authorization failed"
|
||||
"Client API key authorization failed"
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
tracing::info!(
|
||||
auth_failure = error.reason(),
|
||||
"client api key authorization failed"
|
||||
"Client API key authorization failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
//! OpenAI 路由共享错误响应。
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::{json, Value};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{
|
||||
dispatch::errors::{DispatchFailureClass, ResponseDispatchError},
|
||||
upstream::openai::protocol::sse::response_failed_sse_event as encode_response_failed_sse_event,
|
||||
upstream::openai::protocol::{
|
||||
responses::ResponsesSseFailure,
|
||||
sse::response_failed_sse_event as encode_response_failed_sse_event,
|
||||
},
|
||||
upstream::openai::transport::CodexClientError,
|
||||
};
|
||||
|
||||
@@ -47,6 +50,13 @@ struct OpenAiErrorKind {
|
||||
code: &'static str,
|
||||
}
|
||||
|
||||
struct EncodedClientFailure<'a> {
|
||||
status: StatusCode,
|
||||
kind: OpenAiErrorKind,
|
||||
code: &'a str,
|
||||
message: &'a str,
|
||||
}
|
||||
|
||||
const NO_AVAILABLE_ACCOUNTS_ERROR: OpenAiErrorKind = OpenAiErrorKind {
|
||||
error_type: "server_error",
|
||||
code: "no_available_accounts",
|
||||
@@ -117,12 +127,20 @@ pub fn responses_dispatch_error_response(error: ResponseDispatchError) -> Respon
|
||||
|
||||
pub fn responses_dispatch_error_response_ref(error: &ResponseDispatchError) -> Response {
|
||||
if let ResponseDispatchError::Upstream(CodexClientError::Upstream { status, body, .. }) = error
|
||||
&& status.is_client_error()
|
||||
&& let Ok(body) = serde_json::from_str::<Value>(body)
|
||||
{
|
||||
if status.is_client_error() {
|
||||
if let Ok(body) = serde_json::from_str::<Value>(body) {
|
||||
return (*status, Json(body)).into_response();
|
||||
}
|
||||
}
|
||||
return (*status, Json(body)).into_response();
|
||||
}
|
||||
|
||||
if let Some(failure) = response_dispatch_client_failure(error) {
|
||||
return openai_error_response(
|
||||
failure.status,
|
||||
failure.message,
|
||||
failure.kind.error_type,
|
||||
failure.code,
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
match error {
|
||||
@@ -134,12 +152,101 @@ pub fn responses_dispatch_error_response_ref(error: &ResponseDispatchError) -> R
|
||||
}
|
||||
|
||||
pub fn responses_stream_dispatch_failed_sse_event(error: &ResponseDispatchError) -> String {
|
||||
if let Some(failure) = response_dispatch_client_failure(error) {
|
||||
return encode_response_failed_sse_event(
|
||||
failure.kind.error_type,
|
||||
failure.code,
|
||||
failure.message,
|
||||
);
|
||||
}
|
||||
let http_error =
|
||||
response_dispatch_http_error(error, ResponseDispatchMessageStyle::ResponsesStream);
|
||||
let kind = response_dispatch_error_kind(error);
|
||||
responses_failed_sse_event(kind, &http_error.message)
|
||||
}
|
||||
|
||||
pub(super) fn responses_websocket_dispatch_error_event(
|
||||
error: &ResponseDispatchError,
|
||||
request_id: &str,
|
||||
) -> String {
|
||||
if let Some(failure) = response_dispatch_client_failure(error) {
|
||||
return responses_websocket_error_event(
|
||||
failure.status,
|
||||
failure.kind.error_type,
|
||||
failure.code,
|
||||
failure.message,
|
||||
request_id,
|
||||
);
|
||||
}
|
||||
if let Some(event) = upstream_client_websocket_error_event(error, request_id) {
|
||||
return event;
|
||||
}
|
||||
let http_error =
|
||||
response_dispatch_http_error(error, ResponseDispatchMessageStyle::ResponsesStream);
|
||||
let kind = response_dispatch_error_kind(error);
|
||||
responses_websocket_error_event(
|
||||
http_error.status,
|
||||
kind.error_type,
|
||||
kind.code,
|
||||
&http_error.message,
|
||||
request_id,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn responses_websocket_error_event(
|
||||
status: StatusCode,
|
||||
error_type: &str,
|
||||
code: &str,
|
||||
message: &str,
|
||||
request_id: &str,
|
||||
) -> String {
|
||||
json!({
|
||||
"type": "error",
|
||||
"status": status.as_u16(),
|
||||
"error": {
|
||||
"type": error_type,
|
||||
"code": code,
|
||||
"message": message,
|
||||
},
|
||||
"headers": {
|
||||
"x-request-id": request_id,
|
||||
},
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn upstream_client_websocket_error_event(
|
||||
error: &ResponseDispatchError,
|
||||
request_id: &str,
|
||||
) -> Option<String> {
|
||||
let ResponseDispatchError::Upstream(CodexClientError::Upstream { status, body, .. }) = error
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
if !status.is_client_error() {
|
||||
return None;
|
||||
}
|
||||
let Value::Object(mut payload) = serde_json::from_str::<Value>(body).ok()? else {
|
||||
return None;
|
||||
};
|
||||
if !payload.get("error").is_some_and(Value::is_object) {
|
||||
return None;
|
||||
}
|
||||
payload.insert("type".to_string(), Value::String("error".to_string()));
|
||||
payload.insert("status".to_string(), Value::Number(status.as_u16().into()));
|
||||
let headers = payload
|
||||
.entry("headers".to_string())
|
||||
.or_insert_with(|| Value::Object(serde_json::Map::new()));
|
||||
if !headers.is_object() {
|
||||
*headers = Value::Object(serde_json::Map::new());
|
||||
}
|
||||
headers.as_object_mut()?.insert(
|
||||
"x-request-id".to_string(),
|
||||
Value::String(request_id.to_string()),
|
||||
);
|
||||
Some(Value::Object(payload).to_string())
|
||||
}
|
||||
|
||||
fn responses_no_available_accounts_response() -> (StatusCode, Json<Value>) {
|
||||
let kind = NO_AVAILABLE_ACCOUNTS_ERROR;
|
||||
(
|
||||
@@ -242,6 +349,33 @@ fn responses_error_kind_for_status(status: StatusCode) -> OpenAiErrorKind {
|
||||
}
|
||||
}
|
||||
|
||||
fn response_dispatch_client_failure(
|
||||
error: &ResponseDispatchError,
|
||||
) -> Option<EncodedClientFailure<'_>> {
|
||||
let client_failure = match error {
|
||||
ResponseDispatchError::Failed(failure) => failure,
|
||||
_ => return None,
|
||||
};
|
||||
let failure = client_failure.exposed_upstream()?;
|
||||
Some(encoded_client_failure(
|
||||
failure,
|
||||
status_from_u16(client_failure.status_code(), StatusCode::BAD_GATEWAY),
|
||||
))
|
||||
}
|
||||
|
||||
fn encoded_client_failure(
|
||||
failure: &ResponsesSseFailure,
|
||||
status: StatusCode,
|
||||
) -> EncodedClientFailure<'_> {
|
||||
let kind = responses_error_kind_for_status(status);
|
||||
EncodedClientFailure {
|
||||
status,
|
||||
kind,
|
||||
code: failure.upstream_code.as_deref().unwrap_or(kind.code),
|
||||
message: &failure.message,
|
||||
}
|
||||
}
|
||||
|
||||
fn response_dispatch_message(
|
||||
error: &ResponseDispatchError,
|
||||
style: ResponseDispatchMessageStyle,
|
||||
|
||||
@@ -5,4 +5,3 @@ pub mod errors;
|
||||
pub mod models;
|
||||
pub mod responses;
|
||||
pub mod router;
|
||||
pub mod sse;
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
//! OpenAI 模型列表以及模型处理器。
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::IntoResponse,
|
||||
Json,
|
||||
};
|
||||
use serde_json::{json, Value};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{
|
||||
api::client::auth::authorize_client_api_key, api::AppState, models::catalog::ModelCatalog,
|
||||
api::AppState, api::client::auth::authorize_client_api_key, models::catalog::ModelCatalog,
|
||||
};
|
||||
|
||||
use super::errors::{missing_client_api_key_response, model_not_found_response};
|
||||
|
||||
@@ -1,25 +1,28 @@
|
||||
//! OpenAI Responses API 透明代理入口:解析原始 JSON body,提取调度元数据,
|
||||
//! 做最小 patch 后交给调度层,请求语义原样透传上游。
|
||||
|
||||
mod sse;
|
||||
mod websocket;
|
||||
|
||||
pub use websocket::responses_websocket;
|
||||
|
||||
use axum::{
|
||||
Extension, Json,
|
||||
body::{Body, Bytes},
|
||||
extract::State,
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
Extension, Json,
|
||||
};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::{
|
||||
api::middleware::request_id::{ClientIp, RequestId},
|
||||
api::AppState,
|
||||
api::middleware::request_id::{ClientIp, RequestId},
|
||||
dispatch::{errors::ResponseDispatchError, service::ResponseDispatchStream},
|
||||
upstream::openai::protocol::{
|
||||
responses::{CodexCompactRequest, CodexResponsesRequest},
|
||||
sse::sse_body_has_done,
|
||||
},
|
||||
upstream::openai::protocol::{responses::CodexResponsesRequest, sse::sse_body_has_done},
|
||||
};
|
||||
|
||||
use self::sse::{done_sse_frame, event_stream_response as sse_event_stream_response};
|
||||
use super::{
|
||||
errors::{
|
||||
invalid_responses_request_response, missing_client_api_key_response,
|
||||
@@ -27,7 +30,6 @@ use super::{
|
||||
responses_dispatch_error_response_ref, responses_stream_dispatch_failed_sse_event,
|
||||
},
|
||||
models::model_catalog_for_state,
|
||||
sse::{done_sse_frame, event_stream_response as sse_event_stream_response},
|
||||
};
|
||||
|
||||
const OPENAI_SUBAGENT_HEADER: &str = "x-openai-subagent";
|
||||
@@ -101,32 +103,36 @@ pub fn build_codex_request(
|
||||
None => {}
|
||||
}
|
||||
apply_context_header_fields(&mut request, headers);
|
||||
apply_identity_fields(&mut request, headers);
|
||||
apply_session_fields(&mut request, headers);
|
||||
request.client_user_agent = user_agent_from_headers(headers);
|
||||
request
|
||||
}
|
||||
|
||||
fn apply_identity_fields(request: &mut CodexResponsesRequest, headers: &HeaderMap) {
|
||||
request.client_conversation_id = request.prompt_cache_key().map(ToString::to_string);
|
||||
request.client_session_id = identity_context_string(request.body(), "session_id")
|
||||
.or_else(|| header_string(headers, "session-id"));
|
||||
request.client_thread_id = identity_context_string(request.body(), "thread_id")
|
||||
fn apply_session_fields(request: &mut CodexResponsesRequest, headers: &HeaderMap) {
|
||||
request.client_conversation_id = session_context_string(request.body(), "conversation_id")
|
||||
.or_else(|| header_string(headers, "conversation-id"))
|
||||
.or_else(|| header_string(headers, "conversation_id"))
|
||||
.or_else(|| request.prompt_cache_key().map(ToString::to_string));
|
||||
request.client_session_id = session_context_string(request.body(), "session_id")
|
||||
.or_else(|| header_string(headers, "session-id"))
|
||||
.or_else(|| header_string(headers, "session_id"));
|
||||
request.client_thread_id = session_context_string(request.body(), "thread_id")
|
||||
.or_else(|| header_string(headers, "thread-id"));
|
||||
request.client_request_id = identity_context_string(request.body(), "x-client-request-id")
|
||||
request.client_request_id = session_context_string(request.body(), "x-client-request-id")
|
||||
.or_else(|| header_string(headers, "x-client-request-id"));
|
||||
request.client_turn_id = identity_context_string(request.body(), "turn_id")
|
||||
request.client_turn_id = session_context_string(request.body(), "turn_id")
|
||||
.or_else(|| header_string(headers, "x-codex-turn-id"));
|
||||
request.codex_window_id = request.codex_window_id.take().or_else(|| {
|
||||
identity_context_string(request.body(), "x-codex-window-id")
|
||||
session_context_string(request.body(), "x-codex-window-id")
|
||||
.or_else(|| header_string(headers, "x-codex-window-id"))
|
||||
});
|
||||
request.parent_thread_id = request.parent_thread_id.take().or_else(|| {
|
||||
identity_context_string(request.body(), "x-codex-parent-thread-id")
|
||||
session_context_string(request.body(), "x-codex-parent-thread-id")
|
||||
.or_else(|| header_string(headers, "x-codex-parent-thread-id"))
|
||||
});
|
||||
}
|
||||
|
||||
fn identity_context_string(body: &Map<String, Value>, key: &str) -> Option<String> {
|
||||
fn session_context_string(body: &Map<String, Value>, key: &str) -> Option<String> {
|
||||
body_context_string(body, key).or_else(|| {
|
||||
body.get("client_metadata")
|
||||
.and_then(Value::as_object)
|
||||
@@ -138,49 +144,6 @@ fn identity_context_string(body: &Map<String, Value>, key: &str) -> Option<Strin
|
||||
})
|
||||
}
|
||||
|
||||
/// 从客户端原始 Responses JSON body 构造 Codex compact 请求。
|
||||
///
|
||||
/// compact 端点只返回一次性 JSON(代理按非流式读取),故剥离 `stream` 这一
|
||||
/// transport 控制字段,避免上游返回代理无法解析的 SSE 形态。业务语义字段
|
||||
/// (`reasoning`/`text`/`store`/`prompt_cache_key`/`previous_response_id`/
|
||||
/// `include`/`client_metadata`/未知字段)一律原样透传。
|
||||
pub fn build_compact_request(
|
||||
mut body: Map<String, Value>,
|
||||
headers: &HeaderMap,
|
||||
) -> CodexCompactRequest {
|
||||
let client_session_id = identity_context_string(&body, "session_id")
|
||||
.or_else(|| header_string(headers, "session-id"));
|
||||
let client_thread_id =
|
||||
identity_context_string(&body, "thread_id").or_else(|| header_string(headers, "thread-id"));
|
||||
let client_request_id = identity_context_string(&body, "x-client-request-id")
|
||||
.or_else(|| header_string(headers, "x-client-request-id"));
|
||||
let client_turn_id = identity_context_string(&body, "turn_id")
|
||||
.or_else(|| header_string(headers, "x-codex-turn-id"));
|
||||
let client_window_id = identity_context_string(&body, "x-codex-window-id")
|
||||
.or_else(|| header_string(headers, "x-codex-window-id"));
|
||||
let client_parent_thread_id = identity_context_string(&body, "x-codex-parent-thread-id")
|
||||
.or_else(|| header_string(headers, "x-codex-parent-thread-id"));
|
||||
body.remove(COMPACT_STREAM_KEY);
|
||||
for key in TRANSPORT_ONLY_KEYS {
|
||||
body.remove(key);
|
||||
}
|
||||
CodexCompactRequest {
|
||||
body,
|
||||
client_ip: None,
|
||||
client_user_agent: user_agent_from_headers(headers),
|
||||
client_api_key_id: None,
|
||||
client_session_id,
|
||||
client_thread_id,
|
||||
client_request_id,
|
||||
client_turn_id,
|
||||
client_window_id,
|
||||
client_parent_thread_id,
|
||||
}
|
||||
}
|
||||
|
||||
/// compact 端点不支持流式,转发前剥离 `stream`(transport 控制字段,非业务语义)。
|
||||
const COMPACT_STREAM_KEY: &str = "stream";
|
||||
|
||||
fn inject_subagent_metadata(body: &mut Map<String, Value>, subagent: &str) {
|
||||
let metadata = body
|
||||
.entry("client_metadata")
|
||||
@@ -286,24 +249,6 @@ pub async fn review_responses(
|
||||
.await
|
||||
}
|
||||
|
||||
/// `POST /v1/responses/compact`
|
||||
pub async fn compact_responses(
|
||||
State(state): State<AppState>,
|
||||
Extension(request_id): Extension<RequestId>,
|
||||
client_ip: Option<Extension<ClientIp>>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
handle_compact_responses(
|
||||
state,
|
||||
request_id,
|
||||
client_ip.map(|Extension(client_ip)| client_ip.as_str().to_string()),
|
||||
headers,
|
||||
body,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn handle_responses(
|
||||
state: AppState,
|
||||
request_id: RequestId,
|
||||
@@ -322,29 +267,39 @@ async fn handle_responses(
|
||||
let Some(body) = parse_responses_body(&body) else {
|
||||
return invalid_responses_request_response().into_response();
|
||||
};
|
||||
let model = match validated_responses_model(&state, request_model(&body)).await {
|
||||
Ok(model) => model,
|
||||
Err(ResponsesModelValidationError::InvalidRequest) => {
|
||||
let prepared = match prepare_responses_request(
|
||||
&state,
|
||||
body,
|
||||
&headers,
|
||||
forced_subagent,
|
||||
client_ip,
|
||||
client_api_key_id,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(prepared) => prepared,
|
||||
Err(ResponsesRequestValidationError::InvalidRequest) => {
|
||||
return invalid_responses_request_response().into_response();
|
||||
}
|
||||
Err(ResponsesModelValidationError::ModelNotFound) => {
|
||||
Err(ResponsesRequestValidationError::ModelNotFound) => {
|
||||
return model_not_found_response().into_response();
|
||||
}
|
||||
};
|
||||
let mut codex_request = build_codex_request(body, &headers, forced_subagent);
|
||||
codex_request.client_ip = client_ip;
|
||||
codex_request.client_api_key_id = Some(client_api_key_id);
|
||||
let PreparedResponsesRequest {
|
||||
mut request,
|
||||
requested_model,
|
||||
} = prepared;
|
||||
// 客户端未显式指定 transport 时默认偏好 WebSocket。
|
||||
if !codex_request.force_http_sse {
|
||||
codex_request.use_websocket = true;
|
||||
if !request.force_http_sse {
|
||||
request.use_websocket = true;
|
||||
}
|
||||
let stream = codex_request.stream();
|
||||
let stream = request.stream();
|
||||
|
||||
if stream {
|
||||
return match state
|
||||
.services
|
||||
.responses
|
||||
.stream(request_id.as_str(), route, codex_request, &model)
|
||||
.stream(request_id.as_str(), route, request, &requested_model)
|
||||
.await
|
||||
{
|
||||
Ok(stream) => live_event_stream_response(stream),
|
||||
@@ -355,50 +310,7 @@ async fn handle_responses(
|
||||
match state
|
||||
.services
|
||||
.responses
|
||||
.complete(request_id.as_str(), route, codex_request, &model)
|
||||
.await
|
||||
{
|
||||
Ok(result) => apply_safe_response_headers(
|
||||
(StatusCode::OK, Json(result.body)).into_response(),
|
||||
result.response_headers,
|
||||
),
|
||||
Err(error) => responses_dispatch_error_response(error),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_compact_responses(
|
||||
state: AppState,
|
||||
request_id: RequestId,
|
||||
client_ip: Option<String>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
let Some(client_api_key_id) =
|
||||
crate::api::client::auth::authorized_client_api_key_id(&state, &headers).await
|
||||
else {
|
||||
return missing_client_api_key_response().into_response();
|
||||
};
|
||||
|
||||
let Some(body) = parse_responses_body(&body) else {
|
||||
return invalid_responses_request_response().into_response();
|
||||
};
|
||||
let model = match validated_responses_model(&state, request_model(&body)).await {
|
||||
Ok(model) => model,
|
||||
Err(ResponsesModelValidationError::InvalidRequest) => {
|
||||
return invalid_responses_request_response().into_response();
|
||||
}
|
||||
Err(ResponsesModelValidationError::ModelNotFound) => {
|
||||
return model_not_found_response().into_response();
|
||||
}
|
||||
};
|
||||
let mut compact_request = build_compact_request(body, &headers);
|
||||
compact_request.client_ip = client_ip;
|
||||
compact_request.client_api_key_id = Some(client_api_key_id);
|
||||
|
||||
match state
|
||||
.services
|
||||
.responses
|
||||
.compact(request_id.as_str(), compact_request, &model)
|
||||
.complete(request_id.as_str(), route, request, &requested_model)
|
||||
.await
|
||||
{
|
||||
Ok(result) => apply_safe_response_headers(
|
||||
@@ -423,23 +335,47 @@ fn request_model(body: &Map<String, Value>) -> &str {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(super) struct PreparedResponsesRequest {
|
||||
pub(super) request: CodexResponsesRequest,
|
||||
pub(super) requested_model: String,
|
||||
}
|
||||
|
||||
pub(super) async fn prepare_responses_request(
|
||||
state: &AppState,
|
||||
body: Map<String, Value>,
|
||||
headers: &HeaderMap,
|
||||
forced_subagent: Option<&str>,
|
||||
client_ip: Option<String>,
|
||||
client_api_key_id: String,
|
||||
) -> Result<PreparedResponsesRequest, ResponsesRequestValidationError> {
|
||||
let requested_model = validated_responses_model(state, request_model(&body)).await?;
|
||||
let mut request = build_codex_request(body, headers, forced_subagent);
|
||||
request.client_ip = client_ip;
|
||||
request.client_api_key_id = Some(client_api_key_id);
|
||||
Ok(PreparedResponsesRequest {
|
||||
request,
|
||||
requested_model,
|
||||
})
|
||||
}
|
||||
|
||||
async fn validated_responses_model(
|
||||
state: &AppState,
|
||||
raw_model: &str,
|
||||
) -> Result<String, ResponsesModelValidationError> {
|
||||
) -> Result<String, ResponsesRequestValidationError> {
|
||||
let model = raw_model.trim();
|
||||
if model.is_empty() {
|
||||
return Err(ResponsesModelValidationError::InvalidRequest);
|
||||
return Err(ResponsesRequestValidationError::InvalidRequest);
|
||||
}
|
||||
let catalog = model_catalog_for_state(state).await;
|
||||
if catalog.is_recognized_model_name(model) {
|
||||
if catalog.is_empty() || catalog.is_recognized_model_name(model) {
|
||||
Ok(model.to_string())
|
||||
} else {
|
||||
Err(ResponsesModelValidationError::ModelNotFound)
|
||||
Err(ResponsesRequestValidationError::ModelNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
enum ResponsesModelValidationError {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum ResponsesRequestValidationError {
|
||||
InvalidRequest,
|
||||
ModelNotFound,
|
||||
}
|
||||
@@ -449,15 +385,11 @@ pub(crate) fn user_agent_from_headers(headers: &HeaderMap) -> Option<String> {
|
||||
}
|
||||
|
||||
fn openai_subagent_from_headers(headers: &HeaderMap) -> Option<String> {
|
||||
header_string(headers, OPENAI_SUBAGENT_HEADER).and_then(|value| {
|
||||
if matches!(
|
||||
header_string(headers, OPENAI_SUBAGENT_HEADER).filter(|value| {
|
||||
matches!(
|
||||
value.as_str(),
|
||||
"review" | "compact" | "memory_consolidation" | "collab_spawn"
|
||||
) {
|
||||
Some(value)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5,15 +5,15 @@
|
||||
use axum::{
|
||||
body::Body,
|
||||
http::{
|
||||
header::{CACHE_CONTROL, CONTENT_TYPE},
|
||||
StatusCode,
|
||||
header::{CACHE_CONTROL, CONTENT_TYPE},
|
||||
},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
|
||||
use crate::upstream::openai::protocol::sse::DONE_SSE_FRAME;
|
||||
|
||||
use super::errors::openai_error_response;
|
||||
use crate::api::client::errors::openai_error_response;
|
||||
|
||||
/// 编码 OpenAI 流结束标记。
|
||||
pub fn done_sse_frame() -> &'static str {
|
||||
@@ -0,0 +1,567 @@
|
||||
//! 官方 Responses WebSocket 入站协议。
|
||||
|
||||
use axum::{
|
||||
body::Body,
|
||||
extract::{Request, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use hyper::upgrade::Upgraded;
|
||||
use hyper_util::rt::TokioIo;
|
||||
use serde_json::{Map, Value, json};
|
||||
use thiserror::Error;
|
||||
use tokio_tungstenite::{
|
||||
WebSocketStream,
|
||||
tungstenite::{
|
||||
Error as WebSocketError, Message,
|
||||
handshake::server::create_response_with_body,
|
||||
protocol::{CloseFrame, Role, WebSocketConfig, frame::coding::CloseCode},
|
||||
},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
api::{AppState, middleware::request_id::RequestId},
|
||||
dispatch::{
|
||||
service::{ConnectionTranscriptFacts, ResponseDispatchStream},
|
||||
transport::canonical::CanonicalResponseEvent,
|
||||
},
|
||||
upstream::openai::protocol::websocket::is_terminal_websocket_event,
|
||||
};
|
||||
|
||||
use super::{PreparedResponsesRequest, ResponsesRequestValidationError, prepare_responses_request};
|
||||
use crate::api::client::{
|
||||
auth::authorized_client_api_key_id,
|
||||
errors::{
|
||||
missing_client_api_key_response, openai_error_response,
|
||||
responses_websocket_dispatch_error_event, responses_websocket_error_event,
|
||||
},
|
||||
router::MAX_CLIENT_REQUEST_BODY_BYTES,
|
||||
};
|
||||
|
||||
const RESPONSES_ROUTE: &str = "/v1/responses";
|
||||
const INVALID_REQUEST_MESSAGE: &str = "Invalid responses request";
|
||||
const MODEL_NOT_FOUND_MESSAGE: &str = "Model not found";
|
||||
const INVALID_STREAM_MESSAGE: &str = "Responses WebSocket requests require stream=true";
|
||||
const INVALID_UPSTREAM_EVENT_MESSAGE: &str = "Invalid upstream Responses event";
|
||||
const STREAM_DISCONNECTED_MESSAGE: &str = "Upstream stream closed before response.completed";
|
||||
|
||||
type ResponsesWebSocket = WebSocketStream<TokioIo<Upgraded>>;
|
||||
|
||||
/// 将已认证的 `GET /v1/responses` 请求升级为官方 Responses WebSocket 协议。
|
||||
pub async fn responses_websocket(State(state): State<AppState>, mut request: Request) -> Response {
|
||||
let headers = request.headers().clone();
|
||||
let Some(client_api_key_id) = authorized_client_api_key_id(&state, &headers).await else {
|
||||
return missing_client_api_key_response().into_response();
|
||||
};
|
||||
let connection_request_id = request
|
||||
.extensions()
|
||||
.get::<RequestId>()
|
||||
.cloned()
|
||||
.unwrap_or_else(RequestId::generate);
|
||||
let client_ip = request
|
||||
.extensions()
|
||||
.get::<crate::api::middleware::request_id::ClientIp>()
|
||||
.map(|client_ip| client_ip.as_str().to_string());
|
||||
let connection_id = connection_request_id.as_str().to_string();
|
||||
let response = match create_response_with_body(&request, Body::empty) {
|
||||
Ok(response) => response,
|
||||
Err(error) => {
|
||||
tracing::info!(
|
||||
websocket_connection_id = %connection_id,
|
||||
error = %error,
|
||||
"Invalid Responses WebSocket upgrade request"
|
||||
);
|
||||
return openai_error_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Invalid Responses WebSocket upgrade request",
|
||||
"invalid_request_error",
|
||||
"invalid_websocket_upgrade",
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
let upgrade = hyper::upgrade::on(&mut request);
|
||||
let connection_drain = state.services.connection_drain.clone();
|
||||
connection_drain.spawn(async move {
|
||||
match upgrade.await {
|
||||
Ok(upgraded) => {
|
||||
let socket = WebSocketStream::from_raw_socket(
|
||||
TokioIo::new(upgraded),
|
||||
Role::Server,
|
||||
Some(downstream_websocket_config()),
|
||||
)
|
||||
.await;
|
||||
serve_responses_websocket(
|
||||
socket,
|
||||
ResponsesWebSocketSession {
|
||||
state,
|
||||
headers,
|
||||
client_ip,
|
||||
client_api_key_id,
|
||||
connection_id,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
websocket_connection_id = %connection_id,
|
||||
error = %error,
|
||||
"Responses WebSocket upgrade failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
response
|
||||
}
|
||||
|
||||
fn downstream_websocket_config() -> WebSocketConfig {
|
||||
let mut config = WebSocketConfig::default();
|
||||
config.max_message_size = Some(MAX_CLIENT_REQUEST_BODY_BYTES);
|
||||
config.max_frame_size = Some(MAX_CLIENT_REQUEST_BODY_BYTES);
|
||||
config
|
||||
}
|
||||
|
||||
struct ResponsesWebSocketSession {
|
||||
state: AppState,
|
||||
headers: HeaderMap,
|
||||
client_ip: Option<String>,
|
||||
client_api_key_id: String,
|
||||
connection_id: String,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ConnectionTranscriptCollector {
|
||||
completed_items: Vec<Value>,
|
||||
completed: Option<ConnectionTranscriptFacts>,
|
||||
}
|
||||
|
||||
enum ForwardDispatchOutcome {
|
||||
Continue(Option<ConnectionTranscriptFacts>),
|
||||
Disconnect,
|
||||
}
|
||||
|
||||
impl ConnectionTranscriptCollector {
|
||||
fn observe(&mut self, event: &CanonicalResponseEvent) {
|
||||
match event.event_type() {
|
||||
Some("response.output_item.done") => {
|
||||
if let Some(item) = event.data().get("item") {
|
||||
self.completed_items.push(item.clone());
|
||||
}
|
||||
}
|
||||
Some("response.completed") => {
|
||||
let Some(response_id) = event
|
||||
.data()
|
||||
.pointer("/response/id")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToString::to_string)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let output = event
|
||||
.data()
|
||||
.pointer("/response/output")
|
||||
.and_then(Value::as_array)
|
||||
.filter(|output| !output.is_empty())
|
||||
.cloned()
|
||||
.unwrap_or_else(|| self.completed_items.clone());
|
||||
self.completed = Some(ConnectionTranscriptFacts::new(response_id, output));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve_responses_websocket(
|
||||
mut socket: ResponsesWebSocket,
|
||||
session: ResponsesWebSocketSession,
|
||||
) {
|
||||
tracing::info!(
|
||||
websocket_connection_id = %session.connection_id,
|
||||
"Responses WebSocket connected"
|
||||
);
|
||||
let mut request_count = 0u64;
|
||||
let mut replay_snapshot = session
|
||||
.state
|
||||
.services
|
||||
.responses
|
||||
.connection_replay_snapshot();
|
||||
|
||||
while let Some(message) = socket.next().await {
|
||||
let payload = match message {
|
||||
Ok(Message::Text(payload)) => payload,
|
||||
Ok(Message::Ping(_) | Message::Pong(_) | Message::Frame(_)) => continue,
|
||||
Ok(Message::Close(_)) => break,
|
||||
Ok(Message::Binary(_)) => {
|
||||
close_for_protocol_violation(
|
||||
&mut socket,
|
||||
"Responses WebSocket accepts 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 request_id = RequestId::generate();
|
||||
let body = match parse_response_create(payload.as_str()) {
|
||||
Ok(body) => body,
|
||||
Err(error) => {
|
||||
tracing::info!(
|
||||
websocket_connection_id = %session.connection_id,
|
||||
request_id = %request_id.as_str(),
|
||||
error = %error,
|
||||
"Responses WebSocket request rejected"
|
||||
);
|
||||
if !send_error(
|
||||
&mut socket,
|
||||
StatusCode::BAD_REQUEST,
|
||||
"invalid_request_error",
|
||||
"invalid_request",
|
||||
&error.to_string(),
|
||||
request_id.as_str(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut prepared = match prepare_responses_request(
|
||||
&session.state,
|
||||
body,
|
||||
&session.headers,
|
||||
None,
|
||||
session.client_ip.clone(),
|
||||
session.client_api_key_id.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(prepared) => prepared,
|
||||
Err(error) => {
|
||||
let (status, code, message) = match error {
|
||||
ResponsesRequestValidationError::InvalidRequest => (
|
||||
StatusCode::BAD_REQUEST,
|
||||
"invalid_request",
|
||||
INVALID_REQUEST_MESSAGE,
|
||||
),
|
||||
ResponsesRequestValidationError::ModelNotFound => (
|
||||
StatusCode::NOT_FOUND,
|
||||
"model_not_found",
|
||||
MODEL_NOT_FOUND_MESSAGE,
|
||||
),
|
||||
};
|
||||
if !send_error(
|
||||
&mut socket,
|
||||
status,
|
||||
"invalid_request_error",
|
||||
code,
|
||||
message,
|
||||
request_id.as_str(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let replay_plan = session
|
||||
.state
|
||||
.services
|
||||
.responses
|
||||
.prepare_connection_replay(&replay_snapshot, &mut prepared.request);
|
||||
|
||||
match dispatch_response_create(&mut socket, &session, request_id, prepared).await {
|
||||
ForwardDispatchOutcome::Continue(Some(transcript)) => {
|
||||
session.state.services.responses.commit_connection_replay(
|
||||
&mut replay_snapshot,
|
||||
replay_plan,
|
||||
transcript,
|
||||
);
|
||||
}
|
||||
ForwardDispatchOutcome::Continue(None) => {}
|
||||
ForwardDispatchOutcome::Disconnect => break,
|
||||
}
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
websocket_connection_id = %session.connection_id,
|
||||
request_count,
|
||||
"Responses WebSocket disconnected"
|
||||
);
|
||||
}
|
||||
|
||||
async fn dispatch_response_create(
|
||||
socket: &mut ResponsesWebSocket,
|
||||
session: &ResponsesWebSocketSession,
|
||||
request_id: RequestId,
|
||||
prepared: PreparedResponsesRequest,
|
||||
) -> ForwardDispatchOutcome {
|
||||
let PreparedResponsesRequest {
|
||||
mut request,
|
||||
requested_model,
|
||||
} = prepared;
|
||||
if !request.force_http_sse {
|
||||
request.use_websocket = true;
|
||||
}
|
||||
let stream = session
|
||||
.state
|
||||
.services
|
||||
.responses
|
||||
.stream(
|
||||
request_id.as_str(),
|
||||
RESPONSES_ROUTE,
|
||||
request,
|
||||
&requested_model,
|
||||
)
|
||||
.await;
|
||||
let stream = match stream {
|
||||
Ok(stream) => stream,
|
||||
Err(error) => {
|
||||
let event = responses_websocket_dispatch_error_event(&error, request_id.as_str());
|
||||
return if send_text(socket, event).await {
|
||||
ForwardDispatchOutcome::Continue(None)
|
||||
} else {
|
||||
ForwardDispatchOutcome::Disconnect
|
||||
};
|
||||
}
|
||||
};
|
||||
forward_dispatch_stream(socket, stream, request_id.as_str()).await
|
||||
}
|
||||
|
||||
async fn forward_dispatch_stream(
|
||||
socket: &mut ResponsesWebSocket,
|
||||
stream: ResponseDispatchStream,
|
||||
request_id: &str,
|
||||
) -> ForwardDispatchOutcome {
|
||||
let ResponseDispatchStream {
|
||||
body,
|
||||
mut canonical_events,
|
||||
response_headers,
|
||||
} = stream;
|
||||
if !send_text(
|
||||
socket,
|
||||
response_metadata_event(request_id, &response_headers),
|
||||
)
|
||||
.await
|
||||
{
|
||||
return ForwardDispatchOutcome::Disconnect;
|
||||
}
|
||||
|
||||
let mut body = body;
|
||||
let mut terminal_sent = false;
|
||||
let mut completed = ConnectionTranscriptCollector::default();
|
||||
loop {
|
||||
let next = if terminal_sent {
|
||||
ActiveResponseInput::Upstream(body.next().await)
|
||||
} else {
|
||||
tokio::select! {
|
||||
next = body.next() => ActiveResponseInput::Upstream(next),
|
||||
message = socket.next() => ActiveResponseInput::Downstream(message),
|
||||
}
|
||||
};
|
||||
match next {
|
||||
ActiveResponseInput::Upstream(Some(Ok(chunk))) => {
|
||||
let Some(events) = canonical_events.recv().await else {
|
||||
tracing::warn!(
|
||||
request_id,
|
||||
"Canonical Responses event stream closed before body stream"
|
||||
);
|
||||
return ForwardDispatchOutcome::Disconnect;
|
||||
};
|
||||
drop(chunk);
|
||||
if !forward_canonical_events(
|
||||
socket,
|
||||
events,
|
||||
request_id,
|
||||
&mut terminal_sent,
|
||||
&mut completed,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return ForwardDispatchOutcome::Disconnect;
|
||||
}
|
||||
}
|
||||
ActiveResponseInput::Upstream(Some(Err(error))) => {
|
||||
tracing::warn!(request_id, error = %error, "Responses dispatch stream failed");
|
||||
if terminal_sent {
|
||||
return ForwardDispatchOutcome::Continue(completed.completed);
|
||||
}
|
||||
return if send_error(
|
||||
socket,
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"server_error",
|
||||
"upstream_error",
|
||||
STREAM_DISCONNECTED_MESSAGE,
|
||||
request_id,
|
||||
)
|
||||
.await
|
||||
{
|
||||
ForwardDispatchOutcome::Continue(None)
|
||||
} else {
|
||||
ForwardDispatchOutcome::Disconnect
|
||||
};
|
||||
}
|
||||
ActiveResponseInput::Upstream(None) => {
|
||||
if terminal_sent {
|
||||
return ForwardDispatchOutcome::Continue(completed.completed);
|
||||
}
|
||||
return if send_error(
|
||||
socket,
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"server_error",
|
||||
"stream_disconnected",
|
||||
STREAM_DISCONNECTED_MESSAGE,
|
||||
request_id,
|
||||
)
|
||||
.await
|
||||
{
|
||||
ForwardDispatchOutcome::Continue(None)
|
||||
} else {
|
||||
ForwardDispatchOutcome::Disconnect
|
||||
};
|
||||
}
|
||||
ActiveResponseInput::Downstream(Some(Ok(
|
||||
Message::Ping(_) | Message::Pong(_) | Message::Frame(_),
|
||||
))) => {}
|
||||
ActiveResponseInput::Downstream(Some(Ok(Message::Close(_))) | None) => {
|
||||
return ForwardDispatchOutcome::Disconnect;
|
||||
}
|
||||
ActiveResponseInput::Downstream(Some(Ok(Message::Text(_) | Message::Binary(_)))) => {
|
||||
close_for_protocol_violation(
|
||||
socket,
|
||||
"Only one response.create may be active per connection",
|
||||
)
|
||||
.await;
|
||||
return ForwardDispatchOutcome::Disconnect;
|
||||
}
|
||||
ActiveResponseInput::Downstream(Some(Err(error))) => {
|
||||
tracing::info!(request_id, error = %error, "Responses WebSocket client disconnected during response");
|
||||
return ForwardDispatchOutcome::Disconnect;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum ActiveResponseInput {
|
||||
Upstream(Option<Result<bytes::Bytes, crate::dispatch::errors::ResponseDispatchStreamError>>),
|
||||
Downstream(Option<Result<Message, WebSocketError>>),
|
||||
}
|
||||
|
||||
async fn forward_canonical_events(
|
||||
socket: &mut ResponsesWebSocket,
|
||||
events: Vec<CanonicalResponseEvent>,
|
||||
request_id: &str,
|
||||
terminal_sent: &mut bool,
|
||||
completed: &mut ConnectionTranscriptCollector,
|
||||
) -> bool {
|
||||
for event in events {
|
||||
let Some(event_type) = event.event_type() else {
|
||||
tracing::warn!(
|
||||
request_id,
|
||||
"Responses SSE event does not contain a valid JSON type"
|
||||
);
|
||||
let _ = send_error(
|
||||
socket,
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"server_error",
|
||||
"invalid_upstream_response",
|
||||
INVALID_UPSTREAM_EVENT_MESSAGE,
|
||||
request_id,
|
||||
)
|
||||
.await;
|
||||
return false;
|
||||
};
|
||||
completed.observe(&event);
|
||||
if !send_text(socket, event.data().to_string()).await {
|
||||
return false;
|
||||
}
|
||||
*terminal_sent |= is_terminal_websocket_event(event_type);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn response_metadata_event(request_id: &str, response_headers: &[(String, String)]) -> String {
|
||||
let mut headers = response_headers
|
||||
.iter()
|
||||
.map(|(name, value)| (name.clone(), Value::String(value.clone())))
|
||||
.collect::<Map<String, Value>>();
|
||||
headers.insert(
|
||||
"x-request-id".to_string(),
|
||||
Value::String(request_id.to_string()),
|
||||
);
|
||||
json!({
|
||||
"type": "response.metadata",
|
||||
"headers": headers,
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn parse_response_create(payload: &str) -> Result<Map<String, Value>, ResponseCreateFrameError> {
|
||||
let Value::Object(mut body) = serde_json::from_str::<Value>(payload)? else {
|
||||
return Err(ResponseCreateFrameError::ExpectedObject);
|
||||
};
|
||||
match body.remove("type") {
|
||||
Some(Value::String(message_type)) if message_type == "response.create" => {}
|
||||
_ => return Err(ResponseCreateFrameError::UnsupportedType),
|
||||
}
|
||||
if body.get("stream").and_then(Value::as_bool) != Some(true) {
|
||||
return Err(ResponseCreateFrameError::StreamingRequired);
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
enum ResponseCreateFrameError {
|
||||
#[error("Invalid response.create JSON: {0}")]
|
||||
InvalidJson(#[from] serde_json::Error),
|
||||
#[error("A response.create payload must be a JSON object")]
|
||||
ExpectedObject,
|
||||
#[error("Unsupported Responses WebSocket message type")]
|
||||
UnsupportedType,
|
||||
#[error("{INVALID_STREAM_MESSAGE}")]
|
||||
StreamingRequired,
|
||||
}
|
||||
|
||||
async fn send_error(
|
||||
socket: &mut ResponsesWebSocket,
|
||||
status: StatusCode,
|
||||
error_type: &str,
|
||||
code: &str,
|
||||
message: &str,
|
||||
request_id: &str,
|
||||
) -> bool {
|
||||
send_text(
|
||||
socket,
|
||||
responses_websocket_error_event(status, error_type, code, message, request_id),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn send_text(socket: &mut ResponsesWebSocket, 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 ResponsesWebSocket, reason: &'static str) {
|
||||
let _ = socket
|
||||
.send(Message::Close(Some(CloseFrame {
|
||||
code: CloseCode::Policy,
|
||||
reason: reason.into(),
|
||||
})))
|
||||
.await;
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
//! OpenAI 兼容 API 路由。
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
extract::DefaultBodyLimit,
|
||||
routing::{get, post},
|
||||
Router,
|
||||
};
|
||||
|
||||
use crate::api::AppState;
|
||||
|
||||
use super::{
|
||||
models::{model_catalog, model_detail, model_info, models},
|
||||
responses::{compact_responses, responses, review_responses},
|
||||
responses::{responses, responses_websocket, review_responses},
|
||||
};
|
||||
|
||||
pub const MAX_CLIENT_REQUEST_BODY_BYTES: usize = 16 * 1024 * 1024;
|
||||
@@ -18,9 +18,8 @@ pub const MAX_CLIENT_REQUEST_BODY_BYTES: usize = 16 * 1024 * 1024;
|
||||
/// 构造 OpenAI 兼容 API 路由。
|
||||
pub fn router() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/v1/responses", post(responses))
|
||||
.route("/v1/responses", get(responses_websocket).post(responses))
|
||||
.route("/v1/responses/review", post(review_responses))
|
||||
.route("/v1/responses/compact", post(compact_responses))
|
||||
.route("/v1/models", get(models))
|
||||
.route("/v1/models/catalog", get(model_catalog))
|
||||
.route("/v1/models/{model_id}", get(model_detail))
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
//! 进程关闭时统一排空入站 HTTP 流与 WebSocket 任务。
|
||||
|
||||
use std::future::Future;
|
||||
|
||||
use axum::{
|
||||
body::Body,
|
||||
extract::{Request, State},
|
||||
middleware::Next,
|
||||
response::Response,
|
||||
};
|
||||
use futures::StreamExt;
|
||||
use tokio_util::{sync::CancellationToken, task::TaskTracker};
|
||||
|
||||
/// 入站连接排空控制器。
|
||||
#[derive(Clone)]
|
||||
pub struct ConnectionDrain {
|
||||
cancellation: CancellationToken,
|
||||
connection_tasks: TaskTracker,
|
||||
}
|
||||
|
||||
impl Default for ConnectionDrain {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
cancellation: CancellationToken::new(),
|
||||
connection_tasks: TaskTracker::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectionDrain {
|
||||
/// 为下层长生命周期执行器提供与连接排空一致的取消信号。
|
||||
pub(crate) fn cancellation_token(&self) -> CancellationToken {
|
||||
self.cancellation.clone()
|
||||
}
|
||||
|
||||
/// 注册需要随进程关闭而终止的长连接任务。
|
||||
pub fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {
|
||||
let cancellation = self.cancellation.clone();
|
||||
drop(self.connection_tasks.spawn(async move {
|
||||
cancellation.run_until_cancelled(future).await;
|
||||
}));
|
||||
}
|
||||
|
||||
/// 停止所有受管连接,并返回关闭前仍在运行的长连接任务数。
|
||||
pub fn begin_shutdown(&self) -> usize {
|
||||
let active_websocket_connections = self.connection_tasks.len();
|
||||
self.connection_tasks.close();
|
||||
self.cancellation.cancel();
|
||||
active_websocket_connections
|
||||
}
|
||||
|
||||
/// 等待所有受管长连接任务退出。
|
||||
pub async fn wait(&self) {
|
||||
self.connection_tasks.wait().await;
|
||||
}
|
||||
|
||||
/// 是否已进入连接排空阶段。
|
||||
pub fn is_shutting_down(&self) -> bool {
|
||||
self.cancellation.is_cancelled()
|
||||
}
|
||||
}
|
||||
|
||||
/// 将所有 HTTP 响应体接入统一关闭信号。
|
||||
pub async fn drain_response_body(
|
||||
State(connection_drain): State<ConnectionDrain>,
|
||||
request: Request,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
let response = next.run(request).await;
|
||||
let (parts, body) = response.into_parts();
|
||||
let shutdown = connection_drain.cancellation.clone().cancelled_owned();
|
||||
let body = Body::from_stream(body.into_data_stream().take_until(shutdown));
|
||||
Response::from_parts(parts, body)
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! HTTP 中间件 —— 请求 ID 与 Tracing。
|
||||
//! HTTP 中间件 —— 连接排空、请求 ID 与 Tracing。
|
||||
|
||||
pub mod connection_drain;
|
||||
pub mod request_id;
|
||||
pub mod trace;
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use axum::{
|
||||
extract::{connect_info::ConnectInfo, Request},
|
||||
extract::{Request, connect_info::ConnectInfo},
|
||||
http::{HeaderMap, HeaderValue},
|
||||
middleware::Next,
|
||||
response::Response,
|
||||
|
||||
@@ -10,7 +10,7 @@ use tower_http::{
|
||||
classify::{ServerErrorsAsFailures, ServerErrorsFailureClass, SharedClassifier},
|
||||
trace::TraceLayer,
|
||||
};
|
||||
use tracing::{debug, info, warn, Span};
|
||||
use tracing::{Span, debug, info, warn};
|
||||
|
||||
use crate::api::middleware::request_id::{ClientIp, RequestId};
|
||||
|
||||
@@ -48,7 +48,7 @@ fn make_http_span(request: &Request<Body>) -> Span {
|
||||
}
|
||||
|
||||
fn on_http_request(_request: &Request<Body>, _span: &Span) {
|
||||
debug!("received HTTP request");
|
||||
debug!("Received HTTP request");
|
||||
}
|
||||
|
||||
fn on_http_response(response: &Response<Body>, latency: Duration, _span: &Span) {
|
||||
@@ -58,7 +58,7 @@ fn on_http_response(response: &Response<Body>, latency: Duration, _span: &Span)
|
||||
info!(
|
||||
status = response.status().as_u16(),
|
||||
latency_ms = latency.as_millis(),
|
||||
"completed HTTP request"
|
||||
"Completed HTTP request"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ fn on_http_failure(failure_class: ServerErrorsFailureClass, latency: Duration, _
|
||||
warn!(
|
||||
failure = %failure_class,
|
||||
latency_ms = latency.as_millis(),
|
||||
"failed HTTP request"
|
||||
"Failed HTTP request"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::{
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use axum::{extract::State, http::StatusCode, middleware, routing::get, Router};
|
||||
use axum::{Router, extract::State, http::StatusCode, middleware, routing::get};
|
||||
|
||||
use crate::{
|
||||
api::{
|
||||
@@ -26,6 +26,7 @@ use crate::{
|
||||
account_usage::query::AccountUsageQueryService, ops::query::OpsQueryService,
|
||||
usage::query::UsageQueryService,
|
||||
},
|
||||
update::service::SystemUpdateService,
|
||||
upstream::openai::{fingerprint::RuntimeFingerprint, token_client::OpenAiTokenClient},
|
||||
};
|
||||
|
||||
@@ -49,13 +50,14 @@ pub struct ApiServices {
|
||||
pub session_affinity: Arc<SessionAffinityService>,
|
||||
pub fingerprint: RuntimeFingerprint,
|
||||
pub process_control: Arc<dyn ProcessControl>,
|
||||
pub system_update: Arc<SystemUpdateService>,
|
||||
pub connection_drain: crate::api::middleware::connection_drain::ConnectionDrain,
|
||||
}
|
||||
|
||||
/// 由 bootstrap 实现的进程生命周期控制端口。
|
||||
pub trait ProcessControl: Send + Sync + 'static {
|
||||
fn request_shutdown(&self);
|
||||
fn request_restart(&self, executable_path: PathBuf);
|
||||
fn subscribe_shutdown(&self) -> tokio::sync::broadcast::Receiver<()>;
|
||||
}
|
||||
|
||||
/// 由 bootstrap 实现的基础设施健康检查端口。
|
||||
@@ -94,7 +96,7 @@ pub fn router_with_assets(dist_dir: impl AsRef<Path>) -> Router<AppState> {
|
||||
|
||||
async fn healthz(State(state): State<AppState>) -> StatusCode {
|
||||
if let Err(error) = state.services.health_probe.check().await {
|
||||
tracing::warn!(error, "health check failed");
|
||||
tracing::warn!(error, "Health check failed");
|
||||
return StatusCode::SERVICE_UNAVAILABLE;
|
||||
}
|
||||
StatusCode::NO_CONTENT
|
||||
|
||||
@@ -17,6 +17,7 @@ use super::{
|
||||
const LOGIN_FAILURE_WINDOW: Duration = Duration::minutes(15);
|
||||
const LOGIN_LOCK_DURATION: Duration = Duration::minutes(15);
|
||||
const LOGIN_MAX_FAILURES: u32 = 5;
|
||||
const LOGIN_FAILURE_SOURCE_LIMIT: usize = 10_000;
|
||||
|
||||
/// 管理员会话服务。
|
||||
#[derive(Clone)]
|
||||
@@ -134,6 +135,9 @@ impl SessionService {
|
||||
let login_locked = {
|
||||
let mut failures = self.login_failures.lock().await;
|
||||
retain_active_login_failures(&mut failures, now);
|
||||
if !failures.contains_key(source) && failures.len() >= LOGIN_FAILURE_SOURCE_LIMIT {
|
||||
return Err(SessionError::LoginThrottled);
|
||||
}
|
||||
failures
|
||||
.get(source)
|
||||
.and_then(|state| state.locked_until)
|
||||
|
||||
+512
-275
@@ -1,9 +1,23 @@
|
||||
use std::{collections::BTreeMap, env, path::Path};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashSet},
|
||||
env,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use axum::http::HeaderName;
|
||||
use secrecy::{ExposeSecret, SecretBox};
|
||||
use serde::{Deserialize, de::IgnoredAny};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use url::Url;
|
||||
|
||||
const CONFIG_SCHEMA_VERSION: u32 = 1;
|
||||
const CONFIG_RELATIVE_PATH: &str = "deploy/config.yaml";
|
||||
const SERVER_HOST_ENV: &str = "CPR_SERVER_HOST";
|
||||
const SERVER_PORT_ENV: &str = "CPR_SERVER_PORT";
|
||||
const DATABASE_URL_ENV: &str = "CPR_DATABASE_URL";
|
||||
const REDIS_URL_ENV: &str = "CPR_REDIS_URL";
|
||||
const SERVICE_PASSWORD_HEX_LENGTH: usize = 48;
|
||||
|
||||
const WEAK_ADMIN_PASSWORDS: &[&str] = &[
|
||||
"",
|
||||
"admin",
|
||||
@@ -15,49 +29,230 @@ const WEAK_ADMIN_PASSWORDS: &[&str] = &[
|
||||
"codex-proxy-rs",
|
||||
];
|
||||
|
||||
/// 应用运行总配置。
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
type SecretValue = SecretBox<String>;
|
||||
|
||||
/// 已加载并完成校验的启动配置。
|
||||
///
|
||||
/// 数据库、Redis 和管理员初始化密码只在启动阶段保留,并在释放时清零。
|
||||
#[derive(Debug)]
|
||||
pub struct BootstrapConfig {
|
||||
app: AppConfig,
|
||||
database_url: SecretValue,
|
||||
redis_url: SecretValue,
|
||||
admin_default_password: SecretValue,
|
||||
}
|
||||
|
||||
impl BootstrapConfig {
|
||||
/// 从当前目录或父目录中的 `deploy/config.yaml` 加载配置。
|
||||
pub fn load() -> Result<Self, ConfigError> {
|
||||
let current_directory = env::current_dir().map_err(|_| ConfigError::CurrentDirectory)?;
|
||||
let config_path = discover_config_path(¤t_directory)?;
|
||||
let overrides = TopologyOverrides::from_environment()?;
|
||||
Self::load_from_path_with_overrides(config_path, overrides)
|
||||
}
|
||||
|
||||
/// 从指定 YAML 文件加载配置,不应用容器拓扑覆盖。
|
||||
pub fn load_from_path(config_path: impl AsRef<Path>) -> Result<Self, ConfigError> {
|
||||
Self::load_from_path_with_overrides(config_path, TopologyOverrides::default())
|
||||
}
|
||||
|
||||
/// 从指定 YAML 文件加载配置,并应用明确的容器拓扑覆盖。
|
||||
pub fn load_from_path_with_overrides(
|
||||
config_path: impl AsRef<Path>,
|
||||
overrides: TopologyOverrides,
|
||||
) -> Result<Self, ConfigError> {
|
||||
let config_path = absolute_path(config_path.as_ref())?;
|
||||
let config_directory = config_path.parent().ok_or(ConfigError::InvalidConfigPath)?;
|
||||
|
||||
let document: ConfigDocument = ::config::Config::builder()
|
||||
.add_source(::config::File::from(config_path.as_path()).required(true))
|
||||
.build()
|
||||
.and_then(::config::Config::try_deserialize)
|
||||
.map_err(|_| ConfigError::InvalidDocument {
|
||||
path: config_path.clone(),
|
||||
})?;
|
||||
|
||||
let ConfigDocument {
|
||||
cpr: mut file_config,
|
||||
_services: _,
|
||||
} = document;
|
||||
if file_config.schema_version != CONFIG_SCHEMA_VERSION {
|
||||
return Err(ConfigError::UnsupportedSchemaVersion);
|
||||
}
|
||||
|
||||
overrides.apply(&mut file_config);
|
||||
validate_file_config(&file_config)?;
|
||||
|
||||
resolve_relative_path(config_directory, &mut file_config.runtime.data_directory);
|
||||
resolve_relative_path(config_directory, &mut file_config.logging.file.directory);
|
||||
|
||||
let database_url = connection_url_with_password(
|
||||
&file_config.database.url,
|
||||
&file_config.database.password,
|
||||
"database.url",
|
||||
)?;
|
||||
let redis_url = connection_url_with_password(
|
||||
&file_config.redis.url,
|
||||
&file_config.redis.password,
|
||||
"redis.url",
|
||||
)?;
|
||||
|
||||
let FileAppConfig {
|
||||
schema_version: _,
|
||||
server,
|
||||
api,
|
||||
database,
|
||||
redis,
|
||||
runtime,
|
||||
quota,
|
||||
ws_pool,
|
||||
fingerprint,
|
||||
admin,
|
||||
logging,
|
||||
telemetry,
|
||||
} = file_config;
|
||||
|
||||
let app = AppConfig {
|
||||
server,
|
||||
api,
|
||||
model_aliases: BTreeMap::new(),
|
||||
auth: AuthConfig::default(),
|
||||
quota,
|
||||
database: DatabaseConfig { url: database.url },
|
||||
redis: RedisConfig { url: redis.url },
|
||||
runtime,
|
||||
ws_pool,
|
||||
fingerprint,
|
||||
admin: AdminConfig {
|
||||
session_ttl_minutes: admin.session_ttl_minutes,
|
||||
default_username: admin.default_username,
|
||||
},
|
||||
logging,
|
||||
telemetry,
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
app,
|
||||
database_url,
|
||||
redis_url,
|
||||
admin_default_password: admin.default_password,
|
||||
})
|
||||
}
|
||||
|
||||
/// 返回不包含启动密码的应用运行配置。
|
||||
pub fn app(&self) -> &AppConfig {
|
||||
&self.app
|
||||
}
|
||||
|
||||
/// 返回已安全注入密码的 PostgreSQL 连接地址。
|
||||
pub fn database_url(&self) -> &str {
|
||||
self.database_url.expose_secret()
|
||||
}
|
||||
|
||||
/// 返回已安全注入密码的 Redis 连接地址。
|
||||
pub fn redis_url(&self) -> &str {
|
||||
self.redis_url.expose_secret()
|
||||
}
|
||||
|
||||
pub(crate) fn into_parts(self) -> BootstrapConfigParts {
|
||||
BootstrapConfigParts {
|
||||
app: self.app,
|
||||
database_url: self.database_url,
|
||||
redis_url: self.redis_url,
|
||||
admin_default_password: self.admin_default_password,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct BootstrapConfigParts {
|
||||
pub(crate) app: AppConfig,
|
||||
pub(crate) database_url: SecretValue,
|
||||
pub(crate) redis_url: SecretValue,
|
||||
pub(crate) admin_default_password: SecretValue,
|
||||
}
|
||||
|
||||
/// Docker Compose 对容器内部网络拓扑的固定覆盖。
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct TopologyOverrides {
|
||||
/// 容器内监听地址。
|
||||
pub server_host: Option<String>,
|
||||
/// 容器内监听端口。
|
||||
pub server_port: Option<u16>,
|
||||
/// 容器内 PostgreSQL 地址,不包含密码。
|
||||
pub database_url: Option<String>,
|
||||
/// 容器内 Redis 地址,不包含密码。
|
||||
pub redis_url: Option<String>,
|
||||
}
|
||||
|
||||
impl TopologyOverrides {
|
||||
fn from_environment() -> Result<Self, ConfigError> {
|
||||
let server_port = optional_environment_value(SERVER_PORT_ENV)?
|
||||
.map(|value| {
|
||||
value
|
||||
.parse::<u16>()
|
||||
.ok()
|
||||
.filter(|port| *port > 0)
|
||||
.ok_or(ConfigError::InvalidTopologyOverride(SERVER_PORT_ENV))
|
||||
})
|
||||
.transpose()?;
|
||||
|
||||
Ok(Self {
|
||||
server_host: optional_environment_value(SERVER_HOST_ENV)?,
|
||||
server_port,
|
||||
database_url: optional_environment_value(DATABASE_URL_ENV)?,
|
||||
redis_url: optional_environment_value(REDIS_URL_ENV)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn apply(self, config: &mut FileAppConfig) {
|
||||
if let Some(host) = self.server_host {
|
||||
config.server.host = host;
|
||||
}
|
||||
if let Some(port) = self.server_port {
|
||||
config.server.port = port;
|
||||
}
|
||||
if let Some(url) = self.database_url {
|
||||
config.database.url = url;
|
||||
}
|
||||
if let Some(url) = self.redis_url {
|
||||
config.redis.url = url;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 应用运行总配置,不包含任何启动密码。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AppConfig {
|
||||
/// HTTP 服务配置。
|
||||
pub server: ServerConfig,
|
||||
/// API 地址配置。
|
||||
pub api: ApiConfig,
|
||||
/// 运行时模型别名,由数据库设置加载,配置文件不承载该字段。
|
||||
#[serde(skip)]
|
||||
pub model_aliases: BTreeMap<String, String>,
|
||||
/// 认证与刷新配置,由固定默认值和数据库运行时设置承载,配置文件不承载该字段。
|
||||
#[serde(skip)]
|
||||
pub auth: AuthConfig,
|
||||
/// 配额配置。
|
||||
#[serde(default)]
|
||||
pub quota: QuotaConfig,
|
||||
/// 数据库配置。
|
||||
/// PostgreSQL 基础连接地址,不包含密码。
|
||||
pub database: DatabaseConfig,
|
||||
/// Redis 运行态存储配置。
|
||||
/// Redis 基础连接地址,不包含密码。
|
||||
pub redis: RedisConfig,
|
||||
/// TLS 偏好配置。
|
||||
#[serde(default)]
|
||||
pub tls: TlsConfig,
|
||||
/// 本地持久运行目录。
|
||||
pub runtime: RuntimePathsConfig,
|
||||
/// WebSocket 连接池启动设置。
|
||||
#[serde(default)]
|
||||
pub ws_pool: WebSocketPoolSettings,
|
||||
/// 上游请求指纹默认配置。
|
||||
#[serde(default)]
|
||||
pub fingerprint: FingerprintConfig,
|
||||
/// 管理员初始化配置。
|
||||
#[serde(default)]
|
||||
/// 管理员初始化配置,不包含密码。
|
||||
pub admin: AdminConfig,
|
||||
/// 日志配置。
|
||||
#[serde(default)]
|
||||
pub logging: LoggingConfig,
|
||||
/// PostgreSQL 遥测事实记录配置。
|
||||
#[serde(default)]
|
||||
pub telemetry: TelemetryConfig,
|
||||
}
|
||||
|
||||
/// HTTP 监听配置。
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ServerConfig {
|
||||
/// 监听主机。
|
||||
@@ -67,14 +262,15 @@ pub struct ServerConfig {
|
||||
}
|
||||
|
||||
/// 上游 API 地址配置。
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ApiConfig {
|
||||
/// 上游基础 URL。
|
||||
pub base_url: String,
|
||||
}
|
||||
|
||||
/// 认证、轮换与 token 续期配置。
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
pub struct AuthConfig {
|
||||
/// 提前刷新秒数。
|
||||
pub refresh_margin_seconds: u64,
|
||||
@@ -113,58 +309,39 @@ impl Default for AuthConfig {
|
||||
}
|
||||
|
||||
/// 配额刷新与跳过配置。
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct QuotaConfig {
|
||||
/// 配额刷新周期。
|
||||
#[serde(default = "default_quota_refresh_interval_minutes")]
|
||||
pub refresh_interval_minutes: u64,
|
||||
/// 是否跳过已耗尽配额的账号。
|
||||
#[serde(default = "default_skip_exhausted")]
|
||||
pub skip_exhausted: bool,
|
||||
}
|
||||
|
||||
impl Default for QuotaConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
refresh_interval_minutes: default_quota_refresh_interval_minutes(),
|
||||
skip_exhausted: default_skip_exhausted(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_quota_refresh_interval_minutes() -> u64 {
|
||||
5
|
||||
}
|
||||
|
||||
fn default_skip_exhausted() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// 数据库连接配置。
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DatabaseConfig {
|
||||
/// PostgreSQL 连接 URL。
|
||||
/// PostgreSQL 基础连接 URL,不包含密码。
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
/// Redis 连接配置。
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RedisConfig {
|
||||
/// Redis 连接 URL。
|
||||
/// Redis 基础连接 URL,不包含密码。
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
/// TLS/HTTP 协议偏好配置。
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub struct TlsConfig {
|
||||
/// 是否强制 HTTP/1.1。
|
||||
pub force_http11: bool,
|
||||
/// 本地持久运行目录。
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RuntimePathsConfig {
|
||||
/// 持久身份密钥与更新状态目录。
|
||||
pub data_directory: PathBuf,
|
||||
}
|
||||
|
||||
/// WebSocket 连接池启动设置。
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct WebSocketPoolSettings {
|
||||
/// 是否启用连接池。
|
||||
@@ -174,31 +351,11 @@ pub struct WebSocketPoolSettings {
|
||||
/// 单账号最大连接数。
|
||||
pub max_per_account: usize,
|
||||
/// 首个真实输出(首事件)到达前的绝对超时;`0` 表示禁用。
|
||||
///
|
||||
/// 从发出 `response.create` 起算,覆盖建连/发送/上游排队/思考的全程,直到收到
|
||||
/// 首个真实内容帧(`response.created`/`response.in_progress` 等纯生命周期帧不计)。
|
||||
/// 超时判定为连接落到病态上游后端,丢弃并换新连接重试。
|
||||
#[serde(default = "default_ws_initial_event_timeout_ms")]
|
||||
pub initial_event_timeout_ms: u64,
|
||||
}
|
||||
|
||||
fn default_ws_initial_event_timeout_ms() -> u64 {
|
||||
20_000
|
||||
}
|
||||
|
||||
impl Default for WebSocketPoolSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
max_age_ms: 3_300_000,
|
||||
max_per_account: 8,
|
||||
initial_event_timeout_ms: default_ws_initial_event_timeout_ms(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 上游请求指纹默认配置。
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct FingerprintConfig {
|
||||
/// 客户端来源名。
|
||||
@@ -221,53 +378,8 @@ pub struct FingerprintConfig {
|
||||
pub header_order: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for FingerprintConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
originator: "Codex Desktop".to_string(),
|
||||
app_version: "26.519.81530".to_string(),
|
||||
build_number: "3178".to_string(),
|
||||
platform: "darwin".to_string(),
|
||||
arch: "arm64".to_string(),
|
||||
chromium_version: "146".to_string(),
|
||||
user_agent_template: "Codex Desktop/{version} ({platform}; {arch})".to_string(),
|
||||
default_headers: vec![
|
||||
FingerprintHeaderConfig::new("Accept-Encoding", "gzip, deflate, br, zstd"),
|
||||
FingerprintHeaderConfig::new("Accept-Language", "en-US,en;q=0.9"),
|
||||
FingerprintHeaderConfig::new("sec-ch-ua-mobile", "?0"),
|
||||
FingerprintHeaderConfig::new("sec-ch-ua-platform", "\"macOS\""),
|
||||
FingerprintHeaderConfig::new("sec-fetch-site", "same-origin"),
|
||||
FingerprintHeaderConfig::new("sec-fetch-mode", "cors"),
|
||||
FingerprintHeaderConfig::new("sec-fetch-dest", "empty"),
|
||||
],
|
||||
header_order: vec![
|
||||
"authorization".to_string(),
|
||||
"chatgpt-account-id".to_string(),
|
||||
"originator".to_string(),
|
||||
"x-openai-internal-codex-residency".to_string(),
|
||||
"x-client-request-id".to_string(),
|
||||
"x-codex-installation-id".to_string(),
|
||||
"x-codex-turn-state".to_string(),
|
||||
"openai-beta".to_string(),
|
||||
"user-agent".to_string(),
|
||||
"sec-ch-ua".to_string(),
|
||||
"sec-ch-ua-mobile".to_string(),
|
||||
"sec-ch-ua-platform".to_string(),
|
||||
"accept-encoding".to_string(),
|
||||
"accept-language".to_string(),
|
||||
"sec-fetch-site".to_string(),
|
||||
"sec-fetch-mode".to_string(),
|
||||
"sec-fetch-dest".to_string(),
|
||||
"content-type".to_string(),
|
||||
"accept".to_string(),
|
||||
"cookie".to_string(),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 指纹默认请求头配置项。
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct FingerprintHeaderConfig {
|
||||
/// 请求头名称。
|
||||
@@ -276,76 +388,20 @@ pub struct FingerprintHeaderConfig {
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
impl FingerprintHeaderConfig {
|
||||
fn new(name: &str, value: &str) -> Self {
|
||||
Self {
|
||||
name: name.to_string(),
|
||||
value: value.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 管理员初始化与会话配置。
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
/// 管理员初始化与会话配置,不包含初始化密码。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AdminConfig {
|
||||
/// 会话有效期(分钟)。
|
||||
pub session_ttl_minutes: u64,
|
||||
/// 默认管理员用户名(首次启动时创建)
|
||||
#[serde(default = "default_admin_username")]
|
||||
/// 默认管理员用户名(首次启动时创建)。
|
||||
pub default_username: String,
|
||||
/// 默认管理员密码(首次启动时创建)
|
||||
#[serde(default = "default_admin_password")]
|
||||
pub default_password: String,
|
||||
}
|
||||
|
||||
impl Default for AdminConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
session_ttl_minutes: 1440,
|
||||
default_username: default_admin_username(),
|
||||
default_password: default_admin_password(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AdminConfig {
|
||||
/// 校验首次启动创建管理员时使用的默认密码。
|
||||
pub fn validate_default_password(&self) -> Result<(), AdminConfigError> {
|
||||
let password = self.default_password.trim();
|
||||
if password.len() < 12 {
|
||||
return Err(AdminConfigError::WeakDefaultPassword);
|
||||
}
|
||||
if WEAK_ADMIN_PASSWORDS.contains(&password.to_ascii_lowercase().as_str()) {
|
||||
return Err(AdminConfigError::WeakDefaultPassword);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 管理员配置校验错误。
|
||||
#[derive(Debug, Clone, Copy, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum AdminConfigError {
|
||||
/// 默认管理员密码为空、过短或属于常见弱口令。
|
||||
#[error(
|
||||
"admin.default_password must be set to a non-default password with at least 12 characters"
|
||||
)]
|
||||
WeakDefaultPassword,
|
||||
}
|
||||
|
||||
fn default_admin_username() -> String {
|
||||
"admin".to_string()
|
||||
}
|
||||
|
||||
fn default_admin_password() -> String {
|
||||
String::new()
|
||||
}
|
||||
|
||||
/// 应用结构化日志配置。
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct LoggingConfig {
|
||||
/// 默认日志级别;`RUST_LOG` 存在时优先使用环境变量。
|
||||
/// 默认日志级别;进程 `RUST_LOG` 可作临时覆盖。
|
||||
pub level: String,
|
||||
/// 是否写入标准输出。
|
||||
pub stdout: bool,
|
||||
@@ -353,24 +409,14 @@ pub struct LoggingConfig {
|
||||
pub file: FileLoggingConfig,
|
||||
}
|
||||
|
||||
impl Default for LoggingConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
level: "info".to_string(),
|
||||
stdout: true,
|
||||
file: FileLoggingConfig::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 应用结构化文件日志配置。
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct FileLoggingConfig {
|
||||
/// 是否写入轮转文件。
|
||||
pub enabled: bool,
|
||||
/// 日志目录。
|
||||
pub directory: String,
|
||||
pub directory: PathBuf,
|
||||
/// 按中国自然日计算的保留天数。
|
||||
pub retention_days: usize,
|
||||
/// 单文件大小上限,单位 MiB。
|
||||
@@ -379,104 +425,295 @@ pub struct FileLoggingConfig {
|
||||
pub max_files: usize,
|
||||
}
|
||||
|
||||
impl Default for FileLoggingConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
directory: ".runtime/logs".to_string(),
|
||||
retention_days: 14,
|
||||
max_file_size_mb: 20,
|
||||
max_files: 20,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// PostgreSQL 遥测事实记录配置。
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TelemetryConfig {
|
||||
/// 是否记录成功与失败代理事实。
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
impl Default for TelemetryConfig {
|
||||
fn default() -> Self {
|
||||
Self { enabled: true }
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ConfigDocument {
|
||||
#[serde(rename = "x-cpr")]
|
||||
cpr: FileAppConfig,
|
||||
#[serde(rename = "services")]
|
||||
_services: IgnoredAny,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FileAppConfig {
|
||||
schema_version: u32,
|
||||
server: ServerConfig,
|
||||
api: ApiConfig,
|
||||
database: FileDatabaseConfig,
|
||||
redis: FileRedisConfig,
|
||||
runtime: RuntimePathsConfig,
|
||||
quota: QuotaConfig,
|
||||
ws_pool: WebSocketPoolSettings,
|
||||
fingerprint: FingerprintConfig,
|
||||
admin: FileAdminConfig,
|
||||
logging: LoggingConfig,
|
||||
telemetry: TelemetryConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FileDatabaseConfig {
|
||||
url: String,
|
||||
password: SecretValue,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FileRedisConfig {
|
||||
url: String,
|
||||
password: SecretValue,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FileAdminConfig {
|
||||
session_ttl_minutes: u64,
|
||||
default_username: String,
|
||||
default_password: SecretValue,
|
||||
}
|
||||
|
||||
fn discover_config_path(start: &Path) -> Result<PathBuf, ConfigError> {
|
||||
start
|
||||
.ancestors()
|
||||
.map(|directory| directory.join(CONFIG_RELATIVE_PATH))
|
||||
.find(|candidate| candidate.is_file())
|
||||
.ok_or(ConfigError::ConfigFileNotFound)
|
||||
}
|
||||
|
||||
fn absolute_path(path: &Path) -> Result<PathBuf, ConfigError> {
|
||||
if path.is_absolute() {
|
||||
return Ok(path.to_path_buf());
|
||||
}
|
||||
let current_directory = env::current_dir().map_err(|_| ConfigError::CurrentDirectory)?;
|
||||
Ok(current_directory.join(path))
|
||||
}
|
||||
|
||||
fn resolve_relative_path(base: &Path, path: &mut PathBuf) {
|
||||
if path.is_relative() {
|
||||
*path = base.join(&*path);
|
||||
}
|
||||
}
|
||||
|
||||
const CONFIG_FILE_ENV: &str = "CPR_CONFIG_FILE";
|
||||
const ADMIN_DEFAULT_PASSWORD_ENV: &str = "CPR_ADMIN_DEFAULT_PASSWORD";
|
||||
const POSTGRES_PASSWORD_ENV: &str = "CPR_POSTGRES_PASSWORD";
|
||||
const REDIS_PASSWORD_ENV: &str = "CPR_REDIS_PASSWORD";
|
||||
|
||||
impl AppConfig {
|
||||
/// 从 `CPR_CONFIG_FILE` 或当前目录 `config.yaml` 加载配置文件,并应用运行时密码。
|
||||
pub fn load() -> Result<Self, ::config::ConfigError> {
|
||||
let config_file = env::var(CONFIG_FILE_ENV)
|
||||
.ok()
|
||||
.filter(|value| !value.trim().is_empty());
|
||||
match config_file {
|
||||
Some(path) => load_file(path),
|
||||
None => Self::load_from_dir("."),
|
||||
}
|
||||
}
|
||||
|
||||
/// 从指定目录加载配置文件,并应用运行时密码。
|
||||
pub fn load_from_dir(config_dir: impl AsRef<Path>) -> Result<Self, ::config::ConfigError> {
|
||||
load_file(config_dir.as_ref().join("config.yaml"))
|
||||
fn optional_environment_value(name: &'static str) -> Result<Option<String>, ConfigError> {
|
||||
match env::var(name) {
|
||||
Ok(value) if value.trim().is_empty() => Err(ConfigError::InvalidTopologyOverride(name)),
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(env::VarError::NotPresent) => Ok(None),
|
||||
Err(env::VarError::NotUnicode(_)) => Err(ConfigError::InvalidTopologyOverride(name)),
|
||||
}
|
||||
}
|
||||
|
||||
fn load_file(config_file: impl AsRef<Path>) -> Result<AppConfig, ::config::ConfigError> {
|
||||
let mut app_config: AppConfig = ::config::Config::builder()
|
||||
.add_source(::config::File::from(config_file.as_ref()).required(true))
|
||||
.build()?
|
||||
.try_deserialize()?;
|
||||
apply_password_override(
|
||||
&mut app_config.database.url,
|
||||
"database.url",
|
||||
POSTGRES_PASSWORD_ENV,
|
||||
fn validate_file_config(config: &FileAppConfig) -> Result<(), ConfigError> {
|
||||
validate_nonempty("server.host", &config.server.host)?;
|
||||
if config.server.port == 0 {
|
||||
return Err(ConfigError::InvalidField("server.port"));
|
||||
}
|
||||
validate_url(
|
||||
"api.base_url",
|
||||
&config.api.base_url,
|
||||
&["http", "https"],
|
||||
false,
|
||||
)?;
|
||||
apply_password_override(&mut app_config.redis.url, "redis.url", REDIS_PASSWORD_ENV)?;
|
||||
if let Some(password) = password_override(ADMIN_DEFAULT_PASSWORD_ENV)? {
|
||||
app_config.admin.default_password = password;
|
||||
validate_url(
|
||||
"database.url",
|
||||
&config.database.url,
|
||||
&["postgres", "postgresql"],
|
||||
true,
|
||||
)?;
|
||||
validate_url("redis.url", &config.redis.url, &["redis", "rediss"], true)?;
|
||||
validate_service_password("database.password", &config.database.password)?;
|
||||
validate_service_password("redis.password", &config.redis.password)?;
|
||||
validate_admin_password(config.admin.default_password.expose_secret())?;
|
||||
validate_nonempty("admin.default_username", &config.admin.default_username)?;
|
||||
if config.admin.session_ttl_minutes == 0 {
|
||||
return Err(ConfigError::InvalidField("admin.session_ttl_minutes"));
|
||||
}
|
||||
Ok(app_config)
|
||||
}
|
||||
|
||||
fn apply_password_override(
|
||||
raw_url: &mut String,
|
||||
config_key: &str,
|
||||
env_name: &str,
|
||||
) -> Result<(), ::config::ConfigError> {
|
||||
let Some(password) = password_override(env_name)? else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut url = Url::parse(raw_url).map_err(|_| {
|
||||
::config::ConfigError::Message(format!(
|
||||
"{config_key} must be a valid URL when {env_name} is set"
|
||||
))
|
||||
})?;
|
||||
let encoded_password = utf8_percent_encode(&password, NON_ALPHANUMERIC).to_string();
|
||||
url.set_password(Some(&encoded_password)).map_err(|()| {
|
||||
::config::ConfigError::Message(format!(
|
||||
"{config_key} does not support a password override from {env_name}"
|
||||
))
|
||||
})?;
|
||||
*raw_url = url.into();
|
||||
if config.runtime.data_directory.as_os_str().is_empty() {
|
||||
return Err(ConfigError::InvalidField("runtime.data_directory"));
|
||||
}
|
||||
if config.quota.refresh_interval_minutes == 0 {
|
||||
return Err(ConfigError::InvalidField("quota.refresh_interval_minutes"));
|
||||
}
|
||||
if config.ws_pool.max_age_ms == 0 {
|
||||
return Err(ConfigError::InvalidField("ws_pool.max_age_ms"));
|
||||
}
|
||||
if config.ws_pool.max_per_account == 0 {
|
||||
return Err(ConfigError::InvalidField("ws_pool.max_per_account"));
|
||||
}
|
||||
validate_fingerprint(&config.fingerprint)?;
|
||||
validate_logging(&config.logging)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn password_override(env_name: &str) -> Result<Option<String>, ::config::ConfigError> {
|
||||
match env::var(env_name) {
|
||||
Ok(password) if password.is_empty() => Err(::config::ConfigError::Message(format!(
|
||||
"{env_name} must not be empty"
|
||||
))),
|
||||
Ok(password) => Ok(Some(password)),
|
||||
Err(env::VarError::NotPresent) => Ok(None),
|
||||
Err(env::VarError::NotUnicode(_)) => Err(::config::ConfigError::Message(format!(
|
||||
"{env_name} must contain valid UTF-8"
|
||||
))),
|
||||
fn validate_url(
|
||||
field: &'static str,
|
||||
raw_url: &str,
|
||||
allowed_schemes: &[&str],
|
||||
reject_password: bool,
|
||||
) -> Result<(), ConfigError> {
|
||||
let url = Url::parse(raw_url).map_err(|_| ConfigError::InvalidField(field))?;
|
||||
if !allowed_schemes.contains(&url.scheme()) || url.host_str().is_none() {
|
||||
return Err(ConfigError::InvalidField(field));
|
||||
}
|
||||
if reject_password && url.password().is_some() {
|
||||
return Err(ConfigError::PasswordInUrl(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_service_password(
|
||||
field: &'static str,
|
||||
password: &SecretValue,
|
||||
) -> Result<(), ConfigError> {
|
||||
let password = password.expose_secret();
|
||||
if password.len() != SERVICE_PASSWORD_HEX_LENGTH
|
||||
|| !password.bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
{
|
||||
return Err(ConfigError::InvalidServicePassword(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_admin_password(password: &str) -> Result<(), ConfigError> {
|
||||
let password = password.trim();
|
||||
if password.len() < 12
|
||||
|| password.contains('$')
|
||||
|| WEAK_ADMIN_PASSWORDS.contains(&password.to_ascii_lowercase().as_str())
|
||||
{
|
||||
return Err(ConfigError::WeakAdminPassword);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_fingerprint(config: &FingerprintConfig) -> Result<(), ConfigError> {
|
||||
for (field, value) in [
|
||||
("fingerprint.originator", config.originator.as_str()),
|
||||
("fingerprint.app_version", config.app_version.as_str()),
|
||||
("fingerprint.build_number", config.build_number.as_str()),
|
||||
("fingerprint.platform", config.platform.as_str()),
|
||||
("fingerprint.arch", config.arch.as_str()),
|
||||
(
|
||||
"fingerprint.chromium_version",
|
||||
config.chromium_version.as_str(),
|
||||
),
|
||||
(
|
||||
"fingerprint.user_agent_template",
|
||||
config.user_agent_template.as_str(),
|
||||
),
|
||||
] {
|
||||
validate_nonempty(field, value)?;
|
||||
}
|
||||
|
||||
if config.default_headers.is_empty() || config.header_order.is_empty() {
|
||||
return Err(ConfigError::InvalidField("fingerprint"));
|
||||
}
|
||||
|
||||
let mut header_names = HashSet::new();
|
||||
for header in &config.default_headers {
|
||||
let name = header.name.trim().to_ascii_lowercase();
|
||||
if name.is_empty()
|
||||
|| header.value.is_empty()
|
||||
|| HeaderName::from_bytes(name.as_bytes()).is_err()
|
||||
|| !header_names.insert(name)
|
||||
{
|
||||
return Err(ConfigError::InvalidField("fingerprint.default_headers"));
|
||||
}
|
||||
}
|
||||
|
||||
let mut ordered_headers = HashSet::new();
|
||||
for header in &config.header_order {
|
||||
let header = header.trim().to_ascii_lowercase();
|
||||
if header.is_empty()
|
||||
|| HeaderName::from_bytes(header.as_bytes()).is_err()
|
||||
|| !ordered_headers.insert(header)
|
||||
{
|
||||
return Err(ConfigError::InvalidField("fingerprint.header_order"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_logging(config: &LoggingConfig) -> Result<(), ConfigError> {
|
||||
EnvFilter::try_new(&config.level).map_err(|_| ConfigError::InvalidField("logging.level"))?;
|
||||
if !config.stdout && !config.file.enabled {
|
||||
return Err(ConfigError::InvalidField("logging"));
|
||||
}
|
||||
if config.file.directory.as_os_str().is_empty() {
|
||||
return Err(ConfigError::InvalidField("logging.file.directory"));
|
||||
}
|
||||
if config.file.retention_days == 0 {
|
||||
return Err(ConfigError::InvalidField("logging.file.retention_days"));
|
||||
}
|
||||
if config.file.max_file_size_mb == 0 {
|
||||
return Err(ConfigError::InvalidField("logging.file.max_file_size_mb"));
|
||||
}
|
||||
if config.file.max_files == 0 {
|
||||
return Err(ConfigError::InvalidField("logging.file.max_files"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_nonempty(field: &'static str, value: &str) -> Result<(), ConfigError> {
|
||||
if value.trim().is_empty() {
|
||||
return Err(ConfigError::InvalidField(field));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn connection_url_with_password(
|
||||
raw_url: &str,
|
||||
password: &SecretValue,
|
||||
field: &'static str,
|
||||
) -> Result<SecretValue, ConfigError> {
|
||||
let mut url = Url::parse(raw_url).map_err(|_| ConfigError::InvalidField(field))?;
|
||||
url.set_password(Some(password.expose_secret()))
|
||||
.map_err(|()| ConfigError::InvalidField(field))?;
|
||||
Ok(SecretBox::new(Box::new(url.into())))
|
||||
}
|
||||
|
||||
/// 启动配置加载错误。错误文本不会包含配置值或连接地址。
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum ConfigError {
|
||||
/// 无法确定当前工作目录。
|
||||
#[error("failed to determine the current working directory")]
|
||||
CurrentDirectory,
|
||||
/// 从当前目录及父目录找不到配置文件。
|
||||
#[error("deploy/config.yaml was not found in the current directory or its parents")]
|
||||
ConfigFileNotFound,
|
||||
/// 配置路径没有父目录。
|
||||
#[error("configuration file path is invalid")]
|
||||
InvalidConfigPath,
|
||||
/// YAML 无法读取、解析或不符合结构;不透传解析器文本以避免泄露密码。
|
||||
#[error("failed to load configuration file `{path}`; check its permissions and YAML structure")]
|
||||
InvalidDocument {
|
||||
/// 配置文件路径。
|
||||
path: PathBuf,
|
||||
},
|
||||
/// 配置格式版本不受支持。
|
||||
#[error("x-cpr.schema_version must be 1")]
|
||||
UnsupportedSchemaVersion,
|
||||
/// 字段值非法。
|
||||
#[error("configuration field `{0}` is invalid")]
|
||||
InvalidField(&'static str),
|
||||
/// 连接 URL 不允许内嵌密码。
|
||||
#[error("configuration field `{0}` must not contain a password; use its password field")]
|
||||
PasswordInUrl(&'static str),
|
||||
/// PostgreSQL 或 Redis 密码格式非法。
|
||||
#[error("configuration field `{0}` must be exactly 48 hexadecimal characters")]
|
||||
InvalidServicePassword(&'static str),
|
||||
/// 管理员初始化密码非法。
|
||||
#[error("admin.default_password must be strong, at least 12 characters, and contain no `$`")]
|
||||
WeakAdminPassword,
|
||||
/// Compose 拓扑覆盖非法。
|
||||
#[error("container topology override `{0}` is invalid")]
|
||||
InvalidTopologyOverride(&'static str),
|
||||
}
|
||||
|
||||
@@ -1,460 +0,0 @@
|
||||
use futures::TryStreamExt;
|
||||
use sqlx::{types::Json, Postgres, Row, SqlitePool, Transaction};
|
||||
|
||||
use crate::infra::identity::hash_credential;
|
||||
|
||||
use super::{
|
||||
parse_cookie_expiration, parse_json, parse_optional_json, parse_optional_timestamp,
|
||||
parse_timestamp, ImportSqliteError, ImportSqliteReport,
|
||||
};
|
||||
|
||||
pub(super) async fn import_core_tables(
|
||||
source: &SqlitePool,
|
||||
target: &mut Transaction<'_, Postgres>,
|
||||
report: &mut ImportSqliteReport,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
import_admin_users(source, target, report).await?;
|
||||
import_client_api_keys(source, target, report).await?;
|
||||
import_runtime_settings(source, target, report).await?;
|
||||
import_accounts(source, target, report).await?;
|
||||
import_account_usage(source, target, report).await?;
|
||||
import_account_cookies(source, target, report).await?;
|
||||
import_fingerprints(source, target, report).await?;
|
||||
import_fingerprint_history(source, target, report).await
|
||||
}
|
||||
|
||||
async fn import_admin_users(
|
||||
source: &SqlitePool,
|
||||
target: &mut Transaction<'_, Postgres>,
|
||||
report: &mut ImportSqliteReport,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
let mut rows = sqlx::query(
|
||||
"select id, password_hash, created_at, updated_at from admin_users order by id",
|
||||
)
|
||||
.fetch(source);
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
sqlx::query(
|
||||
"insert into admin_users (id, password_hash, created_at, updated_at)
|
||||
values ($1, $2, $3, $4)",
|
||||
)
|
||||
.bind(row.try_get::<String, _>("id")?)
|
||||
.bind(row.try_get::<String, _>("password_hash")?)
|
||||
.bind(parse_timestamp(
|
||||
"admin_users",
|
||||
"created_at",
|
||||
row.try_get("created_at")?,
|
||||
)?)
|
||||
.bind(parse_timestamp(
|
||||
"admin_users",
|
||||
"updated_at",
|
||||
row.try_get("updated_at")?,
|
||||
)?)
|
||||
.execute(&mut **target)
|
||||
.await?;
|
||||
report.add_imported("admin_users");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn import_client_api_keys(
|
||||
source: &SqlitePool,
|
||||
target: &mut Transaction<'_, Postgres>,
|
||||
report: &mut ImportSqliteReport,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
let mut rows = sqlx::query(
|
||||
"select id, name, prefix, key, label, enabled, created_at, last_used_at
|
||||
from client_api_keys order by id",
|
||||
)
|
||||
.fetch(source);
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
sqlx::query(
|
||||
"insert into client_api_keys
|
||||
(id, name, prefix, key, label, enabled, created_at, last_used_at)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8)",
|
||||
)
|
||||
.bind(row.try_get::<String, _>("id")?)
|
||||
.bind(row.try_get::<String, _>("name")?)
|
||||
.bind(row.try_get::<String, _>("prefix")?)
|
||||
.bind(row.try_get::<String, _>("key")?)
|
||||
.bind(row.try_get::<Option<String>, _>("label")?)
|
||||
.bind(row.try_get::<i64, _>("enabled")? == 1)
|
||||
.bind(parse_timestamp(
|
||||
"client_api_keys",
|
||||
"created_at",
|
||||
row.try_get("created_at")?,
|
||||
)?)
|
||||
.bind(parse_optional_timestamp(
|
||||
"client_api_keys",
|
||||
"last_used_at",
|
||||
row.try_get("last_used_at")?,
|
||||
)?)
|
||||
.execute(&mut **target)
|
||||
.await?;
|
||||
report.add_imported("client_api_keys");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn import_runtime_settings(
|
||||
source: &SqlitePool,
|
||||
target: &mut Transaction<'_, Postgres>,
|
||||
report: &mut ImportSqliteReport,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
let mut rows = sqlx::query(
|
||||
"select id, model_aliases_json, refresh_margin_seconds, refresh_concurrency,
|
||||
max_concurrent_per_account, request_interval_ms, rotation_strategy,
|
||||
admin_api_key, updated_at
|
||||
from runtime_settings order by id",
|
||||
)
|
||||
.fetch(source);
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
let aliases: String = row.try_get("model_aliases_json")?;
|
||||
let admin_key = row
|
||||
.try_get::<Option<String>, _>("admin_api_key")?
|
||||
.and_then(|key| (!key.trim().is_empty()).then(|| hash_credential(&key)));
|
||||
sqlx::query(
|
||||
"insert into runtime_settings
|
||||
(id, model_aliases_json, refresh_margin_seconds, refresh_concurrency,
|
||||
max_concurrent_per_account, request_interval_ms, rotation_strategy,
|
||||
admin_api_key_hash, usage_retention_days, ops_error_retention_days,
|
||||
bucket_retention_days, updated_at)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8, 30, 30, 90, $9)",
|
||||
)
|
||||
.bind(row.try_get::<i64, _>("id")?)
|
||||
.bind(Json(parse_json(
|
||||
"runtime_settings",
|
||||
"model_aliases_json",
|
||||
&aliases,
|
||||
)?))
|
||||
.bind(row.try_get::<i64, _>("refresh_margin_seconds")?)
|
||||
.bind(row.try_get::<i64, _>("refresh_concurrency")?)
|
||||
.bind(row.try_get::<i64, _>("max_concurrent_per_account")?)
|
||||
.bind(row.try_get::<i64, _>("request_interval_ms")?)
|
||||
.bind(row.try_get::<String, _>("rotation_strategy")?)
|
||||
.bind(admin_key)
|
||||
.bind(parse_timestamp(
|
||||
"runtime_settings",
|
||||
"updated_at",
|
||||
row.try_get("updated_at")?,
|
||||
)?)
|
||||
.execute(&mut **target)
|
||||
.await?;
|
||||
report.add_imported("runtime_settings");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn import_accounts(
|
||||
source: &SqlitePool,
|
||||
target: &mut Transaction<'_, Postgres>,
|
||||
report: &mut ImportSqliteReport,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
let mut rows = sqlx::query(
|
||||
"select id, email, chatgpt_account_id, chatgpt_user_id, label, plan_type,
|
||||
access_token, refresh_token, access_token_expires_at, next_refresh_at,
|
||||
status, quota_json, quota_fetched_at, quota_limit_reached,
|
||||
quota_verify_required, quota_cooldown_until, cloudflare_cooldown_until,
|
||||
added_at, updated_at
|
||||
from accounts order by id",
|
||||
)
|
||||
.fetch(source);
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
let source_status = row.try_get::<String, _>("status")?;
|
||||
let (status, next_refresh_at) = if source_status == "refreshing" {
|
||||
report.add_normalized("accounts.refreshing_to_expired");
|
||||
("expired", None)
|
||||
} else {
|
||||
(
|
||||
source_status.as_str(),
|
||||
parse_optional_timestamp(
|
||||
"accounts",
|
||||
"next_refresh_at",
|
||||
row.try_get("next_refresh_at")?,
|
||||
)?,
|
||||
)
|
||||
};
|
||||
let quota = parse_optional_json(
|
||||
"accounts",
|
||||
"quota_json",
|
||||
row.try_get::<Option<String>, _>("quota_json")?,
|
||||
)?
|
||||
.map(Json);
|
||||
sqlx::query(
|
||||
"insert into accounts
|
||||
(id, email, chatgpt_account_id, chatgpt_user_id, label, plan_type,
|
||||
access_token, refresh_token, access_token_expires_at, next_refresh_at,
|
||||
status, quota_json, quota_fetched_at, quota_limit_reached,
|
||||
quota_verify_required, quota_cooldown_until, cloudflare_cooldown_until,
|
||||
added_at, updated_at)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13,
|
||||
$14, $15, $16, $17, $18, $19)",
|
||||
)
|
||||
.bind(row.try_get::<String, _>("id")?)
|
||||
.bind(row.try_get::<Option<String>, _>("email")?)
|
||||
.bind(row.try_get::<Option<String>, _>("chatgpt_account_id")?)
|
||||
.bind(row.try_get::<Option<String>, _>("chatgpt_user_id")?)
|
||||
.bind(row.try_get::<Option<String>, _>("label")?)
|
||||
.bind(row.try_get::<Option<String>, _>("plan_type")?)
|
||||
.bind(row.try_get::<String, _>("access_token")?)
|
||||
.bind(row.try_get::<Option<String>, _>("refresh_token")?)
|
||||
.bind(parse_optional_timestamp(
|
||||
"accounts",
|
||||
"access_token_expires_at",
|
||||
row.try_get("access_token_expires_at")?,
|
||||
)?)
|
||||
.bind(next_refresh_at)
|
||||
.bind(status)
|
||||
.bind(quota)
|
||||
.bind(parse_optional_timestamp(
|
||||
"accounts",
|
||||
"quota_fetched_at",
|
||||
row.try_get("quota_fetched_at")?,
|
||||
)?)
|
||||
.bind(row.try_get::<i64, _>("quota_limit_reached")? == 1)
|
||||
.bind(row.try_get::<i64, _>("quota_verify_required")? == 1)
|
||||
.bind(parse_optional_timestamp(
|
||||
"accounts",
|
||||
"quota_cooldown_until",
|
||||
row.try_get("quota_cooldown_until")?,
|
||||
)?)
|
||||
.bind(parse_optional_timestamp(
|
||||
"accounts",
|
||||
"cloudflare_cooldown_until",
|
||||
row.try_get("cloudflare_cooldown_until")?,
|
||||
)?)
|
||||
.bind(parse_timestamp(
|
||||
"accounts",
|
||||
"added_at",
|
||||
row.try_get("added_at")?,
|
||||
)?)
|
||||
.bind(parse_timestamp(
|
||||
"accounts",
|
||||
"updated_at",
|
||||
row.try_get("updated_at")?,
|
||||
)?)
|
||||
.execute(&mut **target)
|
||||
.await?;
|
||||
report.add_imported("accounts");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn import_account_usage(
|
||||
source: &SqlitePool,
|
||||
target: &mut Transaction<'_, Postgres>,
|
||||
report: &mut ImportSqliteReport,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
let mut rows = sqlx::query("select * from account_usage order by account_id").fetch(source);
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
sqlx::query(
|
||||
"insert into account_usage
|
||||
(account_id, request_count, empty_response_count, input_tokens, output_tokens,
|
||||
cached_tokens, reasoning_tokens, total_tokens, image_input_tokens,
|
||||
image_output_tokens, image_request_count, image_request_failed_count,
|
||||
window_request_count, window_input_tokens, window_output_tokens,
|
||||
window_cached_tokens, window_image_input_tokens, window_image_output_tokens,
|
||||
window_image_request_count, window_image_request_failed_count,
|
||||
window_started_at, window_reset_at, limit_window_seconds, last_used_at)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12,
|
||||
$13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24)",
|
||||
)
|
||||
.bind(row.try_get::<String, _>("account_id")?)
|
||||
.bind(row.try_get::<i64, _>("request_count")?)
|
||||
.bind(row.try_get::<i64, _>("empty_response_count")?)
|
||||
.bind(row.try_get::<i64, _>("input_tokens")?)
|
||||
.bind(row.try_get::<i64, _>("output_tokens")?)
|
||||
.bind(row.try_get::<i64, _>("cached_tokens")?)
|
||||
.bind(row.try_get::<i64, _>("reasoning_tokens")?)
|
||||
.bind(row.try_get::<i64, _>("total_tokens")?)
|
||||
.bind(row.try_get::<i64, _>("image_input_tokens")?)
|
||||
.bind(row.try_get::<i64, _>("image_output_tokens")?)
|
||||
.bind(row.try_get::<i64, _>("image_request_count")?)
|
||||
.bind(row.try_get::<i64, _>("image_request_failed_count")?)
|
||||
.bind(row.try_get::<i64, _>("window_request_count")?)
|
||||
.bind(row.try_get::<i64, _>("window_input_tokens")?)
|
||||
.bind(row.try_get::<i64, _>("window_output_tokens")?)
|
||||
.bind(row.try_get::<i64, _>("window_cached_tokens")?)
|
||||
.bind(row.try_get::<i64, _>("window_image_input_tokens")?)
|
||||
.bind(row.try_get::<i64, _>("window_image_output_tokens")?)
|
||||
.bind(row.try_get::<i64, _>("window_image_request_count")?)
|
||||
.bind(row.try_get::<i64, _>("window_image_request_failed_count")?)
|
||||
.bind(parse_optional_timestamp(
|
||||
"account_usage",
|
||||
"window_started_at",
|
||||
row.try_get("window_started_at")?,
|
||||
)?)
|
||||
.bind(parse_optional_timestamp(
|
||||
"account_usage",
|
||||
"window_reset_at",
|
||||
row.try_get("window_reset_at")?,
|
||||
)?)
|
||||
.bind(row.try_get::<Option<i64>, _>("limit_window_seconds")?)
|
||||
.bind(parse_optional_timestamp(
|
||||
"account_usage",
|
||||
"last_used_at",
|
||||
row.try_get("last_used_at")?,
|
||||
)?)
|
||||
.execute(&mut **target)
|
||||
.await?;
|
||||
report.add_imported("account_usage");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn import_account_cookies(
|
||||
source: &SqlitePool,
|
||||
target: &mut Transaction<'_, Postgres>,
|
||||
report: &mut ImportSqliteReport,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
let mut rows = sqlx::query(
|
||||
"select id, account_id, domain, name, value, path, expires_at, updated_at
|
||||
from account_cookies order by id",
|
||||
)
|
||||
.fetch(source);
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
let expires_at = row
|
||||
.try_get::<Option<String>, _>("expires_at")?
|
||||
.and_then(|value| match parse_cookie_expiration(&value) {
|
||||
Some(timestamp) => Some(timestamp),
|
||||
None => {
|
||||
report.add_cookie_expiration_parse_failure();
|
||||
None
|
||||
}
|
||||
});
|
||||
sqlx::query(
|
||||
"insert into account_cookies
|
||||
(id, account_id, domain, name, value, path, expires_at, updated_at)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8)",
|
||||
)
|
||||
.bind(row.try_get::<String, _>("id")?)
|
||||
.bind(row.try_get::<String, _>("account_id")?)
|
||||
.bind(row.try_get::<String, _>("domain")?)
|
||||
.bind(row.try_get::<String, _>("name")?)
|
||||
.bind(row.try_get::<String, _>("value")?)
|
||||
.bind(row.try_get::<String, _>("path")?)
|
||||
.bind(expires_at)
|
||||
.bind(parse_timestamp(
|
||||
"account_cookies",
|
||||
"updated_at",
|
||||
row.try_get("updated_at")?,
|
||||
)?)
|
||||
.execute(&mut **target)
|
||||
.await?;
|
||||
report.add_imported("account_cookies");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn import_fingerprints(
|
||||
source: &SqlitePool,
|
||||
target: &mut Transaction<'_, Postgres>,
|
||||
report: &mut ImportSqliteReport,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
let mut rows = sqlx::query("select * from fingerprints order by id").fetch(source);
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
let default_headers: String = row.try_get("default_headers_json")?;
|
||||
let header_order: String = row.try_get("header_order_json")?;
|
||||
sqlx::query(
|
||||
"insert into fingerprints
|
||||
(id, originator, app_version, build_number, platform, arch, chromium_version,
|
||||
user_agent_template, default_headers_json, header_order_json, source,
|
||||
created_at, updated_at)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)",
|
||||
)
|
||||
.bind(row.try_get::<String, _>("id")?)
|
||||
.bind(row.try_get::<String, _>("originator")?)
|
||||
.bind(row.try_get::<String, _>("app_version")?)
|
||||
.bind(row.try_get::<String, _>("build_number")?)
|
||||
.bind(row.try_get::<String, _>("platform")?)
|
||||
.bind(row.try_get::<String, _>("arch")?)
|
||||
.bind(row.try_get::<String, _>("chromium_version")?)
|
||||
.bind(row.try_get::<String, _>("user_agent_template")?)
|
||||
.bind(Json(parse_json(
|
||||
"fingerprints",
|
||||
"default_headers_json",
|
||||
&default_headers,
|
||||
)?))
|
||||
.bind(Json(parse_json(
|
||||
"fingerprints",
|
||||
"header_order_json",
|
||||
&header_order,
|
||||
)?))
|
||||
.bind(row.try_get::<String, _>("source")?)
|
||||
.bind(parse_timestamp(
|
||||
"fingerprints",
|
||||
"created_at",
|
||||
row.try_get("created_at")?,
|
||||
)?)
|
||||
.bind(parse_timestamp(
|
||||
"fingerprints",
|
||||
"updated_at",
|
||||
row.try_get("updated_at")?,
|
||||
)?)
|
||||
.execute(&mut **target)
|
||||
.await?;
|
||||
report.add_imported("fingerprints");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn import_fingerprint_history(
|
||||
source: &SqlitePool,
|
||||
target: &mut Transaction<'_, Postgres>,
|
||||
report: &mut ImportSqliteReport,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
let mut rows =
|
||||
sqlx::query("select * from fingerprint_update_history order by id").fetch(source);
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
let manifest = parse_optional_json(
|
||||
"fingerprint_update_history",
|
||||
"manifest_json",
|
||||
row.try_get::<Option<String>, _>("manifest_json")?,
|
||||
)?
|
||||
.map(Json);
|
||||
sqlx::query(
|
||||
"insert into fingerprint_update_history
|
||||
(id, current_fingerprint_id, app_version, build_number, chromium_version,
|
||||
source, manifest_json, created_at)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8)",
|
||||
)
|
||||
.bind(row.try_get::<String, _>("id")?)
|
||||
.bind(row.try_get::<String, _>("current_fingerprint_id")?)
|
||||
.bind(row.try_get::<String, _>("app_version")?)
|
||||
.bind(row.try_get::<String, _>("build_number")?)
|
||||
.bind(row.try_get::<Option<String>, _>("chromium_version")?)
|
||||
.bind(row.try_get::<String, _>("source")?)
|
||||
.bind(manifest)
|
||||
.bind(parse_timestamp(
|
||||
"fingerprint_update_history",
|
||||
"created_at",
|
||||
row.try_get("created_at")?,
|
||||
)?)
|
||||
.execute(&mut **target)
|
||||
.await?;
|
||||
report.add_imported("fingerprint_update_history");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn count_discarded_runtime_tables(
|
||||
source: &SqlitePool,
|
||||
report: &mut ImportSqliteReport,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
let (sessions, affinities, leases, snapshots, model_usage): (i64, i64, i64, i64, i64) =
|
||||
sqlx::query_as(
|
||||
"select
|
||||
(select count(*) from admin_sessions),
|
||||
(select count(*) from session_affinities),
|
||||
(select count(*) from account_refresh_leases),
|
||||
(select count(*) from model_plan_snapshots),
|
||||
(select count(*) from account_model_usage)",
|
||||
)
|
||||
.fetch_one(source)
|
||||
.await?;
|
||||
report.add_discarded("admin_sessions", sessions.max(0) as u64);
|
||||
report.add_discarded("session_affinities", affinities.max(0) as u64);
|
||||
report.add_discarded("account_refresh_leases", leases.max(0) as u64);
|
||||
report.add_discarded("model_plan_snapshots", snapshots.max(0) as u64);
|
||||
report.add_discarded("account_model_usage", model_usage.max(0) as u64);
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
//! 一次性 SQLite v3 到 PostgreSQL 终态库导入。
|
||||
|
||||
mod core;
|
||||
mod telemetry;
|
||||
|
||||
use std::{collections::BTreeMap, fmt, path::Path};
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde_json::Value;
|
||||
use sqlx::{
|
||||
sqlite::{SqliteConnectOptions, SqlitePoolOptions},
|
||||
PgPool, Postgres, SqlitePool, Transaction,
|
||||
};
|
||||
use thiserror::Error;
|
||||
|
||||
const SQLITE_SCHEMA_VERSION: i64 = 3;
|
||||
|
||||
/// SQLite 历史库导入结果。
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct ImportSqliteReport {
|
||||
imported: BTreeMap<&'static str, u64>,
|
||||
normalized: BTreeMap<&'static str, u64>,
|
||||
discarded: BTreeMap<&'static str, u64>,
|
||||
cookie_expiration_parse_failures: u64,
|
||||
}
|
||||
|
||||
impl ImportSqliteReport {
|
||||
fn add_imported(&mut self, table: &'static str) {
|
||||
*self.imported.entry(table).or_default() += 1;
|
||||
}
|
||||
|
||||
fn add_discarded(&mut self, reason: &'static str, count: u64) {
|
||||
if count > 0 {
|
||||
*self.discarded.entry(reason).or_default() += count;
|
||||
}
|
||||
}
|
||||
|
||||
fn add_normalized(&mut self, reason: &'static str) {
|
||||
*self.normalized.entry(reason).or_default() += 1;
|
||||
}
|
||||
|
||||
fn add_cookie_expiration_parse_failure(&mut self) {
|
||||
self.cookie_expiration_parse_failures += 1;
|
||||
}
|
||||
|
||||
/// 返回指定目标表导入的行数。
|
||||
pub fn imported_rows(&self, table: &str) -> u64 {
|
||||
self.imported.get(table).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 返回指定原因丢弃的行数。
|
||||
pub fn discarded_rows(&self, reason: &str) -> u64 {
|
||||
self.discarded.get(reason).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 返回指定规则规范化的行数。
|
||||
pub fn normalized_rows(&self, reason: &str) -> u64 {
|
||||
self.normalized.get(reason).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 返回无法解析并降级为会话 Cookie 的过期时间数量。
|
||||
pub fn cookie_expiration_parse_failures(&self) -> u64 {
|
||||
self.cookie_expiration_parse_failures
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ImportSqliteReport {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
writeln!(formatter, "SQLite v3 import completed")?;
|
||||
for (table, count) in &self.imported {
|
||||
writeln!(formatter, " imported {table}: {count}")?;
|
||||
}
|
||||
for (reason, count) in &self.normalized {
|
||||
writeln!(formatter, " normalized {reason}: {count}")?;
|
||||
}
|
||||
for (reason, count) in &self.discarded {
|
||||
writeln!(formatter, " discarded {reason}: {count}")?;
|
||||
}
|
||||
write!(
|
||||
formatter,
|
||||
" cookie expiration parse failures: {}",
|
||||
self.cookie_expiration_parse_failures
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// SQLite 历史库导入错误。
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ImportSqliteError {
|
||||
#[error("database operation failed: {0}")]
|
||||
Database(#[from] sqlx::Error),
|
||||
#[error("unsupported SQLite schema version {actual:?}; expected 3")]
|
||||
UnsupportedSourceVersion { actual: Option<i64> },
|
||||
#[error("target PostgreSQL database is not empty")]
|
||||
TargetNotEmpty,
|
||||
#[error("invalid timestamp in {table}.{column}: {value}")]
|
||||
InvalidTimestamp {
|
||||
table: &'static str,
|
||||
column: &'static str,
|
||||
value: String,
|
||||
},
|
||||
#[error("invalid JSON in {table}.{column}: {source}")]
|
||||
InvalidJson {
|
||||
table: &'static str,
|
||||
column: &'static str,
|
||||
#[source]
|
||||
source: serde_json::Error,
|
||||
},
|
||||
}
|
||||
|
||||
/// 将只读 SQLite v3 历史库一次性导入空的 PostgreSQL 终态库。
|
||||
pub async fn import_sqlite(
|
||||
target: &PgPool,
|
||||
source_path: impl AsRef<Path>,
|
||||
) -> Result<ImportSqliteReport, ImportSqliteError> {
|
||||
let options = SqliteConnectOptions::new()
|
||||
.filename(source_path.as_ref())
|
||||
.read_only(true)
|
||||
.create_if_missing(false);
|
||||
let source = SqlitePoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect_with(options)
|
||||
.await?;
|
||||
validate_source_version(&source).await?;
|
||||
|
||||
let mut transaction = target.begin().await?;
|
||||
reject_nonempty_target(&mut transaction).await?;
|
||||
|
||||
let mut report = ImportSqliteReport::default();
|
||||
core::import_core_tables(&source, &mut transaction, &mut report).await?;
|
||||
telemetry::import_telemetry_tables(&source, &mut transaction, &mut report).await?;
|
||||
core::count_discarded_runtime_tables(&source, &mut report).await?;
|
||||
|
||||
transaction.commit().await?;
|
||||
source.close().await;
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
async fn validate_source_version(source: &SqlitePool) -> Result<(), ImportSqliteError> {
|
||||
let (actual,): (Option<i64>,) = sqlx::query_as("select max(version) from schema_migrations")
|
||||
.fetch_one(source)
|
||||
.await?;
|
||||
if actual != Some(SQLITE_SCHEMA_VERSION) {
|
||||
return Err(ImportSqliteError::UnsupportedSourceVersion { actual });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn reject_nonempty_target(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
let (rows,): (i64,) = sqlx::query_as(
|
||||
"select
|
||||
(select count(*) from admin_users)
|
||||
+ (select count(*) from client_api_keys)
|
||||
+ (select count(*) from runtime_settings)
|
||||
+ (select count(*) from accounts)
|
||||
+ (select count(*) from account_usage)
|
||||
+ (select count(*) from usage_records)
|
||||
+ (select count(*) from ops_error_logs)
|
||||
+ (select count(*) from request_time_buckets)
|
||||
+ (select count(*) from account_cookies)
|
||||
+ (select count(*) from fingerprints)
|
||||
+ (select count(*) from fingerprint_update_history)",
|
||||
)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await?;
|
||||
if rows != 0 {
|
||||
return Err(ImportSqliteError::TargetNotEmpty);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_timestamp(
|
||||
table: &'static str,
|
||||
column: &'static str,
|
||||
value: String,
|
||||
) -> Result<DateTime<Utc>, ImportSqliteError> {
|
||||
DateTime::parse_from_rfc3339(&value)
|
||||
.map(|timestamp| timestamp.with_timezone(&Utc))
|
||||
.map_err(|_| ImportSqliteError::InvalidTimestamp {
|
||||
table,
|
||||
column,
|
||||
value,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_optional_timestamp(
|
||||
table: &'static str,
|
||||
column: &'static str,
|
||||
value: Option<String>,
|
||||
) -> Result<Option<DateTime<Utc>>, ImportSqliteError> {
|
||||
value
|
||||
.map(|value| parse_timestamp(table, column, value))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn parse_cookie_expiration(value: &str) -> Option<DateTime<Utc>> {
|
||||
DateTime::parse_from_rfc3339(value)
|
||||
.or_else(|_| DateTime::parse_from_rfc2822(value))
|
||||
.ok()
|
||||
.map(|timestamp| timestamp.with_timezone(&Utc))
|
||||
}
|
||||
|
||||
fn parse_json(
|
||||
table: &'static str,
|
||||
column: &'static str,
|
||||
value: &str,
|
||||
) -> Result<Value, ImportSqliteError> {
|
||||
serde_json::from_str(value).map_err(|source| ImportSqliteError::InvalidJson {
|
||||
table,
|
||||
column,
|
||||
source,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_optional_json(
|
||||
table: &'static str,
|
||||
column: &'static str,
|
||||
value: Option<String>,
|
||||
) -> Result<Option<Value>, ImportSqliteError> {
|
||||
value
|
||||
.map(|value| parse_json(table, column, &value))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn normalized_dimension(value: Option<String>) -> String {
|
||||
value
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
.unwrap_or_else(|| "__unknown__".to_string())
|
||||
}
|
||||
@@ -1,330 +0,0 @@
|
||||
use futures::TryStreamExt;
|
||||
use serde_json::Value;
|
||||
use sqlx::{types::Json, Postgres, Row, SqlitePool, Transaction};
|
||||
|
||||
use super::{
|
||||
normalized_dimension, parse_json, parse_timestamp, ImportSqliteError, ImportSqliteReport,
|
||||
};
|
||||
|
||||
pub(super) async fn import_telemetry_tables(
|
||||
source: &SqlitePool,
|
||||
target: &mut Transaction<'_, Postgres>,
|
||||
report: &mut ImportSqliteReport,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
import_mixed_usage_records(source, target, report).await?;
|
||||
import_ops_error_logs(source, target, report).await?;
|
||||
import_request_time_buckets(source, target, report).await
|
||||
}
|
||||
|
||||
async fn import_mixed_usage_records(
|
||||
source: &SqlitePool,
|
||||
target: &mut Transaction<'_, Postgres>,
|
||||
report: &mut ImportSqliteReport,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
let mut rows = sqlx::query(
|
||||
"select id, request_id, kind, level, account_id, route, model, status_code,
|
||||
transport, attempt_index, upstream_status_code, failure_class,
|
||||
response_id, upstream_request_id, latency_ms, message, metadata_json,
|
||||
created_at
|
||||
from usage_records order by created_at, id",
|
||||
)
|
||||
.fetch(source);
|
||||
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
let level: String = row.try_get("level")?;
|
||||
let account_id: Option<String> = row.try_get("account_id")?;
|
||||
let model: Option<String> = row.try_get("model")?;
|
||||
let status_code: Option<i64> = row.try_get("status_code")?;
|
||||
let metadata_text: String = row.try_get("metadata_json")?;
|
||||
let metadata = parse_json("usage_records", "metadata_json", &metadata_text)?;
|
||||
|
||||
if level == "error" {
|
||||
insert_usage_error(target, &row, metadata).await?;
|
||||
report.add_imported("ops_error_logs");
|
||||
continue;
|
||||
}
|
||||
|
||||
let valid_account = account_id
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.is_some_and(|value| !value.is_empty());
|
||||
let valid_model = model
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.is_some_and(|value| !value.is_empty());
|
||||
let valid_status = status_code.is_some_and(|status| (200..=399).contains(&status));
|
||||
if !valid_account || !valid_model || !valid_status {
|
||||
report.add_discarded("usage_record_noise", 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
insert_success_record(
|
||||
target,
|
||||
&row,
|
||||
account_id.expect("validated account id"),
|
||||
model.expect("validated model"),
|
||||
status_code.expect("validated status code"),
|
||||
metadata,
|
||||
)
|
||||
.await?;
|
||||
report.add_imported("usage_records");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn insert_success_record(
|
||||
target: &mut Transaction<'_, Postgres>,
|
||||
row: &sqlx::sqlite::SqliteRow,
|
||||
account_id: String,
|
||||
model: String,
|
||||
status_code: i64,
|
||||
mut metadata: Value,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
let requested_model = metadata_string(&metadata, &["requestedModel", "requested_model"]);
|
||||
let upstream_model = metadata_string(&metadata, &["upstreamModel", "upstream_model"]);
|
||||
let service_tier = metadata_string(&metadata, &["serviceTier", "service_tier"]);
|
||||
let first_token_ms = metadata_nonnegative(&metadata, &["firstTokenMs", "first_token_ms"]);
|
||||
let input_tokens = usage_number(&metadata, &["inputTokens", "input_tokens"]);
|
||||
let output_tokens = usage_number(&metadata, &["outputTokens", "output_tokens"]);
|
||||
let cached_tokens = usage_number(&metadata, &["cachedTokens", "cached_tokens"]);
|
||||
let reasoning_tokens = usage_number(&metadata, &["reasoningTokens", "reasoning_tokens"]);
|
||||
strip_promoted_success_fields(&mut metadata);
|
||||
|
||||
sqlx::query(
|
||||
"insert into usage_records
|
||||
(id, request_id, client_api_key_id, kind, route, provider, account_id, model,
|
||||
requested_model, upstream_model, service_tier, status_code, transport,
|
||||
attempt_index, response_id, upstream_request_id, latency_ms, first_token_ms,
|
||||
input_tokens, output_tokens, cached_tokens, reasoning_tokens, message,
|
||||
metadata_json, created_at)
|
||||
values ($1, $2, null, $3, $4, 'openai', $5, $6, $7, $8, $9, $10,
|
||||
$11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23)",
|
||||
)
|
||||
.bind(row.try_get::<String, _>("id")?)
|
||||
.bind(row.try_get::<Option<String>, _>("request_id")?)
|
||||
.bind(row.try_get::<String, _>("kind")?)
|
||||
.bind(row.try_get::<Option<String>, _>("route")?)
|
||||
.bind(account_id)
|
||||
.bind(model)
|
||||
.bind(requested_model)
|
||||
.bind(upstream_model)
|
||||
.bind(service_tier)
|
||||
.bind(status_code as i32)
|
||||
.bind(row.try_get::<Option<String>, _>("transport")?)
|
||||
.bind(row.try_get::<Option<i64>, _>("attempt_index")?)
|
||||
.bind(row.try_get::<Option<String>, _>("response_id")?)
|
||||
.bind(row.try_get::<Option<String>, _>("upstream_request_id")?)
|
||||
.bind(row.try_get::<Option<i64>, _>("latency_ms")?)
|
||||
.bind(first_token_ms)
|
||||
.bind(input_tokens)
|
||||
.bind(output_tokens)
|
||||
.bind(cached_tokens)
|
||||
.bind(reasoning_tokens)
|
||||
.bind(row.try_get::<String, _>("message")?)
|
||||
.bind(Json(metadata))
|
||||
.bind(parse_timestamp(
|
||||
"usage_records",
|
||||
"created_at",
|
||||
row.try_get("created_at")?,
|
||||
)?)
|
||||
.execute(&mut **target)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn insert_usage_error(
|
||||
target: &mut Transaction<'_, Postgres>,
|
||||
row: &sqlx::sqlite::SqliteRow,
|
||||
metadata: Value,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
sqlx::query(
|
||||
"insert into ops_error_logs
|
||||
(id, request_id, client_api_key_id, kind, provider, account_id, route, model,
|
||||
status_code, client_status_code, upstream_status_code, transport, attempt_index,
|
||||
failure_class, response_id, upstream_request_id, latency_ms, message,
|
||||
metadata_json, created_at)
|
||||
values ($1, $2, null, $3, 'openai', $4, $5, $6, $7, null, $8, $9,
|
||||
$10, $11, $12, $13, $14, $15, $16, $17)",
|
||||
)
|
||||
.bind(row.try_get::<String, _>("id")?)
|
||||
.bind(row.try_get::<Option<String>, _>("request_id")?)
|
||||
.bind(row.try_get::<String, _>("kind")?)
|
||||
.bind(row.try_get::<Option<String>, _>("account_id")?)
|
||||
.bind(row.try_get::<Option<String>, _>("route")?)
|
||||
.bind(row.try_get::<Option<String>, _>("model")?)
|
||||
.bind(optional_status(row.try_get("status_code")?))
|
||||
.bind(optional_status(row.try_get("upstream_status_code")?))
|
||||
.bind(row.try_get::<Option<String>, _>("transport")?)
|
||||
.bind(row.try_get::<Option<i64>, _>("attempt_index")?)
|
||||
.bind(row.try_get::<Option<String>, _>("failure_class")?)
|
||||
.bind(row.try_get::<Option<String>, _>("response_id")?)
|
||||
.bind(row.try_get::<Option<String>, _>("upstream_request_id")?)
|
||||
.bind(row.try_get::<Option<i64>, _>("latency_ms")?)
|
||||
.bind(row.try_get::<String, _>("message")?)
|
||||
.bind(Json(metadata))
|
||||
.bind(parse_timestamp(
|
||||
"usage_records",
|
||||
"created_at",
|
||||
row.try_get("created_at")?,
|
||||
)?)
|
||||
.execute(&mut **target)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn import_ops_error_logs(
|
||||
source: &SqlitePool,
|
||||
target: &mut Transaction<'_, Postgres>,
|
||||
report: &mut ImportSqliteReport,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
let mut rows =
|
||||
sqlx::query("select * from ops_error_logs order by created_at, id").fetch(source);
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
let metadata_text: String = row.try_get("metadata_json")?;
|
||||
sqlx::query(
|
||||
"insert into ops_error_logs
|
||||
(id, request_id, client_api_key_id, kind, provider, account_id, route, model,
|
||||
status_code, client_status_code, upstream_status_code, transport, attempt_index,
|
||||
failure_class, response_id, upstream_request_id, latency_ms, message,
|
||||
metadata_json, created_at)
|
||||
values ($1, $2, null, $3, 'openai', $4, $5, $6, $7, $8, $9, $10,
|
||||
$11, $12, $13, $14, $15, $16, $17, $18)",
|
||||
)
|
||||
.bind(row.try_get::<String, _>("id")?)
|
||||
.bind(row.try_get::<Option<String>, _>("request_id")?)
|
||||
.bind(row.try_get::<String, _>("kind")?)
|
||||
.bind(row.try_get::<Option<String>, _>("account_id")?)
|
||||
.bind(row.try_get::<Option<String>, _>("route")?)
|
||||
.bind(row.try_get::<Option<String>, _>("model")?)
|
||||
.bind(optional_status(row.try_get("status_code")?))
|
||||
.bind(optional_status(row.try_get("client_status_code")?))
|
||||
.bind(optional_status(row.try_get("upstream_status_code")?))
|
||||
.bind(row.try_get::<Option<String>, _>("transport")?)
|
||||
.bind(row.try_get::<Option<i64>, _>("attempt_index")?)
|
||||
.bind(row.try_get::<Option<String>, _>("failure_class")?)
|
||||
.bind(row.try_get::<Option<String>, _>("response_id")?)
|
||||
.bind(row.try_get::<Option<String>, _>("upstream_request_id")?)
|
||||
.bind(row.try_get::<Option<i64>, _>("latency_ms")?)
|
||||
.bind(row.try_get::<String, _>("message")?)
|
||||
.bind(Json(parse_json(
|
||||
"ops_error_logs",
|
||||
"metadata_json",
|
||||
&metadata_text,
|
||||
)?))
|
||||
.bind(parse_timestamp(
|
||||
"ops_error_logs",
|
||||
"created_at",
|
||||
row.try_get("created_at")?,
|
||||
)?)
|
||||
.execute(&mut **target)
|
||||
.await?;
|
||||
report.add_imported("ops_error_logs");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn import_request_time_buckets(
|
||||
source: &SqlitePool,
|
||||
target: &mut Transaction<'_, Postgres>,
|
||||
report: &mut ImportSqliteReport,
|
||||
) -> Result<(), ImportSqliteError> {
|
||||
let mut rows =
|
||||
sqlx::query("select * from usage_time_buckets order by bucket_start").fetch(source);
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
let request_count: i64 = row.try_get("request_count")?;
|
||||
let error_count: i64 = row.try_get("error_count")?;
|
||||
let min_latency_ms: i64 = row.try_get("min_latency_ms")?;
|
||||
sqlx::query(
|
||||
"insert into request_time_buckets
|
||||
(bucket_start, provider, account_id, model, service_tier, success_count,
|
||||
error_count, input_tokens, output_tokens, cached_tokens,
|
||||
first_token_latency_sum, first_token_latency_count, latency_sum,
|
||||
latency_count, max_latency_ms, min_latency_ms, updated_at)
|
||||
values ($1, 'openai', $2, $3, $4, $5, $6, $7, $8, $9, $10, $11,
|
||||
$12, $13, $14, $15, $16)",
|
||||
)
|
||||
.bind(parse_timestamp(
|
||||
"usage_time_buckets",
|
||||
"bucket_start",
|
||||
row.try_get("bucket_start")?,
|
||||
)?)
|
||||
.bind(normalized_dimension(row.try_get("account_id")?))
|
||||
.bind(normalized_dimension(row.try_get("model")?))
|
||||
.bind(normalized_dimension(row.try_get("service_tier")?))
|
||||
.bind(request_count.saturating_sub(error_count).max(0))
|
||||
.bind(error_count)
|
||||
.bind(row.try_get::<i64, _>("input_tokens")?)
|
||||
.bind(row.try_get::<i64, _>("output_tokens")?)
|
||||
.bind(row.try_get::<i64, _>("cached_tokens")?)
|
||||
.bind(row.try_get::<i64, _>("first_token_latency_sum")?)
|
||||
.bind(row.try_get::<i64, _>("first_token_latency_count")?)
|
||||
.bind(row.try_get::<i64, _>("latency_sum")?)
|
||||
.bind(row.try_get::<i64, _>("latency_count")?)
|
||||
.bind(row.try_get::<i64, _>("max_latency_ms")?)
|
||||
.bind((min_latency_ms != 0).then_some(min_latency_ms))
|
||||
.bind(parse_timestamp(
|
||||
"usage_time_buckets",
|
||||
"updated_at",
|
||||
row.try_get("updated_at")?,
|
||||
)?)
|
||||
.execute(&mut **target)
|
||||
.await?;
|
||||
report.add_imported("request_time_buckets");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn optional_status(status: Option<i64>) -> Option<i32> {
|
||||
status.and_then(|status| i32::try_from(status).ok())
|
||||
}
|
||||
|
||||
fn metadata_string(metadata: &Value, keys: &[&str]) -> Option<String> {
|
||||
keys.iter().find_map(|key| {
|
||||
metadata
|
||||
.get(*key)
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToString::to_string)
|
||||
})
|
||||
}
|
||||
|
||||
fn metadata_nonnegative(metadata: &Value, keys: &[&str]) -> Option<i64> {
|
||||
keys.iter()
|
||||
.find_map(|key| metadata.get(*key).and_then(Value::as_i64))
|
||||
.filter(|value| *value >= 0)
|
||||
}
|
||||
|
||||
fn usage_number(metadata: &Value, keys: &[&str]) -> Option<i64> {
|
||||
metadata
|
||||
.get("usage")
|
||||
.and_then(|usage| metadata_nonnegative(usage, keys))
|
||||
.or_else(|| metadata_nonnegative(metadata, keys))
|
||||
}
|
||||
|
||||
fn strip_promoted_success_fields(metadata: &mut Value) {
|
||||
let Some(object) = metadata.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
for key in [
|
||||
"usage",
|
||||
"route",
|
||||
"apiKind",
|
||||
"requestedModel",
|
||||
"requested_model",
|
||||
"upstreamModel",
|
||||
"upstream_model",
|
||||
"serviceTier",
|
||||
"service_tier",
|
||||
"statusCode",
|
||||
"transport",
|
||||
"attemptIndex",
|
||||
"responseId",
|
||||
"upstreamRequestId",
|
||||
"openaiRequestId",
|
||||
"firstTokenMs",
|
||||
"first_token_ms",
|
||||
] {
|
||||
object.remove(key);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
//! 进程装配、共享状态与后台任务。
|
||||
|
||||
pub mod config;
|
||||
pub mod import_sqlite;
|
||||
pub mod services;
|
||||
pub mod shutdown;
|
||||
pub mod state;
|
||||
|
||||
@@ -3,13 +3,14 @@
|
||||
use std::{env, error::Error, future::IntoFuture, sync::Arc, time::Duration};
|
||||
|
||||
use axum::Router;
|
||||
use secrecy::ExposeSecret;
|
||||
|
||||
use crate::{
|
||||
auth::{
|
||||
service::SessionService,
|
||||
store::{PgAdminUserStore, RedisAdminSessionStore},
|
||||
},
|
||||
bootstrap::config::AppConfig,
|
||||
bootstrap::config::{AppConfig, BootstrapConfig},
|
||||
dispatch::{
|
||||
affinity::{RedisSessionAffinityStore, SessionAffinityService},
|
||||
service::{ResponseDispatchService, ResponseDispatchServiceParts},
|
||||
@@ -26,7 +27,7 @@ use crate::{
|
||||
infra::{
|
||||
database::connect,
|
||||
identity::AccountPseudonymizer,
|
||||
logging::{init_tracing, LogError, LogGuard, RotationConfig, TracingConfig},
|
||||
logging::{LogError, LogGuard, RotationConfig, TracingConfig, init_tracing},
|
||||
paths::{ensure_data_dir, load_or_create_identity_secret},
|
||||
redis::RedisConnection,
|
||||
},
|
||||
@@ -36,7 +37,7 @@ use crate::{
|
||||
store::{ModelSnapshotStore, RedisModelSnapshotStore},
|
||||
types::ModelConfig,
|
||||
},
|
||||
settings::{service::SettingsService, SettingsSnapshot},
|
||||
settings::{SettingsSnapshot, service::SettingsService},
|
||||
telemetry::{
|
||||
account_usage::query::AccountUsageQueryService,
|
||||
account_usage::store::{AccountUsageStore, PgAccountUsageStore},
|
||||
@@ -45,14 +46,15 @@ use crate::{
|
||||
ops::store::PgOpsErrorLogStore,
|
||||
recorder::Recorder,
|
||||
usage::query::UsageQueryService,
|
||||
usage::store::{PgUsageRecordStore, DEFAULT_USAGE_RECORD_CAPTURE_BODY},
|
||||
usage::store::{DEFAULT_USAGE_RECORD_CAPTURE_BODY, PgUsageRecordStore},
|
||||
},
|
||||
update::service::SystemUpdateService,
|
||||
upstream::openai::{
|
||||
fingerprint::{Fingerprint, PgFingerprintStore, RuntimeFingerprint},
|
||||
token_client::{default_openai_token_client, OpenAiTokenClient, TokenClientConfig},
|
||||
token_client::{OpenAiTokenClient, TokenClientConfig, default_openai_token_client},
|
||||
transport::{
|
||||
build_reqwest_client, tls::CustomCaError, CodexBackendClient, CodexModelCatalogClient,
|
||||
CodexWebSocketPool, CodexWebSocketPoolConfig,
|
||||
CodexBackendClient, CodexModelCatalogClient, CodexWebSocketPool,
|
||||
CodexWebSocketPoolConfig, build_reqwest_client, tls::CustomCaError,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -117,6 +119,8 @@ pub struct Services {
|
||||
pub websocket_pool: Option<Arc<CodexWebSocketPool>>,
|
||||
pub fingerprint: RuntimeFingerprint,
|
||||
pub account_pseudonymizer: Arc<AccountPseudonymizer>,
|
||||
pub system_update: Arc<SystemUpdateService>,
|
||||
pub connection_drain: crate::api::middleware::connection_drain::ConnectionDrain,
|
||||
pub background_tasks: BackgroundTaskStores,
|
||||
pub(crate) account_pool_static: AccountPoolStaticSettings,
|
||||
}
|
||||
@@ -208,7 +212,7 @@ impl Services {
|
||||
let websocket_initial_event_timeout = (config.ws_pool.initial_event_timeout_ms > 0)
|
||||
.then(|| std::time::Duration::from_millis(config.ws_pool.initial_event_timeout_ms));
|
||||
let client = CodexBackendClient::new(
|
||||
build_reqwest_client(config.tls.force_http11)?,
|
||||
build_reqwest_client()?,
|
||||
config.api.base_url.clone(),
|
||||
fingerprint.clone(),
|
||||
)
|
||||
@@ -293,8 +297,10 @@ impl Services {
|
||||
let session_affinity =
|
||||
Arc::new(SessionAffinityService::new(stores.session_affinity.clone()));
|
||||
|
||||
let cloudflare_recovery =
|
||||
crate::dispatch::recovery::cloudflare::CloudflareRecovery::new(stores.cookies.clone());
|
||||
let connection_drain = crate::api::middleware::connection_drain::ConnectionDrain::default();
|
||||
let cloudflare_recovery = crate::dispatch::controllers::cloudflare::CloudflareRecovery::new(
|
||||
stores.cookies.clone(),
|
||||
);
|
||||
let responses = Arc::new(ResponseDispatchService::new(ResponseDispatchServiceParts {
|
||||
account_pool: account_pool.clone(),
|
||||
models: models.clone(),
|
||||
@@ -303,7 +309,9 @@ impl Services {
|
||||
recorder,
|
||||
account_identity,
|
||||
cloudflare: cloudflare_recovery,
|
||||
shutdown: connection_drain.cancellation_token(),
|
||||
}));
|
||||
let system_update = Arc::new(SystemUpdateService::from_env());
|
||||
|
||||
Ok(Self {
|
||||
database,
|
||||
@@ -327,6 +335,8 @@ impl Services {
|
||||
websocket_pool,
|
||||
fingerprint,
|
||||
account_pseudonymizer,
|
||||
system_update,
|
||||
connection_drain,
|
||||
background_tasks: stores,
|
||||
account_pool_static,
|
||||
})
|
||||
@@ -362,6 +372,8 @@ impl From<&Services> for crate::api::router::ApiServices {
|
||||
session_affinity: services.session_affinity.clone(),
|
||||
fingerprint: services.fingerprint.clone(),
|
||||
process_control: Arc::new(crate::bootstrap::shutdown::RuntimeProcessControl),
|
||||
system_update: services.system_update.clone(),
|
||||
connection_drain: services.connection_drain.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -436,15 +448,15 @@ pub fn account_pool_options_from_config(config: &AppConfig) -> AccountPoolOption
|
||||
.pool_options(&settings_snapshot_from_config(config))
|
||||
}
|
||||
|
||||
pub async fn run() -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
pub async fn run(config: BootstrapConfig) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
wait_for_scheduled_restart().await;
|
||||
|
||||
let config = AppConfig::load()?;
|
||||
let host = config.server.host.clone();
|
||||
let port = config.server.port;
|
||||
let log_guard = init_logging(&config)?;
|
||||
let host = config.app().server.host.clone();
|
||||
let port = config.app().server.port;
|
||||
let log_guard = init_logging(config.app())?;
|
||||
let listener = tokio::net::TcpListener::bind((host.as_str(), port)).await?;
|
||||
let (router, task_coordinator) = build_router(config).await?;
|
||||
let (router, task_coordinator, connection_drain) = build_router(config).await?;
|
||||
let mut task_coordinator = Some(task_coordinator);
|
||||
|
||||
let serve_result = {
|
||||
let (graceful_shutdown_tx, graceful_shutdown_rx) = tokio::sync::oneshot::channel();
|
||||
@@ -461,8 +473,28 @@ pub async fn run() -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
result = &mut serve => result,
|
||||
() = crate::bootstrap::shutdown::shutdown_signal() => {
|
||||
let _ = graceful_shutdown_tx.send(());
|
||||
let active_websocket_connections = connection_drain.begin_shutdown();
|
||||
tracing::info!(
|
||||
active_websocket_connections,
|
||||
"正在排空入站连接并关闭运行时任务"
|
||||
);
|
||||
let coordinator = task_coordinator.take();
|
||||
let connection_drain = connection_drain.clone();
|
||||
let runtime_shutdown = async move {
|
||||
let shutdown_tasks = async move {
|
||||
if let Some(coordinator) = coordinator {
|
||||
coordinator.shutdown().await;
|
||||
}
|
||||
};
|
||||
tokio::join!(shutdown_tasks, connection_drain.wait());
|
||||
};
|
||||
let drain_runtime = async {
|
||||
let (serve_result, ()) = tokio::join!(&mut serve, runtime_shutdown);
|
||||
serve_result
|
||||
};
|
||||
tokio::pin!(drain_runtime);
|
||||
tokio::select! {
|
||||
result = &mut serve => result,
|
||||
result = &mut drain_runtime => result,
|
||||
() = tokio::time::sleep(HTTP_DRAIN_TIMEOUT) => {
|
||||
tracing::warn!(
|
||||
timeout_secs = HTTP_DRAIN_TIMEOUT.as_secs(),
|
||||
@@ -471,7 +503,7 @@ pub async fn run() -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
Ok(())
|
||||
}
|
||||
() = crate::bootstrap::shutdown::shutdown_signal() => {
|
||||
tracing::warn!("received a second shutdown signal; cancelling remaining connections");
|
||||
tracing::warn!("Received a second shutdown signal; cancelling remaining connections");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -479,7 +511,14 @@ pub async fn run() -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
}
|
||||
};
|
||||
|
||||
task_coordinator.shutdown().await;
|
||||
if let Some(coordinator) = task_coordinator.take() {
|
||||
let active_websocket_connections = connection_drain.begin_shutdown();
|
||||
tracing::info!(
|
||||
active_websocket_connections,
|
||||
"HTTP 服务已退出,正在关闭其余运行时任务"
|
||||
);
|
||||
tokio::join!(coordinator.shutdown(), connection_drain.wait());
|
||||
}
|
||||
serve_result?;
|
||||
|
||||
if let Some(executable_path) = crate::bootstrap::shutdown::restart_executable_path() {
|
||||
@@ -497,16 +536,26 @@ pub async fn run() -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
const HTTP_DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20);
|
||||
|
||||
async fn build_router(
|
||||
mut config: AppConfig,
|
||||
bootstrap_config: BootstrapConfig,
|
||||
) -> Result<
|
||||
(
|
||||
Router,
|
||||
crate::bootstrap::tasks::coordinator::TaskCoordinator,
|
||||
crate::api::middleware::connection_drain::ConnectionDrain,
|
||||
),
|
||||
Box<dyn Error + Send + Sync>,
|
||||
> {
|
||||
let pool = connect(&config.database.url).await?;
|
||||
let redis = RedisConnection::connect(&config.redis.url, "cpr").await?;
|
||||
let crate::bootstrap::config::BootstrapConfigParts {
|
||||
app: mut config,
|
||||
database_url,
|
||||
redis_url,
|
||||
admin_default_password,
|
||||
} = bootstrap_config.into_parts();
|
||||
|
||||
let pool = connect(database_url.expose_secret()).await?;
|
||||
drop(database_url);
|
||||
let redis = RedisConnection::connect(redis_url.expose_secret(), "cpr").await?;
|
||||
drop(redis_url);
|
||||
let settings =
|
||||
SettingsService::load_or_initialize(settings_snapshot_from_config(&config), &pool).await?;
|
||||
apply_settings_to_config(&mut config, &settings);
|
||||
@@ -529,16 +578,14 @@ async fn build_router(
|
||||
request_buckets: PgRequestBucketStore::new(pool),
|
||||
};
|
||||
|
||||
config.admin.validate_default_password()?;
|
||||
let default_admin_password = config.admin.default_password.clone();
|
||||
let data_dir = ensure_data_dir()?;
|
||||
let data_dir = ensure_data_dir(&config.runtime.data_directory)?;
|
||||
let identity_secret = load_or_create_identity_secret(&data_dir)?;
|
||||
let default_fingerprint = fingerprint_from_config(&config.fingerprint);
|
||||
let runtime_fingerprint = fingerprint_store
|
||||
.ensure_current_seed(&default_fingerprint)
|
||||
.await?;
|
||||
let runtime_fingerprint = RuntimeFingerprint::new(runtime_fingerprint);
|
||||
let runtime_config = crate::bootstrap::state::RuntimeConfig::from(config.clone());
|
||||
let runtime_config = crate::bootstrap::state::RuntimeConfig::from(&config);
|
||||
let services = Services::try_with_identity_secret_and_usage_record_options(
|
||||
&config,
|
||||
stores,
|
||||
@@ -550,8 +597,9 @@ async fn build_router(
|
||||
|
||||
let created_default_admin = services
|
||||
.admin_sessions
|
||||
.ensure_default_admin(&default_admin_password)
|
||||
.ensure_default_admin(admin_default_password.expose_secret())
|
||||
.await?;
|
||||
drop(admin_default_password);
|
||||
tracing::info!(
|
||||
created = created_default_admin,
|
||||
"默认管理员账号已完成初始化检查"
|
||||
@@ -566,11 +614,15 @@ async fn build_router(
|
||||
let task_coordinator =
|
||||
crate::bootstrap::tasks::coordinator::TaskCoordinator::start(&runtime_config, &services);
|
||||
let app_state = crate::api::AppState::from(&services);
|
||||
let connection_drain = services.connection_drain.clone();
|
||||
let router = crate::api::router::router().with_state(app_state).layer(
|
||||
axum::middleware::from_fn_with_state(
|
||||
connection_drain.clone(),
|
||||
crate::api::middleware::connection_drain::drain_response_body,
|
||||
),
|
||||
);
|
||||
|
||||
Ok((
|
||||
crate::api::router::router().with_state(app_state),
|
||||
task_coordinator,
|
||||
))
|
||||
Ok((router, task_coordinator, connection_drain))
|
||||
}
|
||||
|
||||
fn init_logging(config: &AppConfig) -> Result<LogGuard, LogError> {
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
OnceLock,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use tokio::signal;
|
||||
use tokio::sync::broadcast::{self, Receiver};
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
static SHUTDOWN_REQUESTS: OnceLock<broadcast::Sender<()>> = OnceLock::new();
|
||||
static RESTART_REQUESTED: AtomicBool = AtomicBool::new(false);
|
||||
@@ -26,10 +26,6 @@ impl crate::api::router::ProcessControl for RuntimeProcessControl {
|
||||
fn request_restart(&self, executable_path: PathBuf) {
|
||||
request_process_restart(executable_path);
|
||||
}
|
||||
|
||||
fn subscribe_shutdown(&self) -> Receiver<()> {
|
||||
shutdown_subscription()
|
||||
}
|
||||
}
|
||||
|
||||
/// 等待进程关闭信号(Ctrl+C 或 SIGTERM)。
|
||||
@@ -64,11 +60,6 @@ pub fn request_shutdown() {
|
||||
let _ = shutdown_sender().send(());
|
||||
}
|
||||
|
||||
/// 订阅进程关闭请求。
|
||||
pub fn shutdown_subscription() -> Receiver<()> {
|
||||
shutdown_sender().subscribe()
|
||||
}
|
||||
|
||||
/// 请求进程完成优雅关闭后以新二进制替换当前进程。
|
||||
pub fn request_process_restart(executable_path: PathBuf) {
|
||||
let _ = RESTART_EXECUTABLE_PATH.set(executable_path);
|
||||
|
||||
@@ -9,7 +9,6 @@ use crate::{
|
||||
/// 运行时配置镜像(从 AppConfig 衍生)。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RuntimeConfig {
|
||||
pub admin: crate::bootstrap::config::AdminConfig,
|
||||
pub auth: crate::bootstrap::config::AuthConfig,
|
||||
pub quota: crate::bootstrap::config::QuotaConfig,
|
||||
}
|
||||
@@ -40,12 +39,11 @@ impl HealthProbe for RuntimeHealthProbe {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AppConfig> for RuntimeConfig {
|
||||
fn from(config: AppConfig) -> Self {
|
||||
impl From<&AppConfig> for RuntimeConfig {
|
||||
fn from(config: &AppConfig) -> Self {
|
||||
Self {
|
||||
admin: config.admin.clone(),
|
||||
auth: config.auth.clone(),
|
||||
quota: config.quota,
|
||||
quota: config.quota.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use tracing::{debug, info, warn};
|
||||
|
||||
use super::{
|
||||
coordinator::SchedulerHandle,
|
||||
periodic::{spawn_periodic_task, PeriodicTaskConfig, PeriodicTaskRunner},
|
||||
periodic::{PeriodicTaskConfig, PeriodicTaskRunner, spawn_periodic_task},
|
||||
};
|
||||
|
||||
/// 支持按时间清理过期记录的存储。
|
||||
|
||||
@@ -7,8 +7,8 @@ use tokio::task::JoinHandle;
|
||||
use super::{
|
||||
cookie_cleanup::CookieCleanupTask,
|
||||
fingerprint_update::{
|
||||
start_fingerprint_update_task, CODEX_DESKTOP_APPCAST_URL,
|
||||
DEFAULT_EXTRACTED_FINGERPRINT_PATH,
|
||||
CODEX_DESKTOP_APPCAST_URL, DEFAULT_EXTRACTED_FINGERPRINT_PATH,
|
||||
start_fingerprint_update_task,
|
||||
},
|
||||
model_refresh::ModelRefreshTask,
|
||||
quota_refresh::QuotaRefreshTask,
|
||||
|
||||
@@ -5,12 +5,12 @@ use std::path::PathBuf;
|
||||
use tracing::{info, warn};
|
||||
|
||||
use crate::upstream::openai::fingerprint::{
|
||||
PgFingerprintStore, RuntimeFingerprint, UpdateChecker, APPCAST_POLL_INTERVAL,
|
||||
APPCAST_POLL_INTERVAL, PgFingerprintStore, RuntimeFingerprint, UpdateChecker,
|
||||
};
|
||||
|
||||
use super::{
|
||||
coordinator::SchedulerHandle,
|
||||
periodic::{spawn_periodic_task, PeriodicTaskConfig, PeriodicTaskRunner},
|
||||
periodic::{PeriodicTaskConfig, PeriodicTaskRunner, spawn_periodic_task},
|
||||
};
|
||||
|
||||
/// Codex Desktop 官方 appcast 地址。
|
||||
@@ -44,8 +44,8 @@ pub fn start_fingerprint_update_task(
|
||||
},
|
||||
PeriodicTaskConfig::new(
|
||||
APPCAST_POLL_INTERVAL.as_secs(),
|
||||
"fingerprint 后台版本检查器已启动",
|
||||
"fingerprint 后台版本检查器已关闭",
|
||||
"Fingerprint 后台版本检查器已启动",
|
||||
"Fingerprint 后台版本检查器已关闭",
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -68,15 +68,15 @@ impl PeriodicTaskRunner for FingerprintUpdateTask {
|
||||
info!(
|
||||
app_version = %app_version,
|
||||
build_number = %build_number,
|
||||
"fingerprint 运行时版本已更新"
|
||||
"Fingerprint 运行时版本已更新"
|
||||
);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
if first_tick {
|
||||
warn!(error = %error, "fingerprint 首次版本检查失败");
|
||||
warn!(error = %error, "Fingerprint 首次版本检查失败");
|
||||
} else {
|
||||
warn!(error = %error, "fingerprint 定期版本检查失败");
|
||||
warn!(error = %error, "Fingerprint 定期版本检查失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ use crate::models::service::{
|
||||
|
||||
use super::{
|
||||
coordinator::SchedulerHandle,
|
||||
periodic::{spawn_periodic_task, PeriodicTaskConfig, PeriodicTaskRunner, PeriodicTaskStartup},
|
||||
periodic::{PeriodicTaskConfig, PeriodicTaskRunner, PeriodicTaskStartup, spawn_periodic_task},
|
||||
};
|
||||
|
||||
/// 模型刷新任务接线器。
|
||||
|
||||
@@ -19,7 +19,7 @@ use crate::{
|
||||
|
||||
use super::{
|
||||
coordinator::SchedulerHandle,
|
||||
periodic::{spawn_periodic_task, PeriodicTaskConfig, PeriodicTaskRunner},
|
||||
periodic::{PeriodicTaskConfig, PeriodicTaskRunner, spawn_periodic_task},
|
||||
};
|
||||
|
||||
/// 主动配额刷新后台任务。
|
||||
@@ -68,8 +68,8 @@ impl QuotaRefreshTask {
|
||||
pub fn start(self) -> SchedulerHandle {
|
||||
let config = PeriodicTaskConfig::new(
|
||||
self.interval_secs,
|
||||
"quota 刷新任务已启动",
|
||||
"quota 刷新任务已关闭",
|
||||
"Quota 刷新任务已启动",
|
||||
"Quota 刷新任务已关闭",
|
||||
);
|
||||
spawn_periodic_task(self, config)
|
||||
}
|
||||
@@ -96,7 +96,7 @@ impl PeriodicTaskRunner for QuotaRefreshTask {
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
warn!(error = %error, "quota 刷新任务失败");
|
||||
warn!(error = %error, "Quota 刷新任务失败");
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -107,6 +107,6 @@ fn log_refreshed_summary(summary: QuotaRefreshSummary) {
|
||||
info!(
|
||||
refreshed = summary.refreshed,
|
||||
failed = summary.failed,
|
||||
"quota 刷新任务完成"
|
||||
"Quota 刷新任务完成"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ use crate::{
|
||||
|
||||
use super::{
|
||||
coordinator::SchedulerHandle,
|
||||
periodic::{spawn_periodic_task, PeriodicTaskConfig, PeriodicTaskRunner, TaskFuture},
|
||||
periodic::{PeriodicTaskConfig, PeriodicTaskRunner, TaskFuture, spawn_periodic_task},
|
||||
};
|
||||
|
||||
const RETENTION_TRIM_INTERVAL_SECS: u64 = 60 * 60;
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::upstream::openai::token_client::TokenRefresher;
|
||||
|
||||
use super::{
|
||||
coordinator::SchedulerHandle,
|
||||
periodic::{spawn_periodic_task, PeriodicTaskConfig, PeriodicTaskRunner},
|
||||
periodic::{PeriodicTaskConfig, PeriodicTaskRunner, spawn_periodic_task},
|
||||
};
|
||||
|
||||
const DEFAULT_INTERVAL_SECS: u64 = 60;
|
||||
@@ -54,8 +54,8 @@ where
|
||||
pub fn start(self) -> SchedulerHandle {
|
||||
let config = PeriodicTaskConfig::new(
|
||||
self.interval_secs,
|
||||
"token 刷新任务已启动",
|
||||
"token 刷新任务已关闭",
|
||||
"Token 刷新任务已启动",
|
||||
"Token 刷新任务已关闭",
|
||||
);
|
||||
spawn_periodic_task(self, config)
|
||||
}
|
||||
@@ -73,7 +73,7 @@ where
|
||||
scheduled = summary.scheduled,
|
||||
immediate = summary.immediate,
|
||||
replaced = summary.replaced,
|
||||
"token 刷新定时器已调度"
|
||||
"Token 刷新定时器已调度"
|
||||
);
|
||||
}
|
||||
Ok(summary) => {
|
||||
@@ -84,7 +84,7 @@ where
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
warn!(error = %error, "token 刷新定时器调度失败");
|
||||
warn!(error = %error, "Token 刷新定时器调度失败");
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
//! 客户端身份、本地会话索引与账号作用域 wire 身份隔离。
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::{
|
||||
infra::identity::AccountPseudonymizer,
|
||||
upstream::openai::protocol::responses::{CodexCompactRequest, CodexResponsesRequest},
|
||||
upstream::openai::protocol::responses::CodexResponsesRequest,
|
||||
};
|
||||
|
||||
const TURN_STATE_METADATA_KEY: &str = "x-codex-turn-state";
|
||||
const TURN_METADATA_KEY: &str = "x-codex-turn-metadata";
|
||||
|
||||
/// 持久化密钥驱动的账号身份隔离服务。
|
||||
#[derive(Clone)]
|
||||
pub struct AccountIdentityService {
|
||||
@@ -21,25 +26,51 @@ impl std::fmt::Debug for AccountIdentityService {
|
||||
|
||||
/// 单次账号 attempt 的 wire 身份。
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct AccountScopedIdentity {
|
||||
pub prompt_cache_key: Option<String>,
|
||||
pub session_id: Option<String>,
|
||||
pub thread_id: Option<String>,
|
||||
pub client_request_id: String,
|
||||
pub turn_id: Option<String>,
|
||||
pub window_id: Option<String>,
|
||||
pub parent_thread_id: Option<String>,
|
||||
pub(in crate::dispatch) struct AccountScopedIdentity {
|
||||
pub installation_id: String,
|
||||
}
|
||||
|
||||
struct IdentityValues<'a> {
|
||||
prompt_cache_key: Option<&'a str>,
|
||||
session_id: Option<&'a str>,
|
||||
thread_id: Option<&'a str>,
|
||||
client_request_id: Option<&'a str>,
|
||||
turn_id: Option<&'a str>,
|
||||
window_id: Option<&'a str>,
|
||||
parent_thread_id: Option<&'a str>,
|
||||
/// 单个请求内账号绑定 opaque 状态的 owner。
|
||||
pub(in crate::dispatch) struct AccountIdentityScope {
|
||||
turn_state_account_id: Option<String>,
|
||||
}
|
||||
|
||||
impl AccountIdentityScope {
|
||||
pub(in crate::dispatch) fn new(preferred_account_id: Option<String>) -> Self {
|
||||
Self {
|
||||
turn_state_account_id: preferred_account_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn preserves_turn_state(&mut self, account_id: &str, has_turn_state: bool) -> bool {
|
||||
if !has_turn_state {
|
||||
return false;
|
||||
}
|
||||
let owner = self
|
||||
.turn_state_account_id
|
||||
.get_or_insert_with(|| account_id.to_string());
|
||||
owner == account_id
|
||||
}
|
||||
}
|
||||
|
||||
/// 已按当前账号重建 wire 身份、可安全交给上游 transport 的请求。
|
||||
pub(in crate::dispatch) struct AccountScopedRequest {
|
||||
request: CodexResponsesRequest,
|
||||
identity: AccountScopedIdentity,
|
||||
}
|
||||
|
||||
impl AccountScopedRequest {
|
||||
pub(in crate::dispatch) fn request(&self) -> &CodexResponsesRequest {
|
||||
&self.request
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn identity(&self) -> &AccountScopedIdentity {
|
||||
&self.identity
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn into_request(self) -> CodexResponsesRequest {
|
||||
self.request
|
||||
}
|
||||
}
|
||||
|
||||
impl AccountIdentityService {
|
||||
@@ -63,109 +94,183 @@ impl AccountIdentityService {
|
||||
.map(|anchor| format!("lc_{}", self.pseudonym("local-conversation", None, anchor)));
|
||||
}
|
||||
|
||||
pub fn scope(
|
||||
/// 从请求语义为单次账号 attempt 重建完整 wire 身份。
|
||||
pub(in crate::dispatch) fn scope_request(
|
||||
&self,
|
||||
request: &CodexResponsesRequest,
|
||||
scope: &mut AccountIdentityScope,
|
||||
mut request: CodexResponsesRequest,
|
||||
account_id: &str,
|
||||
proxy_request_id: &str,
|
||||
) -> AccountScopedIdentity {
|
||||
self.scope_values(
|
||||
account_id,
|
||||
proxy_request_id,
|
||||
IdentityValues {
|
||||
prompt_cache_key: request.prompt_cache_key(),
|
||||
session_id: request.client_session_id.as_deref(),
|
||||
thread_id: request.client_thread_id.as_deref(),
|
||||
client_request_id: request.client_request_id.as_deref(),
|
||||
turn_id: request.client_turn_id.as_deref(),
|
||||
window_id: request.codex_window_id.as_deref(),
|
||||
parent_thread_id: request.parent_thread_id.as_deref(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn scope_compact(
|
||||
&self,
|
||||
request: &CodexCompactRequest,
|
||||
account_id: &str,
|
||||
proxy_request_id: &str,
|
||||
) -> AccountScopedIdentity {
|
||||
self.scope_values(
|
||||
account_id,
|
||||
proxy_request_id,
|
||||
IdentityValues {
|
||||
prompt_cache_key: request.prompt_cache_key(),
|
||||
session_id: request.client_session_id.as_deref(),
|
||||
thread_id: request.client_thread_id.as_deref(),
|
||||
client_request_id: request.client_request_id.as_deref(),
|
||||
turn_id: request.client_turn_id.as_deref(),
|
||||
window_id: request.client_window_id.as_deref(),
|
||||
parent_thread_id: request.client_parent_thread_id.as_deref(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn scope_auxiliary(
|
||||
&self,
|
||||
account_id: &str,
|
||||
proxy_request_id: &str,
|
||||
) -> AccountScopedIdentity {
|
||||
AccountScopedIdentity {
|
||||
client_request_id: format!(
|
||||
"cr_{}",
|
||||
self.pseudonym("client-request-id", Some(account_id), proxy_request_id)
|
||||
),
|
||||
) -> AccountScopedRequest {
|
||||
let identity = AccountScopedIdentity {
|
||||
installation_id: self.pseudonymizer.installation_id(account_id),
|
||||
..AccountScopedIdentity::default()
|
||||
}
|
||||
};
|
||||
let client_metadata_turn_state = client_metadata_string(&request, TURN_STATE_METADATA_KEY);
|
||||
let preserve_turn_state = scope.preserves_turn_state(
|
||||
account_id,
|
||||
request.turn_state.is_some() || client_metadata_turn_state.is_some(),
|
||||
);
|
||||
let turn_state = if preserve_turn_state {
|
||||
request.turn_state.clone()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let client_metadata_turn_state = if preserve_turn_state {
|
||||
client_metadata_turn_state
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let turn_metadata = request
|
||||
.turn_metadata
|
||||
.as_deref()
|
||||
.map(|raw| Self::scope_turn_metadata(raw, &identity));
|
||||
let client_metadata_turn_metadata = client_metadata_string(&request, TURN_METADATA_KEY)
|
||||
.map(|raw| Self::scope_turn_metadata(&raw, &identity));
|
||||
|
||||
apply_identity_to_request(
|
||||
&mut request,
|
||||
&identity,
|
||||
turn_state.as_deref(),
|
||||
turn_metadata.as_deref(),
|
||||
client_metadata_turn_state.as_deref(),
|
||||
client_metadata_turn_metadata.as_deref(),
|
||||
);
|
||||
request.turn_state = turn_state;
|
||||
request.turn_metadata = turn_metadata;
|
||||
|
||||
AccountScopedRequest { request, identity }
|
||||
}
|
||||
|
||||
fn scope_values(
|
||||
&self,
|
||||
account_id: &str,
|
||||
proxy_request_id: &str,
|
||||
values: IdentityValues<'_>,
|
||||
) -> AccountScopedIdentity {
|
||||
pub(in crate::dispatch) fn scope_auxiliary(&self, account_id: &str) -> AccountScopedIdentity {
|
||||
AccountScopedIdentity {
|
||||
prompt_cache_key: self.scope_optional(
|
||||
"prompt-cache-key",
|
||||
account_id,
|
||||
values.prompt_cache_key,
|
||||
),
|
||||
session_id: self.scope_optional("session-id", account_id, values.session_id),
|
||||
thread_id: self.scope_optional("thread-id", account_id, values.thread_id),
|
||||
client_request_id: format!(
|
||||
"cr_{}",
|
||||
self.pseudonym(
|
||||
"client-request-id",
|
||||
Some(account_id),
|
||||
values.client_request_id.unwrap_or(proxy_request_id),
|
||||
)
|
||||
),
|
||||
turn_id: self.scope_optional("turn-id", account_id, values.turn_id),
|
||||
window_id: self.scope_optional("window-id", account_id, values.window_id),
|
||||
parent_thread_id: self.scope_optional(
|
||||
"parent-thread-id",
|
||||
account_id,
|
||||
values.parent_thread_id,
|
||||
),
|
||||
installation_id: self.pseudonymizer.installation_id(account_id),
|
||||
}
|
||||
}
|
||||
|
||||
fn scope_optional(
|
||||
&self,
|
||||
domain: &str,
|
||||
account_id: &str,
|
||||
value: Option<&str>,
|
||||
) -> Option<String> {
|
||||
value
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(|value| format!("wi_{}", self.pseudonym(domain, Some(account_id), value)))
|
||||
fn scope_turn_metadata(raw: &str, identity: &AccountScopedIdentity) -> String {
|
||||
let Ok(Value::Object(mut metadata)) = serde_json::from_str::<Value>(raw) else {
|
||||
return raw.to_string();
|
||||
};
|
||||
|
||||
let contains_installation_identity = [
|
||||
"installation_id",
|
||||
"installationId",
|
||||
"x-codex-installation-id",
|
||||
]
|
||||
.into_iter()
|
||||
.any(|key| metadata.contains_key(key));
|
||||
if !contains_installation_identity {
|
||||
return raw.to_string();
|
||||
}
|
||||
|
||||
for key in [
|
||||
"installation_id",
|
||||
"installationId",
|
||||
"x-codex-installation-id",
|
||||
] {
|
||||
replace_existing_metadata_field(&mut metadata, key, Some(&identity.installation_id));
|
||||
}
|
||||
|
||||
serde_json::to_string(&metadata).unwrap_or_else(|_| raw.to_string())
|
||||
}
|
||||
|
||||
fn pseudonym(&self, domain: &str, account_id: Option<&str>, value: &str) -> String {
|
||||
self.pseudonymizer.scoped(domain, account_id, value)
|
||||
}
|
||||
}
|
||||
|
||||
fn client_metadata_string(request: &CodexResponsesRequest, key: &str) -> Option<String> {
|
||||
request
|
||||
.client_metadata()?
|
||||
.as_object()?
|
||||
.get(key)?
|
||||
.as_str()
|
||||
.map(ToString::to_string)
|
||||
}
|
||||
|
||||
fn apply_identity_to_request(
|
||||
request: &mut CodexResponsesRequest,
|
||||
identity: &AccountScopedIdentity,
|
||||
turn_state: Option<&str>,
|
||||
turn_metadata: Option<&str>,
|
||||
client_metadata_turn_state: Option<&str>,
|
||||
client_metadata_turn_metadata: Option<&str>,
|
||||
) {
|
||||
for (key, value) in [
|
||||
(
|
||||
"x-codex-installation-id",
|
||||
Some(identity.installation_id.as_str()),
|
||||
),
|
||||
("installation_id", Some(identity.installation_id.as_str())),
|
||||
("installationId", Some(identity.installation_id.as_str())),
|
||||
("turnState", turn_state),
|
||||
("x-codex-turn-state", turn_state),
|
||||
("turnMetadata", turn_metadata),
|
||||
("x-codex-turn-metadata", turn_metadata),
|
||||
] {
|
||||
request.replace_existing_identity_field(key, value);
|
||||
}
|
||||
|
||||
let client_metadata = scoped_client_metadata(
|
||||
request.client_metadata(),
|
||||
identity,
|
||||
client_metadata_turn_state,
|
||||
client_metadata_turn_metadata,
|
||||
);
|
||||
request.set_client_metadata(client_metadata);
|
||||
}
|
||||
|
||||
fn scoped_client_metadata(
|
||||
client_metadata: Option<&Value>,
|
||||
identity: &AccountScopedIdentity,
|
||||
turn_state: Option<&str>,
|
||||
turn_metadata: Option<&str>,
|
||||
) -> Option<Value> {
|
||||
let client_metadata = client_metadata?;
|
||||
let Value::Object(mut metadata) = client_metadata.clone() else {
|
||||
return Some(client_metadata.clone());
|
||||
};
|
||||
|
||||
for (key, value) in [
|
||||
(
|
||||
"x-codex-installation-id",
|
||||
Some(identity.installation_id.as_str()),
|
||||
),
|
||||
(TURN_STATE_METADATA_KEY, turn_state),
|
||||
(TURN_METADATA_KEY, turn_metadata),
|
||||
] {
|
||||
replace_metadata_field(&mut metadata, key, value);
|
||||
}
|
||||
replace_existing_metadata_field(
|
||||
&mut metadata,
|
||||
"installation_id",
|
||||
Some(&identity.installation_id),
|
||||
);
|
||||
replace_existing_metadata_field(
|
||||
&mut metadata,
|
||||
"installationId",
|
||||
Some(&identity.installation_id),
|
||||
);
|
||||
|
||||
(!metadata.is_empty()).then_some(Value::Object(metadata))
|
||||
}
|
||||
|
||||
fn replace_existing_metadata_field(
|
||||
metadata: &mut Map<String, Value>,
|
||||
key: &str,
|
||||
value: Option<&str>,
|
||||
) {
|
||||
if metadata.contains_key(key) {
|
||||
replace_metadata_field(metadata, key, value);
|
||||
}
|
||||
}
|
||||
|
||||
fn replace_metadata_field(metadata: &mut Map<String, Value>, key: &str, value: Option<&str>) {
|
||||
match value.filter(|value| !value.trim().is_empty()) {
|
||||
Some(value) => {
|
||||
metadata.insert(key.to_string(), Value::String(value.to_string()));
|
||||
}
|
||||
None => {
|
||||
metadata.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,8 @@ pub mod service;
|
||||
pub mod store;
|
||||
pub mod types;
|
||||
|
||||
pub use identity::{AccountIdentityService, AccountScopedIdentity};
|
||||
pub use identity::AccountIdentityService;
|
||||
pub(in crate::dispatch) use identity::{AccountIdentityScope, AccountScopedRequest};
|
||||
pub use resolve::*;
|
||||
pub use service::*;
|
||||
pub use store::*;
|
||||
|
||||
@@ -1,108 +1,7 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
affinity::{SessionAffinityEntry, SessionAffinityService},
|
||||
recovery::history::HistoryRecoveryPlan,
|
||||
service::ResponseDispatchService,
|
||||
},
|
||||
upstream::openai::protocol::{
|
||||
events::TokenUsage,
|
||||
responses::{completed_response_metadata, CodexResponsesRequest},
|
||||
},
|
||||
};
|
||||
|
||||
impl ResponseDispatchService {
|
||||
pub(in crate::dispatch) async fn preferred_account_id_for_request(
|
||||
&self,
|
||||
request: &CodexResponsesRequest,
|
||||
history: &HistoryRecoveryPlan,
|
||||
now: DateTime<Utc>,
|
||||
) -> Option<String> {
|
||||
if let Some(account_id) = history.preferred_account_id() {
|
||||
return Some(account_id.to_string());
|
||||
}
|
||||
if request.previous_response_id().is_some() {
|
||||
return None;
|
||||
}
|
||||
self.conversation_account_id(request, now).await
|
||||
}
|
||||
|
||||
async fn conversation_account_id(
|
||||
&self,
|
||||
request: &CodexResponsesRequest,
|
||||
now: DateTime<Utc>,
|
||||
) -> Option<String> {
|
||||
let conversation_id = request
|
||||
.local_conversation_id
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())?;
|
||||
let variant_hash = compute_variant_hash(request);
|
||||
self.session_affinity
|
||||
.lookup_latest_account_by_conversation(conversation_id, None, Some(&variant_hash), now)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn record_response_affinity(
|
||||
session_affinity: &SessionAffinityService,
|
||||
history: &HistoryRecoveryPlan,
|
||||
original_request: &CodexResponsesRequest,
|
||||
account_id: &str,
|
||||
body: &str,
|
||||
turn_state: Option<String>,
|
||||
usage: Option<TokenUsage>,
|
||||
) {
|
||||
let metadata = match completed_response_metadata(body) {
|
||||
Ok(Some(metadata)) => metadata,
|
||||
Ok(None) => return,
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
error = %error,
|
||||
"failed to parse completed response metadata for session affinity"
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let conversation_id = history
|
||||
.conversation_id(original_request)
|
||||
.unwrap_or(&metadata.response_id)
|
||||
.to_string();
|
||||
let variant_hash = compute_variant_hash(original_request);
|
||||
let entry = SessionAffinityEntry {
|
||||
account_id: account_id.to_string(),
|
||||
conversation_id,
|
||||
turn_state: turn_state
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.or_else(|| original_request.turn_state.clone()),
|
||||
instructions_hash: Some(hash_instructions(Some(original_request.instructions()))),
|
||||
input_tokens: usage.map(|usage| usage.input_tokens),
|
||||
function_call_ids: metadata.function_call_ids,
|
||||
variant_hash: Some(variant_hash),
|
||||
continuation_scope: if original_request.store() {
|
||||
crate::upstream::openai::protocol::responses::PreviousResponseScope::Persisted
|
||||
} else {
|
||||
crate::upstream::openai::protocol::responses::PreviousResponseScope::ConnectionLocal
|
||||
},
|
||||
replay: history.completed_replay(original_request, &metadata.output),
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
if let Err(error) = session_affinity
|
||||
.record(metadata.response_id.clone(), entry)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
error = %error,
|
||||
response_id = %metadata.response_id,
|
||||
account_id = %account_id,
|
||||
"failed to record session affinity"
|
||||
);
|
||||
}
|
||||
}
|
||||
use crate::upstream::openai::protocol::responses::CodexResponsesRequest;
|
||||
|
||||
// ====================================================================
|
||||
// Variant identity helpers
|
||||
@@ -146,12 +45,11 @@ fn build_variant_identity(request: &CodexResponsesRequest) -> Option<String> {
|
||||
if let Some(window_id) = non_empty_str(request.codex_window_id.as_deref()) {
|
||||
parts.push(format!("window:{window_id}"));
|
||||
}
|
||||
if request.explicit_prompt_cache_key
|
||||
|| non_empty_str(request.client_conversation_id.as_deref()).is_some()
|
||||
if (request.explicit_prompt_cache_key
|
||||
|| non_empty_str(request.client_conversation_id.as_deref()).is_some())
|
||||
&& let Some(anchor) = derive_stable_conversation_key(request)
|
||||
{
|
||||
if let Some(anchor) = derive_stable_conversation_key(request) {
|
||||
parts.push(format!("anchor:{anchor}"));
|
||||
}
|
||||
parts.push(format!("anchor:{anchor}"));
|
||||
}
|
||||
|
||||
(!parts.is_empty()).then(|| parts.join("\0"))
|
||||
|
||||
@@ -3,15 +3,14 @@
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::infra::redis::RedisConnection;
|
||||
|
||||
use super::{
|
||||
store::{RedisSessionAffinityStore, RedisSessionAffinityStoreError},
|
||||
types::SessionAffinityEntry,
|
||||
};
|
||||
|
||||
const DEFAULT_SESSION_AFFINITY_TTL_SECS: i64 = 4 * 60 * 60;
|
||||
pub const MAX_REPLAY_SNAPSHOT_BYTES: u64 = 2 * 1024 * 1024;
|
||||
pub const MAX_REPLAY_SESSION_BYTES: u64 = 16 * 1024 * 1024;
|
||||
pub const MAX_REPLAY_DEPTH: u16 = 128;
|
||||
|
||||
/// 运行时会话亲和性服务。
|
||||
#[derive(Clone)]
|
||||
@@ -49,36 +48,6 @@ impl SessionAffinityService {
|
||||
self.entry(response_id, now).await
|
||||
}
|
||||
|
||||
pub async fn replay_input(
|
||||
&self,
|
||||
response_id: &str,
|
||||
entry: &SessionAffinityEntry,
|
||||
now: DateTime<Utc>,
|
||||
) -> Option<Vec<serde_json::Value>> {
|
||||
match self
|
||||
.store
|
||||
.replay_input(
|
||||
response_id,
|
||||
entry,
|
||||
now,
|
||||
self.ttl,
|
||||
MAX_REPLAY_DEPTH,
|
||||
MAX_REPLAY_SESSION_BYTES,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(input) => input,
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
response_id,
|
||||
error = %error,
|
||||
"failed to reconstruct Redis response replay history"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn lookup_latest_account_by_conversation(
|
||||
&self,
|
||||
conversation_id: &str,
|
||||
@@ -98,7 +67,7 @@ impl SessionAffinityService {
|
||||
tracing::warn!(
|
||||
response_id,
|
||||
error = %error,
|
||||
"failed to remove Redis session affinity"
|
||||
"Failed to remove Redis session affinity"
|
||||
);
|
||||
false
|
||||
}
|
||||
@@ -109,17 +78,21 @@ impl SessionAffinityService {
|
||||
match self.store.forget_account(account_id).await {
|
||||
Ok(forgotten) => forgotten > 0,
|
||||
Err(error) => {
|
||||
tracing::warn!(account_id, error = %error, "failed to remove account affinities");
|
||||
tracing::warn!(account_id, error = %error, "Failed to remove account affinities");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn redis_connection(&self) -> RedisConnection {
|
||||
self.store.redis_connection()
|
||||
}
|
||||
|
||||
async fn entry(&self, response_id: &str, now: DateTime<Utc>) -> Option<SessionAffinityEntry> {
|
||||
match self.store.get(response_id, now, self.ttl).await {
|
||||
Ok(entry) => entry,
|
||||
Err(error) => {
|
||||
tracing::warn!(response_id, error = %error, "failed to read Redis session affinity");
|
||||
tracing::warn!(response_id, error = %error, "Failed to read Redis session affinity");
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -139,7 +112,7 @@ impl SessionAffinityService {
|
||||
{
|
||||
Ok(entry) => entry,
|
||||
Err(error) => {
|
||||
tracing::warn!(conversation_id, error = %error, "failed to query Redis affinity index");
|
||||
tracing::warn!(conversation_id, error = %error, "Failed to query Redis affinity index");
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,277 @@
|
||||
//! Redis 会话亲和存储。
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use redis::AsyncCommands;
|
||||
use serde_json::Value;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::infra::redis::RedisConnection;
|
||||
|
||||
use super::types::SessionAffinityEntry;
|
||||
|
||||
/// 单会话保留的最近响应元数据数量。
|
||||
pub const MAX_CONVERSATION_AFFINITIES: usize = 128;
|
||||
/// 单账号保留的最近响应索引数量。
|
||||
pub const MAX_ACCOUNT_AFFINITIES: usize = 16_384;
|
||||
/// Redis 全局保留的最近响应元数据数量。
|
||||
pub const MAX_GLOBAL_AFFINITIES: usize = 65_536;
|
||||
/// Redis 全局响应元数据 JSON 字节预算。
|
||||
pub const MAX_GLOBAL_AFFINITY_BYTES: u64 = 128 * 1024 * 1024;
|
||||
|
||||
const MAX_AFFINITY_METADATA_BYTES: usize = 64 * 1024;
|
||||
const GLOBAL_STALE_CLEANUP_BATCH: usize = 256;
|
||||
const AFFINITY_VERSION: &str = "affinity:v3";
|
||||
|
||||
const UPSERT_SCRIPT: &str = r#"
|
||||
local response_id = ARGV[1]
|
||||
local metadata_json = ARGV[2]
|
||||
local score = tonumber(ARGV[3])
|
||||
local expires_at = tonumber(ARGV[4])
|
||||
local ttl_seconds = tonumber(ARGV[5])
|
||||
local cutoff_ms = tonumber(ARGV[6])
|
||||
local response_prefix = ARGV[7]
|
||||
local conversation_prefix = ARGV[8]
|
||||
local account_prefix = ARGV[9]
|
||||
local max_conversation = tonumber(ARGV[10])
|
||||
local max_account = tonumber(ARGV[11])
|
||||
local max_global = tonumber(ARGV[12])
|
||||
local max_global_bytes = tonumber(ARGV[13])
|
||||
local stale_cleanup_batch = tonumber(ARGV[14])
|
||||
|
||||
local current = cjson.decode(metadata_json)
|
||||
local conversation_id = current.conversationId
|
||||
local account_id = current.accountId
|
||||
|
||||
local function decrement_bytes(size)
|
||||
if size <= 0 then
|
||||
return
|
||||
end
|
||||
local remaining = redis.call('DECRBY', KEYS[5], size)
|
||||
if remaining <= 0 then
|
||||
redis.call('DEL', KEYS[5])
|
||||
end
|
||||
end
|
||||
|
||||
local function read_info(id)
|
||||
local raw = redis.call('HGET', KEYS[6], id)
|
||||
if not raw then
|
||||
return nil
|
||||
end
|
||||
local ok, info = pcall(cjson.decode, raw)
|
||||
if not ok then
|
||||
redis.call('HDEL', KEYS[6], id)
|
||||
return nil
|
||||
end
|
||||
return info
|
||||
end
|
||||
|
||||
local function remove_response(id)
|
||||
local response_key = response_prefix .. id
|
||||
local info = read_info(id)
|
||||
local metadata = nil
|
||||
local raw = redis.call('GET', response_key)
|
||||
if raw then
|
||||
local ok, decoded = pcall(cjson.decode, raw)
|
||||
if ok then
|
||||
metadata = decoded
|
||||
end
|
||||
end
|
||||
|
||||
local stored_conversation_id = info and info.conversationId or metadata and metadata.conversationId
|
||||
local stored_account_id = info and info.accountId or metadata and metadata.accountId
|
||||
local metadata_bytes = info and tonumber(info.metadataBytes or 0)
|
||||
or redis.call('STRLEN', response_key)
|
||||
|
||||
redis.call('UNLINK', response_key)
|
||||
redis.call('ZREM', KEYS[4], id)
|
||||
redis.call('HDEL', KEYS[6], id)
|
||||
redis.call('ZREM', KEYS[2], id)
|
||||
redis.call('ZREM', KEYS[3], id)
|
||||
decrement_bytes(metadata_bytes)
|
||||
if stored_conversation_id then
|
||||
redis.call('ZREM', conversation_prefix .. stored_conversation_id, id)
|
||||
end
|
||||
if stored_account_id then
|
||||
redis.call('ZREM', account_prefix .. stored_account_id, id)
|
||||
end
|
||||
end
|
||||
|
||||
local function trim_index(key, max_members)
|
||||
local excess = redis.call('ZCARD', key) - max_members
|
||||
if excess <= 0 then
|
||||
return
|
||||
end
|
||||
local ids = redis.call('ZRANGE', key, 0, excess - 1)
|
||||
for _, id in ipairs(ids) do
|
||||
remove_response(id)
|
||||
end
|
||||
end
|
||||
|
||||
local previous_info = read_info(response_id)
|
||||
if previous_info then
|
||||
if previous_info.conversationId and previous_info.conversationId ~= conversation_id then
|
||||
redis.call('ZREM', conversation_prefix .. previous_info.conversationId, response_id)
|
||||
end
|
||||
if previous_info.accountId and previous_info.accountId ~= account_id then
|
||||
redis.call('ZREM', account_prefix .. previous_info.accountId, response_id)
|
||||
end
|
||||
end
|
||||
local previous_bytes = previous_info and tonumber(previous_info.metadataBytes or 0)
|
||||
or redis.call('STRLEN', KEYS[1])
|
||||
local metadata_bytes = string.len(metadata_json)
|
||||
|
||||
redis.call('SET', KEYS[1], metadata_json, 'EXAT', expires_at)
|
||||
redis.call('ZADD', KEYS[2], score, response_id)
|
||||
redis.call('EXPIRE', KEYS[2], ttl_seconds)
|
||||
redis.call('ZADD', KEYS[3], score, response_id)
|
||||
redis.call('EXPIRE', KEYS[3], ttl_seconds)
|
||||
redis.call('ZADD', KEYS[4], score, response_id)
|
||||
redis.call('EXPIRE', KEYS[4], ttl_seconds)
|
||||
redis.call('INCRBY', KEYS[5], metadata_bytes - previous_bytes)
|
||||
redis.call('EXPIRE', KEYS[5], ttl_seconds)
|
||||
redis.call('HSET', KEYS[6], response_id, cjson.encode({
|
||||
conversationId = conversation_id,
|
||||
accountId = account_id,
|
||||
metadataBytes = metadata_bytes,
|
||||
}))
|
||||
redis.call('EXPIRE', KEYS[6], ttl_seconds)
|
||||
|
||||
local stale_conversation_ids = redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', cutoff_ms)
|
||||
for _, id in ipairs(stale_conversation_ids) do
|
||||
remove_response(id)
|
||||
end
|
||||
local stale_account_ids = redis.call(
|
||||
'ZRANGEBYSCORE', KEYS[3], '-inf', cutoff_ms, 'LIMIT', 0, stale_cleanup_batch
|
||||
)
|
||||
for _, id in ipairs(stale_account_ids) do
|
||||
remove_response(id)
|
||||
end
|
||||
local stale_global_ids = redis.call(
|
||||
'ZRANGEBYSCORE', KEYS[4], '-inf', cutoff_ms, 'LIMIT', 0, stale_cleanup_batch
|
||||
)
|
||||
for _, id in ipairs(stale_global_ids) do
|
||||
remove_response(id)
|
||||
end
|
||||
|
||||
trim_index(KEYS[2], max_conversation)
|
||||
trim_index(KEYS[3], max_account)
|
||||
trim_index(KEYS[4], max_global)
|
||||
|
||||
while tonumber(redis.call('GET', KEYS[5]) or '0') > max_global_bytes do
|
||||
local oldest = redis.call('ZRANGE', KEYS[4], 0, 0)
|
||||
if #oldest == 0 then
|
||||
redis.call('DEL', KEYS[5])
|
||||
break
|
||||
end
|
||||
remove_response(oldest[1])
|
||||
end
|
||||
|
||||
return 1
|
||||
"#;
|
||||
|
||||
const FORGET_SCRIPT: &str = r#"
|
||||
local response_id = ARGV[1]
|
||||
local response_prefix = ARGV[2]
|
||||
local conversation_prefix = ARGV[3]
|
||||
local account_prefix = ARGV[4]
|
||||
local response_key = response_prefix .. response_id
|
||||
local info_json = redis.call('HGET', KEYS[3], response_id)
|
||||
local metadata_json = redis.call('GET', response_key)
|
||||
if not info_json and not metadata_json then
|
||||
return 0
|
||||
end
|
||||
|
||||
local info = nil
|
||||
if info_json then
|
||||
local ok, decoded = pcall(cjson.decode, info_json)
|
||||
if ok then
|
||||
info = decoded
|
||||
end
|
||||
end
|
||||
local metadata = nil
|
||||
if metadata_json then
|
||||
local ok, decoded = pcall(cjson.decode, metadata_json)
|
||||
if ok then
|
||||
metadata = decoded
|
||||
end
|
||||
end
|
||||
local conversation_id = info and info.conversationId or metadata and metadata.conversationId
|
||||
local account_id = info and info.accountId or metadata and metadata.accountId
|
||||
local metadata_bytes = info and tonumber(info.metadataBytes or 0)
|
||||
or redis.call('STRLEN', response_key)
|
||||
|
||||
redis.call('UNLINK', response_key)
|
||||
redis.call('ZREM', KEYS[1], response_id)
|
||||
redis.call('HDEL', KEYS[3], response_id)
|
||||
if metadata_bytes > 0 then
|
||||
local remaining = redis.call('DECRBY', KEYS[2], metadata_bytes)
|
||||
if remaining <= 0 then
|
||||
redis.call('DEL', KEYS[2])
|
||||
end
|
||||
end
|
||||
if conversation_id then
|
||||
redis.call('ZREM', conversation_prefix .. conversation_id, response_id)
|
||||
end
|
||||
if account_id then
|
||||
redis.call('ZREM', account_prefix .. account_id, response_id)
|
||||
end
|
||||
return 1
|
||||
"#;
|
||||
|
||||
const FORGET_ACCOUNT_SCRIPT: &str = r#"
|
||||
local account_id = ARGV[1]
|
||||
local response_prefix = ARGV[2]
|
||||
local conversation_prefix = ARGV[3]
|
||||
local account_prefix = ARGV[4]
|
||||
local account_key = account_prefix .. account_id
|
||||
local response_ids = redis.call('ZRANGE', account_key, 0, -1)
|
||||
|
||||
local function decrement_bytes(size)
|
||||
if size <= 0 then
|
||||
return
|
||||
end
|
||||
local remaining = redis.call('DECRBY', KEYS[3], size)
|
||||
if remaining <= 0 then
|
||||
redis.call('DEL', KEYS[3])
|
||||
end
|
||||
end
|
||||
|
||||
for _, response_id in ipairs(response_ids) do
|
||||
local response_key = response_prefix .. response_id
|
||||
local info_json = redis.call('HGET', KEYS[4], response_id)
|
||||
local metadata_json = redis.call('GET', response_key)
|
||||
local info = nil
|
||||
if info_json then
|
||||
local ok, decoded = pcall(cjson.decode, info_json)
|
||||
if ok then
|
||||
info = decoded
|
||||
end
|
||||
end
|
||||
local metadata = nil
|
||||
if metadata_json then
|
||||
local ok, decoded = pcall(cjson.decode, metadata_json)
|
||||
if ok then
|
||||
metadata = decoded
|
||||
end
|
||||
end
|
||||
local stored_account_id = info and info.accountId or metadata and metadata.accountId
|
||||
if stored_account_id == account_id then
|
||||
local conversation_id = info and info.conversationId or metadata and metadata.conversationId
|
||||
local metadata_bytes = info and tonumber(info.metadataBytes or 0)
|
||||
or redis.call('STRLEN', response_key)
|
||||
redis.call('UNLINK', response_key)
|
||||
redis.call('ZREM', KEYS[2], response_id)
|
||||
redis.call('HDEL', KEYS[4], response_id)
|
||||
decrement_bytes(metadata_bytes)
|
||||
if conversation_id then
|
||||
redis.call('ZREM', conversation_prefix .. conversation_id, response_id)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
redis.call('DEL', account_key)
|
||||
return #response_ids
|
||||
"#;
|
||||
|
||||
/// Redis 会话亲和性存储。
|
||||
#[derive(Clone)]
|
||||
pub struct RedisSessionAffinityStore {
|
||||
@@ -24,6 +285,8 @@ pub enum RedisSessionAffinityStoreError {
|
||||
Redis(#[from] redis::RedisError),
|
||||
#[error("invalid Redis session affinity value: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error("session affinity metadata is too large: {bytes} bytes exceeds {max} bytes")]
|
||||
MetadataTooLarge { bytes: usize, max: usize },
|
||||
}
|
||||
|
||||
pub type RedisSessionAffinityStoreResult<T> = Result<T, RedisSessionAffinityStoreError>;
|
||||
@@ -33,13 +296,16 @@ impl RedisSessionAffinityStore {
|
||||
Self { redis }
|
||||
}
|
||||
|
||||
pub(crate) fn redis_connection(&self) -> RedisConnection {
|
||||
self.redis.clone()
|
||||
}
|
||||
|
||||
pub async fn upsert(
|
||||
&self,
|
||||
response_id: &str,
|
||||
entry: &SessionAffinityEntry,
|
||||
ttl: Duration,
|
||||
) -> RedisSessionAffinityStoreResult<()> {
|
||||
let value = serde_json::to_string(entry)?;
|
||||
let expires_at = entry
|
||||
.created_at
|
||||
.checked_add_signed(ttl)
|
||||
@@ -48,50 +314,40 @@ impl RedisSessionAffinityStore {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let response_key = self.response_key(response_id);
|
||||
let conversation_key = self.conversation_key(&entry.conversation_id);
|
||||
let account_key = self.account_key(&entry.account_id);
|
||||
let metadata_json = serde_json::to_string(entry)?;
|
||||
if metadata_json.len() > MAX_AFFINITY_METADATA_BYTES {
|
||||
return Err(RedisSessionAffinityStoreError::MetadataTooLarge {
|
||||
bytes: metadata_json.len(),
|
||||
max: MAX_AFFINITY_METADATA_BYTES,
|
||||
});
|
||||
}
|
||||
|
||||
let ttl_seconds = ttl.num_seconds().max(1);
|
||||
let cutoff_ms = Utc::now().timestamp_millis() - ttl.num_milliseconds();
|
||||
let mut connection = self.redis.manager();
|
||||
let mut transaction = redis::pipe();
|
||||
transaction
|
||||
.atomic()
|
||||
.cmd("SET")
|
||||
.arg(response_key)
|
||||
.arg(value)
|
||||
.arg("EXAT")
|
||||
let _: i64 = redis::Script::new(UPSERT_SCRIPT)
|
||||
.key(self.response_key(response_id))
|
||||
.key(self.conversation_key(&entry.conversation_id))
|
||||
.key(self.account_key(&entry.account_id))
|
||||
.key(self.global_index_key())
|
||||
.key(self.global_bytes_key())
|
||||
.key(self.global_info_key())
|
||||
.arg(response_id)
|
||||
.arg(metadata_json)
|
||||
.arg(entry.created_at.timestamp_millis())
|
||||
.arg(expires_at.timestamp())
|
||||
.ignore()
|
||||
.cmd("ZADD")
|
||||
.arg(&conversation_key)
|
||||
.arg(entry.created_at.timestamp_millis())
|
||||
.arg(response_id)
|
||||
.ignore()
|
||||
.cmd("EXPIRE")
|
||||
.arg(&conversation_key)
|
||||
.arg(ttl_seconds)
|
||||
.ignore()
|
||||
.cmd("ZADD")
|
||||
.arg(&account_key)
|
||||
.arg(entry.created_at.timestamp_millis())
|
||||
.arg(response_id)
|
||||
.ignore()
|
||||
.cmd("EXPIRE")
|
||||
.arg(&account_key)
|
||||
.arg(ttl_seconds)
|
||||
.ignore()
|
||||
.cmd("ZREMRANGEBYSCORE")
|
||||
.arg(conversation_key)
|
||||
.arg("-inf")
|
||||
.arg(cutoff_ms)
|
||||
.ignore()
|
||||
.cmd("ZREMRANGEBYSCORE")
|
||||
.arg(&account_key)
|
||||
.arg("-inf")
|
||||
.arg(cutoff_ms)
|
||||
.ignore();
|
||||
let _: () = transaction.query_async(&mut connection).await?;
|
||||
.arg(self.response_key_prefix())
|
||||
.arg(self.conversation_key_prefix())
|
||||
.arg(self.account_key_prefix())
|
||||
.arg(MAX_CONVERSATION_AFFINITIES)
|
||||
.arg(MAX_ACCOUNT_AFFINITIES)
|
||||
.arg(MAX_GLOBAL_AFFINITIES)
|
||||
.arg(MAX_GLOBAL_AFFINITY_BYTES)
|
||||
.arg(GLOBAL_STALE_CLEANUP_BATCH)
|
||||
.invoke_async(&mut connection)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -128,163 +384,14 @@ impl RedisSessionAffinityStore {
|
||||
) -> RedisSessionAffinityStoreResult<Option<(String, SessionAffinityEntry)>> {
|
||||
let conversation_key = self.conversation_key(conversation_id);
|
||||
let mut connection = self.redis.manager();
|
||||
let response_ids: Vec<String> = connection.zrevrange(&conversation_key, 0, -1).await?;
|
||||
for response_id in response_ids {
|
||||
let Some(entry) = self.get(&response_id, now, ttl).await? else {
|
||||
let _: usize = connection.zrem(&conversation_key, &response_id).await?;
|
||||
continue;
|
||||
};
|
||||
if entry.conversation_id != conversation_id {
|
||||
let _: usize = connection.zrem(&conversation_key, &response_id).await?;
|
||||
continue;
|
||||
}
|
||||
if variant_hash.is_some_and(|expected| entry.variant_hash.as_deref() != Some(expected))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if max_age.is_some_and(|max_age| now.signed_duration_since(entry.created_at) > max_age)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
return Ok(Some((response_id, entry)));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub async fn replay_input(
|
||||
&self,
|
||||
response_id: &str,
|
||||
head: &SessionAffinityEntry,
|
||||
now: DateTime<Utc>,
|
||||
ttl: Duration,
|
||||
max_depth: u16,
|
||||
max_total_bytes: u64,
|
||||
) -> RedisSessionAffinityStoreResult<Option<Vec<Value>>> {
|
||||
let Some(head_snapshot) = head.replay.as_ref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
if head_snapshot.depth == 0
|
||||
|| head_snapshot.depth > max_depth
|
||||
|| head_snapshot.total_bytes > max_total_bytes
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let conversation_key = self.conversation_key(&head.conversation_id);
|
||||
let mut connection = self.redis.manager();
|
||||
let response_ids: Vec<String> = redis::cmd("ZREVRANGEBYSCORE")
|
||||
let response_ids: Vec<String> = redis::cmd("ZREVRANGE")
|
||||
.arg(&conversation_key)
|
||||
.arg(head.created_at.timestamp_millis())
|
||||
.arg("-inf")
|
||||
.arg("LIMIT")
|
||||
.arg(0)
|
||||
.arg(max_depth)
|
||||
.arg(MAX_CONVERSATION_AFFINITIES.saturating_sub(1))
|
||||
.query_async(&mut connection)
|
||||
.await?;
|
||||
if !response_ids
|
||||
.iter()
|
||||
.any(|candidate| candidate == response_id)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let response_keys = response_ids
|
||||
.iter()
|
||||
.map(|candidate| self.response_key(candidate))
|
||||
.collect::<Vec<_>>();
|
||||
let values: Vec<Option<String>> = redis::cmd("MGET")
|
||||
.arg(&response_keys)
|
||||
.query_async(&mut connection)
|
||||
.await?;
|
||||
let mut entries = HashMap::with_capacity(values.len());
|
||||
for (candidate, value) in response_ids.into_iter().zip(values) {
|
||||
let Some(value) = value else {
|
||||
continue;
|
||||
};
|
||||
let entry: SessionAffinityEntry = serde_json::from_str(&value)?;
|
||||
if entry.conversation_id == head.conversation_id
|
||||
&& entry
|
||||
.created_at
|
||||
.checked_add_signed(ttl)
|
||||
.is_some_and(|expires_at| expires_at > now)
|
||||
{
|
||||
entries.insert(candidate, entry);
|
||||
}
|
||||
}
|
||||
|
||||
let mut current_id = response_id.to_string();
|
||||
let mut expected_depth = head_snapshot.depth;
|
||||
let mut expected_total_bytes = head_snapshot.total_bytes;
|
||||
let mut nodes = Vec::with_capacity(usize::from(expected_depth));
|
||||
loop {
|
||||
let Some(entry) = entries.get(¤t_id) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(snapshot) = entry.replay.as_ref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
if snapshot.depth != expected_depth || snapshot.total_bytes != expected_total_bytes {
|
||||
return Ok(None);
|
||||
}
|
||||
let node_bytes = replay_node_bytes(snapshot)?;
|
||||
if node_bytes > expected_total_bytes {
|
||||
return Ok(None);
|
||||
}
|
||||
nodes.push((snapshot.turn_input.clone(), snapshot.turn_output.clone()));
|
||||
|
||||
match snapshot.parent_response_id.as_deref() {
|
||||
None if expected_depth == 1 && expected_total_bytes == node_bytes => break,
|
||||
Some(parent_response_id) if expected_depth > 1 => {
|
||||
expected_depth -= 1;
|
||||
expected_total_bytes -= node_bytes;
|
||||
current_id = parent_response_id.to_string();
|
||||
}
|
||||
None | Some(_) => return Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
nodes.reverse();
|
||||
let mut full_input = Vec::new();
|
||||
for (mut input, mut output) in nodes {
|
||||
full_input.append(&mut input);
|
||||
full_input.append(&mut output);
|
||||
}
|
||||
Ok(Some(full_input))
|
||||
}
|
||||
|
||||
pub async fn forget(&self, response_id: &str) -> RedisSessionAffinityStoreResult<bool> {
|
||||
let response_key = self.response_key(response_id);
|
||||
let mut connection = self.redis.manager();
|
||||
let value: Option<String> = connection.get(&response_key).await?;
|
||||
let Some(value) = value else {
|
||||
return Ok(false);
|
||||
};
|
||||
let entry: SessionAffinityEntry = serde_json::from_str(&value)?;
|
||||
let mut transaction = redis::pipe();
|
||||
transaction
|
||||
.atomic()
|
||||
.cmd("DEL")
|
||||
.arg(response_key)
|
||||
.ignore()
|
||||
.cmd("ZREM")
|
||||
.arg(self.conversation_key(&entry.conversation_id))
|
||||
.arg(response_id)
|
||||
.ignore()
|
||||
.cmd("ZREM")
|
||||
.arg(self.account_key(&entry.account_id))
|
||||
.arg(response_id)
|
||||
.ignore();
|
||||
let _: () = transaction.query_async(&mut connection).await?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub async fn forget_account(&self, account_id: &str) -> RedisSessionAffinityStoreResult<u64> {
|
||||
let account_key = self.account_key(account_id);
|
||||
let mut connection = self.redis.manager();
|
||||
let response_ids: Vec<String> = connection.zrange(&account_key, 0, -1).await?;
|
||||
if response_ids.is_empty() {
|
||||
let _: usize = connection.del(account_key).await?;
|
||||
return Ok(0);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let response_keys = response_ids
|
||||
@@ -292,67 +399,105 @@ impl RedisSessionAffinityStore {
|
||||
.map(|response_id| self.response_key(response_id))
|
||||
.collect::<Vec<_>>();
|
||||
let values: Vec<Option<String>> = redis::cmd("MGET")
|
||||
.arg(&response_keys)
|
||||
.arg(response_keys)
|
||||
.query_async(&mut connection)
|
||||
.await?;
|
||||
let mut conversation_members = Vec::with_capacity(response_ids.len());
|
||||
for (response_id, value) in response_ids.iter().zip(values) {
|
||||
let mut stale_ids = Vec::new();
|
||||
let mut result = None;
|
||||
for (response_id, value) in response_ids.into_iter().zip(values) {
|
||||
let Some(value) = value else {
|
||||
stale_ids.push(response_id);
|
||||
continue;
|
||||
};
|
||||
match serde_json::from_str::<SessionAffinityEntry>(&value) {
|
||||
Ok(entry) if entry.account_id == account_id => {
|
||||
conversation_members.push((response_id, entry.conversation_id));
|
||||
}
|
||||
Ok(_) => {
|
||||
tracing::warn!(
|
||||
response_id,
|
||||
account_id,
|
||||
"account affinity index points to another account"
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
response_id,
|
||||
account_id,
|
||||
error = %error,
|
||||
"invalid account affinity entry removed during account cleanup"
|
||||
);
|
||||
}
|
||||
let entry: SessionAffinityEntry = serde_json::from_str(&value)?;
|
||||
if entry.conversation_id != conversation_id
|
||||
|| entry
|
||||
.created_at
|
||||
.checked_add_signed(ttl)
|
||||
.is_none_or(|expires_at| expires_at <= now)
|
||||
{
|
||||
stale_ids.push(response_id);
|
||||
continue;
|
||||
}
|
||||
if variant_hash.is_some_and(|expected| entry.variant_hash.as_deref() != Some(expected))
|
||||
|| max_age
|
||||
.is_some_and(|max_age| now.signed_duration_since(entry.created_at) > max_age)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
result = Some((response_id, entry));
|
||||
break;
|
||||
}
|
||||
if !stale_ids.is_empty() {
|
||||
let _: usize = connection.zrem(conversation_key, stale_ids).await?;
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
let mut transaction = redis::pipe();
|
||||
transaction.atomic().cmd("DEL").arg(&response_keys).ignore();
|
||||
for (response_id, conversation_id) in &conversation_members {
|
||||
transaction
|
||||
.cmd("ZREM")
|
||||
.arg(self.conversation_key(conversation_id))
|
||||
.arg(response_id)
|
||||
.ignore();
|
||||
}
|
||||
transaction.cmd("DEL").arg(account_key).ignore();
|
||||
let _: () = transaction.query_async(&mut connection).await?;
|
||||
Ok(response_ids.len() as u64)
|
||||
pub async fn forget(&self, response_id: &str) -> RedisSessionAffinityStoreResult<bool> {
|
||||
let mut connection = self.redis.manager();
|
||||
let forgotten: i64 = redis::Script::new(FORGET_SCRIPT)
|
||||
.key(self.global_index_key())
|
||||
.key(self.global_bytes_key())
|
||||
.key(self.global_info_key())
|
||||
.arg(response_id)
|
||||
.arg(self.response_key_prefix())
|
||||
.arg(self.conversation_key_prefix())
|
||||
.arg(self.account_key_prefix())
|
||||
.invoke_async(&mut connection)
|
||||
.await?;
|
||||
Ok(forgotten > 0)
|
||||
}
|
||||
|
||||
pub async fn forget_account(&self, account_id: &str) -> RedisSessionAffinityStoreResult<u64> {
|
||||
let mut connection = self.redis.manager();
|
||||
let forgotten: u64 = redis::Script::new(FORGET_ACCOUNT_SCRIPT)
|
||||
.key(self.account_key(account_id))
|
||||
.key(self.global_index_key())
|
||||
.key(self.global_bytes_key())
|
||||
.key(self.global_info_key())
|
||||
.arg(account_id)
|
||||
.arg(self.response_key_prefix())
|
||||
.arg(self.conversation_key_prefix())
|
||||
.arg(self.account_key_prefix())
|
||||
.invoke_async(&mut connection)
|
||||
.await?;
|
||||
Ok(forgotten)
|
||||
}
|
||||
|
||||
fn response_key(&self, response_id: &str) -> String {
|
||||
self.redis.key(&format!("affinity:v2:resp:{response_id}"))
|
||||
format!("{}{response_id}", self.response_key_prefix())
|
||||
}
|
||||
|
||||
fn conversation_key(&self, conversation_id: &str) -> String {
|
||||
self.redis
|
||||
.key(&format!("affinity:v2:conv:{conversation_id}"))
|
||||
format!("{}{conversation_id}", self.conversation_key_prefix())
|
||||
}
|
||||
|
||||
fn account_key(&self, account_id: &str) -> String {
|
||||
self.redis.key(&format!("affinity:v2:account:{account_id}"))
|
||||
format!("{}{account_id}", self.account_key_prefix())
|
||||
}
|
||||
|
||||
fn global_index_key(&self) -> String {
|
||||
self.redis.key(&format!("{AFFINITY_VERSION}:global:index"))
|
||||
}
|
||||
|
||||
fn global_bytes_key(&self) -> String {
|
||||
self.redis.key(&format!("{AFFINITY_VERSION}:global:bytes"))
|
||||
}
|
||||
|
||||
fn global_info_key(&self) -> String {
|
||||
self.redis.key(&format!("{AFFINITY_VERSION}:global:info"))
|
||||
}
|
||||
|
||||
fn response_key_prefix(&self) -> String {
|
||||
self.redis.key(&format!("{AFFINITY_VERSION}:resp:"))
|
||||
}
|
||||
|
||||
fn conversation_key_prefix(&self) -> String {
|
||||
self.redis.key(&format!("{AFFINITY_VERSION}:conv:"))
|
||||
}
|
||||
|
||||
fn account_key_prefix(&self) -> String {
|
||||
self.redis.key(&format!("{AFFINITY_VERSION}:account:"))
|
||||
}
|
||||
}
|
||||
|
||||
fn replay_node_bytes(
|
||||
snapshot: &super::types::ResponseReplaySnapshot,
|
||||
) -> Result<u64, serde_json::Error> {
|
||||
serde_json::to_vec(&(&snapshot.turn_input, &snapshot.turn_output))
|
||||
.map(|value| value.len() as u64)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::upstream::openai::protocol::responses::PreviousResponseScope;
|
||||
|
||||
@@ -18,22 +17,5 @@ pub struct SessionAffinityEntry {
|
||||
pub function_call_ids: Vec<String>,
|
||||
pub variant_hash: Option<String>,
|
||||
pub continuation_scope: PreviousResponseScope,
|
||||
pub replay: Option<ResponseReplaySnapshot>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// 单轮 completed response 的有界、无凭据重放增量。
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ResponseReplaySnapshot {
|
||||
/// 上一轮由本代理记录的 completed response。
|
||||
pub parent_response_id: Option<String>,
|
||||
/// 本轮客户端新增的输入,已剥离账号绑定字段。
|
||||
pub turn_input: Vec<Value>,
|
||||
/// 本轮上游输出,已剥离账号绑定字段和上游对象 ID。
|
||||
pub turn_output: Vec<Value>,
|
||||
/// 从会话起点到本节点的增量节点数。
|
||||
pub depth: u16,
|
||||
/// 从会话起点到本节点的 JSON 编码累计字节数。
|
||||
pub total_bytes: u64,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
//! 账号级失败分类、隔离副作用与换号决策 owner。
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
controllers::{
|
||||
ControllerFailureFact,
|
||||
account_state::{AccountStateEffect, AccountStateEffects},
|
||||
},
|
||||
errors::ClientFailure,
|
||||
failure::exhaustion::{AccountExhaustionRecord, ExhaustedAccountKind},
|
||||
lifecycle::contract::{
|
||||
AttemptDecision, AttemptObservation, AttemptObservationKind, CompleteResponseFacts,
|
||||
},
|
||||
transport::observation::{UpstreamFailureFacts, UpstreamFailureKind},
|
||||
},
|
||||
fleet::{account::AccountStatus, pool::AccountPoolService},
|
||||
upstream::openai::{protocol::responses::ResponsesSseFailure, transport::CodexBackendClient},
|
||||
};
|
||||
|
||||
pub(super) struct AccountFailureController;
|
||||
|
||||
pub(super) struct ClassifiedFailure {
|
||||
exhaustion: AccountExhaustionRecord,
|
||||
effect: Option<AccountStateEffect>,
|
||||
}
|
||||
|
||||
impl AccountFailureController {
|
||||
pub(super) fn classify(observation: &AttemptObservation) -> Option<ClassifiedFailure> {
|
||||
let account_id = observation.account.as_ref()?.id.as_str();
|
||||
classify(observation, account_id)
|
||||
}
|
||||
|
||||
pub(super) fn classify_failure(
|
||||
account_id: &str,
|
||||
failure: ControllerFailureFact<'_>,
|
||||
) -> Option<ClassifiedFailure> {
|
||||
classify_failure(account_id, failure)
|
||||
}
|
||||
|
||||
pub(super) async fn apply_effect(
|
||||
account_pool: &AccountPoolService,
|
||||
codex: &CodexBackendClient,
|
||||
classified: &ClassifiedFailure,
|
||||
) {
|
||||
let Some(account_id) = classified.exhaustion.account_id.as_deref() else {
|
||||
return;
|
||||
};
|
||||
if let Some(effect) = &classified.effect {
|
||||
AccountStateEffects::apply(account_pool, codex, account_id, effect).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn decision(
|
||||
observation: &AttemptObservation,
|
||||
classified: ClassifiedFailure,
|
||||
) -> AttemptDecision {
|
||||
if observation.routing.can_retry_next_candidate {
|
||||
AttemptDecision::RetryNextCandidate {
|
||||
exhaustion: Some(classified.exhaustion),
|
||||
on_exhaustion: None,
|
||||
}
|
||||
} else {
|
||||
AttemptDecision::Return(
|
||||
crate::dispatch::lifecycle::contract::AttemptReturnKind::Observed,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn is_retryable_transport(observation: &AttemptObservation) -> bool {
|
||||
let AttemptObservationKind::UpstreamFailure(facts) = &observation.kind else {
|
||||
return false;
|
||||
};
|
||||
matches!(
|
||||
facts.kind,
|
||||
UpstreamFailureKind::HttpConnect
|
||||
| UpstreamFailureKind::HttpTimeout
|
||||
| UpstreamFailureKind::HttpTransport
|
||||
| UpstreamFailureKind::StreamIdle
|
||||
| UpstreamFailureKind::WebSocketTransport
|
||||
| UpstreamFailureKind::WebSocketTimeout
|
||||
) || facts
|
||||
.status_code
|
||||
.is_some_and(|status| (500..=599).contains(&status))
|
||||
}
|
||||
|
||||
pub(super) fn client_failure(
|
||||
classified: &ClassifiedFailure,
|
||||
failure: &ResponsesSseFailure,
|
||||
) -> ClientFailure {
|
||||
let status_code =
|
||||
classified
|
||||
.exhaustion
|
||||
.status_code
|
||||
.unwrap_or(match classified.exhaustion.kind {
|
||||
ExhaustedAccountKind::ModelUnsupported => 400,
|
||||
ExhaustedAccountKind::Expired | ExhaustedAccountKind::Disabled => 401,
|
||||
ExhaustedAccountKind::Banned => 403,
|
||||
ExhaustedAccountKind::QuotaExhausted
|
||||
| ExhaustedAccountKind::RateLimited
|
||||
| ExhaustedAccountKind::CloudflareChallenge
|
||||
| ExhaustedAccountKind::CloudflarePathBlocked
|
||||
| ExhaustedAccountKind::UpstreamUnavailable => 502,
|
||||
});
|
||||
ClientFailure::new(failure.clone(), status_code, false)
|
||||
}
|
||||
|
||||
pub(super) fn unowned_client_failure(failure: &ResponsesSseFailure) -> Option<ClientFailure> {
|
||||
let code = failure
|
||||
.upstream_code
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase();
|
||||
let error_type = failure
|
||||
.upstream_type
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase();
|
||||
let message = failure.message.to_ascii_lowercase();
|
||||
if is_model_unsupported(&code)
|
||||
|| is_model_unsupported(&message)
|
||||
|| code.contains("invalid_request")
|
||||
|| code.contains("not_found")
|
||||
|| code.contains("context_window")
|
||||
|| code.contains("invalid_prompt")
|
||||
|| code.contains("bad_request")
|
||||
{
|
||||
return Some(ClientFailure::new(failure.clone(), 400, false));
|
||||
}
|
||||
if is_auth_failure(&code, &error_type, &message) {
|
||||
return Some(ClientFailure::new(failure.clone(), 401, false));
|
||||
}
|
||||
if code.contains("forbidden") || code.contains("banned") || error_type == "permission_error"
|
||||
{
|
||||
return Some(ClientFailure::new(failure.clone(), 403, false));
|
||||
}
|
||||
if code.contains("server_overloaded") {
|
||||
return Some(ClientFailure::new(failure.clone(), 503, true));
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn classify(observation: &AttemptObservation, account_id: &str) -> Option<ClassifiedFailure> {
|
||||
match &observation.kind {
|
||||
AttemptObservationKind::CompleteResponse(CompleteResponseFacts::Empty) => {
|
||||
Some(ClassifiedFailure {
|
||||
exhaustion: AccountExhaustionRecord::new(
|
||||
account_id,
|
||||
ExhaustedAccountKind::UpstreamUnavailable,
|
||||
"upstream response did not include visible output",
|
||||
),
|
||||
effect: None,
|
||||
})
|
||||
}
|
||||
_ => ControllerFailureFact::from_attempt(observation)
|
||||
.and_then(|failure| classify_failure(account_id, failure)),
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_failure(
|
||||
account_id: &str,
|
||||
failure: ControllerFailureFact<'_>,
|
||||
) -> Option<ClassifiedFailure> {
|
||||
match failure {
|
||||
ControllerFailureFact::Upstream(facts) => classify_upstream(account_id, facts),
|
||||
ControllerFailureFact::Response(failure) => classify_sse(account_id, failure),
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_upstream(account_id: &str, facts: &UpstreamFailureFacts) -> Option<ClassifiedFailure> {
|
||||
let status = facts.status_code;
|
||||
let body = facts.body.as_str();
|
||||
let code = facts.code.as_deref().unwrap_or_default();
|
||||
let error_type = facts.error_type.as_deref().unwrap_or_default();
|
||||
let message = facts.message.as_str();
|
||||
|
||||
if is_model_unsupported(code) || is_model_unsupported(message) || is_model_unsupported(body) {
|
||||
return Some(model_unsupported_failure(account_id, body));
|
||||
}
|
||||
if let Some(account_status) = explicit_account_status(code, error_type, body) {
|
||||
return Some(account_status_failure(
|
||||
account_id,
|
||||
account_status,
|
||||
body,
|
||||
status,
|
||||
));
|
||||
}
|
||||
if status == Some(403) && !is_html(body) {
|
||||
return Some(account_status_failure(
|
||||
account_id,
|
||||
AccountStatus::Banned,
|
||||
body,
|
||||
status,
|
||||
));
|
||||
}
|
||||
if status == Some(401) {
|
||||
return Some(account_status_failure(
|
||||
account_id,
|
||||
AccountStatus::Expired,
|
||||
body,
|
||||
status,
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn classify_sse(account_id: &str, failure: &ResponsesSseFailure) -> Option<ClassifiedFailure> {
|
||||
let code = failure.upstream_code.as_deref().unwrap_or_default();
|
||||
let error_type = failure.upstream_type.as_deref().unwrap_or_default();
|
||||
if is_model_unsupported(code) || is_model_unsupported(&failure.message) {
|
||||
return Some(model_unsupported_failure(
|
||||
account_id,
|
||||
&crate::dispatch::failure::sse::sse_failure_error_body(failure),
|
||||
));
|
||||
}
|
||||
let account_status =
|
||||
explicit_account_status(code, error_type, &failure.message).or_else(|| {
|
||||
(code.eq_ignore_ascii_case("forbidden") || error_type == "permission_error")
|
||||
.then_some(AccountStatus::Banned)
|
||||
})?;
|
||||
Some(account_status_failure(
|
||||
account_id,
|
||||
account_status,
|
||||
&crate::dispatch::failure::sse::sse_failure_error_body(failure),
|
||||
failure.explicit_status_code,
|
||||
))
|
||||
}
|
||||
|
||||
fn model_unsupported_failure(account_id: &str, message: &str) -> ClassifiedFailure {
|
||||
ClassifiedFailure {
|
||||
exhaustion: AccountExhaustionRecord::new(
|
||||
account_id,
|
||||
ExhaustedAccountKind::ModelUnsupported,
|
||||
message,
|
||||
),
|
||||
effect: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn account_status_failure(
|
||||
account_id: &str,
|
||||
status: AccountStatus,
|
||||
message: &str,
|
||||
status_code: Option<u16>,
|
||||
) -> ClassifiedFailure {
|
||||
let kind = match status {
|
||||
AccountStatus::Expired => ExhaustedAccountKind::Expired,
|
||||
AccountStatus::Disabled => ExhaustedAccountKind::Disabled,
|
||||
AccountStatus::Banned => ExhaustedAccountKind::Banned,
|
||||
AccountStatus::Active | AccountStatus::QuotaExhausted => {
|
||||
unreachable!("account failure controller only invalidates unavailable statuses")
|
||||
}
|
||||
};
|
||||
let mut exhaustion = AccountExhaustionRecord::new(account_id, kind, message);
|
||||
if let Some(status_code) = status_code {
|
||||
exhaustion = exhaustion.with_status_code(status_code);
|
||||
}
|
||||
ClassifiedFailure {
|
||||
exhaustion,
|
||||
effect: Some(AccountStateEffect::SetStatus(status)),
|
||||
}
|
||||
}
|
||||
|
||||
fn explicit_account_status(code: &str, error_type: &str, message: &str) -> Option<AccountStatus> {
|
||||
let code = code.trim().to_ascii_lowercase();
|
||||
let error_type = error_type.trim().to_ascii_lowercase();
|
||||
let message = message.to_ascii_lowercase();
|
||||
if matches!(
|
||||
code.as_str(),
|
||||
"identity_verification_required" | "verification_required"
|
||||
) || message.contains("identity verification is required")
|
||||
{
|
||||
return Some(AccountStatus::Disabled);
|
||||
}
|
||||
if matches!(
|
||||
code.as_str(),
|
||||
"account_banned"
|
||||
| "account_deactivated"
|
||||
| "account_disabled"
|
||||
| "account_suspended"
|
||||
| "deactivated_workspace"
|
||||
| "organization_disabled"
|
||||
| "workspace_deactivated"
|
||||
) || message.contains("account is banned")
|
||||
|| message.contains("account has been banned")
|
||||
|| message.contains("account deactivated")
|
||||
|| message.contains("account has been deactivated")
|
||||
|| message.contains("account disabled")
|
||||
|| message.contains("account has been disabled")
|
||||
|| message.contains("account suspended")
|
||||
|| message.contains("organization has been disabled")
|
||||
|| message.contains("workspace has been deactivated")
|
||||
|| message.contains("deactivated_workspace")
|
||||
{
|
||||
return Some(AccountStatus::Banned);
|
||||
}
|
||||
is_auth_failure(&code, &error_type, &message).then_some(AccountStatus::Expired)
|
||||
}
|
||||
|
||||
fn is_auth_failure(code: &str, error_type: &str, message: &str) -> bool {
|
||||
matches!(
|
||||
code,
|
||||
"token_invalid"
|
||||
| "token_invalidated"
|
||||
| "token_expired"
|
||||
| "token_revoked"
|
||||
| "refresh_token_invalidated"
|
||||
| "unauthorized"
|
||||
| "invalid_api_key"
|
||||
| "authentication_error"
|
||||
) || error_type == "authentication_error"
|
||||
|| message.contains("token revoked")
|
||||
|| message.contains("token invalidated")
|
||||
|| message.contains("token invalid")
|
||||
|| message.contains("token expired")
|
||||
|| message.contains("unauthorized")
|
||||
|| message.contains("invalid api key")
|
||||
}
|
||||
|
||||
fn is_model_unsupported(value: &str) -> bool {
|
||||
let value = value.to_ascii_lowercase();
|
||||
value.contains("model_not_supported")
|
||||
|| value.contains("model_not_available")
|
||||
|| (value.contains("model")
|
||||
&& (value.contains("not supported")
|
||||
|| value.contains("not available")
|
||||
|| value.contains("not_supported")
|
||||
|| value.contains("not_available")))
|
||||
}
|
||||
|
||||
fn is_html(value: &str) -> bool {
|
||||
let value = value.trim_start().to_ascii_lowercase();
|
||||
value.starts_with("<!doctype") || value.starts_with("<html") || value.contains("<html")
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//! 明确账号事实触发的运行时失效与连接驱逐。
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
use crate::{
|
||||
fleet::{account::AccountStatus, pool::AccountPoolService},
|
||||
upstream::openai::transport::CodexBackendClient,
|
||||
};
|
||||
|
||||
pub(super) enum AccountStateEffect {
|
||||
SetStatus(AccountStatus),
|
||||
MarkQuotaLimitedUntil(DateTime<Utc>),
|
||||
}
|
||||
|
||||
pub(super) struct AccountStateEffects;
|
||||
|
||||
impl AccountStateEffects {
|
||||
pub(super) async fn apply(
|
||||
account_pool: &AccountPoolService,
|
||||
codex: &CodexBackendClient,
|
||||
account_id: &str,
|
||||
effect: &AccountStateEffect,
|
||||
) {
|
||||
match effect {
|
||||
AccountStateEffect::SetStatus(status) => {
|
||||
account_pool
|
||||
.set_status_immediately(account_id, *status)
|
||||
.await;
|
||||
}
|
||||
AccountStateEffect::MarkQuotaLimitedUntil(until) => {
|
||||
account_pool
|
||||
.mark_quota_limited_until_immediately(account_id, *until)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
codex.evict_websocket_account(account_id).await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
//! 会话亲和性路由与写入的唯一 feature owner。
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use tokio::time::timeout;
|
||||
|
||||
use crate::dispatch::affinity::{
|
||||
SessionAffinityEntry, SessionAffinityService, compute_variant_hash, hash_instructions,
|
||||
};
|
||||
use crate::upstream::openai::protocol::{
|
||||
events::TokenUsage,
|
||||
responses::{CodexResponsesRequest, PreviousResponseScope, completed_response_metadata},
|
||||
};
|
||||
|
||||
const REDIS_BEST_EFFORT_TIMEOUT: Duration = Duration::from_millis(100);
|
||||
|
||||
pub(super) struct AffinityController;
|
||||
|
||||
pub(super) struct ResponseExit<'a> {
|
||||
pub affinity: &'a SessionAffinityService,
|
||||
pub conversation_id: Option<&'a str>,
|
||||
pub request: &'a CodexResponsesRequest,
|
||||
pub account_id: &'a str,
|
||||
pub body: &'a str,
|
||||
pub turn_state: Option<String>,
|
||||
pub usage: Option<TokenUsage>,
|
||||
pub continuation_scope: PreviousResponseScope,
|
||||
}
|
||||
|
||||
pub(super) struct StreamExit<'a> {
|
||||
pub response: ResponseExit<'a>,
|
||||
pub completed: bool,
|
||||
}
|
||||
|
||||
impl AffinityController {
|
||||
pub(super) async fn preferred_account_id(
|
||||
affinity: &SessionAffinityService,
|
||||
request: &CodexResponsesRequest,
|
||||
now: DateTime<Utc>,
|
||||
) -> Option<String> {
|
||||
if request.previous_response_id().is_some() {
|
||||
return None;
|
||||
}
|
||||
let conversation_id = request
|
||||
.local_conversation_id
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())?;
|
||||
let variant_hash = compute_variant_hash(request);
|
||||
match timeout(
|
||||
REDIS_BEST_EFFORT_TIMEOUT,
|
||||
affinity.lookup_latest_account_by_conversation(
|
||||
conversation_id,
|
||||
None,
|
||||
Some(&variant_hash),
|
||||
now,
|
||||
),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(account_id) => account_id,
|
||||
Err(_) => {
|
||||
tracing::warn!(
|
||||
conversation_id,
|
||||
timeout_ms = REDIS_BEST_EFFORT_TIMEOUT.as_millis(),
|
||||
"Timed out reading conversation affinity; continuing without preference"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn leave_complete(exit: ResponseExit<'_>) {
|
||||
record_response_affinity(exit).await;
|
||||
}
|
||||
|
||||
pub(super) async fn leave_stream(exit: StreamExit<'_>) {
|
||||
if !exit.completed {
|
||||
return;
|
||||
}
|
||||
record_response_affinity(exit.response).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn record_response_affinity(exit: ResponseExit<'_>) {
|
||||
let ResponseExit {
|
||||
affinity,
|
||||
conversation_id,
|
||||
request,
|
||||
account_id,
|
||||
body,
|
||||
turn_state,
|
||||
usage,
|
||||
continuation_scope,
|
||||
} = exit;
|
||||
let metadata = match completed_response_metadata(body) {
|
||||
Ok(Some(metadata)) => metadata,
|
||||
Ok(None) => return,
|
||||
Err(error) => {
|
||||
tracing::warn!(error = %error, "Failed to parse completed response metadata for session affinity");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let entry = SessionAffinityEntry {
|
||||
account_id: account_id.to_string(),
|
||||
conversation_id: conversation_id.unwrap_or(&metadata.response_id).to_string(),
|
||||
turn_state: turn_state
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.or_else(|| request.turn_state.clone()),
|
||||
instructions_hash: Some(hash_instructions(Some(request.instructions()))),
|
||||
input_tokens: usage.map(|usage| usage.input_tokens),
|
||||
function_call_ids: metadata.function_call_ids,
|
||||
variant_hash: Some(compute_variant_hash(request)),
|
||||
continuation_scope,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
match timeout(
|
||||
REDIS_BEST_EFFORT_TIMEOUT,
|
||||
affinity.record(metadata.response_id.clone(), entry),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(error)) => {
|
||||
tracing::warn!(error = %error, response_id = %metadata.response_id, account_id, "Failed to record session affinity");
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::warn!(
|
||||
response_id = %metadata.response_id,
|
||||
account_id,
|
||||
timeout_ms = REDIS_BEST_EFFORT_TIMEOUT.as_millis(),
|
||||
"Timed out recording session affinity"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
//! Cloudflare challenge、路径封禁与 Cookie 生命周期的唯一 feature owner。
|
||||
|
||||
use chrono::Utc;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
failure::exhaustion::{AccountExhaustionRecord, ExhaustedAccountKind},
|
||||
lifecycle::contract::{
|
||||
AttemptDecision, AttemptObservation, AttemptObservationKind, AttemptReturnKind,
|
||||
},
|
||||
lifecycle::stream::StreamTerminal,
|
||||
transport::observation::UpstreamFailureFacts,
|
||||
},
|
||||
fleet::{
|
||||
account::AccountStatus,
|
||||
cookies::{CloudflareChallengeCooldownTracker, CloudflarePathBlockTracker, PgCookieStore},
|
||||
pool::AccountPoolService,
|
||||
},
|
||||
};
|
||||
|
||||
pub(super) struct CloudflareController;
|
||||
|
||||
pub(super) struct StreamExit<'a> {
|
||||
pub recovery: &'a CloudflareRecovery,
|
||||
pub account_id: &'a str,
|
||||
pub set_cookie_headers: &'a [String],
|
||||
pub terminal: &'a StreamTerminal,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum CloudflareFailureKind {
|
||||
Challenge,
|
||||
PathBlocked,
|
||||
}
|
||||
|
||||
pub(super) struct CloudflareFailure {
|
||||
kind: CloudflareFailureKind,
|
||||
exhaustion: AccountExhaustionRecord,
|
||||
}
|
||||
|
||||
impl CloudflareController {
|
||||
pub(super) fn classify(observation: &AttemptObservation) -> Option<CloudflareFailure> {
|
||||
classify(observation)
|
||||
}
|
||||
|
||||
pub(super) async fn apply_effect(
|
||||
recovery: &CloudflareRecovery,
|
||||
account_pool: &AccountPoolService,
|
||||
failure: &CloudflareFailure,
|
||||
) {
|
||||
match failure.kind {
|
||||
CloudflareFailureKind::Challenge => {
|
||||
let Some(account_id) = failure.exhaustion.account_id.as_deref() else {
|
||||
return;
|
||||
};
|
||||
recovery.apply_challenge(account_pool, account_id).await;
|
||||
}
|
||||
CloudflareFailureKind::PathBlocked => {
|
||||
let Some(account_id) = failure.exhaustion.account_id.as_deref() else {
|
||||
return;
|
||||
};
|
||||
recovery.apply_path_block(account_pool, account_id).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn decision(
|
||||
observation: &AttemptObservation,
|
||||
failure: CloudflareFailure,
|
||||
) -> AttemptDecision {
|
||||
if observation.routing.can_retry_next_candidate {
|
||||
return AttemptDecision::RetryNextCandidate {
|
||||
exhaustion: Some(failure.exhaustion),
|
||||
on_exhaustion: None,
|
||||
};
|
||||
}
|
||||
AttemptDecision::Return(AttemptReturnKind::Observed)
|
||||
}
|
||||
|
||||
pub(super) async fn leave_complete(recovery: &CloudflareRecovery, account_id: &str) {
|
||||
recovery.reset_account_recovery(account_id).await;
|
||||
}
|
||||
|
||||
pub(super) async fn leave_stream(exit: StreamExit<'_>) {
|
||||
exit.recovery
|
||||
.capture_set_cookie_headers(exit.account_id, exit.set_cookie_headers)
|
||||
.await;
|
||||
if matches!(
|
||||
exit.terminal,
|
||||
StreamTerminal::Completed { .. } | StreamTerminal::Incomplete { .. }
|
||||
) {
|
||||
exit.recovery.reset_account_recovery(exit.account_id).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn classify(observation: &AttemptObservation) -> Option<CloudflareFailure> {
|
||||
let account_id = observation.account.as_ref()?.id.as_str();
|
||||
let AttemptObservationKind::UpstreamFailure(facts) = &observation.kind else {
|
||||
return None;
|
||||
};
|
||||
classify_upstream(account_id, facts)
|
||||
}
|
||||
|
||||
fn classify_upstream(account_id: &str, facts: &UpstreamFailureFacts) -> Option<CloudflareFailure> {
|
||||
if facts.status_code == Some(403) && is_challenge(&facts.body) {
|
||||
return Some(CloudflareFailure {
|
||||
kind: CloudflareFailureKind::Challenge,
|
||||
exhaustion: AccountExhaustionRecord::new(
|
||||
account_id,
|
||||
ExhaustedAccountKind::CloudflareChallenge,
|
||||
"Upstream blocked the request (Cloudflare challenge)",
|
||||
),
|
||||
});
|
||||
}
|
||||
if facts.status_code == Some(404) && facts.body.trim().is_empty() {
|
||||
return Some(CloudflareFailure {
|
||||
kind: CloudflareFailureKind::PathBlocked,
|
||||
exhaustion: AccountExhaustionRecord::new(
|
||||
account_id,
|
||||
ExhaustedAccountKind::CloudflarePathBlocked,
|
||||
"Upstream blocked the request (Cloudflare path-block)",
|
||||
),
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn is_challenge(value: &str) -> bool {
|
||||
let value = value.to_ascii_lowercase();
|
||||
value.contains("cf-mitigated")
|
||||
|| value.contains("cf-chl-bypass")
|
||||
|| value.contains("_cf_chl")
|
||||
|| value.contains("cf_chl")
|
||||
|| value.contains("attention required")
|
||||
|| value.contains("just a moment")
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CloudflareRecovery {
|
||||
path_block_tracker: CloudflarePathBlockTracker,
|
||||
challenge_tracker: CloudflareChallengeCooldownTracker,
|
||||
cookie_store: PgCookieStore,
|
||||
}
|
||||
|
||||
impl CloudflareRecovery {
|
||||
pub fn new(cookie_store: PgCookieStore) -> Self {
|
||||
Self {
|
||||
path_block_tracker: CloudflarePathBlockTracker::default(),
|
||||
challenge_tracker: CloudflareChallengeCooldownTracker::default(),
|
||||
cookie_store,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cookie_header_for_request(&self, account_id: &str, path: &str) -> Option<String> {
|
||||
self.cookie_store
|
||||
.cookie_header_for_request(account_id, "chatgpt.com", path)
|
||||
.await
|
||||
.ok()?
|
||||
}
|
||||
|
||||
pub async fn capture_set_cookie_headers(&self, account_id: &str, headers: &[String]) {
|
||||
for header in headers {
|
||||
if let Err(error) = self
|
||||
.cookie_store
|
||||
.capture_set_cookie(account_id, header)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"Failed to persist upstream set-cookie header"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn apply_challenge(&self, account_pool: &AccountPoolService, account_id: &str) {
|
||||
let now = Utc::now();
|
||||
let cooldown = self
|
||||
.challenge_tracker
|
||||
.record_challenge(account_id, now)
|
||||
.await;
|
||||
account_pool
|
||||
.set_cloudflare_cooldown_until(account_id, cooldown.cooldown_until)
|
||||
.await;
|
||||
if let Err(error) = self
|
||||
.cookie_store
|
||||
.expire_account_cookies_at(account_id, cooldown.cooldown_until)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"Failed to persist Cloudflare challenge cookie cleanup deadline"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn apply_path_block(&self, account_pool: &AccountPoolService, account_id: &str) {
|
||||
self.delete_account_cookies(account_id, "Cloudflare path-block")
|
||||
.await;
|
||||
let now = Utc::now();
|
||||
self.path_block_tracker
|
||||
.record_path_block(account_id, now)
|
||||
.await;
|
||||
if self
|
||||
.path_block_tracker
|
||||
.should_disable(account_id, now)
|
||||
.await
|
||||
{
|
||||
account_pool
|
||||
.set_status(account_id, AccountStatus::Disabled)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn reset_account_recovery(&self, account_id: &str) {
|
||||
self.path_block_tracker.reset(account_id).await;
|
||||
self.challenge_tracker.reset(account_id).await;
|
||||
}
|
||||
|
||||
async fn delete_account_cookies(&self, account_id: &str, reason: &str) {
|
||||
delete_account_cookies(&self.cookie_store, account_id, reason).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn delete_account_cookies(cookie_store: &PgCookieStore, account_id: &str, reason: &str) {
|
||||
if let Err(error) = cookie_store.delete_account_cookies(account_id).await {
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
reason,
|
||||
error = %error,
|
||||
"Failed to delete account cookies after Cloudflare recovery signal"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
//! `cyber_policy` 会话级生命周期控制器。
|
||||
|
||||
use std::{collections::BTreeSet, sync::Arc, time::Duration as StdDuration};
|
||||
|
||||
use chrono::Duration;
|
||||
use sha2::{Digest, Sha256};
|
||||
use tokio::time::timeout;
|
||||
|
||||
mod store;
|
||||
mod types;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
affinity::SessionAffinityService,
|
||||
controllers::ControllerFailureFact,
|
||||
errors::ClientFailure,
|
||||
lifecycle::contract::{AttemptDecision, AttemptObservation, AttemptReturnKind},
|
||||
transport::observation::UpstreamFailureFacts,
|
||||
},
|
||||
upstream::openai::protocol::responses::{CodexResponsesRequest, ResponsesSseFailure},
|
||||
};
|
||||
|
||||
use self::{store::Store, types::SessionState};
|
||||
|
||||
const SESSION_STATE_TTL: Duration = Duration::hours(1);
|
||||
const STATE_IO_TIMEOUT: StdDuration = StdDuration::from_millis(100);
|
||||
|
||||
/// 单次请求使用的 `cyber_policy` 会话路由计划。
|
||||
pub(in crate::dispatch) struct CyberPolicyScope {
|
||||
session_key: Option<String>,
|
||||
state: SessionState,
|
||||
}
|
||||
|
||||
impl CyberPolicyScope {
|
||||
pub(in crate::dispatch) fn excluded_account_ids(&self) -> BTreeSet<String> {
|
||||
self.state.failed_account_ids.iter().cloned().collect()
|
||||
}
|
||||
|
||||
fn session_key(&self) -> Option<&str> {
|
||||
self.session_key.as_deref()
|
||||
}
|
||||
|
||||
fn has_failures(&self) -> bool {
|
||||
!self.state.failed_account_ids.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// 识别失败、维护会话状态,并为下一次请求生成账号排除集合。
|
||||
#[derive(Clone)]
|
||||
pub(in crate::dispatch) struct CyberPolicyController {
|
||||
store: Store,
|
||||
}
|
||||
|
||||
/// 已由 Cyber owner 认领的失败;调用方只能请求 owner 产生 effect 或 decision。
|
||||
pub(super) struct ClassifiedCyberPolicyFailure<'a> {
|
||||
fact: ControllerFailureFact<'a>,
|
||||
}
|
||||
|
||||
impl CyberPolicyController {
|
||||
pub(in crate::dispatch) fn new(session_affinity: Arc<SessionAffinityService>) -> Self {
|
||||
Self {
|
||||
store: Store::new(session_affinity.redis_connection()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn classify(
|
||||
fact: ControllerFailureFact<'_>,
|
||||
) -> Option<ClassifiedCyberPolicyFailure<'_>> {
|
||||
let owned = match fact {
|
||||
ControllerFailureFact::Upstream(facts) => {
|
||||
facts
|
||||
.status_code
|
||||
.is_some_and(|status| (400..=499).contains(&status))
|
||||
&& is_cyber_policy_code(facts.code.as_deref())
|
||||
}
|
||||
ControllerFailureFact::Response(failure) => is_cyber_policy_failure(failure),
|
||||
};
|
||||
owned.then_some(ClassifiedCyberPolicyFailure { fact })
|
||||
}
|
||||
|
||||
pub(super) fn client_failure(classified: &ClassifiedCyberPolicyFailure<'_>) -> ClientFailure {
|
||||
match classified.fact {
|
||||
ControllerFailureFact::Upstream(facts) => ClientFailure::new(
|
||||
failure_from_upstream_facts(facts),
|
||||
facts.status_code.unwrap_or(400),
|
||||
true,
|
||||
),
|
||||
ControllerFailureFact::Response(failure) => {
|
||||
ClientFailure::new(failure.clone(), 400, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn decision(
|
||||
observation: &AttemptObservation,
|
||||
classified: ClassifiedCyberPolicyFailure<'_>,
|
||||
) -> AttemptDecision {
|
||||
let client_failure = Self::client_failure(&classified);
|
||||
if observation.routing.can_retry_next_candidate {
|
||||
AttemptDecision::RetryNextCandidate {
|
||||
exhaustion: None,
|
||||
on_exhaustion: Some(client_failure),
|
||||
}
|
||||
} else {
|
||||
AttemptDecision::Return(AttemptReturnKind::Failed(client_failure))
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn prepare(
|
||||
&self,
|
||||
request: &CodexResponsesRequest,
|
||||
) -> CyberPolicyScope {
|
||||
let Some(session_key) = session_key(request) else {
|
||||
return CyberPolicyScope {
|
||||
session_key: None,
|
||||
state: SessionState::default(),
|
||||
};
|
||||
};
|
||||
let state = match timeout(STATE_IO_TIMEOUT, self.store.load(&session_key)).await {
|
||||
Ok(Ok(state)) => state.unwrap_or_default(),
|
||||
Ok(Err(error)) => {
|
||||
tracing::warn!(error = %error, "Failed to read cyber policy session state");
|
||||
SessionState::default()
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::warn!("Timed out reading cyber policy session state");
|
||||
SessionState::default()
|
||||
}
|
||||
};
|
||||
CyberPolicyScope {
|
||||
session_key: Some(session_key),
|
||||
state,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn exclude_account(&self, plan: &CyberPolicyScope, account_id: &str) {
|
||||
let Some(session_key) = plan.session_key() else {
|
||||
return;
|
||||
};
|
||||
match timeout(
|
||||
STATE_IO_TIMEOUT,
|
||||
self.store
|
||||
.record_failure(session_key, account_id, SESSION_STATE_TTL),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(state)) => tracing::warn!(
|
||||
account_id,
|
||||
excluded_account_count = state.failed_account_ids.len(),
|
||||
"Excluded cyber policy account from this session"
|
||||
),
|
||||
Ok(Err(error)) => tracing::warn!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"Failed to record cyber policy session state"
|
||||
),
|
||||
Err(_) => tracing::warn!(account_id, "Timed out recording cyber policy session state"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn observe_success(&self, plan: &CyberPolicyScope) {
|
||||
if !plan.has_failures() {
|
||||
return;
|
||||
}
|
||||
let Some(session_key) = plan.session_key() else {
|
||||
return;
|
||||
};
|
||||
match timeout(
|
||||
STATE_IO_TIMEOUT,
|
||||
self.store.clear(session_key, &plan.state.revision),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(_)) => {}
|
||||
Ok(Err(error)) => {
|
||||
tracing::warn!(error = %error, "Failed to clear cyber policy session state");
|
||||
}
|
||||
Err(_) => tracing::warn!("Timed out clearing cyber policy session state"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn session_key(request: &CodexResponsesRequest) -> Option<String> {
|
||||
if request.previous_response_id().is_some() {
|
||||
return None;
|
||||
}
|
||||
let api_key_id = non_empty(request.client_api_key_id.as_deref())?;
|
||||
let explicit_session_id = non_empty(request.client_session_id.as_deref())
|
||||
.or_else(|| non_empty(request.client_conversation_id.as_deref()))
|
||||
.or_else(|| {
|
||||
request
|
||||
.explicit_prompt_cache_key
|
||||
.then(|| non_empty(request.prompt_cache_key()))
|
||||
.flatten()
|
||||
})?;
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(b"cyber-policy-session\0");
|
||||
hasher.update(api_key_id.as_bytes());
|
||||
hasher.update(b"\0");
|
||||
hasher.update(explicit_session_id.as_bytes());
|
||||
Some(hex::encode(hasher.finalize()))
|
||||
}
|
||||
|
||||
fn is_cyber_policy_code(code: Option<&str>) -> bool {
|
||||
code.is_some_and(|code| code.trim().eq_ignore_ascii_case("cyber_policy"))
|
||||
}
|
||||
|
||||
fn failure_from_upstream_facts(facts: &UpstreamFailureFacts) -> ResponsesSseFailure {
|
||||
ResponsesSseFailure {
|
||||
event: "error".to_string(),
|
||||
message: facts.message.clone(),
|
||||
upstream_code: facts.code.clone(),
|
||||
upstream_type: None,
|
||||
explicit_status_code: facts.status_code,
|
||||
retry_after_seconds: facts.retry_after_seconds,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn is_cyber_policy_failure(failure: &ResponsesSseFailure) -> bool {
|
||||
is_cyber_policy_code(failure.upstream_code.as_deref())
|
||||
}
|
||||
|
||||
fn non_empty(value: Option<&str>) -> Option<&str> {
|
||||
value.map(str::trim).filter(|value| !value.is_empty())
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
use chrono::Duration;
|
||||
use redis::AsyncCommands;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::infra::redis::RedisConnection;
|
||||
|
||||
use super::types::SessionState;
|
||||
|
||||
const STATE_VERSION: &str = "cyber-policy:v2";
|
||||
|
||||
const RECORD_FAILURE_SCRIPT: &str = r#"
|
||||
local raw = redis.call('GET', KEYS[1])
|
||||
local state = { failedAccountIds = {}, revision = '' }
|
||||
if raw then
|
||||
local ok, decoded = pcall(cjson.decode, raw)
|
||||
if ok and type(decoded) == 'table' and type(decoded.failedAccountIds) == 'table' then
|
||||
state = decoded
|
||||
end
|
||||
end
|
||||
|
||||
local account_id = ARGV[1]
|
||||
local known = false
|
||||
for _, failed_account_id in ipairs(state.failedAccountIds) do
|
||||
if failed_account_id == account_id then
|
||||
known = true
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
if not known then
|
||||
table.insert(state.failedAccountIds, account_id)
|
||||
end
|
||||
|
||||
state.revision = ARGV[3]
|
||||
|
||||
local encoded = cjson.encode(state)
|
||||
redis.call('SET', KEYS[1], encoded, 'EX', tonumber(ARGV[2]))
|
||||
return encoded
|
||||
"#;
|
||||
|
||||
const CLEAR_STATE_SCRIPT: &str = r#"
|
||||
local raw = redis.call('GET', KEYS[1])
|
||||
if not raw then
|
||||
return 0
|
||||
end
|
||||
local ok, state = pcall(cjson.decode, raw)
|
||||
if not ok or type(state) ~= 'table' then
|
||||
return 0
|
||||
end
|
||||
if tostring(state.revision or '') ~= ARGV[1] then
|
||||
return 0
|
||||
end
|
||||
return redis.call('DEL', KEYS[1])
|
||||
"#;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Store {
|
||||
redis: RedisConnection,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum StoreError {
|
||||
#[error("Redis cyber policy operation failed: {0}")]
|
||||
Redis(#[from] redis::RedisError),
|
||||
#[error("invalid Redis cyber policy value: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn new(redis: RedisConnection) -> Self {
|
||||
Self { redis }
|
||||
}
|
||||
|
||||
pub async fn load(&self, session_key: &str) -> Result<Option<SessionState>, StoreError> {
|
||||
let mut connection = self.redis.manager();
|
||||
let value: Option<String> = connection.get(self.key(session_key)).await?;
|
||||
value
|
||||
.map(|value| serde_json::from_str(&value))
|
||||
.transpose()
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
pub async fn record_failure(
|
||||
&self,
|
||||
session_key: &str,
|
||||
account_id: &str,
|
||||
ttl: Duration,
|
||||
) -> Result<SessionState, StoreError> {
|
||||
let mut connection = self.redis.manager();
|
||||
let revision = uuid::Uuid::new_v4().to_string();
|
||||
let value: String = redis::Script::new(RECORD_FAILURE_SCRIPT)
|
||||
.key(self.key(session_key))
|
||||
.arg(account_id)
|
||||
.arg(ttl.num_seconds().max(1))
|
||||
.arg(revision)
|
||||
.invoke_async(&mut connection)
|
||||
.await?;
|
||||
Ok(serde_json::from_str(&value)?)
|
||||
}
|
||||
|
||||
pub async fn clear(
|
||||
&self,
|
||||
session_key: &str,
|
||||
expected_revision: &str,
|
||||
) -> Result<bool, StoreError> {
|
||||
let mut connection = self.redis.manager();
|
||||
let removed: usize = redis::Script::new(CLEAR_STATE_SCRIPT)
|
||||
.key(self.key(session_key))
|
||||
.arg(expected_revision)
|
||||
.invoke_async(&mut connection)
|
||||
.await?;
|
||||
Ok(removed > 0)
|
||||
}
|
||||
|
||||
fn key(&self, session_key: &str) -> String {
|
||||
self.redis
|
||||
.key(&format!("{STATE_VERSION}:session:{session_key}"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SessionState {
|
||||
pub failed_account_ids: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub revision: String,
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
//! previous response 所有权、重放与恢复规则的唯一 owner。
|
||||
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use chrono::Utc;
|
||||
use serde_json::Value;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
affinity::{SessionAffinityEntry, SessionAffinityService},
|
||||
lifecycle::contract::{
|
||||
AttemptDecision, AttemptObservation, AttemptObservationKind, AttemptReturnKind,
|
||||
AttemptRoutingFacts, CompleteResponseFacts, PinnedCandidateAcquireFailureKind,
|
||||
},
|
||||
transport::observation::{UpstreamFailureFacts, UpstreamFailureKind},
|
||||
},
|
||||
upstream::openai::{
|
||||
protocol::responses::{CodexResponsesRequest, PreviousResponseScope, StreamCommitPolicy},
|
||||
transport::CodexBackendTransport,
|
||||
transport::websocket::PreviousResponseUnavailableReason,
|
||||
},
|
||||
};
|
||||
|
||||
const REDIS_BEST_EFFORT_TIMEOUT: Duration = Duration::from_millis(100);
|
||||
const CROSS_ACCOUNT_HISTORY_UNAVAILABLE_MESSAGE: &str =
|
||||
"previous response history cannot be sent to another account";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum HistorySource {
|
||||
None,
|
||||
Managed,
|
||||
ConnectionLocal,
|
||||
ExternalUnknown,
|
||||
}
|
||||
|
||||
/// 单个请求内的 previous response 状态;策略只由 `HistoryController` 解释。
|
||||
pub(super) struct HistoryState {
|
||||
source: HistorySource,
|
||||
managed_entry: Option<SessionAffinityEntry>,
|
||||
local_replay_input: Option<Arc<Vec<Value>>>,
|
||||
external_attempted_account_id: Option<String>,
|
||||
replay_owner_account: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(in crate::dispatch) struct ConnectionReplaySnapshot {
|
||||
last_response_id: Option<String>,
|
||||
input: Option<Arc<Vec<Value>>>,
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) struct ConnectionReplayPlan {
|
||||
update: ConnectionReplayUpdate,
|
||||
}
|
||||
|
||||
enum ConnectionReplayUpdate {
|
||||
Replace(Vec<Value>),
|
||||
Append {
|
||||
history: Arc<Vec<Value>>,
|
||||
input: Vec<Value>,
|
||||
},
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) struct HistoryController;
|
||||
|
||||
impl HistoryController {
|
||||
pub(in crate::dispatch) fn new_connection_replay_snapshot() -> ConnectionReplaySnapshot {
|
||||
ConnectionReplaySnapshot::default()
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn prepare_connection_replay(
|
||||
snapshot: &ConnectionReplaySnapshot,
|
||||
request: &mut CodexResponsesRequest,
|
||||
) -> ConnectionReplayPlan {
|
||||
let turn_input = request.input().to_vec();
|
||||
let update = match request.previous_response_id() {
|
||||
None => {
|
||||
request.local_replay_input = None;
|
||||
ConnectionReplayUpdate::Replace(turn_input)
|
||||
}
|
||||
Some(previous_response_id)
|
||||
if snapshot.last_response_id.as_deref() == Some(previous_response_id) =>
|
||||
{
|
||||
if let Some(history) = snapshot.input.as_ref() {
|
||||
request.local_replay_input = Some(Arc::clone(history));
|
||||
ConnectionReplayUpdate::Append {
|
||||
history: Arc::clone(history),
|
||||
input: turn_input,
|
||||
}
|
||||
} else {
|
||||
request.local_replay_input = None;
|
||||
ConnectionReplayUpdate::Unavailable
|
||||
}
|
||||
}
|
||||
Some(_) => {
|
||||
request.local_replay_input = None;
|
||||
ConnectionReplayUpdate::Unavailable
|
||||
}
|
||||
};
|
||||
request.local_replay_available = !matches!(update, ConnectionReplayUpdate::Unavailable);
|
||||
ConnectionReplayPlan { update }
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn commit_connection_replay(
|
||||
snapshot: &mut ConnectionReplaySnapshot,
|
||||
plan: ConnectionReplayPlan,
|
||||
response_id: String,
|
||||
output: Vec<Value>,
|
||||
) {
|
||||
snapshot.last_response_id = Some(response_id);
|
||||
match plan.update {
|
||||
ConnectionReplayUpdate::Replace(input) => {
|
||||
snapshot.input = Some(Arc::new(sanitized_transcript(input, output)));
|
||||
}
|
||||
ConnectionReplayUpdate::Append { mut history, input } => {
|
||||
let mut turn = sanitized_transcript(input, output);
|
||||
Arc::make_mut(&mut history).append(&mut turn);
|
||||
snapshot.input = Some(history);
|
||||
}
|
||||
ConnectionReplayUpdate::Unavailable => snapshot.input = None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn enter(
|
||||
affinity: &SessionAffinityService,
|
||||
request: &CodexResponsesRequest,
|
||||
) -> HistoryState {
|
||||
let Some(previous_response_id) = request.previous_response_id() else {
|
||||
return HistoryState::empty();
|
||||
};
|
||||
let managed_entry = match timeout(
|
||||
REDIS_BEST_EFFORT_TIMEOUT,
|
||||
affinity.lookup(previous_response_id, Utc::now()),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(entry) => entry,
|
||||
Err(_) => {
|
||||
tracing::warn!(
|
||||
previous_response_id,
|
||||
timeout_ms = REDIS_BEST_EFFORT_TIMEOUT.as_millis(),
|
||||
"Timed out reading previous response affinity; continuing without managed history"
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
let local_replay_input = request.local_replay_input.clone();
|
||||
let source = match (&managed_entry, &local_replay_input) {
|
||||
(Some(_), _) => HistorySource::Managed,
|
||||
(None, Some(_)) => HistorySource::ConnectionLocal,
|
||||
(None, None) => HistorySource::ExternalUnknown,
|
||||
};
|
||||
HistoryState {
|
||||
source,
|
||||
managed_entry,
|
||||
local_replay_input,
|
||||
external_attempted_account_id: None,
|
||||
replay_owner_account: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn preferred_account_id(state: &HistoryState) -> Option<&str> {
|
||||
state
|
||||
.managed_entry
|
||||
.as_ref()
|
||||
.map(|entry| entry.account_id.as_str())
|
||||
}
|
||||
|
||||
pub(super) fn prepare_attempt(
|
||||
state: &mut HistoryState,
|
||||
request: &CodexResponsesRequest,
|
||||
account_id: &str,
|
||||
) -> Result<CodexResponsesRequest, String> {
|
||||
let prepared = match state.source {
|
||||
HistorySource::None => Some(request.clone()),
|
||||
HistorySource::ExternalUnknown => {
|
||||
match state.external_attempted_account_id.as_deref() {
|
||||
None => {
|
||||
state.external_attempted_account_id = Some(account_id.to_string());
|
||||
Some(external_history_request(request))
|
||||
}
|
||||
Some(first_account_id) if first_account_id == account_id => {
|
||||
Some(external_history_request(request))
|
||||
}
|
||||
Some(_) => None,
|
||||
}
|
||||
}
|
||||
HistorySource::ConnectionLocal => state
|
||||
.local_replay_input
|
||||
.as_deref()
|
||||
.map(|replay_input| full_replay_request(request, replay_input)),
|
||||
HistorySource::Managed => prepare_managed_attempt(state, request, account_id),
|
||||
};
|
||||
prepared.ok_or_else(|| CROSS_ACCOUNT_HISTORY_UNAVAILABLE_MESSAGE.to_string())
|
||||
}
|
||||
|
||||
pub(super) fn prepare_same_account_retry(state: &mut HistoryState, account_id: &str) -> bool {
|
||||
if !Self::can_retry_same_account(state, account_id) {
|
||||
return false;
|
||||
}
|
||||
state.replay_owner_account = true;
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn routing_facts(
|
||||
state: &HistoryState,
|
||||
account_id: Option<&str>,
|
||||
) -> AttemptRoutingFacts {
|
||||
AttemptRoutingFacts {
|
||||
external_origin: state.source == HistorySource::ExternalUnknown,
|
||||
can_retry_same_account: account_id
|
||||
.is_some_and(|account_id| Self::can_retry_same_account(state, account_id)),
|
||||
can_retry_next_candidate: match state.source {
|
||||
HistorySource::None | HistorySource::ConnectionLocal => true,
|
||||
HistorySource::Managed => state.local_replay_input.is_some(),
|
||||
HistorySource::ExternalUnknown => false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn conversation_id<'a>(
|
||||
state: &'a HistoryState,
|
||||
request: &'a CodexResponsesRequest,
|
||||
) -> Option<&'a str> {
|
||||
state
|
||||
.managed_entry
|
||||
.as_ref()
|
||||
.map(|entry| entry.conversation_id.as_str())
|
||||
.or_else(|| non_empty(request.local_conversation_id.as_deref()))
|
||||
}
|
||||
|
||||
pub(super) fn decide(observation: &AttemptObservation) -> Option<AttemptDecision> {
|
||||
if let AttemptObservationKind::PinnedCandidateUnavailable { kind, .. } = observation.kind {
|
||||
return Some(match kind {
|
||||
PinnedCandidateAcquireFailureKind::Busy => {
|
||||
AttemptDecision::Return(AttemptReturnKind::ContinuationBusy)
|
||||
}
|
||||
PinnedCandidateAcquireFailureKind::Unavailable => {
|
||||
AttemptDecision::Return(AttemptReturnKind::RouteUnavailable {
|
||||
message: "the account that owns the previous response is unavailable for same-account recovery".to_string(),
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
let detail = match &observation.kind {
|
||||
AttemptObservationKind::UpstreamFailure(facts) if is_continuation_busy(facts) => {
|
||||
if observation.routing.can_retry_same_account {
|
||||
return Some(AttemptDecision::RetrySameAccount);
|
||||
}
|
||||
return Some(AttemptDecision::Return(AttemptReturnKind::ContinuationBusy));
|
||||
}
|
||||
AttemptObservationKind::UpstreamFailure(facts) if is_history_failure(facts) => {
|
||||
facts.body.clone()
|
||||
}
|
||||
AttemptObservationKind::CompleteResponse(CompleteResponseFacts::Failed(failure))
|
||||
| AttemptObservationKind::StreamFailure(failure)
|
||||
if is_history_code(failure.upstream_code.as_deref()) =>
|
||||
{
|
||||
crate::dispatch::failure::sse::sse_failure_error_body(failure)
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
if observation.routing.can_retry_same_account {
|
||||
return Some(AttemptDecision::RetrySameAccount);
|
||||
}
|
||||
if observation.routing.external_origin {
|
||||
return Some(AttemptDecision::Return(AttemptReturnKind::Observed));
|
||||
}
|
||||
Some(AttemptDecision::Return(
|
||||
AttemptReturnKind::RouteUnavailable { message: detail },
|
||||
))
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn continuation_scope(
|
||||
request: &CodexResponsesRequest,
|
||||
transport: CodexBackendTransport,
|
||||
connection_local_continuation: bool,
|
||||
) -> PreviousResponseScope {
|
||||
if request.store() {
|
||||
PreviousResponseScope::Persisted
|
||||
} else if transport == CodexBackendTransport::WebSocket && connection_local_continuation {
|
||||
PreviousResponseScope::ConnectionLocal
|
||||
} else if request.local_replay_available {
|
||||
PreviousResponseScope::ReplayRequired
|
||||
} else {
|
||||
PreviousResponseScope::Unavailable
|
||||
}
|
||||
}
|
||||
|
||||
fn can_retry_same_account(state: &HistoryState, account_id: &str) -> bool {
|
||||
let Some(entry) = state.managed_entry.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
entry.account_id == account_id
|
||||
&& state.local_replay_input.is_some()
|
||||
&& !state.replay_owner_account
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_managed_attempt(
|
||||
state: &HistoryState,
|
||||
request: &CodexResponsesRequest,
|
||||
account_id: &str,
|
||||
) -> Option<CodexResponsesRequest> {
|
||||
let entry = state.managed_entry.as_ref()?;
|
||||
if entry.account_id != account_id || state.replay_owner_account {
|
||||
return replay_for_conversation(state, request, &entry.conversation_id);
|
||||
}
|
||||
|
||||
match entry.continuation_scope {
|
||||
PreviousResponseScope::Persisted
|
||||
| PreviousResponseScope::ConnectionLocal
|
||||
| PreviousResponseScope::ExternalUnknown => {
|
||||
let mut prepared = request.clone();
|
||||
prepared.local_conversation_id = Some(entry.conversation_id.clone());
|
||||
prepared.stream_commit_policy = StreamCommitPolicy::UntilOutputOrTerminal;
|
||||
prepared.previous_response_scope = Some(entry.continuation_scope);
|
||||
if prepared.turn_state.as_deref().is_none_or(str::is_empty) {
|
||||
prepared.turn_state.clone_from(&entry.turn_state);
|
||||
}
|
||||
Some(prepared)
|
||||
}
|
||||
PreviousResponseScope::ReplayRequired => {
|
||||
replay_for_conversation(state, request, &entry.conversation_id)
|
||||
}
|
||||
PreviousResponseScope::Unavailable => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn replay_for_conversation(
|
||||
state: &HistoryState,
|
||||
request: &CodexResponsesRequest,
|
||||
conversation_id: &str,
|
||||
) -> Option<CodexResponsesRequest> {
|
||||
state.local_replay_input.as_deref().map(|replay_input| {
|
||||
let mut prepared = full_replay_request(request, replay_input);
|
||||
prepared.local_conversation_id = Some(conversation_id.to_string());
|
||||
prepared
|
||||
})
|
||||
}
|
||||
|
||||
impl HistoryState {
|
||||
fn empty() -> Self {
|
||||
Self {
|
||||
source: HistorySource::None,
|
||||
managed_entry: None,
|
||||
local_replay_input: None,
|
||||
external_attempted_account_id: None,
|
||||
replay_owner_account: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn external_history_request(original: &CodexResponsesRequest) -> CodexResponsesRequest {
|
||||
let mut request = original.clone();
|
||||
request.stream_commit_policy = StreamCommitPolicy::UntilOutputOrTerminal;
|
||||
request.previous_response_scope =
|
||||
Some(crate::upstream::openai::protocol::responses::PreviousResponseScope::ExternalUnknown);
|
||||
request
|
||||
}
|
||||
|
||||
fn full_replay_request(
|
||||
original: &CodexResponsesRequest,
|
||||
replay_input: &[Value],
|
||||
) -> CodexResponsesRequest {
|
||||
let mut request = original.clone();
|
||||
let mut input = Vec::with_capacity(replay_input.len() + original.input().len());
|
||||
input.extend_from_slice(replay_input);
|
||||
input.extend_from_slice(original.input());
|
||||
sanitize_replay_items(&mut input);
|
||||
request.set_input(input);
|
||||
request.set_previous_response_id(None);
|
||||
request.turn_state = None;
|
||||
request.stream_commit_policy = StreamCommitPolicy::UntilOutputOrTerminal;
|
||||
request
|
||||
}
|
||||
|
||||
fn sanitized_transcript(mut input: Vec<Value>, mut output: Vec<Value>) -> Vec<Value> {
|
||||
sanitize_replay_items(&mut input);
|
||||
sanitize_replay_items(&mut output);
|
||||
input.append(&mut output);
|
||||
input
|
||||
}
|
||||
|
||||
fn sanitize_replay_items(values: &mut [Value]) {
|
||||
for value in values {
|
||||
match value {
|
||||
Value::Array(values) => sanitize_replay_items(values),
|
||||
Value::Object(object) => {
|
||||
object.remove("id");
|
||||
object.remove("encrypted_content");
|
||||
for value in object.values_mut() {
|
||||
sanitize_replay_items(std::slice::from_mut(value));
|
||||
}
|
||||
}
|
||||
Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_continuation_busy(facts: &UpstreamFailureFacts) -> bool {
|
||||
matches!(
|
||||
facts.kind,
|
||||
UpstreamFailureKind::ContinuationUnavailable(
|
||||
PreviousResponseUnavailableReason::ConnectionBusy
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
fn is_history_failure(facts: &UpstreamFailureFacts) -> bool {
|
||||
facts
|
||||
.code
|
||||
.as_deref()
|
||||
.is_some_and(|code| is_history_code(Some(code)))
|
||||
|| matches!(
|
||||
facts.kind,
|
||||
UpstreamFailureKind::ContinuationUnavailable(reason)
|
||||
if reason != PreviousResponseUnavailableReason::ConnectionBusy
|
||||
)
|
||||
}
|
||||
|
||||
fn is_history_code(code: Option<&str>) -> bool {
|
||||
matches!(
|
||||
code,
|
||||
Some(
|
||||
"previous_response_not_found"
|
||||
| "invalid_encrypted_content"
|
||||
| "missing_tool_output"
|
||||
| "no_tool_output"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
fn non_empty(value: Option<&str>) -> Option<&str> {
|
||||
value.map(str::trim).filter(|value| !value.is_empty())
|
||||
}
|
||||
@@ -0,0 +1,997 @@
|
||||
//! v1 请求生命周期控制器集合。
|
||||
//!
|
||||
//! 控制器集合是静态类型的 feature owner 边界:生命周期只依赖这里暴露的
|
||||
//! typed hook,不直接知道具体功能名称或状态存储实现。
|
||||
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
future::Future,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use tokio::time::timeout;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
affinity::{
|
||||
AccountIdentityScope, AccountIdentityService, AccountScopedRequest,
|
||||
SessionAffinityService,
|
||||
},
|
||||
errors::{ClientFailure, ResponseDispatchError, upstream_error_set_cookie_headers},
|
||||
lifecycle::trace::{ResponseDispatchAttempt, ResponseDispatchTrace},
|
||||
},
|
||||
fleet::{account::Account, pool::AccountLease},
|
||||
models::service::ModelService,
|
||||
telemetry::recorder::Recorder,
|
||||
upstream::openai::protocol::events::TokenUsage,
|
||||
upstream::openai::transport::{
|
||||
CodexBackendClient, CodexBackendResponse, CodexBackendTransport, CodexClientError,
|
||||
CodexRateLimitHeaderUpdates, CodexResponseMetadata, CodexTurnStateUpdate,
|
||||
CodexUpstreamDiagnostics, WebSocketPoolDecision,
|
||||
},
|
||||
};
|
||||
use crate::{
|
||||
dispatch::{
|
||||
controllers::cloudflare::CloudflareRecovery,
|
||||
controllers::cyber_policy::{
|
||||
ClassifiedCyberPolicyFailure, CyberPolicyController, CyberPolicyScope,
|
||||
},
|
||||
controllers::{
|
||||
account_failure::AccountFailureController, history::HistoryController,
|
||||
history::HistoryState, quota::QuotaController,
|
||||
},
|
||||
lifecycle::{
|
||||
contract::{
|
||||
AttemptDecision, AttemptObservation, AttemptObservationKind, AttemptReturnKind,
|
||||
AttemptRoutingFacts, FinalOutcome,
|
||||
},
|
||||
stream::StreamTerminal,
|
||||
},
|
||||
transport::observation::UpstreamFailureFacts,
|
||||
},
|
||||
fleet::pool::AccountPoolService,
|
||||
upstream::openai::protocol::responses::{CodexResponsesRequest, ResponsesSseFailure},
|
||||
};
|
||||
|
||||
mod account_failure;
|
||||
mod account_state;
|
||||
mod affinity;
|
||||
pub(crate) mod cloudflare;
|
||||
pub(crate) mod cyber_policy;
|
||||
pub(in crate::dispatch) mod history;
|
||||
mod quota;
|
||||
pub(in crate::dispatch) mod telemetry;
|
||||
mod usage;
|
||||
|
||||
const BEST_EFFORT_IO_TIMEOUT: Duration = Duration::from_millis(100);
|
||||
|
||||
pub(in crate::dispatch) struct CompleteExit<'a> {
|
||||
pub request: &'a CodexResponsesRequest,
|
||||
pub account_id: &'a str,
|
||||
pub body: &'a str,
|
||||
pub turn_state: Option<String>,
|
||||
pub usage: Option<TokenUsage>,
|
||||
pub image_generation_requested: bool,
|
||||
pub completed: bool,
|
||||
pub recorder: &'a Recorder,
|
||||
pub models: &'a ModelService,
|
||||
pub request_id: &'a str,
|
||||
pub route: &'a str,
|
||||
pub requested_model: &'a str,
|
||||
pub display_model: &'a str,
|
||||
pub started_at: Instant,
|
||||
pub response_id: Option<&'a str>,
|
||||
pub response: &'a CodexBackendResponse,
|
||||
pub trace: &'a ResponseDispatchTrace,
|
||||
pub attempt: &'a ResponseDispatchAttempt,
|
||||
}
|
||||
|
||||
/// 已提交 stream 在 controller 洋葱退出阶段消费的稳定事实。
|
||||
///
|
||||
/// 该上下文不包含 live transport 执行器、账号 lease 或 shutdown 控制器;各 feature
|
||||
/// owner 只能通过 `ControllerSet` 分发的窄 typed exit 读取所需字段。
|
||||
pub(in crate::dispatch) struct StreamControllerContext {
|
||||
pub account_id: String,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub request_id: String,
|
||||
pub route: String,
|
||||
pub display_model: String,
|
||||
pub requested_model: String,
|
||||
pub request: CodexResponsesRequest,
|
||||
pub transport: CodexBackendTransport,
|
||||
pub set_cookie_headers: Vec<String>,
|
||||
pub rate_limit_headers: Vec<(String, String)>,
|
||||
pub rate_limit_header_updates: Option<CodexRateLimitHeaderUpdates>,
|
||||
pub turn_state_update: Option<CodexTurnStateUpdate>,
|
||||
pub websocket_pool_decision: Option<WebSocketPoolDecision>,
|
||||
pub turn_state: Option<String>,
|
||||
pub diagnostics: CodexUpstreamDiagnostics,
|
||||
pub response_metadata: CodexResponseMetadata,
|
||||
pub transport_metrics: crate::upstream::openai::transport::CodexTransportMetrics,
|
||||
pub connection_local_continuation: bool,
|
||||
pub attempt: ResponseDispatchAttempt,
|
||||
pub attempts: Vec<ResponseDispatchAttempt>,
|
||||
pub started_at: Instant,
|
||||
}
|
||||
|
||||
/// 单次 attempt 的原始上游失败上下文。
|
||||
///
|
||||
/// 生命周期只负责把事实交给控制器集合;Cloudflare 状态与遥测记录分别由各自
|
||||
/// controller owner 消费,避免失败信息在最终 exhaustion 折叠时丢失。
|
||||
pub(in crate::dispatch) struct AttemptUpstreamErrorContext<'a> {
|
||||
pub request_id: &'a str,
|
||||
pub account: &'a Account,
|
||||
pub route: &'a str,
|
||||
pub model: &'a str,
|
||||
pub started_at: Instant,
|
||||
pub stream: bool,
|
||||
pub transport: crate::upstream::openai::transport::CodexBackendTransport,
|
||||
pub request: &'a CodexResponsesRequest,
|
||||
pub error: &'a CodexClientError,
|
||||
pub trace: &'a ResponseDispatchTrace,
|
||||
pub attempt: &'a ResponseDispatchAttempt,
|
||||
}
|
||||
|
||||
/// 请求在产生最终 dispatch error 后交给 telemetry owner 的稳定事实。
|
||||
pub(in crate::dispatch) struct DispatchErrorObservation<'a> {
|
||||
pub request_id: &'a str,
|
||||
pub client_api_key_id: Option<&'a str>,
|
||||
pub account_id: Option<&'a str>,
|
||||
pub route: &'a str,
|
||||
pub model: &'a str,
|
||||
pub started_at: Instant,
|
||||
pub stream: bool,
|
||||
pub compact: bool,
|
||||
pub transport: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// commit 前 stream failure 的 telemetry 事实;client status 已包含在 typed error 中。
|
||||
pub(in crate::dispatch) struct PrefetchedStreamFailureObservation<'a> {
|
||||
pub request_id: &'a str,
|
||||
pub account_id: &'a str,
|
||||
pub route: &'a str,
|
||||
pub model: &'a str,
|
||||
pub requested_model: &'a str,
|
||||
pub started_at: Instant,
|
||||
pub transport: CodexBackendTransport,
|
||||
pub request: &'a CodexResponsesRequest,
|
||||
pub failure: &'a ResponsesSseFailure,
|
||||
pub error: &'a ResponseDispatchError,
|
||||
pub diagnostics: &'a CodexUpstreamDiagnostics,
|
||||
pub rate_limit_headers: &'a [(String, String)],
|
||||
pub prefetched: &'a [u8],
|
||||
pub trace: &'a ResponseDispatchTrace,
|
||||
pub attempt: &'a ResponseDispatchAttempt,
|
||||
}
|
||||
|
||||
/// 所有 controller owner 共同消费的失败事实。
|
||||
///
|
||||
/// attempt 与 commit 后的 stream finalizer 都必须先归一为该类型,避免同一种
|
||||
/// 上游失败因发生阶段不同而漏掉 feature 副作用。
|
||||
#[derive(Clone, Copy)]
|
||||
enum ControllerFailureFact<'a> {
|
||||
Upstream(&'a UpstreamFailureFacts),
|
||||
Response(&'a ResponsesSseFailure),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum FailureObservation<'a> {
|
||||
Attempt(&'a AttemptObservation),
|
||||
Stream {
|
||||
account_id: &'a str,
|
||||
failure: &'a ResponsesSseFailure,
|
||||
},
|
||||
}
|
||||
|
||||
impl<'a> FailureObservation<'a> {
|
||||
fn fact(self) -> Option<ControllerFailureFact<'a>> {
|
||||
match self {
|
||||
Self::Attempt(observation) => ControllerFailureFact::from_attempt(observation),
|
||||
Self::Stream { failure, .. } => Some(ControllerFailureFact::Response(failure)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum SharedFailureClassification<'a> {
|
||||
CyberPolicy(ClassifiedCyberPolicyFailure<'a>),
|
||||
AccountFailure(account_failure::ClassifiedFailure),
|
||||
Quota(quota::ClassifiedQuotaFailure),
|
||||
}
|
||||
|
||||
impl<'a> ControllerFailureFact<'a> {
|
||||
fn from_attempt(observation: &'a AttemptObservation) -> Option<Self> {
|
||||
match &observation.kind {
|
||||
AttemptObservationKind::UpstreamFailure(facts) => Some(Self::Upstream(facts)),
|
||||
AttemptObservationKind::CompleteResponse(
|
||||
crate::dispatch::lifecycle::contract::CompleteResponseFacts::Failed(failure),
|
||||
)
|
||||
| AttemptObservationKind::StreamFailure(failure) => Some(Self::Response(failure)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 单次 attempt 的唯一分类结果;副作用与 decision 必须共同消费这个值。
|
||||
enum AttemptClassification<'a> {
|
||||
Shared(SharedFailureClassification<'a>),
|
||||
Cloudflare(cloudflare::CloudflareFailure),
|
||||
History(AttemptDecision),
|
||||
Default(AttemptDecision),
|
||||
}
|
||||
|
||||
struct StreamFailureClassification<'a> {
|
||||
failure: &'a ResponsesSseFailure,
|
||||
owner: Option<SharedFailureClassification<'a>>,
|
||||
}
|
||||
|
||||
impl StreamFailureClassification<'_> {
|
||||
fn client_failure(&self) -> ClientFailure {
|
||||
match &self.owner {
|
||||
Some(SharedFailureClassification::CyberPolicy(classified)) => {
|
||||
CyberPolicyController::client_failure(classified)
|
||||
}
|
||||
Some(SharedFailureClassification::AccountFailure(classified)) => {
|
||||
AccountFailureController::client_failure(classified, self.failure)
|
||||
}
|
||||
Some(SharedFailureClassification::Quota(_)) => {
|
||||
QuotaController::client_failure(self.failure)
|
||||
}
|
||||
None => default_response_client_failure(self.failure),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 请求级控制器集合。使用具体类型而非动态 middleware 链,保证调用顺序和所有权可见。
|
||||
#[derive(Clone)]
|
||||
pub(in crate::dispatch) struct ControllerSet {
|
||||
cyber_policy: CyberPolicyController,
|
||||
session_affinity: Arc<SessionAffinityService>,
|
||||
account_pool: Arc<AccountPoolService>,
|
||||
codex: Arc<CodexBackendClient>,
|
||||
cloudflare: CloudflareRecovery,
|
||||
recorder: Arc<Recorder>,
|
||||
}
|
||||
|
||||
/// 控制器在单个请求中的不可变状态快照。
|
||||
pub(in crate::dispatch) struct ControllerRequestScope {
|
||||
cyber_policy: CyberPolicyScope,
|
||||
history: HistoryState,
|
||||
identity: AccountIdentityScope,
|
||||
usage: usage::UsageScope,
|
||||
}
|
||||
|
||||
/// 请求 enter 阶段的控制器结果。
|
||||
pub(in crate::dispatch) struct ControllerEnter {
|
||||
pub scope: ControllerRequestScope,
|
||||
pub preferred_account_id: Option<String>,
|
||||
pub excluded_account_ids: BTreeSet<String>,
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) struct AttemptAccountPreparationContext<'a> {
|
||||
pub codex: &'a CodexBackendClient,
|
||||
pub account_identity: &'a AccountIdentityService,
|
||||
pub request_id: &'a str,
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) struct PreparedAttemptAccount {
|
||||
pub lease: AccountLease,
|
||||
pub cookie_header: Option<String>,
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) enum AttemptAccountPreparation {
|
||||
Ready(Box<PreparedAttemptAccount>),
|
||||
Rejected,
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) struct AttemptRoutePreparationContext<'a> {
|
||||
pub account_identity: &'a AccountIdentityService,
|
||||
pub account_id: &'a str,
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) enum AttemptRoutePreparation {
|
||||
Ready(Box<AccountScopedRequest>),
|
||||
Unavailable { message: String },
|
||||
}
|
||||
|
||||
impl ControllerSet {
|
||||
pub(in crate::dispatch) async fn prepare_attempt_account(
|
||||
&self,
|
||||
context: AttemptAccountPreparationContext<'_>,
|
||||
acquired: AccountLease,
|
||||
) -> AttemptAccountPreparation {
|
||||
let usage_cookie = self
|
||||
.cloudflare
|
||||
.cookie_header_for_request(&acquired.account.id, "/codex/usage")
|
||||
.await;
|
||||
let acquired = match QuotaController::enter(
|
||||
quota::QuotaEnterContext {
|
||||
account_pool: &self.account_pool,
|
||||
codex: context.codex,
|
||||
cookie_header: usage_cookie.as_deref(),
|
||||
account_identity: context.account_identity,
|
||||
request_id: context.request_id,
|
||||
},
|
||||
acquired,
|
||||
)
|
||||
.await
|
||||
{
|
||||
quota::QuotaEnterOutcome::Ready(acquired) => *acquired,
|
||||
quota::QuotaEnterOutcome::LimitReached => {
|
||||
return AttemptAccountPreparation::Rejected;
|
||||
}
|
||||
};
|
||||
let cookie_header = self
|
||||
.cloudflare
|
||||
.cookie_header_for_request(&acquired.account.id, "/codex/responses")
|
||||
.await;
|
||||
AttemptAccountPreparation::Ready(Box::new(PreparedAttemptAccount {
|
||||
lease: acquired,
|
||||
cookie_header,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn prepare_attempt_route(
|
||||
&self,
|
||||
scope: &mut ControllerRequestScope,
|
||||
request: &CodexResponsesRequest,
|
||||
context: AttemptRoutePreparationContext<'_>,
|
||||
) -> AttemptRoutePreparation {
|
||||
let request = match HistoryController::prepare_attempt(
|
||||
&mut scope.history,
|
||||
request,
|
||||
context.account_id,
|
||||
) {
|
||||
Ok(request) => request,
|
||||
Err(message) => return AttemptRoutePreparation::Unavailable { message },
|
||||
};
|
||||
AttemptRoutePreparation::Ready(Box::new(context.account_identity.scope_request(
|
||||
&mut scope.identity,
|
||||
request,
|
||||
context.account_id,
|
||||
)))
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn prepare_same_account_retry(
|
||||
&self,
|
||||
scope: &mut ControllerRequestScope,
|
||||
account_id: &str,
|
||||
) -> bool {
|
||||
HistoryController::prepare_same_account_retry(&mut scope.history, account_id)
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn attempt_routing_facts(
|
||||
&self,
|
||||
scope: &ControllerRequestScope,
|
||||
account_id: Option<&str>,
|
||||
) -> AttemptRoutingFacts {
|
||||
HistoryController::routing_facts(&scope.history, account_id)
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn observe_complete_upstream(
|
||||
&self,
|
||||
account: &Account,
|
||||
set_cookie_headers: &[String],
|
||||
rate_limit_headers: &[(String, String)],
|
||||
) {
|
||||
let _ = best_effort_controller_io(
|
||||
"cookie.complete",
|
||||
self.cloudflare
|
||||
.capture_set_cookie_headers(&account.id, set_cookie_headers),
|
||||
)
|
||||
.await;
|
||||
let _ = best_effort_controller_io(
|
||||
"quota.complete_headers",
|
||||
self.account_pool
|
||||
.sync_passive_rate_limit_headers(account, rate_limit_headers),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn observe_upstream_error(
|
||||
&self,
|
||||
context: AttemptUpstreamErrorContext<'_>,
|
||||
) {
|
||||
let _ = best_effort_controller_io(
|
||||
"cookie.attempt_error",
|
||||
self.cloudflare.capture_set_cookie_headers(
|
||||
&context.account.id,
|
||||
upstream_error_set_cookie_headers(context.error),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let _ = best_effort_controller_io(
|
||||
"telemetry.attempt_error",
|
||||
telemetry::TelemetryController::observe_upstream_error(&self.recorder, &context),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn observe_dispatch_error(
|
||||
&self,
|
||||
observation: DispatchErrorObservation<'_>,
|
||||
error: &ResponseDispatchError,
|
||||
) {
|
||||
let _ = best_effort_controller_io(
|
||||
"telemetry.dispatch_error",
|
||||
telemetry::TelemetryController::observe_dispatch_error(
|
||||
&self.recorder,
|
||||
observation,
|
||||
error,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn observe_prefetched_stream_failure(
|
||||
&self,
|
||||
observation: PrefetchedStreamFailureObservation<'_>,
|
||||
) {
|
||||
let _ = best_effort_controller_io(
|
||||
"telemetry.prefetched_failure",
|
||||
telemetry::TelemetryController::observe_prefetched_stream_failure(
|
||||
&self.recorder,
|
||||
observation,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn finalize_complete(
|
||||
&self,
|
||||
scope: ControllerRequestScope,
|
||||
exit: CompleteExit<'_>,
|
||||
outcome: FinalOutcome,
|
||||
) {
|
||||
let successful = matches!(outcome, FinalOutcome::Completed | FinalOutcome::Incomplete);
|
||||
if successful {
|
||||
let _ = best_effort_controller_io(
|
||||
"cloudflare.complete",
|
||||
cloudflare::CloudflareController::leave_complete(&self.cloudflare, exit.account_id),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
if successful {
|
||||
let _ = best_effort_controller_io(
|
||||
"usage.complete",
|
||||
usage::UsageController::leave_complete(
|
||||
&self.account_pool,
|
||||
exit.account_id,
|
||||
exit.usage,
|
||||
exit.image_generation_requested,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if exit.completed {
|
||||
let conversation_id = HistoryController::conversation_id(&scope.history, exit.request);
|
||||
let continuation_scope = HistoryController::continuation_scope(
|
||||
exit.request,
|
||||
exit.response.transport,
|
||||
exit.response.connection_local_continuation,
|
||||
);
|
||||
let _ = best_effort_controller_io(
|
||||
"affinity.complete",
|
||||
affinity::AffinityController::leave_complete(affinity::ResponseExit {
|
||||
affinity: &self.session_affinity,
|
||||
conversation_id,
|
||||
request: exit.request,
|
||||
account_id: exit.account_id,
|
||||
body: exit.body,
|
||||
turn_state: exit.turn_state.clone(),
|
||||
usage: exit.usage,
|
||||
continuation_scope,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if successful {
|
||||
let _ = best_effort_controller_io(
|
||||
"telemetry.complete",
|
||||
telemetry::TelemetryController::leave_complete(&exit),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
exit.models
|
||||
.observe_models_etag(exit.response.response_metadata.models_etag.as_deref());
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn new(
|
||||
session_affinity: Arc<crate::dispatch::affinity::SessionAffinityService>,
|
||||
account_pool: Arc<AccountPoolService>,
|
||||
codex: Arc<CodexBackendClient>,
|
||||
cloudflare: CloudflareRecovery,
|
||||
recorder: Arc<Recorder>,
|
||||
) -> Self {
|
||||
Self {
|
||||
cyber_policy: CyberPolicyController::new(Arc::clone(&session_affinity)),
|
||||
session_affinity,
|
||||
account_pool,
|
||||
codex,
|
||||
cloudflare,
|
||||
recorder,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn enter(
|
||||
&self,
|
||||
request: &CodexResponsesRequest,
|
||||
now: DateTime<Utc>,
|
||||
) -> ControllerEnter {
|
||||
let usage = usage::UsageController::enter(request);
|
||||
let (history, cyber_policy, affinity_preferred_account_id) = tokio::join!(
|
||||
HistoryController::enter(&self.session_affinity, request),
|
||||
self.cyber_policy.prepare(request),
|
||||
affinity::AffinityController::preferred_account_id(
|
||||
&self.session_affinity,
|
||||
request,
|
||||
now,
|
||||
),
|
||||
);
|
||||
let preferred_account_id = HistoryController::preferred_account_id(&history)
|
||||
.map(str::to_owned)
|
||||
.or(affinity_preferred_account_id);
|
||||
let excluded_account_ids = cyber_policy.excluded_account_ids();
|
||||
ControllerEnter {
|
||||
scope: ControllerRequestScope {
|
||||
cyber_policy,
|
||||
history,
|
||||
identity: AccountIdentityScope::new(preferred_account_id.clone()),
|
||||
usage,
|
||||
},
|
||||
preferred_account_id,
|
||||
excluded_account_ids,
|
||||
}
|
||||
}
|
||||
|
||||
async fn finalize_stream_success(
|
||||
&self,
|
||||
scope: &ControllerRequestScope,
|
||||
terminal: &StreamTerminal,
|
||||
) {
|
||||
match terminal {
|
||||
StreamTerminal::Completed { response } | StreamTerminal::Incomplete { response }
|
||||
if response.is_object() =>
|
||||
{
|
||||
self.cyber_policy.observe_success(&scope.cyber_policy).await
|
||||
}
|
||||
StreamTerminal::Completed { .. }
|
||||
| StreamTerminal::Incomplete { .. }
|
||||
| StreamTerminal::Failed { .. }
|
||||
| StreamTerminal::UpstreamClosed
|
||||
| StreamTerminal::UpstreamError { .. }
|
||||
| StreamTerminal::ProtocolError { .. }
|
||||
| StreamTerminal::CaptureLimitExceeded
|
||||
| StreamTerminal::Cancelled
|
||||
| StreamTerminal::DownstreamClosed
|
||||
| StreamTerminal::Shutdown => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_stream_failure<'a>(
|
||||
&self,
|
||||
account_id: &'a str,
|
||||
failure: &'a ResponsesSseFailure,
|
||||
) -> StreamFailureClassification<'a> {
|
||||
StreamFailureClassification {
|
||||
failure,
|
||||
owner: Self::classify_shared_failure(FailureObservation::Stream {
|
||||
account_id,
|
||||
failure,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
async fn apply_stream_account_state(&self, classification: &StreamFailureClassification<'_>) {
|
||||
match classification.owner.as_ref() {
|
||||
Some(SharedFailureClassification::AccountFailure(classified)) => {
|
||||
AccountFailureController::apply_effect(&self.account_pool, &self.codex, classified)
|
||||
.await;
|
||||
}
|
||||
Some(SharedFailureClassification::Quota(classified)) => {
|
||||
QuotaController::apply_effect(&self.account_pool, &self.codex, classified).await;
|
||||
}
|
||||
Some(SharedFailureClassification::CyberPolicy(_)) | None => {}
|
||||
}
|
||||
}
|
||||
|
||||
async fn apply_stream_policy_failure(
|
||||
&self,
|
||||
scope: &ControllerRequestScope,
|
||||
account_id: &str,
|
||||
classification: &StreamFailureClassification<'_>,
|
||||
) {
|
||||
if matches!(
|
||||
classification.owner,
|
||||
Some(SharedFailureClassification::CyberPolicy(_))
|
||||
) {
|
||||
self.cyber_policy
|
||||
.exclude_account(&scope.cyber_policy, account_id)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// 按固定的反向 leave 顺序收敛 stream 终态;生命周期只调用这一 typed exit。
|
||||
pub(in crate::dispatch) async fn leave_stream(
|
||||
&self,
|
||||
scope: ControllerRequestScope,
|
||||
context: StreamControllerContext,
|
||||
summary: &crate::dispatch::lifecycle::stream::StreamSummary,
|
||||
body: &str,
|
||||
) {
|
||||
let stream_failure = match &summary.terminal {
|
||||
StreamTerminal::Failed { failure } => {
|
||||
Some(self.classify_stream_failure(&context.account_id, failure))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let client_failure_status = stream_failure
|
||||
.as_ref()
|
||||
.map(|failure| i64::from(failure.client_failure().status_code()));
|
||||
let outcome = match &summary.terminal {
|
||||
StreamTerminal::Completed { .. } => FinalOutcome::Completed,
|
||||
StreamTerminal::Incomplete { .. } => FinalOutcome::Incomplete,
|
||||
StreamTerminal::Failed { .. }
|
||||
| StreamTerminal::UpstreamClosed
|
||||
| StreamTerminal::UpstreamError { .. }
|
||||
| StreamTerminal::ProtocolError { .. }
|
||||
| StreamTerminal::CaptureLimitExceeded => FinalOutcome::Failed,
|
||||
StreamTerminal::Cancelled | StreamTerminal::DownstreamClosed => FinalOutcome::Cancelled,
|
||||
StreamTerminal::Shutdown => FinalOutcome::Shutdown,
|
||||
};
|
||||
if !matches!(outcome, FinalOutcome::Cancelled | FinalOutcome::Shutdown)
|
||||
&& let Some(classification) = stream_failure.as_ref()
|
||||
{
|
||||
self.apply_stream_account_state(classification).await;
|
||||
}
|
||||
let _ = best_effort_controller_io(
|
||||
"cloudflare",
|
||||
cloudflare::CloudflareController::leave_stream(cloudflare::StreamExit {
|
||||
recovery: &self.cloudflare,
|
||||
account_id: &context.account_id,
|
||||
set_cookie_headers: &context.set_cookie_headers,
|
||||
terminal: &summary.terminal,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
let fallback = usage::StreamUsageExit {
|
||||
rate_limit_headers: context.rate_limit_headers.clone(),
|
||||
turn_state: context.turn_state.clone(),
|
||||
};
|
||||
let mut usage_exit = best_effort_controller_io(
|
||||
"usage",
|
||||
usage::UsageController::leave_stream(usage::StreamExit {
|
||||
account_pool: &self.account_pool,
|
||||
account_id: &context.account_id,
|
||||
account_plan_type: context.account_plan_type.as_deref(),
|
||||
rate_limit_headers: &context.rate_limit_headers,
|
||||
rate_limit_header_updates: context.rate_limit_header_updates.as_ref(),
|
||||
turn_state_update: context.turn_state_update.as_ref(),
|
||||
turn_state: context.turn_state.as_deref(),
|
||||
usage: summary.usage,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap_or(fallback);
|
||||
|
||||
let conversation_id = HistoryController::conversation_id(&scope.history, &context.request);
|
||||
let continuation_scope = HistoryController::continuation_scope(
|
||||
&context.request,
|
||||
context.transport,
|
||||
context.connection_local_continuation,
|
||||
);
|
||||
affinity::AffinityController::leave_stream(affinity::StreamExit {
|
||||
response: affinity::ResponseExit {
|
||||
affinity: &self.session_affinity,
|
||||
conversation_id,
|
||||
request: &context.request,
|
||||
account_id: &context.account_id,
|
||||
body,
|
||||
turn_state: usage_exit.turn_state.take(),
|
||||
usage: summary.usage,
|
||||
continuation_scope,
|
||||
},
|
||||
completed: matches!(summary.terminal, StreamTerminal::Completed { .. }),
|
||||
})
|
||||
.await;
|
||||
|
||||
let _ = best_effort_controller_io(
|
||||
"telemetry",
|
||||
telemetry::TelemetryController::leave_stream(telemetry::StreamExit {
|
||||
context: telemetry::StreamContext {
|
||||
recorder: &self.recorder,
|
||||
account_id: &context.account_id,
|
||||
request_id: &context.request_id,
|
||||
route: &context.route,
|
||||
display_model: &context.display_model,
|
||||
requested_model: &context.requested_model,
|
||||
request: &context.request,
|
||||
transport: context.transport,
|
||||
websocket_pool_decision: context.websocket_pool_decision,
|
||||
diagnostics: &context.diagnostics,
|
||||
response_metadata: &context.response_metadata,
|
||||
transport_metrics: &context.transport_metrics,
|
||||
attempt: &context.attempt,
|
||||
attempts: &context.attempts,
|
||||
started_at: context.started_at,
|
||||
},
|
||||
summary,
|
||||
rate_limit_headers: &usage_exit.rate_limit_headers,
|
||||
failure_status: client_failure_status,
|
||||
body,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
if !matches!(outcome, FinalOutcome::Cancelled | FinalOutcome::Shutdown) {
|
||||
if let Some(classification) = stream_failure.as_ref() {
|
||||
self.apply_stream_policy_failure(&scope, &context.account_id, classification)
|
||||
.await;
|
||||
} else {
|
||||
self.finalize_stream_success(&scope, &summary.terminal)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 对一次 observation 只分类一次,并保证 feature effects 先于 decision 返回。
|
||||
pub(in crate::dispatch) async fn handle_attempt(
|
||||
&self,
|
||||
scope: &ControllerRequestScope,
|
||||
observation: &AttemptObservation,
|
||||
) -> AttemptDecision {
|
||||
let classification = self.classify_attempt(observation);
|
||||
let _ = best_effort_controller_io(
|
||||
"usage.attempt",
|
||||
usage::UsageController::observe_attempt(&self.account_pool, &scope.usage, observation),
|
||||
)
|
||||
.await;
|
||||
|
||||
if matches!(
|
||||
observation.kind,
|
||||
AttemptObservationKind::CompleteResponse(
|
||||
crate::dispatch::lifecycle::contract::CompleteResponseFacts::Completed
|
||||
| crate::dispatch::lifecycle::contract::CompleteResponseFacts::Incomplete,
|
||||
)
|
||||
) {
|
||||
self.cyber_policy.observe_success(&scope.cyber_policy).await;
|
||||
}
|
||||
|
||||
match &classification {
|
||||
AttemptClassification::Shared(shared) => match shared {
|
||||
SharedFailureClassification::CyberPolicy(_) => {
|
||||
if let Some(account_id) = observation
|
||||
.account
|
||||
.as_ref()
|
||||
.map(|account| account.id.as_str())
|
||||
{
|
||||
self.cyber_policy
|
||||
.exclude_account(&scope.cyber_policy, account_id)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
SharedFailureClassification::AccountFailure(classified) => {
|
||||
AccountFailureController::apply_effect(
|
||||
&self.account_pool,
|
||||
&self.codex,
|
||||
classified,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
SharedFailureClassification::Quota(classified) => {
|
||||
QuotaController::apply_effect(&self.account_pool, &self.codex, classified)
|
||||
.await;
|
||||
}
|
||||
},
|
||||
AttemptClassification::Cloudflare(failure) => {
|
||||
let _ = best_effort_controller_io(
|
||||
"cloudflare.attempt",
|
||||
cloudflare::CloudflareController::apply_effect(
|
||||
&self.cloudflare,
|
||||
&self.account_pool,
|
||||
failure,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
AttemptClassification::History(_) | AttemptClassification::Default(_) => {}
|
||||
}
|
||||
|
||||
self.attempt_decision(observation, classification)
|
||||
}
|
||||
|
||||
fn classify_attempt<'a>(
|
||||
&self,
|
||||
observation: &'a AttemptObservation,
|
||||
) -> AttemptClassification<'a> {
|
||||
let shared = Self::classify_shared_failure(FailureObservation::Attempt(observation));
|
||||
let shared = match shared {
|
||||
Some(shared @ SharedFailureClassification::CyberPolicy(_)) => {
|
||||
return AttemptClassification::Shared(shared);
|
||||
}
|
||||
shared => shared,
|
||||
};
|
||||
if let Some(classified) = cloudflare::CloudflareController::classify(observation) {
|
||||
return AttemptClassification::Cloudflare(classified);
|
||||
}
|
||||
if let Some(decision) = HistoryController::decide(observation) {
|
||||
return AttemptClassification::History(decision);
|
||||
}
|
||||
if let Some(shared) = shared {
|
||||
return AttemptClassification::Shared(shared);
|
||||
}
|
||||
AttemptClassification::Default(Self::default_attempt_decision(observation))
|
||||
}
|
||||
|
||||
/// complete、prefetch 与 committed stream 共用这一份 feature owner 优先级。
|
||||
fn classify_shared_failure<'a>(
|
||||
observation: FailureObservation<'a>,
|
||||
) -> Option<SharedFailureClassification<'a>> {
|
||||
let fact = observation.fact();
|
||||
if let Some(classified) = fact.and_then(CyberPolicyController::classify) {
|
||||
return Some(SharedFailureClassification::CyberPolicy(classified));
|
||||
}
|
||||
|
||||
let account_failure = match observation {
|
||||
FailureObservation::Attempt(observation) => {
|
||||
AccountFailureController::classify(observation)
|
||||
}
|
||||
FailureObservation::Stream { account_id, .. } => {
|
||||
fact.and_then(|fact| AccountFailureController::classify_failure(account_id, fact))
|
||||
}
|
||||
};
|
||||
if let Some(classified) = account_failure {
|
||||
return Some(SharedFailureClassification::AccountFailure(classified));
|
||||
}
|
||||
|
||||
let quota = match observation {
|
||||
FailureObservation::Attempt(observation) => QuotaController::classify(observation),
|
||||
FailureObservation::Stream { account_id, .. } => {
|
||||
fact.and_then(|fact| QuotaController::classify_failure(account_id, fact))
|
||||
}
|
||||
};
|
||||
quota.map(SharedFailureClassification::Quota)
|
||||
}
|
||||
|
||||
fn attempt_decision(
|
||||
&self,
|
||||
observation: &AttemptObservation,
|
||||
classification: AttemptClassification<'_>,
|
||||
) -> AttemptDecision {
|
||||
match classification {
|
||||
AttemptClassification::Shared(shared) => match shared {
|
||||
SharedFailureClassification::CyberPolicy(classified) => {
|
||||
CyberPolicyController::decision(observation, classified)
|
||||
}
|
||||
SharedFailureClassification::AccountFailure(classified) => {
|
||||
let client_failure = response_failure(observation).map(|failure| {
|
||||
AccountFailureController::client_failure(&classified, failure)
|
||||
});
|
||||
with_response_client_failure(
|
||||
AccountFailureController::decision(observation, classified),
|
||||
client_failure,
|
||||
)
|
||||
}
|
||||
SharedFailureClassification::Quota(classified) => {
|
||||
let client_failure =
|
||||
response_failure(observation).map(QuotaController::client_failure);
|
||||
with_response_client_failure(
|
||||
QuotaController::decision(observation, classified),
|
||||
client_failure,
|
||||
)
|
||||
}
|
||||
},
|
||||
AttemptClassification::Cloudflare(classified) => {
|
||||
cloudflare::CloudflareController::decision(observation, classified)
|
||||
}
|
||||
AttemptClassification::History(decision) => with_response_client_failure(
|
||||
decision,
|
||||
response_failure(observation)
|
||||
.map(|failure| ClientFailure::new(failure.clone(), 400, false)),
|
||||
),
|
||||
AttemptClassification::Default(decision) => decision,
|
||||
}
|
||||
}
|
||||
|
||||
fn default_attempt_decision(observation: &AttemptObservation) -> AttemptDecision {
|
||||
match &observation.kind {
|
||||
AttemptObservationKind::CompleteResponse(
|
||||
crate::dispatch::lifecycle::contract::CompleteResponseFacts::Completed
|
||||
| crate::dispatch::lifecycle::contract::CompleteResponseFacts::Incomplete,
|
||||
) => AttemptDecision::Accept,
|
||||
AttemptObservationKind::CompleteResponse(
|
||||
crate::dispatch::lifecycle::contract::CompleteResponseFacts::Failed(failure),
|
||||
) => AttemptDecision::Return(AttemptReturnKind::Failed(
|
||||
default_response_client_failure(failure),
|
||||
)),
|
||||
AttemptObservationKind::CompleteResponse(
|
||||
crate::dispatch::lifecycle::contract::CompleteResponseFacts::MissingCompleted
|
||||
| crate::dispatch::lifecycle::contract::CompleteResponseFacts::Empty,
|
||||
) => AttemptDecision::Return(AttemptReturnKind::Observed),
|
||||
AttemptObservationKind::StreamFailure(failure) => AttemptDecision::Return(
|
||||
AttemptReturnKind::Failed(default_response_client_failure(failure)),
|
||||
),
|
||||
AttemptObservationKind::NoCandidate { .. } => {
|
||||
AttemptDecision::Return(AttemptReturnKind::Observed)
|
||||
}
|
||||
AttemptObservationKind::CandidatePreparationRejected => {
|
||||
unreachable!("candidate preparation controller owns it")
|
||||
}
|
||||
AttemptObservationKind::RoutePreparationRejected { message } => {
|
||||
AttemptDecision::Return(AttemptReturnKind::RouteUnavailable {
|
||||
message: message.clone(),
|
||||
})
|
||||
}
|
||||
AttemptObservationKind::PinnedCandidateUnavailable { .. } => {
|
||||
unreachable!("route controller owns pinned-candidate acquisition failures")
|
||||
}
|
||||
AttemptObservationKind::ProtocolFailure { .. } => {
|
||||
AttemptDecision::Return(AttemptReturnKind::Observed)
|
||||
}
|
||||
AttemptObservationKind::UpstreamFailure(facts) => {
|
||||
if observation.routing.can_retry_next_candidate
|
||||
&& AccountFailureController::is_retryable_transport(observation)
|
||||
{
|
||||
return AttemptDecision::RetryNextCandidate {
|
||||
exhaustion: observation.account.as_ref().map(|account| {
|
||||
crate::dispatch::failure::exhaustion::AccountExhaustionRecord::new(
|
||||
account.id.clone(),
|
||||
crate::dispatch::failure::exhaustion::ExhaustedAccountKind::UpstreamUnavailable,
|
||||
facts.message.clone(),
|
||||
)
|
||||
}),
|
||||
on_exhaustion: None,
|
||||
};
|
||||
}
|
||||
AttemptDecision::Return(AttemptReturnKind::Observed)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn response_failure(observation: &AttemptObservation) -> Option<&ResponsesSseFailure> {
|
||||
match &observation.kind {
|
||||
AttemptObservationKind::CompleteResponse(
|
||||
crate::dispatch::lifecycle::contract::CompleteResponseFacts::Failed(failure),
|
||||
)
|
||||
| AttemptObservationKind::StreamFailure(failure) => Some(failure),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn with_response_client_failure(
|
||||
decision: AttemptDecision,
|
||||
failure: Option<ClientFailure>,
|
||||
) -> AttemptDecision {
|
||||
match (decision, failure) {
|
||||
(AttemptDecision::Return(AttemptReturnKind::Observed), Some(failure)) => {
|
||||
AttemptDecision::Return(AttemptReturnKind::Failed(failure))
|
||||
}
|
||||
(decision, _) => decision,
|
||||
}
|
||||
}
|
||||
|
||||
fn default_response_client_failure(failure: &ResponsesSseFailure) -> ClientFailure {
|
||||
AccountFailureController::unowned_client_failure(failure)
|
||||
.unwrap_or_else(|| ClientFailure::new(failure.clone(), 502, false))
|
||||
}
|
||||
|
||||
async fn best_effort_controller_io<T>(
|
||||
controller: &'static str,
|
||||
operation: impl Future<Output = T>,
|
||||
) -> Option<T> {
|
||||
match timeout(BEST_EFFORT_IO_TIMEOUT, operation).await {
|
||||
Ok(output) => Some(output),
|
||||
Err(_) => {
|
||||
tracing::warn!(
|
||||
controller,
|
||||
timeout_ms = BEST_EFFORT_IO_TIMEOUT.as_millis(),
|
||||
"Timed out running best-effort controller I/O"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
//! 请求前配额验证规则 owner。
|
||||
|
||||
use chrono::{Duration, Utc};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
affinity::AccountIdentityService,
|
||||
controllers::{
|
||||
ControllerFailureFact,
|
||||
account_state::{AccountStateEffect, AccountStateEffects},
|
||||
},
|
||||
errors::ClientFailure,
|
||||
failure::exhaustion::{AccountExhaustionRecord, ExhaustedAccountKind},
|
||||
lifecycle::contract::{
|
||||
AttemptDecision, AttemptObservation, AttemptObservationKind, AttemptReturnKind,
|
||||
},
|
||||
transport::observation::UpstreamFailureFacts,
|
||||
},
|
||||
fleet::{
|
||||
pool::{AccountLease, AccountPoolService},
|
||||
quota::{
|
||||
quota_from_usage, quota_snapshot_limit_reached, quota_snapshot_limit_window_seconds,
|
||||
quota_snapshot_reset_at,
|
||||
},
|
||||
},
|
||||
upstream::openai::{
|
||||
protocol::responses::ResponsesSseFailure,
|
||||
transport::{CodexBackendClient, CodexRequestContext},
|
||||
},
|
||||
};
|
||||
|
||||
const LIMIT_REACHED_MESSAGE: &str = "Upstream usage quota still reports limit_reached";
|
||||
const DEFAULT_RATE_LIMIT_RETRY_SECONDS: u64 = 60;
|
||||
|
||||
pub(super) enum QuotaEnterOutcome {
|
||||
Ready(Box<AccountLease>),
|
||||
LimitReached,
|
||||
}
|
||||
|
||||
pub(super) struct QuotaEnterContext<'a> {
|
||||
pub account_pool: &'a AccountPoolService,
|
||||
pub codex: &'a CodexBackendClient,
|
||||
pub account_identity: &'a AccountIdentityService,
|
||||
pub request_id: &'a str,
|
||||
pub cookie_header: Option<&'a str>,
|
||||
}
|
||||
|
||||
pub(super) struct QuotaController;
|
||||
|
||||
impl QuotaController {
|
||||
pub(super) async fn enter(
|
||||
context: QuotaEnterContext<'_>,
|
||||
acquired: AccountLease,
|
||||
) -> QuotaEnterOutcome {
|
||||
if !acquired.account.quota_verify_required {
|
||||
return QuotaEnterOutcome::Ready(Box::new(acquired));
|
||||
}
|
||||
|
||||
let account_id = acquired.account.id.clone();
|
||||
let identity = context.account_identity.scope_auxiliary(&account_id);
|
||||
let usage = context
|
||||
.codex
|
||||
.fetch_usage(CodexRequestContext {
|
||||
access_token: &acquired.account.access_token,
|
||||
account_id: acquired.account.account_id.as_deref(),
|
||||
request_id: context.request_id,
|
||||
turn_state: None,
|
||||
turn_metadata: None,
|
||||
beta_features: None,
|
||||
include_timing_metrics: None,
|
||||
version: None,
|
||||
codex_window_id: None,
|
||||
parent_thread_id: None,
|
||||
cookie_header: context.cookie_header,
|
||||
installation_id: Some(&identity.installation_id),
|
||||
session_id: None,
|
||||
thread_id: None,
|
||||
client_request_id: None,
|
||||
turn_id: None,
|
||||
})
|
||||
.await;
|
||||
|
||||
let raw = match usage {
|
||||
Ok(raw) => raw,
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
request_id = %context.request_id,
|
||||
account_id = %account_id,
|
||||
quota_verify_required = true,
|
||||
quota_verify_result = "upstream_error",
|
||||
retry_with_another_account = false,
|
||||
error = %error,
|
||||
"Failed to verify stale quota state before upstream request"
|
||||
);
|
||||
return QuotaEnterOutcome::Ready(Box::new(acquired));
|
||||
}
|
||||
};
|
||||
|
||||
let quota = quota_from_usage(&raw);
|
||||
context
|
||||
.account_pool
|
||||
.apply_quota_snapshot(&account_id, "a)
|
||||
.await;
|
||||
if quota_snapshot_limit_reached("a) {
|
||||
acquired.release_without_usage().await;
|
||||
tracing::info!(
|
||||
request_id = %context.request_id,
|
||||
account_id = %account_id,
|
||||
quota_verify_required = true,
|
||||
quota_verify_result = "limit_reached",
|
||||
retry_with_another_account = true,
|
||||
"Quota verification reported exhausted account before upstream request"
|
||||
);
|
||||
return QuotaEnterOutcome::LimitReached;
|
||||
}
|
||||
|
||||
QuotaEnterOutcome::Ready(Box::new(acquired_with_verified_quota(acquired, "a)))
|
||||
}
|
||||
|
||||
pub(super) fn classify(observation: &AttemptObservation) -> Option<ClassifiedQuotaFailure> {
|
||||
if matches!(
|
||||
observation.kind,
|
||||
AttemptObservationKind::CandidatePreparationRejected
|
||||
) {
|
||||
return observation
|
||||
.account
|
||||
.as_ref()
|
||||
.map(|account| ClassifiedQuotaFailure {
|
||||
exhaustion: AccountExhaustionRecord::new(
|
||||
account.id.clone(),
|
||||
ExhaustedAccountKind::RateLimited,
|
||||
LIMIT_REACHED_MESSAGE,
|
||||
),
|
||||
effect: None,
|
||||
});
|
||||
}
|
||||
classify(observation)
|
||||
}
|
||||
|
||||
pub(super) fn classify_failure(
|
||||
account_id: &str,
|
||||
failure: ControllerFailureFact<'_>,
|
||||
) -> Option<ClassifiedQuotaFailure> {
|
||||
classify_failure(account_id, failure)
|
||||
}
|
||||
|
||||
pub(super) fn decision(
|
||||
observation: &AttemptObservation,
|
||||
classified: ClassifiedQuotaFailure,
|
||||
) -> AttemptDecision {
|
||||
if observation.routing.can_retry_next_candidate {
|
||||
return AttemptDecision::RetryNextCandidate {
|
||||
exhaustion: Some(classified.exhaustion),
|
||||
on_exhaustion: None,
|
||||
};
|
||||
}
|
||||
AttemptDecision::Return(AttemptReturnKind::Observed)
|
||||
}
|
||||
|
||||
pub(super) async fn apply_effect(
|
||||
account_pool: &AccountPoolService,
|
||||
codex: &CodexBackendClient,
|
||||
classified: &ClassifiedQuotaFailure,
|
||||
) {
|
||||
let Some(account_id) = classified.exhaustion.account_id.as_deref() else {
|
||||
return;
|
||||
};
|
||||
if let Some(effect) = &classified.effect {
|
||||
AccountStateEffects::apply(account_pool, codex, account_id, effect).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn client_failure(failure: &ResponsesSseFailure) -> ClientFailure {
|
||||
ClientFailure::new(failure.clone(), 429, false)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct ClassifiedQuotaFailure {
|
||||
exhaustion: AccountExhaustionRecord,
|
||||
effect: Option<AccountStateEffect>,
|
||||
}
|
||||
|
||||
fn classify(observation: &AttemptObservation) -> Option<ClassifiedQuotaFailure> {
|
||||
let account_id = observation.account.as_ref()?.id.as_str();
|
||||
ControllerFailureFact::from_attempt(observation)
|
||||
.and_then(|failure| classify_failure(account_id, failure))
|
||||
}
|
||||
|
||||
fn classify_failure(
|
||||
account_id: &str,
|
||||
failure: ControllerFailureFact<'_>,
|
||||
) -> Option<ClassifiedQuotaFailure> {
|
||||
match failure {
|
||||
ControllerFailureFact::Upstream(facts) => classify_upstream(account_id, facts),
|
||||
ControllerFailureFact::Response(failure) => classify_stream(account_id, failure),
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_upstream(
|
||||
account_id: &str,
|
||||
facts: &UpstreamFailureFacts,
|
||||
) -> Option<ClassifiedQuotaFailure> {
|
||||
let signaled_kind = facts
|
||||
.code
|
||||
.as_deref()
|
||||
.and_then(classify_quota_signal)
|
||||
.or_else(|| facts.error_type.as_deref().and_then(classify_quota_signal))
|
||||
.or_else(|| classify_quota_message(&facts.message));
|
||||
match signaled_kind.or(match facts.status_code {
|
||||
Some(429) => Some(StreamQuotaKind::RateLimited),
|
||||
Some(402) => Some(StreamQuotaKind::QuotaExhausted),
|
||||
_ => None,
|
||||
})? {
|
||||
StreamQuotaKind::RateLimited => Some(rate_limited_failure(
|
||||
account_id,
|
||||
facts.body.clone(),
|
||||
facts.retry_after_seconds,
|
||||
)),
|
||||
StreamQuotaKind::QuotaExhausted => {
|
||||
Some(quota_exhausted_failure(account_id, facts.body.clone()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_stream(
|
||||
account_id: &str,
|
||||
failure: &ResponsesSseFailure,
|
||||
) -> Option<ClassifiedQuotaFailure> {
|
||||
let kind = classify_stream_signal(failure).or(match failure.explicit_status_code {
|
||||
Some(429) => Some(StreamQuotaKind::RateLimited),
|
||||
Some(402) => Some(StreamQuotaKind::QuotaExhausted),
|
||||
_ => None,
|
||||
})?;
|
||||
let body = crate::dispatch::failure::sse::sse_failure_error_body(failure);
|
||||
Some(match kind {
|
||||
StreamQuotaKind::RateLimited => {
|
||||
rate_limited_failure(account_id, body, failure.retry_after_seconds)
|
||||
}
|
||||
StreamQuotaKind::QuotaExhausted => quota_exhausted_failure(account_id, body),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum StreamQuotaKind {
|
||||
RateLimited,
|
||||
QuotaExhausted,
|
||||
}
|
||||
|
||||
fn classify_stream_signal(failure: &ResponsesSseFailure) -> Option<StreamQuotaKind> {
|
||||
failure
|
||||
.upstream_code
|
||||
.as_deref()
|
||||
.and_then(classify_quota_signal)
|
||||
.or_else(|| {
|
||||
failure
|
||||
.upstream_type
|
||||
.as_deref()
|
||||
.and_then(classify_quota_signal)
|
||||
})
|
||||
.or_else(|| classify_quota_message(&failure.message))
|
||||
}
|
||||
|
||||
fn classify_quota_signal(signal: &str) -> Option<StreamQuotaKind> {
|
||||
let signal = signal.trim().to_ascii_lowercase();
|
||||
match signal.as_str() {
|
||||
"usage_limit_reached"
|
||||
| "rate_limit_exceeded"
|
||||
| "rate_limit_reached"
|
||||
| "rate_limit_error"
|
||||
| "workspace_owner_usage_limit_reached"
|
||||
| "workspace_member_usage_limit_reached" => Some(StreamQuotaKind::RateLimited),
|
||||
"quota_exhausted"
|
||||
| "quota_exceeded"
|
||||
| "payment_required"
|
||||
| "insufficient_quota"
|
||||
| "workspace_owner_credits_depleted"
|
||||
| "workspace_member_credits_depleted" => Some(StreamQuotaKind::QuotaExhausted),
|
||||
signal if signal.starts_with("billing_limit") => Some(StreamQuotaKind::QuotaExhausted),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_quota_message(message: &str) -> Option<StreamQuotaKind> {
|
||||
let message = message.to_ascii_lowercase();
|
||||
if message.contains("rate limit") || message.contains("usage limit") {
|
||||
return Some(StreamQuotaKind::RateLimited);
|
||||
}
|
||||
if message.contains("quota")
|
||||
|| message.contains("payment required")
|
||||
|| message.contains("billing limit")
|
||||
{
|
||||
return Some(StreamQuotaKind::QuotaExhausted);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn rate_limited_failure(
|
||||
account_id: &str,
|
||||
message: String,
|
||||
retry_after_seconds: Option<u64>,
|
||||
) -> ClassifiedQuotaFailure {
|
||||
let seconds = retry_after_seconds
|
||||
.unwrap_or(DEFAULT_RATE_LIMIT_RETRY_SECONDS)
|
||||
.min(i64::MAX as u64) as i64;
|
||||
ClassifiedQuotaFailure {
|
||||
exhaustion: AccountExhaustionRecord::new(
|
||||
account_id,
|
||||
ExhaustedAccountKind::RateLimited,
|
||||
message,
|
||||
),
|
||||
effect: Some(AccountStateEffect::MarkQuotaLimitedUntil(
|
||||
Utc::now() + Duration::seconds(seconds),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn quota_exhausted_failure(account_id: &str, message: String) -> ClassifiedQuotaFailure {
|
||||
ClassifiedQuotaFailure {
|
||||
exhaustion: AccountExhaustionRecord::new(
|
||||
account_id,
|
||||
ExhaustedAccountKind::QuotaExhausted,
|
||||
message,
|
||||
),
|
||||
effect: Some(AccountStateEffect::SetStatus(
|
||||
crate::fleet::account::AccountStatus::QuotaExhausted,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn acquired_with_verified_quota(mut acquired: AccountLease, quota: &Value) -> AccountLease {
|
||||
let limit_reached = quota_snapshot_limit_reached(quota);
|
||||
acquired.account.quota_verify_required = false;
|
||||
acquired.account.quota_limit_reached = limit_reached;
|
||||
acquired.account.quota_cooldown_until = limit_reached
|
||||
.then_some(quota_snapshot_reset_at(quota))
|
||||
.flatten();
|
||||
if let Some(reset_at) = quota_snapshot_reset_at(quota) {
|
||||
acquired.account.window_reset_at = Some(reset_at);
|
||||
if let Some(limit_window_seconds) = quota_snapshot_limit_window_seconds(quota) {
|
||||
acquired.account.limit_window_seconds = Some(limit_window_seconds);
|
||||
}
|
||||
}
|
||||
acquired
|
||||
}
|
||||
+111
-94
@@ -1,19 +1,20 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::{
|
||||
dispatch::errors::{
|
||||
backend_transport_name, insert_dispatch_error_metadata,
|
||||
insert_upstream_diagnostics_metadata, upstream_error_http_status, DispatchErrorMetadata,
|
||||
DispatchErrorMetadata, backend_transport_name, insert_dispatch_error_metadata,
|
||||
insert_upstream_diagnostics_metadata, upstream_error_http_status,
|
||||
},
|
||||
infra::time::elapsed_millis_i64,
|
||||
telemetry::{
|
||||
ops::types::OpsErrorLog,
|
||||
recorder::{
|
||||
enrich_event_route_metadata, enrich_usage_record_identity,
|
||||
DispatchErrorLogRecord, Recorder, enrich_event_route_metadata,
|
||||
enrich_response_request_semantics, enrich_usage_record_identity,
|
||||
event_kind as response_event_kind, reasoning_effort_from_request,
|
||||
record_dispatch_error_event, DispatchErrorLogRecord, Recorder,
|
||||
record_dispatch_error_event,
|
||||
},
|
||||
usage::types::UsageRecordLevel,
|
||||
},
|
||||
@@ -26,17 +27,16 @@ use crate::{
|
||||
},
|
||||
};
|
||||
|
||||
use super::{
|
||||
use crate::dispatch::{
|
||||
errors::{
|
||||
dispatch_error_metadata, enrich_response_dispatch_error_metadata, ResponseDispatchError,
|
||||
},
|
||||
stream::{
|
||||
live::{latest_response_id, LiveResponseStreamContext},
|
||||
sse_failure::{status_code_for_stream_failure, stream_failure_metadata},
|
||||
trace::{ResponseDispatchAttempt, ResponseDispatchTrace},
|
||||
ResponseDispatchError, dispatch_error_metadata, enrich_response_dispatch_error_metadata,
|
||||
},
|
||||
failure::sse::stream_failure_metadata,
|
||||
lifecycle::trace::{ResponseDispatchAttempt, ResponseDispatchTrace},
|
||||
};
|
||||
|
||||
use super::StreamContext;
|
||||
|
||||
pub(super) struct ResponseUpstreamErrorEventRecord<'a> {
|
||||
pub(super) recorder: &'a Recorder,
|
||||
pub(super) request_id: &'a str,
|
||||
@@ -64,6 +64,7 @@ pub(super) struct ResponseStreamFailureEventRecord<'a> {
|
||||
pub(super) transport: CodexBackendTransport,
|
||||
pub(super) request: &'a CodexResponsesRequest,
|
||||
pub(super) failure: &'a ResponsesSseFailure,
|
||||
pub(super) status_code: i64,
|
||||
pub(super) diagnostics: &'a CodexUpstreamDiagnostics,
|
||||
pub(super) rate_limit_headers: &'a [(String, String)],
|
||||
pub(super) prefetched: &'a [u8],
|
||||
@@ -85,14 +86,6 @@ pub(super) struct ResponseDispatchErrorEventRecord<'a> {
|
||||
pub(super) error: &'a ResponseDispatchError,
|
||||
}
|
||||
|
||||
pub(super) struct ResponseDispatchErrorDetails<'a> {
|
||||
pub(super) client_api_key_id: Option<&'a str>,
|
||||
pub(super) account_id: Option<&'a str>,
|
||||
pub(super) stream: bool,
|
||||
pub(super) compact: bool,
|
||||
pub(super) transport: Option<&'a str>,
|
||||
}
|
||||
|
||||
pub(super) async fn record_response_dispatch_error_event(
|
||||
record: ResponseDispatchErrorEventRecord<'_>,
|
||||
) {
|
||||
@@ -177,16 +170,17 @@ pub(super) async fn record_response_upstream_error_event(
|
||||
reasoning_effort_from_request(record.request),
|
||||
record.request.service_tier(),
|
||||
);
|
||||
enrich_response_request_semantics(&mut metadata, record.request);
|
||||
event.metadata = metadata;
|
||||
if let Err(error) = record.recorder.record_error(event).await {
|
||||
tracing::error!(account_id = %record.account_id, error = %error, "failed to record upstream error event");
|
||||
tracing::error!(account_id = %record.account_id, error = %error, "Failed to record upstream error event");
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn record_prefetched_response_stream_failure_event(
|
||||
record: ResponseStreamFailureEventRecord<'_>,
|
||||
) {
|
||||
let event_status_code = status_code_for_stream_failure(record.failure);
|
||||
let event_status_code = record.status_code;
|
||||
let mut metadata = stream_failure_metadata(record.failure, None);
|
||||
if let Some(object) = metadata.as_object_mut() {
|
||||
if record.transport == CodexBackendTransport::WebSocket {
|
||||
@@ -202,11 +196,13 @@ pub(super) async fn record_prefetched_response_stream_failure_event(
|
||||
diagnostics_status_code(record.diagnostics),
|
||||
);
|
||||
insert_response_request_summary_object(object, record.request, record.transport);
|
||||
object.insert("requestBody".to_string(), json!(record.request));
|
||||
object.insert(
|
||||
"responseBody".to_string(),
|
||||
Value::String(String::from_utf8_lossy(record.prefetched).to_string()),
|
||||
);
|
||||
if record.recorder.captures_body() {
|
||||
object.insert("requestBody".to_string(), json!(record.request));
|
||||
object.insert(
|
||||
"responseBody".to_string(),
|
||||
Value::String(String::from_utf8_lossy(record.prefetched).to_string()),
|
||||
);
|
||||
}
|
||||
insert_upstream_diagnostics_metadata(object, record.diagnostics);
|
||||
insert_response_trace_metadata_object(
|
||||
object,
|
||||
@@ -224,6 +220,7 @@ pub(super) async fn record_prefetched_response_stream_failure_event(
|
||||
reasoning_effort_from_request(record.request),
|
||||
record.request.service_tier(),
|
||||
);
|
||||
enrich_response_request_semantics(&mut metadata, record.request);
|
||||
let mut event = OpsErrorLog::new(
|
||||
response_event_kind(record.route),
|
||||
"v1 responses stream failed",
|
||||
@@ -236,17 +233,17 @@ pub(super) async fn record_prefetched_response_stream_failure_event(
|
||||
event.model = Some(record.model.to_string());
|
||||
event.status_code = Some(event_status_code);
|
||||
event.latency_ms = Some(elapsed_millis_i64(record.started_at));
|
||||
if !record.rate_limit_headers.is_empty() {
|
||||
if let Some(object) = metadata.as_object_mut() {
|
||||
object.insert(
|
||||
"rateLimitHeaders".to_string(),
|
||||
serde_json::json!(record.rate_limit_headers),
|
||||
);
|
||||
}
|
||||
if !record.rate_limit_headers.is_empty()
|
||||
&& let Some(object) = metadata.as_object_mut()
|
||||
{
|
||||
object.insert(
|
||||
"rateLimitHeaders".to_string(),
|
||||
serde_json::json!(record.rate_limit_headers),
|
||||
);
|
||||
}
|
||||
event.metadata = metadata;
|
||||
if let Err(error) = record.recorder.record_error(event).await {
|
||||
tracing::error!(account_id = %record.account_id, error = %error, "failed to record prefetched stream error event");
|
||||
tracing::error!(account_id = %record.account_id, error = %error, "Failed to record prefetched stream error event");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,8 +257,16 @@ fn ensure_stream_metadata_flag(metadata: &mut Value) {
|
||||
.or_insert(Value::Bool(true));
|
||||
}
|
||||
|
||||
fn insert_optional_i64(object: &mut serde_json::Map<String, Value>, key: &str, value: Option<i64>) {
|
||||
if let Some(value) = value {
|
||||
object
|
||||
.entry(key.to_string())
|
||||
.or_insert_with(|| Value::Number(value.into()));
|
||||
}
|
||||
}
|
||||
|
||||
fn enrich_live_response_stream_metadata(
|
||||
context: &LiveResponseStreamContext,
|
||||
context: &StreamContext<'_>,
|
||||
rate_limit_headers: &[(String, String)],
|
||||
metadata: &mut Value,
|
||||
status_code: i64,
|
||||
@@ -283,21 +288,53 @@ fn enrich_live_response_stream_metadata(
|
||||
.entry("websocketPool".to_string())
|
||||
.or_insert_with(|| decision.metadata_value());
|
||||
}
|
||||
if let Some(decision) = context.transport_metrics.decision {
|
||||
object
|
||||
.entry("transportDecision".to_string())
|
||||
.or_insert_with(|| Value::String(decision.as_str().to_string()));
|
||||
}
|
||||
insert_optional_i64(
|
||||
object,
|
||||
"wsConnectMs",
|
||||
context.transport_metrics.ws_connect_ms,
|
||||
);
|
||||
insert_optional_i64(
|
||||
object,
|
||||
"transportDecisionWaitMs",
|
||||
context.transport_metrics.transport_decision_wait_ms,
|
||||
);
|
||||
insert_optional_i64(
|
||||
object,
|
||||
"upstreamHeadersMs",
|
||||
context.transport_metrics.upstream_headers_ms,
|
||||
);
|
||||
insert_optional_i64(
|
||||
object,
|
||||
"firstEventMs",
|
||||
context.transport_metrics.first_event_ms,
|
||||
);
|
||||
if let Some(http_version) = context.transport_metrics.http_version.as_deref() {
|
||||
object
|
||||
.entry("httpVersion".to_string())
|
||||
.or_insert_with(|| Value::String(http_version.to_string()));
|
||||
}
|
||||
insert_response_status_metadata_object(
|
||||
object,
|
||||
status_code,
|
||||
200,
|
||||
diagnostics_status_code(&context.diagnostics),
|
||||
diagnostics_status_code(context.diagnostics),
|
||||
);
|
||||
insert_response_request_summary_object(object, &context.request, context.transport);
|
||||
insert_upstream_diagnostics_metadata(object, &context.diagnostics);
|
||||
insert_response_trace_metadata_object(object, &context.attempts, Some(&context.attempt));
|
||||
object
|
||||
.entry("requestBody".to_string())
|
||||
.or_insert_with(|| serde_json::json!(context.request));
|
||||
object
|
||||
.entry("responseBody".to_string())
|
||||
.or_insert_with(|| Value::String(body.to_string()));
|
||||
insert_response_request_summary_object(object, context.request, context.transport);
|
||||
insert_upstream_diagnostics_metadata(object, context.diagnostics);
|
||||
insert_response_trace_metadata_object(object, context.attempts, Some(context.attempt));
|
||||
if context.recorder.captures_body() {
|
||||
object
|
||||
.entry("requestBody".to_string())
|
||||
.or_insert_with(|| serde_json::json!(context.request));
|
||||
object
|
||||
.entry("responseBody".to_string())
|
||||
.or_insert_with(|| Value::String(body.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn insert_response_upstream_diagnostics(
|
||||
@@ -409,10 +446,15 @@ fn response_request_summary(
|
||||
let body = request.body();
|
||||
let input = body.get("input");
|
||||
let tools = body.get("tools");
|
||||
let semantics = request.semantics();
|
||||
json!({
|
||||
"model": request.model(),
|
||||
"stream": request.stream(),
|
||||
"store": request.store(),
|
||||
"compact": semantics.compact,
|
||||
"requestKind": semantics.request_kind,
|
||||
"subagentKind": semantics.subagent_kind,
|
||||
"reasoningPreset": semantics.reasoning_preset,
|
||||
"transport": backend_transport_name(transport),
|
||||
"inputType": json_value_kind(input),
|
||||
"inputItemsCount": input.and_then(Value::as_array).map(Vec::len),
|
||||
@@ -464,7 +506,7 @@ fn upstream_failure_client_status_code(upstream_status: i64) -> i64 {
|
||||
}
|
||||
|
||||
pub(super) async fn record_live_response_stream_event(
|
||||
context: &LiveResponseStreamContext,
|
||||
context: &StreamContext<'_>,
|
||||
status_code: i64,
|
||||
level: UsageRecordLevel,
|
||||
message: &str,
|
||||
@@ -476,7 +518,7 @@ pub(super) async fn record_live_response_stream_event(
|
||||
.response_metadata
|
||||
.effective_model
|
||||
.as_deref()
|
||||
.unwrap_or(&context.display_model);
|
||||
.unwrap_or(context.display_model);
|
||||
ensure_stream_metadata_flag(&mut metadata);
|
||||
if let Some(object) = metadata.as_object_mut() {
|
||||
object.insert(
|
||||
@@ -496,7 +538,7 @@ pub(super) async fn record_live_response_stream_event(
|
||||
Value::Bool(context.response_metadata.reasoning_included),
|
||||
);
|
||||
}
|
||||
enrich_event_route_metadata(&mut metadata, &context.route);
|
||||
enrich_event_route_metadata(&mut metadata, context.route);
|
||||
enrich_live_response_stream_metadata(
|
||||
context,
|
||||
rate_limit_headers,
|
||||
@@ -504,30 +546,31 @@ pub(super) async fn record_live_response_stream_event(
|
||||
status_code,
|
||||
body,
|
||||
);
|
||||
log_live_response_stream_finalized(context, status_code, level, message, &metadata, body);
|
||||
log_live_response_stream_finalized(context, status_code, level, message, &metadata);
|
||||
enrich_usage_record_identity(
|
||||
&mut metadata,
|
||||
Some(&context.requested_model),
|
||||
Some(context.requested_model),
|
||||
effective_model,
|
||||
context.client_ip.as_deref(),
|
||||
context.request.client_ip.as_deref(),
|
||||
context.request.client_user_agent.as_deref(),
|
||||
reasoning_effort_from_request(&context.request),
|
||||
reasoning_effort_from_request(context.request),
|
||||
context.request.service_tier(),
|
||||
);
|
||||
enrich_response_request_semantics(&mut metadata, context.request);
|
||||
|
||||
if is_success_usage_event(level, status_code) {
|
||||
crate::telemetry::recorder::record_response_event(
|
||||
crate::telemetry::usage::types::ResponseUsageRecord {
|
||||
recorder: &context.recorder,
|
||||
request_id: &context.request_id,
|
||||
recorder: context.recorder,
|
||||
request_id: context.request_id,
|
||||
client_api_key_id: context.request.client_api_key_id.as_deref(),
|
||||
account_id: &context.account_id,
|
||||
route: &context.route,
|
||||
account_id: context.account_id,
|
||||
route: context.route,
|
||||
model: effective_model,
|
||||
requested_model: Some(&context.requested_model),
|
||||
client_ip: context.client_ip.as_deref(),
|
||||
requested_model: Some(context.requested_model),
|
||||
client_ip: context.request.client_ip.as_deref(),
|
||||
client_user_agent: context.request.client_user_agent.as_deref(),
|
||||
reasoning_effort: reasoning_effort_from_request(&context.request),
|
||||
reasoning_effort: reasoning_effort_from_request(context.request),
|
||||
service_tier: context.request.service_tier(),
|
||||
started_at: context.started_at,
|
||||
status_code,
|
||||
@@ -538,18 +581,18 @@ pub(super) async fn record_live_response_stream_event(
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
let mut event = OpsErrorLog::new(response_event_kind(&context.route), message);
|
||||
event.request_id = Some(context.request_id.clone());
|
||||
let mut event = OpsErrorLog::new(response_event_kind(context.route), message);
|
||||
event.request_id = Some(context.request_id.to_string());
|
||||
event.client_api_key_id = context.request.client_api_key_id.clone();
|
||||
event.provider = Some("openai".to_string());
|
||||
event.account_id = Some(context.account_id.clone());
|
||||
event.route = Some(context.route.clone());
|
||||
event.account_id = Some(context.account_id.to_string());
|
||||
event.route = Some(context.route.to_string());
|
||||
event.model = Some(effective_model.to_string());
|
||||
event.status_code = Some(status_code);
|
||||
event.latency_ms = Some(elapsed_millis_i64(context.started_at));
|
||||
event.metadata = metadata;
|
||||
if let Err(error) = context.recorder.record_error(event).await {
|
||||
tracing::error!(account_id = %context.account_id, error = %error, "failed to record live response stream error event");
|
||||
tracing::error!(account_id = %context.account_id, error = %error, "Failed to record live response stream error event");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -559,23 +602,17 @@ fn is_success_usage_event(level: UsageRecordLevel, status_code: i64) -> bool {
|
||||
}
|
||||
|
||||
fn log_live_response_stream_finalized(
|
||||
context: &LiveResponseStreamContext,
|
||||
context: &StreamContext<'_>,
|
||||
status_code: i64,
|
||||
level: UsageRecordLevel,
|
||||
message: &str,
|
||||
metadata: &Value,
|
||||
body: &str,
|
||||
) {
|
||||
let response_id = metadata_string_field(metadata, "responseId")
|
||||
.map(ToString::to_string)
|
||||
.or_else(|| latest_response_id(body));
|
||||
let response_id = metadata_string_field(metadata, "responseId").map(ToString::to_string);
|
||||
let first_token_ms = metadata.get("firstTokenMs").and_then(Value::as_i64);
|
||||
let websocket_pool_kind = context
|
||||
.websocket_pool_decision
|
||||
.map(WebSocketPoolDecision::kind);
|
||||
let websocket_pool_reason = context
|
||||
.websocket_pool_decision
|
||||
.and_then(WebSocketPoolDecision::reason);
|
||||
let completed = metadata.get("completed").and_then(Value::as_bool);
|
||||
let failed = metadata.get("failed").and_then(Value::as_bool);
|
||||
let upstream_code = metadata_string_field(metadata, "upstreamCode");
|
||||
@@ -596,7 +633,6 @@ fn log_live_response_stream_finalized(
|
||||
event_message = %message,
|
||||
transport = %backend_transport_name(context.transport),
|
||||
websocket_pool_kind = ?websocket_pool_kind,
|
||||
websocket_pool_reason = ?websocket_pool_reason,
|
||||
response_id = response_id.as_deref().unwrap_or(""),
|
||||
first_token_ms = ?first_token_ms,
|
||||
latency_ms = elapsed_millis_i64(context.started_at),
|
||||
@@ -606,7 +642,7 @@ fn log_live_response_stream_finalized(
|
||||
failure_class = ?failure_class,
|
||||
failure_source = ?failure_source,
|
||||
failure_detail = ?failure_detail,
|
||||
"live response stream finalized"
|
||||
"Live response stream finalized"
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -631,25 +667,6 @@ fn metadata_string_field<'a>(metadata: &'a Value, field: &str) -> Option<&'a str
|
||||
metadata.get(field).and_then(Value::as_str)
|
||||
}
|
||||
|
||||
pub(super) async fn live_response_rate_limit_headers(
|
||||
context: &LiveResponseStreamContext,
|
||||
) -> Vec<(String, String)> {
|
||||
let mut headers = context.rate_limit_headers.clone();
|
||||
if let Some(updates) = &context.rate_limit_header_updates {
|
||||
headers.extend(updates.lock().await.iter().cloned());
|
||||
}
|
||||
headers
|
||||
}
|
||||
|
||||
pub(super) async fn live_response_turn_state(
|
||||
context: &LiveResponseStreamContext,
|
||||
) -> Option<String> {
|
||||
if let Some(update) = &context.turn_state_update {
|
||||
return update.lock().await.clone();
|
||||
}
|
||||
context.turn_state.clone()
|
||||
}
|
||||
|
||||
pub(super) fn insert_first_token_ms(metadata: &mut Value, first_token_ms: Option<i64>) {
|
||||
let Some(first_token_ms) = first_token_ms else {
|
||||
return;
|
||||
@@ -0,0 +1,359 @@
|
||||
//! 请求终态遥测的唯一 feature owner。
|
||||
|
||||
mod events;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
controllers::telemetry::events::{
|
||||
ResponseUpstreamErrorEventRecord, insert_first_token_ms,
|
||||
insert_response_status_metadata, insert_response_trace_metadata,
|
||||
insert_response_upstream_diagnostics, insert_websocket_pool_decision,
|
||||
record_live_response_stream_event, record_response_upstream_error_event,
|
||||
},
|
||||
controllers::{
|
||||
AttemptUpstreamErrorContext, CompleteExit, DispatchErrorObservation,
|
||||
PrefetchedStreamFailureObservation,
|
||||
},
|
||||
errors::{ResponseDispatchError, backend_transport_name},
|
||||
failure::sse::{
|
||||
STREAM_DISCONNECTED_CODE, STREAM_DISCONNECTED_MESSAGE, stream_failure_metadata,
|
||||
stream_failure_source, synthetic_stream_disconnected_detail,
|
||||
},
|
||||
lifecycle::{
|
||||
stream::{StreamSummary, StreamTerminal},
|
||||
trace::ResponseDispatchAttempt,
|
||||
},
|
||||
},
|
||||
infra::time::elapsed_millis_i64,
|
||||
telemetry::{
|
||||
recorder::{
|
||||
Recorder, enrich_response_request_semantics, reasoning_effort_from_request,
|
||||
record_response_event,
|
||||
},
|
||||
usage::types::{ResponseUsageRecord, UsageRecordLevel},
|
||||
},
|
||||
upstream::openai::{
|
||||
protocol::responses::{CodexResponsesRequest, ResponsesSseFailure},
|
||||
transport::{
|
||||
CodexBackendTransport, CodexResponseMetadata, CodexTransportMetrics,
|
||||
CodexUpstreamDiagnostics, WebSocketPoolDecision,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
pub(super) struct TelemetryController;
|
||||
|
||||
pub(super) struct StreamContext<'a> {
|
||||
pub recorder: &'a Recorder,
|
||||
pub account_id: &'a str,
|
||||
pub request_id: &'a str,
|
||||
pub route: &'a str,
|
||||
pub display_model: &'a str,
|
||||
pub requested_model: &'a str,
|
||||
pub request: &'a CodexResponsesRequest,
|
||||
pub transport: CodexBackendTransport,
|
||||
pub websocket_pool_decision: Option<WebSocketPoolDecision>,
|
||||
pub diagnostics: &'a CodexUpstreamDiagnostics,
|
||||
pub response_metadata: &'a CodexResponseMetadata,
|
||||
pub transport_metrics: &'a CodexTransportMetrics,
|
||||
pub attempt: &'a ResponseDispatchAttempt,
|
||||
pub attempts: &'a [ResponseDispatchAttempt],
|
||||
pub started_at: std::time::Instant,
|
||||
}
|
||||
|
||||
pub(super) struct StreamExit<'a> {
|
||||
pub context: StreamContext<'a>,
|
||||
pub summary: &'a StreamSummary,
|
||||
pub rate_limit_headers: &'a [(String, String)],
|
||||
pub failure_status: Option<i64>,
|
||||
pub body: &'a str,
|
||||
}
|
||||
|
||||
impl TelemetryController {
|
||||
pub(super) async fn observe_dispatch_error(
|
||||
recorder: &Recorder,
|
||||
observation: DispatchErrorObservation<'_>,
|
||||
error: &ResponseDispatchError,
|
||||
) {
|
||||
events::record_response_dispatch_error_event(events::ResponseDispatchErrorEventRecord {
|
||||
recorder,
|
||||
request_id: observation.request_id,
|
||||
client_api_key_id: observation.client_api_key_id,
|
||||
account_id: observation.account_id,
|
||||
route: observation.route,
|
||||
model: observation.model,
|
||||
started_at: observation.started_at,
|
||||
stream: observation.stream,
|
||||
compact: observation.compact,
|
||||
transport: observation.transport,
|
||||
error,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(super) async fn observe_prefetched_stream_failure(
|
||||
recorder: &Recorder,
|
||||
observation: PrefetchedStreamFailureObservation<'_>,
|
||||
) {
|
||||
events::record_prefetched_response_stream_failure_event(
|
||||
events::ResponseStreamFailureEventRecord {
|
||||
recorder,
|
||||
request_id: observation.request_id,
|
||||
account_id: observation.account_id,
|
||||
route: observation.route,
|
||||
model: observation.model,
|
||||
requested_model: observation.requested_model,
|
||||
started_at: observation.started_at,
|
||||
transport: observation.transport,
|
||||
request: observation.request,
|
||||
failure: observation.failure,
|
||||
status_code: i64::from(observation.error.client_http_status_code()),
|
||||
diagnostics: observation.diagnostics,
|
||||
rate_limit_headers: observation.rate_limit_headers,
|
||||
prefetched: observation.prefetched,
|
||||
trace: observation.trace,
|
||||
attempt: observation.attempt,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(super) async fn observe_upstream_error(
|
||||
recorder: &Recorder,
|
||||
context: &AttemptUpstreamErrorContext<'_>,
|
||||
) {
|
||||
record_response_upstream_error_event(ResponseUpstreamErrorEventRecord {
|
||||
recorder,
|
||||
request_id: context.request_id,
|
||||
account_id: &context.account.id,
|
||||
account_email: context.account.email.as_deref(),
|
||||
route: context.route,
|
||||
model: context.model,
|
||||
started_at: context.started_at,
|
||||
stream: context.stream,
|
||||
transport: context.transport,
|
||||
request: context.request,
|
||||
error: context.error,
|
||||
trace: context.trace,
|
||||
attempt: Some(context.attempt),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(super) async fn leave_complete(exit: &CompleteExit<'_>) {
|
||||
let effective_model = exit
|
||||
.response
|
||||
.response_metadata
|
||||
.effective_model
|
||||
.as_deref()
|
||||
.unwrap_or(exit.display_model);
|
||||
let mut metadata = serde_json::json!({
|
||||
"responseId": exit.response_id,
|
||||
"stream": false,
|
||||
"completed": exit.completed,
|
||||
"incomplete": !exit.completed,
|
||||
"transport": backend_transport_name(exit.response.transport),
|
||||
"firstTokenMs": exit.response.first_token_ms,
|
||||
"usage": exit.response.usage,
|
||||
"effectiveModel": effective_model,
|
||||
"modelsEtag": exit.response.response_metadata.models_etag.as_deref(),
|
||||
"reasoningIncluded": exit.response.response_metadata.reasoning_included,
|
||||
"transportDecision": exit.response.transport_metrics.decision.map(|decision| decision.as_str()),
|
||||
"wsConnectMs": exit.response.transport_metrics.ws_connect_ms,
|
||||
"transportDecisionWaitMs": exit.response.transport_metrics.transport_decision_wait_ms,
|
||||
"upstreamHeadersMs": exit.response.transport_metrics.upstream_headers_ms,
|
||||
"firstEventMs": exit.response.transport_metrics.first_event_ms,
|
||||
"httpVersion": exit.response.transport_metrics.http_version.as_deref(),
|
||||
});
|
||||
insert_response_status_metadata(
|
||||
&mut metadata,
|
||||
200,
|
||||
200,
|
||||
exit.response.diagnostics.status_code.map(i64::from),
|
||||
);
|
||||
insert_response_upstream_diagnostics(&mut metadata, &exit.response.diagnostics);
|
||||
insert_response_trace_metadata(&mut metadata, exit.trace, Some(exit.attempt));
|
||||
insert_websocket_pool_decision(&mut metadata, exit.response.websocket_pool_decision);
|
||||
enrich_response_request_semantics(&mut metadata, exit.request);
|
||||
record_response_event(ResponseUsageRecord {
|
||||
recorder: exit.recorder,
|
||||
request_id: exit.request_id,
|
||||
client_api_key_id: exit.request.client_api_key_id.as_deref(),
|
||||
account_id: exit.account_id,
|
||||
route: exit.route,
|
||||
model: effective_model,
|
||||
requested_model: Some(exit.requested_model),
|
||||
client_ip: exit.request.client_ip.as_deref(),
|
||||
client_user_agent: exit.request.client_user_agent.as_deref(),
|
||||
reasoning_effort: reasoning_effort_from_request(exit.request),
|
||||
service_tier: exit.request.service_tier(),
|
||||
started_at: exit.started_at,
|
||||
status_code: 200,
|
||||
message: if exit.completed {
|
||||
"v1 responses completed"
|
||||
} else {
|
||||
"v1 responses incomplete"
|
||||
},
|
||||
metadata,
|
||||
rate_limit_headers: &exit.response.rate_limit_headers,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(super) async fn leave_stream(exit: StreamExit<'_>) {
|
||||
let context = &exit.context;
|
||||
let summary = exit.summary;
|
||||
let rate_limit_headers = exit.rate_limit_headers;
|
||||
let body = exit.body;
|
||||
match &summary.terminal {
|
||||
StreamTerminal::Completed { response } => {
|
||||
record_success(context, summary, response, true, rate_limit_headers, body).await;
|
||||
}
|
||||
StreamTerminal::Incomplete { response } => {
|
||||
record_success(context, summary, response, false, rate_limit_headers, body).await;
|
||||
}
|
||||
StreamTerminal::Failed { failure } => {
|
||||
record_failure(
|
||||
context,
|
||||
summary,
|
||||
failure,
|
||||
exit.failure_status.unwrap_or(502),
|
||||
rate_limit_headers,
|
||||
body,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
terminal @ (StreamTerminal::UpstreamClosed
|
||||
| StreamTerminal::UpstreamError { .. }
|
||||
| StreamTerminal::ProtocolError { .. }
|
||||
| StreamTerminal::CaptureLimitExceeded) => {
|
||||
let failure = synthetic_failure(terminal);
|
||||
record_failure(context, summary, &failure, 502, rate_limit_headers, body).await;
|
||||
}
|
||||
terminal @ (StreamTerminal::Cancelled
|
||||
| StreamTerminal::DownstreamClosed
|
||||
| StreamTerminal::Shutdown) => {
|
||||
let status_code = if matches!(terminal, StreamTerminal::Shutdown) {
|
||||
503
|
||||
} else {
|
||||
499
|
||||
};
|
||||
let mut metadata = serde_json::json!({
|
||||
"stream": true,
|
||||
"cancelled": true,
|
||||
"terminal": terminal.name(),
|
||||
"responseId": summary.last_response_id,
|
||||
"firstEventMs": summary.first_event_ms,
|
||||
"usage": summary.usage,
|
||||
});
|
||||
insert_first_token_ms(&mut metadata, summary.first_token_ms);
|
||||
record_live_response_stream_event(
|
||||
context,
|
||||
status_code,
|
||||
UsageRecordLevel::Warn,
|
||||
"v1 responses stream cancelled",
|
||||
metadata,
|
||||
rate_limit_headers,
|
||||
body,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn record_success(
|
||||
context: &StreamContext<'_>,
|
||||
summary: &StreamSummary,
|
||||
response: &Value,
|
||||
completed: bool,
|
||||
rate_limit_headers: &[(String, String)],
|
||||
body: &str,
|
||||
) {
|
||||
record_live_response_stream_event(
|
||||
context,
|
||||
200,
|
||||
UsageRecordLevel::Info,
|
||||
if completed {
|
||||
"v1 responses stream completed"
|
||||
} else {
|
||||
"v1 responses stream incomplete"
|
||||
},
|
||||
serde_json::json!({
|
||||
"stream": true,
|
||||
"completed": completed,
|
||||
"incomplete": !completed,
|
||||
"responseId": response.get("id").and_then(Value::as_str),
|
||||
"firstEventMs": summary.first_event_ms,
|
||||
"firstTokenMs": summary.first_token_ms,
|
||||
"usage": summary.usage,
|
||||
}),
|
||||
rate_limit_headers,
|
||||
body,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
fn synthetic_failure(terminal: &StreamTerminal) -> ResponsesSseFailure {
|
||||
let detail = terminal.synthetic_failure_detail().unwrap_or_default();
|
||||
ResponsesSseFailure {
|
||||
event: "response.failed".to_string(),
|
||||
message: if detail.trim().is_empty() {
|
||||
STREAM_DISCONNECTED_MESSAGE.to_string()
|
||||
} else {
|
||||
format!("{STREAM_DISCONNECTED_MESSAGE}: {detail}")
|
||||
},
|
||||
upstream_code: Some(STREAM_DISCONNECTED_CODE.to_string()),
|
||||
upstream_type: Some("server_error".to_string()),
|
||||
explicit_status_code: None,
|
||||
retry_after_seconds: None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn record_failure(
|
||||
context: &StreamContext<'_>,
|
||||
summary: &StreamSummary,
|
||||
failure: &ResponsesSseFailure,
|
||||
status_code: i64,
|
||||
rate_limit_headers: &[(String, String)],
|
||||
body: &str,
|
||||
) {
|
||||
let failure_source = stream_failure_source(failure);
|
||||
let failure_detail = synthetic_stream_disconnected_detail(failure);
|
||||
tracing::warn!(
|
||||
account_id = %context.account_id,
|
||||
request_id = %context.request_id,
|
||||
response_id = summary.last_response_id.as_deref().unwrap_or(""),
|
||||
transport = %backend_transport_name(context.transport),
|
||||
websocket_pool_kind = ?context.websocket_pool_decision.map(WebSocketPoolDecision::kind),
|
||||
first_token_ms = ?summary.first_token_ms,
|
||||
first_event_ms = summary.first_event_ms,
|
||||
latency_ms = elapsed_millis_i64(context.started_at),
|
||||
event = %failure.event,
|
||||
code = ?failure.upstream_code.as_deref(),
|
||||
failure_source,
|
||||
failure_detail = ?failure_detail.as_deref(),
|
||||
"Live upstream stream ended with response.failed"
|
||||
);
|
||||
let mut metadata = stream_failure_metadata(failure, summary.usage);
|
||||
metadata["responseId"] = summary
|
||||
.last_response_id
|
||||
.as_ref()
|
||||
.map_or(Value::Null, |response_id| {
|
||||
Value::String(response_id.clone())
|
||||
});
|
||||
insert_first_token_ms(&mut metadata, summary.first_token_ms);
|
||||
metadata["firstEventMs"] = Value::Number(summary.first_event_ms.into());
|
||||
record_live_response_stream_event(
|
||||
context,
|
||||
status_code,
|
||||
UsageRecordLevel::Error,
|
||||
"v1 responses stream failed",
|
||||
metadata,
|
||||
rate_limit_headers,
|
||||
body,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//! 配额响应头与 token 用量写入的唯一 feature owner。
|
||||
|
||||
use crate::{
|
||||
dispatch::lifecycle::contract::{
|
||||
AttemptObservation, AttemptObservationKind, CompleteResponseFacts,
|
||||
},
|
||||
fleet::pool::AccountPoolService,
|
||||
upstream::openai::{
|
||||
protocol::{events::TokenUsage, responses::CodexResponsesRequest},
|
||||
transport::{CodexRateLimitHeaderUpdates, CodexTurnStateUpdate},
|
||||
},
|
||||
};
|
||||
|
||||
pub(super) struct UsageScope {
|
||||
image_generation_requested: bool,
|
||||
}
|
||||
|
||||
pub(super) struct StreamUsageExit {
|
||||
pub(super) rate_limit_headers: Vec<(String, String)>,
|
||||
pub(super) turn_state: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) struct StreamExit<'a> {
|
||||
pub account_pool: &'a AccountPoolService,
|
||||
pub account_id: &'a str,
|
||||
pub account_plan_type: Option<&'a str>,
|
||||
pub rate_limit_headers: &'a [(String, String)],
|
||||
pub rate_limit_header_updates: Option<&'a CodexRateLimitHeaderUpdates>,
|
||||
pub turn_state_update: Option<&'a CodexTurnStateUpdate>,
|
||||
pub turn_state: Option<&'a str>,
|
||||
pub usage: Option<TokenUsage>,
|
||||
}
|
||||
|
||||
pub(super) struct UsageController;
|
||||
|
||||
impl UsageController {
|
||||
pub(super) fn enter(request: &CodexResponsesRequest) -> UsageScope {
|
||||
UsageScope {
|
||||
image_generation_requested: request.expects_image_generation(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn observe_attempt(
|
||||
account_pool: &AccountPoolService,
|
||||
scope: &UsageScope,
|
||||
observation: &AttemptObservation,
|
||||
) {
|
||||
if !matches!(
|
||||
observation.kind,
|
||||
AttemptObservationKind::CompleteResponse(CompleteResponseFacts::Empty)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
let Some(account_id) = observation
|
||||
.account
|
||||
.as_ref()
|
||||
.map(|account| account.id.as_str())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
account_pool
|
||||
.record_empty_response_attempt(account_id, scope.image_generation_requested)
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(super) async fn leave_complete(
|
||||
account_pool: &AccountPoolService,
|
||||
account_id: &str,
|
||||
usage: Option<TokenUsage>,
|
||||
image_generation_requested: bool,
|
||||
) {
|
||||
if let Some(usage) = usage {
|
||||
account_pool
|
||||
.record_response_usage(account_id, usage, image_generation_requested)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn leave_stream(exit: StreamExit<'_>) -> StreamUsageExit {
|
||||
let mut rate_limit_headers = exit.rate_limit_headers.to_vec();
|
||||
if let Some(updates) = exit.rate_limit_header_updates {
|
||||
rate_limit_headers.extend(updates.lock().await.iter().cloned());
|
||||
}
|
||||
exit.account_pool
|
||||
.sync_passive_rate_limit_headers_for_account(
|
||||
exit.account_id,
|
||||
exit.account_plan_type,
|
||||
&rate_limit_headers,
|
||||
)
|
||||
.await;
|
||||
let turn_state = if let Some(update) = exit.turn_state_update {
|
||||
update.lock().await.clone()
|
||||
} else {
|
||||
exit.turn_state.map(ToString::to_string)
|
||||
};
|
||||
if let Some(usage) = exit.usage {
|
||||
exit.account_pool
|
||||
.record_token_usage(exit.account_id, &usage)
|
||||
.await;
|
||||
}
|
||||
StreamUsageExit {
|
||||
rate_limit_headers,
|
||||
turn_state,
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
-138
@@ -1,13 +1,12 @@
|
||||
//! Shared upstream error classification for dispatch routes.
|
||||
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use serde_json::{json, Map, Value};
|
||||
use serde_json::{Map, Value, json};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
recovery::exhaustion::{ExhaustedAccount, ExhaustedAccountKind, ExhaustedAccountRef},
|
||||
stream::sse_failure::{sse_failure_error_body, stream_failure_http_status},
|
||||
dispatch::failure::{
|
||||
exhaustion::{ExhaustedAccount, ExhaustedAccountKind, ExhaustedAccountRef},
|
||||
sse::sse_failure_error_body,
|
||||
},
|
||||
upstream::openai::{
|
||||
protocol::{responses::ResponsesSseFailure, sse::SseError},
|
||||
@@ -15,6 +14,41 @@ use crate::{
|
||||
},
|
||||
};
|
||||
|
||||
/// controller 已经完成分类、可直接交给 API 编码的客户端失败事实。
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ClientFailure {
|
||||
failure: ResponsesSseFailure,
|
||||
status_code: u16,
|
||||
expose_upstream: bool,
|
||||
}
|
||||
|
||||
impl ClientFailure {
|
||||
pub(in crate::dispatch) fn new(
|
||||
failure: ResponsesSseFailure,
|
||||
status_code: u16,
|
||||
expose_upstream: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
failure,
|
||||
status_code,
|
||||
expose_upstream,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn failure(&self) -> &ResponsesSseFailure {
|
||||
&self.failure
|
||||
}
|
||||
|
||||
pub(crate) fn status_code(&self) -> u16 {
|
||||
self.status_code
|
||||
}
|
||||
|
||||
/// 只有 controller 明确允许时,API 才透传上游 code/message。
|
||||
pub(crate) fn exposed_upstream(&self) -> Option<&ResponsesSseFailure> {
|
||||
self.expose_upstream.then_some(&self.failure)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct DispatchErrorMetadata {
|
||||
pub failure_class: DispatchFailureClass,
|
||||
@@ -188,77 +222,7 @@ pub(crate) fn upstream_error_diagnostics(
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_rate_limit_upstream_error(error: &CodexClientError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
CodexClientError::Upstream { status, .. } if status_code_is_rate_limited(status.as_u16())
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn is_retryable_upstream_5xx_error(error: &CodexClientError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
CodexClientError::Upstream { status, .. }
|
||||
if status_code_is_transient_upstream(status.as_u16())
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn is_retryable_account_transport_error(error: &CodexClientError) -> bool {
|
||||
match error {
|
||||
CodexClientError::Http(error) => error.is_connect() || error.is_timeout(),
|
||||
CodexClientError::WebSocket(
|
||||
crate::upstream::openai::transport::websocket::CodexWebSocketExchangeError::Transport(_)
|
||||
| crate::upstream::openai::transport::websocket::CodexWebSocketExchangeError::ClosedBeforeTerminal
|
||||
| crate::upstream::openai::transport::websocket::CodexWebSocketExchangeError::ReceiveIdleTimeout { .. }
|
||||
| crate::upstream::openai::transport::websocket::CodexWebSocketExchangeError::ReusedConnectionDiedBeforeFirstOutput { .. }
|
||||
| crate::upstream::openai::transport::websocket::CodexWebSocketExchangeError::InitialEventTimeout { .. },
|
||||
) => true,
|
||||
_ => is_retryable_upstream_5xx_error(error),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_quota_exhausted_upstream_error(error: &CodexClientError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
CodexClientError::Upstream { status, .. } if status_code_is_quota_exhausted(status.as_u16())
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn is_model_unsupported_upstream_error(error: &CodexClientError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
CodexClientError::Upstream { status, body, .. }
|
||||
if status.is_client_error()
|
||||
&& !matches!(status.as_u16(), 401 | 402 | 403 | 404 | 429)
|
||||
&& is_model_unsupported_signal(body)
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn is_history_recovery_upstream_error(error: &CodexClientError) -> bool {
|
||||
upstream_error_code(error).is_some_and(|code| is_history_recovery_code(&code))
|
||||
|| matches!(
|
||||
error,
|
||||
CodexClientError::WebSocket(
|
||||
crate::upstream::openai::transport::websocket::CodexWebSocketExchangeError::ContinuationUnavailable { reason }
|
||||
) if !matches!(
|
||||
reason,
|
||||
crate::upstream::openai::transport::websocket::PreviousResponseUnavailableReason::ConnectionBusy
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn is_continuation_busy_error(error: &CodexClientError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
CodexClientError::WebSocket(
|
||||
crate::upstream::openai::transport::websocket::CodexWebSocketExchangeError::ContinuationUnavailable {
|
||||
reason: crate::upstream::openai::transport::websocket::PreviousResponseUnavailableReason::ConnectionBusy,
|
||||
}
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn upstream_error_body(error: &CodexClientError) -> String {
|
||||
fn upstream_error_body(error: &CodexClientError) -> String {
|
||||
match error {
|
||||
CodexClientError::Upstream { body, .. } => body.clone(),
|
||||
error => error.to_string(),
|
||||
@@ -274,54 +238,6 @@ pub(crate) fn upstream_error_set_cookie_headers(error: &CodexClientError) -> &[S
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_model_unsupported_signal(value: &str) -> bool {
|
||||
let value = value.to_ascii_lowercase();
|
||||
value.contains("model_not_supported")
|
||||
|| value.contains("model_not_available")
|
||||
|| (value.contains("model")
|
||||
&& (value.contains("not supported")
|
||||
|| value.contains("not available")
|
||||
|| value.contains("not_supported")
|
||||
|| value.contains("not_available")))
|
||||
}
|
||||
|
||||
pub(crate) fn is_history_recovery_code(code: &str) -> bool {
|
||||
matches!(
|
||||
code,
|
||||
"previous_response_not_found"
|
||||
| "invalid_encrypted_content"
|
||||
| "missing_tool_output"
|
||||
| "no_tool_output"
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn upstream_error_code(error: &CodexClientError) -> Option<String> {
|
||||
let CodexClientError::Upstream { body, .. } = error else {
|
||||
return None;
|
||||
};
|
||||
let value = serde_json::from_str::<Value>(body).ok()?;
|
||||
value
|
||||
.pointer("/response/error/code")
|
||||
.or_else(|| value.pointer("/error/code"))
|
||||
.or_else(|| value.get("code"))
|
||||
.and_then(Value::as_str)
|
||||
.map(ToString::to_string)
|
||||
}
|
||||
|
||||
pub(crate) fn rate_limit_cooldown_until(
|
||||
error: &CodexClientError,
|
||||
now: DateTime<Utc>,
|
||||
) -> DateTime<Utc> {
|
||||
let retry_after_seconds = match error {
|
||||
CodexClientError::Upstream {
|
||||
retry_after_seconds,
|
||||
..
|
||||
} => retry_after_seconds.unwrap_or(60),
|
||||
_ => 60,
|
||||
};
|
||||
now + Duration::seconds(retry_after_seconds.min(i64::MAX as u64) as i64)
|
||||
}
|
||||
|
||||
pub(crate) fn upstream_error_http_status(error: &CodexClientError) -> u16 {
|
||||
match error {
|
||||
CodexClientError::Upstream { status, .. } => status.as_u16(),
|
||||
@@ -336,17 +252,6 @@ pub(crate) fn backend_transport_name(transport: CodexBackendTransport) -> &'stat
|
||||
}
|
||||
}
|
||||
|
||||
fn status_code_is_rate_limited(status_code: u16) -> bool {
|
||||
status_code == 429
|
||||
}
|
||||
|
||||
fn status_code_is_quota_exhausted(status_code: u16) -> bool {
|
||||
status_code == 402
|
||||
}
|
||||
|
||||
fn status_code_is_transient_upstream(status_code: u16) -> bool {
|
||||
matches!(status_code, 500..=599)
|
||||
}
|
||||
/// Responses 调度错误。
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ResponseDispatchError {
|
||||
@@ -411,7 +316,7 @@ pub enum ResponseDispatchError {
|
||||
#[error("upstream response did not include visible output")]
|
||||
EmptyUpstreamResponse,
|
||||
#[error("upstream response failed: {0:?}")]
|
||||
Failed(ResponsesSseFailure),
|
||||
Failed(ClientFailure),
|
||||
}
|
||||
|
||||
impl ResponseDispatchError {
|
||||
@@ -471,7 +376,7 @@ impl ResponseDispatchError {
|
||||
| Self::EmptyUpstreamResponse => 502,
|
||||
Self::UpstreamUnavailable { .. } => 503,
|
||||
Self::ContinuationBusy => 503,
|
||||
Self::Failed(failure) => stream_failure_http_status(failure),
|
||||
Self::Failed(failure) => failure.status_code(),
|
||||
Self::ModelUnsupported { .. } | Self::HistoryUnavailable { .. } => 400,
|
||||
Self::Upstream(error) => upstream_error_http_status(error),
|
||||
}
|
||||
@@ -567,7 +472,7 @@ impl ResponseDispatchError {
|
||||
Self::Failed(failure) => DispatchErrorMetadata {
|
||||
failure_class: DispatchFailureClass::ResponseFailed,
|
||||
exhausted_count: None,
|
||||
upstream_error: Some(sse_failure_error_body(failure)),
|
||||
upstream_error: Some(sse_failure_error_body(failure.failure())),
|
||||
upstream_status: None,
|
||||
diagnostics: None,
|
||||
},
|
||||
|
||||
+40
-97
@@ -1,8 +1,6 @@
|
||||
//! 账号耗尽状态聚合。
|
||||
|
||||
use crate::fleet::account::AccountStatus;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum ExhaustedAccountKind {
|
||||
QuotaExhausted,
|
||||
RateLimited,
|
||||
@@ -15,6 +13,35 @@ pub(crate) enum ExhaustedAccountKind {
|
||||
UpstreamUnavailable,
|
||||
}
|
||||
|
||||
/// Controller 交给 attempt runner 聚合的单账号耗尽事实。
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) struct AccountExhaustionRecord {
|
||||
pub account_id: Option<String>,
|
||||
pub kind: ExhaustedAccountKind,
|
||||
pub upstream_error: String,
|
||||
pub status_code: Option<u16>,
|
||||
}
|
||||
|
||||
impl AccountExhaustionRecord {
|
||||
pub(in crate::dispatch) fn new(
|
||||
account_id: impl Into<String>,
|
||||
kind: ExhaustedAccountKind,
|
||||
upstream_error: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
account_id: Some(account_id.into()),
|
||||
kind,
|
||||
upstream_error: upstream_error.into(),
|
||||
status_code: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn with_status_code(mut self, status_code: u16) -> Self {
|
||||
self.status_code = Some(status_code);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl ExhaustedAccountKind {
|
||||
pub(crate) fn message_reason(self) -> &'static str {
|
||||
match self {
|
||||
@@ -31,7 +58,7 @@ impl ExhaustedAccountKind {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct ExhaustedAccount {
|
||||
pub kind: ExhaustedAccountKind,
|
||||
pub count: usize,
|
||||
@@ -69,100 +96,12 @@ struct ExhaustedCounter {
|
||||
}
|
||||
|
||||
impl AccountExhaustionTracker {
|
||||
pub(crate) fn last_account_id(&self) -> Option<&str> {
|
||||
self.last_account_id.as_deref()
|
||||
}
|
||||
|
||||
pub(crate) fn record_rate_limited(
|
||||
&mut self,
|
||||
account_id: Option<&str>,
|
||||
upstream_error: impl Into<String>,
|
||||
) {
|
||||
pub(in crate::dispatch) fn record_exhaustion(&mut self, record: AccountExhaustionRecord) {
|
||||
self.record(
|
||||
account_id,
|
||||
ExhaustedAccountKind::RateLimited,
|
||||
upstream_error,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn record_quota_exhausted(
|
||||
&mut self,
|
||||
account_id: Option<&str>,
|
||||
upstream_error: impl Into<String>,
|
||||
) {
|
||||
self.record(
|
||||
account_id,
|
||||
ExhaustedAccountKind::QuotaExhausted,
|
||||
upstream_error,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn record_auth_failure(
|
||||
&mut self,
|
||||
account_id: Option<&str>,
|
||||
account_status: AccountStatus,
|
||||
upstream_error: impl Into<String>,
|
||||
status_code: Option<u16>,
|
||||
) {
|
||||
let kind = match account_status {
|
||||
AccountStatus::Disabled => ExhaustedAccountKind::Disabled,
|
||||
AccountStatus::Banned => ExhaustedAccountKind::Banned,
|
||||
_ => ExhaustedAccountKind::Expired,
|
||||
};
|
||||
self.record(account_id, kind, upstream_error, status_code);
|
||||
}
|
||||
|
||||
pub(crate) fn record_cloudflare_challenge(
|
||||
&mut self,
|
||||
account_id: Option<&str>,
|
||||
upstream_error: impl Into<String>,
|
||||
) {
|
||||
self.record(
|
||||
account_id,
|
||||
ExhaustedAccountKind::CloudflareChallenge,
|
||||
upstream_error,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn record_cloudflare_path_blocked(
|
||||
&mut self,
|
||||
account_id: Option<&str>,
|
||||
upstream_error: impl Into<String>,
|
||||
) {
|
||||
self.record(
|
||||
account_id,
|
||||
ExhaustedAccountKind::CloudflarePathBlocked,
|
||||
upstream_error,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn record_model_unsupported(
|
||||
&mut self,
|
||||
account_id: Option<&str>,
|
||||
upstream_error: impl Into<String>,
|
||||
) {
|
||||
self.record(
|
||||
account_id,
|
||||
ExhaustedAccountKind::ModelUnsupported,
|
||||
upstream_error,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn record_upstream_unavailable(
|
||||
&mut self,
|
||||
account_id: Option<&str>,
|
||||
upstream_error: impl Into<String>,
|
||||
) {
|
||||
self.record(
|
||||
account_id,
|
||||
ExhaustedAccountKind::UpstreamUnavailable,
|
||||
upstream_error,
|
||||
None,
|
||||
record.account_id.as_deref(),
|
||||
record.kind,
|
||||
record.upstream_error,
|
||||
record.status_code,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -177,6 +116,10 @@ impl AccountExhaustionTracker {
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn last_account_id(&self) -> Option<&str> {
|
||||
self.last_account_id.as_deref()
|
||||
}
|
||||
|
||||
fn record(
|
||||
&mut self,
|
||||
account_id: Option<&str>,
|
||||
@@ -0,0 +1,4 @@
|
||||
//! 已分类账号失败的聚合、状态副作用和 SSE 终态事实。
|
||||
|
||||
pub(crate) mod exhaustion;
|
||||
pub(in crate::dispatch) mod sse;
|
||||
@@ -0,0 +1,78 @@
|
||||
//! Responses SSE 失败事实和流终态元数据。
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::upstream::openai::protocol::{events::TokenUsage, responses::ResponsesSseFailure};
|
||||
|
||||
pub(in crate::dispatch) const STREAM_DISCONNECTED_CODE: &str = "stream_disconnected";
|
||||
pub(in crate::dispatch) const STREAM_DISCONNECTED_MESSAGE: &str =
|
||||
"Upstream stream closed before response.completed";
|
||||
|
||||
pub(in crate::dispatch) fn sse_failure_error_body(failure: &ResponsesSseFailure) -> String {
|
||||
match failure.upstream_code.as_deref() {
|
||||
Some(code) => serde_json::json!({
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": failure.message.as_str(),
|
||||
}
|
||||
})
|
||||
.to_string(),
|
||||
None => failure.message.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn stream_failure_metadata(
|
||||
failure: &ResponsesSseFailure,
|
||||
usage: Option<TokenUsage>,
|
||||
) -> Value {
|
||||
let mut metadata = serde_json::json!({
|
||||
"stream": true,
|
||||
"failed": true,
|
||||
"failureEvent": failure.event,
|
||||
"failureMessage": failure.message,
|
||||
"upstreamCode": failure.upstream_code,
|
||||
"usage": usage,
|
||||
});
|
||||
enrich_stream_failure_source_metadata(&mut metadata, failure);
|
||||
metadata
|
||||
}
|
||||
|
||||
fn enrich_stream_failure_source_metadata(metadata: &mut Value, failure: &ResponsesSseFailure) {
|
||||
let Some(object) = metadata.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
object.insert(
|
||||
"failureSource".to_string(),
|
||||
Value::String(stream_failure_source(failure).to_string()),
|
||||
);
|
||||
if let Some(detail) = synthetic_stream_disconnected_detail(failure) {
|
||||
object.insert("synthetic".to_string(), Value::Bool(true));
|
||||
if !detail.is_empty() {
|
||||
object.insert("failureDetail".to_string(), Value::String(detail));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn stream_failure_source(failure: &ResponsesSseFailure) -> &'static str {
|
||||
if synthetic_stream_disconnected_detail(failure).is_some() {
|
||||
"proxy"
|
||||
} else {
|
||||
"upstream"
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn synthetic_stream_disconnected_detail(
|
||||
failure: &ResponsesSseFailure,
|
||||
) -> Option<String> {
|
||||
if failure.upstream_code.as_deref() != Some(STREAM_DISCONNECTED_CODE) {
|
||||
return None;
|
||||
}
|
||||
let detail = failure
|
||||
.message
|
||||
.strip_prefix(STREAM_DISCONNECTED_MESSAGE)?
|
||||
.strip_prefix(": ")
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_string();
|
||||
Some(detail)
|
||||
}
|
||||
@@ -0,0 +1,990 @@
|
||||
//! 单账号 attempt 的 stepwise 执行器。
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
affinity::AccountIdentityService,
|
||||
controllers::{
|
||||
AttemptAccountPreparation, AttemptAccountPreparationContext, AttemptRoutePreparation,
|
||||
AttemptRoutePreparationContext, AttemptUpstreamErrorContext, ControllerRequestScope,
|
||||
ControllerSet,
|
||||
},
|
||||
errors::{ClientFailure, ResponseDispatchError},
|
||||
failure::exhaustion::AccountExhaustionTracker,
|
||||
routing::candidates::AccountAttemptLedger,
|
||||
transport::{
|
||||
account::{
|
||||
AccountUpstreamContext, create_response_stream_with_account,
|
||||
create_response_with_account, prepare_response_transport_with_account,
|
||||
},
|
||||
canonical::{CanonicalStreamDecoder, normalize_complete_response},
|
||||
observation::upstream_failure_facts,
|
||||
prefetch::{PrefetchedStream, StreamPrefetchError, prefetch_until_commit},
|
||||
},
|
||||
},
|
||||
fleet::{
|
||||
account::Account,
|
||||
pool::{AccountCandidateLease, AccountPoolService},
|
||||
},
|
||||
upstream::openai::{
|
||||
protocol::responses::{
|
||||
CodexResponsesRequest, CollectedResponse, TransportRequirement, transport_requirement,
|
||||
},
|
||||
transport::{CodexBackendClient, CodexBackendStreamingResponse, CodexBackendTransport},
|
||||
},
|
||||
};
|
||||
|
||||
use super::{
|
||||
contract::{
|
||||
AttemptAccountFacts, AttemptApplyOutcome, AttemptContractError, AttemptDecision,
|
||||
AttemptObservation, AttemptObservationKind, AttemptRejection, AttemptReturnKind,
|
||||
CandidateLedgerFacts, CompleteResponseFacts, EstablishedAttemptContext,
|
||||
EstablishedComplete, EstablishedCompleteBody, EstablishedResponse, EstablishedStream,
|
||||
PendingAttempt, PendingCompleteResponse, PendingProtocolFailure, PendingStreamResponse,
|
||||
PinnedCandidateAcquireFailureKind, ProtocolFailureKind,
|
||||
},
|
||||
trace::ResponseDispatchTrace,
|
||||
};
|
||||
|
||||
pub(in crate::dispatch) enum AttemptMode {
|
||||
Complete {
|
||||
started_at: Instant,
|
||||
tuple_schema: Option<Value>,
|
||||
},
|
||||
Stream {
|
||||
tuple_schema: Option<Value>,
|
||||
},
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) struct AttemptRunnerDependencies<'a> {
|
||||
pub account_pool: &'a AccountPoolService,
|
||||
pub codex: &'a CodexBackendClient,
|
||||
pub controllers: &'a ControllerSet,
|
||||
pub account_identity: &'a AccountIdentityService,
|
||||
pub request_id: &'a str,
|
||||
pub route: &'a str,
|
||||
pub requested_model: &'a str,
|
||||
pub started_at: Instant,
|
||||
}
|
||||
|
||||
/// 尚未越过提交边界的 attempt capability;只有该类型接受 retry decision。
|
||||
pub(in crate::dispatch) struct OpenAttempt<'runner, 'dependencies> {
|
||||
runner: &'runner mut AttemptRunner<'dependencies>,
|
||||
observation: Box<AttemptObservation>,
|
||||
}
|
||||
|
||||
impl OpenAttempt<'_, '_> {
|
||||
pub(in crate::dispatch) fn observation(&self) -> &AttemptObservation {
|
||||
&self.observation
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn controller_scope(
|
||||
&self,
|
||||
) -> Result<&ControllerRequestScope, AttemptContractError> {
|
||||
self.runner.controller_scope()
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn apply(
|
||||
self,
|
||||
decision: AttemptDecision,
|
||||
) -> Result<AttemptApplyOutcome, AttemptContractError> {
|
||||
self.runner.apply_open(decision).await
|
||||
}
|
||||
}
|
||||
|
||||
/// 已越过提交边界的 attempt capability;该类型只允许建立 stream。
|
||||
pub(in crate::dispatch) struct CommittedAttempt {
|
||||
established: EstablishedResponse,
|
||||
}
|
||||
|
||||
impl CommittedAttempt {
|
||||
pub(in crate::dispatch) fn accept(self) -> EstablishedResponse {
|
||||
self.established
|
||||
}
|
||||
}
|
||||
|
||||
/// `next` 产出的提交 typestate;Committed 分支没有 decision/retry API。
|
||||
pub(in crate::dispatch) enum AttemptStep<'runner, 'dependencies> {
|
||||
Open(OpenAttempt<'runner, 'dependencies>),
|
||||
Committed(CommittedAttempt),
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) struct AttemptRunner<'a> {
|
||||
dependencies: AttemptRunnerDependencies<'a>,
|
||||
mode: AttemptMode,
|
||||
request: Option<CodexResponsesRequest>,
|
||||
controller_scope: Option<ControllerRequestScope>,
|
||||
candidates: AccountAttemptLedger,
|
||||
exhaustion: AccountExhaustionTracker,
|
||||
on_exhaustion: Option<ClientFailure>,
|
||||
trace: Option<ResponseDispatchTrace>,
|
||||
required_account_id: Option<String>,
|
||||
pending: Option<PendingAttempt>,
|
||||
}
|
||||
|
||||
impl<'a> AttemptRunner<'a> {
|
||||
pub(in crate::dispatch) fn new(
|
||||
dependencies: AttemptRunnerDependencies<'a>,
|
||||
mode: AttemptMode,
|
||||
request: CodexResponsesRequest,
|
||||
controller_scope: ControllerRequestScope,
|
||||
candidates: AccountAttemptLedger,
|
||||
) -> Self {
|
||||
Self {
|
||||
dependencies,
|
||||
mode,
|
||||
request: Some(request),
|
||||
controller_scope: Some(controller_scope),
|
||||
candidates,
|
||||
exhaustion: AccountExhaustionTracker::default(),
|
||||
on_exhaustion: None,
|
||||
trace: Some(ResponseDispatchTrace::default()),
|
||||
required_account_id: None,
|
||||
pending: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn next(
|
||||
&mut self,
|
||||
) -> Result<AttemptStep<'_, 'a>, AttemptContractError> {
|
||||
if self.pending.is_some() {
|
||||
return Err(AttemptContractError::DecisionRequired);
|
||||
}
|
||||
|
||||
let request = self
|
||||
.request
|
||||
.as_ref()
|
||||
.ok_or(AttemptContractError::Terminal)?;
|
||||
let acquired = if let Some(account_id) = self.required_account_id.take() {
|
||||
match self
|
||||
.dependencies
|
||||
.account_pool
|
||||
.acquire_candidate(request.model(), &account_id, chrono::Utc::now())
|
||||
.await
|
||||
{
|
||||
AccountCandidateLease::Acquired(acquired) => Some(*acquired),
|
||||
AccountCandidateLease::Busy => {
|
||||
self.pending = Some(PendingAttempt::PinnedCandidateUnavailable {
|
||||
account_id,
|
||||
kind: PinnedCandidateAcquireFailureKind::Busy,
|
||||
});
|
||||
return self.step();
|
||||
}
|
||||
AccountCandidateLease::Unavailable => {
|
||||
self.pending = Some(PendingAttempt::PinnedCandidateUnavailable {
|
||||
account_id,
|
||||
kind: PinnedCandidateAcquireFailureKind::Unavailable,
|
||||
});
|
||||
return self.step();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.candidates
|
||||
.acquire_next(self.dependencies.account_pool)
|
||||
.await
|
||||
};
|
||||
let Some(acquired) = acquired else {
|
||||
self.pending = Some(PendingAttempt::NoCandidate);
|
||||
return self.step();
|
||||
};
|
||||
|
||||
let account = acquired.account.clone();
|
||||
let controller_scope = self
|
||||
.controller_scope
|
||||
.as_mut()
|
||||
.ok_or(AttemptContractError::Terminal)?;
|
||||
let prepared_account = match self
|
||||
.dependencies
|
||||
.controllers
|
||||
.prepare_attempt_account(
|
||||
AttemptAccountPreparationContext {
|
||||
codex: self.dependencies.codex,
|
||||
account_identity: self.dependencies.account_identity,
|
||||
request_id: self.dependencies.request_id,
|
||||
},
|
||||
acquired,
|
||||
)
|
||||
.await
|
||||
{
|
||||
AttemptAccountPreparation::Ready(prepared) => *prepared,
|
||||
AttemptAccountPreparation::Rejected => {
|
||||
self.pending = Some(PendingAttempt::CandidatePreparationRejected { account });
|
||||
return self.step();
|
||||
}
|
||||
};
|
||||
let acquired = prepared_account.lease;
|
||||
let cookie_header = prepared_account.cookie_header;
|
||||
|
||||
let account_scoped_request = match self.dependencies.controllers.prepare_attempt_route(
|
||||
controller_scope,
|
||||
request,
|
||||
AttemptRoutePreparationContext {
|
||||
account_identity: self.dependencies.account_identity,
|
||||
account_id: &account.id,
|
||||
},
|
||||
) {
|
||||
AttemptRoutePreparation::Ready(request) => *request,
|
||||
AttemptRoutePreparation::Unavailable { message } => {
|
||||
acquired.release_without_usage().await;
|
||||
self.pending = Some(PendingAttempt::RoutePreparationRejected { account, message });
|
||||
return self.step();
|
||||
}
|
||||
};
|
||||
|
||||
let attempt = self
|
||||
.trace
|
||||
.as_mut()
|
||||
.ok_or(AttemptContractError::Terminal)?
|
||||
.start_attempt(&account.id);
|
||||
let upstream_context = AccountUpstreamContext {
|
||||
codex: self.dependencies.codex,
|
||||
request_id: self.dependencies.request_id,
|
||||
account: &account,
|
||||
cookie_header: cookie_header.as_deref(),
|
||||
};
|
||||
let ((), prepared_transport) = tokio::join!(
|
||||
self.dependencies
|
||||
.account_pool
|
||||
.wait_for_request_interval(&acquired),
|
||||
prepare_response_transport_with_account(upstream_context, &account_scoped_request),
|
||||
);
|
||||
let prepared_transport = match prepared_transport {
|
||||
Ok(prepared) => prepared,
|
||||
Err(error) => {
|
||||
let attempt_request = account_scoped_request.into_request();
|
||||
acquired.complete().await;
|
||||
let transport = error
|
||||
.transport()
|
||||
.unwrap_or_else(|| intended_transport(&attempt_request));
|
||||
observe_upstream_error(
|
||||
self.dependencies.controllers,
|
||||
AttemptUpstreamErrorContext {
|
||||
request_id: self.dependencies.request_id,
|
||||
account: &account,
|
||||
route: self.dependencies.route,
|
||||
model: self.dependencies.requested_model,
|
||||
started_at: self.dependencies.started_at,
|
||||
stream: matches!(self.mode, AttemptMode::Stream { .. }),
|
||||
transport,
|
||||
request: &attempt_request,
|
||||
error: &error,
|
||||
trace: self.trace.as_ref().ok_or(AttemptContractError::Terminal)?,
|
||||
attempt: &attempt,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
self.pending = Some(PendingAttempt::UpstreamFailure {
|
||||
account,
|
||||
attempt_request,
|
||||
attempt,
|
||||
transport,
|
||||
error,
|
||||
});
|
||||
return self.step();
|
||||
}
|
||||
};
|
||||
|
||||
match &self.mode {
|
||||
AttemptMode::Complete {
|
||||
started_at,
|
||||
tuple_schema,
|
||||
} => {
|
||||
let result = create_response_with_account(
|
||||
upstream_context,
|
||||
&account_scoped_request,
|
||||
prepared_transport,
|
||||
*started_at,
|
||||
)
|
||||
.await;
|
||||
let attempt_request = account_scoped_request.into_request();
|
||||
acquired.complete().await;
|
||||
self.pending = Some(match result {
|
||||
Ok(response) => {
|
||||
self.dependencies
|
||||
.controllers
|
||||
.observe_complete_upstream(
|
||||
&account,
|
||||
&response.set_cookie_headers,
|
||||
&response.rate_limit_headers,
|
||||
)
|
||||
.await;
|
||||
match normalize_complete_response(&response.body, tuple_schema.as_ref()) {
|
||||
Ok(collected) => PendingAttempt::CompleteResponse(Box::new(
|
||||
PendingCompleteResponse {
|
||||
account,
|
||||
attempt_request,
|
||||
attempt,
|
||||
response,
|
||||
collected,
|
||||
},
|
||||
)),
|
||||
Err(error) => PendingAttempt::ProtocolFailure {
|
||||
account,
|
||||
attempt_request,
|
||||
attempt,
|
||||
transport: response.transport,
|
||||
error: PendingProtocolFailure::InvalidSse(error),
|
||||
},
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
let transport = error
|
||||
.transport()
|
||||
.unwrap_or_else(|| intended_transport(request));
|
||||
observe_upstream_error(
|
||||
self.dependencies.controllers,
|
||||
AttemptUpstreamErrorContext {
|
||||
request_id: self.dependencies.request_id,
|
||||
account: &account,
|
||||
route: self.dependencies.route,
|
||||
model: self.dependencies.requested_model,
|
||||
started_at: self.dependencies.started_at,
|
||||
stream: matches!(self.mode, AttemptMode::Stream { .. }),
|
||||
transport,
|
||||
request: &attempt_request,
|
||||
error: &error,
|
||||
trace: self.trace.as_ref().ok_or(AttemptContractError::Terminal)?,
|
||||
attempt: &attempt,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
PendingAttempt::UpstreamFailure {
|
||||
account,
|
||||
attempt_request,
|
||||
attempt,
|
||||
transport,
|
||||
error,
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
AttemptMode::Stream { tuple_schema } => {
|
||||
let result = create_response_stream_with_account(
|
||||
upstream_context,
|
||||
&account_scoped_request,
|
||||
prepared_transport,
|
||||
)
|
||||
.await;
|
||||
let attempt_request = account_scoped_request.into_request();
|
||||
self.pending = Some(match result {
|
||||
Err(error) => {
|
||||
acquired.complete().await;
|
||||
let transport = error
|
||||
.transport()
|
||||
.unwrap_or_else(|| intended_transport(request));
|
||||
observe_upstream_error(
|
||||
self.dependencies.controllers,
|
||||
AttemptUpstreamErrorContext {
|
||||
request_id: self.dependencies.request_id,
|
||||
account: &account,
|
||||
route: self.dependencies.route,
|
||||
model: self.dependencies.requested_model,
|
||||
started_at: self.dependencies.started_at,
|
||||
stream: matches!(self.mode, AttemptMode::Stream { .. }),
|
||||
transport,
|
||||
request: &attempt_request,
|
||||
error: &error,
|
||||
trace: self.trace.as_ref().ok_or(AttemptContractError::Terminal)?,
|
||||
attempt: &attempt,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
PendingAttempt::UpstreamFailure {
|
||||
account,
|
||||
attempt_request,
|
||||
attempt,
|
||||
transport,
|
||||
error,
|
||||
}
|
||||
}
|
||||
Ok(response) => {
|
||||
let CodexBackendStreamingResponse {
|
||||
body,
|
||||
transport,
|
||||
turn_state,
|
||||
set_cookie_headers,
|
||||
rate_limit_headers,
|
||||
rate_limit_header_updates,
|
||||
turn_state_update,
|
||||
websocket_pool_decision,
|
||||
diagnostics,
|
||||
response_metadata,
|
||||
transport_metrics,
|
||||
connection_local_continuation,
|
||||
} = response;
|
||||
let mut decoder = CanonicalStreamDecoder::new(tuple_schema.clone());
|
||||
match prefetch_until_commit(
|
||||
body,
|
||||
&mut decoder,
|
||||
attempt_request.stream_commit_policy,
|
||||
self.dependencies.started_at,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Err(StreamPrefetchError::Upstream(error)) => {
|
||||
acquired.complete().await;
|
||||
observe_upstream_error(
|
||||
self.dependencies.controllers,
|
||||
AttemptUpstreamErrorContext {
|
||||
request_id: self.dependencies.request_id,
|
||||
account: &account,
|
||||
route: self.dependencies.route,
|
||||
model: self.dependencies.requested_model,
|
||||
started_at: self.dependencies.started_at,
|
||||
stream: matches!(self.mode, AttemptMode::Stream { .. }),
|
||||
transport,
|
||||
request: &attempt_request,
|
||||
error: &error,
|
||||
trace: self
|
||||
.trace
|
||||
.as_ref()
|
||||
.ok_or(AttemptContractError::Terminal)?,
|
||||
attempt: &attempt,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
PendingAttempt::UpstreamFailure {
|
||||
account,
|
||||
attempt_request,
|
||||
attempt,
|
||||
transport,
|
||||
error,
|
||||
}
|
||||
}
|
||||
Err(StreamPrefetchError::Empty) => {
|
||||
acquired.complete().await;
|
||||
PendingAttempt::ProtocolFailure {
|
||||
account,
|
||||
attempt_request,
|
||||
attempt,
|
||||
transport,
|
||||
error: PendingProtocolFailure::EmptyStream,
|
||||
}
|
||||
}
|
||||
Err(StreamPrefetchError::NoCommitBoundary) => {
|
||||
acquired.complete().await;
|
||||
PendingAttempt::ProtocolFailure {
|
||||
account,
|
||||
attempt_request,
|
||||
attempt,
|
||||
transport,
|
||||
error: PendingProtocolFailure::NoCommitBoundary,
|
||||
}
|
||||
}
|
||||
Err(StreamPrefetchError::InvalidSse(error)) => {
|
||||
acquired.complete().await;
|
||||
PendingAttempt::ProtocolFailure {
|
||||
account,
|
||||
attempt_request,
|
||||
attempt,
|
||||
transport,
|
||||
error: PendingProtocolFailure::InvalidSse(error),
|
||||
}
|
||||
}
|
||||
Ok(PrefetchedStream {
|
||||
bytes: prefetched,
|
||||
initial_batch,
|
||||
body,
|
||||
first_event_ms,
|
||||
}) => {
|
||||
let first_failure = initial_batch.first_failure();
|
||||
PendingAttempt::StreamResponse(Box::new(PendingStreamResponse {
|
||||
account,
|
||||
attempt_request,
|
||||
attempt,
|
||||
lease: acquired,
|
||||
response: CodexBackendStreamingResponse {
|
||||
body,
|
||||
transport,
|
||||
turn_state,
|
||||
set_cookie_headers,
|
||||
rate_limit_headers,
|
||||
rate_limit_header_updates,
|
||||
turn_state_update,
|
||||
websocket_pool_decision,
|
||||
diagnostics,
|
||||
response_metadata,
|
||||
transport_metrics,
|
||||
connection_local_continuation,
|
||||
},
|
||||
prefetched,
|
||||
decoder,
|
||||
initial_batch,
|
||||
first_failure,
|
||||
first_event_ms,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
self.step()
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn controller_scope(
|
||||
&self,
|
||||
) -> Result<&ControllerRequestScope, AttemptContractError> {
|
||||
self.controller_scope
|
||||
.as_ref()
|
||||
.ok_or(AttemptContractError::Terminal)
|
||||
}
|
||||
|
||||
async fn apply_open(
|
||||
&mut self,
|
||||
decision: AttemptDecision,
|
||||
) -> Result<AttemptApplyOutcome, AttemptContractError> {
|
||||
let pending = self
|
||||
.pending
|
||||
.take()
|
||||
.ok_or(AttemptContractError::DecisionRequired)?;
|
||||
match decision {
|
||||
AttemptDecision::Accept => self
|
||||
.establish(pending)
|
||||
.map(AttemptApplyOutcome::Established),
|
||||
AttemptDecision::RetrySameAccount => {
|
||||
let account_id = pending_account(&pending)
|
||||
.ok_or_else(|| invalid("retry_same", &pending))?
|
||||
.to_string();
|
||||
if !self.dependencies.controllers.prepare_same_account_retry(
|
||||
self.controller_scope
|
||||
.as_mut()
|
||||
.ok_or(AttemptContractError::Terminal)?,
|
||||
&account_id,
|
||||
) {
|
||||
return Err(invalid("retry_same", &pending));
|
||||
}
|
||||
release_pending_stream(pending).await;
|
||||
self.required_account_id = Some(account_id);
|
||||
Ok(AttemptApplyOutcome::Continue)
|
||||
}
|
||||
AttemptDecision::RetryNextCandidate {
|
||||
exhaustion,
|
||||
on_exhaustion,
|
||||
} => {
|
||||
release_pending_stream(pending).await;
|
||||
self.on_exhaustion = on_exhaustion;
|
||||
if let Some(exhaustion) = exhaustion {
|
||||
self.exhaustion.record_exhaustion(exhaustion);
|
||||
}
|
||||
Ok(AttemptApplyOutcome::Continue)
|
||||
}
|
||||
AttemptDecision::Return(kind) => self.reject(pending, kind).await,
|
||||
}
|
||||
}
|
||||
|
||||
fn step(&mut self) -> Result<AttemptStep<'_, 'a>, AttemptContractError> {
|
||||
let kind = {
|
||||
let pending = self
|
||||
.pending
|
||||
.as_ref()
|
||||
.ok_or(AttemptContractError::DecisionRequired)?;
|
||||
observation_kind(pending, &self.candidates, &self.exhaustion)
|
||||
};
|
||||
let Some(kind) = kind else {
|
||||
let pending = self
|
||||
.pending
|
||||
.take()
|
||||
.ok_or(AttemptContractError::DecisionRequired)?;
|
||||
return Ok(AttemptStep::Committed(CommittedAttempt {
|
||||
established: self.establish(pending)?,
|
||||
}));
|
||||
};
|
||||
let observation = self.observation(kind)?;
|
||||
Ok(AttemptStep::Open(OpenAttempt {
|
||||
runner: self,
|
||||
observation: Box::new(observation),
|
||||
}))
|
||||
}
|
||||
|
||||
fn observation(
|
||||
&self,
|
||||
kind: AttemptObservationKind,
|
||||
) -> Result<AttemptObservation, AttemptContractError> {
|
||||
let pending = self
|
||||
.pending
|
||||
.as_ref()
|
||||
.ok_or(AttemptContractError::DecisionRequired)?;
|
||||
let request = self
|
||||
.request
|
||||
.as_ref()
|
||||
.ok_or(AttemptContractError::Terminal)?;
|
||||
let controller_scope = self
|
||||
.controller_scope
|
||||
.as_ref()
|
||||
.ok_or(AttemptContractError::Terminal)?;
|
||||
let account = pending_account_value(pending);
|
||||
let account_id = account.map(|account| account.id.as_str());
|
||||
Ok(AttemptObservation {
|
||||
account: account.map(AttemptAccountFacts::from),
|
||||
attempt: pending_attempt(pending).cloned(),
|
||||
transport: pending_transport(pending).unwrap_or_else(|| intended_transport(request)),
|
||||
routing: self
|
||||
.dependencies
|
||||
.controllers
|
||||
.attempt_routing_facts(controller_scope, account_id),
|
||||
kind,
|
||||
})
|
||||
}
|
||||
|
||||
fn establish(
|
||||
&mut self,
|
||||
pending: PendingAttempt,
|
||||
) -> Result<EstablishedResponse, AttemptContractError> {
|
||||
let established = match pending {
|
||||
PendingAttempt::CompleteResponse(complete) => {
|
||||
let PendingCompleteResponse {
|
||||
account,
|
||||
attempt,
|
||||
response,
|
||||
collected,
|
||||
..
|
||||
} = *complete;
|
||||
let body = EstablishedCompleteBody::try_from(collected).map_err(|()| {
|
||||
AttemptContractError::InvalidDecision {
|
||||
decision: "establish",
|
||||
observation: "non_successful_complete_response",
|
||||
}
|
||||
})?;
|
||||
EstablishedResponse::Complete(Box::new(EstablishedComplete {
|
||||
context: self.take_established_context(account, attempt)?,
|
||||
response,
|
||||
body,
|
||||
}))
|
||||
}
|
||||
PendingAttempt::StreamResponse(stream) => {
|
||||
let PendingStreamResponse {
|
||||
account,
|
||||
attempt,
|
||||
lease,
|
||||
response,
|
||||
decoder,
|
||||
initial_batch,
|
||||
first_event_ms,
|
||||
..
|
||||
} = *stream;
|
||||
EstablishedResponse::Stream(Box::new(EstablishedStream {
|
||||
context: self.take_established_context(account, attempt)?,
|
||||
lease,
|
||||
response,
|
||||
decoder,
|
||||
initial_batch,
|
||||
first_event_ms,
|
||||
}))
|
||||
}
|
||||
other => return Err(invalid("establish", &other)),
|
||||
};
|
||||
Ok(established)
|
||||
}
|
||||
|
||||
async fn reject(
|
||||
&mut self,
|
||||
pending: PendingAttempt,
|
||||
kind: AttemptReturnKind,
|
||||
) -> Result<AttemptApplyOutcome, AttemptContractError> {
|
||||
let account = pending_account_value(&pending).cloned();
|
||||
let account_id = account
|
||||
.as_ref()
|
||||
.map(|account| account.id.clone())
|
||||
.or_else(|| self.exhaustion.last_account_id().map(ToString::to_string));
|
||||
let attempt_request = pending_attempt_request(&pending).cloned();
|
||||
let attempt = pending_attempt(&pending).cloned();
|
||||
let request = self
|
||||
.request
|
||||
.as_ref()
|
||||
.ok_or(AttemptContractError::Terminal)?;
|
||||
let transport = pending_transport(&pending).unwrap_or_else(|| intended_transport(request));
|
||||
let stream_failure = match &pending {
|
||||
PendingAttempt::StreamResponse(stream) => {
|
||||
stream.first_failure.as_ref().map(|failure| {
|
||||
super::contract::RejectedStreamFailure {
|
||||
failure: failure.clone(),
|
||||
prefetched: stream.prefetched.clone(),
|
||||
diagnostics: stream.response.diagnostics.clone(),
|
||||
rate_limit_headers: stream.response.rate_limit_headers.clone(),
|
||||
}
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let error =
|
||||
rejection_error(pending, kind, &self.exhaustion, self.on_exhaustion.take()).await?;
|
||||
let request = self.request.take().ok_or(AttemptContractError::Terminal)?;
|
||||
self.controller_scope
|
||||
.take()
|
||||
.ok_or(AttemptContractError::Terminal)?;
|
||||
let trace = self.trace.take().ok_or(AttemptContractError::Terminal)?;
|
||||
Ok(AttemptApplyOutcome::Rejected(Box::new(AttemptRejection {
|
||||
request,
|
||||
trace,
|
||||
account_id,
|
||||
account,
|
||||
attempt_request,
|
||||
attempt,
|
||||
transport,
|
||||
stream_failure,
|
||||
error,
|
||||
})))
|
||||
}
|
||||
|
||||
fn take_established_context(
|
||||
&mut self,
|
||||
account: Account,
|
||||
attempt: super::trace::ResponseDispatchAttempt,
|
||||
) -> Result<EstablishedAttemptContext, AttemptContractError> {
|
||||
Ok(EstablishedAttemptContext {
|
||||
request: self.request.take().ok_or(AttemptContractError::Terminal)?,
|
||||
controller_scope: self
|
||||
.controller_scope
|
||||
.take()
|
||||
.ok_or(AttemptContractError::Terminal)?,
|
||||
trace: self.trace.take().ok_or(AttemptContractError::Terminal)?,
|
||||
account,
|
||||
attempt,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn observe_upstream_error(
|
||||
controllers: &ControllerSet,
|
||||
context: AttemptUpstreamErrorContext<'_>,
|
||||
) {
|
||||
controllers.observe_upstream_error(context).await;
|
||||
}
|
||||
|
||||
fn observation_kind(
|
||||
pending: &PendingAttempt,
|
||||
candidates: &AccountAttemptLedger,
|
||||
exhaustion: &AccountExhaustionTracker,
|
||||
) -> Option<AttemptObservationKind> {
|
||||
Some(match pending {
|
||||
PendingAttempt::NoCandidate => AttemptObservationKind::NoCandidate {
|
||||
ledger: CandidateLedgerFacts {
|
||||
candidates: candidates.candidate_count(),
|
||||
attempted: candidates.attempted_count(),
|
||||
state_excluded: candidates.state_excluded_count(),
|
||||
},
|
||||
last_exhausted: exhaustion.last_exhausted(),
|
||||
},
|
||||
PendingAttempt::PinnedCandidateUnavailable { account_id, kind } => {
|
||||
AttemptObservationKind::PinnedCandidateUnavailable {
|
||||
account_id: account_id.clone(),
|
||||
kind: *kind,
|
||||
}
|
||||
}
|
||||
PendingAttempt::CandidatePreparationRejected { .. } => {
|
||||
AttemptObservationKind::CandidatePreparationRejected
|
||||
}
|
||||
PendingAttempt::RoutePreparationRejected { message, .. } => {
|
||||
AttemptObservationKind::RoutePreparationRejected {
|
||||
message: message.clone(),
|
||||
}
|
||||
}
|
||||
PendingAttempt::UpstreamFailure { error, .. } => {
|
||||
AttemptObservationKind::UpstreamFailure(upstream_failure_facts(error))
|
||||
}
|
||||
PendingAttempt::ProtocolFailure { error, .. } => AttemptObservationKind::ProtocolFailure {
|
||||
kind: match error {
|
||||
PendingProtocolFailure::InvalidSse(_) => ProtocolFailureKind::InvalidSse,
|
||||
PendingProtocolFailure::EmptyStream => ProtocolFailureKind::EmptyStream,
|
||||
PendingProtocolFailure::NoCommitBoundary => ProtocolFailureKind::NoCommitBoundary,
|
||||
},
|
||||
message: match error {
|
||||
PendingProtocolFailure::InvalidSse(error) => error.to_string(),
|
||||
PendingProtocolFailure::EmptyStream => {
|
||||
"upstream stream ended without data".to_string()
|
||||
}
|
||||
PendingProtocolFailure::NoCommitBoundary => {
|
||||
"upstream stream ended before output or a terminal event".to_string()
|
||||
}
|
||||
},
|
||||
},
|
||||
PendingAttempt::CompleteResponse(complete) => {
|
||||
AttemptObservationKind::CompleteResponse(match &complete.collected {
|
||||
CollectedResponse::Completed(_) => CompleteResponseFacts::Completed,
|
||||
CollectedResponse::Incomplete(_) => CompleteResponseFacts::Incomplete,
|
||||
CollectedResponse::Failed(failure) => {
|
||||
CompleteResponseFacts::Failed(failure.clone())
|
||||
}
|
||||
CollectedResponse::MissingCompleted => CompleteResponseFacts::MissingCompleted,
|
||||
CollectedResponse::Empty => CompleteResponseFacts::Empty,
|
||||
})
|
||||
}
|
||||
PendingAttempt::StreamResponse(stream) => {
|
||||
return stream
|
||||
.first_failure
|
||||
.clone()
|
||||
.map(AttemptObservationKind::StreamFailure);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn release_pending_stream(pending: PendingAttempt) {
|
||||
if let PendingAttempt::StreamResponse(stream) = pending {
|
||||
stream.lease.complete().await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn rejection_error(
|
||||
pending: PendingAttempt,
|
||||
kind: AttemptReturnKind,
|
||||
exhaustion: &AccountExhaustionTracker,
|
||||
on_exhaustion: Option<ClientFailure>,
|
||||
) -> Result<ResponseDispatchError, AttemptContractError> {
|
||||
match kind {
|
||||
AttemptReturnKind::Failed(failure) => {
|
||||
release_pending_stream(pending).await;
|
||||
Ok(ResponseDispatchError::Failed(failure))
|
||||
}
|
||||
AttemptReturnKind::ContinuationBusy => Ok(ResponseDispatchError::ContinuationBusy),
|
||||
AttemptReturnKind::RouteUnavailable { message } => {
|
||||
Ok(ResponseDispatchError::HistoryUnavailable {
|
||||
upstream_error: message,
|
||||
})
|
||||
}
|
||||
AttemptReturnKind::Observed => match pending {
|
||||
PendingAttempt::NoCandidate | PendingAttempt::CandidatePreparationRejected { .. } => {
|
||||
Ok(on_exhaustion.map_or_else(
|
||||
|| {
|
||||
exhaustion
|
||||
.last_exhausted()
|
||||
.map(ResponseDispatchError::from_exhausted_account)
|
||||
.unwrap_or(ResponseDispatchError::NoActiveAccount)
|
||||
},
|
||||
ResponseDispatchError::Failed,
|
||||
))
|
||||
}
|
||||
PendingAttempt::RoutePreparationRejected { message, .. } => {
|
||||
Ok(ResponseDispatchError::HistoryUnavailable {
|
||||
upstream_error: message,
|
||||
})
|
||||
}
|
||||
PendingAttempt::PinnedCandidateUnavailable { .. } => {
|
||||
Err(invalid("return", &PendingAttempt::NoCandidate))
|
||||
}
|
||||
PendingAttempt::UpstreamFailure { error, .. } => {
|
||||
Ok(ResponseDispatchError::Upstream(error))
|
||||
}
|
||||
PendingAttempt::ProtocolFailure { error, .. } => Ok(match error {
|
||||
PendingProtocolFailure::InvalidSse(error) => {
|
||||
ResponseDispatchError::InvalidSse(error)
|
||||
}
|
||||
PendingProtocolFailure::EmptyStream => ResponseDispatchError::EmptyUpstreamResponse,
|
||||
PendingProtocolFailure::NoCommitBoundary => ResponseDispatchError::MissingCompleted,
|
||||
}),
|
||||
PendingAttempt::CompleteResponse(complete) => match complete.collected {
|
||||
CollectedResponse::Failed(_) => Err(invalid(
|
||||
"return_untyped_failure",
|
||||
&PendingAttempt::NoCandidate,
|
||||
)),
|
||||
CollectedResponse::MissingCompleted => Ok(ResponseDispatchError::MissingCompleted),
|
||||
CollectedResponse::Empty => Ok(ResponseDispatchError::EmptyUpstreamResponse),
|
||||
CollectedResponse::Completed(_) | CollectedResponse::Incomplete(_) => {
|
||||
Err(invalid("return", &PendingAttempt::NoCandidate))
|
||||
}
|
||||
},
|
||||
PendingAttempt::StreamResponse(stream) => match stream.first_failure {
|
||||
Some(failure) => {
|
||||
stream.lease.complete().await;
|
||||
let _ = failure;
|
||||
Err(invalid(
|
||||
"return_untyped_failure",
|
||||
&PendingAttempt::NoCandidate,
|
||||
))
|
||||
}
|
||||
None => Err(invalid("return", &PendingAttempt::NoCandidate)),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_account(pending: &PendingAttempt) -> Option<&str> {
|
||||
pending_account_value(pending).map(|account| account.id.as_str())
|
||||
}
|
||||
|
||||
fn pending_account_value(pending: &PendingAttempt) -> Option<&Account> {
|
||||
match pending {
|
||||
PendingAttempt::NoCandidate | PendingAttempt::PinnedCandidateUnavailable { .. } => None,
|
||||
PendingAttempt::CandidatePreparationRejected { account }
|
||||
| PendingAttempt::RoutePreparationRejected { account, .. }
|
||||
| PendingAttempt::UpstreamFailure { account, .. }
|
||||
| PendingAttempt::ProtocolFailure { account, .. } => Some(account),
|
||||
PendingAttempt::CompleteResponse(complete) => Some(&complete.account),
|
||||
PendingAttempt::StreamResponse(stream) => Some(&stream.account),
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_attempt(pending: &PendingAttempt) -> Option<&super::trace::ResponseDispatchAttempt> {
|
||||
match pending {
|
||||
PendingAttempt::UpstreamFailure { attempt, .. }
|
||||
| PendingAttempt::ProtocolFailure { attempt, .. } => Some(attempt),
|
||||
PendingAttempt::CompleteResponse(complete) => Some(&complete.attempt),
|
||||
PendingAttempt::StreamResponse(stream) => Some(&stream.attempt),
|
||||
PendingAttempt::NoCandidate
|
||||
| PendingAttempt::PinnedCandidateUnavailable { .. }
|
||||
| PendingAttempt::CandidatePreparationRejected { .. }
|
||||
| PendingAttempt::RoutePreparationRejected { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_attempt_request(pending: &PendingAttempt) -> Option<&CodexResponsesRequest> {
|
||||
match pending {
|
||||
PendingAttempt::UpstreamFailure {
|
||||
attempt_request, ..
|
||||
}
|
||||
| PendingAttempt::ProtocolFailure {
|
||||
attempt_request, ..
|
||||
} => Some(attempt_request),
|
||||
PendingAttempt::CompleteResponse(complete) => Some(&complete.attempt_request),
|
||||
PendingAttempt::StreamResponse(stream) => Some(&stream.attempt_request),
|
||||
PendingAttempt::NoCandidate
|
||||
| PendingAttempt::PinnedCandidateUnavailable { .. }
|
||||
| PendingAttempt::CandidatePreparationRejected { .. }
|
||||
| PendingAttempt::RoutePreparationRejected { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_transport(
|
||||
pending: &PendingAttempt,
|
||||
) -> Option<crate::upstream::openai::transport::CodexBackendTransport> {
|
||||
match pending {
|
||||
PendingAttempt::UpstreamFailure { transport, .. }
|
||||
| PendingAttempt::ProtocolFailure { transport, .. } => Some(*transport),
|
||||
PendingAttempt::CompleteResponse(complete) => Some(complete.response.transport),
|
||||
PendingAttempt::StreamResponse(stream) => Some(stream.response.transport),
|
||||
PendingAttempt::NoCandidate
|
||||
| PendingAttempt::PinnedCandidateUnavailable { .. }
|
||||
| PendingAttempt::CandidatePreparationRejected { .. }
|
||||
| PendingAttempt::RoutePreparationRejected { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn intended_transport(request: &CodexResponsesRequest) -> CodexBackendTransport {
|
||||
match transport_requirement(request) {
|
||||
TransportRequirement::HttpRequired => CodexBackendTransport::HttpSse,
|
||||
TransportRequirement::ExplicitWebSocketWarmup
|
||||
| TransportRequirement::ExactWebSocketContinuation
|
||||
| TransportRequirement::PersistedContinuation
|
||||
| TransportRequirement::ExternalUnknown
|
||||
| TransportRequirement::NewChain => CodexBackendTransport::WebSocket,
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid(decision: &'static str, pending: &PendingAttempt) -> AttemptContractError {
|
||||
AttemptContractError::InvalidDecision {
|
||||
decision,
|
||||
observation: match pending {
|
||||
PendingAttempt::NoCandidate => "no_candidate",
|
||||
PendingAttempt::PinnedCandidateUnavailable { .. } => "pinned_candidate_unavailable",
|
||||
PendingAttempt::CandidatePreparationRejected { .. } => "candidate_preparation_rejected",
|
||||
PendingAttempt::RoutePreparationRejected { .. } => "route_preparation_rejected",
|
||||
PendingAttempt::UpstreamFailure { .. } => "upstream_failure",
|
||||
PendingAttempt::ProtocolFailure { .. } => "protocol_failure",
|
||||
PendingAttempt::CompleteResponse(_) => "complete_response",
|
||||
PendingAttempt::StreamResponse(_) => "stream_response",
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
//! Attempt lifecycle 的类型化 observation、decision 与结果。
|
||||
|
||||
use bytes::Bytes;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
errors::{ClientFailure, ResponseDispatchError},
|
||||
failure::exhaustion::{AccountExhaustionRecord, ExhaustedAccount},
|
||||
transport::{
|
||||
canonical::{CanonicalStreamBatch, CanonicalStreamDecoder},
|
||||
observation::UpstreamFailureFacts,
|
||||
},
|
||||
},
|
||||
fleet::{account::Account, pool::AccountLease},
|
||||
upstream::openai::{
|
||||
protocol::{
|
||||
responses::{CodexResponsesRequest, CollectedResponse, ResponsesSseFailure},
|
||||
sse::SseError,
|
||||
},
|
||||
transport::{
|
||||
CodexBackendResponse, CodexBackendStreamingResponse, CodexBackendTransport,
|
||||
CodexClientError, CodexUpstreamDiagnostics,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
use super::trace::{ResponseDispatchAttempt, ResponseDispatchTrace};
|
||||
|
||||
/// Request/Attempt/Stream 共同消费的最终结果类别。
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) enum FinalOutcome {
|
||||
Completed,
|
||||
Incomplete,
|
||||
Failed,
|
||||
Cancelled,
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) struct AttemptAccountFacts {
|
||||
pub id: String,
|
||||
pub email: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
}
|
||||
|
||||
impl From<&Account> for AttemptAccountFacts {
|
||||
fn from(account: &Account) -> Self {
|
||||
Self {
|
||||
id: account.id.clone(),
|
||||
email: account.email.clone(),
|
||||
plan_type: account.plan_type.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) struct AttemptRoutingFacts {
|
||||
pub external_origin: bool,
|
||||
pub can_retry_same_account: bool,
|
||||
pub can_retry_next_candidate: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) struct CandidateLedgerFacts {
|
||||
pub candidates: usize,
|
||||
pub attempted: usize,
|
||||
pub state_excluded: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) enum CompleteResponseFacts {
|
||||
Completed,
|
||||
Incomplete,
|
||||
Failed(ResponsesSseFailure),
|
||||
MissingCompleted,
|
||||
Empty,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) enum ProtocolFailureKind {
|
||||
InvalidSse,
|
||||
EmptyStream,
|
||||
NoCommitBoundary,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) enum PinnedCandidateAcquireFailureKind {
|
||||
Busy,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) enum AttemptObservationKind {
|
||||
NoCandidate {
|
||||
ledger: CandidateLedgerFacts,
|
||||
last_exhausted: Option<ExhaustedAccount>,
|
||||
},
|
||||
CandidatePreparationRejected,
|
||||
RoutePreparationRejected {
|
||||
message: String,
|
||||
},
|
||||
PinnedCandidateUnavailable {
|
||||
account_id: String,
|
||||
kind: PinnedCandidateAcquireFailureKind,
|
||||
},
|
||||
UpstreamFailure(UpstreamFailureFacts),
|
||||
ProtocolFailure {
|
||||
kind: ProtocolFailureKind,
|
||||
message: String,
|
||||
},
|
||||
CompleteResponse(CompleteResponseFacts),
|
||||
StreamFailure(ResponsesSseFailure),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) struct AttemptObservation {
|
||||
pub account: Option<AttemptAccountFacts>,
|
||||
pub attempt: Option<ResponseDispatchAttempt>,
|
||||
pub transport: CodexBackendTransport,
|
||||
pub routing: AttemptRoutingFacts,
|
||||
pub kind: AttemptObservationKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) enum AttemptDecision {
|
||||
Accept,
|
||||
RetrySameAccount,
|
||||
RetryNextCandidate {
|
||||
exhaustion: Option<AccountExhaustionRecord>,
|
||||
on_exhaustion: Option<ClientFailure>,
|
||||
},
|
||||
Return(AttemptReturnKind),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) enum AttemptReturnKind {
|
||||
Observed,
|
||||
Failed(ClientFailure),
|
||||
ContinuationBusy,
|
||||
RouteUnavailable { message: String },
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) struct EstablishedAttemptContext {
|
||||
pub request: CodexResponsesRequest,
|
||||
pub controller_scope: crate::dispatch::controllers::ControllerRequestScope,
|
||||
pub trace: ResponseDispatchTrace,
|
||||
pub account: Account,
|
||||
pub attempt: ResponseDispatchAttempt,
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) struct EstablishedComplete {
|
||||
pub context: EstablishedAttemptContext,
|
||||
pub response: CodexBackendResponse,
|
||||
pub body: EstablishedCompleteBody,
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) enum EstablishedCompleteBody {
|
||||
Completed(serde_json::Value),
|
||||
Incomplete(serde_json::Value),
|
||||
}
|
||||
|
||||
impl TryFrom<CollectedResponse> for EstablishedCompleteBody {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: CollectedResponse) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
CollectedResponse::Completed(body) => Ok(Self::Completed(body)),
|
||||
CollectedResponse::Incomplete(body) => Ok(Self::Incomplete(body)),
|
||||
CollectedResponse::Failed(_)
|
||||
| CollectedResponse::MissingCompleted
|
||||
| CollectedResponse::Empty => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) struct EstablishedStream {
|
||||
pub context: EstablishedAttemptContext,
|
||||
pub lease: AccountLease,
|
||||
pub response: CodexBackendStreamingResponse,
|
||||
pub decoder: CanonicalStreamDecoder,
|
||||
pub initial_batch: CanonicalStreamBatch,
|
||||
pub first_event_ms: i64,
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) enum EstablishedResponse {
|
||||
Complete(Box<EstablishedComplete>),
|
||||
Stream(Box<EstablishedStream>),
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) struct AttemptRejection {
|
||||
pub request: CodexResponsesRequest,
|
||||
pub trace: ResponseDispatchTrace,
|
||||
pub account_id: Option<String>,
|
||||
pub account: Option<Account>,
|
||||
pub attempt_request: Option<CodexResponsesRequest>,
|
||||
pub attempt: Option<ResponseDispatchAttempt>,
|
||||
pub transport: CodexBackendTransport,
|
||||
pub stream_failure: Option<RejectedStreamFailure>,
|
||||
pub error: ResponseDispatchError,
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) struct RejectedStreamFailure {
|
||||
pub failure: ResponsesSseFailure,
|
||||
pub prefetched: Bytes,
|
||||
pub diagnostics: CodexUpstreamDiagnostics,
|
||||
pub rate_limit_headers: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) enum AttemptApplyOutcome {
|
||||
Continue,
|
||||
Established(EstablishedResponse),
|
||||
Rejected(Box<AttemptRejection>),
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(in crate::dispatch) enum AttemptContractError {
|
||||
#[error("the previous attempt observation has not been decided")]
|
||||
DecisionRequired,
|
||||
#[error("attempt runner has already reached a terminal outcome")]
|
||||
Terminal,
|
||||
#[error("decision `{decision}` is invalid for observation `{observation}`")]
|
||||
InvalidDecision {
|
||||
decision: &'static str,
|
||||
observation: &'static str,
|
||||
},
|
||||
}
|
||||
|
||||
pub(super) enum PendingProtocolFailure {
|
||||
InvalidSse(SseError),
|
||||
EmptyStream,
|
||||
NoCommitBoundary,
|
||||
}
|
||||
|
||||
pub(super) struct PendingStreamResponse {
|
||||
pub account: Account,
|
||||
pub attempt_request: CodexResponsesRequest,
|
||||
pub attempt: ResponseDispatchAttempt,
|
||||
pub lease: AccountLease,
|
||||
pub response: CodexBackendStreamingResponse,
|
||||
pub prefetched: Bytes,
|
||||
pub decoder: CanonicalStreamDecoder,
|
||||
pub initial_batch: CanonicalStreamBatch,
|
||||
pub first_failure: Option<ResponsesSseFailure>,
|
||||
pub first_event_ms: i64,
|
||||
}
|
||||
|
||||
pub(super) struct PendingCompleteResponse {
|
||||
pub account: Account,
|
||||
pub attempt_request: CodexResponsesRequest,
|
||||
pub attempt: ResponseDispatchAttempt,
|
||||
pub response: CodexBackendResponse,
|
||||
pub collected: CollectedResponse,
|
||||
}
|
||||
|
||||
pub(super) enum PendingAttempt {
|
||||
NoCandidate,
|
||||
PinnedCandidateUnavailable {
|
||||
account_id: String,
|
||||
kind: PinnedCandidateAcquireFailureKind,
|
||||
},
|
||||
CandidatePreparationRejected {
|
||||
account: Account,
|
||||
},
|
||||
RoutePreparationRejected {
|
||||
account: Account,
|
||||
message: String,
|
||||
},
|
||||
UpstreamFailure {
|
||||
account: Account,
|
||||
attempt_request: CodexResponsesRequest,
|
||||
attempt: ResponseDispatchAttempt,
|
||||
transport: CodexBackendTransport,
|
||||
error: CodexClientError,
|
||||
},
|
||||
ProtocolFailure {
|
||||
account: Account,
|
||||
attempt_request: CodexResponsesRequest,
|
||||
attempt: ResponseDispatchAttempt,
|
||||
transport: CodexBackendTransport,
|
||||
error: PendingProtocolFailure,
|
||||
},
|
||||
CompleteResponse(Box<PendingCompleteResponse>),
|
||||
StreamResponse(Box<PendingStreamResponse>),
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Responses live stream 的唯一结算出口。
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
controllers::{ControllerRequestScope, ControllerSet, StreamControllerContext},
|
||||
errors::ResponseDispatchStreamError,
|
||||
failure::sse::{STREAM_DISCONNECTED_CODE, STREAM_DISCONNECTED_MESSAGE},
|
||||
lifecycle::stream::StreamSummary,
|
||||
transport::canonical::{CanonicalResponseChunk, CanonicalResponseEvent},
|
||||
},
|
||||
fleet::pool::AccountLease,
|
||||
upstream::openai::protocol::sse::{
|
||||
DONE_SSE_FRAME, encode_sse_event, response_failed_sse_data_with_id,
|
||||
},
|
||||
};
|
||||
|
||||
const LEASE_FINALIZE_TIMEOUT: Duration = Duration::from_millis(100);
|
||||
|
||||
/// 消费 stream context,类型层面保证每个 live loop 只能结算一次。
|
||||
pub(in crate::dispatch) struct StreamFinalizer {
|
||||
controllers: ControllerSet,
|
||||
controller_scope: ControllerRequestScope,
|
||||
controller_context: StreamControllerContext,
|
||||
account_lease: AccountLease,
|
||||
}
|
||||
|
||||
impl StreamFinalizer {
|
||||
pub(in crate::dispatch) fn new(
|
||||
controllers: ControllerSet,
|
||||
controller_scope: ControllerRequestScope,
|
||||
controller_context: StreamControllerContext,
|
||||
account_lease: AccountLease,
|
||||
) -> Self {
|
||||
Self {
|
||||
controllers,
|
||||
controller_scope,
|
||||
controller_context,
|
||||
account_lease,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn response_headers(&self) -> &[(String, String)] {
|
||||
&self.controller_context.response_metadata.client_headers
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn started_at(&self) -> Instant {
|
||||
self.controller_context.started_at
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn finalize(
|
||||
self,
|
||||
sender: &mpsc::Sender<Result<Bytes, ResponseDispatchStreamError>>,
|
||||
event_sender: &mpsc::UnboundedSender<Vec<CanonicalResponseEvent>>,
|
||||
mut summary: StreamSummary,
|
||||
) {
|
||||
let Self {
|
||||
controllers,
|
||||
controller_scope,
|
||||
controller_context,
|
||||
account_lease,
|
||||
} = self;
|
||||
let body = String::from_utf8_lossy(&summary.body).into_owned();
|
||||
controllers
|
||||
.leave_stream(controller_scope, controller_context, &summary, &body)
|
||||
.await;
|
||||
if timeout(LEASE_FINALIZE_TIMEOUT, account_lease.complete())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!(
|
||||
timeout_ms = LEASE_FINALIZE_TIMEOUT.as_millis(),
|
||||
"Timed out finalizing response account lease"
|
||||
);
|
||||
}
|
||||
finish_client_stream(sender, event_sender, &mut summary).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn finish_client_stream(
|
||||
sender: &mpsc::Sender<Result<Bytes, ResponseDispatchStreamError>>,
|
||||
event_sender: &mpsc::UnboundedSender<Vec<CanonicalResponseEvent>>,
|
||||
summary: &mut StreamSummary,
|
||||
) {
|
||||
if !summary.terminal.should_finish_client_stream() {
|
||||
return;
|
||||
}
|
||||
if flush_terminal_chunks(sender, event_sender, &mut summary.terminal_chunks)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
if let Some(detail) = summary.terminal.synthetic_failure_detail() {
|
||||
if append_separator_if_needed(sender, event_sender, &mut summary.body)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let failure = response_failed_sse_data_with_id(
|
||||
summary.last_response_id.as_deref(),
|
||||
"server_error",
|
||||
STREAM_DISCONNECTED_CODE,
|
||||
&synthetic_failure_message(detail),
|
||||
);
|
||||
let bytes = Bytes::from(encode_sse_event("response.failed", &failure.to_string()));
|
||||
if append_client_chunk(
|
||||
sender,
|
||||
event_sender,
|
||||
&mut summary.body,
|
||||
CanonicalResponseChunk::new(
|
||||
bytes,
|
||||
vec![CanonicalResponseEvent::proxy_failure(failure)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if !body_has_done(&summary.body) {
|
||||
let _ = append_client_chunk(
|
||||
sender,
|
||||
event_sender,
|
||||
&mut summary.body,
|
||||
CanonicalResponseChunk::new(Bytes::from_static(DONE_SSE_FRAME.as_bytes()), Vec::new()),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn flush_terminal_chunks(
|
||||
sender: &mpsc::Sender<Result<Bytes, ResponseDispatchStreamError>>,
|
||||
event_sender: &mpsc::UnboundedSender<Vec<CanonicalResponseEvent>>,
|
||||
terminal_chunks: &mut Vec<CanonicalResponseChunk>,
|
||||
) -> Result<(), ()> {
|
||||
for chunk in terminal_chunks.drain(..) {
|
||||
let (bytes, events) = chunk.into_parts();
|
||||
let _ = event_sender.send(events);
|
||||
sender.send(Ok(bytes)).await.map_err(|_| ())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn append_separator_if_needed(
|
||||
sender: &mpsc::Sender<Result<Bytes, ResponseDispatchStreamError>>,
|
||||
event_sender: &mpsc::UnboundedSender<Vec<CanonicalResponseEvent>>,
|
||||
body: &mut Vec<u8>,
|
||||
) -> Result<(), ()> {
|
||||
let separator = if body.is_empty()
|
||||
|| body.ends_with(b"\n\n")
|
||||
|| body.ends_with(b"\r\n\r\n")
|
||||
|| body.ends_with(b"\r\r")
|
||||
{
|
||||
return Ok(());
|
||||
} else if body.ends_with(b"\n") || body.ends_with(b"\r") {
|
||||
Bytes::from_static(b"\n")
|
||||
} else {
|
||||
Bytes::from_static(b"\n\n")
|
||||
};
|
||||
append_client_chunk(
|
||||
sender,
|
||||
event_sender,
|
||||
body,
|
||||
CanonicalResponseChunk::new(separator, Vec::new()),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn append_client_chunk(
|
||||
sender: &mpsc::Sender<Result<Bytes, ResponseDispatchStreamError>>,
|
||||
event_sender: &mpsc::UnboundedSender<Vec<CanonicalResponseEvent>>,
|
||||
body: &mut Vec<u8>,
|
||||
chunk: CanonicalResponseChunk,
|
||||
) -> Result<(), ()> {
|
||||
body.extend_from_slice(chunk.bytes());
|
||||
let (bytes, events) = chunk.into_parts();
|
||||
let _ = event_sender.send(events);
|
||||
sender.send(Ok(bytes)).await.map_err(|_| ())
|
||||
}
|
||||
|
||||
fn body_has_done(body: &[u8]) -> bool {
|
||||
String::from_utf8_lossy(body)
|
||||
.trim_end_matches(['\r', '\n'])
|
||||
.ends_with(DONE_SSE_FRAME.trim_end_matches(['\r', '\n']))
|
||||
}
|
||||
|
||||
fn synthetic_failure_message(detail: &str) -> String {
|
||||
if detail.trim().is_empty() {
|
||||
STREAM_DISCONNECTED_MESSAGE.to_string()
|
||||
} else {
|
||||
format!("{STREAM_DISCONNECTED_MESSAGE}: {detail}")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//! `v1/*` 请求的生命周期基础类型与入口准备。
|
||||
|
||||
pub(in crate::dispatch) mod attempt;
|
||||
pub(in crate::dispatch) mod contract;
|
||||
pub(in crate::dispatch) mod finalizer;
|
||||
pub(in crate::dispatch) mod pipeline;
|
||||
pub(in crate::dispatch) mod request;
|
||||
pub(in crate::dispatch) mod stream;
|
||||
pub(in crate::dispatch) mod trace;
|
||||
|
||||
pub(in crate::dispatch) use request::{
|
||||
RequestContext, RequestEnterDependencies, RequestMode, enter_request,
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Attempt 生命周期的唯一静态 pipeline。
|
||||
|
||||
use crate::{
|
||||
dispatch::{controllers::ControllerRequestScope, routing::candidates::AccountAttemptLedger},
|
||||
upstream::openai::protocol::responses::CodexResponsesRequest,
|
||||
};
|
||||
|
||||
use super::{
|
||||
attempt::{AttemptMode, AttemptRunner, AttemptRunnerDependencies, AttemptStep},
|
||||
contract::{AttemptApplyOutcome, AttemptContractError, AttemptRejection, EstablishedResponse},
|
||||
};
|
||||
|
||||
pub(in crate::dispatch) enum AttemptPipelineOutcome {
|
||||
Established(EstablishedResponse),
|
||||
Rejected(Box<AttemptRejection>),
|
||||
}
|
||||
|
||||
/// 执行完整的 attempt/retry/commit 状态机。
|
||||
///
|
||||
/// mode 适配器只能消费最终结果,不能自行复制 retry loop 或越过 commit 边界。
|
||||
pub(in crate::dispatch) async fn run_attempt_pipeline(
|
||||
dependencies: AttemptRunnerDependencies<'_>,
|
||||
mode: AttemptMode,
|
||||
request: CodexResponsesRequest,
|
||||
controller_scope: ControllerRequestScope,
|
||||
candidates: AccountAttemptLedger,
|
||||
) -> Result<AttemptPipelineOutcome, AttemptContractError> {
|
||||
let controllers = dependencies.controllers;
|
||||
let mut runner = AttemptRunner::new(dependencies, mode, request, controller_scope, candidates);
|
||||
|
||||
loop {
|
||||
let outcome = match runner.next().await? {
|
||||
AttemptStep::Open(attempt) => {
|
||||
let decision = controllers
|
||||
.handle_attempt(attempt.controller_scope()?, attempt.observation())
|
||||
.await;
|
||||
attempt.apply(decision).await?
|
||||
}
|
||||
AttemptStep::Committed(attempt) => {
|
||||
return Ok(AttemptPipelineOutcome::Established(attempt.accept()));
|
||||
}
|
||||
};
|
||||
match outcome {
|
||||
AttemptApplyOutcome::Continue => {}
|
||||
AttemptApplyOutcome::Established(established) => {
|
||||
return Ok(AttemptPipelineOutcome::Established(established));
|
||||
}
|
||||
AttemptApplyOutcome::Rejected(rejection) => {
|
||||
return Ok(AttemptPipelineOutcome::Rejected(rejection));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Responses 请求进入 dispatch 的共享生命周期阶段。
|
||||
|
||||
use chrono::Utc;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
affinity::{AccountIdentityService, prepare_variant_identity},
|
||||
controllers::{ControllerEnter, ControllerRequestScope, ControllerSet},
|
||||
routing::candidates::AccountAttemptLedger,
|
||||
},
|
||||
fleet::pool::{AccountAcquireRequest, AccountPoolService},
|
||||
models::service::ModelService,
|
||||
upstream::openai::protocol::responses::CodexResponsesRequest,
|
||||
};
|
||||
|
||||
/// Responses 请求的执行模式。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) enum RequestMode {
|
||||
Complete,
|
||||
Stream,
|
||||
}
|
||||
|
||||
impl RequestMode {
|
||||
fn stream(self) -> bool {
|
||||
matches!(self, Self::Stream)
|
||||
}
|
||||
}
|
||||
|
||||
/// 请求 enter 阶段所需的窄依赖集合。
|
||||
pub(in crate::dispatch) struct RequestEnterDependencies<'a> {
|
||||
pub account_pool: &'a AccountPoolService,
|
||||
pub models: &'a ModelService,
|
||||
pub account_identity: &'a AccountIdentityService,
|
||||
pub controllers: ControllerSet,
|
||||
}
|
||||
|
||||
/// 已完成请求级 enter 的 Responses 上下文。
|
||||
///
|
||||
/// 该类型只承载请求、会话恢复、会话策略和候选快照;账号 attempt
|
||||
/// 与流生命周期由后续 pipeline 接管。
|
||||
pub(in crate::dispatch) struct RequestContext {
|
||||
pub request: CodexResponsesRequest,
|
||||
pub display_model: String,
|
||||
pub compact: bool,
|
||||
pub tuple_schema: Option<Value>,
|
||||
pub image_generation_requested: bool,
|
||||
pub controllers: ControllerSet,
|
||||
pub controller_scope: ControllerRequestScope,
|
||||
pub candidates: AccountAttemptLedger,
|
||||
}
|
||||
|
||||
/// 执行所有 Responses 模式共享的请求 enter 阶段。
|
||||
pub(in crate::dispatch) async fn enter_request(
|
||||
dependencies: RequestEnterDependencies<'_>,
|
||||
mut request: CodexResponsesRequest,
|
||||
requested_model: &str,
|
||||
mode: RequestMode,
|
||||
) -> RequestContext {
|
||||
let catalog = dependencies.models.catalog().await;
|
||||
let display_model = catalog.resolve_model_id(requested_model);
|
||||
request.set_model(display_model.clone());
|
||||
request.set_stream(mode.stream());
|
||||
|
||||
let compact = request.semantics().compact;
|
||||
let tuple_schema = request.tuple_schema.clone();
|
||||
let image_generation_requested = request.expects_image_generation();
|
||||
let now = Utc::now();
|
||||
prepare_variant_identity(&mut request);
|
||||
dependencies
|
||||
.account_identity
|
||||
.prepare_local_identity(&mut request);
|
||||
let controllers = dependencies.controllers;
|
||||
let ControllerEnter {
|
||||
scope,
|
||||
preferred_account_id,
|
||||
excluded_account_ids,
|
||||
} = controllers.enter(&request, now).await;
|
||||
|
||||
let mut acquire_request = AccountAcquireRequest::new(request.model(), now);
|
||||
if let Some(preferred_account_id) = preferred_account_id {
|
||||
acquire_request = acquire_request.with_preferred_account_id(preferred_account_id);
|
||||
}
|
||||
let candidates = AccountAttemptLedger::freeze(
|
||||
dependencies.account_pool,
|
||||
&acquire_request,
|
||||
&excluded_account_ids,
|
||||
)
|
||||
.await;
|
||||
|
||||
RequestContext {
|
||||
request,
|
||||
display_model,
|
||||
compact,
|
||||
tuple_schema,
|
||||
image_generation_requested,
|
||||
controllers,
|
||||
controller_scope: scope,
|
||||
candidates,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Responses live stream 的规范事件与终态。
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
dispatch::transport::canonical::{CanonicalResponseChunk, CanonicalStreamTerminal},
|
||||
upstream::openai::protocol::{events::TokenUsage, responses::ResponsesSseFailure},
|
||||
};
|
||||
|
||||
/// live stream 离开事件循环的唯一终态。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) enum StreamTerminal {
|
||||
Completed { response: Value },
|
||||
Incomplete { response: Value },
|
||||
Failed { failure: ResponsesSseFailure },
|
||||
UpstreamClosed,
|
||||
UpstreamError { detail: String },
|
||||
ProtocolError { detail: String },
|
||||
CaptureLimitExceeded,
|
||||
Cancelled,
|
||||
DownstreamClosed,
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
/// live loop 交给唯一 finalizer 的完整事实快照。
|
||||
pub(in crate::dispatch) struct StreamSummary {
|
||||
pub terminal: StreamTerminal,
|
||||
pub body: Vec<u8>,
|
||||
pub terminal_chunks: Vec<CanonicalResponseChunk>,
|
||||
pub first_token_ms: Option<i64>,
|
||||
pub first_event_ms: i64,
|
||||
pub usage: Option<TokenUsage>,
|
||||
pub last_response_id: Option<String>,
|
||||
}
|
||||
|
||||
impl From<CanonicalStreamTerminal> for StreamTerminal {
|
||||
fn from(terminal: CanonicalStreamTerminal) -> Self {
|
||||
match terminal {
|
||||
CanonicalStreamTerminal::Completed(response) => Self::Completed { response },
|
||||
CanonicalStreamTerminal::Incomplete(response) => Self::Incomplete { response },
|
||||
CanonicalStreamTerminal::Failed(failure) => Self::Failed { failure },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StreamTerminal {
|
||||
/// 只有上游没有给出业务终态时,代理才需要合成 `response.failed`。
|
||||
pub(in crate::dispatch) fn synthetic_failure_detail(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::UpstreamClosed => Some(""),
|
||||
Self::UpstreamError { detail } | Self::ProtocolError { detail } => Some(detail),
|
||||
Self::CaptureLimitExceeded => {
|
||||
Some("upstream response exceeded the 16 MiB proxy capture limit")
|
||||
}
|
||||
Self::Completed { .. }
|
||||
| Self::Incomplete { .. }
|
||||
| Self::Failed { .. }
|
||||
| Self::Cancelled
|
||||
| Self::DownstreamClosed
|
||||
| Self::Shutdown => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn should_finish_client_stream(&self) -> bool {
|
||||
!matches!(
|
||||
self,
|
||||
Self::Cancelled | Self::DownstreamClosed | Self::Shutdown
|
||||
)
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn name(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Completed { .. } => "completed",
|
||||
Self::Incomplete { .. } => "incomplete",
|
||||
Self::Failed { .. } => "failed",
|
||||
Self::UpstreamClosed => "upstream_closed",
|
||||
Self::UpstreamError { .. } => "upstream_error",
|
||||
Self::ProtocolError { .. } => "protocol_error",
|
||||
Self::CaptureLimitExceeded => "capture_limit_exceeded",
|
||||
Self::Cancelled => "cancelled",
|
||||
Self::DownstreamClosed => "downstream_closed",
|
||||
Self::Shutdown => "shutdown",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Request-level trace state for Responses dispatch.
|
||||
//! Responses 请求级账号尝试轨迹。
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(in crate::dispatch) struct ResponseDispatchTrace {
|
||||
@@ -1,10 +1,11 @@
|
||||
//! 请求调度模块(账号选择、回退、恢复、会话亲和性)。
|
||||
|
||||
pub mod affinity;
|
||||
mod attempts;
|
||||
pub(crate) mod controllers;
|
||||
pub mod errors;
|
||||
mod recording;
|
||||
pub mod recovery;
|
||||
pub(crate) mod failure;
|
||||
pub(crate) mod lifecycle;
|
||||
pub(crate) mod routing;
|
||||
pub(crate) mod service;
|
||||
pub(crate) mod stream;
|
||||
pub mod upstream_call;
|
||||
pub(crate) mod transport;
|
||||
|
||||
@@ -1,143 +0,0 @@
|
||||
//! 可换号上游失败的账号风险剥离。
|
||||
|
||||
use chrono::Utc;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
errors::{
|
||||
is_model_unsupported_upstream_error, is_quota_exhausted_upstream_error,
|
||||
is_rate_limit_upstream_error, rate_limit_cooldown_until, upstream_error_body,
|
||||
upstream_error_http_status,
|
||||
},
|
||||
recovery::{
|
||||
auth::{auth_failure_account_status, is_auth_upstream_error},
|
||||
cloudflare::{
|
||||
cloudflare_challenge_error_message, cloudflare_path_block_error_message,
|
||||
is_cloudflare_challenge_upstream_error, is_cloudflare_path_block_upstream_error,
|
||||
CloudflareRecovery,
|
||||
},
|
||||
exhaustion::AccountExhaustionTracker,
|
||||
},
|
||||
stream::sse_failure::{
|
||||
auth_sse_failure_account_status, is_auth_sse_failure, is_model_unsupported_sse_failure,
|
||||
is_quota_exhausted_sse_failure, sse_failure_error_body, stream_failure_http_status,
|
||||
},
|
||||
},
|
||||
fleet::{account::AccountStatus, pool::AccountPoolService},
|
||||
upstream::openai::{
|
||||
protocol::responses::ResponsesSseFailure,
|
||||
transport::{is_banned_upstream_error, CodexClientError},
|
||||
},
|
||||
};
|
||||
|
||||
/// 处理需要隔离当前账号并交回调度器选择下一候选的上游失败。
|
||||
///
|
||||
/// 本函数不选择下一个账号,也不实现固定轮换策略;调用方继续使用请求级候选账本,
|
||||
/// 因而始终服从当前运行时调度策略。
|
||||
pub(crate) async fn isolate_rotatable_account_failure(
|
||||
account_pool: &AccountPoolService,
|
||||
cloudflare: &CloudflareRecovery,
|
||||
exhausted_accounts: &mut AccountExhaustionTracker,
|
||||
account_id: &str,
|
||||
error: &CodexClientError,
|
||||
) -> bool {
|
||||
if is_rate_limit_upstream_error(error) {
|
||||
exhausted_accounts.record_rate_limited(Some(account_id), upstream_error_body(error));
|
||||
account_pool
|
||||
.mark_quota_limited_until(account_id, rate_limit_cooldown_until(error, Utc::now()))
|
||||
.await;
|
||||
return true;
|
||||
}
|
||||
|
||||
if is_quota_exhausted_upstream_error(error) {
|
||||
exhausted_accounts.record_quota_exhausted(Some(account_id), upstream_error_body(error));
|
||||
account_pool
|
||||
.set_status(account_id, AccountStatus::QuotaExhausted)
|
||||
.await;
|
||||
return true;
|
||||
}
|
||||
|
||||
if is_auth_upstream_error(error) {
|
||||
let account_status = auth_failure_account_status(error);
|
||||
exhausted_accounts.record_auth_failure(
|
||||
Some(account_id),
|
||||
account_status,
|
||||
upstream_error_body(error),
|
||||
Some(upstream_error_http_status(error)),
|
||||
);
|
||||
account_pool.set_status(account_id, account_status).await;
|
||||
return true;
|
||||
}
|
||||
|
||||
if is_cloudflare_challenge_upstream_error(error) {
|
||||
exhausted_accounts
|
||||
.record_cloudflare_challenge(Some(account_id), cloudflare_challenge_error_message());
|
||||
cloudflare.apply_challenge(account_pool, account_id).await;
|
||||
return true;
|
||||
}
|
||||
|
||||
if is_cloudflare_path_block_upstream_error(error) {
|
||||
exhausted_accounts.record_cloudflare_path_blocked(
|
||||
Some(account_id),
|
||||
cloudflare_path_block_error_message(),
|
||||
);
|
||||
cloudflare.apply_path_block(account_pool, account_id).await;
|
||||
return true;
|
||||
}
|
||||
|
||||
if is_model_unsupported_upstream_error(error) {
|
||||
exhausted_accounts.record_model_unsupported(Some(account_id), upstream_error_body(error));
|
||||
return true;
|
||||
}
|
||||
|
||||
if is_banned_upstream_error(error) {
|
||||
exhausted_accounts.record_auth_failure(
|
||||
Some(account_id),
|
||||
AccountStatus::Banned,
|
||||
upstream_error_body(error),
|
||||
Some(upstream_error_http_status(error)),
|
||||
);
|
||||
account_pool
|
||||
.set_status(account_id, AccountStatus::Banned)
|
||||
.await;
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// 处理 SSE `response.failed` 中需要隔离当前账号的失败。
|
||||
pub(crate) async fn isolate_sse_account_failure(
|
||||
account_pool: &AccountPoolService,
|
||||
exhausted_accounts: &mut AccountExhaustionTracker,
|
||||
account_id: &str,
|
||||
failure: &ResponsesSseFailure,
|
||||
) -> bool {
|
||||
if is_model_unsupported_sse_failure(failure) {
|
||||
exhausted_accounts
|
||||
.record_model_unsupported(Some(account_id), sse_failure_error_body(failure));
|
||||
return true;
|
||||
}
|
||||
|
||||
if is_quota_exhausted_sse_failure(failure) {
|
||||
exhausted_accounts.record_quota_exhausted(Some(account_id), failure.message.clone());
|
||||
account_pool
|
||||
.set_status(account_id, AccountStatus::QuotaExhausted)
|
||||
.await;
|
||||
return true;
|
||||
}
|
||||
|
||||
if is_auth_sse_failure(failure) {
|
||||
let account_status = auth_sse_failure_account_status(failure);
|
||||
exhausted_accounts.record_auth_failure(
|
||||
Some(account_id),
|
||||
account_status,
|
||||
sse_failure_error_body(failure),
|
||||
Some(stream_failure_http_status(failure)),
|
||||
);
|
||||
account_pool.set_status(account_id, account_status).await;
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
//! 上游认证失败分类。
|
||||
|
||||
use crate::{
|
||||
fleet::account::AccountStatus,
|
||||
upstream::openai::transport::{is_banned_auth_signal, CodexClientError},
|
||||
};
|
||||
|
||||
pub(crate) fn is_auth_upstream_error(error: &CodexClientError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
CodexClientError::Upstream { status, .. } if status.as_u16() == 401
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn auth_failure_account_status(error: &CodexClientError) -> AccountStatus {
|
||||
match error {
|
||||
CodexClientError::Upstream { body, .. } if is_banned_auth_signal(body) => {
|
||||
AccountStatus::Banned
|
||||
}
|
||||
_ => AccountStatus::Expired,
|
||||
}
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
//! Cloudflare challenge and path-block recovery shared by dispatch routes.
|
||||
|
||||
use chrono::Utc;
|
||||
|
||||
use crate::{
|
||||
fleet::{
|
||||
account::AccountStatus,
|
||||
cookies::{CloudflareChallengeCooldownTracker, CloudflarePathBlockTracker, PgCookieStore},
|
||||
pool::AccountPoolService,
|
||||
},
|
||||
upstream::openai::transport::CodexClientError,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CloudflareRecovery {
|
||||
path_block_tracker: CloudflarePathBlockTracker,
|
||||
challenge_tracker: CloudflareChallengeCooldownTracker,
|
||||
cookie_store: PgCookieStore,
|
||||
}
|
||||
|
||||
impl CloudflareRecovery {
|
||||
pub fn new(cookie_store: PgCookieStore) -> Self {
|
||||
Self {
|
||||
path_block_tracker: CloudflarePathBlockTracker::default(),
|
||||
challenge_tracker: CloudflareChallengeCooldownTracker::default(),
|
||||
cookie_store,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cookie_header_for_request(&self, account_id: &str, path: &str) -> Option<String> {
|
||||
self.cookie_store
|
||||
.cookie_header_for_request(account_id, "chatgpt.com", path)
|
||||
.await
|
||||
.ok()?
|
||||
}
|
||||
|
||||
pub async fn capture_set_cookie_headers(&self, account_id: &str, headers: &[String]) {
|
||||
for header in headers {
|
||||
if let Err(error) = self
|
||||
.cookie_store
|
||||
.capture_set_cookie(account_id, header)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"failed to persist upstream set-cookie header"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn apply_challenge(&self, account_pool: &AccountPoolService, account_id: &str) {
|
||||
let now = Utc::now();
|
||||
let cooldown = self
|
||||
.challenge_tracker
|
||||
.record_challenge(account_id, now)
|
||||
.await;
|
||||
account_pool
|
||||
.set_cloudflare_cooldown_until(account_id, cooldown.cooldown_until)
|
||||
.await;
|
||||
if let Err(error) = self
|
||||
.cookie_store
|
||||
.expire_account_cookies_at(account_id, cooldown.cooldown_until)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"failed to persist Cloudflare challenge cookie cleanup deadline"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn apply_path_block(&self, account_pool: &AccountPoolService, account_id: &str) {
|
||||
self.delete_account_cookies(account_id, "Cloudflare path-block")
|
||||
.await;
|
||||
let now = Utc::now();
|
||||
self.path_block_tracker
|
||||
.record_path_block(account_id, now)
|
||||
.await;
|
||||
if self
|
||||
.path_block_tracker
|
||||
.should_disable(account_id, now)
|
||||
.await
|
||||
{
|
||||
account_pool
|
||||
.set_status(account_id, AccountStatus::Disabled)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn reset_account_recovery(&self, account_id: &str) {
|
||||
self.path_block_tracker.reset(account_id).await;
|
||||
self.challenge_tracker.reset(account_id).await;
|
||||
}
|
||||
|
||||
async fn delete_account_cookies(&self, account_id: &str, reason: &str) {
|
||||
delete_account_cookies(&self.cookie_store, account_id, reason).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn delete_account_cookies(cookie_store: &PgCookieStore, account_id: &str, reason: &str) {
|
||||
if let Err(error) = cookie_store.delete_account_cookies(account_id).await {
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
reason,
|
||||
error = %error,
|
||||
"failed to delete account cookies after Cloudflare recovery signal"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_cloudflare_challenge_upstream_error(error: &CodexClientError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
CodexClientError::Upstream { status, body, .. }
|
||||
if status.as_u16() == 403 && is_cloudflare_challenge_signal(body)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn is_cloudflare_path_block_upstream_error(error: &CodexClientError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
CodexClientError::Upstream { status, body, .. }
|
||||
if status.as_u16() == 404 && body.trim().is_empty()
|
||||
)
|
||||
}
|
||||
|
||||
pub fn cloudflare_challenge_error_message() -> &'static str {
|
||||
"Upstream blocked the request (Cloudflare challenge)"
|
||||
}
|
||||
|
||||
pub fn cloudflare_path_block_error_message() -> &'static str {
|
||||
"Upstream blocked the request (Cloudflare path-block)"
|
||||
}
|
||||
|
||||
fn is_cloudflare_challenge_signal(value: &str) -> bool {
|
||||
let value = value.to_ascii_lowercase();
|
||||
value.contains("cf-mitigated")
|
||||
|| value.contains("cf-chl-bypass")
|
||||
|| value.contains("_cf_chl")
|
||||
|| value.contains("cf_chl")
|
||||
|| value.contains("attention required")
|
||||
|| value.contains("just a moment")
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
//! previous response 所有权与完整上下文重放。
|
||||
|
||||
use chrono::Utc;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
dispatch::affinity::{
|
||||
service::{MAX_REPLAY_DEPTH, MAX_REPLAY_SESSION_BYTES, MAX_REPLAY_SNAPSHOT_BYTES},
|
||||
types::ResponseReplaySnapshot,
|
||||
SessionAffinityEntry, SessionAffinityService,
|
||||
},
|
||||
upstream::openai::protocol::responses::{CodexResponsesRequest, StreamCommitPolicy},
|
||||
};
|
||||
|
||||
/// 当前请求的 previous response 来源。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) enum HistorySource {
|
||||
None,
|
||||
Managed,
|
||||
ExternalUnknown,
|
||||
}
|
||||
|
||||
/// 请求级 previous response 恢复计划。
|
||||
pub(in crate::dispatch) struct HistoryRecoveryPlan {
|
||||
source: HistorySource,
|
||||
managed_entry: Option<SessionAffinityEntry>,
|
||||
replay_input: Option<Vec<Value>>,
|
||||
external_attempted_account_id: Option<String>,
|
||||
replay_owner_account: bool,
|
||||
}
|
||||
|
||||
impl HistoryRecoveryPlan {
|
||||
pub(in crate::dispatch) async fn load(
|
||||
session_affinity: &SessionAffinityService,
|
||||
request: &CodexResponsesRequest,
|
||||
) -> Self {
|
||||
let Some(previous_response_id) = request.previous_response_id() else {
|
||||
return Self {
|
||||
source: HistorySource::None,
|
||||
managed_entry: None,
|
||||
replay_input: None,
|
||||
external_attempted_account_id: None,
|
||||
replay_owner_account: false,
|
||||
};
|
||||
};
|
||||
let managed_entry = session_affinity
|
||||
.lookup(previous_response_id, Utc::now())
|
||||
.await;
|
||||
let replay_input = match managed_entry.as_ref() {
|
||||
Some(entry) => {
|
||||
session_affinity
|
||||
.replay_input(previous_response_id, entry, Utc::now())
|
||||
.await
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Self {
|
||||
source: if managed_entry.is_some() {
|
||||
HistorySource::Managed
|
||||
} else {
|
||||
HistorySource::ExternalUnknown
|
||||
},
|
||||
managed_entry,
|
||||
replay_input,
|
||||
external_attempted_account_id: None,
|
||||
replay_owner_account: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn preferred_account_id(&self) -> Option<&str> {
|
||||
self.managed_entry
|
||||
.as_ref()
|
||||
.map(|entry| entry.account_id.as_str())
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn prepare_attempt(
|
||||
&mut self,
|
||||
original: &CodexResponsesRequest,
|
||||
account_id: &str,
|
||||
) -> Option<CodexResponsesRequest> {
|
||||
match self.source {
|
||||
HistorySource::None => Some(original.clone()),
|
||||
HistorySource::ExternalUnknown => match self.external_attempted_account_id.as_deref() {
|
||||
None => {
|
||||
self.external_attempted_account_id = Some(account_id.to_string());
|
||||
let mut request = original.clone();
|
||||
request.stream_commit_policy = StreamCommitPolicy::UntilOutputOrTerminal;
|
||||
request.previous_response_scope = Some(
|
||||
crate::upstream::openai::protocol::responses::PreviousResponseScope::ExternalUnknown,
|
||||
);
|
||||
Some(request)
|
||||
}
|
||||
Some(first_account_id) if first_account_id == account_id => {
|
||||
let mut request = original.clone();
|
||||
request.stream_commit_policy = StreamCommitPolicy::UntilOutputOrTerminal;
|
||||
request.previous_response_scope = Some(
|
||||
crate::upstream::openai::protocol::responses::PreviousResponseScope::ExternalUnknown,
|
||||
);
|
||||
Some(request)
|
||||
}
|
||||
Some(_) => None,
|
||||
},
|
||||
HistorySource::Managed => {
|
||||
let entry = self.managed_entry.as_ref()?;
|
||||
if entry.account_id == account_id && !self.replay_owner_account {
|
||||
let mut request = original.clone();
|
||||
request.local_conversation_id = Some(entry.conversation_id.clone());
|
||||
request.stream_commit_policy = StreamCommitPolicy::UntilOutputOrTerminal;
|
||||
request.previous_response_scope = Some(entry.continuation_scope);
|
||||
if request.turn_state.as_deref().is_none_or(str::is_empty) {
|
||||
request.turn_state.clone_from(&entry.turn_state);
|
||||
}
|
||||
Some(request)
|
||||
} else {
|
||||
self.replay_input.as_ref().map(|replay_input| {
|
||||
let mut request = full_replay_request(original, replay_input);
|
||||
request.local_conversation_id = Some(entry.conversation_id.clone());
|
||||
request
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// previous ID 在原连接不可用时,切换为同账号完整重放。
|
||||
pub(in crate::dispatch) fn recover_managed_history(&mut self, account_id: &str) -> bool {
|
||||
let Some(entry) = self.managed_entry.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
if entry.account_id != account_id
|
||||
|| self.replay_input.is_none()
|
||||
|| self.replay_owner_account
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.replay_owner_account = true;
|
||||
true
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn can_failover(&self) -> bool {
|
||||
!matches!(self.source, HistorySource::ExternalUnknown)
|
||||
&& self
|
||||
.managed_entry
|
||||
.as_ref()
|
||||
.is_none_or(|_| self.replay_input.is_some())
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn is_external_unknown(&self) -> bool {
|
||||
self.source == HistorySource::ExternalUnknown
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn completed_replay(
|
||||
&self,
|
||||
original: &CodexResponsesRequest,
|
||||
output: &[Value],
|
||||
) -> Option<ResponseReplaySnapshot> {
|
||||
let (parent_response_id, parent_depth, parent_bytes) = match self.source {
|
||||
HistorySource::None => (None, 0, 0),
|
||||
HistorySource::Managed => {
|
||||
self.replay_input.as_ref()?;
|
||||
let replay = self.managed_entry.as_ref()?.replay.as_ref()?;
|
||||
(
|
||||
original.previous_response_id().map(ToString::to_string),
|
||||
replay.depth,
|
||||
replay.total_bytes,
|
||||
)
|
||||
}
|
||||
HistorySource::ExternalUnknown => return None,
|
||||
};
|
||||
let depth = parent_depth.checked_add(1)?;
|
||||
if depth > MAX_REPLAY_DEPTH {
|
||||
tracing::warn!(depth, "response replay depth limit reached");
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut turn_input = original.input().to_vec();
|
||||
let mut turn_output = output.to_vec();
|
||||
sanitize_replay_items(&mut turn_input);
|
||||
sanitize_replay_items(&mut turn_output);
|
||||
let Some(node_bytes) = limited_replay_json_bytes(&turn_input, &turn_output) else {
|
||||
tracing::warn!("response replay snapshot byte limit reached");
|
||||
return None;
|
||||
};
|
||||
let total_bytes = parent_bytes.checked_add(node_bytes)?;
|
||||
if total_bytes > MAX_REPLAY_SESSION_BYTES {
|
||||
tracing::warn!(
|
||||
node_bytes,
|
||||
total_bytes,
|
||||
"response replay session byte limit reached"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
Some(ResponseReplaySnapshot {
|
||||
parent_response_id,
|
||||
turn_input,
|
||||
turn_output,
|
||||
depth,
|
||||
total_bytes,
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn conversation_id<'a>(
|
||||
&'a self,
|
||||
original: &'a CodexResponsesRequest,
|
||||
) -> Option<&'a str> {
|
||||
self.managed_entry
|
||||
.as_ref()
|
||||
.map(|entry| entry.conversation_id.as_str())
|
||||
.or_else(|| non_empty(original.local_conversation_id.as_deref()))
|
||||
}
|
||||
}
|
||||
|
||||
fn full_replay_request(
|
||||
original: &CodexResponsesRequest,
|
||||
replay_input: &[Value],
|
||||
) -> CodexResponsesRequest {
|
||||
let mut request = original.clone();
|
||||
let mut input = replay_input.to_vec();
|
||||
input.extend_from_slice(original.input());
|
||||
sanitize_replay_items(&mut input);
|
||||
request.set_input(input);
|
||||
request.set_previous_response_id(None);
|
||||
request.turn_state = None;
|
||||
request.stream_commit_policy = StreamCommitPolicy::UntilOutputOrTerminal;
|
||||
request
|
||||
}
|
||||
|
||||
fn sanitize_replay_items(values: &mut [Value]) {
|
||||
for value in values {
|
||||
match value {
|
||||
Value::Array(values) => sanitize_replay_items(values),
|
||||
Value::Object(object) => {
|
||||
object.remove("id");
|
||||
object.remove("encrypted_content");
|
||||
for value in object.values_mut() {
|
||||
strip_encrypted_content(std::slice::from_mut(value));
|
||||
}
|
||||
}
|
||||
Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn strip_encrypted_content(values: &mut [Value]) {
|
||||
for value in values {
|
||||
match value {
|
||||
Value::Array(values) => strip_encrypted_content(values),
|
||||
Value::Object(object) => {
|
||||
object.remove("encrypted_content");
|
||||
for value in object.values_mut() {
|
||||
strip_encrypted_content(std::slice::from_mut(value));
|
||||
}
|
||||
}
|
||||
Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn limited_replay_json_bytes(input: &[Value], output: &[Value]) -> Option<u64> {
|
||||
let mut writer = ReplaySizeWriter::default();
|
||||
serde_json::to_writer(&mut writer, &(input, output)).ok()?;
|
||||
Some(writer.written)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ReplaySizeWriter {
|
||||
written: u64,
|
||||
}
|
||||
|
||||
impl std::io::Write for ReplaySizeWriter {
|
||||
fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
|
||||
let next = self
|
||||
.written
|
||||
.checked_add(buffer.len() as u64)
|
||||
.filter(|next| *next <= MAX_REPLAY_SNAPSHOT_BYTES)
|
||||
.ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::FileTooLarge,
|
||||
"response replay snapshot byte limit reached",
|
||||
)
|
||||
})?;
|
||||
self.written = next;
|
||||
Ok(buffer.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn non_empty(value: Option<&str>) -> Option<&str> {
|
||||
value.map(str::trim).filter(|value| !value.is_empty())
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
//! 调度失败恢复策略。
|
||||
|
||||
pub(crate) mod account_failure;
|
||||
pub(crate) mod auth;
|
||||
pub mod cloudflare;
|
||||
pub(crate) mod exhaustion;
|
||||
pub(crate) mod history;
|
||||
@@ -3,11 +3,14 @@
|
||||
use std::collections::{BTreeSet, VecDeque};
|
||||
|
||||
use chrono::Utc;
|
||||
use tokio::time::{Duration, Instant, timeout_at};
|
||||
|
||||
use crate::fleet::pool::{
|
||||
AccountAcquireRequest, AccountCandidateLease, AccountLease, AccountPoolService,
|
||||
};
|
||||
|
||||
const ACCOUNT_CANDIDATE_WAIT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// 请求开始时冻结的完整候选集,以及候选的最终处理状态。
|
||||
pub(in crate::dispatch) struct AccountAttemptLedger {
|
||||
model: String,
|
||||
@@ -16,14 +19,17 @@ pub(in crate::dispatch) struct AccountAttemptLedger {
|
||||
busy: VecDeque<String>,
|
||||
attempted: BTreeSet<String>,
|
||||
state_excluded: BTreeSet<String>,
|
||||
busy_wait_deadline: Instant,
|
||||
}
|
||||
|
||||
impl AccountAttemptLedger {
|
||||
pub(in crate::dispatch) async fn freeze(
|
||||
account_pool: &AccountPoolService,
|
||||
request: &AccountAcquireRequest,
|
||||
excluded_account_ids: &BTreeSet<String>,
|
||||
) -> Self {
|
||||
let candidate_ids = account_pool.candidate_snapshot(request).await;
|
||||
let mut candidate_ids = account_pool.candidate_snapshot(request).await;
|
||||
candidate_ids.retain(|account_id| !excluded_account_ids.contains(account_id));
|
||||
Self {
|
||||
model: request.model.clone(),
|
||||
pending: candidate_ids.iter().cloned().collect(),
|
||||
@@ -31,6 +37,7 @@ impl AccountAttemptLedger {
|
||||
busy: VecDeque::new(),
|
||||
attempted: BTreeSet::new(),
|
||||
state_excluded: BTreeSet::new(),
|
||||
busy_wait_deadline: Instant::now() + ACCOUNT_CANDIDATE_WAIT_TIMEOUT,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,7 +70,22 @@ impl AccountAttemptLedger {
|
||||
return None;
|
||||
}
|
||||
|
||||
account_pool.wait_for_candidate_change().await;
|
||||
if timeout_at(
|
||||
self.busy_wait_deadline,
|
||||
account_pool.wait_for_candidate_change(),
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!(
|
||||
candidate_count = self.candidate_ids.len(),
|
||||
attempted_count = self.attempted.len(),
|
||||
busy_count = self.busy.len(),
|
||||
timeout_ms = ACCOUNT_CANDIDATE_WAIT_TIMEOUT.as_millis(),
|
||||
"Timed out waiting for a busy account candidate"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
std::mem::swap(&mut self.pending, &mut self.busy);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
//! 请求级通用账号候选路由。
|
||||
|
||||
pub(in crate::dispatch) mod candidates;
|
||||
+210
-485
@@ -1,7 +1,7 @@
|
||||
//! Responses 创建编排与调度服务。
|
||||
//!
|
||||
//! 包含了将 OpenAI 请求调度到 Codex 上游账号的完整逻辑,包括:
|
||||
//! - 响应创建(非流式 / 流式 / compact)
|
||||
//! - 响应创建(非流式 / 流式)
|
||||
//! - 会话亲和性与隐式续接
|
||||
//! - reasoning replay
|
||||
//! - 账号回退与错误恢复
|
||||
@@ -10,66 +10,44 @@
|
||||
use std::{pin::Pin, sync::Arc, time::Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use chrono::Utc;
|
||||
use futures::stream::Stream;
|
||||
use serde_json::{json, Value};
|
||||
use serde_json::Value;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
affinity::resolve::{prepare_variant_identity, record_response_affinity},
|
||||
affinity::{AccountIdentityService, SessionAffinityService},
|
||||
attempts::AccountAttemptLedger,
|
||||
errors::{
|
||||
backend_transport_name, is_continuation_busy_error, is_history_recovery_upstream_error,
|
||||
is_retryable_account_transport_error, upstream_error_body,
|
||||
upstream_error_set_cookie_headers,
|
||||
},
|
||||
recovery::{
|
||||
account_failure::{isolate_rotatable_account_failure, isolate_sse_account_failure},
|
||||
controllers::{
|
||||
CompleteExit, ControllerSet, DispatchErrorObservation,
|
||||
cloudflare::CloudflareRecovery,
|
||||
exhaustion::AccountExhaustionTracker,
|
||||
history::HistoryRecoveryPlan,
|
||||
history::{
|
||||
ConnectionReplayPlan as HistoryConnectionReplayPlan,
|
||||
ConnectionReplaySnapshot as HistoryConnectionReplaySnapshot, HistoryController,
|
||||
},
|
||||
},
|
||||
upstream_call::{
|
||||
create_response_with_account_retrying_5xx, verify_acquired_quota_if_required,
|
||||
AccountUpstreamContext, QuotaVerificationContext, QuotaVerificationDecision,
|
||||
QUOTA_VERIFY_LIMIT_REACHED_MESSAGE,
|
||||
errors::backend_transport_name,
|
||||
lifecycle::{
|
||||
RequestContext, RequestEnterDependencies, RequestMode,
|
||||
attempt::{AttemptMode, AttemptRunnerDependencies},
|
||||
contract::{
|
||||
AttemptContractError, EstablishedAttemptContext, EstablishedComplete,
|
||||
EstablishedCompleteBody, EstablishedResponse, FinalOutcome,
|
||||
},
|
||||
enter_request,
|
||||
pipeline::{AttemptPipelineOutcome, run_attempt_pipeline},
|
||||
},
|
||||
transport::canonical::CanonicalResponseEvent,
|
||||
},
|
||||
fleet::{
|
||||
account::Account,
|
||||
pool::{AccountAcquireRequest, AccountPoolService},
|
||||
},
|
||||
fleet::pool::AccountPoolService,
|
||||
models::service::ModelService,
|
||||
telemetry::{
|
||||
recorder::{reasoning_effort_from_request, record_response_event, Recorder},
|
||||
usage::types::ResponseUsageRecord,
|
||||
},
|
||||
telemetry::recorder::Recorder,
|
||||
upstream::openai::{
|
||||
protocol::{
|
||||
events::TokenUsage,
|
||||
responses::{response_from_codex_sse, CodexResponsesRequest, CollectedResponse},
|
||||
},
|
||||
transport::{
|
||||
backend_transport_for_response_request, CodexBackendClient, CodexBackendResponse,
|
||||
},
|
||||
protocol::{responses::CodexResponsesRequest, sse::SseError},
|
||||
transport::CodexBackendClient,
|
||||
},
|
||||
};
|
||||
|
||||
use super::{
|
||||
errors::{ResponseDispatchError, ResponseDispatchStreamError},
|
||||
recording::{
|
||||
insert_response_status_metadata, insert_response_trace_metadata,
|
||||
insert_response_upstream_diagnostics, insert_websocket_pool_decision,
|
||||
record_response_dispatch_error_event, record_response_upstream_error_event,
|
||||
ResponseDispatchErrorDetails, ResponseDispatchErrorEventRecord,
|
||||
ResponseUpstreamErrorEventRecord,
|
||||
},
|
||||
stream::{
|
||||
sse_failure::is_history_recovery_sse_failure,
|
||||
trace::{ResponseDispatchAttempt, ResponseDispatchTrace},
|
||||
},
|
||||
};
|
||||
use super::errors::{ResponseDispatchError, ResponseDispatchStreamError};
|
||||
|
||||
/// OpenAI Responses 调度服务。
|
||||
#[derive(Clone)]
|
||||
@@ -81,6 +59,7 @@ pub struct ResponseDispatchService {
|
||||
pub(in crate::dispatch) account_identity: Arc<AccountIdentityService>,
|
||||
pub(in crate::dispatch) recorder: Arc<Recorder>,
|
||||
pub(in crate::dispatch) cloudflare: CloudflareRecovery,
|
||||
pub(in crate::dispatch) shutdown: CancellationToken,
|
||||
}
|
||||
|
||||
pub(crate) struct ResponseDispatchServiceParts {
|
||||
@@ -91,6 +70,7 @@ pub(crate) struct ResponseDispatchServiceParts {
|
||||
pub account_identity: Arc<AccountIdentityService>,
|
||||
pub recorder: Arc<Recorder>,
|
||||
pub cloudflare: CloudflareRecovery,
|
||||
pub shutdown: CancellationToken,
|
||||
}
|
||||
|
||||
/// Responses live SSE 响应体流。
|
||||
@@ -100,6 +80,7 @@ pub type ResponseBodyStream =
|
||||
/// Responses live SSE 调度结果。
|
||||
pub struct ResponseDispatchStream {
|
||||
pub body: ResponseBodyStream,
|
||||
pub(crate) canonical_events: tokio::sync::mpsc::UnboundedReceiver<Vec<CanonicalResponseEvent>>,
|
||||
pub response_headers: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
@@ -109,6 +90,43 @@ pub struct ResponseDispatchResponse {
|
||||
pub response_headers: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// 入站 Responses WebSocket 连接持有的窄重放快照。
|
||||
pub(crate) struct ConnectionReplaySnapshot {
|
||||
inner: HistoryConnectionReplaySnapshot,
|
||||
}
|
||||
|
||||
/// 单次 `response.create` 对快照的待提交重放计划。
|
||||
pub(crate) struct ConnectionReplayPlan {
|
||||
inner: HistoryConnectionReplayPlan,
|
||||
}
|
||||
|
||||
/// API 从 canonical 响应事件采集的原始 transcript 事实。
|
||||
pub(crate) struct ConnectionTranscriptFacts {
|
||||
response_id: String,
|
||||
output: Vec<Value>,
|
||||
}
|
||||
|
||||
impl ConnectionTranscriptFacts {
|
||||
pub(crate) fn new(response_id: String, output: Vec<Value>) -> Self {
|
||||
Self {
|
||||
response_id,
|
||||
output,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn attempt_contract_error(error: AttemptContractError) -> ResponseDispatchError {
|
||||
ResponseDispatchError::InvalidSse(SseError::ParseError(format!(
|
||||
"attempt lifecycle contract violation: {error}"
|
||||
)))
|
||||
}
|
||||
|
||||
fn attempt_mode_mismatch(expected: &str) -> ResponseDispatchError {
|
||||
ResponseDispatchError::InvalidSse(SseError::ParseError(format!(
|
||||
"attempt lifecycle returned a response for the wrong mode; expected {expected}"
|
||||
)))
|
||||
}
|
||||
|
||||
impl ResponseDispatchService {
|
||||
pub(crate) fn new(parts: ResponseDispatchServiceParts) -> Self {
|
||||
Self {
|
||||
@@ -119,469 +137,176 @@ impl ResponseDispatchService {
|
||||
account_identity: parts.account_identity,
|
||||
recorder: parts.recorder,
|
||||
cloudflare: parts.cloudflare,
|
||||
shutdown: parts.shutdown,
|
||||
}
|
||||
}
|
||||
|
||||
async fn record_response_affinity(
|
||||
pub(crate) fn connection_replay_snapshot(&self) -> ConnectionReplaySnapshot {
|
||||
ConnectionReplaySnapshot {
|
||||
inner: HistoryController::new_connection_replay_snapshot(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_connection_replay(
|
||||
&self,
|
||||
history: &HistoryRecoveryPlan,
|
||||
original_request: &CodexResponsesRequest,
|
||||
account_id: &str,
|
||||
body: &str,
|
||||
turn_state: Option<String>,
|
||||
usage: Option<TokenUsage>,
|
||||
snapshot: &ConnectionReplaySnapshot,
|
||||
request: &mut CodexResponsesRequest,
|
||||
) -> ConnectionReplayPlan {
|
||||
ConnectionReplayPlan {
|
||||
inner: HistoryController::prepare_connection_replay(&snapshot.inner, request),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn commit_connection_replay(
|
||||
&self,
|
||||
snapshot: &mut ConnectionReplaySnapshot,
|
||||
plan: ConnectionReplayPlan,
|
||||
transcript: ConnectionTranscriptFacts,
|
||||
) {
|
||||
record_response_affinity(
|
||||
&self.session_affinity,
|
||||
history,
|
||||
original_request,
|
||||
account_id,
|
||||
body,
|
||||
turn_state,
|
||||
usage,
|
||||
)
|
||||
.await;
|
||||
HistoryController::commit_connection_replay(
|
||||
&mut snapshot.inner,
|
||||
plan.inner,
|
||||
transcript.response_id,
|
||||
transcript.output,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl ResponseDispatchService {
|
||||
/// 调度非流式 Responses 请求到 Codex Responses 上游。
|
||||
pub async fn complete(
|
||||
&self,
|
||||
request_id: &str,
|
||||
route: &str,
|
||||
mut request: CodexResponsesRequest,
|
||||
request: CodexResponsesRequest,
|
||||
requested_model: &str,
|
||||
) -> Result<ResponseDispatchResponse, ResponseDispatchError> {
|
||||
let started_at = Instant::now();
|
||||
let catalog = self.models.catalog().await;
|
||||
let display_model = catalog.resolve_model_id(requested_model);
|
||||
request.set_model(display_model.clone());
|
||||
let tuple_schema = request.tuple_schema.clone();
|
||||
let image_generation_requested = request.expects_image_generation();
|
||||
let now = Utc::now();
|
||||
prepare_variant_identity(&mut request);
|
||||
self.account_identity.prepare_local_identity(&mut request);
|
||||
let mut history = HistoryRecoveryPlan::load(&self.session_affinity, &request).await;
|
||||
let preferred_account_id = self
|
||||
.preferred_account_id_for_request(&request, &history, now)
|
||||
.await;
|
||||
let mut acquire_request = AccountAcquireRequest::new(request.model(), now);
|
||||
if let Some(preferred_account_id) = preferred_account_id {
|
||||
acquire_request = acquire_request.with_preferred_account_id(preferred_account_id);
|
||||
}
|
||||
let mut candidates =
|
||||
AccountAttemptLedger::freeze(&self.account_pool, &acquire_request).await;
|
||||
let mut exhausted_accounts = AccountExhaustionTracker::default();
|
||||
let mut next_required_account_id: Option<String> = None;
|
||||
let mut trace = ResponseDispatchTrace::default();
|
||||
let (account, response, collected_response, attempt): (
|
||||
Account,
|
||||
CodexBackendResponse,
|
||||
CollectedResponse,
|
||||
ResponseDispatchAttempt,
|
||||
) = loop {
|
||||
let acquired = if let Some(account_id) = next_required_account_id.take() {
|
||||
match self
|
||||
.account_pool
|
||||
.acquire_with(
|
||||
&AccountAcquireRequest::new(request.model(), Utc::now())
|
||||
.with_required_account_id(account_id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Some(acquired) => Some(acquired),
|
||||
None => candidates.acquire_next(&self.account_pool).await,
|
||||
}
|
||||
} else {
|
||||
candidates.acquire_next(&self.account_pool).await
|
||||
};
|
||||
let Some(acquired) = acquired else {
|
||||
tracing::info!(
|
||||
candidate_count = candidates.candidate_count(),
|
||||
attempted = candidates.attempted_count(),
|
||||
state_excluded = candidates.state_excluded_count(),
|
||||
"Responses account candidate ledger exhausted"
|
||||
);
|
||||
let error = exhausted_accounts
|
||||
.last_exhausted()
|
||||
.map(ResponseDispatchError::from_exhausted_account)
|
||||
.unwrap_or(ResponseDispatchError::NoActiveAccount);
|
||||
self.record_response_dispatch_error(
|
||||
request_id,
|
||||
route,
|
||||
requested_model,
|
||||
started_at,
|
||||
ResponseDispatchErrorDetails {
|
||||
client_api_key_id: request.client_api_key_id.as_deref(),
|
||||
account_id: exhausted_accounts.last_account_id(),
|
||||
stream: false,
|
||||
compact: false,
|
||||
transport: Some(backend_transport_name(
|
||||
backend_transport_for_response_request(&request),
|
||||
)),
|
||||
},
|
||||
&error,
|
||||
)
|
||||
.await;
|
||||
return Err(error);
|
||||
};
|
||||
let acquired_account_id = acquired.account.id.clone();
|
||||
// 配额验证
|
||||
let acquired = match verify_acquired_quota_if_required(
|
||||
QuotaVerificationContext {
|
||||
account_pool: self.account_pool.as_ref(),
|
||||
codex: self.codex.as_ref(),
|
||||
cloudflare: &self.cloudflare,
|
||||
account_identity: &self.account_identity,
|
||||
request_id,
|
||||
},
|
||||
acquired,
|
||||
)
|
||||
.await
|
||||
{
|
||||
QuotaVerificationDecision::Ready(acquired) => *acquired,
|
||||
QuotaVerificationDecision::RetryWithAnotherAccount => {
|
||||
exhausted_accounts.record_rate_limited(
|
||||
Some(&acquired_account_id),
|
||||
QUOTA_VERIFY_LIMIT_REACHED_MESSAGE,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let Some(attempt_request) = history.prepare_attempt(&request, &acquired.account.id)
|
||||
else {
|
||||
acquired.release_without_usage().await;
|
||||
return Err(ResponseDispatchError::HistoryUnavailable {
|
||||
upstream_error: "previous response history cannot be sent to another account"
|
||||
.to_string(),
|
||||
});
|
||||
};
|
||||
self.account_pool.wait_for_request_interval(&acquired).await;
|
||||
let account = acquired.account.clone();
|
||||
let release_account_id = account.id.clone();
|
||||
let attempt = trace.start_attempt(&release_account_id);
|
||||
let response_result = create_response_with_account_retrying_5xx(
|
||||
AccountUpstreamContext {
|
||||
codex: &self.codex,
|
||||
account_identity: &self.account_identity,
|
||||
cloudflare: &self.cloudflare,
|
||||
request_id,
|
||||
account: &account,
|
||||
},
|
||||
&attempt_request,
|
||||
let controllers = ControllerSet::new(
|
||||
Arc::clone(&self.session_affinity),
|
||||
Arc::clone(&self.account_pool),
|
||||
Arc::clone(&self.codex),
|
||||
self.cloudflare.clone(),
|
||||
Arc::clone(&self.recorder),
|
||||
);
|
||||
let context = enter_request(
|
||||
RequestEnterDependencies {
|
||||
account_pool: &self.account_pool,
|
||||
models: &self.models,
|
||||
account_identity: &self.account_identity,
|
||||
controllers,
|
||||
},
|
||||
request,
|
||||
requested_model,
|
||||
RequestMode::Complete,
|
||||
)
|
||||
.await;
|
||||
let RequestContext {
|
||||
request,
|
||||
display_model,
|
||||
compact,
|
||||
tuple_schema,
|
||||
image_generation_requested,
|
||||
controllers,
|
||||
controller_scope,
|
||||
candidates,
|
||||
} = context;
|
||||
let established = match run_attempt_pipeline(
|
||||
AttemptRunnerDependencies {
|
||||
account_pool: self.account_pool.as_ref(),
|
||||
codex: self.codex.as_ref(),
|
||||
controllers: &controllers,
|
||||
account_identity: self.account_identity.as_ref(),
|
||||
request_id,
|
||||
route,
|
||||
requested_model,
|
||||
started_at,
|
||||
)
|
||||
.await;
|
||||
acquired.complete().await;
|
||||
if let Err(error) = &response_result {
|
||||
self.cloudflare
|
||||
.capture_set_cookie_headers(
|
||||
&release_account_id,
|
||||
upstream_error_set_cookie_headers(error),
|
||||
},
|
||||
AttemptMode::Complete {
|
||||
started_at,
|
||||
tuple_schema,
|
||||
},
|
||||
request,
|
||||
controller_scope,
|
||||
candidates,
|
||||
)
|
||||
.await
|
||||
.map_err(attempt_contract_error)?
|
||||
{
|
||||
AttemptPipelineOutcome::Established(established) => match established {
|
||||
EstablishedResponse::Complete(established) => *established,
|
||||
EstablishedResponse::Stream(_) => {
|
||||
return Err(attempt_mode_mismatch("complete"));
|
||||
}
|
||||
},
|
||||
AttemptPipelineOutcome::Rejected(rejection) => {
|
||||
let rejection = *rejection;
|
||||
controllers
|
||||
.observe_dispatch_error(
|
||||
DispatchErrorObservation {
|
||||
request_id,
|
||||
client_api_key_id: rejection.request.client_api_key_id.as_deref(),
|
||||
account_id: rejection.account_id.as_deref(),
|
||||
route,
|
||||
model: requested_model,
|
||||
started_at,
|
||||
stream: false,
|
||||
compact,
|
||||
transport: Some(backend_transport_name(rejection.transport)),
|
||||
},
|
||||
&rejection.error,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
match response_result {
|
||||
Ok(response) => {
|
||||
self.cloudflare
|
||||
.capture_set_cookie_headers(
|
||||
&release_account_id,
|
||||
&response.set_cookie_headers,
|
||||
)
|
||||
.await;
|
||||
self.account_pool
|
||||
.sync_passive_rate_limit_headers(&account, &response.rate_limit_headers)
|
||||
.await;
|
||||
let collected_response =
|
||||
match response_from_codex_sse(&response.body, tuple_schema.as_ref()) {
|
||||
Ok(collected_response) => collected_response,
|
||||
Err(error) => {
|
||||
let error = ResponseDispatchError::InvalidSse(error);
|
||||
self.record_response_dispatch_error(
|
||||
request_id,
|
||||
route,
|
||||
requested_model,
|
||||
started_at,
|
||||
ResponseDispatchErrorDetails {
|
||||
client_api_key_id: request.client_api_key_id.as_deref(),
|
||||
account_id: Some(&release_account_id),
|
||||
stream: false,
|
||||
compact: false,
|
||||
transport: Some(backend_transport_name(response.transport)),
|
||||
},
|
||||
&error,
|
||||
)
|
||||
.await;
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
if matches!(collected_response, CollectedResponse::Empty) {
|
||||
self.account_pool
|
||||
.record_empty_response_attempt(
|
||||
&release_account_id,
|
||||
image_generation_requested,
|
||||
)
|
||||
.await;
|
||||
exhausted_accounts.record_upstream_unavailable(
|
||||
Some(&release_account_id),
|
||||
"upstream response did not include visible output",
|
||||
);
|
||||
if !history.can_failover() {
|
||||
break (account, response, collected_response, attempt);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let CollectedResponse::Failed(failure) = &collected_response {
|
||||
if is_history_recovery_sse_failure(failure)
|
||||
&& history.recover_managed_history(&release_account_id)
|
||||
{
|
||||
next_required_account_id = Some(release_account_id);
|
||||
continue;
|
||||
}
|
||||
if isolate_sse_account_failure(
|
||||
self.account_pool.as_ref(),
|
||||
&mut exhausted_accounts,
|
||||
&release_account_id,
|
||||
failure,
|
||||
)
|
||||
.await
|
||||
{
|
||||
if !history.can_failover() {
|
||||
break (account, response, collected_response, attempt);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
break (account, response, collected_response, attempt);
|
||||
}
|
||||
Err(error) => {
|
||||
if isolate_rotatable_account_failure(
|
||||
self.account_pool.as_ref(),
|
||||
&self.cloudflare,
|
||||
&mut exhausted_accounts,
|
||||
&release_account_id,
|
||||
&error,
|
||||
)
|
||||
.await
|
||||
{
|
||||
if !history.can_failover() {
|
||||
return Err(ResponseDispatchError::Upstream(error));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if is_continuation_busy_error(&error) {
|
||||
if history.recover_managed_history(&release_account_id) {
|
||||
next_required_account_id = Some(release_account_id);
|
||||
continue;
|
||||
}
|
||||
return Err(ResponseDispatchError::ContinuationBusy);
|
||||
}
|
||||
let history_unavailable = is_history_recovery_upstream_error(&error);
|
||||
if history_unavailable && history.recover_managed_history(&release_account_id) {
|
||||
next_required_account_id = Some(release_account_id);
|
||||
continue;
|
||||
}
|
||||
record_response_upstream_error_event(ResponseUpstreamErrorEventRecord {
|
||||
recorder: &self.recorder,
|
||||
request_id,
|
||||
account_id: &release_account_id,
|
||||
account_email: account.email.as_deref(),
|
||||
route,
|
||||
model: requested_model,
|
||||
started_at,
|
||||
stream: false,
|
||||
transport: backend_transport_for_response_request(&attempt_request),
|
||||
request: &attempt_request,
|
||||
error: &error,
|
||||
trace: &trace,
|
||||
attempt: Some(&attempt),
|
||||
})
|
||||
.await;
|
||||
if is_retryable_account_transport_error(&error) {
|
||||
if !history.can_failover() {
|
||||
return Err(ResponseDispatchError::Upstream(error));
|
||||
}
|
||||
exhausted_accounts.record_upstream_unavailable(
|
||||
Some(&release_account_id),
|
||||
upstream_error_body(&error),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if history_unavailable {
|
||||
if history.is_external_unknown() {
|
||||
return Err(ResponseDispatchError::Upstream(error));
|
||||
}
|
||||
return Err(ResponseDispatchError::HistoryUnavailable {
|
||||
upstream_error: upstream_error_body(&error),
|
||||
});
|
||||
}
|
||||
return Err(ResponseDispatchError::Upstream(error));
|
||||
}
|
||||
let error = rejection.error;
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
|
||||
let completed = matches!(&collected_response, CollectedResponse::Completed(_));
|
||||
match collected_response {
|
||||
CollectedResponse::Completed(body) | CollectedResponse::Incomplete(body) => {
|
||||
let response_id = body.get("id").and_then(Value::as_str);
|
||||
self.cloudflare.reset_account_recovery(&account.id).await;
|
||||
if let Some(usage) = response.usage {
|
||||
self.account_pool
|
||||
.record_response_usage(&account.id, usage, image_generation_requested)
|
||||
.await;
|
||||
}
|
||||
if completed {
|
||||
self.record_response_affinity(
|
||||
&history,
|
||||
&request,
|
||||
&account.id,
|
||||
&response.body,
|
||||
response.turn_state.clone(),
|
||||
response.usage,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let effective_model = response
|
||||
.response_metadata
|
||||
.effective_model
|
||||
.as_deref()
|
||||
.unwrap_or(&display_model);
|
||||
let mut metadata = json!({
|
||||
"responseId": response_id,
|
||||
"stream": false,
|
||||
"completed": completed,
|
||||
"incomplete": !completed,
|
||||
"transport": backend_transport_name(response.transport),
|
||||
"firstTokenMs": response.first_token_ms,
|
||||
"usage": response.usage,
|
||||
"effectiveModel": effective_model,
|
||||
"modelsEtag": response.response_metadata.models_etag.as_deref(),
|
||||
"reasoningIncluded": response.response_metadata.reasoning_included,
|
||||
});
|
||||
insert_response_status_metadata(
|
||||
&mut metadata,
|
||||
200,
|
||||
200,
|
||||
response.diagnostics.status_code.map(i64::from),
|
||||
);
|
||||
insert_response_upstream_diagnostics(&mut metadata, &response.diagnostics);
|
||||
insert_response_trace_metadata(&mut metadata, &trace, Some(&attempt));
|
||||
insert_websocket_pool_decision(&mut metadata, response.websocket_pool_decision);
|
||||
record_response_event(ResponseUsageRecord {
|
||||
recorder: &self.recorder,
|
||||
request_id,
|
||||
client_api_key_id: request.client_api_key_id.as_deref(),
|
||||
let EstablishedComplete {
|
||||
context,
|
||||
response,
|
||||
body,
|
||||
} = established;
|
||||
let EstablishedAttemptContext {
|
||||
request,
|
||||
controller_scope,
|
||||
trace,
|
||||
account,
|
||||
attempt,
|
||||
..
|
||||
} = context;
|
||||
let (outcome, body) = match body {
|
||||
EstablishedCompleteBody::Completed(body) => (FinalOutcome::Completed, body),
|
||||
EstablishedCompleteBody::Incomplete(body) => (FinalOutcome::Incomplete, body),
|
||||
};
|
||||
let response_id = body.get("id").and_then(Value::as_str);
|
||||
let completed = outcome == FinalOutcome::Completed;
|
||||
controllers
|
||||
.finalize_complete(
|
||||
controller_scope,
|
||||
CompleteExit {
|
||||
request: &request,
|
||||
account_id: &account.id,
|
||||
route,
|
||||
model: effective_model,
|
||||
requested_model: Some(requested_model),
|
||||
client_ip: request.client_ip.as_deref(),
|
||||
client_user_agent: request.client_user_agent.as_deref(),
|
||||
reasoning_effort: reasoning_effort_from_request(&request),
|
||||
service_tier: request.service_tier(),
|
||||
started_at,
|
||||
status_code: 200,
|
||||
message: if completed {
|
||||
"v1 responses completed"
|
||||
} else {
|
||||
"v1 responses incomplete"
|
||||
},
|
||||
metadata,
|
||||
rate_limit_headers: &response.rate_limit_headers,
|
||||
})
|
||||
.await;
|
||||
self.models
|
||||
.observe_models_etag(response.response_metadata.models_etag.as_deref());
|
||||
Ok(ResponseDispatchResponse {
|
||||
body,
|
||||
response_headers: response.response_metadata.client_headers,
|
||||
})
|
||||
}
|
||||
CollectedResponse::Failed(failure) => {
|
||||
let error = ResponseDispatchError::Failed(failure);
|
||||
self.record_response_dispatch_error(
|
||||
body: &response.body,
|
||||
turn_state: response.turn_state.clone(),
|
||||
usage: response.usage,
|
||||
image_generation_requested,
|
||||
completed,
|
||||
recorder: &self.recorder,
|
||||
models: &self.models,
|
||||
request_id,
|
||||
route,
|
||||
requested_model,
|
||||
display_model: &display_model,
|
||||
started_at,
|
||||
ResponseDispatchErrorDetails {
|
||||
client_api_key_id: request.client_api_key_id.as_deref(),
|
||||
account_id: Some(&account.id),
|
||||
stream: false,
|
||||
compact: false,
|
||||
transport: Some(backend_transport_name(response.transport)),
|
||||
},
|
||||
&error,
|
||||
)
|
||||
.await;
|
||||
Err(error)
|
||||
}
|
||||
CollectedResponse::MissingCompleted => {
|
||||
let error = ResponseDispatchError::MissingCompleted;
|
||||
self.record_response_dispatch_error(
|
||||
request_id,
|
||||
route,
|
||||
requested_model,
|
||||
started_at,
|
||||
ResponseDispatchErrorDetails {
|
||||
client_api_key_id: request.client_api_key_id.as_deref(),
|
||||
account_id: Some(&account.id),
|
||||
stream: false,
|
||||
compact: false,
|
||||
transport: Some(backend_transport_name(response.transport)),
|
||||
},
|
||||
&error,
|
||||
)
|
||||
.await;
|
||||
Err(error)
|
||||
}
|
||||
CollectedResponse::Empty => {
|
||||
let error = ResponseDispatchError::EmptyUpstreamResponse;
|
||||
self.record_response_dispatch_error(
|
||||
request_id,
|
||||
route,
|
||||
requested_model,
|
||||
started_at,
|
||||
ResponseDispatchErrorDetails {
|
||||
client_api_key_id: request.client_api_key_id.as_deref(),
|
||||
account_id: Some(&account.id),
|
||||
stream: false,
|
||||
compact: false,
|
||||
transport: Some(backend_transport_name(response.transport)),
|
||||
},
|
||||
&error,
|
||||
)
|
||||
.await;
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn record_response_dispatch_error(
|
||||
&self,
|
||||
request_id: &str,
|
||||
route: &str,
|
||||
requested_model: &str,
|
||||
started_at: Instant,
|
||||
details: ResponseDispatchErrorDetails<'_>,
|
||||
error: &ResponseDispatchError,
|
||||
) {
|
||||
record_response_dispatch_error_event(ResponseDispatchErrorEventRecord {
|
||||
recorder: &self.recorder,
|
||||
request_id,
|
||||
client_api_key_id: details.client_api_key_id,
|
||||
account_id: details.account_id,
|
||||
route,
|
||||
model: requested_model,
|
||||
started_at,
|
||||
stream: details.stream,
|
||||
compact: details.compact,
|
||||
transport: details.transport,
|
||||
error,
|
||||
response_id,
|
||||
response: &response,
|
||||
trace: &trace,
|
||||
attempt: &attempt,
|
||||
},
|
||||
outcome,
|
||||
)
|
||||
.await;
|
||||
Ok(ResponseDispatchResponse {
|
||||
body,
|
||||
response_headers: response.response_metadata.client_headers,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,46 +1,29 @@
|
||||
use std::{sync::Arc, time::Instant};
|
||||
//! 流式 Responses 在提交前共享的 request/attempt 生命周期。
|
||||
|
||||
use chrono::Utc;
|
||||
use std::{sync::Arc, time::Instant};
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
affinity::prepare_variant_identity,
|
||||
attempts::AccountAttemptLedger,
|
||||
errors::{
|
||||
backend_transport_name, is_continuation_busy_error, is_history_recovery_upstream_error,
|
||||
is_retryable_account_transport_error, upstream_error_body,
|
||||
upstream_error_set_cookie_headers, ResponseDispatchError,
|
||||
controllers::{
|
||||
ControllerSet, DispatchErrorObservation, PrefetchedStreamFailureObservation,
|
||||
StreamControllerContext,
|
||||
},
|
||||
recording::{
|
||||
record_prefetched_response_stream_failure_event, record_response_upstream_error_event,
|
||||
ResponseDispatchErrorDetails, ResponseStreamFailureEventRecord,
|
||||
ResponseUpstreamErrorEventRecord,
|
||||
},
|
||||
recovery::{
|
||||
account_failure::{isolate_rotatable_account_failure, isolate_sse_account_failure},
|
||||
exhaustion::AccountExhaustionTracker,
|
||||
history::HistoryRecoveryPlan,
|
||||
errors::{ResponseDispatchError, backend_transport_name},
|
||||
lifecycle::{
|
||||
RequestContext, RequestEnterDependencies, RequestMode,
|
||||
attempt::{AttemptMode, AttemptRunnerDependencies},
|
||||
contract::{
|
||||
AttemptContractError, EstablishedAttemptContext, EstablishedResponse,
|
||||
EstablishedStream,
|
||||
},
|
||||
enter_request,
|
||||
finalizer::StreamFinalizer,
|
||||
pipeline::{AttemptPipelineOutcome, run_attempt_pipeline},
|
||||
},
|
||||
service::{ResponseDispatchService, ResponseDispatchStream},
|
||||
stream::{
|
||||
live::{spawn_live_response_stream, LiveResponseStreamContext},
|
||||
prefetch::prefetch_first_sse_chunk,
|
||||
sse_failure::{
|
||||
first_sse_failure, is_history_recovery_sse_failure, sse_failure_error_body,
|
||||
},
|
||||
trace::ResponseDispatchTrace,
|
||||
},
|
||||
upstream_call::{
|
||||
create_response_stream_with_account_retrying_5xx, verify_acquired_quota_if_required,
|
||||
AccountUpstreamContext, QuotaVerificationContext, QuotaVerificationDecision,
|
||||
QUOTA_VERIFY_LIMIT_REACHED_MESSAGE,
|
||||
},
|
||||
},
|
||||
fleet::pool::AccountAcquireRequest,
|
||||
upstream::openai::{
|
||||
protocol::responses::CodexResponsesRequest,
|
||||
transport::backend_transport_for_response_request,
|
||||
stream::live::spawn_live_response_stream,
|
||||
},
|
||||
upstream::openai::protocol::{responses::CodexResponsesRequest, sse::SseError},
|
||||
};
|
||||
|
||||
impl ResponseDispatchService {
|
||||
@@ -49,441 +32,180 @@ impl ResponseDispatchService {
|
||||
&self,
|
||||
request_id: &str,
|
||||
route: &str,
|
||||
mut request: CodexResponsesRequest,
|
||||
request: CodexResponsesRequest,
|
||||
requested_model: &str,
|
||||
) -> Result<ResponseDispatchStream, ResponseDispatchError> {
|
||||
let started_at = Instant::now();
|
||||
let catalog = self.models.catalog().await;
|
||||
let display_model = catalog.resolve_model_id(requested_model);
|
||||
request.set_model(display_model.clone());
|
||||
request.set_stream(true);
|
||||
let tuple_schema = request.tuple_schema.clone();
|
||||
let now = Utc::now();
|
||||
prepare_variant_identity(&mut request);
|
||||
self.account_identity.prepare_local_identity(&mut request);
|
||||
let mut history = HistoryRecoveryPlan::load(&self.session_affinity, &request).await;
|
||||
let preferred_account_id = self
|
||||
.preferred_account_id_for_request(&request, &history, now)
|
||||
.await;
|
||||
let mut acquire_request = AccountAcquireRequest::new(request.model(), now);
|
||||
if let Some(preferred_account_id) = preferred_account_id {
|
||||
acquire_request = acquire_request.with_preferred_account_id(preferred_account_id);
|
||||
}
|
||||
let mut candidates =
|
||||
AccountAttemptLedger::freeze(&self.account_pool, &acquire_request).await;
|
||||
let mut exhausted_accounts = AccountExhaustionTracker::default();
|
||||
let mut next_required_account_id: Option<String> = None;
|
||||
let mut trace = ResponseDispatchTrace::default();
|
||||
macro_rules! return_stream_dispatch_error {
|
||||
($error:expr) => {{
|
||||
let error = $error;
|
||||
self.record_response_dispatch_error(
|
||||
request_id,
|
||||
route,
|
||||
requested_model,
|
||||
started_at,
|
||||
ResponseDispatchErrorDetails {
|
||||
client_api_key_id: request.client_api_key_id.as_deref(),
|
||||
account_id: exhausted_accounts.last_account_id(),
|
||||
stream: true,
|
||||
compact: false,
|
||||
transport: Some(backend_transport_name(
|
||||
backend_transport_for_response_request(&request),
|
||||
)),
|
||||
},
|
||||
&error,
|
||||
)
|
||||
.await;
|
||||
return Err(error);
|
||||
}};
|
||||
($error:expr, account_id: $account_id:expr, transport: $transport:expr) => {{
|
||||
let error = $error;
|
||||
self.record_response_dispatch_error(
|
||||
request_id,
|
||||
route,
|
||||
requested_model,
|
||||
started_at,
|
||||
ResponseDispatchErrorDetails {
|
||||
client_api_key_id: request.client_api_key_id.as_deref(),
|
||||
account_id: $account_id,
|
||||
stream: true,
|
||||
compact: false,
|
||||
transport: $transport,
|
||||
},
|
||||
&error,
|
||||
)
|
||||
.await;
|
||||
return Err(error);
|
||||
}};
|
||||
}
|
||||
loop {
|
||||
let acquired = if let Some(account_id) = next_required_account_id.take() {
|
||||
match self
|
||||
.account_pool
|
||||
.acquire_with(
|
||||
&AccountAcquireRequest::new(request.model(), Utc::now())
|
||||
.with_required_account_id(account_id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Some(acquired) => Some(acquired),
|
||||
None => candidates.acquire_next(&self.account_pool).await,
|
||||
let controllers = ControllerSet::new(
|
||||
Arc::clone(&self.session_affinity),
|
||||
Arc::clone(&self.account_pool),
|
||||
Arc::clone(&self.codex),
|
||||
self.cloudflare.clone(),
|
||||
Arc::clone(&self.recorder),
|
||||
);
|
||||
let context = enter_request(
|
||||
RequestEnterDependencies {
|
||||
account_pool: &self.account_pool,
|
||||
models: &self.models,
|
||||
account_identity: &self.account_identity,
|
||||
controllers,
|
||||
},
|
||||
request,
|
||||
requested_model,
|
||||
RequestMode::Stream,
|
||||
)
|
||||
.await;
|
||||
let RequestContext {
|
||||
request,
|
||||
display_model,
|
||||
compact,
|
||||
tuple_schema,
|
||||
controllers,
|
||||
controller_scope,
|
||||
candidates,
|
||||
..
|
||||
} = context;
|
||||
let established = match run_attempt_pipeline(
|
||||
AttemptRunnerDependencies {
|
||||
account_pool: self.account_pool.as_ref(),
|
||||
codex: self.codex.as_ref(),
|
||||
controllers: &controllers,
|
||||
account_identity: self.account_identity.as_ref(),
|
||||
request_id,
|
||||
route,
|
||||
requested_model,
|
||||
started_at,
|
||||
},
|
||||
AttemptMode::Stream {
|
||||
tuple_schema: tuple_schema.clone(),
|
||||
},
|
||||
request,
|
||||
controller_scope,
|
||||
candidates,
|
||||
)
|
||||
.await
|
||||
.map_err(attempt_contract_error)?
|
||||
{
|
||||
AttemptPipelineOutcome::Established(established) => match established {
|
||||
EstablishedResponse::Stream(established) => *established,
|
||||
EstablishedResponse::Complete(_) => return Err(attempt_mode_mismatch()),
|
||||
},
|
||||
AttemptPipelineOutcome::Rejected(rejection) => {
|
||||
let rejection = *rejection;
|
||||
if let (Some(account), Some(attempt_request), Some(attempt), Some(stream_failure)) = (
|
||||
rejection.account.as_ref(),
|
||||
rejection.attempt_request.as_ref(),
|
||||
rejection.attempt.as_ref(),
|
||||
rejection.stream_failure.as_ref(),
|
||||
) {
|
||||
controllers
|
||||
.observe_prefetched_stream_failure(PrefetchedStreamFailureObservation {
|
||||
request_id,
|
||||
account_id: &account.id,
|
||||
route,
|
||||
model: &display_model,
|
||||
requested_model,
|
||||
started_at,
|
||||
transport: rejection.transport,
|
||||
request: attempt_request,
|
||||
failure: &stream_failure.failure,
|
||||
error: &rejection.error,
|
||||
diagnostics: &stream_failure.diagnostics,
|
||||
rate_limit_headers: &stream_failure.rate_limit_headers,
|
||||
prefetched: &stream_failure.prefetched,
|
||||
trace: &rejection.trace,
|
||||
attempt,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
} else {
|
||||
candidates.acquire_next(&self.account_pool).await
|
||||
};
|
||||
let Some(acquired) = acquired else {
|
||||
tracing::info!(
|
||||
candidate_count = candidates.candidate_count(),
|
||||
attempted = candidates.attempted_count(),
|
||||
state_excluded = candidates.state_excluded_count(),
|
||||
"Responses stream account candidate ledger exhausted"
|
||||
);
|
||||
let error = exhausted_accounts
|
||||
.last_exhausted()
|
||||
.map(ResponseDispatchError::from_exhausted_account)
|
||||
.unwrap_or(ResponseDispatchError::NoActiveAccount);
|
||||
return_stream_dispatch_error!(error);
|
||||
};
|
||||
let acquired_account_id = acquired.account.id.clone();
|
||||
let acquired = match verify_acquired_quota_if_required(
|
||||
QuotaVerificationContext {
|
||||
account_pool: self.account_pool.as_ref(),
|
||||
codex: self.codex.as_ref(),
|
||||
cloudflare: &self.cloudflare,
|
||||
account_identity: &self.account_identity,
|
||||
request_id,
|
||||
},
|
||||
acquired,
|
||||
)
|
||||
.await
|
||||
{
|
||||
QuotaVerificationDecision::Ready(acquired) => *acquired,
|
||||
QuotaVerificationDecision::RetryWithAnotherAccount => {
|
||||
exhausted_accounts.record_rate_limited(
|
||||
Some(&acquired_account_id),
|
||||
QUOTA_VERIFY_LIMIT_REACHED_MESSAGE,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let Some(attempt_request) = history.prepare_attempt(&request, &acquired.account.id)
|
||||
else {
|
||||
acquired.release_without_usage().await;
|
||||
return_stream_dispatch_error!(ResponseDispatchError::HistoryUnavailable {
|
||||
upstream_error: "previous response history cannot be sent to another account"
|
||||
.to_string(),
|
||||
});
|
||||
};
|
||||
|
||||
self.account_pool.wait_for_request_interval(&acquired).await;
|
||||
let account = acquired.account.clone();
|
||||
let release_account_id = account.id.clone();
|
||||
let attempt = trace.start_attempt(&release_account_id);
|
||||
let response_result = create_response_stream_with_account_retrying_5xx(
|
||||
AccountUpstreamContext {
|
||||
codex: &self.codex,
|
||||
account_identity: &self.account_identity,
|
||||
cloudflare: &self.cloudflare,
|
||||
request_id,
|
||||
account: &account,
|
||||
},
|
||||
&attempt_request,
|
||||
)
|
||||
.await;
|
||||
if let Err(error) = &response_result {
|
||||
self.cloudflare
|
||||
.capture_set_cookie_headers(
|
||||
&release_account_id,
|
||||
upstream_error_set_cookie_headers(error),
|
||||
controllers
|
||||
.observe_dispatch_error(
|
||||
DispatchErrorObservation {
|
||||
request_id,
|
||||
client_api_key_id: rejection.request.client_api_key_id.as_deref(),
|
||||
account_id: rejection.account_id.as_deref(),
|
||||
route,
|
||||
model: requested_model,
|
||||
started_at,
|
||||
stream: true,
|
||||
compact,
|
||||
transport: Some(backend_transport_name(rejection.transport)),
|
||||
},
|
||||
&rejection.error,
|
||||
)
|
||||
.await;
|
||||
let error = rejection.error;
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
|
||||
match response_result {
|
||||
Ok(response) => {
|
||||
let transport = response.transport;
|
||||
let set_cookie_headers = response.set_cookie_headers;
|
||||
let rate_limit_headers = response.rate_limit_headers;
|
||||
let rate_limit_header_updates = response.rate_limit_header_updates;
|
||||
let turn_state_update = response.turn_state_update;
|
||||
let websocket_pool_decision = response.websocket_pool_decision;
|
||||
let turn_state = response.turn_state;
|
||||
let diagnostics = response.diagnostics;
|
||||
let response_metadata = response.response_metadata;
|
||||
self.models
|
||||
.observe_models_etag(response_metadata.models_etag.as_deref());
|
||||
self.cloudflare
|
||||
.capture_set_cookie_headers(&release_account_id, &set_cookie_headers)
|
||||
.await;
|
||||
self.account_pool
|
||||
.sync_passive_rate_limit_headers(&account, &rate_limit_headers)
|
||||
.await;
|
||||
let (prefetched, body) = match prefetch_first_sse_chunk(response.body).await {
|
||||
Ok(prefetched) => prefetched,
|
||||
Err(ResponseDispatchError::Upstream(error)) => {
|
||||
acquired.complete().await;
|
||||
if isolate_rotatable_account_failure(
|
||||
self.account_pool.as_ref(),
|
||||
&self.cloudflare,
|
||||
&mut exhausted_accounts,
|
||||
&release_account_id,
|
||||
&error,
|
||||
)
|
||||
.await
|
||||
{
|
||||
if history.is_external_unknown() {
|
||||
return_stream_dispatch_error!(
|
||||
ResponseDispatchError::Upstream(error),
|
||||
account_id: Some(&release_account_id),
|
||||
transport: Some(backend_transport_name(transport))
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if is_continuation_busy_error(&error) {
|
||||
if history.recover_managed_history(&release_account_id) {
|
||||
next_required_account_id = Some(release_account_id);
|
||||
continue;
|
||||
}
|
||||
return_stream_dispatch_error!(
|
||||
ResponseDispatchError::ContinuationBusy,
|
||||
account_id: Some(&release_account_id),
|
||||
transport: Some(backend_transport_name(transport))
|
||||
);
|
||||
}
|
||||
let history_unavailable = is_history_recovery_upstream_error(&error);
|
||||
if history_unavailable
|
||||
&& history.recover_managed_history(&release_account_id)
|
||||
{
|
||||
next_required_account_id = Some(release_account_id);
|
||||
continue;
|
||||
}
|
||||
record_response_upstream_error_event(
|
||||
ResponseUpstreamErrorEventRecord {
|
||||
recorder: &self.recorder,
|
||||
request_id,
|
||||
account_id: &release_account_id,
|
||||
account_email: account.email.as_deref(),
|
||||
route,
|
||||
model: requested_model,
|
||||
started_at,
|
||||
stream: true,
|
||||
transport,
|
||||
request: &attempt_request,
|
||||
error: &error,
|
||||
trace: &trace,
|
||||
attempt: Some(&attempt),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
if is_retryable_account_transport_error(&error) {
|
||||
exhausted_accounts.record_upstream_unavailable(
|
||||
Some(&release_account_id),
|
||||
upstream_error_body(&error),
|
||||
);
|
||||
if history.is_external_unknown() {
|
||||
return Err(ResponseDispatchError::Upstream(error));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if history_unavailable {
|
||||
if history.is_external_unknown() {
|
||||
return Err(ResponseDispatchError::Upstream(error));
|
||||
}
|
||||
return Err(ResponseDispatchError::HistoryUnavailable {
|
||||
upstream_error: upstream_error_body(&error),
|
||||
});
|
||||
}
|
||||
return Err(ResponseDispatchError::Upstream(error));
|
||||
}
|
||||
Err(error) => {
|
||||
acquired.complete().await;
|
||||
return_stream_dispatch_error!(
|
||||
error,
|
||||
account_id: Some(&release_account_id),
|
||||
transport: Some(backend_transport_name(transport))
|
||||
);
|
||||
}
|
||||
};
|
||||
let first_failure = match first_sse_failure(&prefetched) {
|
||||
Ok(failure) => failure,
|
||||
Err(error) => {
|
||||
acquired.complete().await;
|
||||
return_stream_dispatch_error!(
|
||||
ResponseDispatchError::InvalidSse(error),
|
||||
account_id: Some(&release_account_id),
|
||||
transport: Some(backend_transport_name(transport))
|
||||
);
|
||||
}
|
||||
};
|
||||
if let Some(failure) = first_failure {
|
||||
if is_history_recovery_sse_failure(&failure)
|
||||
&& history.recover_managed_history(&release_account_id)
|
||||
{
|
||||
acquired.complete().await;
|
||||
next_required_account_id = Some(release_account_id);
|
||||
continue;
|
||||
}
|
||||
if isolate_sse_account_failure(
|
||||
self.account_pool.as_ref(),
|
||||
&mut exhausted_accounts,
|
||||
&release_account_id,
|
||||
&failure,
|
||||
)
|
||||
.await
|
||||
{
|
||||
acquired.complete().await;
|
||||
if history.is_external_unknown() {
|
||||
return_stream_dispatch_error!(
|
||||
ResponseDispatchError::Failed(failure),
|
||||
account_id: Some(&release_account_id),
|
||||
transport: Some(backend_transport_name(transport))
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
acquired.complete().await;
|
||||
record_prefetched_response_stream_failure_event(
|
||||
ResponseStreamFailureEventRecord {
|
||||
recorder: &self.recorder,
|
||||
request_id,
|
||||
account_id: &release_account_id,
|
||||
route,
|
||||
model: &display_model,
|
||||
requested_model,
|
||||
started_at,
|
||||
transport,
|
||||
request: &attempt_request,
|
||||
failure: &failure,
|
||||
diagnostics: &diagnostics,
|
||||
rate_limit_headers: &rate_limit_headers,
|
||||
prefetched: &prefetched,
|
||||
trace: &trace,
|
||||
attempt: &attempt,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let error = if is_history_recovery_sse_failure(&failure)
|
||||
&& !history.is_external_unknown()
|
||||
{
|
||||
ResponseDispatchError::HistoryUnavailable {
|
||||
upstream_error: sse_failure_error_body(&failure),
|
||||
}
|
||||
} else {
|
||||
ResponseDispatchError::Failed(failure.clone())
|
||||
};
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
let context = LiveResponseStreamContext {
|
||||
account_pool: Arc::clone(&self.account_pool),
|
||||
account_lease: acquired,
|
||||
session_affinity: Arc::clone(&self.session_affinity),
|
||||
history,
|
||||
recorder: Arc::clone(&self.recorder),
|
||||
cloudflare: self.cloudflare.clone(),
|
||||
account_id: account.id,
|
||||
account_plan_type: account.plan_type,
|
||||
request_id: request_id.to_string(),
|
||||
route: route.to_string(),
|
||||
display_model: display_model.clone(),
|
||||
requested_model: requested_model.to_string(),
|
||||
client_ip: request.client_ip.clone(),
|
||||
request,
|
||||
tuple_schema,
|
||||
transport,
|
||||
rate_limit_headers,
|
||||
rate_limit_header_updates,
|
||||
turn_state_update,
|
||||
websocket_pool_decision,
|
||||
turn_state,
|
||||
diagnostics,
|
||||
response_metadata,
|
||||
attempt: attempt.clone(),
|
||||
attempts: trace.attempts().to_vec(),
|
||||
started_at,
|
||||
};
|
||||
return Ok(spawn_live_response_stream(context, prefetched, body));
|
||||
}
|
||||
Err(error) => {
|
||||
acquired.complete().await;
|
||||
if isolate_rotatable_account_failure(
|
||||
self.account_pool.as_ref(),
|
||||
&self.cloudflare,
|
||||
&mut exhausted_accounts,
|
||||
&release_account_id,
|
||||
&error,
|
||||
)
|
||||
.await
|
||||
{
|
||||
if history.is_external_unknown() {
|
||||
return_stream_dispatch_error!(
|
||||
ResponseDispatchError::Upstream(error),
|
||||
account_id: Some(&release_account_id),
|
||||
transport: Some(backend_transport_name(
|
||||
backend_transport_for_response_request(&attempt_request)
|
||||
))
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if is_continuation_busy_error(&error) {
|
||||
if history.recover_managed_history(&release_account_id) {
|
||||
next_required_account_id = Some(release_account_id);
|
||||
continue;
|
||||
}
|
||||
return_stream_dispatch_error!(
|
||||
ResponseDispatchError::ContinuationBusy,
|
||||
account_id: Some(&release_account_id),
|
||||
transport: Some(backend_transport_name(
|
||||
backend_transport_for_response_request(&attempt_request)
|
||||
))
|
||||
);
|
||||
}
|
||||
let history_unavailable = is_history_recovery_upstream_error(&error);
|
||||
if history_unavailable && history.recover_managed_history(&release_account_id) {
|
||||
next_required_account_id = Some(release_account_id);
|
||||
continue;
|
||||
}
|
||||
record_response_upstream_error_event(ResponseUpstreamErrorEventRecord {
|
||||
recorder: &self.recorder,
|
||||
request_id,
|
||||
account_id: &release_account_id,
|
||||
account_email: account.email.as_deref(),
|
||||
route,
|
||||
model: requested_model,
|
||||
started_at,
|
||||
stream: true,
|
||||
transport: backend_transport_for_response_request(&attempt_request),
|
||||
request: &attempt_request,
|
||||
error: &error,
|
||||
trace: &trace,
|
||||
attempt: Some(&attempt),
|
||||
})
|
||||
.await;
|
||||
if is_retryable_account_transport_error(&error) {
|
||||
exhausted_accounts.record_upstream_unavailable(
|
||||
Some(&release_account_id),
|
||||
upstream_error_body(&error),
|
||||
);
|
||||
if history.is_external_unknown() {
|
||||
return Err(ResponseDispatchError::Upstream(error));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if history_unavailable {
|
||||
if history.is_external_unknown() {
|
||||
return Err(ResponseDispatchError::Upstream(error));
|
||||
}
|
||||
return Err(ResponseDispatchError::HistoryUnavailable {
|
||||
upstream_error: upstream_error_body(&error),
|
||||
});
|
||||
}
|
||||
return Err(ResponseDispatchError::Upstream(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
let EstablishedStream {
|
||||
context,
|
||||
lease,
|
||||
response,
|
||||
decoder,
|
||||
initial_batch,
|
||||
first_event_ms,
|
||||
} = established;
|
||||
let EstablishedAttemptContext {
|
||||
request,
|
||||
controller_scope,
|
||||
trace,
|
||||
account,
|
||||
attempt,
|
||||
..
|
||||
} = context;
|
||||
self.models
|
||||
.observe_models_etag(response.response_metadata.models_etag.as_deref());
|
||||
let attempts = trace.attempts().to_vec();
|
||||
let transport = response.transport;
|
||||
let finalizer = StreamFinalizer::new(
|
||||
controllers,
|
||||
controller_scope,
|
||||
StreamControllerContext {
|
||||
account_id: account.id,
|
||||
account_plan_type: account.plan_type,
|
||||
request_id: request_id.to_string(),
|
||||
route: route.to_string(),
|
||||
display_model,
|
||||
requested_model: requested_model.to_string(),
|
||||
request,
|
||||
transport,
|
||||
set_cookie_headers: response.set_cookie_headers,
|
||||
rate_limit_headers: response.rate_limit_headers,
|
||||
rate_limit_header_updates: response.rate_limit_header_updates,
|
||||
turn_state_update: response.turn_state_update,
|
||||
websocket_pool_decision: response.websocket_pool_decision,
|
||||
turn_state: response.turn_state,
|
||||
diagnostics: response.diagnostics,
|
||||
response_metadata: response.response_metadata,
|
||||
transport_metrics: response.transport_metrics,
|
||||
connection_local_continuation: response.connection_local_continuation,
|
||||
attempt,
|
||||
attempts,
|
||||
started_at,
|
||||
},
|
||||
lease,
|
||||
);
|
||||
Ok(spawn_live_response_stream(
|
||||
finalizer,
|
||||
decoder,
|
||||
initial_batch,
|
||||
first_event_ms,
|
||||
response.body,
|
||||
self.shutdown.clone(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn attempt_contract_error(error: AttemptContractError) -> ResponseDispatchError {
|
||||
ResponseDispatchError::InvalidSse(SseError::ParseError(format!(
|
||||
"attempt lifecycle contract violation: {error}"
|
||||
)))
|
||||
}
|
||||
|
||||
fn attempt_mode_mismatch() -> ResponseDispatchError {
|
||||
ResponseDispatchError::InvalidSse(SseError::ParseError(
|
||||
"attempt lifecycle returned a non-stream response for stream mode".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
+258
-487
@@ -1,58 +1,32 @@
|
||||
use std::{
|
||||
pin::Pin,
|
||||
sync::Arc,
|
||||
task::{Context, Poll},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::{stream::Stream, StreamExt};
|
||||
use serde_json::Value;
|
||||
use futures::{StreamExt, stream::Stream};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
affinity::{resolve::record_response_affinity, SessionAffinityService},
|
||||
errors::{backend_transport_name, ResponseDispatchStreamError},
|
||||
recording::{
|
||||
insert_first_token_ms, live_response_rate_limit_headers, live_response_turn_state,
|
||||
record_live_response_stream_event,
|
||||
errors::ResponseDispatchStreamError,
|
||||
lifecycle::{
|
||||
finalizer::StreamFinalizer,
|
||||
stream::{StreamSummary, StreamTerminal},
|
||||
},
|
||||
recovery::{cloudflare::CloudflareRecovery, history::HistoryRecoveryPlan},
|
||||
service::ResponseDispatchStream,
|
||||
transport::canonical::{
|
||||
CanonicalResponseChunk, CanonicalResponseEvent, CanonicalStreamBatch,
|
||||
CanonicalStreamDecoder,
|
||||
},
|
||||
},
|
||||
fleet::pool::{AccountLease, AccountPoolService},
|
||||
infra::time::elapsed_millis_i64,
|
||||
telemetry::{recorder::Recorder, usage::types::UsageRecordLevel},
|
||||
upstream::openai::{
|
||||
protocol::{
|
||||
events::extract_sse_usage,
|
||||
responses::{
|
||||
reconvert_responses_sse_event_tuple_values, response_from_codex_sse,
|
||||
response_sse_event_is_terminal, update_first_response_output_ms,
|
||||
CodexResponsesRequest, CollectedResponse,
|
||||
},
|
||||
sse::{
|
||||
encode_sse_event, parse_sse_events, response_failed_sse_event_with_id,
|
||||
sse_body_has_done, sse_frame_end, DONE_SSE_FRAME,
|
||||
},
|
||||
},
|
||||
transport::{
|
||||
CodexBackendSseStream, CodexBackendTransport, CodexRateLimitHeaderUpdates,
|
||||
CodexResponseMetadata, CodexTurnStateUpdate, CodexUpstreamDiagnostics,
|
||||
WebSocketPoolDecision,
|
||||
},
|
||||
},
|
||||
upstream::openai::transport::CodexBackendSseStream,
|
||||
};
|
||||
|
||||
use super::{
|
||||
sse_failure::{
|
||||
status_code_for_stream_failure, stream_failure_metadata, stream_failure_source,
|
||||
synthetic_stream_disconnected_detail, STREAM_DISCONNECTED_CODE,
|
||||
STREAM_DISCONNECTED_MESSAGE,
|
||||
},
|
||||
trace::ResponseDispatchAttempt,
|
||||
};
|
||||
const MAX_LIVE_RESPONSE_CAPTURE_BYTES: usize = 16 * 1024 * 1024;
|
||||
|
||||
struct MpscResponseBodyStream {
|
||||
receiver: mpsc::Receiver<Result<Bytes, ResponseDispatchStreamError>>,
|
||||
@@ -76,105 +50,34 @@ impl Stream for MpscResponseBodyStream {
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn spawn_live_response_stream(
|
||||
context: LiveResponseStreamContext,
|
||||
prefetched: Bytes,
|
||||
mut body: CodexBackendSseStream,
|
||||
finalizer: StreamFinalizer,
|
||||
decoder: CanonicalStreamDecoder,
|
||||
initial_batch: CanonicalStreamBatch,
|
||||
first_event_ms: i64,
|
||||
body: CodexBackendSseStream,
|
||||
shutdown: CancellationToken,
|
||||
) -> ResponseDispatchStream {
|
||||
let response_headers = context.response_metadata.client_headers.clone();
|
||||
let response_headers = finalizer.response_headers().to_vec();
|
||||
let started_at = finalizer.started_at();
|
||||
let (sender, receiver) = mpsc::channel(8);
|
||||
let (cancel_sender, mut cancel_receiver) = oneshot::channel();
|
||||
let (event_sender, canonical_events) = mpsc::unbounded_channel();
|
||||
let (cancel_sender, cancel_receiver) = oneshot::channel();
|
||||
tokio::spawn(async move {
|
||||
let mut tuple_transformer = context
|
||||
.tuple_schema
|
||||
.clone()
|
||||
.map(TupleSseEventTransformer::new);
|
||||
let mut body_bytes = Vec::new();
|
||||
let mut first_token_ms = None;
|
||||
if !send_live_response_stream_chunk(
|
||||
let summary = run_live_response_stream(
|
||||
&sender,
|
||||
&mut body_bytes,
|
||||
tuple_transformer.as_mut(),
|
||||
prefetched,
|
||||
&event_sender,
|
||||
LiveRunInputs {
|
||||
initial_batch,
|
||||
first_event_ms,
|
||||
body,
|
||||
cancel: cancel_receiver,
|
||||
decoder,
|
||||
started_at,
|
||||
shutdown,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
context.account_lease.complete().await;
|
||||
return;
|
||||
}
|
||||
update_first_response_output_ms(context.started_at, &body_bytes, &mut first_token_ms);
|
||||
|
||||
loop {
|
||||
let next = tokio::select! {
|
||||
_ = &mut cancel_receiver => {
|
||||
context.account_lease.complete().await;
|
||||
return;
|
||||
}
|
||||
next = body.next() => next,
|
||||
};
|
||||
let Some(next) = next else {
|
||||
break;
|
||||
};
|
||||
match next {
|
||||
Ok(chunk) => {
|
||||
if !send_live_response_stream_chunk(
|
||||
&sender,
|
||||
&mut body_bytes,
|
||||
tuple_transformer.as_mut(),
|
||||
chunk,
|
||||
)
|
||||
.await
|
||||
{
|
||||
context.account_lease.complete().await;
|
||||
return;
|
||||
}
|
||||
update_first_response_output_ms(
|
||||
context.started_at,
|
||||
&body_bytes,
|
||||
&mut first_token_ms,
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
if !flush_live_response_stream_transformer(
|
||||
&sender,
|
||||
&mut body_bytes,
|
||||
tuple_transformer.as_mut(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
context.account_lease.complete().await;
|
||||
return;
|
||||
}
|
||||
let detail = error.to_string();
|
||||
let Some(body_text) =
|
||||
send_live_response_stream_tail(&sender, &mut body_bytes, Some(&detail))
|
||||
.await
|
||||
else {
|
||||
context.account_lease.complete().await;
|
||||
return;
|
||||
};
|
||||
finalize_live_response_stream(context, body_text, first_token_ms).await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !flush_live_response_stream_transformer(
|
||||
&sender,
|
||||
&mut body_bytes,
|
||||
tuple_transformer.as_mut(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
context.account_lease.complete().await;
|
||||
return;
|
||||
}
|
||||
let Some(body_text) = send_live_response_stream_tail(&sender, &mut body_bytes, None).await
|
||||
else {
|
||||
context.account_lease.complete().await;
|
||||
return;
|
||||
};
|
||||
|
||||
finalize_live_response_stream(context, body_text, first_token_ms).await;
|
||||
.await;
|
||||
finalizer.finalize(&sender, &event_sender, summary).await;
|
||||
});
|
||||
|
||||
ResponseDispatchStream {
|
||||
@@ -182,377 +85,245 @@ pub(in crate::dispatch) fn spawn_live_response_stream(
|
||||
receiver,
|
||||
cancel: Some(cancel_sender),
|
||||
}),
|
||||
canonical_events,
|
||||
response_headers,
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_live_response_stream_chunk(
|
||||
struct LiveRunInputs {
|
||||
initial_batch: CanonicalStreamBatch,
|
||||
first_event_ms: i64,
|
||||
body: CodexBackendSseStream,
|
||||
cancel: oneshot::Receiver<()>,
|
||||
decoder: CanonicalStreamDecoder,
|
||||
started_at: Instant,
|
||||
shutdown: CancellationToken,
|
||||
}
|
||||
|
||||
async fn run_live_response_stream(
|
||||
sender: &mpsc::Sender<Result<Bytes, ResponseDispatchStreamError>>,
|
||||
body_bytes: &mut Vec<u8>,
|
||||
transformer: Option<&mut TupleSseEventTransformer>,
|
||||
chunk: Bytes,
|
||||
) -> bool {
|
||||
let chunks = match transformer {
|
||||
Some(transformer) => transformer.push(&chunk),
|
||||
None => vec![chunk],
|
||||
};
|
||||
send_live_response_stream_chunks(sender, body_bytes, chunks).await
|
||||
}
|
||||
event_sender: &mpsc::UnboundedSender<Vec<CanonicalResponseEvent>>,
|
||||
inputs: LiveRunInputs,
|
||||
) -> StreamSummary {
|
||||
let LiveRunInputs {
|
||||
initial_batch,
|
||||
first_event_ms,
|
||||
mut body,
|
||||
mut cancel,
|
||||
mut decoder,
|
||||
started_at,
|
||||
shutdown,
|
||||
} = inputs;
|
||||
let mut body_bytes = Vec::new();
|
||||
let mut terminal_chunks = Vec::new();
|
||||
let mut first_token_ms = None;
|
||||
|
||||
async fn flush_live_response_stream_transformer(
|
||||
sender: &mpsc::Sender<Result<Bytes, ResponseDispatchStreamError>>,
|
||||
body_bytes: &mut Vec<u8>,
|
||||
transformer: Option<&mut TupleSseEventTransformer>,
|
||||
) -> bool {
|
||||
let Some(transformer) = transformer else {
|
||||
return true;
|
||||
};
|
||||
send_live_response_stream_chunks(sender, body_bytes, transformer.finish()).await
|
||||
}
|
||||
|
||||
async fn send_live_response_stream_chunks(
|
||||
sender: &mpsc::Sender<Result<Bytes, ResponseDispatchStreamError>>,
|
||||
body_bytes: &mut Vec<u8>,
|
||||
chunks: Vec<Bytes>,
|
||||
) -> bool {
|
||||
for chunk in chunks {
|
||||
body_bytes.extend_from_slice(&chunk);
|
||||
if sender.send(Ok(chunk)).await.is_err() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
struct TupleSseEventTransformer {
|
||||
tuple_schema: Value,
|
||||
pending: Vec<u8>,
|
||||
}
|
||||
|
||||
impl TupleSseEventTransformer {
|
||||
fn new(tuple_schema: Value) -> Self {
|
||||
Self {
|
||||
tuple_schema,
|
||||
pending: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, chunk: &[u8]) -> Vec<Bytes> {
|
||||
self.pending.extend_from_slice(chunk);
|
||||
let mut chunks = Vec::new();
|
||||
while let Some(frame_end) = sse_frame_end(&self.pending) {
|
||||
let frame = self.pending.drain(..frame_end).collect::<Vec<_>>();
|
||||
chunks.push(self.transform_frame(&frame));
|
||||
}
|
||||
chunks
|
||||
}
|
||||
|
||||
fn finish(&mut self) -> Vec<Bytes> {
|
||||
if self.pending.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let frame = std::mem::take(&mut self.pending);
|
||||
vec![self.transform_frame(&frame)]
|
||||
}
|
||||
|
||||
fn transform_frame(&self, frame: &[u8]) -> Bytes {
|
||||
let frame_text = String::from_utf8_lossy(frame);
|
||||
let Ok(events) = parse_sse_events(&frame_text) else {
|
||||
return Bytes::copy_from_slice(frame);
|
||||
};
|
||||
let [event] = events.as_slice() else {
|
||||
return Bytes::copy_from_slice(frame);
|
||||
};
|
||||
let Ok(data) = serde_json::from_str::<Value>(&event.data) else {
|
||||
return Bytes::copy_from_slice(frame);
|
||||
};
|
||||
let transformed = reconvert_responses_sse_event_tuple_values(
|
||||
event.event.as_deref(),
|
||||
data,
|
||||
&self.tuple_schema,
|
||||
);
|
||||
Bytes::from(encode_sse_event(
|
||||
event.event.as_deref().unwrap_or_default(),
|
||||
&transformed.to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_live_response_stream_tail(
|
||||
sender: &mpsc::Sender<Result<Bytes, ResponseDispatchStreamError>>,
|
||||
body_bytes: &mut Vec<u8>,
|
||||
failure_detail: Option<&str>,
|
||||
) -> Option<String> {
|
||||
let mut body_text = String::from_utf8_lossy(body_bytes).to_string();
|
||||
if !sse_body_has_terminal_event(&body_text) {
|
||||
if let Some(separator) = missing_sse_event_separator(&body_text) {
|
||||
body_text.push_str(separator);
|
||||
body_bytes.extend_from_slice(separator.as_bytes());
|
||||
if sender
|
||||
.send(Ok(Bytes::copy_from_slice(separator.as_bytes())))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let failure =
|
||||
premature_close_failed_event(latest_response_id(&body_text).as_deref(), failure_detail);
|
||||
body_text.push_str(&failure);
|
||||
body_bytes.extend_from_slice(failure.as_bytes());
|
||||
if sender.send(Ok(Bytes::from(failure))).await.is_err() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
if !sse_body_has_done(&body_text) {
|
||||
body_text.push_str(DONE_SSE_FRAME);
|
||||
body_bytes.extend_from_slice(DONE_SSE_FRAME.as_bytes());
|
||||
if sender
|
||||
.send(Ok(Bytes::from_static(DONE_SSE_FRAME.as_bytes())))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
Some(body_text)
|
||||
}
|
||||
|
||||
fn sse_body_has_terminal_event(body: &str) -> bool {
|
||||
parse_sse_events(body).is_ok_and(|events| events.iter().any(response_sse_event_is_terminal))
|
||||
}
|
||||
|
||||
fn missing_sse_event_separator(body: &str) -> Option<&'static str> {
|
||||
if body.is_empty()
|
||||
|| body.ends_with("\n\n")
|
||||
|| body.ends_with("\r\n\r\n")
|
||||
|| body.ends_with("\r\r")
|
||||
{
|
||||
None
|
||||
} else if body.ends_with('\n') || body.ends_with('\r') {
|
||||
Some("\n")
|
||||
let decoded_terminal = take_stream_terminal(&mut decoder);
|
||||
let terminal = if decoded_terminal.is_some() {
|
||||
stage_terminal_batch(&mut body_bytes, &mut terminal_chunks, initial_batch)
|
||||
.err()
|
||||
.or(decoded_terminal)
|
||||
} else {
|
||||
Some("\n\n")
|
||||
forward_batch(sender, event_sender, &mut body_bytes, initial_batch)
|
||||
.await
|
||||
.err()
|
||||
};
|
||||
update_first_token_ms(&decoder, started_at, &mut first_token_ms);
|
||||
if let Some(terminal) = terminal {
|
||||
return stream_summary(
|
||||
terminal,
|
||||
body_bytes,
|
||||
terminal_chunks,
|
||||
first_token_ms,
|
||||
first_event_ms,
|
||||
&decoder,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) struct LiveResponseStreamContext {
|
||||
pub(in crate::dispatch) account_pool: Arc<AccountPoolService>,
|
||||
pub(in crate::dispatch) account_lease: AccountLease,
|
||||
pub(in crate::dispatch) session_affinity: Arc<SessionAffinityService>,
|
||||
pub(in crate::dispatch) history: HistoryRecoveryPlan,
|
||||
pub(in crate::dispatch) recorder: Arc<Recorder>,
|
||||
pub(in crate::dispatch) cloudflare: CloudflareRecovery,
|
||||
pub(in crate::dispatch) account_id: String,
|
||||
pub(in crate::dispatch) account_plan_type: Option<String>,
|
||||
pub(in crate::dispatch) request_id: String,
|
||||
pub(in crate::dispatch) route: String,
|
||||
pub(in crate::dispatch) display_model: String,
|
||||
pub(in crate::dispatch) requested_model: String,
|
||||
pub(in crate::dispatch) client_ip: Option<String>,
|
||||
pub(in crate::dispatch) request: CodexResponsesRequest,
|
||||
pub(in crate::dispatch) tuple_schema: Option<Value>,
|
||||
pub(in crate::dispatch) transport: CodexBackendTransport,
|
||||
pub(in crate::dispatch) rate_limit_headers: Vec<(String, String)>,
|
||||
pub(in crate::dispatch) rate_limit_header_updates: Option<CodexRateLimitHeaderUpdates>,
|
||||
pub(in crate::dispatch) turn_state_update: Option<CodexTurnStateUpdate>,
|
||||
pub(in crate::dispatch) websocket_pool_decision: Option<WebSocketPoolDecision>,
|
||||
pub(in crate::dispatch) turn_state: Option<String>,
|
||||
pub(in crate::dispatch) diagnostics: CodexUpstreamDiagnostics,
|
||||
pub(in crate::dispatch) response_metadata: CodexResponseMetadata,
|
||||
pub(in crate::dispatch) attempt: ResponseDispatchAttempt,
|
||||
pub(in crate::dispatch) attempts: Vec<ResponseDispatchAttempt>,
|
||||
pub(in crate::dispatch) started_at: Instant,
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn latest_response_id(body: &str) -> Option<String> {
|
||||
parse_sse_events(body).ok().and_then(|events| {
|
||||
events.iter().rev().find_map(|event| {
|
||||
serde_json::from_str::<Value>(&event.data)
|
||||
.ok()
|
||||
.and_then(|data| {
|
||||
data.pointer("/response/id")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|id| !id.trim().is_empty())
|
||||
.map(ToString::to_string)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn premature_close_failed_event(
|
||||
response_id: Option<&str>,
|
||||
detail: Option<&str>,
|
||||
) -> String {
|
||||
let message = match detail.filter(|value| !value.trim().is_empty()) {
|
||||
Some(detail) => format!("{STREAM_DISCONNECTED_MESSAGE}: {detail}"),
|
||||
None => STREAM_DISCONNECTED_MESSAGE.to_string(),
|
||||
};
|
||||
response_failed_sse_event_with_id(
|
||||
response_id,
|
||||
"server_error",
|
||||
STREAM_DISCONNECTED_CODE,
|
||||
&message,
|
||||
)
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn finalize_live_response_stream(
|
||||
context: LiveResponseStreamContext,
|
||||
body: String,
|
||||
first_token_ms: Option<i64>,
|
||||
) {
|
||||
let rate_limit_headers = live_response_rate_limit_headers(&context).await;
|
||||
context
|
||||
.account_pool
|
||||
.sync_passive_rate_limit_headers_for_account(
|
||||
&context.account_id,
|
||||
context.account_plan_type.as_deref(),
|
||||
&rate_limit_headers,
|
||||
)
|
||||
.await;
|
||||
let turn_state = live_response_turn_state(&context).await;
|
||||
let usage = match extract_sse_usage(&body) {
|
||||
Ok(Some(usage)) => {
|
||||
context
|
||||
.account_pool
|
||||
.record_token_usage(&context.account_id, &usage)
|
||||
let mut shutdown = Box::pin(shutdown.cancelled_owned());
|
||||
let terminal = loop {
|
||||
let next = tokio::select! {
|
||||
_ = &mut cancel => break StreamTerminal::Cancelled,
|
||||
() = &mut shutdown => break StreamTerminal::Shutdown,
|
||||
next = body.next() => next,
|
||||
};
|
||||
match next {
|
||||
Some(Ok(chunk)) => match decoder.push(chunk) {
|
||||
Ok(batch) => {
|
||||
update_first_token_ms(&decoder, started_at, &mut first_token_ms);
|
||||
if let Some(terminal) = take_stream_terminal(&mut decoder) {
|
||||
match stage_terminal_batch(&mut body_bytes, &mut terminal_chunks, batch) {
|
||||
Ok(()) => break terminal,
|
||||
Err(terminal) => break terminal,
|
||||
}
|
||||
}
|
||||
if let Err(terminal) =
|
||||
forward_batch(sender, event_sender, &mut body_bytes, batch).await
|
||||
{
|
||||
break terminal;
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
break StreamTerminal::ProtocolError {
|
||||
detail: error.to_string(),
|
||||
};
|
||||
}
|
||||
},
|
||||
Some(Err(error)) => {
|
||||
break finish_decoder(
|
||||
sender,
|
||||
event_sender,
|
||||
&mut body_bytes,
|
||||
&mut terminal_chunks,
|
||||
&mut decoder,
|
||||
StreamTerminal::UpstreamError {
|
||||
detail: error.to_string(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
Some(usage)
|
||||
}
|
||||
Ok(None) => None,
|
||||
Err(error) => {
|
||||
tracing::warn!(account_id = %context.account_id, error = %error, "failed to extract streaming token usage");
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
let collected_response = response_from_codex_sse(&body, context.tuple_schema.as_ref());
|
||||
let completed_terminal = matches!(&collected_response, Ok(CollectedResponse::Completed(_)));
|
||||
match collected_response {
|
||||
Ok(CollectedResponse::Completed(terminal) | CollectedResponse::Incomplete(terminal)) => {
|
||||
context
|
||||
.cloudflare
|
||||
.reset_account_recovery(&context.account_id)
|
||||
.await;
|
||||
let response_id = terminal.get("id").and_then(Value::as_str);
|
||||
if completed_terminal {
|
||||
record_response_affinity(
|
||||
&context.session_affinity,
|
||||
&context.history,
|
||||
&context.request,
|
||||
&context.account_id,
|
||||
&body,
|
||||
turn_state,
|
||||
usage,
|
||||
}
|
||||
None => {
|
||||
break finish_decoder(
|
||||
sender,
|
||||
event_sender,
|
||||
&mut body_bytes,
|
||||
&mut terminal_chunks,
|
||||
&mut decoder,
|
||||
StreamTerminal::UpstreamClosed,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
record_live_response_stream_event(
|
||||
&context,
|
||||
200,
|
||||
UsageRecordLevel::Info,
|
||||
if completed_terminal {
|
||||
"v1 responses stream completed"
|
||||
} else {
|
||||
"v1 responses stream incomplete"
|
||||
},
|
||||
serde_json::json!({
|
||||
"stream": true,
|
||||
"completed": completed_terminal,
|
||||
"incomplete": !completed_terminal,
|
||||
"responseId": response_id,
|
||||
"firstTokenMs": first_token_ms,
|
||||
"usage": usage,
|
||||
}),
|
||||
&rate_limit_headers,
|
||||
&body,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Ok(CollectedResponse::Failed(failure)) => {
|
||||
let response_id = latest_response_id(&body);
|
||||
let latency_ms = elapsed_millis_i64(context.started_at);
|
||||
let failure_source = stream_failure_source(&failure);
|
||||
let failure_detail = synthetic_stream_disconnected_detail(&failure);
|
||||
let websocket_pool_kind = context
|
||||
.websocket_pool_decision
|
||||
.map(|decision| decision.kind());
|
||||
let websocket_pool_reason = context
|
||||
.websocket_pool_decision
|
||||
.and_then(|decision| decision.reason());
|
||||
tracing::warn!(
|
||||
account_id = %context.account_id,
|
||||
request_id = %context.request_id,
|
||||
response_id = response_id.as_deref().unwrap_or(""),
|
||||
transport = %backend_transport_name(context.transport),
|
||||
websocket_pool_kind = ?websocket_pool_kind,
|
||||
websocket_pool_reason = ?websocket_pool_reason,
|
||||
first_token_ms = ?first_token_ms,
|
||||
latency_ms,
|
||||
event = %failure.event,
|
||||
code = ?failure.upstream_code.as_deref(),
|
||||
failure_source = %failure_source,
|
||||
failure_detail = ?failure_detail.as_deref(),
|
||||
"live upstream stream ended with response.failed"
|
||||
);
|
||||
let mut metadata = stream_failure_metadata(&failure, usage);
|
||||
insert_first_token_ms(&mut metadata, first_token_ms);
|
||||
record_live_response_stream_event(
|
||||
&context,
|
||||
status_code_for_stream_failure(&failure),
|
||||
UsageRecordLevel::Error,
|
||||
"v1 responses stream failed",
|
||||
metadata,
|
||||
&rate_limit_headers,
|
||||
&body,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Ok(CollectedResponse::MissingCompleted | CollectedResponse::Empty) => {
|
||||
tracing::warn!(
|
||||
account_id = %context.account_id,
|
||||
"live upstream stream ended without response.completed"
|
||||
);
|
||||
let mut metadata = serde_json::json!({
|
||||
"stream": true,
|
||||
"failed": true,
|
||||
"upstreamCode": "missing_completed",
|
||||
"usage": usage,
|
||||
});
|
||||
insert_first_token_ms(&mut metadata, first_token_ms);
|
||||
record_live_response_stream_event(
|
||||
&context,
|
||||
502,
|
||||
UsageRecordLevel::Error,
|
||||
"v1 responses stream ended without response.completed",
|
||||
metadata,
|
||||
&rate_limit_headers,
|
||||
&body,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
};
|
||||
|
||||
update_first_token_ms(&decoder, started_at, &mut first_token_ms);
|
||||
stream_summary(
|
||||
terminal,
|
||||
body_bytes,
|
||||
terminal_chunks,
|
||||
first_token_ms,
|
||||
first_event_ms,
|
||||
&decoder,
|
||||
)
|
||||
}
|
||||
|
||||
async fn finish_decoder(
|
||||
sender: &mpsc::Sender<Result<Bytes, ResponseDispatchStreamError>>,
|
||||
event_sender: &mpsc::UnboundedSender<Vec<CanonicalResponseEvent>>,
|
||||
body_bytes: &mut Vec<u8>,
|
||||
terminal_chunks: &mut Vec<CanonicalResponseChunk>,
|
||||
decoder: &mut CanonicalStreamDecoder,
|
||||
fallback: StreamTerminal,
|
||||
) -> StreamTerminal {
|
||||
let batch = match decoder.finish() {
|
||||
Ok(batch) => batch,
|
||||
Err(error) => {
|
||||
tracing::warn!(account_id = %context.account_id, error = %error, "failed to parse completed live stream");
|
||||
let mut metadata = serde_json::json!({
|
||||
"stream": true,
|
||||
"sseParseError": error.to_string(),
|
||||
"usage": usage,
|
||||
});
|
||||
insert_first_token_ms(&mut metadata, first_token_ms);
|
||||
record_live_response_stream_event(
|
||||
&context,
|
||||
502,
|
||||
UsageRecordLevel::Warn,
|
||||
"v1 responses stream SSE response invalid",
|
||||
metadata,
|
||||
&rate_limit_headers,
|
||||
&body,
|
||||
)
|
||||
.await;
|
||||
return StreamTerminal::ProtocolError {
|
||||
detail: error.to_string(),
|
||||
};
|
||||
}
|
||||
};
|
||||
if let Some(terminal) = take_stream_terminal(decoder) {
|
||||
return match stage_terminal_batch(body_bytes, terminal_chunks, batch) {
|
||||
Ok(()) => terminal,
|
||||
Err(terminal) => terminal,
|
||||
};
|
||||
}
|
||||
if let Err(terminal) = forward_batch(sender, event_sender, body_bytes, batch).await {
|
||||
return terminal;
|
||||
}
|
||||
fallback
|
||||
}
|
||||
|
||||
fn take_stream_terminal(decoder: &mut CanonicalStreamDecoder) -> Option<StreamTerminal> {
|
||||
let terminal = decoder.take_terminal().map(StreamTerminal::from);
|
||||
let transport_done = decoder.take_transport_done();
|
||||
terminal.or_else(|| transport_done.then_some(StreamTerminal::UpstreamClosed))
|
||||
}
|
||||
|
||||
fn stage_terminal_batch(
|
||||
body_bytes: &mut Vec<u8>,
|
||||
terminal_chunks: &mut Vec<CanonicalResponseChunk>,
|
||||
batch: CanonicalStreamBatch,
|
||||
) -> Result<(), StreamTerminal> {
|
||||
let batch_bytes = batch.chunks.iter().fold(0usize, |total, chunk| {
|
||||
total.saturating_add(chunk.bytes().len())
|
||||
});
|
||||
ensure_capture_capacity(body_bytes.len(), batch_bytes)?;
|
||||
for chunk in batch.chunks {
|
||||
body_bytes.extend_from_slice(chunk.bytes());
|
||||
terminal_chunks.push(chunk);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn forward_batch(
|
||||
sender: &mpsc::Sender<Result<Bytes, ResponseDispatchStreamError>>,
|
||||
event_sender: &mpsc::UnboundedSender<Vec<CanonicalResponseEvent>>,
|
||||
body_bytes: &mut Vec<u8>,
|
||||
batch: CanonicalStreamBatch,
|
||||
) -> Result<(), StreamTerminal> {
|
||||
for chunk in batch.chunks {
|
||||
capture_chunk(body_bytes, &chunk)?;
|
||||
let (bytes, events) = chunk.into_parts();
|
||||
let _ = event_sender.send(events);
|
||||
if sender.send(Ok(bytes)).await.is_err() {
|
||||
return Err(StreamTerminal::DownstreamClosed);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
context.account_lease.complete().await;
|
||||
fn capture_chunk(
|
||||
body_bytes: &mut Vec<u8>,
|
||||
chunk: &CanonicalResponseChunk,
|
||||
) -> Result<(), StreamTerminal> {
|
||||
ensure_capture_capacity(body_bytes.len(), chunk.bytes().len())?;
|
||||
body_bytes.extend_from_slice(chunk.bytes());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_capture_capacity(
|
||||
captured_bytes: usize,
|
||||
incoming_bytes: usize,
|
||||
) -> Result<(), StreamTerminal> {
|
||||
if captured_bytes.saturating_add(incoming_bytes) > MAX_LIVE_RESPONSE_CAPTURE_BYTES {
|
||||
tracing::warn!(
|
||||
captured_bytes,
|
||||
incoming_bytes,
|
||||
capture_limit_bytes = MAX_LIVE_RESPONSE_CAPTURE_BYTES,
|
||||
"Live response capture limit exceeded"
|
||||
);
|
||||
return Err(StreamTerminal::CaptureLimitExceeded);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn update_first_token_ms(
|
||||
decoder: &CanonicalStreamDecoder,
|
||||
started_at: Instant,
|
||||
first_token_ms: &mut Option<i64>,
|
||||
) {
|
||||
if first_token_ms.is_none() && decoder.first_output_seen() {
|
||||
*first_token_ms = Some(elapsed_millis_i64(started_at).max(1));
|
||||
}
|
||||
}
|
||||
|
||||
fn stream_summary(
|
||||
terminal: StreamTerminal,
|
||||
body: Vec<u8>,
|
||||
terminal_chunks: Vec<CanonicalResponseChunk>,
|
||||
first_token_ms: Option<i64>,
|
||||
first_event_ms: i64,
|
||||
decoder: &CanonicalStreamDecoder,
|
||||
) -> StreamSummary {
|
||||
StreamSummary {
|
||||
terminal,
|
||||
body,
|
||||
terminal_chunks,
|
||||
first_token_ms,
|
||||
first_event_ms,
|
||||
usage: decoder.usage(),
|
||||
last_response_id: decoder.last_response_id().map(ToString::to_string),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,3 @@
|
||||
|
||||
pub(crate) mod lifecycle;
|
||||
pub(crate) mod live;
|
||||
pub(crate) mod prefetch;
|
||||
pub(crate) mod sse_failure;
|
||||
pub(crate) mod trace;
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
use bytes::Bytes;
|
||||
use futures::StreamExt;
|
||||
|
||||
use crate::upstream::openai::{
|
||||
protocol::sse::{sse_frame_end, SseError},
|
||||
transport::CodexBackendSseStream,
|
||||
};
|
||||
|
||||
use crate::dispatch::errors::ResponseDispatchError;
|
||||
|
||||
const MAX_STREAM_PREFETCH_BYTES: usize = 64 * 1024;
|
||||
|
||||
pub(in crate::dispatch) async fn prefetch_first_sse_chunk(
|
||||
mut body: CodexBackendSseStream,
|
||||
) -> Result<(Bytes, CodexBackendSseStream), ResponseDispatchError> {
|
||||
let mut prefetched = Vec::new();
|
||||
while sse_frame_end(&prefetched).is_none() {
|
||||
let Some(next) = body.next().await else {
|
||||
if prefetched.is_empty() {
|
||||
return Err(ResponseDispatchError::EmptyUpstreamResponse);
|
||||
}
|
||||
return Err(ResponseDispatchError::MissingCompleted);
|
||||
};
|
||||
let chunk = next.map_err(ResponseDispatchError::Upstream)?;
|
||||
prefetched.extend_from_slice(&chunk);
|
||||
if prefetched.len() > MAX_STREAM_PREFETCH_BYTES {
|
||||
return Err(ResponseDispatchError::InvalidSse(
|
||||
SseError::BufferExceeded {
|
||||
max_bytes: MAX_STREAM_PREFETCH_BYTES,
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok((Bytes::from(prefetched), body))
|
||||
}
|
||||
@@ -1,221 +0,0 @@
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
dispatch::errors::{is_history_recovery_code, is_model_unsupported_signal},
|
||||
fleet::account::AccountStatus,
|
||||
upstream::openai::{
|
||||
protocol::{
|
||||
events::TokenUsage,
|
||||
responses::{response_from_codex_sse, CollectedResponse, ResponsesSseFailure},
|
||||
sse::SseError,
|
||||
},
|
||||
transport::is_banned_auth_signal,
|
||||
},
|
||||
};
|
||||
|
||||
pub(in crate::dispatch) const STREAM_DISCONNECTED_CODE: &str = "stream_disconnected";
|
||||
pub(in crate::dispatch) const STREAM_DISCONNECTED_MESSAGE: &str =
|
||||
"Upstream stream closed before response.completed";
|
||||
|
||||
pub(in crate::dispatch) fn sse_failure_error_body(failure: &ResponsesSseFailure) -> String {
|
||||
match failure.upstream_code.as_deref() {
|
||||
Some(code) => serde_json::json!({
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": failure.message.as_str(),
|
||||
}
|
||||
})
|
||||
.to_string(),
|
||||
None => failure.message.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn sse_failure_matches<F>(failure: &ResponsesSseFailure, signal: F) -> bool
|
||||
where
|
||||
F: Fn(&str) -> bool,
|
||||
{
|
||||
failure.upstream_code.as_deref().is_some_and(&signal) || signal(&failure.message)
|
||||
}
|
||||
|
||||
fn sse_failure_matches_parts<C, M>(
|
||||
failure: &ResponsesSseFailure,
|
||||
code_signal: C,
|
||||
message_signal: M,
|
||||
) -> bool
|
||||
where
|
||||
C: Fn(&str) -> bool,
|
||||
M: Fn(&str) -> bool,
|
||||
{
|
||||
failure.upstream_code.as_deref().is_some_and(code_signal) || message_signal(&failure.message)
|
||||
}
|
||||
|
||||
pub(crate) fn is_quota_exhausted_sse_failure(failure: &ResponsesSseFailure) -> bool {
|
||||
sse_failure_matches_parts(
|
||||
failure,
|
||||
|code| matches!(code, "quota_exceeded" | "insufficient_quota"),
|
||||
|message| message.to_ascii_lowercase().contains("quota"),
|
||||
)
|
||||
}
|
||||
|
||||
fn is_auth_sse_failure_code(code: &str) -> bool {
|
||||
let code = code.to_ascii_lowercase();
|
||||
matches!(
|
||||
code.as_str(),
|
||||
"token_invalid"
|
||||
| "token_expired"
|
||||
| "token_revoked"
|
||||
| "account_deactivated"
|
||||
| "unauthorized"
|
||||
| "invalid_api_key"
|
||||
)
|
||||
}
|
||||
|
||||
fn is_auth_sse_failure_message(message: &str) -> bool {
|
||||
let message = message.to_ascii_lowercase();
|
||||
message.contains("token revoked")
|
||||
|| message.contains("token invalid")
|
||||
|| message.contains("token expired")
|
||||
}
|
||||
|
||||
pub(crate) fn is_auth_sse_failure(failure: &ResponsesSseFailure) -> bool {
|
||||
sse_failure_matches_parts(
|
||||
failure,
|
||||
is_auth_sse_failure_code,
|
||||
is_auth_sse_failure_message,
|
||||
)
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn is_model_unsupported_sse_failure(failure: &ResponsesSseFailure) -> bool {
|
||||
sse_failure_matches(failure, is_model_unsupported_signal)
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn is_history_recovery_sse_failure(failure: &ResponsesSseFailure) -> bool {
|
||||
failure
|
||||
.upstream_code
|
||||
.as_deref()
|
||||
.is_some_and(is_history_recovery_code)
|
||||
}
|
||||
|
||||
pub(crate) fn auth_sse_failure_account_status(failure: &ResponsesSseFailure) -> AccountStatus {
|
||||
if sse_failure_matches(failure, is_banned_auth_signal) {
|
||||
AccountStatus::Banned
|
||||
} else {
|
||||
AccountStatus::Expired
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn first_sse_failure(
|
||||
prefetched: &[u8],
|
||||
) -> Result<Option<ResponsesSseFailure>, SseError> {
|
||||
let body = String::from_utf8_lossy(prefetched);
|
||||
match response_from_codex_sse(&body, None)? {
|
||||
CollectedResponse::Failed(failure) => Ok(Some(failure)),
|
||||
CollectedResponse::Completed(_)
|
||||
| CollectedResponse::Incomplete(_)
|
||||
| CollectedResponse::MissingCompleted
|
||||
| CollectedResponse::Empty => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn stream_failure_metadata(
|
||||
failure: &ResponsesSseFailure,
|
||||
usage: Option<TokenUsage>,
|
||||
) -> Value {
|
||||
let mut metadata = serde_json::json!({
|
||||
"stream": true,
|
||||
"failed": true,
|
||||
"failureEvent": failure.event,
|
||||
"failureMessage": failure.message,
|
||||
"upstreamCode": failure.upstream_code,
|
||||
"usage": usage,
|
||||
});
|
||||
enrich_stream_failure_source_metadata(&mut metadata, failure);
|
||||
metadata
|
||||
}
|
||||
|
||||
fn enrich_stream_failure_source_metadata(metadata: &mut Value, failure: &ResponsesSseFailure) {
|
||||
let Some(object) = metadata.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
object.insert(
|
||||
"failureSource".to_string(),
|
||||
Value::String(stream_failure_source(failure).to_string()),
|
||||
);
|
||||
if let Some(detail) = synthetic_stream_disconnected_detail(failure) {
|
||||
object.insert("synthetic".to_string(), Value::Bool(true));
|
||||
if !detail.is_empty() {
|
||||
object.insert("failureDetail".to_string(), Value::String(detail));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn stream_failure_source(failure: &ResponsesSseFailure) -> &'static str {
|
||||
if synthetic_stream_disconnected_detail(failure).is_some() {
|
||||
"proxy"
|
||||
} else {
|
||||
"upstream"
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn synthetic_stream_disconnected_detail(
|
||||
failure: &ResponsesSseFailure,
|
||||
) -> Option<String> {
|
||||
if failure.upstream_code.as_deref() != Some(STREAM_DISCONNECTED_CODE) {
|
||||
return None;
|
||||
}
|
||||
let detail = failure
|
||||
.message
|
||||
.strip_prefix(STREAM_DISCONNECTED_MESSAGE)?
|
||||
.strip_prefix(": ")
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_string();
|
||||
Some(detail)
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn status_code_for_stream_failure(failure: &ResponsesSseFailure) -> i64 {
|
||||
let code = failure
|
||||
.upstream_code
|
||||
.as_deref()
|
||||
.unwrap_or("error")
|
||||
.to_ascii_lowercase();
|
||||
if code.contains("model") && (code.contains("not_supported") || code.contains("not_available"))
|
||||
{
|
||||
return 400;
|
||||
}
|
||||
if code.contains("invalid_request") || code.contains("not_found") {
|
||||
return 400;
|
||||
}
|
||||
if code.contains("context_window")
|
||||
|| code.contains("invalid_prompt")
|
||||
|| code.contains("cyber_policy")
|
||||
|| code.contains("bad_request")
|
||||
{
|
||||
return 400;
|
||||
}
|
||||
if code.contains("rate_limit") || code.contains("usage_limit") {
|
||||
return 429;
|
||||
}
|
||||
if code.contains("unauthorized")
|
||||
|| code.contains("invalid_api_key")
|
||||
|| code == "token_invalid"
|
||||
|| code == "token_expired"
|
||||
|| code == "account_deactivated"
|
||||
{
|
||||
return 401;
|
||||
}
|
||||
if code.contains("forbidden") || code.contains("banned") {
|
||||
return 403;
|
||||
}
|
||||
if code.contains("payment") || code.contains("quota") {
|
||||
return 429;
|
||||
}
|
||||
if code.contains("server_overloaded") {
|
||||
return 503;
|
||||
}
|
||||
502
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn stream_failure_http_status(failure: &ResponsesSseFailure) -> u16 {
|
||||
u16::try_from(status_code_for_stream_failure(failure)).unwrap_or(502)
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! 调度层共享的账号级 Codex 上游调用。
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::{
|
||||
dispatch::affinity::AccountScopedRequest,
|
||||
fleet::account::Account,
|
||||
upstream::openai::transport::{
|
||||
CodexBackendClient, CodexBackendResponse, CodexBackendStreamingResponse, CodexClientError,
|
||||
CodexRequestContext, PreparedResponseTransport,
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::dispatch) struct AccountUpstreamContext<'a> {
|
||||
pub codex: &'a CodexBackendClient,
|
||||
pub request_id: &'a str,
|
||||
pub account: &'a Account,
|
||||
pub cookie_header: Option<&'a str>,
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn create_response_with_account(
|
||||
context: AccountUpstreamContext<'_>,
|
||||
request: &AccountScopedRequest,
|
||||
prepared: PreparedResponseTransport,
|
||||
started_at: Instant,
|
||||
) -> Result<CodexBackendResponse, CodexClientError> {
|
||||
context
|
||||
.codex
|
||||
.create_response_with_prepared(
|
||||
request.request(),
|
||||
codex_request_context(context, request),
|
||||
prepared,
|
||||
started_at,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn prepare_response_transport_with_account(
|
||||
context: AccountUpstreamContext<'_>,
|
||||
request: &AccountScopedRequest,
|
||||
) -> Result<PreparedResponseTransport, CodexClientError> {
|
||||
context
|
||||
.codex
|
||||
.prepare_response_transport_with_pool_account(
|
||||
request.request(),
|
||||
codex_request_context(context, request),
|
||||
Some(&context.account.id),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn create_response_stream_with_account(
|
||||
context: AccountUpstreamContext<'_>,
|
||||
request: &AccountScopedRequest,
|
||||
prepared: PreparedResponseTransport,
|
||||
) -> Result<CodexBackendStreamingResponse, CodexClientError> {
|
||||
context
|
||||
.codex
|
||||
.create_response_stream_with_prepared(
|
||||
request.request(),
|
||||
codex_request_context(context, request),
|
||||
prepared,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn codex_request_context<'a>(
|
||||
context: AccountUpstreamContext<'a>,
|
||||
request: &'a AccountScopedRequest,
|
||||
) -> CodexRequestContext<'a> {
|
||||
let request_body = request.request();
|
||||
let identity = request.identity();
|
||||
CodexRequestContext {
|
||||
access_token: &context.account.access_token,
|
||||
account_id: context.account.account_id.as_deref(),
|
||||
request_id: context.request_id,
|
||||
turn_state: request_body.turn_state.as_deref(),
|
||||
turn_metadata: request_body.turn_metadata.as_deref(),
|
||||
beta_features: request_body.beta_features.as_deref(),
|
||||
include_timing_metrics: request_body.include_timing_metrics.as_deref(),
|
||||
version: request_body.version.as_deref(),
|
||||
codex_window_id: request_body.codex_window_id.as_deref(),
|
||||
parent_thread_id: request_body.parent_thread_id.as_deref(),
|
||||
cookie_header: context.cookie_header,
|
||||
installation_id: Some(&identity.installation_id),
|
||||
session_id: request_body.client_session_id.as_deref(),
|
||||
thread_id: request_body.client_thread_id.as_deref(),
|
||||
client_request_id: request_body.client_request_id.as_deref(),
|
||||
turn_id: request_body.client_turn_id.as_deref(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
//! Responses SSE 原始帧到规范事件的唯一解码入口。
|
||||
|
||||
use bytes::Bytes;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::upstream::openai::protocol::{
|
||||
events::{TokenUsage, extract_usage},
|
||||
responses::{
|
||||
CollectedResponse, ResponsesSseFailure, StreamCommitPolicy,
|
||||
reconvert_responses_sse_event_tuple_values,
|
||||
},
|
||||
sse::{
|
||||
MAX_SSE_EVENT_BUFFER_BYTES, SseError, encode_sse_event, parse_sse_events, sse_frame_end,
|
||||
sse_frame_is_done,
|
||||
},
|
||||
};
|
||||
|
||||
/// 将 complete transport 的原始 SSE 归一化为类型化终态事实。
|
||||
pub(in crate::dispatch) fn normalize_complete_response(
|
||||
body: &str,
|
||||
tuple_schema: Option<&Value>,
|
||||
) -> Result<CollectedResponse, SseError> {
|
||||
let events = parse_sse_events(body)?;
|
||||
let mut output_text = String::new();
|
||||
let mut output_items = Vec::new();
|
||||
let mut terminal_response = None;
|
||||
let mut terminal_incomplete = false;
|
||||
let mut failed_response = None;
|
||||
|
||||
for event in events {
|
||||
let Ok(mut value) = serde_json::from_str::<Value>(&event.data) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(tuple_schema) = tuple_schema {
|
||||
value = reconvert_responses_sse_event_tuple_values(
|
||||
event.event.as_deref(),
|
||||
value,
|
||||
tuple_schema,
|
||||
);
|
||||
}
|
||||
match event.event.as_deref() {
|
||||
Some("response.output_text.delta") => {
|
||||
if let Some(delta) = value.get("delta").and_then(Value::as_str) {
|
||||
output_text.push_str(delta);
|
||||
}
|
||||
}
|
||||
Some("response.output_item.done") => {
|
||||
if let Some(item) = value.get("item") {
|
||||
output_items.push(item.clone());
|
||||
}
|
||||
}
|
||||
Some("response.completed") => {
|
||||
terminal_response = value.get("response").cloned();
|
||||
terminal_incomplete = false;
|
||||
}
|
||||
Some("response.incomplete") => {
|
||||
terminal_response = value.get("response").cloned();
|
||||
terminal_incomplete = true;
|
||||
}
|
||||
Some(event_name @ ("error" | "response.failed")) if failed_response.is_none() => {
|
||||
failed_response = Some(ResponsesSseFailure::from_event(event_name, &value));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(failure) = failed_response {
|
||||
return Ok(CollectedResponse::Failed(failure));
|
||||
}
|
||||
let Some(response) = terminal_response else {
|
||||
return Ok(CollectedResponse::MissingCompleted);
|
||||
};
|
||||
if terminal_incomplete {
|
||||
return Ok(CollectedResponse::Incomplete(response));
|
||||
}
|
||||
if complete_response_is_empty(&response, &output_text, &output_items) {
|
||||
return Ok(CollectedResponse::Empty);
|
||||
}
|
||||
Ok(CollectedResponse::Completed(response))
|
||||
}
|
||||
|
||||
fn complete_response_is_empty(response: &Value, output_text: &str, output_items: &[Value]) -> bool {
|
||||
if !output_text.trim().is_empty() || !output_items.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if response.get("status").and_then(Value::as_str) == Some("incomplete") {
|
||||
return false;
|
||||
}
|
||||
response
|
||||
.pointer("/usage/output_tokens")
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or_default()
|
||||
== 0
|
||||
}
|
||||
|
||||
/// 一次解码后可同时供 HTTP SSE、Responses WebSocket 与生命周期控制器消费的事件。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct CanonicalResponseEvent {
|
||||
event_type: Option<String>,
|
||||
data: Value,
|
||||
}
|
||||
|
||||
impl CanonicalResponseEvent {
|
||||
pub(crate) fn event_type(&self) -> Option<&str> {
|
||||
self.event_type.as_deref()
|
||||
}
|
||||
|
||||
pub(crate) fn data(&self) -> &Value {
|
||||
&self.data
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn response_id(&self) -> Option<&str> {
|
||||
self.data
|
||||
.pointer("/response/id")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn usage(&self) -> Option<TokenUsage> {
|
||||
self.data
|
||||
.get("response")
|
||||
.and_then(extract_usage)
|
||||
.or_else(|| extract_usage(&self.data))
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn has_first_output(&self) -> bool {
|
||||
match self.event_type() {
|
||||
Some(
|
||||
"response.output_text.delta"
|
||||
| "response.reasoning_summary_text.delta"
|
||||
| "response.reasoning_text.delta"
|
||||
| "response.function_call_arguments.delta"
|
||||
| "response.custom_tool_call_input.delta",
|
||||
) => self
|
||||
.data
|
||||
.get("delta")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|value| !value.is_empty()),
|
||||
Some("response.output_text.done") => self
|
||||
.data
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|value| !value.is_empty()),
|
||||
Some("response.function_call_arguments.done") => self
|
||||
.data
|
||||
.get("arguments")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|value| !value.is_empty()),
|
||||
Some("response.output_item.done") => {
|
||||
self.data.get("item").is_some_and(Value::is_object)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn terminal(&self) -> Option<CanonicalStreamTerminal> {
|
||||
match self.event_type() {
|
||||
Some("response.completed") => self
|
||||
.data
|
||||
.get("response")
|
||||
.filter(|response| response.is_object())
|
||||
.cloned()
|
||||
.map(CanonicalStreamTerminal::Completed),
|
||||
Some("response.incomplete") => self
|
||||
.data
|
||||
.get("response")
|
||||
.filter(|response| response.is_object())
|
||||
.cloned()
|
||||
.map(CanonicalStreamTerminal::Incomplete),
|
||||
Some(event @ ("response.failed" | "error")) => Some(CanonicalStreamTerminal::Failed(
|
||||
ResponsesSseFailure::from_event(event, &self.data),
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn proxy_failure(data: Value) -> Self {
|
||||
Self {
|
||||
event_type: Some("response.failed".to_string()),
|
||||
data,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 上游明确发出的业务终态。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(in crate::dispatch) enum CanonicalStreamTerminal {
|
||||
Completed(Value),
|
||||
Incomplete(Value),
|
||||
Failed(ResponsesSseFailure),
|
||||
}
|
||||
|
||||
/// 已解码事件与对应下游字节的单个 fanout 单元。
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct CanonicalResponseChunk {
|
||||
bytes: Bytes,
|
||||
events: Vec<CanonicalResponseEvent>,
|
||||
}
|
||||
|
||||
impl CanonicalResponseChunk {
|
||||
pub(in crate::dispatch) fn new(bytes: Bytes, events: Vec<CanonicalResponseEvent>) -> Self {
|
||||
Self { bytes, events }
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn bytes(&self) -> &Bytes {
|
||||
&self.bytes
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn into_parts(self) -> (Bytes, Vec<CanonicalResponseEvent>) {
|
||||
(self.bytes, self.events)
|
||||
}
|
||||
|
||||
pub(crate) fn events(&self) -> &[CanonicalResponseEvent] {
|
||||
&self.events
|
||||
}
|
||||
}
|
||||
|
||||
/// 单次输入产生的所有下游 fanout 单元。
|
||||
#[derive(Debug)]
|
||||
pub(in crate::dispatch) struct CanonicalStreamBatch {
|
||||
pub chunks: Vec<CanonicalResponseChunk>,
|
||||
}
|
||||
|
||||
impl CanonicalStreamBatch {
|
||||
pub(in crate::dispatch) fn append(&mut self, mut other: Self) {
|
||||
self.chunks.append(&mut other.chunks);
|
||||
}
|
||||
|
||||
/// 只把真实输出前出现的失败视为可在 attempt 阶段处理的失败。
|
||||
/// 同一上游 chunk 可能同时包含输出与终态,事件顺序不能被网络分块抹掉。
|
||||
pub(in crate::dispatch) fn first_failure(&self) -> Option<ResponsesSseFailure> {
|
||||
for event in self.chunks.iter().flat_map(|chunk| chunk.events()) {
|
||||
if event.has_first_output() {
|
||||
return None;
|
||||
}
|
||||
if let Some(terminal) = event.terminal() {
|
||||
return match terminal {
|
||||
CanonicalStreamTerminal::Failed(failure) => Some(failure),
|
||||
CanonicalStreamTerminal::Completed(_)
|
||||
| CanonicalStreamTerminal::Incomplete(_) => None,
|
||||
};
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// 原始 SSE 在整个 attempt/live 生命周期中唯一持有的增量 decoder。
|
||||
pub(in crate::dispatch) struct CanonicalStreamDecoder {
|
||||
tuple_schema: Option<Value>,
|
||||
pending: Vec<u8>,
|
||||
forwardable_frame_seen: bool,
|
||||
first_output_seen: bool,
|
||||
terminal: Option<CanonicalStreamTerminal>,
|
||||
transport_done_seen: bool,
|
||||
completed_usage: Option<TokenUsage>,
|
||||
fallback_usage: Option<TokenUsage>,
|
||||
last_response_id: Option<String>,
|
||||
}
|
||||
|
||||
impl CanonicalStreamDecoder {
|
||||
pub(in crate::dispatch) fn new(tuple_schema: Option<Value>) -> Self {
|
||||
Self {
|
||||
tuple_schema,
|
||||
pending: Vec::new(),
|
||||
forwardable_frame_seen: false,
|
||||
first_output_seen: false,
|
||||
terminal: None,
|
||||
transport_done_seen: false,
|
||||
completed_usage: None,
|
||||
fallback_usage: None,
|
||||
last_response_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn push(
|
||||
&mut self,
|
||||
chunk: Bytes,
|
||||
) -> Result<CanonicalStreamBatch, SseError> {
|
||||
self.pending.extend_from_slice(&chunk);
|
||||
let mut transformed_chunks = Vec::new();
|
||||
let mut consumed = 0usize;
|
||||
|
||||
while let Some(frame_len) = sse_frame_end(&self.pending[consumed..]) {
|
||||
let end = consumed.saturating_add(frame_len);
|
||||
let frame = self.pending[consumed..end].to_vec();
|
||||
if let Some((transformed, events)) = self.normalize_frame(&frame)? {
|
||||
transformed_chunks.push(CanonicalResponseChunk::new(transformed, events));
|
||||
}
|
||||
consumed = end;
|
||||
if self.terminal.is_some() || self.transport_done_seen {
|
||||
consumed = self.pending.len();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if consumed != 0 {
|
||||
self.pending.drain(..consumed);
|
||||
}
|
||||
if self.pending.len() > MAX_SSE_EVENT_BUFFER_BYTES {
|
||||
return Err(SseError::BufferExceeded {
|
||||
max_bytes: MAX_SSE_EVENT_BUFFER_BYTES,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(CanonicalStreamBatch {
|
||||
chunks: transformed_chunks,
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn finish(&mut self) -> Result<CanonicalStreamBatch, SseError> {
|
||||
if self.pending.is_empty() {
|
||||
return Ok(CanonicalStreamBatch { chunks: Vec::new() });
|
||||
}
|
||||
let frame = std::mem::take(&mut self.pending);
|
||||
let Some((transformed, events)) = self.normalize_frame(&frame)? else {
|
||||
return Ok(CanonicalStreamBatch { chunks: Vec::new() });
|
||||
};
|
||||
Ok(CanonicalStreamBatch {
|
||||
chunks: vec![CanonicalResponseChunk::new(transformed, events)],
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn take_terminal(&mut self) -> Option<CanonicalStreamTerminal> {
|
||||
self.terminal.take()
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn take_transport_done(&mut self) -> bool {
|
||||
std::mem::take(&mut self.transport_done_seen)
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn transport_done_seen(&self) -> bool {
|
||||
self.transport_done_seen
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn first_output_seen(&self) -> bool {
|
||||
self.first_output_seen
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn commit_boundary_reached(&self, policy: StreamCommitPolicy) -> bool {
|
||||
match policy {
|
||||
StreamCommitPolicy::FirstForwardableEvent => self.forwardable_frame_seen,
|
||||
StreamCommitPolicy::UntilOutputOrTerminal => {
|
||||
self.first_output_seen || self.terminal.is_some()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn usage(&self) -> Option<TokenUsage> {
|
||||
self.completed_usage.or(self.fallback_usage)
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) fn last_response_id(&self) -> Option<&str> {
|
||||
self.last_response_id.as_deref()
|
||||
}
|
||||
|
||||
fn normalize_frame(
|
||||
&mut self,
|
||||
frame: &[u8],
|
||||
) -> Result<Option<(Bytes, Vec<CanonicalResponseEvent>)>, SseError> {
|
||||
let frame_text =
|
||||
std::str::from_utf8(frame).map_err(|error| SseError::ParseError(error.to_string()))?;
|
||||
if sse_frame_is_done(frame_text) {
|
||||
self.transport_done_seen = true;
|
||||
return Ok(None);
|
||||
}
|
||||
let events = parse_sse_events(frame_text)?;
|
||||
let mut canonical_events = Vec::new();
|
||||
let mut transformed = String::new();
|
||||
|
||||
for event in events {
|
||||
let Ok(mut data) = serde_json::from_str::<Value>(&event.data) else {
|
||||
continue;
|
||||
};
|
||||
let event_type = event.event.or_else(|| {
|
||||
data.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToString::to_string)
|
||||
});
|
||||
if let Some(tuple_schema) = self.tuple_schema.as_ref() {
|
||||
data = reconvert_responses_sse_event_tuple_values(
|
||||
event_type.as_deref(),
|
||||
data,
|
||||
tuple_schema,
|
||||
);
|
||||
transformed.push_str(&encode_sse_event(
|
||||
event_type.as_deref().unwrap_or_default(),
|
||||
&data.to_string(),
|
||||
));
|
||||
}
|
||||
let canonical = CanonicalResponseEvent { event_type, data };
|
||||
self.observe(&canonical);
|
||||
canonical_events.push(canonical);
|
||||
}
|
||||
|
||||
self.forwardable_frame_seen = true;
|
||||
|
||||
Ok(Some((
|
||||
if self.tuple_schema.is_some() && !transformed.is_empty() {
|
||||
Bytes::from(transformed)
|
||||
} else {
|
||||
Bytes::copy_from_slice(frame)
|
||||
},
|
||||
canonical_events,
|
||||
)))
|
||||
}
|
||||
|
||||
fn observe(&mut self, event: &CanonicalResponseEvent) {
|
||||
self.first_output_seen |= event.has_first_output();
|
||||
if let Some(response_id) = event.response_id() {
|
||||
self.last_response_id = Some(response_id.to_string());
|
||||
}
|
||||
if let Some(usage) = event.usage() {
|
||||
if event.event_type() == Some("response.completed") {
|
||||
self.completed_usage = Some(usage);
|
||||
} else {
|
||||
self.fallback_usage = Some(usage);
|
||||
}
|
||||
}
|
||||
if self.terminal.is_none() {
|
||||
self.terminal = event.terminal();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
//! Attempt 阶段的账号作用域上游调用与事实规范化。
|
||||
|
||||
pub(in crate::dispatch) mod account;
|
||||
pub(crate) mod canonical;
|
||||
pub(in crate::dispatch) mod observation;
|
||||
pub(in crate::dispatch) mod prefetch;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user