mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-07 08:05:32 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bfd05722d5 | ||
|
|
9dc2ea4a2f | ||
|
|
6fb27e869e | ||
|
|
81c58b1cdc | ||
|
|
c8dc2e293a | ||
|
|
25081de913 | ||
|
|
6eb0917ff1 | ||
|
|
72d892d5e3 | ||
|
|
0b2da3087b | ||
|
|
5391fdb31c | ||
|
|
24036f1f84 | ||
|
|
b043fced0c | ||
|
|
40a2b70bf2 | ||
|
|
1e6ac77d3c | ||
|
|
3340934944 | ||
|
|
37a368de32 | ||
|
|
79cd8ac965 | ||
|
|
57c6b95596 | ||
|
|
a4f1843876 | ||
|
|
096e48621a | ||
|
|
36828b1a7e | ||
|
|
05ec1a4d38 | ||
|
|
9808e5939c | ||
|
|
a58911c127 | ||
|
|
0b9e080f1b | ||
|
|
f218e31c72 | ||
|
|
83f2f55e4a | ||
|
|
0384e39289 | ||
|
|
9036288d69 | ||
|
|
77b18eec68 | ||
|
|
3f7d473bea | ||
|
|
99cf39c76d | ||
|
|
f4d0576e6b | ||
|
|
2d9510d9e3 | ||
|
|
36d6e26291 | ||
|
|
eff522f2b6 | ||
|
|
65a175d48c | ||
|
|
f1872df293 | ||
|
|
71d87c5ab9 | ||
|
|
e23689ae22 |
@@ -34,6 +34,8 @@ updates:
|
||||
day: monday
|
||||
time: '09:20'
|
||||
timezone: Asia/Shanghai
|
||||
cooldown:
|
||||
default-days: 1
|
||||
groups:
|
||||
minor-and-patch:
|
||||
update-types:
|
||||
|
||||
@@ -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,25 +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
|
||||
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 "SHOW TimeZone;" | tr -d '\r')" = Asia/Shanghai
|
||||
"${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 \
|
||||
"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
|
||||
@@ -146,24 +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"
|
||||
@@ -195,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
|
||||
@@ -207,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|
|
||||
@@ -243,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"
|
||||
|
||||
@@ -93,7 +93,7 @@ jobs:
|
||||
version: 11.7.0
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
|
||||
@@ -3,8 +3,10 @@ name: CI
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- '**'
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -621,7 +621,7 @@ jobs:
|
||||
cosign sign --yes "${images[@]}"
|
||||
|
||||
- name: Publish GitHub Release
|
||||
uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3.0.1
|
||||
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3.0.2
|
||||
with:
|
||||
tag_name: ${{ needs.release-info.outputs.tag }}
|
||||
generate_release_notes: true
|
||||
|
||||
@@ -3,8 +3,10 @@ name: Security Scan
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- '**'
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
schedule:
|
||||
- cron: '0 3 * * 1'
|
||||
|
||||
@@ -55,7 +57,7 @@ jobs:
|
||||
version: 11.7.0
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
|
||||
+1
-7
@@ -19,13 +19,7 @@
|
||||
*.log
|
||||
|
||||
# Local configuration and secrets
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
!**/.env.example
|
||||
/.envrc
|
||||
/config.yaml
|
||||
/backend/config.yaml
|
||||
/deploy/config.yaml
|
||||
|
||||
# Editors and operating systems
|
||||
/.idea/
|
||||
|
||||
@@ -1,124 +1,110 @@
|
||||
<!-- prettier-ignore -->
|
||||
<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.97" src="https://img.shields.io/badge/Rust-1.97-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="80" height="80" />
|
||||
|
||||
# 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://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
|
||||
[](https://opensource.org/license/mit)
|
||||
|
||||
[快速开始](#快速开始) · [客户端接入](#客户端接入) · [运维](#运维) · [部署文档](deploy/README.md) · [架构](docs/architecture.md)
|
||||
|
||||
</div>
|
||||
|
||||
Codex Proxy RS 为多个 Codex 账号提供统一的 Responses API。客户端使用同一个服务地址和 API Key;账号调度、并发限制、额度检查、故障换号和会话续接都在服务端完成。
|
||||
> [!NOTE]
|
||||
> 只支持 OpenAI Responses API,不提供 `/v1/chat/completions`。
|
||||
|
||||
## 功能
|
||||
## 能力
|
||||
|
||||
- 兼容 `/v1/responses`、SSE、官方 Responses WebSocket 和模型查询。
|
||||
- 客户端与上游均可使用 HTTP/SSE 或 WebSocket。
|
||||
- 提供 `smart`、额度重置优先、轮询和粘性四种账号调度策略。
|
||||
- 单个账号发生额度、认证、模型或传输故障时,继续使用账号池中的其他可用账号。
|
||||
- 支持跨账号会话续接,并隔离不同账号的会话状态。
|
||||
- 提供账号、API Key、模型映射、运行参数、用量、错误记录和系统更新管理界面。
|
||||
- 使用 PostgreSQL 保存权威业务数据,使用 Redis 保存会话、租约、模型快照和会话亲和数据。
|
||||
- 内置日志轮转、遥测保留期清理和 PostgreSQL/Redis 健康检查。
|
||||
| 领域 | 实现 |
|
||||
| -------- | ------------------------------------------------ |
|
||||
| 协议 | Responses HTTP、SSE、官方 WebSocket |
|
||||
| 传输 | 会话级 WebSocket 池、共享 HTTP/2 后备 |
|
||||
| 调度 | 智能调度、额度优先、轮询、粘滞 |
|
||||
| 故障处理 | 额度、认证、封禁、模型与传输故障切换 |
|
||||
| 身份 | 账号身份隔离、稳定 installation ID、会话拓扑透传 |
|
||||
| 管理 | 账号、客户端 Key、模型别名、运行设置与在线更新 |
|
||||
| 遥测 | Token、费用、缓存、TTFT、延迟与错误 |
|
||||
|
||||
除账号调度和会话恢复外,请求与响应尽量保持原有语义。
|
||||
## 快速开始
|
||||
|
||||
## 快速部署
|
||||
需要 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
|
||||
|
||||
mkdir -p .runtime/data .runtime/logs
|
||||
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
|
||||
```
|
||||
|
||||
### 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
|
||||
openssl rand -hex 24
|
||||
```
|
||||
|
||||
编辑 `deploy/.env`:
|
||||
将结果写入 `deploy/config.yaml`:
|
||||
|
||||
```dotenv
|
||||
CPR_ADMIN_DEFAULT_PASSWORD='<管理员密码,至少 12 个字符>'
|
||||
CPR_POSTGRES_PASSWORD='<PostgreSQL 密码>'
|
||||
CPR_REDIS_PASSWORD='<Redis 密码>'
|
||||
```
|
||||
| 配置 | 约束 |
|
||||
| ------------------------------ | ------------------------ |
|
||||
| `x-cpr.database.password` | 48 位十六进制 |
|
||||
| `x-cpr.redis.password` | 48 位十六进制 |
|
||||
| `x-cpr.admin.default_password` | 至少 12 位,不能包含 `$` |
|
||||
|
||||
`deploy/.env` 已被 Git 忽略。应用会安全地把 PostgreSQL 和 Redis 密码写入运行时连接 URL,不需要把真实密码填入 `.runtime/config.yaml`。
|
||||
|
||||
Linux 宿主机需要保证容器用户 `10001:10001` 可以读写数据和日志目录:
|
||||
Linux 需要允许容器组写入运行目录:
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
### 3. 启动
|
||||
### 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
|
||||
```
|
||||
|
||||
检查服务:
|
||||
|
||||
```bash
|
||||
docker compose --env-file deploy/.env -f deploy/docker-compose.yml ps
|
||||
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
|
||||
curl -i http://127.0.0.1:8080/healthz
|
||||
```
|
||||
|
||||
`/healthz` 正常时返回 `204 No Content`。随后打开 <http://127.0.0.1:8080>:
|
||||
`204 No Content` 表示应用、PostgreSQL 与 Redis 均可用。管理端地址:
|
||||
`http://127.0.0.1:8080`。
|
||||
|
||||
- 用户名:`admin@cpr.local`
|
||||
- 密码:`deploy/.env` 中的 `CPR_ADMIN_DEFAULT_PASSWORD`
|
||||
### 3. 初始化
|
||||
|
||||
首次登录后导入账号,在“API 密钥”页面创建客户端 Key。
|
||||
1. 使用 `admin@cpr.local` 与初始密码登录。
|
||||
2. 添加 Codex 账号并执行连接测试。
|
||||
3. 创建 `sk_...` 客户端 Key。
|
||||
4. 复制 Codex CLI 配置,或导入 CCSwitch。
|
||||
|
||||
### 本地构建镜像
|
||||
> [!NOTE]
|
||||
> `admin.default_password` 只在首次创建管理员时生效。
|
||||
|
||||
需要验证当前源码时,不拉取 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
|
||||
```
|
||||
完整部署、权限和密码轮换规则见 [deploy/README.md](deploy/README.md)。
|
||||
|
||||
## 客户端接入
|
||||
|
||||
OpenAI 兼容客户端填写:
|
||||
|
||||
- Base URL:`http://127.0.0.1:8080/v1`
|
||||
- API Key:管理端创建的 `sk_...` 客户端 Key
|
||||
|
||||
Responses 请求示例:
|
||||
| 配置 | 值 |
|
||||
| -------- | ---------------------------------------- |
|
||||
| Base URL | `http://127.0.0.1:8080/v1` |
|
||||
| API Key | 管理端创建的 `sk_...` |
|
||||
| 鉴权 | `Authorization: Bearer <client-api-key>` |
|
||||
|
||||
```bash
|
||||
curl http://127.0.0.1:8080/v1/models \
|
||||
-H 'Authorization: Bearer <client-api-key>'
|
||||
|
||||
curl http://127.0.0.1:8080/v1/responses \
|
||||
-H 'Authorization: Bearer <client-api-key>' \
|
||||
-H 'Content-Type: application/json' \
|
||||
@@ -129,98 +115,46 @@ curl http://127.0.0.1:8080/v1/responses \
|
||||
}'
|
||||
```
|
||||
|
||||
可用接口:
|
||||
<details>
|
||||
<summary>API 路由</summary>
|
||||
|
||||
| 路由 | 说明 |
|
||||
| --- | --- |
|
||||
| `POST /v1/responses` | Responses 非流式或 SSE 流式请求 |
|
||||
| `GET /v1/responses` | 官方 Responses WebSocket |
|
||||
| `POST /v1/responses/review` | Review 请求 |
|
||||
| `GET /v1/models` | 模型列表 |
|
||||
| `GET /v1/models/catalog` | 模型目录 |
|
||||
| `GET /v1/models/{model_id}` | 模型详情 |
|
||||
| `GET /v1/models/{model_id}/info` | 模型运行信息 |
|
||||
| 路由 | 用途 |
|
||||
| --------------------------- | ------------------- |
|
||||
| `POST /v1/responses` | JSON 或 SSE |
|
||||
| `GET /v1/responses` | Responses WebSocket |
|
||||
| `POST /v1/responses/review` | Review |
|
||||
| `GET /v1/models` | 模型列表 |
|
||||
| `GET /v1/models/catalog` | 模型目录 |
|
||||
| `GET /v1/models/{model_id}` | 模型详情 |
|
||||
|
||||
Compose 默认只监听宿主机 `127.0.0.1`。需要从其他设备访问时,应在前面配置 HTTPS 反向代理,不要直接暴露 PostgreSQL 和 Redis 端口。
|
||||
所有 `/v1/*` 路由都需要客户端 API Key。
|
||||
|
||||
## 管理端
|
||||
</details>
|
||||
|
||||
管理端提供以下页面:
|
||||
|
||||
- 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
|
||||
|
||||
# 日志
|
||||
docker compose -f deploy/compose.yaml logs -f codex-proxy-rs
|
||||
|
||||
# 从源码构建
|
||||
docker compose -f deploy/compose.yaml build codex-proxy-rs
|
||||
docker compose -f deploy/compose.yaml up -d
|
||||
```
|
||||
|
||||
更新镜像不会删除数据库卷,但仍应在升级前备份 PostgreSQL 和 `.runtime/data`。
|
||||
> [!IMPORTANT]
|
||||
> `.runtime/` 保存数据库、Redis、身份密钥和日志。删除该目录会永久清除运行状态。
|
||||
|
||||
不要使用 `docker compose down -v` 做普通升级,该命令会删除 PostgreSQL 与 Redis 命名卷。
|
||||
Compose 默认只绑定 `127.0.0.1`。公网接入应使用 HTTPS 反向代理,转发 WebSocket
|
||||
upgrade 与真实客户端 IP;不要暴露 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
|
||||
```
|
||||
|
||||
`/healthz` 返回 `503` 时,先检查 PostgreSQL 和 Redis 的健康状态。容器反复重启时,再检查 `.runtime/config.yaml`、`deploy/.env` 和 `.runtime/data`、`.runtime/logs` 的权限。
|
||||
|
||||
## 架构
|
||||
|
||||
模块边界、请求链路、存储归属和后台任务见 [架构说明](docs/architecture.md)。
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
- [部署](deploy/README.md)
|
||||
- [架构](docs/architecture.md)
|
||||
- [Release](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
- [容器镜像](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
|
||||
|
||||
Generated
+17
-55
@@ -359,7 +359,6 @@ dependencies = [
|
||||
"bytes",
|
||||
"chrono",
|
||||
"config",
|
||||
"dirs",
|
||||
"flate2",
|
||||
"futures",
|
||||
"hex",
|
||||
@@ -368,11 +367,11 @@ dependencies = [
|
||||
"hyper-util",
|
||||
"indexmap",
|
||||
"ipnet",
|
||||
"percent-encoding",
|
||||
"rand 0.10.2",
|
||||
"rand_core 0.6.4",
|
||||
"redis",
|
||||
"reqwest",
|
||||
"roxmltree",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"rustls-pki-types",
|
||||
@@ -653,27 +652,6 @@ dependencies = [
|
||||
"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"
|
||||
@@ -1388,15 +1366,6 @@ 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"
|
||||
@@ -1560,12 +1529,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"
|
||||
@@ -1822,9 +1785,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "redis"
|
||||
version = "1.3.0"
|
||||
version = "1.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2fa6f8e4b491d7a8ef3a9550a4d71969bd0064f46e32b8dbbcc7fc60dad94fed"
|
||||
checksum = "3cb5358643f48330db5c78856982faf39c93ba50c60d682b43d0344a3b649769"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"arcstr",
|
||||
@@ -1856,17 +1819,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"
|
||||
@@ -1954,6 +1906,15 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "roxmltree"
|
||||
version = "0.21.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.3"
|
||||
@@ -1975,9 +1936,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.36"
|
||||
version = "0.23.42"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b"
|
||||
checksum = "3c54fcab019b409d04215d3a17cb438fd7fbf192ee61461f20f4fe18704bc138"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"ring",
|
||||
@@ -2053,6 +2014,7 @@ version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e891af845473308773346dc847b2c23ee78fe442e0472ac50e22a18a93d3ae5a"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
@@ -2930,9 +2892,9 @@ checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.23.4"
|
||||
version = "1.23.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bf80a72845275afea99e7f2b434723d3bc7e38470fcd1c7ed39a599c73319a53"
|
||||
checksum = "ea5fab0d6c3c01ae70085a09cb03d4c7a1d6314e2b3e075392783396d724ca0a"
|
||||
dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"js-sys",
|
||||
|
||||
+3
-4
@@ -13,7 +13,6 @@ 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"
|
||||
@@ -22,17 +21,17 @@ 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"] }
|
||||
redis = { version = "1.3.0", default-features = false, features = ["tokio-comp", "connection-manager", "script"] }
|
||||
roxmltree = "0.21.1"
|
||||
# Pinned to the Codex Desktop 26.707.41301 HTTP stack; re-audit a newer Desktop before upgrading.
|
||||
reqwest = { version = "=0.12.28", default-features = false, features = ["json", "stream", "cookies", "rustls-tls-native-roots", "gzip", "brotli", "zstd", "deflate", "http2"] }
|
||||
rustls = { version = "=0.23.36", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
rustls = { version = "=0.23.42", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
rustls-native-certs = "0.8.4"
|
||||
rustls-pki-types = "1.14.1"
|
||||
secrecy = "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"] }
|
||||
|
||||
@@ -114,7 +114,7 @@ pub(crate) async fn logout(
|
||||
.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(
|
||||
|
||||
@@ -28,10 +28,7 @@ use crate::{
|
||||
},
|
||||
infra::{
|
||||
format::{format_duration_ms, format_tokens},
|
||||
time::{
|
||||
china_datetime, china_datetime_rfc3339_str, china_day_start, china_quarter_hour_start,
|
||||
china_relative_time,
|
||||
},
|
||||
time::{china_datetime, china_day_start, china_quarter_hour_start, china_relative_time},
|
||||
},
|
||||
telemetry::{
|
||||
account_usage::query::AccountUsageTimeBucket,
|
||||
@@ -41,11 +38,11 @@ use crate::{
|
||||
dashboard_health_timeline_data, dashboard_trend_data,
|
||||
},
|
||||
usage::{
|
||||
insights::RequestHealthTimeBucket,
|
||||
query::{UsageQueryFilter, UsageRecordAccountUsage},
|
||||
types::{UsageRecord, metadata_string},
|
||||
},
|
||||
},
|
||||
upstream::openai::fingerprint::Fingerprint,
|
||||
};
|
||||
|
||||
const DASHBOARD_ACCOUNT_USAGE_LIMIT: u32 = 4;
|
||||
@@ -69,7 +66,7 @@ struct DashboardSummaryData {
|
||||
trend: DashboardTrendData,
|
||||
health_timeline: DashboardHealthTimelineData,
|
||||
account_usage: Vec<DashboardAccountUsageData>,
|
||||
service_statuses: Vec<DashboardServiceStatusData>,
|
||||
wire_profile: DashboardWireProfileData,
|
||||
usage_records: Vec<DashboardUsageRecordData>,
|
||||
pool_summary: AccountPoolDiagnostics,
|
||||
capacity_info: AccountCapacityDiagnostics,
|
||||
@@ -102,6 +99,7 @@ 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>,
|
||||
@@ -113,11 +111,50 @@ struct DashboardUsageRecordData {
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct DashboardServiceStatusData {
|
||||
label: String,
|
||||
value: String,
|
||||
detail: String,
|
||||
tone: String,
|
||||
struct DashboardWireProfileData {
|
||||
originator: String,
|
||||
codex_version: String,
|
||||
desktop_version: String,
|
||||
desktop_build: String,
|
||||
target: DashboardWireTargetData,
|
||||
user_agent: String,
|
||||
verified_at: DateTime<Utc>,
|
||||
release: DashboardDesktopReleaseData,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct DashboardWireTargetData {
|
||||
os_type: String,
|
||||
os_version: String,
|
||||
arch: String,
|
||||
terminal: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct DashboardDesktopReleaseData {
|
||||
status: &'static str,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
checked_at: Option<DateTime<Utc>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
latest_version: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
latest_build: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
published_at: Option<DateTime<Utc>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
minimum_system_version: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
hardware_requirements: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
download_url: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
download_size: Option<u64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
signature_present: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize)]
|
||||
@@ -141,35 +178,6 @@ struct AccountCapacityDiagnostics {
|
||||
available_slots: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct FingerprintDiagnostics {
|
||||
source: &'static str,
|
||||
originator: String,
|
||||
app_version: String,
|
||||
build_number: String,
|
||||
platform: String,
|
||||
arch: String,
|
||||
chromium_version: String,
|
||||
user_agent: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
updated_at: Option<String>,
|
||||
}
|
||||
|
||||
fn fingerprint_diagnostics(fingerprint: &Fingerprint) -> FingerprintDiagnostics {
|
||||
FingerprintDiagnostics {
|
||||
source: "runtime",
|
||||
originator: fingerprint.originator.clone(),
|
||||
app_version: fingerprint.app_version.clone(),
|
||||
build_number: fingerprint.build_number.clone(),
|
||||
platform: fingerprint.platform.clone(),
|
||||
arch: fingerprint.arch.clone(),
|
||||
chromium_version: fingerprint.chromium_version.clone(),
|
||||
user_agent: fingerprint.user_agent(),
|
||||
updated_at: fingerprint.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AccountCapacitySummary> for AccountCapacityDiagnostics {
|
||||
fn from(summary: AccountCapacitySummary) -> Self {
|
||||
Self {
|
||||
@@ -204,12 +212,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_summary()
|
||||
.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
|
||||
@@ -223,7 +231,10 @@ pub(crate) async fn dashboard_summary(
|
||||
.await
|
||||
.map_err(|error| dashboard_data_error("recent usage records", &error))?;
|
||||
|
||||
let time_buckets = dashboard_time_buckets(&state, now).await?;
|
||||
let (time_buckets, health_buckets) = tokio::try_join!(
|
||||
dashboard_time_buckets(&state, now),
|
||||
dashboard_health_buckets(&state, now),
|
||||
)?;
|
||||
let account_ids = accounts
|
||||
.iter()
|
||||
.map(|account| account.id.clone())
|
||||
@@ -255,17 +266,17 @@ 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),
|
||||
health_timeline: dashboard_health_timeline_data(&health_buckets),
|
||||
account_usage: account_usage_data(
|
||||
&accounts,
|
||||
&account_usage_records,
|
||||
"a_used_by_account,
|
||||
now,
|
||||
),
|
||||
service_statuses: service_status_data(&state),
|
||||
wire_profile: wire_profile_data(&state),
|
||||
usage_records: dashboard_usage_records,
|
||||
pool_summary,
|
||||
capacity_info: AccountCapacityDiagnostics::from(capacity),
|
||||
@@ -314,6 +325,18 @@ async fn dashboard_time_buckets(
|
||||
.map_err(|error| dashboard_data_error("time buckets", &error))
|
||||
}
|
||||
|
||||
async fn dashboard_health_buckets(
|
||||
state: &AppState,
|
||||
now: DateTime<Utc>,
|
||||
) -> Result<Vec<RequestHealthTimeBucket>, AdminError> {
|
||||
state
|
||||
.services
|
||||
.usage_records
|
||||
.health_timeline(china_day_start(now), now)
|
||||
.await
|
||||
.map_err(|error| dashboard_data_error("health timeline", &error))
|
||||
}
|
||||
|
||||
fn dashboard_account_counts(accounts: &[Account]) -> DashboardAccountCounts {
|
||||
DashboardAccountCounts {
|
||||
total: accounts.len() as u64,
|
||||
@@ -418,7 +441,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")
|
||||
}
|
||||
|
||||
@@ -517,6 +540,7 @@ 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")
|
||||
@@ -541,6 +565,7 @@ fn dashboard_usage_record_data(
|
||||
client_ip,
|
||||
user_agent,
|
||||
reasoning_effort,
|
||||
reasoning_preset,
|
||||
compact,
|
||||
request_kind,
|
||||
subagent_kind,
|
||||
@@ -551,66 +576,53 @@ fn dashboard_usage_record_data(
|
||||
}
|
||||
}
|
||||
|
||||
fn service_status_data(state: &AppState) -> Vec<DashboardServiceStatusData> {
|
||||
let current_fingerprint = state.services.fingerprint.snapshot();
|
||||
let fingerprint = fingerprint_diagnostics(¤t_fingerprint);
|
||||
vec![
|
||||
DashboardServiceStatusData {
|
||||
label: "客户端版本".to_string(),
|
||||
value: empty_dash(fingerprint.app_version),
|
||||
detail: if fingerprint.build_number.trim().is_empty() {
|
||||
"-".to_string()
|
||||
} else {
|
||||
format!("Build {}", fingerprint.build_number)
|
||||
},
|
||||
tone: "info".to_string(),
|
||||
},
|
||||
DashboardServiceStatusData {
|
||||
label: "平台架构".to_string(),
|
||||
value: empty_dash(fingerprint.platform),
|
||||
detail: empty_dash(fingerprint.arch),
|
||||
tone: "info".to_string(),
|
||||
},
|
||||
DashboardServiceStatusData {
|
||||
label: "Chromium".to_string(),
|
||||
value: if fingerprint.chromium_version.trim().is_empty() {
|
||||
"-".to_string()
|
||||
} else {
|
||||
format!("v{}", fingerprint.chromium_version)
|
||||
},
|
||||
detail: empty_dash(fingerprint.originator),
|
||||
tone: "normal".to_string(),
|
||||
},
|
||||
DashboardServiceStatusData {
|
||||
label: "更新时间".to_string(),
|
||||
value: format_fingerprint_updated_at(fingerprint.updated_at),
|
||||
detail: String::new(),
|
||||
tone: "normal".to_string(),
|
||||
},
|
||||
DashboardServiceStatusData {
|
||||
label: "User Agent".to_string(),
|
||||
value: fingerprint.user_agent,
|
||||
detail: String::new(),
|
||||
tone: "normal".to_string(),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn empty_dash(value: String) -> String {
|
||||
if value.trim().is_empty() {
|
||||
"-".to_string()
|
||||
fn wire_profile_data(state: &AppState) -> DashboardWireProfileData {
|
||||
let profile = &state.services.wire_profile;
|
||||
let release_snapshot = state.services.desktop_release.snapshot();
|
||||
let release_status = if release_snapshot.last_error.is_some() {
|
||||
"check_failed"
|
||||
} else if let Some(latest) = &release_snapshot.latest {
|
||||
if latest.version == profile.desktop_version && latest.build == profile.desktop_build {
|
||||
"aligned"
|
||||
} else {
|
||||
"review_required"
|
||||
}
|
||||
} else {
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
fn format_fingerprint_updated_at(value: Option<String>) -> String {
|
||||
let Some(value) = value else {
|
||||
return "-".to_string();
|
||||
"unchecked"
|
||||
};
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
return "-".to_string();
|
||||
let latest = release_snapshot.latest;
|
||||
|
||||
DashboardWireProfileData {
|
||||
originator: profile.originator.clone(),
|
||||
codex_version: profile.codex_version.clone(),
|
||||
desktop_version: profile.desktop_version.clone(),
|
||||
desktop_build: profile.desktop_build.clone(),
|
||||
target: DashboardWireTargetData {
|
||||
os_type: profile.os_type.clone(),
|
||||
os_version: profile.os_version.clone(),
|
||||
arch: profile.arch.clone(),
|
||||
terminal: profile.terminal.clone(),
|
||||
},
|
||||
user_agent: profile.user_agent(),
|
||||
verified_at: profile.verified_at,
|
||||
release: DashboardDesktopReleaseData {
|
||||
status: release_status,
|
||||
checked_at: release_snapshot.checked_at,
|
||||
latest_version: latest.as_ref().map(|release| release.version.clone()),
|
||||
latest_build: latest.as_ref().map(|release| release.build.clone()),
|
||||
published_at: latest.as_ref().and_then(|release| release.published_at),
|
||||
minimum_system_version: latest
|
||||
.as_ref()
|
||||
.and_then(|release| release.minimum_system_version.clone()),
|
||||
hardware_requirements: latest
|
||||
.as_ref()
|
||||
.and_then(|release| release.hardware_requirements.clone()),
|
||||
download_url: latest
|
||||
.as_ref()
|
||||
.and_then(|release| release.download_url.clone()),
|
||||
download_size: latest.as_ref().and_then(|release| release.download_size),
|
||||
signature_present: latest.as_ref().map(|release| release.signature_present),
|
||||
error: release_snapshot.last_error,
|
||||
},
|
||||
}
|
||||
china_datetime_rfc3339_str(value)
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! 使用记录 HTTP 处理器。
|
||||
//! 使用统计与请求记录 HTTP 处理器。
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -26,6 +26,7 @@ use crate::{
|
||||
time::china_datetime,
|
||||
},
|
||||
telemetry::{
|
||||
usage::insights::{UsageDiagnosticsDimension, default_time_range},
|
||||
usage::query::{
|
||||
UsageQueryError, UsageQueryFilter, UsageRecordBreakdown, UsageRecordModelSource,
|
||||
UsageRecordSummary, UsageRecordTrendPoint, usage_record_billing,
|
||||
@@ -64,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 {
|
||||
@@ -88,6 +104,7 @@ 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>,
|
||||
@@ -303,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,
|
||||
@@ -404,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 => {
|
||||
@@ -442,6 +511,7 @@ 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")
|
||||
@@ -463,6 +533,7 @@ fn usage_record_data(
|
||||
client_ip,
|
||||
user_agent,
|
||||
reasoning_effort,
|
||||
reasoning_preset,
|
||||
compact,
|
||||
request_kind,
|
||||
subagent_kind,
|
||||
@@ -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
|
||||
};
|
||||
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,10 @@ 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",
|
||||
@@ -123,6 +133,16 @@ pub fn responses_dispatch_error_response_ref(error: &ResponseDispatchError) -> R
|
||||
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 {
|
||||
ResponseDispatchError::NoActiveAccount => {
|
||||
responses_no_available_accounts_response().into_response()
|
||||
@@ -132,6 +152,13 @@ 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);
|
||||
@@ -142,6 +169,15 @@ 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;
|
||||
}
|
||||
@@ -313,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,
|
||||
|
||||
@@ -103,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)
|
||||
|
||||
@@ -22,11 +22,11 @@ use tokio_tungstenite::{
|
||||
|
||||
use crate::{
|
||||
api::{AppState, middleware::request_id::RequestId},
|
||||
dispatch::service::ResponseDispatchStream,
|
||||
upstream::openai::protocol::{
|
||||
sse::{SseEvent, SseEventDecoder},
|
||||
websocket::{is_terminal_websocket_event, websocket_event_type},
|
||||
dispatch::{
|
||||
service::{ConnectionTranscriptFacts, ResponseDispatchStream},
|
||||
transport::canonical::CanonicalResponseEvent,
|
||||
},
|
||||
upstream::openai::protocol::websocket::is_terminal_websocket_event,
|
||||
};
|
||||
|
||||
use super::{PreparedResponsesRequest, ResponsesRequestValidationError, prepare_responses_request};
|
||||
@@ -70,7 +70,7 @@ pub async fn responses_websocket(State(state): State<AppState>, mut request: Req
|
||||
tracing::info!(
|
||||
websocket_connection_id = %connection_id,
|
||||
error = %error,
|
||||
"invalid Responses WebSocket upgrade request"
|
||||
"Invalid Responses WebSocket upgrade request"
|
||||
);
|
||||
return openai_error_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
@@ -131,6 +131,48 @@ struct ResponsesWebSocketSession {
|
||||
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,
|
||||
@@ -140,6 +182,11 @@ async fn serve_responses_websocket(
|
||||
"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 {
|
||||
@@ -190,7 +237,7 @@ async fn serve_responses_websocket(
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let prepared = match prepare_responses_request(
|
||||
let mut prepared = match prepare_responses_request(
|
||||
&session.state,
|
||||
body,
|
||||
&session.headers,
|
||||
@@ -229,9 +276,22 @@ async fn serve_responses_websocket(
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let replay_plan = session
|
||||
.state
|
||||
.services
|
||||
.responses
|
||||
.prepare_connection_replay(&replay_snapshot, &mut prepared.request);
|
||||
|
||||
if !dispatch_response_create(&mut socket, &session, request_id, prepared).await {
|
||||
break;
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,7 +307,7 @@ async fn dispatch_response_create(
|
||||
session: &ResponsesWebSocketSession,
|
||||
request_id: RequestId,
|
||||
prepared: PreparedResponsesRequest,
|
||||
) -> bool {
|
||||
) -> ForwardDispatchOutcome {
|
||||
let PreparedResponsesRequest {
|
||||
mut request,
|
||||
requested_model,
|
||||
@@ -270,7 +330,11 @@ async fn dispatch_response_create(
|
||||
Ok(stream) => stream,
|
||||
Err(error) => {
|
||||
let event = responses_websocket_dispatch_error_event(&error, request_id.as_str());
|
||||
return send_text(socket, event).await;
|
||||
return if send_text(socket, event).await {
|
||||
ForwardDispatchOutcome::Continue(None)
|
||||
} else {
|
||||
ForwardDispatchOutcome::Disconnect
|
||||
};
|
||||
}
|
||||
};
|
||||
forward_dispatch_stream(socket, stream, request_id.as_str()).await
|
||||
@@ -280,9 +344,10 @@ async fn forward_dispatch_stream(
|
||||
socket: &mut ResponsesWebSocket,
|
||||
stream: ResponseDispatchStream,
|
||||
request_id: &str,
|
||||
) -> bool {
|
||||
) -> ForwardDispatchOutcome {
|
||||
let ResponseDispatchStream {
|
||||
body,
|
||||
mut canonical_events,
|
||||
response_headers,
|
||||
} = stream;
|
||||
if !send_text(
|
||||
@@ -291,12 +356,12 @@ async fn forward_dispatch_stream(
|
||||
)
|
||||
.await
|
||||
{
|
||||
return false;
|
||||
return ForwardDispatchOutcome::Disconnect;
|
||||
}
|
||||
|
||||
let mut body = body;
|
||||
let mut decoder = SseEventDecoder::default();
|
||||
let mut terminal_sent = false;
|
||||
let mut completed = ConnectionTranscriptCollector::default();
|
||||
loop {
|
||||
let next = if terminal_sent {
|
||||
ActiveResponseInput::Upstream(body.next().await)
|
||||
@@ -308,33 +373,32 @@ async fn forward_dispatch_stream(
|
||||
};
|
||||
match next {
|
||||
ActiveResponseInput::Upstream(Some(Ok(chunk))) => {
|
||||
let events = match decoder.push(&chunk) {
|
||||
Ok(events) => events,
|
||||
Err(error) => {
|
||||
tracing::warn!(request_id, error = %error, "failed to decode Responses SSE for WebSocket forwarding");
|
||||
let sent = send_error(
|
||||
socket,
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"server_error",
|
||||
"invalid_upstream_response",
|
||||
INVALID_UPSTREAM_EVENT_MESSAGE,
|
||||
request_id,
|
||||
)
|
||||
.await;
|
||||
drop(body);
|
||||
return sent;
|
||||
}
|
||||
let Some(events) = canonical_events.recv().await else {
|
||||
tracing::warn!(
|
||||
request_id,
|
||||
"Canonical Responses event stream closed before body stream"
|
||||
);
|
||||
return ForwardDispatchOutcome::Disconnect;
|
||||
};
|
||||
if !forward_sse_events(socket, events, request_id, &mut terminal_sent).await {
|
||||
return false;
|
||||
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 true;
|
||||
return ForwardDispatchOutcome::Continue(completed.completed);
|
||||
}
|
||||
return send_error(
|
||||
return if send_error(
|
||||
socket,
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"server_error",
|
||||
@@ -342,31 +406,18 @@ async fn forward_dispatch_stream(
|
||||
STREAM_DISCONNECTED_MESSAGE,
|
||||
request_id,
|
||||
)
|
||||
.await;
|
||||
.await
|
||||
{
|
||||
ForwardDispatchOutcome::Continue(None)
|
||||
} else {
|
||||
ForwardDispatchOutcome::Disconnect
|
||||
};
|
||||
}
|
||||
ActiveResponseInput::Upstream(None) => {
|
||||
let events = match decoder.finish() {
|
||||
Ok(events) => events,
|
||||
Err(error) => {
|
||||
tracing::warn!(request_id, error = %error, "failed to finish Responses SSE decoding");
|
||||
return send_error(
|
||||
socket,
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"server_error",
|
||||
"invalid_upstream_response",
|
||||
INVALID_UPSTREAM_EVENT_MESSAGE,
|
||||
request_id,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
};
|
||||
if !forward_sse_events(socket, events, request_id, &mut terminal_sent).await {
|
||||
return false;
|
||||
}
|
||||
if terminal_sent {
|
||||
return true;
|
||||
return ForwardDispatchOutcome::Continue(completed.completed);
|
||||
}
|
||||
return send_error(
|
||||
return if send_error(
|
||||
socket,
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"server_error",
|
||||
@@ -374,23 +425,30 @@ async fn forward_dispatch_stream(
|
||||
STREAM_DISCONNECTED_MESSAGE,
|
||||
request_id,
|
||||
)
|
||||
.await;
|
||||
.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 false,
|
||||
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 false;
|
||||
return ForwardDispatchOutcome::Disconnect;
|
||||
}
|
||||
ActiveResponseInput::Downstream(Some(Err(error))) => {
|
||||
tracing::info!(request_id, error = %error, "Responses WebSocket client disconnected during response");
|
||||
return false;
|
||||
return ForwardDispatchOutcome::Disconnect;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -401,14 +459,15 @@ enum ActiveResponseInput {
|
||||
Downstream(Option<Result<Message, WebSocketError>>),
|
||||
}
|
||||
|
||||
async fn forward_sse_events(
|
||||
async fn forward_canonical_events(
|
||||
socket: &mut ResponsesWebSocket,
|
||||
events: Vec<SseEvent>,
|
||||
events: Vec<CanonicalResponseEvent>,
|
||||
request_id: &str,
|
||||
terminal_sent: &mut bool,
|
||||
completed: &mut ConnectionTranscriptCollector,
|
||||
) -> bool {
|
||||
for event in events {
|
||||
let Some(event_type) = websocket_event_type(&event.data) else {
|
||||
let Some(event_type) = event.event_type() else {
|
||||
tracing::warn!(
|
||||
request_id,
|
||||
"Responses SSE event does not contain a valid JSON type"
|
||||
@@ -424,10 +483,11 @@ async fn forward_sse_events(
|
||||
.await;
|
||||
return false;
|
||||
};
|
||||
if !send_text(socket, event.data).await {
|
||||
completed.observe(&event);
|
||||
if !send_text(socket, event.data().to_string()).await {
|
||||
return false;
|
||||
}
|
||||
*terminal_sent |= is_terminal_websocket_event(&event_type);
|
||||
*terminal_sent |= is_terminal_websocket_event(event_type);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -28,6 +28,11 @@ impl Default for ConnectionDrain {
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,10 @@ use crate::{
|
||||
usage::query::UsageQueryService,
|
||||
},
|
||||
update::service::SystemUpdateService,
|
||||
upstream::openai::{fingerprint::RuntimeFingerprint, token_client::OpenAiTokenClient},
|
||||
upstream::openai::{
|
||||
desktop_release::DesktopReleaseStatus, profile::CodexWireProfile,
|
||||
token_client::OpenAiTokenClient,
|
||||
},
|
||||
};
|
||||
|
||||
/// HTTP API 所需的领域服务集合。
|
||||
@@ -48,7 +51,8 @@ pub struct ApiServices {
|
||||
pub token_refresh: Arc<TokenRefreshService<OpenAiTokenClient>>,
|
||||
pub responses: Arc<ResponseDispatchService>,
|
||||
pub session_affinity: Arc<SessionAffinityService>,
|
||||
pub fingerprint: RuntimeFingerprint,
|
||||
pub wire_profile: Arc<CodexWireProfile>,
|
||||
pub desktop_release: DesktopReleaseStatus,
|
||||
pub process_control: Arc<dyn ProcessControl>,
|
||||
pub system_update: Arc<SystemUpdateService>,
|
||||
pub connection_drain: crate::api::middleware::connection_drain::ConnectionDrain,
|
||||
@@ -96,7 +100,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)
|
||||
|
||||
+525
-304
@@ -1,9 +1,23 @@
|
||||
use std::{collections::BTreeMap, env, path::Path};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
env,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use chrono::{DateTime, Utc};
|
||||
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,
|
||||
wire_profile,
|
||||
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,
|
||||
wire_profile,
|
||||
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)]
|
||||
/// 经审计固定的 Codex Desktop 上游请求画像。
|
||||
pub wire_profile: WireProfileConfig,
|
||||
/// 管理员初始化配置,不包含密码。
|
||||
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,178 +351,47 @@ 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)]
|
||||
/// 经审计固定的 Codex Desktop 上游请求画像配置。
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct FingerprintConfig {
|
||||
/// 客户端来源名。
|
||||
pub struct WireProfileConfig {
|
||||
/// `originator` 请求头及 User-Agent 产品名。
|
||||
pub originator: String,
|
||||
/// 应用版本。
|
||||
pub app_version: String,
|
||||
/// 构建号。
|
||||
pub build_number: String,
|
||||
/// 平台名。
|
||||
pub platform: String,
|
||||
/// 架构名。
|
||||
/// bundled Codex Core 版本。
|
||||
pub codex_version: String,
|
||||
/// Desktop 应用版本。
|
||||
pub desktop_version: String,
|
||||
/// Desktop 制品构建号。
|
||||
pub desktop_build: String,
|
||||
/// Codex Core UA 中的目标操作系统类型。
|
||||
pub os_type: String,
|
||||
/// Codex Core UA 中的目标操作系统版本。
|
||||
pub os_version: String,
|
||||
/// Codex Core UA 中的目标架构。
|
||||
pub arch: String,
|
||||
/// Chromium 主版本。
|
||||
pub chromium_version: String,
|
||||
/// User-Agent 模板。
|
||||
pub user_agent_template: String,
|
||||
/// 默认请求头。
|
||||
pub default_headers: Vec<FingerprintHeaderConfig>,
|
||||
/// 请求头排序优先级。
|
||||
pub header_order: Vec<String>,
|
||||
/// Codex Core UA 中的终端标记。
|
||||
pub terminal: String,
|
||||
/// 此画像最后一次经制品与源码核验的时间。
|
||||
pub verified_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
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)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct FingerprintHeaderConfig {
|
||||
/// 请求头名称。
|
||||
pub name: String,
|
||||
/// 请求头值。
|
||||
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 +399,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 +415,289 @@ 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,
|
||||
wire_profile: WireProfileConfig,
|
||||
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_wire_profile(&config.wire_profile)?;
|
||||
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_wire_profile(config: &WireProfileConfig) -> Result<(), ConfigError> {
|
||||
for (field, value) in [
|
||||
("wire_profile.originator", config.originator.as_str()),
|
||||
("wire_profile.codex_version", config.codex_version.as_str()),
|
||||
(
|
||||
"wire_profile.desktop_version",
|
||||
config.desktop_version.as_str(),
|
||||
),
|
||||
("wire_profile.desktop_build", config.desktop_build.as_str()),
|
||||
("wire_profile.os_type", config.os_type.as_str()),
|
||||
("wire_profile.os_version", config.os_version.as_str()),
|
||||
("wire_profile.arch", config.arch.as_str()),
|
||||
("wire_profile.terminal", config.terminal.as_str()),
|
||||
] {
|
||||
validate_nonempty(field, value)?;
|
||||
}
|
||||
|
||||
if semver::Version::parse(&config.codex_version).is_err() {
|
||||
return Err(ConfigError::InvalidField("wire_profile.codex_version"));
|
||||
}
|
||||
if !is_numeric_dotted_version(&config.desktop_version) {
|
||||
return Err(ConfigError::InvalidField("wire_profile.desktop_version"));
|
||||
}
|
||||
if !config
|
||||
.desktop_build
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_digit())
|
||||
{
|
||||
return Err(ConfigError::InvalidField("wire_profile.desktop_build"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_numeric_dotted_version(value: &str) -> bool {
|
||||
let mut parts = value.split('.');
|
||||
let valid_parts = parts
|
||||
.by_ref()
|
||||
.filter(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
|
||||
.count();
|
||||
valid_parts >= 2 && valid_parts == value.split('.').count()
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
|
||||
@@ -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},
|
||||
@@ -49,7 +50,8 @@ use crate::{
|
||||
},
|
||||
update::service::SystemUpdateService,
|
||||
upstream::openai::{
|
||||
fingerprint::{Fingerprint, PgFingerprintStore, RuntimeFingerprint},
|
||||
desktop_release::DesktopReleaseStatus,
|
||||
profile::CodexWireProfile,
|
||||
token_client::{OpenAiTokenClient, TokenClientConfig, default_openai_token_client},
|
||||
transport::{
|
||||
CodexBackendClient, CodexModelCatalogClient, CodexWebSocketPool,
|
||||
@@ -79,7 +81,6 @@ pub struct BackgroundTaskStores {
|
||||
pub admin_users: PgAdminUserStore,
|
||||
pub admin_sessions: RedisAdminSessionStore,
|
||||
pub cookies: PgCookieStore,
|
||||
pub fingerprints: PgFingerprintStore,
|
||||
pub session_affinity: RedisSessionAffinityStore,
|
||||
pub refresh_leases: RedisRefreshLeaseStore,
|
||||
pub model_snapshots: RedisModelSnapshotStore,
|
||||
@@ -116,7 +117,8 @@ pub struct Services {
|
||||
pub session_affinity: Arc<SessionAffinityService>,
|
||||
pub codex: Arc<CodexBackendClient>,
|
||||
pub websocket_pool: Option<Arc<CodexWebSocketPool>>,
|
||||
pub fingerprint: RuntimeFingerprint,
|
||||
pub wire_profile: Arc<CodexWireProfile>,
|
||||
pub desktop_release: DesktopReleaseStatus,
|
||||
pub account_pseudonymizer: Arc<AccountPseudonymizer>,
|
||||
pub system_update: Arc<SystemUpdateService>,
|
||||
pub connection_drain: crate::api::middleware::connection_drain::ConnectionDrain,
|
||||
@@ -144,21 +146,21 @@ impl Services {
|
||||
pub fn new(
|
||||
config: &AppConfig,
|
||||
stores: BackgroundTaskStores,
|
||||
fingerprint: RuntimeFingerprint,
|
||||
wire_profile: Arc<CodexWireProfile>,
|
||||
) -> Self {
|
||||
Self::try_new(config, stores, fingerprint)
|
||||
Self::try_new(config, stores, wire_profile)
|
||||
.expect("failed to build runtime services with configured TLS transport")
|
||||
}
|
||||
|
||||
pub fn try_new(
|
||||
config: &AppConfig,
|
||||
stores: BackgroundTaskStores,
|
||||
fingerprint: RuntimeFingerprint,
|
||||
wire_profile: Arc<CodexWireProfile>,
|
||||
) -> Result<Self, CustomCaError> {
|
||||
Self::try_with_usage_record_options(
|
||||
config,
|
||||
stores,
|
||||
fingerprint,
|
||||
wire_profile,
|
||||
UsageRecordOptions::from_config(config),
|
||||
)
|
||||
}
|
||||
@@ -166,7 +168,7 @@ impl Services {
|
||||
pub fn try_with_usage_record_options(
|
||||
config: &AppConfig,
|
||||
stores: BackgroundTaskStores,
|
||||
fingerprint: RuntimeFingerprint,
|
||||
wire_profile: Arc<CodexWireProfile>,
|
||||
usage_record_options: UsageRecordOptions,
|
||||
) -> Result<Self, CustomCaError> {
|
||||
let mut identity_secret = [0u8; 32];
|
||||
@@ -174,7 +176,7 @@ impl Services {
|
||||
Self::try_with_identity_secret_and_usage_record_options(
|
||||
config,
|
||||
stores,
|
||||
fingerprint,
|
||||
wire_profile,
|
||||
identity_secret,
|
||||
usage_record_options,
|
||||
)
|
||||
@@ -183,7 +185,7 @@ impl Services {
|
||||
fn try_with_identity_secret_and_usage_record_options(
|
||||
config: &AppConfig,
|
||||
stores: BackgroundTaskStores,
|
||||
fingerprint: RuntimeFingerprint,
|
||||
wire_profile: Arc<CodexWireProfile>,
|
||||
identity_secret: [u8; 32],
|
||||
usage_record_options: UsageRecordOptions,
|
||||
) -> Result<Self, CustomCaError> {
|
||||
@@ -211,9 +213,9 @@ 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(),
|
||||
wire_profile.clone(),
|
||||
)
|
||||
.with_websocket_initial_event_timeout(websocket_initial_event_timeout);
|
||||
if let Some(pool) = &websocket_pool {
|
||||
@@ -296,8 +298,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(),
|
||||
@@ -306,9 +310,11 @@ impl Services {
|
||||
recorder,
|
||||
account_identity,
|
||||
cloudflare: cloudflare_recovery,
|
||||
shutdown: connection_drain.cancellation_token(),
|
||||
}));
|
||||
let system_update = Arc::new(SystemUpdateService::from_env());
|
||||
let connection_drain = crate::api::middleware::connection_drain::ConnectionDrain::default();
|
||||
|
||||
let desktop_release = DesktopReleaseStatus::default();
|
||||
|
||||
Ok(Self {
|
||||
database,
|
||||
@@ -330,7 +336,8 @@ impl Services {
|
||||
session_affinity,
|
||||
codex,
|
||||
websocket_pool,
|
||||
fingerprint,
|
||||
wire_profile,
|
||||
desktop_release,
|
||||
account_pseudonymizer,
|
||||
system_update,
|
||||
connection_drain,
|
||||
@@ -367,7 +374,8 @@ impl From<&Services> for crate::api::router::ApiServices {
|
||||
token_refresh: services.token_refresh.clone(),
|
||||
responses: services.responses.clone(),
|
||||
session_affinity: services.session_affinity.clone(),
|
||||
fingerprint: services.fingerprint.clone(),
|
||||
wire_profile: services.wire_profile.clone(),
|
||||
desktop_release: services.desktop_release.clone(),
|
||||
process_control: Arc::new(crate::bootstrap::shutdown::RuntimeProcessControl),
|
||||
system_update: services.system_update.clone(),
|
||||
connection_drain: services.connection_drain.clone(),
|
||||
@@ -416,24 +424,19 @@ pub fn apply_settings_to_config(config: &mut AppConfig, settings: &SettingsSnaps
|
||||
config.auth.rotation_strategy = settings.rotation_strategy.clone();
|
||||
}
|
||||
|
||||
pub fn fingerprint_from_config(
|
||||
config: &crate::bootstrap::config::FingerprintConfig,
|
||||
) -> Fingerprint {
|
||||
Fingerprint {
|
||||
pub fn wire_profile_from_config(
|
||||
config: &crate::bootstrap::config::WireProfileConfig,
|
||||
) -> CodexWireProfile {
|
||||
CodexWireProfile {
|
||||
originator: config.originator.clone(),
|
||||
app_version: config.app_version.clone(),
|
||||
build_number: config.build_number.clone(),
|
||||
platform: config.platform.clone(),
|
||||
codex_version: config.codex_version.clone(),
|
||||
desktop_version: config.desktop_version.clone(),
|
||||
desktop_build: config.desktop_build.clone(),
|
||||
os_type: config.os_type.clone(),
|
||||
os_version: config.os_version.clone(),
|
||||
arch: config.arch.clone(),
|
||||
chromium_version: config.chromium_version.clone(),
|
||||
user_agent_template: config.user_agent_template.clone(),
|
||||
default_headers: config
|
||||
.default_headers
|
||||
.iter()
|
||||
.map(|header| (header.name.clone(), header.value.clone()))
|
||||
.collect(),
|
||||
header_order: config.header_order.clone(),
|
||||
updated_at: None,
|
||||
terminal: config.terminal.clone(),
|
||||
verified_at: config.verified_at,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -445,13 +448,12 @@ 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, connection_drain) = build_router(config).await?;
|
||||
let mut task_coordinator = Some(task_coordinator);
|
||||
@@ -501,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(())
|
||||
}
|
||||
}
|
||||
@@ -534,7 +536,7 @@ 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,
|
||||
@@ -543,20 +545,27 @@ async fn build_router(
|
||||
),
|
||||
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);
|
||||
|
||||
let fingerprint_store = PgFingerprintStore::new(pool.clone());
|
||||
let stores = BackgroundTaskStores {
|
||||
redis: redis.clone(),
|
||||
accounts: PgAccountStore::new(pool.clone()),
|
||||
admin_users: PgAdminUserStore::new(pool.clone()),
|
||||
admin_sessions: RedisAdminSessionStore::new(redis.clone()),
|
||||
cookies: PgCookieStore::new(pool.clone()),
|
||||
fingerprints: fingerprint_store.clone(),
|
||||
session_affinity: RedisSessionAffinityStore::new(redis.clone()),
|
||||
refresh_leases: RedisRefreshLeaseStore::new(redis.clone()),
|
||||
model_snapshots: RedisModelSnapshotStore::new(redis.clone()),
|
||||
@@ -567,20 +576,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 wire_profile = Arc::new(wire_profile_from_config(&config.wire_profile));
|
||||
let runtime_config = crate::bootstrap::state::RuntimeConfig::from(&config);
|
||||
let services = Services::try_with_identity_secret_and_usage_record_options(
|
||||
&config,
|
||||
stores,
|
||||
runtime_fingerprint,
|
||||
wire_profile,
|
||||
identity_secret,
|
||||
UsageRecordOptions::from_config(&config),
|
||||
)?;
|
||||
@@ -588,8 +591,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,
|
||||
"默认管理员账号已完成初始化检查"
|
||||
|
||||
@@ -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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,13 @@
|
||||
//! 后台任务协调器。
|
||||
|
||||
use std::{future::Future, path::PathBuf, sync::Arc, time::Duration};
|
||||
use std::{future::Future, sync::Arc, time::Duration};
|
||||
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use super::{
|
||||
cookie_cleanup::CookieCleanupTask,
|
||||
fingerprint_update::{
|
||||
CODEX_DESKTOP_APPCAST_URL, DEFAULT_EXTRACTED_FINGERPRINT_PATH,
|
||||
start_fingerprint_update_task,
|
||||
},
|
||||
model_refresh::ModelRefreshTask,
|
||||
quota_refresh::QuotaRefreshTask,
|
||||
retention_trim::RetentionTrimTask,
|
||||
token_refresh::TokenRefreshTask,
|
||||
cookie_cleanup::CookieCleanupTask, desktop_release_update::start_desktop_release_update_task,
|
||||
model_refresh::ModelRefreshTask, quota_refresh::QuotaRefreshTask,
|
||||
retention_trim::RetentionTrimTask, token_refresh::TokenRefreshTask,
|
||||
};
|
||||
|
||||
/// 后台任务协调器。
|
||||
@@ -46,7 +40,6 @@ impl TaskCoordinator {
|
||||
stores.usage_records.clone(),
|
||||
stores.ops_errors.clone(),
|
||||
stores.request_buckets.clone(),
|
||||
stores.fingerprints.clone(),
|
||||
)
|
||||
.start(),
|
||||
);
|
||||
@@ -82,6 +75,7 @@ impl TaskCoordinator {
|
||||
stores.accounts.clone(),
|
||||
stores.account_usage.clone(),
|
||||
services.codex.clone(),
|
||||
services.account_pool.clone(),
|
||||
services.account_pseudonymizer.clone(),
|
||||
config
|
||||
.quota
|
||||
@@ -91,20 +85,15 @@ impl TaskCoordinator {
|
||||
30 * 60,
|
||||
)
|
||||
.with_cookie_store(stores.cookies.clone())
|
||||
.with_account_pool(services.account_pool.clone())
|
||||
.start(),
|
||||
);
|
||||
coordinator.push("fingerprint_update", {
|
||||
let fingerprint = services.fingerprint.snapshot();
|
||||
start_fingerprint_update_task(
|
||||
stores.fingerprints.clone(),
|
||||
services.fingerprint.clone(),
|
||||
CODEX_DESKTOP_APPCAST_URL.to_string(),
|
||||
PathBuf::from(DEFAULT_EXTRACTED_FINGERPRINT_PATH),
|
||||
fingerprint.app_version,
|
||||
fingerprint.build_number,
|
||||
)
|
||||
});
|
||||
coordinator.push(
|
||||
"desktop_release_update",
|
||||
start_desktop_release_update_task(
|
||||
services.desktop_release.clone(),
|
||||
crate::upstream::openai::desktop_release::CODEX_DESKTOP_APPCAST_URL.to_string(),
|
||||
),
|
||||
);
|
||||
if let Some(pool) = &services.websocket_pool {
|
||||
coordinator.push(
|
||||
"websocket_pool",
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Codex Desktop 官方发布观测任务接线。
|
||||
|
||||
use tracing::{info, warn};
|
||||
|
||||
use crate::upstream::openai::desktop_release::{
|
||||
APPCAST_POLL_INTERVAL, DesktopReleaseChecker, DesktopReleaseStatus,
|
||||
};
|
||||
|
||||
use super::{
|
||||
coordinator::SchedulerHandle,
|
||||
periodic::{PeriodicTaskConfig, PeriodicTaskRunner, spawn_periodic_task},
|
||||
};
|
||||
|
||||
/// 启动 Desktop 官方发布检查后台任务。
|
||||
pub fn start_desktop_release_update_task(
|
||||
status: DesktopReleaseStatus,
|
||||
appcast_url: String,
|
||||
) -> SchedulerHandle {
|
||||
let checker = DesktopReleaseChecker::with_client(reqwest::Client::new(), appcast_url, status);
|
||||
spawn_periodic_task(
|
||||
DesktopReleaseUpdateTask {
|
||||
checker,
|
||||
first_tick: true,
|
||||
},
|
||||
PeriodicTaskConfig::new(
|
||||
APPCAST_POLL_INTERVAL.as_secs(),
|
||||
"Codex Desktop 发布检查器已启动",
|
||||
"Codex Desktop 发布检查器已关闭",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
struct DesktopReleaseUpdateTask {
|
||||
checker: DesktopReleaseChecker,
|
||||
first_tick: bool,
|
||||
}
|
||||
|
||||
impl PeriodicTaskRunner for DesktopReleaseUpdateTask {
|
||||
fn tick(&mut self) -> super::periodic::TaskFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
let first_tick = std::mem::take(&mut self.first_tick);
|
||||
match self.checker.check_and_record().await {
|
||||
Ok(release) => info!(
|
||||
version = %release.version,
|
||||
build = %release.build,
|
||||
"Codex Desktop 最新发布信息已刷新"
|
||||
),
|
||||
Err(error) if first_tick => {
|
||||
warn!(error = %error, "Codex Desktop 首次发布检查失败");
|
||||
}
|
||||
Err(error) => {
|
||||
warn!(error = %error, "Codex Desktop 定期发布检查失败");
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
//! 指纹更新任务接线。
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use tracing::{info, warn};
|
||||
|
||||
use crate::upstream::openai::fingerprint::{
|
||||
APPCAST_POLL_INTERVAL, PgFingerprintStore, RuntimeFingerprint, UpdateChecker,
|
||||
};
|
||||
|
||||
use super::{
|
||||
coordinator::SchedulerHandle,
|
||||
periodic::{PeriodicTaskConfig, PeriodicTaskRunner, spawn_periodic_task},
|
||||
};
|
||||
|
||||
/// Codex Desktop 官方 appcast 地址。
|
||||
pub const CODEX_DESKTOP_APPCAST_URL: &str =
|
||||
"https://persistent.oaistatic.com/codex-app-prod/appcast.xml";
|
||||
/// 本地可选完整指纹提取文件路径。
|
||||
pub const DEFAULT_EXTRACTED_FINGERPRINT_PATH: &str = "data/extracted-fingerprint.json";
|
||||
|
||||
/// 启动指纹自动更新后台任务。
|
||||
pub fn start_fingerprint_update_task(
|
||||
store: PgFingerprintStore,
|
||||
runtime_fingerprint: RuntimeFingerprint,
|
||||
appcast_url: String,
|
||||
extracted_fingerprint_path: PathBuf,
|
||||
current_version: String,
|
||||
current_build: String,
|
||||
) -> SchedulerHandle {
|
||||
let update_checker = UpdateChecker::with_client(
|
||||
store,
|
||||
reqwest::Client::new(),
|
||||
appcast_url,
|
||||
extracted_fingerprint_path,
|
||||
current_version,
|
||||
current_build,
|
||||
);
|
||||
spawn_periodic_task(
|
||||
FingerprintUpdateTask {
|
||||
checker: update_checker,
|
||||
runtime_fingerprint,
|
||||
first_tick: true,
|
||||
},
|
||||
PeriodicTaskConfig::new(
|
||||
APPCAST_POLL_INTERVAL.as_secs(),
|
||||
"fingerprint 后台版本检查器已启动",
|
||||
"fingerprint 后台版本检查器已关闭",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
struct FingerprintUpdateTask {
|
||||
checker: UpdateChecker,
|
||||
runtime_fingerprint: RuntimeFingerprint,
|
||||
first_tick: bool,
|
||||
}
|
||||
|
||||
impl PeriodicTaskRunner for FingerprintUpdateTask {
|
||||
fn tick(&mut self) -> super::periodic::TaskFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
let first_tick = std::mem::take(&mut self.first_tick);
|
||||
match self.checker.check_and_apply_update().await {
|
||||
Ok(Some(fingerprint)) => {
|
||||
let app_version = fingerprint.app_version.clone();
|
||||
let build_number = fingerprint.build_number.clone();
|
||||
self.runtime_fingerprint.replace(fingerprint);
|
||||
info!(
|
||||
app_version = %app_version,
|
||||
build_number = %build_number,
|
||||
"fingerprint 运行时版本已更新"
|
||||
);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
if first_tick {
|
||||
warn!(error = %error, "fingerprint 首次版本检查失败");
|
||||
} else {
|
||||
warn!(error = %error, "fingerprint 定期版本检查失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
mod cleanup;
|
||||
pub mod cookie_cleanup;
|
||||
pub mod coordinator;
|
||||
pub mod fingerprint_update;
|
||||
pub mod desktop_release_update;
|
||||
pub mod model_refresh;
|
||||
mod periodic;
|
||||
pub mod quota_refresh;
|
||||
|
||||
@@ -35,6 +35,7 @@ impl QuotaRefreshTask {
|
||||
store: PgAccountStore,
|
||||
usage_store: PgAccountUsageStore,
|
||||
codex: Arc<CodexBackendClient>,
|
||||
account_pool: Arc<AccountPoolService>,
|
||||
account_pseudonymizer: Arc<AccountPseudonymizer>,
|
||||
interval_secs: u64,
|
||||
min_refresh_interval_secs: u64,
|
||||
@@ -44,6 +45,7 @@ impl QuotaRefreshTask {
|
||||
store,
|
||||
usage_store,
|
||||
codex,
|
||||
account_pool,
|
||||
account_pseudonymizer,
|
||||
min_refresh_interval_secs,
|
||||
),
|
||||
@@ -58,18 +60,12 @@ impl QuotaRefreshTask {
|
||||
self
|
||||
}
|
||||
|
||||
/// 设置运行时账号池,用于刷新后同步内存调度状态。
|
||||
pub fn with_account_pool(mut self, account_pool: Arc<AccountPoolService>) -> Self {
|
||||
self.service = self.service.with_account_pool(account_pool);
|
||||
self
|
||||
}
|
||||
|
||||
/// 启动后台刷新任务。
|
||||
pub fn start(self) -> SchedulerHandle {
|
||||
let config = PeriodicTaskConfig::new(
|
||||
self.interval_secs,
|
||||
"quota 刷新任务已启动",
|
||||
"quota 刷新任务已关闭",
|
||||
"Quota 刷新任务已启动",
|
||||
"Quota 刷新任务已关闭",
|
||||
);
|
||||
spawn_periodic_task(self, config)
|
||||
}
|
||||
@@ -96,7 +92,7 @@ impl PeriodicTaskRunner for QuotaRefreshTask {
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
warn!(error = %error, "quota 刷新任务失败");
|
||||
warn!(error = %error, "Quota 刷新任务失败");
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -107,6 +103,6 @@ fn log_refreshed_summary(summary: QuotaRefreshSummary) {
|
||||
info!(
|
||||
refreshed = summary.refreshed,
|
||||
failed = summary.failed,
|
||||
"quota 刷新任务完成"
|
||||
"Quota 刷新任务完成"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,12 +3,9 @@
|
||||
use chrono::Utc;
|
||||
use tracing::{info, warn};
|
||||
|
||||
use crate::{
|
||||
telemetry::{
|
||||
buckets::store::PgRequestBucketStore, ops::store::PgOpsErrorLogStore,
|
||||
usage::store::PgUsageRecordStore,
|
||||
},
|
||||
upstream::openai::fingerprint::PgFingerprintStore,
|
||||
use crate::telemetry::{
|
||||
buckets::store::PgRequestBucketStore, ops::store::PgOpsErrorLogStore,
|
||||
usage::store::PgUsageRecordStore,
|
||||
};
|
||||
|
||||
use super::{
|
||||
@@ -17,13 +14,11 @@ use super::{
|
||||
};
|
||||
|
||||
const RETENTION_TRIM_INTERVAL_SECS: u64 = 60 * 60;
|
||||
const FINGERPRINT_HISTORY_LIMIT: std::num::NonZeroU32 = std::num::NonZeroU32::new(100).unwrap();
|
||||
|
||||
pub struct RetentionTrimTask {
|
||||
usage_records: PgUsageRecordStore,
|
||||
ops_errors: PgOpsErrorLogStore,
|
||||
buckets: PgRequestBucketStore,
|
||||
fingerprints: PgFingerprintStore,
|
||||
}
|
||||
|
||||
impl RetentionTrimTask {
|
||||
@@ -31,13 +26,11 @@ impl RetentionTrimTask {
|
||||
usage_records: PgUsageRecordStore,
|
||||
ops_errors: PgOpsErrorLogStore,
|
||||
buckets: PgRequestBucketStore,
|
||||
fingerprints: PgFingerprintStore,
|
||||
) -> Self {
|
||||
Self {
|
||||
usage_records,
|
||||
ops_errors,
|
||||
buckets,
|
||||
fingerprints,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,17 +63,6 @@ impl RetentionTrimTask {
|
||||
Ok(_) => {}
|
||||
Err(error) => warn!(error = %error, "清理请求时间桶失败"),
|
||||
}
|
||||
match self
|
||||
.fingerprints
|
||||
.trim_update_history_to_limit(FINGERPRINT_HISTORY_LIMIT)
|
||||
.await
|
||||
{
|
||||
Ok(deleted) if deleted > 0 => {
|
||||
info!(deleted, "已清理超限指纹更新历史")
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(error) => warn!(error = %error, "清理超限指纹更新历史失败"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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::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,88 +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(
|
||||
) -> AccountScopedRequest {
|
||||
let identity = AccountScopedIdentity {
|
||||
installation_id: self.pseudonymizer.installation_id(account_id),
|
||||
};
|
||||
let client_metadata_turn_state = client_metadata_string(&request, TURN_STATE_METADATA_KEY);
|
||||
let preserve_turn_state = scope.preserves_turn_state(
|
||||
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(),
|
||||
},
|
||||
)
|
||||
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 }
|
||||
}
|
||||
|
||||
pub fn scope_auxiliary(
|
||||
&self,
|
||||
account_id: &str,
|
||||
proxy_request_id: &str,
|
||||
) -> AccountScopedIdentity {
|
||||
pub(in crate::dispatch) fn scope_auxiliary(&self, account_id: &str) -> AccountScopedIdentity {
|
||||
AccountScopedIdentity {
|
||||
client_request_id: format!(
|
||||
"cr_{}",
|
||||
self.pseudonym("client-request-id", Some(account_id), proxy_request_id)
|
||||
),
|
||||
installation_id: self.pseudonymizer.installation_id(account_id),
|
||||
..AccountScopedIdentity::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn scope_values(
|
||||
&self,
|
||||
account_id: &str,
|
||||
proxy_request_id: &str,
|
||||
values: IdentityValues<'_>,
|
||||
) -> 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::{CodexResponsesRequest, completed_response_metadata},
|
||||
},
|
||||
};
|
||||
|
||||
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
|
||||
|
||||
@@ -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,208 @@
|
||||
//! 账号级失败分类、隔离副作用与换号决策 owner。
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
controllers::ControllerFailureFact,
|
||||
errors::ClientFailure,
|
||||
failure::exhaustion::{AccountExhaustionRecord, ExhaustedAccountKind},
|
||||
lifecycle::contract::{
|
||||
AttemptDecision, AttemptObservation, AttemptObservationKind, CompleteResponseFacts,
|
||||
},
|
||||
},
|
||||
fleet::{
|
||||
account_failure::{
|
||||
AccountFailureKind, AccountStateEffect, apply_account_state_effect_immediately,
|
||||
classify_response_failure, classify_upstream_failure,
|
||||
},
|
||||
pool::AccountPoolService,
|
||||
},
|
||||
upstream::openai::{
|
||||
failure::{UpstreamFailureFacts, UpstreamFailureKind},
|
||||
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 {
|
||||
apply_account_state_effect_immediately(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();
|
||||
if 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 code.contains("server_overloaded") {
|
||||
return Some(ClientFailure::new(failure.clone(), 503, true));
|
||||
}
|
||||
classify_response_failure(failure).map(|classified| {
|
||||
let status = match classified.kind {
|
||||
AccountFailureKind::ModelUnsupported => 400,
|
||||
AccountFailureKind::Expired => 401,
|
||||
AccountFailureKind::Disabled | AccountFailureKind::Banned => 403,
|
||||
AccountFailureKind::QuotaExhausted | AccountFailureKind::RateLimited => 429,
|
||||
};
|
||||
ClientFailure::new(failure.clone(), status, false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
classified_failure(
|
||||
account_id,
|
||||
&facts.body,
|
||||
facts.status_code,
|
||||
classify_upstream_failure(facts)?,
|
||||
)
|
||||
}
|
||||
|
||||
fn classify_sse(account_id: &str, failure: &ResponsesSseFailure) -> Option<ClassifiedFailure> {
|
||||
classified_failure(
|
||||
account_id,
|
||||
&crate::dispatch::failure::sse::sse_failure_error_body(failure),
|
||||
failure.explicit_status_code,
|
||||
classify_response_failure(failure)?,
|
||||
)
|
||||
}
|
||||
|
||||
fn classified_failure(
|
||||
account_id: &str,
|
||||
message: &str,
|
||||
status_code: Option<u16>,
|
||||
classified: crate::fleet::account_failure::ClassifiedAccountFailure,
|
||||
) -> Option<ClassifiedFailure> {
|
||||
let kind = match classified.kind {
|
||||
AccountFailureKind::ModelUnsupported => ExhaustedAccountKind::ModelUnsupported,
|
||||
AccountFailureKind::Expired => ExhaustedAccountKind::Expired,
|
||||
AccountFailureKind::Disabled => ExhaustedAccountKind::Disabled,
|
||||
AccountFailureKind::Banned => ExhaustedAccountKind::Banned,
|
||||
AccountFailureKind::QuotaExhausted | AccountFailureKind::RateLimited => return None,
|
||||
};
|
||||
let mut exhaustion = AccountExhaustionRecord::new(account_id, kind, message);
|
||||
if let Some(status_code) = status_code {
|
||||
exhaustion = exhaustion.with_status_code(status_code);
|
||||
}
|
||||
Some(ClassifiedFailure {
|
||||
exhaustion,
|
||||
effect: classified.effect,
|
||||
})
|
||||
}
|
||||
@@ -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,
|
||||
},
|
||||
fleet::{
|
||||
account::AccountStatus,
|
||||
cookies::{CloudflareChallengeCooldownTracker, CloudflarePathBlockTracker, PgCookieStore},
|
||||
pool::AccountPoolService,
|
||||
},
|
||||
upstream::openai::failure::UpstreamFailureFacts,
|
||||
};
|
||||
|
||||
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,227 @@
|
||||
//! `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},
|
||||
},
|
||||
upstream::openai::{
|
||||
failure::UpstreamFailureFacts,
|
||||
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,
|
||||
},
|
||||
},
|
||||
upstream::openai::{
|
||||
failure::{UpstreamFailureFacts, UpstreamFailureKind},
|
||||
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,998 @@
|
||||
//! 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,
|
||||
},
|
||||
},
|
||||
fleet::pool::AccountPoolService,
|
||||
upstream::openai::{
|
||||
failure::UpstreamFailureFacts,
|
||||
protocol::responses::{CodexResponsesRequest, ResponsesSseFailure},
|
||||
},
|
||||
};
|
||||
|
||||
mod account_failure;
|
||||
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,247 @@
|
||||
//! 请求前配额验证规则 owner。
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
affinity::AccountIdentityService,
|
||||
controllers::ControllerFailureFact,
|
||||
errors::ClientFailure,
|
||||
failure::exhaustion::{AccountExhaustionRecord, ExhaustedAccountKind},
|
||||
lifecycle::contract::{
|
||||
AttemptDecision, AttemptObservation, AttemptObservationKind, AttemptReturnKind,
|
||||
},
|
||||
},
|
||||
fleet::{
|
||||
account_failure::{
|
||||
AccountFailureKind, AccountStateEffect, apply_account_state_effect_immediately,
|
||||
classify_response_failure, classify_upstream_failure,
|
||||
},
|
||||
pool::{AccountLease, AccountPoolService},
|
||||
quota::{
|
||||
quota_from_usage, quota_snapshot_limit_reached, quota_snapshot_limit_window_seconds,
|
||||
quota_snapshot_reset_at,
|
||||
},
|
||||
},
|
||||
upstream::openai::{
|
||||
failure::UpstreamFailureFacts,
|
||||
protocol::responses::ResponsesSseFailure,
|
||||
transport::{CodexBackendClient, CodexRequestContext},
|
||||
},
|
||||
};
|
||||
|
||||
const LIMIT_REACHED_MESSAGE: &str = "Upstream usage quota still reports limit_reached";
|
||||
|
||||
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 {
|
||||
apply_account_state_effect_immediately(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> {
|
||||
classified_quota_failure(account_id, &facts.body, classify_upstream_failure(facts)?)
|
||||
}
|
||||
|
||||
fn classify_stream(
|
||||
account_id: &str,
|
||||
failure: &ResponsesSseFailure,
|
||||
) -> Option<ClassifiedQuotaFailure> {
|
||||
let body = crate::dispatch::failure::sse::sse_failure_error_body(failure);
|
||||
classified_quota_failure(account_id, &body, classify_response_failure(failure)?)
|
||||
}
|
||||
|
||||
fn classified_quota_failure(
|
||||
account_id: &str,
|
||||
message: &str,
|
||||
classified: crate::fleet::account_failure::ClassifiedAccountFailure,
|
||||
) -> Option<ClassifiedQuotaFailure> {
|
||||
let kind = match classified.kind {
|
||||
AccountFailureKind::RateLimited => ExhaustedAccountKind::RateLimited,
|
||||
AccountFailureKind::QuotaExhausted => ExhaustedAccountKind::QuotaExhausted,
|
||||
AccountFailureKind::ModelUnsupported
|
||||
| AccountFailureKind::Expired
|
||||
| AccountFailureKind::Disabled
|
||||
| AccountFailureKind::Banned => return None,
|
||||
};
|
||||
Some(ClassifiedQuotaFailure {
|
||||
exhaustion: AccountExhaustionRecord::new(account_id, kind, message),
|
||||
effect: classified.effect,
|
||||
})
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
+107
-82
@@ -27,17 +27,16 @@ use crate::{
|
||||
},
|
||||
};
|
||||
|
||||
use super::{
|
||||
use crate::dispatch::{
|
||||
errors::{
|
||||
ResponseDispatchError, dispatch_error_metadata, enrich_response_dispatch_error_metadata,
|
||||
},
|
||||
stream::{
|
||||
live::{LiveResponseStreamContext, latest_response_id},
|
||||
sse_failure::{status_code_for_stream_failure, stream_failure_metadata},
|
||||
trace::{ResponseDispatchAttempt, ResponseDispatchTrace},
|
||||
},
|
||||
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,
|
||||
@@ -65,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],
|
||||
@@ -86,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<'_>,
|
||||
) {
|
||||
@@ -181,14 +173,14 @@ pub(super) async fn record_response_upstream_error_event(
|
||||
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 {
|
||||
@@ -204,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,
|
||||
@@ -249,7 +243,7 @@ pub(super) async fn record_prefetched_response_stream_failure_event(
|
||||
}
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -263,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,
|
||||
@@ -286,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(
|
||||
@@ -420,6 +454,7 @@ fn response_request_summary(
|
||||
"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),
|
||||
@@ -471,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,
|
||||
@@ -483,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(
|
||||
@@ -503,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,
|
||||
@@ -511,31 +546,34 @@ pub(super) async fn record_live_response_stream_event(
|
||||
status_code,
|
||||
body,
|
||||
);
|
||||
log_live_response_stream_finalized(context, status_code, level, message, &metadata, body);
|
||||
if !is_success_usage_event(level, status_code) {
|
||||
ensure_stream_failure_class(&mut metadata);
|
||||
}
|
||||
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);
|
||||
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,
|
||||
@@ -546,18 +584,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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -566,24 +604,31 @@ fn is_success_usage_event(level: UsageRecordLevel, status_code: i64) -> bool {
|
||||
level != UsageRecordLevel::Error && status_code < 400
|
||||
}
|
||||
|
||||
fn ensure_stream_failure_class(metadata: &mut Value) {
|
||||
let failure_class = ["failureClass", "upstreamCode", "terminal"]
|
||||
.into_iter()
|
||||
.find_map(|field| metadata_string_field(metadata, field))
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToString::to_string);
|
||||
let (Some(failure_class), Some(object)) = (failure_class, metadata.as_object_mut()) else {
|
||||
return;
|
||||
};
|
||||
object.insert("failureClass".to_string(), Value::String(failure_class));
|
||||
}
|
||||
|
||||
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");
|
||||
@@ -604,7 +649,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),
|
||||
@@ -614,7 +658,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"
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -639,25 +683,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,
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
-137
@@ -1,13 +1,12 @@
|
||||
//! Shared upstream error classification for dispatch routes.
|
||||
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
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},
|
||||
prefetch::{PrefetchedStream, StreamPrefetchError, prefetch_until_commit},
|
||||
},
|
||||
},
|
||||
fleet::{
|
||||
account::Account,
|
||||
pool::{AccountCandidateLease, AccountPoolService},
|
||||
},
|
||||
upstream::openai::{
|
||||
failure::upstream_failure_facts,
|
||||
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,282 @@
|
||||
//! Attempt lifecycle 的类型化 observation、decision 与结果。
|
||||
|
||||
use bytes::Bytes;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
errors::{ClientFailure, ResponseDispatchError},
|
||||
failure::exhaustion::{AccountExhaustionRecord, ExhaustedAccount},
|
||||
transport::canonical::{CanonicalStreamBatch, CanonicalStreamDecoder},
|
||||
},
|
||||
fleet::{account::Account, pool::AccountLease},
|
||||
upstream::openai::{
|
||||
failure::UpstreamFailureFacts,
|
||||
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,205 @@
|
||||
//! 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;
|
||||
let mut lease_completion = Box::pin(account_lease.complete());
|
||||
if timeout(LEASE_FINALIZE_TIMEOUT, lease_completion.as_mut())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!(
|
||||
timeout_ms = LEASE_FINALIZE_TIMEOUT.as_millis(),
|
||||
"Response account lease is continuing finalization in the background"
|
||||
);
|
||||
// 超时只约束客户端收尾,不取消已经开始的 slot 释放与请求用量持久化。
|
||||
drop(tokio::spawn(lease_completion));
|
||||
}
|
||||
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::{
|
||||
CloudflareRecovery, cloudflare_challenge_error_message,
|
||||
cloudflare_path_block_error_message, is_cloudflare_challenge_upstream_error,
|
||||
is_cloudflare_path_block_upstream_error,
|
||||
},
|
||||
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::{CodexClientError, is_banned_upstream_error},
|
||||
},
|
||||
};
|
||||
|
||||
/// 处理需要隔离当前账号并交回调度器选择下一候选的上游失败。
|
||||
///
|
||||
/// 本函数不选择下一个账号,也不实现固定轮换策略;调用方继续使用请求级候选账本,
|
||||
/// 因而始终服从当前运行时调度策略。
|
||||
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::{CodexClientError, is_banned_auth_signal},
|
||||
};
|
||||
|
||||
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::{
|
||||
SessionAffinityEntry, SessionAffinityService,
|
||||
service::{MAX_REPLAY_DEPTH, MAX_REPLAY_SESSION_BYTES, MAX_REPLAY_SNAPSHOT_BYTES},
|
||||
types::ResponseReplaySnapshot,
|
||||
},
|
||||
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;
|
||||
+209
-489
@@ -10,69 +10,44 @@
|
||||
use std::{pin::Pin, sync::Arc, time::Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use chrono::Utc;
|
||||
use futures::stream::Stream;
|
||||
use serde_json::{Value, json};
|
||||
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::{
|
||||
AccountUpstreamContext, QUOTA_VERIFY_LIMIT_REACHED_MESSAGE, QuotaVerificationContext,
|
||||
QuotaVerificationDecision, create_response_with_account_retrying_5xx,
|
||||
verify_acquired_quota_if_required,
|
||||
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::{
|
||||
Recorder, enrich_response_request_semantics, reasoning_effort_from_request,
|
||||
record_response_event,
|
||||
},
|
||||
usage::types::ResponseUsageRecord,
|
||||
},
|
||||
telemetry::recorder::Recorder,
|
||||
upstream::openai::{
|
||||
protocol::{
|
||||
events::TokenUsage,
|
||||
responses::{CodexResponsesRequest, CollectedResponse, response_from_codex_sse},
|
||||
},
|
||||
transport::{
|
||||
CodexBackendClient, CodexBackendResponse, backend_transport_for_response_request,
|
||||
},
|
||||
protocol::{responses::CodexResponsesRequest, sse::SseError},
|
||||
transport::CodexBackendClient,
|
||||
},
|
||||
};
|
||||
|
||||
use super::{
|
||||
errors::{ResponseDispatchError, ResponseDispatchStreamError},
|
||||
recording::{
|
||||
ResponseDispatchErrorDetails, ResponseDispatchErrorEventRecord,
|
||||
ResponseUpstreamErrorEventRecord, 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,
|
||||
},
|
||||
stream::{
|
||||
sse_failure::is_history_recovery_sse_failure,
|
||||
trace::{ResponseDispatchAttempt, ResponseDispatchTrace},
|
||||
},
|
||||
};
|
||||
use super::errors::{ResponseDispatchError, ResponseDispatchStreamError};
|
||||
|
||||
/// OpenAI Responses 调度服务。
|
||||
#[derive(Clone)]
|
||||
@@ -84,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 {
|
||||
@@ -94,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 响应体流。
|
||||
@@ -103,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)>,
|
||||
}
|
||||
|
||||
@@ -112,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 {
|
||||
@@ -122,471 +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 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);
|
||||
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,
|
||||
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,
|
||||
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);
|
||||
enrich_response_request_semantics(&mut metadata, &request);
|
||||
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,
|
||||
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,
|
||||
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,
|
||||
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::{
|
||||
ResponseDispatchError, 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,
|
||||
controllers::{
|
||||
ControllerSet, DispatchErrorObservation, PrefetchedStreamFailureObservation,
|
||||
StreamControllerContext,
|
||||
},
|
||||
recording::{
|
||||
ResponseDispatchErrorDetails, ResponseStreamFailureEventRecord,
|
||||
ResponseUpstreamErrorEventRecord, record_prefetched_response_stream_failure_event,
|
||||
record_response_upstream_error_event,
|
||||
},
|
||||
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::{LiveResponseStreamContext, spawn_live_response_stream},
|
||||
prefetch::prefetch_first_sse_chunk,
|
||||
sse_failure::{
|
||||
first_sse_failure, is_history_recovery_sse_failure, sse_failure_error_body,
|
||||
},
|
||||
trace::ResponseDispatchTrace,
|
||||
},
|
||||
upstream_call::{
|
||||
AccountUpstreamContext, QUOTA_VERIFY_LIMIT_REACHED_MESSAGE, QuotaVerificationContext,
|
||||
QuotaVerificationDecision, create_response_stream_with_account_retrying_5xx,
|
||||
verify_acquired_quota_if_required,
|
||||
},
|
||||
},
|
||||
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,442 +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 compact = request.semantics().compact;
|
||||
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,
|
||||
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,
|
||||
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(),
|
||||
))
|
||||
}
|
||||
|
||||
+257
-485
@@ -1,57 +1,32 @@
|
||||
use std::{
|
||||
pin::Pin,
|
||||
sync::Arc,
|
||||
task::{Context, Poll},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::{StreamExt, stream::Stream};
|
||||
use serde_json::Value;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
affinity::{SessionAffinityService, resolve::record_response_affinity},
|
||||
errors::{ResponseDispatchStreamError, backend_transport_name},
|
||||
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::{
|
||||
CodexResponsesRequest, CollectedResponse,
|
||||
reconvert_responses_sse_event_tuple_values, response_from_codex_sse,
|
||||
response_sse_event_is_terminal, update_first_response_output_ms,
|
||||
},
|
||||
sse::{
|
||||
DONE_SSE_FRAME, encode_sse_event, parse_sse_events,
|
||||
response_failed_sse_event_with_id, sse_body_has_done, sse_frame_end,
|
||||
},
|
||||
},
|
||||
transport::{
|
||||
CodexBackendSseStream, CodexBackendTransport, CodexRateLimitHeaderUpdates,
|
||||
CodexResponseMetadata, CodexTurnStateUpdate, CodexUpstreamDiagnostics,
|
||||
WebSocketPoolDecision,
|
||||
},
|
||||
},
|
||||
upstream::openai::transport::CodexBackendSseStream,
|
||||
};
|
||||
|
||||
use super::{
|
||||
sse_failure::{
|
||||
STREAM_DISCONNECTED_CODE, STREAM_DISCONNECTED_MESSAGE, status_code_for_stream_failure,
|
||||
stream_failure_metadata, stream_failure_source, synthetic_stream_disconnected_detail,
|
||||
},
|
||||
trace::ResponseDispatchAttempt,
|
||||
};
|
||||
const MAX_LIVE_RESPONSE_CAPTURE_BYTES: usize = 16 * 1024 * 1024;
|
||||
|
||||
struct MpscResponseBodyStream {
|
||||
receiver: mpsc::Receiver<Result<Bytes, ResponseDispatchStreamError>>,
|
||||
@@ -75,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 {
|
||||
@@ -181,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::{SseError, sse_frame_end},
|
||||
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::{CollectedResponse, ResponsesSseFailure, response_from_codex_sse},
|
||||
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,5 @@
|
||||
//! Attempt 阶段的账号作用域上游调用与流规范化。
|
||||
|
||||
pub(in crate::dispatch) mod account;
|
||||
pub(crate) mod canonical;
|
||||
pub(in crate::dispatch) mod prefetch;
|
||||
@@ -0,0 +1,80 @@
|
||||
//! 上游 SSE 提交边界前的规范事件预取。
|
||||
|
||||
use bytes::Bytes;
|
||||
use std::time::Instant;
|
||||
|
||||
use futures::StreamExt;
|
||||
|
||||
use crate::{
|
||||
dispatch::transport::canonical::{CanonicalStreamBatch, CanonicalStreamDecoder},
|
||||
upstream::openai::{
|
||||
protocol::{responses::StreamCommitPolicy, sse::SseError},
|
||||
transport::{CodexBackendSseStream, CodexClientError},
|
||||
},
|
||||
};
|
||||
|
||||
const MAX_STREAM_PREFETCH_BYTES: usize = 64 * 1024;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(in crate::dispatch) enum StreamPrefetchError {
|
||||
#[error("upstream stream failed before the commit boundary: {0}")]
|
||||
Upstream(#[from] CodexClientError),
|
||||
#[error("upstream stream ended without any data")]
|
||||
Empty,
|
||||
#[error("upstream stream ended before output or a terminal event")]
|
||||
NoCommitBoundary,
|
||||
#[error("invalid upstream SSE response: {0}")]
|
||||
InvalidSse(#[from] SseError),
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) struct PrefetchedStream {
|
||||
pub bytes: Bytes,
|
||||
pub initial_batch: CanonicalStreamBatch,
|
||||
pub body: CodexBackendSseStream,
|
||||
pub first_event_ms: i64,
|
||||
}
|
||||
|
||||
pub(in crate::dispatch) async fn prefetch_until_commit(
|
||||
mut body: CodexBackendSseStream,
|
||||
decoder: &mut CanonicalStreamDecoder,
|
||||
policy: StreamCommitPolicy,
|
||||
started_at: Instant,
|
||||
) -> Result<PrefetchedStream, StreamPrefetchError> {
|
||||
let mut prefetched = Vec::new();
|
||||
let mut initial_batch = CanonicalStreamBatch { chunks: Vec::new() };
|
||||
let mut first_event_ms = None;
|
||||
while !decoder.commit_boundary_reached(policy) {
|
||||
let Some(next) = body.next().await else {
|
||||
if prefetched.is_empty() {
|
||||
return Err(StreamPrefetchError::Empty);
|
||||
}
|
||||
initial_batch.append(decoder.finish()?);
|
||||
if decoder.commit_boundary_reached(policy) {
|
||||
break;
|
||||
}
|
||||
return Err(StreamPrefetchError::NoCommitBoundary);
|
||||
};
|
||||
let chunk = next?;
|
||||
first_event_ms
|
||||
.get_or_insert_with(|| crate::infra::time::elapsed_millis_i64(started_at).max(1));
|
||||
prefetched.extend_from_slice(&chunk);
|
||||
let batch = decoder.push(chunk)?;
|
||||
initial_batch.append(batch);
|
||||
if decoder.transport_done_seen() && !decoder.commit_boundary_reached(policy) {
|
||||
return Err(StreamPrefetchError::NoCommitBoundary);
|
||||
}
|
||||
if !decoder.commit_boundary_reached(policy) && prefetched.len() > MAX_STREAM_PREFETCH_BYTES
|
||||
{
|
||||
return Err(StreamPrefetchError::InvalidSse(SseError::BufferExceeded {
|
||||
max_bytes: MAX_STREAM_PREFETCH_BYTES,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(PrefetchedStream {
|
||||
bytes: Bytes::from(prefetched),
|
||||
initial_batch,
|
||||
body,
|
||||
first_event_ms: first_event_ms.ok_or(StreamPrefetchError::Empty)?,
|
||||
})
|
||||
}
|
||||
@@ -1,318 +0,0 @@
|
||||
//! 调度层共享的账号级 Codex 上游调用。
|
||||
|
||||
use std::{future::Future, time::Instant};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
dispatch::{
|
||||
affinity::AccountIdentityService, errors::is_retryable_upstream_5xx_error,
|
||||
recovery::cloudflare::CloudflareRecovery,
|
||||
},
|
||||
fleet::{
|
||||
account::Account,
|
||||
pool::{AccountLease, AccountPoolService},
|
||||
quota::{
|
||||
quota_from_usage, quota_snapshot_limit_reached, quota_snapshot_limit_window_seconds,
|
||||
quota_snapshot_reset_at,
|
||||
},
|
||||
},
|
||||
upstream::openai::{
|
||||
protocol::responses::CodexResponsesRequest,
|
||||
transport::{
|
||||
CodexBackendClient, CodexBackendResponse, CodexBackendStreamingResponse,
|
||||
CodexClientError, CodexRequestContext,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
pub(crate) const QUOTA_VERIFY_LIMIT_REACHED_MESSAGE: &str =
|
||||
"Upstream usage quota still reports limit_reached";
|
||||
|
||||
pub(crate) enum QuotaVerificationDecision {
|
||||
Ready(Box<AccountLease>),
|
||||
RetryWithAnotherAccount,
|
||||
}
|
||||
|
||||
pub(crate) struct QuotaVerificationContext<'a> {
|
||||
pub account_pool: &'a AccountPoolService,
|
||||
pub codex: &'a CodexBackendClient,
|
||||
pub cloudflare: &'a CloudflareRecovery,
|
||||
pub account_identity: &'a AccountIdentityService,
|
||||
pub request_id: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct AccountUpstreamContext<'a> {
|
||||
pub codex: &'a CodexBackendClient,
|
||||
pub account_identity: &'a AccountIdentityService,
|
||||
pub cloudflare: &'a CloudflareRecovery,
|
||||
pub request_id: &'a str,
|
||||
pub account: &'a Account,
|
||||
}
|
||||
|
||||
pub(crate) async fn verify_acquired_quota_if_required(
|
||||
context: QuotaVerificationContext<'_>,
|
||||
acquired: AccountLease,
|
||||
) -> QuotaVerificationDecision {
|
||||
if !acquired.account.quota_verify_required {
|
||||
return QuotaVerificationDecision::Ready(Box::new(acquired));
|
||||
}
|
||||
|
||||
let account_id = acquired.account.id.clone();
|
||||
let identity = context
|
||||
.account_identity
|
||||
.scope_auxiliary(&account_id, context.request_id);
|
||||
let cookie_header = context
|
||||
.cloudflare
|
||||
.cookie_header_for_request(&account_id, "/codex/usage")
|
||||
.await;
|
||||
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: cookie_header.as_deref(),
|
||||
installation_id: Some(&identity.installation_id),
|
||||
session_id: None,
|
||||
thread_id: None,
|
||||
prompt_cache_key: None,
|
||||
client_request_id: Some(&identity.client_request_id),
|
||||
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 QuotaVerificationDecision::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 QuotaVerificationDecision::RetryWithAnotherAccount;
|
||||
}
|
||||
|
||||
QuotaVerificationDecision::Ready(Box::new(acquired_with_verified_quota(acquired, "a)))
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
pub(crate) async fn create_response_with_account(
|
||||
context: AccountUpstreamContext<'_>,
|
||||
request: &CodexResponsesRequest,
|
||||
started_at: Instant,
|
||||
) -> Result<CodexBackendResponse, CodexClientError> {
|
||||
let cookie_header = context
|
||||
.cloudflare
|
||||
.cookie_header_for_request(&context.account.id, "/codex/responses")
|
||||
.await;
|
||||
let identity = context
|
||||
.account_identity
|
||||
.scope(request, &context.account.id, context.request_id);
|
||||
context
|
||||
.codex
|
||||
.create_response_with_pool_account_started_at(
|
||||
request,
|
||||
CodexRequestContext {
|
||||
access_token: &context.account.access_token,
|
||||
account_id: context.account.account_id.as_deref(),
|
||||
request_id: context.request_id,
|
||||
turn_state: request.turn_state.as_deref(),
|
||||
turn_metadata: request.turn_metadata.as_deref(),
|
||||
beta_features: request.beta_features.as_deref(),
|
||||
include_timing_metrics: request.include_timing_metrics.as_deref(),
|
||||
version: request.version.as_deref(),
|
||||
codex_window_id: identity.window_id.as_deref(),
|
||||
parent_thread_id: identity.parent_thread_id.as_deref(),
|
||||
cookie_header: cookie_header.as_deref(),
|
||||
installation_id: Some(&identity.installation_id),
|
||||
session_id: identity.session_id.as_deref(),
|
||||
thread_id: identity.thread_id.as_deref(),
|
||||
prompt_cache_key: identity.prompt_cache_key.as_deref(),
|
||||
client_request_id: Some(&identity.client_request_id),
|
||||
turn_id: identity.turn_id.as_deref(),
|
||||
},
|
||||
Some(&context.account.id),
|
||||
started_at,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn create_response_stream_with_account(
|
||||
context: AccountUpstreamContext<'_>,
|
||||
request: &CodexResponsesRequest,
|
||||
) -> Result<CodexBackendStreamingResponse, CodexClientError> {
|
||||
let cookie_header = context
|
||||
.cloudflare
|
||||
.cookie_header_for_request(&context.account.id, "/codex/responses")
|
||||
.await;
|
||||
let identity = context
|
||||
.account_identity
|
||||
.scope(request, &context.account.id, context.request_id);
|
||||
context
|
||||
.codex
|
||||
.create_response_stream_with_pool_account(
|
||||
request,
|
||||
CodexRequestContext {
|
||||
access_token: &context.account.access_token,
|
||||
account_id: context.account.account_id.as_deref(),
|
||||
request_id: context.request_id,
|
||||
turn_state: request.turn_state.as_deref(),
|
||||
turn_metadata: request.turn_metadata.as_deref(),
|
||||
beta_features: request.beta_features.as_deref(),
|
||||
include_timing_metrics: request.include_timing_metrics.as_deref(),
|
||||
version: request.version.as_deref(),
|
||||
codex_window_id: identity.window_id.as_deref(),
|
||||
parent_thread_id: identity.parent_thread_id.as_deref(),
|
||||
cookie_header: cookie_header.as_deref(),
|
||||
installation_id: Some(&identity.installation_id),
|
||||
session_id: identity.session_id.as_deref(),
|
||||
thread_id: identity.thread_id.as_deref(),
|
||||
prompt_cache_key: identity.prompt_cache_key.as_deref(),
|
||||
client_request_id: Some(&identity.client_request_id),
|
||||
turn_id: identity.turn_id.as_deref(),
|
||||
},
|
||||
Some(&context.account.id),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
const MAX_UPSTREAM_5XX_RETRIES_PER_ACCOUNT: usize = 2;
|
||||
|
||||
async fn retry_upstream_5xx<T, F, Fut>(
|
||||
request_id: &str,
|
||||
account_id: &str,
|
||||
endpoint: Option<&str>,
|
||||
retry_message: &'static str,
|
||||
mut operation: F,
|
||||
) -> Result<T, CodexClientError>
|
||||
where
|
||||
F: FnMut() -> Fut,
|
||||
Fut: Future<Output = Result<T, CodexClientError>>,
|
||||
{
|
||||
let mut retries = 0;
|
||||
loop {
|
||||
let result = operation().await;
|
||||
match result {
|
||||
Err(error)
|
||||
if is_retryable_upstream_5xx_error(&error)
|
||||
&& retries < MAX_UPSTREAM_5XX_RETRIES_PER_ACCOUNT =>
|
||||
{
|
||||
log_upstream_retry(
|
||||
request_id,
|
||||
account_id,
|
||||
endpoint,
|
||||
retries + 1,
|
||||
&error,
|
||||
retry_message,
|
||||
);
|
||||
retries += 1;
|
||||
}
|
||||
Ok(response) => return Ok(response),
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn log_upstream_retry(
|
||||
request_id: &str,
|
||||
account_id: &str,
|
||||
endpoint: Option<&str>,
|
||||
retry: usize,
|
||||
error: &CodexClientError,
|
||||
message: &'static str,
|
||||
) {
|
||||
if let Some(endpoint) = endpoint {
|
||||
tracing::debug!(
|
||||
request_id,
|
||||
account_id = %account_id,
|
||||
endpoint,
|
||||
retry,
|
||||
error = %error,
|
||||
message
|
||||
);
|
||||
} else {
|
||||
tracing::debug!(
|
||||
request_id,
|
||||
account_id = %account_id,
|
||||
retry,
|
||||
error = %error,
|
||||
message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn create_response_with_account_retrying_5xx(
|
||||
context: AccountUpstreamContext<'_>,
|
||||
request: &CodexResponsesRequest,
|
||||
started_at: Instant,
|
||||
) -> Result<CodexBackendResponse, CodexClientError> {
|
||||
retry_upstream_5xx(
|
||||
context.request_id,
|
||||
&context.account.id,
|
||||
None,
|
||||
"upstream response request failed with retryable 5xx",
|
||||
|| create_response_with_account(context, request, started_at),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn create_response_stream_with_account_retrying_5xx(
|
||||
context: AccountUpstreamContext<'_>,
|
||||
request: &CodexResponsesRequest,
|
||||
) -> Result<CodexBackendStreamingResponse, CodexClientError> {
|
||||
retry_upstream_5xx(
|
||||
context.request_id,
|
||||
&context.account.id,
|
||||
None,
|
||||
"upstream response stream request failed with retryable 5xx",
|
||||
|| create_response_stream_with_account(context, request),
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
//! 上游失败到账号状态 effect 的唯一领域分类。
|
||||
|
||||
use chrono::{Duration, Utc};
|
||||
|
||||
use crate::{
|
||||
fleet::{account::AccountStatus, pool::AccountPoolService},
|
||||
upstream::openai::{
|
||||
failure::{UpstreamFailureFacts, upstream_failure_facts},
|
||||
protocol::responses::ResponsesSseFailure,
|
||||
transport::{CodexBackendClient, CodexClientError},
|
||||
},
|
||||
};
|
||||
|
||||
const DEFAULT_RATE_LIMIT_RETRY_SECONDS: u64 = 60;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AccountFailureKind {
|
||||
ModelUnsupported,
|
||||
Expired,
|
||||
Disabled,
|
||||
Banned,
|
||||
QuotaExhausted,
|
||||
RateLimited,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AccountStateEffect {
|
||||
SetStatus(AccountStatus),
|
||||
MarkQuotaLimitedUntil(chrono::DateTime<Utc>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClassifiedAccountFailure {
|
||||
pub kind: AccountFailureKind,
|
||||
pub effect: Option<AccountStateEffect>,
|
||||
}
|
||||
|
||||
impl ClassifiedAccountFailure {
|
||||
pub fn account_status(&self) -> Option<AccountStatus> {
|
||||
match self.effect.as_ref()? {
|
||||
AccountStateEffect::SetStatus(status) => Some(*status),
|
||||
AccountStateEffect::MarkQuotaLimitedUntil(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn classify_client_failure(error: &CodexClientError) -> Option<ClassifiedAccountFailure> {
|
||||
classify_upstream_failure(&upstream_failure_facts(error))
|
||||
}
|
||||
|
||||
pub fn classify_upstream_failure(facts: &UpstreamFailureFacts) -> Option<ClassifiedAccountFailure> {
|
||||
classify_failure(FailureFields {
|
||||
status_code: facts.status_code,
|
||||
code: facts.code.as_deref(),
|
||||
error_type: facts.error_type.as_deref(),
|
||||
message: &facts.message,
|
||||
body: &facts.body,
|
||||
retry_after_seconds: facts.retry_after_seconds,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn classify_response_failure(
|
||||
failure: &ResponsesSseFailure,
|
||||
) -> Option<ClassifiedAccountFailure> {
|
||||
classify_failure(FailureFields {
|
||||
status_code: failure.explicit_status_code,
|
||||
code: failure.upstream_code.as_deref(),
|
||||
error_type: failure.upstream_type.as_deref(),
|
||||
message: &failure.message,
|
||||
body: &failure.message,
|
||||
retry_after_seconds: failure.retry_after_seconds,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn apply_account_state_effect_immediately(
|
||||
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;
|
||||
}
|
||||
|
||||
pub async fn apply_account_state_effect(
|
||||
account_pool: &AccountPoolService,
|
||||
codex: &CodexBackendClient,
|
||||
account_id: &str,
|
||||
effect: &AccountStateEffect,
|
||||
) -> bool {
|
||||
let updated = match effect {
|
||||
AccountStateEffect::SetStatus(status) => account_pool.set_status(account_id, *status).await,
|
||||
AccountStateEffect::MarkQuotaLimitedUntil(until) => {
|
||||
account_pool
|
||||
.mark_quota_limited_until(account_id, *until)
|
||||
.await
|
||||
}
|
||||
};
|
||||
codex.evict_websocket_account(account_id).await;
|
||||
updated
|
||||
}
|
||||
|
||||
pub async fn apply_client_failure_effect(
|
||||
account_pool: &AccountPoolService,
|
||||
codex: &CodexBackendClient,
|
||||
account_id: &str,
|
||||
error: &CodexClientError,
|
||||
) -> Option<ClassifiedAccountFailure> {
|
||||
let classified = classify_client_failure(error)?;
|
||||
if let Some(effect) = &classified.effect {
|
||||
apply_account_state_effect(account_pool, codex, account_id, effect).await;
|
||||
}
|
||||
Some(classified)
|
||||
}
|
||||
|
||||
struct FailureFields<'a> {
|
||||
status_code: Option<u16>,
|
||||
code: Option<&'a str>,
|
||||
error_type: Option<&'a str>,
|
||||
message: &'a str,
|
||||
body: &'a str,
|
||||
retry_after_seconds: Option<u64>,
|
||||
}
|
||||
|
||||
fn classify_failure(fields: FailureFields<'_>) -> Option<ClassifiedAccountFailure> {
|
||||
let code = fields.code.unwrap_or_default();
|
||||
let error_type = fields.error_type.unwrap_or_default();
|
||||
|
||||
if [code, fields.message, fields.body]
|
||||
.into_iter()
|
||||
.any(is_model_unsupported)
|
||||
{
|
||||
return Some(classified(AccountFailureKind::ModelUnsupported, None));
|
||||
}
|
||||
if let Some(status) = explicit_account_status(code, error_type, fields.message)
|
||||
.or_else(|| explicit_account_status(code, error_type, fields.body))
|
||||
{
|
||||
return Some(status_failure(status));
|
||||
}
|
||||
if fields.status_code == Some(403) && !is_html(fields.body) {
|
||||
return Some(status_failure(AccountStatus::Banned));
|
||||
}
|
||||
if fields.status_code == Some(401) {
|
||||
return Some(status_failure(AccountStatus::Expired));
|
||||
}
|
||||
|
||||
let quota_kind = [code, error_type]
|
||||
.into_iter()
|
||||
.find_map(classify_quota_signal)
|
||||
.or_else(|| classify_quota_message(fields.message))
|
||||
.or_else(|| classify_quota_message(fields.body))
|
||||
.or(match fields.status_code {
|
||||
Some(429) => Some(AccountFailureKind::RateLimited),
|
||||
Some(402) => Some(AccountFailureKind::QuotaExhausted),
|
||||
_ => None,
|
||||
})?;
|
||||
Some(match quota_kind {
|
||||
AccountFailureKind::RateLimited => {
|
||||
let seconds = fields
|
||||
.retry_after_seconds
|
||||
.unwrap_or(DEFAULT_RATE_LIMIT_RETRY_SECONDS)
|
||||
.min(i64::MAX as u64) as i64;
|
||||
classified(
|
||||
AccountFailureKind::RateLimited,
|
||||
Some(AccountStateEffect::MarkQuotaLimitedUntil(
|
||||
Utc::now() + Duration::seconds(seconds),
|
||||
)),
|
||||
)
|
||||
}
|
||||
AccountFailureKind::QuotaExhausted => classified(
|
||||
AccountFailureKind::QuotaExhausted,
|
||||
Some(AccountStateEffect::SetStatus(AccountStatus::QuotaExhausted)),
|
||||
),
|
||||
AccountFailureKind::ModelUnsupported
|
||||
| AccountFailureKind::Expired
|
||||
| AccountFailureKind::Disabled
|
||||
| AccountFailureKind::Banned => unreachable!("quota classifier returned account status"),
|
||||
})
|
||||
}
|
||||
|
||||
fn status_failure(status: AccountStatus) -> ClassifiedAccountFailure {
|
||||
let kind = match status {
|
||||
AccountStatus::Expired => AccountFailureKind::Expired,
|
||||
AccountStatus::Disabled => AccountFailureKind::Disabled,
|
||||
AccountStatus::Banned => AccountFailureKind::Banned,
|
||||
AccountStatus::Active | AccountStatus::QuotaExhausted => {
|
||||
unreachable!("explicit account failure must make the account unavailable")
|
||||
}
|
||||
};
|
||||
classified(kind, Some(AccountStateEffect::SetStatus(status)))
|
||||
}
|
||||
|
||||
fn classified(
|
||||
kind: AccountFailureKind,
|
||||
effect: Option<AccountStateEffect>,
|
||||
) -> ClassifiedAccountFailure {
|
||||
ClassifiedAccountFailure { kind, effect }
|
||||
}
|
||||
|
||||
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")
|
||||
|| code == "forbidden"
|
||||
|| error_type == "permission_error"
|
||||
{
|
||||
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 classify_quota_signal(signal: &str) -> Option<AccountFailureKind> {
|
||||
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(AccountFailureKind::RateLimited),
|
||||
"quota_exhausted"
|
||||
| "quota_exceeded"
|
||||
| "payment_required"
|
||||
| "insufficient_quota"
|
||||
| "workspace_owner_credits_depleted"
|
||||
| "workspace_member_credits_depleted" => Some(AccountFailureKind::QuotaExhausted),
|
||||
signal if signal.starts_with("billing_limit") => Some(AccountFailureKind::QuotaExhausted),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_quota_message(message: &str) -> Option<AccountFailureKind> {
|
||||
let message = message.to_ascii_lowercase();
|
||||
if message.contains("rate limit") || message.contains("usage limit") {
|
||||
return Some(AccountFailureKind::RateLimited);
|
||||
}
|
||||
if message.contains("quota")
|
||||
|| message.contains("payment required")
|
||||
|| message.contains("billing limit")
|
||||
{
|
||||
return Some(AccountFailureKind::QuotaExhausted);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
@@ -321,6 +321,8 @@ impl CloudflarePathBlockTracker {
|
||||
/// 记录一次 path-block 失败,并返回当前未过期次数。
|
||||
pub async fn record_path_block(&self, account_id: &str, now: DateTime<Utc>) -> u32 {
|
||||
let mut counts = self.counts.write().await;
|
||||
counts
|
||||
.retain(|_, state| now.signed_duration_since(state.last_at) <= PATH_BLOCK_STALE_AFTER);
|
||||
let count = counts
|
||||
.get(account_id)
|
||||
.filter(|state| now.signed_duration_since(state.last_at) <= PATH_BLOCK_STALE_AFTER)
|
||||
@@ -377,6 +379,9 @@ impl CloudflareChallengeCooldownTracker {
|
||||
) -> CloudflareChallengeCooldown {
|
||||
let challenge_count = {
|
||||
let mut states = self.states.write().await;
|
||||
states.retain(|_, state| {
|
||||
now.signed_duration_since(state.updated_at) <= CHALLENGE_STALE_AFTER
|
||||
});
|
||||
let challenge_count = states
|
||||
.get(account_id)
|
||||
.filter(|state| {
|
||||
|
||||
@@ -208,7 +208,6 @@ impl AccountManageService {
|
||||
installation_id: installation_id.as_deref(),
|
||||
session_id: None,
|
||||
thread_id: None,
|
||||
prompt_cache_key: None,
|
||||
client_request_id: None,
|
||||
turn_id: None,
|
||||
};
|
||||
@@ -229,7 +228,7 @@ impl AccountManageService {
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
error = %error,
|
||||
"failed to fetch supplemental account information during import"
|
||||
"Failed to fetch supplemental account information during import"
|
||||
);
|
||||
ImportSupplementalAccountInfo {
|
||||
status: import_status_from_usage_error(&error),
|
||||
|
||||
@@ -17,6 +17,7 @@ const OPENAI_OAUTH_AUTHORIZE_ENDPOINT: &str = "https://auth.openai.com/oauth/aut
|
||||
const OPENAI_OAUTH_REDIRECT_URI: &str = "http://localhost:1455/auth/callback";
|
||||
const OPENAI_OAUTH_SCOPE: &str = "openid profile email offline_access";
|
||||
const OAUTH_SESSION_TTL_MINUTES: i64 = 30;
|
||||
const MAX_PENDING_OAUTH_SESSIONS: usize = 1_024;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AccountOAuthService {
|
||||
@@ -51,6 +52,14 @@ impl AccountOAuthService {
|
||||
|
||||
let mut sessions = self.sessions.lock().await;
|
||||
sessions.retain(|_, session| session.expires_at > now);
|
||||
if sessions.len() >= MAX_PENDING_OAUTH_SESSIONS
|
||||
&& let Some(oldest_id) = sessions
|
||||
.iter()
|
||||
.min_by_key(|(_, session)| session.expires_at)
|
||||
.map(|(session_id, _)| session_id.clone())
|
||||
{
|
||||
sessions.remove(&oldest_id);
|
||||
}
|
||||
sessions.insert(session_id.clone(), session);
|
||||
drop(sessions);
|
||||
|
||||
|
||||
@@ -7,16 +7,18 @@ use serde_json::{Value, json};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::{
|
||||
fleet::{account::AccountStatus, store::StoredAccount},
|
||||
fleet::{
|
||||
account::AccountStatus,
|
||||
account_failure::{classify_client_failure, classify_response_failure},
|
||||
store::StoredAccount,
|
||||
},
|
||||
models::{service::ModelRefreshPlanAccount, types::CodexModelInfo},
|
||||
upstream::openai::{
|
||||
protocol::{
|
||||
responses::{CodexResponsesRequest, ResponsesSseFailure},
|
||||
sse::{SseEvent, encode_sse_event, parse_sse_events},
|
||||
},
|
||||
transport::{
|
||||
CodexClientError, CodexRequestContext, is_banned_auth_signal, is_banned_upstream_error,
|
||||
},
|
||||
transport::{CodexClientError, CodexRequestContext},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -103,7 +105,7 @@ impl AccountManageService {
|
||||
account_id = %account.id,
|
||||
plan_type,
|
||||
error = %error,
|
||||
"failed to refresh account plan models"
|
||||
"Failed to refresh account plan models"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -171,7 +173,6 @@ impl AccountManageService {
|
||||
installation_id: Some(&installation_id),
|
||||
session_id: None,
|
||||
thread_id: None,
|
||||
prompt_cache_key: None,
|
||||
client_request_id: None,
|
||||
turn_id: None,
|
||||
};
|
||||
@@ -214,7 +215,7 @@ impl AccountManageService {
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"failed to inspect account after connection test"
|
||||
"Failed to inspect account after connection test"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
@@ -231,7 +232,7 @@ impl AccountManageService {
|
||||
account_id,
|
||||
status = %status,
|
||||
error = %error,
|
||||
"failed to persist account status after connection test"
|
||||
"Failed to persist account status after connection test"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
@@ -243,7 +244,7 @@ impl AccountManageService {
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"failed to clear token refresh schedule after connection test"
|
||||
"Failed to clear token refresh schedule after connection test"
|
||||
);
|
||||
}
|
||||
self.sync_account_pool_best_effort(account_id, "connection test")
|
||||
@@ -367,54 +368,11 @@ async fn process_sse_event(
|
||||
}
|
||||
|
||||
fn account_status_from_client_error(error: &CodexClientError) -> Option<AccountStatus> {
|
||||
if is_banned_upstream_error(error) {
|
||||
Some(AccountStatus::Banned)
|
||||
} else {
|
||||
match error {
|
||||
CodexClientError::Upstream { status, .. } if status.as_u16() == 402 => {
|
||||
Some(AccountStatus::QuotaExhausted)
|
||||
}
|
||||
CodexClientError::Upstream { status, body, .. } if status.as_u16() == 401 => {
|
||||
Some(if is_banned_auth_signal(body) {
|
||||
AccountStatus::Banned
|
||||
} else {
|
||||
AccountStatus::Expired
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
classify_client_failure(error)?.account_status()
|
||||
}
|
||||
|
||||
fn sse_failure_account_status(failure: &ResponsesSseFailure) -> Option<AccountStatus> {
|
||||
let code = failure
|
||||
.upstream_code
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase();
|
||||
let message = failure.message.to_ascii_lowercase();
|
||||
if matches!(code.as_str(), "quota_exceeded" | "insufficient_quota") || message.contains("quota")
|
||||
{
|
||||
return Some(AccountStatus::QuotaExhausted);
|
||||
}
|
||||
let authentication_failed = matches!(
|
||||
code.as_str(),
|
||||
"token_invalid"
|
||||
| "token_expired"
|
||||
| "token_revoked"
|
||||
| "account_deactivated"
|
||||
| "unauthorized"
|
||||
| "invalid_api_key"
|
||||
) || message.contains("token revoked")
|
||||
|| message.contains("token invalid")
|
||||
|| message.contains("token expired");
|
||||
authentication_failed.then(|| {
|
||||
if is_banned_auth_signal(&failure.message) {
|
||||
AccountStatus::Banned
|
||||
} else {
|
||||
AccountStatus::Expired
|
||||
}
|
||||
})
|
||||
classify_response_failure(failure)?.account_status()
|
||||
}
|
||||
|
||||
fn take_sse_frame(buffer: &mut String) -> Option<String> {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use secrecy::ExposeSecret;
|
||||
|
||||
use super::{AccountManageService, types::AccountManageError};
|
||||
use crate::fleet::account_failure::apply_client_failure_effect;
|
||||
|
||||
impl AccountManageService {
|
||||
async fn usage_cookie_header(&self, account_id: &str) -> Option<String> {
|
||||
@@ -50,15 +51,17 @@ impl AccountManageService {
|
||||
installation_id: Some(&installation_id),
|
||||
session_id: None,
|
||||
thread_id: None,
|
||||
prompt_cache_key: None,
|
||||
client_request_id: None,
|
||||
turn_id: None,
|
||||
};
|
||||
let raw = self
|
||||
.codex
|
||||
.fetch_usage(context)
|
||||
.await
|
||||
.map_err(|e| AccountManageError::FetchQuota(e.to_string()))?;
|
||||
let raw = match self.codex.fetch_usage(context).await {
|
||||
Ok(raw) => raw,
|
||||
Err(error) => {
|
||||
apply_client_failure_effect(&self.account_pool, &self.codex, account_id, &error)
|
||||
.await;
|
||||
return Err(AccountManageError::FetchQuota(error.to_string()));
|
||||
}
|
||||
};
|
||||
let normalized = crate::fleet::quota::quota_from_usage(&raw);
|
||||
self.account_pool
|
||||
.apply_quota_snapshot(account_id, &normalized)
|
||||
|
||||
@@ -121,7 +121,7 @@ impl AccountManageService {
|
||||
account_id,
|
||||
operation,
|
||||
error = %error,
|
||||
"failed to sync runtime account pool after admin account update"
|
||||
"Failed to sync runtime account pool after admin account update"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -145,7 +145,7 @@ impl AccountManageService {
|
||||
tracing::warn!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"failed to inspect account while evicting websocket pool"
|
||||
"Failed to inspect account while evicting WebSocket pool"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ use thiserror::Error;
|
||||
use crate::{
|
||||
fleet::{
|
||||
account::{AccountStatus, AccountStatus as AcctStatus},
|
||||
account_failure::classify_client_failure,
|
||||
store::StoredAccountMetadata,
|
||||
},
|
||||
upstream::openai::{token_client::RefreshFailure, transport::CodexClientError},
|
||||
@@ -323,11 +324,9 @@ fn normalized_plan_type(value: &str) -> Option<String> {
|
||||
}
|
||||
|
||||
pub(super) fn import_status_from_usage_error(error: &CodexClientError) -> Option<AccountStatus> {
|
||||
if crate::upstream::openai::transport::is_banned_upstream_error(error) {
|
||||
Some(AccountStatus::Banned)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
classify_client_failure(error)?
|
||||
.account_status()
|
||||
.filter(|status| *status == AccountStatus::Banned)
|
||||
}
|
||||
|
||||
pub(super) fn parse_account_status(status: &str) -> Result<AcctStatus, AccountManageError> {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! 账号、调度、配额与刷新领域。
|
||||
|
||||
pub mod account;
|
||||
pub mod account_failure;
|
||||
pub mod cookies;
|
||||
pub mod import;
|
||||
pub mod manage;
|
||||
|
||||
@@ -33,8 +33,11 @@ use crate::upstream::openai::protocol::events::{
|
||||
pub use crate::fleet::scheduler::RotationStrategy;
|
||||
|
||||
mod filters;
|
||||
mod persistence;
|
||||
mod state;
|
||||
|
||||
use persistence::AccountStatePersistence;
|
||||
|
||||
pub use filters::*;
|
||||
pub use state::*;
|
||||
|
||||
@@ -71,6 +74,7 @@ pub struct AccountPoolService {
|
||||
usage_store: Arc<dyn AccountUsageStore>,
|
||||
request_interval: Arc<std::sync::RwLock<StdDuration>>,
|
||||
candidate_changed: Arc<tokio::sync::Notify>,
|
||||
state_persistence: AccountStatePersistence,
|
||||
}
|
||||
|
||||
/// 一次请求对账号池 slot 的唯一所有权凭据。
|
||||
@@ -191,6 +195,7 @@ impl AccountPoolService {
|
||||
options: AccountPoolOptions,
|
||||
request_interval_ms: u64,
|
||||
) -> Self {
|
||||
let state_persistence = AccountStatePersistence::new(Arc::clone(&store));
|
||||
Self {
|
||||
pool: Arc::new(tokio::sync::Mutex::new(AccountPool::with_options(options))),
|
||||
store,
|
||||
@@ -199,6 +204,7 @@ impl AccountPoolService {
|
||||
request_interval_ms,
|
||||
))),
|
||||
candidate_changed: Arc::new(tokio::sync::Notify::new()),
|
||||
state_persistence,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -321,7 +327,7 @@ impl AccountPoolService {
|
||||
tracing::error!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"failed to persist account request usage"
|
||||
"Failed to persist account request usage"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -334,15 +340,32 @@ impl AccountPoolService {
|
||||
tracing::error!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"failed to persist account status"
|
||||
"Failed to persist account status"
|
||||
);
|
||||
false
|
||||
}
|
||||
};
|
||||
let in_memory = self.pool.lock().await.set_status(account_id, status);
|
||||
if in_memory {
|
||||
self.candidate_changed.notify_waiters();
|
||||
}
|
||||
persisted || in_memory
|
||||
}
|
||||
|
||||
/// 先在线性化的内存池中更新账号状态,再将持久化写入后台队列。
|
||||
pub async fn set_status_immediately(&self, account_id: &str, status: AccountStatus) -> bool {
|
||||
let in_memory = {
|
||||
let mut pool = self.pool.lock().await;
|
||||
let in_memory = pool.set_status(account_id, status);
|
||||
self.state_persistence.set_status(account_id, status);
|
||||
in_memory
|
||||
};
|
||||
if in_memory {
|
||||
self.candidate_changed.notify_waiters();
|
||||
}
|
||||
in_memory
|
||||
}
|
||||
|
||||
/// 标记账号 quota 冷却状态。
|
||||
pub async fn mark_quota_limited_until(&self, account_id: &str, until: DateTime<Utc>) -> bool {
|
||||
let persisted = match self.store.mark_quota_limited_until(account_id, until).await {
|
||||
@@ -351,7 +374,7 @@ impl AccountPoolService {
|
||||
tracing::error!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"failed to persist quota cooldown state"
|
||||
"Failed to persist quota cooldown state"
|
||||
);
|
||||
false
|
||||
}
|
||||
@@ -361,9 +384,31 @@ impl AccountPoolService {
|
||||
.lock()
|
||||
.await
|
||||
.mark_quota_limited_until(account_id, until);
|
||||
if in_memory {
|
||||
self.candidate_changed.notify_waiters();
|
||||
}
|
||||
persisted || in_memory
|
||||
}
|
||||
|
||||
/// 先在线性化的内存池中标记配额冷却,再将持久化写入后台队列。
|
||||
pub async fn mark_quota_limited_until_immediately(
|
||||
&self,
|
||||
account_id: &str,
|
||||
until: DateTime<Utc>,
|
||||
) -> bool {
|
||||
let in_memory = {
|
||||
let mut pool = self.pool.lock().await;
|
||||
let in_memory = pool.mark_quota_limited_until(account_id, until);
|
||||
self.state_persistence
|
||||
.mark_quota_limited_until(account_id, until);
|
||||
in_memory
|
||||
};
|
||||
if in_memory {
|
||||
self.candidate_changed.notify_waiters();
|
||||
}
|
||||
in_memory
|
||||
}
|
||||
|
||||
/// 按请求上下文获取可用账号。
|
||||
pub async fn acquire_with(&self, request: &AccountAcquireRequest) -> Option<AccountLease> {
|
||||
let refresh = self.pool.lock().await.acquire_with_status_refresh(request);
|
||||
@@ -454,7 +499,7 @@ impl AccountPoolService {
|
||||
tracing::error!(
|
||||
account_id = %refreshed.account.id,
|
||||
error = %error,
|
||||
"failed to persist refreshed runtime account state"
|
||||
"Failed to persist refreshed runtime account state"
|
||||
);
|
||||
}
|
||||
if refreshed.sync_usage_window
|
||||
@@ -469,7 +514,7 @@ impl AccountPoolService {
|
||||
tracing::error!(
|
||||
account_id = %refreshed.account.id,
|
||||
error = %error,
|
||||
"failed to persist refreshed runtime account usage window"
|
||||
"Failed to persist refreshed runtime account usage window"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -530,7 +575,7 @@ impl AccountPoolService {
|
||||
tracing::error!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"failed to persist account token usage"
|
||||
"Failed to persist account token usage"
|
||||
);
|
||||
}
|
||||
self.pool.lock().await.record_window_token_usage(
|
||||
@@ -562,7 +607,7 @@ impl AccountPoolService {
|
||||
tracing::error!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"failed to persist empty response usage"
|
||||
"Failed to persist empty response usage"
|
||||
);
|
||||
}
|
||||
if image_generation_requested {
|
||||
@@ -607,7 +652,7 @@ impl AccountPoolService {
|
||||
tracing::error!(
|
||||
account_id = %account_id,
|
||||
error = %error,
|
||||
"failed to read existing quota json before passive rate-limit sync"
|
||||
"Failed to read existing quota JSON before passive rate-limit sync"
|
||||
);
|
||||
None
|
||||
}
|
||||
@@ -634,7 +679,7 @@ impl AccountPoolService {
|
||||
tracing::error!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"failed to persist verified quota snapshot"
|
||||
"Failed to persist verified quota snapshot"
|
||||
);
|
||||
false
|
||||
}
|
||||
@@ -649,7 +694,7 @@ impl AccountPoolService {
|
||||
tracing::error!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"failed to persist verified quota window"
|
||||
"Failed to persist verified quota window"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -712,7 +757,7 @@ impl AccountPoolService {
|
||||
tracing::error!(
|
||||
account_id,
|
||||
error = %error,
|
||||
"failed to persist Cloudflare cooldown state"
|
||||
"Failed to persist Cloudflare cooldown state"
|
||||
);
|
||||
false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
//! 账号运行状态的有序后台持久化。
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::fleet::{account::AccountStatus, store::AccountStore};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct AccountStatePersistence {
|
||||
sender: mpsc::UnboundedSender<AccountStateWrite>,
|
||||
}
|
||||
|
||||
enum AccountStateWrite {
|
||||
SetStatus {
|
||||
account_id: String,
|
||||
status: AccountStatus,
|
||||
},
|
||||
MarkQuotaLimitedUntil {
|
||||
account_id: String,
|
||||
until: DateTime<Utc>,
|
||||
},
|
||||
}
|
||||
|
||||
impl AccountStatePersistence {
|
||||
pub(super) fn new(store: Arc<dyn AccountStore>) -> Self {
|
||||
let (sender, receiver) = mpsc::unbounded_channel();
|
||||
tokio::spawn(run(receiver, store));
|
||||
Self { sender }
|
||||
}
|
||||
|
||||
pub(super) fn set_status(&self, account_id: &str, status: AccountStatus) {
|
||||
self.enqueue(AccountStateWrite::SetStatus {
|
||||
account_id: account_id.to_owned(),
|
||||
status,
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn mark_quota_limited_until(&self, account_id: &str, until: DateTime<Utc>) {
|
||||
self.enqueue(AccountStateWrite::MarkQuotaLimitedUntil {
|
||||
account_id: account_id.to_owned(),
|
||||
until,
|
||||
});
|
||||
}
|
||||
|
||||
fn enqueue(&self, write: AccountStateWrite) {
|
||||
if self.sender.send(write).is_err() {
|
||||
tracing::error!("Account state persistence worker stopped unexpectedly");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(
|
||||
mut receiver: mpsc::UnboundedReceiver<AccountStateWrite>,
|
||||
store: Arc<dyn AccountStore>,
|
||||
) {
|
||||
while let Some(write) = receiver.recv().await {
|
||||
match write {
|
||||
AccountStateWrite::SetStatus { account_id, status } => {
|
||||
match store.set_status(&account_id, status).await {
|
||||
Ok(true) => {}
|
||||
Ok(false) => tracing::warn!(
|
||||
account_id,
|
||||
?status,
|
||||
"Account disappeared before deferred status persistence"
|
||||
),
|
||||
Err(error) => tracing::error!(
|
||||
account_id,
|
||||
?status,
|
||||
error = %error,
|
||||
"Failed to persist deferred account status"
|
||||
),
|
||||
}
|
||||
}
|
||||
AccountStateWrite::MarkQuotaLimitedUntil { account_id, until } => {
|
||||
match store.mark_quota_limited_until(&account_id, until).await {
|
||||
Ok(true) => {}
|
||||
Ok(false) => tracing::warn!(
|
||||
account_id,
|
||||
%until,
|
||||
"Account disappeared before deferred quota persistence"
|
||||
),
|
||||
Err(error) => tracing::error!(
|
||||
account_id,
|
||||
%until,
|
||||
error = %error,
|
||||
"Failed to persist deferred quota state"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -418,7 +418,7 @@ impl AccountPool {
|
||||
quota_limit_reached = selected.quota_limit_reached,
|
||||
quota_cooldown_until = ?selected.quota_cooldown_until,
|
||||
previous_slot_at = ?previous_slot_at,
|
||||
"account selected for upstream request"
|
||||
"Account selected for upstream request"
|
||||
);
|
||||
|
||||
let selected_id = selected.id.clone();
|
||||
@@ -645,7 +645,7 @@ impl AccountPool {
|
||||
last_used_at = account.last_used_at.as_deref().unwrap_or_default(),
|
||||
quota_limit_reached = account.quota_limit_reached,
|
||||
quota_cooldown_until = ?account.quota_cooldown_until,
|
||||
"account selected for model refresh"
|
||||
"Account selected for model refresh"
|
||||
);
|
||||
selected_accounts.push((plan_type, account));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
//! 运行时 quota refresh 业务服务。
|
||||
|
||||
use std::{collections::HashMap, sync::Arc, time::Duration};
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use chrono::Utc;
|
||||
use thiserror::Error;
|
||||
@@ -8,7 +12,8 @@ use tokio::time::{Instant, sleep};
|
||||
use tracing::warn;
|
||||
|
||||
use crate::fleet::{
|
||||
account::AccountStatus,
|
||||
account::{Account, AccountStatus},
|
||||
account_failure::apply_client_failure_effect,
|
||||
pool::AccountPoolService,
|
||||
quota::{
|
||||
quota_from_usage, quota_snapshot_limit_reached, quota_snapshot_limit_window_seconds,
|
||||
@@ -37,7 +42,7 @@ pub struct QuotaRefreshService {
|
||||
request_spacing: Duration,
|
||||
account_pseudonymizer: Arc<crate::infra::identity::AccountPseudonymizer>,
|
||||
cookie_store: Option<PgCookieStore>,
|
||||
account_pool: Option<Arc<AccountPoolService>>,
|
||||
account_pool: Arc<AccountPoolService>,
|
||||
}
|
||||
|
||||
impl QuotaRefreshService {
|
||||
@@ -46,6 +51,7 @@ impl QuotaRefreshService {
|
||||
store: PgAccountStore,
|
||||
usage_store: PgAccountUsageStore,
|
||||
codex: Arc<CodexBackendClient>,
|
||||
account_pool: Arc<AccountPoolService>,
|
||||
account_pseudonymizer: Arc<crate::infra::identity::AccountPseudonymizer>,
|
||||
) -> Self {
|
||||
Self {
|
||||
@@ -56,7 +62,7 @@ impl QuotaRefreshService {
|
||||
request_spacing: Self::default_request_spacing(),
|
||||
account_pseudonymizer,
|
||||
cookie_store: None,
|
||||
account_pool: None,
|
||||
account_pool,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,6 +75,7 @@ impl QuotaRefreshService {
|
||||
store: PgAccountStore,
|
||||
usage_store: PgAccountUsageStore,
|
||||
codex: Arc<CodexBackendClient>,
|
||||
account_pool: Arc<AccountPoolService>,
|
||||
account_pseudonymizer: Arc<crate::infra::identity::AccountPseudonymizer>,
|
||||
min_refresh_interval_secs: u64,
|
||||
) -> Self {
|
||||
@@ -80,7 +87,7 @@ impl QuotaRefreshService {
|
||||
request_spacing: Self::default_request_spacing(),
|
||||
account_pseudonymizer,
|
||||
cookie_store: None,
|
||||
account_pool: None,
|
||||
account_pool,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,12 +103,6 @@ impl QuotaRefreshService {
|
||||
self
|
||||
}
|
||||
|
||||
/// 设置运行时账号池,用于刷新后同步内存调度状态。
|
||||
pub fn with_account_pool(mut self, account_pool: Arc<AccountPoolService>) -> Self {
|
||||
self.account_pool = Some(account_pool);
|
||||
self
|
||||
}
|
||||
|
||||
/// 执行一次配额锁定或待验证账号刷新,复用调用方传入的最近刷新记录。
|
||||
pub async fn refresh_locked_accounts(
|
||||
&self,
|
||||
@@ -120,13 +121,16 @@ impl QuotaRefreshService {
|
||||
let now = Instant::now();
|
||||
let now_utc = Utc::now();
|
||||
|
||||
let candidate_ids = accounts
|
||||
.iter()
|
||||
.filter(|account| quota_refresh_candidate(account))
|
||||
.map(|account| account.id.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
last_refreshed.retain(|account_id, _| candidate_ids.contains(account_id.as_str()));
|
||||
|
||||
let mut candidates = accounts
|
||||
.into_iter()
|
||||
.filter(|account| {
|
||||
account.status == AccountStatus::QuotaExhausted
|
||||
|| (account.status == AccountStatus::Active
|
||||
&& (account.quota_limit_reached || account.quota_verify_required))
|
||||
})
|
||||
.filter(quota_refresh_candidate)
|
||||
.peekable();
|
||||
|
||||
while let Some(account) = candidates.next() {
|
||||
@@ -169,7 +173,6 @@ impl QuotaRefreshService {
|
||||
installation_id: Some(&installation_id),
|
||||
session_id: None,
|
||||
thread_id: None,
|
||||
prompt_cache_key: None,
|
||||
client_request_id: None,
|
||||
turn_id: None,
|
||||
})
|
||||
@@ -205,10 +208,17 @@ impl QuotaRefreshService {
|
||||
self.sync_runtime_pool_account(&account.id).await;
|
||||
}
|
||||
Err(error) => {
|
||||
apply_client_failure_effect(
|
||||
&self.account_pool,
|
||||
&self.codex,
|
||||
&account.id,
|
||||
&error,
|
||||
)
|
||||
.await;
|
||||
warn!(
|
||||
account_id = %account.id,
|
||||
error = %error,
|
||||
"quota usage 拉取失败"
|
||||
"Quota usage 拉取失败"
|
||||
);
|
||||
summary.failed += 1;
|
||||
}
|
||||
@@ -232,19 +242,22 @@ impl QuotaRefreshService {
|
||||
}
|
||||
|
||||
async fn sync_runtime_pool_account(&self, account_id: &str) {
|
||||
let Some(account_pool) = &self.account_pool else {
|
||||
return;
|
||||
};
|
||||
if let Err(error) = account_pool.sync_account_from_store(account_id).await {
|
||||
if let Err(error) = self.account_pool.sync_account_from_store(account_id).await {
|
||||
warn!(
|
||||
account_id = %account_id,
|
||||
error = %error,
|
||||
"failed to sync runtime account pool after quota refresh"
|
||||
"Failed to sync runtime account pool after quota refresh"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn quota_refresh_candidate(account: &Account) -> bool {
|
||||
account.status == AccountStatus::QuotaExhausted
|
||||
|| (account.status == AccountStatus::Active
|
||||
&& (account.quota_limit_reached || account.quota_verify_required))
|
||||
}
|
||||
|
||||
fn quota_cooldown_ready(cooldown_until: chrono::DateTime<Utc>, now: chrono::DateTime<Utc>) -> bool {
|
||||
cooldown_until
|
||||
.checked_add_signed(chrono::Duration::seconds(COOLDOWN_REFRESH_GRACE_SECS))
|
||||
|
||||
@@ -148,7 +148,7 @@ impl Drop for RefreshLeaseGuard {
|
||||
drop(tasks.spawn_on(
|
||||
async move {
|
||||
if let Err(error) = store.release(&account_id, &owner).await {
|
||||
warn!(account_id, error = %error, "failed to release cancelled token refresh lease");
|
||||
warn!(account_id, error = %error, "Failed to release cancelled token refresh lease");
|
||||
}
|
||||
},
|
||||
&runtime,
|
||||
@@ -452,7 +452,7 @@ where
|
||||
warn!(
|
||||
account_id = %timer_account_id,
|
||||
error = %error,
|
||||
"scheduled token refresh failed"
|
||||
"Scheduled token refresh failed"
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -503,7 +503,7 @@ where
|
||||
warn!(
|
||||
remaining_tasks = self.tasks.len(),
|
||||
timeout_secs = REFRESH_TASK_SHUTDOWN_TIMEOUT.as_secs(),
|
||||
"waiting for in-flight token refresh tasks timed out"
|
||||
"Waiting for in-flight token refresh tasks timed out"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -561,7 +561,7 @@ where
|
||||
if delay.is_zero() {
|
||||
debug!(
|
||||
account_id = %account.id,
|
||||
"refreshed token is already within refresh margin; skipping next timer"
|
||||
"Refreshed token is already within refresh margin; skipping next timer"
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -617,7 +617,7 @@ where
|
||||
next_refresh_at = ?updated.next_refresh_at,
|
||||
refresh_token_present = updated.refresh_token.is_some(),
|
||||
refresh_token_rotated,
|
||||
"token refresh succeeded"
|
||||
"Token refresh succeeded"
|
||||
);
|
||||
return Ok(TokenRefreshOutcome::Refreshed(Box::new(updated)));
|
||||
}
|
||||
|
||||
@@ -4,6 +4,9 @@ use std::time::Duration;
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::{PgPool, Postgres, Row, Transaction, postgres::PgPoolOptions};
|
||||
use tracing::info;
|
||||
|
||||
const MIGRATION_LOCK_KEY: i64 = i64::from_be_bytes(*b"CPR-MIGR");
|
||||
|
||||
const MIGRATIONS: &[Migration] = &[Migration {
|
||||
version: 1,
|
||||
@@ -50,7 +53,7 @@ pub async fn migrate(pool: &PgPool) -> Result<(), sqlx::Error> {
|
||||
validate_migration_catalog()?;
|
||||
|
||||
let mut tx = pool.begin().await?;
|
||||
ensure_migrations_table(&mut tx).await?;
|
||||
let migration_table_created = ensure_migrations_table(&mut tx).await?;
|
||||
|
||||
let applied = applied_migrations(&mut tx).await?;
|
||||
if applied.is_empty() {
|
||||
@@ -63,7 +66,14 @@ pub async fn migrate(pool: &PgPool) -> Result<(), sqlx::Error> {
|
||||
record_migration(&mut tx, migration).await?;
|
||||
}
|
||||
|
||||
tx.commit().await
|
||||
tx.commit().await?;
|
||||
|
||||
if migration_table_created {
|
||||
info!("数据库迁移表已创建");
|
||||
} else {
|
||||
info!("数据库迁移表已存在,跳过创建");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_migration_catalog() -> Result<(), sqlx::Error> {
|
||||
@@ -86,9 +96,29 @@ fn validate_migration_catalog() -> Result<(), sqlx::Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ensure_migrations_table(tx: &mut Transaction<'_, Postgres>) -> Result<(), sqlx::Error> {
|
||||
async fn ensure_migrations_table(tx: &mut Transaction<'_, Postgres>) -> Result<bool, sqlx::Error> {
|
||||
sqlx::query("select pg_advisory_xact_lock($1)")
|
||||
.bind(MIGRATION_LOCK_KEY)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
|
||||
let exists = sqlx::query_scalar(
|
||||
"select exists (
|
||||
select 1
|
||||
from information_schema.tables
|
||||
where table_schema = current_schema()
|
||||
and table_name = 'schema_migrations'
|
||||
and table_type = 'BASE TABLE'
|
||||
)",
|
||||
)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
if exists {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"create table if not exists schema_migrations (
|
||||
"create table schema_migrations (
|
||||
version bigint not null check (version > 0),
|
||||
name text not null,
|
||||
checksum text not null,
|
||||
@@ -98,7 +128,7 @@ async fn ensure_migrations_table(tx: &mut Transaction<'_, Postgres>) -> Result<(
|
||||
)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn applied_migrations(
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::{
|
||||
backtrace::Backtrace,
|
||||
env, fmt, fs,
|
||||
fs::{File, OpenOptions},
|
||||
io::{self, Write},
|
||||
io::{self, IsTerminal, Write},
|
||||
panic,
|
||||
path::{Path, PathBuf},
|
||||
sync::mpsc,
|
||||
@@ -22,7 +22,7 @@ use tracing_subscriber::{
|
||||
util::SubscriberInitExt,
|
||||
};
|
||||
|
||||
use crate::infra::time::{china_date, china_rfc3339_millis};
|
||||
use crate::infra::time::{china_date, china_datetime, china_rfc3339_millis};
|
||||
|
||||
const LOG_PREFIX: &str = "codex-proxy-rs";
|
||||
const LOG_SUFFIX: &str = "log";
|
||||
@@ -169,6 +169,7 @@ pub fn init_tracing(config: &TracingConfig) -> Result<LogGuard, LogError> {
|
||||
let mut writer_guards = Vec::new();
|
||||
let mut counters = Vec::new();
|
||||
|
||||
let stdout_is_terminal = io::stdout().is_terminal();
|
||||
let stdout_writer = config.stdout.then(|| {
|
||||
let (writer, guard) = NonBlockingBuilder::default()
|
||||
.lossy(true)
|
||||
@@ -194,13 +195,20 @@ pub fn init_tracing(config: &TracingConfig) -> Result<LogGuard, LogError> {
|
||||
writer
|
||||
});
|
||||
|
||||
let stdout_layer = stdout_writer.map(json_layer);
|
||||
let (compact_stdout_writer, json_stdout_writer) = match stdout_writer {
|
||||
Some(writer) if stdout_is_terminal => (Some(writer), None),
|
||||
Some(writer) => (None, Some(writer)),
|
||||
None => (None, None),
|
||||
};
|
||||
let compact_stdout_layer = compact_stdout_writer.map(compact_layer);
|
||||
let json_stdout_layer = json_stdout_writer.map(json_layer);
|
||||
let file_layer = file_writer.map(json_layer);
|
||||
let drop_monitor = DroppedLogMonitor::start(counters)?;
|
||||
|
||||
let init_result = tracing_subscriber::registry()
|
||||
.with(filter)
|
||||
.with(stdout_layer)
|
||||
.with(compact_stdout_layer)
|
||||
.with(json_stdout_layer)
|
||||
.with(file_layer)
|
||||
.try_init()
|
||||
.map_err(|_| LogError::SubscriberAlreadyInitialized);
|
||||
@@ -217,13 +225,36 @@ pub fn init_tracing(config: &TracingConfig) -> Result<LogGuard, LogError> {
|
||||
})
|
||||
}
|
||||
|
||||
fn compact_layer<S>(
|
||||
writer: tracing_appender::non_blocking::NonBlocking,
|
||||
) -> tracing_subscriber::fmt::Layer<
|
||||
S,
|
||||
tracing_subscriber::fmt::format::DefaultFields,
|
||||
tracing_subscriber::fmt::format::Format<
|
||||
tracing_subscriber::fmt::format::Compact,
|
||||
ChinaConsoleTimer,
|
||||
>,
|
||||
tracing_appender::non_blocking::NonBlocking,
|
||||
>
|
||||
where
|
||||
S: tracing::Subscriber + for<'span> tracing_subscriber::registry::LookupSpan<'span>,
|
||||
{
|
||||
tracing_fmt::layer()
|
||||
.compact()
|
||||
.with_timer(ChinaConsoleTimer)
|
||||
.with_writer(writer)
|
||||
.with_ansi(true)
|
||||
.with_target(true)
|
||||
.with_level(true)
|
||||
}
|
||||
|
||||
fn install_panic_hook() {
|
||||
let previous_hook = panic::take_hook();
|
||||
panic::set_hook(Box::new(move |panic_info| {
|
||||
tracing::error!(
|
||||
panic = %panic_info,
|
||||
backtrace = %Backtrace::force_capture(),
|
||||
"process panicked"
|
||||
"Process panicked"
|
||||
);
|
||||
previous_hook(panic_info);
|
||||
}));
|
||||
@@ -316,6 +347,15 @@ impl Write for ChinaDailyFileAppender {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct ChinaConsoleTimer;
|
||||
|
||||
impl FormatTime for ChinaConsoleTimer {
|
||||
fn format_time(&self, writer: &mut Writer<'_>) -> fmt::Result {
|
||||
write!(writer, "{}", china_datetime(&Utc::now()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct ChinaLogTimer;
|
||||
|
||||
|
||||
@@ -231,35 +231,3 @@ create index idx_account_cookies_account_domain
|
||||
on account_cookies(account_id, domain);
|
||||
create index idx_account_cookies_expires
|
||||
on account_cookies(expires_at) where expires_at is not null;
|
||||
|
||||
create table fingerprints (
|
||||
id text primary key,
|
||||
originator text not null,
|
||||
app_version text not null,
|
||||
build_number text not null,
|
||||
platform text not null,
|
||||
arch text not null,
|
||||
chromium_version text not null,
|
||||
user_agent_template text not null,
|
||||
default_headers_json jsonb not null,
|
||||
header_order_json jsonb not null,
|
||||
source text not null,
|
||||
created_at timestamptz not null,
|
||||
updated_at timestamptz not null
|
||||
);
|
||||
|
||||
create table fingerprint_update_history (
|
||||
id text primary key,
|
||||
current_fingerprint_id text not null references fingerprints(id) on delete cascade,
|
||||
app_version text not null,
|
||||
build_number text not null,
|
||||
chromium_version text,
|
||||
source text not null,
|
||||
manifest_json jsonb,
|
||||
created_at timestamptz not null
|
||||
);
|
||||
|
||||
create index idx_fingerprint_update_history_created_id
|
||||
on fingerprint_update_history(created_at desc, id desc);
|
||||
create index idx_fingerprint_update_history_fingerprint
|
||||
on fingerprint_update_history(current_fingerprint_id);
|
||||
|
||||
@@ -10,15 +10,11 @@ use rand::Rng;
|
||||
|
||||
const IDENTITY_SECRET_FILE_NAME: &str = "identity_hmac_secret";
|
||||
|
||||
fn data_dir() -> PathBuf {
|
||||
dirs::data_local_dir().unwrap_or_else(|| PathBuf::from(".runtime/data"))
|
||||
}
|
||||
|
||||
/// 确保本地数据目录存在。
|
||||
pub fn ensure_data_dir() -> std::io::Result<PathBuf> {
|
||||
let dir = data_dir();
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(dir)
|
||||
pub fn ensure_data_dir(directory: impl AsRef<Path>) -> std::io::Result<PathBuf> {
|
||||
let directory = directory.as_ref();
|
||||
std::fs::create_dir_all(directory)?;
|
||||
Ok(directory.to_path_buf())
|
||||
}
|
||||
|
||||
/// 读取或创建账号身份隔离使用的 256-bit HMAC 密钥。
|
||||
|
||||
@@ -86,7 +86,7 @@ impl KeyVerifier {
|
||||
pub async fn flush_pending_last_used(&self) {
|
||||
let updates = self.take_pending_last_used();
|
||||
if let Err(error) = self.store.touch_last_used_batch(&updates).await {
|
||||
tracing::error!(error = %error, "failed to flush client key last_used_at batch");
|
||||
tracing::error!(error = %error, "Failed to flush client key last_used_at batch");
|
||||
merge_last_used_updates(
|
||||
&mut self
|
||||
.pending_last_used
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user