diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 00000000..ae37d740 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,118 @@ +name: Bug 报告 +description: 报告可稳定复现的功能、兼容性或部署问题。 +title: "[Bug]: " +labels: + - bug +body: + - type: markdown + attributes: + value: | + 感谢反馈问题。请尽量提供最小复现步骤和经过脱敏的日志、请求或响应。 + + 请勿提交 Access Token、Refresh Token、Cookie、API Key、账号密码或其他敏感信息。安全漏洞请不要通过公开 Issue 披露。 + + - type: dropdown + id: area + attributes: + label: 问题模块 + description: 请选择问题主要出现在哪个模块。 + options: + - OpenAI API 兼容层(Responses / Chat Completions) + - 模型同步、映射、路由与定价 + - 账号、Provider、OAuth 与凭据 + - 额度、计费与请求审计 + - 图片、视频与媒体处理 + - 管理端前端界面 + - SQLite / PostgreSQL 数据库 + - Docker、配置、部署与网络出口 + - 其他 + validations: + required: true + + - type: dropdown + id: provider + attributes: + label: 相关 Provider + description: 请选择受影响的上游渠道。 + options: + - Grok Build + - Grok Web + - Grok Console + - 多个 Provider + - 与 Provider 无关 + validations: + required: true + + - type: input + id: version + attributes: + label: 版本信息 + description: 请提供版本号、Docker 镜像标签或 Commit SHA。 + placeholder: "v0.2.99、ghcr.io/chenyme/grok2api:latest、main@abcdef1" + validations: + required: true + + - type: textarea + id: environment + attributes: + label: 部署与运行环境 + description: 请填写与问题相关的部署方式、系统、架构、数据库和网络环境。 + placeholder: | + 部署方式:Docker Compose / Docker Run / 源码运行 + 操作系统:Debian 13 / Ubuntu 24.04 / macOS ... + CPU 架构:amd64 / arm64 + 数据库:SQLite / PostgreSQL + 反向代理:Nginx / Nginx Proxy Manager / 无 + 出口网络:直连 / HTTP Proxy / SOCKS5 / WARP + validations: + required: true + + - type: textarea + id: steps + attributes: + label: 复现步骤 + description: 请提供能够稳定复现问题的最小操作步骤。 + placeholder: | + 1. 使用配置……启动服务 + 2. 导入或选择……账号 + 3. 请求……接口 + 4. 出现……错误 + validations: + required: true + + - type: textarea + id: expected + attributes: + label: 预期行为 + description: 正常情况下应该发生什么? + validations: + required: true + + - type: textarea + id: actual + attributes: + label: 实际行为 + description: 实际发生了什么?请包含完整错误信息。 + validations: + required: true + + - type: textarea + id: evidence + attributes: + label: 请求、响应、日志与截图 + description: 请提供脱敏后的最小请求、状态码、响应体、容器日志、请求 ID 或截图。长日志请仅保留问题前后的关键部分。 + placeholder: 可粘贴内容或直接拖放截图、日志文件;提交前请再次确认内容已经脱敏。 + validations: + required: false + + - type: checkboxes + id: checklist + attributes: + label: 提交前检查 + options: + - label: 我已经搜索现有 Issue 和 Pull Request,确认没有相同问题。 + required: true + - label: 我已经删除 Token、Cookie、API Key、账号凭据和个人信息。 + required: true + - label: 这不是需要私下披露的安全漏洞。 + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000..3ba13e0c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/.github/ISSUE_TEMPLATE/documentation.yml b/.github/ISSUE_TEMPLATE/documentation.yml new file mode 100644 index 00000000..7dd0c7a9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/documentation.yml @@ -0,0 +1,95 @@ +name: 文档改进 +description: 报告缺失、错误、过时或难以理解的文档内容。 +title: "[Docs]: " +labels: + - documentation +body: + - type: markdown + attributes: + value: | + 请指出具体文档位置,并说明当前内容的问题和建议修改方向。 + + - type: dropdown + id: area + attributes: + label: 文档范围 + options: + - README + - 配置文件与 config.example.yaml + - Docker 与部署说明 + - Grok Build / Web / Console 账号接入 + - OpenAI API 兼容与 Swagger 契约 + - 模型同步、映射、路由与定价 + - 故障排查与常见问题 + - 开发规范与项目架构 + - 管理端界面文案 + - 其他 + validations: + required: true + + - type: dropdown + id: issue_type + attributes: + label: 问题类型 + options: + - 文档缺失 + - 内容错误 + - 内容已过时 + - 描述不清晰 + - 缺少示例 + - 链接失效 + - 格式或用词不统一 + - 其他 + validations: + required: true + + - type: input + id: location + attributes: + label: 文档位置 + description: 请提供文件路径、页面链接、章节名称或 API 路径。 + placeholder: "README.md#docker、config.example.yaml、/v1/responses" + validations: + required: true + + - type: textarea + id: issue + attributes: + label: 当前问题 + description: 当前文档缺少什么、哪里错误或为什么难以理解? + validations: + required: true + + - type: textarea + id: expected + attributes: + label: 建议修改 + description: 请描述建议补充、修正或重写的内容;如有条件可提供示例文本。 + validations: + required: false + + - type: dropdown + id: audience + attributes: + label: 主要受众 + options: + - 新用户 + - API 调用方 + - Docker 部署者 + - 系统管理员 + - 前端开发者 + - 后端开发者 + - 项目贡献者 + - 其他 + validations: + required: true + + - type: checkboxes + id: checklist + attributes: + label: 提交前检查 + options: + - label: 我已经搜索现有 Issue 和 Pull Request,确认没有相同文档问题。 + required: true + - label: 我已经提供尽可能具体的文档位置。 + required: true diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 00000000..506317ce --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,114 @@ +name: 功能建议 +description: 提议新的功能、兼容能力或工程改进。 +title: "[Feature]: " +labels: + - enhancement +body: + - type: markdown + attributes: + value: | + 请围绕一个明确的问题或使用场景提出建议,并说明预期行为、兼容性和部署影响。 + + - type: dropdown + id: area + attributes: + label: 功能模块 + description: 请选择建议主要影响的模块。 + options: + - OpenAI API 兼容层(Responses / Chat Completions) + - 模型同步、映射、路由与定价 + - 账号、Provider、OAuth 与凭据 + - 额度、计费与请求审计 + - 图片、视频与媒体处理 + - 管理端前端界面 + - SQLite / PostgreSQL 数据库 + - Docker、配置、部署与网络出口 + - 开发体验与工程质量 + - 其他 + validations: + required: true + + - type: dropdown + id: provider + attributes: + label: 相关 Provider + options: + - Grok Build + - Grok Web + - Grok Console + - 多个 Provider + - 新 Provider + - 与 Provider 无关 + validations: + required: true + + - type: textarea + id: problem + attributes: + label: 问题与使用场景 + description: 当前存在什么限制?谁会受到影响?为什么需要解决? + placeholder: 请描述实际使用场景,而不仅是功能名称。 + validations: + required: true + + - type: textarea + id: proposal + attributes: + label: 建议方案 + description: 请描述期望的交互、API、配置或运行行为。 + validations: + required: true + + - type: textarea + id: acceptance + attributes: + label: 验收标准 + description: 满足哪些可验证条件时,可以认为该功能已经完成? + placeholder: | + - 当……时,系统应…… + - API 应返回…… + - 现有配置和客户端应继续兼容…… + validations: + required: true + + - type: textarea + id: api_example + attributes: + label: API、配置或界面示例 + description: 如适用,请提供期望的请求响应、配置片段或界面流程。 + validations: + required: false + + - type: textarea + id: alternatives + attributes: + label: 替代方案 + description: 请描述目前的解决办法、绕过方式或考虑过的其他设计。 + validations: + required: false + + - type: textarea + id: compatibility + attributes: + label: 兼容性、部署与迁移影响 + description: 请说明是否影响 API 协议、模型命名、配置、数据库、Docker 部署或现有客户端。 + placeholder: | + API 兼容性: + 配置变更: + 数据库迁移: + Docker / 网络变更: + 向后兼容性: + validations: + required: false + + - type: checkboxes + id: checklist + attributes: + label: 提交前检查 + options: + - label: 我已经搜索现有 Issue 和 Pull Request,确认没有相同建议。 + required: true + - label: 该 Issue 只聚焦一个功能或改进方向。 + required: true + - label: 我已经说明用户价值和可验证的验收标准。 + required: true diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 00000000..99e7d25d --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,49 @@ +name: CodeQL Advanced + +on: + push: + branches: + - main + pull_request: + branches: + - main + schedule: + - cron: "0 0 * * *" + +concurrency: + group: codeql-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + analyze: + name: Analyze (${{ matrix.language }}) + runs-on: ubuntu-latest + permissions: + security-events: write + packages: read + actions: read + contents: read + strategy: + fail-fast: false + matrix: + include: + - language: actions + build-mode: none + - language: go + build-mode: autobuild + - language: javascript-typescript + build-mode: none + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Initialize CodeQL + uses: github/codeql-action/init@v4 + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix.build-mode }} + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v4 + with: + category: /language:${{ matrix.language }} diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml deleted file mode 100644 index 5348a09a..00000000 --- a/.github/workflows/docker-publish.yml +++ /dev/null @@ -1,119 +0,0 @@ -name: Docker - -on: - push: - branches: - - main - tags: - - "v*" - pull_request: - workflow_dispatch: - -concurrency: - group: docker-${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -permissions: - contents: read - packages: write - -env: - REGISTRY: ghcr.io - IMAGE_NAME: chenyme/grok2api - -jobs: - verify: - name: Verify - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Set up Go - uses: actions/setup-go@v5 - with: - go-version-file: backend/go.mod - cache-dependency-path: backend/go.sum - - - name: Test backend - working-directory: backend - run: go test ./... - - - name: Vet backend - working-directory: backend - run: go vet ./... - - - name: Verify Swagger document - run: | - make swagger - git diff --exit-code -- backend/docs/docs.go backend/docs/swagger.json backend/docs/swagger.yaml - - - name: Set up pnpm - uses: pnpm/action-setup@v4 - with: - version: 11.5.2 - - - name: Set up Node.js - uses: actions/setup-node@v4 - with: - node-version: 22 - cache: pnpm - cache-dependency-path: frontend/pnpm-lock.yaml - - - name: Install frontend dependencies - working-directory: frontend - run: pnpm install --frozen-lockfile - - - name: Lint frontend - working-directory: frontend - run: pnpm lint - - - name: Build frontend - working-directory: frontend - run: pnpm build - - image: - name: Build and publish image - needs: verify - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Set up QEMU - uses: docker/setup-qemu-action@v3 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 - - - name: Log in to GHCR - if: github.event_name != 'pull_request' - uses: docker/login-action@v3 - with: - registry: ${{ env.REGISTRY }} - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Extract image metadata - id: metadata - uses: docker/metadata-action@v5 - with: - images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - tags: | - type=raw,value=latest,enable={{is_default_branch}} - type=semver,pattern={{version}} - type=semver,pattern={{major}}.{{minor}} - type=sha,prefix=sha- - - - name: Build and publish - uses: docker/build-push-action@v6 - with: - context: . - platforms: linux/amd64,linux/arm64 - push: ${{ github.event_name != 'pull_request' }} - tags: ${{ steps.metadata.outputs.tags }} - labels: ${{ steps.metadata.outputs.labels }} - cache-from: type=gha - cache-to: ${{ github.event_name != 'pull_request' && 'type=gha,mode=max' || '' }} - provenance: mode=max - sbom: true diff --git a/.github/workflows/ghcr-image.yml b/.github/workflows/ghcr-image.yml new file mode 100644 index 00000000..06aa63bd --- /dev/null +++ b/.github/workflows/ghcr-image.yml @@ -0,0 +1,219 @@ +name: GHCR Image + +on: + push: + branches: + - main + tags: + - "v*.*.*" + pull_request: + branches: + - main + workflow_dispatch: + +concurrency: + group: ghcr-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + verify: + name: Verify + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + + - name: Test backend + working-directory: backend + run: go test ./... + + - name: Vet backend + working-directory: backend + run: go vet ./... + + - name: Verify Swagger document + run: | + make swagger + git diff --exit-code -- backend/docs/docs.go backend/docs/swagger.json backend/docs/swagger.yaml + + - name: Set up pnpm + uses: pnpm/action-setup@v4 + with: + version: 11.5.2 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: 22 + cache: pnpm + cache-dependency-path: frontend/pnpm-lock.yaml + + - name: Install frontend dependencies + working-directory: frontend + run: pnpm install --frozen-lockfile + + - name: Lint frontend + working-directory: frontend + run: pnpm lint + + - name: Build frontend + working-directory: frontend + run: pnpm build + + check_ghcr_image: + name: Build image (${{ matrix.arch }}) + if: github.event_name != 'push' + needs: verify + strategy: + fail-fast: false + matrix: + include: + - arch: amd64 + platform: linux/amd64 + runner: ubuntu-24.04 + - arch: arm64 + platform: linux/arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Buildx + uses: docker/setup-buildx-action@v3 + + - name: Build + uses: docker/build-push-action@v6 + with: + context: . + file: ./Dockerfile + platforms: ${{ matrix.platform }} + push: false + cache-from: type=gha,scope=${{ matrix.arch }} + provenance: false + sbom: false + + build_ghcr_image: + name: Publish image (${{ matrix.arch }}) + if: github.event_name == 'push' + needs: verify + permissions: + contents: read + packages: write + strategy: + fail-fast: false + matrix: + include: + - arch: amd64 + platform: linux/amd64 + runner: ubuntu-24.04 + - arch: arm64 + platform: linux/arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Buildx + uses: docker/setup-buildx-action@v3 + + - name: Normalize image name + id: image + shell: bash + run: | + image_name=$(printf '%s' "$GITHUB_REPOSITORY" | tr '[:upper:]' '[:lower:]') + echo "name=ghcr.io/$image_name" >> "$GITHUB_OUTPUT" + + - name: Docker metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ steps.image.outputs.name }} + tags: | + type=ref,event=branch,suffix=-${{ matrix.arch }} + type=ref,event=tag,suffix=-${{ matrix.arch }} + type=raw,value=latest-${{ matrix.arch }},enable=${{ github.ref == 'refs/heads/main' }} + + - name: Login to GHCR + uses: docker/login-action@v4 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and publish + uses: docker/build-push-action@v6 + with: + context: . + file: ./Dockerfile + platforms: ${{ matrix.platform }} + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha,scope=${{ matrix.arch }} + cache-to: type=gha,scope=${{ matrix.arch }},mode=max + provenance: mode=max + sbom: true + + merge: + name: Merge image + if: github.event_name == 'push' + needs: + - build_ghcr_image + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + + steps: + - name: Set up Buildx + uses: docker/setup-buildx-action@v3 + + - name: Normalize image name + id: image + shell: bash + run: | + image_name=$(printf '%s' "$GITHUB_REPOSITORY" | tr '[:upper:]' '[:lower:]') + echo "name=ghcr.io/$image_name" >> "$GITHUB_OUTPUT" + + - name: Docker metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ steps.image.outputs.name }} + tags: | + type=ref,event=branch + type=ref,event=tag + type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }} + + - name: Login to GHCR + uses: docker/login-action@v4 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Create manifest list + shell: bash + run: | + jq -cr '.tags[]' <<< "$DOCKER_METADATA_OUTPUT_JSON" | while read -r tag; do + docker buildx imagetools create \ + -t "$tag" \ + "${tag}-amd64" \ + "${tag}-arm64" + done + + - name: Inspect image + run: docker buildx imagetools inspect "${{ steps.image.outputs.name }}:${{ steps.meta.outputs.version }}" diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 00000000..e5634213 --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,30 @@ +name: Close inactive issues and PRs + +on: + schedule: + - cron: "30 1 * * *" + workflow_dispatch: + +permissions: + issues: write + pull-requests: write + +jobs: + stale: + name: Mark and close inactive issues and PRs + runs-on: ubuntu-latest + + steps: + - name: Process stale issues and PRs + uses: actions/stale@v10 + with: + days-before-issue-stale: 7 + days-before-pr-stale: 7 + days-before-issue-close: 7 + days-before-pr-close: 7 + stale-issue-label: stale + stale-pr-label: stale + stale-issue-message: This issue has had no activity for 7 days. It will be closed in 7 days if there is no further activity. + stale-pr-message: This pull request has had no activity for 7 days. It will be closed in 7 days if there is no further activity. + close-issue-message: This issue was closed because it had no activity for 7 days after being marked stale. + close-pr-message: This pull request was closed because it had no activity for 7 days after being marked stale. diff --git a/backend/docs/RESPONSES_COMPATIBILITY.md b/backend/docs/RESPONSES_COMPATIBILITY.md index 2a3e18f3..6b684e0a 100644 --- a/backend/docs/RESPONSES_COMPATIBILITY.md +++ b/backend/docs/RESPONSES_COMPATIBILITY.md @@ -128,8 +128,11 @@ Messages 转换层兼容 Claude Code 常见载荷:标准顶层 `system` 与误 - `media_input_images` - `media_output_images` - `media_output_seconds` +- `egress_mode`(`proxy` 或 `direct`) +- `egress_scope` +- `egress_node_id` / `egress_node_name`(出口节点快照) -不保存 prompt、response body、encrypted reasoning 内容或工具参数。 +不保存 prompt、response body、encrypted reasoning 内容、工具参数、代理 URL、代理认证信息、User-Agent 或 Cookie。 Grok Web 未提供与公开 API 等价的精确 Token 计量,因此聊天审计标记 `usageSource: estimated`;图片和视频标记 `usageSource: none`,不会伪造 Token,用量费用仅按已配置的官方媒体单价估算。 @@ -189,7 +192,7 @@ JSON 只接受当前 `accounts` 结构。SSO 不存在自动刷新:上游返 - `sso`、`sso-rw` 始终从当前账号的加密 SSO Token 生成。 - Clearance 与出口节点绑定;403 或挑战只重建当前节点会话并降低健康分,下一次优先选择更健康节点,不会冷却或移除账号。 - User-Agent 必须与获取 Clearance 时一致。当前 TLS 客户端使用其最新 Chrome 146 profile;自定义为 Firefox、Safari 等非 Chromium UA 会造成明显指纹不一致。 -- 出口节点按 `Grok Build`、`Grok Web`、`Grok Web(仅资源)` 三个作用域独立管理代理、健康度和冷却状态。Grok Build 始终沿用 Provider 的 CLI User-Agent,节点不能覆盖;Grok Web 和 Web 资源节点独立管理浏览器 User-Agent 与 Cloudflare Cookie。Web 资源未配置专用节点时仅回退到 Grok Web 节点。 +- 出口节点按 `Grok Build`、`Grok Web`、`Grok Console`、`Grok Web(仅资源)` 四个作用域独立管理代理、健康度和冷却状态。Grok Build 始终沿用 Provider 的 CLI User-Agent,节点不能覆盖;Grok Web、Console 和 Web 资源节点独立管理浏览器 User-Agent 与 Cloudflare Cookie。Web 资源未配置专用节点时仅回退到 Grok Web 节点。 - 代理地址支持 HTTP、HTTPS、SOCKS4、SOCKS4A、SOCKS5 与 SOCKS5H,可携带用户名和密码。Cloudflare Cookie 只适用于 Grok Web。 - 配置过对应作用域的出口节点后,如果全部节点不可用,服务不会静默退回直连;只有该作用域完全没有配置节点时才使用 direct。Grok Build 未配置节点时保持原有标准 HTTP 直连。 - 首版仅支持 `none/manual` Clearance,不接 FlareSolverr。 diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index ef56214c..cc1b010a 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -151,7 +151,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat database.Close() return nil, fmt.Errorf("不支持的运行态驱动: %s", cfg.RuntimeStore.Driver) } - mediaService := mediaapp.NewService(mediaAssetRepo, localMediaStore, refreshLock, mediaConfig(cfg)) + mediaService := mediaapp.NewService(mediaAssetRepo, mediaJobRepo, localMediaStore, refreshLock, mediaConfig(cfg)) egressManager := infraegress.NewManager(egressRepo, cipher) cliAdapter := cliprovider.NewAdapter(cliprovider.Config{BaseURL: cfg.Provider.Build.BaseURL, ClientVersion: cfg.Provider.Build.ClientVersion, ClientIdentifier: cfg.Provider.Build.ClientIdentifier, TokenAuth: cfg.Provider.Build.TokenAuth, UserAgent: cfg.Provider.Build.UserAgent}, cipher) @@ -277,7 +277,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat readiness := func(readyCtx context.Context) httpserver.ReadinessSnapshot { return readinessSnapshot(readyCtx, startup, runtimeHealth, modelRepo, accountRepo, providers) } - router := httpserver.New(httpserver.Dependencies{Logger: logger, RequestTimeout: cfg.Server.RequestTimeout.Value(), MaxBodyBytes: cfg.Server.MaxBodyBytes, SecureCookies: cfg.Auth.SecureCookies, SwaggerEnabled: cfg.Server.SwaggerEnabled, PublicAPIBaseURL: cfg.Frontend.PublicAPIBaseURL, FrontendStaticPath: cfg.Frontend.StaticPath, Readiness: readiness, TrafficReady: startup.acceptsTraffic, AdminAuth: adminService, Accounts: accountService, AccountSync: accountSyncService, Models: modelService, ClientKeys: clientKeyService, Audits: auditService, Dashboard: dashboardService, Gateway: gatewayService, Media: mediaService, Settings: settingsService, Egress: egressService}) + router := httpserver.New(httpserver.Dependencies{Logger: logger, RequestTimeout: cfg.Server.RequestTimeout.Value(), MaxBodyBytes: cfg.Server.MaxBodyBytes, SecureCookies: cfg.Auth.SecureCookies, SwaggerEnabled: cfg.Server.SwaggerEnabled, PublicAPIBaseURL: cfg.Frontend.EffectivePublicAPIBaseURL(), FrontendStaticPath: cfg.Frontend.StaticPath, Readiness: readiness, TrafficReady: startup.acceptsTraffic, AdminAuth: adminService, Accounts: accountService, AccountSync: accountSyncService, Models: modelService, ClientKeys: clientKeyService, Audits: auditService, Dashboard: dashboardService, Gateway: gatewayService, Media: mediaService, Settings: settingsService, Egress: egressService}) server := &http.Server{Addr: cfg.Server.Listen, Handler: router, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: cfg.Server.ReadTimeout.Value(), IdleTimeout: 2 * time.Minute, MaxHeaderBytes: 64 << 10} return &Application{ logger: logger, database: database, server: server, @@ -311,7 +311,7 @@ func consoleProviderConfig(cfg config.Config) consoleprovider.Config { func mediaConfig(cfg config.Config) mediaapp.Config { return mediaapp.Config{ - PublicBaseURL: cfg.Frontend.PublicAPIBaseURL, PreferRequestBaseURL: cfg.Frontend.PreferRequestBaseURL, + PublicBaseURL: cfg.Frontend.EffectivePublicAPIBaseURL(), MaxImageBytes: cfg.Media.MaxImageBytes, MaxTotalBytes: cfg.Media.MaxTotalBytes, CleanupThresholdPercent: cfg.Media.CleanupThresholdPercent, CleanupInterval: cfg.Media.CleanupInterval.Value(), } diff --git a/backend/internal/application/audit/service.go b/backend/internal/application/audit/service.go index f14bf7aa..fff53abc 100644 --- a/backend/internal/application/audit/service.go +++ b/backend/internal/application/audit/service.go @@ -178,6 +178,10 @@ func (s *Service) List(ctx context.Context, page, pageSize int) ([]auditdomain.R return s.audits.List(ctx, (page-1)*pageSize, pageSize) } +func (s *Service) Get(ctx context.Context, id uint64) (auditdomain.Record, error) { + return s.audits.Get(ctx, id) +} + // CursorResult 表示按递减 ID 游标读取的一页审计记录。 type CursorResult struct { Items []auditdomain.Record diff --git a/backend/internal/application/gateway/attempt.go b/backend/internal/application/gateway/attempt.go new file mode 100644 index 00000000..ee24f42a --- /dev/null +++ b/backend/internal/application/gateway/attempt.go @@ -0,0 +1,356 @@ +package gateway + +import ( + "bytes" + "context" + "crypto/tls" + "crypto/x509" + "errors" + "io" + "net" + "net/http" + "net/url" + "reflect" + "regexp" + "strings" + "time" + "unicode/utf8" + + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/domain/audit" + "github.com/chenyme/grok2api/backend/internal/infra/provider" +) + +type failureAttemptRecorder struct { + method string + path string + remainingBodyBudget int + attempts []audit.Attempt +} + +func newFailureAttemptRecorder(method, path string) *failureAttemptRecorder { + return &failureAttemptRecorder{method: method, path: sanitizeRequestPath(path), remainingBodyBudget: diagnosticTotalBodyLimit} +} + +const ( + diagnosticBodyLimit = 64 << 10 + diagnosticTotalBodyLimit = 256 << 10 + diagnosticTextLimit = 2048 + diagnosticHeadersLimit = 4 << 10 + diagnosticHeaderValueLimit = 512 + diagnosticErrorFrameLimit = 8 +) + +var ( + diagnosticAuthorizationPattern = regexp.MustCompile(`(?i)\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]+`) + diagnosticCookiePattern = regexp.MustCompile(`(?i)\b(cookie|set-cookie)\b\s*[:=]\s*[^\r\n]+`) + diagnosticSecretPattern = regexp.MustCompile(`(?i)(["']?(?:authorization|proxy-authorization|x-api-key|api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token)["']?\s*[:=]\s*["']?)[^"'\s,;}]+`) + diagnosticURLPattern = regexp.MustCompile(`https?://[^\s"'<>]+`) +) + +func (r *failureAttemptRecorder) captureCredentialFailure(credential accountdomain.Credential, startedAt time.Time, force bool, err error) { + if err == nil { + return + } + stage := "credential_validation" + if force { + stage = "credential_refresh" + } + r.append(audit.Attempt{ + Source: audit.AttemptSourceCredential, + Stage: stage, + AccountID: auditAccountID(credential.ID), + AccountName: credential.Name, + StartedAt: startedAt.UTC(), + DurationMS: time.Since(startedAt).Milliseconds(), + TransportError: sanitizeDiagnosticText(err.Error(), diagnosticTextLimit), + ErrorChain: errorFrames(err), + }) +} + +func (r *failureAttemptRecorder) captureResponse(credential accountdomain.Credential, startedAt time.Time, response *provider.Response, requestErr error) error { + if requestErr != nil { + r.append(audit.Attempt{ + Source: audit.AttemptSourceTransport, + Stage: transportStage(requestErr), + AccountID: auditAccountID(credential.ID), + AccountName: credential.Name, + Method: r.method, + RequestPath: r.path, + UpstreamURL: sanitizeUpstreamURL(errorUpstreamURL(requestErr)), + StartedAt: startedAt.UTC(), + DurationMS: time.Since(startedAt).Milliseconds(), + TransportError: sanitizeDiagnosticText(requestErr.Error(), diagnosticTextLimit), + ErrorChain: errorFrames(requestErr), + }) + return requestErr + } + if response.StatusCode >= 200 && response.StatusCode < 300 { + return nil + } + + statusCode := response.StatusCode + status := response.Status + headers := sanitizeDiagnosticHeaders(response.Header) + var body []byte + var bodyTruncated bool + if response.Diagnostic != nil { + statusCode = response.Diagnostic.StatusCode + status = response.Diagnostic.Status + headers = sanitizeDiagnosticHeaders(response.Diagnostic.Header) + body, bodyTruncated = r.captureBody(response.Diagnostic.Body, response.Diagnostic.BodyTruncated) + } else { + var err error + var replay io.ReadCloser + body, replay, bodyTruncated, err = readResponseBody(response.Body) + response.Body = replay + body, bodyTruncated = r.captureBody(body, bodyTruncated) + if err != nil { + r.append(audit.Attempt{ + Source: audit.AttemptSourceUpstreamHTTP, + Stage: "response_body", + AccountID: auditAccountID(credential.ID), + AccountName: credential.Name, + Method: r.method, + RequestPath: r.path, + UpstreamURL: sanitizeUpstreamURL(response.UpstreamURL), + StartedAt: startedAt.UTC(), + DurationMS: time.Since(startedAt).Milliseconds(), + UpstreamStatusCode: &statusCode, + UpstreamStatus: status, + ResponseHeaders: headers, + ResponseBody: body, + ResponseBodyTruncated: bodyTruncated, + TransportError: sanitizeDiagnosticText(err.Error(), diagnosticTextLimit), + ErrorChain: errorFrames(err), + }) + return err + } + } + r.append(audit.Attempt{ + Source: audit.AttemptSourceUpstreamHTTP, + Stage: "upstream_response", + AccountID: auditAccountID(credential.ID), + AccountName: credential.Name, + Method: r.method, + RequestPath: r.path, + UpstreamURL: sanitizeUpstreamURL(response.UpstreamURL), + StartedAt: startedAt.UTC(), + DurationMS: time.Since(startedAt).Milliseconds(), + UpstreamStatusCode: &statusCode, + UpstreamStatus: status, + ResponseHeaders: headers, + ResponseBody: body, + ResponseBodyTruncated: bodyTruncated, + }) + return nil +} + +func (r *failureAttemptRecorder) append(attempt audit.Attempt) { + attempt.Number = len(r.attempts) + 1 + r.attempts = append(r.attempts, attempt) +} + +// captureBody 在单次和单请求预算内保留可读的脱敏正文片段。 +func (r *failureAttemptRecorder) captureBody(body []byte, alreadyTruncated bool) ([]byte, bool) { + if len(body) == 0 { + return nil, alreadyTruncated + } + if !utf8.Valid(body) { + return nil, true + } + limit := min(diagnosticBodyLimit, r.remainingBodyBudget) + if limit <= 0 { + return nil, true + } + truncated := alreadyTruncated || len(body) > limit + if len(body) > limit { + body = body[:limit] + } + result := []byte(sanitizeDiagnosticText(string(body), limit)) + r.remainingBodyBudget -= len(result) + return result, truncated +} + +func (r *failureAttemptRecorder) snapshot() []audit.Attempt { + return append([]audit.Attempt(nil), r.attempts...) +} + +func auditAccountID(id uint64) *uint64 { + if id == 0 { + return nil + } + return &id +} + +type replayReadCloser struct { + io.Reader + source io.Closer +} + +func (r *replayReadCloser) Close() error { return r.source.Close() } + +// readResponseBody 只读取诊断上限,同时把已读取前缀接回原始响应供后续错误处理。 +func readResponseBody(body io.ReadCloser) ([]byte, io.ReadCloser, bool, error) { + if body == nil { + return nil, io.NopCloser(bytes.NewReader(nil)), false, nil + } + data, err := io.ReadAll(io.LimitReader(body, diagnosticBodyLimit+1)) + truncated := len(data) > diagnosticBodyLimit + if truncated || err != nil { + captured := data + if len(captured) > diagnosticBodyLimit { + captured = captured[:diagnosticBodyLimit] + } + replay := &replayReadCloser{Reader: io.MultiReader(bytes.NewReader(data), body), source: body} + return captured, replay, truncated, err + } + closeErr := body.Close() + return data, io.NopCloser(bytes.NewReader(data)), false, closeErr +} + +func errorFrames(err error) []audit.ErrorFrame { + frames := make([]audit.ErrorFrame, 0, 4) + appendErrorFrames(&frames, err) + return frames +} + +func appendErrorFrames(frames *[]audit.ErrorFrame, err error) { + if err == nil || len(*frames) >= diagnosticErrorFrameLimit { + return + } + *frames = append(*frames, audit.ErrorFrame{Type: truncateDiagnosticText(reflect.TypeOf(err).String(), 256), Message: sanitizeDiagnosticText(err.Error(), 512)}) + if joined, ok := err.(interface{ Unwrap() []error }); ok { + for _, nested := range joined.Unwrap() { + appendErrorFrames(frames, nested) + } + return + } + appendErrorFrames(frames, errors.Unwrap(err)) +} + +func sanitizeDiagnosticHeaders(headers http.Header) map[string][]string { + result := make(map[string][]string) + remaining := diagnosticHeadersLimit + for name, values := range headers { + if remaining <= 0 { + break + } + lowerName := strings.ToLower(name) + if !isAllowedDiagnosticHeader(lowerName) { + continue + } + cleanValues := make([]string, 0, min(len(values), 8)) + for _, value := range values { + if len(cleanValues) == 8 || remaining <= len(name) { + break + } + cleanValue := sanitizeDiagnosticText(value, min(diagnosticHeaderValueLimit, remaining-len(name))) + cleanValues = append(cleanValues, cleanValue) + remaining -= len(name) + len(cleanValue) + } + if len(cleanValues) > 0 { + result[http.CanonicalHeaderKey(name)] = cleanValues + } + } + return result +} + +func isAllowedDiagnosticHeader(name string) bool { + if strings.HasPrefix(name, "x-ratelimit-") || strings.HasPrefix(name, "ratelimit-") { + return true + } + switch name { + case "content-length", "content-type", "date", "retry-after", "server", "cf-ray", "request-id", "traceparent", "tracestate", "via", "x-correlation-id", "x-request-id", "x-grok2api-compatibility-warnings": + return true + default: + return false + } +} + +func sanitizeDiagnosticText(value string, limit int) string { + value = diagnosticCookiePattern.ReplaceAllString(value, "$1: [REDACTED]") + value = diagnosticAuthorizationPattern.ReplaceAllString(value, "$1 [REDACTED]") + value = diagnosticSecretPattern.ReplaceAllString(value, "$1[REDACTED]") + value = diagnosticURLPattern.ReplaceAllStringFunc(value, sanitizeUpstreamURL) + return truncateDiagnosticText(value, limit) +} + +func truncateDiagnosticText(value string, limit int) string { + if limit <= 0 { + return "" + } + if len(value) <= limit { + return value + } + for limit > 0 && !utf8.ValidString(value[:limit]) { + limit-- + } + return value[:limit] +} + +func sanitizeRequestPath(value string) string { + parsed, err := url.ParseRequestURI(value) + if err != nil { + return truncateDiagnosticText(strings.SplitN(value, "?", 2)[0], 2048) + } + parsed.RawQuery = "" + parsed.ForceQuery = false + parsed.Fragment = "" + return truncateDiagnosticText(parsed.String(), 2048) +} + +func sanitizeUpstreamURL(value string) string { + parsed, err := url.Parse(value) + if err != nil || parsed.Scheme == "" || parsed.Host == "" { + return "" + } + parsed.User = nil + parsed.RawQuery = "" + parsed.ForceQuery = false + parsed.Fragment = "" + parsed.RawFragment = "" + return truncateDiagnosticText(parsed.String(), 4096) +} + +func errorUpstreamURL(err error) string { + var urlErr *url.Error + if errors.As(err, &urlErr) { + return urlErr.URL + } + return "" +} + +func transportStage(err error) string { + switch { + case errors.Is(err, context.Canceled): + return "request_canceled" + case errors.Is(err, context.DeadlineExceeded): + return "request_timeout" + } + var dnsErr *net.DNSError + if errors.As(err, &dnsErr) { + return "dns_lookup" + } + var certificateError *tls.CertificateVerificationError + if errors.As(err, &certificateError) { + return "tls_verification" + } + var unknownAuthority x509.UnknownAuthorityError + if errors.As(err, &unknownAuthority) { + return "tls_verification" + } + var recordHeaderError tls.RecordHeaderError + if errors.As(err, &recordHeaderError) { + return "tls_handshake" + } + var networkError net.Error + if errors.As(err, &networkError) && networkError.Timeout() { + return "network_timeout" + } + var operationError *net.OpError + if errors.As(err, &operationError) && operationError.Op != "" { + return operationError.Op + } + return "transport" +} diff --git a/backend/internal/application/gateway/attempt_test.go b/backend/internal/application/gateway/attempt_test.go new file mode 100644 index 00000000..e3699c7c --- /dev/null +++ b/backend/internal/application/gateway/attempt_test.go @@ -0,0 +1,115 @@ +package gateway + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strings" + "testing" + "time" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/domain/audit" + "github.com/chenyme/grok2api/backend/internal/infra/provider" +) + +func TestFailureAttemptRecorderLimitsAndSanitizesHTTPResponse(t *testing.T) { + body := strings.Repeat("upstream failure\n", 8192) + recorder := newFailureAttemptRecorder(http.MethodPost, "/responses") + response := &provider.Response{ + StatusCode: http.StatusBadGateway, + Status: "502 Bad Gateway", + Header: http.Header{"Content-Type": {"text/plain"}, "Set-Cookie": {"session=secret"}, "X-Request-ID": {"req-123"}}, + Body: io.NopCloser(strings.NewReader(body)), + UpstreamURL: "https://user:password@api.example.test/v1/responses?token=secret#debug", + } + if err := recorder.captureResponse(account.Credential{ID: 9, Name: "primary"}, time.Now(), response, nil); err != nil { + t.Fatal(err) + } + stored := recorder.snapshot() + if len(stored) != 1 || stored[0].Source != audit.AttemptSourceUpstreamHTTP || len(stored[0].ResponseBody) != diagnosticBodyLimit || !stored[0].ResponseBodyTruncated { + t.Fatalf("attempt = %#v", stored) + } + headers := http.Header(stored[0].ResponseHeaders) + if stored[0].UpstreamURL != "https://api.example.test/v1/responses" || headers.Get("Set-Cookie") != "" || headers.Get("X-Request-Id") != "req-123" { + t.Fatalf("sanitized attempt = %#v", stored[0]) + } + rebuilt, err := io.ReadAll(response.Body) + if err != nil || string(rebuilt) != body { + t.Fatalf("rebuilt body length = %d, err = %v", len(rebuilt), err) + } +} + +func TestFailureAttemptRecorderUsesProviderDiagnosticResponse(t *testing.T) { + recorder := newFailureAttemptRecorder(http.MethodPost, "/responses") + response := &provider.Response{ + StatusCode: http.StatusBadGateway, + Status: "502 Bad Gateway", + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"normalized"}}`)), + UpstreamURL: "https://api.example.test/v1/responses", + Diagnostic: &provider.DiagnosticResponse{ + StatusCode: http.StatusBadGateway, + Status: "502 Bad Gateway", + Header: http.Header{"Content-Type": {"text/plain"}, "Authorization": {"Bearer secret"}}, + Body: []byte("failure access_token=secret-token"), + }, + } + if err := recorder.captureResponse(account.Credential{ID: 9, Name: "primary"}, time.Now(), response, nil); err != nil { + t.Fatal(err) + } + stored := recorder.snapshot()[0] + if string(stored.ResponseBody) != "failure access_token=[REDACTED]" || http.Header(stored.ResponseHeaders).Get("Authorization") != "" { + t.Fatalf("attempt = %#v", stored) + } + converted, err := io.ReadAll(response.Body) + if err != nil || !strings.Contains(string(converted), "normalized") { + t.Fatalf("provider response body = %q, err = %v", converted, err) + } +} + +func TestFailureAttemptRecorderClassifiesTransportErrorChain(t *testing.T) { + dnsErr := &net.DNSError{Err: "no such host", Name: "api.example.test", IsNotFound: true} + requestErr := &url.Error{Op: "Post", URL: "https://user:password@api.example.test/v1/responses?token=secret", Err: dnsErr} + recorder := newFailureAttemptRecorder(http.MethodPost, "/responses") + if err := recorder.captureResponse(account.Credential{ID: 3, Name: "primary"}, time.Now(), nil, requestErr); !errors.Is(err, dnsErr) { + t.Fatalf("capture error = %v", err) + } + stored := recorder.snapshot() + if len(stored) != 1 || stored[0].Stage != "dns_lookup" || stored[0].UpstreamURL != "https://api.example.test/v1/responses" || len(stored[0].ErrorChain) != 2 { + t.Fatalf("attempt = %#v", stored) + } + if transportStage(context.DeadlineExceeded) != "request_timeout" { + t.Fatalf("deadline stage = %s", transportStage(context.DeadlineExceeded)) + } +} + +func TestFailureAttemptRecorderBoundsTotalBodyAndErrorChain(t *testing.T) { + recorder := newFailureAttemptRecorder(http.MethodPost, "/responses") + for index := 0; index < 5; index++ { + response := &provider.Response{StatusCode: http.StatusBadGateway, Header: http.Header{"Content-Type": {"text/plain"}}, Body: io.NopCloser(strings.NewReader(strings.Repeat("x", diagnosticBodyLimit)))} + if err := recorder.captureResponse(account.Credential{ID: uint64(index + 1)}, time.Now(), response, nil); err != nil { + t.Fatal(err) + } + } + stored := recorder.snapshot() + var captured int + for _, attempt := range stored { + captured += len(attempt.ResponseBody) + } + if captured != diagnosticTotalBodyLimit || len(stored[4].ResponseBody) != 0 || !stored[4].ResponseBodyTruncated { + t.Fatalf("captured = %d, final attempt = %#v", captured, stored[4]) + } + + var wrapped error = errors.New("root") + for index := 0; index < 20; index++ { + wrapped = fmt.Errorf("layer %d: %w", index, wrapped) + } + if frames := errorFrames(wrapped); len(frames) != diagnosticErrorFrameLimit { + t.Fatalf("error frames = %d", len(frames)) + } +} diff --git a/backend/internal/application/gateway/egress_audit.go b/backend/internal/application/gateway/egress_audit.go new file mode 100644 index 00000000..fe546d97 --- /dev/null +++ b/backend/internal/application/gateway/egress_audit.go @@ -0,0 +1,55 @@ +package gateway + +import ( + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/domain/audit" + egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress" + "github.com/chenyme/grok2api/backend/internal/domain/media" + infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" +) + +func applyAuditEgress(record *audit.Record, trace *infraegress.Trace, provider accountdomain.Provider) { + selection, ok := trace.Selection(primaryEgressScope(provider)) + if !ok { + return + } + record.EgressNodeName = selection.NodeName + record.EgressScope = string(selection.Scope) + if selection.Proxied { + record.EgressMode = audit.EgressModeProxy + } else { + record.EgressMode = audit.EgressModeDirect + } + if selection.NodeID != 0 { + id := selection.NodeID + record.EgressNodeID = &id + } +} + +func applyMediaJobEgress(job *media.Job, trace *infraegress.Trace, provider accountdomain.Provider) { + selection, ok := trace.Selection(primaryEgressScope(provider)) + if !ok { + return + } + job.EgressNodeName = selection.NodeName + job.EgressScope = string(selection.Scope) + job.EgressMode = string(audit.EgressModeDirect) + if selection.Proxied { + job.EgressMode = string(audit.EgressModeProxy) + } + if selection.NodeID != 0 { + id := selection.NodeID + job.EgressNodeID = &id + } +} + +func primaryEgressScope(provider accountdomain.Provider) egressdomain.Scope { + switch provider { + case accountdomain.ProviderWeb: + return egressdomain.ScopeWeb + case accountdomain.ProviderConsole: + return egressdomain.ScopeConsole + default: + return egressdomain.ScopeBuild + } +} diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 837f1c9b..f1019536 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -23,6 +23,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/clientkey" inferencedomain "github.com/chenyme/grok2api/backend/internal/domain/inference" 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/security" "github.com/chenyme/grok2api/backend/internal/repository" @@ -37,7 +38,6 @@ var ( ErrConversationUnsupported = errors.New("目标模型不支持当前对话协议") ) -const maxRetryableBodyBytes = 64 << 10 const responseOwnershipTTL = 30 * 24 * time.Hour const finalizationTimeout = 5 * time.Second const textBillingReservationTTL = 2 * time.Hour @@ -54,7 +54,6 @@ type Input struct { PromptCacheKey string PreviousResponseID string Operation audit.Operation - PublicBaseURL string } type Usage struct { @@ -259,6 +258,7 @@ func (s *Service) selectMediaRoute(routes []modeldomain.Route, key clientkey.Key } func (s *Service) createResponseAt(ctx context.Context, input Input, path string) (*Result, error) { + ctx, egressTrace := infraegress.WithTrace(ctx) startedAt := time.Now() eventID := newAuditEventID() operation := input.Operation @@ -312,6 +312,7 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string record.DurationMS = time.Since(startedAt).Milliseconds() record.ErrorCode = "model_not_allowed" record.CreatedAt = time.Now().UTC() + applyAuditEgress(&record, egressTrace, route.Provider) if err := s.audits.Create(ctx, record); err != nil { s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", input.RequestID, "error", err) } @@ -346,15 +347,18 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string quotaProbeAttempted := false var lastErr error var lastFailure *UpstreamFailure + failureAttempts := newFailureAttemptRecorder(http.MethodPost, path) forwardResponse := func(credential accountdomain.Credential) (*provider.Response, error) { started := time.Now() - response, err := adapter.ForwardResponse(ctx, provider.ResponseResourceRequest{Credential: credential, Method: http.MethodPost, Path: path, Model: route.UpstreamModel, PromptCacheKey: input.PromptCacheKey, IdempotencyID: idempotencyID, Body: input.Body, Streaming: input.Streaming, NormalizeBody: true, Operation: string(operation), PublicBaseURL: input.PublicBaseURL}) + response, err := adapter.ForwardResponse(ctx, provider.ResponseResourceRequest{Credential: credential, Method: http.MethodPost, Path: path, Model: route.UpstreamModel, PromptCacheKey: input.PromptCacheKey, IdempotencyID: idempotencyID, Body: input.Body, Streaming: input.Streaming, NormalizeBody: true, Operation: string(operation)}) + err = failureAttempts.captureResponse(credential, started, response, err) timing.markUpstream(time.Since(started)) return response, err } ensureCredential := func(credential accountdomain.Credential, force bool) (accountdomain.Credential, error) { started := time.Now() result, err := s.accounts.EnsureCredential(ctx, credential, force) + failureAttempts.captureCredentialFailure(credential, started, force, err) timing.markCredential(time.Since(started)) return result, err } @@ -571,7 +575,11 @@ attemptLoop: record.ContextOutputTokens = usage.ContextOutputTokens record.DurationMS = time.Since(startedAt).Milliseconds() record.ErrorCode = errorCode + if response.StatusCode < 200 || response.StatusCode >= 300 || errorCode != "" { + record.Attempts = failureAttempts.snapshot() + } record.CreatedAt = now + applyAuditEgress(&record, egressTrace, route.Provider) if err := s.audits.Create(persistCtx, record); err != nil { s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", input.RequestID, "error", err) } @@ -611,7 +619,9 @@ attemptLoop: record.StatusCode = lastFailure.HTTPStatus record.DurationMS = time.Since(startedAt).Milliseconds() record.ErrorCode = lastFailure.AuditCode() + record.Attempts = failureAttempts.snapshot() record.CreatedAt = time.Now().UTC() + applyAuditEgress(&record, egressTrace, route.Provider) if lastFailure.AccountID != 0 { accountID := lastFailure.AccountID record.AccountID = &accountID @@ -631,7 +641,9 @@ attemptLoop: record.StatusCode = http.StatusServiceUnavailable record.DurationMS = time.Since(startedAt).Milliseconds() record.ErrorCode = "upstream_unavailable" + record.Attempts = failureAttempts.snapshot() record.CreatedAt = time.Now().UTC() + applyAuditEgress(&record, egressTrace, route.Provider) persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout) defer cancel() if err := s.audits.Create(persistCtx, record); err != nil { @@ -686,7 +698,6 @@ type ImageGenerationInput struct { Resolution string ResponseFormat string Streaming bool - PublicBaseURL string } type ImageEditInput struct { @@ -698,31 +709,29 @@ type ImageEditInput struct { Count int Resolution string ResponseFormat string - PublicBaseURL string } func (s *Service) GenerateImage(ctx context.Context, input ImageGenerationInput) (*Result, error) { - return s.executeImage(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationImage, func(adapter provider.ImageAdapter, credential accountdomain.Credential, upstream string) (*provider.Response, error) { - return adapter.GenerateImage(ctx, provider.ImageGenerationRequest{ + return s.executeImage(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationImage, func(executionCtx context.Context, adapter provider.ImageAdapter, credential accountdomain.Credential, upstream string) (*provider.Response, error) { + return adapter.GenerateImage(executionCtx, provider.ImageGenerationRequest{ Credential: credential, Model: upstream, Prompt: input.Prompt, Count: input.Count, Size: input.Size, AspectRatio: input.AspectRatio, Resolution: input.Resolution, ResponseFormat: input.ResponseFormat, Streaming: input.Streaming, - PublicBaseURL: input.PublicBaseURL, }) }, input.Streaming, input.Resolution, input.Count, 0) } func (s *Service) EditImage(ctx context.Context, input ImageEditInput) (*Result, error) { - return s.executeImage(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationImageEdit, func(adapter provider.ImageAdapter, credential accountdomain.Credential, upstream string) (*provider.Response, error) { - return adapter.EditImage(ctx, provider.ImageEditRequest{ + return s.executeImage(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationImageEdit, func(executionCtx context.Context, adapter provider.ImageAdapter, credential accountdomain.Credential, upstream string) (*provider.Response, error) { + return adapter.EditImage(executionCtx, provider.ImageEditRequest{ Credential: credential, Model: upstream, Prompt: input.Prompt, ImageURLs: input.ImageURLs, Count: input.Count, Resolution: input.Resolution, ResponseFormat: input.ResponseFormat, - PublicBaseURL: input.PublicBaseURL, }) }, false, input.Resolution, input.Count, len(input.ImageURLs)) } -func (s *Service) executeImage(ctx context.Context, requestID string, key clientkey.Key, publicModel string, operation audit.Operation, execute func(provider.ImageAdapter, accountdomain.Credential, string) (*provider.Response, error), streaming bool, resolution string, requestedCount, inputImageCount int) (*Result, error) { +func (s *Service) executeImage(ctx context.Context, requestID string, key clientkey.Key, publicModel string, operation audit.Operation, execute func(context.Context, provider.ImageAdapter, accountdomain.Credential, string) (*provider.Response, error), streaming bool, resolution string, requestedCount, inputImageCount int) (*Result, error) { + ctx, egressTrace := infraegress.WithTrace(ctx) startedAt := time.Now() eventID := newAuditEventID() routes, err := s.models.GetByPublicIDCandidates(ctx, publicModel) @@ -745,6 +754,32 @@ func (s *Service) executeImage(ctx context.Context, requestID string, key client if !ok { return nil, ErrNoAvailableAccount } + auditBase := audit.Record{ + EventID: eventID, RequestID: requestID, ClientKeyID: key.ID, ClientKeyName: key.Name, + ModelRouteID: route.ID, ModelPublicID: externalModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel), + Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone, Streaming: streaming, + } + if operation == audit.OperationImageEdit { + auditBase.MediaInputImages = int64(max(0, inputImageCount)) + } + writeFailureAudit := func(statusCode int, errorCode string, credential *accountdomain.Credential) { + record := auditBase + record.StatusCode = statusCode + record.ErrorCode = errorCode + record.DurationMS = time.Since(startedAt).Milliseconds() + record.CreatedAt = time.Now().UTC() + if credential != nil { + accountID := credential.ID + record.AccountID = &accountID + record.AccountName = credential.Name + } + applyAuditEgress(&record, egressTrace, route.Provider) + persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout) + defer cancel() + if auditErr := s.audits.Create(persistCtx, record); auditErr != nil { + s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", requestID, "error", auditErr) + } + } pricingModel := s.providers.PricingModel(route.Provider, route.UpstreamModel) var reservation audit.PricingResult var priced bool @@ -776,23 +811,34 @@ func (s *Service) executeImage(ctx context.Context, requestID string, key client var lease *accountLease var credential accountdomain.Credential var response *provider.Response + var lastCredentialFailure *accountdomain.Credential for attempt := 0; attempt < attempts; attempt++ { lease, err = s.selector.Acquire(ctx, route.Provider, route.UpstreamModel, quotaMode, "", excluded, false) if err != nil { + writeFailureAudit(http.StatusServiceUnavailable, "upstream_unavailable", lastCredentialFailure) return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, err) } excluded[lease.Credential.ID] = true credential, err = s.accounts.EnsureCredential(ctx, lease.Credential, false) if err != nil { s.logger.Error("image_credential_failed", "event_id", eventID, "request_id", requestID, "model", externalModel, "provider", route.Provider, "account_id", lease.Credential.ID, "error", err) + failedCredential := lease.Credential + lastCredentialFailure = &failedCredential lease.Release() - return nil, err + continue } - response, err = execute(adapter, credential, route.UpstreamModel) + response, err = execute(ctx, adapter, credential, route.UpstreamModel) if err != nil { s.logger.Error("image_upstream_failed", "event_id", eventID, "request_id", requestID, "model", externalModel, "provider", route.Provider, "account_id", credential.ID, "error", err) - s.selector.MarkFailure(ctx, credential, 0, 0) + if !provider.IsMediaPostProcessingError(err) { + s.selector.MarkFailure(ctx, credential, 0, 0) + } lease.Release() + errorCode := "upstream_unavailable" + if provider.IsMediaPostProcessingError(err) { + errorCode = "media_postprocessing_failed" + } + writeFailureAudit(http.StatusBadGateway, errorCode, &credential) return nil, err } if s.providers.RetryForbiddenAsEgress(credential.Provider) && response.StatusCode == http.StatusForbidden && attempt == 0 && attempt+1 < attempts { @@ -828,22 +874,13 @@ func (s *Service) executeImage(ctx context.Context, requestID string, key client lease.Release() persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout) defer cancel() - record := audit.Record{ - EventID: eventID, RequestID: requestID, ClientKeyID: key.ID, ClientKeyName: key.Name, - ModelRouteID: route.ID, ModelPublicID: externalModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel), - Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone, - AccountID: &accountID, AccountName: credential.Name, StatusCode: response.StatusCode, - Streaming: streaming, ErrorCode: errorCode, - DurationMS: time.Since(startedAt).Milliseconds(), CreatedAt: time.Now().UTC(), - } - switch operation { - case audit.OperationImage: - record.MediaOutputImages = int64(max(0, requestedCount)) - case audit.OperationImageEdit: - record.MediaInputImages = int64(max(0, inputImageCount)) - record.MediaOutputImages = int64(max(0, requestedCount)) - } + record := auditBase + record.AccountID, record.AccountName, record.StatusCode = &accountID, credential.Name, response.StatusCode + record.ErrorCode = errorCode + record.DurationMS, record.CreatedAt = time.Since(startedAt).Milliseconds(), time.Now().UTC() + applyAuditEgress(&record, egressTrace, route.Provider) if response.StatusCode >= 200 && response.StatusCode < 300 && errorCode == "" { + record.MediaOutputImages = int64(max(0, requestedCount)) var pricing audit.PricingResult var priced bool switch operation { @@ -968,7 +1005,8 @@ func readRetryableBody(body io.ReadCloser) ([]byte, error) { return nil, nil } defer body.Close() - return io.ReadAll(io.LimitReader(body, maxRetryableBodyBytes)) + data, _, err := provider.ReadDiagnosticBody(body) + return data, err } func parseFreeQuotaExhaustion(body []byte) (int64, int64, bool) { diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index 005ebbf6..1befadd5 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -19,8 +19,10 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/account" "github.com/chenyme/grok2api/backend/internal/domain/audit" "github.com/chenyme/grok2api/backend/internal/domain/clientkey" + egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress" inferencedomain "github.com/chenyme/grok2api/backend/internal/domain/inference" 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/persistence/relational" "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/infra/runtime/memory" @@ -94,9 +96,13 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { t.Fatalf("observed account = %#v, err = %v", observedAccount, err) } logs, total, err := auditRepo.List(ctx, 0, 10) - if err != nil || total != 1 || logs[0].AccountID == nil || *logs[0].AccountID != second.ID || logs[0].ClientKeyName != "test-key" || logs[0].ModelPublicID != "grok-test" || logs[0].ModelUpstreamModel != "Build/grok-test" || logs[0].AccountName != "second" || logs[0].CachedInputTokens != 80 { + if err != nil || total != 1 || logs[0].AccountID == nil || *logs[0].AccountID != second.ID || logs[0].ClientKeyName != "test-key" || logs[0].ModelPublicID != "grok-test" || logs[0].ModelUpstreamModel != "Build/grok-test" || logs[0].AccountName != "second" || logs[0].CachedInputTokens != 80 || logs[0].AttemptCount != 0 { t.Fatalf("audit = %#v, %d, %v", logs, total, err) } + detail, err := auditRepo.Get(ctx, logs[0].ID) + if err != nil || len(detail.Attempts) != 0 { + t.Fatalf("audit detail = %#v, err = %v", detail, err) + } ownership, err := responseRepo.Get(ctx, "resp-test", clientKey.ID, time.Now().UTC()) if err != nil || ownership.AccountID != second.ID { t.Fatalf("ownership = %#v, err = %v", ownership, err) @@ -651,6 +657,47 @@ func TestImageStreamPropagatesWithoutTouchingChatQuota(t *testing.T) { if adapter.EditResolution() != "2k" { t.Fatalf("image edit resolution = %q", adapter.EditResolution()) } + + billingBeforeFailure, err := keyRepo.Get(ctx, key.ID) + if err != nil { + t.Fatal(err) + } + backupCredential, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderWeb, AuthType: account.AuthTypeSSO, WebTier: account.WebTierSuper, + Name: "web-image-backup", SourceKey: "web-image-backup", EncryptedAccessToken: "encrypted-backup", Enabled: true, + AuthStatus: account.AuthStatusActive, MaxConcurrent: 2, + }) + if err != nil { + t.Fatal(err) + } + if err := modelRepo.ReplaceAccountCapabilities(ctx, backupCredential.ID, []string{"grok-imagine-image-quality"}, now); err != nil { + t.Fatal(err) + } + selector.MarkQuotaStateChanged(account.ProviderWeb) + service.UpdateMaxAttempts(3) + attemptsBeforeFailure := len(adapter.Attempts()) + adapter.FailWithEgress(infraegress.NewManager(relational.NewEgressRepository(database), testCipher(t))) + if _, err := service.GenerateImage(ctx, ImageGenerationInput{ + RequestID: "req-image-failed", ClientKey: key, PublicModel: "grok-imagine-image-quality", + Prompt: "test", Count: 1, Resolution: "1k", ResponseFormat: "url", + }); err == nil { + t.Fatal("expected image transport failure") + } + if attempts := adapter.Attempts(); len(attempts) != attemptsBeforeFailure+1 { + t.Fatalf("image failure switched accounts after generation started: %#v", attempts) + } + logs, total, err = auditRepo.List(ctx, 0, 10) + if err != nil || total != 5 || len(logs) != 5 { + t.Fatalf("failure audit logs=%#v total=%d err=%v", logs, total, err) + } + failureAudit := logs[0] + if failureAudit.RequestID != "req-image-failed" || failureAudit.StatusCode != http.StatusBadGateway || failureAudit.ErrorCode != "upstream_unavailable" || failureAudit.MediaOutputImages != 0 || failureAudit.EstimatedCostInUSDTicks != 0 || failureAudit.EgressMode != audit.EgressModeDirect || failureAudit.EgressScope != string(egressdomain.ScopeWeb) || failureAudit.EgressNodeName != "direct" { + t.Fatalf("failure audit = %#v", failureAudit) + } + updatedKey, err := keyRepo.Get(ctx, key.ID) + if err != nil || updatedKey.ReservedUsageUSDTicks != 0 || updatedKey.BilledUsageUSDTicks != billingBeforeFailure.BilledUsageUSDTicks { + t.Fatalf("failed image billing key = %#v, err = %v", updatedKey, err) + } } func TestSuccessfulWebChatRefreshesCurrentModeQuota(t *testing.T) { @@ -844,6 +891,8 @@ type webImageStreamAdapter struct { streaming bool editResolution string synced chan string + failureEgress *infraegress.Manager + attempts []uint64 } type webChatQuotaAdapter struct { @@ -877,10 +926,20 @@ func (a *webImageStreamAdapter) QuotaMode(model string) string { func (a *webImageStreamAdapter) TierOrder(string) []account.WebTier { return []account.WebTier{account.WebTierSuper, account.WebTierHeavy} } -func (a *webImageStreamAdapter) GenerateImage(_ context.Context, request provider.ImageGenerationRequest) (*provider.Response, error) { +func (a *webImageStreamAdapter) GenerateImage(ctx context.Context, request provider.ImageGenerationRequest) (*provider.Response, error) { a.mu.Lock() a.streaming = request.Streaming + failureEgress := a.failureEgress + a.attempts = append(a.attempts, request.Credential.ID) a.mu.Unlock() + if failureEgress != nil { + lease, err := failureEgress.Acquire(ctx, egressdomain.ScopeWeb, "image-failure") + if err != nil { + return nil, err + } + lease.Release() + return nil, errors.New("simulated image transport failure") + } body := "event: image_generation.completed\ndata: {}\n\ndata: [DONE]\n\n" return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: http.Header{"Content-Type": {"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(body)), QuotaUnits: 1}, nil } @@ -909,6 +968,16 @@ func (a *webImageStreamAdapter) EditResolution() string { defer a.mu.Unlock() return a.editResolution } +func (a *webImageStreamAdapter) FailWithEgress(manager *infraegress.Manager) { + a.mu.Lock() + a.failureEgress = manager + a.mu.Unlock() +} +func (a *webImageStreamAdapter) Attempts() []uint64 { + a.mu.Lock() + defer a.mu.Unlock() + return append([]uint64(nil), a.attempts...) +} func (a *webImageStreamAdapter) SyncQuota(context.Context, account.Credential) (provider.QuotaSnapshot, error) { return provider.QuotaSnapshot{}, errors.New("unexpected full quota sync") } diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index e37eb9a2..0426a1f9 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -14,6 +14,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/clientkey" "github.com/chenyme/grok2api/backend/internal/domain/media" "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/security" "github.com/chenyme/grok2api/backend/internal/pkg/batch" @@ -200,16 +201,7 @@ func (s *Service) processVideoJob(ctx context.Context, id string) { route, err = s.models.GetByPublicID(ctx, job.Model) } if err != nil { - now := time.Now().UTC() - job.Status = media.StatusFailed - job.ErrorCode = "model_not_found" - job.ErrorMessage = "模型路由不存在" - job.LeaseUntil, job.UpdatedAt, job.CompletedAt = nil, now, &now - if err := s.mediaJobs.UpdateMediaJob(ctx, job); err != nil { - s.logger.Warn("video_job_terminal_write_failed", "job_id", job.ID, "error", err) - } else { - s.cancelBillingReservation("video_usage_" + job.ID) - } + s.failVideoJob(ctx, job, "model_not_found", errors.New("模型路由不存在")) return } s.runVideoJob(ctx, job, route) @@ -243,12 +235,15 @@ func (s *Service) claimVideoJob(ctx context.Context, id string) (media.Job, bool func (s *Service) runVideoJob(parent context.Context, job media.Job, route model.Route) { ctx, cancel := context.WithTimeout(parent, videoJobTimeout) defer cancel() + ctx, egressTrace := infraegress.WithTrace(ctx) startedAt := time.Now() job.Progress = max(job.Progress, 1) job.UpdatedAt = time.Now().UTC() if err := s.mediaJobs.UpdateMediaJob(ctx, job); err != nil { s.logger.Warn("video_job_progress_write_failed", "job_id", job.ID, "error", err) } + // 视频任务创建时已持久化账号归属;恢复只能重新获取原账号,禁止因后续 + // 轮询或结果处理失败切换到其他账号。 lease, err := s.selector.AcquirePinned(ctx, route.Provider, job.AccountID, route.UpstreamModel, "", true) if err != nil { if parent.Err() != nil { @@ -291,18 +286,20 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model _ = s.accounts.MarkReauthRequired(context.Background(), lease.Credential.ID, fmt.Sprintf("%s SSO credential rejected", lease.Credential.Provider)) } s.selector.MarkFailure(context.Background(), lease.Credential, 0, 0) + applyMediaJobEgress(&job, egressTrace, route.Provider) s.failVideoJob(parent, job, "generation_failed", err) return } now := time.Now().UTC() job.Status, job.Progress, job.UpstreamURL, job.ContentType = media.StatusCompleted, 100, result.URL, result.ContentType + applyMediaJobEgress(&job, egressTrace, route.Provider) job.LeaseUntil, job.UpdatedAt, job.CompletedAt = nil, now, &now if err := s.persistVideoJobWithRetry(parent, job); err != nil { s.logger.Error("video_job_terminal_write_failed", "job_id", job.ID, "error", err) return } s.selector.MarkSuccess(context.Background(), lease.Credential) - if err := s.recordVideoUsage(context.Background(), job, time.Since(startedAt).Milliseconds()); err != nil { + 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" { @@ -311,7 +308,7 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model } func (s *Service) reconcileVideoUsage(ctx context.Context) error { - jobs, err := s.mediaJobs.ListUnrecordedCompletedMediaJobs(ctx, 200) + jobs, err := s.mediaJobs.ListUnrecordedTerminalMediaJobs(ctx, 200) if err != nil { return err } @@ -321,28 +318,42 @@ func (s *Service) reconcileVideoUsage(ctx context.Context) error { if job.CompletedAt != nil { durationMS = max(int64(0), job.CompletedAt.Sub(job.CreatedAt).Milliseconds()) } - if err := s.recordVideoUsage(ctx, job, durationMS); err != nil { + if err := s.recordVideoAudit(ctx, job, durationMS); err != nil { result = firstError(result, fmt.Errorf("任务 %s: %w", job.ID, err)) } } return result } -func (s *Service) recordVideoUsage(ctx context.Context, job media.Job, durationMS int64) error { +func (s *Service) recordVideoAudit(ctx context.Context, job media.Job, durationMS int64) error { accountID := job.AccountID createdAt := time.Now().UTC() if job.CompletedAt != nil && !job.CompletedAt.IsZero() { createdAt = job.CompletedAt.UTC() } + statusCode := http.StatusOK + if job.Status == media.StatusFailed { + statusCode = http.StatusBadGateway + switch job.ErrorCode { + case "account_unavailable", "provider_unavailable": + statusCode = http.StatusServiceUnavailable + case "model_not_found": + statusCode = http.StatusNotFound + } + } record := audit.Record{ EventID: "video_usage_" + job.ID, RequestID: job.RequestID, ClientKeyID: job.ClientKeyID, ClientKeyName: job.ClientKeyName, ModelRouteID: job.ModelRouteID, ModelPublicID: job.Model, ModelUpstreamModel: job.UpstreamModel, Provider: job.Provider, Operation: audit.OperationVideo, UsageSource: audit.UsageSourceNone, - AccountID: &accountID, AccountName: job.AccountName, StatusCode: http.StatusOK, - MediaInputImages: int64(len(decodeVideoInput(job.InputJSON))), MediaOutputSeconds: int64(max(0, job.Seconds)), - DurationMS: durationMS, CreatedAt: createdAt, + AccountID: &accountID, AccountName: job.AccountName, StatusCode: statusCode, ErrorCode: job.ErrorCode, + EgressNodeID: job.EgressNodeID, EgressNodeName: job.EgressNodeName, EgressScope: job.EgressScope, EgressMode: audit.EgressMode(job.EgressMode), + MediaInputImages: int64(len(decodeVideoInput(job.InputJSON))), + DurationMS: durationMS, CreatedAt: createdAt, } - if pricing, ok := audit.EstimateOfficialVideoCost(job.Model, job.Quality, job.Seconds); ok { + if job.Status == media.StatusCompleted { + record.MediaOutputSeconds = int64(max(0, job.Seconds)) + } + if pricing, ok := audit.EstimateOfficialVideoCost(job.Model, job.Quality, job.Seconds); ok && job.Status == media.StatusCompleted { record.EstimatedCostInUSDTicks = pricing.CostInUSDTicks record.PricingModel = pricing.Model record.PricingVersion = audit.OfficialPricingAsOf @@ -383,6 +394,9 @@ func (s *Service) failVideoJob(ctx context.Context, job media.Job, code string, s.logger.Error("video_job_terminal_write_failed", "job_id", job.ID, "error", updateErr) return } + if auditErr := s.recordVideoAudit(context.Background(), job, max(int64(0), now.Sub(job.CreatedAt).Milliseconds())); auditErr != nil { + s.logger.Error("video_usage_record_failed", "job_id", job.ID, "event_id", "video_usage_"+job.ID, "error", auditErr) + } s.cancelBillingReservation("video_usage_" + job.ID) } diff --git a/backend/internal/application/gateway/video_test.go b/backend/internal/application/gateway/video_test.go index 6b433430..d2ff1291 100644 --- a/backend/internal/application/gateway/video_test.go +++ b/backend/internal/application/gateway/video_test.go @@ -9,6 +9,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/audit" "github.com/chenyme/grok2api/backend/internal/domain/media" + "github.com/chenyme/grok2api/backend/internal/repository" ) func TestRecoverVideoJobsRetriesUsageWithoutRegeneratingVideo(t *testing.T) { @@ -38,6 +39,33 @@ func TestRecoverVideoJobsRetriesUsageWithoutRegeneratingVideo(t *testing.T) { } } +func TestRecoverVideoJobsRecordsFailedAuditWithEgress(t *testing.T) { + completedAt := time.Now().UTC() + nodeID := uint64(42) + repository := &videoUsageRepository{job: media.Job{ + ID: "video_failed_recovery", RequestID: "request-failed-recovery", + ClientKeyID: 1, ClientKeyName: "client", AccountID: 2, AccountName: "account", + Provider: "grok_web", Model: "grok-imagine-video", ModelRouteID: 3, UpstreamModel: "video", + Seconds: 8, Quality: "720p", Status: media.StatusFailed, ErrorCode: "generation_failed", ErrorMessage: "upstream disconnected", + EgressNodeID: &nodeID, EgressNodeName: "warp", EgressScope: "grok_web", EgressMode: "proxy", + InputJSON: `{}`, CreatedAt: completedAt.Add(-time.Minute), CompletedAt: &completedAt, + }} + recorder := &durableVideoAuditRecorder{} + service := &Service{mediaJobs: repository, audits: recorder} + if err := service.RecoverVideoJobs(context.Background()); err != nil { + t.Fatal(err) + } + if repository.job.UsageRecordedAt == nil || recorder.calls != 1 { + t.Fatalf("recordedAt = %v, audit calls = %d", repository.job.UsageRecordedAt, recorder.calls) + } + if recorder.last.StatusCode != 502 || recorder.last.ErrorCode != "generation_failed" || recorder.last.EgressNodeID == nil || *recorder.last.EgressNodeID != nodeID || recorder.last.EgressNodeName != "warp" || recorder.last.EgressMode != audit.EgressModeProxy { + t.Fatalf("audit = %#v", recorder.last) + } + if recorder.last.EstimatedCostInUSDTicks != 0 || recorder.last.MediaOutputSeconds != 0 { + t.Fatalf("failed job was billed: %#v", recorder.last) + } +} + func TestVideoQueueIsBoundedAndDeduplicated(t *testing.T) { service := &Service{} service.ConfigureMedia(&videoUsageRepository{}, 1) @@ -82,12 +110,20 @@ func (r *videoUsageRepository) GetMediaJob(context.Context, string, uint64) (med func (r *videoUsageRepository) UpdateMediaJob(context.Context, media.Job) error { return nil } +func (r *videoUsageRepository) ListMediaJobs(context.Context, repository.MediaJobListQuery) ([]media.Job, int64, error) { + return nil, 0, nil +} + +func (r *videoUsageRepository) SummarizeMediaJobs(context.Context) (repository.MediaJobStats, error) { + return repository.MediaJobStats{}, nil +} + func (r *videoUsageRepository) ListRecoverableMediaJobs(context.Context, int) ([]media.Job, error) { return nil, nil } -func (r *videoUsageRepository) ListUnrecordedCompletedMediaJobs(context.Context, int) ([]media.Job, error) { - if r.job.UsageRecordedAt != nil { +func (r *videoUsageRepository) ListUnrecordedTerminalMediaJobs(context.Context, int) ([]media.Job, error) { + if r.job.UsageRecordedAt != nil || (r.job.Status != media.StatusCompleted && r.job.Status != media.StatusFailed) { return nil, nil } return []media.Job{r.job}, nil diff --git a/backend/internal/application/media/service.go b/backend/internal/application/media/service.go index b6b5a329..094916ed 100644 --- a/backend/internal/application/media/service.go +++ b/backend/internal/application/media/service.go @@ -21,45 +21,55 @@ import ( ) var ( - ErrAssetNotFound = errors.New("媒体资源不存在") - ErrInvalidImage = errors.New("图片内容无效") + ErrAssetNotFound = errors.New("媒体资源不存在") + ErrInvalidImage = errors.New("图片内容无效") + ErrInvalidFilter = errors.New("媒体筛选条件无效") + ErrMediaJobsUnavailable = errors.New("视频任务仓储未配置") ) -// defaultPublicBaseURL is the last-resort fallback used when neither the -// explicit config nor the request-derived base URL is available. -const defaultPublicBaseURL = "http://127.0.0.1:8000" - // Service 负责图片校验、文件落盘和元数据持久化的一致性收口。 type Service struct { - assets repository.MediaAssetRepository - objects repository.MediaObjectStorage - cleanupLock repository.DistributedLock - publicBaseURL string - preferRequestBaseURL bool - configMu sync.RWMutex - maxImageBytes int64 - maxTotalBytes int64 - cleanupAt int - cleanupEvery time.Duration - cleanupSignal chan struct{} - configChanged chan struct{} - totalBytes atomic.Int64 + assets repository.MediaAssetRepository + jobs repository.MediaJobRepository + objects repository.MediaObjectStorage + cleanupLock repository.DistributedLock + publicBaseURL string + configMu sync.RWMutex + maxImageBytes int64 + maxTotalBytes int64 + cleanupAt int + cleanupEvery time.Duration + cleanupSignal chan struct{} + configChanged chan struct{} + totalBytes atomic.Int64 } type Config struct { PublicBaseURL string - PreferRequestBaseURL bool MaxImageBytes int64 MaxTotalBytes int64 CleanupThresholdPercent int CleanupInterval time.Duration } -func NewService(assets repository.MediaAssetRepository, objects repository.MediaObjectStorage, cleanupLock repository.DistributedLock, cfg Config) *Service { +type ImageStats struct { + TotalImages int64 + TotalBytes int64 +} + +type VideoStats struct { + TotalJobs int64 + Completed int64 + Failed int64 + InProgress int64 + Queued int64 +} + +func NewService(assets repository.MediaAssetRepository, jobs repository.MediaJobRepository, objects repository.MediaObjectStorage, cleanupLock repository.DistributedLock, cfg Config) *Service { return &Service{ - assets: assets, objects: objects, cleanupLock: cleanupLock, - publicBaseURL: strings.TrimRight(cfg.PublicBaseURL, "/"), preferRequestBaseURL: cfg.PreferRequestBaseURL, - maxImageBytes: cfg.MaxImageBytes, maxTotalBytes: cfg.MaxTotalBytes, cleanupAt: cfg.CleanupThresholdPercent, cleanupEvery: cfg.CleanupInterval, + assets: assets, jobs: jobs, objects: objects, cleanupLock: cleanupLock, + publicBaseURL: strings.TrimRight(strings.TrimSpace(cfg.PublicBaseURL), "/"), maxImageBytes: cfg.MaxImageBytes, + maxTotalBytes: cfg.MaxTotalBytes, cleanupAt: cfg.CleanupThresholdPercent, cleanupEvery: cfg.CleanupInterval, cleanupSignal: make(chan struct{}, 1), configChanged: make(chan struct{}, 1), } } @@ -67,8 +77,7 @@ func NewService(assets repository.MediaAssetRepository, objects repository.Media // UpdateConfig 热更新媒体容量和清理策略,不重建底层存储实例。 func (s *Service) UpdateConfig(cfg Config) { s.configMu.Lock() - s.publicBaseURL = strings.TrimRight(cfg.PublicBaseURL, "/") - s.preferRequestBaseURL = cfg.PreferRequestBaseURL + s.publicBaseURL = strings.TrimRight(strings.TrimSpace(cfg.PublicBaseURL), "/") s.maxImageBytes = cfg.MaxImageBytes s.maxTotalBytes = cfg.MaxTotalBytes s.cleanupAt = cfg.CleanupThresholdPercent @@ -118,26 +127,8 @@ func (s *Service) SaveImage(ctx context.Context, data []byte) (mediadomain.Asset } // PublicImageURL 返回可直接用于图片展示的公开资源地址。 -// Priority: -// 1. request-derived baseURL when preferRequestBaseURL is enabled and request base is non-empty -// 2. configured PublicBaseURL when non-empty -// 3. request-derived baseURL when available -// 4. defaultPublicBaseURL as a last-resort fallback -func (s *Service) PublicImageURL(baseURL, id string) string { - cfg := s.runtimeConfig() - requestBase := strings.TrimRight(strings.TrimSpace(baseURL), "/") - configuredBase := strings.TrimRight(strings.TrimSpace(cfg.PublicBaseURL), "/") - switch { - case cfg.PreferRequestBaseURL && requestBase != "": - baseURL = requestBase - case configuredBase != "": - baseURL = configuredBase - case requestBase != "": - baseURL = requestBase - default: - baseURL = defaultPublicBaseURL - } - return strings.TrimRight(baseURL, "/") + "/v1/media/images/" + id +func (s *Service) PublicImageURL(id string) string { + return s.runtimeConfig().PublicBaseURL + "/v1/media/images/" + id } // OpenImage 读取图片元数据和正文,不向调用方暴露实际文件路径。 @@ -162,6 +153,72 @@ func (s *Service) OpenImage(ctx context.Context, id string) (mediadomain.Asset, return asset, body, nil } +// AdminListImages 分页返回图片资源列表。 +func (s *Service) AdminListImages(ctx context.Context, page, pageSize int, search string) ([]mediadomain.Asset, int64, error) { + return s.assets.ListMediaAssets(ctx, repository.MediaAssetListQuery{Page: mediaPageQuery(page, pageSize, search, repository.SortQuery{})}) +} + +// AdminListVideoJobs 分页返回视频任务列表。 +func (s *Service) AdminListVideoJobs(ctx context.Context, page, pageSize int, search, status string, sort repository.SortQuery) ([]mediadomain.Job, int64, error) { + if s.jobs == nil { + return nil, 0, ErrMediaJobsUnavailable + } + status = strings.TrimSpace(status) + if !validMediaStatus(status) || !repository.IsValidSort(sort, "prompt", "model", "status", "progress", "spec", "account", "createdAt", "completedAt") { + return nil, 0, ErrInvalidFilter + } + return s.jobs.ListMediaJobs(ctx, repository.MediaJobListQuery{ + Page: mediaPageQuery(page, pageSize, search, sort), + Filter: repository.MediaJobListFilter{Status: status}, + }) +} + +// AdminImageStats 返回图片统计信息。 +func (s *Service) AdminImageStats(ctx context.Context) (ImageStats, error) { + stats, err := s.assets.SummarizeMediaAssets(ctx) + if err != nil { + return ImageStats{}, err + } + return ImageStats{TotalImages: stats.TotalImages, TotalBytes: stats.TotalBytes}, nil +} + +// AdminVideoStats 返回视频任务统计信息。 +func (s *Service) AdminVideoStats(ctx context.Context) (VideoStats, error) { + if s.jobs == nil { + return VideoStats{}, ErrMediaJobsUnavailable + } + stats, err := s.jobs.SummarizeMediaJobs(ctx) + if err != nil { + return VideoStats{}, err + } + return VideoStats{ + TotalJobs: stats.TotalJobs, Completed: stats.Completed, Failed: stats.Failed, + InProgress: stats.InProgress, Queued: stats.Queued, + }, nil +} + +func mediaPageQuery(page, pageSize int, search string, sort repository.SortQuery) repository.PageQuery { + if page < 1 { + page = 1 + } + if pageSize < 1 { + pageSize = 20 + } + if pageSize > 100 { + pageSize = 100 + } + return repository.PageQuery{Offset: (page - 1) * pageSize, Limit: pageSize, Search: strings.TrimSpace(search), Sort: sort} +} + +func validMediaStatus(status string) bool { + switch mediadomain.Status(status) { + case "", mediadomain.StatusQueued, mediadomain.StatusInProgress, mediadomain.StatusCompleted, mediadomain.StatusFailed: + return true + default: + return false + } +} + // RunCleanup 响应容量阈值并按周期清理最旧媒体资源。 func (s *Service) RunCleanup(ctx context.Context, onError func(error)) { cfg := s.runtimeConfig() @@ -250,7 +307,7 @@ func (s *Service) runtimeConfig() Config { s.configMu.RLock() defer s.configMu.RUnlock() return Config{ - PublicBaseURL: s.publicBaseURL, PreferRequestBaseURL: s.preferRequestBaseURL, + PublicBaseURL: s.publicBaseURL, MaxImageBytes: s.maxImageBytes, MaxTotalBytes: s.maxTotalBytes, CleanupThresholdPercent: s.cleanupAt, CleanupInterval: s.cleanupEvery, } diff --git a/backend/internal/application/media/service_test.go b/backend/internal/application/media/service_test.go index ac170f3d..9b89bf38 100644 --- a/backend/internal/application/media/service_test.go +++ b/backend/internal/application/media/service_test.go @@ -33,7 +33,7 @@ func TestServicePersistsAndReopensImage(t *testing.T) { if err != nil { t.Fatal(err) } - service := NewService(relational.NewMediaAssetRepository(database), objects, nil, Config{ + service := NewService(relational.NewMediaAssetRepository(database), relational.NewMediaJobRepository(database), objects, nil, Config{ PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: 10 * time.Minute, }) @@ -45,7 +45,7 @@ func TestServicePersistsAndReopensImage(t *testing.T) { if asset.MIMEType != "image/png" || asset.SizeBytes != int64(len(raw)) || len(asset.SHA256) != 64 { t.Fatalf("asset = %#v", asset) } - if got := service.PublicImageURL("", asset.ID); got != "https://api.example/v1/media/images/"+asset.ID { + if got := service.PublicImageURL(asset.ID); got != "https://api.example/v1/media/images/"+asset.ID { t.Fatalf("public URL = %q", got) } stored, body, err := service.OpenImage(ctx, asset.ID) @@ -96,7 +96,7 @@ func TestCleanupDeletesOldestAssetsAtThreshold(t *testing.T) { t.Fatal(err) } } - service := NewService(repository, objects, nil, Config{ + service := NewService(repository, relational.NewMediaJobRepository(database), objects, nil, Config{ PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: int64(len(raw) * 2), CleanupThresholdPercent: 50, CleanupInterval: 10 * time.Minute, @@ -146,7 +146,7 @@ func TestCleanupPreservesMetadataWhenLocalObjectIsMissing(t *testing.T) { if err := objects.Delete(ctx, key); err != nil { t.Fatal(err) } - service := NewService(repository, objects, nil, Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: int64(len(raw)), CleanupThresholdPercent: 50, CleanupInterval: 10 * time.Minute}) + service := NewService(repository, relational.NewMediaJobRepository(database), objects, nil, Config{PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: int64(len(raw)), CleanupThresholdPercent: 50, CleanupInterval: 10 * time.Minute}) if _, err := service.Cleanup(ctx); !errors.Is(err, os.ErrNotExist) { t.Fatalf("cleanup error = %v", err) } @@ -155,28 +155,15 @@ func TestCleanupPreservesMetadataWhenLocalObjectIsMissing(t *testing.T) { } } -func TestPublicImageURLPriority(t *testing.T) { - cases := []struct { - name string - prefer bool - configured string - requestBase string - wantPrefix string - }{ - {name: "prefer request when enabled", prefer: true, configured: "https://config.example", requestBase: "https://request.example", wantPrefix: "https://request.example"}, - {name: "configured wins when prefer disabled", prefer: false, configured: "https://config.example", requestBase: "https://request.example", wantPrefix: "https://config.example"}, - {name: "configured fallback when request empty", prefer: true, configured: "https://config.example", requestBase: "", wantPrefix: "https://config.example"}, - {name: "request fallback when config empty and prefer disabled", prefer: false, configured: "", requestBase: "https://request.example", wantPrefix: "https://request.example"}, - {name: "default fallback when both empty", prefer: true, configured: "", requestBase: "", wantPrefix: "http://127.0.0.1:8000"}, +func TestPublicImageURLUsesHotReloadedBase(t *testing.T) { + service := NewService(nil, nil, nil, nil, Config{PublicBaseURL: "https://config.example/base/"}) + if got := service.PublicImageURL("img_demo"); got != "https://config.example/base/v1/media/images/img_demo" { + t.Fatalf("configured URL = %q", got) } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - service := NewService(nil, nil, nil, Config{PublicBaseURL: tc.configured, PreferRequestBaseURL: tc.prefer}) - got := service.PublicImageURL(tc.requestBase, "img_demo") - want := tc.wantPrefix + "/v1/media/images/img_demo" - if got != want { - t.Fatalf("got %q want %q", got, want) - } - }) + updated := service.runtimeConfig() + updated.PublicBaseURL = "https://runtime.example/api/" + service.UpdateConfig(updated) + if got := service.PublicImageURL("img_demo"); got != "https://runtime.example/api/v1/media/images/img_demo" { + t.Fatalf("hot-reloaded URL = %q", got) } } diff --git a/backend/internal/application/settings/service.go b/backend/internal/application/settings/service.go index 103a001d..f1a3d15c 100644 --- a/backend/internal/application/settings/service.go +++ b/backend/internal/application/settings/service.go @@ -73,8 +73,7 @@ type MediaConfig struct { // FrontendConfig 是管理接口使用的公开 API 地址输入。 type FrontendConfig struct { - PublicAPIBaseURL string - PreferRequestBaseURL bool + PublicAPIBaseURL string } // RoutingConfig 是管理接口使用的路由可编辑输入。 @@ -166,11 +165,11 @@ func (s *Service) Get() Snapshot { return s.snapshotLocked() } -// PublicAPIBaseURL 返回当前配置的公开 API 根地址(可能为空)。 +// PublicAPIBaseURL 返回运行设置、配置文件或内置默认值解析后的公开 API 根地址。 func (s *Service) PublicAPIBaseURL() string { s.mu.RLock() defer s.mu.RUnlock() - return strings.TrimRight(strings.TrimSpace(s.cfg.Frontend.PublicAPIBaseURL), "/") + return s.cfg.Frontend.EffectivePublicAPIBaseURL() } // Update 校验并持久化运行设置,再原子替换进程内配置。 @@ -282,13 +281,7 @@ func applyDomainConfig(base config.Config, value settingsdomain.Config) config.C base.Media.MaxTotalBytes = value.Media.MaxTotalBytes base.Media.CleanupThresholdPercent = value.Media.CleanupThresholdPercent base.Media.CleanupInterval = config.Duration(value.Media.CleanupInterval) - // 旧持久化数据没有 Frontend 字段时保持 YAML/默认值,避免把 publicApiBaseURL 清空。 - if value.Frontend.PreferRequestBaseURL != nil || strings.TrimSpace(value.Frontend.PublicAPIBaseURL) != "" { - base.Frontend.PublicAPIBaseURL = strings.TrimSpace(value.Frontend.PublicAPIBaseURL) - if value.Frontend.PreferRequestBaseURL != nil { - base.Frontend.PreferRequestBaseURL = *value.Frontend.PreferRequestBaseURL - } - } + base.Frontend.PublicAPIBaseURLOverride = strings.TrimSpace(value.Frontend.PublicAPIBaseURL) base.Routing = config.RoutingConfig{ StickyTTL: config.Duration(value.Routing.StickyTTL), CooldownBase: config.Duration(value.Routing.CooldownBase), CooldownMax: config.Duration(value.Routing.CooldownMax), CapacityWait: config.Duration(capacityWait), MaxAttempts: value.Routing.MaxAttempts, @@ -333,7 +326,7 @@ func toDomainConfig(value config.Config) settingsdomain.Config { CleanupThresholdPercent: value.Media.CleanupThresholdPercent, CleanupInterval: value.Media.CleanupInterval.Value(), }, Frontend: settingsdomain.FrontendConfig{ - PublicAPIBaseURL: value.Frontend.PublicAPIBaseURL, PreferRequestBaseURL: boolPtr(value.Frontend.PreferRequestBaseURL), + PublicAPIBaseURL: value.Frontend.PublicAPIBaseURLOverride, }, Routing: settingsdomain.RoutingConfig{ StickyTTL: value.Routing.StickyTTL.Value(), CooldownBase: value.Routing.CooldownBase.Value(), @@ -396,8 +389,7 @@ func mergeEditable(current config.Config, input EditableConfig) (config.Config, next.Media.MaxImageBytes = input.Media.MaxImageBytes next.Media.MaxTotalBytes = input.Media.MaxTotalBytes next.Media.CleanupThresholdPercent = input.Media.CleanupThresholdPercent - next.Frontend.PublicAPIBaseURL = strings.TrimSpace(input.Frontend.PublicAPIBaseURL) - next.Frontend.PreferRequestBaseURL = input.Frontend.PreferRequestBaseURL + next.Frontend.PublicAPIBaseURLOverride = strings.TrimSpace(input.Frontend.PublicAPIBaseURL) next.Routing.MaxAttempts = input.Routing.MaxAttempts next.Audit.BufferSize = input.Audit.BufferSize next.Audit.BatchSize = input.Audit.BatchSize @@ -467,7 +459,7 @@ func toEditable(cfg config.Config) EditableConfig { CleanupThresholdPercent: cfg.Media.CleanupThresholdPercent, CleanupInterval: cfg.Media.CleanupInterval.String(), }, Frontend: FrontendConfig{ - PublicAPIBaseURL: cfg.Frontend.PublicAPIBaseURL, PreferRequestBaseURL: cfg.Frontend.PreferRequestBaseURL, + PublicAPIBaseURL: cfg.Frontend.PublicAPIBaseURLOverride, }, Routing: RoutingConfig{ StickyTTL: cfg.Routing.StickyTTL.String(), CooldownBase: cfg.Routing.CooldownBase.String(), @@ -479,7 +471,3 @@ func toEditable(cfg config.Config) EditableConfig { ClientKeyDefaults: ClientKeyDefaultsConfig{RPMLimit: cfg.ClientKeyDefaults.RPMLimit, MaxConcurrent: cfg.ClientKeyDefaults.MaxConcurrent}, } } - -func boolPtr(value bool) *bool { - return &value -} diff --git a/backend/internal/application/settings/service_test.go b/backend/internal/application/settings/service_test.go index 0e519014..a31d60ee 100644 --- a/backend/internal/application/settings/service_test.go +++ b/backend/internal/application/settings/service_test.go @@ -50,7 +50,6 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) { input.Media.CleanupThresholdPercent = 75 input.Media.CleanupInterval = "5m" input.Frontend.PublicAPIBaseURL = "http://public.example.com" - input.Frontend.PreferRequestBaseURL = false input.ProviderConsole.BaseURL = "https://console.example.com" input.ProviderConsole.UserAgent = "console-test-agent" input.ProviderConsole.ChatTimeout = "6m" @@ -66,7 +65,7 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) { if applied.Media.MaxTotalBytes != 2<<30 || applied.Media.CleanupThresholdPercent != 75 || applied.Media.CleanupInterval.Value() != 5*time.Minute { t.Fatalf("media configuration was not applied: %#v", applied.Media) } - if applied.Frontend.PublicAPIBaseURL != "http://public.example.com" || applied.Frontend.PreferRequestBaseURL { + if applied.Frontend.PublicAPIBaseURLOverride != "http://public.example.com" || applied.Frontend.EffectivePublicAPIBaseURL() != "http://public.example.com" { t.Fatalf("frontend configuration was not applied: %#v", applied.Frontend) } if applied.Batch.ImportConcurrency != 26 || applied.Batch.ConversionConcurrency != 27 || applied.Batch.SyncConcurrency != 28 || applied.Batch.RefreshConcurrency != 29 || applied.Batch.RandomDelay.Value() != 750*time.Millisecond { @@ -271,51 +270,37 @@ func testConfig(t *testing.T) config.Config { func TestLoadPersistedKeepsYAMLFrontendWhenUnset(t *testing.T) { cfg := testConfig(t) cfg.Frontend.PublicAPIBaseURL = "http://yaml.example.com" - cfg.Frontend.PreferRequestBaseURL = true - randomDelay := cfg.Batch.RandomDelay.Value() + value := toDomainConfig(cfg) + value.Frontend = settingsdomain.FrontendConfig{} repository := &runtimeSettingsRepositoryStub{ - value: settingsdomain.Config{ - ProviderBuild: settingsdomain.ProviderBuildConfig{ - BaseURL: cfg.Provider.Build.BaseURL, ClientVersion: cfg.Provider.Build.ClientVersion, - ClientIdentifier: cfg.Provider.Build.ClientIdentifier, TokenAuth: cfg.Provider.Build.TokenAuth, - UserAgent: cfg.Provider.Build.UserAgent, - }, - ProviderWeb: settingsdomain.ProviderWebConfig{ - BaseURL: cfg.Provider.Web.BaseURL, StatsigMode: cfg.Provider.Web.StatsigMode, StatsigSignerURL: cfg.Provider.Web.StatsigSignerURL, - QuotaTimeout: cfg.Provider.Web.QuotaTimeout.Value(), ChatTimeout: cfg.Provider.Web.ChatTimeout.Value(), - ImageTimeout: cfg.Provider.Web.ImageTimeout.Value(), VideoTimeout: cfg.Provider.Web.VideoTimeout.Value(), - MediaConcurrency: cfg.Provider.Web.MediaConcurrency, AllowNSFW: cfg.Provider.Web.AllowNSFW, - RecoveryBackoffBase: cfg.Provider.Web.RecoveryBackoffBase.Value(), RecoveryBackoffMax: cfg.Provider.Web.RecoveryBackoffMax.Value(), - }, - ProviderConsole: settingsdomain.ProviderConsoleConfig{ - BaseURL: cfg.Provider.Console.BaseURL, UserAgent: cfg.Provider.Console.UserAgent, ChatTimeout: cfg.Provider.Console.ChatTimeout.Value(), - }, - Batch: settingsdomain.BatchConfig{ - ImportConcurrency: cfg.Batch.ImportConcurrency, ConversionConcurrency: cfg.Batch.ConversionConcurrency, - SyncConcurrency: cfg.Batch.SyncConcurrency, RefreshConcurrency: cfg.Batch.RefreshConcurrency, RandomDelay: &randomDelay, - }, - Media: settingsdomain.MediaConfig{ - MaxImageBytes: cfg.Media.MaxImageBytes, MaxTotalBytes: cfg.Media.MaxTotalBytes, - CleanupThresholdPercent: cfg.Media.CleanupThresholdPercent, CleanupInterval: cfg.Media.CleanupInterval.Value(), - }, - Routing: settingsdomain.RoutingConfig{ - StickyTTL: cfg.Routing.StickyTTL.Value(), CooldownBase: cfg.Routing.CooldownBase.Value(), - CooldownMax: cfg.Routing.CooldownMax.Value(), CapacityWait: cfg.Routing.CapacityWait.Value(), MaxAttempts: cfg.Routing.MaxAttempts, - }, - Audit: settingsdomain.AuditConfig{ - BufferSize: cfg.Audit.BufferSize, BatchSize: cfg.Audit.BatchSize, FlushInterval: cfg.Audit.FlushInterval.Value(), - }, - ClientKeyDefaults: settingsdomain.ClientKeyDefaultsConfig{ - RPMLimit: cfg.ClientKeyDefaults.RPMLimit, MaxConcurrent: cfg.ClientKeyDefaults.MaxConcurrent, - }, - }, + value: value, found: true, revision: 1, updatedAt: time.Now().UTC(), } loaded, _, _, err := LoadPersisted(context.Background(), cfg, repository) if err != nil { t.Fatal(err) } - if loaded.Frontend.PublicAPIBaseURL != "http://yaml.example.com" || !loaded.Frontend.PreferRequestBaseURL { + if loaded.Frontend.PublicAPIBaseURL != "http://yaml.example.com" || loaded.Frontend.PublicAPIBaseURLOverride != "" || loaded.Frontend.EffectivePublicAPIBaseURL() != "http://yaml.example.com" { t.Fatalf("frontend = %#v", loaded.Frontend) } } + +func TestUpdateEmptyFrontendOverrideFallsBackToYAML(t *testing.T) { + cfg := testConfig(t) + cfg.Frontend.PublicAPIBaseURL = "http://yaml.example.com" + cfg.Frontend.PublicAPIBaseURLOverride = "http://runtime.example.com" + repository := &runtimeSettingsRepositoryStub{} + var applied config.Config + service := NewService(cfg, time.Time{}, 0, repository, nil, func(next config.Config) { applied = next }) + input := service.Get().Config + input.Frontend.PublicAPIBaseURL = "" + if _, err := service.Update(context.Background(), 0, input); err != nil { + t.Fatal(err) + } + if applied.Frontend.PublicAPIBaseURLOverride != "" || applied.Frontend.EffectivePublicAPIBaseURL() != "http://yaml.example.com" { + t.Fatalf("frontend fallback = %#v", applied.Frontend) + } + if repository.value.Frontend.PublicAPIBaseURL != "" { + t.Fatalf("persisted override = %q", repository.value.Frontend.PublicAPIBaseURL) + } +} diff --git a/backend/internal/domain/audit/audit.go b/backend/internal/domain/audit/audit.go index 67ea6afa..fb949cd5 100644 --- a/backend/internal/domain/audit/audit.go +++ b/backend/internal/domain/audit/audit.go @@ -21,7 +21,50 @@ const ( UsageSourceNone UsageSource = "none" ) -// Record 表示不包含提示词和响应正文的推理请求审计记录。 +type AttemptSource string + +const ( + AttemptSourceUpstreamHTTP AttemptSource = "upstream_http" + AttemptSourceTransport AttemptSource = "gateway_transport" + AttemptSourceCredential AttemptSource = "credential" +) + +type ErrorFrame struct { + Type string + Message string +} + +// Attempt 保存一次失败尝试经过裁剪和脱敏的管理员诊断快照。 +type Attempt struct { + ID uint64 + AuditID uint64 + Number int + Source AttemptSource + Stage string + AccountID *uint64 + AccountName string + Method string + RequestPath string + UpstreamURL string + StartedAt time.Time + DurationMS int64 + UpstreamStatusCode *int + UpstreamStatus string + ResponseHeaders map[string][]string + ResponseBody []byte + ResponseBodyTruncated bool + TransportError string + ErrorChain []ErrorFrame +} + +type EgressMode string + +const ( + EgressModeDirect EgressMode = "direct" + EgressModeProxy EgressMode = "proxy" +) + +// Record 表示推理请求审计;成功请求不保存正文,失败请求仅保留受限诊断快照。 type Record struct { ID uint64 EventID string @@ -36,6 +79,10 @@ type Record struct { UsageSource UsageSource AccountID *uint64 AccountName string + EgressNodeID *uint64 + EgressNodeName string + EgressScope string + EgressMode EgressMode StatusCode int Streaming bool MediaInputImages int64 @@ -56,6 +103,8 @@ type Record struct { ContextOutputTokens int64 DurationMS int64 ErrorCode string + AttemptCount int + Attempts []Attempt CreatedAt time.Time } diff --git a/backend/internal/domain/media/job.go b/backend/internal/domain/media/job.go index 21826f90..54723688 100644 --- a/backend/internal/domain/media/job.go +++ b/backend/internal/domain/media/job.go @@ -19,6 +19,10 @@ type Job struct { ClientKeyName string AccountID uint64 AccountName string + EgressNodeID *uint64 + EgressNodeName string + EgressScope string + EgressMode string Provider string Model string ModelRouteID uint64 diff --git a/backend/internal/domain/settings/settings.go b/backend/internal/domain/settings/settings.go index 3ad91213..bcb7242d 100644 --- a/backend/internal/domain/settings/settings.go +++ b/backend/internal/domain/settings/settings.go @@ -15,11 +15,9 @@ type Config struct { ClientKeyDefaults ClientKeyDefaultsConfig } -// FrontendConfig 定义公开 API 地址与图片 URL 解析策略。 -// PreferRequestBaseURL 使用指针,便于旧持久化数据缺省时保留默认 true。 +// FrontendConfig 定义公开 API 地址的运行时覆盖值;留空时使用配置文件值。 type FrontendConfig struct { - PublicAPIBaseURL string - PreferRequestBaseURL *bool + PublicAPIBaseURL string } type ProviderConsoleConfig struct { diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index 99b9a8de..4f7f0d1f 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -61,9 +61,21 @@ type ServerConfig struct { } type FrontendConfig struct { - PublicAPIBaseURL string `yaml:"publicApiBaseURL"` - PreferRequestBaseURL bool `yaml:"preferRequestBaseURL"` - StaticPath string `yaml:"staticPath"` + PublicAPIBaseURL string `yaml:"publicApiBaseURL"` + PublicAPIBaseURLOverride string `yaml:"-"` + StaticPath string `yaml:"staticPath"` +} + +const DefaultPublicAPIBaseURL = "http://127.0.0.1:8000" + +// EffectivePublicAPIBaseURL 按运行设置、配置文件、内置默认值的顺序解析公开地址。 +func (c FrontendConfig) EffectivePublicAPIBaseURL() string { + for _, value := range []string{c.PublicAPIBaseURLOverride, c.PublicAPIBaseURL} { + if value = strings.TrimRight(strings.TrimSpace(value), "/"); value != "" { + return value + } + } + return DefaultPublicAPIBaseURL } type DatabaseConfig struct { @@ -288,13 +300,21 @@ func (c Config) Validate() error { if c.Server.RequestTimeout.Value() <= 0 || c.Server.RequestTimeout.Value() > maxRequestTimeout { return errors.New("server.requestTimeout 必须大于零且不超过 24 小时") } - if publicBase := strings.TrimSpace(c.Frontend.PublicAPIBaseURL); publicBase != "" { - publicAPIURL, err := url.ParseRequestURI(publicBase) - if err != nil || (publicAPIURL.Scheme != "http" && publicAPIURL.Scheme != "https") || publicAPIURL.Host == "" || publicAPIURL.User != nil || publicAPIURL.RawQuery != "" || publicAPIURL.Fragment != "" { - return errors.New("frontend.publicApiBaseURL 必须是不含凭据、查询参数和片段的 HTTP(S) URL") - } - if publicAPIURL.Scheme == "https" && !c.Auth.SecureCookies { - return errors.New("HTTPS 公共地址必须启用 auth.secureCookies") + for _, item := range []struct { + name string + value string + }{ + {name: "frontend.publicApiBaseURL", value: c.Frontend.PublicAPIBaseURL}, + {name: "frontend.publicApiBaseURL 运行设置", value: c.Frontend.PublicAPIBaseURLOverride}, + } { + if publicBase := strings.TrimSpace(item.value); publicBase != "" { + publicAPIURL, err := url.ParseRequestURI(publicBase) + if err != nil || (publicAPIURL.Scheme != "http" && publicAPIURL.Scheme != "https") || publicAPIURL.Host == "" || publicAPIURL.User != nil || publicAPIURL.RawQuery != "" || publicAPIURL.Fragment != "" { + return fmt.Errorf("%s 必须是不含凭据、查询参数和片段的 HTTP(S) URL", item.name) + } + if publicAPIURL.Scheme == "https" && !c.Auth.SecureCookies { + return errors.New("HTTPS 公共地址必须启用 auth.secureCookies") + } } } switch c.Database.Driver { @@ -434,7 +454,7 @@ func defaultConfig() Config { ReadTimeout: Duration(15 * time.Minute), RequestTimeout: Duration(2 * time.Hour), }, - Frontend: FrontendConfig{PublicAPIBaseURL: "", PreferRequestBaseURL: true, StaticPath: "./frontend/dist"}, + Frontend: FrontendConfig{PublicAPIBaseURL: DefaultPublicAPIBaseURL, StaticPath: "./frontend/dist"}, Database: DatabaseConfig{ Driver: "sqlite", SQLite: SQLiteDatabaseConfig{Path: "./data/backend.db"}, diff --git a/backend/internal/infra/config/config_test.go b/backend/internal/infra/config/config_test.go index fc4ef53b..c9a93b11 100644 --- a/backend/internal/infra/config/config_test.go +++ b/backend/internal/infra/config/config_test.go @@ -273,3 +273,22 @@ func TestValidateFrontendPublicAPIBaseURL(t *testing.T) { t.Fatalf("valid frontend.publicApiBaseURL rejected: %v", err) } } + +func TestEffectivePublicAPIBaseURLPriority(t *testing.T) { + cases := []struct { + name string + frontend FrontendConfig + want string + }{ + {name: "runtime override", frontend: FrontendConfig{PublicAPIBaseURL: "https://yaml.example/base", PublicAPIBaseURLOverride: "https://runtime.example/api/"}, want: "https://runtime.example/api"}, + {name: "yaml fallback", frontend: FrontendConfig{PublicAPIBaseURL: "https://yaml.example/base/"}, want: "https://yaml.example/base"}, + {name: "local fallback", frontend: FrontendConfig{}, want: DefaultPublicAPIBaseURL}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := tc.frontend.EffectivePublicAPIBaseURL(); got != tc.want { + t.Fatalf("EffectivePublicAPIBaseURL() = %q, want %q", got, tc.want) + } + }) + } +} diff --git a/backend/internal/infra/egress/manager.go b/backend/internal/infra/egress/manager.go index dda0c74a..f3226f99 100644 --- a/backend/internal/infra/egress/manager.go +++ b/backend/internal/infra/egress/manager.go @@ -24,6 +24,7 @@ const nodeSnapshotTTL = time.Second type Lease struct { NodeID uint64 + NodeName string Scope domain.Scope ProxyURL string UserAgent string @@ -111,6 +112,7 @@ func (m *Manager) acquire(ctx context.Context, scope domain.Scope, affinity stri return nil, false, fmt.Errorf("当前没有可用的 %s 出口节点", scope) } if !allowDirect { + recordSelection(ctx, Selection{NodeName: "direct", Scope: scope}) return nil, false, nil } available = []domain.Node{{ID: 0, Name: "direct", Scope: scope, Enabled: true, Health: 1}} @@ -147,8 +149,9 @@ func (m *Manager) acquire(ctx context.Context, scope domain.Scope, affinity stri m.mu.Lock() m.inflight[selected.ID]++ m.mu.Unlock() + recordSelection(ctx, Selection{NodeID: selected.ID, NodeName: selected.Name, Scope: scope, Proxied: proxyURL != ""}) var once sync.Once - return &Lease{NodeID: selected.ID, Scope: scope, ProxyURL: proxyURL, UserAgent: userAgent, CFCookies: cookies, client: client.client, browser: client.browser, release: func() { + return &Lease{NodeID: selected.ID, NodeName: selected.Name, Scope: scope, ProxyURL: proxyURL, UserAgent: userAgent, CFCookies: cookies, client: client.client, browser: client.browser, release: func() { once.Do(func() { m.mu.Lock() m.inflight[selected.ID]-- diff --git a/backend/internal/infra/egress/manager_test.go b/backend/internal/infra/egress/manager_test.go index fd8bd99a..39646c8c 100644 --- a/backend/internal/infra/egress/manager_test.go +++ b/backend/internal/infra/egress/manager_test.go @@ -58,10 +58,39 @@ func TestAcquireIfConfiguredDoesNotChangeBuildDirectTransport(t *testing.T) { t.Fatal(err) } manager := NewManager(egressRepositoryTestStub{}, cipher) - lease, configured, err := manager.AcquireIfConfigured(context.Background(), domain.ScopeBuild, "") + ctx, trace := WithTrace(context.Background()) + lease, configured, err := manager.AcquireIfConfigured(ctx, domain.ScopeBuild, "") if err != nil || configured || lease != nil { t.Fatalf("lease=%#v configured=%v err=%v", lease, configured, err) } + selection, ok := trace.Selection(domain.ScopeBuild) + if !ok || selection.NodeID != 0 || selection.NodeName != "direct" || selection.Proxied { + t.Fatalf("direct selection = %#v, ok=%v", selection, ok) + } +} + +func TestTraceRecordsConfiguredProxyWithoutCredentials(t *testing.T) { + cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") + if err != nil { + t.Fatal(err) + } + encryptedProxy, err := cipher.Encrypt("socks5h://secret:password@127.0.0.1:1080") + if err != nil { + t.Fatal(err) + } + manager := NewManager(egressRepositoryTestStub{nodes: []domain.Node{{ + ID: 42, Name: "primary-proxy", Scope: domain.ScopeBuild, Enabled: true, Health: 1, EncryptedProxyURL: encryptedProxy, + }}}, cipher) + ctx, trace := WithTrace(context.Background()) + lease, configured, err := manager.AcquireIfConfigured(ctx, domain.ScopeBuild, "") + if err != nil || !configured || lease == nil { + t.Fatalf("lease=%#v configured=%v err=%v", lease, configured, err) + } + defer lease.Release() + selection, ok := trace.Selection(domain.ScopeBuild) + if !ok || selection.NodeID != 42 || selection.NodeName != "primary-proxy" || !selection.Proxied { + t.Fatalf("proxy selection = %#v, ok=%v", selection, ok) + } } func TestConfiguredBuildNodeDoesNotOverrideProviderUserAgent(t *testing.T) { diff --git a/backend/internal/infra/egress/trace.go b/backend/internal/infra/egress/trace.go new file mode 100644 index 00000000..79267b8d --- /dev/null +++ b/backend/internal/infra/egress/trace.go @@ -0,0 +1,65 @@ +package egress + +import ( + "context" + "sync" + + domain "github.com/chenyme/grok2api/backend/internal/domain/egress" +) + +// Selection 是一次上游请求实际选择的出口快照。它只包含可安全写入审计的元数据, +// 不包含代理 URL、认证信息、User-Agent 或 Cookie。 +type Selection struct { + NodeID uint64 + NodeName string + Scope domain.Scope + Proxied bool +} + +// Trace 按作用域保留最后一次实际出口选择。相同请求发生出口重试时,审计记录最终尝试; +// Web 资源归档使用独立作用域,不会覆盖主要的 Grok Web 推理出口。 +type Trace struct { + mu sync.RWMutex + selections map[domain.Scope]Selection +} + +type traceContextKey struct{} + +// WithTrace 为一次网关请求创建或复用并发安全的出口选择轨迹。 +func WithTrace(ctx context.Context) (context.Context, *Trace) { + if existing := TraceFromContext(ctx); existing != nil { + return ctx, existing + } + trace := &Trace{selections: make(map[domain.Scope]Selection)} + return context.WithValue(ctx, traceContextKey{}, trace), trace +} + +// TraceFromContext 返回上下文中的出口轨迹;未配置时返回 nil。 +func TraceFromContext(ctx context.Context) *Trace { + if ctx == nil { + return nil + } + trace, _ := ctx.Value(traceContextKey{}).(*Trace) + return trace +} + +// Selection 返回指定作用域最后一次实际出口选择的安全快照。 +func (t *Trace) Selection(scope domain.Scope) (Selection, bool) { + if t == nil { + return Selection{}, false + } + t.mu.RLock() + defer t.mu.RUnlock() + value, ok := t.selections[scope] + return value, ok +} + +func recordSelection(ctx context.Context, value Selection) { + trace := TraceFromContext(ctx) + if trace == nil { + return + } + trace.mu.Lock() + trace.selections[value.Scope] = value + trace.mu.Unlock() +} diff --git a/backend/internal/infra/persistence/relational/audit_repository.go b/backend/internal/infra/persistence/relational/audit_repository.go index b8224fcf..0178a19f 100644 --- a/backend/internal/infra/persistence/relational/audit_repository.go +++ b/backend/internal/infra/persistence/relational/audit_repository.go @@ -3,6 +3,7 @@ package relational import ( "context" "crypto/sha256" + "encoding/json" "errors" "fmt" "math" @@ -20,9 +21,12 @@ type AuditRepository struct{ db *Database } func NewAuditRepository(db *Database) *AuditRepository { return &AuditRepository{db: db} } func (r *AuditRepository) Create(ctx context.Context, value audit.Record) error { - row := toAuditModel(value) + row, attempts, err := toAuditModels(value) + if err != nil { + return err + } return r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { - return createAuditAndBill(tx, row) + return createAuditAndBill(tx, &row, attempts) }) } @@ -33,12 +37,18 @@ func (r *AuditRepository) CreateBatch(ctx context.Context, values []audit.Record return r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { insertedRows := make([]requestAuditModel, 0, len(values)) for _, value := range values { - row := toAuditModel(value) - inserted, err := insertAudit(tx, row) + row, attempts, err := toAuditModels(value) + if err != nil { + return err + } + inserted, err := insertAudit(tx, &row) if err != nil { return err } if inserted { + if err := insertAuditAttempts(tx, row.ID, attempts); err != nil { + return err + } insertedRows = append(insertedRows, row) } } @@ -67,7 +77,7 @@ func (r *AuditRepository) CreateBatch(ctx context.Context, values []audit.Record }) } -func toAuditModel(value audit.Record) requestAuditModel { +func toAuditModels(value audit.Record) (requestAuditModel, []requestAuditAttemptModel, error) { provider := value.Provider if provider == "" { provider = "grok_build" @@ -85,39 +95,98 @@ func toAuditModel(value audit.Record) requestAuditModel { digest := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%d\x00%d\x00%d", value.RequestID, value.ClientKeyID, value.ModelRouteID, value.CreatedAt.UnixNano()))) eventID = fmt.Sprintf("evt_%x", digest[:18]) } - return requestAuditModel{ + row := requestAuditModel{ EventID: truncate(eventID, 64), RequestID: truncate(value.RequestID, 64), ClientKeyID: value.ClientKeyID, ClientKeyName: truncate(value.ClientKeyName, 160), ModelRouteID: value.ModelRouteID, ModelPublicID: truncate(value.ModelPublicID, 255), ModelUpstreamModel: truncate(value.ModelUpstreamModel, 255), Provider: truncate(provider, 32), Operation: string(operation), UsageSource: string(usageSource), - AccountID: value.AccountID, AccountName: truncate(value.AccountName, 160), StatusCode: value.StatusCode, Streaming: value.Streaming, + AccountID: value.AccountID, AccountName: truncate(value.AccountName, 160), + EgressNodeID: value.EgressNodeID, EgressNodeName: truncate(value.EgressNodeName, 160), EgressScope: truncate(value.EgressScope, 32), EgressMode: string(value.EgressMode), + StatusCode: value.StatusCode, Streaming: value.Streaming, MediaInputImages: nonNegative(value.MediaInputImages), MediaOutputImages: nonNegative(value.MediaOutputImages), MediaOutputSeconds: nonNegative(value.MediaOutputSeconds), InputTokens: nonNegative(value.InputTokens), CachedInputTokens: nonNegative(value.CachedInputTokens), OutputTokens: nonNegative(value.OutputTokens), ReasoningTokens: nonNegative(value.ReasoningTokens), TotalTokens: nonNegative(value.TotalTokens), CostInUSDTicks: nonNegative(value.CostInUSDTicks), EstimatedCostInUSDTicks: nonNegative(value.EstimatedCostInUSDTicks), PricingModel: truncate(value.PricingModel, 100), PricingVersion: truncate(value.PricingVersion, 20), NumSourcesUsed: nonNegative(value.NumSourcesUsed), NumServerSideToolsUsed: nonNegative(value.NumServerSideToolsUsed), ContextInputTokens: nonNegative(value.ContextInputTokens), ContextOutputTokens: nonNegative(value.ContextOutputTokens), DurationMS: nonNegative(value.DurationMS), - ErrorCode: truncate(value.ErrorCode, 100), CreatedAt: value.CreatedAt, + ErrorCode: truncate(value.ErrorCode, 100), AttemptCount: len(value.Attempts), CreatedAt: value.CreatedAt, } + attempts := make([]requestAuditAttemptModel, 0, len(value.Attempts)) + for _, attempt := range value.Attempts { + responseHeaders, err := json.Marshal(attempt.ResponseHeaders) + if err != nil { + return requestAuditModel{}, nil, fmt.Errorf("序列化审计响应头: %w", err) + } + if attempt.ResponseHeaders == nil { + responseHeaders = []byte("{}") + } + errorChain, err := json.Marshal(attempt.ErrorChain) + if err != nil { + return requestAuditModel{}, nil, fmt.Errorf("序列化审计错误链: %w", err) + } + if attempt.ErrorChain == nil { + errorChain = []byte("[]") + } + attempts = append(attempts, requestAuditAttemptModel{ + Number: attempt.Number, + Source: string(attempt.Source), + Stage: attempt.Stage, + AccountID: attempt.AccountID, + AccountName: truncate(attempt.AccountName, 160), + Method: truncate(attempt.Method, 16), + RequestPath: truncate(attempt.RequestPath, 2048), + UpstreamURL: truncate(attempt.UpstreamURL, 4096), + StartedAt: attempt.StartedAt, + DurationMS: nonNegative(attempt.DurationMS), + UpstreamStatusCode: attempt.UpstreamStatusCode, + UpstreamStatus: truncate(attempt.UpstreamStatus, 128), + ResponseHeadersJSON: string(responseHeaders), + ResponseBody: truncateBytes(attempt.ResponseBody, 65536), + ResponseBodyTruncated: attempt.ResponseBodyTruncated || len(attempt.ResponseBody) > 65536, + TransportError: truncate(attempt.TransportError, 2048), + ErrorChainJSON: string(errorChain), + }) + } + return row, attempts, nil } -func createAuditAndBill(tx *gorm.DB, row requestAuditModel) error { +func truncateBytes(value []byte, limit int) []byte { + if len(value) <= limit { + return value + } + return value[:limit] +} + +func createAuditAndBill(tx *gorm.DB, row *requestAuditModel, attempts []requestAuditAttemptModel) error { inserted, err := insertAudit(tx, row) if err != nil || !inserted { return err } + if err := insertAuditAttempts(tx, row.ID, attempts); err != nil { + return err + } var reservation billingReservationModel reservationErr := tx.Where("event_id = ?", row.EventID).First(&reservation).Error if reservationErr != nil && !errors.Is(reservationErr, gorm.ErrRecordNotFound) { return reservationErr } - return billInsertedAudit(tx, row, reservation, reservationErr == nil) + return billInsertedAudit(tx, *row, reservation, reservationErr == nil) } -func insertAudit(tx *gorm.DB, row requestAuditModel) (bool, error) { - result := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&row) +func insertAudit(tx *gorm.DB, row *requestAuditModel) (bool, error) { + result := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(row) return result.RowsAffected == 1, result.Error } +func insertAuditAttempts(tx *gorm.DB, auditID uint64, attempts []requestAuditAttemptModel) error { + if len(attempts) == 0 { + return nil + } + for index := range attempts { + attempts[index].AuditID = auditID + } + return tx.Create(&attempts).Error +} + func billInsertedAudit(tx *gorm.DB, row requestAuditModel, reservation billingReservationModel, hasReservation bool) error { amount := row.CostInUSDTicks if amount <= 0 { @@ -214,6 +283,27 @@ func (r *AuditRepository) List(ctx context.Context, offset, limit int) ([]audit. return out, total, nil } +func (r *AuditRepository) Get(ctx context.Context, id uint64) (audit.Record, error) { + var row requestAuditModel + if err := r.db.db.WithContext(ctx).First(&row, id).Error; err != nil { + return audit.Record{}, mapError(err) + } + var attemptRows []requestAuditAttemptModel + if err := r.db.db.WithContext(ctx).Where("audit_id = ?", id).Order("number ASC").Find(&attemptRows).Error; err != nil { + return audit.Record{}, err + } + value := toAuditDomain(row) + value.Attempts = make([]audit.Attempt, 0, len(attemptRows)) + for _, attemptRow := range attemptRows { + attempt, err := toAuditAttemptDomain(attemptRow) + if err != nil { + return audit.Record{}, err + } + value.Attempts = append(value.Attempts, attempt) + } + return value, nil +} + // ListCursor 使用“排序值 + ID”复合游标读取审计,避免深分页和同值记录漏读。 func (r *AuditRepository) ListCursor(ctx context.Context, input repository.AuditCursorQuery) ([]audit.Record, bool, error) { query := r.db.db.WithContext(ctx).Model(&requestAuditModel{}) @@ -301,7 +391,7 @@ func (r *AuditRepository) Summarize(ctx context.Context, input repository.AuditS func applyAuditQuery(query *gorm.DB, search string, start, end time.Time, filter repository.AuditListFilter) *gorm.DB { if value := strings.TrimSpace(search); value != "" { pattern := "%" + strings.ToLower(value) + "%" - query = query.Where("LOWER(request_id) LIKE ? OR LOWER(model_public_id) LIKE ? OR LOWER(model_upstream_model) LIKE ?", pattern, pattern, pattern) + query = query.Where("LOWER(request_id) LIKE ? OR LOWER(model_public_id) LIKE ? OR LOWER(model_upstream_model) LIKE ? OR LOWER(egress_node_name) LIKE ?", pattern, pattern, pattern, pattern) } if !start.IsZero() { query = query.Where("created_at >= ?", start) diff --git a/backend/internal/infra/persistence/relational/audit_repository_test.go b/backend/internal/infra/persistence/relational/audit_repository_test.go index bf0d4338..9dc1d75b 100644 --- a/backend/internal/infra/persistence/relational/audit_repository_test.go +++ b/backend/internal/infra/persistence/relational/audit_repository_test.go @@ -2,6 +2,8 @@ package relational import ( "context" + "errors" + "net/http" "path/filepath" "testing" "time" @@ -58,7 +60,7 @@ func TestAuditRepositoryBatchAndCursor(t *testing.T) { {RequestID: "cursor-old", ClientKeyID: 1, ModelRouteID: 1, StatusCode: 200, CreatedAt: now.Add(-48 * time.Hour)}, {RequestID: "cursor-1", ClientKeyID: 1, ModelRouteID: 1, StatusCode: 200, CreatedAt: now.Add(-3 * time.Minute)}, {RequestID: "cursor-2", ClientKeyID: 1, ModelRouteID: 1, StatusCode: 200, CreatedAt: now.Add(-2 * time.Minute)}, - {RequestID: "cursor-3", ClientKeyID: 1, ClientKeyName: "production", ModelRouteID: 1, ModelPublicID: "grok-test", ModelUpstreamModel: "grok-test-upstream", AccountName: "primary", StatusCode: 200, CreatedAt: now.Add(-time.Minute)}, + {RequestID: "cursor-3", ClientKeyID: 1, ClientKeyName: "production", ModelRouteID: 1, ModelPublicID: "grok-test", ModelUpstreamModel: "grok-test-upstream", AccountName: "primary", EgressNodeID: uint64Pointer(42), EgressNodeName: "proxy-shanghai", EgressScope: "grok_web", EgressMode: audit.EgressModeProxy, StatusCode: 200, CreatedAt: now.Add(-time.Minute)}, } if err := repository.CreateBatch(ctx, values); err != nil { t.Fatal(err) @@ -71,9 +73,13 @@ func TestAuditRepositoryBatchAndCursor(t *testing.T) { if len(first) != 2 || !hasMore || first[0].ID <= first[1].ID { t.Fatalf("first page = %#v, hasMore = %v", first, hasMore) } - if first[0].ClientKeyName != "production" || first[0].ModelPublicID != "grok-test" || first[0].ModelUpstreamModel != "grok-test-upstream" || first[0].AccountName != "primary" { + if first[0].ClientKeyName != "production" || first[0].ModelPublicID != "grok-test" || first[0].ModelUpstreamModel != "grok-test-upstream" || first[0].AccountName != "primary" || first[0].EgressNodeID == nil || *first[0].EgressNodeID != 42 || first[0].EgressNodeName != "proxy-shanghai" || first[0].EgressMode != audit.EgressModeProxy { t.Fatalf("audit snapshots = %#v", first[0]) } + matched, _, err := repository.ListCursor(ctx, repositorypkg.AuditCursorQuery{Limit: 10, Search: "proxy-shanghai", Sort: sort}) + if err != nil || len(matched) != 1 || matched[0].RequestID != "cursor-3" { + t.Fatalf("egress search = %#v, err = %v", matched, err) + } second, _, err := repository.ListCursor(ctx, repositorypkg.AuditCursorQuery{Cursor: &repositorypkg.SortCursor{ID: first[len(first)-1].ID, Value: first[len(first)-1].CreatedAt}, Limit: 2, Sort: sort}) if err != nil { t.Fatal(err) @@ -190,6 +196,64 @@ func TestAuditRepositoryAllowsRepeatedExternalRequestIDs(t *testing.T) { } } +func TestAuditRepositoryRoundTripsFailureAttempts(t *testing.T) { + ctx := context.Background() + database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "audit-attempts.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repository := NewAuditRepository(database) + now := time.Now().UTC() + status := http.StatusBadGateway + record := audit.Record{ + EventID: "evt_failure_attempts_0001", RequestID: "failure-attempts", ClientKeyID: 1, ModelRouteID: 1, + StatusCode: http.StatusBadGateway, CreatedAt: now, + Attempts: []audit.Attempt{ + { + Number: 1, Source: audit.AttemptSourceTransport, Stage: "dns_lookup", AccountID: uint64Pointer(7), AccountName: "primary", + Method: http.MethodPost, RequestPath: "/responses", UpstreamURL: "https://api.example.test/v1/responses", StartedAt: now.Add(-2 * time.Second), DurationMS: 125, + TransportError: "lookup api.example.test: no such host", ErrorChain: []audit.ErrorFrame{{Type: "*url.Error", Message: "Post request failed"}, {Type: "*net.DNSError", Message: "no such host"}}, + }, + { + Number: 2, Source: audit.AttemptSourceUpstreamHTTP, Stage: "upstream_response", AccountID: uint64Pointer(8), AccountName: "secondary", + Method: http.MethodPost, RequestPath: "/responses", UpstreamURL: "https://api.example.test/v1/responses", StartedAt: now.Add(-time.Second), DurationMS: 250, + UpstreamStatusCode: &status, UpstreamStatus: "502 Bad Gateway", ResponseHeaders: http.Header{"Content-Type": {"application/json"}, "X-Upstream": {"edge-a", "edge-b"}}, + ResponseBody: []byte{'{', '"', 'e', 'r', 'r', 'o', 'r', '"', ':', ' ', '"', 'f', 'a', 'i', 'l', 'e', 'd', '"', '}', 0xff}, ResponseBodyTruncated: true, + }, + }, + } + if err := repository.Create(ctx, record); err != nil { + t.Fatal(err) + } + stored, err := repository.Get(ctx, 1) + if err != nil { + t.Fatal(err) + } + if stored.AttemptCount != 2 || len(stored.Attempts) != 2 { + t.Fatalf("attempt count = %d, attempts = %#v", stored.AttemptCount, stored.Attempts) + } + if stored.Attempts[0].Number != 1 || stored.Attempts[0].Stage != "dns_lookup" || len(stored.Attempts[0].ErrorChain) != 2 { + t.Fatalf("transport attempt = %#v", stored.Attempts[0]) + } + httpAttempt := stored.Attempts[1] + if httpAttempt.Number != 2 || httpAttempt.UpstreamStatusCode == nil || *httpAttempt.UpstreamStatusCode != status || string(httpAttempt.ResponseBody) != string(record.Attempts[1].ResponseBody) || !httpAttempt.ResponseBodyTruncated || len(httpAttempt.ResponseHeaders["X-Upstream"]) != 2 { + t.Fatalf("HTTP attempt = %#v", httpAttempt) + } + if err := repository.Create(ctx, record); err != nil { + t.Fatal(err) + } + if count := tableRowCount(t, database, "request_audit_attempts"); count != 2 { + t.Fatalf("idempotent attempts = %d", count) + } + if _, err := repository.Get(ctx, 999); !errors.Is(err, repositorypkg.ErrNotFound) { + t.Fatalf("missing audit error = %v", err) + } +} + func TestAuditRepositoryNormalizesUntrustedUsage(t *testing.T) { ctx := context.Background() database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "audit-normalize.db")) diff --git a/backend/internal/infra/persistence/relational/mapping.go b/backend/internal/infra/persistence/relational/mapping.go index 6fb2aab4..74470d1e 100644 --- a/backend/internal/infra/persistence/relational/mapping.go +++ b/backend/internal/infra/persistence/relational/mapping.go @@ -147,13 +147,47 @@ func toAuditDomain(value requestAuditModel) audit.Record { ID: value.ID, EventID: value.EventID, RequestID: value.RequestID, ClientKeyID: value.ClientKeyID, ClientKeyName: value.ClientKeyName, ModelRouteID: value.ModelRouteID, ModelPublicID: value.ModelPublicID, ModelUpstreamModel: value.ModelUpstreamModel, Provider: value.Provider, Operation: audit.Operation(value.Operation), UsageSource: audit.UsageSource(value.UsageSource), - AccountID: value.AccountID, AccountName: value.AccountName, StatusCode: value.StatusCode, Streaming: value.Streaming, + AccountID: value.AccountID, AccountName: value.AccountName, + EgressNodeID: value.EgressNodeID, EgressNodeName: value.EgressNodeName, EgressScope: value.EgressScope, EgressMode: audit.EgressMode(value.EgressMode), + StatusCode: value.StatusCode, Streaming: value.Streaming, MediaInputImages: value.MediaInputImages, MediaOutputImages: value.MediaOutputImages, MediaOutputSeconds: value.MediaOutputSeconds, InputTokens: value.InputTokens, CachedInputTokens: value.CachedInputTokens, OutputTokens: value.OutputTokens, ReasoningTokens: value.ReasoningTokens, TotalTokens: value.TotalTokens, CostInUSDTicks: value.CostInUSDTicks, EstimatedCostInUSDTicks: value.EstimatedCostInUSDTicks, PricingModel: value.PricingModel, PricingVersion: value.PricingVersion, NumSourcesUsed: value.NumSourcesUsed, NumServerSideToolsUsed: value.NumServerSideToolsUsed, ContextInputTokens: value.ContextInputTokens, ContextOutputTokens: value.ContextOutputTokens, DurationMS: value.DurationMS, - ErrorCode: value.ErrorCode, CreatedAt: value.CreatedAt, + ErrorCode: value.ErrorCode, AttemptCount: value.AttemptCount, CreatedAt: value.CreatedAt, } } + +func toAuditAttemptDomain(value requestAuditAttemptModel) (audit.Attempt, error) { + var responseHeaders map[string][]string + if err := json.Unmarshal([]byte(value.ResponseHeadersJSON), &responseHeaders); err != nil { + return audit.Attempt{}, err + } + var errorChain []audit.ErrorFrame + if err := json.Unmarshal([]byte(value.ErrorChainJSON), &errorChain); err != nil { + return audit.Attempt{}, err + } + return audit.Attempt{ + ID: value.ID, + AuditID: value.AuditID, + Number: value.Number, + Source: audit.AttemptSource(value.Source), + Stage: value.Stage, + AccountID: value.AccountID, + AccountName: value.AccountName, + Method: value.Method, + RequestPath: value.RequestPath, + UpstreamURL: value.UpstreamURL, + StartedAt: value.StartedAt, + DurationMS: value.DurationMS, + UpstreamStatusCode: value.UpstreamStatusCode, + UpstreamStatus: value.UpstreamStatus, + ResponseHeaders: responseHeaders, + ResponseBody: value.ResponseBody, + ResponseBodyTruncated: value.ResponseBodyTruncated, + TransportError: value.TransportError, + ErrorChain: errorChain, + }, nil +} diff --git a/backend/internal/infra/persistence/relational/media_repository.go b/backend/internal/infra/persistence/relational/media_repository.go index ad68ac50..326a5150 100644 --- a/backend/internal/infra/persistence/relational/media_repository.go +++ b/backend/internal/infra/persistence/relational/media_repository.go @@ -2,6 +2,7 @@ package relational import ( "context" + "strings" "time" "github.com/chenyme/grok2api/backend/internal/domain/media" @@ -37,6 +38,40 @@ func (r *MediaAssetRepository) GetMediaAsset(ctx context.Context, id string) (me }, nil } +// ListMediaAssets 通过字段投影返回符合筛选条件的稳定分页结果。 +func (r *MediaAssetRepository) ListMediaAssets(ctx context.Context, input repository.MediaAssetListQuery) ([]media.Asset, int64, error) { + query := r.db.db.WithContext(ctx).Model(&mediaAssetModel{}) + if search := strings.TrimSpace(input.Page.Search); search != "" { + pattern := "%" + strings.ToLower(search) + "%" + query = query.Where("LOWER(id) LIKE ? OR LOWER(kind) LIKE ? OR LOWER(mime_type) LIKE ? OR LOWER(sha256) LIKE ?", pattern, pattern, pattern, pattern) + } + var total int64 + if err := query.Count(&total).Error; err != nil { + return nil, 0, err + } + var rows []mediaAssetModel + if err := query.Select("id", "kind", "mime_type", "size_bytes", "sha256", "created_at").Order("created_at DESC, id DESC").Offset(input.Page.Offset).Limit(input.Page.Limit).Find(&rows).Error; err != nil { + return nil, 0, err + } + values := make([]media.Asset, 0, len(rows)) + for _, row := range rows { + values = append(values, media.Asset{ + ID: row.ID, Kind: row.Kind, StorageKey: row.StorageKey, MIMEType: row.MIMEType, + SizeBytes: row.SizeBytes, SHA256: row.SHA256, CreatedAt: row.CreatedAt, + }) + } + return values, total, nil +} + +// SummarizeMediaAssets 通过单次聚合查询返回图片数量和存储占用。 +func (r *MediaAssetRepository) SummarizeMediaAssets(ctx context.Context) (repository.MediaAssetStats, error) { + var stats repository.MediaAssetStats + err := r.db.db.WithContext(ctx).Model(&mediaAssetModel{}). + Select("COUNT(*) AS total_images, COALESCE(SUM(size_bytes), 0) AS total_bytes"). + Scan(&stats).Error + return stats, err +} + func (r *MediaAssetRepository) TotalMediaAssetBytes(ctx context.Context) (int64, error) { var total int64 err := r.db.db.WithContext(ctx).Model(&mediaAssetModel{}).Select("COALESCE(SUM(size_bytes), 0)").Scan(&total).Error @@ -90,7 +125,7 @@ func (r *MediaJobRepository) UpdateMediaJob(ctx context.Context, value media.Job if value.ClaimToken != "" { query = query.Where("claim_token = ?", value.ClaimToken) } - result := query.Select("request_id", "client_key_name", "account_id", "account_name", "provider", "model", "model_route_id", "upstream_model", "prompt", "seconds", "size", "quality", "status", "progress", "input_json", "upstream_url", "content_type", "error_code", "error_message", "lease_until", "claim_token", "updated_at", "completed_at", "usage_recorded_at").Updates(updates) + result := query.Select("request_id", "client_key_name", "account_id", "account_name", "egress_node_id", "egress_node_name", "egress_scope", "egress_mode", "provider", "model", "model_route_id", "upstream_model", "prompt", "seconds", "size", "quality", "status", "progress", "input_json", "upstream_url", "content_type", "error_code", "error_message", "lease_until", "claim_token", "updated_at", "completed_at", "usage_recorded_at").Updates(updates) if result.Error != nil { return result.Error } @@ -100,12 +135,65 @@ func (r *MediaJobRepository) UpdateMediaJob(ctx context.Context, value media.Job return nil } -func (r *MediaJobRepository) ListUnrecordedCompletedMediaJobs(ctx context.Context, limit int) ([]media.Job, error) { +// ListMediaJobs 通过固定搜索字段和排序白名单返回稳定分页结果。 +func (r *MediaJobRepository) ListMediaJobs(ctx context.Context, input repository.MediaJobListQuery) ([]media.Job, int64, error) { + query := r.db.db.WithContext(ctx).Model(&mediaJobModel{}) + if input.Filter.Status != "" { + query = query.Where("status = ?", input.Filter.Status) + } + if search := strings.TrimSpace(input.Page.Search); search != "" { + pattern := "%" + strings.ToLower(search) + "%" + query = query.Where("LOWER(id) LIKE ? OR LOWER(prompt) LIKE ? OR LOWER(model) LIKE ? OR LOWER(account_name) LIKE ? OR LOWER(client_key_name) LIKE ?", pattern, pattern, pattern, pattern, pattern) + } + var total int64 + if err := query.Count(&total).Error; err != nil { + return nil, 0, err + } + var rows []mediaJobModel + query = applyStableSort(query, input.Page.Sort, map[string]sortSpec{ + "prompt": {expression: "LOWER(prompt)"}, + "model": {expression: "LOWER(model)"}, + "status": {expression: "status"}, + "progress": {expression: "progress", defaultDirection: repository.SortDescending}, + "spec": {expression: "LOWER(size) || ' ' || LOWER(quality)"}, + "account": {expression: "LOWER(account_name)"}, + "createdAt": {expression: "created_at", defaultDirection: repository.SortDescending}, + "completedAt": {expression: "completed_at", nullsLast: true, defaultDirection: repository.SortDescending}, + }, sortSpec{expression: "created_at", defaultDirection: repository.SortDescending}, "id") + if err := query.Select( + "id", "client_key_name", "account_name", "model", "prompt", "seconds", "size", "quality", + "status", "progress", "error_message", "created_at", "completed_at", + ).Offset(input.Page.Offset).Limit(input.Page.Limit).Find(&rows).Error; err != nil { + return nil, 0, err + } + values := make([]media.Job, 0, len(rows)) + for _, row := range rows { + values = append(values, mediaJobToDomain(row)) + } + return values, total, nil +} + +// SummarizeMediaJobs 通过单次条件聚合查询统计全部任务状态。 +func (r *MediaJobRepository) SummarizeMediaJobs(ctx context.Context) (repository.MediaJobStats, error) { + var stats repository.MediaJobStats + err := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).Select(` + COUNT(*) AS total_jobs, + COALESCE(SUM(CASE WHEN status = ? THEN 1 ELSE 0 END), 0) AS completed, + COALESCE(SUM(CASE WHEN status = ? THEN 1 ELSE 0 END), 0) AS failed, + COALESCE(SUM(CASE WHEN status = ? THEN 1 ELSE 0 END), 0) AS in_progress, + COALESCE(SUM(CASE WHEN status = ? THEN 1 ELSE 0 END), 0) AS queued`, + media.StatusCompleted, media.StatusFailed, media.StatusInProgress, media.StatusQueued, + ).Scan(&stats).Error + return stats, err +} + +// ListUnrecordedTerminalMediaJobs 返回尚未完成审计写入的成功或失败任务。 +func (r *MediaJobRepository) ListUnrecordedTerminalMediaJobs(ctx context.Context, limit int) ([]media.Job, error) { if limit <= 0 || limit > 1000 { limit = 200 } var rows []mediaJobModel - if err := r.db.db.WithContext(ctx).Where("status = ? AND usage_recorded_at IS NULL", media.StatusCompleted).Order("completed_at ASC, id ASC").Limit(limit).Find(&rows).Error; err != nil { + if err := r.db.db.WithContext(ctx).Where("status IN ? AND usage_recorded_at IS NULL", []media.Status{media.StatusCompleted, media.StatusFailed}).Order("completed_at ASC, id ASC").Limit(limit).Find(&rows).Error; err != nil { return nil, err } values := make([]media.Job, 0, len(rows)) @@ -116,13 +204,14 @@ func (r *MediaJobRepository) ListUnrecordedCompletedMediaJobs(ctx context.Contex } func (r *MediaJobRepository) MarkMediaJobUsageRecorded(ctx context.Context, id string, recordedAt time.Time) error { - result := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ? AND status = ? AND usage_recorded_at IS NULL", id, media.StatusCompleted).Update("usage_recorded_at", recordedAt) + terminalStatuses := []media.Status{media.StatusCompleted, media.StatusFailed} + result := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ? AND status IN ? AND usage_recorded_at IS NULL", id, terminalStatuses).Update("usage_recorded_at", recordedAt) if result.Error != nil { return result.Error } if result.RowsAffected == 0 { var count int64 - if err := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ? AND status = ? AND usage_recorded_at IS NOT NULL", id, media.StatusCompleted).Count(&count).Error; err != nil { + if err := r.db.db.WithContext(ctx).Model(&mediaJobModel{}).Where("id = ? AND status IN ? AND usage_recorded_at IS NOT NULL", id, terminalStatuses).Count(&count).Error; err != nil { return err } if count == 0 { @@ -169,8 +258,10 @@ func (r *MediaJobRepository) TryClaimMediaJob(ctx context.Context, id string, no func mediaJobFromDomain(value media.Job) *mediaJobModel { return &mediaJobModel{ ID: value.ID, RequestID: value.RequestID, ClientKeyID: value.ClientKeyID, ClientKeyName: value.ClientKeyName, - AccountID: value.AccountID, AccountName: value.AccountName, Provider: value.Provider, - Model: value.Model, ModelRouteID: value.ModelRouteID, UpstreamModel: value.UpstreamModel, + AccountID: value.AccountID, AccountName: value.AccountName, + EgressNodeID: value.EgressNodeID, EgressNodeName: value.EgressNodeName, EgressScope: value.EgressScope, EgressMode: value.EgressMode, + Provider: value.Provider, + Model: value.Model, ModelRouteID: value.ModelRouteID, UpstreamModel: value.UpstreamModel, Prompt: value.Prompt, Seconds: value.Seconds, Size: value.Size, Quality: value.Quality, Status: string(value.Status), Progress: value.Progress, InputJSON: value.InputJSON, UpstreamURL: value.UpstreamURL, ContentType: value.ContentType, ErrorCode: value.ErrorCode, ErrorMessage: value.ErrorMessage, @@ -182,8 +273,10 @@ func mediaJobFromDomain(value media.Job) *mediaJobModel { func mediaJobToDomain(row mediaJobModel) media.Job { return media.Job{ ID: row.ID, RequestID: row.RequestID, ClientKeyID: row.ClientKeyID, ClientKeyName: row.ClientKeyName, - AccountID: row.AccountID, AccountName: row.AccountName, Provider: row.Provider, - Model: row.Model, ModelRouteID: row.ModelRouteID, UpstreamModel: row.UpstreamModel, + AccountID: row.AccountID, AccountName: row.AccountName, + EgressNodeID: row.EgressNodeID, EgressNodeName: row.EgressNodeName, EgressScope: row.EgressScope, EgressMode: row.EgressMode, + Provider: row.Provider, + Model: row.Model, ModelRouteID: row.ModelRouteID, UpstreamModel: row.UpstreamModel, Prompt: row.Prompt, Seconds: row.Seconds, Size: row.Size, Quality: row.Quality, Status: media.Status(row.Status), Progress: row.Progress, InputJSON: row.InputJSON, UpstreamURL: row.UpstreamURL, ContentType: row.ContentType, ErrorCode: row.ErrorCode, ErrorMessage: row.ErrorMessage, diff --git a/backend/internal/infra/persistence/relational/media_repository_test.go b/backend/internal/infra/persistence/relational/media_repository_test.go new file mode 100644 index 00000000..a1d3bec2 --- /dev/null +++ b/backend/internal/infra/persistence/relational/media_repository_test.go @@ -0,0 +1,252 @@ +package relational + +import ( + "context" + "strings" + "testing" + "time" + + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" + "github.com/chenyme/grok2api/backend/internal/repository" +) + +func TestMediaJobRepositoryListMediaJobsPaginatesAndFilters(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + + accountValue, _, err := NewAccountRepository(database).UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderWeb, + AuthType: accountdomain.AuthTypeSSO, + WebTier: accountdomain.WebTierBasic, + Name: "media-list-account", + SourceKey: "media-list-account", + EncryptedAccessToken: testEncryptedToken, + AuthStatus: accountdomain.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + key := clientKeyModel{Name: "media-list-key", Prefix: "media-list-key", SecretHash: testSecretHash, EncryptedSecret: testEncryptedToken, Enabled: true, RPMLimit: 60, MaxConcurrent: 4} + if err := database.db.WithContext(ctx).Create(&key).Error; err != nil { + t.Fatal(err) + } + + jobRepo := NewMediaJobRepository(database) + now := time.Date(2026, 7, 13, 12, 0, 0, 0, time.UTC) + jobs := []mediadomain.Job{ + testMediaJob("media_job_completed_old", accountValue.ID, key.ID, mediadomain.StatusCompleted, now.Add(-4*time.Hour)), + testMediaJob("media_job_queued_mid", accountValue.ID, key.ID, mediadomain.StatusQueued, now.Add(-3*time.Hour)), + testMediaJob("media_job_failed_newer", accountValue.ID, key.ID, mediadomain.StatusFailed, now.Add(-2*time.Hour)), + testMediaJob("media_job_completed_new", accountValue.ID, key.ID, mediadomain.StatusCompleted, now.Add(-time.Hour)), + } + jobs[0].Prompt = "A quiet harbor" + jobs[1].Prompt = "Northern lights" + jobs[2].Prompt = "Desert sunrise" + jobs[3].Prompt = "City skyline" + for _, job := range jobs { + if err := jobRepo.CreateMediaJob(ctx, job); err != nil { + t.Fatal(err) + } + } + + firstPage, total, err := jobRepo.ListMediaJobs(ctx, repository.MediaJobListQuery{ + Page: repository.PageQuery{Offset: 0, Limit: 2}, + }) + if err != nil { + t.Fatal(err) + } + if total != 4 { + t.Fatalf("total = %d", total) + } + assertMediaJobIDs(t, firstPage, "media_job_completed_new", "media_job_failed_newer") + + secondPage, total, err := jobRepo.ListMediaJobs(ctx, repository.MediaJobListQuery{ + Page: repository.PageQuery{Offset: 2, Limit: 2}, + }) + if err != nil { + t.Fatal(err) + } + if total != 4 { + t.Fatalf("second page total = %d", total) + } + assertMediaJobIDs(t, secondPage, "media_job_queued_mid", "media_job_completed_old") + + completed, total, err := jobRepo.ListMediaJobs(ctx, repository.MediaJobListQuery{ + Page: repository.PageQuery{Offset: 0, Limit: 10}, + Filter: repository.MediaJobListFilter{Status: string(mediadomain.StatusCompleted)}, + }) + if err != nil { + t.Fatal(err) + } + if total != 2 { + t.Fatalf("completed total = %d", total) + } + assertMediaJobIDs(t, completed, "media_job_completed_new", "media_job_completed_old") + + searched, total, err := jobRepo.ListMediaJobs(ctx, repository.MediaJobListQuery{ + Page: repository.PageQuery{Offset: 0, Limit: 1, Search: "northern"}, + }) + if err != nil { + t.Fatal(err) + } + if total != 1 { + t.Fatalf("searched total = %d", total) + } + assertMediaJobIDs(t, searched, "media_job_queued_mid") + + sorted, total, err := jobRepo.ListMediaJobs(ctx, repository.MediaJobListQuery{ + Page: repository.PageQuery{ + Offset: 0, + Limit: 4, + Sort: repository.SortQuery{Field: "prompt", Direction: repository.SortAscending}, + }, + }) + if err != nil { + t.Fatal(err) + } + if total != 4 { + t.Fatalf("sorted total = %d", total) + } + assertMediaJobIDs(t, sorted, "media_job_completed_old", "media_job_completed_new", "media_job_failed_newer", "media_job_queued_mid") + + stats, err := jobRepo.SummarizeMediaJobs(ctx) + if err != nil { + t.Fatal(err) + } + if stats.TotalJobs != 4 || stats.Completed != 2 || stats.Failed != 1 || stats.InProgress != 0 || stats.Queued != 1 { + t.Fatalf("stats = %#v", stats) + } +} + +func TestMediaAssetRepositoryListMediaAssetsPaginatesAndCounts(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + assetRepo := NewMediaAssetRepository(database) + + stats, err := assetRepo.SummarizeMediaAssets(ctx) + if err != nil { + t.Fatal(err) + } + if stats.TotalImages != 0 || stats.TotalBytes != 0 { + t.Fatalf("initial stats = %#v", stats) + } + + now := time.Date(2026, 7, 13, 12, 0, 0, 0, time.UTC) + assets := []mediadomain.Asset{ + testMediaAsset("media_asset_0001", "media/asset-0001.png", now.Add(-3*time.Hour)), + testMediaAsset("media_asset_0002", "media/asset-0002.png", now.Add(-2*time.Hour)), + testMediaAsset("media_asset_0003", "media/asset-0003.png", now.Add(-time.Hour)), + } + for _, asset := range assets { + if err := assetRepo.CreateMediaAsset(ctx, asset); err != nil { + t.Fatal(err) + } + } + + firstPage, total, err := assetRepo.ListMediaAssets(ctx, repository.MediaAssetListQuery{ + Page: repository.PageQuery{Offset: 0, Limit: 2}, + }) + if err != nil { + t.Fatal(err) + } + if total != 3 { + t.Fatalf("total = %d", total) + } + assertMediaAssetIDs(t, firstPage, "media_asset_0003", "media_asset_0002") + + secondPage, total, err := assetRepo.ListMediaAssets(ctx, repository.MediaAssetListQuery{ + Page: repository.PageQuery{Offset: 2, Limit: 2}, + }) + if err != nil { + t.Fatal(err) + } + if total != 3 { + t.Fatalf("second page total = %d", total) + } + assertMediaAssetIDs(t, secondPage, "media_asset_0001") + + searched, total, err := assetRepo.ListMediaAssets(ctx, repository.MediaAssetListQuery{ + Page: repository.PageQuery{Offset: 0, Limit: 1, Search: "0001"}, + }) + if err != nil { + t.Fatal(err) + } + if total != 1 { + t.Fatalf("searched total = %d", total) + } + assertMediaAssetIDs(t, searched, "media_asset_0001") + + stats, err = assetRepo.SummarizeMediaAssets(ctx) + if err != nil { + t.Fatal(err) + } + if stats.TotalImages != 3 || stats.TotalBytes != 3*1024 { + t.Fatalf("stats = %#v", stats) + } +} + +func testMediaJob(id string, accountID, clientKeyID uint64, status mediadomain.Status, createdAt time.Time) mediadomain.Job { + job := mediadomain.Job{ + ID: id, + RequestID: "request-" + id, + ClientKeyID: clientKeyID, + ClientKeyName: "media-list-key", + AccountID: accountID, + AccountName: "media-list-account", + Provider: "grok_web", + Model: "grok-imagine-video", + ModelRouteID: 1, + UpstreamModel: "grok-imagine-video-upstream", + Prompt: "test prompt", + Seconds: 8, + Size: "16:9", + Quality: "720p", + Status: status, + InputJSON: `{}`, + CreatedAt: createdAt, + UpdatedAt: createdAt, + } + if status == mediadomain.StatusCompleted || status == mediadomain.StatusFailed { + job.Progress = 100 + completedAt := createdAt.Add(time.Minute) + job.CompletedAt = &completedAt + } + return job +} + +func testMediaAsset(id, storageKey string, createdAt time.Time) mediadomain.Asset { + return mediadomain.Asset{ + ID: id, + Kind: "image", + StorageKey: storageKey, + MIMEType: "image/png", + SizeBytes: 1024, + SHA256: strings.Repeat("a", 64), + CreatedAt: createdAt, + } +} + +func assertMediaJobIDs(t *testing.T, values []mediadomain.Job, expected ...string) { + t.Helper() + if len(values) != len(expected) { + t.Fatalf("len(values) = %d, expected %d: %#v", len(values), len(expected), values) + } + for index, id := range expected { + if values[index].ID != id { + t.Fatalf("values[%d].ID = %q, expected %q; values = %#v", index, values[index].ID, id, values) + } + } +} + +func assertMediaAssetIDs(t *testing.T, values []mediadomain.Asset, expected ...string) { + t.Helper() + if len(values) != len(expected) { + t.Fatalf("len(values) = %d, expected %d: %#v", len(values), len(expected), values) + } + for index, id := range expected { + if values[index].ID != id { + t.Fatalf("values[%d].ID = %q, expected %q; values = %#v", index, values[index].ID, id, values) + } + } +} diff --git a/backend/internal/infra/persistence/relational/models.go b/backend/internal/infra/persistence/relational/models.go index 9aaeb34c..3b496cf6 100644 --- a/backend/internal/infra/persistence/relational/models.go +++ b/backend/internal/infra/persistence/relational/models.go @@ -260,6 +260,10 @@ type requestAuditModel struct { UsageSource string `gorm:"size:16;not null;check:chk_request_audits_usage_source,usage_source IN ('upstream','estimated','none')"` AccountID *uint64 `gorm:"check:chk_request_audits_account_id,account_id IS NULL OR account_id > 0"` AccountName string `gorm:"size:160;check:chk_request_audits_account_name,length(account_name) <= 160"` + 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')"` + 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"` MediaInputImages int64 `gorm:"not null;default:0"` @@ -280,11 +284,37 @@ type requestAuditModel struct { ContextOutputTokens int64 `gorm:"not null;default:0"` DurationMS int64 `gorm:"not null;default:0"` ErrorCode string `gorm:"size:100;check:chk_request_audits_error_code,length(error_code) <= 100"` + AttemptCount int `gorm:"not null;default:0;check:chk_request_audits_attempt_count,attempt_count >= 0"` CreatedAt time.Time `gorm:"not null"` } func (requestAuditModel) TableName() string { return "request_audits" } +type requestAuditAttemptModel struct { + ID uint64 `gorm:"primaryKey;autoIncrement"` + AuditID uint64 `gorm:"not null;uniqueIndex:uidx_audit_attempt_number;check:chk_request_audit_attempts_audit_id,audit_id > 0"` + Number int `gorm:"not null;uniqueIndex:uidx_audit_attempt_number;check:chk_request_audit_attempts_number,number > 0"` + Source string `gorm:"size:32;not null;check:chk_request_audit_attempts_source,source IN ('upstream_http','gateway_transport','credential')"` + Stage string `gorm:"size:64;not null;check:chk_request_audit_attempts_stage,length(trim(stage)) BETWEEN 1 AND 64"` + AccountID *uint64 `gorm:"check:chk_request_audit_attempts_account_id,account_id IS NULL OR account_id > 0"` + AccountName string `gorm:"size:160;not null;default:'';check:chk_request_audit_attempts_account_name,length(account_name) <= 160"` + Method string `gorm:"size:16;not null;default:'';check:chk_request_audit_attempts_method,length(method) <= 16"` + RequestPath string `gorm:"type:text;not null;default:'';check:chk_request_audit_attempts_request_path,length(request_path) <= 2048"` + UpstreamURL string `gorm:"type:text;not null;default:'';check:chk_request_audit_attempts_upstream_url,length(upstream_url) <= 4096"` + StartedAt time.Time `gorm:"not null"` + DurationMS int64 `gorm:"not null;default:0;check:chk_request_audit_attempts_duration,duration_ms >= 0"` + UpstreamStatusCode *int `gorm:"check:chk_request_audit_attempts_status,upstream_status_code IS NULL OR upstream_status_code BETWEEN 100 AND 599"` + UpstreamStatus string `gorm:"size:128;not null;default:'';check:chk_request_audit_attempts_status_text,length(upstream_status) <= 128"` + ResponseHeadersJSON string `gorm:"type:text;not null;default:'{}';check:chk_request_audit_attempts_headers,length(response_headers_json) <= 32768"` + ResponseBody []byte `gorm:"check:chk_request_audit_attempts_body,length(response_body) <= 65536"` + ResponseBodyTruncated bool `gorm:"not null;default:false"` + TransportError string `gorm:"type:text;not null;default:'';check:chk_request_audit_attempts_transport_error,length(transport_error) <= 2048"` + ErrorChainJSON string `gorm:"type:text;not null;default:'[]';check:chk_request_audit_attempts_error_chain,length(error_chain_json) <= 32768"` + Audit *requestAuditModel `gorm:"foreignKey:AuditID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"` +} + +func (requestAuditAttemptModel) TableName() string { return "request_audit_attempts" } + type responseOwnershipModel struct { ResponseID string `gorm:"size:255;primaryKey;check:chk_response_ownership_id,length(response_id) BETWEEN 1 AND 255"` AccountID uint64 `gorm:"not null"` @@ -315,27 +345,31 @@ type webResponseStateModel struct { func (webResponseStateModel) TableName() string { return "web_response_states" } type mediaJobModel struct { - ID string `gorm:"size:64;primaryKey;check:chk_media_jobs_id,length(id) BETWEEN 1 AND 64"` - RequestID string `gorm:"size:64;not null;check:chk_media_jobs_request_id,length(request_id) BETWEEN 1 AND 64"` - ClientKeyID uint64 `gorm:"not null;check:chk_media_jobs_client_key_id,client_key_id > 0"` - ClientKeyName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_client_key_name,length(client_key_name) <= 160"` - AccountID uint64 `gorm:"not null;check:chk_media_jobs_account_id,account_id > 0"` - AccountName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_account_name,length(account_name) <= 160"` - Provider string `gorm:"size:32;not null;check:chk_media_jobs_provider,provider IN ('grok_web')"` - 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"` - Prompt string `gorm:"type:text;not null;check:chk_media_jobs_prompt,length(prompt) BETWEEN 0 AND 100000"` - Seconds int `gorm:"not null;check:chk_media_jobs_seconds,seconds BETWEEN 1 AND 15"` - Size string `gorm:"size:32;not null;check:chk_media_jobs_size,length(trim(size)) BETWEEN 1 AND 32"` - Quality string `gorm:"size:32;not null;check:chk_media_jobs_quality,length(trim(quality)) BETWEEN 1 AND 32"` - Status string `gorm:"size:32;not null;check:chk_media_jobs_status,status IN ('queued','in_progress','completed','failed')"` - Progress int `gorm:"not null;check:chk_media_jobs_progress,progress BETWEEN 0 AND 100"` - InputJSON string `gorm:"type:text;not null;default:'{}';check:chk_media_jobs_input_json,length(input_json) <= 1048576"` - UpstreamURL string `gorm:"type:text;not null;default:'';check:chk_media_jobs_upstream_url,length(upstream_url) <= 8192"` - ContentType string `gorm:"size:128;not null;default:'';check:chk_media_jobs_content_type,length(content_type) <= 128"` - ErrorCode string `gorm:"size:100;not null;default:'';check:chk_media_jobs_error_code,length(error_code) <= 100"` - ErrorMessage string `gorm:"size:512;not null;default:'';check:chk_media_jobs_error_message,length(error_message) <= 512"` + ID string `gorm:"size:64;primaryKey;check:chk_media_jobs_id,length(id) BETWEEN 1 AND 64"` + RequestID string `gorm:"size:64;not null;check:chk_media_jobs_request_id,length(request_id) BETWEEN 1 AND 64"` + ClientKeyID uint64 `gorm:"not null;check:chk_media_jobs_client_key_id,client_key_id > 0"` + ClientKeyName string `gorm:"size:160;not null;default:'';check:chk_media_jobs_client_key_name,length(client_key_name) <= 160"` + AccountID uint64 `gorm:"not null;check:chk_media_jobs_account_id,account_id > 0"` + 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')"` + 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')"` + 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"` + Prompt string `gorm:"type:text;not null;check:chk_media_jobs_prompt,length(prompt) BETWEEN 0 AND 100000"` + Seconds int `gorm:"not null;check:chk_media_jobs_seconds,seconds BETWEEN 1 AND 15"` + Size string `gorm:"size:32;not null;check:chk_media_jobs_size,length(trim(size)) BETWEEN 1 AND 32"` + Quality string `gorm:"size:32;not null;check:chk_media_jobs_quality,length(trim(quality)) BETWEEN 1 AND 32"` + Status string `gorm:"size:32;not null;check:chk_media_jobs_status,status IN ('queued','in_progress','completed','failed')"` + Progress int `gorm:"not null;check:chk_media_jobs_progress,progress BETWEEN 0 AND 100"` + InputJSON string `gorm:"type:text;not null;default:'{}';check:chk_media_jobs_input_json,length(input_json) <= 1048576"` + UpstreamURL string `gorm:"type:text;not null;default:'';check:chk_media_jobs_upstream_url,length(upstream_url) <= 8192"` + ContentType string `gorm:"size:128;not null;default:'';check:chk_media_jobs_content_type,length(content_type) <= 128"` + ErrorCode string `gorm:"size:100;not null;default:'';check:chk_media_jobs_error_code,length(error_code) <= 100"` + ErrorMessage string `gorm:"size:512;not null;default:'';check:chk_media_jobs_error_message,length(error_message) <= 512"` LeaseUntil *time.Time ClaimToken string `gorm:"size:64;not null;default:'';check:chk_media_jobs_claim_token,claim_token = '' OR length(claim_token) BETWEEN 16 AND 64"` CreatedAt time.Time `gorm:"not null"` diff --git a/backend/internal/infra/persistence/relational/schema.go b/backend/internal/infra/persistence/relational/schema.go index cac42664..5b8e8753 100644 --- a/backend/internal/infra/persistence/relational/schema.go +++ b/backend/internal/infra/persistence/relational/schema.go @@ -26,6 +26,7 @@ var schemaModels = []any{ &clientKeyModelPermission{}, &billingReservationModel{}, &requestAuditModel{}, + &requestAuditAttemptModel{}, &responseOwnershipModel{}, &webResponseStateModel{}, &mediaJobModel{}, @@ -61,6 +62,7 @@ var schemaIndexes = []string{ "CREATE INDEX IF NOT EXISTS idx_audits_account_created_id ON request_audits(account_id, created_at DESC, id DESC)", "CREATE INDEX IF NOT EXISTS idx_audits_status_created_id ON request_audits(status_code, created_at DESC, id DESC)", "CREATE INDEX IF NOT EXISTS idx_audits_streaming_created_id ON request_audits(streaming, created_at DESC, id DESC)", + "CREATE INDEX IF NOT EXISTS idx_audit_attempts_audit_number ON request_audit_attempts(audit_id, number)", "CREATE INDEX IF NOT EXISTS idx_response_ownership_expires ON response_ownership(expires_at)", "CREATE INDEX IF NOT EXISTS idx_response_ownership_account ON response_ownership(account_id)", "CREATE INDEX IF NOT EXISTS idx_response_ownership_client_key ON response_ownership(client_key_id)", diff --git a/backend/internal/infra/persistence/relational/web_state_repository_test.go b/backend/internal/infra/persistence/relational/web_state_repository_test.go index a3e0b62a..f0a1fc7e 100644 --- a/backend/internal/infra/persistence/relational/web_state_repository_test.go +++ b/backend/internal/infra/persistence/relational/web_state_repository_test.go @@ -68,15 +68,29 @@ func TestWebResponseStateAndMediaJobRoundTrip(t *testing.T) { if err := jobs.UpdateMediaJob(ctx, claimed); err != nil { t.Fatal(err) } - unrecorded, err := jobs.ListUnrecordedCompletedMediaJobs(ctx, 10) + unrecorded, err := jobs.ListUnrecordedTerminalMediaJobs(ctx, 10) if err != nil || len(unrecorded) != 1 || unrecorded[0].RequestID != job.RequestID || unrecorded[0].ModelRouteID != job.ModelRouteID { t.Fatalf("unrecorded jobs = %#v, err = %v", unrecorded, err) } if err := jobs.MarkMediaJobUsageRecorded(ctx, job.ID, completedAt.Add(time.Second)); err != nil { t.Fatal(err) } - unrecorded, err = jobs.ListUnrecordedCompletedMediaJobs(ctx, 10) + unrecorded, err = jobs.ListUnrecordedTerminalMediaJobs(ctx, 10) if err != nil || len(unrecorded) != 0 { t.Fatalf("recorded jobs = %#v, err = %v", unrecorded, err) } + failedAt := completedAt.Add(2 * time.Second) + failed := job + failed.ID, failed.RequestID, failed.Status, failed.ErrorCode = "video_failed", "request-video-failed", mediadomain.StatusFailed, "generation_failed" + failed.Progress, failed.ClaimToken, failed.CompletedAt, failed.UpdatedAt = 50, "", &failedAt, failedAt + if err := jobs.CreateMediaJob(ctx, failed); err != nil { + t.Fatal(err) + } + unrecorded, err = jobs.ListUnrecordedTerminalMediaJobs(ctx, 10) + if err != nil || len(unrecorded) != 1 || unrecorded[0].ID != failed.ID { + t.Fatalf("failed unrecorded jobs = %#v, err = %v", unrecorded, err) + } + if err := jobs.MarkMediaJobUsageRecorded(ctx, failed.ID, failedAt.Add(time.Second)); err != nil { + t.Fatal(err) + } } diff --git a/backend/internal/infra/provider/cli/adapter.go b/backend/internal/infra/provider/cli/adapter.go index 42d55faf..94ee8337 100644 --- a/backend/internal/infra/provider/cli/adapter.go +++ b/backend/internal/infra/provider/cli/adapter.go @@ -160,24 +160,39 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response resp.Header.Del("Content-Length") resp.Header.Set("Content-Type", "text/event-stream") } else { - data, readErr := io.ReadAll(io.LimitReader(resp.Body, (64<<20)+1)) + var data []byte + var readErr error + var diagnosticTruncated bool + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + data, readErr = io.ReadAll(io.LimitReader(resp.Body, (64<<20)+1)) + } else { + data, diagnosticTruncated, readErr = provider.ReadDiagnosticBody(resp.Body) + } _ = resp.Body.Close() if readErr != nil { return nil, readErr } - if len(data) > 64<<20 { + if resp.StatusCode >= 200 && resp.StatusCode < 300 && len(data) > 64<<20 { return nil, fmt.Errorf("上游对话响应超过 64 MiB") } + var diagnostic *provider.DiagnosticResponse + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + diagnostic = &provider.DiagnosticResponse{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: data, BodyTruncated: diagnosticTruncated} + } converted, convertErr := conversation.ConvertResponseJSONWithOptions(data, request.Operation, conversationOptions) if convertErr != nil { - return nil, convertErr + if diagnostic == nil { + return nil, convertErr + } + return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: diagnostic.Header.Clone(), Body: io.NopCloser(bytes.NewReader(data)), UpstreamURL: req.URL.String(), Diagnostic: diagnostic}, nil } resp.Body = io.NopCloser(bytes.NewReader(converted)) resp.Header.Set("Content-Length", strconv.Itoa(len(converted))) resp.Header.Set("Content-Type", "application/json") + return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: req.URL.String(), Diagnostic: diagnostic}, nil } } - return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body}, nil + return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: req.URL.String()}, nil } // invalidResponsesResponse 将本地协议校验错误转换为标准 OpenAI 错误响应,避免触发上游账号重试。 diff --git a/backend/internal/infra/provider/cli/normalize.go b/backend/internal/infra/provider/cli/normalize.go index 0881ed74..e3283915 100644 --- a/backend/internal/infra/provider/cli/normalize.go +++ b/backend/internal/infra/provider/cli/normalize.go @@ -62,7 +62,7 @@ func normalizeResponseFormat(raw json.RawMessage) (json.RawMessage, error) { if err := json.Unmarshal(format["json_schema"], &schema); err != nil { return nil, fmt.Errorf("解析 response_format.json_schema: %w", err) } - result := make(map[string]json.RawMessage, len(schema)+1) + result := make(map[string]json.RawMessage, len(schema)) result["type"] = mustJSON("json_schema") for key, value := range schema { result[key] = value diff --git a/backend/internal/infra/provider/console/adapter.go b/backend/internal/infra/provider/console/adapter.go index 0a9d07e2..1e1e112a 100644 --- a/backend/internal/infra/provider/console/adapter.go +++ b/backend/internal/infra/provider/console/adapter.go @@ -164,8 +164,10 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response cancel() return nil, err } + responseBodyTruncated := false if response.StatusCode == http.StatusTooManyRequests { - if err := normalizeRateLimitResponse(response); err != nil { + responseBodyTruncated, err = normalizeRateLimitResponse(response) + if err != nil { _ = response.Body.Close() lease.Release() cancel() @@ -184,20 +186,31 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response response.Header.Set("Content-Type", "text/event-stream") return responseResult(response, &releaseBody{ReadCloser: response.Body, release: release}), nil } - data, readErr := io.ReadAll(io.LimitReader(response.Body, (64<<20)+1)) + var data []byte + var readErr error + var diagnosticTruncated bool + if response.StatusCode >= 200 && response.StatusCode < 300 { + data, readErr = io.ReadAll(io.LimitReader(response.Body, (64<<20)+1)) + } else { + data, diagnosticTruncated, readErr = provider.ReadDiagnosticBody(response.Body) + diagnosticTruncated = diagnosticTruncated || responseBodyTruncated + } _ = response.Body.Close() release() if readErr != nil { return nil, readErr } - if len(data) > 64<<20 { + if response.StatusCode >= 200 && response.StatusCode < 300 && len(data) > 64<<20 { return nil, fmt.Errorf("Console 对话响应超过 64 MiB") } if response.StatusCode < 200 || response.StatusCode >= 300 { + diagnostic := &provider.DiagnosticResponse{StatusCode: response.StatusCode, Status: response.Status, Header: response.Header.Clone(), Body: data, BodyTruncated: diagnosticTruncated} converted := normalizeConversationError(data, request.Operation, response.StatusCode) response.Header.Set("Content-Length", strconv.Itoa(len(converted))) response.Header.Set("Content-Type", "application/json") - return responseResult(response, io.NopCloser(bytes.NewReader(converted))), nil + result := responseResult(response, io.NopCloser(bytes.NewReader(converted))) + result.Diagnostic = diagnostic + return result, nil } converted, convertErr := conversation.ConvertResponseJSONWithOptions(data, request.Operation, conversationOptions) if convertErr != nil { @@ -293,13 +306,10 @@ func applyHeaders(request *http.Request, token, configuredUserAgent string, leas request.Header.Set("x-cluster", "https://us-east-1.api.x.ai") } -func normalizeRateLimitResponse(response *http.Response) error { - data, err := io.ReadAll(io.LimitReader(response.Body, (1<<20)+1)) +func normalizeRateLimitResponse(response *http.Response) (bool, error) { + data, truncated, err := provider.ReadDiagnosticBody(response.Body) if err != nil { - return err - } - if len(data) > 1<<20 { - return fmt.Errorf("Console 错误响应超过 1 MiB") + return truncated, err } _ = response.Body.Close() response.Body = io.NopCloser(bytes.NewReader(data)) @@ -310,12 +320,16 @@ func normalizeRateLimitResponse(response *http.Response) error { response.Header.Set("Retry-After", strconv.FormatInt(int64(retryAfter/time.Second), 10)) } } - return nil + return truncated, nil } func responseResult(response *http.Response, body io.ReadCloser) *provider.Response { + upstreamURL := "" + if response.Request != nil && response.Request.URL != nil { + upstreamURL = response.Request.URL.String() + } return &provider.Response{ - StatusCode: response.StatusCode, Status: response.Status, Header: response.Header.Clone(), Body: body, QuotaUnits: 1, + StatusCode: response.StatusCode, Status: response.Status, Header: response.Header.Clone(), Body: body, QuotaUnits: 1, UpstreamURL: upstreamURL, } } diff --git a/backend/internal/infra/provider/conversation/conversation_test.go b/backend/internal/infra/provider/conversation/conversation_test.go index e6578bb6..53086998 100644 --- a/backend/internal/infra/provider/conversation/conversation_test.go +++ b/backend/internal/infra/provider/conversation/conversation_test.go @@ -455,3 +455,23 @@ func TestConvertResponsesStreamEmitsDoneOnlyToolArguments(t *testing.T) { t.Fatalf("tool block closed multiple times: %s", text) } } + +func TestConvertResponsesStreamMessagesInputTokens(t *testing.T) { + stream := strings.Join([]string{ + `event: response.created`, + `data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.5","status":"in_progress"}}`, "", + `event: response.output_text.delta`, + `data: {"type":"response.output_text.delta","delta":"hello"}`, "", + `event: response.completed`, + `data: {"type":"response.completed","response":{"id":"resp_1","model":"grok-4.5","status":"completed","usage":{"input_tokens":194,"output_tokens":7}}}`, "", "", + }, "\n") + converted, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationMessages)) + if err != nil { + t.Fatal(err) + } + text := string(converted) + + if !strings.Contains(text, `"input_tokens":194`) { + t.Fatalf("message_delta should contain input_tokens from response.completed usage:\n%s", text) + } +} diff --git a/backend/internal/infra/provider/conversation/request.go b/backend/internal/infra/provider/conversation/request.go index 3243f5b0..3472c969 100644 --- a/backend/internal/infra/provider/conversation/request.go +++ b/backend/internal/infra/provider/conversation/request.go @@ -294,7 +294,7 @@ func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions, "model": model, "input": input, "stream": request.Stream, "max_output_tokens": request.MaxTokens, "store": false, } - instructions := make([]string, 0, len(inlineInstructions)+1) + instructions := make([]string, 0, len(inlineInstructions)) if system, err := anthropicSystemText(request.System); err != nil { return nil, ResponseOptions{}, err } else if system != "" { diff --git a/backend/internal/infra/provider/conversation/stream.go b/backend/internal/infra/provider/conversation/stream.go index 7b136810..9f0da8ea 100644 --- a/backend/internal/infra/provider/conversation/stream.go +++ b/backend/internal/infra/provider/conversation/stream.go @@ -413,7 +413,7 @@ func (c *streamConverter) done(status string) error { } if err := c.writeEvent("message_delta", map[string]any{ "type": "message_delta", "delta": map[string]any{"stop_reason": stopReason, "stop_sequence": nullableAnthropicString(c.stopSequence)}, - "usage": map[string]any{"output_tokens": c.usage.OutputTokens}, + "usage": map[string]any{"input_tokens": c.usage.InputTokens, "output_tokens": c.usage.OutputTokens}, }); err != nil { return err } diff --git a/backend/internal/infra/provider/definition_contract_test.go b/backend/internal/infra/provider/definition_contract_test.go index 8a67c6ce..d4e897f4 100644 --- a/backend/internal/infra/provider/definition_contract_test.go +++ b/backend/internal/infra/provider/definition_contract_test.go @@ -2,6 +2,7 @@ package provider_test import ( "reflect" + "strings" "testing" "github.com/chenyme/grok2api/backend/internal/domain/account" @@ -12,6 +13,14 @@ import ( webprovider "github.com/chenyme/grok2api/backend/internal/infra/provider/web" ) +func TestReadDiagnosticBodyAppliesHardLimit(t *testing.T) { + body := strings.Repeat("x", provider.MaxDiagnosticBodyBytes+4096) + data, truncated, err := provider.ReadDiagnosticBody(strings.NewReader(body)) + if err != nil || !truncated || len(data) != provider.MaxDiagnosticBodyBytes { + t.Fatalf("diagnostic body length = %d, truncated = %v, err = %v", len(data), truncated, err) + } +} + func TestProductionProviderDefinitionsMatchImplementedCapabilities(t *testing.T) { registry := provider.NewRegistry( cliprovider.NewAdapter(cliprovider.Config{}, nil), diff --git a/backend/internal/infra/provider/provider.go b/backend/internal/infra/provider/provider.go index 320ff5b6..11f7320c 100644 --- a/backend/internal/infra/provider/provider.go +++ b/backend/internal/infra/provider/provider.go @@ -21,6 +21,49 @@ var ( ErrUnauthorized = errors.New("upstream credential unauthorized") ) +// MediaPostProcessingStage 标识媒体已经生成后失败的本地处理阶段。 +type MediaPostProcessingStage string + +const ( + MediaPostProcessingDownload MediaPostProcessingStage = "download" + MediaPostProcessingStorage MediaPostProcessingStage = "storage" +) + +// MediaPostProcessingError 表示上游媒体已经产生,后续下载或保存失败。 +// 此类错误不得触发换号重新生成,也不应降低生成账号的健康度。 +type MediaPostProcessingError struct { + Stage MediaPostProcessingStage + Cause error +} + +func (e *MediaPostProcessingError) Error() string { + if e == nil || e.Cause == nil { + return "media post-processing failed" + } + return fmt.Sprintf("media post-processing %s failed: %v", e.Stage, e.Cause) +} + +func (e *MediaPostProcessingError) Unwrap() error { + if e == nil { + return nil + } + return e.Cause +} + +// NewMediaPostProcessingError 将下载或保存错误标记为不可跨账号重试。 +func NewMediaPostProcessingError(stage MediaPostProcessingStage, cause error) error { + if cause == nil { + return nil + } + return &MediaPostProcessingError{Stage: stage, Cause: cause} +} + +// IsMediaPostProcessingError 判断错误是否发生在媒体生成后的本地处理阶段。 +func IsMediaPostProcessingError(err error) bool { + var target *MediaPostProcessingError + return errors.As(err, &target) +} + // CredentialRefreshError 区分需要重新认证的永久 OAuth 错误与可后台退避重试的临时错误。 type CredentialRefreshError struct { Status int @@ -62,16 +105,40 @@ type ResponseResourceRequest struct { Streaming bool NormalizeBody bool Operation string - PublicBaseURL string } // Response 表示尚未写入下游的上游响应。 type Response struct { - StatusCode int - Status string - Header http.Header - Body io.ReadCloser - QuotaUnits int + StatusCode int + Status string + Header http.Header + Body io.ReadCloser + QuotaUnits int + UpstreamURL string + Diagnostic *DiagnosticResponse +} + +const MaxDiagnosticBodyBytes = 64 << 10 + +// DiagnosticResponse 保留 Provider 转换前经过容量限制的失败响应。 +type DiagnosticResponse struct { + StatusCode int + Status string + Header http.Header + Body []byte + BodyTruncated bool +} + +// ReadDiagnosticBody 最多读取诊断正文上限,并报告上游是否还有未保留内容。 +func ReadDiagnosticBody(body io.Reader) ([]byte, bool, error) { + if body == nil { + return nil, false, nil + } + data, err := io.ReadAll(io.LimitReader(body, MaxDiagnosticBodyBytes+1)) + if len(data) <= MaxDiagnosticBodyBytes { + return data, false, err + } + return data[:MaxDiagnosticBodyBytes], true, err } // DeviceAuthorization 表示 Device OAuth 启动结果。 @@ -116,7 +183,6 @@ type ImageGenerationRequest struct { Resolution string ResponseFormat string Streaming bool - PublicBaseURL string } type ImageInput struct { @@ -133,7 +199,6 @@ type ImageEditRequest struct { Count int Resolution string ResponseFormat string - PublicBaseURL string } type VideoRequest struct { @@ -215,7 +280,7 @@ type ImageAdapter interface { // ImageAssetStore 将生成图片归档为可由后端稳定读取的本地资源。 type ImageAssetStore interface { SaveImage(ctx context.Context, data []byte) (media.Asset, error) - PublicImageURL(baseURL, id string) string + PublicImageURL(id string) string } type VideoAdapter interface { diff --git a/backend/internal/infra/provider/web/chat.go b/backend/internal/infra/provider/web/chat.go index 96aa56cb..25cc1b03 100644 --- a/backend/internal/infra/provider/web/chat.go +++ b/backend/internal/infra/provider/web/chat.go @@ -165,6 +165,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response } return &provider.Response{ StatusCode: upstream.StatusCode, Status: upstream.Status, Header: http.Header(upstream.Header), + UpstreamURL: upstream.Request.URL.String(), Body: &releaseBody{ReadCloser: upstream.Body, release: func() { a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, upstream.StatusCode, nil) lease.Release() @@ -175,7 +176,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response if streaming { prepared, preflightErr := preflightUpstream(upstream.Body) if preflightErr == nil { - body := a.streamOpenAIResponse(ctx, prepared, lease, request.Credential, responseID, input.Model, request.Operation, normalized.Prompt, previous, tools, parallelTools, conversationOptions, request.PublicBaseURL) + body := a.streamOpenAIResponse(ctx, prepared, lease, request.Credential, responseID, input.Model, request.Operation, normalized.Prompt, previous, tools, parallelTools, conversationOptions) return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: body}, nil } if errors.Is(preflightErr, errWebAntiBot) && attempt == 0 && a.invalidateSignedStatsig(http.MethodPost, statsigTarget) { @@ -215,7 +216,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response parsed.ToolChoice = tools.ResponseChoice parsed.ParallelTools = parallelTools applyParsedToolCalls(&parsed, tools) - if err := a.archiveChatImages(ctx, request.Credential, &parsed, request.PublicBaseURL); err != nil { + if err := a.archiveChatImages(ctx, request.Credential, &parsed); err != nil { return nil, err } payload := buildOpenAIResult(request.Operation, responseID, input.Model, parsed, false, conversationOptions) @@ -351,7 +352,7 @@ func (a *Adapter) handleResponseResource(ctx context.Context, request provider.R return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: jsonHeaders(), Body: io.NopCloser(strings.NewReader(state.ResponseJSON))}, nil } -func (a *Adapter) streamOpenAIResponse(ctx context.Context, source io.ReadCloser, lease *infraegress.Lease, credential account.Credential, responseID, model, operation, prompt string, previous *inferencedomain.WebResponseState, tools toolConfiguration, parallelTools bool, options conversation.ResponseOptions, publicBaseURL string) io.ReadCloser { +func (a *Adapter) streamOpenAIResponse(ctx context.Context, source io.ReadCloser, lease *infraegress.Lease, credential account.Credential, responseID, model, operation, prompt string, previous *inferencedomain.WebResponseState, tools toolConfiguration, parallelTools bool, options conversation.ResponseOptions) io.ReadCloser { reader, writer := io.Pipe() go func() { defer source.Close() @@ -379,7 +380,7 @@ func (a *Adapter) streamOpenAIResponse(ctx context.Context, source io.ReadCloser } if kind == "image" { rawURL := delta - item, imageErr := a.imageDataItem(ctx, credential, imagineImageValue{URL: delta}, "url", publicBaseURL) + item, imageErr := a.imageDataItem(ctx, credential, imagineImageValue{URL: delta}, "url") if imageErr != nil { return imageErr } @@ -441,7 +442,7 @@ func (a *Adapter) streamOpenAIResponse(ctx context.Context, source io.ReadCloser if _, exists := archivedImages[rawURL]; exists { continue } - item, imageErr := a.imageDataItem(ctx, credential, imagineImageValue{URL: rawURL}, "url", publicBaseURL) + item, imageErr := a.imageDataItem(ctx, credential, imagineImageValue{URL: rawURL}, "url") if imageErr != nil { _ = writer.CloseWithError(imageErr) return @@ -950,9 +951,9 @@ func applyParsedToolCalls(parsed *parsedChat, configuration toolConfiguration) { parsed.ToolCalls = result.Calls } -func (a *Adapter) archiveChatImages(ctx context.Context, credential account.Credential, parsed *parsedChat, publicBaseURL string) error { +func (a *Adapter) archiveChatImages(ctx context.Context, credential account.Credential, parsed *parsedChat) error { for _, rawURL := range parsed.Images { - item, err := a.imageDataItem(ctx, credential, imagineImageValue{URL: rawURL}, "url", publicBaseURL) + item, err := a.imageDataItem(ctx, credential, imagineImageValue{URL: rawURL}, "url") if err != nil { return err } diff --git a/backend/internal/infra/provider/web/image.go b/backend/internal/infra/provider/web/image.go index 47ffc67a..39608df1 100644 --- a/backend/internal/infra/provider/web/image.go +++ b/backend/internal/infra/provider/web/image.go @@ -19,11 +19,16 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/account" domainegress "github.com/chenyme/grok2api/backend/internal/domain/egress" + mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" ) -const maxGeneratedImages = 10 +const ( + maxGeneratedImages = 10 + mediaOutputAttempts = 3 + imageDownloadTimeout = 60 * time.Second +) var errLiteImageReady = errors.New("Lite 图片已完成") @@ -271,7 +276,7 @@ func (a *Adapter) generateLiteImage(ctx context.Context, request provider.ImageG } urls = append(urls, value) } - response, err := a.imageResponse(ctx, request.Credential, urls, nil, count, format, request.PublicBaseURL) + response, err := a.imageResponse(ctx, request.Credential, urls, nil, count, format) if response != nil { response.QuotaUnits = count } @@ -411,7 +416,7 @@ func (a *Adapter) forwardLiteChatCompletion(ctx context.Context, request provide if streaming { reader, writer := io.Pipe() streamCtx, cancel := context.WithCancel(ctx) - go a.streamLiteChatImages(streamCtx, writer, request.Credential, spec, responseID, input.Model, normalized.Prompt, count, format, request.PublicBaseURL) + go a.streamLiteChatImages(streamCtx, writer, request.Credential, spec, responseID, input.Model, normalized.Prompt, count, format) return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: &cancelBody{ReadCloser: reader, cancel: cancel}, QuotaUnits: count}, nil } parsed := parsedChat{ResponseID: responseID, InputTokens: estimateTokens(normalized.Prompt)} @@ -424,7 +429,7 @@ func (a *Adapter) forwardLiteChatCompletion(ctx context.Context, request provide } return nil, err } - item, err := a.imageDataItem(ctx, request.Credential, imagineImageValue{URL: rawURL}, format, request.PublicBaseURL) + item, err := a.imageDataItem(ctx, request.Credential, imagineImageValue{URL: rawURL}, format) if err != nil { return nil, err } @@ -441,7 +446,7 @@ func (a *Adapter) forwardLiteChatCompletion(ctx context.Context, request provide return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: jsonHeaders(), Body: io.NopCloser(bytes.NewReader(data)), QuotaUnits: count}, nil } -func (a *Adapter) streamLiteChatImages(ctx context.Context, writer *io.PipeWriter, credential account.Credential, spec ModelSpec, responseID, model, prompt string, count int, format string, publicBaseURL string) { +func (a *Adapter) streamLiteChatImages(ctx context.Context, writer *io.PipeWriter, credential account.Credential, spec ModelSpec, responseID, model, prompt string, count int, format string) { parsed := parsedChat{ResponseID: responseID, InputTokens: estimateTokens(prompt)} writeStreamStart(writer, "chat", responseID, model, parsed.InputTokens) for range count { @@ -450,7 +455,7 @@ func (a *Adapter) streamLiteChatImages(ctx context.Context, writer *io.PipeWrite _ = writer.CloseWithError(err) return } - item, err := a.imageDataItem(ctx, credential, imagineImageValue{URL: rawURL}, format, publicBaseURL) + item, err := a.imageDataItem(ctx, credential, imagineImageValue{URL: rawURL}, format) if err != nil { _ = writer.CloseWithError(err) return @@ -529,6 +534,7 @@ func (a *Adapter) generateWSImage(ctx context.Context, request provider.ImageGen connection.SetReadLimit(64 << 20) deadline := time.Now().Add(time.Duration(cfg.ImageTimeoutSeconds) * time.Second) _ = connection.SetReadDeadline(deadline) + _ = connection.SetWriteDeadline(deadline) if err := connection.WriteJSON(imagineResetMessage()); err != nil { a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, err) return nil, err @@ -543,7 +549,7 @@ func (a *Adapter) generateWSImage(ctx context.Context, request provider.ImageGen leaseOwned = false connectionOwned = false streamID := newWebID("imggen") - go a.streamImagineImages(streamCtx, writer, connection, lease, request.Credential, streamID, count, format, ratio, resolution, modelConfig, request.PublicBaseURL) + go a.streamImagineImages(streamCtx, writer, connection, lease, request.Credential, streamID, count, format, ratio, resolution, modelConfig) return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: &cancelBody{ReadCloser: reader, cancel: cancel}, QuotaUnits: count}, nil } @@ -585,7 +591,7 @@ func (a *Adapter) generateWSImage(ctx context.Context, request provider.ImageGen urls = append(urls, image.URL) blobs = append(blobs, image.Blob) } - result, err := a.imageResponse(ctx, request.Credential, urls, blobs, count, format, request.PublicBaseURL) + result, err := a.imageResponse(ctx, request.Credential, urls, blobs, count, format) if result != nil { result.QuotaUnits = count } @@ -676,7 +682,7 @@ func (a *Adapter) EditImage(ctx context.Context, request provider.ImageEditReque if len(urls) == 0 { return nil, fmt.Errorf("图片编辑完成但没有返回图片") } - result, err := a.imageResponse(ctx, request.Credential, urls, nil, count, format, request.PublicBaseURL) + result, err := a.imageResponse(ctx, request.Credential, urls, nil, count, format) if result != nil { result.QuotaUnits = count } @@ -937,14 +943,14 @@ func (a *Adapter) postJSONWithReferer(ctx context.Context, cfg Config, lease *eg return nil, fmt.Errorf("Grok Web Statsig 刷新失败") } -func (a *Adapter) imageResponse(ctx context.Context, credential account.Credential, urls, blobs []string, count int, format string, publicBaseURL string) (*provider.Response, error) { +func (a *Adapter) imageResponse(ctx context.Context, credential account.Credential, urls, blobs []string, count int, format string) (*provider.Response, error) { data := make([]any, 0, min(count, len(urls))) for index := 0; index < count && index < len(urls); index++ { blob := "" if index < len(blobs) { blob = blobs[index] } - item, err := a.imageDataItem(ctx, credential, imagineImageValue{URL: urls[index], Blob: blob}, format, publicBaseURL) + item, err := a.imageDataItem(ctx, credential, imagineImageValue{URL: urls[index], Blob: blob}, format) if err != nil { return nil, err } @@ -953,24 +959,43 @@ func (a *Adapter) imageResponse(ctx context.Context, credential account.Credenti return jsonProviderResponse(http.StatusOK, map[string]any{"created": time.Now().Unix(), "data": data}), nil } -func (a *Adapter) imageDataItem(ctx context.Context, credential account.Credential, image imagineImageValue, format string, publicBaseURL string) (map[string]any, error) { +func (a *Adapter) imageDataItem(ctx context.Context, credential account.Credential, image imagineImageValue, format string) (map[string]any, error) { if a.assets == nil { - return nil, fmt.Errorf("图片媒体存储未配置") + return nil, provider.NewMediaPostProcessingError(provider.MediaPostProcessingStorage, fmt.Errorf("图片媒体存储未配置")) } raw, err := a.imageBytes(ctx, credential, image) if err != nil { - return nil, err + return nil, provider.NewMediaPostProcessingError(provider.MediaPostProcessingDownload, err) } - asset, err := a.assets.SaveImage(ctx, raw) + asset, err := a.saveImageWithRetry(ctx, raw) if err != nil { - return nil, err + return nil, provider.NewMediaPostProcessingError(provider.MediaPostProcessingStorage, err) } if format != "b64_json" { - return map[string]any{"url": a.assets.PublicImageURL(publicBaseURL, asset.ID), "mime_type": asset.MIMEType, "revised_prompt": ""}, nil + return map[string]any{"url": a.assets.PublicImageURL(asset.ID), "mime_type": asset.MIMEType, "revised_prompt": ""}, nil } return map[string]any{"b64_json": base64.StdEncoding.EncodeToString(raw), "mime_type": asset.MIMEType, "revised_prompt": ""}, nil } +// saveImageWithRetry 只重试当前生成结果的本地持久化,不重新请求上游生成。 +func (a *Adapter) saveImageWithRetry(ctx context.Context, raw []byte) (mediadomain.Asset, error) { + var lastErr error + for attempt := 0; attempt < mediaOutputAttempts; attempt++ { + asset, err := a.assets.SaveImage(ctx, raw) + if err == nil { + return asset, nil + } + lastErr = err + if ctx.Err() != nil || attempt+1 >= mediaOutputAttempts { + break + } + if err := waitMediaOutputRetry(ctx, attempt); err != nil { + return mediadomain.Asset{}, err + } + } + return mediadomain.Asset{}, lastErr +} + func (a *Adapter) imageBytes(ctx context.Context, credential account.Credential, image imagineImageValue) ([]byte, error) { if strings.TrimSpace(image.Blob) != "" { raw, err := decodeImageBlob(image.Blob) @@ -984,7 +1009,7 @@ func (a *Adapter) imageBytes(ctx context.Context, credential account.Credential, return a.downloadImage(ctx, credential, image.URL) } -func (a *Adapter) streamImagineImages(ctx context.Context, writer *io.PipeWriter, connection *websocket.Conn, lease *egress.Lease, credential account.Credential, streamID string, count int, format, ratio, resolution string, modelConfig imagineModelConfig, publicBaseURL string) { +func (a *Adapter) streamImagineImages(ctx context.Context, writer *io.PipeWriter, connection *websocket.Conn, lease *egress.Lease, credential account.Credential, streamID string, count int, format, ratio, resolution string, modelConfig imagineModelConfig) { defer lease.Release() defer connection.Close() done := make(chan struct{}) @@ -1038,7 +1063,7 @@ func (a *Adapter) streamImagineImages(ctx context.Context, writer *io.PipeWriter if emitted >= count { break } - item, err := a.imageDataItem(ctx, credential, image, format, publicBaseURL) + item, err := a.imageDataItem(ctx, credential, image, format) if err != nil { writeImagineStreamFailure(writer, streamID, "image_output_error", "图片结果处理失败") _ = writer.CloseWithError(err) @@ -1091,34 +1116,76 @@ func (a *Adapter) downloadImage(ctx context.Context, credential account.Credenti if err != nil { return nil, err } - lease, err := a.egress.Acquire(ctx, domainegress.ScopeWebAsset, fmt.Sprintf("%d", credential.ID)) + downloadCtx, cancel := context.WithTimeout(ctx, imageDownloadTimeout) + defer cancel() + var lastErr error + for attempt := 0; attempt < mediaOutputAttempts; attempt++ { + raw, retryable, attemptErr := a.downloadImageAttempt(downloadCtx, credential.ID, token, parsed.String()) + if attemptErr == nil { + return raw, nil + } + lastErr = attemptErr + if !retryable || downloadCtx.Err() != nil || attempt+1 >= mediaOutputAttempts { + break + } + if err := waitMediaOutputRetry(downloadCtx, attempt); err != nil { + return nil, err + } + } + return nil, lastErr +} + +// downloadImageAttempt 每次沿用同一账号,只允许出口管理器重新选择资源节点。 +func (a *Adapter) downloadImageAttempt(ctx context.Context, accountID uint64, token, rawURL string) ([]byte, bool, error) { + lease, err := a.egress.Acquire(ctx, domainegress.ScopeWebAsset, fmt.Sprintf("%d", accountID)) if err != nil { - return nil, err + return nil, true, err } defer lease.Release() - request, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil) + request, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) if err != nil { - return nil, err + return nil, false, err } request.Header = buildHeaders(token, lease, "") request.Header.Del("Content-Type") response, err := lease.Do(request) if err != nil { - return nil, err + a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, err) + return nil, ctx.Err() == nil, err } defer response.Body.Close() if response.StatusCode < 200 || response.StatusCode >= 300 { - return nil, fmt.Errorf("下载图片返回 %d", response.StatusCode) + a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, response.StatusCode, nil) + retryable := response.StatusCode == http.StatusForbidden || response.StatusCode == http.StatusRequestTimeout || response.StatusCode == http.StatusTooEarly || response.StatusCode == http.StatusTooManyRequests || response.StatusCode >= 500 + return nil, retryable, fmt.Errorf("下载图片返回 %d", response.StatusCode) } contentType := strings.ToLower(strings.TrimSpace(strings.Split(response.Header.Get("Content-Type"), ";")[0])) if contentType != "" && !strings.HasPrefix(contentType, "image/") { - return nil, fmt.Errorf("上游图片 Content-Type 无效") + return nil, false, fmt.Errorf("上游图片 Content-Type 无效") } raw, err := io.ReadAll(io.LimitReader(response.Body, (32<<20)+1)) - if err != nil || len(raw) > 32<<20 { - return nil, fmt.Errorf("图片下载失败或超过 32 MiB") + if err != nil { + a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, err) + return nil, ctx.Err() == nil, fmt.Errorf("读取图片内容: %w", err) + } + if len(raw) > 32<<20 { + return nil, false, fmt.Errorf("图片下载超过 32 MiB") + } + a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, response.StatusCode, nil) + return raw, false, nil +} + +func waitMediaOutputRetry(ctx context.Context, attempt int) error { + delays := [...]time.Duration{200 * time.Millisecond, 750 * time.Millisecond} + delay := delays[min(attempt, len(delays)-1)] + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return nil } - return raw, nil } func decodeImageBlob(value string) ([]byte, error) { diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index cf215ea5..0f6672dc 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -546,11 +546,11 @@ func TestGeneratedImageAssetHostsRemainStrict(t *testing.T) { func TestImageStreamExtensionEventsAndPayloads(t *testing.T) { adapter := &Adapter{assets: imageAssetStoreStub{}} - urlItem, err := adapter.imageDataItem(context.Background(), account.Credential{}, imagineImageValue{URL: "https://imgen.x.ai/image.jpg", Blob: "aW1hZ2U="}, "url", "https://api.example") + urlItem, err := adapter.imageDataItem(context.Background(), account.Credential{}, imagineImageValue{URL: "https://imgen.x.ai/image.jpg", Blob: "aW1hZ2U="}, "url") if err != nil || urlItem["url"] != "https://api.example/v1/media/images/img_test" || urlItem["mime_type"] != "image/jpeg" || urlItem["revised_prompt"] != "" { t.Fatalf("url item = %#v, err=%v", urlItem, err) } - b64Item, err := adapter.imageDataItem(context.Background(), account.Credential{}, imagineImageValue{Blob: "aW1hZ2U="}, "b64_json", "https://api.example") + b64Item, err := adapter.imageDataItem(context.Background(), account.Credential{}, imagineImageValue{Blob: "aW1hZ2U="}, "b64_json") if err != nil || b64Item["b64_json"] != "aW1hZ2U=" || b64Item["mime_type"] != "image/jpeg" { t.Fatalf("base64 item = %#v, err=%v", b64Item, err) } @@ -562,16 +562,58 @@ func TestImageStreamExtensionEventsAndPayloads(t *testing.T) { } } +func TestImageDataItemRetriesStorageWithoutRegenerating(t *testing.T) { + store := &imageAssetStoreRetryStub{failures: 2} + adapter := &Adapter{assets: store} + item, err := adapter.imageDataItem(context.Background(), account.Credential{ID: 42}, imagineImageValue{Blob: "aW1hZ2U="}, "url") + if err != nil { + t.Fatal(err) + } + if store.calls != mediaOutputAttempts || item["url"] != "https://api.example/v1/media/images/img_retry" { + t.Fatalf("storage retry calls=%d item=%#v", store.calls, item) + } +} + +func TestImageDataItemClassifiesExhaustedStorageFailure(t *testing.T) { + store := &imageAssetStoreRetryStub{failures: mediaOutputAttempts} + adapter := &Adapter{assets: store} + _, err := adapter.imageDataItem(context.Background(), account.Credential{ID: 42}, imagineImageValue{Blob: "aW1hZ2U="}, "url") + if err == nil || !provider.IsMediaPostProcessingError(err) || store.calls != mediaOutputAttempts { + t.Fatalf("storage failure err=%v calls=%d", err, store.calls) + } + var processingErr *provider.MediaPostProcessingError + if !errors.As(err, &processingErr) || processingErr.Stage != provider.MediaPostProcessingStorage { + t.Fatalf("storage failure classification = %#v", processingErr) + } +} + type imageAssetStoreStub struct{} func (imageAssetStoreStub) SaveImage(context.Context, []byte) (mediadomain.Asset, error) { return mediadomain.Asset{ID: "img_test", MIMEType: "image/jpeg"}, nil } -func (imageAssetStoreStub) PublicImageURL(string, string) string { +func (imageAssetStoreStub) PublicImageURL(string) string { return "https://api.example/v1/media/images/img_test" } +type imageAssetStoreRetryStub struct { + failures int + calls int +} + +func (s *imageAssetStoreRetryStub) SaveImage(context.Context, []byte) (mediadomain.Asset, error) { + s.calls++ + if s.calls <= s.failures { + return mediadomain.Asset{}, errors.New("temporary storage failure") + } + return mediadomain.Asset{ID: "img_retry", MIMEType: "image/jpeg"}, nil +} + +func (*imageAssetStoreRetryStub) PublicImageURL(string) string { + return "https://api.example/v1/media/images/img_retry" +} + func TestParseVideoStreamFixture(t *testing.T) { fixture := `data: {"result":{"response":{"streamingVideoGenerationResponse":{"progress":42,"videoPostId":"post_1"}}}}` + "\n" + `data: {"result":{"response":{"streamingVideoGenerationResponse":{"progress":100,"videoPostId":"post_1","videoUrl":"/videos/final.mp4"}}}}` + "\n" diff --git a/backend/internal/infra/provider/web/quota.go b/backend/internal/infra/provider/web/quota.go index fb86dd11..46a5b39b 100644 --- a/backend/internal/infra/provider/web/quota.go +++ b/backend/internal/infra/provider/web/quota.go @@ -57,12 +57,12 @@ func resolveWebTierFromQuota(current account.WebTier, windows []account.QuotaWin } return tier, weeklyAvailable && tier != account.WebTierBasic } - // 周额度是付费账号信号,但无法区分 Super/Heavy。只有已确认的 Heavy - // 可以在模式额度暂时不可用时保留,其余账号只授予最低付费等级。 - if current == account.WebTierHeavy { - return account.WebTierHeavy, weeklyAvailable + // 周额度是付费账号信号,但无法区分 Super/Heavy。已确认的等级在模式 + // 额度暂时不可用时保留;未确认(Auto/Basic)的不能凭周额度提权。 + if current == account.WebTierHeavy || current == account.WebTierSuper { + return current, weeklyAvailable } - return account.WebTierSuper, weeklyAvailable + return current, false } // inferWebTierFromQuota 使用 Grok Web /rest/rate-limits 的真实额度形态判级。 diff --git a/backend/internal/infra/provider/web/quota_test.go b/backend/internal/infra/provider/web/quota_test.go index b1e7a104..082cccdb 100644 --- a/backend/internal/infra/provider/web/quota_test.go +++ b/backend/internal/infra/provider/web/quota_test.go @@ -85,6 +85,21 @@ func TestResolveWebTierUsesFreshWebQuotaOverStoredTier(t *testing.T) { if tier != account.WebTierAuto || useWeekly { t.Fatalf("unknown snapshot resolved to %q, weekly=%v", tier, useWeekly) } + + tier, useWeekly = resolveWebTierFromQuota(account.WebTierSuper, nil, true) + if tier != account.WebTierSuper || !useWeekly { + t.Fatalf("super weekly fallback resolved to %q, weekly=%v", tier, useWeekly) + } + + tier, useWeekly = resolveWebTierFromQuota(account.WebTierBasic, nil, true) + if tier != account.WebTierBasic || useWeekly { + t.Fatalf("basic should not be promoted when modes unavailable: got %q, weekly=%v", tier, useWeekly) + } + + tier, useWeekly = resolveWebTierFromQuota(account.WebTierAuto, nil, true) + if tier != account.WebTierAuto || useWeekly { + t.Fatalf("auto should not be promoted when modes unavailable: got %q, weekly=%v", tier, useWeekly) + } } func TestSyncQuotaCorrectsStoredSuperFromFreshWebQuota(t *testing.T) { diff --git a/backend/internal/repository/audit.go b/backend/internal/repository/audit.go index be710f59..a29e56d0 100644 --- a/backend/internal/repository/audit.go +++ b/backend/internal/repository/audit.go @@ -11,6 +11,7 @@ import ( type AuditRepository interface { Create(ctx context.Context, value audit.Record) error CreateBatch(ctx context.Context, values []audit.Record) error + Get(ctx context.Context, id uint64) (audit.Record, error) List(ctx context.Context, offset, limit int) ([]audit.Record, int64, error) ListCursor(ctx context.Context, query AuditCursorQuery) ([]audit.Record, bool, error) Summarize(ctx context.Context, query AuditSummaryQuery) (audit.Summary, error) diff --git a/backend/internal/repository/media.go b/backend/internal/repository/media.go index a62f52f7..525ec405 100644 --- a/backend/internal/repository/media.go +++ b/backend/internal/repository/media.go @@ -8,12 +8,45 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/media" ) +// MediaAssetListQuery 表示管理端媒体资源列表的查询条件。 +type MediaAssetListQuery struct { + Page PageQuery +} + +// MediaJobListFilter 表示视频任务列表允许使用的业务筛选条件。 +type MediaJobListFilter struct { + Status string +} + +// MediaJobListQuery 表示管理端视频任务列表的查询条件。 +type MediaJobListQuery struct { + Page PageQuery + Filter MediaJobListFilter +} + +// MediaAssetStats 表示媒体资源的聚合统计结果。 +type MediaAssetStats struct { + TotalImages int64 + TotalBytes int64 +} + +// MediaJobStats 表示各状态视频任务的聚合统计结果。 +type MediaJobStats struct { + TotalJobs int64 + Completed int64 + Failed int64 + InProgress int64 + Queued int64 +} + type MediaJobRepository interface { CreateMediaJob(ctx context.Context, value media.Job) error GetMediaJob(ctx context.Context, id string, clientKeyID uint64) (media.Job, error) UpdateMediaJob(ctx context.Context, value media.Job) error + ListMediaJobs(ctx context.Context, query MediaJobListQuery) ([]media.Job, int64, error) + SummarizeMediaJobs(ctx context.Context) (MediaJobStats, error) ListRecoverableMediaJobs(ctx context.Context, limit int) ([]media.Job, error) - ListUnrecordedCompletedMediaJobs(ctx context.Context, limit int) ([]media.Job, error) + ListUnrecordedTerminalMediaJobs(ctx context.Context, limit int) ([]media.Job, error) TryClaimMediaJob(ctx context.Context, id string, now, leaseUntil time.Time, claimToken string) (media.Job, bool, error) MarkMediaJobUsageRecorded(ctx context.Context, id string, recordedAt time.Time) error } @@ -22,6 +55,8 @@ type MediaJobRepository interface { type MediaAssetRepository interface { CreateMediaAsset(ctx context.Context, value media.Asset) error GetMediaAsset(ctx context.Context, id string) (media.Asset, error) + ListMediaAssets(ctx context.Context, query MediaAssetListQuery) ([]media.Asset, int64, error) + SummarizeMediaAssets(ctx context.Context) (MediaAssetStats, error) TotalMediaAssetBytes(ctx context.Context) (int64, error) ListOldestMediaAssets(ctx context.Context, limit int) ([]media.Asset, error) DeleteMediaAsset(ctx context.Context, id string) error diff --git a/backend/internal/transport/http/audit/handler.go b/backend/internal/transport/http/audit/handler.go index 302cc5c6..b3af6d03 100644 --- a/backend/internal/transport/http/audit/handler.go +++ b/backend/internal/transport/http/audit/handler.go @@ -1,10 +1,12 @@ package audit import ( + "encoding/base64" "errors" "net/http" "strconv" "time" + "unicode/utf8" auditapp "github.com/chenyme/grok2api/backend/internal/application/audit" auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit" @@ -20,6 +22,7 @@ func NewHandler(service *auditapp.Service) *Handler { return &Handler{service: s func (h *Handler) Register(router *gin.RouterGroup) { router.GET("/request-audits", h.list) router.GET("/request-audits/summary", h.summary) + router.GET("/request-audits/:id", h.get) } type auditResponse struct { @@ -35,6 +38,10 @@ type auditResponse struct { UsageSource string `json:"usageSource"` AccountID *uint64 `json:"accountId,string,omitempty"` AccountName string `json:"accountName,omitempty"` + EgressNodeID *uint64 `json:"egressNodeId,string,omitempty"` + EgressNodeName string `json:"egressNodeName,omitempty"` + EgressScope string `json:"egressScope,omitempty"` + EgressMode string `json:"egressMode,omitempty"` StatusCode int `json:"statusCode"` Streaming bool `json:"streaming"` MediaInputImages int64 `json:"mediaInputImages"` @@ -55,9 +62,42 @@ type auditResponse struct { ContextOutputTokens int64 `json:"contextOutputTokens"` DurationMS int64 `json:"durationMs"` ErrorCode string `json:"errorCode,omitempty"` + AttemptCount int `json:"attemptCount"` CreatedAt time.Time `json:"createdAt"` } +type auditAttemptResponse struct { + ID uint64 `json:"id,string"` + Number int `json:"number"` + Source string `json:"source"` + Stage string `json:"stage"` + AccountID *uint64 `json:"accountId,string,omitempty"` + AccountName string `json:"accountName,omitempty"` + Method string `json:"method,omitempty"` + RequestPath string `json:"requestPath,omitempty"` + UpstreamURL string `json:"upstreamUrl,omitempty"` + StartedAt time.Time `json:"startedAt"` + DurationMS int64 `json:"durationMs"` + UpstreamStatusCode *int `json:"upstreamStatusCode,omitempty"` + UpstreamStatus string `json:"upstreamStatus,omitempty"` + ResponseHeaders map[string][]string `json:"responseHeaders"` + ResponseBody string `json:"responseBody"` + ResponseBodyEncoding string `json:"responseBodyEncoding"` + ResponseBodyTruncated bool `json:"responseBodyTruncated"` + TransportError string `json:"transportError,omitempty"` + ErrorChain []auditErrorFrameResponse `json:"errorChain"` +} + +type auditErrorFrameResponse struct { + Type string `json:"type"` + Message string `json:"message"` +} + +type auditDetailResponse struct { + Audit auditResponse `json:"audit"` + Attempts []auditAttemptResponse `json:"attempts"` +} + func (h *Handler) list(c *gin.Context) { if c.Query("pagination") == "cursor" { h.listCursor(c) @@ -112,6 +152,46 @@ func (h *Handler) listCursor(c *gin.Context) { response.Success(c, http.StatusOK, gin.H{"items": items, "pageSize": pageSize, "nextCursor": result.NextCursor, "hasMore": result.HasMore}) } +func (h *Handler) get(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil || id == 0 { + response.Error(c, http.StatusBadRequest, "invalidId", "审计 ID 无效") + return + } + value, err := h.service.Get(c.Request.Context(), id) + if errors.Is(err, repository.ErrNotFound) { + response.Error(c, http.StatusNotFound, "auditNotFound", "审计记录不存在") + return + } + if err != nil { + response.Error(c, http.StatusInternalServerError, "auditDetailFailed", "读取审计详情失败") + return + } + attempts := make([]auditAttemptResponse, 0, len(value.Attempts)) + for _, attempt := range value.Attempts { + body := string(attempt.ResponseBody) + encoding := "utf8" + if !utf8.Valid(attempt.ResponseBody) { + body = base64.StdEncoding.EncodeToString(attempt.ResponseBody) + encoding = "base64" + } + errorChain := make([]auditErrorFrameResponse, 0, len(attempt.ErrorChain)) + for _, frame := range attempt.ErrorChain { + errorChain = append(errorChain, auditErrorFrameResponse{Type: frame.Type, Message: frame.Message}) + } + attempts = append(attempts, auditAttemptResponse{ + ID: attempt.ID, Number: attempt.Number, Source: string(attempt.Source), Stage: attempt.Stage, + AccountID: attempt.AccountID, AccountName: attempt.AccountName, Method: attempt.Method, RequestPath: attempt.RequestPath, + UpstreamURL: attempt.UpstreamURL, StartedAt: attempt.StartedAt, DurationMS: attempt.DurationMS, + UpstreamStatusCode: attempt.UpstreamStatusCode, UpstreamStatus: attempt.UpstreamStatus, + ResponseHeaders: attempt.ResponseHeaders, ResponseBody: body, ResponseBodyEncoding: encoding, + ResponseBodyTruncated: attempt.ResponseBodyTruncated, + TransportError: attempt.TransportError, ErrorChain: errorChain, + }) + } + response.Success(c, http.StatusOK, auditDetailResponse{Audit: newAuditResponse(value), Attempts: attempts}) +} + type summaryResponse struct { Period string `json:"period"` GeneratedAt time.Time `json:"generatedAt"` @@ -195,13 +275,15 @@ func newAuditResponse(value auditdomain.Record) auditResponse { ID: value.ID, RequestID: value.RequestID, ClientKeyID: value.ClientKeyID, ClientKeyName: value.ClientKeyName, ModelRouteID: value.ModelRouteID, ModelPublicID: value.ModelPublicID, ModelUpstreamModel: value.ModelUpstreamModel, Provider: value.Provider, Operation: string(value.Operation), UsageSource: string(value.UsageSource), - AccountID: value.AccountID, AccountName: value.AccountName, StatusCode: value.StatusCode, Streaming: value.Streaming, + AccountID: value.AccountID, AccountName: value.AccountName, + EgressNodeID: value.EgressNodeID, EgressNodeName: value.EgressNodeName, EgressScope: value.EgressScope, EgressMode: string(value.EgressMode), + StatusCode: value.StatusCode, Streaming: value.Streaming, MediaInputImages: value.MediaInputImages, MediaOutputImages: value.MediaOutputImages, MediaOutputSeconds: value.MediaOutputSeconds, InputTokens: value.InputTokens, CachedInputTokens: value.CachedInputTokens, OutputTokens: value.OutputTokens, ReasoningTokens: value.ReasoningTokens, TotalTokens: value.TotalTokens, CostInUSDTicks: value.CostInUSDTicks, EstimatedCostInUSDTicks: value.EstimatedCostInUSDTicks, PricingModel: value.PricingModel, PricingVersion: value.PricingVersion, NumSourcesUsed: value.NumSourcesUsed, NumServerSideToolsUsed: value.NumServerSideToolsUsed, ContextInputTokens: value.ContextInputTokens, ContextOutputTokens: value.ContextOutputTokens, DurationMS: value.DurationMS, - ErrorCode: value.ErrorCode, CreatedAt: value.CreatedAt, + ErrorCode: value.ErrorCode, AttemptCount: value.AttemptCount, CreatedAt: value.CreatedAt, } } diff --git a/backend/internal/transport/http/audit/handler_test.go b/backend/internal/transport/http/audit/handler_test.go new file mode 100644 index 00000000..bca270aa --- /dev/null +++ b/backend/internal/transport/http/audit/handler_test.go @@ -0,0 +1,82 @@ +package audit + +import ( + "context" + "encoding/base64" + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + "time" + + auditapp "github.com/chenyme/grok2api/backend/internal/application/audit" + auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit" + "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" + "github.com/gin-gonic/gin" +) + +func TestAuditDetailReturnsCompleteTextAndBinaryBodies(t *testing.T) { + gin.SetMode(gin.TestMode) + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "audit-handler.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repository := relational.NewAuditRepository(database) + now := time.Now().UTC() + status := http.StatusBadGateway + if err := repository.Create(ctx, auditdomain.Record{ + EventID: "evt_audit_handler_0001", RequestID: "request-detail", ClientKeyID: 1, ModelRouteID: 1, StatusCode: status, CreatedAt: now, + Attempts: []auditdomain.Attempt{ + {Number: 1, Source: auditdomain.AttemptSourceUpstreamHTTP, Stage: "upstream_response", StartedAt: now, UpstreamStatusCode: &status, ResponseHeaders: http.Header{"Content-Type": {"application/json"}}, ResponseBody: []byte(`{"error":"complete"}`), ResponseBodyTruncated: true}, + {Number: 2, Source: auditdomain.AttemptSourceUpstreamHTTP, Stage: "upstream_response", StartedAt: now, UpstreamStatusCode: &status, ResponseHeaders: http.Header{}, ResponseBody: []byte{0x00, 0xff, 0x01}}, + }, + }); err != nil { + t.Fatal(err) + } + service := auditapp.NewService(repository, slog.Default(), 8, 4, time.Second) + router := gin.New() + NewHandler(service).Register(router.Group("/api/admin/v1")) + + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/admin/v1/request-audits/1", nil)) + if recorder.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", recorder.Code, recorder.Body.String()) + } + var payload struct { + Data struct { + Audit struct { + AttemptCount int `json:"attemptCount"` + } `json:"audit"` + Attempts []struct { + ResponseBody string `json:"responseBody"` + ResponseBodyEncoding string `json:"responseBodyEncoding"` + ResponseBodyTruncated bool `json:"responseBodyTruncated"` + } `json:"attempts"` + } `json:"data"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil { + t.Fatal(err) + } + if payload.Data.Audit.AttemptCount != 2 || len(payload.Data.Attempts) != 2 { + t.Fatalf("payload = %#v", payload) + } + if payload.Data.Attempts[0].ResponseBodyEncoding != "utf8" || payload.Data.Attempts[0].ResponseBody != `{"error":"complete"}` || !payload.Data.Attempts[0].ResponseBodyTruncated { + t.Fatalf("text body = %#v", payload.Data.Attempts[0]) + } + if payload.Data.Attempts[1].ResponseBodyEncoding != "base64" || payload.Data.Attempts[1].ResponseBody != base64.StdEncoding.EncodeToString([]byte{0x00, 0xff, 0x01}) { + t.Fatalf("binary body = %#v", payload.Data.Attempts[1]) + } + + missing := httptest.NewRecorder() + router.ServeHTTP(missing, httptest.NewRequest(http.MethodGet, "/api/admin/v1/request-audits/999", nil)) + if missing.Code != http.StatusNotFound { + t.Fatalf("missing status = %d, body = %s", missing.Code, missing.Body.String()) + } +} diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index 57f25336..29f853ba 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -190,7 +190,7 @@ func (h *Handler) createChatCompletion(c *gin.Context) { requestIDValue, _ := requestID.(string) result, err := h.gateway.CreateChatCompletion(c.Request.Context(), gateway.Input{ RequestID: requestIDValue, ClientKey: clientKey, PublicModel: request.Model, - Body: body, Streaming: request.Stream, PublicBaseURL: requestBaseURL(c.Request), + Body: body, Streaming: request.Stream, }) if err != nil { writeGatewayError(c, err) @@ -229,7 +229,7 @@ func (h *Handler) createMessage(c *gin.Context) { requestIDValue, _ := requestID.(string) result, err := h.gateway.CreateMessage(c.Request.Context(), gateway.Input{ RequestID: requestIDValue, ClientKey: clientKey, PublicModel: request.Model, - Body: body, Streaming: request.Stream, PublicBaseURL: requestBaseURL(c.Request), + Body: body, Streaming: request.Stream, }) if err != nil { writeGatewayAnthropicError(c, err) @@ -269,7 +269,6 @@ func (h *Handler) generateImage(c *gin.Context) { RequestID: requestID, ClientKey: clientKey, PublicModel: request.Model, Prompt: request.Prompt, Count: count, Size: request.Size, AspectRatio: request.AspectRatio, Resolution: request.Resolution, ResponseFormat: request.ResponseFormat, Streaming: request.Stream, - PublicBaseURL: requestBaseURL(c.Request), }) if err != nil { writeGatewayError(c, err) @@ -425,7 +424,6 @@ func (h *Handler) editImage(c *gin.Context) { result, err := h.gateway.EditImage(c.Request.Context(), gateway.ImageEditInput{ RequestID: requestID, ClientKey: clientKey, PublicModel: model, Prompt: prompt, ImageURLs: imageURLs, Count: count, Resolution: resolution, ResponseFormat: request.ResponseFormat, - PublicBaseURL: requestBaseURL(c.Request), }) if err != nil { writeGatewayError(c, err) @@ -654,7 +652,7 @@ func (h *Handler) handleCreate(c *gin.Context, compact bool) { } requestID, _ := c.Get(middleware.RequestIDKey) requestIDValue, _ := requestID.(string) - input := gateway.Input{RequestID: requestIDValue, ClientKey: clientKey, PublicModel: request.Model, Body: body, Streaming: request.Stream, PromptCacheKey: request.PromptCacheKey, PreviousResponseID: request.PreviousResponseID, PublicBaseURL: requestBaseURL(c.Request)} + input := gateway.Input{RequestID: requestIDValue, ClientKey: clientKey, PublicModel: request.Model, Body: body, Streaming: request.Stream, PromptCacheKey: request.PromptCacheKey, PreviousResponseID: request.PreviousResponseID} var result *gateway.Result if compact { result, err = h.gateway.CompactResponse(c.Request.Context(), input) @@ -673,28 +671,6 @@ func isJSONRequest(c *gin.Context) bool { return err == nil && strings.EqualFold(mediaType, "application/json") } -// requestBaseURL derives the public base URL from the incoming HTTP request, -// respecting X-Forwarded-Proto and X-Forwarded-Host headers set by reverse -// proxies. Returns an empty string when the request has no usable host. -func requestBaseURL(r *http.Request) string { - scheme := r.Header.Get("X-Forwarded-Proto") - if scheme == "" { - if r.TLS != nil { - scheme = "https" - } else { - scheme = "http" - } - } - host := r.Header.Get("X-Forwarded-Host") - if host == "" { - host = r.Host - } - if host == "" { - return "" - } - return scheme + "://" + strings.TrimRight(host, "/") -} - func decodeSingleJSON(reader io.Reader, target any, disallowUnknown bool) error { decoder := json.NewDecoder(reader) if disallowUnknown { diff --git a/backend/internal/transport/http/media/dto.go b/backend/internal/transport/http/media/dto.go new file mode 100644 index 00000000..58295594 --- /dev/null +++ b/backend/internal/transport/http/media/dto.go @@ -0,0 +1,40 @@ +package media + +type mediaAssetDTO struct { + ID string `json:"id"` + Kind string `json:"kind"` + MimeType string `json:"mimeType"` + SizeBytes int64 `json:"sizeBytes"` + SHA256 string `json:"sha256"` + CreatedAt string `json:"createdAt"` + URL string `json:"url"` +} + +type imageStatsDTO struct { + TotalImages int64 `json:"totalImages"` + TotalBytes int64 `json:"totalBytes"` +} + +type mediaJobDTO struct { + ID string `json:"id"` + Model string `json:"model"` + Prompt string `json:"prompt"` + Status string `json:"status"` + Progress int `json:"progress"` + Seconds int `json:"seconds"` + Size string `json:"size"` + Quality string `json:"quality"` + AccountName string `json:"accountName"` + ClientKeyName string `json:"clientKeyName"` + CreatedAt string `json:"createdAt"` + CompletedAt *string `json:"completedAt"` + ErrorMessage string `json:"errorMessage"` +} + +type videoStatsDTO struct { + TotalJobs int64 `json:"totalJobs"` + Completed int64 `json:"completed"` + Failed int64 `json:"failed"` + InProgress int64 `json:"inProgress"` + Queued int64 `json:"queued"` +} diff --git a/backend/internal/transport/http/media/handler.go b/backend/internal/transport/http/media/handler.go index b5eeff0d..4e7863d6 100644 --- a/backend/internal/transport/http/media/handler.go +++ b/backend/internal/transport/http/media/handler.go @@ -8,6 +8,8 @@ import ( "strings" mediaapp "github.com/chenyme/grok2api/backend/internal/application/media" + "github.com/chenyme/grok2api/backend/internal/repository" + "github.com/chenyme/grok2api/backend/internal/shared/response" "github.com/gin-gonic/gin" ) @@ -23,6 +25,14 @@ func (h *Handler) RegisterPublic(router *gin.Engine) { router.HEAD("/v1/media/images/:assetId", h.getImage) } +// RegisterAdmin 注册管理端媒体列表和统计端点。 +func (h *Handler) RegisterAdmin(router *gin.RouterGroup) { + router.GET("/media/images", h.listImages) + router.GET("/media/images/stats", h.imageStats) + router.GET("/media/videos", h.listVideos) + router.GET("/media/videos/stats", h.videoStats) +} + func (h *Handler) getImage(c *gin.Context) { asset, body, err := h.service.OpenImage(c.Request.Context(), c.Param("assetId")) if errors.Is(err, mediaapp.ErrAssetNotFound) { @@ -52,3 +62,86 @@ func (h *Handler) getImage(c *gin.Context) { c.Status(http.StatusOK) _, _ = io.Copy(c.Writer, body) } + +func (h *Handler) listImages(c *gin.Context) { + page, pageSize := parsePagination(c) + assets, total, err := h.service.AdminListImages(c.Request.Context(), page, pageSize, c.Query("search")) + if err != nil { + response.Error(c, http.StatusInternalServerError, "mediaListImagesFailed", "读取图片列表失败") + return + } + items := make([]mediaAssetDTO, 0, len(assets)) + for _, a := range assets { + items = append(items, mediaAssetDTO{ + ID: a.ID, Kind: a.Kind, MimeType: a.MIMEType, SizeBytes: a.SizeBytes, + SHA256: a.SHA256, CreatedAt: a.CreatedAt.Format("2006-01-02T15:04:05Z"), + URL: h.service.PublicImageURL(a.ID), + }) + } + response.Success(c, http.StatusOK, gin.H{"items": items, "page": page, "pageSize": pageSize, "total": total}) +} + +func (h *Handler) imageStats(c *gin.Context) { + stats, err := h.service.AdminImageStats(c.Request.Context()) + if err != nil { + response.Error(c, http.StatusInternalServerError, "mediaImageStatsFailed", "读取图片统计失败") + return + } + response.Success(c, http.StatusOK, imageStatsDTO{TotalImages: stats.TotalImages, TotalBytes: stats.TotalBytes}) +} + +func (h *Handler) listVideos(c *gin.Context) { + page, pageSize := parsePagination(c) + jobs, total, err := h.service.AdminListVideoJobs(c.Request.Context(), page, pageSize, c.Query("search"), c.Query("status"), repository.SortQuery{Field: c.Query("sortBy"), Direction: repository.SortDirection(c.Query("sortOrder"))}) + if errors.Is(err, mediaapp.ErrInvalidFilter) { + response.Error(c, http.StatusBadRequest, "invalidFilter", err.Error()) + return + } + if err != nil { + response.Error(c, http.StatusInternalServerError, "mediaListVideosFailed", "读取视频任务列表失败") + return + } + items := make([]mediaJobDTO, 0, len(jobs)) + for _, j := range jobs { + var completedAt *string + if j.CompletedAt != nil { + formatted := j.CompletedAt.Format("2006-01-02T15:04:05Z") + completedAt = &formatted + } + items = append(items, mediaJobDTO{ + ID: j.ID, Model: j.Model, Prompt: j.Prompt, Status: string(j.Status), + Progress: j.Progress, Seconds: j.Seconds, Size: j.Size, Quality: j.Quality, + AccountName: j.AccountName, ClientKeyName: j.ClientKeyName, + CreatedAt: j.CreatedAt.Format("2006-01-02T15:04:05Z"), + CompletedAt: completedAt, ErrorMessage: j.ErrorMessage, + }) + } + response.Success(c, http.StatusOK, gin.H{"items": items, "page": page, "pageSize": pageSize, "total": total}) +} + +func (h *Handler) videoStats(c *gin.Context) { + stats, err := h.service.AdminVideoStats(c.Request.Context()) + if err != nil { + response.Error(c, http.StatusInternalServerError, "mediaVideoStatsFailed", "读取视频统计失败") + return + } + response.Success(c, http.StatusOK, videoStatsDTO{ + TotalJobs: stats.TotalJobs, Completed: stats.Completed, Failed: stats.Failed, + InProgress: stats.InProgress, Queued: stats.Queued, + }) +} + +func parsePagination(c *gin.Context) (int, int) { + page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "20")) + if page < 1 { + page = 1 + } + if pageSize < 1 { + pageSize = 20 + } + if pageSize > 100 { + pageSize = 100 + } + return page, pageSize +} diff --git a/backend/internal/transport/http/media/handler_test.go b/backend/internal/transport/http/media/handler_test.go index bb76a9fe..ce83de2d 100644 --- a/backend/internal/transport/http/media/handler_test.go +++ b/backend/internal/transport/http/media/handler_test.go @@ -30,7 +30,7 @@ func TestPublicImageSupportsGetHeadAndETag(t *testing.T) { if err != nil { t.Fatal(err) } - service := mediaapp.NewService(relational.NewMediaAssetRepository(database), objects, nil, mediaapp.Config{ + service := mediaapp.NewService(relational.NewMediaAssetRepository(database), relational.NewMediaJobRepository(database), objects, nil, mediaapp.Config{ PublicBaseURL: "https://api.example", MaxImageBytes: 32 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: 10 * time.Minute, }) @@ -61,3 +61,37 @@ func TestPublicImageSupportsGetHeadAndETag(t *testing.T) { t.Fatalf("conditional GET status=%d size=%d", notModified.Code, notModified.Body.Len()) } } + +func TestAdminVideoListRejectsInvalidFilters(t *testing.T) { + gin.SetMode(gin.TestMode) + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "media-admin-http.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + service := mediaapp.NewService( + relational.NewMediaAssetRepository(database), + relational.NewMediaJobRepository(database), + nil, + nil, + mediaapp.Config{}, + ) + router := gin.New() + NewHandler(service).RegisterAdmin(router.Group("/api/admin/v1")) + + for _, path := range []string{ + "/api/admin/v1/media/videos?status=unknown", + "/api/admin/v1/media/videos?sortBy=input_json&sortOrder=asc", + "/api/admin/v1/media/videos?sortBy=createdAt&sortOrder=sideways", + } { + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, path, nil)) + if recorder.Code != http.StatusBadRequest { + t.Fatalf("GET %s status = %d, body = %s", path, recorder.Code, recorder.Body.String()) + } + } +} diff --git a/backend/internal/transport/http/server.go b/backend/internal/transport/http/server.go index c4f2fa0a..8f3d2598 100644 --- a/backend/internal/transport/http/server.go +++ b/backend/internal/transport/http/server.go @@ -126,7 +126,8 @@ func New(deps Dependencies) *gin.Engine { if deps.SwaggerEnabled { router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) } - mediahttp.NewHandler(deps.Media).RegisterPublic(router) + mediaHandler := mediahttp.NewHandler(deps.Media) + mediaHandler.RegisterPublic(router) adminRoot := router.Group("/api/admin/v1") authHandler := adminauthhttp.NewHandler(deps.AdminAuth, deps.SecureCookies) @@ -139,6 +140,7 @@ func New(deps Dependencies) *gin.Engine { clientkeyhttp.NewHandler(deps.ClientKeys).Register(adminProtected) audithttp.NewHandler(deps.Audits).Register(adminProtected) dashboardhttp.NewHandler(deps.Dashboard).Register(adminProtected) + mediaHandler.RegisterAdmin(adminProtected) settingshttp.NewHandler(deps.Settings).Register(adminProtected) egresshttp.NewHandler(deps.Egress).Register(adminProtected) systemhttp.NewHandler(func() string { diff --git a/backend/internal/transport/http/settings/handler.go b/backend/internal/transport/http/settings/handler.go index 7f5c5db8..2b975ddc 100644 --- a/backend/internal/transport/http/settings/handler.go +++ b/backend/internal/transport/http/settings/handler.go @@ -46,8 +46,7 @@ type mediaConfigDTO struct { } type frontendConfigDTO struct { - PublicAPIBaseURL string `json:"publicApiBaseURL"` - PreferRequestBaseURL bool `json:"preferRequestBaseURL"` + PublicAPIBaseURL string `json:"publicApiBaseURL"` } type providerBuildConfigDTO struct { @@ -176,7 +175,7 @@ func (value settingsConfigDTO) toApplication() settingsapp.EditableConfig { CleanupThresholdPercent: value.Media.CleanupThresholdPercent, CleanupInterval: value.Media.CleanupInterval, }, Frontend: settingsapp.FrontendConfig{ - PublicAPIBaseURL: value.Frontend.PublicAPIBaseURL, PreferRequestBaseURL: value.Frontend.PreferRequestBaseURL, + PublicAPIBaseURL: value.Frontend.PublicAPIBaseURL, }, Routing: settingsapp.RoutingConfig{ StickyTTL: value.Routing.StickyTTL, CooldownBase: value.Routing.CooldownBase, @@ -223,7 +222,7 @@ func newSettingsResponse(value settingsapp.Snapshot) settingsResponse { CleanupThresholdPercent: config.Media.CleanupThresholdPercent, CleanupInterval: config.Media.CleanupInterval, }, Frontend: frontendConfigDTO{ - PublicAPIBaseURL: config.Frontend.PublicAPIBaseURL, PreferRequestBaseURL: config.Frontend.PreferRequestBaseURL, + PublicAPIBaseURL: config.Frontend.PublicAPIBaseURL, }, Routing: routingConfigDTO{ StickyTTL: config.Routing.StickyTTL, CooldownBase: config.Routing.CooldownBase, diff --git a/config.example.yaml b/config.example.yaml index 77be4c6d..6e11cf9a 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -29,10 +29,9 @@ bootstrapAdmin: password: "replace-with-a-strong-password" frontend: - # [按需修改] 生产环境可填外部 HTTPS 地址,例如 https://api.example.com;也可留空,由请求地址自动推导。 + # [按需修改] 管理端公共 API 地址留空时使用此值;本项也留空则回退到 http://127.0.0.1:8000。 + # 生产环境建议填写外部 HTTPS 地址,例如 https://api.example.com。 publicApiBaseURL: "http://127.0.0.1:8000" - # [按需修改] true 时优先使用客户端实际访问地址(含反向代理转发头);false 时固定使用上面的公共地址。 - preferRequestBaseURL: true # [通常不要修改] Go 服务同源托管的前端构建目录。 staticPath: "./frontend/dist" diff --git a/frontend/src/app/app-shell.tsx b/frontend/src/app/app-shell.tsx index ccc45865..c70c6853 100644 --- a/frontend/src/app/app-shell.tsx +++ b/frontend/src/app/app-shell.tsx @@ -24,6 +24,8 @@ const navigation = [ { href: "/accounts", label: "nav.accounts", icon: Users }, { href: "/client-keys", label: "nav.clientKeys", icon: KeyRound }, { href: "/models", label: "nav.models", icon: Box }, + { href: "/gallery", label: "nav.gallery", icon: Image }, + { href: "/video-gallery", label: "nav.videoGallery", icon: Video }, { href: "/request-audits", label: "nav.audits", icon: Eye }, ] as const; diff --git a/frontend/src/app/deferred-pages.tsx b/frontend/src/app/deferred-pages.tsx index 7ba12213..958f78c8 100644 --- a/frontend/src/app/deferred-pages.tsx +++ b/frontend/src/app/deferred-pages.tsx @@ -8,6 +8,8 @@ const RequestAuditsPage = lazyNamed(() => import("@/features/audits/request-audi const ClientKeysPage = lazyNamed(() => import("@/features/client-keys/client-keys-page"), "ClientKeysPage"); const DashboardPage = lazyNamed(() => import("@/features/dashboard/dashboard-page"), "DashboardPage"); const ApiDocsPage = lazyNamed(() => import("@/features/docs/api-docs-page"), "ApiDocsPage"); +const GalleryPage = lazyNamed(() => import("@/features/media/gallery-page"), "GalleryPage"); +const VideoGalleryPage = lazyNamed(() => import("@/features/media/video-gallery-page"), "VideoGalleryPage"); const ModelsPage = lazyNamed(() => import("@/features/models/models-page"), "ModelsPage"); const SettingsPage = lazyNamed(() => import("@/features/settings/settings-page"), "SettingsPage"); @@ -43,6 +45,14 @@ export function DeferredRequestAuditsPage() { return ; } +export function DeferredGalleryPage() { + return ; +} + +export function DeferredVideoGalleryPage() { + return ; +} + export function DeferredApiDocsPage() { return ; } diff --git a/frontend/src/app/router.tsx b/frontend/src/app/router.tsx index 68d04a67..ecbefca9 100644 --- a/frontend/src/app/router.tsx +++ b/frontend/src/app/router.tsx @@ -1,7 +1,7 @@ import { Navigate, createBrowserRouter } from "react-router-dom"; import { AnonymousBoundary, AuthBoundary } from "@/app/auth-boundary"; -import { DeferredAccountsPage, DeferredApiDocsPage, DeferredAppShell, DeferredClientKeysPage, DeferredDashboardPage, DeferredModelsPage, DeferredRequestAuditsPage, DeferredSettingsPage } from "@/app/deferred-pages"; +import { DeferredAccountsPage, DeferredApiDocsPage, DeferredAppShell, DeferredClientKeysPage, DeferredDashboardPage, DeferredGalleryPage, DeferredModelsPage, DeferredRequestAuditsPage, DeferredSettingsPage, DeferredVideoGalleryPage } from "@/app/deferred-pages"; import { LoginPage } from "@/features/auth/login-page"; export const router = createBrowserRouter([ @@ -20,6 +20,8 @@ export const router = createBrowserRouter([ { path: "/accounts", element: }, { path: "/models", element: }, { path: "/client-keys", element: }, + { path: "/gallery", element: }, + { path: "/video-gallery", element: }, { path: "/request-audits", element: }, { path: "/docs", element: }, { path: "/docs/:category/:endpoint", element: }, diff --git a/frontend/src/features/accounts/accounts-page.tsx b/frontend/src/features/accounts/accounts-page.tsx index 5261693e..cfe61bb8 100644 --- a/frontend/src/features/accounts/accounts-page.tsx +++ b/frontend/src/features/accounts/accounts-page.tsx @@ -1,13 +1,13 @@ import { zodResolver } from "@hookform/resolvers/zod"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { ArrowRight, ClipboardPaste, Compass, Copy, Download, ExternalLink, FileUp, Link2, MoreHorizontal, Pencil, RefreshCw, RotateCw, Search, SquareTerminal, Trash2, TriangleAlert, Webhook } from "lucide-react"; +import { ArrowRight, ClipboardPaste, Compass, Download, ExternalLink, FileUp, Link2, MoreHorizontal, Pencil, RefreshCw, RotateCw, Search, SquareTerminal, Trash2, TriangleAlert, Webhook } from "lucide-react"; import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"; import { useForm, useWatch } from "react-hook-form"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import { z } from "zod"; -import { copyToClipboard } from "@/shared/clipboard"; +import { CopyButton } from "@/shared/components/copy-button"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; @@ -778,15 +778,7 @@ export function AccountsPage() {
{deviceSession.userCode} - - - - - {t("common.copy")} - + toast.success(t("common.copied"))} />
+ ); +} + +function AttemptDetail({ attempt }: { attempt: AuditAttemptDTO }) { + const { t } = useTranslation(); + const headersText = JSON.stringify(attempt.responseHeaders, null, 2); + const errorChainText = JSON.stringify(attempt.errorChain, null, 2); + return ( +
+ + +
+ + {t("audits.overview")} + {t("audits.responseBody")} + {t("audits.responseHeaders")} + {t("audits.errorChain")} + +
+ + + + + + + + + + + + +
+
+ ); +} + +function DiagnosticBanner({ attempt }: { attempt: AuditAttemptDTO }) { + const { t } = useTranslation(); + const isHTTP = attempt.source === "upstream_http"; + const Icon = isHTTP ? Server : attempt.source === "gateway_transport" ? Network : KeyRound; + const title = isHTTP + ? t("audits.upstreamHttpFailure", { status: attempt.upstreamStatusCode ?? "-" }) + : attempt.source === "gateway_transport" ? t("audits.gatewayTransportFailure") : t("audits.credentialFailure"); + const description = isHTTP ? t("audits.upstreamResponseReceived") : t("audits.noUpstreamResponse"); + return ( +
+ +
+

{title}

+

{description}

+
+ {attempt.stage} +
+ ); +} + +function AttemptOverview({ attempt }: { attempt: AuditAttemptDTO }) { + const { t, i18n } = useTranslation(); + return ( +
+
+ + + + + + +
+ + {attempt.transportError ? : null} +
+ ); +} + +function InfoCard({ label, value, mono }: { label: string; value: string; mono?: boolean }) { + return ( +
+

{label}

+

{value}

+
+ ); +} + +function DetailField({ label, value, mono, copy }: { label: string; value: string; mono?: boolean; copy?: boolean }) { + return ( +
+
+ {label} + {copy ? : null} +
+

{value}

+
+ ); +} + +function CodePanel({ value, displayValue, emptyMessage, encoding, truncated }: { value: string; displayValue: string; emptyMessage: string; encoding: string; truncated: boolean }) { + const { t } = useTranslation(); + if (!value) return } message={emptyMessage} />; + return ( +
+
+ + {t("audits.bodyEncoding", { encoding })} + {truncated ? {t("audits.bodyTruncated")} : null} + + +
+
{displayValue}
+
+ ); +} + +function HeadersPanel({ headers, copyValue }: { headers: Record; copyValue: string }) { + const { t } = useTranslation(); + const entries = Object.entries(headers); + if (entries.length === 0) return } message={t("audits.emptyResponseHeaders")} />; + return ( +
+
+ {t("audits.headerCount", { count: entries.length })} + +
+
+ {entries.map(([name, values]) => ( +
+ {name} +
{values.map((value, index) => {value})}
+
+ ))} +
+
+ ); +} + +function ErrorChainPanel({ attempt, copyValue }: { attempt: AuditAttemptDTO; copyValue: string }) { + const { t } = useTranslation(); + if (attempt.errorChain.length === 0) return } message={t("audits.emptyErrorChain")} />; + return ( +
+
+ {t("audits.errorFrameCount", { count: attempt.errorChain.length })} + +
+
    + {attempt.errorChain.map((frame, index) => ( +
  1. +
    #{index + 1}{frame.type}
    +
    {frame.message}
    +
  2. + ))} +
+
+ ); +} + +function EmptyPanel({ icon, message }: { icon: ReactNode; message: string }) { + return
{icon}

{message}

; +} + +function formattedResponseBody(attempt: AuditAttemptDTO): string { + if (attempt.responseBodyEncoding !== "utf8") return attempt.responseBody; + const contentType = Object.entries(attempt.responseHeaders).find(([name]) => name.toLowerCase() === "content-type")?.[1].join(";") ?? ""; + if (!contentType.toLowerCase().includes("json")) return attempt.responseBody; + try { + return JSON.stringify(JSON.parse(attempt.responseBody), null, 2); + } catch { + return attempt.responseBody; + } +} + +function sourceLabel(attempt: AuditAttemptDTO, t: (key: string, options?: Record) => string): string { + if (attempt.source === "upstream_http") return t("audits.upstreamHttpFailure", { status: attempt.upstreamStatusCode ?? "-" }); + if (attempt.source === "gateway_transport") return t("audits.gatewayTransportFailure"); + return t("audits.credentialFailure"); +} + +function StatusBadge({ statusCode }: { statusCode: number }) { + const className = statusCode >= 500 + ? "bg-red-500/10 text-red-700 dark:text-red-300" + : statusCode >= 400 ? "bg-amber-500/10 text-amber-700 dark:text-amber-300" + : statusCode >= 200 && statusCode < 300 ? "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300" : "bg-muted text-muted-foreground"; + return {statusCode}; +} diff --git a/frontend/src/features/audits/request-audits-api.ts b/frontend/src/features/audits/request-audits-api.ts index abe02cbd..0de95535 100644 --- a/frontend/src/features/audits/request-audits-api.ts +++ b/frontend/src/features/audits/request-audits-api.ts @@ -1,5 +1,5 @@ import { apiRequest } from "@/shared/api/client"; -import { createObjectDecoder, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isString } from "@/shared/api/decoder"; +import { createObjectDecoder, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isRecordOf, isString } from "@/shared/api/decoder"; import type { PeriodValue } from "@/shared/lib/period"; import type { SortOrder } from "@/shared/lib/table-sort"; @@ -18,6 +18,10 @@ export type AuditDTO = { usageSource: "upstream" | "estimated" | "none"; accountId?: string; accountName?: string; + egressNodeId?: string; + egressNodeName?: string; + egressScope?: "grok_build" | "grok_web" | "grok_console" | "grok_web_asset"; + egressMode?: "direct" | "proxy"; statusCode: number; streaming: boolean; mediaInputImages: number; @@ -38,9 +42,37 @@ export type AuditDTO = { contextOutputTokens: number; durationMs: number; errorCode?: string; + attemptCount: number; createdAt: string; }; +export type AuditAttemptDTO = { + id: string; + number: number; + source: "upstream_http" | "gateway_transport" | "credential"; + stage: string; + accountId?: string; + accountName?: string; + method?: string; + requestPath?: string; + upstreamUrl?: string; + startedAt: string; + durationMs: number; + upstreamStatusCode?: number; + upstreamStatus?: string; + responseHeaders: Record; + responseBody: string; + responseBodyEncoding: "utf8" | "base64"; + responseBodyTruncated: boolean; + transportError?: string; + errorChain: Array<{ type: string; message: string }>; +}; + +export type AuditDetailDTO = { + audit: AuditDTO; + attempts: AuditAttemptDTO[]; +}; + export type AuditCursorPageDTO = { items: AuditDTO[]; pageSize: number; @@ -79,12 +111,22 @@ const auditValidator = hasShape({ id: isString, requestId: isString, clientKeyId: isString, clientKeyName: isOptional(isString), modelRouteId: isString, modelPublicId: isOptional(isString), modelUpstreamModel: isOptional(isString), provider: isOneOf("grok_build", "grok_web", "grok_console"), operation: isOneOf("responses", "chat", "messages", "image", "image_edit", "video"), usageSource: isOneOf("upstream", "estimated", "none"), - accountId: isOptional(isString), accountName: isOptional(isString), statusCode: isNumber, streaming: isBoolean, + 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")), + statusCode: isNumber, streaming: isBoolean, mediaInputImages: isNumber, mediaOutputImages: isNumber, mediaOutputSeconds: isNumber, inputTokens: isNumber, cachedInputTokens: isNumber, outputTokens: isNumber, reasoningTokens: isNumber, totalTokens: isNumber, costInUsdTicks: isNumber, estimatedCostInUsdTicks: isNumber, pricingModel: isOptional(isString), pricingVersion: isOptional(isString), numSourcesUsed: isNumber, numServerSideToolsUsed: isNumber, contextInputTokens: isNumber, contextOutputTokens: isNumber, - durationMs: isNumber, errorCode: isOptional(isString), createdAt: isString, + durationMs: isNumber, errorCode: isOptional(isString), attemptCount: isNumber, createdAt: isString, +}); +const auditAttemptValidator = hasShape({ + id: isString, number: isNumber, source: isOneOf("upstream_http", "gateway_transport", "credential"), stage: isString, + accountId: isOptional(isString), accountName: isOptional(isString), method: isOptional(isString), requestPath: isOptional(isString), upstreamUrl: isOptional(isString), + startedAt: isString, durationMs: isNumber, upstreamStatusCode: isOptional(isNumber), upstreamStatus: isOptional(isString), + responseHeaders: isRecordOf(isArrayOf(isString)), responseBody: isString, responseBodyEncoding: isOneOf("utf8", "base64"), responseBodyTruncated: isBoolean, + transportError: isOptional(isString), errorChain: isArrayOf(hasShape({ type: isString, message: isString })), }); const decodeAuditPage = createObjectDecoder("audit page", { items: isArrayOf(auditValidator), pageSize: isNumber, nextCursor: isString, hasMore: isBoolean, @@ -100,6 +142,10 @@ const decodeAuditSummary = createObjectDecoder("audit summary", source: isString, asOf: isString, pricedRequests: isNumber, unpricedRequests: isNumber, pricedTokens: isNumber, unpricedTokens: isNumber, }), }); +const decodeAuditDetail = createObjectDecoder("audit detail", { + audit: auditValidator, + attempts: isArrayOf(auditAttemptValidator), +}); type AuditQuery = { cursor?: string; @@ -142,3 +188,7 @@ export function getRequestAuditSummary(input: Omit { + return apiRequest(`/api/admin/v1/request-audits/${id}`, {}, decodeAuditDetail); +} diff --git a/frontend/src/features/audits/request-audits-page.tsx b/frontend/src/features/audits/request-audits-page.tsx index addb1572..97a5229b 100644 --- a/frontend/src/features/audits/request-audits-page.tsx +++ b/frontend/src/features/audits/request-audits-page.tsx @@ -7,9 +7,10 @@ import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Spinner } from "@/components/ui/spinner"; -import { Table, TableBody, TableCell, TableHeader, TableRow } from "@/components/ui/table"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { listModels } from "@/entities/model/model-api"; +import { RequestAuditDetailDialog } from "@/features/audits/request-audit-detail-dialog"; import { getRequestAudits, getRequestAuditSummary, type AuditDTO, type AuditPeriod } from "@/features/audits/request-audits-api"; import { EmptyState, ErrorState, TableLoadingRow } from "@/shared/components/data-state"; import { DataTableShell } from "@/shared/components/data-table-shell"; @@ -36,6 +37,7 @@ export function RequestAuditsPage() { const [periodDays, setPeriodDays] = useState(1); const [sort, setSort] = useState({ field: "createdAt", order: "desc" }); const [manualRefreshing, setManualRefreshing] = useState(false); + const [selectedAudit, setSelectedAudit] = useState(null); const forceSummaryRefresh = useRef(false); const debouncedSearch = useDebouncedValue(search); const debouncedKeyFilter = useDebouncedValue(keyFilter); @@ -153,21 +155,23 @@ export function RequestAuditsPage() { {auditsQuery.isError ? void auditsQuery.refetch()} /> : null} {result && result.items.length === 0 ? : null} {auditsQuery.isPending || (result && result.items.length > 0) ? ( - +
- - - - - + + + + - + + + {t("audits.request")} {t("audits.model")} + {t("audits.egress")} {t("audits.billing")} {t("audits.tokens")} {t("audits.status")} @@ -177,7 +181,7 @@ export function RequestAuditsPage() { - {auditsQuery.isPending ? : result?.items.map((audit) => ( + {auditsQuery.isPending ? : result?.items.map((audit) => ( {audit.requestId} @@ -190,9 +194,10 @@ export function RequestAuditsPage() { clientKey={audit.clientKeyName || `#${audit.clientKeyId}`} /> + - + setSelectedAudit(audit)} /> {audit.streaming ? "Stream" : "Non-Stream"} {formatNumber(audit.durationMs, i18n.language)} ms {formatDateTime(audit.createdAt, i18n.language)} @@ -202,10 +207,37 @@ export function RequestAuditsPage() {
) : null} + !open && setSelectedAudit(null)} /> ); } +function EgressValue({ audit }: { audit: AuditDTO }) { + const { t } = useTranslation(); + if (!audit.egressMode) { + return -; + } + const proxied = audit.egressMode === "proxy"; + const node = audit.egressNodeName || (proxied ? t("audits.egressUnknown") : t("audits.egressDirect")); + const details = [audit.egressScope, audit.egressNodeId ? `#${audit.egressNodeId}` : ""].filter(Boolean).join(" · "); + return ( + + + + + +
{node}
+ {details ?
{details}
: null} +
+
+ ); +} + function BillingValue({ audit }: { audit: AuditDTO }) { const { t } = useTranslation(); const upstreamReported = audit.costInUsdTicks > 0; @@ -350,17 +382,19 @@ function StatusBadge({ statusCode }: { statusCode: number }) { return {statusCode || "-"}; } -function AuditStatus({ statusCode, errorCode }: { statusCode: number; errorCode?: string }) { - if (!errorCode) return ; +function AuditStatus({ audit, onOpen }: { audit: AuditDTO; onOpen: () => void }) { + const { t } = useTranslation(); + if (!audit.errorCode && audit.attemptCount === 0) return ; return ( - - {errorCode} + {audit.errorCode || t("audits.openDiagnostics")} ); diff --git a/frontend/src/features/client-keys/client-keys-page.tsx b/frontend/src/features/client-keys/client-keys-page.tsx index 8b90f867..8032327b 100644 --- a/frontend/src/features/client-keys/client-keys-page.tsx +++ b/frontend/src/features/client-keys/client-keys-page.tsx @@ -7,7 +7,7 @@ import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import { z } from "zod"; -import { copyToClipboard } from "@/shared/clipboard"; +import { CopyButton } from "@/shared/components/copy-button"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog"; import { Badge } from "@/components/ui/badge"; @@ -36,6 +36,11 @@ import { nextTableSort, type SortOrder, type TableSort } from "@/shared/lib/tabl const USD_TICKS = 10_000_000_000; const MAX_BILLING_LIMIT_USD = 900_000; +type SecretDialogState = { + secret: string; + source: "created" | "retrieved"; +}; + export function ClientKeysPage() { const { t, i18n } = useTranslation(); const queryClient = useQueryClient(); @@ -49,7 +54,7 @@ export function ClientKeysPage() { const [batchDeleteOpen, setBatchDeleteOpen] = useState(false); const [editing, setEditing] = useState(null); const [deleting, setDeleting] = useState(null); - const [createdSecret, setCreatedSecret] = useState(null); + const [secretDialog, setSecretDialog] = useState(null); const [modelOptionsPage, setModelOptionsPage] = useState(1); const [modelOptionsSearch, setModelOptionsSearch] = useState(""); const [statusReferenceTime] = useState(() => Date.now()); @@ -104,7 +109,7 @@ export function ClientKeysPage() { onSuccess: (result) => { void queryClient.invalidateQueries({ queryKey: ["client-keys"] }); if ("secret" in result) { - setCreatedSecret(result.secret); + setSecretDialog({ secret: result.secret, source: "created" }); toast.success(t("keys.created")); } else { toast.success(t("keys.updated")); @@ -125,12 +130,8 @@ export function ClientKeysPage() { }); const copyMutation = useMutation({ - mutationFn: async (id: string) => { - const result = await getClientKeySecret(id); - await copyToClipboard(result.secret); - return id; - }, - onSuccess: () => toast.success(t("common.copied")), + mutationFn: getClientKeySecret, + onSuccess: (result) => setSecretDialog({ secret: result.secret, source: "retrieved" }), onError: showError, }); @@ -329,93 +330,85 @@ export function ClientKeysPage() { !open && setEditing(null)}> - - + + {editing === "new" ? t("keys.createTitle") : t("keys.editTitle")} {editing === "new" ? t("keys.description") : editing?.prefix} -
saveMutation.mutate(values))}> -
{form.formState.errors.name ?

{form.formState.errors.name.message}

: null}
-
form.setValue("enabled", checked)} />
-
-
-
-
-
-
- -
- {t("keys.unlimited")} - form.setValue("billingUnlimited", checked, { shouldDirty: true })} /> + saveMutation.mutate(values))}> +
+
{form.formState.errors.name ?

{form.formState.errors.name.message}

: null}
+
form.setValue("enabled", checked)} />
+
+
+
+
+
+
+ +
+ {t("keys.unlimited")} + form.setValue("billingUnlimited", checked, { shouldDirty: true })} /> +
-
-
- $ - -
-

{t("keys.billingLimitDescription")}

-
-
- - } /> -
-
-
- {t("keys.models")} - {selectedModels.length === 0 ? t("keys.allModels") : t("keys.selectedModels", { count: selectedModels.length })} -
-
-
- - { setModelOptionsSearch(event.target.value); setModelOptionsPage(1); }} placeholder={t("keys.modelSearch")} aria-label={t("keys.modelSearch")} /> +
+ $ +
-
- {modelsQuery.isPending ? : modelsQuery.data?.items.map((model) => { - const checked = selectedModels.includes(model.id); - const controlId = `allowed-model-${model.id}`; - return ( - - ); - })} - {modelsQuery.data?.items.length === 0 ?

{t("common.noData")}

: null} -
- {modelsQuery.data && modelsQuery.data.total > modelsQuery.data.pageSize ? : null} +

{t("keys.billingLimitDescription")}

-
- +
+ + } /> +
+
+
+ {t("keys.models")} + {selectedModels.length === 0 ? t("keys.allModels") : t("keys.selectedModels", { count: selectedModels.length })} +
+
+
+ + { setModelOptionsSearch(event.target.value); setModelOptionsPage(1); }} placeholder={t("keys.modelSearch")} aria-label={t("keys.modelSearch")} /> +
+
+ {modelsQuery.isPending ? : modelsQuery.data?.items.map((model) => { + const checked = selectedModels.includes(model.id); + const controlId = `allowed-model-${model.id}`; + return ( + + ); + })} + {modelsQuery.data?.items.length === 0 ?

{t("common.noData")}

: null} +
+ {modelsQuery.data && modelsQuery.data.total > modelsQuery.data.pageSize ? : null} +
+
+
+
- !open && setCreatedSecret(null)}> + !open && setSecretDialog(null)}> - {t("keys.secretTitle")} - {t("keys.secretDescription")} + {t(secretDialog?.source === "created" ? "keys.secretTitle" : "keys.copySecretTitle")} + {t(secretDialog?.source === "created" ? "keys.secretDescription" : "keys.copySecretDescription")}
- {createdSecret} - - - - - {t("keys.copySecret")} - + {secretDialog?.source === "created" ? secretDialog.secret : t("keys.secretReady")} + toast.success(t("common.copied"))} />
- +
diff --git a/frontend/src/features/docs/api-docs-page.tsx b/frontend/src/features/docs/api-docs-page.tsx index c7558c4c..b17e3891 100644 --- a/frontend/src/features/docs/api-docs-page.tsx +++ b/frontend/src/features/docs/api-docs-page.tsx @@ -1,17 +1,16 @@ import { useQuery } from "@tanstack/react-query"; -import { Braces, Check, Code2, Copy, Info, Link2 } from "lucide-react"; +import { Braces, Code2, Info, Link2 } from "lucide-react"; import { useState, type ReactNode } from "react"; import { Navigate, useParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { Button } from "@/components/ui/button"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { listModels } from "@/entities/model/model-api"; import type { ModelRouteDTO } from "@/entities/model/types"; import { getSystemInfo } from "@/entities/system/system-api"; import { runtimeConfig } from "@/shared/config/runtime-config"; -import { copyToClipboard } from "@/shared/clipboard"; +import { CopyButton } from "@/shared/components/copy-button"; import { cn } from "@/shared/lib/cn"; type ExampleLanguage = "curl" | "python" | "javascript"; @@ -362,13 +361,3 @@ function ExamplePanel({ ); } - -function CopyButton({ value, className }: { value: string; className?: string }) { - const { t } = useTranslation(); - const [copied, setCopied] = useState(false); - return ( - - ); -} diff --git a/frontend/src/features/media/gallery-page.tsx b/frontend/src/features/media/gallery-page.tsx new file mode 100644 index 00000000..99512c37 --- /dev/null +++ b/frontend/src/features/media/gallery-page.tsx @@ -0,0 +1,145 @@ +import { useQuery } from "@tanstack/react-query"; +import { Database, Image as ImageIcon, RefreshCw, Search, type LucideIcon } from "lucide-react"; +import { useState } from "react"; +import { useTranslation } from "react-i18next"; + +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Spinner } from "@/components/ui/spinner"; +import { getImageStats, listImages } from "@/features/media/media-api"; +import type { MediaAssetDTO } from "@/features/media/types"; +import { EmptyState, ErrorState, LoadingState } from "@/shared/components/data-state"; +import { PageHeader } from "@/shared/components/page-header"; +import { Pagination } from "@/shared/components/pagination"; +import { useDebouncedValue } from "@/shared/hooks/use-debounced-value"; +import { formatDateTime, formatNumber } from "@/shared/lib/format"; + +export function GalleryPage() { + const { t, i18n } = useTranslation(); + const [page, setPage] = useState(1); + const [pageSize, setPageSize] = useState(20); + const [search, setSearch] = useState(""); + const debouncedSearch = useDebouncedValue(search); + const normalizedSearch = debouncedSearch.trim(); + + const imagesQuery = useQuery({ + queryKey: ["media", "images", page, pageSize, normalizedSearch], + queryFn: () => listImages({ page, pageSize, search: normalizedSearch || undefined }), + }); + const statsQuery = useQuery({ + queryKey: ["media", "images", "stats"], + queryFn: getImageStats, + staleTime: 30_000, + }); + + const result = imagesQuery.data; + const refreshing = imagesQuery.isFetching || statsQuery.isFetching; + + function refreshAll(): void { + void imagesQuery.refetch(); + void statsQuery.refetch(); + } + + return ( +
+ + + {t("common.refresh")} + + )} + /> + +
+ + +
+ +
+
+
+ + { setSearch(event.target.value); setPage(1); }} + placeholder={t("media.images.search")} + aria-label={t("media.images.search")} + /> +
+ {result ? {t("media.images.pageSummary", { count: result.items.length, total: result.total })} : null} +
+ + {imagesQuery.isError ? void imagesQuery.refetch()} /> : null} + {imagesQuery.isPending ? : null} + {!imagesQuery.isPending && result && result.items.length === 0 ? : null} + + {!imagesQuery.isPending && result && result.items.length > 0 ? ( +
+ {result.items.map((image) => )} +
+ ) : null} + + {result && result.total > 0 ? ( + { setPageSize(value); setPage(1); }} + /> + ) : null} +
+
+ ); +} + +function ImageCard({ image, locale }: { image: MediaAssetDTO; locale: string }) { + const { t } = useTranslation(); + return ( + +
+ {image.id} +
+
+
+ {image.id} + {formatBytes(image.sizeBytes, locale)} +
+
+ {image.mimeType || image.kind} + {formatDateTime(image.createdAt, locale)} +
+
{t("media.images.sha256")}: {image.sha256}
+
+
+ ); +} + +function MediaMetric({ icon: Icon, label, value, detail, loading }: { icon: LucideIcon; label: string; value: string; detail: string; loading: boolean }) { + return ( +
+
+ {label} + +
+
{loading ? : value}
+

{detail}

+
+ ); +} + +function formatBytes(value: number, locale: string): string { + if (!Number.isFinite(value) || value <= 0) return "0 B"; + const units = ["B", "KB", "MB", "GB", "TB"]; + let size = value; + let unitIndex = 0; + while (size >= 1024 && unitIndex < units.length - 1) { + size /= 1024; + unitIndex += 1; + } + return `${new Intl.NumberFormat(locale, { maximumFractionDigits: unitIndex === 0 || size >= 10 ? 0 : 1 }).format(size)} ${units[unitIndex]}`; +} diff --git a/frontend/src/features/media/media-api.ts b/frontend/src/features/media/media-api.ts new file mode 100644 index 00000000..e09f2423 --- /dev/null +++ b/frontend/src/features/media/media-api.ts @@ -0,0 +1,89 @@ +import type { MediaAssetDTO, ImageStatsDTO, MediaJobDTO, VideoStatsDTO } from "@/features/media/types"; +import { apiRequest, type PaginatedDTO } from "@/shared/api/client"; +import { + createObjectDecoder, + createPaginatedDecoder, + hasShape, + isNumber, + isString, + isOneOf, +} from "@/shared/api/decoder"; +import type { SortOrder } from "@/shared/lib/table-sort"; + +export type ListImagesInput = { + page: number; + pageSize: number; + search?: string; +}; + +export type ListVideosInput = { + page: number; + pageSize: number; + status?: MediaJobDTO["status"] | ""; + search?: string; + sortBy?: string; + sortOrder?: SortOrder; +}; + +const mediaAssetShape = { + id: isString, + kind: isString, + mimeType: isString, + sizeBytes: isNumber, + sha256: isString, + createdAt: isString, + url: isString, +}; + +const mediaJobShape = { + id: isString, + model: isString, + prompt: isString, + status: isOneOf("queued", "in_progress", "completed", "failed"), + progress: isNumber, + seconds: isNumber, + size: isString, + quality: isString, + accountName: isString, + clientKeyName: isString, + createdAt: isString, + completedAt: (value: unknown) => value === null || isString(value), + errorMessage: isString, +}; + +const decodeImageStats = createObjectDecoder("image stats", { + totalImages: isNumber, + totalBytes: isNumber, +}); +const decodeVideoStats = createObjectDecoder("video stats", { + totalJobs: isNumber, + completed: isNumber, + failed: isNumber, + inProgress: isNumber, + queued: isNumber, +}); + +export function listImages(input: ListImagesInput): Promise> { + const query = new URLSearchParams({ page: String(input.page), pageSize: String(input.pageSize) }); + if (input.search) query.set("search", input.search); + return apiRequest(`/api/admin/v1/media/images?${query}`, {}, createPaginatedDecoder(hasShape(mediaAssetShape))); +} + +export function getImageStats(): Promise { + return apiRequest("/api/admin/v1/media/images/stats", {}, decodeImageStats); +} + +export function listVideos(input: ListVideosInput): Promise> { + const query = new URLSearchParams({ page: String(input.page), pageSize: String(input.pageSize) }); + if (input.status) query.set("status", input.status); + if (input.search) query.set("search", input.search); + if (input.sortBy && input.sortOrder) { + query.set("sortBy", input.sortBy); + query.set("sortOrder", input.sortOrder); + } + return apiRequest(`/api/admin/v1/media/videos?${query}`, {}, createPaginatedDecoder(hasShape(mediaJobShape))); +} + +export function getVideoStats(): Promise { + return apiRequest("/api/admin/v1/media/videos/stats", {}, decodeVideoStats); +} diff --git a/frontend/src/features/media/types.ts b/frontend/src/features/media/types.ts new file mode 100644 index 00000000..620f081c --- /dev/null +++ b/frontend/src/features/media/types.ts @@ -0,0 +1,28 @@ +export type MediaAssetDTO = { + id: string; + kind: string; + mimeType: string; + sizeBytes: number; + sha256: string; + createdAt: string; + url: string; +}; + +export type MediaJobDTO = { + id: string; + model: string; + prompt: string; + status: "queued" | "in_progress" | "completed" | "failed"; + progress: number; + seconds: number; + size: string; + quality: string; + accountName: string; + clientKeyName: string; + createdAt: string; + completedAt: string | null; + errorMessage: string; +}; + +export type ImageStatsDTO = { totalImages: number; totalBytes: number }; +export type VideoStatsDTO = { totalJobs: number; completed: number; failed: number; inProgress: number; queued: number }; diff --git a/frontend/src/features/media/video-gallery-page.tsx b/frontend/src/features/media/video-gallery-page.tsx new file mode 100644 index 00000000..7c565b7b --- /dev/null +++ b/frontend/src/features/media/video-gallery-page.tsx @@ -0,0 +1,231 @@ +import { useQuery } from "@tanstack/react-query"; +import { AlertCircle, CheckCircle2, Clock, ListVideo, Loader2, RefreshCw, Search, type LucideIcon } from "lucide-react"; +import { useState } from "react"; +import { useTranslation } from "react-i18next"; + +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Spinner } from "@/components/ui/spinner"; +import { Table, TableBody, TableCell, TableHeader, TableRow } from "@/components/ui/table"; +import { getVideoStats, listVideos } from "@/features/media/media-api"; +import type { MediaJobDTO } from "@/features/media/types"; +import { EmptyState, ErrorState, TableLoadingRow } from "@/shared/components/data-state"; +import { DataTableShell } from "@/shared/components/data-table-shell"; +import { PageHeader } from "@/shared/components/page-header"; +import { Pagination } from "@/shared/components/pagination"; +import { SortableTableHead } from "@/shared/components/sortable-table-head"; +import { useDebouncedValue } from "@/shared/hooks/use-debounced-value"; +import { cn } from "@/shared/lib/cn"; +import { formatDateTime, formatNumber } from "@/shared/lib/format"; +import { nextTableSort, type SortOrder, type TableSort } from "@/shared/lib/table-sort"; + +type VideoStatusFilter = MediaJobDTO["status"] | ""; + +const statusOptions: VideoStatusFilter[] = ["", "queued", "in_progress", "completed", "failed"]; + +export function VideoGalleryPage() { + const { t, i18n } = useTranslation(); + const [page, setPage] = useState(1); + const [pageSize, setPageSize] = useState(20); + const [search, setSearch] = useState(""); + const [statusFilter, setStatusFilter] = useState(""); + const [sort, setSort] = useState({ field: "createdAt", order: "desc" }); + const debouncedSearch = useDebouncedValue(search); + const normalizedSearch = debouncedSearch.trim(); + + const videosQuery = useQuery({ + queryKey: ["media", "videos", page, pageSize, statusFilter, normalizedSearch, sort.field, sort.order], + queryFn: () => listVideos({ page, pageSize, status: statusFilter, search: normalizedSearch || undefined, sortBy: sort.field, sortOrder: sort.order }), + }); + const statsQuery = useQuery({ + queryKey: ["media", "videos", "stats"], + queryFn: getVideoStats, + staleTime: 30_000, + }); + + const result = videosQuery.data; + const refreshing = videosQuery.isFetching || statsQuery.isFetching; + + function refreshAll(): void { + void videosQuery.refetch(); + void statsQuery.refetch(); + } + + function changeSort(field: string, initialOrder: SortOrder): void { + setSort((current) => nextTableSort(current, field, initialOrder)); + setPage(1); + } + + return ( +
+ + + {t("common.refresh")} + + )} + /> + +
+ + + + + +
+ + +
+
+ + { setSearch(event.target.value); setPage(1); }} + placeholder={t("media.videos.search")} + aria-label={t("media.videos.search")} + /> +
+ +
+ {result ? {t("media.videos.pageSummary", { count: result.items.length, total: result.total })} : null} + + )} + footer={result && result.total > 0 ? ( + { setPageSize(value); setPage(1); }} + /> + ) : undefined} + > + {videosQuery.isError ? void videosQuery.refetch()} /> : null} + {result && result.items.length === 0 ? : null} + {videosQuery.isPending || (result && result.items.length > 0) ? ( + + + + + + + + + + + + + + {t("media.videos.prompt")} + {t("media.videos.model")} + {t("media.videos.status")} + {t("media.videos.progress")} + {t("media.videos.spec")} + {t("media.videos.owner")} + {t("media.videos.createdAt")} + {t("media.videos.completedAt")} + + + + {videosQuery.isPending ? : result?.items.map((job) => ( + + +
+ {job.prompt || "-"} + {job.id} + {job.errorMessage ? {job.errorMessage} : null} +
+
+ {job.model || "-"} + + + +
+ {formatSpec(job)} + {t("media.videos.seconds", { count: job.seconds })} +
+
+ +
+ {job.accountName || "-"} + {job.clientKeyName || "-"} +
+
+ {formatDateTime(job.createdAt, i18n.language)} + {formatDateTime(job.completedAt, i18n.language)} +
+ ))} +
+
+ ) : null} +
+
+ ); +} + +function VideoMetric({ icon: Icon, label, value, loading }: { icon: LucideIcon; label: string; value: string; loading: boolean }) { + return ( +
+
+ {label} + +
+
{loading ? : value}
+
+ ); +} + +function VideoStatusBadge({ status }: { status: MediaJobDTO["status"] }) { + const { t } = useTranslation(); + return ( + + {t(`media.videoStatus.${status}`)} + + ); +} + +function ProgressValue({ value, locale }: { value: number; locale: string }) { + const normalized = Math.max(0, Math.min(100, value)); + return ( +
+ {formatNumber(normalized, locale, 0)}% + + + +
+ ); +} + +function statusClassName(status: MediaJobDTO["status"]): string { + switch (status) { + case "completed": + return "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"; + case "failed": + return "bg-red-500/10 text-red-700 dark:text-red-300"; + case "in_progress": + return "bg-sky-500/10 text-sky-700 dark:text-sky-300"; + case "queued": + return "bg-amber-500/10 text-amber-700 dark:text-amber-300"; + } +} + +function formatSpec(job: MediaJobDTO): string { + return [job.size, job.quality].filter(Boolean).join(" · ") || "-"; +} diff --git a/frontend/src/features/settings/egress-nodes.tsx b/frontend/src/features/settings/egress-nodes.tsx index 750f8926..0a0f37ff 100644 --- a/frontend/src/features/settings/egress-nodes.tsx +++ b/frontend/src/features/settings/egress-nodes.tsx @@ -15,6 +15,7 @@ import { Switch } from "@/components/ui/switch"; import { Table, TableActionCell, TableActionHead, TableBody, TableCell, TableHeader, TableRow } from "@/components/ui/table"; import { createEgressNode, deleteEgressNode, listEgressNodes, updateEgressNode, type EgressNodeDTO, type EgressNodeInput, type EgressScope } from "@/features/settings/settings-api"; import { SortableTableHead } from "@/shared/components/sortable-table-head"; +import { ErrorState } from "@/shared/components/data-state"; import { nextTableSort, type SortOrder, type TableSort } from "@/shared/lib/table-sort"; const emptyInput: EgressNodeInput = { name: "", scope: "grok_build", enabled: true, proxyURL: "", userAgent: "", cloudflareCookies: "" }; @@ -84,7 +85,7 @@ export function EgressNodes() {

{t("console.egressDescription")}

-
+ {query.isError ? void query.refetch()} /> :
{t("settings.egress.name")}{t("settings.egress.scope")}{t("settings.egress.proxy")}{t("settings.egress.clearance")}{t("settings.egress.health")} @@ -104,7 +105,7 @@ export function EgressNodes() { ))}
-
+
} { if (!open) setEditing(undefined); }}> diff --git a/frontend/src/features/settings/settings-api.ts b/frontend/src/features/settings/settings-api.ts index a9e5a201..d38d8722 100644 --- a/frontend/src/features/settings/settings-api.ts +++ b/frontend/src/features/settings/settings-api.ts @@ -16,7 +16,7 @@ export type SettingsConfigDTO = { maxImageBytes: number; maxTotalBytes: number; cleanupThresholdPercent: number; cleanupInterval: string; }; - frontend: { publicApiBaseURL: string; preferRequestBaseURL: boolean }; + frontend: { publicApiBaseURL: string }; routing: { stickyTTL: string; cooldownBase: string; cooldownMax: string; capacityWait: string; maxAttempts: number }; audit: { bufferSize: number; batchSize: number; flushInterval: string }; clientKeyDefaults: { rpmLimit: number; maxConcurrent: number }; @@ -53,7 +53,7 @@ const settingsConfigValidator = hasShape({ }), batch: hasShape({ importConcurrency: isNumber, conversionConcurrency: isNumber, syncConcurrency: isNumber, refreshConcurrency: isNumber, randomDelay: isString }), media: hasShape({ maxImageBytes: isNumber, maxTotalBytes: isNumber, cleanupThresholdPercent: isNumber, cleanupInterval: isString }), - frontend: hasShape({ publicApiBaseURL: isString, preferRequestBaseURL: isBoolean }), + frontend: hasShape({ publicApiBaseURL: isString }), routing: hasShape({ stickyTTL: isString, cooldownBase: isString, cooldownMax: isString, capacityWait: isString, maxAttempts: isNumber }), audit: hasShape({ bufferSize: isNumber, batchSize: isNumber, flushInterval: isString }), clientKeyDefaults: hasShape({ rpmLimit: isNumber, maxConcurrent: isNumber }), @@ -66,18 +66,18 @@ const decodeSettingsSnapshot = createObjectDecoder("setting restartRequired: isArrayOf(isString), }); const egressNodeValidator = hasShape({ - id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_web_asset"), enabled: isBoolean, + id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset"), enabled: isBoolean, proxyConfigured: isBoolean, userAgent: isString, cookieConfigured: isBoolean, health: isNumber, failureCount: isNumber, cooldownUntil: isOptional(isString), lastError: isOptional(isString), }); const decodeEgressNode = createObjectDecoder("egress node", { - id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_web_asset"), enabled: isBoolean, + id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset"), enabled: isBoolean, proxyConfigured: isBoolean, userAgent: isString, cookieConfigured: isBoolean, health: isNumber, failureCount: isNumber, cooldownUntil: isOptional(isString), lastError: isOptional(isString), }); const decodeEgressNodeList = createObjectDecoder("egress node list", { items: isArrayOf(egressNodeValidator), - defaultUserAgents: hasShape({ grok_build: isString, grok_web: isString, grok_web_asset: isString }), + defaultUserAgents: hasShape({ grok_build: isString, grok_web: isString, grok_console: isString, grok_web_asset: isString }), }); export function getSettings(): Promise { diff --git a/frontend/src/features/settings/settings-model.ts b/frontend/src/features/settings/settings-model.ts index 6a40a587..7cb2353f 100644 --- a/frontend/src/features/settings/settings-model.ts +++ b/frontend/src/features/settings/settings-model.ts @@ -22,7 +22,6 @@ const consoleChatDuration = durationSchema.refine((value) => { return seconds >= 5 && seconds <= 30 * 60; }); - function validPublicAPIBaseURL(value: string): boolean { const trimmed = value.trim(); if (trimmed.length === 0) return true; @@ -93,7 +92,6 @@ export const settingsSchema = z.object({ }).refine((value) => byteSizeBytes(value.maxTotalSize) >= byteSizeBytes(value.maxImageSize), { path: ["maxTotalSize"] }), frontend: z.object({ publicApiBaseURL: z.string().trim().max(2048).refine((value) => validPublicAPIBaseURL(value), { message: "invalid" }), - preferRequestBaseURL: z.boolean(), }), routing: z.object({ stickyTTL: routingTTLDuration, @@ -127,8 +125,7 @@ export function toSettingsForm(config: SettingsConfigDTO): SettingsForm { cleanupInterval: parseDuration(config.media.cleanupInterval), }, frontend: { - publicApiBaseURL: config.frontend?.publicApiBaseURL ?? "", - preferRequestBaseURL: config.frontend?.preferRequestBaseURL ?? true, + publicApiBaseURL: config.frontend.publicApiBaseURL, }, routing: { stickyTTL: parseDuration(config.routing.stickyTTL), cooldownBase: parseDuration(config.routing.cooldownBase), @@ -157,7 +154,6 @@ export function toSettingsDTO(config: SettingsForm): SettingsConfigDTO { }, frontend: { publicApiBaseURL: config.frontend.publicApiBaseURL.trim(), - preferRequestBaseURL: config.frontend.preferRequestBaseURL, }, routing: { stickyTTL: formatDuration(config.routing.stickyTTL), cooldownBase: formatDuration(config.routing.cooldownBase), diff --git a/frontend/src/features/settings/settings-page.tsx b/frontend/src/features/settings/settings-page.tsx index 5d0a6708..4cf4763d 100644 --- a/frontend/src/features/settings/settings-page.tsx +++ b/frontend/src/features/settings/settings-page.tsx @@ -155,9 +155,6 @@ export function SettingsPage() { - -
} /> -
diff --git a/frontend/src/features/settings/use-settings.ts b/frontend/src/features/settings/use-settings.ts index 58127226..edd99e56 100644 --- a/frontend/src/features/settings/use-settings.ts +++ b/frontend/src/features/settings/use-settings.ts @@ -17,6 +17,7 @@ export function useSettings() { mutationFn: (config: SettingsForm) => updateSettings(settingsQuery.data?.revision ?? "0", toSettingsDTO(config)), onSuccess: (snapshot) => { queryClient.setQueryData(["settings"], snapshot); + void queryClient.invalidateQueries({ queryKey: ["system-info"] }); form.reset(toSettingsForm(snapshot.config)); toast.success(t("settings.saved")); }, diff --git a/frontend/src/shared/clipboard.ts b/frontend/src/shared/clipboard.ts index a222ab05..89085c3a 100644 --- a/frontend/src/shared/clipboard.ts +++ b/frontend/src/shared/clipboard.ts @@ -1,13 +1,62 @@ -export async function copyToClipboard(text: string): Promise { +export async function copyToClipboard(text: string): Promise { if (navigator.clipboard?.writeText) { - return navigator.clipboard.writeText(text); + try { + await navigator.clipboard.writeText(text); + return true; + } catch { + // The async Clipboard API can reject in a non-secure context (plain + // HTTP on a LAN IP) or when the document is not focused. Fall through to + // the synchronous execCommand fallback so copying still works there. + } } + return legacyCopy(text); +} + +// execCommand("copy") is deprecated but remains the standard way to copy +// programmatically when the async Clipboard API is unavailable. +function legacyCopy(text: string): boolean { + if (typeof document === "undefined") return false; const textarea = document.createElement("textarea"); textarea.value = text; + textarea.setAttribute("readonly", ""); textarea.style.position = "fixed"; - textarea.style.opacity = "0"; + textarea.style.top = "0"; + textarea.style.left = "0"; + textarea.style.width = "1em"; + textarea.style.height = "1em"; + // A large font keeps iOS Safari from zooming the page and lets the + // selection persist on the programmatically created element. + textarea.style.fontSize = "2em"; + textarea.style.padding = "0"; + textarea.style.border = "none"; + textarea.style.outline = "none"; + textarea.style.boxShadow = "none"; + textarea.style.background = "transparent"; + + const activeElement = document.activeElement as Element | null; + const selection = document.getSelection(); + let savedRange: Range | null = null; + if (selection && selection.rangeCount > 0) savedRange = selection.getRangeAt(0); + document.body.appendChild(textarea); + textarea.focus(); textarea.select(); - document.execCommand("copy"); + textarea.setSelectionRange(0, text.length); + + let ok = false; + try { + ok = document.execCommand("copy"); + } catch { + // execCommand may throw in restricted environments; ok stays false. + } + document.body.removeChild(textarea); + if (savedRange && selection) { + selection.removeAllRanges(); + selection.addRange(savedRange); + } + if (activeElement instanceof HTMLElement && typeof activeElement.focus === "function") { + activeElement.focus(); + } + return ok; } diff --git a/frontend/src/shared/components/copy-button.tsx b/frontend/src/shared/components/copy-button.tsx new file mode 100644 index 00000000..7fa84978 --- /dev/null +++ b/frontend/src/shared/components/copy-button.tsx @@ -0,0 +1,63 @@ +import { Check, Copy } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; + +import { Button } from "@/components/ui/button"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { copyToClipboard } from "@/shared/clipboard"; +import { cn } from "@/shared/lib/cn"; + +export function CopyButton({ + value, + className, + disabled, + copyLabel, + onCopied, + onError, +}: { + value: string; + className?: string; + disabled?: boolean; + copyLabel?: string; + onCopied?: () => void; + onError?: (error: unknown) => void; +}) { + const { t } = useTranslation(); + const [copiedValue, setCopiedValue] = useState(null); + const resetTimerRef = useRef(null); + + useEffect(() => () => { + if (resetTimerRef.current !== null) window.clearTimeout(resetTimerRef.current); + }, []); + + async function handleClick() { + const ok = await copyToClipboard(value); + if (ok) { + if (resetTimerRef.current !== null) window.clearTimeout(resetTimerRef.current); + setCopiedValue(value); + resetTimerRef.current = window.setTimeout(() => { + setCopiedValue(null); + resetTimerRef.current = null; + }, 1500); + onCopied?.(); + } else { + const message = t("common.copyFailed"); + toast.error(message); + onError?.(new Error(message)); + } + } + + const copied = copiedValue === value; + const label = copied ? t("common.copied") : copyLabel ?? t("common.copy"); + return ( + + + + + {label} + + ); +} diff --git a/frontend/src/shared/components/data-state.tsx b/frontend/src/shared/components/data-state.tsx index 364eaf34..a1963cc6 100644 --- a/frontend/src/shared/components/data-state.tsx +++ b/frontend/src/shared/components/data-state.tsx @@ -40,7 +40,7 @@ export function ErrorState({ message, onRetry }: { message: string; onRetry: ()

{message}

- +
); } diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 79de01ba..fb7724c6 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -50,6 +50,7 @@ const resources = { close: "关闭", copy: "复制", copied: "已复制", + copyFailed: "复制失败", create: "创建", delete: "删除", disabled: "已停用", @@ -86,10 +87,55 @@ const resources = { accounts: "账号", models: "模型", clientKeys: "密钥", + gallery: "图库", + videoGallery: "视频库", audits: "请求审计", docs: "文档", settings: "设置", }, + media: { + images: { + title: "图库", + description: "浏览已生成的图片资源", + search: "搜索 ID、类型或哈希", + empty: "暂无图片", + noMatches: "未找到匹配的图片", + sha256: "SHA256", + totalImages: "图片总数", + totalImagesDetail: "已归档的图片数量", + totalBytes: "占用空间", + totalBytesDetail: "所有图片文件总大小", + pageSummary: "显示 {{count}} / {{total}} 张", + }, + videos: { + title: "视频库", + description: "查看视频生成任务记录", + search: "搜索提示词或 ID", + empty: "暂无视频任务", + statusFilter: "状态筛选", + totalJobs: "任务总数", + queued: "排队中", + inProgress: "进行中", + completed: "已完成", + failed: "失败", + prompt: "提示词", + model: "模型", + status: "状态", + progress: "进度", + spec: "规格", + owner: "归属", + createdAt: "创建时间", + completedAt: "完成时间", + seconds: "{{count}} 秒", + pageSummary: "显示 {{count}} / {{total}} 条", + }, + videoStatus: { + queued: "排队中", + in_progress: "进行中", + completed: "已完成", + failed: "失败", + }, + }, auth: { title: "管理员登录", productTitle: "轻量 API 网关", @@ -379,9 +425,12 @@ const resources = { createTitle: "创建密钥", editTitle: "编辑密钥", secretTitle: "密钥已创建", - secretDescription: "请妥善保管此密钥。列表中默认隐藏,后续可随时重新复制。", - secretLabel: "完整密钥", - copySecret: "复制完整密钥", + secretDescription: "请妥善保管。", + secretLabel: "密钥", + copySecret: "复制", + copySecretTitle: "复制密钥", + copySecretDescription: "点击下方按钮复制您的密钥", + secretReady: "已就绪", created: "密钥已创建", updated: "密钥已更新", deleted: "密钥已删除", @@ -392,8 +441,8 @@ const resources = { }, audits: { title: "请求审计", - description: "仅记录路由、状态、耗时和用量明细,不保存请求或响应正文。", - search: "搜索请求 ID 或模型", + description: "成功请求仅记录元数据;失败请求保留经过脱敏和裁剪的诊断快照。", + search: "搜索请求 ID、模型或出口节点", request: "请求 ID", route: "路由", status: "状态", @@ -410,6 +459,10 @@ const resources = { model: "模型", account: "账号", accountFilterPlaceholder: "输入账号名称或 ID", + egress: "出口", + egressProxy: "代理", + egressDirect: "直连", + egressUnknown: "未命名节点", owningAccount: "所属账号", owningKey: "所属密钥", routeDetails: "查看路由详情", @@ -438,6 +491,37 @@ const resources = { costUsd: "成本 ${{value}}", sources: "来源 {{count}}", serverTools: "调用服务端工具 {{count}} 次", + detailTitle: "请求诊断详情", + failedAttemptCount: "{{count}} 次失败", + attemptTimeline: "失败尝试", + noFailureAttempts: "该请求没有可用的失败尝试诊断。", + attemptNumber: "尝试 #{{number}}", + openDiagnostics: "查看安全诊断", + viewDetails: "查看详情", + overview: "概览", + responseBody: "响应 Body", + responseHeaders: "响应 Headers", + errorChain: "Error Chain", + upstreamHttpFailure: "上游 HTTP {{status}}", + gatewayTransportFailure: "网关 Transport 错误", + credentialFailure: "凭据处理错误", + upstreamResponseReceived: "已收到上游 HTTP 响应;下方仅保留经过脱敏和裁剪的诊断快照。", + noUpstreamResponse: "网关未收到上游 HTTP 响应;请根据阶段、目标地址与脱敏错误链排查。", + attemptStartedAt: "开始时间", + requestMethod: "请求方法", + requestPath: "请求路径", + upstreamStatus: "上游状态", + upstreamUrl: "上游 URL", + upstreamUrlUnavailable: "未生成或无法从错误中解析上游 URL", + transportError: "Transport Error", + attemptError: "错误详情", + emptyResponseBody: "上游未返回响应 Body。", + emptyResponseHeaders: "没有可用的响应 Headers。", + emptyErrorChain: "该次尝试没有 Error Chain。", + bodyEncoding: "内容编码:{{encoding}}", + bodyTruncated: "内容已裁剪至安全上限", + headerCount: "{{count}} 个 Header", + errorFrameCount: "{{count}} 层错误", }, settings: { title: "运行设置", @@ -450,7 +534,7 @@ const resources = { provider: { title: "Grok Build", baseURL: "上游地址", clientVersion: "客户端版本", clientIdentifier: "客户端标识", tokenAuth: "Token Auth", userAgent: "User-Agent", recommendedVersion: "推荐 {{version}}", syncRecommendedVersion: "同步推荐版本", recommendedVersionApplied: "已是推荐版本", syncRecommendedVersionDescription: "填入后端当前已完成兼容回归的版本和 User-Agent,保存后生效。" }, web: { title: "Grok Web", baseURL: "上游地址", statsigMode: "x-statsig 获取方式", statsigManual: "手动填写", statsigURL: "URL 获取", statsigValue: "x-statsig-id", statsigConfigured: "已配置", statsigKeepConfigured: "留空保持当前配置", statsigValuePlaceholder: "粘贴 x-statsig-id", statsigSignerURL: "签名服务 URL", quotaTimeout: "额度请求超时", chatTimeout: "聊天超时", imageTimeout: "图片超时", videoTimeout: "视频超时", mediaConcurrency: "媒体任务并发", recoveryBackoffBase: "额度恢复退避", recoveryBackoffMax: "额度恢复最大退避", allowNSFW: "允许 NSFW 图片" }, batch: { title: "批量任务", importConcurrency: "导入同步并发", conversionConcurrency: "账号转换并发", syncConcurrency: "数据同步并发", refreshConcurrency: "凭据刷新并发", randomDelay: "随机延迟上限(ms)" }, - media: { title: "媒体存储", maxImageSize: "单张图片上限", maxTotalSize: "媒体存储上限", cleanupThresholdPercent: "自动清理阈值", cleanupInterval: "容量检查间隔", sizeUnit: "存储单位", publicApiBaseURL: "公共 API 地址", publicApiBaseURLHelp: "用于生成图片公开 URL 与文档示例地址。可留空;留空时由请求地址自动推导。", preferRequestBaseURL: "请求地址优先", preferRequestBaseURLHelp: "开启后优先使用客户端实际访问地址(含反向代理转发头);关闭后固定使用上面配置的公共地址。" }, + media: { title: "媒体存储", maxImageSize: "单张图片上限", maxTotalSize: "媒体存储上限", cleanupThresholdPercent: "自动清理阈值", cleanupInterval: "容量检查间隔", sizeUnit: "存储单位", publicApiBaseURL: "公共 API 地址", publicApiBaseURLHelp: "用于生成图片公开 URL 与文档示例地址。留空时使用 config.yaml 配置;仍为空则使用 http://127.0.0.1:8000。" }, egress: { title: "出口代理", description: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源独立管理代理和健康状态。Build 沿用 Provider 的 User-Agent;Web 与 Console 节点单独管理浏览器 User-Agent 与 Cookie。代理地址和 Cloudflare Cookie 仅写入。", add: "添加节点", saved: "代理节点已保存", deleted: "代理节点已删除", name: "名称", scope: "作用域", proxy: "代理", clearance: "Clearance", health: "健康度", directFallback: "未配置节点时使用直连", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web(仅资源)", configured: "已配置", direct: "直连", none: "无", editTitle: "编辑代理节点", addTitle: "添加代理节点", dialogDescription: "Build 节点只配置代理并沿用 Provider 的 User-Agent;Web 与 Console 节点使用各自的浏览器 User-Agent 和 Cloudflare Cookie。", enabled: "启用", proxyURL: "代理地址", proxyProtocols: "支持 HTTP、HTTPS、SOCKS4、SOCKS4A、SOCKS5、SOCKS5H,可携带用户名和密码。", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "已配置,留空保持不变", operationFailed: "操作失败" }, routing: { title: "路由策略", stickyTTL: "会话粘性时长", cooldownBase: "基础冷却时间", cooldownMax: "最大冷却时间", capacityWait: "账号满载等待", maxAttempts: "最大尝试次数" }, audit: { title: "请求审计", bufferSize: "队列容量", batchSize: "批量写入数", flushInterval: "刷新间隔" }, @@ -504,7 +588,7 @@ const resources = { failoverBehavior: "请求前故障切换", failoverBehaviorDescription: "上游在返回有效响应前出现凭据失效、限流或可重试错误时,网关会刷新凭据或切换账号;SSE 开始后不跨账号拼接。", privacyBehavior: "审计最小化", - privacyBehaviorDescription: "仅保存路由、状态、耗时与 usage 元数据,不保存请求正文、响应正文、encrypted reasoning 内容或工具参数。", + privacyBehaviorDescription: "成功请求仅保存路由、状态、耗时与 usage 元数据;失败请求可保存经过脱敏和容量限制的诊断快照。请求正文、encrypted reasoning 内容和工具参数不会进入审计。", requestFields: "常用字段", fieldModel: "模型页中已启用且当前可用的公开模型 ID。", fieldInstructions: "可选系统级指令,按标准 Responses 字段原样转发。", @@ -701,16 +785,106 @@ const resources = { expiresAt: "Credential expires: {{time}}", expiryUnknown: "Credential expiry is unknown", }, - common: { actions: "Actions", cancel: "Cancel", close: "Close", copy: "Copy", copied: "Copied", create: "Create", delete: "Delete", disabled: "Disabled", disable: "Disable", edit: "Edit", enabled: "Enabled", enable: "Enable", loading: "Loading", importingProgress: "Importing, completed {{completed}} / {{total}}", syncingProgress: "Syncing initial data, completed {{completed}} / {{total}}", noData: "No data", pageOf: "Page {{page}}/{{pages}}", perPage: "Per page", rows: "rows", firstPage: "First page", lastPage: "Last page", previousPage: "Previous page", nextPage: "Next page", selectedCount: "{{count}} selected", selectPage: "Select this page", selectItem: "Select {{name}}", refresh: "Refresh", retry: "Retry", filter: "Filters", all: "All", clearFilters: "Clear filters", save: "Save", reset: "Reset", sortAscending: "Sort {{column}} ascending", sortDescending: "Sort {{column}} descending" }, - nav: { dashboard: "Dashboard", accounts: "Accounts", models: "Models", clientKeys: "Client keys", audits: "Request audits", docs: "Documentation", settings: "Settings" }, + common: { actions: "Actions", cancel: "Cancel", close: "Close", copy: "Copy", copied: "Copied", copyFailed: "Copy failed", create: "Create", delete: "Delete", disabled: "Disabled", disable: "Disable", edit: "Edit", enabled: "Enabled", enable: "Enable", loading: "Loading", importingProgress: "Importing, completed {{completed}} / {{total}}", syncingProgress: "Syncing initial data, completed {{completed}} / {{total}}", noData: "No data", pageOf: "Page {{page}}/{{pages}}", perPage: "Per page", rows: "rows", firstPage: "First page", lastPage: "Last page", previousPage: "Previous page", nextPage: "Next page", selectedCount: "{{count}} selected", selectPage: "Select this page", selectItem: "Select {{name}}", refresh: "Refresh", retry: "Retry", filter: "Filters", all: "All", clearFilters: "Clear filters", save: "Save", reset: "Reset", sortAscending: "Sort {{column}} ascending", sortDescending: "Sort {{column}} descending" }, + nav: { dashboard: "Dashboard", accounts: "Accounts", models: "Models", clientKeys: "Client keys", gallery: "Gallery", videoGallery: "Video Gallery", audits: "Request audits", docs: "Documentation", settings: "Settings" }, + media: { images: { title: "Gallery", description: "Browse generated image assets", search: "Search ID, type, or hash", empty: "No images", noMatches: "No matching images", sha256: "SHA256", totalImages: "Total images", totalImagesDetail: "Archived image count", totalBytes: "Storage", totalBytesDetail: "Total size of all image files", pageSummary: "Showing {{count}} / {{total}}" }, videos: { title: "Video Gallery", description: "View video generation job records", search: "Search prompt or ID", empty: "No video jobs", statusFilter: "Status filter", totalJobs: "Total jobs", queued: "Queued", inProgress: "In progress", completed: "Completed", failed: "Failed", prompt: "Prompt", model: "Model", status: "Status", progress: "Progress", spec: "Spec", owner: "Owner", createdAt: "Created", completedAt: "Completed", seconds: "{{count}} sec", pageSummary: "Showing {{count}} / {{total}}" }, videoStatus: { queued: "Queued", in_progress: "In progress", completed: "Completed", failed: "Failed" } }, auth: { title: "Admin sign in", productTitle: "Lightweight API gateway", subtitle: "Manage upstream accounts, model routes, and client access.", username: "Username", password: "Password", usernameRequired: "Enter your username", passwordRequired: "Enter your password", signIn: "Sign in", signingIn: "Signing in", signOut: "Sign out", changePassword: "Change password", currentPassword: "Current password", newPassword: "New password", passwordUpdated: "Password updated. Sign in again.", sessionUnavailable: "Unable to restore the session", sessionUnavailableDescription: "The service may be temporarily unavailable. Your session was not cleared; please retry shortly.", retrySession: "Retry" }, shell: { appearance: "Appearance", dark: "Dark", light: "Light", system: "System", language: "Language", navigation: "Navigation", openNavigation: "Open navigation" }, dashboard: { title: "Dashboard", subtitle: "Welcome, {{name}}", lastUpdated: "Updated {{time}}", welcome: "Welcome, {{name}}", gatewayOnline: "Gateway healthy", gatewayOffline: "Unavailable", gatewayReady: "The gateway is ready to process API requests.", gatewayNeedsAccount: "Connect an available account to process API requests.", manageAccounts: "Manage accounts", usage: "Usage overview", seeAll: "View audits", activeAccounts: "Available accounts", accountCapacity: "{{total}} accounts · {{rate}}% success", manage: "Manage", tokens: "Total tokens", requests: "Requests", successRate: "Success rate", availableSummary: "{{active}} / {{total}} available", requestBreakdown: "{{success}} succeeded · {{failed}} failed", requestQualitySummary: "{{success}}% success · {{failed}} failed", periodSummary: "Current {{period}} range", successSummary: "{{success}} / {{total}} requests succeeded", trend: "Usage trend", trendRequests: "Requests", trendTokens: "Tokens", resourcesTitle: "Resource status", qualityTitle: "Request quality", successfulRequests: "Successful requests", failedRequests: "Failed requests", topModels: "Top 10 models", model: "Model", share: "Call share", noTopModels: "No model calls in this period", billing: "Billing", billingSummary: "Accumulated in the current {{period}} range", inputTokens: "Input", cachedTokens: "Cached", outputTokens: "Output", reasoningTokens: "Reasoning", uncachedInput: "Uncached input", visibleOutput: "Visible output", otherModels: "Other models", tokenBreakdown: "Input {{input}} · Cached {{cached}} · Output {{output}} · Reasoning {{reasoning}}", tokenEfficiency: "Cache hit rate {{rate}}%", explore: "Manage resources", accountsProduct: "Upstream accounts", accountsProductDescription: "Manage OAuth credentials, health, quota, and concurrency.", keysProduct: "Client keys", keysProductDescription: "Create downstream API keys and control models, RPM, and concurrency.", modelsProduct: "Model routes", modelsProductDescription: "Manage public model IDs, upstream mappings, and availability.", auditsProduct: "Request audits", auditsProductDescription: "Inspect status, latency, and token usage records.", gatewayFooter: "A lightweight API gateway", learnMore: "View models", unknown: "Unknown" }, accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "The selected {{count}} accounts will use SSO to complete Device OAuth automatically. Linked accounts are skipped and conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens directly. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export all accounts", exported: "Account credentials exported", exportTitle: "Export all account credentials?", exportDescription: "The exported JSON contains OAuth credentials that can access the upstream service. Store it only in a trusted location and never upload, share, or commit it to version control.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamConfirmed: "Exhaustion confirmed by upstream", waitingReset: "Waiting reset", waitingResetUntil: "Waiting for reset · probe after {{time}} on real traffic", paidWaitingResetUntil: "Waiting for reset · check the upstream Billing period after {{time}}", probing: "Probing", probingQuota: "Checking quota recovery with real traffic", paidProbingQuota: "Checking whether the upstream Billing period has recovered", upstreamBilling: "Upstream billing data", deviceTitle: "Connect Grok Build", deviceDescription: "Complete authorization in a new window. This page will check status automatically.", userCode: "Device code", openVerification: "Open authorization", waiting: "Waiting for authorization", expiresAt: "Expires {{time}}", deleteTitle: "Delete account?", deleteDescription: "Credentials and quota snapshots will be removed. This cannot be undone.", batchUpdated: "Selected accounts updated", batchBillingRefreshed: "Quota sync complete: {{succeeded}} succeeded, {{failed}} failed", batchDeleteTitle: "Delete {{count}} selected accounts?" }, models: { title: "Model routes", description: "Map one client-facing model name to provider-specific Build, Web, and Console routes.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a custom Grok Build route. The public model name has no source prefix; the upstream model uses Build/ to identify its actual channel.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "When enabled, only selected accounts are routed and treated as manually confirmed to support the model. Otherwise model sync decides automatically.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" }, - keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", allModels: "All models", modelSearch: "Search models. Leave blank to allow all models.", selectedModels: "{{count}} models selected", neverExpires: "Never expires", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely. It is hidden by default in the list and can be copied again later.", secretLabel: "Complete key", copySecret: "Copy complete key", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" }, - audits: { title: "Request audits", description: "Stores routing, status, latency, and usage details only. Request and response bodies are never saved.", search: "Search request ID or model", request: "Request ID", route: "Route", status: "Status", mode: "Mode", tokens: "Details", billing: "Billing", duration: "Duration", createdAt: "Time", stream: "Streaming", nonStream: "Non-streaming", cursorPage: "Page {{page}}", key: "Key", keyFilterPlaceholder: "Enter key name or ID", model: "Model", account: "Account", accountFilterPlaceholder: "Enter account name or ID", owningAccount: "Account", owningKey: "Client key", routeDetails: "View routing details", statusSuccess: "Success", statusClientError: "Client error", statusServerError: "Server error", usageSummary: "Usage summary", totalRequests: "Total requests", requestBreakdown: "{{success}} succeeded · {{failed}} failed", totalTokens: "Total tokens", tokenEfficiency: "Cache hit rate {{cacheRate}}%", tokenBreakdown: "Input {{input}} · Output {{output}} · Cached {{cached}} · Reasoning {{reasoning}}", successRate: "Success rate", averageDuration: "Average duration {{duration}}", estimatedCost: "Estimated cost", pricingCoverage: "{{priced}} priced · {{unpriced}} unpriced", pricingDescription: "Calculated using the latest official xAI model prices. Models without a listed price are excluded.", total: "Total", input: "Input", output: "Output", mediaInput: "Media Input", imageCount: "{{count}} images", secondsCount: "{{count}} sec", cached: "Cached", reasoning: "Reasoning", costUsd: "Cost ${{value}}", sources: "Sources {{count}}", serverTools: "Server tools called {{count}} times" }, - settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies" }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", clientVersion: "Client version", clientIdentifier: "Client identifier", tokenAuth: "Token auth", userAgent: "User-Agent", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync recommended version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill in the backend version and User-Agent that passed compatibility regression; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", statsigMode: "x-statsig source", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", quotaTimeout: "Quota timeout", chatTimeout: "Chat timeout", imageTimeout: "Image timeout", videoTimeout: "Video timeout", mediaConcurrency: "Media job concurrency", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffMax: "Maximum recovery backoff", allowNSFW: "Allow NSFW images" }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", conversionConcurrency: "Account conversion concurrency", syncConcurrency: "Data sync concurrency", refreshConcurrency: "Credential refresh concurrency", randomDelay: "Maximum random delay (ms)" }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxTotalSize: "Media storage limit", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupInterval: "Capacity check interval", sizeUnit: "Storage unit", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs and docs examples. Leave empty to derive from the request.", preferRequestBaseURL: "Prefer request base URL", preferRequestBaseURLHelp: "When enabled, use the client request host/proto (including forwarded headers). When disabled, always use the configured public base URL if set." }, egress: { title: "Egress proxies", description: "Nodes manage proxy and health independently for Grok Build, Grok Web, or Web assets. Build inherits the Provider User-Agent; Web nodes manage their own browser User-Agent and cookies. Proxy URLs and Cloudflare cookies are write-only.", add: "Add node", saved: "Proxy node saved", deleted: "Proxy node deleted", name: "Name", scope: "Scope", proxy: "Proxy", clearance: "Clearance", health: "Health", directFallback: "Direct connection is used when no node is configured", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web (assets only)", configured: "Configured", direct: "Direct", none: "None", editTitle: "Edit proxy node", addTitle: "Add proxy node", dialogDescription: "Build nodes only configure the proxy and inherit the Provider User-Agent; Web nodes use their own browser User-Agent and Cloudflare cookies.", enabled: "Enabled", proxyURL: "Proxy URL", proxyProtocols: "Supports HTTP, HTTPS, SOCKS4, SOCKS4A, SOCKS5, and SOCKS5H with optional username and password.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed" }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", cooldownBase: "Base cooldown", cooldownMax: "Maximum cooldown", maxAttempts: "Maximum attempts" }, audit: { title: "Request audit", bufferSize: "Queue capacity", batchSize: "Batch size", flushInterval: "Flush interval" }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", maxConcurrent: "Default concurrency" }, units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" } }, + keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", allModels: "All models", modelSearch: "Search models. Leave blank to allow all models.", selectedModels: "{{count}} models selected", neverExpires: "Never expires", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" }, + audits: { + title: "Request audits", + description: "Successful requests store metadata only. Failed requests retain a redacted and size-limited diagnostic snapshot.", + search: "Search request ID, model, or egress node", + request: "Request ID", + route: "Route", + status: "Status", + mode: "Mode", + tokens: "Details", + billing: "Billing", + duration: "Duration", + createdAt: "Time", + stream: "Streaming", + nonStream: "Non-streaming", + cursorPage: "Page {{page}}", + key: "Key", + keyFilterPlaceholder: "Enter key name or ID", + model: "Model", + account: "Account", + accountFilterPlaceholder: "Enter account name or ID", + egress: "Egress", + egressProxy: "Proxy", + egressDirect: "Direct", + egressUnknown: "Unnamed node", + owningAccount: "Account", + owningKey: "Client key", + routeDetails: "View routing details", + statusSuccess: "Success", + statusClientError: "Client error", + statusServerError: "Server error", + usageSummary: "Usage summary", + totalRequests: "Total requests", + requestBreakdown: "{{success}} succeeded · {{failed}} failed", + totalTokens: "Total tokens", + tokenEfficiency: "Cache hit rate {{cacheRate}}%", + tokenBreakdown: "Input {{input}} · Output {{output}} · Cached {{cached}} · Reasoning {{reasoning}}", + successRate: "Success rate", + averageDuration: "Average duration {{duration}}", + estimatedCost: "Estimated cost", + pricingCoverage: "{{priced}} priced · {{unpriced}} unpriced", + pricingDescription: "Calculated using the latest official xAI model prices. Models without a listed price are excluded.", + total: "Total", + input: "Input", + output: "Output", + mediaInput: "Media Input", + imageCount: "{{count}} images", + secondsCount: "{{count}} sec", + cached: "Cached", + reasoning: "Reasoning", + costUsd: "Cost ${{value}}", + sources: "Sources {{count}}", + serverTools: "Server tools called {{count}} times", + detailTitle: "Request diagnostics", + failedAttemptCount: "{{count}} failed", + failedAttemptCount_one: "{{count}} failed attempt", + failedAttemptCount_other: "{{count}} failed attempts", + attemptTimeline: "Failed attempts", + noFailureAttempts: "No failed-attempt diagnostics are available for this request.", + attemptNumber: "Attempt #{{number}}", + openDiagnostics: "View safe diagnostics", + viewDetails: "View details", + overview: "Overview", + responseBody: "Response body", + responseHeaders: "Response headers", + errorChain: "Error chain", + upstreamHttpFailure: "Upstream HTTP {{status}}", + gatewayTransportFailure: "Gateway transport error", + credentialFailure: "Credential processing error", + upstreamResponseReceived: "An upstream HTTP response was received. Only a redacted and size-limited diagnostic snapshot is retained below.", + noUpstreamResponse: "The gateway did not receive an upstream HTTP response. Use the stage, target, and redacted error chain to diagnose it.", + attemptStartedAt: "Started at", + requestMethod: "Method", + requestPath: "Request path", + upstreamStatus: "Upstream status", + upstreamUrl: "Upstream URL", + upstreamUrlUnavailable: "No upstream URL was generated or parsed from the error", + transportError: "Transport error", + attemptError: "Error details", + emptyResponseBody: "The upstream returned no response body.", + emptyResponseHeaders: "No response headers are available.", + emptyErrorChain: "This attempt has no error chain.", + bodyEncoding: "Content encoding: {{encoding}}", + bodyTruncated: "Content truncated at the safety limit", + headerCount: "{{count}} headers", + headerCount_one: "{{count}} header", + headerCount_other: "{{count}} headers", + errorFrameCount: "{{count}} error frames", + errorFrameCount_one: "{{count}} error frame", + errorFrameCount_other: "{{count}} error frames", + }, + settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies" }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", clientVersion: "Client version", clientIdentifier: "Client identifier", tokenAuth: "Token auth", userAgent: "User-Agent", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync recommended version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill in the backend version and User-Agent that passed compatibility regression; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", statsigMode: "x-statsig source", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", quotaTimeout: "Quota timeout", chatTimeout: "Chat timeout", imageTimeout: "Image timeout", videoTimeout: "Video timeout", mediaConcurrency: "Media job concurrency", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffMax: "Maximum recovery backoff", allowNSFW: "Allow NSFW images" }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", conversionConcurrency: "Account conversion concurrency", syncConcurrency: "Data sync concurrency", refreshConcurrency: "Credential refresh concurrency", randomDelay: "Maximum random delay (ms)" }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxTotalSize: "Media storage limit", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupInterval: "Capacity check interval", sizeUnit: "Storage unit", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs and docs examples. Leave empty to use config.yaml; if that is also empty, http://127.0.0.1:8000 is used." }, egress: { title: "Egress proxies", description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, or Web assets. Build inherits the Provider User-Agent; Web and Console nodes manage their own browser User-Agent and cookies. Proxy URLs and Cloudflare cookies are write-only.", add: "Add node", saved: "Proxy node saved", deleted: "Proxy node deleted", name: "Name", scope: "Scope", proxy: "Proxy", clearance: "Clearance", health: "Health", directFallback: "Direct connection is used when no node is configured", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web (assets only)", configured: "Configured", direct: "Direct", none: "None", editTitle: "Edit proxy node", addTitle: "Add proxy node", dialogDescription: "Build nodes only configure the proxy and inherit the Provider User-Agent; Web and Console nodes use their own browser User-Agent and Cloudflare cookies.", enabled: "Enabled", proxyURL: "Proxy URL", proxyProtocols: "Supports HTTP, HTTPS, SOCKS4, SOCKS4A, SOCKS5, and SOCKS5H with optional username and password.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed" }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", cooldownBase: "Base cooldown", cooldownMax: "Maximum cooldown", maxAttempts: "Maximum attempts" }, audit: { title: "Request audit", bufferSize: "Queue capacity", batchSize: "Batch size", flushInterval: "Flush interval" }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", maxConcurrent: "Default concurrency" }, units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" } }, docs: { title: "API documentation", description: "OpenAI Responses compatibility, account routing, and conversation-state behavior for this gateway.", @@ -758,7 +932,7 @@ const resources = { failoverBehavior: "Pre-response failover", failoverBehaviorDescription: "Before a usable response is returned, credential expiry, rate limits, and retryable upstream errors can trigger credential refresh or account failover. SSE streams are never spliced across accounts.", privacyBehavior: "Minimal auditing", - privacyBehaviorDescription: "Only routing, status, latency, and usage metadata are stored. Request bodies, response bodies, encrypted reasoning content, and tool arguments are not stored.", + privacyBehaviorDescription: "Successful requests store routing, status, latency, and usage metadata only. Failed requests may retain redacted, size-limited diagnostics. Request bodies, encrypted reasoning content, and tool arguments are never audited.", requestFields: "Common fields", fieldModel: "A public model ID that is enabled and currently available on the Models page.", fieldInstructions: "Optional system-level instructions forwarded as a standard Responses field.",