diff --git a/Grok2API-部署教程.md b/Grok2API-部署教程.md new file mode 100644 index 00000000..8c4ad798 --- /dev/null +++ b/Grok2API-部署教程.md @@ -0,0 +1,1033 @@ +--- + +## title: "Grok2API 部署指南" +date: 2026-08-04 +description: "分别使用 SQLite、PostgreSQL 和 PostgreSQL + Redis 部署 Grok2API,并按需接入 WARP、FlareSolverr 与 Egress Quality Guard。" +tags: + - Grok2API + - Docker Compose + - PostgreSQL + - Redis + +# Grok2API 部署指南 + +Grok2API 是面向 Grok Build、Grok Web 和 Grok Console 的多账号 API 网关,提供 OpenAI Responses、Chat Completions 与 Anthropic Messages 兼容接口,并集成账号管理、模型路由、额度与并发控制、故障转移、审计、媒体归档和出口管理。 + +## 架构选型 + +本文不把所有组件堆进同一份配置,而是提供三套边界清晰的部署方案: + + +| 方案 | 适用场景 | 数据库 | 运行态存储 | 应用副本 | +| --- | ------------ | ---------- | ------ | ---- | +| 方案一 | 个人、测试、普通单机 | SQLite | Memory | 1 | +| 方案二 | 单实例生产、托管数据库 | PostgreSQL | Memory | 1 | +| 方案三 | 同主机双实例或多实例验证 | PostgreSQL | Redis | 2 | + + +建议从最符合当前需求的方案中选择一套,不要混用三套主配置。WARP、FlareSolverr 和 Egress Quality Guard 位于文章后半部分,作为独立 Compose 扩展叠加到主方案上。 + +项目地址:[https://github.com/chenyme/grok2api](https://github.com/chenyme/grok2api) + +> 请仅接入已获授权使用的账号与网络资源,并遵守相关服务条款、当地法律及组织安全规范。 + + + +## 准备工作 + +以下三套方案均要求: + +- Linux `amd64` 或 `arm64` 主机; +- Docker Engine; +- Docker Compose v2,即使用 `docker compose`; +- 可以访问 Grok2API 镜像仓库及所需上游服务的网络。 + +确认运行环境: + +```bash +docker version +docker compose version +``` + +下载项目: + +```bash +git clone https://github.com/chenyme/grok2api.git +cd grok2api +``` + +生成应用密钥: + +```bash +openssl rand -hex 32 +openssl rand -base64 32 +``` + +第一条命令的输出用于 `secrets.jwtSecret`,第二条命令的输出用于 `secrets.credentialEncryptionKey`。这两个值必须妥善保存,其中 `credentialEncryptionKey` 一旦用于写入账号凭据,就不能随意更换,否则已有凭据将无法解密。 + +--- + + + +## SQLite 单实例 + +这是依赖最少的基线方案,适合个人使用、功能验证以及普通单实例部署。数据库和本地媒体都保存在 Docker 数据卷中。 + +### 文件布局 + +```text +grok2api/ +├── docker-compose.yml +└── config.yaml +``` + + + +### Compose 配置 + +```yaml +name: grok2api + +services: + grok2api: + image: "${GROK2API_IMAGE:-ghcr.io/chenyme/grok2api:latest}" + ports: + - "${GROK2API_PORT:-8000}:8000" + environment: + TZ: "${TZ:-Asia/Shanghai}" + volumes: + - "./config.yaml:/run/grok2api/config.yaml:ro" + - grok2api-data:/app/data + restart: unless-stopped + init: true + stop_grace_period: 30s + security_opt: + - no-new-privileges:true + +volumes: + grok2api-data: +``` + + + +### 应用配置 + +```yaml +server: + swaggerEnabled: false + +auth: + # 直接使用 HTTP 测试时保持 false;启用 HTTPS 后改为 true。 + secureCookies: false + +secrets: + jwtSecret: "替换为 openssl rand -hex 32 的输出" + credentialEncryptionKey: "替换为 openssl rand -base64 32 的输出" + +bootstrapAdmin: + username: "admin" + password: "替换为高强度初始密码" + +database: + driver: sqlite + sqlite: + path: "./data/backend.db" + +runtimeStore: + driver: memory + +deployment: + replicas: 1 + clusterID: "grok2api" + +media: + driver: local + local: + path: "./data/media" +``` + +未在该文件中列出的启动项使用项目内置默认值。需要进一步调整时,以仓库中的 `config.example.yaml` 为准。 + +### 启动验证 + +```bash +chmod 600 config.yaml +docker compose pull +docker compose up -d +docker compose ps +docker compose logs --tail=200 grok2api +``` + +健康检查: + +```bash +curl -fsS http://127.0.0.1:8000/healthz +curl -fsS http://127.0.0.1:8000/readyz +``` + +默认访问地址为 `http://服务器地址:8000`。如需更换宿主机端口,可在 `.env` 中设置: + +```dotenv +GROK2API_PORT=18000 +``` + +方案一的数据位置: + +- SQLite:卷内 `/app/data/backend.db`; +- 媒体:卷内 `/app/data/media`; +- 宿主机配置:`./config.yaml`。 + +--- + + + +## PostgreSQL 单实例 + +该方案仍运行一个 Grok2API 副本,但把业务数据迁移到 PostgreSQL。适合托管数据库、PaaS 或希望独立管理数据库备份的部署。 + +示例 Compose 同时启动 PostgreSQL;如果使用云数据库,可以删除 `postgres` 服务与 `postgres-data` 卷,并把 `GROK2API_DATABASE_URL` 改为云数据库地址。 + +### 文件布局 + +```text +grok2api/ +├── .env +├── docker-compose.yml +└── config.yaml +``` + + + +### 环境变量 + +```dotenv +POSTGRES_DB=grok2api +POSTGRES_USER=grok2api +POSTGRES_PASSWORD=替换为高强度数据库密码 + +# 密码包含特殊字符时,这里的用户名和密码必须进行 URL 编码。 +GROK2API_DATABASE_URL=postgresql://grok2api:替换为URL编码后的密码@postgres:5432/grok2api?sslmode=disable +``` + +`POSTGRES_PASSWORD` 是 PostgreSQL 容器使用的原始密码;URL 中的密码是同一个值经过 URL 编码后的结果。不要为两者配置不同密码。 + +### Compose 配置 + +```yaml +name: grok2api + +services: + postgres: + image: "${POSTGRES_IMAGE:-postgres:16-alpine}" + environment: + POSTGRES_DB: "${POSTGRES_DB:-grok2api}" + POSTGRES_USER: "${POSTGRES_USER:-grok2api}" + POSTGRES_PASSWORD: "${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}" + volumes: + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""] + interval: 10s + timeout: 5s + retries: 10 + restart: unless-stopped + security_opt: + - no-new-privileges:true + + grok2api: + image: "${GROK2API_IMAGE:-ghcr.io/chenyme/grok2api:latest}" + depends_on: + postgres: + condition: service_healthy + ports: + - "${GROK2API_PORT:-8000}:8000" + environment: + TZ: "${TZ:-Asia/Shanghai}" + GROK2API_DATABASE_URL: "${GROK2API_DATABASE_URL:?set GROK2API_DATABASE_URL in .env}" + volumes: + - "./config.yaml:/run/grok2api/config.yaml:ro" + - app-data:/app/data + restart: unless-stopped + init: true + stop_grace_period: 30s + security_opt: + - no-new-privileges:true + +volumes: + postgres-data: + app-data: +``` + +PostgreSQL 未映射宿主机端口,只允许 Compose 内网中的服务访问。如果使用外部管理工具,应通过受控网络、SSH Tunnel 或数据库平台提供的安全入口连接,而不是直接开放 `5432` 到公网。 + +### 应用配置 + +```yaml +server: + swaggerEnabled: false + +auth: + secureCookies: false + +secrets: + jwtSecret: "替换为 openssl rand -hex 32 的输出" + credentialEncryptionKey: "替换为 openssl rand -base64 32 的输出" + +bootstrapAdmin: + username: "admin" + password: "替换为高强度初始密码" + +database: + driver: postgres + postgres: + # 实际运行时由 GROK2API_DATABASE_URL 覆盖。 + dsn: "postgresql://grok2api@postgres:5432/grok2api?sslmode=disable" + maxOpenConns: 50 + maxIdleConns: 10 + +runtimeStore: + driver: memory + +deployment: + replicas: 1 + clusterID: "grok2api" + +media: + driver: local + local: + path: "./data/media" +``` + +数据库配置优先级为: + +```text +内置默认值 < config.yaml < GROK2API_DATABASE_URL < CLI 覆盖 +``` + +当前 CLI 没有数据库参数,因此非空的 `GROK2API_DATABASE_URL` 是数据库配置的最高优先级。它会覆盖 `database.postgres.dsn`,并自动选择 PostgreSQL 驱动。应用不会隐式读取通用的 `DATABASE_URL`;PaaS 只提供该变量时,需要显式映射为 `GROK2API_DATABASE_URL`。 + +### 启动验证 + +```bash +chmod 600 .env config.yaml +docker compose config --quiet +docker compose pull +docker compose up -d +docker compose ps +docker compose logs --tail=200 postgres grok2api +``` + +```bash +curl -fsS http://127.0.0.1:8000/healthz +curl -fsS http://127.0.0.1:8000/readyz +``` + +方案二中,PostgreSQL 数据位于 `postgres-data` 卷,本地媒体位于 `app-data` 卷。两者必须分别备份。 + +--- + + + +## PostgreSQL + Redis 双实例 + +该方案用于验证 Grok2API 的多实例约束,或在同一台主机上运行两个应用副本。它不是跨主机高可用方案:PostgreSQL、Redis、媒体卷和 Docker 主机仍可能是单点。 + +真正的跨主机部署必须使用外部 PostgreSQL、外部 Redis、多个主机都能访问的共享媒体存储,以及独立负载均衡器。 + +### 部署约束 + +Grok2API 的每个副本必须满足: + +- 使用同一个 PostgreSQL 数据库; +- 使用同一个 Redis; +- 使用相同的 `jwtSecret` 和 `credentialEncryptionKey`; +- 使用相同的 `deployment.clusterID`; +- 使用不同且稳定的 `deployment.instanceID`; +- `deployment.replicas` 设置为实际副本数; +- `deployment.sharedMedia` 设置为 `true`; +- 挂载同一个可读写媒体目录。 + +因此不能让两个副本共用完全相同的 `config.yaml`,也不能直接执行 `docker compose up --scale grok2api=2`。本方案使用 `config.node-1.yaml` 和 `config.node-2.yaml`,两者仅在实例身份和首次管理员配置上存在差异。 + +### 文件布局 + +```text +grok2api/ +├── .env +├── docker-compose.yml +├── config.node-1.yaml +└── config.node-2.yaml +``` + + + +### 环境变量 + +```dotenv +POSTGRES_DB=grok2api +POSTGRES_USER=grok2api +POSTGRES_PASSWORD=替换为高强度数据库密码 +GROK2API_DATABASE_URL=postgresql://grok2api:替换为URL编码后的密码@postgres:5432/grok2api?sslmode=disable + +# 该值还需要原样写入两个节点配置的 runtimeStore.redis.password。 +REDIS_PASSWORD=替换为高强度Redis密码 +``` + + + +### Compose 配置 + +```yaml +name: grok2api + +x-grok2api-common: &grok2api-common + image: "${GROK2API_IMAGE:-ghcr.io/chenyme/grok2api:latest}" + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + environment: + TZ: "${TZ:-Asia/Shanghai}" + GROK2API_DATABASE_URL: "${GROK2API_DATABASE_URL:?set GROK2API_DATABASE_URL in .env}" + volumes: + - app-data:/app/data + restart: unless-stopped + init: true + stop_grace_period: 30s + security_opt: + - no-new-privileges:true + +services: + postgres: + image: "${POSTGRES_IMAGE:-postgres:16-alpine}" + environment: + POSTGRES_DB: "${POSTGRES_DB:-grok2api}" + POSTGRES_USER: "${POSTGRES_USER:-grok2api}" + POSTGRES_PASSWORD: "${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}" + volumes: + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""] + interval: 10s + timeout: 5s + retries: 10 + restart: unless-stopped + security_opt: + - no-new-privileges:true + + redis: + image: "${REDIS_IMAGE:-redis:7-alpine}" + environment: + REDIS_PASSWORD: "${REDIS_PASSWORD:?set REDIS_PASSWORD in .env}" + command: + - sh + - -c + - 'exec redis-server --appendonly yes --requirepass "$${REDIS_PASSWORD}"' + volumes: + - redis-data:/data + healthcheck: + test: ["CMD-SHELL", "redis-cli -a \"$${REDIS_PASSWORD}\" ping | grep -q PONG"] + interval: 10s + timeout: 5s + retries: 10 + restart: unless-stopped + security_opt: + - no-new-privileges:true + + grok2api: + <<: *grok2api-common + ports: + - "127.0.0.1:8001:8000" + volumes: + - "./config.node-1.yaml:/run/grok2api/config.yaml:ro" + - app-data:/app/data + + grok2api-2: + <<: *grok2api-common + ports: + - "127.0.0.1:8002:8000" + volumes: + - "./config.node-2.yaml:/run/grok2api/config.yaml:ro" + - app-data:/app/data + +volumes: + postgres-data: + redis-data: + app-data: +``` + + + +### 节点 1 配置 + +```yaml +server: + swaggerEnabled: false + +auth: + secureCookies: false + +secrets: + jwtSecret: "两个节点完全相同的 JWT 密钥" + credentialEncryptionKey: "两个节点完全相同的 Base64 加密密钥" + +bootstrapAdmin: + username: "admin" + password: "替换为高强度初始密码" + +database: + driver: postgres + postgres: + dsn: "postgresql://grok2api@postgres:5432/grok2api?sslmode=disable" + maxOpenConns: 25 + maxIdleConns: 5 + +runtimeStore: + driver: redis + redis: + address: "redis:6379" + username: "" + password: "必须与 .env 中 REDIS_PASSWORD 完全相同" + database: 0 + keyPrefix: "grok2api:" + tls: false + +deployment: + replicas: 2 + instanceID: "grok2api-node-1" + clusterID: "grok2api-production" + sharedMedia: true + +media: + driver: local + local: + path: "./data/media" +``` + + + +### 节点 2 配置 + +```yaml +server: + swaggerEnabled: false + +auth: + secureCookies: false + +secrets: + jwtSecret: "与 node-1 完全相同" + credentialEncryptionKey: "与 node-1 完全相同" + +# 第二个节点不负责首次创建管理员,因此不配置 bootstrapAdmin。 + +database: + driver: postgres + postgres: + dsn: "postgresql://grok2api@postgres:5432/grok2api?sslmode=disable" + maxOpenConns: 25 + maxIdleConns: 5 + +runtimeStore: + driver: redis + redis: + address: "redis:6379" + username: "" + password: "必须与 node-1 和 .env 中 REDIS_PASSWORD 完全相同" + database: 0 + keyPrefix: "grok2api:" + tls: false + +deployment: + replicas: 2 + instanceID: "grok2api-node-2" + clusterID: "grok2api-production" + sharedMedia: true + +media: + driver: local + local: + path: "./data/media" +``` + +两个配置文件中的 `jwtSecret`、`credentialEncryptionKey`、Redis 密码和 `clusterID` 必须一致;只有 `instanceID` 必须不同。 + +### 启动验证 + +先启动基础设施和第一个节点,由第一个节点完成数据库迁移与管理员初始化: + +```bash +chmod 600 .env config.node-1.yaml config.node-2.yaml +docker compose config --quiet +docker compose up -d postgres redis grok2api +curl -fsS http://127.0.0.1:8001/readyz +``` + +第一个节点就绪后再启动第二个节点: + +```bash +docker compose up -d grok2api-2 +curl -fsS http://127.0.0.1:8002/readyz +``` + +随后由外部 Nginx、Nginx Proxy Manager、HAProxy 或云负载均衡器把流量分发到: + +```text +127.0.0.1:8001 +127.0.0.1:8002 +``` + +Redis 负责共享并发租约、Sticky Session、限流及失效通知等运行态;PostgreSQL 保存业务数据;`app-data` 卷作为同主机共享媒体目录。 + +--- + + + +## 应用初始化 + +主服务就绪后按以下顺序初始化: + +1. 使用 `bootstrapAdmin` 登录管理端; +2. 修改管理员密码; +3. 删除首个节点配置中的 `bootstrapAdmin`,并重启对应服务; +4. 接入 Grok Build、Grok Web 或 Grok Console 账号; +5. 等待账号额度和模型能力同步; +6. 在“模型路由”中确认公开模型; +7. 在“客户端密钥”中创建调用密钥,并配置模型白名单、RPM、并发和用量限制。 + +列出模型: + +```bash +curl -fsS http://127.0.0.1:8000/v1/models \ + -H "Authorization: Bearer g2a_xxx_xxx" +``` + +方案三应把端口改为 `8001`、`8002` 或负载均衡入口。 + +发送 Responses API 请求: + +```bash +curl http://127.0.0.1:8000/v1/responses \ + -H "Authorization: Bearer g2a_xxx_xxx" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "替换为 /v1/models 返回的模型 ID", + "input": "用三句话解释量子隧穿。", + "stream": true + }' +``` + +推理接口使用管理端创建的客户端密钥,不使用管理员登录令牌。 + +--- + + + +## 可选扩展 + + + +### WARP + +WARP 适用于需要额外落地网络的场景。它需要 `NET_ADMIN` 能力,不应在没有明确网络需求时默认启用。 + +新建 `compose.warp.yml`: + +```yaml +services: + warp: + image: caomingjun/warp:latest + profiles: ["warp"] + restart: unless-stopped + environment: + WARP_SLEEP: "2" + cap_add: + - NET_ADMIN +``` + +启动时同时加载主 Compose 与扩展文件: + +```bash +docker compose \ + -f docker-compose.yml \ + -f compose.warp.yml \ + --profile warp up -d +``` + +然后在管理端“设置 → 出口代理”中新增: + +```text +socks5://warp:1080 +``` + +Compose 服务位于同一默认网络时,应使用服务名 `warp`,而不是 `127.0.0.1`。 + +--- + + + +### FlareSolverr + +FlareSolverr 用于 Grok Web 的 Cloudflare Clearance 管理。没有 Grok Web Clearance 需求时无需部署。 + +新建 `compose.flaresolverr.yml`: + +```yaml +services: + flaresolverr: + image: ghcr.io/flaresolverr/flaresolverr:latest + profiles: ["flaresolverr"] + environment: + TZ: "${TZ:-Asia/Shanghai}" + LOG_LEVEL: info + restart: unless-stopped +``` + +启动: + +```bash +docker compose \ + -f docker-compose.yml \ + -f compose.flaresolverr.yml \ + --profile flaresolverr up -d +``` + +在管理端将 Clearance 模式设置为 `FlareSolverr`,地址填写: + +```text +http://flaresolverr:8191 +``` + +不需要把 `8191` 映射到公网。 + +--- + + + +### Egress Quality Guard + +Egress Quality Guard 是 Grok Build 出口质量守护 sidecar,支持主动/被动质量检测、隔离和健康恢复。普通 Grok2API 推理不依赖该服务。 + +#### 应用配置 + +方案一或方案二直接修改 `config.yaml`;方案三需在 `config.node-1.yaml` 和 `config.node-2.yaml` 中写入相同的配置: + +```yaml +qualityGuard: + enabled: true + model: "grok-4.5" + mode: hybrid + activeInterval: 30m + passivePollInterval: 5s + softTPS: 500 + hardTPS: 1000 + consecutiveSoft: 2 + consecutiveErrors: 2 + quarantineDuration: 5m + noAccountBackoff: 5m + minimumHealthyNodes: 3 + failClosed: false + nodeIDs: [] +``` + +`nodeIDs` 为空时管理全部符合条件的 Grok Build 节点。阈值应先结合真实流量观察,再决定是否启用严格隔离。 + +#### Compose 配置 + +三套方案中的主服务都命名为 `grok2api`,因此可以共用以下扩展: + +```yaml +services: + grok2api: + environment: + GROK2API_QUALITY_GUARD_DIR: /var/lib/grok2api-quality-guard + volumes: + - quality_guard_state:/var/lib/grok2api-quality-guard + + egress-quality-guard: + profiles: ["quality-guard"] + build: + context: . + dockerfile: tools/egress-quality-guard/Dockerfile + depends_on: + grok2api: + condition: service_healthy + volumes: + - quality_guard_state:/var/lib/grok2api-quality-guard + restart: "on-failure:5" + init: true + stop_grace_period: 30s + security_opt: + - no-new-privileges:true + +volumes: + quality_guard_state: +``` + +方案三还应让第二个应用实例挂载同一个私有状态卷。在上述 `compose.quality-guard.yml` 的 `services` 中追加: + +```yaml + grok2api-2: + environment: + GROK2API_QUALITY_GUARD_DIR: /var/lib/grok2api-quality-guard + volumes: + - quality_guard_state:/var/lib/grok2api-quality-guard +``` + +只启动一个 `egress-quality-guard` sidecar 即可。它固定通过 Compose 内网访问 `grok2api:8000`;第二个应用实例挂载状态卷,是为了让管理请求经负载均衡命中任意实例时,都能读取相同的守护状态与热更新策略。 + +启动: + +```bash +docker compose \ + -f docker-compose.yml \ + -f compose.quality-guard.yml \ + --profile quality-guard up -d --build +``` + +主程序会自动创建不可导出的内部探测身份,并把受限凭据写入私有共享卷;无需配置 Client Key ID。修改 `qualityGuard` 启动配置后,应重启主服务和 sidecar: + +```bash +docker compose \ + -f docker-compose.yml \ + -f compose.quality-guard.yml \ + --profile quality-guard restart grok2api egress-quality-guard +``` + +方案三同时修改了两个节点的启动配置时,将上述命令的服务列表改为 `grok2api grok2api-2 egress-quality-guard`。管理界面保存的运行策略会通过共享状态卷热加载,不需要重启。 + +只停止守护程序不会影响主 API: + +```bash +docker compose \ + -f docker-compose.yml \ + -f compose.quality-guard.yml \ + --profile quality-guard stop egress-quality-guard +``` + +--- + + + +### 组合启用 + +Compose 扩展可以叠加。例如同时启用 WARP、FlareSolverr 和 Quality Guard: + +```bash +docker compose \ + -f docker-compose.yml \ + -f compose.warp.yml \ + -f compose.flaresolverr.yml \ + -f compose.quality-guard.yml \ + --profile warp \ + --profile flaresolverr \ + --profile quality-guard \ + up -d --build +``` + +扩展文件只增加对应服务,不改变主数据库方案。排查问题时可逐个移除扩展文件,以区分主程序故障和扩展组件故障。 + +--- + + + +## 反向代理 + +生产环境应通过 Nginx、Caddy、Traefik、Nginx Proxy Manager 或云负载均衡器终止 TLS。启用 HTTPS 后,将应用配置调整为: + +```yaml +auth: + secureCookies: true + +frontend: + publicApiBaseURL: "https://grok.example.com" +``` + +单实例 Nginx 核心配置: + +```nginx +location / { + proxy_pass http://127.0.0.1:8000; + proxy_http_version 1.1; + + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; +} +``` + +方案三可以定义双节点 upstream: + +```nginx +upstream grok2api_backend { + server 127.0.0.1:8001; + server 127.0.0.1:8002; + keepalive 32; +} + +location / { + proxy_pass http://grok2api_backend; + proxy_http_version 1.1; + + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; +} +``` + +关闭代理缓冲对于 Responses、Chat 和 Messages 的 SSE 流式输出非常重要。反向代理与 Grok2API 不在同一主机时,应使用受控内网地址或 Docker 网络服务名,不能使用远端主机的 `127.0.0.1`。 + +--- + + + +## 运维管理 + + + +### 升级 + +```bash +git pull --ff-only +docker compose pull +docker compose up -d +docker compose ps +docker compose logs --tail=200 grok2api +``` + +生产环境建议通过 `.env` 固定已验证镜像版本: + +```dotenv +GROK2API_IMAGE=ghcr.io/chenyme/grok2api:替换为已验证版本 +``` + +不要在升级时执行 `docker compose down -v`,其中 `-v` 会删除 Compose 管理的数据卷。 + +### SQLite 备份 + +方案一需要备份 `config.yaml` 和 `grok2api_grok2api-data` 卷。为获得一致的 SQLite 备份,可以短暂停止主服务: + +```bash +mkdir -p backups +docker compose stop grok2api +docker run --rm \ + -v grok2api_grok2api-data:/data:ro \ + -v "$PWD/backups:/backup" \ + alpine:3.23 \ + tar -czf /backup/grok2api-data.tar.gz -C /data . +docker compose start grok2api +``` + + + +### PostgreSQL 与多实例备份 + +PostgreSQL 应使用数据库平台快照、PITR 或与服务器版本匹配的 `pg_dump`。本地媒体卷仍需单独备份。方案三还应保留两个节点配置及 Redis 配置;Redis 主要保存运行态,不能替代 PostgreSQL 数据备份。 + +任何回滚都应同时考虑应用镜像和数据库 Schema。旧镜像不代表数据库可以自动降级,重大升级前应在独立环境验证恢复流程。 + +--- + + + +## 故障排查 + + + +### 配置文件未挂载 + +```text +missing config: /run/grok2api/config.yaml +``` + +检查 Compose 挂载路径及文件是否存在: + +```bash +ls -l config*.yaml +docker compose config +``` + + + +### 就绪检查失败 + +进程存活不代表依赖已经就绪。检查数据库、Redis 和启动迁移日志: + +```bash +docker compose logs --tail=300 grok2api postgres redis +``` + +方案中没有对应服务时,从命令中移除其名称。 + +### PostgreSQL 连接失败 + +检查: + +- URL 是否使用 `postgres://` 或 `postgresql://`; +- 是否误用了 SQLAlchemy 的 `postgresql+asyncpg://`; +- DSN 中的密码是否正确 URL 编码; +- 数据库域名、端口、安全组、IP 白名单及 `sslmode` 是否正确; +- “副本数 × maxOpenConns”是否超过数据库连接上限。 + +Grok2API 会对连接错误中的完整 DSN 和密码进行脱敏。 + +### 多实例校验失败 + +重点核对: + +- `database.driver=postgres`; +- `runtimeStore.driver=redis`; +- 两个节点的 `instanceID` 不同; +- `clusterID` 和应用密钥相同; +- `sharedMedia=true`; +- 两个容器挂载同一个媒体卷。 + + + +### SSE 响应被缓冲 + +确认反向代理已关闭 `proxy_buffering` 与缓存,并设置足够长的读取超时。 + +### 模型列表为空 + +检查账号是否启用、凭据是否有效、模型能力同步是否完成,以及管理端是否存在可用模型路由。Build 模型按账号能力动态发现,不应依赖静态模型清单。 + +--- + + + +## 生产检查清单 + +- [ ] 所有示例密钥和密码均已替换; +- [ ] 首次登录后已删除 `bootstrapAdmin`; +- [ ] 已离线备份且固定 `credentialEncryptionKey`; +- [ ] 配置文件与 `.env` 权限为 `0600`; +- [ ] PostgreSQL、Redis 和代理端口未直接暴露到公网; +- [ ] 公网入口已启用 HTTPS 和 `auth.secureCookies`; +- [ ] 反向代理已关闭 SSE 缓冲; +- [ ] 客户端密钥已配置模型白名单、RPM、并发和用量限制; +- [ ] 数据库、媒体目录和配置文件均有可恢复备份; +- [ ] `/healthz` 与 `/readyz` 已纳入监控; +- [ ] 多实例的 `instanceID` 唯一,`clusterID` 与应用密钥一致; +- [ ] WARP、FlareSolverr 和 Quality Guard 仅在存在明确需求时启用。 + + + +## 结语 + +三套方案的核心区别不是组件数量,而是状态边界:SQLite 适合单实例基线,PostgreSQL 适合独立数据库管理,PostgreSQL + Redis + 共享媒体才满足多实例前提。出口扩展应作为独立 Compose 层按需叠加,不应与数据库架构绑定。 + +按照这种拆分方式,部署文件可以直接复用,故障定位也更清晰:先验证主方案,再逐项启用网络和质量治理扩展。 \ No newline at end of file diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index ef7b974e..2808d4d8 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -222,7 +222,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat cliAdapter.SetReasoningReplay(reasoningReplay) webAdapter := webprovider.NewAdapter(webProviderConfig(cfg), egressManager, cipher, responseRepo, mediaService) webAdapter.SetLogger(logger) - consoleAdapter := consoleprovider.NewAdapter(consoleProviderConfig(cfg), egressManager, cipher) + consoleAdapter := consoleprovider.NewAdapter(consoleProviderConfig(cfg), egressManager, cipher, mediaService) providers := provider.NewRegistry(cliAdapter, webAdapter, consoleAdapter) if err := providers.Validate(); err != nil { if runtimeStore != nil { @@ -562,8 +562,8 @@ func (a *Application) Run(ctx context.Context) error { a.quotaRecovery.Run(taskCtx) return nil }) - startBackground("web_quota_refresh", func(taskCtx context.Context) error { - a.accounts.RunWebQuotaRefresh(taskCtx) + startBackground("quota_refresh", func(taskCtx context.Context) error { + a.accounts.RunQuotaRefresh(taskCtx) return nil }) startBackground("credential_refresh", func(taskCtx context.Context) error { @@ -582,6 +582,10 @@ func (a *Application) Run(ctx context.Context) error { a.runWebQuotaCatchup(taskCtx) return nil }) + startBackground("console_usage_migration", func(taskCtx context.Context) error { + a.runConsoleUsageMigration(taskCtx) + return nil + }) startBackground("model_catalog_startup_catchup", func(taskCtx context.Context) error { a.runModelCatalogCatchup(taskCtx) return nil diff --git a/backend/internal/app/console_routes_test.go b/backend/internal/app/console_routes_test.go index 0efe0901..01331b52 100644 --- a/backend/internal/app/console_routes_test.go +++ b/backend/internal/app/console_routes_test.go @@ -13,20 +13,31 @@ func TestConsoleRoutesUseStableProviderNamespace(t *testing.T) { if len(routes) == 0 { t.Fatal("console catalog is empty") } - seen := make(map[string]bool, len(routes)) + seen := make(map[string]map[string]bool, len(routes)) for _, route := range routes { if route.Provider != account.ProviderConsole || !strings.HasPrefix(route.PublicID, "Console/") { t.Fatalf("non-canonical console route = %#v", route) } - if seen[route.PublicID] { - t.Fatalf("duplicate console public id %q", route.PublicID) + if seen[route.PublicID] == nil { + seen[route.PublicID] = make(map[string]bool) } - seen[route.PublicID] = true + if seen[route.PublicID][string(route.Capability)] { + t.Fatalf("duplicate console public id/capability %q/%q", route.PublicID, route.Capability) + } + seen[route.PublicID][string(route.Capability)] = true } - if seen["Console/grok-4.3-console"] { + if seen["Console/grok-4.3-console"] != nil { t.Fatal("legacy conflict suffix leaked into canonical Console model IDs") } - if !seen["Console/grok-4.3"] { + if seen["Console/grok-4.3"] == nil { t.Fatal("canonical Console/grok-4.3 route is missing") } + for _, modelID := range []string{"Console/grok-imagine-image-quality", "Console/grok-imagine-image"} { + if !seen[modelID]["image"] || !seen[modelID]["image_edit"] { + t.Fatalf("Console image route capabilities for %s = %#v", modelID, seen[modelID]) + } + } + if !seen["Console/grok-imagine-video"]["video"] { + t.Fatal("Console video route is missing") + } } diff --git a/backend/internal/app/startup.go b/backend/internal/app/startup.go index 71b4c7be..12eadcf1 100644 --- a/backend/internal/app/startup.go +++ b/backend/internal/app/startup.go @@ -16,14 +16,16 @@ import ( ) const ( - startupRecoveryBudget = 20 * time.Second - startupCriticalWindow = 2 * time.Minute - startupCriticalLimit = 100 - statsigWarmupInterval = 15 * time.Minute - webQuotaStaleAfter = 30 * time.Minute - webQuotaCatchupEvery = 30 * time.Minute - modelCatalogStaleAfter = 24 * time.Hour - modelCatalogCatchupEvery = 6 * time.Hour + startupRecoveryBudget = 20 * time.Second + startupCriticalWindow = 2 * time.Minute + startupCriticalLimit = 100 + statsigWarmupInterval = 15 * time.Minute + webQuotaStaleAfter = 30 * time.Minute + webQuotaCatchupEvery = 30 * time.Minute + consoleUsageMigrationEvery = 24 * time.Hour + consoleUsageMigrationRetry = 5 * time.Minute + modelCatalogStaleAfter = 24 * time.Hour + modelCatalogCatchupEvery = 6 * time.Hour ) type startupReport struct { @@ -381,7 +383,7 @@ func (a *Application) queueDueWebQuotaRefresh(ctx context.Context) { return } for _, window := range windows { - a.accounts.QueueWebQuotaRefresh(window.AccountID, window.Mode) + a.accounts.QueueQuotaRefresh(window.AccountID, window.Mode) } a.startup.updateReport(func(report *startupReport) { report.DueWebQuotasQueued = len(windows) }) if len(windows) > 0 { @@ -416,6 +418,30 @@ func (a *Application) runWebQuotaCatchup(ctx context.Context) { } } +func (a *Application) runConsoleUsageMigration(ctx context.Context) { + timer := time.NewTimer(5 * time.Second) + defer timer.Stop() + for { + select { + case <-ctx.Done(): + return + case <-timer.C: + } + succeeded, failed, err := a.accounts.SyncIncompleteConsoleQuotas(ctx) + nextRun := consoleUsageMigrationEvery + if err != nil && ctx.Err() == nil { + a.logger.Warn("console_usage_migration_failed", "succeeded", succeeded, "failed", failed, "error", err) + nextRun = consoleUsageMigrationRetry + } else if failed > 0 { + a.logger.Warn("console_usage_migration_incomplete", "succeeded", succeeded, "failed", failed) + nextRun = consoleUsageMigrationRetry + } else if succeeded > 0 { + a.logger.Info("console_usage_migration_completed", "succeeded", succeeded, "failed", failed) + } + resetTimer(timer, nextRun) + } +} + func (a *Application) runModelCatalogCatchup(ctx context.Context) { timer := time.NewTimer(20 * time.Second) defer timer.Stop() diff --git a/backend/internal/application/account/console_quota_test.go b/backend/internal/application/account/console_quota_test.go index 6579add5..e7675b2a 100644 --- a/backend/internal/application/account/console_quota_test.go +++ b/backend/internal/application/account/console_quota_test.go @@ -7,19 +7,76 @@ import ( accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" ) -func TestPreserveActiveQuotaWindowsUntilReset(t *testing.T) { +func TestPreserveActiveLocalQuotaWindowsUntilReset(t *testing.T) { now := time.Now().UTC() future := now.Add(time.Hour) past := now.Add(-time.Second) - incoming := []accountdomain.QuotaWindow{{Mode: "console", Remaining: 20, Total: 20}} + incoming := []accountdomain.QuotaWindow{{Mode: "fast", Remaining: 20, Total: 20}} - active := preserveActiveQuotaWindows([]accountdomain.QuotaWindow{{Mode: "console", Remaining: 7, Total: 20, ResetAt: &future}}, incoming, now) + active := preserveActiveQuotaWindows([]accountdomain.QuotaWindow{{Mode: "fast", Remaining: 7, Total: 20, ResetAt: &future}}, incoming, now) if len(active) != 1 || active[0].Remaining != 7 { t.Fatalf("active window = %#v", active) } - expired := preserveActiveQuotaWindows([]accountdomain.QuotaWindow{{Mode: "console", Remaining: 0, Total: 20, ResetAt: &past}}, incoming, now) + expired := preserveActiveQuotaWindows([]accountdomain.QuotaWindow{{Mode: "fast", Remaining: 0, Total: 20, ResetAt: &past}}, incoming, now) if len(expired) != 1 || expired[0].Remaining != 20 { t.Fatalf("expired window = %#v", expired) } } + +func TestQuotaRecoveryDueAtSchedulesUnknownRemoteWindowProbe(t *testing.T) { + now := time.Date(2026, 8, 5, 8, 0, 0, 0, time.UTC) + window := accountdomain.QuotaWindow{Mode: "console", Remaining: 0, Source: accountdomain.QuotaSourceUpstream} + dueAt := quotaRecoveryDueAt(window, now, true) + if dueAt == nil || !dueAt.Equal(now.Add(consolePredictedQuotaProbeDelay)) { + t.Fatalf("Console predicted dueAt = %v", dueAt) + } + if value := quotaRecoveryDueAt(window, now, false); value != nil { + t.Fatalf("available window dueAt = %v", value) + } + window = accountdomain.QuotaWindow{Mode: "fast", Remaining: 0, Source: accountdomain.QuotaSourceDefault} + if value := quotaRecoveryDueAt(window, now, true); value != nil { + t.Fatalf("unknown local window dueAt = %v", value) + } + window.Source = accountdomain.QuotaSourceUpstream + if value := quotaRecoveryDueAt(window, now, true); value == nil || !value.Equal(now.Add(unknownRemoteQuotaProbeDelay)) { + t.Fatalf("generic remote dueAt = %v", value) + } +} + +func TestCompleteConsoleUsageSnapshotRejectsLegacyAndPartialWindows(t *testing.T) { + now := time.Now().UTC() + legacy := []accountdomain.QuotaWindow{{Mode: "console", Source: accountdomain.QuotaSourceDefault, SyncedAt: &now}} + if completeConsoleUsageSnapshot(legacy) { + t.Fatal("legacy synthetic Console window was accepted") + } + partial := []accountdomain.QuotaWindow{ + {Mode: "console", Source: accountdomain.QuotaSourceUpstream, SyncedAt: &now}, + {Mode: "console_image", Source: accountdomain.QuotaSourceUpstream, SyncedAt: &now}, + } + if completeConsoleUsageSnapshot(partial) { + t.Fatal("partial Console usage snapshot was accepted") + } + complete := append(partial, accountdomain.QuotaWindow{Mode: "console_video", Source: accountdomain.QuotaSourceUpstream, SyncedAt: &now}) + if !completeConsoleUsageSnapshot(complete) { + t.Fatal("complete Console usage snapshot was rejected") + } +} + +func TestConsoleQuotaWindowsControlTheirMatchingRoutes(t *testing.T) { + for _, mode := range []string{"console", "console_image", "console_video"} { + if !quotaWindowControlsRouting(accountdomain.ProviderConsole, mode) { + t.Fatalf("%s must control its matching Console route", mode) + } + window := accountdomain.QuotaWindow{Mode: mode, Remaining: 0, Source: accountdomain.QuotaSourceUpstream} + if dueAt := quotaRecoveryDueAt(window, time.Now().UTC(), true); dueAt == nil { + t.Fatalf("%s must schedule a predicted recovery probe", mode) + } + } + if quotaWindowControlsRouting(accountdomain.ProviderConsole, "unknown") { + t.Fatal("unknown Console quota mode must not control routing") + } + if !quotaWindowControlsRouting(accountdomain.ProviderWeb, "weekly") { + t.Fatal("Web quota behavior must remain unchanged") + } +} diff --git a/backend/internal/application/account/export_test.go b/backend/internal/application/account/export_test.go index e082b8a0..b49cb067 100644 --- a/backend/internal/application/account/export_test.go +++ b/backend/internal/application/account/export_test.go @@ -201,7 +201,7 @@ func TestExportProviderCredentialsRoundTripsSSOProviders(t *testing.T) { webTier accountdomain.WebTier }{ {name: "web", providerValue: accountdomain.ProviderWeb, adapter: webprovider.NewAdapter(webprovider.Config{}, nil, nil, nil, nil), webTier: accountdomain.WebTierSuper}, - {name: "console", providerValue: accountdomain.ProviderConsole, adapter: consoleprovider.NewAdapter(consoleprovider.Config{}, nil, nil)}, + {name: "console", providerValue: accountdomain.ProviderConsole, adapter: consoleprovider.NewAdapter(consoleprovider.Config{}, nil, nil, nil)}, } { t.Run(test.name, func(t *testing.T) { ctx := context.Background() diff --git a/backend/internal/application/account/quota_refresh_redis_integration_test.go b/backend/internal/application/account/quota_refresh_redis_integration_test.go index 17b4839d..0dd14ca0 100644 --- a/backend/internal/application/account/quota_refresh_redis_integration_test.go +++ b/backend/internal/application/account/quota_refresh_redis_integration_test.go @@ -81,8 +81,8 @@ func TestRedisQuotaRefreshCrossInstanceTrailing(t *testing.T) { runCtx, cancel := context.WithCancel(ctx) done := make(chan struct{}, 2) - go func() { first.RunWebQuotaRefresh(runCtx); done <- struct{}{} }() - go func() { second.RunWebQuotaRefresh(runCtx); done <- struct{}{} }() + go func() { first.RunQuotaRefresh(runCtx); done <- struct{}{} }() + go func() { second.RunQuotaRefresh(runCtx); done <- struct{}{} }() t.Cleanup(func() { for range 4 { adapter.modeRelease <- struct{}{} @@ -128,7 +128,7 @@ func TestRedisQuotaRefreshCrossInstanceTrailing(t *testing.T) { if calls := adapter.modeCalls.Load(); calls != 2 { t.Fatalf("Redis-backed refresh calls = %d, want 2", calls) } - time.Sleep(2 * webQuotaRefreshRetryInterval) + time.Sleep(2 * quotaRefreshPollInterval) if calls := adapter.modeCalls.Load(); calls != 2 { t.Fatalf("Redis-backed losing instance performed duplicate refresh: %d", calls) } diff --git a/backend/internal/application/account/quota_refresh_test.go b/backend/internal/application/account/quota_refresh_test.go index 2a377e00..95cd2e0d 100644 --- a/backend/internal/application/account/quota_refresh_test.go +++ b/backend/internal/application/account/quota_refresh_test.go @@ -18,13 +18,16 @@ import ( func TestWebQuotaRefreshDeduplicatesPerMode(t *testing.T) { service := NewService(nil, nil, nil, nil, nil, nil, nil) - service.QueueWebQuotaRefresh(42, "fast") - service.QueueWebQuotaRefresh(42, "expert") - service.QueueWebQuotaRefresh(42, "fast") + service.QueueQuotaRefresh(42, "fast") + service.QueueQuotaRefresh(42, "expert") + service.QueueQuotaRefresh(42, "fast") + service.QueueQuotaRefresh(43, "console") + service.QueueQuotaRefresh(43, "console_image") + service.QueueQuotaRefresh(43, "console_video") service.quotaRefreshMu.Lock() defer service.quotaRefreshMu.Unlock() - if len(service.quotaRefreshes) != 2 { + if len(service.quotaRefreshes) != 5 { t.Fatalf("refresh states = %#v", service.quotaRefreshes) } if service.quotaRefreshes["42:fast"].generation != 2 || !service.quotaRefreshes["42:fast"].queued { @@ -33,7 +36,15 @@ func TestWebQuotaRefreshDeduplicatesPerMode(t *testing.T) { if service.quotaRefreshes["42:expert"].generation != 1 || !service.quotaRefreshes["42:expert"].queued { t.Fatal("independent expert refresh state is invalid") } - if len(service.quotaRefreshQueue) != 2 { + if service.quotaRefreshes["43:console"].generation != 1 || !service.quotaRefreshes["43:console"].queued { + t.Fatal("Console refresh state is invalid") + } + for _, mode := range []string{"console_image", "console_video"} { + if state := service.quotaRefreshes["43:"+mode]; state == nil || state.generation != 1 || !state.queued { + t.Fatalf("Console %s refresh state is invalid: %#v", mode, state) + } + } + if len(service.quotaRefreshQueue) != 5 { t.Fatalf("queued refreshes = %d", len(service.quotaRefreshQueue)) } } @@ -67,7 +78,7 @@ func TestWeeklyQuotaRefreshPreservesTrailingSnapshot(t *testing.T) { request := <-service.quotaRefreshQueue done := make(chan struct{}) go func() { - service.runWebQuotaRefresh(ctx, request) + service.runQuotaRefresh(ctx, request) close(done) }() @@ -104,7 +115,7 @@ func TestWeeklyQuotaRefreshPreservesTrailingSnapshot(t *testing.T) { func TestQuotaRefreshQueueOverflowRetainsDirtyState(t *testing.T) { service := NewService(nil, nil, nil, nil, nil, nil, nil) - service.quotaRefreshQueue = make(chan webQuotaRefreshRequest, 1) + service.quotaRefreshQueue = make(chan quotaRefreshRequest, 1) service.QueueQuotaRefresh(1, "fast") service.QueueQuotaRefresh(2, "fast") @@ -133,6 +144,75 @@ func TestQuotaRefreshQueueOverflowRetainsDirtyState(t *testing.T) { } } +func TestQuotaRefreshFailureUsesBoundedExponentialBackoff(t *testing.T) { + service := NewService(nil, nil, nil, nil, nil, nil, nil) + now := time.Date(2026, 8, 5, 8, 0, 0, 0, time.UTC) + service.now = func() time.Time { return now } + service.quotaRefreshes["1:console"] = "aRefreshState{running: true} + for failure := 1; failure <= 10; failure++ { + service.deferQuotaRefresh("1:console") + state := service.quotaRefreshes["1:console"] + maximum := quotaRefreshBackoffBase * time.Duration(1< quotaRefreshBackoffMax { + maximum = quotaRefreshBackoffMax + } + delay := state.nextAttemptAt.Sub(now) + if state.failures != failure || !state.pending || delay < maximum/2 || delay > maximum { + t.Fatalf("failure=%d state=%#v delay=%s range=[%s,%s]", failure, state, delay, maximum/2, maximum) + } + } +} + +func TestRecentConsoleUsageSnapshotSuppressesDuplicateUpstreamRefresh(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "console-refresh-throttle.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = database.Close() }) + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := relational.NewAccountRepository(database) + credential, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderConsole, AuthType: accountdomain.AuthTypeSSO, + Name: "console-throttle", SourceKey: "console-throttle", EncryptedAccessToken: "encrypted", + Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + now := time.Date(2026, 8, 5, 8, 0, 0, 0, time.UTC) + windows := []accountdomain.QuotaWindow{ + {AccountID: credential.ID, Mode: "console", Remaining: 9, Total: 10, SyncedAt: &now, Source: accountdomain.QuotaSourceUpstream, UpdatedAt: now}, + {AccountID: credential.ID, Mode: "console_image", Remaining: 5, Total: 5, SyncedAt: &now, Source: accountdomain.QuotaSourceUpstream, UpdatedAt: now}, + {AccountID: credential.ID, Mode: "console_video", Remaining: 2, Total: 2, SyncedAt: &now, Source: accountdomain.QuotaSourceUpstream, UpdatedAt: now}, + } + if err := accounts.ReplaceQuotaWindows(ctx, credential.ID, "", now, windows); err != nil { + t.Fatal(err) + } + adapter := &consoleQuotaSnapshotAdapter{} + service := NewService(accounts, nil, nil, nil, provider.NewRegistry(adapter), nil, nil) + service.now = func() time.Time { return now.Add(10 * time.Second) } + service.QueueQuotaRefresh(credential.ID, "console") + request := <-service.quotaRefreshQueue + service.quotaRefreshMu.Lock() + state := service.quotaRefreshes[request.key] + state.queued = false + state.running = true + service.quotaRefreshMu.Unlock() + service.runQuotaRefresh(ctx, request) + if adapter.fullCalls.Load() != 0 { + t.Fatalf("recent Console snapshot triggered %d upstream refreshes", adapter.fullCalls.Load()) + } + service.quotaRefreshMu.Lock() + state = service.quotaRefreshes[request.key] + service.quotaRefreshMu.Unlock() + if state == nil || state.running || state.pending || !state.nextAttemptAt.Equal(now.Add(10*time.Second+consoleQuotaRefreshMinInterval)) { + t.Fatalf("Console cooldown state = %#v", state) + } +} + func TestQuotaRefreshCrossInstanceGenerationTriggersSingleTrailingRefresh(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "quota-cross-instance.db")) @@ -162,8 +242,8 @@ func TestQuotaRefreshCrossInstanceGenerationTriggersSingleTrailingRefresh(t *tes second.SetQuotaRefreshCoordinator(coordinator) runCtx, cancel := context.WithCancel(ctx) done := make(chan struct{}, 2) - go func() { first.RunWebQuotaRefresh(runCtx); done <- struct{}{} }() - go func() { second.RunWebQuotaRefresh(runCtx); done <- struct{}{} }() + go func() { first.RunQuotaRefresh(runCtx); done <- struct{}{} }() + go func() { second.RunQuotaRefresh(runCtx); done <- struct{}{} }() t.Cleanup(func() { for range 4 { adapter.modeRelease <- struct{}{} @@ -209,7 +289,7 @@ func TestQuotaRefreshCrossInstanceGenerationTriggersSingleTrailingRefresh(t *tes if calls := adapter.modeCalls.Load(); calls != 2 { t.Fatalf("refresh calls = %d, want 2", calls) } - time.Sleep(2 * webQuotaRefreshRetryInterval) + time.Sleep(2 * quotaRefreshPollInterval) if calls := adapter.modeCalls.Load(); calls != 2 { t.Fatalf("losing instance performed duplicate refresh: %d", calls) } @@ -254,7 +334,7 @@ func TestRefreshQuotaModeDoesNotTriggerFullProviderSyncForAutoTier(t *testing.T) service.QueueQuotaRefresh(credential.ID, "fast") service.QueueQuotaRefresh(credential.ID, "fast") request := <-service.quotaRefreshQueue - service.runWebQuotaRefresh(ctx, request) + service.runQuotaRefresh(ctx, request) if adapter.modeCalls.Load() != 2 || adapter.fullCalls.Load() != 0 { t.Fatalf("coalesced mode calls = %d, full calls = %d", adapter.modeCalls.Load(), adapter.fullCalls.Load()) } @@ -268,12 +348,184 @@ func TestRefreshQuotaModeDoesNotTriggerFullProviderSyncForAutoTier(t *testing.T) service.refreshLock = deniedQuotaRefreshLock{} service.QueueQuotaRefresh(credential.ID, "fast") request = <-service.quotaRefreshQueue - service.runWebQuotaRefresh(ctx, request) + service.runQuotaRefresh(ctx, request) if adapter.modeCalls.Load() != 2 { t.Fatalf("worker without distributed lease made %d mode calls", adapter.modeCalls.Load()) } } +func TestRefreshConsoleQuotaModePersistsCompleteUsageSnapshot(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "console-quota-mode.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = database.Close() }) + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := relational.NewAccountRepository(database) + credential, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderConsole, AuthType: accountdomain.AuthTypeSSO, + Name: "console", SourceKey: "console", EncryptedAccessToken: "encrypted", + Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + if err := accounts.SaveQuotaWindows(ctx, credential.ID, "", now, []accountdomain.QuotaWindow{{ + AccountID: credential.ID, Mode: "console", Remaining: 20, Total: 20, + WindowSeconds: 3600, Source: accountdomain.QuotaSourceDefault, UpdatedAt: now, + }}); err != nil { + t.Fatal(err) + } + adapter := &consoleQuotaSnapshotAdapter{} + service := NewService(accounts, nil, nil, nil, provider.NewRegistry(adapter), nil, nil) + queue := memory.NewQuotaRecoveryQueue() + service.SetQuotaRecoveryQueue(queue) + if err := queue.ScheduleQuotaRecovery(ctx, accountdomain.QuotaRecoveryEvent{AccountID: credential.ID, Mode: "console", DueAt: now.Add(24 * time.Hour)}); err != nil { + t.Fatal(err) + } + window, err := service.RefreshQuotaMode(ctx, credential.ID, "console") + if err != nil { + t.Fatal(err) + } + if window.Remaining != 9 || adapter.fullCalls.Load() != 1 || adapter.modeCalls.Load() != 0 { + t.Fatalf("window=%#v full=%d mode=%d", window, adapter.fullCalls.Load(), adapter.modeCalls.Load()) + } + stored, err := accounts.GetQuotaWindows(ctx, []uint64{credential.ID}) + if err != nil { + t.Fatal(err) + } + if values := stored[credential.ID]; len(values) != 3 || !completeConsoleUsageSnapshot(values) { + t.Fatalf("stored Console usage snapshot = %#v", values) + } + if values, claimErr := queue.ClaimDueQuotaRecoveries(ctx, now.Add(25*time.Hour), 1, time.Minute); claimErr != nil || len(values) != 0 { + t.Fatalf("healthy Console refresh retained stale recovery event: %#v, err = %v", values, claimErr) + } +} + +func TestConsoleFullAndModeQuotaRefreshShareOneSnapshot(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "console-quota-singleflight.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = database.Close() }) + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := relational.NewAccountRepository(database) + credential, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderConsole, AuthType: accountdomain.AuthTypeSSO, + Name: "console-singleflight", SourceKey: "console-singleflight", EncryptedAccessToken: "encrypted", + Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + adapter := &consoleQuotaSnapshotAdapter{fullStarted: make(chan struct{}, 1), fullRelease: make(chan struct{})} + service := NewService(accounts, nil, nil, nil, provider.NewRegistry(adapter), nil, nil) + + fullDone := make(chan error, 1) + go func() { + windows, refreshErr := service.RefreshQuota(ctx, credential.ID) + if refreshErr == nil && len(windows) != 3 { + refreshErr = errors.New("full refresh did not return complete Console snapshot") + } + fullDone <- refreshErr + }() + select { + case <-adapter.fullStarted: + case <-time.After(time.Second): + t.Fatal("full Console quota refresh did not start") + } + probeDone := make(chan error, 1) + go func() { + window, probeErr := service.ProbeQuotaMode(ctx, credential.ID, "console") + if probeErr == nil && window.Remaining != 9 { + probeErr = errors.New("mode probe did not receive shared Console snapshot") + } + probeDone <- probeErr + }() + // Give the second caller time to join the in-flight singleflight call before + // releasing the adapter. A duplicate call remains observable via fullCalls. + time.Sleep(20 * time.Millisecond) + close(adapter.fullRelease) + if err := <-fullDone; err != nil { + t.Fatal(err) + } + if err := <-probeDone; err != nil { + t.Fatal(err) + } + if calls := adapter.fullCalls.Load(); calls != 1 { + t.Fatalf("Console full and mode refresh made %d upstream calls", calls) + } +} + +func TestSyncIncompleteConsoleQuotasMigratesOnlyLegacySnapshot(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "console-quota-migration.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = database.Close() }) + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := relational.NewAccountRepository(database) + now := time.Now().UTC() + create := func(name string, windows []accountdomain.QuotaWindow) uint64 { + credential, _, createErr := accounts.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderConsole, AuthType: accountdomain.AuthTypeSSO, + Name: name, SourceKey: name, EncryptedAccessToken: "encrypted", Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + }) + if createErr != nil { + t.Fatal(createErr) + } + for index := range windows { + windows[index].AccountID = credential.ID + } + if err := accounts.ReplaceQuotaWindows(ctx, credential.ID, "", now, windows); err != nil { + t.Fatal(err) + } + return credential.ID + } + legacyID := create("legacy-console", []accountdomain.QuotaWindow{{Mode: "console", Remaining: 20, Total: 20, SyncedAt: &now, Source: accountdomain.QuotaSourceDefault, UpdatedAt: now}}) + completeWindows := []accountdomain.QuotaWindow{ + {Mode: "console", Remaining: 9, Total: 10, SyncedAt: &now, Source: accountdomain.QuotaSourceUpstream, UpdatedAt: now}, + {Mode: "console_image", Remaining: 5, Total: 5, SyncedAt: &now, Source: accountdomain.QuotaSourceUpstream, UpdatedAt: now}, + {Mode: "console_video", Remaining: 2, Total: 2, SyncedAt: &now, Source: accountdomain.QuotaSourceUpstream, UpdatedAt: now}, + } + completeID := create("complete-console", completeWindows) + adapter := &consoleQuotaSnapshotAdapter{} + service := NewService(accounts, nil, nil, nil, provider.NewRegistry(adapter), nil, nil) + succeeded, failed, err := service.SyncIncompleteConsoleQuotas(ctx) + if err != nil { + t.Fatal(err) + } + if succeeded != 1 || failed != 0 || adapter.fullCalls.Load() != 1 { + t.Fatalf("migration succeeded=%d failed=%d calls=%d", succeeded, failed, adapter.fullCalls.Load()) + } + stored, err := accounts.GetQuotaWindows(ctx, []uint64{legacyID, completeID}) + if err != nil { + t.Fatal(err) + } + if !completeConsoleUsageSnapshot(stored[legacyID]) || !completeConsoleUsageSnapshot(stored[completeID]) { + t.Fatalf("migration snapshots = %#v", stored) + } + blockedID := create("blocked-console", []accountdomain.QuotaWindow{{Mode: "console", Remaining: 20, Total: 20, SyncedAt: &now, Source: accountdomain.QuotaSourceDefault, UpdatedAt: now}}) + service.refreshLock = deniedQuotaRefreshLock{} + succeeded, failed, err = service.SyncIncompleteConsoleQuotas(ctx) + if err != nil { + t.Fatal(err) + } + if succeeded != 0 || failed != 1 { + t.Fatalf("locked migration succeeded=%d failed=%d for account %d", succeeded, failed, blockedID) + } +} + func TestObserveResponseModelCoalescesUnchangedValues(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "observed-model.db")) @@ -584,6 +836,45 @@ type quotaCountingAdapter struct { modeRelease chan struct{} } +type consoleQuotaSnapshotAdapter struct { + fullCalls atomic.Int64 + modeCalls atomic.Int64 + fullStarted chan struct{} + fullRelease chan struct{} +} + +func (a *consoleQuotaSnapshotAdapter) Provider() accountdomain.Provider { + return accountdomain.ProviderConsole +} + +func (a *consoleQuotaSnapshotAdapter) Definition() provider.Definition { + return provider.Definition{ + Provider: accountdomain.ProviderConsole, ModelNamespace: accountdomain.ProviderConsole.ModelNamespace(), + Quota: provider.QuotaRemoteWindow, Credential: provider.CredentialSurface{AuthType: accountdomain.AuthTypeSSO}, + } +} + +func (a *consoleQuotaSnapshotAdapter) SyncQuota(_ context.Context, credential accountdomain.Credential) (provider.QuotaSnapshot, error) { + a.fullCalls.Add(1) + if a.fullStarted != nil { + a.fullStarted <- struct{}{} + } + if a.fullRelease != nil { + <-a.fullRelease + } + now := time.Now().UTC() + return provider.QuotaSnapshot{SyncedAt: now, Windows: []accountdomain.QuotaWindow{ + {AccountID: credential.ID, Mode: "console", Remaining: 9, Total: 10, SyncedAt: &now, Source: accountdomain.QuotaSourceUpstream, UpdatedAt: now}, + {AccountID: credential.ID, Mode: "console_image", Remaining: 4, Total: 5, SyncedAt: &now, Source: accountdomain.QuotaSourceUpstream, UpdatedAt: now}, + {AccountID: credential.ID, Mode: "console_video", Remaining: 2, Total: 2, SyncedAt: &now, Source: accountdomain.QuotaSourceUpstream, UpdatedAt: now}, + }}, nil +} + +func (a *consoleQuotaSnapshotAdapter) SyncQuotaMode(_ context.Context, _ accountdomain.Credential, _ string) (accountdomain.QuotaWindow, error) { + a.modeCalls.Add(1) + return accountdomain.QuotaWindow{}, errors.New("unexpected single-mode Console sync") +} + func (a *quotaCountingAdapter) Provider() accountdomain.Provider { return accountdomain.ProviderWeb } func (a *quotaCountingAdapter) Definition() provider.Definition { diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index e02210f5..3962940c 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "log/slog" + "math/rand/v2" "net/http" "slices" "strconv" @@ -43,6 +44,7 @@ var ( ) var ErrCredentialRefreshPermanent = errors.New("OAuth refresh token 已永久失效") +var errQuotaRefreshBusy = errors.New("额度同步已由其他实例执行") const ( // estimatedFreeTokenLimit is only a fallback until an upstream exhaustion @@ -58,11 +60,16 @@ const ( credentialStateWriteTimeout time.Duration = 5 * time.Second credentialRefreshBatchSize = 100 managedTaskWorkerCeiling = 50 - webQuotaRefreshQueueSize = 4096 - webQuotaRefreshTimeout = 30 * time.Second - webQuotaRefreshDirtyTTL = 24 * time.Hour - webQuotaRefreshRetryInterval = 500 * time.Millisecond - webQuotaRefreshSharedPoll = time.Second + quotaRefreshQueueSize = 4096 + quotaRefreshTimeout = 30 * time.Second + quotaRefreshDirtyTTL = 24 * time.Hour + quotaRefreshPollInterval = 500 * time.Millisecond + quotaRefreshSharedPoll = time.Second + quotaRefreshBackoffBase = time.Second + quotaRefreshBackoffMax = time.Minute + consoleQuotaRefreshMinInterval = 30 * time.Second + unknownRemoteQuotaProbeDelay time.Duration = 5 * time.Minute + consolePredictedQuotaProbeDelay time.Duration = 24 * time.Hour observedModelPersistInterval = 30 * time.Minute observedModelLocalCacheTTL = 5 * time.Second observedModelLockShards = 64 @@ -88,12 +95,14 @@ const ( const permanentRefreshExpiredReason = "OAuth refresh token 已永久失效且 access token 已过期" const buildBotFlagCacheKey = "build-bot-flagged-account-ids" -type webQuotaRefreshState struct { +type quotaRefreshState struct { generation uint64 publishedGeneration uint64 sharedGeneration uint64 queued bool running bool + pending bool + failures int nextAttemptAt time.Time } @@ -108,12 +117,17 @@ type observedModelShard struct { lastCleanupAt time.Time } -type webQuotaRefreshRequest struct { +type quotaRefreshRequest struct { key string accountID uint64 mode string } +type quotaRefreshResult struct { + Credential accountdomain.Credential + Windows []accountdomain.QuotaWindow +} + type QuotaRefreshStats struct { Pending int Queued int @@ -356,8 +370,8 @@ type Service struct { lastRefreshAt map[uint64]time.Time observedModelShards [observedModelLockShards]observedModelShard quotaRefreshMu sync.Mutex - quotaRefreshes map[string]*webQuotaRefreshState - quotaRefreshQueue chan webQuotaRefreshRequest + quotaRefreshes map[string]*quotaRefreshState + quotaRefreshQueue chan quotaRefreshRequest quotaRefreshWake chan struct{} conversionPool *batch.Pool syncPool *batch.Pool @@ -385,11 +399,14 @@ func (s *Service) SetQuotaRefreshCoordinator(value repository.QuotaRefreshCoordi func (s *Service) QuotaRefreshStats() QuotaRefreshStats { s.quotaRefreshMu.Lock() defer s.quotaRefreshMu.Unlock() - result := QuotaRefreshStats{Pending: len(s.quotaRefreshes)} + result := QuotaRefreshStats{} for _, state := range s.quotaRefreshes { if state == nil { continue } + if state.pending || state.queued || state.running { + result.Pending++ + } if state.queued { result.Queued++ } @@ -414,8 +431,8 @@ func NewService(accounts repository.AccountRepository, audits repository.AuditRe return &Service{ accounts: accounts, audits: audits, deviceSessions: deviceSessions, sticky: sticky, providers: providers, cipher: cipher, refreshLock: refreshLock, - lastRefreshAt: make(map[uint64]time.Time), quotaRefreshes: make(map[string]*webQuotaRefreshState), - quotaRefreshQueue: make(chan webQuotaRefreshRequest, webQuotaRefreshQueueSize), + lastRefreshAt: make(map[uint64]time.Time), quotaRefreshes: make(map[string]*quotaRefreshState), + quotaRefreshQueue: make(chan quotaRefreshRequest, quotaRefreshQueueSize), quotaRefreshWake: make(chan struct{}, 1), credentialRefreshWake: make(chan struct{}, 1), autoClean: AutoCleanConfig{ @@ -2560,13 +2577,7 @@ func (s *Service) ExhaustQuota(ctx context.Context, id uint64, mode string, rese if window.Mode != mode { continue } - if window.ResetAt != nil && window.ResetAt.After(s.now()) { - value := *window.ResetAt - resetAt = &value - } else if window.WindowSeconds > 0 { - value := s.now().Add(time.Duration(window.WindowSeconds) * time.Second) - resetAt = &value - } + resetAt = quotaRecoveryDueAt(window, s.now(), true) break } } @@ -2591,64 +2602,61 @@ func (s *Service) RefreshQuota(ctx context.Context, id uint64) ([]accountdomain. if err != nil { return nil, err } - windows, ok := result.([]accountdomain.QuotaWindow) + refreshed, ok := result.(quotaRefreshResult) if !ok { return nil, fmt.Errorf("Provider 额度同步返回类型无效") } - return windows, nil -} - -func (s *Service) RefreshWebQuota(ctx context.Context, id uint64) ([]accountdomain.QuotaWindow, error) { - return s.RefreshQuota(ctx, id) -} - -func (s *Service) refreshQuota(ctx context.Context, id uint64) ([]accountdomain.QuotaWindow, error) { - value, err := s.accounts.Get(ctx, id) - if err != nil { - return nil, mapRepositoryError(err) - } - adapter, ok := s.providers.Quota(value.Provider) - if !ok { - return nil, fmt.Errorf("%s Quota Provider 未注册", value.Provider) - } - snapshot, err := adapter.SyncQuota(ctx, value) - if err != nil { - if errors.Is(err, provider.ErrUnauthorized) { - err = errors.Join(err, s.markSSOCredentialRejected(ctx, value, fmt.Sprintf("%s SSO credential rejected", value.Provider))) - } - return nil, err - } - quotaKind, _ := s.providers.QuotaKind(value.Provider) - if quotaKind == provider.QuotaLocalWindow { - existing, loadErr := s.accounts.GetQuotaWindows(ctx, []uint64{id}) - if loadErr != nil { - return nil, loadErr - } - snapshot.Windows = preserveActiveQuotaWindows(existing[id], snapshot.Windows, s.now()) - } - if err := s.accounts.ReplaceQuotaWindows(ctx, id, snapshot.Tier, snapshot.SyncedAt, snapshot.Windows); err != nil { - return nil, err - } - for _, window := range snapshot.Windows { - if window.Remaining == 0 && window.ResetAt != nil && s.quotaQueue != nil { - if err := s.quotaQueue.ScheduleQuotaRecovery(ctx, accountdomain.QuotaRecoveryEvent{AccountID: id, Mode: window.Mode, DueAt: *window.ResetAt}); err != nil { - return snapshot.Windows, fmt.Errorf("安排额度恢复事件: %w", err) - } - } + if err := s.reconcileQuotaRecoveryWindows(ctx, refreshed.Credential.Provider, id, refreshed.Windows); err != nil { + return refreshed.Windows, err } // 身份补全是非关键操作:只在额度落库和恢复任务调度完成后执行, // 并沿用调用方取消语义,不能反向影响额度同步结果。 + value := refreshed.Credential if (value.Provider == accountdomain.ProviderWeb || value.Provider == accountdomain.ProviderConsole) && ctx.Err() == nil { if strings.TrimSpace(value.UserID) == "" && strings.TrimSpace(value.Email) == "" { if identityErr := s.syncAccountIdentityBestEffort(ctx, id); errors.Is(identityErr, provider.ErrUnauthorized) { - return snapshot.Windows, identityErr + return refreshed.Windows, identityErr } } else { // 已有 Session 身份时只做本地增量关联,不再访问上游。 s.reconcileProviderLinksBestEffort(ctx, id) } } - return snapshot.Windows, nil + return refreshed.Windows, nil +} + +func (s *Service) RefreshWebQuota(ctx context.Context, id uint64) ([]accountdomain.QuotaWindow, error) { + return s.RefreshQuota(ctx, id) +} + +func (s *Service) refreshQuota(ctx context.Context, id uint64) (quotaRefreshResult, error) { + value, err := s.accounts.Get(ctx, id) + if err != nil { + return quotaRefreshResult{}, mapRepositoryError(err) + } + adapter, ok := s.providers.Quota(value.Provider) + if !ok { + return quotaRefreshResult{}, fmt.Errorf("%s Quota Provider 未注册", value.Provider) + } + snapshot, err := adapter.SyncQuota(ctx, value) + if err != nil { + if errors.Is(err, provider.ErrUnauthorized) { + err = errors.Join(err, s.markSSOCredentialRejected(ctx, value, fmt.Sprintf("%s SSO credential rejected", value.Provider))) + } + return quotaRefreshResult{}, err + } + quotaKind, _ := s.providers.QuotaKind(value.Provider) + if quotaKind == provider.QuotaLocalWindow { + existing, loadErr := s.accounts.GetQuotaWindows(ctx, []uint64{id}) + if loadErr != nil { + return quotaRefreshResult{}, loadErr + } + snapshot.Windows = preserveActiveQuotaWindows(existing[id], snapshot.Windows, s.now()) + } + if err := s.accounts.ReplaceQuotaWindows(ctx, id, snapshot.Tier, snapshot.SyncedAt, snapshot.Windows); err != nil { + return quotaRefreshResult{}, err + } + return quotaRefreshResult{Credential: value, Windows: snapshot.Windows}, nil } func preserveActiveQuotaWindows(existing, incoming []accountdomain.QuotaWindow, now time.Time) []accountdomain.QuotaWindow { @@ -2692,84 +2700,215 @@ func (s *Service) ReconcileWebRateLimit(ctx context.Context, id uint64, mode str } func (s *Service) RefreshQuotaMode(ctx context.Context, id uint64, mode string) (accountdomain.QuotaWindow, error) { - key := strings.TrimSpace(mode) + ":" + strconv.FormatUint(id, 10) + mode = strings.TrimSpace(mode) + key := quotaSyncKey(id, mode) result, err, _ := s.quotaSyncs.Do(key, func() (any, error) { return s.refreshQuotaMode(ctx, id, mode) }) if err != nil { return accountdomain.QuotaWindow{}, err } - window, ok := result.(accountdomain.QuotaWindow) + refreshed, ok := result.(quotaRefreshResult) if !ok { return accountdomain.QuotaWindow{}, fmt.Errorf("Provider 模式额度同步返回类型无效") } + window, ok := quotaWindowByMode(refreshed.Windows, mode) + if !ok { + return accountdomain.QuotaWindow{}, fmt.Errorf("Provider usage 响应缺少 %s 额度", mode) + } + if refreshed.Credential.Provider == accountdomain.ProviderConsole { + // One Console request refreshes all three authoritative windows. Reconcile + // every matching recovery event so externally consumed media quota cannot + // remain unscheduled merely because a different kind triggered the refresh. + if err := s.reconcileQuotaRecoveryWindows(ctx, refreshed.Credential.Provider, id, refreshed.Windows); err != nil { + return window, err + } + } else if err := s.reconcileQuotaRecoveryWindow(ctx, refreshed.Credential.Provider, id, window); err != nil { + return window, err + } return window, nil } -func (s *Service) RefreshWebQuotaMode(ctx context.Context, id uint64, mode string) (accountdomain.QuotaWindow, error) { - return s.RefreshQuotaMode(ctx, id, mode) +// ProbeQuotaMode refreshes a claimed recovery event without scheduling a +// second event for the same account and mode. The recovery worker owns the +// current claim and is responsible for acknowledging or rescheduling it. +func (s *Service) ProbeQuotaMode(ctx context.Context, id uint64, mode string) (accountdomain.QuotaWindow, error) { + mode = strings.TrimSpace(mode) + key := quotaSyncKey(id, mode) + result, err, _ := s.quotaSyncs.Do(key, func() (any, error) { + return s.refreshQuotaMode(ctx, id, mode) + }) + if err != nil { + return accountdomain.QuotaWindow{}, err + } + refreshed, ok := result.(quotaRefreshResult) + if !ok { + return accountdomain.QuotaWindow{}, fmt.Errorf("Provider 模式额度探测返回类型无效") + } + window, ok := quotaWindowByMode(refreshed.Windows, mode) + if !ok { + return accountdomain.QuotaWindow{}, fmt.Errorf("Provider usage 响应缺少 %s 额度", mode) + } + return window, nil } -func (s *Service) refreshQuotaMode(ctx context.Context, id uint64, mode string) (accountdomain.QuotaWindow, error) { +func (s *Service) refreshQuotaMode(ctx context.Context, id uint64, mode string) (quotaRefreshResult, error) { value, err := s.accounts.Get(ctx, id) if err != nil { - return accountdomain.QuotaWindow{}, mapRepositoryError(err) + return quotaRefreshResult{}, mapRepositoryError(err) } adapter, ok := s.providers.Quota(value.Provider) if !ok { - return accountdomain.QuotaWindow{}, fmt.Errorf("%s Quota Provider 未注册", value.Provider) + return quotaRefreshResult{}, fmt.Errorf("%s Quota Provider 未注册", value.Provider) + } + var window accountdomain.QuotaWindow + var windows []accountdomain.QuotaWindow + var syncedAt time.Time + var tier accountdomain.WebTier + if value.Provider == accountdomain.ProviderConsole { + // Console /usage always returns Chat, Image and Video together. Persist the + // response as one authoritative snapshot so each media route observes the + // same upstream usage generation. + var snapshot provider.QuotaSnapshot + snapshot, err = adapter.SyncQuota(ctx, value) + if err == nil { + windows = snapshot.Windows + syncedAt = snapshot.SyncedAt + for _, candidate := range windows { + if candidate.Mode == mode { + window = candidate + break + } + } + if window.Mode == "" { + err = fmt.Errorf("Console usage 响应缺少 %s 额度", mode) + } + } + } else { + window, err = adapter.SyncQuotaMode(ctx, value, mode) + windows = []accountdomain.QuotaWindow{window} + syncedAt = s.now() } - window, err := adapter.SyncQuotaMode(ctx, value, mode) if err != nil { if errors.Is(err, provider.ErrUnauthorized) { err = errors.Join(err, s.markSSOCredentialRejected(ctx, value, fmt.Sprintf("%s SSO credential rejected", value.Provider))) } - return accountdomain.QuotaWindow{}, err + return quotaRefreshResult{}, err } - var tier accountdomain.WebTier quotaKind, _ := s.providers.QuotaKind(value.Provider) if quotaKind == provider.QuotaRemoteWindow { - // A single-mode reconciliation updates only the window associated with this 429. - // Full quota synchronization remains responsible for tier detection and other modes. + // Web reconciliation updates one mode; Console already supplied and + // persisted its complete /usage snapshot above. tier = value.WebTier } - now := s.now() - if err := s.accounts.SaveQuotaWindows(ctx, id, tier, now, []accountdomain.QuotaWindow{window}); err != nil { - return accountdomain.QuotaWindow{}, err + if syncedAt.IsZero() { + syncedAt = s.now() } - if window.Remaining == 0 && window.ResetAt != nil && s.quotaQueue != nil { - if err := s.quotaQueue.ScheduleQuotaRecovery(ctx, accountdomain.QuotaRecoveryEvent{AccountID: id, Mode: mode, DueAt: *window.ResetAt}); err != nil { - return window, fmt.Errorf("安排额度恢复事件: %w", err) + if value.Provider == accountdomain.ProviderConsole { + if err := s.accounts.ReplaceQuotaWindows(ctx, id, tier, syncedAt, windows); err != nil { + return quotaRefreshResult{}, err + } + } else if err := s.accounts.SaveQuotaWindows(ctx, id, tier, syncedAt, windows); err != nil { + return quotaRefreshResult{}, err + } + return quotaRefreshResult{Credential: value, Windows: windows}, nil +} + +func quotaSyncKey(accountID uint64, mode string) string { + mode = strings.TrimSpace(mode) + if isConsoleUsageQuotaMode(mode) { + return "all:" + strconv.FormatUint(accountID, 10) + } + return mode + ":" + strconv.FormatUint(accountID, 10) +} + +func quotaWindowByMode(windows []accountdomain.QuotaWindow, mode string) (accountdomain.QuotaWindow, bool) { + for _, window := range windows { + if window.Mode == mode { + return window, true } } - return window, nil + return accountdomain.QuotaWindow{}, false +} + +func (s *Service) reconcileQuotaRecoveryWindows(ctx context.Context, providerValue accountdomain.Provider, accountID uint64, windows []accountdomain.QuotaWindow) error { + for _, window := range windows { + if err := s.reconcileQuotaRecoveryWindow(ctx, providerValue, accountID, window); err != nil { + return err + } + } + return nil +} + +func (s *Service) reconcileQuotaRecoveryWindow(ctx context.Context, providerValue accountdomain.Provider, accountID uint64, window accountdomain.QuotaWindow) error { + if s.quotaQueue == nil || !quotaWindowControlsRouting(providerValue, window.Mode) { + return nil + } + if dueAt := quotaRecoveryDueAt(window, s.now(), window.Remaining == 0); dueAt != nil { + if err := s.quotaQueue.ScheduleQuotaRecovery(ctx, accountdomain.QuotaRecoveryEvent{AccountID: accountID, Mode: window.Mode, DueAt: *dueAt}); err != nil { + return fmt.Errorf("安排额度恢复事件: %w", err) + } + return nil + } + if err := s.quotaQueue.CancelQuotaRecovery(ctx, accountID, window.Mode); err != nil { + return fmt.Errorf("取消额度恢复事件: %w", err) + } + return nil +} + +// quotaRecoveryDueAt keeps upstream quota exhaustion recoverable even when +// the Provider reports no reset timestamp. Console uses a conservative +// predicted 24-hour probe window; generic remote windows retain the shorter +// fallback and transport failures use the recovery queue's bounded backoff. +func quotaRecoveryDueAt(window accountdomain.QuotaWindow, now time.Time, exhausted bool) *time.Time { + if !exhausted { + return nil + } + if window.ResetAt != nil && window.ResetAt.After(now) { + value := *window.ResetAt + return &value + } + if isConsoleUsageQuotaMode(window.Mode) { + value := now.Add(consolePredictedQuotaProbeDelay) + return &value + } + if window.Source == accountdomain.QuotaSourceUpstream { + value := now.Add(unknownRemoteQuotaProbeDelay) + return &value + } + return nil } // QueueQuotaRefresh asynchronously refreshes the remote quota window after a successful request. func (s *Service) QueueQuotaRefresh(id uint64, mode string) { mode = strings.TrimSpace(mode) - if id == 0 || (mode != "weekly" && !isWebChatQuotaMode(mode)) { + if id == 0 || (!isConsoleUsageQuotaMode(mode) && mode != "weekly" && !isWebChatQuotaMode(mode)) { return } key := strconv.FormatUint(id, 10) + ":" + mode s.quotaRefreshMu.Lock() state := s.quotaRefreshes[key] + now := s.now().UTC() + if state != nil && !state.pending && !state.queued && !state.running && !now.Before(state.nextAttemptAt) { + delete(s.quotaRefreshes, key) + state = nil + } if state == nil { - state = &webQuotaRefreshState{} + state = "aRefreshState{} s.quotaRefreshes[key] = state } state.generation++ - state.nextAttemptAt = time.Time{} - enqueued := state.queued || state.running || s.enqueueQuotaRefreshLocked(webQuotaRefreshRequest{key: key, accountID: id, mode: mode}, state) + state.pending = true + enqueued := state.queued || state.running || now.Before(state.nextAttemptAt) || s.enqueueQuotaRefreshLocked(quotaRefreshRequest{key: key, accountID: id, mode: mode}, state) s.quotaRefreshMu.Unlock() if !enqueued { perfmetrics.Default.Add("quota_refresh_events", perfmetrics.Labels{Subsystem: "quota", Stage: "enqueue", Outcome: "queue_full"}, 1) - s.logger.Warn("web_quota_refresh_queue_full", "account_id", id, "mode", mode) + s.logger.Warn("quota_refresh_queue_full", "account_id", id, "mode", mode) s.wakeQuotaRefreshRecovery() } } -func (s *Service) enqueueQuotaRefreshLocked(request webQuotaRefreshRequest, state *webQuotaRefreshState) bool { +func (s *Service) enqueueQuotaRefreshLocked(request quotaRefreshRequest, state *quotaRefreshState) bool { if state == nil || state.queued || state.running { return state != nil } @@ -2789,13 +2928,8 @@ func (s *Service) wakeQuotaRefreshRecovery() { } } -// QueueWebQuotaRefresh preserves the existing internal API while delegating to QueueQuotaRefresh. -func (s *Service) QueueWebQuotaRefresh(id uint64, mode string) { - s.QueueQuotaRefresh(id, mode) -} - -// RunWebQuotaRefresh uses a fixed worker set to avoid unbounded goroutine creation. -func (s *Service) RunWebQuotaRefresh(ctx context.Context) { +// RunQuotaRefresh uses a fixed worker set to avoid unbounded goroutine creation. +func (s *Service) RunQuotaRefresh(ctx context.Context) { var workers sync.WaitGroup workers.Add(managedTaskWorkerCeiling + 1) for range managedTaskWorkerCeiling { @@ -2814,24 +2948,27 @@ func (s *Service) RunWebQuotaRefresh(ctx context.Context) { } state.queued = false state.running = true + state.pending = false s.quotaRefreshMu.Unlock() if err := batch.Do(ctx, func(workCtx context.Context) error { - s.runWebQuotaRefresh(workCtx, request) + s.runQuotaRefresh(workCtx, request) return nil }); err != nil { s.quotaRefreshMu.Lock() if state := s.quotaRefreshes[request.key]; state != nil { state.running = false - state.nextAttemptAt = time.Now().UTC().Add(webQuotaRefreshRetryInterval) + state.pending = true + state.failures++ + state.nextAttemptAt = s.now().UTC().Add(quotaRefreshRetryDelay(state.failures)) } s.quotaRefreshMu.Unlock() s.wakeQuotaRefreshRecovery() if ctx.Err() == nil { var panicErr *batch.PanicError if errors.As(err, &panicErr) { - s.logger.Error("web_quota_refresh_worker_panicked", "account_id", request.accountID, "mode", request.mode, "error", panicErr, "stack", string(panicErr.Stack)) + s.logger.Error("quota_refresh_worker_panicked", "account_id", request.accountID, "mode", request.mode, "error", panicErr, "stack", string(panicErr.Stack)) } else { - s.logger.Error("web_quota_refresh_worker_failed", "account_id", request.accountID, "mode", request.mode, "error", err) + s.logger.Error("quota_refresh_worker_failed", "account_id", request.accountID, "mode", request.mode, "error", err) } } } @@ -2846,7 +2983,7 @@ func (s *Service) RunWebQuotaRefresh(ctx context.Context) { workers.Wait() } -func (s *Service) runWebQuotaRefresh(parent context.Context, request webQuotaRefreshRequest) { +func (s *Service) runQuotaRefresh(parent context.Context, request quotaRefreshRequest) { for { s.quotaRefreshMu.Lock() state := s.quotaRefreshes[request.key] @@ -2857,16 +2994,17 @@ func (s *Service) runWebQuotaRefresh(parent context.Context, request webQuotaRef localGeneration := state.generation publishedGeneration := state.publishedGeneration sharedGeneration := state.sharedGeneration + state.pending = false s.quotaRefreshMu.Unlock() - ctx, cancel := context.WithTimeout(parent, webQuotaRefreshTimeout) + ctx, cancel := context.WithTimeout(parent, quotaRefreshTimeout) if s.quotaRefreshState != nil && publishedGeneration < localGeneration { - generation, err := s.quotaRefreshState.MarkQuotaRefreshDirty(ctx, request.accountID, request.mode, webQuotaRefreshDirtyTTL) + generation, err := s.quotaRefreshState.MarkQuotaRefreshDirty(ctx, request.accountID, request.mode, quotaRefreshDirtyTTL) if err != nil { cancel() s.deferQuotaRefresh(request.key) perfmetrics.Default.Add("quota_refresh_events", perfmetrics.Labels{Subsystem: "quota", Stage: "publish", Outcome: "failed"}, 1) - s.logger.Warn("web_quota_refresh_dirty_publish_failed", "account_id", request.accountID, "mode", request.mode, "error", err) + s.logger.Warn("quota_refresh_dirty_publish_failed", "account_id", request.accountID, "mode", request.mode, "error", err) return } sharedGeneration = generation @@ -2903,24 +3041,42 @@ func (s *Service) runWebQuotaRefresh(parent context.Context, request webQuotaRef } } refreshMode := request.mode + consoleMode := isConsoleUsageQuotaMode(request.mode) + skipUpstream := false if windows, err := s.accounts.GetQuotaWindows(ctx, []uint64{request.accountID}); err == nil { - for _, window := range windows[request.accountID] { - if window.Mode == "weekly" { - refreshMode = "weekly" - break + if consoleMode { + for _, window := range windows[request.accountID] { + if window.Mode == request.mode && window.SyncedAt != nil && s.now().UTC().Sub(window.SyncedAt.UTC()) < consoleQuotaRefreshMinInterval { + skipUpstream = true + break + } + } + } else { + // Weekly remains a Grok Web capability. Console never inherits this + // legacy mode and always refreshes its authoritative /usage snapshot. + for _, window := range windows[request.accountID] { + if window.Mode == "weekly" { + refreshMode = "weekly" + break + } } } } var refreshErr error acquired := true var release func() - if s.refreshLock != nil { + if !skipUpstream && s.refreshLock != nil { effectiveKey := strconv.FormatUint(request.accountID, 10) + ":" + refreshMode - release, acquired, refreshErr = s.refreshLock.Acquire(ctx, "quota-refresh:"+effectiveKey, webQuotaRefreshTimeout) + if consoleMode { + // Every Console mode reads the same /usage snapshot. Serialize all + // three kinds across instances to avoid duplicate upstream probes. + effectiveKey = "console:" + strconv.FormatUint(request.accountID, 10) + } + release, acquired, refreshErr = s.refreshLock.Acquire(ctx, "quota-refresh:"+effectiveKey, quotaRefreshTimeout) } - if refreshErr == nil && acquired { + if !skipUpstream && refreshErr == nil && acquired { if err := s.syncPool.Do(ctx, func(workCtx context.Context) error { - _, refreshErr = s.RefreshWebQuotaMode(workCtx, request.accountID, refreshMode) + _, refreshErr = s.RefreshQuotaMode(workCtx, request.accountID, refreshMode) return refreshErr }); err != nil { refreshErr = err @@ -2932,7 +3088,7 @@ func (s *Service) runWebQuotaRefresh(parent context.Context, request webQuotaRef cancel() if refreshErr != nil || !acquired { if refreshErr != nil && !errors.Is(refreshErr, context.Canceled) { - s.logger.Warn("web_quota_refresh_failed", "account_id", request.accountID, "mode", refreshMode, "error", refreshErr) + s.logger.Warn("quota_refresh_failed", "account_id", request.accountID, "mode", refreshMode, "error", refreshErr) } s.deferQuotaRefresh(request.key) perfmetrics.Default.Add("quota_refresh_events", perfmetrics.Labels{Subsystem: "quota", Stage: "refresh", Outcome: "retry"}, 1) @@ -2957,6 +3113,10 @@ func (s *Service) runWebQuotaRefresh(parent context.Context, request webQuotaRef s.quotaRefreshMu.Unlock() if localChanged || (s.quotaRefreshState != nil && currentShared != sharedGeneration) { perfmetrics.Default.Add("quota_refresh_events", perfmetrics.Labels{Subsystem: "quota", Stage: "refresh", Outcome: "trailing"}, 1) + if consoleMode { + s.deferSuccessfulQuotaRefresh(request.key, true) + return + } continue } if s.quotaRefreshState != nil && sharedDirty { @@ -2965,7 +3125,11 @@ func (s *Service) runWebQuotaRefresh(parent context.Context, request webQuotaRef clearCancel() if clearErr != nil || !cleared { if clearErr != nil { - s.logger.Warn("web_quota_refresh_dirty_clear_failed", "account_id", request.accountID, "mode", request.mode, "error", clearErr) + s.logger.Warn("quota_refresh_dirty_clear_failed", "account_id", request.accountID, "mode", request.mode, "error", clearErr) + } + if consoleMode { + s.deferSuccessfulQuotaRefresh(request.key, true) + return } continue } @@ -2973,11 +3137,27 @@ func (s *Service) runWebQuotaRefresh(parent context.Context, request webQuotaRef s.quotaRefreshMu.Lock() state = s.quotaRefreshes[request.key] if state != nil && state.generation == localGeneration { - delete(s.quotaRefreshes, request.key) + if consoleMode { + state.running = false + state.pending = false + state.failures = 0 + state.nextAttemptAt = s.now().UTC().Add(consoleQuotaRefreshMinInterval) + } else { + delete(s.quotaRefreshes, request.key) + } s.quotaRefreshMu.Unlock() perfmetrics.Default.Add("quota_refresh_events", perfmetrics.Labels{Subsystem: "quota", Stage: "refresh", Outcome: "success"}, 1) return } + if consoleMode && state != nil { + state.running = false + state.pending = true + state.failures = 0 + state.nextAttemptAt = s.now().UTC().Add(consoleQuotaRefreshMinInterval) + s.quotaRefreshMu.Unlock() + s.wakeQuotaRefreshRecovery() + return + } s.quotaRefreshMu.Unlock() } } @@ -2986,15 +3166,47 @@ func (s *Service) deferQuotaRefresh(key string) { s.quotaRefreshMu.Lock() if state := s.quotaRefreshes[key]; state != nil { state.running = false - state.nextAttemptAt = time.Now().UTC().Add(webQuotaRefreshRetryInterval) + state.pending = true + state.failures++ + state.nextAttemptAt = s.now().UTC().Add(quotaRefreshRetryDelay(state.failures)) } s.quotaRefreshMu.Unlock() s.wakeQuotaRefreshRecovery() } +func (s *Service) deferSuccessfulQuotaRefresh(key string, pending bool) { + s.quotaRefreshMu.Lock() + if state := s.quotaRefreshes[key]; state != nil { + state.running = false + state.pending = pending + state.failures = 0 + state.nextAttemptAt = s.now().UTC().Add(consoleQuotaRefreshMinInterval) + } + s.quotaRefreshMu.Unlock() + s.wakeQuotaRefreshRecovery() +} + +func quotaRefreshRetryDelay(failures int) time.Duration { + if failures < 1 { + failures = 1 + } + shift := min(failures-1, 6) + delay := quotaRefreshBackoffBase * time.Duration(1< quotaRefreshBackoffMax { + delay = quotaRefreshBackoffMax + } + // Equal jitter keeps retries bounded away from zero while preventing a + // shared upstream outage from synchronizing every account worker. + half := delay / 2 + if half <= 0 { + return delay + } + return half + time.Duration(rand.Int64N(int64(half)+1)) +} + func (s *Service) runQuotaRefreshRecovery(ctx context.Context) { - retryTicker := time.NewTicker(webQuotaRefreshRetryInterval) - sharedTicker := time.NewTicker(webQuotaRefreshSharedPoll) + retryTicker := time.NewTicker(quotaRefreshPollInterval) + sharedTicker := time.NewTicker(quotaRefreshSharedPoll) defer retryTicker.Stop() defer sharedTicker.Stop() for { @@ -3013,10 +3225,20 @@ func (s *Service) runQuotaRefreshRecovery(ctx context.Context) { } func (s *Service) requeueQuotaRefreshes() { - now := time.Now().UTC() + now := s.now().UTC() s.quotaRefreshMu.Lock() for key, state := range s.quotaRefreshes { - if state == nil || state.queued || state.running || now.Before(state.nextAttemptAt) { + if state == nil { + delete(s.quotaRefreshes, key) + continue + } + if !state.pending { + if !state.queued && !state.running && !now.Before(state.nextAttemptAt) { + delete(s.quotaRefreshes, key) + } + continue + } + if state.queued || state.running || now.Before(state.nextAttemptAt) { continue } separator := strings.IndexByte(key, ':') @@ -3027,7 +3249,7 @@ func (s *Service) requeueQuotaRefreshes() { if err != nil { continue } - if !s.enqueueQuotaRefreshLocked(webQuotaRefreshRequest{key: key, accountID: accountID, mode: key[separator+1:]}, state) { + if !s.enqueueQuotaRefreshLocked(quotaRefreshRequest{key: key, accountID: accountID, mode: key[separator+1:]}, state) { break } } @@ -3042,7 +3264,7 @@ func (s *Service) recoverSharedQuotaRefreshes(parent context.Context, now time.T values, err := s.quotaRefreshState.ListQuotaRefreshDirty(ctx, now, 100) cancel() if err != nil { - s.logger.Warn("web_quota_refresh_dirty_list_failed", "error", err) + s.logger.Warn("quota_refresh_dirty_list_failed", "error", err) return } s.quotaRefreshMu.Lock() @@ -3050,12 +3272,15 @@ func (s *Service) recoverSharedQuotaRefreshes(parent context.Context, now time.T key := strconv.FormatUint(value.AccountID, 10) + ":" + value.Mode state := s.quotaRefreshes[key] if state == nil { - state = &webQuotaRefreshState{generation: 1, publishedGeneration: 1, sharedGeneration: value.Generation} + state = "aRefreshState{generation: 1, publishedGeneration: 1, sharedGeneration: value.Generation, pending: true} s.quotaRefreshes[key] = state - } else if value.Generation > state.sharedGeneration { - state.sharedGeneration = value.Generation + } else { + if value.Generation > state.sharedGeneration { + state.sharedGeneration = value.Generation + } + state.pending = true } - if !state.queued && !state.running && !s.enqueueQuotaRefreshLocked(webQuotaRefreshRequest{key: key, accountID: value.AccountID, mode: value.Mode}, state) { + if !state.queued && !state.running && !now.Before(state.nextAttemptAt) && !s.enqueueQuotaRefreshLocked(quotaRefreshRequest{key: key, accountID: value.AccountID, mode: value.Mode}, state) { break } } @@ -3096,6 +3321,19 @@ func isWebChatQuotaMode(mode string) bool { } } +func isConsoleUsageQuotaMode(mode string) bool { + switch mode { + case "console", "console_image", "console_video": + return true + default: + return false + } +} + +func quotaWindowControlsRouting(providerValue accountdomain.Provider, mode string) bool { + return providerValue != accountdomain.ProviderConsole || isConsoleUsageQuotaMode(mode) +} + // SyncAllBilling 尽力刷新全部启用账号,单个账号失败不阻断其他账号。 func (s *Service) SyncAllBilling(ctx context.Context) (int, int, error) { return s.SyncAllBillingWithProgress(ctx, nil) @@ -3137,6 +3375,88 @@ func (s *Service) SyncAllConsoleQuotasWithProgress(ctx context.Context, progress return s.syncAllQuotasWithProgress(ctx, accountdomain.ProviderConsole, "console_quota_sync", progress) } +// SyncIncompleteConsoleQuotas replaces pre-/usage synthetic windows and +// partial snapshots without refreshing accounts that already have all three +// authoritative Console quota kinds. It is safe to run periodically and uses +// the shared sync pool to preserve the deployment-wide upstream limit. +func (s *Service) SyncIncompleteConsoleQuotas(ctx context.Context) (int, int, error) { + const batchSize = 1000 + var succeeded, failed int + var afterID uint64 + for { + values, _, err := s.accounts.ListProviderAccountBatch(ctx, accountdomain.ProviderConsole, afterID, batchSize) + if err != nil { + return succeeded, failed, err + } + if len(values) == 0 { + return succeeded, failed, nil + } + ids := make([]uint64, 0, len(values)) + for _, value := range values { + if value.Enabled && value.AuthStatus == accountdomain.AuthStatusActive { + ids = append(ids, value.ID) + } + } + windows, err := s.accounts.GetQuotaWindows(ctx, ids) + if err != nil { + return succeeded, failed, err + } + pending := make([]uint64, 0, len(ids)) + for _, id := range ids { + if !completeConsoleUsageSnapshot(windows[id]) { + pending = append(pending, id) + } + } + var batchSucceeded, batchFailed int + if len(pending) > 0 { + batchSucceeded, batchFailed, err = s.runAccountBatch(ctx, "console_usage_migration", pending, s.syncPool, nil, func(workCtx context.Context, id uint64) error { + var release func() + if s.refreshLock != nil { + var acquired bool + var lockErr error + release, acquired, lockErr = s.refreshLock.Acquire(workCtx, "quota-refresh:"+strconv.FormatUint(id, 10)+":console", 2*quotaRefreshTimeout) + if lockErr != nil { + return lockErr + } + if !acquired { + return errQuotaRefreshBusy + } + defer release() + } + _, refreshErr := s.RefreshQuotaMode(workCtx, id, "console") + return refreshErr + }) + } + succeeded += batchSucceeded + failed += batchFailed + if err != nil { + return succeeded, failed, err + } + afterID = values[len(values)-1].ID + if len(values) < batchSize { + return succeeded, failed, nil + } + } +} + +func completeConsoleUsageSnapshot(windows []accountdomain.QuotaWindow) bool { + var present uint8 + for _, window := range windows { + if window.Source != accountdomain.QuotaSourceUpstream || window.SyncedAt == nil { + continue + } + switch window.Mode { + case "console": + present |= 1 + case "console_image": + present |= 2 + case "console_video": + present |= 4 + } + } + return present == 7 +} + func (s *Service) syncAllQuotasWithProgress(ctx context.Context, providerValue accountdomain.Provider, operation string, progress BatchProgressObserver) (int, int, error) { ids, err := s.accounts.ListEnabledAccountIDs(ctx, providerValue, false) if err != nil { diff --git a/backend/internal/application/egress/operations.go b/backend/internal/application/egress/operations.go index a7b7dc96..a21883ce 100644 --- a/backend/internal/application/egress/operations.go +++ b/backend/internal/application/egress/operations.go @@ -423,8 +423,8 @@ func (s *Service) UpdateOperationsConfig(ctx context.Context, input OperationsCo } func (s *Service) validateFallbacks(ctx context.Context, current domain.OperationsConfig, input map[domain.Scope]FallbackConfigInput) (map[domain.Scope]domain.FallbackConfig, error) { - result := make(map[domain.Scope]domain.FallbackConfig, 4) - for _, scope := range []domain.Scope{domain.ScopeBuild, domain.ScopeWeb, domain.ScopeConsole, domain.ScopeWebAsset} { + result := make(map[domain.Scope]domain.FallbackConfig, len(allOperationScopes())) + for _, scope := range allOperationScopes() { result[scope] = current.FallbackFor(scope) } for scope, fallback := range input { @@ -544,7 +544,11 @@ func publicSource(value domain.SubscriptionSource) domain.PublicSubscriptionSour } func validScope(scope domain.Scope) bool { - return scope == domain.ScopeBuild || scope == domain.ScopeWeb || scope == domain.ScopeConsole || scope == domain.ScopeWebAsset + return scope == domain.ScopeBuild || scope == domain.ScopeWeb || scope == domain.ScopeConsole || scope == domain.ScopeWebAsset || scope == domain.ScopeConsoleAsset +} + +func allOperationScopes() []domain.Scope { + return []domain.Scope{domain.ScopeBuild, domain.ScopeWeb, domain.ScopeConsole, domain.ScopeWebAsset, domain.ScopeConsoleAsset} } func validateImportInput(input ImportInput) error { diff --git a/backend/internal/application/egress/service.go b/backend/internal/application/egress/service.go index 3e6b5d70..4ab205dc 100644 --- a/backend/internal/application/egress/service.go +++ b/backend/internal/application/egress/service.go @@ -231,7 +231,7 @@ func (s *Service) DefaultUserAgents() map[string]string { defer s.mu.RUnlock() return map[string]string{ string(domain.ScopeBuild): "", string(domain.ScopeWeb): s.browserUA, string(domain.ScopeConsole): s.browserUA, - string(domain.ScopeWebAsset): s.browserUA, + string(domain.ScopeWebAsset): s.browserUA, string(domain.ScopeConsoleAsset): s.browserUA, } } @@ -285,7 +285,11 @@ func (s *Service) publicNodes(values []domain.Node) []domain.PublicNode { } func validListScope(scope domain.Scope) bool { - return scope == "" || scope == domain.ScopeBuild || scope == domain.ScopeWeb || scope == domain.ScopeConsole || scope == domain.ScopeWebAsset + return scope == "" || scope == domain.ScopeBuild || scope == domain.ScopeWeb || scope == domain.ScopeConsole || scope == domain.ScopeWebAsset || scope == domain.ScopeConsoleAsset +} + +func allServiceScopes() []domain.Scope { + return []domain.Scope{domain.ScopeBuild, domain.ScopeWeb, domain.ScopeConsole, domain.ScopeWebAsset, domain.ScopeConsoleAsset} } func validListValue(value string, allowed ...string) bool { @@ -352,7 +356,7 @@ func (s *Service) validateFallbackNodeUpdate(ctx context.Context, node domain.No } func (s *Service) validateFallbackNodeUpdateWithConfig(node domain.Node, config domain.OperationsConfig) error { - for _, scope := range []domain.Scope{domain.ScopeBuild, domain.ScopeWeb, domain.ScopeConsole, domain.ScopeWebAsset} { + for _, scope := range allServiceScopes() { fallback := config.FallbackFor(scope) if fallback.Mode != domain.FallbackModeFixed || fallback.NodeID != node.ID { continue @@ -373,7 +377,7 @@ func (s *Service) UpdateManyEnabled(ctx context.Context, nodeIDs []uint64, enabl } // Disabling a fixed fallback would make the persisted routing policy - // invalid. At most four fallback nodes need point lookups, regardless of + // invalid. At most five fallback nodes need point lookups, regardless of // the batch size. if !enabled && s.operations != nil { config, err := s.operations.GetEgressOperationsConfig(ctx) @@ -384,8 +388,8 @@ func (s *Service) UpdateManyEnabled(ctx context.Context, nodeIDs []uint64, enabl for _, id := range ids { selected[id] = struct{}{} } - fallbackNodeIDs := make(map[uint64]struct{}, 4) - for _, scope := range []domain.Scope{domain.ScopeBuild, domain.ScopeWeb, domain.ScopeConsole, domain.ScopeWebAsset} { + fallbackNodeIDs := make(map[uint64]struct{}, len(allServiceScopes())) + for _, scope := range allServiceScopes() { fallback := config.FallbackFor(scope) if fallback.Mode == domain.FallbackModeFixed { if _, exists := selected[fallback.NodeID]; exists { @@ -714,8 +718,8 @@ func (s *Service) applyInput(value domain.Node, input Input, create bool) (domai if name == "" || len(name) > 160 { return domain.Node{}, fmt.Errorf("%w: 名称必须在 1 到 160 个字符之间", ErrInvalidInput) } - if input.Scope != domain.ScopeBuild && input.Scope != domain.ScopeWeb && input.Scope != domain.ScopeConsole && input.Scope != domain.ScopeWebAsset { - return domain.Node{}, fmt.Errorf("%w: scope 必须是 grok_build、grok_web、grok_console 或 grok_web_asset", ErrInvalidInput) + if !validListScope(input.Scope) || input.Scope == "" { + return domain.Node{}, fmt.Errorf("%w: scope 必须是 grok_build、grok_web、grok_console、grok_web_asset 或 grok_console_asset", ErrInvalidInput) } value.Name, value.Scope, value.Enabled, value.ProxyPool = name, input.Scope, input.Enabled, proxyPool if input.AccountCapacity != nil { @@ -756,7 +760,7 @@ func (s *Service) applyInput(value domain.Node, input Input, create bool) (domai if value.ProxyPool && strings.TrimSpace(value.EncryptedProxyURL) == "" { return domain.Node{}, fmt.Errorf("%w: 代理池模式需要配置代理地址", ErrInvalidInput) } - if input.Scope == domain.ScopeBuild { + if input.Scope == domain.ScopeBuild || input.Scope == domain.ScopeConsoleAsset { value.EncryptedCloudflareCookie = "" } else if input.ClearCookies { value.EncryptedCloudflareCookie = "" diff --git a/backend/internal/application/egress/service_test.go b/backend/internal/application/egress/service_test.go index e454d850..d848d6cd 100644 --- a/backend/internal/application/egress/service_test.go +++ b/backend/internal/application/egress/service_test.go @@ -84,7 +84,7 @@ func TestBuildNodeAlwaysUsesProviderUserAgent(t *testing.T) { if value.UserAgent != "" || service.publicNode(value).UserAgent != "" { t.Fatalf("build node userAgent = %q", value.UserAgent) } - if defaults := service.DefaultUserAgents(); defaults[string(domain.ScopeBuild)] != "" || defaults[string(domain.ScopeWeb)] != "browser-agent" || defaults[string(domain.ScopeConsole)] != "browser-agent" { + if defaults := service.DefaultUserAgents(); defaults[string(domain.ScopeBuild)] != "" || defaults[string(domain.ScopeWeb)] != "browser-agent" || defaults[string(domain.ScopeConsole)] != "browser-agent" || defaults[string(domain.ScopeWebAsset)] != "browser-agent" || defaults[string(domain.ScopeConsoleAsset)] != "browser-agent" { t.Fatalf("default user agents = %#v", defaults) } } @@ -104,6 +104,27 @@ func TestConsoleNodeUsesBrowserDefaultUserAgent(t *testing.T) { } } +func TestConsoleAssetNodeUsesBrowserAgentButDropsClearanceCookie(t *testing.T) { + cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") + if err != nil { + t.Fatal(err) + } + existingCookie, err := cipher.Encrypt("cf_clearance=legacy") + if err != nil { + t.Fatal(err) + } + service := NewService(nil, cipher, "browser-agent") + value, err := service.applyInput(domain.Node{EncryptedCloudflareCookie: existingCookie}, Input{ + Name: "console-assets", Scope: domain.ScopeConsoleAsset, Enabled: true, + }, false) + if err != nil { + t.Fatal(err) + } + if value.UserAgent != "browser-agent" || value.EncryptedCloudflareCookie != "" { + t.Fatalf("Console asset node identity = %#v", value) + } +} + func TestPublicNodeReportsAccountBoundProxy(t *testing.T) { cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") if err != nil { diff --git a/backend/internal/application/gateway/model_alias_test.go b/backend/internal/application/gateway/model_alias_test.go index 724da934..3bb7b206 100644 --- a/backend/internal/application/gateway/model_alias_test.go +++ b/backend/internal/application/gateway/model_alias_test.go @@ -151,7 +151,7 @@ func TestResolvePublicModelRoutesGatesDynamicAliasesAndPreservesCompatibility(t models: &aliasRouteResolver{ byPublic: map[string][]modeldomain.Route{"Build/grok-4.5": {route}}, }, - providers: provider.NewRegistry(console.NewAdapter(console.Config{}, nil, nil)), + providers: provider.NewRegistry(console.NewAdapter(console.Config{}, nil, nil, nil)), } // Base model always works. diff --git a/backend/internal/application/gateway/selector.go b/backend/internal/application/gateway/selector.go index 549fd76d..40c2642b 100644 --- a/backend/internal/application/gateway/selector.go +++ b/backend/internal/application/gateway/selector.go @@ -1133,7 +1133,7 @@ func (s *Selector) loadLayeredCandidates(ctx context.Context, provider account.P checkTime = time.Now().UTC() continue } - values := assembleRoutingCandidates(provider, bases, overlay) + values := assembleRoutingCandidates(provider, quotaMode, bases, overlay) s.candidateMu.Lock() stable := baseVersion == s.routingBaseVersionLocked(provider) && overlayVersion == s.routingOverlayVersionLocked(provider) if stable { @@ -1550,7 +1550,7 @@ type routingOverlayLoadResult struct { version routingLayerVersion } -func assembleRoutingCandidates(provider account.Provider, bases []account.RoutingAccountBase, overlay account.RoutingOverlaySnapshot) []account.RoutingCandidate { +func assembleRoutingCandidates(provider account.Provider, quotaMode string, bases []account.RoutingAccountBase, overlay account.RoutingOverlaySnapshot) []account.RoutingCandidate { byAccount := make(map[uint64]account.RoutingAccountOverlay, len(overlay.Values)) for _, value := range overlay.Values { byAccount[value.AccountID] = value @@ -1566,13 +1566,16 @@ func assembleRoutingCandidates(provider account.Provider, bases []account.Routin } } result := make([]account.RoutingCandidate, 0, len(bases)) + staticConsoleModel := provider == account.ProviderConsole && strings.TrimSpace(quotaMode) != "" for _, base := range bases { overlayValue := byAccount[base.Credential.ID] if overlay.HasBindings && !overlayValue.Bound { continue } known, supports := overlayValue.ModelCapabilityKnown, overlayValue.SupportsModel - if overlay.HasBindings { + if staticConsoleModel { + known, supports = true, true + } else if overlay.HasBindings { known, supports = true, true } else if sharedSuperBuildModel && account.IsBuildSuper(base.Credential, base.Billing) { known, supports = true, true diff --git a/backend/internal/application/gateway/selector_layered_test.go b/backend/internal/application/gateway/selector_layered_test.go index 7c631ab6..68acd7ce 100644 --- a/backend/internal/application/gateway/selector_layered_test.go +++ b/backend/internal/application/gateway/selector_layered_test.go @@ -695,12 +695,30 @@ func TestLayeredRoutingMatchesCombinedRepositoryResult(t *testing.T) { if err != nil { t.Fatal(err) } - layered := assembleRoutingCandidates(account.ProviderBuild, bases, overlay) + layered := assembleRoutingCandidates(account.ProviderBuild, "", bases, overlay) if !reflect.DeepEqual(layered, combined) { t.Fatalf("layered = %#v\ncombined = %#v", layered, combined) } } +func TestAssembleRoutingCandidatesAllowsRecognizedStaticConsoleModelWithStaleSnapshot(t *testing.T) { + bases := []account.RoutingAccountBase{{Credential: account.Credential{ + ID: 1, Provider: account.ProviderConsole, Enabled: true, AuthStatus: account.AuthStatusActive, + }}} + overlay := account.RoutingOverlaySnapshot{Values: []account.RoutingAccountOverlay{{ + AccountID: 1, ModelCapabilityKnown: true, SupportsModel: false, + }}} + + recognized := assembleRoutingCandidates(account.ProviderConsole, "console_image", bases, overlay) + if len(recognized) != 1 || !recognized[0].ModelCapabilityKnown || !recognized[0].SupportsModel { + t.Fatalf("recognized static Console model = %#v", recognized) + } + unknown := assembleRoutingCandidates(account.ProviderConsole, "", bases, overlay) + if len(unknown) != 1 || !unknown[0].ModelCapabilityKnown || unknown[0].SupportsModel { + t.Fatalf("unknown Console model = %#v", unknown) + } +} + func newLayeredRepositoryFixture() *layeredAccountRepository { return &layeredAccountRepository{ bases: []account.RoutingAccountBase{{Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, Enabled: true, AuthStatus: account.AuthStatusActive}}}, diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index caedd263..9546aeb1 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -2211,7 +2211,7 @@ func runQuotaRefreshWorkers(t *testing.T, service *accountapp.Service) { ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) go func() { - service.RunWebQuotaRefresh(ctx) + service.RunQuotaRefresh(ctx) close(done) }() t.Cleanup(func() { diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index 76b91ecc..2199885e 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -291,7 +291,8 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model } // 视频任务创建时已持久化账号归属;恢复只能重新获取原账号,禁止因后续 // 轮询或结果处理失败切换到其他账号。 - lease, err := s.selector.AcquirePinned(ctx, route.Provider, job.AccountID, route.ID, route.UpstreamModel, "", true) + quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel) + lease, err := s.selector.AcquirePinned(ctx, route.Provider, job.AccountID, route.ID, route.UpstreamModel, quotaMode, true) if err != nil { if parent.Err() != nil { s.deferVideoJob(parent, job) @@ -404,10 +405,20 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model return } s.selector.MarkSuccess(context.Background(), lease.Credential) + if lease.QuotaMode != "" && lease.QuotaMode != "weekly" { + quotaCtx, quotaCancel := context.WithTimeout(context.Background(), accountStateWriteTimeout) + updated, quotaErr := s.accounts.DecrementQuota(quotaCtx, job.AccountID, lease.QuotaMode, 1) + quotaCancel() + if quotaErr != nil { + s.logger.Warn("video_quota_decrement_failed", "provider", route.Provider, "account_id", job.AccountID, "mode", lease.QuotaMode, "error", quotaErr) + } else if updated { + s.selector.ConsumeQuota(route.Provider, job.AccountID, lease.QuotaMode, 1) + } + } if err := s.recordVideoAudit(context.Background(), job, time.Since(startedAt).Milliseconds()); err != nil { s.logger.Error("video_usage_record_failed", "job_id", job.ID, "event_id", "video_usage_"+job.ID, "error", err) } - if quotaKind, _ := s.providers.QuotaKind(route.Provider); quotaKind == provider.QuotaRemoteWindow && lease.QuotaMode == "weekly" { + if quotaKind, _ := s.providers.QuotaKind(route.Provider); quotaKind == provider.QuotaRemoteWindow && lease.QuotaMode != "" { s.accounts.QueueQuotaRefresh(job.AccountID, lease.QuotaMode) } } diff --git a/backend/internal/application/model/service.go b/backend/internal/application/model/service.go index 2e5394f7..79b3b4eb 100644 --- a/backend/internal/application/model/service.go +++ b/backend/internal/application/model/service.go @@ -21,6 +21,8 @@ import ( const defaultModelSyncWorkers = 25 const syncFailurePersistTimeout = 5 * time.Second +var maxModelBatchSize = repository.MaxPageSize * len(modeldomain.Capabilities()) + var ( ErrInvalidFilter = errors.New("模型筛选条件无效") ErrInvalidInput = errors.New("模型参数无效") @@ -48,6 +50,11 @@ type AccountOption struct { Name string } +type RouteGroup struct { + Routes []modeldomain.Route + EndpointCapabilities []string +} + type ListFilter struct { Provider string Providers []string @@ -97,6 +104,67 @@ func (s *Service) List(ctx context.Context, page, pageSize int, search string, f return s.models.List(ctx, repository.ModelListQuery{Page: repository.PageQuery{Offset: (page - 1) * pageSize, Limit: pageSize, Search: search, Sort: filter.Sort}, Filter: repository.ModelListFilter{Provider: filter.Provider, Providers: filter.Providers, Tiers: filter.Tiers, Enabled: enabled, ActiveScope: filter.ActiveScope}}) } +func (s *Service) ListGroups(ctx context.Context, page, pageSize int, search string, filter ListFilter) ([]RouteGroup, int64, error) { + page, pageSize = normalizePage(page, pageSize) + if !validProviderFilter(filter.Provider) || !validModelFilter(filter.Status, "", "enabled", "disabled") || !repository.IsValidSort(filter.Sort, "publicId", "upstreamModel", "status", "provider", "accountSupport", "lastSyncedAt") { + return nil, 0, ErrInvalidFilter + } + var enabled *bool + if filter.Status != "" { + value := filter.Status == "enabled" + enabled = &value + } + values, total, err := s.models.ListGroups(ctx, repository.ModelListQuery{ + Page: repository.PageQuery{Offset: (page - 1) * pageSize, Limit: pageSize, Search: search, Sort: filter.Sort}, + Filter: repository.ModelListFilter{Provider: filter.Provider, Enabled: enabled}, + }) + if err != nil { + return nil, 0, err + } + groups := make([]RouteGroup, 0, len(values)) + for _, value := range values { + groups = append(groups, RouteGroup{Routes: value.Routes, EndpointCapabilities: s.endpointCapabilities(value.Routes)}) + } + return groups, total, nil +} + +func (s *Service) endpointCapabilities(routes []modeldomain.Route) []string { + if len(routes) == 0 || s.providers == nil { + return nil + } + definition, ok := s.providers.Definition(routes[0].Provider) + if !ok { + return nil + } + return endpointCapabilitiesForDefinition(routes, definition) +} + +func endpointCapabilitiesForDefinition(routes []modeldomain.Route, definition provider.Definition) []string { + available := make(map[string]bool, 6) + for _, route := range routes { + switch route.Capability { + case modeldomain.CapabilityResponses, modeldomain.CapabilityChat: + available["completions"] = definition.Conversation.ChatCompletions + available["responses"] = definition.Conversation.Responses + available["messages"] = definition.Conversation.Messages + case modeldomain.CapabilityImage: + available["image"] = definition.Media.ImageGeneration + case modeldomain.CapabilityImageEdit: + available["image_edit"] = definition.Media.ImageEdit + case modeldomain.CapabilityVideo: + available["video"] = definition.Media.VideoGeneration + } + } + order := []string{"completions", "responses", "messages", "image", "image_edit", "video"} + result := make([]string, 0, len(order)) + for _, capability := range order { + if available[capability] { + result = append(result, capability) + } + } + return result +} + func validProviderFilter(value string) bool { return value == "" || account.Provider(value).IsValid() } @@ -241,7 +309,7 @@ func (s *Service) Delete(ctx context.Context, id uint64) error { } func (s *Service) BatchDelete(ctx context.Context, ids []uint64) (int64, error) { - values, err := normalizeBatchIDs(ids) + values, err := normalizeModelRouteBatchIDs(ids) if err != nil { return 0, err } @@ -320,7 +388,7 @@ func (s *Service) validateBoundAccounts(ctx context.Context, providerValue accou // BatchSetEnabled 批量更新模型路由启停状态。 func (s *Service) BatchSetEnabled(ctx context.Context, ids []uint64, enabled bool) (int64, error) { - values, err := normalizeBatchIDs(ids) + values, err := normalizeModelRouteBatchIDs(ids) if err != nil { return 0, err } @@ -533,11 +601,19 @@ func normalizePage(page, pageSize int) (int, int) { } func normalizeBatchIDs(ids []uint64) ([]uint64, error) { + return normalizeIDs(ids, repository.MaxPageSize, "模型") +} + +func normalizeModelRouteBatchIDs(ids []uint64) ([]uint64, error) { + return normalizeIDs(ids, maxModelBatchSize, "模型能力路由") +} + +func normalizeIDs(ids []uint64, limit int, label string) ([]uint64, error) { if len(ids) == 0 { return nil, invalidInput("至少选择一个模型") } - if len(ids) > repository.MaxPageSize { - return nil, invalidInput(fmt.Sprintf("单次最多处理 %d 个模型", repository.MaxPageSize)) + if len(ids) > limit { + return nil, invalidInput(fmt.Sprintf("单次最多处理 %d 条%s", limit, label)) } seen := make(map[uint64]struct{}, len(ids)) result := make([]uint64, 0, len(ids)) diff --git a/backend/internal/application/model/service_test.go b/backend/internal/application/model/service_test.go index 48267162..3bc6a3d8 100644 --- a/backend/internal/application/model/service_test.go +++ b/backend/internal/application/model/service_test.go @@ -31,6 +31,36 @@ func TestModelProviderFilterAcceptsOnlyKnownProviders(t *testing.T) { } } +func TestEndpointCapabilitiesFollowProviderSurface(t *testing.T) { + routes := []modeldomain.Route{ + {Provider: account.ProviderConsole, Capability: modeldomain.CapabilityResponses}, + {Provider: account.ProviderConsole, Capability: modeldomain.CapabilityImage}, + {Provider: account.ProviderConsole, Capability: modeldomain.CapabilityImageEdit}, + } + capabilities := endpointCapabilitiesForDefinition(routes, provider.Definition{ + Conversation: provider.ConversationSurface{Responses: true, Messages: true}, + Media: provider.MediaSurface{ImageGeneration: true}, + }) + want := []string{"responses", "messages", "image"} + if fmt.Sprint(capabilities) != fmt.Sprint(want) { + t.Fatalf("endpoint capabilities = %v, want %v", capabilities, want) + } +} + +func TestNormalizeBatchIDsAllowsGroupedRouteExpansion(t *testing.T) { + ids := make([]uint64, maxModelBatchSize) + for index := range ids { + ids[index] = uint64(index + 1) + } + if values, err := normalizeModelRouteBatchIDs(ids); err != nil || len(values) != maxModelBatchSize { + t.Fatalf("expanded grouped batch = %d, err=%v", len(values), err) + } + ids = append(ids, uint64(maxModelBatchSize+1)) + if _, err := normalizeModelRouteBatchIDs(ids); err == nil { + t.Fatal("oversized grouped batch was accepted") + } +} + func TestSyncAggregatesCapabilitiesFromAllAccounts(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "model-sync.db")) diff --git a/backend/internal/application/quotarecovery/service.go b/backend/internal/application/quotarecovery/service.go index f24d1981..38ef6024 100644 --- a/backend/internal/application/quotarecovery/service.go +++ b/backend/internal/application/quotarecovery/service.go @@ -17,10 +17,11 @@ const ( recoveryProbeTimeout = 30 * time.Second recoveryReconcileEvery = time.Minute recoveryReconcileLimit = 1000 + consoleProbeInterval = 24 * time.Hour ) type quotaSynchronizer interface { - RefreshQuotaMode(ctx context.Context, accountID uint64, mode string) (accountdomain.QuotaWindow, error) + ProbeQuotaMode(ctx context.Context, accountID uint64, mode string) (accountdomain.QuotaWindow, error) ListDueQuotaWindows(ctx context.Context, now time.Time, limit int) ([]accountdomain.QuotaWindow, error) } @@ -91,7 +92,7 @@ func (s *Service) runDue(ctx context.Context, now time.Time) { func (s *Service) runOne(ctx context.Context, now time.Time, value accountdomain.QuotaRecoveryEvent) { probeCtx, cancel := context.WithTimeout(ctx, recoveryProbeTimeout) - window, probeErr := s.syncer.RefreshQuotaMode(probeCtx, value.AccountID, value.Mode) + window, probeErr := s.syncer.ProbeQuotaMode(probeCtx, value.AccountID, value.Mode) cancel() if probeErr == nil && window.Remaining > 0 { if err := s.queue.AckQuotaRecovery(ctx, value); err != nil { @@ -105,6 +106,15 @@ func (s *Service) runOne(ctx context.Context, now time.Time, value accountdomain value.Attempts++ if probeErr == nil && window.ResetAt != nil && window.ResetAt.After(now) { value.DueAt = *window.ResetAt + } else if probeErr == nil && value.Mode == "console" { + // Console usage currently exposes no reset timestamp. A healthy zero + // result is therefore rechecked after the fixed 24-hour prediction + // window; transport failures still use bounded exponential backoff. + value.DueAt = now.Add(consoleProbeInterval) + } else if probeErr == nil && window.WindowSeconds > 0 { + // Preserve Provider-specific upstream window semantics. In particular, + // Grok Web can report a duration without an absolute reset timestamp. + value.DueAt = now.Add(time.Duration(window.WindowSeconds) * time.Second) } else { value.DueAt = now.Add(s.backoff(value.Attempts)) } diff --git a/backend/internal/application/quotarecovery/service_test.go b/backend/internal/application/quotarecovery/service_test.go index e8edcd5a..48705e5b 100644 --- a/backend/internal/application/quotarecovery/service_test.go +++ b/backend/internal/application/quotarecovery/service_test.go @@ -47,14 +47,42 @@ func TestReconcileDueRestoresMissingQueueEvents(t *testing.T) { } } +func TestRunOneKeepsPredictedRecoveryWindow(t *testing.T) { + now := time.Date(2026, 8, 5, 8, 0, 0, 0, time.UTC) + queue := "aQueueStub{} + syncer := "aSyncStub{window: accountdomain.QuotaWindow{Mode: "console", Remaining: 0}} + service := NewService(testLogger(), queue, syncer, 30*time.Second, 30*time.Minute) + + service.runOne(context.Background(), now, accountdomain.QuotaRecoveryEvent{AccountID: 7, Mode: "console", DueAt: now, ClaimToken: "claim"}) + + if len(queue.rescheduled) != 1 || !queue.rescheduled[0].DueAt.Equal(now.Add(24*time.Hour)) { + t.Fatalf("rescheduled = %#v", queue.rescheduled) + } +} + +func TestRunOnePreservesNonConsoleWindowDuration(t *testing.T) { + now := time.Date(2026, 8, 5, 8, 0, 0, 0, time.UTC) + queue := "aQueueStub{} + syncer := "aSyncStub{window: accountdomain.QuotaWindow{Mode: "fast", Remaining: 0, WindowSeconds: 3600}} + service := NewService(testLogger(), queue, syncer, 30*time.Second, 30*time.Minute) + + service.runOne(context.Background(), now, accountdomain.QuotaRecoveryEvent{AccountID: 8, Mode: "fast", DueAt: now, ClaimToken: "claim"}) + + if len(queue.rescheduled) != 1 || !queue.rescheduled[0].DueAt.Equal(now.Add(time.Hour)) { + t.Fatalf("rescheduled = %#v", queue.rescheduled) + } +} + type quotaQueueStub struct { - mu sync.Mutex - claimed []accountdomain.QuotaRecoveryEvent - claimLimit int - claimLease time.Duration - acked int - scheduled []accountdomain.QuotaRecoveryEvent - ensured []accountdomain.QuotaRecoveryEvent + mu sync.Mutex + claimed []accountdomain.QuotaRecoveryEvent + claimLimit int + claimLease time.Duration + acked int + scheduled []accountdomain.QuotaRecoveryEvent + ensured []accountdomain.QuotaRecoveryEvent + rescheduled []accountdomain.QuotaRecoveryEvent + cancelled []accountdomain.QuotaRecoveryEvent } func (q *quotaQueueStub) EnsureQuotaRecovery(_ context.Context, value accountdomain.QuotaRecoveryEvent) error { @@ -72,6 +100,13 @@ func (q *quotaQueueStub) ScheduleQuotaRecovery(_ context.Context, value accountd return nil } +func (q *quotaQueueStub) CancelQuotaRecovery(_ context.Context, accountID uint64, mode string) error { + q.mu.Lock() + q.cancelled = append(q.cancelled, accountdomain.QuotaRecoveryEvent{AccountID: accountID, Mode: mode}) + q.mu.Unlock() + return nil +} + func (q *quotaQueueStub) ClaimDueQuotaRecoveries(_ context.Context, _ time.Time, limit int, lease time.Duration) ([]accountdomain.QuotaRecoveryEvent, error) { q.claimLimit, q.claimLease = limit, lease return q.claimed, nil @@ -84,7 +119,10 @@ func (q *quotaQueueStub) AckQuotaRecovery(_ context.Context, _ accountdomain.Quo return nil } -func (q *quotaQueueStub) RescheduleQuotaRecovery(context.Context, accountdomain.QuotaRecoveryEvent) error { +func (q *quotaQueueStub) RescheduleQuotaRecovery(_ context.Context, value accountdomain.QuotaRecoveryEvent) error { + q.mu.Lock() + q.rescheduled = append(q.rescheduled, value) + q.mu.Unlock() return nil } @@ -93,9 +131,10 @@ type quotaSyncStub struct { current int maxConcurrent int due []accountdomain.QuotaWindow + window accountdomain.QuotaWindow } -func (s *quotaSyncStub) RefreshQuotaMode(_ context.Context, accountID uint64, mode string) (accountdomain.QuotaWindow, error) { +func (s *quotaSyncStub) ProbeQuotaMode(_ context.Context, accountID uint64, mode string) (accountdomain.QuotaWindow, error) { s.mu.Lock() s.current++ if s.current > s.maxConcurrent { @@ -106,6 +145,11 @@ func (s *quotaSyncStub) RefreshQuotaMode(_ context.Context, accountID uint64, mo s.mu.Lock() s.current-- s.mu.Unlock() + if s.window.Mode != "" { + window := s.window + window.AccountID = accountID + return window, nil + } return accountdomain.QuotaWindow{AccountID: accountID, Mode: mode, Remaining: 1}, nil } diff --git a/backend/internal/domain/account/account.go b/backend/internal/domain/account/account.go index f6608266..44609479 100644 --- a/backend/internal/domain/account/account.go +++ b/backend/internal/domain/account/account.go @@ -266,7 +266,7 @@ const ( QuotaSourceUpstream QuotaSource = "upstream" ) -// QuotaWindow 表示 Grok Web 单个模式的请求额度窗口。 +// QuotaWindow 表示 Provider 单个模式的额度窗口。 type QuotaWindow struct { AccountID uint64 Mode string diff --git a/backend/internal/domain/audit/pricing.go b/backend/internal/domain/audit/pricing.go index aecc18d0..19226cba 100644 --- a/backend/internal/domain/audit/pricing.go +++ b/backend/internal/domain/audit/pricing.go @@ -10,6 +10,7 @@ const ( OfficialPricingSource = "https://docs.x.ai/developers/pricing" OfficialPricingAsOf = "2026-07-14" officialImageEditInputTicks int64 = 100_000_000 + officialLiteImageInputTicks int64 = 20_000_000 ) type PricingResult struct { @@ -260,25 +261,42 @@ func EstimateOfficialImageCost(model, resolution string, count int) (PricingResu // EstimateOfficialImageEditCost 按输出图片数量计费,并叠加每张输入图片的处理费用。 func EstimateOfficialImageEditCost(model, resolution string, outputCount, inputCount int) (PricingResult, bool) { - if normalizePricingModel(model) != "grok-imagine-image-edit" || outputCount <= 0 || inputCount <= 0 { + model = normalizePricingModel(model) + if outputCount <= 0 || inputCount <= 0 { return PricingResult{}, false } resolution = strings.ToLower(strings.TrimSpace(resolution)) if resolution == "" { resolution = "1k" } + pricingModel := "" + inputTicks := officialImageEditInputTicks var outputTicks int64 - switch resolution { - case "1k": - outputTicks = 500_000_000 - case "2k": - outputTicks = 700_000_000 + switch model { + case "grok-imagine-image-edit": + pricingModel = "grok-imagine-image-edit-" + resolution + case "grok-imagine-image-quality": + pricingModel = "grok-imagine-image-quality-edit-" + resolution + case "grok-imagine-image": + pricingModel = "grok-imagine-image-edit-lite-" + resolution + inputTicks = officialLiteImageInputTicks + outputTicks = 200_000_000 default: return PricingResult{}, false } + if resolution != "1k" && resolution != "2k" { + return PricingResult{}, false + } + if outputTicks == 0 { + if resolution == "1k" { + outputTicks = 500_000_000 + } else { + outputTicks = 700_000_000 + } + } return PricingResult{ - Model: "grok-imagine-image-edit-" + resolution, - CostInUSDTicks: int64(outputCount)*outputTicks + int64(inputCount)*officialImageEditInputTicks, + Model: pricingModel, + CostInUSDTicks: int64(outputCount)*outputTicks + int64(inputCount)*inputTicks, }, true } @@ -319,9 +337,17 @@ func ReconstructOfficialCost(model string, inputTokens, cachedInputTokens, outpu case "grok-imagine-image-quality-2k": return reconstructImageCost("grok-imagine-image-quality", "2k", outputImages) case "grok-imagine-image-edit-1k": - return reconstructImageEditCost("1k", inputImages, outputImages) + return reconstructImageEditCost("grok-imagine-image-edit", "1k", inputImages, outputImages) case "grok-imagine-image-edit-2k": - return reconstructImageEditCost("2k", inputImages, outputImages) + return reconstructImageEditCost("grok-imagine-image-edit", "2k", inputImages, outputImages) + case "grok-imagine-image-quality-edit-1k": + return reconstructImageEditCost("grok-imagine-image-quality", "1k", inputImages, outputImages) + case "grok-imagine-image-quality-edit-2k": + return reconstructImageEditCost("grok-imagine-image-quality", "2k", inputImages, outputImages) + case "grok-imagine-image-edit-lite-1k": + return reconstructImageEditCost("grok-imagine-image", "1k", inputImages, outputImages) + case "grok-imagine-image-edit-lite-2k": + return reconstructImageEditCost("grok-imagine-image", "2k", inputImages, outputImages) case "grok-imagine-video-480p": return reconstructVideoCost("grok-imagine-video", "480p", outputSeconds) case "grok-imagine-video-720p": @@ -371,21 +397,25 @@ func reconstructImageCost(model, resolution string, count int64) (PricingBreakdo ), true } -func reconstructImageEditCost(resolution string, inputCount, outputCount int64) (PricingBreakdown, bool) { +func reconstructImageEditCost(model, resolution string, inputCount, outputCount int64) (PricingBreakdown, bool) { if inputCount <= 0 || outputCount <= 0 || int64(int(inputCount)) != inputCount || int64(int(outputCount)) != outputCount { return PricingBreakdown{}, false } - result, ok := EstimateOfficialImageEditCost("grok-imagine-image-edit", resolution, int(outputCount), int(inputCount)) + result, ok := EstimateOfficialImageEditCost(model, resolution, int(outputCount), int(inputCount)) if !ok { return PricingBreakdown{}, false } - outputCost := result.CostInUSDTicks - inputCount*officialImageEditInputTicks + inputTicks := officialImageEditInputTicks + if normalizePricingModel(model) == "grok-imagine-image" { + inputTicks = officialLiteImageInputTicks + } + outputCost := result.CostInUSDTicks - inputCount*inputTicks if outputCost < 0 || outputCost%outputCount != 0 { return PricingBreakdown{}, false } return newPricingBreakdown(result.Model, PricingTierMedia, newPricingComponent(PricingComponentOutputImage, PricingUnitImage, outputCount, outputCost/outputCount), - newPricingComponent(PricingComponentInputImage, PricingUnitImage, inputCount, officialImageEditInputTicks), + newPricingComponent(PricingComponentInputImage, PricingUnitImage, inputCount, inputTicks), ), true } diff --git a/backend/internal/domain/audit/pricing_test.go b/backend/internal/domain/audit/pricing_test.go index 4359bafa..a5440bbd 100644 --- a/backend/internal/domain/audit/pricing_test.go +++ b/backend/internal/domain/audit/pricing_test.go @@ -126,6 +126,14 @@ func TestEstimateOfficialImageEditCost(t *testing.T) { if result, ok = EstimateOfficialImageEditCost("grok-imagine-image-edit", "4k", 1, 1); ok || result.CostInUSDTicks != 0 { t.Fatalf("unknown edit resolution = %#v, ok = %v", result, ok) } + result, ok = EstimateOfficialImageEditCost("Console/grok-imagine-image-quality", "2k", 1, 2) + if !ok || result.Model != "grok-imagine-image-quality-edit-2k" || result.CostInUSDTicks != 900_000_000 { + t.Fatalf("Console quality edit price = %#v, ok = %v", result, ok) + } + result, ok = EstimateOfficialImageEditCost("Console/grok-imagine-image", "1k", 1, 2) + if !ok || result.Model != "grok-imagine-image-edit-lite-1k" || result.CostInUSDTicks != 240_000_000 { + t.Fatalf("Console lite edit price = %#v, ok = %v", result, ok) + } } func TestEstimateOfficialVideoCost(t *testing.T) { diff --git a/backend/internal/domain/egress/egress.go b/backend/internal/domain/egress/egress.go index 80fb018f..f84ddff9 100644 --- a/backend/internal/domain/egress/egress.go +++ b/backend/internal/domain/egress/egress.go @@ -15,10 +15,11 @@ const LastErrorTransport = "transport error" type Scope string const ( - ScopeBuild Scope = "grok_build" - ScopeWeb Scope = "grok_web" - ScopeConsole Scope = "grok_console" - ScopeWebAsset Scope = "grok_web_asset" + ScopeBuild Scope = "grok_build" + ScopeWeb Scope = "grok_web" + ScopeConsole Scope = "grok_console" + ScopeWebAsset Scope = "grok_web_asset" + ScopeConsoleAsset Scope = "grok_console_asset" ) type Node struct { @@ -227,10 +228,11 @@ func DefaultOperationsConfig() OperationsConfig { ProbeIntervalSeconds: 900, AssignmentIntervalSeconds: 300, Fallbacks: map[Scope]FallbackConfig{ - ScopeBuild: {Mode: FallbackModeNone}, - ScopeWeb: {Mode: FallbackModeNone}, - ScopeConsole: {Mode: FallbackModeNone}, - ScopeWebAsset: {Mode: FallbackModeNone}, + ScopeBuild: {Mode: FallbackModeNone}, + ScopeWeb: {Mode: FallbackModeNone}, + ScopeConsole: {Mode: FallbackModeNone}, + ScopeWebAsset: {Mode: FallbackModeNone}, + ScopeConsoleAsset: {Mode: FallbackModeNone}, }, } } @@ -247,11 +249,19 @@ func (value OperationsConfig) FallbackFor(scope Scope) FallbackConfig { } // SupportsScope reports whether a node can serve requests for the supplied -// scope. Console may intentionally reuse a Web browser proxy, and Web assets -// inherit a Web node when no asset-specific node is required. +// scope. Console may intentionally reuse a Web browser proxy. Resource scopes +// may reuse their provider's primary node so explicit account bindings remain +// authoritative when no independently bound resource identity exists. func SupportsScope(nodeScope, requestScope Scope) bool { if nodeScope == requestScope { return true } - return (requestScope == ScopeWebAsset || requestScope == ScopeConsole) && nodeScope == ScopeWeb + switch requestScope { + case ScopeWebAsset, ScopeConsole: + return nodeScope == ScopeWeb + case ScopeConsoleAsset: + return nodeScope == ScopeConsole || nodeScope == ScopeWeb + default: + return false + } } diff --git a/backend/internal/domain/egress/egress_test.go b/backend/internal/domain/egress/egress_test.go new file mode 100644 index 00000000..75e99683 --- /dev/null +++ b/backend/internal/domain/egress/egress_test.go @@ -0,0 +1,26 @@ +package egress + +import "testing" + +func TestSupportsScopePreservesPrimaryAndResourceCompatibility(t *testing.T) { + tests := []struct { + name string + nodeScope, request Scope + want bool + }{ + {name: "exact Console asset", nodeScope: ScopeConsoleAsset, request: ScopeConsoleAsset, want: true}, + {name: "Console serves Console asset", nodeScope: ScopeConsole, request: ScopeConsoleAsset, want: true}, + {name: "Web serves Console asset", nodeScope: ScopeWeb, request: ScopeConsoleAsset, want: true}, + {name: "Web serves Web asset", nodeScope: ScopeWeb, request: ScopeWebAsset, want: true}, + {name: "Console asset does not serve primary Console", nodeScope: ScopeConsoleAsset, request: ScopeConsole, want: false}, + {name: "Web asset does not serve primary Web", nodeScope: ScopeWebAsset, request: ScopeWeb, want: false}, + {name: "Build remains isolated", nodeScope: ScopeBuild, request: ScopeConsoleAsset, want: false}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := SupportsScope(test.nodeScope, test.request); got != test.want { + t.Fatalf("SupportsScope(%q, %q) = %v, want %v", test.nodeScope, test.request, got, test.want) + } + }) + } +} diff --git a/backend/internal/domain/model/model.go b/backend/internal/domain/model/model.go index 38cc8d6c..684d5b98 100644 --- a/backend/internal/domain/model/model.go +++ b/backend/internal/domain/model/model.go @@ -24,6 +24,18 @@ const ( CapabilityVideo Capability = "video" ) +// Capabilities returns every persisted route capability. Callers use this as +// the single source of truth for bounds that depend on the maximum group size. +func Capabilities() []Capability { + return []Capability{ + CapabilityResponses, + CapabilityChat, + CapabilityImage, + CapabilityImageEdit, + CapabilityVideo, + } +} + const ( OriginCatalog Origin = "catalog" OriginDiscovered Origin = "discovered" @@ -48,6 +60,14 @@ type Route struct { UpdatedAt time.Time } +// RouteGroup is the admin-facing projection of one logical model target. +// Managed catalog capabilities share a group. Manual routes remain independent +// scheduling targets even when their visible names happen to match: neither a +// display name nor an upstream model is a stable identity for account bindings. +type RouteGroup struct { + Routes []Route +} + // NormalizePublicID 将内部路由 ID 规范化为稳定的 Provider 命名空间。 // Provider 前缀只用于区分内部路由目标,不应直接暴露给下游客户端。 func NormalizePublicID(provider account.Provider, value string) (string, bool) { diff --git a/backend/internal/infra/egress/manager.go b/backend/internal/infra/egress/manager.go index aa28b898..4847782c 100644 --- a/backend/internal/infra/egress/manager.go +++ b/backend/internal/infra/egress/manager.go @@ -838,10 +838,10 @@ func (m *Manager) acquire(ctx context.Context, scope domain.Scope, affinity stri } fallbackConfig, fallbackSupported, fallbackConfigErr := m.loadOperationsConfig(ctx, now) fallback := domain.FallbackConfig{Mode: domain.FallbackModeNone} - reservedFallbackNodes := make(map[uint64]struct{}, 4) + reservedFallbackNodes := make(map[uint64]struct{}, len(allEgressScopes())) if fallbackConfigErr == nil && fallbackSupported { fallback = fallbackConfig.FallbackFor(scope) - for _, fallbackScope := range []domain.Scope{domain.ScopeBuild, domain.ScopeWeb, domain.ScopeConsole, domain.ScopeWebAsset} { + for _, fallbackScope := range allEgressScopes() { configuredFallback := fallbackConfig.FallbackFor(fallbackScope) if configuredFallback.Mode == domain.FallbackModeFixed && configuredFallback.NodeID != 0 { reservedFallbackNodes[configuredFallback.NodeID] = struct{}{} @@ -1062,7 +1062,7 @@ func (m *Manager) leaseForNode(ctx context.Context, scope domain.Scope, affinity func (m *Manager) leaseForNodeWithOptions(ctx context.Context, scope domain.Scope, affinity, encryptedCredentialCookies string, managedClearance bool, selected domain.Node, options clientOptions) (*Lease, bool, error) { credentialCookies := "" - if !managedClearance && scope != domain.ScopeBuild && strings.TrimSpace(encryptedCredentialCookies) != "" { + if !managedClearance && usesBrowserClearance(scope) && strings.TrimSpace(encryptedCredentialCookies) != "" { decryptedCookies, decryptErr := m.cipher.Decrypt(encryptedCredentialCookies) if decryptErr != nil { return nil, true, decryptErr @@ -1091,7 +1091,7 @@ func (m *Manager) leaseForNodeWithOptions(ctx context.Context, scope domain.Scop } } cookies := "" - if scope != domain.ScopeBuild { + if usesBrowserClearance(scope) { cookies, err = m.cipher.Decrypt(selected.EncryptedCloudflareCookie) if err != nil { // Managed mode can recover a damaged persisted cookie by asking the @@ -1127,7 +1127,10 @@ func (m *Manager) leaseForNodeWithOptions(ctx context.Context, scope domain.Scop // Derive identity independently of the current toggle. clientFor applies one // authoritative toggle snapshot, so enabling isolation between these two // stages cannot accidentally place an account request in the shared bucket. - accountIdentity := isolationAccountIdentity(ctx, scope, affinity) + accountIdentity := "" + if scope != domain.ScopeConsoleAsset { + accountIdentity = isolationAccountIdentity(ctx, scope, affinity) + } client, err := m.clientForWithOptions(selected.ID, scope, proxyURL, userAgent, cookies, sticky, accountIdentity, options) if err != nil { return nil, false, err @@ -1142,6 +1145,14 @@ func (m *Manager) leaseForNodeWithOptions(ctx context.Context, scope domain.Scop }}, true, nil } +// Console assets are served from public media hosts. They still need the +// selected proxy and browser user agent, but forwarding account or node +// clearance cookies would unnecessarily expose credentials to a different +// origin and make an otherwise anonymous download depend on cookie storage. +func usesBrowserClearance(scope domain.Scope) bool { + return scope != domain.ScopeBuild && scope != domain.ScopeConsoleAsset +} + func (m *Manager) inflightCounter(nodeID uint64) *atomic.Int64 { // Counters remain address-stable for the manager lifetime so a concurrent // release can never decrement a replacement counter after an ABA deletion. @@ -1289,6 +1300,9 @@ func fallbackScopes(scope domain.Scope) []domain.Scope { if scope == domain.ScopeWebAsset { return []domain.Scope{domain.ScopeWebAsset, domain.ScopeWeb} } + if scope == domain.ScopeConsoleAsset { + return []domain.Scope{domain.ScopeConsoleAsset, domain.ScopeConsole, domain.ScopeWeb} + } if scope == domain.ScopeConsole { // Console uses the same browser/clearance surface as Grok Web. A // dedicated Console node is preferred, but a Web node is a safe and @@ -1451,7 +1465,7 @@ func (m *Manager) createAndCacheClient(key clientCacheKey, id uint64, scope doma } if id != 0 && !sticky { for previousKey, previous := range m.clients { - if previousKey.nodeID != id { + if previousKey.nodeID != id || previousKey.scope != key.scope { continue } // Keep other accounts' pools when isolation is on. @@ -1588,6 +1602,13 @@ func (m *Manager) FeedbackForScope(ctx context.Context, scope domain.Scope, node if status == clientClosedRequestStatus || errors.Is(transportErr, context.Canceled) { return } + // Console media hosts are public and do not use clearance credentials. A + // 403 there commonly describes the object URL (expired, rejected, or + // missing), not the proxy's ability to reach the origin, so it must not cool + // or rotate an otherwise healthy primary Console node. + if scope == domain.ScopeConsoleAsset && transportErr == nil && status == http.StatusForbidden { + return + } if scope == domain.ScopeBuild && neterrorpkg.IsResponseHeaderTimeout(transportErr) { return } @@ -2116,7 +2137,7 @@ func (m *Manager) ForgetClearances(nodeIDs []uint64) { if m.nodeVersions == nil { m.nodeVersions = make(map[domain.Scope]uint64) } - for _, scope := range []domain.Scope{domain.ScopeBuild, domain.ScopeWeb, domain.ScopeConsole, domain.ScopeWebAsset} { + for _, scope := range allEgressScopes() { m.nodeVersions[scope]++ } clear(m.nodes) @@ -2226,6 +2247,10 @@ func isGrokWebScope(scope domain.Scope) bool { return scope == domain.ScopeWeb || scope == domain.ScopeWebAsset || scope == domain.ScopeConsole } +func allEgressScopes() []domain.Scope { + return []domain.Scope{domain.ScopeBuild, domain.ScopeWeb, domain.ScopeConsole, domain.ScopeWebAsset, domain.ScopeConsoleAsset} +} + func (m *Manager) isStickyProxyNode(value domain.Node) bool { if m == nil || m.cipher == nil || strings.TrimSpace(value.EncryptedProxyURL) == "" { return false diff --git a/backend/internal/infra/egress/manager_test.go b/backend/internal/infra/egress/manager_test.go index fced3115..6ec555b9 100644 --- a/backend/internal/infra/egress/manager_test.go +++ b/backend/internal/infra/egress/manager_test.go @@ -162,6 +162,15 @@ func TestCanceledRequestDoesNotInvalidateDirectClient(t *testing.T) { } } +func TestConsoleAssetForbiddenDoesNotPenalizeProxy(t *testing.T) { + repository := &mutableEgressRepository{node: domain.Node{ID: 1, Name: "console", Scope: domain.ScopeConsole, Enabled: true, Health: 1}} + manager := NewManager(repository, nil) + manager.FeedbackForScope(context.Background(), domain.ScopeConsoleAsset, 1, http.StatusForbidden, nil) + if repository.updates != 0 || repository.node.Health != 1 || repository.node.CooldownUntil != nil { + t.Fatalf("Console asset object rejection changed proxy health: updates=%d node=%#v", repository.updates, repository.node) + } +} + func TestProbeEgressNodeLogsSuccessWithoutProxyCredentials(t *testing.T) { cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") if err != nil { @@ -1006,6 +1015,110 @@ func TestAcquireCredentialUsesExplicitBoundNode(t *testing.T) { } } +func TestConsoleAssetCredentialPrefersDedicatedNodeWithoutCookies(t *testing.T) { + cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") + if err != nil { + t.Fatal(err) + } + encryptProxy := func(raw string) string { + t.Helper() + value, encryptErr := cipher.Encrypt(raw) + if encryptErr != nil { + t.Fatal(encryptErr) + } + return value + } + manager := NewManager(egressRepositoryTestStub{nodes: []domain.Node{ + {ID: 1, Name: "web", Scope: domain.ScopeWeb, Enabled: true, Health: 1, EncryptedProxyURL: encryptProxy("http://web.example:8080")}, + {ID: 2, Name: "console", Scope: domain.ScopeConsole, Enabled: true, Health: 1, EncryptedProxyURL: encryptProxy("http://console.example:8080")}, + {ID: 3, Name: "console-assets", Scope: domain.ScopeConsoleAsset, Enabled: true, Health: 1, EncryptedProxyURL: encryptProxy("http://assets.example:8080"), EncryptedCloudflareCookie: "damaged-node-cookie", UserAgent: "asset-agent"}, + }}, cipher) + lease, err := manager.AcquireCredential(context.Background(), domain.ScopeConsoleAsset, accountdomain.Credential{ + ID: 42, Provider: accountdomain.ProviderConsole, EncryptedCloudflareCookie: "damaged-account-cookie", + }) + if err != nil { + t.Fatal(err) + } + defer lease.Release() + if lease.NodeID != 3 || lease.Scope != domain.ScopeConsoleAsset || lease.UserAgent != "asset-agent" { + t.Fatalf("asset lease = %#v", lease) + } + if lease.CFCookies != "" { + t.Fatalf("anonymous Console asset lease exposed cookies: %q", lease.CFCookies) + } +} + +func TestConsoleAssetCredentialPreservesExplicitConsoleBinding(t *testing.T) { + cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") + if err != nil { + t.Fatal(err) + } + boundProxy, err := cipher.Encrypt("http://bound-console.example:8080") + if err != nil { + t.Fatal(err) + } + assetProxy, err := cipher.Encrypt("http://assets.example:8080") + if err != nil { + t.Fatal(err) + } + manager := NewManager(egressRepositoryTestStub{nodes: []domain.Node{ + {ID: 2, Name: "bound-console", Scope: domain.ScopeConsole, Enabled: true, Health: 1, EncryptedProxyURL: boundProxy}, + {ID: 3, Name: "console-assets", Scope: domain.ScopeConsoleAsset, Enabled: true, Health: 1, EncryptedProxyURL: assetProxy}, + }}, cipher) + lease, err := manager.AcquireCredential(context.Background(), domain.ScopeConsoleAsset, accountdomain.Credential{ + ID: 42, Provider: accountdomain.ProviderConsole, EgressNodeID: 2, + }) + if err != nil { + t.Fatal(err) + } + defer lease.Release() + if lease.NodeID != 2 || lease.NodeName != "bound-console" { + t.Fatalf("explicit Console binding was not preserved: node=%d name=%q", lease.NodeID, lease.NodeName) + } +} + +func TestConsoleAssetClientDoesNotEvictPrimaryConsoleClient(t *testing.T) { + cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") + if err != nil { + t.Fatal(err) + } + proxyURL, err := cipher.Encrypt("http://console.example:8080") + if err != nil { + t.Fatal(err) + } + cookie, err := cipher.Encrypt("cf_clearance=console") + if err != nil { + t.Fatal(err) + } + manager := NewManager(egressRepositoryTestStub{nodes: []domain.Node{{ + ID: 2, Name: "console", Scope: domain.ScopeConsole, Enabled: true, Health: 1, EncryptedProxyURL: proxyURL, + }}}, cipher) + credential := accountdomain.Credential{ + ID: 42, Provider: accountdomain.ProviderConsole, EgressNodeID: 2, EncryptedCloudflareCookie: cookie, + } + primary, err := manager.AcquireCredential(context.Background(), domain.ScopeConsole, credential) + if err != nil { + t.Fatal(err) + } + defer primary.Release() + asset, err := manager.AcquireCredential(context.Background(), domain.ScopeConsoleAsset, credential) + if err != nil { + t.Fatal(err) + } + defer asset.Release() + primaryAgain, err := manager.AcquireCredential(context.Background(), domain.ScopeConsole, credential) + if err != nil { + t.Fatal(err) + } + defer primaryAgain.Release() + if primary.client != primaryAgain.client { + t.Fatal("Console asset download evicted the primary Console connection pool") + } + if primary.client == asset.client || len(manager.clients) != 2 { + t.Fatalf("primary and anonymous asset clients were not isolated: cached=%d", len(manager.clients)) + } +} + func TestAcquireCredentialDoesNotRouteDirectWhenBoundNodeHasNoProxy(t *testing.T) { cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") if err != nil { diff --git a/backend/internal/infra/persistence/relational/account_repository.go b/backend/internal/infra/persistence/relational/account_repository.go index e72db9cb..e5332131 100644 --- a/backend/internal/infra/persistence/relational/account_repository.go +++ b/backend/internal/infra/persistence/relational/account_repository.go @@ -50,7 +50,7 @@ const ( accountFreeBillingSignal = `(` + accountFreePlanSignal + ` OR ` + accountInferredFreeBillingSignal + `)` accountFreeSignalPredicate = `(provider_accounts.provider = 'grok_build' AND (LOWER(TRIM(provider_accounts.observed_model)) LIKE '%-build-free' OR EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = provider_accounts.id AND ` + accountFreeBillingSignal + `)))` accountRecoveryPredicate = `EXISTS (SELECT 1 FROM account_quota_recovery recovery WHERE recovery.account_id = provider_accounts.id AND recovery.status IN ('exhausted', 'probing'))` - providerQuotaExhaustedPredicate = `((provider_accounts.provider = 'grok_web' AND ((EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly') AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly' AND quota.remaining > 0)) OR (NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly') AND EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id) AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.remaining > 0)))) OR (provider_accounts.provider = 'grok_console' AND EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id) AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.remaining > 0)))` + providerQuotaExhaustedPredicate = `((provider_accounts.provider = 'grok_web' AND ((EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly') AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly' AND quota.remaining > 0)) OR (NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly') AND EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id) AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.remaining > 0)))) OR (provider_accounts.provider = 'grok_console' AND EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'console') AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'console' AND quota.remaining > 0)))` accountTypeSortExpression = `CASE WHEN provider_accounts.provider = 'grok_web' THEN COALESCE((SELECT profile.tier FROM web_account_profiles profile WHERE profile.account_id = provider_accounts.id), 'auto') WHEN ` + accountBuildSuperPredicate + ` THEN 'paid' WHEN ` + accountFreeSignalPredicate + ` THEN 'free' ELSE 'unknown' END` accountStatusSortExpression = `CASE WHEN provider_accounts.enabled = FALSE THEN 4 WHEN provider_accounts.auth_status = 'reauthRequired' THEN 5 WHEN EXISTS (SELECT 1 FROM account_quota_recovery recovery WHERE recovery.account_id = provider_accounts.id AND recovery.status = 'probing') THEN 3 WHEN EXISTS (SELECT 1 FROM account_quota_recovery recovery WHERE recovery.account_id = provider_accounts.id AND recovery.status = 'exhausted') OR ` + providerQuotaExhaustedPredicate + ` THEN 2 WHEN provider_accounts.cooldown_until > CURRENT_TIMESTAMP THEN 1 ELSE 0 END` missingConsoleAccountPredicate = `NOT EXISTS (SELECT 1 FROM provider_accounts AS console_account WHERE console_account.provider = ? AND console_account.source_key = ('console-' || provider_accounts.source_key))` @@ -296,9 +296,17 @@ func (r *AccountRepository) ListRoutingCandidates(ctx context.Context, provider } } result := make([]account.RoutingCandidate, 0, len(values)) + staticConsoleModel := provider == account.ProviderConsole && strings.TrimSpace(quotaMode) != "" for _, value := range values { capabilityKnown, supportsModel := known[value.ID], supported[value.ID] - if len(bound) > 0 { + if staticConsoleModel { + // Console exposes a provider-wide static catalog. Historical account + // snapshots may predate newly shipped catalog entries, but must not + // make those built-in routes unroutable until every account is synced + // again. A non-empty quota mode proves the adapter recognizes the + // upstream model; unknown/manual models keep snapshot-based gating. + capabilityKnown, supportsModel = true, true + } else if len(bound) > 0 { capabilityKnown, supportsModel = true, true } else if sharedSuperBuildModel { var billing *account.Billing @@ -2125,9 +2133,28 @@ func (r *AccountRepository) ResetProviderQuotaState(ctx context.Context, provide } func (r *AccountRepository) HasQuotaWindows(ctx context.Context, accountID uint64) (bool, error) { + var providerRow struct { + Provider string + } + if err := r.db.db.WithContext(ctx).Model(&accountModel{}).Select("provider").Where("id = ?", accountID).Take(&providerRow).Error; err != nil { + return false, err + } var count int64 - err := r.db.db.WithContext(ctx).Model("aWindowModel{}).Where("account_id = ? AND synced_at IS NOT NULL", accountID).Count(&count).Error - return count > 0, err + query := r.db.db.WithContext(ctx).Model("aWindowModel{}).Where("account_id = ? AND synced_at IS NOT NULL", accountID) + if account.Provider(providerRow.Provider) == account.ProviderConsole { + // Pre-usage Console releases stored one synthetic local chat window. + // Only the complete authoritative /usage snapshot counts as initialized, + // so re-import and startup migration replace that legacy state. + query = query.Where("source = ? AND mode IN ?", account.QuotaSourceUpstream, []string{"console", "console_image", "console_video"}).Distinct("mode") + if err := query.Count(&count).Error; err != nil { + return false, err + } + return count == 3, nil + } + if err := query.Count(&count).Error; err != nil { + return false, err + } + return count > 0, nil } func (r *AccountRepository) GetQuotaWindows(ctx context.Context, accountIDs []uint64) (map[uint64][]account.QuotaWindow, error) { diff --git a/backend/internal/infra/persistence/relational/audit_repository.go b/backend/internal/infra/persistence/relational/audit_repository.go index 53a15f37..9bd9ed9e 100644 --- a/backend/internal/infra/persistence/relational/audit_repository.go +++ b/backend/internal/infra/persistence/relational/audit_repository.go @@ -111,7 +111,7 @@ func validatePreparedAudit(value preparedAudit) error { if row.EgressNodeID != nil && *row.EgressNodeID == 0 { return errors.New("egress_node_id must be positive when present") } - if !auditStringAllowed(row.EgressScope, "", "grok_build", "grok_web", "grok_console", "grok_web_asset") { + if !auditStringAllowed(row.EgressScope, "", "grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset") { return errors.New("egress_scope is invalid") } if !auditStringAllowed(row.EgressMode, "", "direct", "proxy") { diff --git a/backend/internal/infra/persistence/relational/console_provider_test.go b/backend/internal/infra/persistence/relational/console_provider_test.go index d3ab2749..c5252382 100644 --- a/backend/internal/infra/persistence/relational/console_provider_test.go +++ b/backend/internal/infra/persistence/relational/console_provider_test.go @@ -29,12 +29,19 @@ func TestConsoleQuotaParticipatesInRoutingAndSummary(t *testing.T) { } now := time.Now().UTC() resetAt := now.Add(time.Hour) - if err := repository.SaveQuotaWindows(ctx, credential.ID, "", now, []account.QuotaWindow{{ - AccountID: credential.ID, Mode: "console", Remaining: 20, Total: 20, WindowSeconds: 3600, - ResetAt: &resetAt, Source: account.QuotaSourceDefault, UpdatedAt: now, - }}); err != nil { + if err := repository.SaveQuotaWindows(ctx, credential.ID, "", now, []account.QuotaWindow{ + { + AccountID: credential.ID, Mode: "console", Remaining: 20, Total: 20, WindowSeconds: 3600, + ResetAt: &resetAt, SyncedAt: &now, Source: account.QuotaSourceUpstream, UpdatedAt: now, + }, + {AccountID: credential.ID, Mode: "console_image", Remaining: 0, Total: 5, SyncedAt: &now, Source: account.QuotaSourceUpstream, UpdatedAt: now}, + {AccountID: credential.ID, Mode: "console_video", Remaining: 2, Total: 2, SyncedAt: &now, Source: account.QuotaSourceUpstream, UpdatedAt: now}, + }); err != nil { t.Fatal(err) } + if complete, err := repository.HasQuotaWindows(ctx, credential.ID); err != nil || !complete { + t.Fatalf("complete Console snapshot = %v, err = %v", complete, err) + } var profileCount int64 if err := database.db.WithContext(ctx).Model(&webAccountProfileModel{}).Where("account_id = ?", credential.ID).Count(&profileCount).Error; err != nil { t.Fatal(err) @@ -67,3 +74,37 @@ func TestConsoleQuotaParticipatesInRoutingAndSummary(t *testing.T) { t.Fatalf("summary after exhaustion = %#v", summary) } } + +func TestHasQuotaWindowsRejectsLegacyConsoleSnapshot(t *testing.T) { + ctx := context.Background() + database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "console-legacy.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repository := NewAccountRepository(database) + credential, _, err := repository.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderConsole, AuthType: account.AuthTypeSSO, Name: "legacy", SourceKey: "console:legacy", + EncryptedAccessToken: "encrypted", Enabled: true, AuthStatus: account.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + if err := repository.SaveQuotaWindows(ctx, credential.ID, "", now, []account.QuotaWindow{{ + AccountID: credential.ID, Mode: "console", Remaining: 20, Total: 20, WindowSeconds: 3600, + Source: account.QuotaSourceDefault, UpdatedAt: now, + }}); err != nil { + t.Fatal(err) + } + complete, err := repository.HasQuotaWindows(ctx, credential.ID) + if err != nil { + t.Fatal(err) + } + if complete { + t.Fatal("legacy synthetic Console quota must require /usage migration") + } +} diff --git a/backend/internal/infra/persistence/relational/egress_operations_test.go b/backend/internal/infra/persistence/relational/egress_operations_test.go index 21d7dddd..634a04fb 100644 --- a/backend/internal/infra/persistence/relational/egress_operations_test.go +++ b/backend/internal/infra/persistence/relational/egress_operations_test.go @@ -884,8 +884,9 @@ func TestEgressOperationsConfigPersistsFixedFallback(t *testing.T) { saved, err := service.UpdateOperationsConfig(ctx, egressapp.OperationsConfigInput{ ProbeProvider: egress.ProbeProviderCloudflare, ProbeIntervalSeconds: 900, AssignmentIntervalSeconds: 300, Fallbacks: map[egress.Scope]egressapp.FallbackConfigInput{ - egress.ScopeBuild: {Mode: egress.FallbackModeFixed, NodeID: fixed.ID}, - egress.ScopeWeb: {Mode: egress.FallbackModeDirect}, + egress.ScopeBuild: {Mode: egress.FallbackModeFixed, NodeID: fixed.ID}, + egress.ScopeWeb: {Mode: egress.FallbackModeDirect}, + egress.ScopeConsoleAsset: {Mode: egress.FallbackModeDirect}, }, }) if err != nil { @@ -903,6 +904,9 @@ func TestEgressOperationsConfigPersistsFixedFallback(t *testing.T) { if fallback := saved.FallbackFor(egress.ScopeConsole); fallback.Mode != egress.FallbackModeNone || fallback.NodeID != 0 { t.Fatalf("default Console fallback = %#v", fallback) } + if fallback := saved.FallbackFor(egress.ScopeConsoleAsset); fallback.Mode != egress.FallbackModeDirect || fallback.NodeID != 0 { + t.Fatalf("saved Console asset fallback = %#v", fallback) + } stored, err := nodes.GetEgressOperationsConfig(ctx) if err != nil { @@ -914,6 +918,9 @@ func TestEgressOperationsConfigPersistsFixedFallback(t *testing.T) { if fallback := stored.FallbackFor(egress.ScopeWeb); fallback.Mode != egress.FallbackModeDirect || fallback.NodeID != 0 { t.Fatalf("stored Web fallback = %#v", fallback) } + if fallback := stored.FallbackFor(egress.ScopeConsoleAsset); fallback.Mode != egress.FallbackModeDirect || fallback.NodeID != 0 { + t.Fatalf("stored Console asset fallback = %#v", fallback) + } if stored.ProbeProvider != egress.ProbeProviderCloudflare { t.Fatalf("stored probe provider = %q", stored.ProbeProvider) } @@ -929,6 +936,9 @@ func TestEgressOperationsConfigPersistsFixedFallback(t *testing.T) { if fallback := updated.FallbackFor(egress.ScopeWeb); fallback.Mode != egress.FallbackModeDirect { t.Fatalf("sparse update reset Web fallback = %#v", fallback) } + if fallback := updated.FallbackFor(egress.ScopeConsoleAsset); fallback.Mode != egress.FallbackModeDirect { + t.Fatalf("sparse update reset Console asset fallback = %#v", fallback) + } } func TestFixedFallbackReferenceIsProtectedAndClearedOnDelete(t *testing.T) { diff --git a/backend/internal/infra/persistence/relational/egress_repository.go b/backend/internal/infra/persistence/relational/egress_repository.go index f1812c64..c5f58fbe 100644 --- a/backend/internal/infra/persistence/relational/egress_repository.go +++ b/backend/internal/infra/persistence/relational/egress_repository.go @@ -509,6 +509,7 @@ func configReferencesAnyFallbackNode(config egressOperationsConfigModel, ids []u {config.WebFallbackMode, config.WebFallbackNodeID}, {config.ConsoleFallbackMode, config.ConsoleFallbackNodeID}, {config.WebAssetFallbackMode, config.WebAssetFallbackNodeID}, + {config.ConsoleAssetFallbackMode, config.ConsoleAssetFallbackNodeID}, } { if egress.FallbackMode(fallback.mode).Normalized() != egress.FallbackModeFixed { continue @@ -530,6 +531,7 @@ func validateLockedEgressFallbackNodes(tx *gorm.DB, config egressOperationsConfi {egress.ScopeWeb, config.WebFallbackMode, config.WebFallbackNodeID}, {egress.ScopeConsole, config.ConsoleFallbackMode, config.ConsoleFallbackNodeID}, {egress.ScopeWebAsset, config.WebAssetFallbackMode, config.WebAssetFallbackNodeID}, + {egress.ScopeConsoleAsset, config.ConsoleAssetFallbackMode, config.ConsoleAssetFallbackNodeID}, } ids := make([]uint64, 0, len(fallbacks)) for _, fallback := range fallbacks { @@ -667,6 +669,7 @@ func clearEgressFallbackNodeReferences(tx *gorm.DB, ids []uint64) error { {"web_fallback_mode", "web_fallback_node_id"}, {"console_fallback_mode", "console_fallback_node_id"}, {"web_asset_fallback_mode", "web_asset_fallback_node_id"}, + {"console_asset_fallback_mode", "console_asset_fallback_node_id"}, } { if err := tx.Model(&egressOperationsConfigModel{}). Where("id = ? AND "+columns[1]+" IN ?", 1, ids). @@ -695,6 +698,7 @@ func clearInvalidEgressFallbackNodeReferences(tx *gorm.DB) error { {egress.ScopeWeb, config.WebFallbackMode, config.WebFallbackNodeID, "web_fallback_mode", "web_fallback_node_id"}, {egress.ScopeConsole, config.ConsoleFallbackMode, config.ConsoleFallbackNodeID, "console_fallback_mode", "console_fallback_node_id"}, {egress.ScopeWebAsset, config.WebAssetFallbackMode, config.WebAssetFallbackNodeID, "web_asset_fallback_mode", "web_asset_fallback_node_id"}, + {egress.ScopeConsoleAsset, config.ConsoleAssetFallbackMode, config.ConsoleAssetFallbackNodeID, "console_asset_fallback_mode", "console_asset_fallback_node_id"}, } { if egress.FallbackMode(fallback.mode).Normalized() != egress.FallbackModeFixed { continue @@ -841,10 +845,11 @@ func toEgressOperationsConfigDomain(row egressOperationsConfigModel) egress.Oper ProbeIntervalSeconds: row.ProbeIntervalSeconds, AutoAssignEnabled: row.AutoAssignEnabled, AutoBalanceEnabled: row.AutoBalanceEnabled, AssignmentIntervalSeconds: row.AssignmentIntervalSeconds, Fallbacks: map[egress.Scope]egress.FallbackConfig{ - egress.ScopeBuild: {Mode: egress.FallbackMode(row.BuildFallbackMode).Normalized(), NodeID: row.BuildFallbackNodeID}, - egress.ScopeWeb: {Mode: egress.FallbackMode(row.WebFallbackMode).Normalized(), NodeID: row.WebFallbackNodeID}, - egress.ScopeConsole: {Mode: egress.FallbackMode(row.ConsoleFallbackMode).Normalized(), NodeID: row.ConsoleFallbackNodeID}, - egress.ScopeWebAsset: {Mode: egress.FallbackMode(row.WebAssetFallbackMode).Normalized(), NodeID: row.WebAssetFallbackNodeID}, + egress.ScopeBuild: {Mode: egress.FallbackMode(row.BuildFallbackMode).Normalized(), NodeID: row.BuildFallbackNodeID}, + egress.ScopeWeb: {Mode: egress.FallbackMode(row.WebFallbackMode).Normalized(), NodeID: row.WebFallbackNodeID}, + egress.ScopeConsole: {Mode: egress.FallbackMode(row.ConsoleFallbackMode).Normalized(), NodeID: row.ConsoleFallbackNodeID}, + egress.ScopeWebAsset: {Mode: egress.FallbackMode(row.WebAssetFallbackMode).Normalized(), NodeID: row.WebAssetFallbackNodeID}, + egress.ScopeConsoleAsset: {Mode: egress.FallbackMode(row.ConsoleAssetFallbackMode).Normalized(), NodeID: row.ConsoleAssetFallbackNodeID}, }, UpdatedAt: row.UpdatedAt, } @@ -855,6 +860,7 @@ func fromEgressOperationsConfigDomain(value egress.OperationsConfig) egressOpera webFallback := value.FallbackFor(egress.ScopeWeb) consoleFallback := value.FallbackFor(egress.ScopeConsole) webAssetFallback := value.FallbackFor(egress.ScopeWebAsset) + consoleAssetFallback := value.FallbackFor(egress.ScopeConsoleAsset) return egressOperationsConfigModel{ ID: 1, ProbeProvider: string(value.ProbeProvider.Normalized()), ProbeIntervalSeconds: value.ProbeIntervalSeconds, AutoAssignEnabled: value.AutoAssignEnabled, AutoBalanceEnabled: value.AutoBalanceEnabled, AssignmentIntervalSeconds: value.AssignmentIntervalSeconds, @@ -862,6 +868,7 @@ func fromEgressOperationsConfigDomain(value egress.OperationsConfig) egressOpera WebFallbackMode: string(webFallback.Mode), WebFallbackNodeID: webFallback.NodeID, ConsoleFallbackMode: string(consoleFallback.Mode), ConsoleFallbackNodeID: consoleFallback.NodeID, WebAssetFallbackMode: string(webAssetFallback.Mode), WebAssetFallbackNodeID: webAssetFallback.NodeID, + ConsoleAssetFallbackMode: string(consoleAssetFallback.Mode), ConsoleAssetFallbackNodeID: consoleAssetFallback.NodeID, UpdatedAt: value.UpdatedAt, } } diff --git a/backend/internal/infra/persistence/relational/model_capability_repository_test.go b/backend/internal/infra/persistence/relational/model_capability_repository_test.go index 201139de..64b84ac1 100644 --- a/backend/internal/infra/persistence/relational/model_capability_repository_test.go +++ b/backend/internal/infra/persistence/relational/model_capability_repository_test.go @@ -85,6 +85,189 @@ func TestModelCapabilitiesAggregateAndGateEnabledRoutes(t *testing.T) { } } +func TestConsoleBuiltInModelIgnoresStaleAccountCapabilitySnapshot(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + accounts := NewAccountRepository(database) + models := NewModelRepository(database) + + credential, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderConsole, Name: "console", SourceKey: "console", + EncryptedAccessToken: testEncryptedToken, Enabled: true, AuthStatus: account.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + if err := models.ReplaceAccountCapabilities(ctx, credential.ID, []string{"grok-4.3"}, time.Now().UTC()); err != nil { + t.Fatal(err) + } + + candidates, err := accounts.ListRoutingCandidates(ctx, account.ProviderConsole, 0, "grok-imagine-image-quality", "console_image") + if err != nil { + t.Fatal(err) + } + if len(candidates) != 1 || !candidates[0].ModelCapabilityKnown || !candidates[0].SupportsModel { + t.Fatalf("built-in Console model must survive a stale account snapshot: %#v", candidates) + } + + candidates, err = accounts.ListRoutingCandidates(ctx, account.ProviderConsole, 0, "unknown-console-model", "") + if err != nil { + t.Fatal(err) + } + if len(candidates) != 1 || !candidates[0].ModelCapabilityKnown || candidates[0].SupportsModel { + t.Fatalf("unknown Console model must retain capability gating: %#v", candidates) + } +} + +func TestConsoleCatalogRoutesUseAutomaticAccountPoolWithoutCapabilitySnapshot(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + accounts := NewAccountRepository(database) + models := NewModelRepository(database) + + createAccount := func(name string) account.Credential { + t.Helper() + value, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderConsole, Name: name, SourceKey: name, + EncryptedAccessToken: testEncryptedToken, AuthStatus: account.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + return value + } + first := createAccount("console-first") + second := createAccount("console-second") + disabled := createAccount("console-disabled") + disabled.Enabled = false + if _, err := accounts.Update(ctx, disabled); err != nil { + t.Fatal(err) + } + reauth := createAccount("console-reauth") + reauth.AuthStatus = account.AuthStatusReauthRequired + if _, err := accounts.Update(ctx, reauth); err != nil { + t.Fatal(err) + } + + const publicID = "grok-imagine-image-quality" + if err := models.UpsertRoutes(ctx, []model.Route{ + {PublicID: publicID, Provider: account.ProviderConsole, UpstreamModel: publicID, Capability: model.CapabilityImage, Origin: model.OriginCatalog, Enabled: true}, + {PublicID: publicID, Provider: account.ProviderConsole, UpstreamModel: publicID, Capability: model.CapabilityImageEdit, Origin: model.OriginCatalog, Enabled: true}, + }); err != nil { + t.Fatal(err) + } + + enabled, err := models.ListEnabled(ctx) + if err != nil { + t.Fatal(err) + } + if len(enabled) != 2 { + t.Fatalf("enabled Console routes = %#v", enabled) + } + for _, route := range enabled { + if route.SupportedAccounts != 2 || route.TotalAccounts != 2 || route.SyncedAccounts != 0 || len(route.BoundAccountIDs) != 0 { + t.Fatalf("automatic Console account pool = %#v", route) + } + } + unknown, err := models.Create(ctx, model.Route{ + PublicID: "legacy-unknown-console", Provider: account.ProviderConsole, UpstreamModel: "unknown-console-model", + Capability: model.CapabilityImage, Enabled: true, + }, nil) + if err != nil { + t.Fatal(err) + } + if unknown.SupportedAccounts != 0 || unknown.TotalAccounts != 2 { + t.Fatalf("unknown Console route must not inherit static catalog support: %#v", unknown) + } + if enabledAfterUnknown, err := models.ListEnabled(ctx); err != nil || len(enabledAfterUnknown) != 2 { + t.Fatalf("unknown Console route leaked into enabled routes: %#v, err=%v", enabledAfterUnknown, err) + } + alias, err := models.Create(ctx, model.Route{ + PublicID: "console-image-alias", Provider: account.ProviderConsole, UpstreamModel: publicID, + Capability: model.CapabilityImage, Enabled: true, + }, nil) + if err != nil { + t.Fatal(err) + } + if alias.SupportedAccounts != 2 || alias.TotalAccounts != 2 { + t.Fatalf("manual alias for Console catalog route = %#v", alias) + } + + boundIDs := []uint64{first.ID} + boundRoute := enabled[0] + boundRoute, err = models.Update(ctx, boundRoute, &boundIDs) + if err != nil { + t.Fatal(err) + } + if boundRoute.SupportedAccounts != 1 || boundRoute.TotalAccounts != 1 || len(boundRoute.BoundAccountIDs) != 1 || boundRoute.BoundAccountIDs[0] != first.ID { + t.Fatalf("manually bound Console route = %#v; second=%d", boundRoute, second.ID) + } +} + +func TestModelRouteGroupsKeepCapabilitiesCompleteAcrossStatusFilters(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + models := NewModelRepository(database) + + const publicID = "grouped-console-image" + if err := models.UpsertRoutes(ctx, []model.Route{ + {PublicID: publicID, Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImage, Origin: model.OriginCatalog, Enabled: true}, + {PublicID: publicID, Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImageEdit, Origin: model.OriginCatalog, Enabled: true}, + }); err != nil { + t.Fatal(err) + } + values, total, err := models.ListGroups(ctx, repository.ModelListQuery{Page: repository.PageQuery{Limit: 20}}) + if err != nil || total != 1 || len(values) != 1 || len(values[0].Routes) != 2 { + t.Fatalf("initial groups = %#v, total=%d, err=%v", values, total, err) + } + disabled := false + editRoute := values[0].Routes[0] + if editRoute.Capability != model.CapabilityImageEdit { + editRoute = values[0].Routes[1] + } + editRoute.Enabled = false + if _, err := models.Update(ctx, editRoute, nil); err != nil { + t.Fatal(err) + } + + enabled := true + values, total, err = models.ListGroups(ctx, repository.ModelListQuery{ + Page: repository.PageQuery{Limit: 1}, Filter: repository.ModelListFilter{Enabled: &enabled}, + }) + if err != nil || total != 1 || len(values) != 1 || len(values[0].Routes) != 2 { + t.Fatalf("enabled-filtered groups lost a capability: %#v, total=%d, err=%v", values, total, err) + } + if values[0].Routes[0].Enabled == values[0].Routes[1].Enabled { + t.Fatalf("mixed group status was not preserved: %#v", values[0]) + } + values, total, err = models.ListGroups(ctx, repository.ModelListQuery{ + Page: repository.PageQuery{Limit: 20}, Filter: repository.ModelListFilter{Enabled: &disabled}, + }) + if err != nil || total != 0 || len(values) != 0 { + t.Fatalf("partially enabled group leaked into disabled filter: %#v, total=%d, err=%v", values, total, err) + } + + for _, capability := range []model.Capability{model.CapabilityImage, model.CapabilityImageEdit} { + if _, err := models.Create(ctx, model.Route{ + PublicID: "manual-group-target", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", + Capability: capability, Enabled: true, + }, nil); err != nil { + t.Fatal(err) + } + } + values, total, err = models.ListGroups(ctx, repository.ModelListQuery{Page: repository.PageQuery{Limit: 20}}) + if err != nil || total != 3 || len(values) != 3 { + t.Fatalf("manual targets must remain independent: %#v, total=%d, err=%v", values, total, err) + } + for _, field := range []string{"publicId", "upstreamModel", "status", "provider", "accountSupport", "lastSyncedAt"} { + if _, _, err := models.ListGroups(ctx, repository.ModelListQuery{Page: repository.PageQuery{ + Limit: 20, Sort: repository.SortQuery{Field: field, Direction: repository.SortDescending}, + }}); err != nil { + t.Fatalf("sort grouped models by %s: %v", field, err) + } + } +} + func TestBuildPaidCapabilitiesAreSharedAcrossActiveSuperAccounts(t *testing.T) { ctx := context.Background() database := openTestDatabase(t) diff --git a/backend/internal/infra/persistence/relational/model_repository.go b/backend/internal/infra/persistence/relational/model_repository.go index 3e05a13f..6a63d4f6 100644 --- a/backend/internal/infra/persistence/relational/model_repository.go +++ b/backend/internal/infra/persistence/relational/model_repository.go @@ -5,6 +5,8 @@ import ( "database/sql" "errors" "fmt" + "sort" + "strconv" "strings" "time" @@ -20,6 +22,32 @@ type ModelRepository struct { observer repository.InvalidationObserver } +// Console static support is anchored to the reconciled catalog routes instead +// of the provider name alone. Manual aliases remain supported while an +// equivalent catalog route exists, and stale aliases stop advertising support +// as soon as that catalog entry is removed. +const modelConsoleStaticSupportExpression = `(model_routes.provider = 'grok_console' AND ( + model_routes.origin = 'catalog' + OR EXISTS ( + SELECT 1 FROM model_routes console_catalog_route + WHERE console_catalog_route.provider = model_routes.provider + AND console_catalog_route.upstream_model = model_routes.upstream_model + AND console_catalog_route.capability = model_routes.capability + AND console_catalog_route.origin = 'catalog' + ) +))` + +const modelConsoleStaticSupportAvailabilityExpression = `(route.provider = 'grok_console' AND ( + route.origin = 'catalog' + OR EXISTS ( + SELECT 1 FROM model_routes console_catalog_route + WHERE console_catalog_route.provider = route.provider + AND console_catalog_route.upstream_model = route.upstream_model + AND console_catalog_route.capability = route.capability + AND console_catalog_route.origin = 'catalog' + ) +))` + const availableRoutePredicate = ` EXISTS ( SELECT 1 FROM provider_accounts account @@ -34,10 +62,13 @@ const availableRoutePredicate = ` ) OR ( NOT EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id) - AND EXISTS ( - SELECT 1 FROM account_model_capabilities capability - WHERE capability.account_id = account.id - AND capability.upstream_model = model_routes.upstream_model + AND ( + ` + modelConsoleStaticSupportExpression + ` + OR EXISTS ( + SELECT 1 FROM account_model_capabilities capability + WHERE capability.account_id = account.id + AND capability.upstream_model = model_routes.upstream_model + ) ) ) ) @@ -110,7 +141,8 @@ const modelRouteAccountCapabilityPredicate = `( OR ( NOT EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id) AND ( - EXISTS ( + ` + modelConsoleStaticSupportExpression + ` + OR EXISTS ( SELECT 1 FROM account_model_capabilities capability WHERE capability.account_id = account.id AND capability.upstream_model = model_routes.upstream_model @@ -129,7 +161,8 @@ const modelAvailableRouteAccountCapabilityPredicate = `( OR ( NOT EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id) AND ( - EXISTS ( + ` + modelConsoleStaticSupportExpression + ` + OR EXISTS ( SELECT 1 FROM account_model_capabilities capability WHERE capability.account_id = account.id AND capability.upstream_model = model_routes.upstream_model @@ -173,7 +206,7 @@ func modelTierAvailabilityPredicateWithAvailability(tiers []string, activeOnly b const ( modelProviderPriorityExpression = "CASE model_routes.provider WHEN 'grok_build' THEN 0 WHEN 'grok_web' THEN 1 WHEN 'grok_console' THEN 2 ELSE 3 END" - modelSupportSortExpression = `(SELECT COUNT(*) FROM provider_accounts account WHERE account.provider = model_routes.provider AND account.enabled = TRUE AND account.auth_status = 'active' AND (EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id AND binding.account_id = account.id) OR (NOT EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id) AND (EXISTS (SELECT 1 FROM account_model_capabilities capability WHERE capability.account_id = account.id AND capability.upstream_model = model_routes.upstream_model) OR ` + modelSharedPaidBuildSupportSortExpression + `))))` + modelSupportSortExpression = `(SELECT COUNT(*) FROM provider_accounts account WHERE account.provider = model_routes.provider AND account.enabled = TRUE AND account.auth_status = 'active' AND (EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id AND binding.account_id = account.id) OR (NOT EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id) AND (` + modelConsoleStaticSupportExpression + ` OR EXISTS (SELECT 1 FROM account_model_capabilities capability WHERE capability.account_id = account.id AND capability.upstream_model = model_routes.upstream_model) OR ` + modelSharedPaidBuildSupportSortExpression + `))))` modelSyncedSortExpression = `(SELECT MAX(sync.last_success_at) FROM provider_accounts account JOIN account_model_sync_states sync ON sync.account_id = account.id WHERE account.provider = model_routes.provider AND account.enabled = TRUE AND account.auth_status = 'active')` ) @@ -237,6 +270,188 @@ func (r *ModelRepository) List(ctx context.Context, input repository.ModelListQu return values, total, nil } +type modelRouteGroupRow struct { + Provider string + PublicID string + UpstreamModel string + Origin string + ManualRouteID uint64 + RouteIDs string +} + +// ListGroups paginates logical model targets before loading their member +// routes. This keeps capability groups complete under filters and avoids the +// admin UI fetching and annotating the entire route table. +func (r *ModelRepository) ListGroups(ctx context.Context, input repository.ModelListQuery) ([]model.RouteGroup, int64, error) { + // Route-level metrics must be calculated before grouping. In particular, + // PostgreSQL does not allow a correlated metric to reference model_routes.id + // from inside a grouped SELECT when id is not itself a grouping key. + buildRouteMetricsQuery := func(includeMetrics bool) *gorm.DB { + columns := []string{ + "model_routes.id", + "model_routes.provider", + "model_routes.public_id", + "model_routes.upstream_model", + "model_routes.origin", + "model_routes.enabled", + "model_routes.created_at", + } + if includeMetrics && input.Page.Sort.Field == "accountSupport" { + columns = append(columns, modelSupportSortExpression+" AS support_sort") + } + if includeMetrics && input.Page.Sort.Field == "lastSyncedAt" { + columns = append(columns, modelSyncedSortExpression+" AS last_synced_sort") + } + query := r.db.db.WithContext(ctx).Model(&modelRouteModel{}).Select(strings.Join(columns, ", ")) + if search := strings.TrimSpace(input.Page.Search); search != "" { + pattern := "%" + strings.ToLower(search) + "%" + query = query.Where("LOWER(model_routes.public_id) LIKE ? OR LOWER(model_routes.upstream_model) LIKE ?", pattern, pattern) + } + if input.Filter.Provider != "" { + query = query.Where("model_routes.provider = ?", input.Filter.Provider) + } + return query + } + + manualRouteIDExpression := "CASE WHEN route_metrics.origin = 'manual' THEN route_metrics.id ELSE 0 END" + routeIDsExpression := "GROUP_CONCAT(CAST(route_metrics.id AS TEXT), ',')" + if r.db.dialect == "postgres" { + routeIDsExpression = "STRING_AGG(CAST(route_metrics.id AS TEXT), ',' ORDER BY route_metrics.id)" + } + enabledCountExpression := "SUM(CASE WHEN route_metrics.enabled = TRUE THEN 1 ELSE 0 END)" + groupColumns := "route_metrics.provider, route_metrics.public_id, route_metrics.upstream_model, route_metrics.origin, " + manualRouteIDExpression + supportSortExpression := "0" + if input.Page.Sort.Field == "accountSupport" { + supportSortExpression = "MAX(route_metrics.support_sort)" + } + lastSyncedSortExpression := "NULL" + if input.Page.Sort.Field == "lastSyncedAt" { + lastSyncedSortExpression = "MAX(route_metrics.last_synced_sort)" + } + + buildQuery := func(includeMetrics bool) *gorm.DB { + query := r.db.db.WithContext(ctx).Table("(?) AS route_metrics", buildRouteMetricsQuery(includeMetrics)) + if includeMetrics { + query = query.Select(fmt.Sprintf(` + route_metrics.provider, + route_metrics.public_id, + route_metrics.upstream_model, + route_metrics.origin, + %s AS manual_route_id, + %s AS route_ids, + CASE + WHEN %s = COUNT(*) THEN 0 + WHEN %s > 0 THEN 1 + ELSE 2 + END AS status_sort, + %s AS group_support_sort, + %s AS group_last_synced_sort, + MAX(route_metrics.created_at) AS created_sort + `, manualRouteIDExpression, routeIDsExpression, enabledCountExpression, enabledCountExpression, supportSortExpression, lastSyncedSortExpression)) + } else { + query = query.Select("route_metrics.provider, route_metrics.public_id, route_metrics.upstream_model, route_metrics.origin, " + manualRouteIDExpression + " AS manual_route_id") + } + query = query.Group(groupColumns) + if input.Filter.Enabled != nil { + if *input.Filter.Enabled { + query = query.Having(enabledCountExpression + " > 0") + } else { + query = query.Having(enabledCountExpression + " = 0") + } + } + return query + } + + var total int64 + if err := r.db.db.WithContext(ctx).Table("(?) AS grouped_model_routes", buildQuery(false)).Count(&total).Error; err != nil { + return nil, 0, err + } + + query := buildQuery(true) + spec, direction := stableSortSpec(input.Page.Sort, map[string]sortSpec{ + "publicId": {expression: "LOWER(route_metrics.public_id)"}, + "upstreamModel": {expression: "LOWER(route_metrics.upstream_model)"}, + "status": {expression: "status_sort"}, + "provider": {expression: "route_metrics.provider"}, + "accountSupport": {expression: "group_support_sort", defaultDirection: repository.SortDescending}, + "lastSyncedAt": {expression: "group_last_synced_sort", nullsLast: true, defaultDirection: repository.SortDescending}, + }, sortSpec{expression: "created_sort", defaultDirection: repository.SortDescending}) + if spec.nullsLast { + // PostgreSQL permits a SELECT alias as a plain ORDER BY item, but not + // inside another ORDER BY expression. Repeat the aggregate only for the + // NULL discriminator and use the alias for the value ordering below. + nullSortExpression := spec.expression + if input.Page.Sort.Field == "lastSyncedAt" { + nullSortExpression = lastSyncedSortExpression + } + query = query.Order("CASE WHEN " + nullSortExpression + " IS NULL THEN 1 ELSE 0 END ASC") + } + query = query.Order(spec.expression + " " + direction). + Order("route_metrics.provider ASC"). + Order("LOWER(route_metrics.public_id) ASC"). + Order("LOWER(route_metrics.upstream_model) ASC"). + Order("route_metrics.origin ASC"). + Order("manual_route_id ASC") + var groupRows []modelRouteGroupRow + if err := query.Offset(input.Page.Offset).Limit(input.Page.Limit).Scan(&groupRows).Error; err != nil { + return nil, 0, err + } + + groupIDs := make([][]uint64, 0, len(groupRows)) + allIDs := make([]uint64, 0, len(groupRows)*2) + for _, row := range groupRows { + ids, err := parseModelRouteGroupIDs(row.RouteIDs) + if err != nil { + return nil, 0, err + } + groupIDs = append(groupIDs, ids) + allIDs = append(allIDs, ids...) + } + if len(allIDs) == 0 { + return []model.RouteGroup{}, total, nil + } + var rows []modelRouteModel + if err := r.db.db.WithContext(ctx).Where("id IN ?", allIDs).Find(&rows).Error; err != nil { + return nil, 0, err + } + values := mapModelRows(rows) + if err := r.annotateAvailability(ctx, values); err != nil { + return nil, 0, err + } + byID := make(map[uint64]model.Route, len(values)) + for _, value := range values { + byID[value.ID] = value + } + groups := make([]model.RouteGroup, 0, len(groupIDs)) + for _, ids := range groupIDs { + members := make([]model.Route, 0, len(ids)) + for _, id := range ids { + if value, ok := byID[id]; ok { + members = append(members, value) + } + } + if len(members) == 0 { + continue + } + groups = append(groups, model.RouteGroup{Routes: members}) + } + return groups, total, nil +} + +func parseModelRouteGroupIDs(value string) ([]uint64, error) { + parts := strings.Split(strings.TrimSpace(value), ",") + ids := make([]uint64, 0, len(parts)) + for _, part := range parts { + id, err := strconv.ParseUint(strings.TrimSpace(part), 10, 64) + if err != nil || id == 0 { + return nil, fmt.Errorf("模型能力组包含无效路由 ID %q", part) + } + ids = append(ids, id) + } + sort.Slice(ids, func(left, right int) bool { return ids[left] < ids[right] }) + return ids, nil +} + func (r *ModelRepository) ListEnabled(ctx context.Context) ([]model.Route, error) { var rows []modelRouteModel if err := r.availableRoutes(r.db.db.WithContext(ctx)).Where("enabled = ?", true).Order("public_id ASC, id ASC").Find(&rows).Error; err != nil { @@ -462,10 +677,14 @@ func (r *ModelRepository) UpsertDiscovered(ctx context.Context, provider account if err := tx.Where("provider = ?", provider).Find(&existing).Error; err != nil { return err } - publicIDs := make(map[string]bool, len(existing)) + type managedRouteKey struct { + publicID string + capability model.Capability + } + publicIDs := make(map[managedRouteKey]bool, len(existing)) for _, row := range existing { if row.Origin != string(model.OriginManual) { - publicIDs[row.PublicID] = true + publicIDs[managedRouteKey{publicID: row.PublicID, capability: model.Capability(row.Capability)}] = true } } rows := make([]modelRouteModel, 0, len(upstreamModels)) @@ -475,15 +694,16 @@ func (r *ModelRepository) UpsertDiscovered(ctx context.Context, provider account if !ok { return fmt.Errorf("Provider %s 发现了无效模型 ID %q", provider, localID) } - // Managed routes are idempotent by canonical public_id. Manual targets - // with the same name remain independent pool members. - if publicIDs[publicID] { + // Managed routes are idempotent by canonical public_id and capability. + // Manual targets with the same name remain independent pool members. + key := managedRouteKey{publicID: publicID, capability: capability} + if publicIDs[key] { continue } if err := ensureModelPublicIDNotAlias(tx, publicID, 0); err != nil { return err } - publicIDs[publicID] = true + publicIDs[key] = true rows = append(rows, modelRouteModel{PublicID: publicID, Provider: string(provider), UpstreamModel: upstreamModel, Capability: string(capability), Origin: string(model.OriginDiscovered), Enabled: true}) } if len(rows) > 0 { @@ -518,6 +738,18 @@ func discoveredRouteDefaults(provider account.Provider, upstreamModel string) (s return upstreamModel, model.CapabilityVideo } return upstreamModel, model.CapabilityResponses + case account.ProviderConsole: + switch upstreamModel { + case "grok-imagine-image", "grok-imagine-image-quality": + // The catalog also registers image_edit for the same public model. + // Discovery only needs one existing managed capability to remain + // idempotent and must never synthesize a Responses route. + return upstreamModel, model.CapabilityImage + case "grok-imagine-video": + return upstreamModel, model.CapabilityVideo + default: + return upstreamModel, model.CapabilityResponses + } default: return upstreamModel, model.CapabilityResponses } @@ -541,7 +773,7 @@ func (r *ModelRepository) UpsertRoutes(ctx context.Context, values []model.Route return fmt.Errorf("模型路由目录包含无效条目") } var existing modelRouteModel - err := tx.Where("public_id = ? AND origin <> ?", value.PublicID, model.OriginManual).First(&existing).Error + err := tx.Where("public_id = ? AND capability = ? AND origin <> ?", value.PublicID, value.Capability, model.OriginManual).First(&existing).Error if err == nil { continue } @@ -591,27 +823,34 @@ func (r *ModelRepository) ReplaceProviderRoutes(ctx context.Context, provider ac return err } - byPublicID := make(map[string]modelRouteModel, len(existing)) - byUpstreamNonManual := make(map[string][]modelRouteModel, len(existing)) + type catalogRouteKey struct { + value string + capability model.Capability + } + byPublicID := make(map[catalogRouteKey]modelRouteModel, len(existing)) + byUpstreamNonManual := make(map[catalogRouteKey][]modelRouteModel, len(existing)) for _, row := range existing { if row.Origin == string(model.OriginManual) { continue } - if current, exists := byPublicID[row.PublicID]; !exists || row.ID < current.ID { - byPublicID[row.PublicID] = row + publicKey := catalogRouteKey{value: row.PublicID, capability: model.Capability(row.Capability)} + if current, exists := byPublicID[publicKey]; !exists || row.ID < current.ID { + byPublicID[publicKey] = row } - byUpstreamNonManual[row.UpstreamModel] = append(byUpstreamNonManual[row.UpstreamModel], row) + upstreamKey := catalogRouteKey{value: row.UpstreamModel, capability: model.Capability(row.Capability)} + byUpstreamNonManual[upstreamKey] = append(byUpstreamNonManual[upstreamKey], row) } matched := make(map[int]modelRouteModel, len(values)) usedIDs := make(map[uint64]bool, len(values)) for index, value := range values { - if row, ok := byPublicID[value.PublicID]; ok && !usedIDs[row.ID] { + publicKey := catalogRouteKey{value: value.PublicID, capability: value.Capability} + if row, ok := byPublicID[publicKey]; ok && !usedIDs[row.ID] { matched[index] = row usedIDs[row.ID] = true continue } // 仅回退匹配非手动路由,避免把手动别名路由改写成目录项。 - candidates := byUpstreamNonManual[value.UpstreamModel] + candidates := byUpstreamNonManual[catalogRouteKey{value: value.UpstreamModel, capability: value.Capability}] var chosen modelRouteModel found := false for _, candidate := range candidates { @@ -899,7 +1138,7 @@ func (r *ModelRepository) annotateAvailability(ctx context.Context, values []mod SELECT route.id AS route_id, CASE WHEN COUNT(DISTINCT binding.account_id) > 0 THEN COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND binding.account_id IS NOT NULL THEN account.id END) - ELSE COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND (capability.account_id IS NOT NULL OR `+modelSharedPaidBuildSupportAvailabilityExpression+`) THEN account.id END) + ELSE COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND (`+modelConsoleStaticSupportAvailabilityExpression+` OR capability.account_id IS NOT NULL OR `+modelSharedPaidBuildSupportAvailabilityExpression+`) THEN account.id END) END AS supported_accounts, CASE WHEN COUNT(DISTINCT binding.account_id) > 0 THEN COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND binding.account_id IS NOT NULL AND sync.last_success_at IS NOT NULL THEN account.id END) diff --git a/backend/internal/infra/persistence/relational/models.go b/backend/internal/infra/persistence/relational/models.go index 1d83f350..9479fb3b 100644 --- a/backend/internal/infra/persistence/relational/models.go +++ b/backend/internal/infra/persistence/relational/models.go @@ -302,7 +302,7 @@ type requestAuditModel struct { AccountName string `gorm:"size:160;check:chk_request_audits_account_name,length(account_name) <= 160"` EgressNodeID *uint64 `gorm:"check:chk_request_audits_egress_node_id,egress_node_id IS NULL OR egress_node_id > 0"` EgressNodeName string `gorm:"size:160;not null;default:'';check:chk_request_audits_egress_node_name,length(egress_node_name) <= 160"` - EgressScope string `gorm:"size:32;not null;default:'';check:chk_request_audits_egress_scope,egress_scope IN ('','grok_build','grok_web','grok_console','grok_web_asset')"` + EgressScope string `gorm:"size:32;not null;default:'';check:chk_request_audits_egress_scope,egress_scope IN ('','grok_build','grok_web','grok_console','grok_web_asset','grok_console_asset')"` EgressMode string `gorm:"size:16;not null;default:'';check:chk_request_audits_egress_mode,egress_mode IN ('','direct','proxy')"` StatusCode int `gorm:"not null;check:chk_request_audits_status_code,status_code BETWEEN 100 AND 599"` Streaming bool `gorm:"not null;default:false"` @@ -397,9 +397,9 @@ type mediaJobModel struct { AccountName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_account_name,length(account_name) <= 160"` EgressNodeID *uint64 `gorm:"check:chk_media_jobs_egress_node_id,egress_node_id IS NULL OR egress_node_id > 0"` EgressNodeName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_egress_node_name,length(egress_node_name) <= 160"` - EgressScope string `gorm:"size:32;not null;default:'';check:chk_media_jobs_egress_scope,egress_scope IN ('','grok_web','grok_build')"` + EgressScope string `gorm:"size:32;not null;default:'';check:chk_media_jobs_egress_scope,egress_scope IN ('','grok_web','grok_build','grok_console')"` EgressMode string `gorm:"size:16;not null;default:'';check:chk_media_jobs_egress_mode,egress_mode IN ('','direct','proxy')"` - Provider string `gorm:"size:32;not null;check:chk_media_jobs_provider,provider IN ('grok_web','grok_build')"` + Provider string `gorm:"size:32;not null;check:chk_media_jobs_provider,provider IN ('grok_web','grok_build','grok_console')"` Model string `gorm:"size:255;not null;check:chk_media_jobs_model,length(trim(model)) BETWEEN 1 AND 255"` ModelRouteID uint64 `gorm:"not null;check:chk_media_jobs_model_route_id,model_route_id > 0"` UpstreamModel string `gorm:"size:255;not null;check:chk_media_jobs_upstream_model,length(trim(upstream_model)) BETWEEN 1 AND 255"` @@ -472,7 +472,7 @@ func (runtimeSettingsModel) TableName() string { return "runtime_settings" } type egressSubscriptionSourceModel struct { ID uint64 `gorm:"primaryKey;autoIncrement"` Name string `gorm:"size:160;not null;uniqueIndex;check:chk_egress_subscription_sources_name,length(trim(name)) BETWEEN 1 AND 160"` - Scope string `gorm:"size:32;not null;check:chk_egress_subscription_sources_scope,scope IN ('grok_build','grok_web','grok_console','grok_web_asset')"` + Scope string `gorm:"size:32;not null;check:chk_egress_subscription_sources_scope,scope IN ('grok_build','grok_web','grok_console','grok_web_asset','grok_console_asset')"` Enabled bool `gorm:"not null;default:true"` EncryptedURL string `gorm:"type:text;not null;default:'';check:chk_egress_subscription_sources_url,length(encrypted_url) <= 65536"` RefreshIntervalSeconds int `gorm:"not null;default:900;check:chk_egress_subscription_sources_refresh,refresh_interval_seconds BETWEEN 60 AND 86400"` @@ -490,7 +490,7 @@ func (egressSubscriptionSourceModel) TableName() string { return "egress_subscri type egressNodeModel struct { ID uint64 `gorm:"primaryKey;autoIncrement"` Name string `gorm:"size:160;not null;check:chk_egress_nodes_name,length(trim(name)) BETWEEN 1 AND 160"` - Scope string `gorm:"size:32;not null;check:chk_egress_nodes_specific_scope,scope IN ('grok_build','grok_web','grok_console','grok_web_asset')"` + Scope string `gorm:"size:32;not null;check:chk_egress_nodes_specific_scope,scope IN ('grok_build','grok_web','grok_console','grok_web_asset','grok_console_asset')"` Enabled bool `gorm:"not null;default:true"` ProxyPool bool `gorm:"not null;default:false"` SourceID *uint64 `gorm:"uniqueIndex:uidx_egress_nodes_source_key,priority:1;index:idx_egress_nodes_source;constraint:OnUpdate:CASCADE,OnDelete:SET NULL"` @@ -530,21 +530,23 @@ type egressNodeModel struct { func (egressNodeModel) TableName() string { return "egress_nodes" } type egressOperationsConfigModel struct { - ID uint64 `gorm:"primaryKey;check:chk_egress_operations_config_id,id = 1"` - ProbeProvider string `gorm:"size:16;not null;default:cloudflare;check:chk_egress_operations_config_probe_provider,probe_provider IN ('ipinfo','cloudflare')"` - ProbeIntervalSeconds int `gorm:"not null;default:900;check:chk_egress_operations_config_probe_interval,probe_interval_seconds BETWEEN 60 AND 86400"` - AutoAssignEnabled bool `gorm:"not null;default:false"` - AutoBalanceEnabled bool `gorm:"not null;default:false"` - AssignmentIntervalSeconds int `gorm:"not null;default:300;check:chk_egress_operations_config_assignment_interval,assignment_interval_seconds BETWEEN 60 AND 86400"` - BuildFallbackMode string `gorm:"size:16;not null;default:none"` - BuildFallbackNodeID uint64 `gorm:"not null;default:0"` - WebFallbackMode string `gorm:"size:16;not null;default:none"` - WebFallbackNodeID uint64 `gorm:"not null;default:0"` - ConsoleFallbackMode string `gorm:"size:16;not null;default:none"` - ConsoleFallbackNodeID uint64 `gorm:"not null;default:0"` - WebAssetFallbackMode string `gorm:"size:16;not null;default:none"` - WebAssetFallbackNodeID uint64 `gorm:"not null;default:0"` - UpdatedAt time.Time `gorm:"not null"` + ID uint64 `gorm:"primaryKey;check:chk_egress_operations_config_id,id = 1"` + ProbeProvider string `gorm:"size:16;not null;default:cloudflare;check:chk_egress_operations_config_probe_provider,probe_provider IN ('ipinfo','cloudflare')"` + ProbeIntervalSeconds int `gorm:"not null;default:900;check:chk_egress_operations_config_probe_interval,probe_interval_seconds BETWEEN 60 AND 86400"` + AutoAssignEnabled bool `gorm:"not null;default:false"` + AutoBalanceEnabled bool `gorm:"not null;default:false"` + AssignmentIntervalSeconds int `gorm:"not null;default:300;check:chk_egress_operations_config_assignment_interval,assignment_interval_seconds BETWEEN 60 AND 86400"` + BuildFallbackMode string `gorm:"size:16;not null;default:none"` + BuildFallbackNodeID uint64 `gorm:"not null;default:0"` + WebFallbackMode string `gorm:"size:16;not null;default:none"` + WebFallbackNodeID uint64 `gorm:"not null;default:0"` + ConsoleFallbackMode string `gorm:"size:16;not null;default:none"` + ConsoleFallbackNodeID uint64 `gorm:"not null;default:0"` + WebAssetFallbackMode string `gorm:"size:16;not null;default:none"` + WebAssetFallbackNodeID uint64 `gorm:"not null;default:0"` + ConsoleAssetFallbackMode string `gorm:"size:16;not null;default:none"` + ConsoleAssetFallbackNodeID uint64 `gorm:"not null;default:0"` + UpdatedAt time.Time `gorm:"not null"` } func (egressOperationsConfigModel) TableName() string { return "egress_operations_config" } diff --git a/backend/internal/infra/persistence/relational/postgres_model_group_test.go b/backend/internal/infra/persistence/relational/postgres_model_group_test.go new file mode 100644 index 00000000..347ebd96 --- /dev/null +++ b/backend/internal/infra/persistence/relational/postgres_model_group_test.go @@ -0,0 +1,57 @@ +package relational + +import ( + "context" + "os" + "testing" + "time" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/domain/model" + "github.com/chenyme/grok2api/backend/internal/repository" +) + +func TestPostgresModelGroupsAggregateRouteMetricsBeforeGrouping(t *testing.T) { + dsn := os.Getenv("TEST_POSTGRES_DSN") + if dsn == "" { + t.Skip("TEST_POSTGRES_DSN is not configured") + } + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + database, err := OpenPostgres(ctx, dsn, 5, 2) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = database.Close() }) + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + + accounts := NewAccountRepository(database) + if _, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderConsole, Name: "model-group-postgres", SourceKey: "model-group-postgres", + EncryptedAccessToken: testEncryptedToken, Enabled: true, AuthStatus: account.AuthStatusActive, + }); err != nil { + t.Fatal(err) + } + models := NewModelRepository(database) + const publicID = "postgres-grouped-console-image" + if err := models.UpsertRoutes(ctx, []model.Route{ + {PublicID: publicID, Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImage, Origin: model.OriginCatalog, Enabled: true}, + {PublicID: publicID, Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImageEdit, Origin: model.OriginCatalog, Enabled: true}, + }); err != nil { + t.Fatal(err) + } + + for _, field := range []string{"accountSupport", "lastSyncedAt"} { + values, total, err := models.ListGroups(ctx, repository.ModelListQuery{Page: repository.PageQuery{ + Limit: 20, Search: publicID, Sort: repository.SortQuery{Field: field, Direction: repository.SortDescending}, + }}) + if err != nil { + t.Fatalf("sort PostgreSQL model groups by %s: %v", field, err) + } + if total != 1 || len(values) != 1 || len(values[0].Routes) != 2 { + t.Fatalf("PostgreSQL group sorted by %s = %#v, total=%d", field, values, total) + } + } +} diff --git a/backend/internal/infra/persistence/relational/schema.go b/backend/internal/infra/persistence/relational/schema.go index f8e409d9..dacca43d 100644 --- a/backend/internal/infra/persistence/relational/schema.go +++ b/backend/internal/infra/persistence/relational/schema.go @@ -64,10 +64,12 @@ var schemaIndexes = []string{ "CREATE INDEX IF NOT EXISTS idx_account_credentials_refresh_due ON account_credentials(refresh_due_at, account_id)", "CREATE INDEX IF NOT EXISTS idx_quota_windows_due ON account_quota_windows(remaining, reset_at, account_id)", "CREATE INDEX IF NOT EXISTS idx_model_routes_public_id_lookup ON model_routes(public_id)", - // Catalog/discovered rows remain idempotent across concurrent syncs. Manual - // rows intentionally may share a public ID and form a route-target pool. - "CREATE UNIQUE INDEX IF NOT EXISTS uidx_model_routes_managed_public_id ON model_routes(public_id) WHERE origin IN ('catalog', 'discovered')", + // Catalog/discovered rows remain idempotent per API capability. One public + // image model may intentionally serve both generation and editing, while + // manual rows may still share a public ID and form a route-target pool. + "CREATE UNIQUE INDEX IF NOT EXISTS uidx_model_routes_managed_public_capability ON model_routes(public_id, capability) WHERE origin IN ('catalog', 'discovered')", "CREATE INDEX IF NOT EXISTS idx_model_routes_provider_upstream ON model_routes(provider, upstream_model)", + "CREATE INDEX IF NOT EXISTS idx_model_routes_grouping ON model_routes(provider, public_id, upstream_model, origin, id)", "CREATE INDEX IF NOT EXISTS idx_model_routes_created_id ON model_routes(created_at DESC, id DESC)", "CREATE INDEX IF NOT EXISTS idx_model_routes_enabled ON model_routes(enabled, public_id, id)", "CREATE INDEX IF NOT EXISTS idx_model_route_aliases_route ON model_route_aliases(model_route_id, alias)", @@ -154,6 +156,9 @@ func (d *Database) initializeSchema(ctx context.Context) error { if err := d.ensureConsoleConstraints(ctx); err != nil { return fmt.Errorf("迁移 Console 数据库约束: %w", err) } + if err := d.ensureEgressAssetScopeConstraints(ctx); err != nil { + return fmt.Errorf("迁移资源出口数据库约束: %w", err) + } if err := d.ensureAuditOperationConstraints(ctx); err != nil { return fmt.Errorf("迁移请求审计操作约束: %w", err) } @@ -276,12 +281,13 @@ func (d *Database) dropProviderUpstreamUniqueIndex(ctx context.Context) error { return nil } -// dropModelPublicIDUniqueIndex upgrades the original one-route-per-name model. -// A separately named non-unique lookup index and managed-route partial unique index are -// recreated by schemaIndexes after this migration step. +// dropModelPublicIDUniqueIndex upgrades both historical one-route-per-name +// indexes. The capability-aware managed index is recreated by schemaIndexes. func (d *Database) dropModelPublicIDUniqueIndex(ctx context.Context) error { - if err := d.db.WithContext(ctx).Exec("DROP INDEX IF EXISTS idx_model_routes_public_id").Error; err != nil { - return fmt.Errorf("drop index idx_model_routes_public_id: %w", err) + for _, name := range []string{"idx_model_routes_public_id", "uidx_model_routes_managed_public_id"} { + if err := d.db.WithContext(ctx).Exec("DROP INDEX IF EXISTS " + name).Error; err != nil { + return fmt.Errorf("drop index %s: %w", name, err) + } } return nil } @@ -311,6 +317,16 @@ func (d *Database) ensureConsoleConstraints(ctx context.Context) error { }, "grok_console") } +// ensureEgressAssetScopeConstraints upgrades existing SQLite/PostgreSQL CHECK +// definitions so Console CDN traffic can use an independently managed scope. +func (d *Database) ensureEgressAssetScopeConstraints(ctx context.Context) error { + return d.ensureNamedConstraints(ctx, []consoleConstraint{ + {model: &egressNodeModel{}, table: "egress_nodes", name: "chk_egress_nodes_specific_scope"}, + {model: &egressSubscriptionSourceModel{}, table: "egress_subscription_sources", name: "chk_egress_subscription_sources_scope"}, + {model: &requestAuditModel{}, table: "request_audits", name: "chk_request_audits_egress_scope"}, + }, "grok_console_asset") +} + // ensureAuditOperationConstraints upgrades existing databases so Codex remote // compaction can be recorded separately from ordinary Responses requests. func (d *Database) ensureAuditOperationConstraints(ctx context.Context) error { @@ -319,13 +335,17 @@ func (d *Database) ensureAuditOperationConstraints(ctx context.Context) error { }, "compaction") } -// ensureMediaJobConstraints 将历史仅允许 grok_web 的 media job CHECK 升级到支持 Build 视频。 +// ensureMediaJobConstraints 将历史仅允许 grok_web 的 media job CHECK 升级到支持 Build 与 Console 视频。 // AutoMigrate 不会可靠替换已有 PostgreSQL CHECK,因此启动时幂等检测并重建。 func (d *Database) ensureMediaJobConstraints(ctx context.Context) error { - return d.ensureNamedConstraints(ctx, []consoleConstraint{ + if err := d.ensureNamedConstraints(ctx, []consoleConstraint{ {model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_provider"}, + }, "grok_console"); err != nil { + return err + } + return d.ensureNamedConstraints(ctx, []consoleConstraint{ {model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_egress_scope"}, - }, "grok_build") + }, "grok_console") } // ensureMediaJobInputConstraint 允许异步视频任务持久化 Base64 首图。 diff --git a/backend/internal/infra/persistence/relational/schema_console_upgrade_test.go b/backend/internal/infra/persistence/relational/schema_console_upgrade_test.go index 8987c145..21022ff0 100644 --- a/backend/internal/infra/persistence/relational/schema_console_upgrade_test.go +++ b/backend/internal/infra/persistence/relational/schema_console_upgrade_test.go @@ -20,7 +20,7 @@ func TestInitializeSchemaUpgradesProviderChecksForConsole(t *testing.T) { defer database.Close() legacy := []any{ &legacyProviderAccountModel{}, &legacyModelRouteModel{}, &legacyRequestAuditModel{}, - &legacyResponseOwnershipModel{}, &legacyEgressNodeModel{}, + &legacyResponseOwnershipModel{}, &legacyEgressSubscriptionSourceModel{}, &legacyEgressNodeModel{}, } if err := database.db.WithContext(ctx).AutoMigrate(legacy...); err != nil { t.Fatal(err) @@ -53,7 +53,7 @@ func TestInitializeSchemaUpgradesProviderChecksForConsole(t *testing.T) { if err != nil || len(windows[created.ID]) != 1 || windows[created.ID][0].Remaining != 7 { t.Fatalf("existing quota windows were not preserved: %#v, err=%v", windows, err) } - for _, table := range []string{"provider_accounts", "model_routes", "request_audits", "response_ownership", "egress_nodes"} { + for _, table := range []string{"provider_accounts", "model_routes", "request_audits", "response_ownership", "egress_nodes", "egress_subscription_sources"} { var sql string if err := database.db.WithContext(ctx).Raw("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", table).Scan(&sql).Error; err != nil { t.Fatal(err) @@ -61,13 +61,16 @@ func TestInitializeSchemaUpgradesProviderChecksForConsole(t *testing.T) { if !strings.Contains(sql, "grok_console") { t.Fatalf("table %s was not upgraded: %s", table, sql) } + if (table == "request_audits" || table == "egress_nodes" || table == "egress_subscription_sources") && !strings.Contains(sql, "grok_console_asset") { + t.Fatalf("table %s was not upgraded for Console assets: %s", table, sql) + } if table == "request_audits" && !strings.Contains(sql, "compaction") { t.Fatalf("table %s operation constraint was not upgraded: %s", table, sql) } } assertSQLiteUniqueIndexes(t, database, "provider_accounts", "idx_provider_accounts_identity_key") - assertSQLiteUniqueIndexes(t, database, "model_routes", "uidx_model_routes_managed_public_id") - assertSQLiteIndexes(t, database, "model_routes", "idx_model_routes_public_id_lookup", "idx_model_routes_provider_upstream") + assertSQLiteUniqueIndexes(t, database, "model_routes", "uidx_model_routes_managed_public_capability") + assertSQLiteIndexes(t, database, "model_routes", "idx_model_routes_public_id_lookup", "idx_model_routes_provider_upstream", "idx_model_routes_grouping") assertSQLiteMissingIndexes(t, database, "model_routes", "idx_model_routes_public_id") assertSQLiteMissingIndexes(t, database, "model_routes", "uidx_provider_upstream") assertTableColumns(t, database, "request_audits", []string{"first_token_ms"}, nil) @@ -118,7 +121,7 @@ func TestInitializeSchemaUpgradesPublicIDUniqueIndexForManualTargetPools(t *test if err := database.InitializeSchema(ctx); err != nil { t.Fatal(err) } - for _, index := range []string{"uidx_model_routes_managed_public_id", "idx_model_routes_public_id_lookup"} { + for _, index := range []string{"uidx_model_routes_managed_public_capability", "idx_model_routes_public_id_lookup"} { if err := database.db.Exec("DROP INDEX IF EXISTS " + index).Error; err != nil { t.Fatal(err) } @@ -144,7 +147,49 @@ func TestInitializeSchemaUpgradesPublicIDUniqueIndexForManualTargetPools(t *test } assertSQLiteMissingIndexes(t, database, "model_routes", "idx_model_routes_public_id") assertSQLiteIndexes(t, database, "model_routes", "idx_model_routes_public_id_lookup") - assertSQLiteUniqueIndexes(t, database, "model_routes", "uidx_model_routes_managed_public_id") + assertSQLiteUniqueIndexes(t, database, "model_routes", "uidx_model_routes_managed_public_capability") + assertSQLiteMissingIndexes(t, database, "model_routes", "uidx_model_routes_managed_public_id") +} + +func TestManagedRoutesAllowOnePublicIDPerCapability(t *testing.T) { + ctx := context.Background() + database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "model-capability-pool.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repo := NewModelRepository(database) + routes := []modeldomain.Route{ + {PublicID: "grok-imagine-image-quality", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image-quality", Capability: modeldomain.CapabilityImage, Enabled: true}, + {PublicID: "grok-imagine-image-quality", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image-quality", Capability: modeldomain.CapabilityImageEdit, Enabled: true}, + } + if err := repo.ReplaceProviderRoutes(ctx, account.ProviderConsole, routes); err != nil { + t.Fatal(err) + } + if err := repo.UpsertDiscovered(ctx, account.ProviderConsole, []string{"grok-imagine-image-quality"}); err != nil { + t.Fatal(err) + } + var rows []modelRouteModel + if err := database.db.Where("public_id = ?", "Console/grok-imagine-image-quality").Order("capability ASC").Find(&rows).Error; err != nil { + t.Fatal(err) + } + if len(rows) != 2 || rows[0].Capability == rows[1].Capability { + t.Fatalf("managed capability routes = %#v", rows) + } + firstIDs := []uint64{rows[0].ID, rows[1].ID} + if err := repo.ReplaceProviderRoutes(ctx, account.ProviderConsole, routes); err != nil { + t.Fatal(err) + } + rows = nil + if err := database.db.Where("public_id = ?", "Console/grok-imagine-image-quality").Order("capability ASC").Find(&rows).Error; err != nil { + t.Fatal(err) + } + if len(rows) != 2 || rows[0].ID != firstIDs[0] || rows[1].ID != firstIDs[1] { + t.Fatalf("managed capability route IDs changed: before=%v after=%#v", firstIDs, rows) + } } func assertSQLiteUniqueIndexes(t *testing.T, database *Database, table string, expected ...string) { @@ -224,9 +269,10 @@ type legacyModelRouteModel struct { func (legacyModelRouteModel) TableName() string { return "model_routes" } type legacyRequestAuditModel struct { - ID uint64 `gorm:"primaryKey"` - Provider string `gorm:"size:32;not null;check:chk_request_audits_provider,provider IN ('grok_build','grok_web')"` - Operation string `gorm:"size:32;not null;default:'responses';check:chk_request_audits_operation,operation IN ('responses','chat','messages','image','image_edit','video')"` + ID uint64 `gorm:"primaryKey"` + Provider string `gorm:"size:32;not null;check:chk_request_audits_provider,provider IN ('grok_build','grok_web')"` + Operation string `gorm:"size:32;not null;default:'responses';check:chk_request_audits_operation,operation IN ('responses','chat','messages','image','image_edit','video')"` + EgressScope string `gorm:"size:32;not null;default:'';check:chk_request_audits_egress_scope,egress_scope IN ('','grok_build','grok_web','grok_web_asset')"` } func (legacyRequestAuditModel) TableName() string { return "request_audits" } @@ -238,6 +284,15 @@ type legacyResponseOwnershipModel struct { func (legacyResponseOwnershipModel) TableName() string { return "response_ownership" } +type legacyEgressSubscriptionSourceModel struct { + ID uint64 `gorm:"primaryKey"` + Scope string `gorm:"size:32;not null;check:chk_egress_subscription_sources_scope,scope IN ('grok_build','grok_web','grok_web_asset')"` +} + +func (legacyEgressSubscriptionSourceModel) TableName() string { + return "egress_subscription_sources" +} + type legacyEgressNodeModel struct { ID uint64 `gorm:"primaryKey"` Scope string `gorm:"size:32;not null;check:chk_egress_nodes_specific_scope,scope IN ('all','grok_build','grok_web','grok_web_asset')"` diff --git a/backend/internal/infra/persistence/relational/schema_media_job_upgrade_test.go b/backend/internal/infra/persistence/relational/schema_media_job_upgrade_test.go index dd281e7e..9609dd4e 100644 --- a/backend/internal/infra/persistence/relational/schema_media_job_upgrade_test.go +++ b/backend/internal/infra/persistence/relational/schema_media_job_upgrade_test.go @@ -15,7 +15,7 @@ import ( mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" ) -func TestMediaJobModelTagsAllowBuildVideoProviderAndScope(t *testing.T) { +func TestMediaJobModelTagsAllowAllVideoProvidersAndPrimaryScopes(t *testing.T) { modelType := reflect.TypeOf(mediaJobModel{}) providerField, ok := modelType.FieldByName("Provider") if !ok { @@ -25,7 +25,7 @@ func TestMediaJobModelTagsAllowBuildVideoProviderAndScope(t *testing.T) { if !strings.Contains(providerTag, "chk_media_jobs_provider") || !strings.Contains(providerTag, "grok_web") || !strings.Contains(providerTag, "grok_build") || - strings.Contains(providerTag, "grok_console") { + !strings.Contains(providerTag, "grok_console") { t.Fatalf("provider tag = %q", providerTag) } scopeField, ok := modelType.FieldByName("EgressScope") @@ -37,7 +37,8 @@ func TestMediaJobModelTagsAllowBuildVideoProviderAndScope(t *testing.T) { !strings.Contains(scopeTag, "''") || !strings.Contains(scopeTag, "grok_web") || !strings.Contains(scopeTag, "grok_build") || - strings.Contains(scopeTag, "grok_console") { + !strings.Contains(scopeTag, "grok_console") || + strings.Contains(scopeTag, "grok_console_asset") { t.Fatalf("egress_scope tag = %q", scopeTag) } inputField, ok := modelType.FieldByName("InputJSON") @@ -212,7 +213,7 @@ func TestInitializeSchemaUpgradesMediaJobChecksForBuild(t *testing.T) { } assertMediaJobSQLContainsBuild(t, database) - // 升级后 Build job 与 grok_build egress scope 均可写入。 + // 升级后 Build/Console job 与各自主请求 egress scope 均可写入。 legacyJob.EgressScope = "grok_build" if err := jobs.CreateMediaJob(ctx, legacyJob); err != nil { t.Fatalf("upgraded schema rejected build media job: %v", err) @@ -229,21 +230,31 @@ func TestInitializeSchemaUpgradesMediaJobChecksForBuild(t *testing.T) { if err := jobs.CreateMediaJob(ctx, webJob); err != nil { t.Fatalf("web media job regression: %v", err) } + consoleJob := webJob + consoleJob.ID = "video_console_ok" + consoleJob.RequestID = "request-console-ok" + consoleJob.Provider = "grok_console" + consoleJob.Model = "grok-imagine-video" + consoleJob.ModelRouteID = 3 + consoleJob.EgressScope = "grok_console" + if err := jobs.CreateMediaJob(ctx, consoleJob); err != nil { + t.Fatalf("console media job rejected: %v", err) + } // 非法 provider / scope 仍应被拒绝。 invalidProvider := legacyJob - invalidProvider.ID = "video_console_blocked" - invalidProvider.RequestID = "request-console-blocked" - invalidProvider.Provider = "grok_console" + invalidProvider.ID = "video_provider_blocked" + invalidProvider.RequestID = "request-provider-blocked" + invalidProvider.Provider = "invalid_provider" if err := jobs.CreateMediaJob(ctx, invalidProvider); err == nil { - t.Fatal("console provider was accepted for media jobs") + t.Fatal("invalid provider was accepted for media jobs") } invalidScope := legacyJob invalidScope.ID = "video_scope_blocked" invalidScope.RequestID = "request-scope-blocked" - invalidScope.EgressScope = "grok_console" + invalidScope.EgressScope = "grok_console_asset" if err := jobs.CreateMediaJob(ctx, invalidScope); err == nil { - t.Fatal("console egress scope was accepted for media jobs") + t.Fatal("resource-only egress scope was accepted as a primary media job scope") } // 重复迁移幂等,且已有 Build 任务仍在。 @@ -338,8 +349,8 @@ func assertMediaJobSQLContainsBuild(t *testing.T, database *Database) { if !strings.Contains(sql, "grok_build") { t.Fatalf("media_jobs was not upgraded with grok_build: %s", sql) } - if strings.Contains(sql, "grok_console") { - t.Fatalf("media_jobs unexpectedly allows console: %s", sql) + if !strings.Contains(sql, "grok_console") || strings.Contains(sql, "grok_console_asset") { + t.Fatalf("media_jobs primary scopes are incomplete: %s", sql) } if !strings.Contains(strings.ToUpper(sql), "ON DELETE SET NULL") { t.Fatalf("media_jobs account history is not detached on account delete: %s", sql) diff --git a/backend/internal/infra/provider/console/adapter.go b/backend/internal/infra/provider/console/adapter.go index 92d6fdfb..d491f020 100644 --- a/backend/internal/infra/provider/console/adapter.go +++ b/backend/internal/infra/provider/console/adapter.go @@ -14,6 +14,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/account" egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" @@ -31,10 +32,12 @@ type Adapter struct { cfg Config egress *infraegress.Manager cipher *security.Cipher + assets provider.ImageAssetStore + dpop *dpopSessionManager } -func NewAdapter(cfg Config, egress *infraegress.Manager, cipher *security.Cipher) *Adapter { - return &Adapter{cfg: cfg, egress: egress, cipher: cipher} +func NewAdapter(cfg Config, egress *infraegress.Manager, cipher *security.Cipher, assets provider.ImageAssetStore) *Adapter { + return &Adapter{cfg: cfg, egress: egress, cipher: cipher, assets: assets, dpop: newDPoPSessionManager()} } func (a *Adapter) Provider() account.Provider { return account.ProviderConsole } @@ -57,6 +60,12 @@ func (a *Adapter) QuotaMode(upstreamModel string) string { if _, ok := Resolve(upstreamModel); ok { return QuotaMode } + if ResolveMedia(upstreamModel, modeldomain.CapabilityImage) || ResolveMedia(upstreamModel, modeldomain.CapabilityImageEdit) { + return QuotaModeImage + } + if ResolveMedia(upstreamModel, modeldomain.CapabilityVideo) { + return QuotaModeVideo + } return "" } @@ -65,11 +74,7 @@ func (a *Adapter) TierOrder(string) []account.WebTier { return nil } func (a *Adapter) PricingModel(upstreamModel string) string { return upstreamModel } func (a *Adapter) ListModels(context.Context, account.Credential) ([]string, error) { - values := make([]string, 0, len(catalog)) - for _, spec := range catalog { - values = append(values, spec.UpstreamModel) - } - return values, nil + return allModels(), nil } func (a *Adapter) ParseImportedCredentials(data []byte) ([]provider.CredentialSeed, error) { @@ -80,26 +85,6 @@ func (a *Adapter) MarshalCredentials(values []provider.CredentialSeed) ([]byte, return marshalCredentials(values) } -func (a *Adapter) SyncQuota(_ context.Context, credential account.Credential) (provider.QuotaSnapshot, error) { - now := time.Now().UTC() - resetAt := now.Add(DefaultQuotaWindow * time.Second) - return provider.QuotaSnapshot{SyncedAt: now, Windows: []account.QuotaWindow{{ - AccountID: credential.ID, Mode: QuotaMode, Remaining: DefaultQuotaLimit, Total: DefaultQuotaLimit, - WindowSeconds: DefaultQuotaWindow, ResetAt: &resetAt, SyncedAt: &now, Source: account.QuotaSourceDefault, UpdatedAt: now, - }}}, nil -} - -func (a *Adapter) SyncQuotaMode(ctx context.Context, credential account.Credential, mode string) (account.QuotaWindow, error) { - if mode != QuotaMode { - return account.QuotaWindow{}, fmt.Errorf("不支持的 Console 额度模式 %q", mode) - } - snapshot, err := a.SyncQuota(ctx, credential) - if err != nil { - return account.QuotaWindow{}, err - } - return snapshot.Windows[0], nil -} - func (a *Adapter) ForwardResponse(ctx context.Context, request provider.ResponseResourceRequest) (*provider.Response, error) { if request.Method != http.MethodPost || request.Path != "/responses" { return jsonProviderResponse(http.StatusBadRequest, map[string]any{"error": map[string]any{"type": "invalid_request_error", "message": "Grok Console 仅支持 POST /responses"}}), nil @@ -134,17 +119,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response cancel() return nil, err } - upstream, err := http.NewRequestWithContext(requestCtx, http.MethodPost, consoleEndpoint(cfg.BaseURL), bytes.NewReader(body)) - if err != nil { - lease.Release() - cancel() - return nil, err - } - applyHeaders(upstream, token, lease) - if request.Streaming { - upstream.Header.Set("Accept", "text/event-stream") - } - response, err := lease.DoDeferredForbidden(upstream) + response, err := a.doDPoPRequest(requestCtx, request.Credential, token, lease, http.MethodPost, consoleEndpoint(cfg.BaseURL), body, "*/*") if err != nil { a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, 0, err) lease.Release() @@ -298,11 +273,7 @@ func conversationErrorType(status int, operation string) string { } func consoleEndpoint(baseURL string) string { - baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/") - if strings.HasSuffix(baseURL, "/v1") { - return baseURL + "/responses" - } - return baseURL + "/v1/responses" + return consoleV1Endpoint(baseURL, "/responses") } func normalizeRateLimitResponse(response *http.Response) (bool, *provider.RateLimitMetadata, error) { diff --git a/backend/internal/infra/provider/console/catalog.go b/backend/internal/infra/provider/console/catalog.go index ff7e67d2..848e6540 100644 --- a/backend/internal/infra/provider/console/catalog.go +++ b/backend/internal/infra/provider/console/catalog.go @@ -7,9 +7,9 @@ import ( ) const ( - QuotaMode = "console" - DefaultQuotaLimit = 20 - DefaultQuotaWindow = 3600 + QuotaMode = "console" + QuotaModeImage = "console_image" + QuotaModeVideo = "console_video" ) type ModelSpec struct { @@ -24,22 +24,32 @@ type ModelSpec struct { var catalog = []ModelSpec{ {PublicID: "grok-4.3", UpstreamModel: "grok-4.3", SupportsReasoning: true, SupportsReasoningEffort: true, DefaultReasoningEffort: "medium", MaxOutputTokens: 1_000_000, SearchTools: true}, - {PublicID: "grok-4.20-0309", UpstreamModel: "grok-4.20-0309", MaxOutputTokens: 1_000_000, SearchTools: true}, {PublicID: "grok-4.20-0309-reasoning", UpstreamModel: "grok-4.20-0309-reasoning", SupportsReasoning: true, MaxOutputTokens: 1_000_000, SearchTools: true}, {PublicID: "grok-4.20-0309-non-reasoning", UpstreamModel: "grok-4.20-0309-non-reasoning", MaxOutputTokens: 1_000_000, SearchTools: true}, - {PublicID: "grok-4.20-multi-agent-0309", UpstreamModel: "grok-4.20-multi-agent-0309", SupportsReasoning: true, SupportsReasoningEffort: true, DefaultReasoningEffort: "medium", MaxOutputTokens: 2_000_000, SearchTools: true}, + {PublicID: "grok-4.20-multi-agent-0309", UpstreamModel: "grok-4.20-multi-agent-0309", SupportsReasoning: true, SupportsReasoningEffort: true, MaxOutputTokens: 1_000_000, SearchTools: true}, + {PublicID: "grok-4.5", UpstreamModel: "grok-4.5", SupportsReasoning: true, SupportsReasoningEffort: true, DefaultReasoningEffort: "medium", MaxOutputTokens: 1_000_000, SearchTools: true}, {PublicID: "grok-build-0.1", UpstreamModel: "grok-build-0.1", MaxOutputTokens: 256_000, SearchTools: true}, } +var mediaCatalog = []struct { + PublicID string + UpstreamModel string + Capabilities []modeldomain.Capability +}{ + {PublicID: "grok-imagine-image-quality", UpstreamModel: "grok-imagine-image-quality", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}}, + {PublicID: "grok-imagine-image", UpstreamModel: "grok-imagine-image", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}}, + {PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", Capabilities: []modeldomain.Capability{modeldomain.CapabilityVideo}}, +} + // Effort-suffixed aliases only include levels each Provider/model combination // actually supports (see domain/model.SupportedReasoningEffortsForProvider). // No blanket none/low/medium/high/xhigh/max template. var aliases = []provider.ModelAlias{ consoleAlias("grok-4.3-console", "grok-4.3", "grok-4.3", ""), - consoleAlias("grok-4.20-0309-console", "grok-4.20-0309", "grok-4.20-0309", ""), consoleAlias("grok-4.20-0309-reasoning-console", "grok-4.20-0309-reasoning", "grok-4.20-0309-reasoning", ""), consoleAlias("grok-4.20-0309-non-reasoning-console", "grok-4.20-0309-non-reasoning", "grok-4.20-0309-non-reasoning", ""), consoleAlias("grok-4.20-multi-agent-console", "grok-4.20-multi-agent-0309", "grok-4.20-multi-agent-0309", ""), + consoleAlias("grok-4.5-console", "grok-4.5", "grok-4.5", ""), consoleAlias("grok-build-console", "grok-build-0.1", "grok-build-0.1", ""), consoleAlias("grok-4.3-low", "grok-4.3", "grok-4.3", "low"), consoleAlias("grok-4.3-medium", "grok-4.3", "grok-4.3", "medium"), @@ -61,7 +71,11 @@ func consoleAlias(alias, publicModel, upstreamModel, effort string) provider.Mod func Catalog() []ModelSpec { return append([]ModelSpec(nil), catalog...) } func Routes() []modeldomain.Route { - values := make([]modeldomain.Route, 0, len(catalog)) + capacity := len(catalog) + for _, spec := range mediaCatalog { + capacity += len(spec.Capabilities) + } + values := make([]modeldomain.Route, 0, capacity) for _, spec := range catalog { publicID, _ := modeldomain.NormalizePublicID(account.ProviderConsole, spec.PublicID) values = append(values, modeldomain.Route{ @@ -69,6 +83,15 @@ func Routes() []modeldomain.Route { Capability: modeldomain.CapabilityResponses, Enabled: true, }) } + for _, spec := range mediaCatalog { + publicID, _ := modeldomain.NormalizePublicID(account.ProviderConsole, spec.PublicID) + for _, capability := range spec.Capabilities { + values = append(values, modeldomain.Route{ + PublicID: publicID, Provider: account.ProviderConsole, UpstreamModel: spec.UpstreamModel, + Capability: capability, Enabled: true, + }) + } + } return values } @@ -81,4 +104,29 @@ func Resolve(upstreamModel string) (ModelSpec, bool) { return ModelSpec{}, false } +func ResolveMedia(upstreamModel string, capability modeldomain.Capability) bool { + for _, spec := range mediaCatalog { + if spec.UpstreamModel != upstreamModel { + continue + } + for _, supported := range spec.Capabilities { + if supported == capability { + return true + } + } + } + return false +} + +func allModels() []string { + values := make([]string, 0, len(catalog)+len(mediaCatalog)) + for _, spec := range catalog { + values = append(values, spec.UpstreamModel) + } + for _, spec := range mediaCatalog { + values = append(values, spec.UpstreamModel) + } + return values +} + func Aliases() []provider.ModelAlias { return append([]provider.ModelAlias(nil), aliases...) } diff --git a/backend/internal/infra/provider/console/console_test.go b/backend/internal/infra/provider/console/console_test.go index 6aed012c..91089b23 100644 --- a/backend/internal/infra/provider/console/console_test.go +++ b/backend/internal/infra/provider/console/console_test.go @@ -3,45 +3,63 @@ package console import ( "bytes" "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/sha256" "encoding/base64" "encoding/json" "errors" + "fmt" "io" + "math/big" "net/http" "net/http/httptest" + "strconv" "strings" "sync" + "sync/atomic" "testing" "time" "github.com/chenyme/grok2api/backend/internal/domain/account" egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress" + mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" "github.com/chenyme/grok2api/backend/internal/infra/security" "github.com/chenyme/grok2api/backend/internal/repository" + "github.com/golang-jwt/jwt/v5" ) func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) { - expected := map[string]string{ - "Console/grok-4.3": "grok-4.3", - "Console/grok-4.20-0309": "grok-4.20-0309", - "Console/grok-4.20-0309-reasoning": "grok-4.20-0309-reasoning", - "Console/grok-4.20-0309-non-reasoning": "grok-4.20-0309-non-reasoning", - "Console/grok-4.20-multi-agent-0309": "grok-4.20-multi-agent-0309", - "Console/grok-build-0.1": "grok-build-0.1", + type routeKey struct { + publicID string + capability modeldomain.Capability + } + expected := map[routeKey]string{ + {publicID: "Console/grok-4.3", capability: modeldomain.CapabilityResponses}: "grok-4.3", + {publicID: "Console/grok-4.20-0309-reasoning", capability: modeldomain.CapabilityResponses}: "grok-4.20-0309-reasoning", + {publicID: "Console/grok-4.20-0309-non-reasoning", capability: modeldomain.CapabilityResponses}: "grok-4.20-0309-non-reasoning", + {publicID: "Console/grok-4.20-multi-agent-0309", capability: modeldomain.CapabilityResponses}: "grok-4.20-multi-agent-0309", + {publicID: "Console/grok-4.5", capability: modeldomain.CapabilityResponses}: "grok-4.5", + {publicID: "Console/grok-build-0.1", capability: modeldomain.CapabilityResponses}: "grok-build-0.1", + {publicID: "Console/grok-imagine-image-quality", capability: modeldomain.CapabilityImage}: "grok-imagine-image-quality", + {publicID: "Console/grok-imagine-image-quality", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image-quality", + {publicID: "Console/grok-imagine-image", capability: modeldomain.CapabilityImage}: "grok-imagine-image", + {publicID: "Console/grok-imagine-image", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image", + {publicID: "Console/grok-imagine-video", capability: modeldomain.CapabilityVideo}: "grok-imagine-video", } routes := Routes() if len(routes) != len(expected) { t.Fatalf("routes = %d, want %d", len(routes), len(expected)) } for _, route := range routes { - if route.Provider != account.ProviderConsole || route.Capability != modeldomain.CapabilityResponses || !route.Enabled { + if route.Provider != account.ProviderConsole || !route.Enabled { t.Fatalf("invalid route: %#v", route) } - if expected[route.PublicID] != route.UpstreamModel { + if expected[routeKey{publicID: route.PublicID, capability: route.Capability}] != route.UpstreamModel { t.Fatalf("route %q = %q", route.PublicID, route.UpstreamModel) } } @@ -49,14 +67,15 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) { if len(aliases) != 13 { t.Fatalf("aliases = %d, want 13", len(aliases)) } - registry := provider.NewRegistry(NewAdapter(Config{}, nil, nil)) + registry := provider.NewRegistry(NewAdapter(Config{}, nil, nil, nil)) if registry.SupportsStoredResponses(account.ProviderConsole) { t.Fatal("console must not advertise stored Responses support") } for _, name := range []string{ - "grok-4.3-console", "grok-4.20-0309-console", "grok-4.20-0309-reasoning-console", + "grok-4.3-console", "grok-4.20-0309-reasoning-console", "grok-4.20-0309-non-reasoning-console", "grok-4.20-multi-agent-console", "grok-build-console", "grok-4.3-low", "grok-4.3-medium", "grok-4.3-high", + "grok-4.5-console", "grok-4.20-multi-agent-low", "grok-4.20-multi-agent-medium", "grok-4.20-multi-agent-high", "grok-4.20-multi-agent-xhigh", } { alias, ok := registry.ResolveModelAlias(name) @@ -67,6 +86,15 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) { t.Fatalf("alias %q targets non-canonical model %q", name, alias.PublicModel) } } + adapter := NewAdapter(Config{}, nil, nil, nil) + for model, want := range map[string]string{ + "grok-4.5": QuotaMode, "grok-imagine-image-quality": QuotaModeImage, + "grok-imagine-image": QuotaModeImage, "grok-imagine-video": QuotaModeVideo, + } { + if got := adapter.QuotaMode(model); got != want { + t.Fatalf("QuotaMode(%q) = %q, want %q", model, got, want) + } + } } func TestSyncAccountIdentityUsesWebSessionWithConsoleCredential(t *testing.T) { @@ -92,7 +120,7 @@ func TestSyncAccountIdentityUsesWebSessionWithConsoleCredential(t *testing.T) { } token, _ := cipher.Encrypt("test-sso") cookies, _ := cipher.Encrypt("cf_clearance=clear") - adapter := NewAdapter(Config{SessionBaseURL: server.URL}, infraegress.NewManager(consoleEgressRepositoryStub{}, cipher), cipher) + adapter := NewAdapter(Config{SessionBaseURL: server.URL}, infraegress.NewManager(consoleEgressRepositoryStub{}, cipher), cipher, nil) identity, err := adapter.SyncAccountIdentity(context.Background(), account.Credential{ ID: 1, Provider: account.ProviderConsole, AuthType: account.AuthTypeSSO, EncryptedAccessToken: token, EncryptedCloudflareCookie: cookies, @@ -155,10 +183,45 @@ func TestNormalizeRequestAppliesConsoleContract(t *testing.T) { } } -func TestNormalizeRequestAppliesConsoleCompatibilityBoundary(t *testing.T) { - spec, ok := Resolve("grok-4.20-0309") +func TestNormalizeRequestMatchesCapturedMultiAgentDefaults(t *testing.T) { + spec, ok := Resolve("grok-4.20-multi-agent-0309") if !ok { - t.Fatal("grok-4.20-0309 missing") + t.Fatal("grok-4.20-multi-agent-0309 missing") + } + body, err := normalizeRequest([]byte(`{ + "model":"grok-4.20-multi-agent-0309", + "input":[{"role":"system","content":"hello"},{"role":"user","content":[{"type":"input_text","text":"news"}]}], + "stream":true + }`), spec) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + if payload["max_output_tokens"] != float64(1_000_000) || payload["reasoning"] != nil || payload["store"] != false { + t.Fatalf("multi-agent defaults = %#v", payload) + } + include, _ := payload["include"].([]any) + tools, _ := payload["tools"].([]any) + if len(include) != 1 || include[0] != "reasoning.encrypted_content" || len(tools) != 2 || toolIdentity(tools[0]) != "web_search" || toolIdentity(tools[1]) != "x_search" { + t.Fatalf("multi-agent compatibility = %#v", payload) + } + explicit, err := normalizeRequest([]byte(`{"model":"grok-4.20-multi-agent-0309","input":"hello","reasoning":{"effort":"xhigh"}}`), spec) + if err != nil { + t.Fatal(err) + } + payload = nil + if json.Unmarshal(explicit, &payload) != nil || payload["reasoning"].(map[string]any)["effort"] != "xhigh" { + t.Fatalf("explicit multi-agent effort = %#v", payload) + } +} + +func TestNormalizeRequestAppliesConsoleCompatibilityBoundary(t *testing.T) { + spec, ok := Resolve("grok-4.20-0309-non-reasoning") + if !ok { + t.Fatal("grok-4.20-0309-non-reasoning missing") } body, err := normalizeRequest([]byte(`{ "model":"public", @@ -449,7 +512,10 @@ func TestParseConsoleRateLimitMetadataExtractsTeamAndModel(t *testing.T) { } func TestAdapterAttachesConsoleRateLimitMetadata(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } writer.Header().Set("Content-Type", "text/plain") writer.WriteHeader(http.StatusTooManyRequests) _, _ = io.WriteString(writer, "Too many requests for team 00000000-0000-0000-0000-000000000013 and model grok-4.20-multi-agent-0309. Requests per Second (actual/limit): 2/2") @@ -486,7 +552,10 @@ func TestAdapterDoesNotPenalizeEgressForBlockedAccount(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } writer.Header().Set("Content-Type", "application/json") writer.WriteHeader(http.StatusForbidden) _, _ = io.WriteString(writer, test.body) @@ -504,7 +573,7 @@ func TestAdapterDoesNotPenalizeEgressForBlockedAccount(t *testing.T) { repository := &recordingConsoleEgressRepository{node: egressdomain.Node{ ID: 1, Name: "console", Scope: egressdomain.ScopeConsole, Enabled: true, Health: 1, }} - adapter := NewAdapter(Config{BaseURL: server.URL, TimeoutSeconds: 5}, infraegress.NewManager(repository, cipher), cipher) + adapter := NewAdapter(Config{BaseURL: server.URL, TimeoutSeconds: 5}, infraegress.NewManager(repository, cipher), cipher, nil) credential := account.Credential{ID: 1, Provider: account.ProviderConsole, AuthType: account.AuthTypeSSO, EncryptedAccessToken: encrypted} response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ Credential: credential, Method: http.MethodPost, Path: "/responses", Model: "grok-4.3", @@ -531,12 +600,16 @@ func TestAdapterDoesNotPenalizeEgressForBlockedAccount(t *testing.T) { func TestAdapterForwardsConsoleHeadersAndNormalizedBody(t *testing.T) { var received map[string]any server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } if request.URL.Path != "/v1/responses" || request.Method != http.MethodPost { t.Errorf("request = %s %s", request.Method, request.URL.Path) } - if request.Header.Get("Authorization") != "Bearer anonymous" || request.Header.Get("x-cluster") != "https://us-east-1.api.x.ai" || request.Header.Get("Accept") != "*/*" || request.Header.Get("Priority") != "u=1, i" { + if !strings.HasPrefix(request.Header.Get("Authorization"), "DPoP ") || request.Header.Get("DPoP") == "" || request.Header.Get("x-cluster") != "https://us-east-1.api.x.ai" || request.Header.Get("Accept") != "*/*" || request.Header.Get("Priority") != "u=1, i" { t.Errorf("headers = %#v", request.Header) } + verifyTestDPoPProof(t, request) if request.Header.Get("User-Agent") != infraegress.DefaultUserAgent { t.Errorf("user-agent = %q", request.Header.Get("User-Agent")) } @@ -592,7 +665,10 @@ func TestApplyChromiumClientHintsSkipsNonChromiumUserAgent(t *testing.T) { } func TestAdapterPreservesConversationRateLimitStatusAndProtocol(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } writer.Header().Set("Content-Type", "text/plain") writer.WriteHeader(http.StatusTooManyRequests) _, _ = io.WriteString(writer, "Rate limit reached. Resets in: 1h 2m 3s") @@ -638,7 +714,557 @@ func TestAdapterPreservesConversationRateLimitStatusAndProtocol(t *testing.T) { } } +func TestSyncQuotaUsesDPoPUsageQuotas(t *testing.T) { + var tokenRequests atomic.Int32 + var usageRequests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.URL.Path == "/v1/dpop/token" { + tokenRequests.Add(1) + serveTestDPoPToken(t, writer, request) + return + } + if request.URL.Path != "/v1/usage" || request.Method != http.MethodGet { + http.NotFound(writer, request) + return + } + usageRequests.Add(1) + verifyTestDPoPProof(t, request) + if request.Header.Get("x-cluster") != "" { + t.Errorf("usage x-cluster = %q", request.Header.Get("x-cluster")) + } + writer.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(writer, `{"quotas":[{"kind":"chat","limit":10,"used":1,"remaining":9,"last_consumed_at":1785895737},{"kind":"image","limit":5,"used":0,"remaining":5},{"kind":"video","limit":2,"used":0,"remaining":2}]}`) + })) + defer server.Close() + adapter, credential := newConsoleTestAdapter(t, server.URL) + for range 2 { + snapshot, err := adapter.SyncQuota(context.Background(), credential) + if err != nil { + t.Fatal(err) + } + if len(snapshot.Windows) != 3 { + t.Fatalf("quota windows = %#v", snapshot.Windows) + } + want := []struct { + mode string + remaining, total, windowSecs int + }{ + {mode: QuotaMode, remaining: 9, total: 10, windowSecs: 24 * 60 * 60}, + {mode: QuotaModeImage, remaining: 5, total: 5}, + {mode: QuotaModeVideo, remaining: 2, total: 2}, + } + for index, expected := range want { + window := snapshot.Windows[index] + if window.Mode != expected.mode || window.Remaining != expected.remaining || window.Total != expected.total || window.Source != account.QuotaSourceUpstream || window.ResetAt != nil || window.WindowSeconds != expected.windowSecs { + t.Fatalf("quota[%d] = %#v", index, window) + } + } + } + if tokenRequests.Load() != 1 || usageRequests.Load() != 2 { + t.Fatalf("requests token=%d usage=%d", tokenRequests.Load(), usageRequests.Load()) + } +} + +func TestSyncQuotaPredictsChatRecoveryAfter24Hours(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.URL.Path == "/v1/dpop/token" { + serveTestDPoPToken(t, writer, request) + return + } + writer.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(writer, `{"quotas":[{"kind":"chat","limit":10,"used":10,"remaining":0},{"kind":"image","limit":5,"used":0,"remaining":5},{"kind":"video","limit":2,"used":0,"remaining":2}]}`) + })) + defer server.Close() + adapter, credential := newConsoleTestAdapter(t, server.URL) + startedAt := time.Now().UTC() + snapshot, err := adapter.SyncQuota(context.Background(), credential) + if err != nil { + t.Fatal(err) + } + chat := snapshot.Windows[0] + if chat.ResetAt == nil || chat.WindowSeconds != 24*60*60 { + t.Fatalf("chat recovery = %#v", chat) + } + want := startedAt.Add(24 * time.Hour) + if chat.ResetAt.Before(want) || chat.ResetAt.After(time.Now().UTC().Add(24*time.Hour)) { + t.Fatalf("predicted recovery = %s, want around %s", chat.ResetAt, want) + } +} + +func TestSyncQuotaModeSelectsConsoleMediaWindow(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.URL.Path == "/v1/dpop/token" { + serveTestDPoPToken(t, writer, request) + return + } + writer.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(writer, `{"quotas":[{"kind":"chat","limit":10,"used":1,"remaining":9},{"kind":"image","limit":5,"used":2,"remaining":3},{"kind":"video","limit":2,"used":0,"remaining":2}]}`) + })) + defer server.Close() + adapter, credential := newConsoleTestAdapter(t, server.URL) + window, err := adapter.SyncQuotaMode(context.Background(), credential, QuotaModeImage) + if err != nil { + t.Fatal(err) + } + if window.Mode != QuotaModeImage || window.Remaining != 3 || window.Total != 5 || window.UsagePercent != 40 { + t.Fatalf("image quota = %#v", window) + } +} + +func TestSyncQuotaRejectsPartialUsageSnapshot(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.URL.Path == "/v1/dpop/token" { + serveTestDPoPToken(t, writer, request) + return + } + writer.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(writer, `{"quotas":[{"kind":"chat","limit":10,"used":1,"remaining":9}]}`) + })) + defer server.Close() + adapter, credential := newConsoleTestAdapter(t, server.URL) + if _, err := adapter.SyncQuota(context.Background(), credential); err == nil || !strings.Contains(err.Error(), "image") { + t.Fatalf("partial usage err = %v", err) + } +} + +func TestAdapterRefreshesDPoPSessionOnceAfterUnauthorized(t *testing.T) { + var tokenRequests atomic.Int32 + var responseRequests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.URL.Path == "/v1/dpop/token" { + tokenRequests.Add(1) + serveTestDPoPToken(t, writer, request) + return + } + currentResponse := responseRequests.Add(1) + verifyTestDPoPProof(t, request) + if currentResponse == 1 { + writer.WriteHeader(http.StatusUnauthorized) + _, _ = io.WriteString(writer, `{"error":"expired dpop token"}`) + return + } + writer.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(writer, `{"id":"resp_refreshed","object":"response","status":"completed","output":[]}`) + })) + defer server.Close() + adapter, credential := newConsoleTestAdapter(t, server.URL) + response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: credential, Method: http.MethodPost, Path: "/responses", Model: "grok-4.3", + Operation: conversation.OperationResponses, NormalizeBody: true, Body: []byte(`{"model":"grok-4.3","input":"hello"}`), + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK || tokenRequests.Load() != 2 || responseRequests.Load() != 2 { + t.Fatalf("status=%d token=%d responses=%d", response.StatusCode, tokenRequests.Load(), responseRequests.Load()) + } +} + +func TestAdapterCoalescesConcurrentDPoPTokenExchange(t *testing.T) { + const workers = 16 + var tokenRequests atomic.Int32 + var responseRequests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.URL.Path == "/v1/dpop/token" { + tokenRequests.Add(1) + time.Sleep(20 * time.Millisecond) + serveTestDPoPToken(t, writer, request) + return + } + responseRequests.Add(1) + verifyTestDPoPProof(t, request) + writer.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(writer, `{"id":"resp_concurrent","object":"response","status":"completed","output":[]}`) + })) + defer server.Close() + adapter, credential := newConsoleTestAdapter(t, server.URL) + start := make(chan struct{}) + errorsChannel := make(chan error, workers) + var group sync.WaitGroup + group.Add(workers) + for range workers { + go func() { + defer group.Done() + <-start + response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: credential, Method: http.MethodPost, Path: "/responses", Model: "grok-4.3", + Operation: conversation.OperationResponses, NormalizeBody: true, Body: []byte(`{"model":"grok-4.3","input":"hello"}`), + }) + if err == nil { + _, err = io.Copy(io.Discard, response.Body) + closeErr := response.Body.Close() + if err == nil { + err = closeErr + } + } + errorsChannel <- err + }() + } + close(start) + group.Wait() + close(errorsChannel) + for err := range errorsChannel { + if err != nil { + t.Fatal(err) + } + } + if tokenRequests.Load() != 1 || responseRequests.Load() != workers { + t.Fatalf("requests token=%d responses=%d", tokenRequests.Load(), responseRequests.Load()) + } +} + +func TestAdapterCoalescesConcurrentDPoPRefreshAfterUnauthorized(t *testing.T) { + const workers = 16 + var tokenRequests atomic.Int32 + var responseRequests atomic.Int32 + var initialRequests atomic.Int32 + var releaseInitial sync.Once + initialReady := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.URL.Path == "/v1/dpop/token" { + tokenRequests.Add(1) + time.Sleep(20 * time.Millisecond) + serveTestDPoPToken(t, writer, request) + return + } + responseRequests.Add(1) + verifyTestDPoPProof(t, request) + if current := initialRequests.Add(1); current <= workers { + if current == workers { + releaseInitial.Do(func() { close(initialReady) }) + } + <-initialReady + writer.WriteHeader(http.StatusUnauthorized) + _, _ = io.WriteString(writer, `{"error":"expired dpop token"}`) + return + } + writer.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(writer, `{"id":"resp_refreshed","object":"response","status":"completed","output":[]}`) + })) + defer server.Close() + adapter, credential := newConsoleTestAdapter(t, server.URL) + start := make(chan struct{}) + errorsChannel := make(chan error, workers) + var group sync.WaitGroup + group.Add(workers) + for range workers { + go func() { + defer group.Done() + <-start + response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: credential, Method: http.MethodPost, Path: "/responses", Model: "grok-4.3", + Operation: conversation.OperationResponses, NormalizeBody: true, Body: []byte(`{"model":"grok-4.3","input":"hello"}`), + }) + if err == nil { + _, err = io.Copy(io.Discard, response.Body) + closeErr := response.Body.Close() + if err == nil { + err = closeErr + } + } + errorsChannel <- err + }() + } + close(start) + group.Wait() + close(errorsChannel) + for err := range errorsChannel { + if err != nil { + t.Fatal(err) + } + } + if tokenRequests.Load() != 2 || responseRequests.Load() != workers*2 { + t.Fatalf("requests token=%d responses=%d", tokenRequests.Load(), responseRequests.Load()) + } +} + +func TestDPoPSessionCacheUsesBoundedLRUEviction(t *testing.T) { + manager := newDPoPSessionManager() + now := time.Date(2026, 8, 5, 8, 0, 0, 0, time.UTC) + manager.now = func() time.Time { return now } + for index := range dpopSessionCacheLimit { + manager.store(strconv.Itoa(index), dpopSession{accessToken: strconv.Itoa(index), expiresAt: now.Add(time.Minute)}) + } + if _, ok := manager.cached("0"); !ok { + t.Fatal("failed to touch oldest cache entry") + } + manager.store("new", dpopSession{accessToken: "new", expiresAt: now.Add(time.Minute)}) + if len(manager.sessions) != dpopSessionCacheLimit { + t.Fatalf("cache size = %d", len(manager.sessions)) + } + if _, ok := manager.cached("0"); !ok { + t.Fatal("recently used entry was evicted") + } + if _, ok := manager.cached("1"); ok { + t.Fatal("least recently used entry was retained") + } +} + +func TestConsoleImageGenerationForwardsStandardDPoPRequest(t *testing.T) { + imageBytes := []byte("\x89PNG\r\n\x1a\nconsole-image") + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } + if request.URL.Path == "/generated.png" && request.Method == http.MethodGet { + if request.Header.Get("Authorization") != "" || request.Header.Get("DPoP") != "" || request.Header.Get("Cookie") != "" { + t.Errorf("asset request leaked credentials: %#v", request.Header) + } + writer.Header().Set("Content-Type", "image/png") + _, _ = writer.Write(imageBytes) + return + } + if request.URL.Path != "/v1/images/generations" || request.Method != http.MethodPost { + http.NotFound(writer, request) + return + } + verifyTestDPoPProof(t, request) + if request.Header.Get("x-cluster") != "" { + t.Errorf("image x-cluster = %q", request.Header.Get("x-cluster")) + } + var payload map[string]any + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Error(err) + } + if payload["model"] != "grok-imagine-image-quality" || payload["prompt"] != "draw" || payload["n"] != float64(2) || payload["aspect_ratio"] != "3:2" || payload["resolution"] != "2k" || payload["response_format"] != "url" { + t.Errorf("image payload = %#v", payload) + } + writer.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(writer).Encode(map[string]any{"created": 123, "data": []any{map[string]any{"url": "http://" + request.Host + "/generated.png", "revised_prompt": "drawn"}}}) + })) + t.Cleanup(server.Close) + store := &consoleImageAssetStoreStub{} + adapter, credential := newConsoleTestAdapterWithAssets(t, server.URL, store) + ctx, trace := infraegress.WithTrace(context.Background()) + response, err := adapter.GenerateImage(ctx, provider.ImageGenerationRequest{ + Credential: credential, Model: "grok-imagine-image-quality", Prompt: "draw", Count: 2, + Size: "1536x1024", Resolution: "2k", ResponseFormat: "url", + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK || response.QuotaUnits != 2 { + t.Fatalf("image response = %#v", response) + } + body, err := io.ReadAll(response.Body) + if err != nil { + t.Fatal(err) + } + var result struct { + Created int64 `json:"created"` + Data []struct { + URL string `json:"url"` + MIMEType string `json:"mime_type"` + RevisedPrompt string `json:"revised_prompt"` + } `json:"data"` + } + if err := json.Unmarshal(body, &result); err != nil { + t.Fatal(err) + } + if result.Created != 123 || len(result.Data) != 1 || result.Data[0].URL != "https://local.example/v1/media/images/console-1" || result.Data[0].MIMEType != "image/png" || result.Data[0].RevisedPrompt != "drawn" { + t.Fatalf("localized image response = %s", body) + } + if saved := store.Saved(); len(saved) != 1 || !bytes.Equal(saved[0], imageBytes) { + t.Fatalf("saved images = %#v", saved) + } + if selection, ok := trace.Selection(egressdomain.ScopeConsoleAsset); !ok || selection.Scope != egressdomain.ScopeConsoleAsset { + t.Fatalf("Console image asset selection = %#v, ok=%v", selection, ok) + } +} + +func TestConsoleImageEditForwardsMultipleImages(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } + if request.URL.Path != "/v1/images/edits" { + http.NotFound(writer, request) + return + } + verifyTestDPoPProof(t, request) + var payload map[string]any + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Error(err) + } + images, _ := payload["images"].([]any) + if len(images) != 2 || payload["image"] != nil || payload["model"] != "grok-imagine-image" || payload["n"] != float64(2) { + t.Errorf("edit payload = %#v", payload) + } + if payload["response_format"] != "b64_json" { + t.Errorf("response_format = %#v", payload["response_format"]) + } + writer.Header().Set("Content-Type", "application/json") + _, _ = writer.Write([]byte(`{"data":[{"b64_json":"aW1hZ2U=","revised_prompt":"merged"}]}`)) + })) + t.Cleanup(server.Close) + adapter, credential := newConsoleTestAdapter(t, server.URL) + response, err := adapter.EditImage(context.Background(), provider.ImageEditRequest{ + Credential: credential, Model: "grok-imagine-image", Prompt: "merge", Count: 2, + ImageURLs: []string{"https://example.com/a.png", "data:image/png;base64,AAAA"}, Resolution: "1k", ResponseFormat: "b64_json", + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK || response.QuotaUnits != 2 { + t.Fatalf("edit response = %#v", response) + } + body, err := io.ReadAll(response.Body) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(body, []byte(`"b64_json":"aW1hZ2U="`)) { + t.Fatalf("b64 response = %s", body) + } +} + +func TestConsoleVideoCreatesAndPollsStandardResources(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } + verifyTestDPoPProof(t, request) + writer.Header().Set("Content-Type", "application/json") + switch { + case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations": + var payload map[string]any + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Error(err) + } + if payload["model"] != "grok-imagine-video" || payload["duration"] != float64(6) || payload["resolution"] != "720p" { + t.Errorf("video payload = %#v", payload) + } + _, _ = writer.Write([]byte(`{"request_id":"upstream-video-1"}`)) + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-1": + _, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result.mp4"}}`)) + default: + http.NotFound(writer, request) + } + })) + t.Cleanup(server.Close) + adapter, credential := newConsoleTestAdapter(t, server.URL) + progress := 0 + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p", + Progress: func(value int) { progress = value }, + }) + if err != nil { + t.Fatal(err) + } + if result.URL != "https://vidgen.x.ai/result.mp4" || result.ContentType != "video/mp4" || progress != 99 { + t.Fatalf("video result = %#v, progress = %d", result, progress) + } +} + +func TestParseConsoleVideoStatusRejectsUnknownState(t *testing.T) { + if _, _, err := parseConsoleVideoStatus([]byte(`{"status":"mystery"}`), nil); err == nil || !strings.Contains(err.Error(), "状态无效") { + t.Fatalf("unknown status error = %v", err) + } +} + +func serveTestDPoPToken(t *testing.T, writer http.ResponseWriter, request *http.Request) bool { + t.Helper() + if request.URL.Path != "/v1/dpop/token" { + return false + } + if request.Method != http.MethodPost { + t.Errorf("DPoP token method = %s", request.Method) + writer.WriteHeader(http.StatusMethodNotAllowed) + return true + } + if request.Header.Get("Authorization") != "" || request.Header.Get("DPoP") != "" { + t.Errorf("DPoP token request unexpectedly authenticated: %#v", request.Header) + } + if request.Header.Get("x-cluster") != "" { + t.Errorf("DPoP token x-cluster = %q", request.Header.Get("x-cluster")) + } + if !strings.Contains(request.Header.Get("Cookie"), "sso=test-sso") { + t.Errorf("DPoP token cookie = %q", request.Header.Get("Cookie")) + } + var payload struct { + JWK dpopJWK `json:"jwk"` + } + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Errorf("decode DPoP token request: %v", err) + writer.WriteHeader(http.StatusBadRequest) + return true + } + thumbprint, err := dpopJWKThumbprint(payload.JWK) + if err != nil { + t.Errorf("DPoP thumbprint: %v", err) + writer.WriteHeader(http.StatusBadRequest) + return true + } + header, _ := json.Marshal(map[string]any{"alg": "HS256", "typ": "JWT"}) + claims, _ := json.Marshal(map[string]any{ + "sub": "test-user", "iat": time.Now().UTC().Unix(), "exp": time.Now().UTC().Add(5 * time.Minute).Unix(), + "cnf": map[string]any{"jkt": thumbprint}, "token_use": "dpop-bound", + }) + accessToken := base64.RawURLEncoding.EncodeToString(header) + "." + base64.RawURLEncoding.EncodeToString(claims) + ".dGVzdA" + writer.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(writer).Encode(map[string]any{"access_token": accessToken, "token_type": "DPoP", "expires_in": 300}) + return true +} + +func verifyTestDPoPProof(t *testing.T, request *http.Request) { + t.Helper() + authorization := strings.TrimSpace(request.Header.Get("Authorization")) + accessToken := strings.TrimSpace(strings.TrimPrefix(authorization, "DPoP ")) + proofValue := strings.TrimSpace(request.Header.Get("DPoP")) + parsed, err := jwt.Parse(proofValue, func(token *jwt.Token) (any, error) { + if token.Method != jwt.SigningMethodES256 || token.Header["typ"] != "dpop+jwt" { + return nil, fmt.Errorf("unexpected DPoP header: %#v", token.Header) + } + encoded, err := json.Marshal(token.Header["jwk"]) + if err != nil { + return nil, err + } + var jwk dpopJWK + if err := json.Unmarshal(encoded, &jwk); err != nil { + return nil, err + } + xBytes, err := base64.RawURLEncoding.DecodeString(jwk.X) + if err != nil { + return nil, err + } + yBytes, err := base64.RawURLEncoding.DecodeString(jwk.Y) + if err != nil { + return nil, err + } + publicKey := &ecdsa.PublicKey{Curve: elliptic.P256(), X: new(big.Int).SetBytes(xBytes), Y: new(big.Int).SetBytes(yBytes)} + if !publicKey.Curve.IsOnCurve(publicKey.X, publicKey.Y) { + return nil, errors.New("DPoP JWK point is not on P-256") + } + return publicKey, nil + }, jwt.WithValidMethods([]string{"ES256"})) + if err != nil || !parsed.Valid { + t.Fatalf("invalid DPoP proof: valid=%v err=%v", parsed != nil && parsed.Valid, err) + } + claims, ok := parsed.Claims.(jwt.MapClaims) + if !ok { + t.Fatalf("DPoP claims = %#v", parsed.Claims) + } + wantHTU := "http://" + request.Host + request.URL.EscapedPath() + if claims["htm"] != request.Method || claims["htu"] != wantHTU || strings.TrimSpace(fmt.Sprint(claims["jti"])) == "" { + t.Fatalf("DPoP request binding = %#v", claims) + } + digest := sha256.Sum256([]byte(accessToken)) + if claims["ath"] != base64.RawURLEncoding.EncodeToString(digest[:]) { + t.Fatalf("DPoP ath = %#v", claims["ath"]) + } + iat, ok := claims["iat"].(float64) + if !ok || time.Since(time.Unix(int64(iat), 0)) > time.Minute { + t.Fatalf("DPoP iat = %#v", claims["iat"]) + } +} + func newConsoleTestAdapter(t *testing.T, baseURL string) (*Adapter, account.Credential) { + return newConsoleTestAdapterWithAssets(t, baseURL, nil) +} + +func newConsoleTestAdapterWithAssets(t *testing.T, baseURL string, assets provider.ImageAssetStore) (*Adapter, account.Credential) { t.Helper() cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) if err != nil { @@ -648,11 +1274,37 @@ func newConsoleTestAdapter(t *testing.T, baseURL string) (*Adapter, account.Cred if err != nil { t.Fatal(err) } - adapter := NewAdapter(Config{BaseURL: baseURL, TimeoutSeconds: 5}, infraegress.NewManager(consoleEgressRepositoryStub{}, cipher), cipher) + adapter := NewAdapter(Config{BaseURL: baseURL, TimeoutSeconds: 5}, infraegress.NewManager(consoleEgressRepositoryStub{}, cipher), cipher, assets) credential := account.Credential{ID: 1, Provider: account.ProviderConsole, AuthType: account.AuthTypeSSO, EncryptedAccessToken: encrypted} return adapter, credential } +type consoleImageAssetStoreStub struct { + mu sync.Mutex + saved [][]byte +} + +func (s *consoleImageAssetStoreStub) SaveImage(_ context.Context, data []byte) (mediadomain.Asset, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.saved = append(s.saved, bytes.Clone(data)) + return mediadomain.Asset{ID: fmt.Sprintf("console-%d", len(s.saved)), MIMEType: "image/png"}, nil +} + +func (*consoleImageAssetStoreStub) PublicImageURL(id string) string { + return "https://local.example/v1/media/images/" + id +} + +func (s *consoleImageAssetStoreStub) Saved() [][]byte { + s.mu.Lock() + defer s.mu.Unlock() + result := make([][]byte, len(s.saved)) + for index := range s.saved { + result[index] = bytes.Clone(s.saved[index]) + } + return result +} + type consoleEgressRepositoryStub struct{} func (consoleEgressRepositoryStub) ListEgressNodes(context.Context, egressdomain.Scope, repository.SortQuery) ([]egressdomain.Node, error) { diff --git a/backend/internal/infra/provider/console/definition.go b/backend/internal/infra/provider/console/definition.go index d77eafa1..94eb6e57 100644 --- a/backend/internal/infra/provider/console/definition.go +++ b/backend/internal/infra/provider/console/definition.go @@ -6,20 +6,29 @@ import ( "github.com/chenyme/grok2api/backend/internal/infra/provider" ) -// Definition declares the stable Grok Console capability boundary; Console retains stateless Responses semantics. +// Definition declares the stable Grok Console capability boundary. Conversation +// remains stateless while media uses the standard asynchronous xAI resources. func (a *Adapter) Definition() provider.Definition { return provider.Definition{ - Provider: account.ProviderConsole, - ModelNamespace: account.ProviderConsole.ModelNamespace(), - ModelCatalog: provider.ModelCatalogStatic, - ModelCapabilities: []modeldomain.Capability{modeldomain.CapabilityResponses}, - Quota: provider.QuotaLocalWindow, + Provider: account.ProviderConsole, + ModelNamespace: account.ProviderConsole.ModelNamespace(), + ModelCatalog: provider.ModelCatalogStatic, + ModelCapabilities: []modeldomain.Capability{ + modeldomain.CapabilityResponses, + modeldomain.CapabilityImage, + modeldomain.CapabilityImageEdit, + modeldomain.CapabilityVideo, + }, + Quota: provider.QuotaRemoteWindow, Credential: provider.CredentialSurface{ AuthType: account.AuthTypeSSO, Import: true, }, Conversation: provider.ConversationSurface{ Responses: true, ChatCompletions: true, Messages: true, }, + Media: provider.MediaSurface{ + ImageGeneration: true, ImageEdit: true, VideoGeneration: true, + }, // Console shares the browser/clearance surface with Web. A 403 is // therefore normally an egress challenge, not proof that the SSO // credential is invalid; the gateway must retry after rebuilding the diff --git a/backend/internal/infra/provider/console/dpop.go b/backend/internal/infra/provider/console/dpop.go new file mode 100644 index 00000000..33ed5025 --- /dev/null +++ b/backend/internal/infra/provider/console/dpop.go @@ -0,0 +1,401 @@ +package console + +import ( + "bytes" + "container/list" + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "sync" + "time" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" + "github.com/chenyme/grok2api/backend/internal/infra/provider" + "github.com/chenyme/grok2api/backend/internal/infra/security" + "github.com/golang-jwt/jwt/v5" + "github.com/google/uuid" + "golang.org/x/sync/singleflight" +) + +const ( + dpopSessionCacheLimit = 4096 + dpopRefreshSkew = 20 * time.Second + maxDPoPTokenLifetime = time.Hour +) + +type dpopJWK struct { + Kty string `json:"kty"` + Crv string `json:"crv"` + X string `json:"x"` + Y string `json:"y"` +} + +type dpopSession struct { + accessToken string + privateKey *ecdsa.PrivateKey + publicJWK dpopJWK + expiresAt time.Time +} + +type dpopSessionManager struct { + mu sync.Mutex + sessions map[string]*dpopSessionEntry + lru list.List + loads singleflight.Group + now func() time.Time +} + +type dpopSessionEntry struct { + key string + session dpopSession + element *list.Element +} + +type dpopTokenEndpointError struct { + status int + statusText string + header http.Header + body []byte + bodyTruncated bool + request *http.Request +} + +func (e *dpopTokenEndpointError) Error() string { + suffix := "" + if e.bodyTruncated { + suffix = " (response truncated)" + } + return fmt.Sprintf("Console DPoP token 接口返回 %d%s", e.status, suffix) +} + +func (e *dpopTokenEndpointError) response() *http.Response { + header := e.header.Clone() + header.Set("Content-Length", strconv.Itoa(len(e.body))) + if e.bodyTruncated { + header.Set("X-Grok2API-Body-Truncated", "1") + } + return &http.Response{ + StatusCode: e.status, Status: e.statusText, Header: header, + Body: io.NopCloser(bytes.NewReader(e.body)), ContentLength: int64(len(e.body)), Request: e.request, + } +} + +func newDPoPSessionManager() *dpopSessionManager { + return &dpopSessionManager{sessions: make(map[string]*dpopSessionEntry), now: time.Now} +} + +func (m *dpopSessionManager) get( + ctx context.Context, + adapter *Adapter, + credential account.Credential, + ssoToken string, + lease *infraegress.Lease, +) (dpopSession, string, error) { + key := dpopSessionCacheKey(adapter.config().BaseURL, credential, ssoToken, lease) + if session, ok := m.cached(key); ok { + return session, key, nil + } + value, err, _ := m.loads.Do(key, func() (any, error) { + if session, ok := m.cached(key); ok { + return session, nil + } + session, fetchErr := adapter.fetchDPoPSession(ctx, ssoToken, lease) + if fetchErr != nil { + return dpopSession{}, fetchErr + } + m.store(key, session) + return session, nil + }) + if err != nil { + return dpopSession{}, key, err + } + session, ok := value.(dpopSession) + if !ok { + return dpopSession{}, key, errors.New("Console DPoP session 类型无效") + } + return session, key, nil +} + +func (m *dpopSessionManager) cached(key string) (dpopSession, bool) { + m.mu.Lock() + defer m.mu.Unlock() + entry, ok := m.sessions[key] + if !ok { + return dpopSession{}, false + } + if !entry.session.expiresAt.After(m.now().UTC().Add(dpopRefreshSkew)) { + m.removeLocked(entry) + return dpopSession{}, false + } + m.lru.MoveToFront(entry.element) + return entry.session, true +} + +func (m *dpopSessionManager) store(key string, session dpopSession) { + m.mu.Lock() + defer m.mu.Unlock() + if entry := m.sessions[key]; entry != nil { + entry.session = session + m.lru.MoveToFront(entry.element) + return + } + if len(m.sessions) >= dpopSessionCacheLimit { + if oldest := m.lru.Back(); oldest != nil { + m.removeLocked(oldest.Value.(*dpopSessionEntry)) + } + } + entry := &dpopSessionEntry{key: key, session: session} + entry.element = m.lru.PushFront(entry) + m.sessions[key] = entry +} + +func (m *dpopSessionManager) invalidate(key, accessToken string) { + m.mu.Lock() + defer m.mu.Unlock() + current := m.sessions[key] + if current == nil || (accessToken != "" && current.session.accessToken != accessToken) { + return + } + m.removeLocked(current) + // Do not call singleflight.Forget here. A concurrent refresh must remain + // coalesced; forgetting it can start a second token exchange for the same + // account and egress after an expired token produces a burst of 401s. +} + +func (m *dpopSessionManager) removeLocked(entry *dpopSessionEntry) { + if entry == nil { + return + } + delete(m.sessions, entry.key) + if entry.element != nil { + m.lru.Remove(entry.element) + entry.element = nil + } +} + +func dpopSessionCacheKey(baseURL string, credential account.Credential, ssoToken string, lease *infraegress.Lease) string { + nodeID := uint64(0) + if lease != nil { + nodeID = lease.NodeID + } + return strings.TrimRight(strings.TrimSpace(baseURL), "/") + "|" + + strconv.FormatUint(credential.ID, 10) + "|" + strconv.FormatUint(nodeID, 10) + "|" + security.HashToken(ssoToken) +} + +func (a *Adapter) fetchDPoPSession(ctx context.Context, ssoToken string, lease *infraegress.Lease) (dpopSession, error) { + privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return dpopSession{}, fmt.Errorf("生成 Console DPoP 密钥: %w", err) + } + publicJWK := publicDPoPJWK(&privateKey.PublicKey) + payload, err := json.Marshal(map[string]any{"jwk": publicJWK}) + if err != nil { + return dpopSession{}, err + } + endpoint := consoleV1Endpoint(a.config().BaseURL, "/dpop/token") + request, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload)) + if err != nil { + return dpopSession{}, err + } + applyBrowserHeaders(request, ssoToken, lease) + request.Header.Set("Content-Type", "application/json") + response, err := lease.DoDeferredForbidden(request) + if err != nil { + return dpopSession{}, err + } + data, truncated, readErr := provider.ReadDiagnosticBody(response.Body) + _ = response.Body.Close() + if readErr != nil { + return dpopSession{}, readErr + } + if response.StatusCode < 200 || response.StatusCode >= 300 { + if response.StatusCode == http.StatusForbidden { + if !provider.IsDefinitiveAccountBlockBody(data) { + lease.InvalidateClearance() + } + } + return dpopSession{}, &dpopTokenEndpointError{ + status: response.StatusCode, statusText: response.Status, header: response.Header.Clone(), + body: data, bodyTruncated: truncated, request: response.Request, + } + } + var tokenResponse struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + ExpiresIn int `json:"expires_in"` + } + if err := json.Unmarshal(data, &tokenResponse); err != nil { + return dpopSession{}, fmt.Errorf("解析 Console DPoP token: %w", err) + } + if strings.TrimSpace(tokenResponse.AccessToken) == "" || !strings.EqualFold(strings.TrimSpace(tokenResponse.TokenType), "DPoP") { + return dpopSession{}, errors.New("Console DPoP token 响应无效") + } + if tokenResponse.ExpiresIn <= 0 || time.Duration(tokenResponse.ExpiresIn)*time.Second > maxDPoPTokenLifetime { + return dpopSession{}, errors.New("Console DPoP token 有效期无效") + } + thumbprint, err := dpopJWKThumbprint(publicJWK) + if err != nil { + return dpopSession{}, err + } + tokenExpiry, tokenThumbprint, err := parseDPoPAccessToken(tokenResponse.AccessToken) + if err != nil { + return dpopSession{}, err + } + if tokenThumbprint != thumbprint { + return dpopSession{}, errors.New("Console DPoP token 与本地密钥不匹配") + } + now := time.Now().UTC() + expiresAt := now.Add(time.Duration(tokenResponse.ExpiresIn) * time.Second) + if tokenExpiry.Before(expiresAt) { + expiresAt = tokenExpiry + } + if !expiresAt.After(now.Add(dpopRefreshSkew)) { + return dpopSession{}, errors.New("Console DPoP token 已过期或即将过期") + } + return dpopSession{accessToken: tokenResponse.AccessToken, privateKey: privateKey, publicJWK: publicJWK, expiresAt: expiresAt}, nil +} + +func (a *Adapter) doDPoPRequest( + ctx context.Context, + credential account.Credential, + ssoToken string, + lease *infraegress.Lease, + method, endpoint string, + body []byte, + accept string, +) (*http.Response, error) { + for attempt := 0; attempt < 2; attempt++ { + session, cacheKey, err := a.dpop.get(ctx, a, credential, ssoToken, lease) + if err != nil { + var endpointErr *dpopTokenEndpointError + if errors.As(err, &endpointErr) { + return endpointErr.response(), nil + } + return nil, err + } + request, err := http.NewRequestWithContext(ctx, method, endpoint, bytes.NewReader(body)) + if err != nil { + return nil, err + } + applyBrowserHeaders(request, ssoToken, lease) + if len(body) > 0 { + request.Header.Set("Content-Type", "application/json") + } + if strings.TrimSpace(accept) != "" { + request.Header.Set("Accept", accept) + } + if strings.HasSuffix(request.URL.Path, "/responses") { + request.Header.Set("x-cluster", "https://us-east-1.api.x.ai") + } + if err := applyDPoPAuthorization(request, session); err != nil { + return nil, err + } + response, err := lease.DoDeferredForbidden(request) + if err != nil { + return nil, err + } + if response.StatusCode != http.StatusUnauthorized || attempt > 0 { + return response, nil + } + _, _, _ = provider.ReadDiagnosticBody(response.Body) + _ = response.Body.Close() + a.dpop.invalidate(cacheKey, session.accessToken) + } + return nil, errors.New("Console DPoP 重试状态无效") +} + +func publicDPoPJWK(key *ecdsa.PublicKey) dpopJWK { + return dpopJWK{ + Kty: "EC", Crv: "P-256", + X: base64.RawURLEncoding.EncodeToString(key.X.FillBytes(make([]byte, 32))), + Y: base64.RawURLEncoding.EncodeToString(key.Y.FillBytes(make([]byte, 32))), + } +} + +func dpopJWKThumbprint(jwk dpopJWK) (string, error) { + canonical := struct { + Crv string `json:"crv"` + Kty string `json:"kty"` + X string `json:"x"` + Y string `json:"y"` + }{Crv: jwk.Crv, Kty: jwk.Kty, X: jwk.X, Y: jwk.Y} + data, err := json.Marshal(canonical) + if err != nil { + return "", err + } + digest := sha256.Sum256(data) + return base64.RawURLEncoding.EncodeToString(digest[:]), nil +} + +func parseDPoPAccessToken(value string) (time.Time, string, error) { + parts := strings.Split(value, ".") + if len(parts) != 3 { + return time.Time{}, "", errors.New("Console DPoP access token 格式无效") + } + payload, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + return time.Time{}, "", errors.New("Console DPoP access token payload 无效") + } + var claims struct { + ExpiresAt int64 `json:"exp"` + CNF struct { + JKT string `json:"jkt"` + } `json:"cnf"` + } + if err := json.Unmarshal(payload, &claims); err != nil || claims.ExpiresAt <= 0 || strings.TrimSpace(claims.CNF.JKT) == "" { + return time.Time{}, "", errors.New("Console DPoP access token claims 无效") + } + return time.Unix(claims.ExpiresAt, 0).UTC(), claims.CNF.JKT, nil +} + +func applyDPoPAuthorization(request *http.Request, session dpopSession) error { + if request == nil || request.URL == nil || session.privateKey == nil || strings.TrimSpace(session.accessToken) == "" { + return errors.New("Console DPoP 请求参数无效") + } + digest := sha256.Sum256([]byte(session.accessToken)) + claims := jwt.MapClaims{ + "jti": uuid.NewString(), + "htm": strings.ToUpper(request.Method), + "htu": dpopHTU(request), + "iat": time.Now().UTC().Unix(), + "ath": base64.RawURLEncoding.EncodeToString(digest[:]), + } + proof := jwt.NewWithClaims(jwt.SigningMethodES256, claims) + proof.Header["typ"] = "dpop+jwt" + proof.Header["jwk"] = session.publicJWK + signed, err := proof.SignedString(session.privateKey) + if err != nil { + return fmt.Errorf("签名 Console DPoP proof: %w", err) + } + request.Header.Set("Authorization", "DPoP "+session.accessToken) + request.Header.Set("DPoP", signed) + return nil +} + +func dpopHTU(request *http.Request) string { + path := request.URL.EscapedPath() + if path == "" { + path = "/" + } + return request.URL.Scheme + "://" + request.URL.Host + path +} + +func consoleV1Endpoint(baseURL, path string) string { + baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/") + path = "/" + strings.TrimLeft(strings.TrimSpace(path), "/") + if strings.HasSuffix(baseURL, "/v1") { + return baseURL + path + } + return baseURL + "/v1" + path +} diff --git a/backend/internal/infra/provider/console/headers.go b/backend/internal/infra/provider/console/headers.go index ea943d70..cfde42ee 100644 --- a/backend/internal/infra/provider/console/headers.go +++ b/backend/internal/infra/provider/console/headers.go @@ -8,7 +8,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/infra/provider/browserheaders" ) -func applyHeaders(request *http.Request, token string, lease *infraegress.Lease) { +func applyBrowserHeaders(request *http.Request, token string, lease *infraegress.Lease) { userAgent := strings.TrimSpace(lease.UserAgent) if userAgent == "" { userAgent = infraegress.DefaultUserAgent @@ -16,8 +16,7 @@ func applyHeaders(request *http.Request, token string, lease *infraegress.Lease) request.Header.Set("Accept", "*/*") request.Header.Set("Accept-Encoding", "gzip, deflate, br, zstd") request.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8") - request.Header.Set("Authorization", "Bearer anonymous") - request.Header.Set("Content-Type", "application/json") + request.Header.Set("Cache-Control", "no-cache") request.Header.Set("Cookie", infraegress.BuildSSOCookie(token, lease.CFCookies)) request.Header.Set("Origin", "https://console.x.ai") request.Header.Set("Referer", "https://console.x.ai/") @@ -25,8 +24,8 @@ func applyHeaders(request *http.Request, token string, lease *infraegress.Lease) request.Header.Set("Sec-Fetch-Mode", "cors") request.Header.Set("Sec-Fetch-Site", "same-origin") request.Header.Set("Priority", "u=1, i") + request.Header.Set("Pragma", "no-cache") request.Header.Set("User-Agent", userAgent) - request.Header.Set("x-cluster", "https://us-east-1.api.x.ai") applyChromiumClientHints(request.Header, userAgent) } diff --git a/backend/internal/infra/provider/console/media.go b/backend/internal/infra/provider/console/media.go new file mode 100644 index 00000000..f7819e8d --- /dev/null +++ b/backend/internal/infra/provider/console/media.go @@ -0,0 +1,727 @@ +package console + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress" + mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" + infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" + "github.com/chenyme/grok2api/backend/internal/infra/provider" +) + +const ( + consoleMediaBodyLimit = 2 << 20 + consoleImageBodyLimit = 32 << 20 + consoleImageDownloadTimeout = 45 * time.Second + consoleMediaOutputAttempts = 3 + consoleVideoPollEvery = 2 * time.Second + consoleMaxEditImages = 3 + consoleMaxVideoImages = 1 +) + +type consoleMediaUpstreamError struct { + status int + summary string +} + +func (e *consoleMediaUpstreamError) Error() string { + if e == nil { + return "" + } + return e.summary +} + +func (e *consoleMediaUpstreamError) HTTPStatusCode() int { + if e == nil { + return 0 + } + return e.status +} + +func (a *Adapter) GenerateImage(ctx context.Context, request provider.ImageGenerationRequest) (*provider.Response, error) { + if !ResolveMedia(request.Model, modeldomain.CapabilityImage) { + return invalidConsoleMediaRequest("模型不支持 Console 图片生成"), nil + } + if request.Streaming || request.PartialImages != 0 { + return invalidConsoleMediaRequest("Grok Console 标准图片接口不支持 stream 或 partial_images"), nil + } + count := request.Count + if count <= 0 { + count = 1 + } + if count > 10 { + return invalidConsoleMediaRequest("n 必须在 1 到 10 之间"), nil + } + format, err := normalizeConsoleImageFormat(request.ResponseFormat) + if err != nil { + return invalidConsoleMediaRequest(err.Error()), nil + } + ratio, err := resolveConsoleImageAspectRatio(request.AspectRatio, request.Size) + if err != nil { + return invalidConsoleMediaRequest(err.Error()), nil + } + resolution, err := normalizeConsoleImageResolution(request.Resolution) + if err != nil { + return invalidConsoleMediaRequest(err.Error()), nil + } + payload := map[string]any{"model": request.Model, "prompt": request.Prompt, "n": count, "response_format": format} + if ratio != "" { + payload["aspect_ratio"] = ratio + } + if resolution != "" { + payload["resolution"] = resolution + } + return a.forwardConsoleMedia(ctx, request.Credential, "/images/generations", payload, format, count) +} + +func (a *Adapter) EditImage(ctx context.Context, request provider.ImageEditRequest) (*provider.Response, error) { + if !ResolveMedia(request.Model, modeldomain.CapabilityImageEdit) { + return invalidConsoleMediaRequest("模型不支持 Console 图片编辑"), nil + } + if request.Streaming || request.PartialImages != 0 { + return invalidConsoleMediaRequest("Grok Console 标准图片接口不支持 stream 或 partial_images"), nil + } + if len(request.ImageURLs) == 0 || len(request.ImageURLs) > consoleMaxEditImages { + return invalidConsoleMediaRequest("Console 图片编辑必须提供 1 到 3 张图片"), nil + } + count := request.Count + if count <= 0 { + count = 1 + } + if count > 10 { + return invalidConsoleMediaRequest("n 必须在 1 到 10 之间"), nil + } + format, err := normalizeConsoleImageFormat(request.ResponseFormat) + if err != nil { + return invalidConsoleMediaRequest(err.Error()), nil + } + ratio, err := resolveConsoleImageAspectRatio(request.AspectRatio, request.Size) + if err != nil { + return invalidConsoleMediaRequest(err.Error()), nil + } + resolution, err := normalizeConsoleImageResolution(request.Resolution) + if err != nil { + return invalidConsoleMediaRequest(err.Error()), nil + } + images := make([]map[string]any, 0, len(request.ImageURLs)) + for _, rawURL := range request.ImageURLs { + value := strings.TrimSpace(rawURL) + if !validConsoleMediaInputURL(value, "image") { + return invalidConsoleMediaRequest("每张编辑图片都必须是 HTTPS URL 或 image data URL"), nil + } + images = append(images, map[string]any{"type": "image_url", "url": value}) + } + payload := map[string]any{"model": request.Model, "prompt": request.Prompt, "n": count, "response_format": format} + if len(images) == 1 { + payload["image"] = images[0] + } else { + payload["images"] = images + } + if ratio != "" { + payload["aspect_ratio"] = ratio + } + if resolution != "" { + payload["resolution"] = resolution + } + return a.forwardConsoleMedia(ctx, request.Credential, "/images/edits", payload, format, count) +} + +func (a *Adapter) forwardConsoleMedia(ctx context.Context, credential account.Credential, path string, payload any, format string, quotaUnits int) (*provider.Response, error) { + token, err := a.cipher.Decrypt(credential.EncryptedAccessToken) + if err != nil { + return nil, err + } + body, err := json.Marshal(payload) + if err != nil { + return nil, err + } + cfg := a.config() + requestCtx, cancel := context.WithTimeout(ctx, time.Duration(cfg.TimeoutSeconds)*time.Second) + lease, err := a.egress.AcquireCredential(requestCtx, egressdomain.ScopeConsole, credential) + if err != nil { + cancel() + return nil, err + } + response, err := a.doDPoPRequest(requestCtx, credential, token, lease, http.MethodPost, consoleV1Endpoint(cfg.BaseURL, path), body, "application/json") + if err != nil { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, 0, err) + lease.Release() + cancel() + return nil, err + } + var rateLimit *provider.RateLimitMetadata + if response.StatusCode == http.StatusTooManyRequests { + _, rateLimit, err = normalizeRateLimitResponse(response) + if err != nil { + lease.Release() + cancel() + return nil, err + } + } + if response.StatusCode < 200 || response.StatusCode >= 300 { + data, truncated, readErr := provider.ReadDiagnosticBody(response.Body) + _ = response.Body.Close() + if response.StatusCode == http.StatusForbidden && !provider.IsDefinitiveAccountBlockBody(data) { + lease.InvalidateClearance() + } + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil) + lease.Release() + cancel() + if readErr != nil { + return nil, readErr + } + response.Body = io.NopCloser(bytes.NewReader(data)) + response.ContentLength = int64(len(data)) + response.Header.Set("Content-Length", strconv.Itoa(len(data))) + if truncated { + response.Header.Set("X-Grok2API-Body-Truncated", "1") + } + result := responseResult(response, response.Body) + result.Diagnostic = &provider.DiagnosticResponse{StatusCode: response.StatusCode, Status: response.Status, Header: response.Header.Clone(), Body: data, BodyTruncated: truncated} + result.RateLimit = rateLimit + return result, nil + } + if format == "url" { + data, readErr := io.ReadAll(io.LimitReader(response.Body, consoleMediaBodyLimit+1)) + _ = response.Body.Close() + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, readErr) + lease.Release() + cancel() + if readErr == nil && len(data) > consoleMediaBodyLimit { + readErr = errors.New("Console 图片上游响应超过 2 MiB") + } + if readErr == nil { + data, readErr = a.localizeConsoleImageResponse(ctx, credential, cfg.BaseURL, data) + } + if readErr != nil { + if !provider.IsMediaPostProcessingError(readErr) { + readErr = provider.NewMediaPostProcessingError(provider.MediaPostProcessingDownload, readErr) + } + return nil, readErr + } + response.Body = io.NopCloser(bytes.NewReader(data)) + response.ContentLength = int64(len(data)) + response.Header.Set("Content-Length", strconv.Itoa(len(data))) + response.Header.Set("Content-Type", "application/json") + result := responseResult(response, response.Body) + result.QuotaUnits = max(1, quotaUnits) + result.RateLimit = rateLimit + return result, nil + } + release := func() { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil) + lease.Release() + cancel() + } + result := responseResult(response, &releaseBody{ReadCloser: response.Body, release: release}) + result.QuotaUnits = max(1, quotaUnits) + result.RateLimit = rateLimit + return result, nil +} + +func (a *Adapter) localizeConsoleImageResponse(ctx context.Context, credential account.Credential, baseURL string, data []byte) ([]byte, error) { + if a.assets == nil { + return nil, provider.NewMediaPostProcessingError(provider.MediaPostProcessingStorage, errors.New("图片媒体存储未配置")) + } + var envelope map[string]json.RawMessage + if err := json.Unmarshal(data, &envelope); err != nil { + return nil, provider.NewMediaPostProcessingError(provider.MediaPostProcessingDownload, fmt.Errorf("解析 Console 图片响应: %w", err)) + } + var items []map[string]json.RawMessage + if err := json.Unmarshal(envelope["data"], &items); err != nil || len(items) == 0 || len(items) > 10 { + return nil, provider.NewMediaPostProcessingError(provider.MediaPostProcessingDownload, errors.New("Console 图片响应缺少有效 data")) + } + + for index, item := range items { + var rawURL string + if err := json.Unmarshal(item["url"], &rawURL); err != nil || strings.TrimSpace(rawURL) == "" { + return nil, provider.NewMediaPostProcessingError(provider.MediaPostProcessingDownload, fmt.Errorf("Console 图片响应第 %d 项缺少 URL", index+1)) + } + raw, err := a.downloadConsoleImage(ctx, credential, baseURL, rawURL) + if err != nil { + return nil, provider.NewMediaPostProcessingError(provider.MediaPostProcessingDownload, err) + } + asset, err := a.saveConsoleImage(ctx, raw) + if err != nil { + return nil, provider.NewMediaPostProcessingError(provider.MediaPostProcessingStorage, err) + } + items[index]["url"], _ = json.Marshal(a.assets.PublicImageURL(asset.ID)) + items[index]["mime_type"], _ = json.Marshal(asset.MIMEType) + } + encodedItems, err := json.Marshal(items) + if err != nil { + return nil, provider.NewMediaPostProcessingError(provider.MediaPostProcessingStorage, err) + } + envelope["data"] = encodedItems + encoded, err := json.Marshal(envelope) + if err != nil { + return nil, provider.NewMediaPostProcessingError(provider.MediaPostProcessingStorage, err) + } + return encoded, nil +} + +func (a *Adapter) downloadConsoleImage(ctx context.Context, credential account.Credential, baseURL, rawURL string) ([]byte, error) { + parsed, err := trustedConsoleImageURL(rawURL, baseURL) + if err != nil { + return nil, err + } + downloadCtx, cancel := context.WithTimeout(ctx, consoleImageDownloadTimeout) + defer cancel() + var lastErr error + for attempt := 0; attempt < consoleMediaOutputAttempts; attempt++ { + raw, retryable, attemptErr := a.downloadConsoleImageAttempt(downloadCtx, credential, baseURL, parsed.String()) + if attemptErr == nil { + return raw, nil + } + lastErr = attemptErr + if !retryable || downloadCtx.Err() != nil || attempt+1 >= consoleMediaOutputAttempts { + break + } + if err := waitConsoleMediaRetry(downloadCtx, attempt); err != nil { + return nil, err + } + } + return nil, lastErr +} + +func (a *Adapter) downloadConsoleImageAttempt(ctx context.Context, credential account.Credential, baseURL, rawURL string) ([]byte, bool, error) { + lease, err := a.egress.AcquireCredential(ctx, egressdomain.ScopeConsoleAsset, credential) + if err != nil { + return nil, true, err + } + defer lease.Release() + request, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return nil, false, err + } + request.Header.Set("Accept", "image/*,*/*;q=0.8") + userAgent := strings.TrimSpace(lease.UserAgent) + if userAgent == "" { + userAgent = infraegress.DefaultUserAgent + } + request.Header.Set("User-Agent", userAgent) + response, err := lease.DoDeferredForbidden(request) + if err != nil { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsoleAsset, lease.NodeID, 0, err) + return nil, ctx.Err() == nil, fmt.Errorf("下载 Console 图片: %w", err) + } + defer response.Body.Close() + // 标准 net/http 响应会保留最终请求 URL;兼容不填充 Request 的自定义出口客户端时, + // 初始 URL 已在发起请求前完成校验。若存在最终 URL,则额外检查重定向目标。 + if response.Request != nil && response.Request.URL != nil { + if _, err := trustedConsoleImageURL(response.Request.URL.String(), baseURL); err != nil { + return nil, false, errors.New("Console 图片下载重定向到不受信任的地址") + } + } + if response.StatusCode < 200 || response.StatusCode >= 300 { + retryable := response.StatusCode == http.StatusRequestTimeout || response.StatusCode == http.StatusTooEarly || response.StatusCode == http.StatusTooManyRequests || response.StatusCode >= 500 + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsoleAsset, lease.NodeID, response.StatusCode, nil) + return nil, retryable, fmt.Errorf("下载 Console 图片返回 %d", response.StatusCode) + } + contentType := strings.ToLower(strings.TrimSpace(strings.Split(response.Header.Get("Content-Type"), ";")[0])) + if contentType != "" && contentType != "application/octet-stream" && !strings.HasPrefix(contentType, "image/") { + return nil, false, errors.New("Console 图片 Content-Type 无效") + } + raw, err := io.ReadAll(io.LimitReader(response.Body, consoleImageBodyLimit+1)) + if err != nil { + return nil, ctx.Err() == nil, fmt.Errorf("读取 Console 图片: %w", err) + } + if len(raw) == 0 || len(raw) > consoleImageBodyLimit { + return nil, false, errors.New("Console 图片为空或超过 32 MiB") + } + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsoleAsset, lease.NodeID, response.StatusCode, nil) + return raw, false, nil +} + +func (a *Adapter) saveConsoleImage(ctx context.Context, raw []byte) (asset mediadomain.Asset, err error) { + for attempt := 0; attempt < consoleMediaOutputAttempts; attempt++ { + asset, err = a.assets.SaveImage(ctx, raw) + if err == nil || ctx.Err() != nil || attempt+1 >= consoleMediaOutputAttempts { + return asset, err + } + if err = waitConsoleMediaRetry(ctx, attempt); err != nil { + return mediadomain.Asset{}, err + } + } + return asset, err +} + +func waitConsoleMediaRetry(ctx context.Context, attempt int) error { + delays := [...]time.Duration{200 * time.Millisecond, 750 * time.Millisecond} + timer := time.NewTimer(delays[min(attempt, len(delays)-1)]) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return nil + } +} + +func trustedConsoleImageURL(rawURL, baseURL string) (*url.URL, error) { + parsed, err := url.Parse(strings.TrimSpace(rawURL)) + if err != nil || parsed.User != nil || parsed.Hostname() == "" { + return nil, errors.New("Console 图片内容 URL 不受信任") + } + if parsed.Scheme == "https" && trustedConsoleImageHost(parsed.Hostname()) { + return parsed, nil + } + base, baseErr := url.Parse(strings.TrimSpace(baseURL)) + if baseErr == nil && base.User == nil && strings.EqualFold(parsed.Scheme, base.Scheme) && strings.EqualFold(parsed.Host, base.Host) && (parsed.Scheme == "http" || parsed.Scheme == "https") { + return parsed, nil + } + return nil, errors.New("Console 图片内容 URL 不受信任") +} + +func trustedConsoleImageHost(host string) bool { + return strings.EqualFold(host, "assets.grok.com") || strings.EqualFold(host, "imagine-public.x.ai") || strings.EqualFold(host, "imgen.x.ai") +} + +func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoRequest) (provider.VideoResult, error) { + if !ResolveMedia("grok-imagine-video", modeldomain.CapabilityVideo) { + return provider.VideoResult{}, errors.New("Console 视频模型未注册") + } + if len(request.ReferenceURLs) > consoleMaxVideoImages { + return provider.VideoResult{}, fmt.Errorf("Console grok-imagine-video 最多支持 1 张首图,当前为 %d 张", len(request.ReferenceURLs)) + } + if request.Duration < 1 || request.Duration > 15 { + return provider.VideoResult{}, errors.New("duration 必须在 1 到 15 秒之间") + } + if request.Resolution != "" && request.Resolution != "480p" && request.Resolution != "720p" { + return provider.VideoResult{}, errors.New("grok-imagine-video 仅支持 480p 或 720p") + } + payload := map[string]any{ + "model": "grok-imagine-video", "duration": request.Duration, + } + if prompt := strings.TrimSpace(request.Prompt); prompt != "" { + payload["prompt"] = prompt + } + if ratio := strings.TrimSpace(request.AspectRatio); ratio != "" { + payload["aspect_ratio"] = ratio + } + if resolution := strings.TrimSpace(request.Resolution); resolution != "" { + payload["resolution"] = resolution + } + if len(request.ReferenceURLs) == 1 { + value := strings.TrimSpace(request.ReferenceURLs[0]) + if !validConsoleMediaInputURL(value, "image") { + return provider.VideoResult{}, errors.New("视频首图必须是 HTTPS URL 或 image data URL") + } + payload["image"] = map[string]any{"url": value} + } + if _, hasPrompt := payload["prompt"]; !hasPrompt { + if _, hasImage := payload["image"]; !hasImage { + return provider.VideoResult{}, errors.New("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + } + } + + token, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken) + if err != nil { + return provider.VideoResult{}, err + } + lease, err := a.egress.AcquireCredential(ctx, egressdomain.ScopeConsole, request.Credential) + if err != nil { + return provider.VideoResult{}, err + } + defer lease.Release() + body, err := json.Marshal(payload) + if err != nil { + return provider.VideoResult{}, err + } + baseURL := a.config().BaseURL + created, err := a.doConsoleVideoJSON(ctx, request.Credential, token, lease, http.MethodPost, consoleV1Endpoint(baseURL, "/videos/generations"), body) + if err != nil { + return provider.VideoResult{}, err + } + requestID, err := parseConsoleVideoCreate(created) + if err != nil { + return provider.VideoResult{}, err + } + if request.Progress != nil { + request.Progress(1) + } + ticker := time.NewTicker(consoleVideoPollEvery) + defer ticker.Stop() + for { + statusBody, pollErr := a.doConsoleVideoJSON(ctx, request.Credential, token, lease, http.MethodGet, consoleV1Endpoint(baseURL, "/videos/"+url.PathEscape(requestID)), nil) + if pollErr != nil { + return provider.VideoResult{}, pollErr + } + result, done, parseErr := parseConsoleVideoStatus(statusBody, request.Progress) + if parseErr != nil { + return provider.VideoResult{}, parseErr + } + if done { + return result, nil + } + select { + case <-ctx.Done(): + return provider.VideoResult{}, ctx.Err() + case <-ticker.C: + } + } +} + +func (a *Adapter) doConsoleVideoJSON(ctx context.Context, credential account.Credential, token string, lease *infraegress.Lease, method, endpoint string, body []byte) ([]byte, error) { + requestCtx := ctx + cancel := func() {} + if timeout := a.config().TimeoutSeconds; timeout > 0 { + requestCtx, cancel = context.WithTimeout(ctx, time.Duration(timeout)*time.Second) + } + defer cancel() + response, err := a.doDPoPRequest(requestCtx, credential, token, lease, method, endpoint, body, "application/json") + if err != nil { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, 0, err) + return nil, err + } + defer response.Body.Close() + data, err := io.ReadAll(io.LimitReader(response.Body, consoleMediaBodyLimit+1)) + if err != nil { + return nil, err + } + if len(data) > consoleMediaBodyLimit { + return nil, errors.New("Console 视频上游响应超过 2 MiB") + } + if response.StatusCode == http.StatusUnauthorized { + return nil, provider.ErrUnauthorized + } + if response.StatusCode < 200 || response.StatusCode >= 300 { + if response.StatusCode == http.StatusForbidden && !provider.IsDefinitiveAccountBlockBody(data) { + lease.InvalidateClearance() + } + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil) + return nil, newConsoleMediaUpstreamError(response.StatusCode, data) + } + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil) + return data, nil +} + +func (a *Adapter) DownloadVideo(ctx context.Context, credential account.Credential, rawURL string) (io.ReadCloser, string, int64, error) { + parsed, err := url.Parse(strings.TrimSpace(rawURL)) + if err != nil || parsed.Scheme != "https" || parsed.User != nil || !trustedConsoleVideoHost(parsed.Hostname()) { + return nil, "", 0, errors.New("Console 视频内容 URL 不受信任") + } + lease, err := a.egress.AcquireCredential(ctx, egressdomain.ScopeConsoleAsset, credential) + if err != nil { + return nil, "", 0, err + } + request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil) + if err != nil { + lease.Release() + return nil, "", 0, err + } + request.Header.Set("Accept", "video/*,*/*;q=0.8") + userAgent := strings.TrimSpace(lease.UserAgent) + if userAgent == "" { + userAgent = infraegress.DefaultUserAgent + } + request.Header.Set("User-Agent", userAgent) + response, err := lease.DoDeferredForbidden(request) + if err != nil { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsoleAsset, lease.NodeID, 0, err) + lease.Release() + return nil, "", 0, err + } + if response.Request != nil && response.Request.URL != nil { + finalURL := response.Request.URL + if finalURL.Scheme != "https" || finalURL.User != nil || !trustedConsoleVideoHost(finalURL.Hostname()) { + _ = response.Body.Close() + lease.Release() + return nil, "", 0, errors.New("Console 视频下载重定向到不受信任的地址") + } + } + if response.StatusCode < 200 || response.StatusCode >= 300 { + _ = response.Body.Close() + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsoleAsset, lease.NodeID, response.StatusCode, nil) + lease.Release() + return nil, "", 0, fmt.Errorf("下载 Console 视频返回 %d", response.StatusCode) + } + contentType := strings.ToLower(strings.TrimSpace(strings.Split(response.Header.Get("Content-Type"), ";")[0])) + if contentType == "" || contentType == "application/octet-stream" { + contentType = "video/mp4" + } + if !strings.HasPrefix(contentType, "video/") { + _ = response.Body.Close() + lease.Release() + return nil, "", 0, errors.New("Console 视频 Content-Type 无效") + } + onFinished := func(readErr error, complete bool) { + if readErr != nil { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsoleAsset, lease.NodeID, 0, readErr) + } else if complete { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsoleAsset, lease.NodeID, response.StatusCode, nil) + } + lease.Release() + } + return provider.NewCompletionReadCloser(response.Body, onFinished), contentType, response.ContentLength, nil +} + +func invalidConsoleMediaRequest(message string) *provider.Response { + return jsonProviderResponse(http.StatusBadRequest, map[string]any{"error": map[string]any{ + "message": message, "type": "invalid_request_error", + }}) +} + +func normalizeConsoleImageFormat(value string) (string, error) { + value = strings.ToLower(strings.TrimSpace(value)) + if value == "" { + return "url", nil + } + if value != "url" && value != "b64_json" { + return "", errors.New("response_format 必须是 url 或 b64_json") + } + return value, nil +} + +func normalizeConsoleImageResolution(value string) (string, error) { + value = strings.ToLower(strings.TrimSpace(value)) + if value == "" { + return "", nil + } + if value != "1k" && value != "2k" { + return "", errors.New("resolution 必须是 1k 或 2k") + } + return value, nil +} + +func resolveConsoleImageAspectRatio(aspectRatio, size string) (string, error) { + value := strings.ToLower(strings.TrimSpace(aspectRatio)) + if value == "" { + value = strings.ToLower(strings.TrimSpace(size)) + } + if value == "" || value == "auto" { + return "", nil + } + values := map[string]string{ + "1:1": "1:1", "16:9": "16:9", "9:16": "9:16", "4:3": "4:3", "3:4": "3:4", "3:2": "3:2", "2:3": "2:3", "2:1": "2:1", "1:2": "1:2", + "1024x1024": "1:1", "1280x720": "16:9", "720x1280": "9:16", "1792x1024": "3:2", "1536x1024": "3:2", "1024x1792": "2:3", "1024x1536": "2:3", + } + if resolved := values[value]; resolved != "" { + return resolved, nil + } + return "", errors.New("aspect_ratio 或 size 不受支持") +} + +func validConsoleMediaInputURL(value, mediaType string) bool { + lower := strings.ToLower(strings.TrimSpace(value)) + if strings.HasPrefix(lower, "data:"+mediaType+"/") { + return strings.Contains(lower, ";base64,") + } + parsed, err := url.Parse(value) + return err == nil && parsed.Scheme == "https" && parsed.Host != "" && parsed.User == nil +} + +func parseConsoleVideoCreate(body []byte) (string, error) { + var payload struct { + RequestID string `json:"request_id"` + } + if err := json.Unmarshal(body, &payload); err != nil { + return "", fmt.Errorf("解析 Console 视频创建响应: %w", err) + } + if strings.TrimSpace(payload.RequestID) == "" { + return "", errors.New("Console 视频创建响应缺少 request_id") + } + return payload.RequestID, nil +} + +func parseConsoleVideoStatus(body []byte, progress func(int)) (provider.VideoResult, bool, error) { + var payload struct { + Status string `json:"status"` + Progress int `json:"progress"` + Video struct { + URL string `json:"url"` + } `json:"video"` + Error any `json:"error"` + } + if err := json.Unmarshal(body, &payload); err != nil { + return provider.VideoResult{}, false, fmt.Errorf("解析 Console 视频状态响应: %w", err) + } + if progress != nil && payload.Progress > 0 { + progress(min(99, payload.Progress)) + } + switch status := strings.ToLower(strings.TrimSpace(payload.Status)); status { + case "done", "completed", "succeeded", "success", "ready": + if strings.TrimSpace(payload.Video.URL) == "" { + return provider.VideoResult{}, false, errors.New("Console 视频生成完成但没有返回内容 URL") + } + return provider.VideoResult{URL: strings.TrimSpace(payload.Video.URL), ContentType: "video/mp4"}, true, nil + case "failed", "expired", "cancelled", "canceled", "error": + message := safeConsoleMediaErrorValue(payload.Error) + if message == "" { + message = strings.ToLower(strings.TrimSpace(payload.Status)) + } + return provider.VideoResult{}, false, fmt.Errorf("Console 视频生成失败: %s", message) + case "pending", "processing", "in_progress", "queued": + return provider.VideoResult{}, false, nil + default: + return provider.VideoResult{}, false, fmt.Errorf("Console 视频状态无效: %q", safeConsoleMediaText(status)) + } +} + +func newConsoleMediaUpstreamError(status int, body []byte) error { + message := "" + var payload map[string]any + if json.Unmarshal(body, &payload) == nil { + message = safeConsoleMediaErrorValue(payload["error"]) + if message == "" { + message = safeConsoleMediaErrorValue(payload["message"]) + } + } + summary := fmt.Sprintf("Console 媒体上游返回 %d", status) + if message != "" { + summary += ": " + message + } + return &consoleMediaUpstreamError{status: status, summary: summary} +} + +func safeConsoleMediaErrorValue(value any) string { + if object, ok := value.(map[string]any); ok { + for _, key := range []string{"message", "code", "type"} { + raw, exists := object[key] + if !exists || raw == nil { + continue + } + if text := safeConsoleMediaText(fmt.Sprint(raw)); text != "" { + return text + } + } + } + if text, ok := value.(string); ok { + return safeConsoleMediaText(text) + } + return "" +} + +func safeConsoleMediaText(value string) string { + value = strings.Join(strings.Fields(value), " ") + if strings.Contains(strings.ToLower(value), "authorization") || strings.Contains(strings.ToLower(value), "cookie") { + return "上游拒绝请求" + } + const limit = 160 + if len(value) <= limit { + return value + } + end := limit + for end > 0 && !utf8.ValidString(value[:end]) { + end-- + } + return value[:end] +} + +func trustedConsoleVideoHost(host string) bool { + host = strings.ToLower(strings.TrimSpace(host)) + return host == "vidgen.x.ai" || strings.HasSuffix(host, ".vidgen.x.ai") +} diff --git a/backend/internal/infra/provider/console/quota.go b/backend/internal/infra/provider/console/quota.go new file mode 100644 index 00000000..1196a458 --- /dev/null +++ b/backend/internal/infra/provider/console/quota.go @@ -0,0 +1,167 @@ +package console + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "strings" + "time" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress" + "github.com/chenyme/grok2api/backend/internal/infra/provider" +) + +const ( + consoleQuotaTimeout = 30 * time.Second + consolePredictedChatRecoveryWindow = 24 * time.Hour +) + +func (a *Adapter) SyncQuota(ctx context.Context, credential account.Credential) (provider.QuotaSnapshot, error) { + windows, syncedAt, err := a.syncConsoleQuotas(ctx, credential) + if err != nil { + return provider.QuotaSnapshot{}, err + } + return provider.QuotaSnapshot{Windows: windows, SyncedAt: syncedAt}, nil +} + +func (a *Adapter) SyncQuotaMode(ctx context.Context, credential account.Credential, mode string) (account.QuotaWindow, error) { + if !isConsoleQuotaMode(mode) { + return account.QuotaWindow{}, fmt.Errorf("不支持的 Console 额度模式 %q", mode) + } + windows, _, err := a.syncConsoleQuotas(ctx, credential) + if err != nil { + return account.QuotaWindow{}, err + } + for _, window := range windows { + if window.Mode == mode { + return window, nil + } + } + return account.QuotaWindow{}, fmt.Errorf("Console usage 响应缺少 %s 额度", consoleQuotaKind(mode)) +} + +func (a *Adapter) syncConsoleQuotas(ctx context.Context, credential account.Credential) ([]account.QuotaWindow, time.Time, error) { + ssoToken, err := a.cipher.Decrypt(credential.EncryptedAccessToken) + if err != nil { + return nil, time.Time{}, err + } + requestCtx, cancel := context.WithTimeout(ctx, consoleQuotaTimeout) + defer cancel() + lease, err := a.egress.AcquireCredential(requestCtx, egressdomain.ScopeConsole, credential) + if err != nil { + return nil, time.Time{}, err + } + defer lease.Release() + endpoint := consoleV1Endpoint(a.config().BaseURL, "/usage") + response, err := a.doDPoPRequest(requestCtx, credential, ssoToken, lease, http.MethodGet, endpoint, nil, "application/json") + if err != nil { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, 0, err) + return nil, time.Time{}, err + } + data, truncated, readErr := provider.ReadDiagnosticBody(response.Body) + _ = response.Body.Close() + if readErr != nil { + return nil, time.Time{}, readErr + } + if response.StatusCode < 200 || response.StatusCode >= 300 { + if response.StatusCode == http.StatusUnauthorized || + (response.StatusCode == http.StatusForbidden && provider.IsDefinitiveAccountBlockBody(data)) { + return nil, time.Time{}, fmt.Errorf("%w: Console usage rejected", provider.ErrUnauthorized) + } + if response.StatusCode == http.StatusForbidden { + lease.InvalidateClearance() + } + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil) + suffix := "" + if truncated { + suffix = " (响应已截断)" + } + return nil, time.Time{}, fmt.Errorf("Console usage 接口返回 %d%s", response.StatusCode, suffix) + } + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil) + var payload struct { + Quotas []struct { + Kind string `json:"kind"` + Limit int `json:"limit"` + Used int `json:"used"` + Remaining int `json:"remaining"` + LastConsumedAt int64 `json:"last_consumed_at"` + } `json:"quotas"` + } + if err := json.Unmarshal(data, &payload); err != nil { + return nil, time.Time{}, fmt.Errorf("解析 Console usage: %w", err) + } + now := time.Now().UTC() + byMode := make(map[string]account.QuotaWindow, 3) + for _, quota := range payload.Quotas { + mode := consoleQuotaMode(quota.Kind) + if mode == "" { + continue + } + if quota.Limit < 0 || quota.Used < 0 || quota.Remaining < 0 || quota.Remaining > quota.Limit { + return nil, time.Time{}, fmt.Errorf("Console %s 额度响应无效", consoleQuotaKind(mode)) + } + usagePercent := 0.0 + if quota.Limit > 0 { + usagePercent = float64(quota.Limit-quota.Remaining) / float64(quota.Limit) * 100 + } + windowSeconds := 0 + var resetAt *time.Time + if mode == QuotaMode { + windowSeconds = int(consolePredictedChatRecoveryWindow / time.Second) + if quota.Remaining == 0 { + predicted := now.Add(consolePredictedChatRecoveryWindow) + resetAt = &predicted + } + } + byMode[mode] = account.QuotaWindow{ + AccountID: credential.ID, Mode: mode, Remaining: quota.Remaining, Total: quota.Limit, + UsagePercent: usagePercent, WindowSeconds: windowSeconds, ResetAt: resetAt, + SyncedAt: &now, Source: account.QuotaSourceUpstream, UpdatedAt: now, + } + } + for _, mode := range []string{QuotaMode, QuotaModeImage, QuotaModeVideo} { + if _, ok := byMode[mode]; !ok { + return nil, time.Time{}, fmt.Errorf("Console usage 响应缺少 %s 额度", consoleQuotaKind(mode)) + } + } + windows := make([]account.QuotaWindow, 0, 3) + for _, mode := range []string{QuotaMode, QuotaModeImage, QuotaModeVideo} { + if window, ok := byMode[mode]; ok { + windows = append(windows, window) + } + } + return windows, now, nil +} + +func isConsoleQuotaMode(mode string) bool { + return mode == QuotaMode || mode == QuotaModeImage || mode == QuotaModeVideo +} + +func consoleQuotaMode(kind string) string { + switch strings.ToLower(strings.TrimSpace(kind)) { + case "chat": + return QuotaMode + case "image": + return QuotaModeImage + case "video": + return QuotaModeVideo + default: + return "" + } +} + +func consoleQuotaKind(mode string) string { + switch mode { + case QuotaMode: + return "chat" + case QuotaModeImage: + return "image" + case QuotaModeVideo: + return "video" + default: + return mode + } +} diff --git a/backend/internal/infra/provider/definition_contract_test.go b/backend/internal/infra/provider/definition_contract_test.go index 1d51cbad..d9e79abc 100644 --- a/backend/internal/infra/provider/definition_contract_test.go +++ b/backend/internal/infra/provider/definition_contract_test.go @@ -25,7 +25,7 @@ func TestProductionProviderDefinitionsMatchImplementedCapabilities(t *testing.T) registry := provider.NewRegistry( cliprovider.NewAdapter(cliprovider.Config{}, nil), webprovider.NewAdapter(webprovider.Config{}, nil, nil, nil, nil), - consoleprovider.NewAdapter(consoleprovider.Config{}, nil, nil), + consoleprovider.NewAdapter(consoleprovider.Config{}, nil, nil, nil), ) if err := registry.Validate(); err != nil { t.Fatalf("production registry validation failed: %v", err) @@ -61,10 +61,11 @@ func TestProductionProviderDefinitionsMatchImplementedCapabilities(t *testing.T) inference: provider.InferencePolicy{Usage: provider.UsageEstimated, RetryForbiddenAsEgress: true}, }, { - provider: account.ProviderConsole, catalog: provider.ModelCatalogStatic, quota: provider.QuotaLocalWindow, - capabilities: []modeldomain.Capability{modeldomain.CapabilityResponses}, + provider: account.ProviderConsole, catalog: provider.ModelCatalogStatic, quota: provider.QuotaRemoteWindow, + capabilities: []modeldomain.Capability{modeldomain.CapabilityResponses, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo}, credential: provider.CredentialSurface{AuthType: account.AuthTypeSSO, Import: true}, conversation: provider.ConversationSurface{Responses: true, ChatCompletions: true, Messages: true}, + media: provider.MediaSurface{ImageGeneration: true, ImageEdit: true, VideoGeneration: true}, inference: provider.InferencePolicy{Usage: provider.UsageUpstream, RetryForbiddenAsEgress: true}, }, } diff --git a/backend/internal/infra/provider/read_closer.go b/backend/internal/infra/provider/read_closer.go new file mode 100644 index 00000000..8fe6a1f8 --- /dev/null +++ b/backend/internal/infra/provider/read_closer.go @@ -0,0 +1,46 @@ +package provider + +import ( + "errors" + "io" + "sync" +) + +// NewCompletionReadCloser reports whether a streamed body reached EOF before +// it was closed. Callers can record success only after a complete transfer, +// while still observing transport and close errors exactly once. +func NewCompletionReadCloser(body io.ReadCloser, onFinished func(error, bool)) io.ReadCloser { + return &completionReadCloser{ReadCloser: body, onFinished: onFinished} +} + +type completionReadCloser struct { + io.ReadCloser + onFinished func(error, bool) + once sync.Once + readErr error + complete bool +} + +func (c *completionReadCloser) Read(buffer []byte) (int, error) { + read, err := c.ReadCloser.Read(buffer) + if errors.Is(err, io.EOF) { + c.complete = true + } else if err != nil { + c.readErr = err + } + return read, err +} + +func (c *completionReadCloser) Close() error { + closeErr := c.ReadCloser.Close() + c.once.Do(func() { + feedbackErr := c.readErr + if feedbackErr == nil { + feedbackErr = closeErr + } + if c.onFinished != nil { + c.onFinished(feedbackErr, c.complete) + } + }) + return closeErr +} diff --git a/backend/internal/infra/provider/read_closer_test.go b/backend/internal/infra/provider/read_closer_test.go new file mode 100644 index 00000000..6e8fc0c9 --- /dev/null +++ b/backend/internal/infra/provider/read_closer_test.go @@ -0,0 +1,69 @@ +package provider + +import ( + "errors" + "io" + "strings" + "testing" +) + +func TestCompletionReadCloserReportsCompletedTransferOnce(t *testing.T) { + calls := 0 + var finishedErr error + completed := false + body := NewCompletionReadCloser(io.NopCloser(strings.NewReader("video")), func(err error, complete bool) { + calls++ + finishedErr, completed = err, complete + }) + if _, err := io.ReadAll(body); err != nil { + t.Fatal(err) + } + if err := body.Close(); err != nil { + t.Fatal(err) + } + if err := body.Close(); err != nil { + t.Fatal(err) + } + if calls != 1 || finishedErr != nil || !completed { + t.Fatalf("finish calls=%d err=%v completed=%v", calls, finishedErr, completed) + } +} + +func TestCompletionReadCloserDoesNotReportEarlyCloseAsSuccess(t *testing.T) { + calls := 0 + completed := true + body := NewCompletionReadCloser(io.NopCloser(strings.NewReader("video")), func(_ error, complete bool) { + calls++ + completed = complete + }) + buffer := make([]byte, 1) + if _, err := body.Read(buffer); err != nil { + t.Fatal(err) + } + if err := body.Close(); err != nil { + t.Fatal(err) + } + if calls != 1 || completed { + t.Fatalf("finish calls=%d completed=%v", calls, completed) + } +} + +type failingReadCloser struct{ err error } + +func (value failingReadCloser) Read([]byte) (int, error) { return 0, value.err } +func (failingReadCloser) Close() error { return nil } + +func TestCompletionReadCloserReportsReadFailure(t *testing.T) { + want := errors.New("stream interrupted") + var finishedErr error + body := NewCompletionReadCloser(failingReadCloser{err: want}, func(err error, _ bool) { finishedErr = err }) + if _, err := io.ReadAll(body); !errors.Is(err, want) { + t.Fatalf("read error = %v", err) + } + if err := body.Close(); err != nil { + t.Fatal(err) + } + if !errors.Is(finishedErr, want) { + t.Fatalf("finish error = %v", finishedErr) + } +} diff --git a/backend/internal/infra/provider/web/video.go b/backend/internal/infra/provider/web/video.go index 1a2582ce..2289eb25 100644 --- a/backend/internal/infra/provider/web/video.go +++ b/backend/internal/infra/provider/web/video.go @@ -282,20 +282,6 @@ func (a *Adapter) prepareVideoReference(ctx context.Context, cfg Config, lease * return uploaded.URI, nil } -type videoContentReadCloser struct { - io.ReadCloser - release func() -} - -func (c *videoContentReadCloser) Close() error { - err := c.ReadCloser.Close() - if c.release != nil { - c.release() - c.release = nil - } - return err -} - // DownloadVideo retrieves a completed Grok asset through its source SSO // session. Direct asset URLs are not public and must not be exposed as a // substitute for this authenticated transfer. @@ -323,11 +309,13 @@ func (a *Adapter) DownloadVideo(ctx context.Context, credential account.Credenti request.Header.Del("Content-Type") response, err := lease.Do(request) if err != nil { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), domainegress.ScopeWebAsset, lease.NodeID, 0, err) lease.Release() return nil, "", 0, err } if response.StatusCode < 200 || response.StatusCode >= 300 { _ = response.Body.Close() + a.egress.FeedbackForScope(context.WithoutCancel(ctx), domainegress.ScopeWebAsset, lease.NodeID, response.StatusCode, nil) lease.Release() return nil, "", 0, fmt.Errorf("下载视频返回 %d", response.StatusCode) } @@ -340,7 +328,15 @@ func (a *Adapter) DownloadVideo(ctx context.Context, credential account.Credenti lease.Release() return nil, "", 0, fmt.Errorf("上游视频 Content-Type 无效") } - return &videoContentReadCloser{ReadCloser: response.Body, release: lease.Release}, contentType, response.ContentLength, nil + onFinished := func(readErr error, complete bool) { + if readErr != nil { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), domainegress.ScopeWebAsset, lease.NodeID, 0, readErr) + } else if complete { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), domainegress.ScopeWebAsset, lease.NodeID, response.StatusCode, nil) + } + lease.Release() + } + return provider.NewCompletionReadCloser(response.Body, onFinished), contentType, response.ContentLength, nil } func parseVideoStream(response *http.Response, progress func(int)) (provider.VideoResult, string, error) { diff --git a/backend/internal/infra/runtime/memory/quota_queue.go b/backend/internal/infra/runtime/memory/quota_queue.go index 47a3f767..c66d107e 100644 --- a/backend/internal/infra/runtime/memory/quota_queue.go +++ b/backend/internal/infra/runtime/memory/quota_queue.go @@ -61,6 +61,12 @@ func (q *QuotaRecoveryQueue) ScheduleQuotaRecovery(_ context.Context, value acco defer q.mu.Unlock() key := quotaEventKey(value) if existing := q.items[key]; existing != nil { + // A recovery worker owns a claimed event until it acknowledges or + // reschedules it. Concurrent quota refreshes must not clear that claim; + // the worker already has the authoritative probe result in flight. + if existing.value.ClaimToken != "" { + return nil + } value.ClaimToken = "" existing.value = value heap.Fix(&q.heap, existing.index) @@ -94,6 +100,21 @@ func (q *QuotaRecoveryQueue) EnsureQuotaRecovery(_ context.Context, value accoun return nil } +func (q *QuotaRecoveryQueue) CancelQuotaRecovery(_ context.Context, accountID uint64, mode string) error { + if accountID == 0 || mode == "" { + return fmt.Errorf("额度恢复事件无效") + } + q.mu.Lock() + defer q.mu.Unlock() + item := q.items[fmt.Sprintf("%d:%s", accountID, mode)] + if item == nil || item.value.ClaimToken != "" { + return nil + } + heap.Remove(&q.heap, item.index) + delete(q.items, quotaEventKey(item.value)) + return nil +} + func (q *QuotaRecoveryQueue) ClaimDueQuotaRecoveries(_ context.Context, now time.Time, limit int, lease time.Duration) ([]account.QuotaRecoveryEvent, error) { if limit <= 0 { limit = 100 diff --git a/backend/internal/infra/runtime/memory/quota_queue_test.go b/backend/internal/infra/runtime/memory/quota_queue_test.go index be819aad..632019e8 100644 --- a/backend/internal/infra/runtime/memory/quota_queue_test.go +++ b/backend/internal/infra/runtime/memory/quota_queue_test.go @@ -56,3 +56,56 @@ func TestEnsureQuotaRecoveryPreservesExistingBackoffAndClaim(t *testing.T) { t.Fatalf("ensure overwrote active claim: %v", err) } } + +func TestScheduleQuotaRecoveryPreservesActiveClaim(t *testing.T) { + ctx := context.Background() + queue := NewQuotaRecoveryQueue() + now := time.Now().UTC() + event := account.QuotaRecoveryEvent{AccountID: 1, Mode: "console", DueAt: now.Add(-time.Second), Attempts: 2} + if err := queue.ScheduleQuotaRecovery(ctx, event); err != nil { + t.Fatal(err) + } + claimed, err := queue.ClaimDueQuotaRecoveries(ctx, now, 1, time.Minute) + if err != nil || len(claimed) != 1 || claimed[0].ClaimToken == "" { + t.Fatalf("claimed = %#v, err = %v", claimed, err) + } + if err := queue.ScheduleQuotaRecovery(ctx, account.QuotaRecoveryEvent{AccountID: 1, Mode: "console", DueAt: now.Add(24 * time.Hour)}); err != nil { + t.Fatal(err) + } + claimed[0].DueAt = now.Add(24 * time.Hour) + claimed[0].Attempts++ + if err := queue.RescheduleQuotaRecovery(ctx, claimed[0]); err != nil { + t.Fatalf("concurrent schedule overwrote active claim: %v", err) + } +} + +func TestCancelQuotaRecoveryRemovesOnlyUnclaimedEvent(t *testing.T) { + ctx := context.Background() + queue := NewQuotaRecoveryQueue() + now := time.Now().UTC() + if err := queue.ScheduleQuotaRecovery(ctx, account.QuotaRecoveryEvent{AccountID: 1, Mode: "console", DueAt: now.Add(time.Hour)}); err != nil { + t.Fatal(err) + } + if err := queue.CancelQuotaRecovery(ctx, 1, "console"); err != nil { + t.Fatal(err) + } + values, err := queue.ClaimDueQuotaRecoveries(ctx, now.Add(2*time.Hour), 1, time.Minute) + if err != nil || len(values) != 0 { + t.Fatalf("cancelled event was claimable: %#v, err = %v", values, err) + } + + if err := queue.ScheduleQuotaRecovery(ctx, account.QuotaRecoveryEvent{AccountID: 2, Mode: "console", DueAt: now.Add(-time.Second)}); err != nil { + t.Fatal(err) + } + claimed, err := queue.ClaimDueQuotaRecoveries(ctx, now, 1, time.Minute) + if err != nil || len(claimed) != 1 { + t.Fatalf("claimed = %#v, err = %v", claimed, err) + } + if err := queue.CancelQuotaRecovery(ctx, 2, "console"); err != nil { + t.Fatal(err) + } + claimed[0].DueAt = now.Add(time.Hour) + if err := queue.RescheduleQuotaRecovery(ctx, claimed[0]); err != nil { + t.Fatalf("cancel removed active claim: %v", err) + } +} diff --git a/backend/internal/infra/runtime/redis/store.go b/backend/internal/infra/runtime/redis/store.go index c9bd7dbc..7af0ad51 100644 --- a/backend/internal/infra/runtime/redis/store.go +++ b/backend/internal/infra/runtime/redis/store.go @@ -129,6 +129,7 @@ return redis.call('DEL', KEYS[1]) var scheduleQuotaRecoveryScript = redisclient.NewScript(` if not redis.call('ZSCORE', KEYS[1], ARGV[1]) and redis.call('ZCARD', KEYS[1]) >= tonumber(ARGV[4]) then return 0 end +if redis.call('HEXISTS', KEYS[3], ARGV[1]) == 1 then return 2 end redis.call('ZADD', KEYS[1], ARGV[2], ARGV[1]) redis.call('HSET', KEYS[2], ARGV[1], ARGV[3]) redis.call('HDEL', KEYS[3], ARGV[1]) @@ -143,6 +144,13 @@ redis.call('HSET', KEYS[2], ARGV[1], ARGV[3]) return 1 `) +var cancelQuotaRecoveryScript = redisclient.NewScript(` +if redis.call('HEXISTS', KEYS[3], ARGV[1]) == 1 then return 2 end +redis.call('HDEL', KEYS[2], ARGV[1]) +redis.call('HDEL', KEYS[3], ARGV[1]) +return redis.call('ZREM', KEYS[1], ARGV[1]) +`) + var claimQuotaRecoveryScript = redisclient.NewScript(` local values = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', ARGV[1], 'LIMIT', 0, ARGV[2]) local result = {} @@ -789,6 +797,16 @@ func (s *Store) EnsureQuotaRecovery(ctx context.Context, value account.QuotaReco return nil } +func (s *Store) CancelQuotaRecovery(ctx context.Context, accountID uint64, mode string) error { + mode = strings.TrimSpace(mode) + if accountID == 0 || mode == "" { + return fmt.Errorf("额度恢复事件无效") + } + member := strconv.FormatUint(accountID, 10) + ":" + mode + _, err := cancelQuotaRecoveryScript.Run(ctx, s.client, []string{s.key("quota-recovery", "events"), s.key("quota-recovery", "attempts"), s.key("quota-recovery", "claims")}, member).Int() + return err +} + func (s *Store) ClaimDueQuotaRecoveries(ctx context.Context, now time.Time, limit int, lease time.Duration) ([]account.QuotaRecoveryEvent, error) { if limit <= 0 { limit = 100 diff --git a/backend/internal/infra/runtime/redis/store_integration_test.go b/backend/internal/infra/runtime/redis/store_integration_test.go index b0eac3b2..e1a28954 100644 --- a/backend/internal/infra/runtime/redis/store_integration_test.go +++ b/backend/internal/infra/runtime/redis/store_integration_test.go @@ -225,10 +225,16 @@ func TestRedisRuntimeStoreIntegration(t *testing.T) { if err != nil || len(claimed) != 1 || claimed[0].Attempts != 3 { t.Fatalf("claimed quota recoveries = %#v, err = %v", claimed, err) } + if err := store.ScheduleQuotaRecovery(ctx, account.QuotaRecoveryEvent{AccountID: 42, Mode: "fast", DueAt: time.Now().UTC().Add(time.Hour)}); err != nil { + t.Fatal(err) + } + if err := store.CancelQuotaRecovery(ctx, 42, "fast"); err != nil { + t.Fatal(err) + } claimed[0].Attempts++ claimed[0].DueAt = time.Now().UTC().Add(-time.Second) if err := store.RescheduleQuotaRecovery(ctx, claimed[0]); err != nil { - t.Fatal(err) + t.Fatalf("concurrent schedule overwrote active Redis claim: %v", err) } claimed, err = store.ClaimDueQuotaRecoveries(ctx, time.Now().UTC(), 10, time.Minute) if err != nil || len(claimed) != 1 || claimed[0].Attempts != 4 { @@ -237,6 +243,16 @@ func TestRedisRuntimeStoreIntegration(t *testing.T) { if err := store.AckQuotaRecovery(ctx, claimed[0]); err != nil { t.Fatal(err) } + if err := store.ScheduleQuotaRecovery(ctx, account.QuotaRecoveryEvent{AccountID: 43, Mode: "console", DueAt: time.Now().UTC().Add(time.Hour)}); err != nil { + t.Fatal(err) + } + if err := store.CancelQuotaRecovery(ctx, 43, "console"); err != nil { + t.Fatal(err) + } + cancelled, err := store.ClaimDueQuotaRecoveries(ctx, time.Now().UTC().Add(2*time.Hour), 10, time.Minute) + if err != nil || len(cancelled) != 0 { + t.Fatalf("cancelled Redis quota recovery was claimable: %#v, err = %v", cancelled, err) + } firstGeneration, err := store.MarkQuotaRefreshDirty(ctx, 42, "fast", 200*time.Millisecond) if err != nil || firstGeneration != 1 { diff --git a/backend/internal/repository/model.go b/backend/internal/repository/model.go index 63bef5da..ddb576e0 100644 --- a/backend/internal/repository/model.go +++ b/backend/internal/repository/model.go @@ -11,6 +11,7 @@ import ( // ModelRepository 定义公开模型路由持久化能力。 type ModelRepository interface { List(ctx context.Context, query ModelListQuery) ([]model.Route, int64, error) + ListGroups(ctx context.Context, query ModelListQuery) ([]model.RouteGroup, int64, error) ListEnabled(ctx context.Context) ([]model.Route, error) ListEnabledForScope(ctx context.Context, filter ModelListFilter) ([]model.Route, error) ListConfiguredEnabled(ctx context.Context) ([]model.Route, error) diff --git a/backend/internal/repository/runtime.go b/backend/internal/repository/runtime.go index 56ab7c8f..bf3217c6 100644 --- a/backend/internal/repository/runtime.go +++ b/backend/internal/repository/runtime.go @@ -165,6 +165,7 @@ type InvalidationBus interface { type QuotaRecoveryQueue interface { ScheduleQuotaRecovery(ctx context.Context, value account.QuotaRecoveryEvent) error EnsureQuotaRecovery(ctx context.Context, value account.QuotaRecoveryEvent) error + CancelQuotaRecovery(ctx context.Context, accountID uint64, mode string) error ClaimDueQuotaRecoveries(ctx context.Context, now time.Time, limit int, lease time.Duration) ([]account.QuotaRecoveryEvent, error) AckQuotaRecovery(ctx context.Context, value account.QuotaRecoveryEvent) error RescheduleQuotaRecovery(ctx context.Context, value account.QuotaRecoveryEvent) error diff --git a/backend/internal/transport/http/egress/handler.go b/backend/internal/transport/http/egress/handler.go index dba0f37a..dd8570d4 100644 --- a/backend/internal/transport/http/egress/handler.go +++ b/backend/internal/transport/http/egress/handler.go @@ -899,8 +899,8 @@ func newSourceResponse(value egressdomain.PublicSubscriptionSource) sourceRespon } func newOperationsConfigResponse(value egressdomain.OperationsConfig) operationsConfigResponse { - fallbacks := make(map[string]operationsFallbackResponse, 4) - for _, scope := range []egressdomain.Scope{egressdomain.ScopeBuild, egressdomain.ScopeWeb, egressdomain.ScopeConsole, egressdomain.ScopeWebAsset} { + fallbacks := make(map[string]operationsFallbackResponse, 5) + for _, scope := range []egressdomain.Scope{egressdomain.ScopeBuild, egressdomain.ScopeWeb, egressdomain.ScopeConsole, egressdomain.ScopeWebAsset, egressdomain.ScopeConsoleAsset} { fallback := value.FallbackFor(scope) item := operationsFallbackResponse{Mode: string(fallback.Mode)} if fallback.NodeID != 0 { diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index bc0499f0..c514478d 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -364,7 +364,7 @@ func (h *Handler) generateImage(c *gin.Context) { return } if value := bytes.TrimSpace(request.StorageOptions); len(value) > 0 && !bytes.Equal(value, []byte("null")) { - writeOpenAIError(c, http.StatusBadRequest, "unsupported_parameter", "当前 Grok Web Provider 不支持 storage_options") + writeOpenAIError(c, http.StatusBadRequest, "unsupported_parameter", "当前兼容层暂不支持 storage_options") return } count := 1 @@ -507,7 +507,7 @@ func (h *Handler) editImage(c *gin.Context) { return } if value := bytes.TrimSpace(request.StorageOptions); len(value) > 0 && !bytes.Equal(value, []byte("null")) { - writeOpenAIError(c, http.StatusBadRequest, "unsupported_parameter", "当前 Grok Web Provider 不支持 storage_options") + writeOpenAIError(c, http.StatusBadRequest, "unsupported_parameter", "当前兼容层暂不支持 storage_options") return } model := strings.TrimSpace(request.Model) @@ -542,8 +542,8 @@ func (h *Handler) editImage(c *gin.Context) { writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "图片编辑缺少有效 model 或 prompt") return } - if count != 1 { - writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", "Grok Web 图片编辑当前仅支持 n=1") + if count < 1 || count > 10 { + writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", "n 必须在 1 到 10 之间") return } partialImages := 0 @@ -572,8 +572,8 @@ func (h *Handler) editImage(c *gin.Context) { if resolution == "" { resolution = "1k" } - if resolution != "1k" { - writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", "Grok Web 图片编辑当前仅支持 resolution=1k") + if resolution != "1k" && resolution != "2k" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", "resolution 必须是 1k 或 2k") return } clientKey, requestID, ok := requestIdentity(c) @@ -617,11 +617,11 @@ func (h *Handler) generateVideo(c *gin.Context) { return } if hasJSONValue(request.Output) { - writeOpenAIError(c, http.StatusBadRequest, "unsupported_parameter", "当前 Grok Web Provider 不支持 output.upload_url") + writeOpenAIError(c, http.StatusBadRequest, "unsupported_parameter", "当前兼容层暂不支持 output.upload_url") return } if hasJSONValue(request.StorageOptions) { - writeOpenAIError(c, http.StatusBadRequest, "unsupported_parameter", "当前 Grok Web Provider 不支持 storage_options") + writeOpenAIError(c, http.StatusBadRequest, "unsupported_parameter", "当前兼容层暂不支持 storage_options") return } duration, err := parseVideoDuration(request.Duration) diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index dc6dd8fc..666c15e8 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -475,24 +475,35 @@ func TestImageEditAcceptsOfficialJSONShape(t *testing.T) { } invalidResolution := httptest.NewRequest(http.MethodPost, "/v1/images/edits", strings.NewReader(`{ - "model":"grok-imagine-image-edit","prompt":"test","resolution":"2k", + "model":"grok-imagine-image-edit","prompt":"test","resolution":"4k", "image":{"url":"https://example.com/input.png"} }`)) invalidResolution.Header.Set("Content-Type", "application/json") invalidResolutionRecorder := httptest.NewRecorder() router.ServeHTTP(invalidResolutionRecorder, invalidResolution) - if invalidResolutionRecorder.Code != http.StatusBadRequest || !strings.Contains(invalidResolutionRecorder.Body.String(), "仅支持 resolution=1k") { + if invalidResolutionRecorder.Code != http.StatusBadRequest || !strings.Contains(invalidResolutionRecorder.Body.String(), "resolution 必须是 1k 或 2k") { t.Fatalf("invalid resolution status=%d body=%s", invalidResolutionRecorder.Code, invalidResolutionRecorder.Body.String()) } + validBatchCount := httptest.NewRequest(http.MethodPost, "/v1/images/edits", strings.NewReader(`{ + "model":"grok-imagine-image-quality","prompt":"test","n":2, + "image":{"url":"https://example.com/input.png"} + }`)) + validBatchCount.Header.Set("Content-Type", "application/json") + validBatchRecorder := httptest.NewRecorder() + router.ServeHTTP(validBatchRecorder, validBatchCount) + if validBatchRecorder.Code != http.StatusUnauthorized { + t.Fatalf("valid batch count status=%d body=%s", validBatchRecorder.Code, validBatchRecorder.Body.String()) + } + invalidCount := httptest.NewRequest(http.MethodPost, "/v1/images/edits", strings.NewReader(`{ - "model":"grok-imagine-image-edit","prompt":"test","n":2, + "model":"grok-imagine-image-quality","prompt":"test","n":11, "image":{"url":"https://example.com/input.png"} }`)) invalidCount.Header.Set("Content-Type", "application/json") invalidCountRecorder := httptest.NewRecorder() router.ServeHTTP(invalidCountRecorder, invalidCount) - if invalidCountRecorder.Code != http.StatusBadRequest || !strings.Contains(invalidCountRecorder.Body.String(), "仅支持 n=1") { + if invalidCountRecorder.Code != http.StatusBadRequest || !strings.Contains(invalidCountRecorder.Body.String(), "n 必须在 1 到 10 之间") { t.Fatalf("invalid count status=%d body=%s", invalidCountRecorder.Code, invalidCountRecorder.Body.String()) } diff --git a/backend/internal/transport/http/inference/model_list_test.go b/backend/internal/transport/http/inference/model_list_test.go index c357f4ab..6207c70b 100644 --- a/backend/internal/transport/http/inference/model_list_test.go +++ b/backend/internal/transport/http/inference/model_list_test.go @@ -19,8 +19,10 @@ func TestNewModelListItemsDeduplicatesSharedPublicName(t *testing.T) { {PublicID: "Build/grok-shared", Provider: account.ProviderBuild, CreatedAt: now}, {PublicID: "Console/grok-shared", Provider: account.ProviderConsole, CreatedAt: now.Add(time.Second)}, {PublicID: "Web/grok-chat-fast", Provider: account.ProviderWeb, CreatedAt: now}, + {PublicID: "Console/grok-imagine-image", Provider: account.ProviderConsole, Capability: modeldomain.CapabilityImage, CreatedAt: now}, + {PublicID: "Console/grok-imagine-image", Provider: account.ProviderConsole, Capability: modeldomain.CapabilityImageEdit, CreatedAt: now.Add(time.Second)}, }) - if len(items) != 2 || items[0].ID != "grok-shared" || items[1].ID != "grok-chat-fast" { + if len(items) != 3 || items[0].ID != "grok-shared" || items[1].ID != "grok-chat-fast" || items[2].ID != "grok-imagine-image" { t.Fatalf("model list = %#v", items) } } diff --git a/backend/internal/transport/http/model/handler.go b/backend/internal/transport/http/model/handler.go index 6a185281..6fc6060d 100644 --- a/backend/internal/transport/http/model/handler.go +++ b/backend/internal/transport/http/model/handler.go @@ -22,6 +22,7 @@ func NewHandler(service *modelapp.Service) *Handler { return &Handler{service: s func (h *Handler) Register(router *gin.RouterGroup) { router.GET("/models", h.list) + router.GET("/models/groups", h.listGroups) router.GET("/models/accounts", h.listAccounts) router.POST("/models", h.create) router.POST("/models/sync", h.sync) @@ -73,6 +74,12 @@ type modelResponse struct { LastSyncedAt *time.Time `json:"lastSyncedAt,omitempty"` } +type modelGroupResponse struct { + Key string `json:"key"` + Routes []modelResponse `json:"routes"` + EndpointCapabilities []string `json:"endpointCapabilities"` +} + type accountOptionResponse struct { ID uint64 `json:"id,string"` Name string `json:"name"` @@ -101,6 +108,27 @@ func (h *Handler) list(c *gin.Context) { response.Success(c, http.StatusOK, gin.H{"items": items, "page": page, "pageSize": pageSize, "total": total}) } +func (h *Handler) listGroups(c *gin.Context) { + page, pageSize := pagination(c) + values, total, err := h.service.ListGroups(c.Request.Context(), page, pageSize, c.Query("search"), modelapp.ListFilter{ + Provider: c.Query("provider"), Status: c.Query("status"), + Sort: repository.SortQuery{Field: c.Query("sortBy"), Direction: repository.SortDirection(c.Query("sortOrder"))}, + }) + if errors.Is(err, modelapp.ErrInvalidFilter) { + response.Error(c, http.StatusBadRequest, "invalidFilter", err.Error()) + return + } + if err != nil { + response.Error(c, http.StatusInternalServerError, "modelListFailed", "读取模型能力组失败") + return + } + items := make([]modelGroupResponse, 0, len(values)) + for _, value := range values { + items = append(items, newModelGroupResponse(value)) + } + response.Success(c, http.StatusOK, gin.H{"items": items, "page": page, "pageSize": pageSize, "total": total}) +} + func splitScopeQuery(values []string) []string { if len(values) == 0 { return nil @@ -271,7 +299,9 @@ func (h *Handler) writeServiceError(c *gin.Context, code string, err error) { func newModelResponse(value modeldomain.Route) modelResponse { manualBinding := len(value.BoundAccountIDs) > 0 - capabilityKnown := manualBinding || value.SyncedAccounts > 0 + // Console uses a provider-wide static catalog, so catalog support is known + // even when an account capability snapshot predates a newly shipped model. + capabilityKnown := manualBinding || value.SyncedAccounts > 0 || (value.Provider == account.ProviderConsole && (value.Origin == modeldomain.OriginCatalog || value.SupportedAccounts > 0)) available := value.TotalAccounts > 0 && (value.SupportedAccounts > 0 || (!manualBinding && value.SyncedAccounts < value.TotalAccounts)) accountIDs := make([]string, 0, len(value.BoundAccountIDs)) for _, id := range value.BoundAccountIDs { @@ -285,6 +315,16 @@ func newModelResponse(value modeldomain.Route) modelResponse { } } +func newModelGroupResponse(value modelapp.RouteGroup) modelGroupResponse { + routes := make([]modelResponse, 0, len(value.Routes)) + ids := make([]string, 0, len(value.Routes)) + for _, route := range value.Routes { + routes = append(routes, newModelResponse(route)) + ids = append(ids, strconv.FormatUint(route.ID, 10)) + } + return modelGroupResponse{Key: strings.Join(ids, ":"), Routes: routes, EndpointCapabilities: append([]string(nil), value.EndpointCapabilities...)} +} + func parseIDs(values []string) ([]uint64, error) { ids := make([]uint64, 0, len(values)) for _, value := range values { diff --git a/backend/internal/transport/http/model/handler_test.go b/backend/internal/transport/http/model/handler_test.go index abb6713f..37a789c2 100644 --- a/backend/internal/transport/http/model/handler_test.go +++ b/backend/internal/transport/http/model/handler_test.go @@ -3,6 +3,7 @@ package model import ( "testing" + modelapp "github.com/chenyme/grok2api/backend/internal/application/model" "github.com/chenyme/grok2api/backend/internal/domain/account" modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" ) @@ -17,6 +18,29 @@ func TestNewModelResponseSeparatesPublicAndUpstreamNames(t *testing.T) { } } +func TestNewModelGroupResponseKeepsAllMemberRoutes(t *testing.T) { + response := newModelGroupResponse(modelapp.RouteGroup{ + Routes: []modeldomain.Route{ + {ID: 10, PublicID: "Console/grok-imagine-image", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: modeldomain.CapabilityImage, Origin: modeldomain.OriginCatalog}, + {ID: 11, PublicID: "Console/grok-imagine-image", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: modeldomain.CapabilityImageEdit, Origin: modeldomain.OriginCatalog}, + }, + EndpointCapabilities: []string{"image", "image_edit"}, + }) + if response.Key != "10:11" || len(response.Routes) != 2 || len(response.EndpointCapabilities) != 2 { + t.Fatalf("model group response = %#v", response) + } +} + +func TestNewModelResponseKnowsStaticConsoleCapabilityWithoutAccountSync(t *testing.T) { + response := newModelResponse(modeldomain.Route{ + ID: 2, PublicID: "Console/grok-imagine-image", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", + Capability: modeldomain.CapabilityImageEdit, Enabled: true, SupportedAccounts: 20, TotalAccounts: 20, + }) + if !response.CapabilityKnown || !response.Available || response.BindingMode || response.SupportedAccounts != 20 { + t.Fatalf("static Console model response = %#v", response) + } +} + func TestParseOptionalBoolRejectsAmbiguousValues(t *testing.T) { for _, test := range []struct { input string diff --git a/frontend/src/entities/model/model-api.ts b/frontend/src/entities/model/model-api.ts index 049126c9..2303e683 100644 --- a/frontend/src/entities/model/model-api.ts +++ b/frontend/src/entities/model/model-api.ts @@ -1,9 +1,9 @@ -import type { ModelRouteDTO } from "@/entities/model/types"; +import type { ModelRouteDTO, ModelRouteGroupDTO } from "@/entities/model/types"; import { apiRequest, type PaginatedDTO } from "@/shared/api/client"; import { createObjectDecoder, createPaginatedDecoder, decodeBooleanResult, decodeCountResult, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isString } from "@/shared/api/decoder"; import type { SortOrder } from "@/shared/lib/table-sort"; -type ListModelsInput = { +export type ListModelsInput = { page: number; pageSize: number; search?: string; @@ -40,6 +40,12 @@ const decodeModelRoute = createObjectDecoder("model route", { syncedAccounts: isNumber, totalAccounts: isNumber, capabilityKnown: isBoolean, available: isBoolean, lastSyncedAt: isOptional(isString), }); const decodeModelPage = createPaginatedDecoder(modelRouteValidator); +const modelRouteGroupValidator = hasShape({ + key: isString, + routes: (value) => Array.isArray(value) && value.length > 0 && value.every(modelRouteValidator), + endpointCapabilities: isArrayOf(isOneOf("completions", "responses", "messages", "image", "image_edit", "video")), +}); +const decodeModelGroupPage = createPaginatedDecoder(modelRouteGroupValidator); const modelAccountValidator = hasShape({ id: isString, name: isString }); const decodeModelAccounts = createObjectDecoder<{ items: ModelAccountOptionDTO[] }>("model accounts", { items: isArrayOf(modelAccountValidator) }); @@ -58,6 +64,18 @@ export function listModels(input: ListModelsInput): Promise> { + const query = new URLSearchParams({ page: String(input.page), pageSize: String(input.pageSize) }); + if (input.search) query.set("search", input.search); + if (input.status) query.set("status", input.status); + if (input.provider) query.set("provider", input.provider); + if (input.sortBy && input.sortOrder) { + query.set("sortBy", input.sortBy); + query.set("sortOrder", input.sortOrder); + } + return apiRequest(`/api/admin/v1/models/groups?${query}`, {}, decodeModelGroupPage); +} + export function syncModels(): Promise<{ synced: number }> { return apiRequest("/api/admin/v1/models/sync", { method: "POST" }, decodeCountResult<{ synced: number }>("synced")); } diff --git a/frontend/src/entities/model/types.ts b/frontend/src/entities/model/types.ts index af4f497a..997d81d6 100644 --- a/frontend/src/entities/model/types.ts +++ b/frontend/src/entities/model/types.ts @@ -15,3 +15,11 @@ export type ModelRouteDTO = { available: boolean; lastSyncedAt?: string; }; + +export type ModelEndpointCapability = "completions" | "responses" | "messages" | "image" | "image_edit" | "video"; + +export type ModelRouteGroupDTO = { + key: string; + routes: ModelRouteDTO[]; + endpointCapabilities: ModelEndpointCapability[]; +}; diff --git a/frontend/src/features/accounts/account-quota.tsx b/frontend/src/features/accounts/account-quota.tsx index 4889453a..778c295f 100644 --- a/frontend/src/features/accounts/account-quota.tsx +++ b/frontend/src/features/accounts/account-quota.tsx @@ -105,9 +105,24 @@ const visibleWebQuotaModes = ["auto", "fast", "expert", "heavy"] as const; export function ConsoleQuota({ windows, locale }: { windows: NonNullable; locale: string }) { const { t } = useTranslation(); - const window = windows.find((value) => value.mode === "console") ?? windows[0]; - if (!window) return {t("accounts.quotaNotSynced")}; - return ; + if (windows.length === 0) return {t("accounts.quotaNotSynced")}; + const windowsByMode = new Map(windows.map((window) => [window.mode, window])); + const modes = [ + { mode: "console", label: t("creativeConsole.modes.chat") }, + { mode: "console_image", label: t("creativeConsole.modes.image") }, + { mode: "console_video", label: t("creativeConsole.modes.video") }, + ] as const; + return ( +
+ {modes.map(({ mode, label }) => { + const window = windowsByMode.get(mode); + if (!window) { + return
{label}-
; + } + return ; + })} +
+ ); } export function WebQuota({ windows, locale, tier }: { windows: NonNullable; locale: string; tier?: AccountDTO["webTier"] }) { @@ -157,7 +172,7 @@ function WeeklyWebQuota({ window, locale, t }: { window: WebQuotaWindow; locale: ); } -function WebQuotaMode({ mode, window, locale, compact = false }: { mode: string; window: WebQuotaWindow; locale: string; compact?: boolean }) { +function WebQuotaMode({ mode, window, locale, compact = false, recoveryProbe = false }: { mode: string; window: WebQuotaWindow; locale: string; compact?: boolean; recoveryProbe?: boolean }) { const { t } = useTranslation(); const used = Math.max(0, window.total - window.remaining); const percent = window.total > 0 ? Math.max(0, Math.min(100, used / window.total * 100)) : 0; @@ -169,7 +184,7 @@ function WebQuotaMode({ mode, window, locale, compact = false }: { mode: string;
-
{t("accounts.webModeQuotaRemaining", { mode, remaining: formatNumber(window.remaining, locale, 0) })}
{window.resetAt ? t("accounts.quotaResetAt", { time: formatDateTime(window.resetAt, locale) }) : t("accounts.quotaResetUnknown")}
+
{t("accounts.webModeQuotaRemaining", { mode, remaining: formatNumber(window.remaining, locale, 0) })}
{window.resetAt ? recoveryProbe ? t("console.recoveryProbeAt", { time: formatDateTime(window.resetAt, locale) }) : t("accounts.quotaResetAt", { time: formatDateTime(window.resetAt, locale) }) : t("accounts.quotaResetUnknown")}
); } diff --git a/frontend/src/features/audits/request-audits-api.ts b/frontend/src/features/audits/request-audits-api.ts index 7943fa98..baec6447 100644 --- a/frontend/src/features/audits/request-audits-api.ts +++ b/frontend/src/features/audits/request-audits-api.ts @@ -38,7 +38,7 @@ export type AuditDTO = { accountName?: string; egressNodeId?: string; egressNodeName?: string; - egressScope?: "grok_build" | "grok_web" | "grok_console" | "grok_web_asset"; + egressScope?: "grok_build" | "grok_web" | "grok_console" | "grok_web_asset" | "grok_console_asset"; egressMode?: "direct" | "proxy"; statusCode: number; streaming: boolean; @@ -143,7 +143,7 @@ const auditValidator = hasShape({ operation: isOneOf("responses", "compaction", "chat", "messages", "image", "image_edit", "video"), usageSource: isOneOf("upstream", "estimated", "none"), accountId: isOptional(isString), accountName: isOptional(isString), egressNodeId: isOptional(isString), egressNodeName: isOptional(isString), - egressScope: isOptional(isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset")), egressMode: isOptional(isOneOf("direct", "proxy")), + egressScope: isOptional(isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset")), egressMode: isOptional(isOneOf("direct", "proxy")), statusCode: isNumber, streaming: isBoolean, mediaInputImages: isNumber, mediaOutputImages: isNumber, mediaOutputSeconds: isNumber, inputTokens: isNumber, cachedInputTokens: isNumber, outputTokens: isNumber, reasoningTokens: isNumber, totalTokens: isNumber, diff --git a/frontend/src/features/models/models-page.tsx b/frontend/src/features/models/models-page.tsx index ad6777d1..8895513b 100644 --- a/frontend/src/features/models/models-page.tsx +++ b/frontend/src/features/models/models-page.tsx @@ -1,7 +1,8 @@ import { zodResolver } from "@hookform/resolvers/zod"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { MoreHorizontal, Pencil, Plus, RefreshCw, Search, Trash2 } from "lucide-react"; -import { useState } from "react"; +import type { TFunction } from "i18next"; +import { Clapperboard, Image as ImageIcon, MessagesSquare, MessageSquareText, MoreHorizontal, Paintbrush, Pencil, Plus, RefreshCw, Search, SquareTerminal, Trash2 } from "lucide-react"; +import { useMemo, useState } from "react"; import { useForm, useWatch } from "react-hook-form"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; @@ -19,8 +20,9 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@ import { Switch } from "@/components/ui/switch"; import { Spinner } from "@/components/ui/spinner"; import { Table, TableActionCell, TableActionHead, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; -import { createModel, deleteModel, deleteModels, listModelAccountOptions, listModels, syncModels, updateModel, updateModelsEnabled } from "@/entities/model/model-api"; -import type { ModelRouteDTO } from "@/entities/model/types"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { createModel, deleteModel, deleteModels, listModelAccountOptions, listModelGroups, syncModels, updateModel, updateModelsEnabled } from "@/entities/model/model-api"; +import type { ModelEndpointCapability, ModelRouteDTO, ModelRouteGroupDTO } from "@/entities/model/types"; import { EmptyState, ErrorState, TableLoadingRow } from "@/shared/components/data-state"; import { DataTableShell } from "@/shared/components/data-table-shell"; import { DataTableFilters } from "@/shared/components/data-table-filters"; @@ -43,7 +45,7 @@ export function ModelsPage() { const [sort, setSort] = useState({ field: "", order: "asc" }); const [selected, setSelected] = useState>(() => new Set()); const [editing, setEditing] = useState(null); - const [deleting, setDeleting] = useState(null); + const [deleting, setDeleting] = useState(null); const [batchDeleteOpen, setBatchDeleteOpen] = useState(false); const [accountSearch, setAccountSearch] = useState(""); const debouncedSearch = useDebouncedValue(search); @@ -68,8 +70,8 @@ export function ModelsPage() { const selectedAccountIDs = useWatch({ control: form.control, name: "accountIds" }); const modelsQuery = useQuery({ - queryKey: ["models", page, pageSize, debouncedSearch, statusFilter, providerFilter, sort.field, sort.order], - queryFn: () => listModels({ page, pageSize, search: debouncedSearch, status: statusFilter, provider: providerFilter, sortBy: sort.field || undefined, sortOrder: sort.field ? sort.order : undefined }), + queryKey: ["models", "grouped", page, pageSize, debouncedSearch, statusFilter, providerFilter, sort.field, sort.order], + queryFn: () => listModelGroups({ page, pageSize, search: debouncedSearch, status: statusFilter, provider: providerFilter, sortBy: sort.field || undefined, sortOrder: sort.field ? sort.order : undefined }), }); const accountOptionsQuery = useQuery({ @@ -86,6 +88,7 @@ export function ModelsPage() { return updateModel(editing.id, { publicId: input.publicId, enabled: input.enabled, accountIds: input.accountIds }); }, onSuccess: () => { + setSelected(new Set()); void queryClient.invalidateQueries({ queryKey: ["models"] }); setEditing(null); toast.success(t(editing === "new" ? "models.created" : "models.updated")); @@ -94,10 +97,15 @@ export function ModelsPage() { }); const deleteMutation = useMutation({ - mutationFn: (id: string) => deleteModel(id), + mutationFn: async (routes: ModelRouteDTO[]) => { + if (routes.length === 1) await deleteModel(routes[0].id); + else await deleteModels(routes.map((route) => route.id)); + }, onSuccess: () => { + setSelected(new Set()); void queryClient.invalidateQueries({ queryKey: ["models"] }); setDeleting(null); + setPage(1); toast.success(t("models.deleted")); }, onError: showError, @@ -108,6 +116,7 @@ export function ModelsPage() { onSuccess: (result) => { setSelected(new Set()); setBatchDeleteOpen(false); + setPage(1); void queryClient.invalidateQueries({ queryKey: ["models"] }); toast.success(t("models.batchDeleted", { count: result.deleted })); }, @@ -118,6 +127,7 @@ export function ModelsPage() { mutationFn: (enabled: boolean) => updateModelsEnabled([...selected], enabled), onSuccess: () => { setSelected(new Set()); + setPage(1); void queryClient.invalidateQueries({ queryKey: ["models"] }); toast.success(t("models.batchUpdated")); }, @@ -127,6 +137,8 @@ export function ModelsPage() { const syncMutation = useMutation({ mutationFn: syncModels, onSuccess: (result) => { + setSelected(new Set()); + setPage(1); void queryClient.invalidateQueries({ queryKey: ["models"] }); toast.success(t("models.synced", { count: result.synced })); }, @@ -168,10 +180,11 @@ export function ModelsPage() { ? accountOptions.filter((account) => account.name.toLocaleLowerCase().includes(normalizedAccountSearch) || account.id.includes(normalizedAccountSearch)) : accountOptions; - const result = modelsQuery.data; - const pageIDs = result?.items.map((model) => model.id) ?? []; + const result = useMemo(() => modelsQuery.data ? { ...modelsQuery.data, items: modelsQuery.data.items.map((group) => newModelRouteGroup(group, t)) } : undefined, [modelsQuery.data, t]); + const pageIDs = result?.items.flatMap((group) => group.routes.map((route) => route.id)) ?? []; const selectedOnPage = pageIDs.filter((id) => selected.has(id)); const allPageSelected = pageIDs.length > 0 && selectedOnPage.length === pageIDs.length; + const selectedGroupCount = result?.items.filter((group) => group.routes.some((route) => selected.has(route.id))).length ?? 0; function togglePage(checked: boolean): void { setSelected((current) => { @@ -184,11 +197,13 @@ export function ModelsPage() { }); } - function toggleModel(id: string, checked: boolean): void { + function toggleModelGroup(routes: ModelRouteDTO[], checked: boolean): void { setSelected((current) => { const next = new Set(current); - if (checked) next.add(id); - else next.delete(id); + for (const route of routes) { + if (checked) next.add(route.id); + else next.delete(route.id); + } return next; }); } @@ -196,6 +211,7 @@ export function ModelsPage() { function changeSort(field: string, initialOrder: SortOrder): void { setSort((current) => nextTableSort(current, field, initialOrder)); setPage(1); + setSelected(new Set()); } return ( @@ -211,15 +227,15 @@ export function ModelsPage() {
- { setSearch(event.target.value); setPage(1); }} placeholder={t("models.search")} aria-label={t("models.search")} /> + { setSearch(event.target.value); setPage(1); setSelected(new Set()); }} placeholder={t("models.search")} aria-label={t("models.search")} />
{ setProviderFilter(value as ModelRouteDTO["provider"] | ""); setPage(1); }, options: [ + { id: "provider", label: t("models.provider"), value: providerFilter, onChange: (value) => { setProviderFilter(value as ModelRouteDTO["provider"] | ""); setPage(1); setSelected(new Set()); }, options: [ { value: "grok_build", label: t("models.providerGrokBuild") }, { value: "grok_web", label: t("models.providerGrokWeb") }, { value: "grok_console", label: t("console.name") }, ] }, - { id: "status", label: t("models.status"), value: statusFilter, onChange: (value) => { setStatusFilter(value); setPage(1); }, options: [ + { id: "status", label: t("models.status"), value: statusFilter, onChange: (value) => { setStatusFilter(value); setPage(1); setSelected(new Set()); }, options: [ { value: "enabled", label: t("common.enabled") }, { value: "disabled", label: t("common.disabled") }, ] }, @@ -228,7 +244,7 @@ export function ModelsPage() {
{selected.size > 0 ? ( <> - {t("common.selectedCount", { count: selected.size })} + {t("common.selectedCount", { count: selectedGroupCount })} @@ -242,15 +258,16 @@ export function ModelsPage() {
)} - footer={result && result.total > 0 ? { setPageSize(value); setPage(1); }} /> : undefined} + footer={result && result.total > 0 ? { setPage(value); setSelected(new Set()); }} onPageSizeChange={(value) => { setPageSize(value); setPage(1); setSelected(new Set()); }} /> : undefined} > {modelsQuery.isError ? void modelsQuery.refetch()} /> : null} - {result && result.items.length === 0 ? : null} + {!modelsQuery.isPending && !modelsQuery.isError && result?.items.length === 0 ? : null} {modelsQuery.isPending || (result && result.items.length > 0) ? ( - +
+ @@ -263,6 +280,7 @@ export function ModelsPage() { 0 ? "indeterminate" : false} onCheckedChange={(checked) => togglePage(checked === true)} aria-label={t("common.selectPage")} />{t("models.model")}{t("models.upstream")} + {t("models.capability")}{t("models.status")}{t("models.provider")}{t("models.accountSupport")} @@ -271,23 +289,26 @@ export function ModelsPage() { {modelsQuery.isPending ? ( - + ) : ( - ( - - toggleModel(model.id, checked === true)} aria-label={t("common.selectItem", { name: model.publicId })} /> + { + const selectedRoutes = model.routes.filter((route) => selected.has(route.id)).length; + return ( + 0 ? "selected" : undefined}> + 0 ? "indeterminate" : false} onCheckedChange={(checked) => toggleModelGroup(model.routes, checked === true)} aria-label={t("common.selectItem", { name: model.publicId })} /> {model.publicId} {model.upstreamModel} - {model.enabled ? {t("common.enabled")} : {t("common.disabled")}} + + {model.enabledState === "enabled" ? {t("common.enabled")} : model.enabledState === "disabled" ? {t("common.disabled")} : {t("models.partiallyEnabled")}} -
- 0 ? "text-emerald-600 dark:text-emerald-400" : "text-muted-foreground")}>{model.supportedAccounts}/ {model.totalAccounts} - {model.bindingMode ? {t("models.boundAccounts")} : null} +
+ 0 ? "text-emerald-600 dark:text-emerald-400" : "text-muted-foreground")}>{model.supportedLabel}/ {model.totalLabel} + {t(model.bindingState === "bound" ? "models.boundAccounts" : model.bindingState === "automatic" ? "models.automaticAccounts" : "models.mixedAccounts")}
{formatDateTime(model.lastSyncedAt, i18n.language)} @@ -295,13 +316,14 @@ export function ModelsPage() { - beginEdit(model)}>{t("common.edit")} + {model.routes.map((route) => beginEdit(route)}>{model.routes.length === 1 ? t("common.edit") : t("models.editCapability", { capability: capabilityLabel(route.capability, t) })})} setDeleting(model)}>{t("common.delete")} - )} /> + ); + }} /> )}
) : null} @@ -389,14 +411,14 @@ export function ModelsPage() { !open && setDeleting(null)}> - {t("models.deleteTitle")}{t("models.deleteDescription", { name: deleting?.publicId ?? "" })} - {t("common.cancel")} deleting && deleteMutation.mutate(deleting.id)}>{deleteMutation.isPending ? : null}{t("common.delete")} + {t("models.deleteTitle")}{t(deleting && deleting.routes.length > 1 ? "models.deleteGroupDescription" : "models.deleteDescription", { name: deleting?.publicId ?? "", count: deleting?.routes.length ?? 0 })} + {t("common.cancel")} deleting && deleteMutation.mutate(deleting.routes)}>{deleteMutation.isPending ? : null}{t("common.delete")} - {t("models.batchDeleteTitle", { count: selected.size })}{t("models.batchDeleteDescription")} + {t("models.batchDeleteTitle", { count: selectedGroupCount })}{t("models.batchDeleteDescription")} {t("common.cancel")} batchDeleteMutation.mutate()}>{batchDeleteMutation.isPending ? : null}{t("common.delete")} @@ -415,3 +437,101 @@ function ModelProvider({ provider }: { provider: ModelRouteDTO["provider"] }) { ); } + +function ModelCapabilities({ capabilities }: { capabilities: ModelDisplayCapability[] }) { + const { t } = useTranslation(); + return ( + + {capabilities.map((capability) => { + const metadata = endpointCapabilityMetadata[capability]; + const Icon = metadata.icon; + const label = displayCapabilityLabel(capability, t); + return ( + + + + + + + +
{label}
+ {metadata.method} {metadata.path} +
+
+ ); + })} +
+ ); +} + +type ModelDisplayCapability = ModelEndpointCapability; + +const endpointCapabilityMetadata = { + completions: { icon: MessageSquareText, method: "POST", path: "/v1/chat/completions", color: "text-sky-600 dark:text-sky-400" }, + responses: { icon: SquareTerminal, method: "POST", path: "/v1/responses", color: "text-violet-600 dark:text-violet-400" }, + messages: { icon: MessagesSquare, method: "POST", path: "/v1/messages", color: "text-orange-600 dark:text-orange-400" }, + image: { icon: ImageIcon, method: "POST", path: "/v1/images/generations", color: "text-emerald-600 dark:text-emerald-400" }, + image_edit: { icon: Paintbrush, method: "POST", path: "/v1/images/edits", color: "text-amber-700 dark:text-amber-400" }, + video: { icon: Clapperboard, method: "POST", path: "/v1/videos/generations", color: "text-rose-600 dark:text-rose-400" }, +} as const; + +type ModelRouteGroup = { + key: string; + routes: ModelRouteDTO[]; + publicId: string; + provider: ModelRouteDTO["provider"]; + upstreamModel: string; + capabilities: ModelDisplayCapability[]; + enabledState: "enabled" | "disabled" | "mixed"; + bindingState: "automatic" | "bound" | "mixed"; + supportedMax: number; + supportedLabel: string; + totalLabel: string; + supportTitle: string; + lastSyncedAt?: string; +}; + +function newModelRouteGroup(value: ModelRouteGroupDTO, t: TFunction): ModelRouteGroup { + const routes = value.routes; + const first = routes[0]; + const enabledCount = routes.filter((route) => route.enabled).length; + const boundCount = routes.filter((route) => route.bindingMode).length; + const supportedValues = routes.map((route) => route.supportedAccounts); + const totalValues = routes.map((route) => route.totalAccounts); + const supportedMin = Math.min(...supportedValues); + const supportedMax = Math.max(...supportedValues); + const totalMin = Math.min(...totalValues); + const totalMax = Math.max(...totalValues); + const syncedTimes = routes.map((route) => route.lastSyncedAt).filter((value): value is string => Boolean(value)).sort(); + return { + key: value.key, + routes, + publicId: first.publicId, + provider: first.provider, + upstreamModel: first.upstreamModel, + capabilities: value.endpointCapabilities, + enabledState: enabledCount === routes.length ? "enabled" : enabledCount === 0 ? "disabled" : "mixed", + bindingState: boundCount === routes.length ? "bound" : boundCount === 0 ? "automatic" : "mixed", + supportedMax, + supportedLabel: supportedMin === supportedMax ? String(supportedMax) : `${supportedMin}–${supportedMax}`, + totalLabel: totalMin === totalMax ? String(totalMax) : `${totalMin}–${totalMax}`, + supportTitle: routes.map((route) => `${capabilityLabel(route.capability, t)}: ${t("models.supportSummary", { supported: route.supportedAccounts, total: route.totalAccounts })}`).join("\n"), + lastSyncedAt: syncedTimes.at(-1), + }; +} + +function capabilityLabel(capability: ModelRouteDTO["capability"], t: TFunction): string { + if (capability === "responses" || capability === "chat") return t("models.capabilityConversation"); + return displayCapabilityLabel(capability, t); +} + +function displayCapabilityLabel(capability: ModelDisplayCapability, t: TFunction): string { + return { + completions: t("models.capabilityCompletions"), + responses: t("models.capabilityResponses"), + messages: t("models.capabilityMessages"), + image: t("models.capabilityImage"), + image_edit: t("models.capabilityImageEdit"), + video: t("models.capabilityVideo"), + }[capability]; +} diff --git a/frontend/src/features/settings/egress-nodes.tsx b/frontend/src/features/settings/egress-nodes.tsx index 447a5f66..157ce75f 100644 --- a/frontend/src/features/settings/egress-nodes.tsx +++ b/frontend/src/features/settings/egress-nodes.tsx @@ -168,7 +168,7 @@ export function EgressNodes({ title, clearanceMode }: { title: string; clearance ...form, scope, userAgent: scope === "grok_build" ? "" : (form.userAgent === "" || form.userAgent === previousDefault ? nextDefault : form.userAgent), - cloudflareCookies: scope === "grok_build" ? "" : form.cloudflareCookies, + cloudflareCookies: scope === "grok_build" || scope === "grok_console_asset" ? "" : form.cloudflareCookies, }); } @@ -176,6 +176,7 @@ export function EgressNodes({ title, clearanceMode }: { title: string; clearance if (scope === "grok_build") return t("settings.egress.scopeBuild"); if (scope === "grok_console") return t("console.name"); if (scope === "grok_web_asset") return t("settings.egress.scopeWebAsset"); + if (scope === "grok_console_asset") return t("settings.egress.scopeConsoleAsset"); return t("settings.egress.scopeWeb"); } @@ -235,6 +236,7 @@ export function EgressNodes({ title, clearanceMode }: { title: string; clearance { value: "grok_web", label: scopeLabel("grok_web") }, { value: "grok_console", label: scopeLabel("grok_console") }, { value: "grok_web_asset", label: scopeLabel("grok_web_asset") }, + { value: "grok_console_asset", label: scopeLabel("grok_console_asset") }, ] }, { id: "enabled", label: t("settings.egress.enabled"), value: enabledFilter, onChange: (value) => { setEnabledFilter(value); setPage(1); setSelected(new Map()); }, options: [ { value: "enabled", label: t("common.enable") }, @@ -391,10 +393,11 @@ export function EgressNodes({ title, clearanceMode }: { title: string; clearance {t("settings.egress.scopeWeb")} {t("console.name")} {t("settings.egress.scopeWebAsset")} + {t("settings.egress.scopeConsoleAsset")} - {form.scope !== "grok_build" ? ( + {form.scope !== "grok_build" && form.scope !== "grok_console_asset" ? (
{t("settings.egress.clearance")} @@ -415,12 +418,12 @@ export function EgressNodes({ title, clearanceMode }: { title: string; clearance
setForm({ ...form, proxyPool })} />
- {form.scope !== "grok_build" && clearanceMode === "manual" ? ( + {form.scope !== "grok_build" && (clearanceMode === "manual" || form.scope === "grok_console_asset") ? ( setForm({ ...form, userAgent: event.target.value })} /> ) : null} - {form.scope !== "grok_build" && clearanceMode === "manual" ? ( + {form.scope !== "grok_build" && form.scope !== "grok_console_asset" && clearanceMode === "manual" ? ( setForm({ ...form, cloudflareCookies: event.target.value })} /> @@ -447,6 +450,7 @@ export function EgressNodes({ title, clearanceMode }: { title: string; clearance {t("settings.egress.scopeWeb")} {t("console.name")} {t("settings.egress.scopeWebAsset")} + {t("settings.egress.scopeConsoleAsset")} diff --git a/frontend/src/features/settings/egress-operations.tsx b/frontend/src/features/settings/egress-operations.tsx index 1f1c916b..6e0ada7e 100644 --- a/frontend/src/features/settings/egress-operations.tsx +++ b/frontend/src/features/settings/egress-operations.tsx @@ -49,18 +49,19 @@ const emptySource: SourceForm = { // 15-second ceiling. Keeping a request to 32 nodes leaves enough headroom for // the admin HTTP timeout. const egressProbeBatchSize = 32; -const fallbackScopes: EgressScope[] = ["grok_build", "grok_web", "grok_console", "grok_web_asset"]; +const fallbackScopes: EgressScope[] = ["grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset"]; const fallbackDescriptionKeys: Record = { grok_build: "settings.egress.fallbackBuildHelp", grok_web: "settings.egress.fallbackWebHelp", grok_console: "settings.egress.fallbackConsoleHelp", grok_web_asset: "settings.egress.fallbackWebAssetHelp", + grok_console_asset: "settings.egress.fallbackConsoleAssetHelp", }; function defaultFallbacks(): Record { return { grok_build: { mode: "none" }, grok_web: { mode: "none" }, - grok_console: { mode: "none" }, grok_web_asset: { mode: "none" }, + grok_console: { mode: "none" }, grok_web_asset: { mode: "none" }, grok_console_asset: { mode: "none" }, }; } @@ -83,6 +84,7 @@ function operationsFormFrom(value?: EgressOperationsConfigDTO): Omit
@@ -376,11 +379,13 @@ function nodeCooling(node: EgressNodeDTO): boolean { } function supportsFallbackScope(nodeScope: EgressScope, requestScope: EgressScope): boolean { - return nodeScope === requestScope || ((requestScope === "grok_console" || requestScope === "grok_web_asset") && nodeScope === "grok_web"); + if (nodeScope === requestScope) return true; + if (requestScope === "grok_console" || requestScope === "grok_web_asset") return nodeScope === "grok_web"; + return requestScope === "grok_console_asset" && (nodeScope === "grok_console" || nodeScope === "grok_web"); } function ScopeSelect({ value, onChange, scopeLabel }: { value: EgressScope; onChange: (value: EgressScope) => void; scopeLabel: (scope: EgressScope) => string }) { - return ; + return ; } function OperationSectionHeader({ title, help, children }: { title: string; help: string; children?: ReactNode }) { diff --git a/frontend/src/features/settings/settings-api.ts b/frontend/src/features/settings/settings-api.ts index 4be90813..f2b648d9 100644 --- a/frontend/src/features/settings/settings-api.ts +++ b/frontend/src/features/settings/settings-api.ts @@ -52,7 +52,7 @@ export type EgressNodeInput = { accountCapacity: number; clearProxyURL?: boolean; userAgent: string; cloudflareCookies?: string; clearCookies?: boolean; }; -export type EgressScope = "grok_build" | "grok_web" | "grok_console" | "grok_web_asset"; +export type EgressScope = "grok_build" | "grok_web" | "grok_console" | "grok_web_asset" | "grok_console_asset"; export type EgressFallbackMode = "none" | "direct" | "fixed"; export type EgressFallbackConfigDTO = { mode: EgressFallbackMode; nodeId?: string }; export type EgressNodeListDTO = { @@ -187,7 +187,7 @@ const withEgressNodeProbeDefaults = (value: EgressNodeWireDTO): EgressNodeDTO => ipv6Probe: value.ipv6Probe ?? unknownEgressIPProbe(), }); const egressNodeValidator = hasShape({ - id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset"), enabled: isBoolean, + id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset"), enabled: isBoolean, proxyConfigured: isBoolean, userAgent: isString, cookieConfigured: isBoolean, accountBoundProxy: isBoolean, proxyPool: isBoolean, health: isNumber, failureCount: isNumber, sourceId: isOptional(isString), accountCapacity: isNumber, assignedAccountCount: isNumber, probeStatus: isOneOf("unknown", "healthy", "unhealthy"), lastProbedAt: isOptional(isString), probeLatencyMs: isNumber, exitIp: isOptional(isString), probeError: isOptional(isString), probeProvider: isOptional(isOneOf("ipinfo", "cloudflare")), @@ -195,7 +195,7 @@ const egressNodeValidator = hasShape({ cooldownUntil: isOptional(isString), lastError: isOptional(isString), }); const decodeEgressNodeRaw = createObjectDecoder("egress node", { - id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset"), enabled: isBoolean, + id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset"), enabled: isBoolean, proxyConfigured: isBoolean, userAgent: isString, cookieConfigured: isBoolean, accountBoundProxy: isBoolean, proxyPool: isBoolean, health: isNumber, failureCount: isNumber, sourceId: isOptional(isString), accountCapacity: isNumber, assignedAccountCount: isNumber, probeStatus: isOneOf("unknown", "healthy", "unhealthy"), lastProbedAt: isOptional(isString), probeLatencyMs: isNumber, exitIp: isOptional(isString), probeError: isOptional(isString), probeProvider: isOptional(isOneOf("ipinfo", "cloudflare")), @@ -208,14 +208,14 @@ type EgressNodeListWireDTO = { page?: number; pageSize?: number; total?: number; - defaultUserAgents: Record; + defaultUserAgents: Omit, "grok_console_asset"> & { grok_console_asset?: string }; }; const decodeEgressNodeListRaw = createObjectDecoder("egress node list", { items: isArrayOf(egressNodeValidator), page: isOptional(isNumber), pageSize: isOptional(isNumber), total: isOptional(isNumber), - defaultUserAgents: hasShape({ grok_build: isString, grok_web: isString, grok_console: isString, grok_web_asset: isString }), + defaultUserAgents: hasShape({ grok_build: isString, grok_web: isString, grok_console: isString, grok_web_asset: isString, grok_console_asset: isOptional(isString) }), }); const decodeEgressNodeList = (value: unknown): EgressNodeListDTO => { const decoded = decodeEgressNodeListRaw(value); @@ -225,15 +225,19 @@ const decodeEgressNodeList = (value: unknown): EgressNodeListDTO => { page: decoded.page ?? 1, pageSize: decoded.pageSize ?? Math.max(20, decoded.items.length), total: decoded.total ?? decoded.items.length, + defaultUserAgents: { + ...decoded.defaultUserAgents, + grok_console_asset: decoded.defaultUserAgents.grok_console_asset ?? decoded.defaultUserAgents.grok_console, + }, }; }; const egressSourceValidator = hasShape({ - id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset"), enabled: isBoolean, urlConfigured: isBoolean, + id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset"), enabled: isBoolean, urlConfigured: isBoolean, refreshIntervalSeconds: isNumber, defaultAccountCapacity: isNumber, lastSyncedAt: isOptional(isString), nextSyncAt: isOptional(isString), lastSyncImported: isNumber, lastSyncError: isOptional(isString), }); const decodeEgressSource = createObjectDecoder("egress source", { - id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset"), enabled: isBoolean, urlConfigured: isBoolean, + id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset"), enabled: isBoolean, urlConfigured: isBoolean, refreshIntervalSeconds: isNumber, defaultAccountCapacity: isNumber, lastSyncedAt: isOptional(isString), nextSyncAt: isOptional(isString), lastSyncImported: isNumber, lastSyncError: isOptional(isString), }); diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 49a70bce..a8fdffbc 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -79,7 +79,7 @@ const resources = { name: "Grok Console", type: "Console", accountsDescription: "分别管理 Grok Build OAuth、Grok Web SSO 与 Grok Console SSO 号池、健康状态、并发和额度。", - egressDescription: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源作用域独立管理代理与健康状态。代理地址和 Cloudflare Cookie 仅写入。", + egressDescription: "节点按 Grok Build、Grok Web、Grok Console、Web 资源或 Console 资源作用域独立管理代理与健康状态。代理地址和 Cloudflare Cookie 仅写入。", egressDialogDescription: "配置节点作用域、代理地址和浏览器身份。", syncAllDescription: "将同步所有已启用 Grok Console 账号的额度状态。", importFile: "导入账号文件", @@ -89,6 +89,7 @@ const resources = { availableBreakdown: "Build {{build}} · Web {{web}} · Console {{console}} 可用", baseURL: "上游地址", chatTimeout: "聊天超时", + recoveryProbeAt: "下次主动恢复探测 {{time}}", }, accountCredential: { label: "凭据续期", @@ -1214,7 +1215,7 @@ const resources = { name: "Grok Console", type: "Console", accountsDescription: "Manage separate Grok Build OAuth, Grok Web SSO, and Grok Console SSO pools, including health, concurrency, and quotas.", - egressDescription: "Manage proxy and health independently for Grok Build, Grok Web, Grok Console, and Web asset scopes. Proxy URLs and Cloudflare cookies are write-only.", + egressDescription: "Manage proxy and health independently for Grok Build, Grok Web, Grok Console, Web assets, and Console assets. Proxy URLs and Cloudflare cookies are write-only.", egressDialogDescription: "Configure the node scope, proxy address, and browser identity.", syncAllDescription: "Sync quota state for every enabled Grok Console account.", importFile: "Import account files", @@ -1224,6 +1225,7 @@ const resources = { availableBreakdown: "Build {{build}} · Web {{web}} · Console {{console}} available", baseURL: "Upstream URL", chatTimeout: "Chat timeout", + recoveryProbeAt: "Next active recovery probe {{time}}", }, accountCredential: { label: "Credential renewal", @@ -1668,9 +1670,45 @@ const resources = { }, } as const; +Object.assign(resources["zh-CN"].translation.models as unknown as Record, { + capability: "接口能力", + capabilityConversation: "对话", + capabilityCompletions: "Completions", + capabilityResponses: "Responses", + capabilityMessages: "Messages", + capabilityImage: "Image", + capabilityImageEdit: "Image Edit", + capabilityVideo: "Video", + automaticAccounts: "自动账号池", + mixedAccounts: "混合账号池", + partiallyEnabled: "部分启用", + editCapability: "编辑 {{capability}}", + deleteGroupDescription: "这将删除 {{name}} 的全部 {{count}} 项接口能力及其客户端密钥权限。后续目录同步可能重新创建仍受上游支持的能力。", + bindAccountsDescription: "开启后仅通过指定账号路由;关闭后由对应 Provider 的可用账号池自动调度。Console 内置模型无需逐账号硬绑定。", +}); +Object.assign(resources.en.translation.models as unknown as Record, { + capability: "Endpoint capability", + capabilityConversation: "Conversation", + capabilityCompletions: "Completions", + capabilityResponses: "Responses", + capabilityMessages: "Messages", + capabilityImage: "Image", + capabilityImageEdit: "Image Edit", + capabilityVideo: "Video", + automaticAccounts: "Automatic pool", + mixedAccounts: "Mixed account pools", + partiallyEnabled: "Partially enabled", + editCapability: "Edit {{capability}}", + deleteGroupDescription: "This removes all {{count}} endpoint capabilities for {{name}} and their client-key permissions. A later catalog sync may recreate capabilities that the upstream still supports.", + bindAccountsDescription: "When enabled, route only through the selected accounts. Otherwise, schedule from the provider's eligible account pool automatically. Built-in Console models do not require per-account bindings.", +}); + // Kept separate from the legacy one-line settings resources so proxy // operations can evolve without making that catalog harder to review. Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Record, { + description: "节点按 Grok Build、Grok Web、Grok Console、Web 资源和 Console 资源独立管理代理与健康状态。Console 资源节点仅使用代理与 User-Agent,不发送账号或 Cloudflare Cookie。代理地址和 Cookie 仅写入。", + dialogDescription: "配置节点作用域、代理地址和浏览器身份;Console 资源节点用于匿名媒体下载,不使用 Clearance Cookie。", + scopeConsoleAsset: "Grok Console(仅资源)", health: "请求健康", healthHelp: "由真实 Grok 请求的成功、连接失败和反爬拒绝累计得出,与连通探测独立。", probe: "连通探测", @@ -1680,6 +1718,9 @@ Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Recor probeProviderHelp: "选择 IPv4 与 IPv6 连通探测使用的固定服务。Cloudflare 为默认服务,IPinfo 可手动切换。", }); Object.assign(resources.en.translation.settings.egress as unknown as Record, { + description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, Web assets, and Console assets. Console asset nodes use only the proxy and User-Agent and never send account or Cloudflare cookies. Proxy URLs and cookies are write-only.", + dialogDescription: "Configure the node scope, proxy address, and browser identity. Console asset nodes are for anonymous media downloads and do not use clearance cookies.", + scopeConsoleAsset: "Grok Console (assets only)", accounts: "Bound", health: "Request health", healthHelp: "Accumulated from real Grok request successes, transport failures, and anti-bot rejections; independent of the connectivity probe.", addManually: "Form entry", probe: "Connectivity probe", probeHelp: "The latest independent IPv4 and IPv6 checks through the provider recorded with each result. This only confirms access to the IP echo endpoint; it does not guarantee Grok upstream availability or represent real request health.", probeLatency: "Probe latency: {{latency}} ms", probeProvider: "IP echo service", probeProviderHelp: "Choose the fixed service used for IPv4 and IPv6 connectivity checks. Cloudflare is the default and IPinfo remains selectable.", healthy: "Healthy", unhealthy: "Unhealthy", notTested: "Not tested", test: "Test proxy", testedOne: "Proxy test completed", @@ -1706,6 +1747,7 @@ Object.assign(resources.en.translation.settings.egress as unknown as Record