From be6aa130d24d1289cc3838977a80dab866c17517 Mon Sep 17 00:00:00 2001 From: Zyy Date: Wed, 25 Nov 2026 16:03:37 +0800 Subject: [PATCH] feat(gateway): integrate Antigravity and reorganize architecture Preserve main quota, Guardian, and WebSocket fixes alongside the new provider and module organization. Co-authored-by: Codex --- .agents/skills/cpr-dev-guide/SKILL.md | 9 +- .../cpr-dev-guide/references/frontend.md | 2 + backend/Cargo.lock | 38 + backend/Cargo.toml | 1 + backend/apps/gateway/Cargo.toml | 1 + backend/apps/gateway/src/bootstrap/mod.rs | 2 + backend/apps/gateway/src/bootstrap/server.rs | 3 +- backend/apps/gateway/src/bootstrap/startup.rs | 22 +- backend/apps/gateway/tests/architecture.rs | 156 +- backend/crates/gateway-admin/src/bootstrap.rs | 10 +- .../gateway-admin/src/model/accounts.rs | 4 + .../gateway-admin/src/model/backup/mod.rs | 2 + backend/crates/gateway-admin/src/model/mod.rs | 1 - .../crates/gateway-admin/src/model/pricing.rs | 1 + .../src/model/provider_credentials.rs | 4 +- .../src/model/quota_forecast/mod.rs | 14 + .../projection.rs} | 6 +- .../sampling.rs} | 2 +- .../gateway-admin/src/model/settings.rs | 6 +- .../crates/gateway-admin/src/ports/pricing.rs | 88 +- .../gateway-admin/src/ports/provider.rs | 66 +- .../crates/gateway-admin/src/ports/store.rs | 2 +- .../src/use_case/accounts/mod.rs | 93 +- .../gateway-admin/src/use_case/backup.rs | 14 +- .../gateway-admin/src/use_case/client_keys.rs | 21 +- .../crates/gateway-admin/src/use_case/mod.rs | 1 - .../src/use_case/observability/billing.rs | 145 ++ .../src/use_case/observability/dashboard.rs | 295 +++ .../src/use_case/observability/export/mod.rs | 3 +- .../src/use_case/observability/insights.rs | 393 +++ .../src/use_case/observability/metrics.rs | 13 + .../src/use_case/observability/mod.rs | 1439 +---------- .../src/use_case/observability/service.rs | 610 +++++ .../src/use_case/peer_link/projection.rs | 72 +- .../gateway-admin/src/use_case/settings.rs | 75 +- .../gateway-admin/src/use_case/system/mod.rs | 8 + .../preflight.rs} | 2 +- .../use_case/{system.rs => system/service.rs} | 2 +- .../gateway-admin/tests/backup/support.rs | 11 + .../crates/gateway-admin/tests/backup/task.rs | 1 + .../tests/model/backup/contract.rs | 121 + .../gateway-admin/tests/model/backup/mod.rs | 119 +- .../crates/gateway-admin/tests/model/mod.rs | 1 - .../tests/model/plugins/contract.rs | 93 + .../gateway-admin/tests/model/plugins/mod.rs | 91 +- .../tests/model/quota_forecast/mod.rs | 4 + .../projection.rs} | 2 +- .../sampling.rs} | 2 +- .../tests/use_case/accounts/mod.rs | 97 +- .../gateway-admin/tests/use_case/backup.rs | 33 +- .../tests/use_case/client_keys.rs | 29 + .../tests/use_case/freeze_recovery.rs | 4 +- .../gateway-admin/tests/use_case/mod.rs | 37 +- .../tests/use_case/observability/dashboard.rs | 571 +++++ .../tests/use_case/observability/insights.rs | 49 + .../tests/use_case/observability/mod.rs | 1382 +--------- .../tests/use_case/observability/service.rs | 407 +++ .../use_case/observability/store_cache.rs | 363 +++ .../gateway-admin/tests/use_case/settings.rs | 138 +- .../tests/use_case/system/mod.rs | 4 + .../preflight.rs} | 18 +- .../use_case/{system.rs => system/service.rs} | 9 +- .../tests/use_case/usage_data/contract.rs | 108 + .../tests/use_case/usage_data/mod.rs | 102 +- .../gateway-api/src/admin/account_groups.rs | 2 +- .../src/admin/accounts/concurrency.rs | 2 +- .../src/admin/accounts/handlers.rs | 2 +- .../src/admin/accounts/import_tasks.rs | 2 +- .../src/admin/accounts/presenter.rs | 2 +- .../gateway-api/src/admin/accounts/wire.rs | 8 + backend/crates/gateway-api/src/admin/auth.rs | 4 +- .../crates/gateway-api/src/admin/backups.rs | 35 +- .../gateway-api/src/admin/client_key_usage.rs | 2 +- .../gateway-api/src/admin/client_keys.rs | 8 +- backend/crates/gateway-api/src/admin/mod.rs | 2 +- .../src/admin/observability/export/mod.rs | 2 +- .../src/admin/observability/routes.rs | 2 +- .../src/admin/plugins/artifacts.rs | 2 +- .../src/admin/plugins/distribution.rs | 2 +- .../src/admin/plugins/instances.rs | 2 +- .../src/admin/plugins/management.rs | 12 +- .../gateway-api/src/admin/plugins/mod.rs | 3 +- .../crates/gateway-api/src/admin/proxies.rs | 2 +- .../crates/gateway-api/src/admin/settings.rs | 23 +- .../crates/gateway-api/src/admin/system.rs | 2 +- backend/crates/gateway-api/src/auth.rs | 38 +- .../src/{openai => data_plane}/auth.rs | 6 +- .../responses/error.rs => data_plane/body.rs} | 108 +- .../chat_completions/delivery.rs | 2 +- .../chat_completions/http.rs | 13 +- .../chat_completions/mod.rs | 0 .../chat_completions/request.rs | 10 +- .../chat_completions/response.rs | 14 +- .../src/{openai => data_plane}/error.rs | 0 .../gateway-api/src/data_plane/genai/error.rs | 71 + .../gateway-api/src/data_plane/genai/mod.rs | 230 ++ .../src/data_plane/genai/models.rs | 206 ++ .../{openai => data_plane}/generation/http.rs | 99 +- .../generation}/keepalive.rs | 8 +- .../src/data_plane/generation/mod.rs | 97 + .../generation/request.rs | 16 +- .../generation/response.rs | 105 +- .../generation/validation.rs | 86 +- .../src/{openai => data_plane}/images/http.rs | 13 +- .../src/{openai => data_plane}/images/mod.rs | 0 .../{openai => data_plane}/images/request.rs | 0 .../src/{openai => data_plane}/live/http.rs | 10 +- .../src/{openai => data_plane}/live/mod.rs | 2 +- .../{openai => data_plane}/live/websocket.rs | 4 +- .../src/{openai => data_plane}/messages.rs | 19 +- .../{openai => data_plane}/middleware/http.rs | 4 +- .../{openai => data_plane}/middleware/mod.rs | 0 .../middleware/request.rs | 2 +- .../middleware/session.rs | 0 .../src/{openai => data_plane}/mod.rs | 9 +- .../src/{openai => data_plane}/models.rs | 10 +- .../openai_endpoints.rs} | 54 +- .../{openai => data_plane}/peer_link/mod.rs | 9 +- .../{openai => data_plane}/peer_link/wire.rs | 0 .../provider_endpoints.rs} | 8 +- .../src/data_plane/responses/error.rs | 33 + .../{openai => data_plane}/responses/http.rs | 8 +- .../{openai => data_plane}/responses/mod.rs | 16 +- .../responses/request.rs | 92 +- .../responses/response.rs | 2 +- .../responses/validation.rs | 30 +- .../responses/websocket/connection/frame.rs | 0 .../responses/websocket/connection/handle.rs | 0 .../websocket/connection/middleware.rs | 0 .../responses/websocket/connection/mod.rs | 0 .../responses/websocket/connection/pump.rs | 0 .../responses/websocket/connection/state.rs | 0 .../websocket/connection/transport.rs | 0 .../responses/websocket/forward.rs | 11 +- .../responses/websocket/interrupt.rs | 0 .../responses/websocket/mod.rs | 25 +- .../responses/websocket/protocol.rs | 6 +- .../src/{openai => data_plane}/router.rs | 60 +- .../src/{openai => data_plane}/search/http.rs | 13 +- .../src/{openai => data_plane}/search/mod.rs | 0 .../src/{openai => data_plane}/service.rs | 50 +- .../src/{openai => data_plane}/usage.rs | 9 +- backend/crates/gateway-api/src/diagnostics.rs | 26 +- .../crates/gateway-api/src/key_usage/mod.rs | 12 +- backend/crates/gateway-api/src/lib.rs | 24 +- .../gateway-api/src/openai/generation/mod.rs | 82 - .../{session_cookie.rs => session/cookie.rs} | 0 backend/crates/gateway-api/src/session/mod.rs | 7 + .../crates/gateway-api/src/session/state.rs | 8 + .../tests/admin/accounts/handlers.rs | 26 +- .../gateway-api/tests/admin/client_keys.rs | 30 +- .../gateway-api/tests/admin/compression.rs | 2 +- .../tests/admin/error_diagnostics.rs | 2 +- .../crates/gateway-api/tests/admin/errors.rs | 4 +- backend/crates/gateway-api/tests/admin/mod.rs | 20 +- .../admin/observability/export/contract.rs | 393 +++ .../tests/admin/observability/export/mod.rs | 391 +-- .../tests/admin/plugins/management.rs | 43 +- .../gateway-api/tests/admin/settings.rs | 63 +- .../crates/gateway-api/tests/admin/system.rs | 2 +- .../tests/{openai => data_plane}/auth.rs | 2 +- .../chat_completions/http.rs | 6 +- .../chat_completions/mod.rs | 0 .../chat_completions/request.rs | 0 .../chat_completions/response.rs | 0 .../tests/{openai => data_plane}/error.rs | 10 +- .../tests/data_plane/genai/contract.rs | 340 +++ .../gateway-api/tests/data_plane/genai/mod.rs | 128 + .../tests/data_plane/genai/models.rs | 125 + .../group_permissions.rs | 0 .../{openai => data_plane}/images/mod.rs | 4 +- .../{openai => data_plane}/images/request.rs | 2 +- .../tests/{openai => data_plane}/live/mod.rs | 0 .../{openai => data_plane}/live/websocket.rs | 2 +- .../tests/{openai => data_plane}/messages.rs | 0 .../middleware/fixture.rs} | 34 +- .../tests/data_plane/middleware/mod.rs | 5 + .../tests/{openai => data_plane}/mod.rs | 11 +- .../tests/{openai => data_plane}/models.rs | 8 +- .../openai_endpoints.rs} | 0 .../peer_link/catalog.rs | 0 .../{openai => data_plane}/peer_link/mod.rs | 0 .../provider_endpoints.rs} | 16 +- .../{openai => data_plane}/responses/http.rs | 56 +- .../{openai => data_plane}/responses/mod.rs | 9 +- .../responses/request.rs | 3 +- .../websocket/connection/middleware.rs | 16 +- .../responses/websocket/connection/mod.rs | 8 +- .../websocket/connection/transport.rs | 0 .../responses/websocket/forward.rs | 2 +- .../responses/websocket/interrupt.rs | 2 +- .../responses/websocket/mod.rs | 8 +- .../responses/websocket/protocol.rs | 4 +- .../tests/{openai => data_plane}/router.rs | 0 .../tests/data_plane/search/http.rs | 142 ++ .../{openai => data_plane}/search/mod.rs | 144 +- .../tests/{openai => data_plane}/usage.rs | 4 +- .../crates/gateway-api/tests/diagnostics.rs | 2 +- backend/crates/gateway-api/tests/health.rs | 8 +- .../crates/gateway-api/tests/key_usage/mod.rs | 24 +- backend/crates/gateway-api/tests/main.rs | 5 +- .../gateway-api/tests/middleware/mod.rs | 8 +- .../crates/gateway-api/tests/support/mod.rs | 2 +- .../gateway-core/src/account/selection.rs | 26 +- .../gateway-core/src/engine/coordinator.rs | 4 +- .../src/engine/execution/service.rs | 2 +- .../gateway-core/src/engine/provider.rs | 20 +- backend/crates/gateway-core/src/operation.rs | 68 +- .../gateway-core/src/provider_ports/mod.rs | 2 + .../src/provider_ports/session_affinity.rs | 97 + .../crates/gateway-core/src/routing/mod.rs | 39 + .../gateway-core/src/routing/snapshot.rs | 56 +- .../gateway-core/src/settings/compiled.rs | 8 +- .../gateway-core/src/settings/values.rs | 18 +- .../gateway-core/tests/engine/coordinator.rs | 19 +- .../tests/engine/execution/mod.rs | 100 + .../gateway-core/tests/error/contract.rs | 261 ++ .../gateway-core/tests/error/details.rs | 79 + .../crates/gateway-core/tests/error/mod.rs | 377 +-- .../crates/gateway-core/tests/error/source.rs | 43 + .../crates/gateway-core/tests/operation.rs | 21 + .../tests/policy/client_version.rs | 67 + .../gateway-core/tests/policy/contract.rs | 66 + .../crates/gateway-core/tests/policy/mod.rs | 129 +- .../tests/provider_ports/affinity.rs | 10 + .../tests/provider_ports/lease.rs | 33 + .../gateway-core/tests/provider_ports/mod.rs | 301 +-- .../tests/provider_ports/oauth.rs | 30 + .../tests/provider_ports/refresh.rs | 147 ++ .../tests/provider_ports/runtime_policy.rs | 88 + .../tests/provider_ports/session_affinity.rs | 159 ++ .../crates/gateway-core/tests/routing/mod.rs | 140 ++ .../tests/routing/request_settings.rs | 12 +- backend/crates/gateway-host/src/pricing.rs | 38 +- .../gateway-host/src/system_update/mod.rs | 1 - .../src/system_update/swap/mod.rs | 9 + .../{swap_paths.rs => swap/paths.rs} | 0 .../{swap.rs => swap/release.rs} | 8 +- backend/crates/gateway-host/tests/pricing.rs | 92 +- .../gateway-host/tests/system_update/mod.rs | 2 +- .../tests/system_update/swap/mod.rs | 3 + .../{swap_paths.rs => swap/paths.rs} | 2 +- .../runtime/src/adapter/middleware/http.rs | 2 +- .../src/adapter/upstream_adapter/mod.rs | 5 +- .../adapter/upstream_adapter/registration.rs | 7 +- .../runtime/src/callback/call_resources.rs | 4 +- .../runtime/src/callback/dispatch.rs | 4 +- .../{http_dispatch.rs => http/dispatch.rs} | 12 +- .../middleware}/mod.rs | 4 +- .../middleware}/resources.rs | 0 .../middleware}/websocket.rs | 0 .../runtime/src/callback/http/mod.rs | 8 + .../callback/{http.rs => http/outbound.rs} | 34 +- .../runtime/src/callback/middleware/mod.rs | 2 +- .../runtime/src/callback/mod.rs | 4 +- .../runtime/src/callback/upstream/mod.rs | 2 +- .../crates/gateway-plugin/runtime/src/lib.rs | 1 + .../target.rs => upstream_target.rs} | 4 +- .../tests/generation/policy/facts/contract.rs | 286 +++ .../tests/generation/policy/facts/mod.rs | 284 +-- .../policy/http/websocket/contract.rs | 354 +++ .../generation/policy/http/websocket/mod.rs | 352 +-- .../generation/policy/service/contract.rs | 544 ++++ .../tests/generation/policy/service/mod.rs | 541 +--- .../generation/policy/websocket/contract.rs | 89 + .../tests/generation/policy/websocket/mod.rs | 84 +- .../runtime/tests/support/environment.rs | 5 +- .../gateway-plugin/sdk/docs/capabilities.md | 1 + .../sdk/src/call/services/settings.rs | 13 +- .../gateway-protocol/src/anthropic/content.rs | 1 + .../gateway-protocol/src/anthropic/mod.rs | 2 + .../gateway-protocol/src/anthropic/request.rs | 13 +- .../gateway-protocol/src/capabilities.rs | 20 + .../gateway-protocol/src/genai/messages.rs | 238 ++ .../crates/gateway-protocol/src/genai/mod.rs | 20 + .../gateway-protocol/src/genai/request.rs | 82 + .../gateway-protocol/src/genai/response.rs | 186 ++ .../gateway-protocol/src/genai/stream.rs | 203 ++ .../gateway-protocol/src/genai/tokens.rs | 27 + backend/crates/gateway-protocol/src/lib.rs | 5 + .../crates/gateway-protocol/src/request.rs | 27 +- .../gateway-protocol/tests/genai/messages.rs | 238 ++ .../gateway-protocol/tests/genai/mod.rs | 6 + .../gateway-protocol/tests/genai/response.rs | 112 + .../gateway-protocol/tests/genai/tokens.rs | 38 + backend/crates/gateway-protocol/tests/main.rs | 1 + .../crates/gateway-protocol/tests/request.rs | 39 + .../crates/gateway-store/src/admin_adapter.rs | 4 +- .../gateway-store/src/postgres/backup.rs | 26 + .../buffer.rs} | 2 +- .../src/postgres/client_budgets/mod.rs | 9 + .../store.rs} | 20 +- .../windows.rs} | 10 +- .../gateway-store/src/postgres/client_keys.rs | 4 +- .../src/postgres/control_plane.rs | 10 +- .../crates/gateway-store/src/postgres/mod.rs | 5 +- .../observability/analytics/forecast.rs | 2 +- .../provider_accounts/admin_adapter.rs | 6 +- .../src/postgres/provider_accounts/mod.rs | 3 - .../{quota.rs => quota/document.rs} | 12 +- .../{quota_forecast.rs => quota/forecast.rs} | 10 +- .../{quota_history.rs => quota/history.rs} | 4 +- .../postgres/provider_accounts/quota/mod.rs | 10 + .../{quota_warmup.rs => quota/warmup.rs} | 6 +- .../src/postgres/runtime_settings.rs | 34 +- .../gateway-store/src/postgres/snapshot.rs | 12 +- .../gateway-store/tests/postgres/backup.rs | 66 +- .../buffer.rs} | 6 +- .../tests/postgres/client_budgets/mod.rs | 133 + .../store.rs} | 129 +- .../windows.rs} | 6 +- .../tests/postgres/control_plane.rs | 24 +- .../gateway-store/tests/postgres/mod.rs | 2 - .../gateway-store/tests/postgres/pricing.rs | 5 + .../tests/postgres/provider_accounts/mod.rs | 2 - .../{quota.rs => quota/document.rs} | 68 +- .../{quota_forecast.rs => quota/forecast.rs} | 12 +- .../{quota_history.rs => quota/history.rs} | 2 +- .../postgres/provider_accounts/quota/mod.rs | 11 + .../provider_accounts/quota/warmup.rs | 68 + .../tests/postgres/runtime_settings.rs | 29 +- .../crates/providers/antigravity/Cargo.toml | 50 + .../providers/antigravity/src/admin/mod.rs | 5 + .../antigravity/src/admin/provider.rs | 228 ++ .../antigravity/src/billing/calculate.rs | 183 ++ .../antigravity/src/billing/catalog.rs | 230 ++ .../providers/antigravity/src/billing/mod.rs | 10 + .../src/credential/authorization.rs | 210 ++ .../antigravity/src/credential/catalog.rs | 370 +++ .../antigravity/src/credential/documents.rs | 189 ++ .../antigravity/src/credential/mod.rs | 12 + .../antigravity/src/credential/oauth.rs | 515 ++++ .../src/credential/quota/document.rs | 164 ++ .../antigravity/src/credential/quota/mod.rs | 6 + .../src/credential/quota/service.rs | 335 +++ .../antigravity/src/credential/refresh.rs | 137 + .../antigravity/src/credential/service.rs | 301 +++ .../crates/providers/antigravity/src/lib.rs | 74 + .../antigravity/src/profile/archive.rs | 322 +++ .../antigravity/src/profile/artifact.rs | 295 +++ .../providers/antigravity/src/profile/mod.rs | 33 + .../antigravity/src/profile/release.rs | 359 +++ .../antigravity/src/profile/selection.rs | 258 ++ .../antigravity/src/profile/verification.rs | 163 ++ .../providers/antigravity/src/profile/view.rs | 85 + .../antigravity/src/provider/affinity.rs | 74 + .../antigravity/src/provider/candidates.rs | 194 ++ .../antigravity/src/provider/execution.rs | 164 ++ .../antigravity/src/provider/feedback.rs | 68 + .../providers/antigravity/src/provider/mod.rs | 130 + .../antigravity/src/provider/selection.rs | 336 +++ .../antigravity/src/provider/translation.rs | 213 ++ .../antigravity/src/provider/workers.rs | 149 ++ .../antigravity/src/transport/account.rs | 81 + .../antigravity/src/transport/client.rs | 285 +++ .../antigravity/src/transport/count.rs | 57 + .../antigravity/src/transport/failure.rs | 153 ++ .../antigravity/src/transport/headers.rs | 70 + .../antigravity/src/transport/mod.rs | 15 + .../antigravity/src/transport/pool.rs | 64 + .../antigravity/src/transport/response.rs | 255 ++ .../antigravity/tests/billing/calculate.rs | 219 ++ .../antigravity/tests/billing/mod.rs | 5 + .../antigravity/tests/credential/catalog.rs | 178 ++ .../antigravity/tests/credential/documents.rs | 489 ++++ .../antigravity/tests/credential/fixture.rs | 76 + .../antigravity/tests/credential/mod.rs | 31 + .../antigravity/tests/credential/oauth.rs | 266 ++ .../antigravity/tests/credential/quota/mod.rs | 3 + .../tests/credential/quota/service.rs | 236 ++ .../providers/antigravity/tests/main.rs | 27 + .../antigravity/tests/profile/archive.rs | 124 + .../antigravity/tests/profile/artifact.rs | 153 ++ .../antigravity/tests/profile/mod.rs | 7 + .../antigravity/tests/profile/release.rs | 52 + .../antigravity/tests/profile/selection.rs | 77 + .../antigravity/tests/profile/verification.rs | 163 ++ .../antigravity/tests/provider/affinity.rs | 531 ++++ .../antigravity/tests/provider/execution.rs | 533 ++++ .../antigravity/tests/provider/headers.rs | 141 ++ .../antigravity/tests/provider/middleware.rs | 135 + .../antigravity/tests/provider/mod.rs | 8 + .../antigravity/tests/provider/round_robin.rs | 370 +++ .../antigravity/tests/provider/selection.rs | 224 ++ .../antigravity/tests/support/mod.rs | 397 +++ .../antigravity/tests/support/ports.rs | 648 +++++ .../antigravity/tests/support/profile.rs | 77 + .../antigravity/tests/transport/client.rs | 391 +++ .../antigravity/tests/transport/count.rs | 210 ++ .../antigravity/tests/transport/mod.rs | 5 + .../antigravity/tests/transport/pool.rs | 284 +++ .../providers/openai/src/admin/credentials.rs | 183 ++ .../providers/openai/src/admin/error.rs | 377 +++ .../crates/providers/openai/src/admin/mod.rs | 2136 +--------------- .../providers/openai/src/admin/pending.rs | 270 ++ .../providers/openai/src/admin/profile.rs | 131 + .../providers/openai/src/admin/provider.rs | 1139 +++++++++ .../providers/openai/src/admin/quota.rs | 232 +- .../src/{transport => }/automatic_context.rs | 14 +- .../providers/openai/src/billing/calculate.rs | 406 +++ .../providers/openai/src/billing/catalog.rs | 624 +++++ .../providers/openai/src/billing/images.rs | 110 + .../providers/openai/src/billing/mod.rs | 14 + .../providers/openai/src/credential/admin.rs | 15 +- .../openai/src/credential/catalog/mod.rs | 2 +- .../providers/openai/src/credential/mod.rs | 1 - .../providers/openai/src/credential/oauth.rs | 2 +- .../src/credential/profile_statistics.rs | 8 +- .../openai/src/credential/quota/mod.rs | 2 +- .../openai/src/credential/selector.rs | 8 +- .../openai/src/credential/token_client.rs | 2 +- .../providers/openai/src/credential/types.rs | 16 - backend/crates/providers/openai/src/lib.rs | 71 +- .../src/{transport => }/profile/baseline.rs | 0 .../{transport => }/profile/cli_release.rs | 0 .../src/{transport => }/profile/context.rs | 2 +- .../profile/desktop_artifact.rs | 0 .../src/{transport => }/profile/identity.rs | 14 +- .../providers/openai/src/profile/mod.rs | 24 + .../profile/platform_release/artifact.rs | 0 .../profile/platform_release/mod.rs | 0 .../profile/platform_release/range.rs | 0 .../profile/platform_release/xz.rs | 0 .../profile/mod.rs => profile/release.rs} | 335 +-- .../src/{transport => }/profile/selection.rs | 6 +- .../providers/openai/src/profile/state.rs | 313 +++ .../openai/src/provider/execution.rs | 6 +- .../providers/openai/src/provider/failure.rs | 4 +- .../providers/openai/src/provider/guardian.rs | 2 +- .../providers/openai/src/provider/live.rs | 2 +- .../openai/src/provider/messages/stream.rs | 2 +- .../providers/openai/src/provider/mod.rs | 41 +- .../openai/src/provider/upstream_adapter.rs | 4 +- .../providers/openai/src/provider/workers.rs | 6 +- .../providers/openai/src/request_identity.rs | 18 +- .../openai/src/transport/canonical.rs | 4 +- .../{client.rs => client/backend.rs} | 160 +- .../{client_catalog.rs => client/catalog.rs} | 41 +- .../{client_json.rs => client/json.rs} | 23 +- .../{client_live.rs => client/live.rs} | 19 +- .../messages.rs} | 13 +- .../openai/src/transport/client/mod.rs | 21 + .../{client_stream.rs => client/stream.rs} | 21 +- .../openai/src/transport/correlation.rs | 2 +- .../providers/openai/src/transport/headers.rs | 2 +- .../providers/openai/src/transport/mod.rs | 14 +- .../openai/src/transport/privacy/carrier.rs | 4 +- .../openai/src/transport/profile_avatar.rs | 5 +- .../providers/openai/src/transport/request.rs | 2 +- .../providers/openai/src/transport/usage.rs | 1111 +------- .../providers/openai/tests/admin/mod.rs | 2229 +---------------- .../providers/openai/tests/admin/peer_info.rs | 8 +- .../providers/openai/tests/admin/provider.rs | 2208 ++++++++++++++++ .../openai/tests/billing/calculate.rs | 573 +++++ .../providers/openai/tests/billing/mod.rs | 3 + .../providers/openai/tests/compat/headers.rs | 5 +- .../openai/tests/credential/admin.rs | 40 +- .../tests/credential/catalog/contract.rs | 1303 ++++++++++ .../openai/tests/credential/catalog/mod.rs | 1542 +----------- .../tests/credential/catalog/refresh.rs | 235 ++ .../tests/credential/contract/capacity.rs | 2 +- .../openai/tests/credential/contract/mod.rs | 6 +- .../contract/scheduling_projection.rs | 6 +- .../openai/tests/credential/oauth.rs | 4 +- .../tests/credential/profile_statistics.rs | 4 +- .../openai/tests/credential/quota/mod.rs | 4 +- .../openai/tests/credential/refresh.rs | 2 +- .../openai/tests/credential/token_client.rs | 21 +- backend/crates/providers/openai/tests/main.rs | 6 + .../{transport => }/profile/cli_release.rs | 20 +- .../profile/desktop_artifact.rs | 2 +- .../tests/{transport => }/profile/identity.rs | 8 +- .../providers/openai/tests/profile/mod.rs | 198 ++ .../profile/platform_release/artifact.rs | 2 +- .../profile/platform_release/mod.rs | 6 +- .../profile/platform_release/range.rs | 2 +- .../profile/platform_release/xz.rs | 2 +- .../profile/mod.rs => profile/release.rs} | 298 +-- .../{transport => }/profile/selection.rs | 13 +- .../providers/openai/tests/profile/state.rs | 97 + .../provider/contract/account_eligibility.rs | 2 +- .../provider/contract/cache_preference.rs | 4 +- .../tests/provider/contract/guardian_model.rs | 3 +- .../provider/contract/image_model_access.rs | 2 +- .../provider/contract/messages/affinity.rs | 2 +- .../openai/tests/provider/contract/mod.rs | 6 +- .../provider/contract/search_model_access.rs | 2 +- .../provider/contract/session_binding.rs | 15 +- .../tests/provider/contract/turn_state.rs | 2 +- .../providers/openai/tests/provider/live.rs | 4 +- .../openai/tests/provider/workers.rs | 5 +- .../crates/providers/openai/tests/support.rs | 2 +- .../openai/tests/transport/catalog.rs | 4 +- .../{client.rs => client/backend.rs} | 0 .../openai/tests/transport/client/mod.rs | 3 + .../tests/transport/diagnostics/contract.rs | 468 ++++ .../tests/transport/diagnostics/evidence.rs | 85 + .../openai/tests/transport/diagnostics/mod.rs | 551 +--- .../openai/tests/transport/headers.rs | 13 +- .../providers/openai/tests/transport/mod.rs | 5 +- .../tests/transport/profile_contract.rs | 7 +- .../openai/tests/transport/request.rs | 2 +- .../openai/tests/transport/reset_credits.rs | 4 +- .../providers/openai/tests/transport/usage.rs | 578 +---- .../transport/websocket/pool/contract.rs | 118 + .../tests/transport/websocket/pool/mod.rs | 116 +- .../providers/xai/src/admin/credentials.rs | 206 ++ .../crates/providers/xai/src/admin/error.rs | 113 + backend/crates/providers/xai/src/admin/mod.rs | 10 + .../crates/providers/xai/src/admin/pending.rs | 215 ++ .../crates/providers/xai/src/admin/profile.rs | 34 + .../xai/src/{admin.rs => admin/provider.rs} | 763 +----- .../crates/providers/xai/src/admin/quota.rs | 139 + .../providers/xai/src/billing/calculate.rs | 161 ++ .../providers/xai/src/billing/catalog.rs | 158 ++ .../crates/providers/xai/src/billing/mod.rs | 10 + .../xai/src/credential/repository.rs | 10 +- .../providers/xai/src/credential/selector.rs | 104 +- backend/crates/providers/xai/src/lib.rs | 60 +- .../crates/providers/xai/src/profile/mod.rs | 13 + .../profile.rs => profile/release.rs} | 102 +- .../selection.rs} | 2 +- .../crates/providers/xai/src/profile/state.rs | 103 + .../crates/providers/xai/src/provider/mod.rs | 7 +- .../xai/src/provider/upstream_adapter.rs | 2 +- .../providers/xai/src/provider/workers.rs | 2 +- .../providers/xai/src/transport/canonical.rs | 328 +-- .../crates/providers/xai/src/transport/mod.rs | 7 +- .../providers/xai/src/transport/session.rs | 27 +- .../xai/tests/{admin.rs => admin/mod.rs} | 665 +---- .../providers/xai/tests/admin/provider.rs | 632 +++++ .../crates/providers/xai/tests/admin/quota.rs | 25 + .../providers/xai/tests/billing/calculate.rs | 50 + .../crates/providers/xai/tests/billing/mod.rs | 3 + .../xai/tests/credential/contract.rs | 29 +- .../xai/tests/credential/selector.rs | 218 ++ backend/crates/providers/xai/tests/main.rs | 6 + .../crates/providers/xai/tests/profile/mod.rs | 52 + .../providers/xai/tests/profile/release.rs | 47 + .../selection.rs} | 2 +- .../providers/xai/tests/profile/state.rs | 22 + .../xai/tests/provider/contract/mod.rs | 3 +- .../xai/tests/provider/contract/scheduling.rs | 2 + .../provider/contract/selection_retry.rs | 1 + backend/crates/providers/xai/tests/support.rs | 56 +- .../xai/tests/transport/canonical.rs | 51 +- .../providers/xai/tests/transport/mod.rs | 2 - .../providers/xai/tests/transport/profile.rs | 109 - backend/migrations/.frozen-sha256 | 2 + .../0047_runtime_settings_revision.sql | 5 + .../0048_general_session_affinity.sql | 5 + docs/api.md | 188 +- docs/architecture.md | 138 +- docs/development.md | 2 +- docs/theme.md | 10 +- frontend/build/plugin-bridge.ts | 2 +- frontend/src/App.vue | 3 +- frontend/src/api/index.ts | 4 + frontend/src/api/modules/accounts/index.ts | 2 +- .../src/api/modules/accounts/management.ts | 15 +- frontend/src/api/modules/accounts/types.ts | 4 + frontend/src/api/modules/dashboard.ts | 2 +- frontend/src/api/modules/keys.ts | 2 +- frontend/src/api/modules/settings/backups.ts | 8 +- frontend/src/api/modules/settings/index.ts | 7 +- frontend/src/api/modules/settings/pricing.ts | 1 + frontend/src/api/modules/settings/profiles.ts | 141 +- frontend/src/api/request/plugins/feedback.ts | 2 +- frontend/src/api/request/plugins/session.ts | 2 +- frontend/src/api/types/request-profile.ts | 3 + .../AccountRequestTimeline.vue | 2 +- frontend/src/components/AppLanguageMenu.vue | 9 +- frontend/src/components/HelpPopover.vue | 6 +- .../components/KeyUsageBudget.vue | 10 +- frontend/src/components/ProviderFilter.vue | 2 +- frontend/src/components/ProviderIconGroup.vue | 2 +- .../{usage => }/UsageRecordStatusFilter.vue | 2 +- .../AccountModelCleanupPopover.vue | 0 .../AccountModelOption.vue | 0 .../index.vue | 19 +- .../validation.ts} | 6 - .../AccountUpstreamBadge.vue | 0 .../index.vue} | 22 +- .../account-usage-window/index.vue | 10 +- .../account-usage-window/presenter.ts | 33 +- .../api-key-config-modal}/client.ts | 0 .../index.vue} | 4 +- .../BaseChart.vue => base-chart/index.vue} | 0 .../{charts => base-chart}/timeSeriesGap.ts | 0 .../{charts => base-chart}/tooltip.ts | 0 .../client-profile/ClientProfileEditor.vue | 153 -- .../ClientProfilePreviewPanel.vue | 50 - .../ProviderRequestProfilesEditor.vue | 126 - .../client-profile/XaiClientProfileEditor.vue | 176 -- .../HealthTimelinePointPopover.vue | 2 +- .../health.ts | 0 .../index.vue} | 4 +- .../request-profile/ProfileEditorFrame.vue | 62 + .../RequestProfilePreviewPanel.vue | 52 + .../src/components/request-profile/changes.ts | 14 + .../src/components/request-profile/index.vue | 120 + .../request-profile/useProfileEditor.ts | 135 + frontend/src/components/schema-form/index.vue | 3 +- frontend/src/components/schema-form/schema.ts | 31 + .../UsageBillingCell.vue | 4 +- .../UsageClientIpCell.vue | 2 +- .../UsageDetailPopover.vue | 0 .../UsageErrorCell.vue | 2 +- .../UsageLatencyCell.vue | 4 +- .../UsageModelCell.vue | 4 +- .../UsagePerformanceCell.vue | 4 +- .../UsagePerformanceHeader.vue | 18 + .../UsageReasoningEffortCell.vue | 4 +- .../UsageRouteCell.vue | 11 +- .../UsageTimeCell.vue | 0 .../UsageTokenCell.vue | 10 +- .../UsageTransportBadge.vue | 2 +- .../UsageTransportCell.vue | 2 +- .../shared => usage-records-table}/columns.ts | 7 +- .../shared => usage-records-table}/errors.ts | 2 +- .../index.vue} | 31 +- .../presenter.ts | 26 +- frontend/src/composables/useAsyncAction.ts | 2 +- frontend/src/composables/useCopyText.ts | 2 +- frontend/src/composables/useLocale.ts | 9 - frontend/src/i18n/index.ts | 7 + frontend/src/i18n/locales/en/accounts.json | 9 +- frontend/src/i18n/locales/en/dashboard.json | 1 + frontend/src/i18n/locales/en/settings.json | 74 +- frontend/src/i18n/locales/en/usage.json | 3 +- .../src/i18n/locales/zh-Hans/accounts.json | 9 +- .../src/i18n/locales/zh-Hans/dashboard.json | 1 + .../src/i18n/locales/zh-Hans/settings.json | 76 +- frontend/src/i18n/locales/zh-Hans/usage.json | 3 +- .../src/i18n/locales/zh-Hant/accounts.json | 9 +- .../src/i18n/locales/zh-Hant/dashboard.json | 1 + .../src/i18n/locales/zh-Hant/settings.json | 76 +- frontend/src/i18n/locales/zh-Hant/usage.json | 3 +- frontend/src/i18n/ui.ts | 8 - frontend/src/layout/components/AppSidebar.vue | 2 +- .../components/system-update-modal/index.vue | 2 +- frontend/src/main.ts | 3 +- .../src/{utils => plugins}/notification.ts | 2 +- frontend/src/providers/accounts.ts | 91 + .../AntigravityRequestProfileEditor.vue | 131 + .../antigravity/request-profile/profile.ts | 30 + .../providers.ts => providers/catalog.ts} | 30 +- .../openai/accounts/ApiKeyFields.vue} | 15 +- .../OpenAiAccountConnectionEditor.vue | 23 + .../accounts/OpenAiApiKeyImportForm.vue | 25 + .../openai/accounts/connection.ts} | 13 +- .../src/providers/openai/accounts/import.ts | 53 + .../openai/accounts/useApiKeyFormRules.ts} | 14 +- .../openai/accounts/useConnectionEditor.ts | 96 + .../InstallationSeedField.vue} | 0 .../OpenAiRequestProfileEditor.vue | 45 + .../openai/request-profile/ProfileFields.vue} | 70 +- .../request-profile/installationSeed.ts | 42 + .../openai/request-profile/profile.ts | 68 + .../XaiRequestProfileEditor.vue | 89 + .../providers/xai/request-profile/profile.ts | 19 + frontend/src/{utils => router}/plugin.ts | 0 frontend/src/router/routes.ts | 10 +- frontend/src/utils/data.ts | 32 - frontend/src/utils/format.ts | 16 +- .../components/AccountBatchEditModal.vue | 2 + .../accounts/components/AccountEditModal.vue | 55 +- .../components/AccountIdentityCell.vue | 2 +- .../components}/AccountQuotaWindowDetails.vue | 4 +- .../components/AccountSettingsFields.vue | 8 +- .../components/AccountTableActions.vue | 11 +- .../accounts/components/AccountUsagePanel.vue | 4 +- .../AccountConcurrencyTable.vue | 2 +- .../index.vue} | 2 +- .../useAccountConcurrency.ts | 0 .../AccountOAuthFields.vue | 3 +- .../AccountProviderChooser.vue | 2 +- .../AccountSetupFields.vue | 2 + .../components/account-create-modal/index.vue | 52 +- .../account-create-modal/presenter.ts | 20 +- .../account-profile-modal/ProfileHero.vue | 2 +- .../account-profile-modal/index.vue | 2 +- .../useAccountPersonalInfo.ts | 2 +- .../AccountProxyTestBadge.vue | 0 .../index.vue} | 2 +- .../useAccountProxyTest.ts | 2 +- .../account-quota-forecast-modal/index.vue | 2 +- .../useAccountQuotaForecast.ts | 2 +- .../components/account-quota-panel/Entry.vue | 4 +- .../account-quota-panel/PoolChart.vue | 4 +- .../account-quota-panel/QuotaSettings.vue | 2 +- .../account-quota-panel/ResetCredits.vue | 2 +- .../account-quota-panel/UpstreamPool.vue | 2 +- .../account-quota-panel/UsageLimits.vue | 2 +- .../components/account-quota-panel/index.vue | 17 +- .../components/account-quota-panel/pool.ts | 2 +- .../useAccountResetCredits.ts | 2 +- .../usePoolQuotaWindows.ts | 0 .../account-quota-summary-cell/Entry.vue | 6 +- .../WindowGroup.vue | 2 +- .../account-quota-summary-cell/index.vue | 2 +- .../account-status-badge/presenter.ts | 2 +- .../composables/useAccountAuthorization.ts | 2 +- .../composables/useAccountBatchEditor.ts | 7 +- .../composables/useAccountConnectionTest.ts | 2 +- .../accounts/composables/useAccountEditor.ts | 105 +- .../composables/useAccountImportTasks.ts | 2 +- .../composables/useAccountMutations.ts | 7 +- .../composables/useAccountOnboarding.ts | 38 +- .../useAccountSettingsFormRules.ts | 2 +- frontend/src/views/accounts/constants.ts | 11 +- frontend/src/views/accounts/index.vue | 14 +- .../accounts}/utils/account-upstream.ts | 0 .../src/views/accounts/utils/accountCreate.ts | 35 +- .../src/views/accounts/utils/accountImport.ts | 60 +- .../dashboard/components/DashboardContent.vue | 120 - .../components/DashboardOverview.vue | 95 + .../dashboard/components/UsageRecordCard.vue | 10 +- .../DashboardAccountIdentity.vue | 11 +- .../index.vue} | 15 +- .../{ => dashboard-metrics}/MetricCard.vue | 7 +- .../components/dashboard-metrics/cards.ts | 232 ++ .../components/dashboard-metrics/index.vue | 20 + .../index.vue} | 38 +- .../components/request-trend/series.ts | 161 ++ .../request-trend}/useRequestTrendChart.ts | 21 +- .../components/wire-profile/identity.ts | 73 + .../index.vue} | 117 +- .../dashboard/composables/useDashboard.ts | 56 +- frontend/src/views/dashboard/constants.ts | 2 +- frontend/src/views/dashboard/index.vue | 42 +- frontend/src/views/dashboard/presenter.ts | 435 ---- frontend/src/views/dashboard/utils/format.ts | 5 + .../components/AccountGroupFormModal.vue | 4 +- .../groups/composables/useAccountGroups.ts | 2 +- .../key-usage/components/KeyUsageRecords.vue | 30 +- .../key-usage/components/KeyUsageSummary.vue | 7 +- .../key-usage/components/KeyUsageTrend.vue | 13 +- .../key-usage/composables/useKeyConfig.ts | 4 +- .../key-usage/composables/useKeyUsage.ts | 4 +- frontend/src/views/key-usage/index.vue | 6 +- frontend/src/views/key-usage/utils/format.ts | 15 - frontend/src/views/key-usage/utils/metrics.ts | 4 +- .../keys/components/ApiKeyBatchEditModal.vue | 15 +- .../keys/components/ApiKeyBudgetAlignment.vue | 2 +- .../components/ApiKeyBudgetResetModal.vue | 2 +- .../views/keys/components/ApiKeyFormModal.vue | 10 +- .../keys/components/ApiKeyStatisticsModal.vue | 6 +- .../views/keys/composables/useApiKeyEditor.ts | 46 +- .../keys/composables/useApiKeyMutations.ts | 2 +- .../views/keys/composables/useApiKeyUse.ts | 4 +- frontend/src/views/keys/index.vue | 2 +- .../components/PluginConfigurationFields.vue | 2 +- .../components/PluginConfigurationModal.vue | 2 +- .../plugins/components/PluginDetailModal.vue | 2 +- .../components/PluginExtensionsPanel.vue | 2 +- .../PluginFrontendAuthenticationEditor.vue | 2 +- .../plugins/components/PluginInstallModal.vue | 2 +- .../plugins/components/PluginManagement.vue | 283 --- .../components/PluginResourcePicker.vue | 2 +- .../PluginExternalLinkDialog.vue | 0 .../bridge-contract.ts | 0 .../plugin-management-frame}/bridge-models.ts | 0 .../bridge-runtime.ts | 0 .../plugin-management-frame}/frame.ts | 0 .../index.vue} | 4 +- .../plugin-management-frame}/model-streams.ts | 0 .../usePluginFrameSession.ts | 10 +- .../composables/usePluginArtifactActions.ts | 2 +- .../composables/usePluginCredentials.ts | 2 +- .../composables/usePluginInstallation.ts | 2 +- .../plugins/composables/usePluginInstances.ts | 2 +- .../plugins/composables/usePluginUninstall.ts | 2 +- .../plugins/composables/usePluginVersions.ts | 2 +- frontend/src/views/plugins/index.vue | 280 ++- .../PluginPage.vue => page/index.vue} | 6 +- frontend/src/views/plugins/utils/actions.ts | 2 +- .../ProxyAssignAccountsModal.vue | 4 +- .../index.vue} | 4 +- .../useProxyAccountAssignment.ts | 2 +- .../proxy-accounts-modal}/useProxyAccounts.ts | 2 +- .../ProxyBatchCreateFields.vue | 4 +- .../ProxyBatchResults.vue | 6 +- .../index.vue} | 4 +- .../proxy-form-modal}/useProxyBatchCreate.ts | 8 +- .../views/proxies/composables/useProxies.ts | 2 +- .../composables/useProxyBatchTesting.ts | 2 +- frontend/src/views/proxies/index.vue | 4 +- .../components/AccountAffinityCard.vue | 13 +- .../settings/components/AccountWarmupCard.vue | 18 +- .../settings/components/ClientProfileCard.vue | 38 - .../components/ConcurrencyPolicyCard.vue | 82 +- .../components/GuardianReviewCard.vue | 53 + .../settings/components/ModelAliasesCard.vue | 30 +- .../components/ProviderSettingsNav.vue | 31 + .../components/RequestCountryCard.vue | 4 +- .../components/RequestHistoryCard.vue | 4 +- .../components/RequestLocationCard.vue | 18 +- .../components/RequestProfileCard.vue | 28 + .../settings/components/ResetCreditCard.vue | 10 +- .../settings/components/RetryPolicyCard.vue | 79 + .../components/RotationStrategyCard.vue | 6 +- .../settings/components/TokenRefreshCard.vue | 4 +- .../components/backup/BackupRecordsCard.vue | 8 +- .../components/backup/BackupScheduleCard.vue | 37 +- .../components/backup/BackupStorageCard.vue | 9 +- .../{SettingsBackupSection.vue => index.vue} | 29 +- .../backup}/useBackupRecords.ts | 2 +- .../backup}/useBackupSettings.ts | 32 +- .../ClientCliInstallPanel.vue | 0 .../ClientDesktopInstallPanel.vue | 0 .../ClientDesktopOfflineDownloads.vue | 0 .../ClientInstallCommandList.vue | 0 .../ClientVersionGuideModal.vue | 0 .../ClientVersionPolicyCard.vue | 4 +- .../components/client-version/index.vue | 6 +- .../{composables => }/useClientDownloads.ts | 0 .../ProtectionConditionEditor.vue | 4 +- .../error-protection/ProtectionRuleEditor.vue | 4 +- .../error-protection/ProtectionRuleRow.vue | 4 +- ...countErrorProtectionCard.vue => index.vue} | 19 +- .../error-protection/{form.ts => policy.ts} | 2 +- .../pricing/PricingBatchModal.vue | 0 .../pricing/PricingEditor.vue | 14 +- .../pricing/PricingRateFields.vue | 0 .../pricing/PricingSyncModal.vue | 74 +- .../{ => components}/pricing/PricingTable.vue | 0 .../pricing/PricingToolbar.vue | 2 +- .../{ => components}/pricing/PricingUnit.vue | 0 .../{ => components}/pricing/index.vue | 8 +- .../{ => components}/pricing/model.ts | 7 +- .../{ => components}/pricing/usePricing.ts | 12 +- .../components/privacy/PolicyPreview.vue | 4 +- .../components/privacy/RuleEditor.vue | 4 +- .../components/privacy/RulesTable.vue | 2 +- .../components/privacy/StepFields.vue | 2 +- .../settings/components/privacy/StepList.vue | 2 +- .../{PrivacyPolicyCard.vue => index.vue} | 2 +- .../settings/components/privacy/presets.ts | 2 +- .../privacy}/usePrivacyPreview.ts | 4 +- .../{ => settings-access}/AdminApiKeyCard.vue | 2 +- .../AdminPasswordCard.vue | 2 +- .../ChangePasswordModal.vue | 2 +- .../ResponseBodyLimitCard.vue | 4 +- .../index.vue} | 8 +- .../settings-access}/useAdminApiKey.ts | 2 +- .../settings/composables/useSettingsForm.ts | 49 +- .../composables/useSettingsFormRules.ts | 6 +- frontend/src/views/settings/index.vue | 286 ++- .../components/AppearanceSettingsSection.vue | 2 +- .../components/ThemeComponentPreview.vue | 2 +- .../components/ThemeDashboardPreview.vue | 32 +- .../theme/components/ThemeEditorPreview.vue | 2 +- .../components/ThemeGlobalTokenPanel.vue | 2 +- .../ThemePreviewScope.vue | 0 .../index.vue} | 2 +- .../useThemePreviewCanvas.ts | 0 .../src/views/theme/fixtures/dashboard.ts | 4 +- .../views/usage/components/UsageCostCard.vue | 6 +- .../usage/components/UsageDiagnosticCard.vue | 4 +- .../components/UsageErrorDetailModal.vue | 4 +- .../usage/components/UsageErrorDiagnosis.vue | 4 +- .../usage/components/UsageHealthCard.vue | 4 +- .../usage/components/UsagePerformanceCard.vue | 6 +- .../components/UsageRecordDetailModal.vue | 8 +- .../composables/useUsageRecordColumns.ts | 4 +- frontend/src/views/usage/index.vue | 4 +- frontend/src/views/usage/utils/chart.ts | 4 +- frontend/tsconfig.source.json | 3 + modules/ui | 2 +- 870 files changed, 40252 insertions(+), 21631 deletions(-) create mode 100644 backend/crates/gateway-admin/src/model/quota_forecast/mod.rs rename backend/crates/gateway-admin/src/model/{quota_forecast.rs => quota_forecast/projection.rs} (97%) rename backend/crates/gateway-admin/src/model/{quota_forecast_sampling.rs => quota_forecast/sampling.rs} (99%) create mode 100644 backend/crates/gateway-admin/src/use_case/observability/billing.rs create mode 100644 backend/crates/gateway-admin/src/use_case/observability/dashboard.rs create mode 100644 backend/crates/gateway-admin/src/use_case/observability/insights.rs create mode 100644 backend/crates/gateway-admin/src/use_case/observability/metrics.rs create mode 100644 backend/crates/gateway-admin/src/use_case/observability/service.rs create mode 100644 backend/crates/gateway-admin/src/use_case/system/mod.rs rename backend/crates/gateway-admin/src/use_case/{system_preflight.rs => system/preflight.rs} (99%) rename backend/crates/gateway-admin/src/use_case/{system.rs => system/service.rs} (98%) create mode 100644 backend/crates/gateway-admin/tests/model/backup/contract.rs create mode 100644 backend/crates/gateway-admin/tests/model/plugins/contract.rs create mode 100644 backend/crates/gateway-admin/tests/model/quota_forecast/mod.rs rename backend/crates/gateway-admin/tests/model/{quota_forecast.rs => quota_forecast/projection.rs} (99%) rename backend/crates/gateway-admin/tests/model/{quota_forecast_sampling.rs => quota_forecast/sampling.rs} (99%) create mode 100644 backend/crates/gateway-admin/tests/use_case/observability/dashboard.rs create mode 100644 backend/crates/gateway-admin/tests/use_case/observability/insights.rs create mode 100644 backend/crates/gateway-admin/tests/use_case/observability/service.rs create mode 100644 backend/crates/gateway-admin/tests/use_case/observability/store_cache.rs create mode 100644 backend/crates/gateway-admin/tests/use_case/system/mod.rs rename backend/crates/gateway-admin/tests/use_case/{system_preflight.rs => system/preflight.rs} (97%) rename backend/crates/gateway-admin/tests/use_case/{system.rs => system/service.rs} (96%) create mode 100644 backend/crates/gateway-admin/tests/use_case/usage_data/contract.rs rename backend/crates/gateway-api/src/{openai => data_plane}/auth.rs (99%) rename backend/crates/gateway-api/src/{openai/responses/error.rs => data_plane/body.rs} (60%) rename backend/crates/gateway-api/src/{openai => data_plane}/chat_completions/delivery.rs (99%) rename backend/crates/gateway-api/src/{openai => data_plane}/chat_completions/http.rs (89%) rename backend/crates/gateway-api/src/{openai => data_plane}/chat_completions/mod.rs (100%) rename backend/crates/gateway-api/src/{openai => data_plane}/chat_completions/request.rs (98%) rename backend/crates/gateway-api/src/{openai => data_plane}/chat_completions/response.rs (98%) rename backend/crates/gateway-api/src/{openai => data_plane}/error.rs (100%) create mode 100644 backend/crates/gateway-api/src/data_plane/genai/error.rs create mode 100644 backend/crates/gateway-api/src/data_plane/genai/mod.rs create mode 100644 backend/crates/gateway-api/src/data_plane/genai/models.rs rename backend/crates/gateway-api/src/{openai => data_plane}/generation/http.rs (92%) rename backend/crates/gateway-api/src/{openai/responses => data_plane/generation}/keepalive.rs (95%) create mode 100644 backend/crates/gateway-api/src/data_plane/generation/mod.rs rename backend/crates/gateway-api/src/{openai => data_plane}/generation/request.rs (90%) rename backend/crates/gateway-api/src/{openai => data_plane}/generation/response.rs (62%) rename backend/crates/gateway-api/src/{openai => data_plane}/generation/validation.rs (68%) rename backend/crates/gateway-api/src/{openai => data_plane}/images/http.rs (93%) rename backend/crates/gateway-api/src/{openai => data_plane}/images/mod.rs (100%) rename backend/crates/gateway-api/src/{openai => data_plane}/images/request.rs (100%) rename backend/crates/gateway-api/src/{openai => data_plane}/live/http.rs (98%) rename backend/crates/gateway-api/src/{openai => data_plane}/live/mod.rs (99%) rename backend/crates/gateway-api/src/{openai => data_plane}/live/websocket.rs (99%) rename backend/crates/gateway-api/src/{openai => data_plane}/messages.rs (95%) rename backend/crates/gateway-api/src/{openai => data_plane}/middleware/http.rs (99%) rename backend/crates/gateway-api/src/{openai => data_plane}/middleware/mod.rs (100%) rename backend/crates/gateway-api/src/{openai => data_plane}/middleware/request.rs (99%) rename backend/crates/gateway-api/src/{openai => data_plane}/middleware/session.rs (100%) rename backend/crates/gateway-api/src/{openai => data_plane}/mod.rs (89%) rename backend/crates/gateway-api/src/{openai => data_plane}/models.rs (98%) rename backend/crates/gateway-api/src/{openai/endpoint.rs => data_plane/openai_endpoints.rs} (82%) rename backend/crates/gateway-api/src/{openai => data_plane}/peer_link/mod.rs (94%) rename backend/crates/gateway-api/src/{openai => data_plane}/peer_link/wire.rs (100%) rename backend/crates/gateway-api/src/{provider.rs => data_plane/provider_endpoints.rs} (99%) create mode 100644 backend/crates/gateway-api/src/data_plane/responses/error.rs rename backend/crates/gateway-api/src/{openai => data_plane}/responses/http.rs (89%) rename backend/crates/gateway-api/src/{openai => data_plane}/responses/mod.rs (67%) rename backend/crates/gateway-api/src/{openai => data_plane}/responses/request.rs (83%) rename backend/crates/gateway-api/src/{openai => data_plane}/responses/response.rs (99%) rename backend/crates/gateway-api/src/{openai => data_plane}/responses/validation.rs (96%) rename backend/crates/gateway-api/src/{openai => data_plane}/responses/websocket/connection/frame.rs (100%) rename backend/crates/gateway-api/src/{openai => data_plane}/responses/websocket/connection/handle.rs (100%) rename backend/crates/gateway-api/src/{openai => data_plane}/responses/websocket/connection/middleware.rs (100%) rename backend/crates/gateway-api/src/{openai => data_plane}/responses/websocket/connection/mod.rs (100%) rename backend/crates/gateway-api/src/{openai => data_plane}/responses/websocket/connection/pump.rs (100%) rename backend/crates/gateway-api/src/{openai => data_plane}/responses/websocket/connection/state.rs (100%) rename backend/crates/gateway-api/src/{openai => data_plane}/responses/websocket/connection/transport.rs (100%) rename backend/crates/gateway-api/src/{openai => data_plane}/responses/websocket/forward.rs (98%) rename backend/crates/gateway-api/src/{openai => data_plane}/responses/websocket/interrupt.rs (100%) rename backend/crates/gateway-api/src/{openai => data_plane}/responses/websocket/mod.rs (96%) rename backend/crates/gateway-api/src/{openai => data_plane}/responses/websocket/protocol.rs (97%) rename backend/crates/gateway-api/src/{openai => data_plane}/router.rs (51%) rename backend/crates/gateway-api/src/{openai => data_plane}/search/http.rs (90%) rename backend/crates/gateway-api/src/{openai => data_plane}/search/mod.rs (100%) rename backend/crates/gateway-api/src/{openai => data_plane}/service.rs (77%) rename backend/crates/gateway-api/src/{openai => data_plane}/usage.rs (93%) delete mode 100644 backend/crates/gateway-api/src/openai/generation/mod.rs rename backend/crates/gateway-api/src/{session_cookie.rs => session/cookie.rs} (100%) create mode 100644 backend/crates/gateway-api/src/session/mod.rs create mode 100644 backend/crates/gateway-api/src/session/state.rs create mode 100644 backend/crates/gateway-api/tests/admin/observability/export/contract.rs rename backend/crates/gateway-api/tests/{openai => data_plane}/auth.rs (99%) rename backend/crates/gateway-api/tests/{openai => data_plane}/chat_completions/http.rs (99%) rename backend/crates/gateway-api/tests/{openai => data_plane}/chat_completions/mod.rs (100%) rename backend/crates/gateway-api/tests/{openai => data_plane}/chat_completions/request.rs (100%) rename backend/crates/gateway-api/tests/{openai => data_plane}/chat_completions/response.rs (100%) rename backend/crates/gateway-api/tests/{openai => data_plane}/error.rs (99%) create mode 100644 backend/crates/gateway-api/tests/data_plane/genai/contract.rs create mode 100644 backend/crates/gateway-api/tests/data_plane/genai/mod.rs create mode 100644 backend/crates/gateway-api/tests/data_plane/genai/models.rs rename backend/crates/gateway-api/tests/{openai => data_plane}/group_permissions.rs (100%) rename backend/crates/gateway-api/tests/{openai => data_plane}/images/mod.rs (98%) rename backend/crates/gateway-api/tests/{openai => data_plane}/images/request.rs (99%) rename backend/crates/gateway-api/tests/{openai => data_plane}/live/mod.rs (100%) rename backend/crates/gateway-api/tests/{openai => data_plane}/live/websocket.rs (99%) rename backend/crates/gateway-api/tests/{openai => data_plane}/messages.rs (100%) rename backend/crates/gateway-api/tests/{openai/middleware/mod.rs => data_plane/middleware/fixture.rs} (88%) create mode 100644 backend/crates/gateway-api/tests/data_plane/middleware/mod.rs rename backend/crates/gateway-api/tests/{openai => data_plane}/mod.rs (98%) rename backend/crates/gateway-api/tests/{openai => data_plane}/models.rs (98%) rename backend/crates/gateway-api/tests/{openai/endpoint.rs => data_plane/openai_endpoints.rs} (100%) rename backend/crates/gateway-api/tests/{openai => data_plane}/peer_link/catalog.rs (100%) rename backend/crates/gateway-api/tests/{openai => data_plane}/peer_link/mod.rs (100%) rename backend/crates/gateway-api/tests/{provider.rs => data_plane/provider_endpoints.rs} (96%) rename backend/crates/gateway-api/tests/{openai => data_plane}/responses/http.rs (98%) rename backend/crates/gateway-api/tests/{openai => data_plane}/responses/mod.rs (99%) rename backend/crates/gateway-api/tests/{openai => data_plane}/responses/request.rs (98%) rename backend/crates/gateway-api/tests/{openai => data_plane}/responses/websocket/connection/middleware.rs (97%) rename backend/crates/gateway-api/tests/{openai => data_plane}/responses/websocket/connection/mod.rs (99%) rename backend/crates/gateway-api/tests/{openai => data_plane}/responses/websocket/connection/transport.rs (100%) rename backend/crates/gateway-api/tests/{openai => data_plane}/responses/websocket/forward.rs (99%) rename backend/crates/gateway-api/tests/{openai => data_plane}/responses/websocket/interrupt.rs (99%) rename backend/crates/gateway-api/tests/{openai => data_plane}/responses/websocket/mod.rs (99%) rename backend/crates/gateway-api/tests/{openai => data_plane}/responses/websocket/protocol.rs (97%) rename backend/crates/gateway-api/tests/{openai => data_plane}/router.rs (100%) create mode 100644 backend/crates/gateway-api/tests/data_plane/search/http.rs rename backend/crates/gateway-api/tests/{openai => data_plane}/search/mod.rs (52%) rename backend/crates/gateway-api/tests/{openai => data_plane}/usage.rs (98%) create mode 100644 backend/crates/gateway-core/src/provider_ports/session_affinity.rs create mode 100644 backend/crates/gateway-core/tests/error/contract.rs create mode 100644 backend/crates/gateway-core/tests/error/details.rs create mode 100644 backend/crates/gateway-core/tests/error/source.rs create mode 100644 backend/crates/gateway-core/tests/policy/client_version.rs create mode 100644 backend/crates/gateway-core/tests/policy/contract.rs create mode 100644 backend/crates/gateway-core/tests/provider_ports/affinity.rs create mode 100644 backend/crates/gateway-core/tests/provider_ports/lease.rs create mode 100644 backend/crates/gateway-core/tests/provider_ports/oauth.rs create mode 100644 backend/crates/gateway-core/tests/provider_ports/refresh.rs create mode 100644 backend/crates/gateway-core/tests/provider_ports/runtime_policy.rs create mode 100644 backend/crates/gateway-core/tests/provider_ports/session_affinity.rs create mode 100644 backend/crates/gateway-host/src/system_update/swap/mod.rs rename backend/crates/gateway-host/src/system_update/{swap_paths.rs => swap/paths.rs} (100%) rename backend/crates/gateway-host/src/system_update/{swap.rs => swap/release.rs} (98%) create mode 100644 backend/crates/gateway-host/tests/system_update/swap/mod.rs rename backend/crates/gateway-host/tests/system_update/{swap_paths.rs => swap/paths.rs} (98%) rename backend/crates/gateway-plugin/runtime/src/callback/{http_dispatch.rs => http/dispatch.rs} (86%) rename backend/crates/gateway-plugin/runtime/src/callback/{http_middleware => http/middleware}/mod.rs (98%) rename backend/crates/gateway-plugin/runtime/src/callback/{http_middleware => http/middleware}/resources.rs (100%) rename backend/crates/gateway-plugin/runtime/src/callback/{http_middleware => http/middleware}/websocket.rs (100%) create mode 100644 backend/crates/gateway-plugin/runtime/src/callback/http/mod.rs rename backend/crates/gateway-plugin/runtime/src/callback/{http.rs => http/outbound.rs} (90%) rename backend/crates/gateway-plugin/runtime/src/{adapter/upstream_adapter/target.rs => upstream_target.rs} (91%) create mode 100644 backend/crates/gateway-plugin/runtime/tests/generation/policy/facts/contract.rs create mode 100644 backend/crates/gateway-plugin/runtime/tests/generation/policy/http/websocket/contract.rs create mode 100644 backend/crates/gateway-plugin/runtime/tests/generation/policy/service/contract.rs create mode 100644 backend/crates/gateway-plugin/runtime/tests/generation/policy/websocket/contract.rs create mode 100644 backend/crates/gateway-protocol/src/capabilities.rs create mode 100644 backend/crates/gateway-protocol/src/genai/messages.rs create mode 100644 backend/crates/gateway-protocol/src/genai/mod.rs create mode 100644 backend/crates/gateway-protocol/src/genai/request.rs create mode 100644 backend/crates/gateway-protocol/src/genai/response.rs create mode 100644 backend/crates/gateway-protocol/src/genai/stream.rs create mode 100644 backend/crates/gateway-protocol/src/genai/tokens.rs create mode 100644 backend/crates/gateway-protocol/tests/genai/messages.rs create mode 100644 backend/crates/gateway-protocol/tests/genai/mod.rs create mode 100644 backend/crates/gateway-protocol/tests/genai/response.rs create mode 100644 backend/crates/gateway-protocol/tests/genai/tokens.rs rename backend/crates/gateway-store/src/postgres/{client_budget_buffer.rs => client_budgets/buffer.rs} (99%) create mode 100644 backend/crates/gateway-store/src/postgres/client_budgets/mod.rs rename backend/crates/gateway-store/src/postgres/{client_budgets.rs => client_budgets/store.rs} (97%) rename backend/crates/gateway-store/src/postgres/{client_budget_windows.rs => client_budgets/windows.rs} (96%) rename backend/crates/gateway-store/src/postgres/provider_accounts/{quota.rs => quota/document.rs} (91%) rename backend/crates/gateway-store/src/postgres/provider_accounts/{quota_forecast.rs => quota/forecast.rs} (80%) rename backend/crates/gateway-store/src/postgres/provider_accounts/{quota_history.rs => quota/history.rs} (97%) create mode 100644 backend/crates/gateway-store/src/postgres/provider_accounts/quota/mod.rs rename backend/crates/gateway-store/src/postgres/provider_accounts/{quota_warmup.rs => quota/warmup.rs} (94%) rename backend/crates/gateway-store/tests/postgres/{client_budget_buffer.rs => client_budgets/buffer.rs} (99%) create mode 100644 backend/crates/gateway-store/tests/postgres/client_budgets/mod.rs rename backend/crates/gateway-store/tests/postgres/{client_budgets.rs => client_budgets/store.rs} (92%) rename backend/crates/gateway-store/tests/postgres/{client_budget_windows.rs => client_budgets/windows.rs} (99%) rename backend/crates/gateway-store/tests/postgres/provider_accounts/{quota.rs => quota/document.rs} (83%) rename backend/crates/gateway-store/tests/postgres/provider_accounts/{quota_forecast.rs => quota/forecast.rs} (98%) rename backend/crates/gateway-store/tests/postgres/provider_accounts/{quota_history.rs => quota/history.rs} (99%) create mode 100644 backend/crates/gateway-store/tests/postgres/provider_accounts/quota/mod.rs create mode 100644 backend/crates/gateway-store/tests/postgres/provider_accounts/quota/warmup.rs create mode 100644 backend/crates/providers/antigravity/Cargo.toml create mode 100644 backend/crates/providers/antigravity/src/admin/mod.rs create mode 100644 backend/crates/providers/antigravity/src/admin/provider.rs create mode 100644 backend/crates/providers/antigravity/src/billing/calculate.rs create mode 100644 backend/crates/providers/antigravity/src/billing/catalog.rs create mode 100644 backend/crates/providers/antigravity/src/billing/mod.rs create mode 100644 backend/crates/providers/antigravity/src/credential/authorization.rs create mode 100644 backend/crates/providers/antigravity/src/credential/catalog.rs create mode 100644 backend/crates/providers/antigravity/src/credential/documents.rs create mode 100644 backend/crates/providers/antigravity/src/credential/mod.rs create mode 100644 backend/crates/providers/antigravity/src/credential/oauth.rs create mode 100644 backend/crates/providers/antigravity/src/credential/quota/document.rs create mode 100644 backend/crates/providers/antigravity/src/credential/quota/mod.rs create mode 100644 backend/crates/providers/antigravity/src/credential/quota/service.rs create mode 100644 backend/crates/providers/antigravity/src/credential/refresh.rs create mode 100644 backend/crates/providers/antigravity/src/credential/service.rs create mode 100644 backend/crates/providers/antigravity/src/lib.rs create mode 100644 backend/crates/providers/antigravity/src/profile/archive.rs create mode 100644 backend/crates/providers/antigravity/src/profile/artifact.rs create mode 100644 backend/crates/providers/antigravity/src/profile/mod.rs create mode 100644 backend/crates/providers/antigravity/src/profile/release.rs create mode 100644 backend/crates/providers/antigravity/src/profile/selection.rs create mode 100644 backend/crates/providers/antigravity/src/profile/verification.rs create mode 100644 backend/crates/providers/antigravity/src/profile/view.rs create mode 100644 backend/crates/providers/antigravity/src/provider/affinity.rs create mode 100644 backend/crates/providers/antigravity/src/provider/candidates.rs create mode 100644 backend/crates/providers/antigravity/src/provider/execution.rs create mode 100644 backend/crates/providers/antigravity/src/provider/feedback.rs create mode 100644 backend/crates/providers/antigravity/src/provider/mod.rs create mode 100644 backend/crates/providers/antigravity/src/provider/selection.rs create mode 100644 backend/crates/providers/antigravity/src/provider/translation.rs create mode 100644 backend/crates/providers/antigravity/src/provider/workers.rs create mode 100644 backend/crates/providers/antigravity/src/transport/account.rs create mode 100644 backend/crates/providers/antigravity/src/transport/client.rs create mode 100644 backend/crates/providers/antigravity/src/transport/count.rs create mode 100644 backend/crates/providers/antigravity/src/transport/failure.rs create mode 100644 backend/crates/providers/antigravity/src/transport/headers.rs create mode 100644 backend/crates/providers/antigravity/src/transport/mod.rs create mode 100644 backend/crates/providers/antigravity/src/transport/pool.rs create mode 100644 backend/crates/providers/antigravity/src/transport/response.rs create mode 100644 backend/crates/providers/antigravity/tests/billing/calculate.rs create mode 100644 backend/crates/providers/antigravity/tests/billing/mod.rs create mode 100644 backend/crates/providers/antigravity/tests/credential/catalog.rs create mode 100644 backend/crates/providers/antigravity/tests/credential/documents.rs create mode 100644 backend/crates/providers/antigravity/tests/credential/fixture.rs create mode 100644 backend/crates/providers/antigravity/tests/credential/mod.rs create mode 100644 backend/crates/providers/antigravity/tests/credential/oauth.rs create mode 100644 backend/crates/providers/antigravity/tests/credential/quota/mod.rs create mode 100644 backend/crates/providers/antigravity/tests/credential/quota/service.rs create mode 100644 backend/crates/providers/antigravity/tests/main.rs create mode 100644 backend/crates/providers/antigravity/tests/profile/archive.rs create mode 100644 backend/crates/providers/antigravity/tests/profile/artifact.rs create mode 100644 backend/crates/providers/antigravity/tests/profile/mod.rs create mode 100644 backend/crates/providers/antigravity/tests/profile/release.rs create mode 100644 backend/crates/providers/antigravity/tests/profile/selection.rs create mode 100644 backend/crates/providers/antigravity/tests/profile/verification.rs create mode 100644 backend/crates/providers/antigravity/tests/provider/affinity.rs create mode 100644 backend/crates/providers/antigravity/tests/provider/execution.rs create mode 100644 backend/crates/providers/antigravity/tests/provider/headers.rs create mode 100644 backend/crates/providers/antigravity/tests/provider/middleware.rs create mode 100644 backend/crates/providers/antigravity/tests/provider/mod.rs create mode 100644 backend/crates/providers/antigravity/tests/provider/round_robin.rs create mode 100644 backend/crates/providers/antigravity/tests/provider/selection.rs create mode 100644 backend/crates/providers/antigravity/tests/support/mod.rs create mode 100644 backend/crates/providers/antigravity/tests/support/ports.rs create mode 100644 backend/crates/providers/antigravity/tests/support/profile.rs create mode 100644 backend/crates/providers/antigravity/tests/transport/client.rs create mode 100644 backend/crates/providers/antigravity/tests/transport/count.rs create mode 100644 backend/crates/providers/antigravity/tests/transport/mod.rs create mode 100644 backend/crates/providers/antigravity/tests/transport/pool.rs create mode 100644 backend/crates/providers/openai/src/admin/credentials.rs create mode 100644 backend/crates/providers/openai/src/admin/error.rs create mode 100644 backend/crates/providers/openai/src/admin/pending.rs create mode 100644 backend/crates/providers/openai/src/admin/profile.rs create mode 100644 backend/crates/providers/openai/src/admin/provider.rs rename backend/crates/providers/openai/src/{transport => }/automatic_context.rs (94%) create mode 100644 backend/crates/providers/openai/src/billing/calculate.rs create mode 100644 backend/crates/providers/openai/src/billing/catalog.rs create mode 100644 backend/crates/providers/openai/src/billing/images.rs create mode 100644 backend/crates/providers/openai/src/billing/mod.rs rename backend/crates/providers/openai/src/{transport => }/profile/baseline.rs (100%) rename backend/crates/providers/openai/src/{transport => }/profile/cli_release.rs (100%) rename backend/crates/providers/openai/src/{transport => }/profile/context.rs (96%) rename backend/crates/providers/openai/src/{transport => }/profile/desktop_artifact.rs (100%) rename backend/crates/providers/openai/src/{transport => }/profile/identity.rs (97%) create mode 100644 backend/crates/providers/openai/src/profile/mod.rs rename backend/crates/providers/openai/src/{transport => }/profile/platform_release/artifact.rs (100%) rename backend/crates/providers/openai/src/{transport => }/profile/platform_release/mod.rs (100%) rename backend/crates/providers/openai/src/{transport => }/profile/platform_release/range.rs (100%) rename backend/crates/providers/openai/src/{transport => }/profile/platform_release/xz.rs (100%) rename backend/crates/providers/openai/src/{transport/profile/mod.rs => profile/release.rs} (65%) rename backend/crates/providers/openai/src/{transport => }/profile/selection.rs (98%) create mode 100644 backend/crates/providers/openai/src/profile/state.rs rename backend/crates/providers/openai/src/transport/{client.rs => client/backend.rs} (88%) rename backend/crates/providers/openai/src/transport/{client_catalog.rs => client/catalog.rs} (83%) rename backend/crates/providers/openai/src/transport/{client_json.rs => client/json.rs} (87%) rename backend/crates/providers/openai/src/transport/{client_live.rs => client/live.rs} (94%) rename backend/crates/providers/openai/src/transport/{client_messages.rs => client/messages.rs} (91%) create mode 100644 backend/crates/providers/openai/src/transport/client/mod.rs rename backend/crates/providers/openai/src/transport/{client_stream.rs => client/stream.rs} (97%) create mode 100644 backend/crates/providers/openai/tests/admin/provider.rs create mode 100644 backend/crates/providers/openai/tests/billing/calculate.rs create mode 100644 backend/crates/providers/openai/tests/billing/mod.rs create mode 100644 backend/crates/providers/openai/tests/credential/catalog/contract.rs create mode 100644 backend/crates/providers/openai/tests/credential/catalog/refresh.rs rename backend/crates/providers/openai/tests/{transport => }/profile/cli_release.rs (94%) rename backend/crates/providers/openai/tests/{transport => }/profile/desktop_artifact.rs (98%) rename backend/crates/providers/openai/tests/{transport => }/profile/identity.rs (96%) create mode 100644 backend/crates/providers/openai/tests/profile/mod.rs rename backend/crates/providers/openai/tests/{transport => }/profile/platform_release/artifact.rs (99%) rename backend/crates/providers/openai/tests/{transport => }/profile/platform_release/mod.rs (97%) rename backend/crates/providers/openai/tests/{transport => }/profile/platform_release/range.rs (98%) rename backend/crates/providers/openai/tests/{transport => }/profile/platform_release/xz.rs (97%) rename backend/crates/providers/openai/tests/{transport/profile/mod.rs => profile/release.rs} (52%) rename backend/crates/providers/openai/tests/{transport => }/profile/selection.rs (95%) create mode 100644 backend/crates/providers/openai/tests/profile/state.rs rename backend/crates/providers/openai/tests/transport/{client.rs => client/backend.rs} (100%) create mode 100644 backend/crates/providers/openai/tests/transport/client/mod.rs create mode 100644 backend/crates/providers/openai/tests/transport/diagnostics/contract.rs create mode 100644 backend/crates/providers/openai/tests/transport/diagnostics/evidence.rs create mode 100644 backend/crates/providers/openai/tests/transport/websocket/pool/contract.rs create mode 100644 backend/crates/providers/xai/src/admin/credentials.rs create mode 100644 backend/crates/providers/xai/src/admin/error.rs create mode 100644 backend/crates/providers/xai/src/admin/mod.rs create mode 100644 backend/crates/providers/xai/src/admin/pending.rs create mode 100644 backend/crates/providers/xai/src/admin/profile.rs rename backend/crates/providers/xai/src/{admin.rs => admin/provider.rs} (55%) create mode 100644 backend/crates/providers/xai/src/admin/quota.rs create mode 100644 backend/crates/providers/xai/src/billing/calculate.rs create mode 100644 backend/crates/providers/xai/src/billing/catalog.rs create mode 100644 backend/crates/providers/xai/src/billing/mod.rs create mode 100644 backend/crates/providers/xai/src/profile/mod.rs rename backend/crates/providers/xai/src/{transport/profile.rs => profile/release.rs} (68%) rename backend/crates/providers/xai/src/{transport/client_profile.rs => profile/selection.rs} (98%) create mode 100644 backend/crates/providers/xai/src/profile/state.rs rename backend/crates/providers/xai/tests/{admin.rs => admin/mod.rs} (52%) create mode 100644 backend/crates/providers/xai/tests/admin/provider.rs create mode 100644 backend/crates/providers/xai/tests/admin/quota.rs create mode 100644 backend/crates/providers/xai/tests/billing/calculate.rs create mode 100644 backend/crates/providers/xai/tests/billing/mod.rs create mode 100644 backend/crates/providers/xai/tests/profile/mod.rs create mode 100644 backend/crates/providers/xai/tests/profile/release.rs rename backend/crates/providers/xai/tests/{transport/client_profile.rs => profile/selection.rs} (96%) create mode 100644 backend/crates/providers/xai/tests/profile/state.rs delete mode 100644 backend/crates/providers/xai/tests/transport/profile.rs create mode 100644 backend/migrations/0047_runtime_settings_revision.sql create mode 100644 backend/migrations/0048_general_session_affinity.sql create mode 100644 frontend/src/api/types/request-profile.ts rename frontend/src/components/{account/account-usage-window => }/AccountRequestTimeline.vue (88%) rename frontend/src/{views/key-usage => }/components/KeyUsageBudget.vue (88%) rename frontend/src/components/{usage => }/UsageRecordStatusFilter.vue (94%) rename frontend/src/components/{account/model-access => account-model-access-field}/AccountModelCleanupPopover.vue (100%) rename frontend/src/components/{account/model-access => account-model-access-field}/AccountModelOption.vue (100%) rename frontend/src/components/{account/model-access => account-model-access-field}/index.vue (96%) rename frontend/src/components/{account/model-access/modelAccess.ts => account-model-access-field/validation.ts} (83%) rename frontend/src/components/{account => account-plan-badge}/AccountUpstreamBadge.vue (100%) rename frontend/src/components/{account/AccountPlanBadge.vue => account-plan-badge/index.vue} (80%) rename frontend/src/components/{account => }/account-usage-window/index.vue (91%) rename frontend/src/components/{account => }/account-usage-window/presenter.ts (93%) rename frontend/src/{utils => components/api-key-config-modal}/client.ts (100%) rename frontend/src/components/{ApiKeyConfigModal.vue => api-key-config-modal/index.vue} (97%) rename frontend/src/components/{charts/BaseChart.vue => base-chart/index.vue} (100%) rename frontend/src/components/{charts => base-chart}/timeSeriesGap.ts (100%) rename frontend/src/components/{charts => base-chart}/tooltip.ts (100%) delete mode 100644 frontend/src/components/client-profile/ClientProfileEditor.vue delete mode 100644 frontend/src/components/client-profile/ClientProfilePreviewPanel.vue delete mode 100644 frontend/src/components/client-profile/ProviderRequestProfilesEditor.vue delete mode 100644 frontend/src/components/client-profile/XaiClientProfileEditor.vue rename frontend/src/components/{usage => request-health-timeline-card}/HealthTimelinePointPopover.vue (99%) rename frontend/src/components/{usage/shared => request-health-timeline-card}/health.ts (100%) rename frontend/src/components/{usage/RequestHealthTimelineCard.vue => request-health-timeline-card/index.vue} (98%) create mode 100644 frontend/src/components/request-profile/ProfileEditorFrame.vue create mode 100644 frontend/src/components/request-profile/RequestProfilePreviewPanel.vue create mode 100644 frontend/src/components/request-profile/changes.ts create mode 100644 frontend/src/components/request-profile/index.vue create mode 100644 frontend/src/components/request-profile/useProfileEditor.ts rename frontend/src/components/{usage => usage-records-table}/UsageBillingCell.vue (97%) rename frontend/src/components/{usage => usage-records-table}/UsageClientIpCell.vue (90%) rename frontend/src/components/{usage => usage-records-table}/UsageDetailPopover.vue (100%) rename frontend/src/components/{usage => usage-records-table}/UsageErrorCell.vue (99%) rename frontend/src/components/{usage => usage-records-table}/UsageLatencyCell.vue (95%) rename frontend/src/components/{usage => usage-records-table}/UsageModelCell.vue (90%) rename frontend/src/components/{usage => usage-records-table}/UsagePerformanceCell.vue (85%) create mode 100644 frontend/src/components/usage-records-table/UsagePerformanceHeader.vue rename frontend/src/components/{usage => usage-records-table}/UsageReasoningEffortCell.vue (89%) rename frontend/src/components/{usage => usage-records-table}/UsageRouteCell.vue (57%) rename frontend/src/components/{usage => usage-records-table}/UsageTimeCell.vue (100%) rename frontend/src/components/{usage => usage-records-table}/UsageTokenCell.vue (89%) rename frontend/src/components/{usage => usage-records-table}/UsageTransportBadge.vue (82%) rename frontend/src/components/{usage => usage-records-table}/UsageTransportCell.vue (94%) rename frontend/src/components/{usage/shared => usage-records-table}/columns.ts (95%) rename frontend/src/components/{usage/shared => usage-records-table}/errors.ts (98%) rename frontend/src/components/{usage/UsageRecordsTable.vue => usage-records-table/index.vue} (81%) rename frontend/src/components/{usage/shared => usage-records-table}/presenter.ts (91%) delete mode 100644 frontend/src/composables/useLocale.ts delete mode 100644 frontend/src/i18n/ui.ts rename frontend/src/{utils => plugins}/notification.ts (76%) create mode 100644 frontend/src/providers/accounts.ts create mode 100644 frontend/src/providers/antigravity/request-profile/AntigravityRequestProfileEditor.vue create mode 100644 frontend/src/providers/antigravity/request-profile/profile.ts rename frontend/src/{utils/providers.ts => providers/catalog.ts} (59%) rename frontend/src/{views/accounts/components/AccountApiKeyFields.vue => providers/openai/accounts/ApiKeyFields.vue} (70%) create mode 100644 frontend/src/providers/openai/accounts/OpenAiAccountConnectionEditor.vue create mode 100644 frontend/src/providers/openai/accounts/OpenAiApiKeyImportForm.vue rename frontend/src/{views/accounts/utils/upstreamApiKey.ts => providers/openai/accounts/connection.ts} (64%) create mode 100644 frontend/src/providers/openai/accounts/import.ts rename frontend/src/{views/accounts/composables/useAccountApiKeyFormRules.ts => providers/openai/accounts/useApiKeyFormRules.ts} (84%) create mode 100644 frontend/src/providers/openai/accounts/useConnectionEditor.ts rename frontend/src/{views/keys/components/ApiKeyInstallationSeedField.vue => providers/openai/request-profile/InstallationSeedField.vue} (100%) create mode 100644 frontend/src/providers/openai/request-profile/OpenAiRequestProfileEditor.vue rename frontend/src/{components/client-profile/ClientProfilePresetFields.vue => providers/openai/request-profile/ProfileFields.vue} (78%) create mode 100644 frontend/src/providers/openai/request-profile/installationSeed.ts create mode 100644 frontend/src/providers/openai/request-profile/profile.ts create mode 100644 frontend/src/providers/xai/request-profile/XaiRequestProfileEditor.vue create mode 100644 frontend/src/providers/xai/request-profile/profile.ts rename frontend/src/{utils => router}/plugin.ts (100%) rename frontend/src/{components/account => views/accounts/components}/AccountQuotaWindowDetails.vue (97%) rename frontend/src/views/accounts/components/{ => account-concurrency-modal}/AccountConcurrencyTable.vue (96%) rename frontend/src/views/accounts/components/{AccountConcurrencyModal.vue => account-concurrency-modal/index.vue} (92%) rename frontend/src/views/accounts/{composables => components/account-concurrency-modal}/useAccountConcurrency.ts (100%) rename frontend/src/views/accounts/{composables => components/account-profile-modal}/useAccountPersonalInfo.ts (97%) rename frontend/src/views/accounts/components/{ => account-proxy-field}/AccountProxyTestBadge.vue (100%) rename frontend/src/views/accounts/components/{AccountProxyField.vue => account-proxy-field/index.vue} (98%) rename frontend/src/views/accounts/{composables => components/account-proxy-field}/useAccountProxyTest.ts (97%) rename frontend/src/views/accounts/{composables => components/account-quota-forecast-modal}/useAccountQuotaForecast.ts (96%) rename frontend/src/views/accounts/{composables => components/account-quota-panel}/useAccountResetCredits.ts (99%) rename frontend/src/views/accounts/{composables => components/account-quota-panel}/usePoolQuotaWindows.ts (100%) rename frontend/src/{ => views/accounts}/utils/account-upstream.ts (100%) delete mode 100644 frontend/src/views/dashboard/components/DashboardContent.vue create mode 100644 frontend/src/views/dashboard/components/DashboardOverview.vue rename frontend/src/views/dashboard/components/{ => account-overview}/DashboardAccountIdentity.vue (89%) rename frontend/src/views/dashboard/components/{AccountOverviewCard.vue => account-overview/index.vue} (97%) rename frontend/src/views/dashboard/components/{ => dashboard-metrics}/MetricCard.vue (96%) create mode 100644 frontend/src/views/dashboard/components/dashboard-metrics/cards.ts create mode 100644 frontend/src/views/dashboard/components/dashboard-metrics/index.vue rename frontend/src/views/dashboard/components/{RequestTrendCard.vue => request-trend/index.vue} (78%) create mode 100644 frontend/src/views/dashboard/components/request-trend/series.ts rename frontend/src/views/dashboard/{composables => components/request-trend}/useRequestTrendChart.ts (96%) create mode 100644 frontend/src/views/dashboard/components/wire-profile/identity.ts rename frontend/src/views/dashboard/components/{WireProfileCard.vue => wire-profile/index.vue} (75%) delete mode 100644 frontend/src/views/dashboard/presenter.ts create mode 100644 frontend/src/views/dashboard/utils/format.ts delete mode 100644 frontend/src/views/key-usage/utils/format.ts delete mode 100644 frontend/src/views/plugins/components/PluginManagement.vue rename frontend/src/views/plugins/components/{ => plugin-management-frame}/PluginExternalLinkDialog.vue (100%) rename frontend/src/views/plugins/{management => components/plugin-management-frame}/bridge-contract.ts (100%) rename frontend/src/views/plugins/{management => components/plugin-management-frame}/bridge-models.ts (100%) rename frontend/src/views/plugins/{management => components/plugin-management-frame}/bridge-runtime.ts (100%) rename frontend/src/views/plugins/{management => components/plugin-management-frame}/frame.ts (100%) rename frontend/src/views/plugins/components/{PluginManagementFrame.vue => plugin-management-frame/index.vue} (95%) rename frontend/src/views/plugins/{management => components/plugin-management-frame}/model-streams.ts (100%) rename frontend/src/views/plugins/{composables => components/plugin-management-frame}/usePluginFrameSession.ts (98%) rename frontend/src/views/plugins/{components/PluginPage.vue => page/index.vue} (94%) rename frontend/src/views/proxies/components/{ => proxy-accounts-modal}/ProxyAssignAccountsModal.vue (97%) rename frontend/src/views/proxies/components/{ProxyAccountsModal.vue => proxy-accounts-modal/index.vue} (98%) rename frontend/src/views/proxies/{composables => components/proxy-accounts-modal}/useProxyAccountAssignment.ts (97%) rename frontend/src/views/proxies/{composables => components/proxy-accounts-modal}/useProxyAccounts.ts (97%) rename frontend/src/views/proxies/components/{ => proxy-form-modal}/ProxyBatchCreateFields.vue (96%) rename frontend/src/views/proxies/components/{ => proxy-form-modal}/ProxyBatchResults.vue (97%) rename frontend/src/views/proxies/components/{ProxyFormModal.vue => proxy-form-modal/index.vue} (98%) rename frontend/src/views/proxies/{composables => components/proxy-form-modal}/useProxyBatchCreate.ts (95%) delete mode 100644 frontend/src/views/settings/components/ClientProfileCard.vue create mode 100644 frontend/src/views/settings/components/GuardianReviewCard.vue create mode 100644 frontend/src/views/settings/components/ProviderSettingsNav.vue create mode 100644 frontend/src/views/settings/components/RequestProfileCard.vue create mode 100644 frontend/src/views/settings/components/RetryPolicyCard.vue rename frontend/src/views/settings/components/backup/{SettingsBackupSection.vue => index.vue} (81%) rename frontend/src/views/settings/{composables => components/backup}/useBackupRecords.ts (98%) rename frontend/src/views/settings/{composables => components/backup}/useBackupSettings.ts (83%) rename frontend/src/views/settings/components/client-version/{components => }/ClientCliInstallPanel.vue (100%) rename frontend/src/views/settings/components/client-version/{components => }/ClientDesktopInstallPanel.vue (100%) rename frontend/src/views/settings/components/client-version/{components => }/ClientDesktopOfflineDownloads.vue (100%) rename frontend/src/views/settings/components/client-version/{components => }/ClientInstallCommandList.vue (100%) rename frontend/src/views/settings/components/client-version/{components => }/ClientVersionGuideModal.vue (100%) rename frontend/src/views/settings/components/client-version/{components => }/ClientVersionPolicyCard.vue (93%) rename frontend/src/views/settings/components/client-version/{composables => }/useClientDownloads.ts (100%) rename frontend/src/views/settings/components/error-protection/{AccountErrorProtectionCard.vue => index.vue} (94%) rename frontend/src/views/settings/components/error-protection/{form.ts => policy.ts} (98%) rename frontend/src/views/settings/{ => components}/pricing/PricingBatchModal.vue (100%) rename frontend/src/views/settings/{ => components}/pricing/PricingEditor.vue (96%) rename frontend/src/views/settings/{ => components}/pricing/PricingRateFields.vue (100%) rename frontend/src/views/settings/{ => components}/pricing/PricingSyncModal.vue (69%) rename frontend/src/views/settings/{ => components}/pricing/PricingTable.vue (100%) rename frontend/src/views/settings/{ => components}/pricing/PricingToolbar.vue (98%) rename frontend/src/views/settings/{ => components}/pricing/PricingUnit.vue (100%) rename frontend/src/views/settings/{ => components}/pricing/index.vue (88%) rename frontend/src/views/settings/{ => components}/pricing/model.ts (91%) rename frontend/src/views/settings/{ => components}/pricing/usePricing.ts (92%) rename frontend/src/views/settings/components/privacy/{PrivacyPolicyCard.vue => index.vue} (98%) rename frontend/src/views/settings/{composables => components/privacy}/usePrivacyPreview.ts (88%) rename frontend/src/views/settings/components/{ => settings-access}/AdminApiKeyCard.vue (98%) rename frontend/src/views/settings/components/{ => settings-access}/AdminPasswordCard.vue (93%) rename frontend/src/views/settings/components/{ => settings-access}/ChangePasswordModal.vue (98%) rename frontend/src/views/settings/components/{ => settings-access}/ResponseBodyLimitCard.vue (82%) rename frontend/src/views/settings/components/{SettingsAccessSection.vue => settings-access/index.vue} (85%) rename frontend/src/views/settings/{composables => components/settings-access}/useAdminApiKey.ts (96%) rename frontend/src/views/theme/components/{ => theme-preview-canvas}/ThemePreviewScope.vue (100%) rename frontend/src/views/theme/components/{ThemePreviewCanvas.vue => theme-preview-canvas/index.vue} (97%) rename frontend/src/views/theme/{composables => components/theme-preview-canvas}/useThemePreviewCanvas.ts (100%) diff --git a/.agents/skills/cpr-dev-guide/SKILL.md b/.agents/skills/cpr-dev-guide/SKILL.md index cd72f6a81..7ad6d1f41 100644 --- a/.agents/skills/cpr-dev-guide/SKILL.md +++ b/.agents/skills/cpr-dev-guide/SKILL.md @@ -31,7 +31,8 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与 | 开发、排查或审查服务端接口、路由、调度、账号与用量规则、持久化、后台任务或协议行为;目标是 `backend/` 中的实现、配置、迁移,或 Rust 源码 | [Workspace 边界](../../../docs/architecture.md#3-workspace-边界)的模块与依赖规则、所属模块及[后端自审](../../../docs/architecture.md#后端自审);Rust 使用 `$rust-best-practices` 和下方后端注释要求,宿主 Rust 同时读取 [Rust 模块组织约定](../../../docs/architecture.md#32-rust-模块组织约定) | | 修改页面接口调用,或开发、排查、审查面向管理端或模型客户端的 HTTP/WS API 合同 | [API](../../../docs/api.md)对应章节;优先复用已有接口,核对调用方 → 服务端解析 → 实际查询或执行,不能只凭前端类型认定参数生效;按实际改动叠加前后端规范 | | 新增、修改或审查客户端可见错误、失败提示、后台任务状态文案 | 下方[错误文案](#错误文案),并按实际出口核对[错误与诊断三层边界](../../../docs/architecture.md#错误与诊断三层边界) | -| 模块或调用链变更 | [Workspace 边界](../../../docs/architecture.md#3-workspace-边界)及所属模块章节,不通读整份架构 | +| 模块或调用链变更,包括目录整理 | [Workspace 边界](../../../docs/architecture.md#3-workspace-边界)及所属模块章节;并排核对任务范围内同类实现的职责归属、公开入口与依赖方向,再决定目录与共享合同的位置 | +| 新增内置 Provider、接入客户端协议,或让已有入口支持另一种实现 | 对照[Provider 与协议边界](../../../docs/architecture.md#5-provider-与协议边界),并排追踪新旧实现从入口到执行的路径。沿用目录或类型前,确认名称仍能描述扩展后的职责。共享层按厂商分支时,核实哪个接口合同指定了上游。按能力选择时,核对谁声明能力、谁匹配候选,用同名模型支持不同协议等场景验证。涉及选号时,对照已有实现的满载与取消行为 | | 新增、调整、清理或审查测试 | 下方[测试维护](#测试维护),按当前行为、职责归属与已有覆盖判断保留、合并或删除 | | 修改部署行为、`deploy/` 配置或数据库迁移 | 按范围读取[部署](../../../deploy/README.md)、[迁移](../../../backend/migrations/README.md)对应章节 | | 修改或审查文档;实现或审查用法、公开合同、职责、约束或运维操作的变化 | [文档检查](references/documentation.md),按最终行为核对是否漏更;纯文档任务只补读核实所述事实需要的领域条款 | @@ -42,7 +43,7 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与 1. 遵守已提供的 [AGENTS.md](../../../AGENTS.md),按其 CodeGraph 约定定位代码;确认工作区、任务范围与已有改动,找到事实归属、同类实现和调用链,补齐上表命中规范及[项目约定](../../../CONTRIBUTING.md#项目约定)对应条目后再修改 2. 以最终差异重新匹配上表,补齐新增领域的规范并检查实际实现,再处理本次引入的职责越界、重复规则、冗余状态与无依据分支;删除或替换功能时一并清理失效的配置、类型、调用、测试与文档,已部署数据和公开合同仍遵守所属迁移及兼容规则;仅审查时报告,不自行修复 -3. 在本任务内同步受影响的文档、示例和引用 +3. 模块移动或重命名时,同步核对源码、测试、公开导出及配置、脚本中的名称和路径引用;在本任务内更新受影响的文档、示例和引用 4. 按变更范围执行[验证](../../../CONTRIBUTING.md#验证)及其停止条件,后端命令见[验证命令](../../../docs/architecture.md#验证命令);复用仍适用的验证证据与用户已确定的验收分工,区分通过、失败、跳过与未执行 5. 交付前按[首要写作要求](#首要写作要求言简意赅)通读本次新增或修改的文字。交代实际结果与验证缺口;前端按[前端流程](references/frontend.md)核对运行证据,后端按上表检查生命周期,不把构建通过当作行为验收 6. 按授权完成提交与交付;提交前按[提交约定](../../../CONTRIBUTING.md#项目约定)准备提交信息与实际共同作者署名,提交后核对实际提交消息,PR 的 AI 披露不能替代提交署名 @@ -50,9 +51,11 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与 ## 测试维护 - 测试随当前功能维护,名称、夹具和断言描述当前输入、行为与结果;功能变更时优先更新所属模块的现有用例,不为每次改动叠加一组记录变更经过的测试 +- 移动或重命名测试时,核对受影响的场景覆盖是否保留;涉及子进程调用或名称过滤时,同步更新调用入口并实际运行,确认目标用例确实执行且行为断言通过 - 清理只证明旧字段、旧路由或旧实现已经消失的用例与附带断言;未知字段校验使用合法请求基线加无业务含义的未知字段,避免因缺少必填项等其他错误而误通过 - 同一层对同一行为的重复覆盖合并为清晰的场景矩阵,复用相邻测试夹具;跨层测试确有不同职责或失败路径时保留,不为统一而扩大测试辅助抽象 -- 断言可观察的行为与业务不变量,避免复述结构体赋值、罗列表列或字段清单、匹配 SQL 文本与源码布局;项目明确要求的架构边界检查继续维护 +- 断言可观察的行为与业务不变量,避免复述结构体赋值、罗列表列或字段清单、匹配 SQL 文本与源码布局 +- 维护项目明确要求的架构边界检查;发现漏检时,对照规则核实扫描范围、排除项与被检查的依赖关系,优先补齐现有检查中能稳定判定的缺口 - 当前协议兼容、数据读取兼容、安全边界、并发和资源生命周期仍需覆盖,不按 `old`、`legacy` 等名称机械删除,也不能用改名代替无效用例清理 - 不在仓库中新增或保留迁移 SQL 专项测试,包括迁移文本、schema 演变与指定版本升级用例;需要验证迁移执行、数据保留或回滚时,在临时目录编写一次性验证并使用隔离数据库,测试通过即可,临时脚本不纳入维护测试集 - 持久化功能测试使用当前完整 schema,验证现行读写、事务与数据约束;插件运行时状态迁移等业务能力按当前功能测试,不归为迁移 SQL 专项测试 diff --git a/.agents/skills/cpr-dev-guide/references/frontend.md b/.agents/skills/cpr-dev-guide/references/frontend.md index 19e4039c3..272f43768 100644 --- a/.agents/skills/cpr-dev-guide/references/frontend.md +++ b/.agents/skills/cpr-dev-guide/references/frontend.md @@ -35,6 +35,8 @@ - **核对位置与对齐**时,结合周围内容查看实际页面或 PR 截图,确认操作归属一眼可辨,对照相邻行列检查边缘、文字基线和组间留白。发现错位时指出具体控件、对齐参照和受影响的状态 - **精简文案**,删去重复说明,压短必要提示,检查自写文案中的句号和分号 - **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确 +- **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置 +- **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属 - **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,核对 loading、禁用状态的影响范围;沿用请求层错误处理,不在页面叠加同一错误的提示 - **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行 diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 2cb522b3d..68b0eba6f 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -921,6 +921,7 @@ dependencies = [ "gateway-host", "gateway-plugin-runtime", "gateway-store", + "provider-antigravity", "provider-openai", "provider-xai", "serde", @@ -3376,6 +3377,42 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "provider-antigravity" +version = "0.0.0" +dependencies = [ + "async-compression", + "async-stream", + "async-trait", + "base64 0.23.1", + "bytes", + "chrono", + "flate2", + "futures", + "gateway-admin", + "gateway-core", + "gateway-egress", + "gateway-protocol", + "getrandom 0.4.3", + "hex", + "http", + "http-body-util", + "reqwest", + "serde", + "serde_json", + "sha2", + "tar", + "tempfile", + "thiserror", + "tokio", + "tokio-util", + "tracing", + "url", + "uuid", + "wiremock", + "zip", +] + [[package]] name = "provider-openai" version = "0.0.0" @@ -5108,6 +5145,7 @@ dependencies = [ "idna", "percent-encoding", "serde", + "serde_derive", ] [[package]] diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 3dc801f16..dee1eac83 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -11,6 +11,7 @@ members = [ "crates/gateway-plugin/sdk", "crates/gateway-protocol", "crates/gateway-store", + "crates/providers/antigravity", "crates/providers/openai", "crates/providers/xai", ] diff --git a/backend/apps/gateway/Cargo.toml b/backend/apps/gateway/Cargo.toml index 305e739e3..59bc02708 100644 --- a/backend/apps/gateway/Cargo.toml +++ b/backend/apps/gateway/Cargo.toml @@ -18,6 +18,7 @@ gateway-core = { path = "../../crates/gateway-core" } gateway-host = { path = "../../crates/gateway-host" } gateway-plugin-runtime = { path = "../../crates/gateway-plugin/runtime" } gateway-store = { path = "../../crates/gateway-store" } +provider-antigravity = { path = "../../crates/providers/antigravity" } provider-openai = { path = "../../crates/providers/openai" } provider-xai = { path = "../../crates/providers/xai" } serde = { version = "1.0.228", features = ["derive"] } diff --git a/backend/apps/gateway/src/bootstrap/mod.rs b/backend/apps/gateway/src/bootstrap/mod.rs index 2505a9260..2ba1f7e4e 100644 --- a/backend/apps/gateway/src/bootstrap/mod.rs +++ b/backend/apps/gateway/src/bootstrap/mod.rs @@ -32,6 +32,8 @@ pub enum BootstrapError { #[error(transparent)] Xai(#[from] provider_xai::XaiInitializeError), #[error(transparent)] + Antigravity(#[from] provider_antigravity::ConfigError), + #[error(transparent)] Registry(#[from] gateway_core::engine::provider::RegistryError), #[error(transparent)] Core(#[from] gateway_core::CoreError), diff --git a/backend/apps/gateway/src/bootstrap/server.rs b/backend/apps/gateway/src/bootstrap/server.rs index 61e5fc387..2cf5bab72 100644 --- a/backend/apps/gateway/src/bootstrap/server.rs +++ b/backend/apps/gateway/src/bootstrap/server.rs @@ -174,8 +174,7 @@ pub async fn run() -> Result<(), BootstrapError> { gateway_host::retention::worker(store.retention()) )); plan.extend(core.take_worker_contributions()); - plan.extend(providers.openai.take_worker_contributions()); - plan.extend(providers.xai.take_worker_contributions()); + plan.extend(providers.workers); plan.extend(admin.take_worker_contributions()); plan.extend(providers.peer.take_worker_contributions()); plan.push(or_shutdown!( diff --git a/backend/apps/gateway/src/bootstrap/startup.rs b/backend/apps/gateway/src/bootstrap/startup.rs index e1ba0e60f..09863fd92 100644 --- a/backend/apps/gateway/src/bootstrap/startup.rs +++ b/backend/apps/gateway/src/bootstrap/startup.rs @@ -59,8 +59,7 @@ impl Environment { } pub(super) struct Providers { - pub(super) openai: provider_openai::ProviderBundle, - pub(super) xai: provider_xai::ProviderBundle, + pub(super) workers: Vec, pub(super) core: ProviderRegistry, pub(super) admin: ProviderAdminRegistry, pub(super) peer: gateway_admin::PeerUpstreamBundle, @@ -80,11 +79,21 @@ impl Providers { ) .await?; environment.host.report_startup_ready("OpenAI Provider"); + let antigravity = provider_antigravity::initialize(ports.clone())?; + environment + .host + .report_startup_ready("Antigravity Provider"); let xai = provider_xai::initialize(ports).await?; environment.host.report_startup_ready("xAI Provider"); - let core = ProviderRegistry::new([openai.core_provider(), xai.core_provider()])?; - let admin = ProviderAdminRegistry::new([openai.admin_provider(), xai.admin_provider()]) - .map_err(|_| gateway_admin::model::AdminError::invalid("Provider 管理身份冲突"))?; + let bundles = [openai, xai, antigravity]; + let core = ProviderRegistry::new(bundles.iter().map(|bundle| bundle.core.clone()))?; + let admin = + ProviderAdminRegistry::new(bundles.iter().map(|bundle| bundle.admin.clone())) + .map_err(|_| gateway_admin::model::AdminError::invalid("Provider 管理身份冲突"))?; + let workers = bundles + .into_iter() + .flat_map(|bundle| bundle.workers) + .collect(); let peer = gateway_admin::initialize_peer_upstream( environment.store.provider_ports().accounts(), &admin, @@ -98,8 +107,7 @@ impl Providers { .map_err(|_| gateway_admin::model::AdminError::invalid("互联观测端口重复绑定"))?; Ok(Self { peer, - openai, - xai, + workers, core, admin, }) diff --git a/backend/apps/gateway/tests/architecture.rs b/backend/apps/gateway/tests/architecture.rs index 2001e4b2f..037436fb6 100644 --- a/backend/apps/gateway/tests/architecture.rs +++ b/backend/apps/gateway/tests/architecture.rs @@ -22,6 +22,7 @@ pub(super) const WORKSPACE_MEMBERS: &[&str] = &[ "crates/gateway-plugin/sdk", "crates/gateway-protocol", "crates/gateway-store", + "crates/providers/antigravity", "crates/providers/openai", "crates/providers/xai", ]; @@ -62,6 +63,7 @@ fn gateway_core_depends_on_no_http_db_redis_or_provider_crate() { "redis", "gateway-host", "gateway-store", + "provider-antigravity", "provider-openai", "provider-xai", ], @@ -115,17 +117,50 @@ fn core_value_owners_do_not_depend_on_execution_or_routing() { #[test] fn domain_owner_paths_form_a_dag() { - for member in ["crates/gateway-core", "crates/gateway-admin"] { - assert_owner_paths_form_a_dag(member); + let cycles = WORKSPACE_MEMBERS + .iter() + .flat_map(|member| owner_dependency_cycles(member)) + .collect::>(); + assert!( + cycles.is_empty(), + "owner dependency cycles:\n{}", + cycles.join("\n") + ); +} + +#[test] +fn provider_shared_owners_use_consistent_directories() { + for member in provider_members() { + let root = backend_root().join(member).join("src"); + for owner in [ + "admin", + "billing", + "credential", + "profile", + "provider", + "transport", + ] { + assert!( + root.join(owner).join("mod.rs").is_file(), + "{member} must place its {owner} owner in {owner}/mod.rs", + ); + } } } -fn assert_owner_paths_form_a_dag(member: &str) { +fn provider_members() -> impl Iterator { + WORKSPACE_MEMBERS + .iter() + .copied() + .filter(|member| member.starts_with("crates/providers/")) +} + +fn owner_dependency_cycles(member: &str) -> Vec { let root = backend_root().join(member).join("src"); let reexports = read_root_reexport_owners(&root); let mut graph = BTreeMap::>::new(); for relative in super::rust_files(&root) { - if relative == Path::new("lib.rs") { + if relative == Path::new("lib.rs") || relative == Path::new("main.rs") { continue; } let mut references = CrateReferences::in_module(&relative).with_root_reexports(&reexports); @@ -135,35 +170,52 @@ fn assert_owner_paths_form_a_dag(member: &str) { references.owners.remove(&owner); graph.entry(owner).or_default().extend(references.owners); } + let mut cycles = Vec::new(); for owner in graph.keys() { - let mut pending = graph[owner].iter().cloned().collect::>(); + let mut pending = graph[owner] + .iter() + .map(|dependency| (dependency.clone(), vec![owner.clone()])) + .collect::>(); let mut visited = BTreeSet::new(); - while let Some(dependency) = pending.pop() { - assert_ne!( - &dependency, owner, - "{member} owner dependency cycle reaches {owner}" - ); + while let Some((dependency, mut path)) = pending.pop() { + path.push(dependency.clone()); + if &dependency == owner { + cycles.push(format!("{member}: {}", path.join(" -> "))); + break; + } if visited.insert(dependency.clone()) && let Some(next) = graph.get(&dependency) { - pending.extend(next.iter().cloned()); + pending.extend( + next.iter() + .map(|dependency| (dependency.clone(), path.clone())), + ); } } } + cycles } #[test] fn shared_owners_do_not_depend_on_their_callers() { let boundaries: &[(&str, &str, &[&str])] = &[ - ("crates/providers/xai", "transport", &["credential"]), - ("crates/providers/openai", "transport", &["provider"]), + ( + "crates/providers/xai", + "transport", + &["credential", "provider"], + ), + ( + "crates/providers/openai", + "transport", + &["credential", "provider"], + ), ("crates/gateway-api", "time", &["admin"]), ( "crates/gateway-api", "client_error", - &["admin", "openai", "middleware"], + &["admin", "data_plane", "middleware"], ), - ("crates/gateway-api", "middleware", &["openai"]), + ("crates/gateway-api", "middleware", &["data_plane"]), ("crates/gateway-host", "system_update", &["config"]), ("crates/gateway-plugin/runtime", "package", &["callback"]), ]; @@ -189,6 +241,39 @@ fn shared_owners_do_not_depend_on_their_callers() { } } +#[test] +fn provider_billing_is_private_and_independent_of_other_provider_owners() { + for member in provider_members() { + let root = backend_root().join(member).join("src"); + let source = fs::read_to_string(root.join("lib.rs")).expect("read provider root"); + let syntax = syn::parse_file(&source).expect("parse provider root"); + assert!( + syntax.items.iter().any(|item| matches!(item, + Item::Mod(module) if module.ident == "billing" + && matches!(module.vis, syn::Visibility::Inherited) + )), + "{member} must keep billing behind a private owner", + ); + let reexports = read_root_reexport_owners(&root); + for relative in super::rust_files(&root) { + let mut references = + CrateReferences::in_module(&relative).with_root_reexports(&reexports); + if references.module_path.first().map(String::as_str) != Some("billing") { + continue; + } + let source = fs::read_to_string(root.join(&relative)).expect("read billing source"); + references.visit_file(&syn::parse_file(&source).expect("parse billing source")); + references.owners.remove("billing"); + assert!( + references.owners.is_empty(), + "{member}/src/{} billing must consume explicit facts, not depend on {:?}", + relative.display(), + references.owners, + ); + } + } +} + #[test] fn owner_reference_scan_resolves_groups_reexports_and_relative_paths() { let syntax = syn::parse_file( @@ -252,7 +337,12 @@ fn owner_reference_scan_resolves_crate_root_reexports() { } fn read_root_reexport_owners(root: &Path) -> BTreeMap { - let source = fs::read_to_string(root.join("lib.rs")).expect("read crate root"); + let root_file = if root.join("lib.rs").is_file() { + root.join("lib.rs") + } else { + root.join("main.rs") + }; + let source = fs::read_to_string(root_file).expect("read crate root"); root_reexport_owners(&syn::parse_file(&source).expect("parse crate root")) } @@ -430,8 +520,18 @@ fn plugin_sdk_has_no_workspace_dependencies() { #[test] fn provider_crates_do_not_depend_on_each_other() { - assert_no_dependency("crates/providers/openai", &["provider-xai"]); - assert_no_dependency("crates/providers/xai", &["provider-openai"]); + let providers = PACKAGE_TO_MEMBER + .iter() + .filter(|(_, member)| member.starts_with("crates/providers/")) + .collect::>(); + for (package, member) in &providers { + let forbidden = providers + .iter() + .filter(|(other, _)| other != package) + .map(|(other, _)| *other) + .collect::>(); + assert_no_dependency(member, &forbidden); + } } #[test] @@ -455,6 +555,7 @@ const PACKAGE_TO_MEMBER: &[(&str, &str)] = &[ ("gateway-plugin-sdk", "crates/gateway-plugin/sdk"), ("gateway-protocol", "crates/gateway-protocol"), ("gateway-store", "crates/gateway-store"), + ("provider-antigravity", "crates/providers/antigravity"), ("provider-openai", "crates/providers/openai"), ("provider-xai", "crates/providers/xai"), ]; @@ -463,7 +564,7 @@ const PACKAGE_TO_MEMBER: &[(&str, &str)] = &[ const ADAPTER_PUBLIC_MODULES: &[(&str, &[&str])] = &[ ("crates/gateway-plugin/sdk", &["call", "client"]), ("crates/gateway-plugin/runtime", &[]), - ("crates/gateway-api", &["admin", "auth", "openai"]), + ("crates/gateway-api", &["admin", "auth", "data_plane"]), ( "crates/gateway-host", &[ @@ -485,9 +586,10 @@ const ADAPTER_PUBLIC_MODULES: &[(&str, &[&str])] = &[ ("crates/gateway-store", &["backup", "postgres", "redis"]), ( "crates/providers/openai", - &["config", "credential", "transport"], + &["config", "credential", "profile", "transport"], ), - ("crates/providers/xai", &["transport"]), + ("crates/providers/antigravity", &[]), + ("crates/providers/xai", &["profile", "transport"]), ]; /// 不对应单一生产模块、而是校验 crate/workspace 整体契约的根级测试场景 @@ -505,6 +607,7 @@ const ALLOWED_INTERNAL_EDGES: &[(&str, &str)] = &[ ("codex-proxy-rs", "gateway-host"), ("codex-proxy-rs", "gateway-plugin-runtime"), ("codex-proxy-rs", "gateway-store"), + ("codex-proxy-rs", "provider-antigravity"), ("codex-proxy-rs", "provider-openai"), ("codex-proxy-rs", "provider-xai"), ("gateway-admin", "gateway-core"), @@ -525,6 +628,10 @@ const ALLOWED_INTERNAL_EDGES: &[(&str, &str)] = &[ ("gateway-plugin-runtime", "gateway-protocol"), ("gateway-store", "gateway-admin"), ("gateway-store", "gateway-core"), + ("provider-antigravity", "gateway-admin"), + ("provider-antigravity", "gateway-core"), + ("provider-antigravity", "gateway-egress"), + ("provider-antigravity", "gateway-protocol"), ("provider-openai", "gateway-admin"), ("provider-openai", "gateway-core"), ("provider-openai", "gateway-egress"), @@ -646,10 +753,9 @@ fn workspace_modules_follow_conventional_file_layout() { let tests = member_root.join("tests"); if tests.is_dir() { let roots = targets.get(&tests).expect("Cargo test source roots"); - assert_module_tree( - &tests, - &roots.iter().map(String::as_str).collect::>(), - ); + let roots = roots.iter().map(String::as_str).collect::>(); + assert_module_tree(&tests, &roots); + assert_directory_modules_have_children(&tests, &roots); } } } diff --git a/backend/crates/gateway-admin/src/bootstrap.rs b/backend/crates/gateway-admin/src/bootstrap.rs index b977eb9f7..61201206f 100644 --- a/backend/crates/gateway-admin/src/bootstrap.rs +++ b/backend/crates/gateway-admin/src/bootstrap.rs @@ -117,12 +117,10 @@ async fn initialize_inner( backup_ports.object_store(), ) .with_timezone(timezone); - let system_preflight = Arc::new( - use_case::system_preflight::PluginSystemUpdatePreflight::new( - store.plugins(), - plugin_inspector.clone(), - ), - ); + let system_preflight = Arc::new(use_case::system::PluginSystemUpdatePreflight::new( + store.plugins(), + plugin_inspector.clone(), + )); let system = Arc::new(DefaultSystemService::new(system, system_preflight)); let observations: Arc = Arc::new( use_case::observability::CachedObservabilityStore::new(store.observability()), diff --git a/backend/crates/gateway-admin/src/model/accounts.rs b/backend/crates/gateway-admin/src/model/accounts.rs index a031f9903..244dec1f3 100644 --- a/backend/crates/gateway-admin/src/model/accounts.rs +++ b/backend/crates/gateway-admin/src/model/accounts.rs @@ -21,6 +21,10 @@ pub use gateway_core::account::{ /// 账号可用的管理操作 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct ProviderAccountCapabilities { + pub credential_refresh: bool, + pub reauthorize: bool, + pub credential_export: bool, + pub model_catalog_download: bool, pub quota_settings_supported: bool, pub quota_credits: bool, pub quota: bool, diff --git a/backend/crates/gateway-admin/src/model/backup/mod.rs b/backend/crates/gateway-admin/src/model/backup/mod.rs index f7e400c0c..0878787e5 100644 --- a/backend/crates/gateway-admin/src/model/backup/mod.rs +++ b/backend/crates/gateway-admin/src/model/backup/mod.rs @@ -156,6 +156,7 @@ impl BackupStatusTransition { /// S3 存储配置更新命令;`secret_access_key` 为 `None` 表示保留旧值 #[derive(Clone)] pub struct UpdateBackupStorageCommand { + pub storage_revision: u64, pub endpoint: String, pub region: String, pub bucket: String, @@ -183,6 +184,7 @@ impl fmt::Debug for UpdateBackupStorageCommand { /// 调度配置更新命令 #[derive(Debug, Clone, PartialEq, Eq)] pub struct UpdateBackupScheduleCommand { + pub storage_revision: u64, pub schedule_enabled: bool, pub cron_expression: String, pub retention_days: u32, diff --git a/backend/crates/gateway-admin/src/model/mod.rs b/backend/crates/gateway-admin/src/model/mod.rs index 75e7a100b..674304796 100644 --- a/backend/crates/gateway-admin/src/model/mod.rs +++ b/backend/crates/gateway-admin/src/model/mod.rs @@ -22,7 +22,6 @@ pub mod pricing; pub mod provider_credentials; pub mod proxies; pub mod quota_forecast; -pub mod quota_forecast_sampling; pub mod quota_history; pub mod reset_credit_automation; pub mod retention; diff --git a/backend/crates/gateway-admin/src/model/pricing.rs b/backend/crates/gateway-admin/src/model/pricing.rs index 9dbc482bf..e93bb37f3 100644 --- a/backend/crates/gateway-admin/src/model/pricing.rs +++ b/backend/crates/gateway-admin/src/model/pricing.rs @@ -5,6 +5,7 @@ use std::collections::{BTreeMap, BTreeSet}; #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct PricingCatalog { + pub supported_bands: BTreeMap>, pub defaults: PricingOverrides, pub overrides: PricingOverrides, pub synced: PricingOverrides, diff --git a/backend/crates/gateway-admin/src/model/provider_credentials.rs b/backend/crates/gateway-admin/src/model/provider_credentials.rs index 9f15d2b1c..503b71d7a 100644 --- a/backend/crates/gateway-admin/src/model/provider_credentials.rs +++ b/backend/crates/gateway-admin/src/model/provider_credentials.rs @@ -828,7 +828,7 @@ impl ProviderQuotaWindow { } } -/// 账号用量统计周期,完整周/月额度优先,随后使用 Provider 提供的本地滚动日统计 +/// 账号用量统计周期,完整周/月额度优先,缺少可归属窗口时使用本地滚动日统计 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum AccountUsagePeriod { Weekly, @@ -1280,6 +1280,8 @@ pub struct AccountDirectoryItem { pub plan_type_display: Option, pub projection: gateway_core::account::AccountStatusProjection, pub usage: Option, + /// Admin 选择的本地统计周期,不要求存在对应的上游额度窗口 + pub usage_period: Option, pub quota: ProviderQuota, } diff --git a/backend/crates/gateway-admin/src/model/quota_forecast/mod.rs b/backend/crates/gateway-admin/src/model/quota_forecast/mod.rs new file mode 100644 index 000000000..484872272 --- /dev/null +++ b/backend/crates/gateway-admin/src/model/quota_forecast/mod.rs @@ -0,0 +1,14 @@ +//! 额度预测投影与历史采样的模块门面 + +mod projection; +mod sampling; + +pub(crate) use projection::quota_forecast_source_window; +pub use projection::{ + AccountQuotaForecast, AccountQuotaForecastReport, QuotaForecastSource, account_quota_forecasts, +}; +pub use sampling::{ + MAX_FORECAST_HISTORY_POINTS, QuotaForecastHistory, QuotaForecastHistoryPoint, + QuotaForecastMethod, QuotaForecastObservation, QuotaForecastPoint, QuotaForecastSample, + QuotaForecastUsage, select_forecast_sample, +}; diff --git a/backend/crates/gateway-admin/src/model/quota_forecast.rs b/backend/crates/gateway-admin/src/model/quota_forecast/projection.rs similarity index 97% rename from backend/crates/gateway-admin/src/model/quota_forecast.rs rename to backend/crates/gateway-admin/src/model/quota_forecast/projection.rs index 0be0bbfa7..dbe05fec5 100644 --- a/backend/crates/gateway-admin/src/model/quota_forecast.rs +++ b/backend/crates/gateway-admin/src/model/quota_forecast/projection.rs @@ -2,8 +2,8 @@ use chrono::{DateTime, Duration, Utc}; -use super::provider_credentials::{AccountUsagePeriod, ProviderQuota, ProviderQuotaWindow}; -use super::quota_forecast_sampling::{QuotaForecastMethod, QuotaForecastSample}; +use super::super::provider_credentials::{AccountUsagePeriod, ProviderQuota, ProviderQuotaWindow}; +use super::sampling::{QuotaForecastMethod, QuotaForecastSample}; const DAY_SECONDS: u64 = 86_400; const MIN_USED_PERCENT: f64 = 5.0; @@ -73,7 +73,7 @@ pub fn account_quota_forecasts( target_seconds, extrapolated: false, source: None, - unavailable_reason: Some("缺少周/月额度窗口,请刷新账号额度"), + unavailable_reason: Some("缺少可归属整个账号的周/月额度窗口"), low_sample: false, incomplete_cost: false, incomplete_tokens: false, diff --git a/backend/crates/gateway-admin/src/model/quota_forecast_sampling.rs b/backend/crates/gateway-admin/src/model/quota_forecast/sampling.rs similarity index 99% rename from backend/crates/gateway-admin/src/model/quota_forecast_sampling.rs rename to backend/crates/gateway-admin/src/model/quota_forecast/sampling.rs index f5107d715..2b0784b0c 100644 --- a/backend/crates/gateway-admin/src/model/quota_forecast_sampling.rs +++ b/backend/crates/gateway-admin/src/model/quota_forecast/sampling.rs @@ -2,7 +2,7 @@ use chrono::{DateTime, Utc}; -use super::provider_credentials::ProviderDocument; +use super::super::provider_credentials::ProviderDocument; /// 限制带 Provider 文档的历史点数量;累计用量仍覆盖整个查询区间 pub const MAX_FORECAST_HISTORY_POINTS: usize = 128; diff --git a/backend/crates/gateway-admin/src/model/settings.rs b/backend/crates/gateway-admin/src/model/settings.rs index 69a0d95ce..5f2edc468 100644 --- a/backend/crates/gateway-admin/src/model/settings.rs +++ b/backend/crates/gateway-admin/src/model/settings.rs @@ -60,9 +60,9 @@ pub struct RuntimeSettingsValues { pub switch_account_on_queue_failure: bool, pub max_retry_after_seconds: u32, pub openai_guardian_reserved_concurrency: u32, - pub openai_account_affinity: gateway_core::account::AccountAffinity, + pub account_affinity: gateway_core::account::AccountAffinity, pub max_account_rotations: u32, - pub openai_session_affinity_ttl_hours: u32, + pub session_affinity_ttl_hours: u32, pub responses_max_decompressed_body_bytes: u64, pub smart_scheduling: gateway_core::account::SmartSchedulingConfig, pub quota_reset_window_weights: gateway_core::account::ResetWindowWeights, @@ -213,7 +213,7 @@ impl RuntimeSettingsValues { self.key_queue_timeout_seconds, self.account_queue_timeout_seconds, self.max_account_rotations, - self.openai_session_affinity_ttl_hours, + self.session_affinity_ttl_hours, )?; gateway_core::settings::response_body_limit(self.responses_max_decompressed_body_bytes)?; gateway_core::settings::client_min_versions( diff --git a/backend/crates/gateway-admin/src/ports/pricing.rs b/backend/crates/gateway-admin/src/ports/pricing.rs index 970fc2aa3..dcbf3acd2 100644 --- a/backend/crates/gateway-admin/src/ports/pricing.rs +++ b/backend/crates/gateway-admin/src/ports/pricing.rs @@ -2,8 +2,94 @@ use crate::model::{AdminError, pricing::PricingSyncPreview}; use async_trait::async_trait; +use std::collections::{BTreeMap, BTreeSet}; + +/// Provider 明确登记的外部参考模型,不按名称前缀猜测不同产品的对应关系 +pub struct PricingSourceModel { + pub provider: String, + pub model: String, +} + +/// 同名外部目录可直接同步,跨平台模型只采用 Provider 登记的参考价 +pub enum PricingCatalogSource { + Direct, + References(BTreeMap), +} + +/// 同一次同步用相同的来源声明选择外部目录并映射网关模型 +pub struct PricingSourceScope { + pub catalogs: BTreeMap, +} + +impl PricingSourceScope { + pub fn vendors(&self) -> BTreeSet<&str> { + let mut vendors = BTreeSet::new(); + for (kind, source) in &self.catalogs { + match source { + PricingCatalogSource::Direct => { + vendors.insert(kind.as_str()); + } + PricingCatalogSource::References(models) => { + vendors.extend(models.values().map(|model| model.provider.as_str())) + } + } + } + vendors + } + + pub fn requires_catalog(&self, vendor: &str) -> bool { + matches!( + self.catalogs.get(vendor), + Some(PricingCatalogSource::Direct) + ) + } + + pub(crate) fn project(self, source: PricingSyncPreview) -> PricingSyncPreview { + let mut result = PricingSyncPreview { + prices: BTreeMap::new(), + skipped: Vec::new(), + }; + for (kind, catalog) in self.catalogs { + let prices = match catalog { + PricingCatalogSource::Direct => { + let prefix = format!("{kind}/"); + result.skipped.extend( + source + .skipped + .iter() + .filter(|id| id.starts_with(&prefix)) + .cloned(), + ); + source.prices.get(&kind).cloned().unwrap_or_default() + } + PricingCatalogSource::References(models) => { + let mut prices = BTreeMap::new(); + for (model, reference) in models { + match source + .prices + .get(&reference.provider) + .and_then(|models| models.get(&reference.model)) + { + Some(price) => { + prices.insert(model, price.clone()); + } + None => result.skipped.push(format!("{kind}/{model}")), + } + } + prices + } + }; + if !prices.is_empty() { + result.prices.insert(kind, prices); + } + } + result.skipped.sort(); + result.skipped.dedup(); + result + } +} #[async_trait] pub trait PricingSource: Send + Sync { - async fn fetch(&self) -> Result; + async fn fetch(&self, scope: &PricingSourceScope) -> Result; } diff --git a/backend/crates/gateway-admin/src/ports/provider.rs b/backend/crates/gateway-admin/src/ports/provider.rs index ea107753b..01ada76ff 100644 --- a/backend/crates/gateway-admin/src/ports/provider.rs +++ b/backend/crates/gateway-admin/src/ports/provider.rs @@ -24,7 +24,7 @@ use crate::model::provider_credentials::{ }; use crate::model::{ provider_credentials::{ProviderDocument, ProviderQuotaWindow}, - quota_forecast_sampling::QuotaForecastObservation, + quota_forecast::QuotaForecastObservation, }; /// 按原生 Token 口径计算的报价输入,额外费用由调用方处理 @@ -35,6 +35,19 @@ pub struct ProviderUsagePricingInput { pub usage: gateway_core::metering::Usage, } +/// 账号目录中的模型与独立额度观测,缺少观测不能解释为可用 +#[derive(Debug, Clone)] +pub struct ProviderPeerAccountModels { + pub credential_revision: gateway_core::account::CredentialRevision, + pub models: BTreeMap>, +} + +#[derive(Debug, Clone, Copy)] +pub struct ProviderPeerModelQuota { + pub state: gateway_core::account::QuotaState, + pub valid_until: std::time::SystemTime, +} + /// Provider 管理失败的稳定分类 #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ProviderAdminErrorKind { @@ -165,11 +178,21 @@ pub trait ProviderAdmin: Send + Sync { }) } - /// 只读内置价目;没有本地计价能力的 Provider 返回空目录 + /// 管理端允许为当前 Provider 覆盖的计费档位 + fn supported_pricing_bands(&self) -> &'static [&'static str] { + &["standard"] + } + + /// 只读内置价目,没有本地计价能力时返回空目录 fn pricing_catalog(&self) -> crate::model::pricing::ProviderPricingCatalog { Default::default() } + /// 外部参考价到本 Provider 上游模型的对应关系,与内置价共用登记 + fn pricing_source(&self) -> crate::ports::pricing::PricingCatalogSource { + crate::ports::pricing::PricingCatalogSource::Direct + } + fn evaluate_usage_pricing( &self, _input: &ProviderUsagePricingInput, @@ -193,6 +216,14 @@ pub trait ProviderAdmin: Send + Sync { None } + /// 批量读取已授权账号的原生模型事实,不访问上游;None 沿用整号额度合同 + async fn peer_model_facts( + &self, + _accounts: &[crate::model::accounts::AccountRecord], + ) -> Result>, ProviderAdminError> { + Ok(None) + } + /// 只读取原生 Provider 能力及账号类型,不执行网络或数据库查询 fn account_capabilities( &self, @@ -436,6 +467,13 @@ pub trait ProviderAdmin: Send + Sync { ) -> Result; } +/// 内置 Provider 在启动时一次交付数据面、管理面与后台任务 +pub struct ProviderBundle { + pub core: Arc, + pub admin: Arc, + pub workers: Vec, +} + /// 启动时注册原生 Provider,按 ProviderKind 查找管理能力 #[derive(Clone)] pub struct ProviderAdminRegistry { @@ -443,10 +481,34 @@ pub struct ProviderAdminRegistry { } impl ProviderAdminRegistry { + pub(crate) fn pricing_source_scope(&self) -> crate::ports::pricing::PricingSourceScope { + crate::ports::pricing::PricingSourceScope { + catalogs: self + .providers + .iter() + .map(|(kind, provider)| (kind.to_string(), provider.pricing_source())) + .collect(), + } + } + pub(crate) fn registered(&self) -> BTreeMap> { self.providers.as_ref().clone() } + pub(crate) fn supported_pricing_bands(&self) -> BTreeMap> { + self.providers + .iter() + .map(|(kind, provider)| { + let bands = provider + .supported_pricing_bands() + .iter() + .map(|&band| band.to_owned()) + .collect(); + (kind.to_string(), bands) + }) + .collect() + } + pub fn pricing_catalog(&self) -> gateway_core::metering::PricingOverrides { self.providers .iter() diff --git a/backend/crates/gateway-admin/src/ports/store.rs b/backend/crates/gateway-admin/src/ports/store.rs index c85018730..23b9a532b 100644 --- a/backend/crates/gateway-admin/src/ports/store.rs +++ b/backend/crates/gateway-admin/src/ports/store.rs @@ -40,7 +40,7 @@ use crate::model::{ CredentialMutationResult, CredentialRotationCommit, PluginAccountListQuery, PluginAccountPage, ProviderExportCredentialInput, }, - quota_forecast_sampling::QuotaForecastHistory, + quota_forecast::QuotaForecastHistory, settings::{AdminApiKey, AdminApiKeyMutation, ReplaceRuntimeSettings, RuntimeSettings}, }; diff --git a/backend/crates/gateway-admin/src/use_case/accounts/mod.rs b/backend/crates/gateway-admin/src/use_case/accounts/mod.rs index 21b0d5011..17d30c13a 100644 --- a/backend/crates/gateway-admin/src/use_case/accounts/mod.rs +++ b/backend/crates/gateway-admin/src/use_case/accounts/mod.rs @@ -39,7 +39,7 @@ use crate::{ quota_forecast::{ AccountQuotaForecastReport, account_quota_forecasts, quota_forecast_source_window, }, - quota_forecast_sampling::{QuotaForecastPoint, select_forecast_sample}, + quota_forecast::{QuotaForecastPoint, select_forecast_sample}, }, ports::{ provider::ProviderAdminRegistry, @@ -501,15 +501,16 @@ impl DefaultAccountsService { std::slice::from_mut(&mut quota), ) .await?; - let usage = self + let api_key_usage = self .load_api_key_usage(std::slice::from_ref(&stored), std::slice::from_ref("a)) .await? - .remove(&stored.account.id) - .or_else(|| { - quota - .usage_window() - .and_then(|(window, _)| window.local_usage.clone()) - }); + .remove(&stored.account.id); + let (usage, usage_period) = resolve_account_usage( + &stored.account.authentication_kind, + "a, + rolling_usage, + api_key_usage, + ); Ok(AccountDirectoryItem { protection_rules: stored.protection_rules, capacity: super::peer_link::upstream::account_capacity( @@ -526,6 +527,7 @@ impl DefaultAccountsService { ), projection: stored.projection, usage, + usage_period, account: stored.account, quota, }) @@ -598,7 +600,7 @@ impl AccountsService for DefaultAccountsService { .load_account_usage(rolling_range, &ids) .await .map_err(|error| map_store_error(error, "rolling account usage"))?; - let rolling_usage = rolling_usage + let mut rolling_usage = rolling_usage .into_iter() .map(|usage| (usage.account_id.clone(), usage)) .collect::>(); @@ -619,11 +621,12 @@ impl AccountsService for DefaultAccountsService { provider.account_capabilities(&id, &item.account.authentication_kind) }) .unwrap_or_default(); - let usage = api_key_usage.remove(&item.account.id).or_else(|| { - quota - .usage_window() - .and_then(|(window, _)| window.local_usage.clone()) - }); + let (usage, usage_period) = resolve_account_usage( + &item.account.authentication_kind, + "a, + rolling_usage.remove(&item.account.id), + api_key_usage.remove(&item.account.id), + ); Ok(AccountDirectoryItem { protection_rules: item.protection_rules, capacity: crate::model::accounts::AccountCapacity { @@ -643,6 +646,7 @@ impl AccountsService for DefaultAccountsService { Some("a), ), usage, + usage_period, account: item.account, projection: item.projection, quota, @@ -662,37 +666,30 @@ impl AccountsService for DefaultAccountsService { context: &MutationContext, account_ids: Vec, ) -> Result { - let providers = &self.providers; if account_ids.is_empty() || account_ids.len() > 200 { return Err(AdminError::invalid("账号导出数量必须在 1 到 200 之间")); } let exported_ids = account_ids.clone(); - let mut grouped = BTreeMap::>::new(); - for account_id in account_ids { - let account = self.load_account(&account_id).await?; - grouped - .entry(account.account.provider_kind) - .or_default() - .push(account_id); + let mut grouped = BTreeMap::new(); + // 混选时先检查每个账号的导出能力,再读取任何一组明文凭据 + for id in account_ids { + let (item, provider) = self.provider_for_account(&id).await?; + if !provider + .account_capabilities(&id, &item.account.authentication_kind) + .credential_export + { + return Err(AdminError::invalid("所选账号不支持导出")); + } + let (_, ids) = grouped + .entry(item.account.provider_kind) + .or_insert_with(|| (provider, Vec::new())); + if ids.contains(&id) { + return Err(AdminError::invalid("账号导出列表包含重复 ID")); + } + ids.push(id); } - if grouped.values().any(|ids| { - let unique = ids.iter().collect::>(); - unique.len() != ids.len() - }) { - return Err(AdminError::invalid("账号导出列表包含重复 ID")); - } - // 混选时先确认全部 Provider 已注册,拒绝路径不读取任何一组明文凭据 - let export_groups = grouped - .into_iter() - .map(|(provider_kind, ids)| { - let provider = providers - .require(&provider_kind) - .map_err(|error| map_provider_error(error, "provider account export"))?; - Ok((provider_kind, provider, ids)) - }) - .collect::, AdminError>>()?; - let mut documents = Vec::with_capacity(export_groups.len()); - for (provider_kind, provider, ids) in export_groups { + let mut documents = Vec::with_capacity(grouped.len()); + for (provider_kind, (provider, ids)) in grouped { let credentials = self .accounts .load_credentials_for_export(&provider_kind, &ids) @@ -1346,6 +1343,22 @@ impl AccountsService for DefaultAccountsService { } } +fn resolve_account_usage( + authentication_kind: &str, + quota: &ProviderQuota, + rolling_usage: Option, + api_key_usage: Option, +) -> (Option, Option) { + if authentication_kind == "api_key" { + return (api_key_usage, None); + } + if let Some((window, period)) = quota.usage_window() { + return (window.local_usage.clone(), Some(period)); + } + // 模型分组额度无法归属整号用量,本地统计独立回退,不能为此合成上游额度桶 + (rolling_usage, Some(AccountUsagePeriod::Daily)) +} + fn map_reset_credits_error_after_refresh( error: crate::ports::provider::ProviderAdminError, ) -> AdminError { diff --git a/backend/crates/gateway-admin/src/use_case/backup.rs b/backend/crates/gateway-admin/src/use_case/backup.rs index f894458cb..a37341a59 100644 --- a/backend/crates/gateway-admin/src/use_case/backup.rs +++ b/backend/crates/gateway-admin/src/use_case/backup.rs @@ -48,6 +48,7 @@ pub trait BackupService: Send + Sync { async fn test_connection( &self, context: &MutationContext, + storage_revision: u64, ) -> Result; async fn create_backup( @@ -151,12 +152,17 @@ impl BackupService for DefaultBackupService { async fn test_connection( &self, context: &MutationContext, + storage_revision: u64, ) -> Result { let settings = self .repository .load_settings() .await .map_err(|error| map_store_error(error, "backup settings"))?; + let stale = || AdminError::conflict("备份存储配置已更改,请刷新后重新测试"); + if settings.storage_revision != storage_revision { + return Err(stale()); + } let Some(config) = BackupStorageConfig::from_settings(&settings) else { return Ok(ConnectionTestResult { ok: false, @@ -170,12 +176,14 @@ impl BackupService for DefaultBackupService { .test_connection(&config) .await .map_err(map_backup_error)?; - if result.ok { - let _ = self + if result.ok + && !self .repository .record_verification(config.storage_revision, Utc::now()) .await - .map_err(|error| map_store_error(error, "backup settings"))?; + .map_err(|error| map_store_error(error, "backup settings"))? + { + return Err(stale()); } self.append_audit( context, diff --git a/backend/crates/gateway-admin/src/use_case/client_keys.rs b/backend/crates/gateway-admin/src/use_case/client_keys.rs index 539ab5a8f..73d879134 100644 --- a/backend/crates/gateway-admin/src/use_case/client_keys.rs +++ b/backend/crates/gateway-admin/src/use_case/client_keys.rs @@ -118,13 +118,18 @@ impl DefaultClientKeyService { fn validate_profile( &self, kind: &ProviderKind, - profile: &OpaqueProviderData, + profile: Option<&OpaqueProviderData>, ) -> Result<(), AdminError> { - self.providers + let provider = self + .providers .require(kind) - .and_then(|provider| provider.preview_key_client_profile(profile, None)) - .map(|_| ()) - .map_err(|error| super::map_provider_error(error, "client profile")) + .map_err(|error| super::map_provider_error(error, "client profile"))?; + if let Some(profile) = profile { + provider + .preview_key_client_profile(profile, None) + .map_err(|error| super::map_provider_error(error, "client profile"))?; + } + Ok(()) } fn batch_profile_merger( @@ -335,7 +340,7 @@ impl ClientKeyService for DefaultClientKeyService { crate::model::client_keys::validate_group_ids(&command.group_ids) .map_err(|_| AdminError::invalid("API Key 分组不合法"))?; for (provider, profile) in &command.request_profile_overrides { - self.validate_profile(provider, profile)?; + self.validate_profile(provider, Some(profile))?; } validate_peer_sharing(command.peer_sharing, &command.group_ids)?; let id = ClientApiKeyId::new(format!("key_{}", Uuid::now_v7().simple())) @@ -378,9 +383,7 @@ impl ClientKeyService for DefaultClientKeyService { crate::model::client_keys::validate_group_ids(&command.group_ids) .map_err(|_| AdminError::invalid("API Key 分组不合法"))?; for (provider, profile) in &command.request_profile_override_updates { - if let Some(profile) = profile { - self.validate_profile(provider, profile)?; - } + self.validate_profile(provider, profile.as_ref())?; } if let Some(sharing) = command.peer_sharing { validate_peer_sharing(sharing, &command.group_ids)?; diff --git a/backend/crates/gateway-admin/src/use_case/mod.rs b/backend/crates/gateway-admin/src/use_case/mod.rs index b1bdb4de6..320492407 100644 --- a/backend/crates/gateway-admin/src/use_case/mod.rs +++ b/backend/crates/gateway-admin/src/use_case/mod.rs @@ -18,7 +18,6 @@ pub mod plugins; pub mod proxies; pub mod settings; pub mod system; -pub(crate) mod system_preflight; pub mod usage_data; mod credential_mutation; diff --git a/backend/crates/gateway-admin/src/use_case/observability/billing.rs b/backend/crates/gateway-admin/src/use_case/observability/billing.rs new file mode 100644 index 000000000..f9c6fc621 --- /dev/null +++ b/backend/crates/gateway-admin/src/use_case/observability/billing.rs @@ -0,0 +1,145 @@ +//! 历史费用场景的 Provider 计价投影 + +use crate::model::AdminError; +use crate::model::observability::{ + CurrencyCost, DecimalAmount, ProviderBillingInput, UsageBillingProjection, + UsageCalculatedBillingFact, +}; +use crate::ports::provider::{ProviderAdminErrorKind, ProviderAdminRegistry}; +use crate::ports::store::UsageBillingProjector; +use crate::use_case::map_provider_error; +use gateway_core::routing::ProviderKind; +use std::str::FromStr; + +/// 在后台投影时恢复费用场景,查询不再逐请求读取计费快照 +pub struct ProviderUsageBillingProjector { + providers: ProviderAdminRegistry, +} + +impl ProviderUsageBillingProjector { + #[must_use] + pub fn new(providers: ProviderAdminRegistry) -> Self { + Self { providers } + } +} + +impl UsageBillingProjector for ProviderUsageBillingProjector { + fn project( + &self, + fact: &UsageCalculatedBillingFact, + ) -> Result { + let Ok(provider_kind) = ProviderKind::new(fact.provider_kind.clone()) else { + return Ok(UsageBillingProjection::default()); + }; + let input = ProviderBillingInput { + upstream_model_id: fact.upstream_model_id.clone(), + service_tier: fact.service_tier.clone(), + input_tokens: fact.input_tokens, + output_tokens: fact.output_tokens, + cached_input_tokens: fact.cached_input_tokens, + cache_write_input_tokens: fact.cache_write_input_tokens, + total: fact.total.clone(), + }; + let breakdown = match fact + .breakdown + .as_ref() + .filter(|breakdown| breakdown.total_amount == input.total) + .cloned() + .map_or_else( + || self.providers.calculated_billing(&provider_kind, &input), + |breakdown| Ok(Some(breakdown)), + ) { + Ok(breakdown) => breakdown, + Err(error) if error.kind() == ProviderAdminErrorKind::Unsupported => { + return Ok(UsageBillingProjection::default()); + } + Err(error) => return Err(map_provider_error(error, "usage billing")), + }; + let Some(breakdown) = breakdown else { + return Ok(UsageBillingProjection::default()); + }; + if !breakdown + .standard_amount + .currency + .eq_ignore_ascii_case("USD") + { + return Ok(UsageBillingProjection::default()); + } + Ok(UsageBillingProjection { + standard_amount: Some(breakdown.standard_amount.amount.clone()), + no_cache_amount: no_cache_cost(fact, &breakdown), + }) + } +} + +fn no_cache_cost( + fact: &UsageCalculatedBillingFact, + breakdown: &crate::model::observability::CalculatedBillingBreakdown, +) -> Option { + let image = breakdown.image.as_ref(); + let input_tokens = fact + .input_tokens? + .checked_sub(image.map_or(0, |i| i.input_tokens))?; + let cached_input_tokens = fact + .cached_input_tokens + .unwrap_or_default() + .checked_sub(image.map_or(0, |i| i.cached_input_tokens))? + .min(input_tokens); + let cache_write_input_tokens = fact + .cache_write_input_tokens + .unwrap_or_default() + .min(input_tokens.saturating_sub(cached_input_tokens)); + let input_rate = decimal(&breakdown.input_price_per_million.amount)?; + let replaced_input_amount = input_rate + .scaled() + .checked_mul(u128::from( + cached_input_tokens.saturating_add(cache_write_input_tokens), + ))? + .checked_div(1_000_000)?; + let mut total = decimal(&breakdown.total_amount.amount)? + .scaled() + .checked_sub(decimal(&breakdown.cache_read_amount.amount)?.scaled())? + .checked_sub(decimal(&breakdown.cache_write_amount.amount)?.scaled())? + .checked_add(replaced_input_amount)?; + if let Some(image) = image { + let image_no_cache = decimal(&image.input_price_per_million.amount)? + .scaled() + .checked_mul(u128::from(image.cached_input_tokens))? + .checked_div(1_000_000)?; + total = total + .checked_sub(decimal(&image.cache_read_amount.amount)?.scaled())? + .checked_add(image_no_cache)?; + } + DecimalAmount::from_str( + &gateway_core::metering::Decimal::from_scaled(total) + .ok()? + .canonical(), + ) + .ok() +} + +pub(super) fn amount_difference( + larger: Option<&DecimalAmount>, + smaller: Option<&DecimalAmount>, +) -> Option { + let difference = decimal(larger?)? + .scaled() + .checked_sub(decimal(smaller?)?.scaled())?; + DecimalAmount::from_str( + &gateway_core::metering::Decimal::from_scaled(difference) + .ok()? + .canonical(), + ) + .ok() +} + +fn decimal(value: &DecimalAmount) -> Option { + value.as_str().parse().ok() +} + +pub(super) fn usd_cost(costs: &[CurrencyCost]) -> Option { + costs + .iter() + .find(|cost| cost.currency.eq_ignore_ascii_case("USD")) + .map(|cost| cost.amount.clone()) +} diff --git a/backend/crates/gateway-admin/src/use_case/observability/dashboard.rs b/backend/crates/gateway-admin/src/use_case/observability/dashboard.rs new file mode 100644 index 000000000..fcbff4365 --- /dev/null +++ b/backend/crates/gateway-admin/src/use_case/observability/dashboard.rs @@ -0,0 +1,295 @@ +//! 仪表盘趋势、健康时间桶与期间指标 + +use super::metrics::{average, rate_or_zero, ratio}; +use crate::model::AdminError; +use crate::model::observability::{ + CostCoverage, CurrencyCost, DashboardPeriodMetrics, DecimalAmount, HealthStatus, + HealthTimeline, HealthTimelinePoint, RequestHealth, RequestMetricPoint, RequestMetrics, Trend, + TrendKind, TrendPoint, TrendSummary, +}; +use chrono::{DateTime, Duration, Utc}; +use std::collections::BTreeMap; + +const HEALTH_TIMELINE_SLOT_MINUTES: i64 = 15; +const HEALTH_TIMELINE_MIN_SAMPLE_SIZE: u64 = 10; +const HEALTH_TIMELINE_UNAVAILABLE_FAILURE_THRESHOLD: u64 = 3; +const HEALTH_TIMELINE_STABLE_RELIABILITY: f64 = 95.0; +/// 按部署时区的自然日计算 15 分钟健康桶,桶数随夏令时变化 +pub(in crate::use_case) fn health_timeline_at( + records: &[RequestMetricPoint], + now: DateTime, + timezone: gateway_core::time::DeploymentTimeZone, +) -> Result { + let start = timezone + .day_start(now) + .ok_or_else(|| AdminError::internal("时间超出支持范围"))?; + let end = timezone + .days_after(now, 1) + .ok_or_else(|| AdminError::internal("时间超出支持范围"))?; + let current_slot = start + + Duration::minutes( + (now - start) + .num_minutes() + .div_euclid(HEALTH_TIMELINE_SLOT_MINUTES) + * HEALTH_TIMELINE_SLOT_MINUTES, + ); + let slots = ((end - start).num_minutes() + HEALTH_TIMELINE_SLOT_MINUTES - 1) + / HEALTH_TIMELINE_SLOT_MINUTES; + let mut buckets = (0..slots) + .map(|index| { + ( + start + Duration::minutes(HEALTH_TIMELINE_SLOT_MINUTES * index), + RequestHealth::default(), + ) + }) + .collect::>(); + for record in records { + if record.bucket_start < start || record.bucket_start > now { + continue; + } + let record_slot = start + + Duration::minutes( + (record.bucket_start - start) + .num_minutes() + .div_euclid(HEALTH_TIMELINE_SLOT_MINUTES) + * HEALTH_TIMELINE_SLOT_MINUTES, + ); + if let Some((_, bucket)) = buckets + .iter_mut() + .find(|(bucket_start, _)| *bucket_start == record_slot) + { + bucket.add_metrics(&record.metrics); + } + } + + let totals = buckets + .iter() + .filter(|(bucket_start, _)| *bucket_start <= current_slot) + .fold(RequestHealth::default(), |mut totals, (_, bucket)| { + totals.add_window(*bucket); + totals + }); + Ok(HealthTimeline { + reliability_percent: health_reliability(totals), + status: health_status(totals, false), + success_requests: totals.success_requests, + failed_requests: totals.failed_requests, + cancelled_requests: totals.cancelled_requests, + incomplete_requests: totals.incomplete_requests, + caller_error_requests: totals.caller_error_requests, + points: buckets + .into_iter() + .map(|(bucket_start, bucket)| HealthTimelinePoint { + bucket_start, + status: health_status(bucket, bucket_start > current_slot), + reliability_percent: health_reliability(bucket), + success_requests: bucket.success_requests, + failed_requests: bucket.failed_requests, + cancelled_requests: bucket.cancelled_requests, + incomplete_requests: bucket.incomplete_requests, + caller_error_requests: bucket.caller_error_requests, + }) + .collect(), + }) +} + +pub(super) fn trend( + kind: TrendKind, + points: Vec, + analytics: crate::model::analytics::AnalyticsMetadata, +) -> Result { + let mut metrics = RequestMetrics::default(); + let mut coverage = CostCoverage::default(); + let mut costs = BTreeMap::::new(); + for point in &points { + add_request_metrics(&mut metrics, &point.metrics); + coverage.provider_reported_count = coverage + .provider_reported_count + .saturating_add(point.cost_coverage.provider_reported_count); + coverage.calculated_count = coverage + .calculated_count + .saturating_add(point.cost_coverage.calculated_count); + coverage.partial_count = coverage + .partial_count + .saturating_add(point.cost_coverage.partial_count); + coverage.unavailable_count = coverage + .unavailable_count + .saturating_add(point.cost_coverage.unavailable_count); + coverage.not_billable_count = coverage + .not_billable_count + .saturating_add(point.cost_coverage.not_billable_count); + for cost in &point.costs { + if let Some(amount) = costs.get_mut(&cost.currency) { + *amount = amount + .checked_add(&cost.amount) + .ok_or_else(|| AdminError::internal("成本聚合结果超出数值范围"))?; + } else { + costs.insert(cost.currency.clone(), cost.amount.clone()); + } + } + } + let average_latency_ms = average(metrics.latency_sum_ms, metrics.latency_count); + let health = RequestHealth::from_metrics(&metrics); + let error_count = health.non_success_requests(); + let success_rate = health.success_ratio(); + let cache_hit_request_rate = ratio( + metrics.cache_hit_request_count, + metrics.cache_eligible_request_count, + ); + let peak_first_token_p95_ms = points + .iter() + .filter_map(|point| point.metrics.first_token_latency_percentiles.p95_ms) + .map(|value| value.as_f64()) + .reduce(f64::max); + let peak_latency_p95_ms = points + .iter() + .filter_map(|point| point.metrics.latency_percentiles.p95_ms) + .map(|value| value.as_f64()) + .reduce(f64::max); + let minimum_output_throughput_p50 = points + .iter() + .filter_map(|point| point.metrics.output_throughput_p50) + .min(); + Ok(Trend { + analytics, + kind, + points: points.into_iter().map(trend_point).collect(), + summary: TrendSummary { + request_count: metrics.request_count, + input_tokens: metrics.input_tokens, + output_tokens: metrics.output_tokens, + cached_input_tokens: metrics.cached_input_tokens, + total_tokens: metrics.total_tokens, + error_count, + average_latency_ms, + max_latency_ms: metrics.max_latency_ms, + min_latency_ms: metrics.min_latency_ms, + peak_first_token_p95_ms, + peak_latency_p95_ms, + minimum_output_throughput_p50, + success_rate, + cache_hit_request_rate, + costs: costs + .into_iter() + .map(|(currency, amount)| CurrencyCost { currency, amount }) + .collect(), + cost_coverage: coverage, + }, + }) +} + +fn trend_point(point: RequestMetricPoint) -> TrendPoint { + let health = RequestHealth::from_metrics(&point.metrics); + TrendPoint { + bucket_start: point.bucket_start, + granularity: point.granularity, + error_count: health.non_success_requests(), + average_latency_ms: average(point.metrics.latency_sum_ms, point.metrics.latency_count), + average_first_token_latency_ms: average( + point.metrics.first_token_latency_sum_ms, + point.metrics.first_token_latency_count, + ), + cached_token_rate: rate_or_zero( + point.metrics.cached_input_tokens, + point.metrics.input_tokens, + ), + cache_hit_request_rate: ratio( + point.metrics.cache_hit_request_count, + point.metrics.cache_eligible_request_count, + ), + success_rate: health.success_ratio(), + metrics: point.metrics, + cost_coverage: point.cost_coverage, + costs: point.costs, + } +} + +pub(super) fn dashboard_period_metrics<'a>( + metrics: impl IntoIterator, +) -> DashboardPeriodMetrics { + let mut result = DashboardPeriodMetrics::default(); + for metrics in metrics { + result.request_count = result.request_count.saturating_add(metrics.request_count); + result.input_tokens = result.input_tokens.saturating_add(metrics.input_tokens); + result.output_tokens = result.output_tokens.saturating_add(metrics.output_tokens); + result.cached_input_tokens = result + .cached_input_tokens + .saturating_add(metrics.cached_input_tokens); + result.total_tokens = result.total_tokens.saturating_add(metrics.total_tokens); + } + result.cached_token_rate = rate_or_zero(result.cached_input_tokens, result.input_tokens); + result.observed_cached_token_rate = ratio(result.cached_input_tokens, result.input_tokens); + result +} + +fn add_request_metrics(total: &mut RequestMetrics, value: &RequestMetrics) { + total.request_count = total.request_count.saturating_add(value.request_count); + total.success_count = total.success_count.saturating_add(value.success_count); + total.failure_count = total.failure_count.saturating_add(value.failure_count); + total.cancelled_count = total.cancelled_count.saturating_add(value.cancelled_count); + total.incomplete_count = total + .incomplete_count + .saturating_add(value.incomplete_count); + total.caller_error_count = total + .caller_error_count + .saturating_add(value.caller_error_count); + total.input_tokens = total.input_tokens.saturating_add(value.input_tokens); + total.output_tokens = total.output_tokens.saturating_add(value.output_tokens); + total.cached_input_tokens = total + .cached_input_tokens + .saturating_add(value.cached_input_tokens); + total.cache_write_input_tokens = total + .cache_write_input_tokens + .saturating_add(value.cache_write_input_tokens); + total.reasoning_output_tokens = total + .reasoning_output_tokens + .saturating_add(value.reasoning_output_tokens); + total.total_tokens = total.total_tokens.saturating_add(value.total_tokens); + total.first_token_latency_sum_ms = total + .first_token_latency_sum_ms + .saturating_add(value.first_token_latency_sum_ms); + total.first_token_latency_count = total + .first_token_latency_count + .saturating_add(value.first_token_latency_count); + total.latency_sum_ms = total.latency_sum_ms.saturating_add(value.latency_sum_ms); + total.latency_count = total.latency_count.saturating_add(value.latency_count); + total.min_latency_ms = match (total.min_latency_ms, value.min_latency_ms) { + (Some(left), Some(right)) => Some(left.min(right)), + (left, right) => left.or(right), + }; + total.max_latency_ms = match (total.max_latency_ms, value.max_latency_ms) { + (Some(left), Some(right)) => Some(left.max(right)), + (left, right) => left.or(right), + }; + total.cache_eligible_request_count = total + .cache_eligible_request_count + .saturating_add(value.cache_eligible_request_count); + total.cache_hit_request_count = total + .cache_hit_request_count + .saturating_add(value.cache_hit_request_count); +} + +fn health_status(bucket: RequestHealth, is_future: bool) -> HealthStatus { + let eligible_requests = bucket.eligible_requests(); + if is_future { + HealthStatus::Future + } else if eligible_requests == 0 { + HealthStatus::NoData + } else if bucket.success_requests == 0 + && bucket.non_success_requests() >= HEALTH_TIMELINE_UNAVAILABLE_FAILURE_THRESHOLD + { + HealthStatus::Unavailable + } else if eligible_requests < HEALTH_TIMELINE_MIN_SAMPLE_SIZE { + HealthStatus::LowSample + } else if health_reliability(bucket) + .is_some_and(|reliability| reliability < HEALTH_TIMELINE_STABLE_RELIABILITY) + { + HealthStatus::Unstable + } else { + HealthStatus::Stable + } +} + +fn health_reliability(bucket: RequestHealth) -> Option { + bucket.success_rate() +} diff --git a/backend/crates/gateway-admin/src/use_case/observability/export/mod.rs b/backend/crates/gateway-admin/src/use_case/observability/export/mod.rs index 4eeac61fa..573124006 100644 --- a/backend/crates/gateway-admin/src/use_case/observability/export/mod.rs +++ b/backend/crates/gateway-admin/src/use_case/observability/export/mod.rs @@ -9,12 +9,13 @@ use tokio::time::{Instant, timeout_at}; mod availability; -use super::{DefaultObservabilityService, map_store_error}; +use super::DefaultObservabilityService; use crate::model::{ AdminError, AdminErrorKind, diagnostics::{DiagnosticBundle, DiagnosticGap, DiagnosticRequest, DiagnosticTarget}, observability::OpsError, }; +use crate::use_case::map_store_error; const MAX_REQUESTS: usize = 8; const MAX_ERRORS: u16 = 128; diff --git a/backend/crates/gateway-admin/src/use_case/observability/insights.rs b/backend/crates/gateway-admin/src/use_case/observability/insights.rs new file mode 100644 index 000000000..9c9a05b46 --- /dev/null +++ b/backend/crates/gateway-admin/src/use_case/observability/insights.rs @@ -0,0 +1,393 @@ +//! 用量洞察与费用场景的纯聚合 + +use super::billing::{amount_difference, usd_cost}; +use super::metrics::{rate_or_zero, ratio}; +use crate::model::AdminError; +use crate::model::observability::{ + DecimalAmount, RequestHealth, RequestMetricPoint, UsageCacheEfficiency, UsageConcurrencyPoint, + UsageCostComparison, UsageCostSummary, UsageInsight, UsageInsightData, UsageInsightMetric, + UsageInsights, UsageInsightsCost, UsageInsightsCostPoint, UsageInsightsHealth, + UsageInsightsHealthPoint, UsageInsightsLoad, UsageInsightsObservation, + UsageInsightsPerformance, UsageInsightsPerformancePoint, UsageMetricPoint, UsageMetricSeries, + UsageOverview, UsageThroughputPercentiles, +}; +use chrono::{DateTime, Utc}; +use std::collections::BTreeMap; +use std::collections::btree_map::Entry; + +pub(super) fn insights_from_observation( + observation: UsageInsightsObservation, +) -> Result { + let mut standard_costs = UsageCostScenarios::default(); + for point in observation.costs { + if let Some(amount) = point.standard_amount { + standard_costs.standard.add(point.bucket_start, amount)?; + } + if let Some(amount) = point.no_cache_amount { + standard_costs.no_cache.add(point.bucket_start, amount)?; + } + } + let overview = observation.overview; + let trend = observation.trend; + build_usage_insights(overview, trend, standard_costs, observation.concurrency) +} + +pub(super) fn select_usage_metric( + insights: UsageInsights, + metric: UsageInsightMetric, +) -> UsageInsight { + let activity = insights + .health + .points + .iter() + .map(|point| (point.bucket_start, point.total_requests)) + .collect::>(); + let data = match metric { + UsageInsightMetric::Health => UsageInsightData::Health(insights.health), + UsageInsightMetric::Latency => UsageInsightData::Latency(metric_series( + insights.performance.latency_percentiles, + insights + .performance + .points + .into_iter() + .map(|point| (point.bucket_start, point.latency_percentiles)), + &activity, + )), + UsageInsightMetric::FirstToken => UsageInsightData::FirstToken(metric_series( + insights.performance.first_token_latency_percentiles, + insights + .performance + .points + .into_iter() + .map(|point| (point.bucket_start, point.first_token_latency_percentiles)), + &activity, + )), + UsageInsightMetric::Throughput => UsageInsightData::Throughput(metric_series( + UsageThroughputPercentiles { + p10: insights.performance.output_throughput_p10, + p50: insights.performance.output_throughput_p50, + p90: insights.performance.output_throughput_p90, + }, + insights.performance.points.into_iter().map(|point| { + ( + point.bucket_start, + UsageThroughputPercentiles { + p10: point.output_throughput_p10, + p50: point.output_throughput_p50, + p90: point.output_throughput_p90, + }, + ) + }), + &activity, + )), + UsageInsightMetric::Load => UsageInsightData::Load(metric_series( + insights.performance.load, + insights + .performance + .points + .into_iter() + .map(|point| (point.bucket_start, point.load)), + &activity, + )), + UsageInsightMetric::Cost => UsageInsightData::Cost(metric_series( + cost_summary(&insights.cost), + insights.cost.points.into_iter().map(|point| { + ( + point.bucket_start, + UsageCostComparison { + estimated_cost: point.estimated_cost, + no_cache_cost: point.no_cache_cost, + }, + ) + }), + &activity, + )), + UsageInsightMetric::Savings => UsageInsightData::Savings(metric_series( + cost_summary(&insights.cost), + insights + .cost + .points + .into_iter() + .map(|point| (point.bucket_start, point.cache_savings)), + &activity, + )), + UsageInsightMetric::Cache => UsageInsightData::Cache(metric_series( + cost_summary(&insights.cost), + insights.cost.points.into_iter().map(|point| { + ( + point.bucket_start, + UsageCacheEfficiency { + input_tokens: point.input_tokens, + cached_token_rate: point.cached_token_rate, + cache_hit_request_rate: point.cache_hit_request_rate, + }, + ) + }), + &activity, + )), + }; + UsageInsight { + analytics: insights.analytics, + granularity: insights.granularity, + data, + } +} + +fn cost_summary(cost: &UsageInsightsCost) -> UsageCostSummary { + UsageCostSummary { + estimated_cost: cost.estimated_cost.clone(), + cache_savings: cost.cache_savings.clone(), + tier_premium: cost.tier_premium.clone(), + cost_per_successful_request: cost.cost_per_successful_request.clone(), + coverage: cost.coverage.clone(), + } +} + +fn metric_series( + summary: S, + points: impl Iterator, P)>, + activity: &BTreeMap, u64>, +) -> UsageMetricSeries { + UsageMetricSeries { + summary, + points: points + .map(|(bucket_start, value)| UsageMetricPoint { + bucket_start, + request_count: activity.get(&bucket_start).copied().unwrap_or_default(), + value, + }) + .collect(), + } +} + +fn build_usage_insights( + overview: UsageOverview, + trend: Vec, + standard_costs: UsageCostScenarios, + concurrency: Vec, +) -> Result { + let granularity = trend.first().map_or( + crate::model::observability::Granularity::FifteenMinutes, + |point| point.granularity, + ); + if trend.iter().any(|point| point.granularity != granularity) { + return Err(AdminError::internal("用量洞察趋势包含不一致的时间粒度")); + } + + let requests = &overview.requests; + let health_window = RequestHealth::from_metrics(requests); + let failed_requests = health_window.failed_requests; + let health = UsageInsightsHealth { + total_requests: requests.request_count, + success_requests: requests.success_count, + failed_requests, + cancelled_requests: requests.cancelled_count, + incomplete_requests: requests.incomplete_count, + caller_error_requests: requests.caller_error_count, + success_rate: health_window.success_ratio(), + completion_rate: rate_or_zero( + requests + .success_count + .saturating_add(requests.failure_count), + requests.request_count, + ), + points: trend + .iter() + .map(|point| { + let health_window = RequestHealth::from_metrics(&point.metrics); + UsageInsightsHealthPoint { + total_requests: point.metrics.request_count, + bucket_start: point.bucket_start, + success_requests: point.metrics.success_count, + failed_requests: health_window.failed_requests, + cancelled_requests: point.metrics.cancelled_count, + incomplete_requests: point.metrics.incomplete_count, + caller_error_requests: point.metrics.caller_error_count, + error_rate: health_window.error_ratio(), + } + }) + .collect(), + }; + let concurrency_by_bucket = concurrency + .iter() + .map(|point| (point.bucket_start, point)) + .collect::>(); + let mut weighted_concurrency_micros = 0.0; + let mut effective_micros = 0_i64; + for (index, point) in concurrency.iter().enumerate() { + let start = point.bucket_start.max(overview.range.start); + let end = concurrency + .get(index + 1) + .map_or(overview.range.end, |next| next.bucket_start) + .min(overview.range.end); + let micros = (end - start).num_microseconds().unwrap_or(0).max(0); + effective_micros = effective_micros.saturating_add(micros); + weighted_concurrency_micros += point.average_concurrency * micros as f64; + } + let average_concurrency = if effective_micros > 0 { + weighted_concurrency_micros / effective_micros as f64 + } else { + 0.0 + }; + let peak_concurrency = concurrency + .iter() + .map(|point| point.peak_concurrency) + .max() + .unwrap_or(0); + let performance = UsageInsightsPerformance { + latency_percentiles: requests.latency_percentiles, + first_token_latency_percentiles: requests.first_token_latency_percentiles, + output_throughput_p10: requests.output_throughput_p10, + output_throughput_p50: requests.output_throughput_p50, + output_throughput_p90: requests.output_throughput_p90, + load: UsageInsightsLoad { + average_concurrency, + peak_concurrency, + admission_decision_p95_ms: requests.admission_decision_percentiles.p95_ms, + account_selection_wait_p95_ms: requests.account_selection_wait_percentiles.p95_ms, + }, + points: trend + .iter() + .map(|point| { + let concurrency = concurrency_by_bucket.get(&point.bucket_start); + UsageInsightsPerformancePoint { + bucket_start: point.bucket_start, + latency_percentiles: point.metrics.latency_percentiles, + first_token_latency_percentiles: point.metrics.first_token_latency_percentiles, + output_throughput_p10: point.metrics.output_throughput_p10, + output_throughput_p50: point.metrics.output_throughput_p50, + output_throughput_p90: point.metrics.output_throughput_p90, + load: UsageInsightsLoad { + average_concurrency: concurrency + .map_or(0.0, |point| point.average_concurrency), + peak_concurrency: concurrency.map_or(0, |point| point.peak_concurrency), + admission_decision_p95_ms: point + .metrics + .admission_decision_percentiles + .p95_ms, + account_selection_wait_p95_ms: point + .metrics + .account_selection_wait_percentiles + .p95_ms, + }, + } + }) + .collect(), + }; + let estimated_cost = usd_cost(&overview.attempts.costs); + let UsageCostScenarios { + standard: + ScenarioCosts { + total: standard_cost, + by_bucket: standard_costs_by_bucket, + }, + no_cache: + ScenarioCosts { + total: no_cache_cost, + by_bucket: no_cache_costs_by_bucket, + }, + } = standard_costs; + let cache_savings = amount_difference(no_cache_cost.as_ref(), estimated_cost.as_ref()); + let tier_premium = amount_difference(estimated_cost.as_ref(), standard_cost.as_ref()); + let cost_per_request = estimated_cost + .as_ref() + .and_then(|cost| cost.checked_div_u64(requests.request_count)); + let cost_per_successful_request = estimated_cost + .as_ref() + .and_then(|cost| cost.checked_div_u64(requests.success_count)); + let cost = UsageInsightsCost { + cost_per_request, + estimated_cost, + standard_cost, + no_cache_cost, + cache_savings, + tier_premium, + tokens_per_request: rate_or_zero(requests.total_tokens, requests.request_count), + cost_per_successful_request, + cached_token_rate: rate_or_zero(requests.cached_input_tokens, requests.input_tokens), + cache_hit_request_rate: ratio( + requests.cache_hit_request_count, + requests.cache_eligible_request_count, + ), + input_tokens: requests.input_tokens, + output_tokens: requests.output_tokens, + cached_input_tokens: requests.cached_input_tokens, + total_tokens: requests.total_tokens, + points: trend + .iter() + .map(|point| UsageInsightsCostPoint { + bucket_start: point.bucket_start, + input_tokens: point.metrics.input_tokens, + output_tokens: point.metrics.output_tokens, + cached_input_tokens: point.metrics.cached_input_tokens, + total_tokens: point.metrics.total_tokens, + estimated_cost: usd_cost(&point.costs), + standard_cost: standard_costs_by_bucket.get(&point.bucket_start).cloned(), + no_cache_cost: no_cache_costs_by_bucket.get(&point.bucket_start).cloned(), + cache_savings: amount_difference( + no_cache_costs_by_bucket.get(&point.bucket_start), + usd_cost(&point.costs).as_ref(), + ), + cached_token_rate: rate_or_zero( + point.metrics.cached_input_tokens, + point.metrics.input_tokens, + ), + cache_hit_request_rate: ratio( + point.metrics.cache_hit_request_count, + point.metrics.cache_eligible_request_count, + ), + }) + .collect(), + costs: overview.attempts.costs.clone(), + coverage: overview.attempts.cost_coverage.clone(), + }; + Ok(UsageInsights { + analytics: overview.analytics, + granularity, + health, + performance, + cost, + attempts: overview.attempts, + providers: overview.providers, + }) +} + +#[derive(Debug, Default)] +struct ScenarioCosts { + total: Option, + by_bucket: BTreeMap, DecimalAmount>, +} + +impl ScenarioCosts { + fn add( + &mut self, + bucket_start: DateTime, + amount: DecimalAmount, + ) -> Result<(), AdminError> { + self.total = Some(match self.total.take() { + Some(current) => current + .checked_add(&amount) + .ok_or_else(|| AdminError::internal("用量标准成本超出数值范围"))?, + None => amount.clone(), + }); + match self.by_bucket.entry(bucket_start) { + Entry::Occupied(mut entry) => { + let sum = entry + .get() + .checked_add(&amount) + .ok_or_else(|| AdminError::internal("用量标准成本超出数值范围"))?; + entry.insert(sum); + } + Entry::Vacant(entry) => { + entry.insert(amount); + } + } + Ok(()) + } +} + +#[derive(Debug, Default)] +struct UsageCostScenarios { + standard: ScenarioCosts, + no_cache: ScenarioCosts, +} diff --git a/backend/crates/gateway-admin/src/use_case/observability/metrics.rs b/backend/crates/gateway-admin/src/use_case/observability/metrics.rs new file mode 100644 index 000000000..433025c68 --- /dev/null +++ b/backend/crates/gateway-admin/src/use_case/observability/metrics.rs @@ -0,0 +1,13 @@ +//! 观测指标的均值与比率计算 + +pub(super) fn average(sum: u64, count: u64) -> Option { + (count > 0).then(|| sum / count) +} + +pub(super) fn ratio(numerator: u64, denominator: u64) -> Option { + (denominator > 0).then(|| numerator as f64 / denominator as f64) +} + +pub(super) fn rate_or_zero(numerator: u64, denominator: u64) -> f64 { + ratio(numerator, denominator).unwrap_or(0.0) +} diff --git a/backend/crates/gateway-admin/src/use_case/observability/mod.rs b/backend/crates/gateway-admin/src/use_case/observability/mod.rs index 26719871a..1a84a0684 100644 --- a/backend/crates/gateway-admin/src/use_case/observability/mod.rs +++ b/backend/crates/gateway-admin/src/use_case/observability/mod.rs @@ -1,1433 +1,16 @@ -//! 观测查询、趋势、费用覆盖与健康阈值规则 +//! 观测查询、费用场景与指标投影的用例入口 -use std::{ - collections::{BTreeMap, HashMap, btree_map::Entry}, - str::FromStr, - sync::Arc, -}; - -use async_trait::async_trait; -use chrono::{DateTime, Duration, Utc}; -use futures::StreamExt as _; -use gateway_core::{account::ProviderAccountId, routing::ProviderKind}; - -use crate::{ - model::{ - AdminError, - observability::{ - CostCoverage, CurrencyCost, DashboardAccountUsage, DashboardCapacity, - DashboardPeriodMetrics, DashboardQuery, DashboardResult, DecimalAmount, - DiagnosticDimension, DiagnosticsItem, DiagnosticsResult, Granularity, HealthStatus, - HealthTimeline, HealthTimelinePoint, OpsErrorPage, OpsErrorQuery, ProviderBillingInput, - RequestHealth, RequestMetricPoint, RequestMetrics, TimeRange, Trend, TrendKind, - TrendPoint, TrendSummary, UsageBilling, UsageBillingProjection, UsageCacheEfficiency, - UsageCalculatedBillingFact, UsageConcurrencyPoint, UsageCostComparison, - UsageCostSummary, UsageDetail, UsageFilter, UsageInsight, UsageInsightData, - UsageInsightMetric, UsageInsights, UsageInsightsCost, UsageInsightsCostPoint, - UsageInsightsHealth, UsageInsightsHealthPoint, UsageInsightsLoad, - UsageInsightsObservation, UsageInsightsPerformance, UsageInsightsPerformancePoint, - UsageMetricPoint, UsageMetricSeries, UsageOverview, UsagePage, UsageQuery, - UsageSummary, UsageThroughputPercentiles, - }, - provider_credentials::ProviderQuotaRequest, - }, - ports::{ - provider::{ProviderAdminErrorKind, ProviderAdminRegistry}, - store::{AccountStore, ObservabilityStore, SettingsStore, UsageBillingProjector}, - }, -}; - -use super::{map_provider_error, map_store_error}; - -const HEALTH_TIMELINE_SLOT_MINUTES: i64 = 15; -const HEALTH_TIMELINE_MIN_SAMPLE_SIZE: u64 = 10; -const HEALTH_TIMELINE_UNAVAILABLE_FAILURE_THRESHOLD: u64 = 3; -const HEALTH_TIMELINE_STABLE_RELIABILITY: f64 = 95.0; +mod billing; +mod dashboard; mod errors; mod export; +mod insights; +mod metrics; +mod service; mod store_cache; + +pub use billing::ProviderUsageBillingProjector; +pub(super) use dashboard::health_timeline_at; +pub(crate) use service::DefaultObservabilityService; +pub use service::ObservabilityService; pub(crate) use store_cache::CachedObservabilityStore; - -/// API 消费的观测控制面服务 -#[async_trait] -pub trait ObservabilityService: Send + Sync { - async fn dashboard_summary( - &self, - range: TimeRange, - kind: TrendKind, - ) -> Result; - async fn dashboard_trend(&self, range: TimeRange, kind: TrendKind) - -> Result; - async fn usage_records(&self, query: UsageQuery) -> Result; - async fn usage_record_detail(&self, request_id: &str) -> Result; - async fn client_key_statistics( - &self, - range: TimeRange, - id: &gateway_core::policy::ClientApiKeyId, - query: crate::model::observability::KeyUsageMetric, - ) -> Result; - - async fn client_key_models( - &self, - range: TimeRange, - id: &gateway_core::policy::ClientApiKeyId, - ) -> Result, AdminError>; - - async fn usage_summary( - &self, - range: TimeRange, - filter: UsageFilter, - ) -> Result; - async fn usage_insights( - &self, - range: TimeRange, - filter: UsageFilter, - ) -> Result; - async fn usage_metric( - &self, - range: TimeRange, - filter: UsageFilter, - metric: UsageInsightMetric, - ) -> Result; - async fn diagnostics( - &self, - range: TimeRange, - filter: UsageFilter, - dimension: DiagnosticDimension, - ) -> Result; - async fn ops_errors(&self, query: OpsErrorQuery) -> Result; - async fn export_diagnostics( - &self, - target: crate::model::diagnostics::DiagnosticTarget, - ) -> Result; -} - -pub(crate) struct DefaultObservabilityService { - timezone: gateway_core::time::DeploymentTimeZone, - store: Arc, - accounts: Arc, - settings: Arc, - providers: ProviderAdminRegistry, - system: Arc, - upstream_info: Option>, -} - -impl DefaultObservabilityService { - #[must_use] - pub(crate) fn new( - store: Arc, - accounts: Arc, - settings: Arc, - providers: ProviderAdminRegistry, - timezone: gateway_core::time::DeploymentTimeZone, - system: Arc, - upstream_info: Option>, - ) -> Self { - Self { - timezone, - store, - accounts, - settings, - providers, - system, - upstream_info, - } - } - - async fn load_dashboard_summary( - &self, - range: TimeRange, - ) -> Result { - let observed_at = Utc::now(); - let query = DashboardQuery::new(range, self.timezone) - .map_err(|_| AdminError::internal("时间超出支持范围"))?; - let today_start = query.yesterday_range.end; - let (mut observation, settings) = futures::try_join!( - self.store.dashboard_summary(query, observed_at), - self.settings.load_runtime_settings(), - ) - .map_err(|error| map_store_error(error, "dashboard"))?; - let runtime_slots = observation.runtime_slots.as_ref(); - self.enrich_list_records(&mut observation.recent_requests) - .await; - self.enrich_dashboard_quotas(&mut observation.account_usage) - .await; - for account in &mut observation.account_usage { - account.plan_type_display = self - .providers - .plan_type_display(&account.provider_kind, account.plan_type.as_deref()); - } - let today = dashboard_period_metrics( - observation - .trend - .iter() - .filter(|point| { - point.bucket_start >= today_start && point.bucket_start < observation.range.end - }) - .map(|point| &point.metrics), - ); - let yesterday = dashboard_period_metrics(std::iter::once(&observation.yesterday)); - let total_billing_usd = observation.totals.billing_usd.clone(); - let total_cached_token_rate = rate_or_zero( - observation.totals.cached_input_tokens, - observation.totals.input_tokens, - ); - let (first_token_latency_sum_ms, first_token_latency_count) = observation - .trend - .iter() - .fold((0_u64, 0_u64), |(sum, count), point| { - ( - sum.saturating_add(point.metrics.first_token_latency_sum_ms), - count.saturating_add(point.metrics.first_token_latency_count), - ) - }); - let average_first_token_latency_ms = - average(first_token_latency_sum_ms, first_token_latency_count); - let trend = trend( - TrendKind::Usage, - observation.trend.clone(), - observation.analytics.clone(), - )?; - let health_timeline = - health_timeline_at(&observation.trend, observation.range.end, self.timezone)?; - let wire_profiles = self - .providers - .dashboard_wire_profiles(&settings.request_profiles); - let max_concurrent_per_account = u64::from(settings.values.max_concurrent_per_account); - let (mut inherited_accounts, mut overridden_slots) = runtime_slots - .map_or((observation.provider_accounts.normal, 0), |slots| { - (slots.inherited_accounts, slots.overridden_slots) - }); - if let (Some(peer), Some(slots)) = (&self.upstream_info, runtime_slots) { - let now = std::time::SystemTime::now(); - for version in &slots.inherited_versions { - if let Some(limit) = peer.observed_concurrency_limit(version, now) { - inherited_accounts -= 1; - overridden_slots = overridden_slots.saturating_add(u64::from(limit.get())); - } - } - } - let total_slots = (max_concurrent_per_account > 0 || inherited_accounts == 0).then(|| { - inherited_accounts - .saturating_mul(max_concurrent_per_account) - .saturating_add(overridden_slots) - }); - let used_slots = runtime_slots.and_then(|slots| slots.used_slots); - Ok(DashboardResult { - capacity: DashboardCapacity { - max_concurrent_per_account, - total_slots, - used_slots, - available_slots: used_slots - .zip(total_slots) - .map(|(used, total)| total.saturating_sub(used)), - }, - rotation_strategy: settings.rotation_strategy, - observation, - today, - yesterday, - total_billing_usd, - total_cached_token_rate, - average_first_token_latency_ms, - trend, - health_timeline, - wire_profiles, - }) - } -} - -#[async_trait] -impl ObservabilityService for DefaultObservabilityService { - async fn export_diagnostics( - &self, - target: crate::model::diagnostics::DiagnosticTarget, - ) -> Result { - self.collect_diagnostics(target).await - } - - async fn dashboard_summary( - &self, - range: TimeRange, - kind: TrendKind, - ) -> Result { - let mut result = self.load_dashboard_summary(range).await?; - result.trend = trend( - kind, - result.observation.trend.clone(), - result.observation.analytics.clone(), - )?; - Ok(result) - } - - async fn dashboard_trend( - &self, - range: TimeRange, - kind: TrendKind, - ) -> Result { - let observation = self - .store - .usage_insights_observation( - range, - UsageFilter::default(), - Granularity::for_range(range), - false, - ) - .await - .map_err(|error| map_store_error(error, "dashboard trend"))?; - trend(kind, observation.trend, observation.overview.analytics) - } - - async fn usage_records(&self, query: UsageQuery) -> Result { - let mut page = self - .store - .list_usage_records(query) - .await - .map_err(|error| map_store_error(error, "usage records"))?; - self.enrich_list_records(&mut page.items).await; - Ok(page) - } - - async fn usage_record_detail(&self, request_id: &str) -> Result { - if request_id.trim().is_empty() { - return Err(AdminError::invalid("用量记录 ID 不能为空")); - } - let mut detail = self - .store - .usage_record_detail(request_id) - .await - .map_err(|error| map_store_error(error, "usage record"))?; - self.enrich_detail_billing(std::slice::from_mut(&mut detail.request)); - Ok(detail) - } - - async fn client_key_statistics( - &self, - range: TimeRange, - id: &gateway_core::policy::ClientApiKeyId, - query: crate::model::observability::KeyUsageMetric, - ) -> Result { - self.store - .client_key_statistics(range, id, query) - .await - .map_err(|error| map_store_error(error, "client key statistics")) - } - - async fn client_key_models( - &self, - range: TimeRange, - id: &gateway_core::policy::ClientApiKeyId, - ) -> Result, AdminError> { - self.store - .client_key_models(range, id) - .await - .map_err(|error| map_store_error(error, "client key statistics")) - } - - async fn usage_summary( - &self, - range: TimeRange, - filter: UsageFilter, - ) -> Result { - let observation = self - .store - .usage_summary(range, filter) - .await - .map_err(|error| map_store_error(error, "usage summary"))?; - let average_latency_ms = average( - observation.requests.latency_sum_ms, - observation.requests.latency_count, - ); - Ok(UsageSummary { - observation, - average_latency_ms, - }) - } - - async fn usage_insights( - &self, - range: TimeRange, - filter: UsageFilter, - ) -> Result { - let granularity = Granularity::for_range(range); - let observation = self - .store - .usage_insights_observation(range, filter, granularity, true) - .await - .map_err(|error| map_store_error(error, "usage insights"))?; - insights_from_observation(observation) - } - - async fn usage_metric( - &self, - range: TimeRange, - filter: UsageFilter, - metric: UsageInsightMetric, - ) -> Result { - let observation = self - .store - .usage_metric_observation(range, filter, Granularity::for_range(range), metric) - .await - .map_err(|error| map_store_error(error, "usage metric"))?; - let insights = insights_from_observation(observation)?; - Ok(select_usage_metric(insights, metric)) - } - - async fn diagnostics( - &self, - range: TimeRange, - filter: UsageFilter, - dimension: DiagnosticDimension, - ) -> Result { - let observation = self - .store - .usage_diagnostics(range, filter, dimension, 100) - .await - .map_err(|error| map_store_error(error, "usage diagnostics"))?; - let peers = if dimension == DiagnosticDimension::Account { - self.current_upstream_peers(observation.items.iter().map(|item| item.key.as_str())) - .await - } else { - HashMap::new() - }; - let items = observation - .items - .into_iter() - .map(|item| { - let health = RequestHealth::from_counts( - item.success_count, - item.failure_count, - item.cancelled_count, - item.incomplete_count, - item.caller_error_count, - ); - let non_completion_count = - item.cancelled_count.saturating_add(item.incomplete_count); - let non_completion_rate = rate_or_zero(non_completion_count, item.request_count); - let retry_rate = rate_or_zero(item.retried_request_count, item.request_count); - DiagnosticsItem { - account_upstream_peer: peers.get(&item.key).copied(), - key: item.key, - name: item.name, - account_authentication_kind: item.account_authentication_kind, - account_plan_type_display: item.account_provider_kind.as_deref().and_then( - |provider| { - self.providers - .plan_type_display(provider, item.account_plan_type.as_deref()) - }, - ), - account_plan_type: item.account_plan_type, - request_count: item.request_count, - success_count: item.success_count, - error_count: health.non_success_requests(), - error_rate: health.error_ratio(), - request_share: rate_or_zero( - item.request_count, - observation.total_request_count, - ), - average_latency_ms: item.average_latency_ms, - latency_p95_ms: item.latency_p95_ms, - first_token_p95_ms: item.first_token_p95_ms, - non_completion_count, - non_completion_rate, - retry_count: item.retry_count, - retry_rate, - estimated_cost: usd_cost(&item.costs), - attempt_count: item.attempt_count, - total_tokens: item.total_tokens, - } - }) - .collect::>(); - Ok(DiagnosticsResult { - analytics: observation.analytics, - dimension, - items, - }) - } - - async fn ops_errors(&self, query: OpsErrorQuery) -> Result { - let mut page = self - .store - .list_ops_errors(query) - .await - .map_err(|error| map_store_error(error, "operations errors"))?; - for error in &mut page.items { - error.provider_account_plan_type_display = - error.provider_kind.as_deref().and_then(|provider| { - self.providers - .plan_type_display(provider, error.provider_account_plan_type.as_deref()) - }); - } - Ok(page) - } -} - -fn insights_from_observation( - observation: UsageInsightsObservation, -) -> Result { - let mut standard_costs = UsageCostScenarios::default(); - for point in observation.costs { - if let Some(amount) = point.standard_amount { - standard_costs.standard.add(point.bucket_start, amount)?; - } - if let Some(amount) = point.no_cache_amount { - standard_costs.no_cache.add(point.bucket_start, amount)?; - } - } - let overview = observation.overview; - let trend = observation.trend; - build_usage_insights(overview, trend, standard_costs, observation.concurrency) -} - -fn select_usage_metric(insights: UsageInsights, metric: UsageInsightMetric) -> UsageInsight { - let activity = insights - .health - .points - .iter() - .map(|point| (point.bucket_start, point.total_requests)) - .collect::>(); - let data = match metric { - UsageInsightMetric::Health => UsageInsightData::Health(insights.health), - UsageInsightMetric::Latency => UsageInsightData::Latency(metric_series( - insights.performance.latency_percentiles, - insights - .performance - .points - .into_iter() - .map(|point| (point.bucket_start, point.latency_percentiles)), - &activity, - )), - UsageInsightMetric::FirstToken => UsageInsightData::FirstToken(metric_series( - insights.performance.first_token_latency_percentiles, - insights - .performance - .points - .into_iter() - .map(|point| (point.bucket_start, point.first_token_latency_percentiles)), - &activity, - )), - UsageInsightMetric::Throughput => UsageInsightData::Throughput(metric_series( - UsageThroughputPercentiles { - p10: insights.performance.output_throughput_p10, - p50: insights.performance.output_throughput_p50, - p90: insights.performance.output_throughput_p90, - }, - insights.performance.points.into_iter().map(|point| { - ( - point.bucket_start, - UsageThroughputPercentiles { - p10: point.output_throughput_p10, - p50: point.output_throughput_p50, - p90: point.output_throughput_p90, - }, - ) - }), - &activity, - )), - UsageInsightMetric::Load => UsageInsightData::Load(metric_series( - insights.performance.load, - insights - .performance - .points - .into_iter() - .map(|point| (point.bucket_start, point.load)), - &activity, - )), - UsageInsightMetric::Cost => UsageInsightData::Cost(metric_series( - cost_summary(&insights.cost), - insights.cost.points.into_iter().map(|point| { - ( - point.bucket_start, - UsageCostComparison { - estimated_cost: point.estimated_cost, - no_cache_cost: point.no_cache_cost, - }, - ) - }), - &activity, - )), - UsageInsightMetric::Savings => UsageInsightData::Savings(metric_series( - cost_summary(&insights.cost), - insights - .cost - .points - .into_iter() - .map(|point| (point.bucket_start, point.cache_savings)), - &activity, - )), - UsageInsightMetric::Cache => UsageInsightData::Cache(metric_series( - cost_summary(&insights.cost), - insights.cost.points.into_iter().map(|point| { - ( - point.bucket_start, - UsageCacheEfficiency { - input_tokens: point.input_tokens, - cached_token_rate: point.cached_token_rate, - cache_hit_request_rate: point.cache_hit_request_rate, - }, - ) - }), - &activity, - )), - }; - UsageInsight { - analytics: insights.analytics, - granularity: insights.granularity, - data, - } -} - -fn cost_summary(cost: &UsageInsightsCost) -> UsageCostSummary { - UsageCostSummary { - estimated_cost: cost.estimated_cost.clone(), - cache_savings: cost.cache_savings.clone(), - tier_premium: cost.tier_premium.clone(), - cost_per_successful_request: cost.cost_per_successful_request.clone(), - coverage: cost.coverage.clone(), - } -} - -fn metric_series( - summary: S, - points: impl Iterator, P)>, - activity: &BTreeMap, u64>, -) -> UsageMetricSeries { - UsageMetricSeries { - summary, - points: points - .map(|(bucket_start, value)| UsageMetricPoint { - bucket_start, - request_count: activity.get(&bucket_start).copied().unwrap_or_default(), - value, - }) - .collect(), - } -} - -fn build_usage_insights( - overview: UsageOverview, - trend: Vec, - standard_costs: UsageCostScenarios, - concurrency: Vec, -) -> Result { - let granularity = trend.first().map_or( - crate::model::observability::Granularity::FifteenMinutes, - |point| point.granularity, - ); - if trend.iter().any(|point| point.granularity != granularity) { - return Err(AdminError::internal("用量洞察趋势包含不一致的时间粒度")); - } - - let requests = &overview.requests; - let health_window = RequestHealth::from_metrics(requests); - let failed_requests = health_window.failed_requests; - let health = UsageInsightsHealth { - total_requests: requests.request_count, - success_requests: requests.success_count, - failed_requests, - cancelled_requests: requests.cancelled_count, - incomplete_requests: requests.incomplete_count, - caller_error_requests: requests.caller_error_count, - success_rate: health_window.success_ratio(), - completion_rate: rate_or_zero( - requests - .success_count - .saturating_add(requests.failure_count), - requests.request_count, - ), - points: trend - .iter() - .map(|point| { - let health_window = RequestHealth::from_metrics(&point.metrics); - UsageInsightsHealthPoint { - total_requests: point.metrics.request_count, - bucket_start: point.bucket_start, - success_requests: point.metrics.success_count, - failed_requests: health_window.failed_requests, - cancelled_requests: point.metrics.cancelled_count, - incomplete_requests: point.metrics.incomplete_count, - caller_error_requests: point.metrics.caller_error_count, - error_rate: health_window.error_ratio(), - } - }) - .collect(), - }; - let concurrency_by_bucket = concurrency - .iter() - .map(|point| (point.bucket_start, point)) - .collect::>(); - let mut weighted_concurrency_micros = 0.0; - let mut effective_micros = 0_i64; - for (index, point) in concurrency.iter().enumerate() { - let start = point.bucket_start.max(overview.range.start); - let end = concurrency - .get(index + 1) - .map_or(overview.range.end, |next| next.bucket_start) - .min(overview.range.end); - let micros = (end - start).num_microseconds().unwrap_or(0).max(0); - effective_micros = effective_micros.saturating_add(micros); - weighted_concurrency_micros += point.average_concurrency * micros as f64; - } - let average_concurrency = if effective_micros > 0 { - weighted_concurrency_micros / effective_micros as f64 - } else { - 0.0 - }; - let peak_concurrency = concurrency - .iter() - .map(|point| point.peak_concurrency) - .max() - .unwrap_or(0); - let performance = UsageInsightsPerformance { - latency_percentiles: requests.latency_percentiles, - first_token_latency_percentiles: requests.first_token_latency_percentiles, - output_throughput_p10: requests.output_throughput_p10, - output_throughput_p50: requests.output_throughput_p50, - output_throughput_p90: requests.output_throughput_p90, - load: UsageInsightsLoad { - average_concurrency, - peak_concurrency, - admission_decision_p95_ms: requests.admission_decision_percentiles.p95_ms, - account_selection_wait_p95_ms: requests.account_selection_wait_percentiles.p95_ms, - }, - points: trend - .iter() - .map(|point| { - let concurrency = concurrency_by_bucket.get(&point.bucket_start); - UsageInsightsPerformancePoint { - bucket_start: point.bucket_start, - latency_percentiles: point.metrics.latency_percentiles, - first_token_latency_percentiles: point.metrics.first_token_latency_percentiles, - output_throughput_p10: point.metrics.output_throughput_p10, - output_throughput_p50: point.metrics.output_throughput_p50, - output_throughput_p90: point.metrics.output_throughput_p90, - load: UsageInsightsLoad { - average_concurrency: concurrency - .map_or(0.0, |point| point.average_concurrency), - peak_concurrency: concurrency.map_or(0, |point| point.peak_concurrency), - admission_decision_p95_ms: point - .metrics - .admission_decision_percentiles - .p95_ms, - account_selection_wait_p95_ms: point - .metrics - .account_selection_wait_percentiles - .p95_ms, - }, - } - }) - .collect(), - }; - let estimated_cost = usd_cost(&overview.attempts.costs); - let UsageCostScenarios { - standard: - ScenarioCosts { - total: standard_cost, - by_bucket: standard_costs_by_bucket, - }, - no_cache: - ScenarioCosts { - total: no_cache_cost, - by_bucket: no_cache_costs_by_bucket, - }, - } = standard_costs; - let cache_savings = amount_difference(no_cache_cost.as_ref(), estimated_cost.as_ref()); - let tier_premium = amount_difference(estimated_cost.as_ref(), standard_cost.as_ref()); - let cost_per_request = estimated_cost - .as_ref() - .and_then(|cost| cost.checked_div_u64(requests.request_count)); - let cost_per_successful_request = estimated_cost - .as_ref() - .and_then(|cost| cost.checked_div_u64(requests.success_count)); - let cost = UsageInsightsCost { - cost_per_request, - estimated_cost, - standard_cost, - no_cache_cost, - cache_savings, - tier_premium, - tokens_per_request: rate_or_zero(requests.total_tokens, requests.request_count), - cost_per_successful_request, - cached_token_rate: rate_or_zero(requests.cached_input_tokens, requests.input_tokens), - cache_hit_request_rate: ratio( - requests.cache_hit_request_count, - requests.cache_eligible_request_count, - ), - input_tokens: requests.input_tokens, - output_tokens: requests.output_tokens, - cached_input_tokens: requests.cached_input_tokens, - total_tokens: requests.total_tokens, - points: trend - .iter() - .map(|point| UsageInsightsCostPoint { - bucket_start: point.bucket_start, - input_tokens: point.metrics.input_tokens, - output_tokens: point.metrics.output_tokens, - cached_input_tokens: point.metrics.cached_input_tokens, - total_tokens: point.metrics.total_tokens, - estimated_cost: usd_cost(&point.costs), - standard_cost: standard_costs_by_bucket.get(&point.bucket_start).cloned(), - no_cache_cost: no_cache_costs_by_bucket.get(&point.bucket_start).cloned(), - cache_savings: amount_difference( - no_cache_costs_by_bucket.get(&point.bucket_start), - usd_cost(&point.costs).as_ref(), - ), - cached_token_rate: rate_or_zero( - point.metrics.cached_input_tokens, - point.metrics.input_tokens, - ), - cache_hit_request_rate: ratio( - point.metrics.cache_hit_request_count, - point.metrics.cache_eligible_request_count, - ), - }) - .collect(), - costs: overview.attempts.costs.clone(), - coverage: overview.attempts.cost_coverage.clone(), - }; - Ok(UsageInsights { - analytics: overview.analytics, - granularity, - health, - performance, - cost, - attempts: overview.attempts, - providers: overview.providers, - }) -} - -#[derive(Debug, Default)] -struct ScenarioCosts { - total: Option, - by_bucket: BTreeMap, DecimalAmount>, -} - -impl ScenarioCosts { - fn add( - &mut self, - bucket_start: DateTime, - amount: DecimalAmount, - ) -> Result<(), AdminError> { - self.total = Some(match self.total.take() { - Some(current) => current - .checked_add(&amount) - .ok_or_else(|| AdminError::internal("用量标准成本超出数值范围"))?, - None => amount.clone(), - }); - match self.by_bucket.entry(bucket_start) { - Entry::Occupied(mut entry) => { - let sum = entry - .get() - .checked_add(&amount) - .ok_or_else(|| AdminError::internal("用量标准成本超出数值范围"))?; - entry.insert(sum); - } - Entry::Vacant(entry) => { - entry.insert(amount); - } - } - Ok(()) - } -} - -#[derive(Debug, Default)] -struct UsageCostScenarios { - standard: ScenarioCosts, - no_cache: ScenarioCosts, -} - -/// 在后台投影时恢复费用场景,查询不再逐请求读取计费快照 -pub struct ProviderUsageBillingProjector { - providers: ProviderAdminRegistry, -} - -impl ProviderUsageBillingProjector { - #[must_use] - pub fn new(providers: ProviderAdminRegistry) -> Self { - Self { providers } - } -} - -impl UsageBillingProjector for ProviderUsageBillingProjector { - fn project( - &self, - fact: &UsageCalculatedBillingFact, - ) -> Result { - let Ok(provider_kind) = ProviderKind::new(fact.provider_kind.clone()) else { - return Ok(UsageBillingProjection::default()); - }; - let input = ProviderBillingInput { - upstream_model_id: fact.upstream_model_id.clone(), - service_tier: fact.service_tier.clone(), - input_tokens: fact.input_tokens, - output_tokens: fact.output_tokens, - cached_input_tokens: fact.cached_input_tokens, - cache_write_input_tokens: fact.cache_write_input_tokens, - total: fact.total.clone(), - }; - let breakdown = match fact - .breakdown - .as_ref() - .filter(|breakdown| breakdown.total_amount == input.total) - .cloned() - .map_or_else( - || self.providers.calculated_billing(&provider_kind, &input), - |breakdown| Ok(Some(breakdown)), - ) { - Ok(breakdown) => breakdown, - Err(error) if error.kind() == ProviderAdminErrorKind::Unsupported => { - return Ok(UsageBillingProjection::default()); - } - Err(error) => return Err(map_provider_error(error, "usage billing")), - }; - let Some(breakdown) = breakdown else { - return Ok(UsageBillingProjection::default()); - }; - if !breakdown - .standard_amount - .currency - .eq_ignore_ascii_case("USD") - { - return Ok(UsageBillingProjection::default()); - } - Ok(UsageBillingProjection { - standard_amount: Some(breakdown.standard_amount.amount.clone()), - no_cache_amount: no_cache_cost(fact, &breakdown), - }) - } -} - -fn no_cache_cost( - fact: &UsageCalculatedBillingFact, - breakdown: &crate::model::observability::CalculatedBillingBreakdown, -) -> Option { - let image = breakdown.image.as_ref(); - let input_tokens = fact - .input_tokens? - .checked_sub(image.map_or(0, |i| i.input_tokens))?; - let cached_input_tokens = fact - .cached_input_tokens - .unwrap_or_default() - .checked_sub(image.map_or(0, |i| i.cached_input_tokens))? - .min(input_tokens); - let cache_write_input_tokens = fact - .cache_write_input_tokens - .unwrap_or_default() - .min(input_tokens.saturating_sub(cached_input_tokens)); - let input_rate = decimal(&breakdown.input_price_per_million.amount)?; - let replaced_input_amount = input_rate - .scaled() - .checked_mul(u128::from( - cached_input_tokens.saturating_add(cache_write_input_tokens), - ))? - .checked_div(1_000_000)?; - let mut total = decimal(&breakdown.total_amount.amount)? - .scaled() - .checked_sub(decimal(&breakdown.cache_read_amount.amount)?.scaled())? - .checked_sub(decimal(&breakdown.cache_write_amount.amount)?.scaled())? - .checked_add(replaced_input_amount)?; - if let Some(image) = image { - let image_no_cache = decimal(&image.input_price_per_million.amount)? - .scaled() - .checked_mul(u128::from(image.cached_input_tokens))? - .checked_div(1_000_000)?; - total = total - .checked_sub(decimal(&image.cache_read_amount.amount)?.scaled())? - .checked_add(image_no_cache)?; - } - DecimalAmount::from_str( - &gateway_core::metering::Decimal::from_scaled(total) - .ok()? - .canonical(), - ) - .ok() -} - -fn amount_difference( - larger: Option<&DecimalAmount>, - smaller: Option<&DecimalAmount>, -) -> Option { - let difference = decimal(larger?)? - .scaled() - .checked_sub(decimal(smaller?)?.scaled())?; - DecimalAmount::from_str( - &gateway_core::metering::Decimal::from_scaled(difference) - .ok()? - .canonical(), - ) - .ok() -} - -fn decimal(value: &DecimalAmount) -> Option { - value.as_str().parse().ok() -} - -fn usd_cost(costs: &[CurrencyCost]) -> Option { - costs - .iter() - .find(|cost| cost.currency.eq_ignore_ascii_case("USD")) - .map(|cost| cost.amount.clone()) -} - -impl DefaultObservabilityService { - async fn current_upstream_peers<'a>( - &self, - ids: impl Iterator, - ) -> HashMap { - let Some(peer) = self.upstream_info.as_deref() else { - return HashMap::new(); - }; - let ids = ids - .map(str::to_owned) - .collect::>(); - // 同一页重复账号只读取一次摘要,单个账号不存在或读取失败不阻断历史记录 - futures::stream::iter(ids) - .map(|id: String| async move { - let account_id = ProviderAccountId::new(id.clone()).ok()?; - let upstream = peer.read_summary(&account_id).await.ok()??.upstream?; - Some((id, upstream.discovered && upstream.observed_at.is_some())) - }) - .buffer_unordered(8) - .filter_map(|value| async move { value }) - .collect() - .await - } - - async fn enrich_dashboard_quotas(&self, accounts: &mut [DashboardAccountUsage]) { - if accounts.is_empty() { - return; - } - let now = Utc::now(); - let ids = accounts - .iter() - .map(|account| account.account_id.clone()) - .collect::>(); - let mut rolling_usage = self - .accounts - .load_account_usage( - TimeRange { - start: now - Duration::hours(24), - end: now, - }, - &ids, - ) - .await - .unwrap_or_default() - .into_iter() - .map(|usage| (usage.account_id.clone(), usage)) - .collect::>(); - let providers = self.providers.clone(); - let peer = self.upstream_info.as_deref(); - let quota_reads = accounts.iter().map(|account| { - let rolling_usage = rolling_usage.remove(&account.account_id); - let account_id = ProviderAccountId::new(account.account_id.clone()).ok(); - let provider = ProviderKind::new(account.provider_kind.clone()) - .ok() - .and_then(|kind| providers.require(&kind).ok()); - async move { - let (Some(account_id), Some(provider)) = (account_id, provider) else { - return None; - }; - if let Some(peer) = peer - && let Ok(Some(quota)) = peer.read_summary(&account_id).await - { - return Some(quota); - } - provider - .quota(ProviderQuotaRequest { - account_id, - refresh: false, - rolling_usage, - }) - .await - .ok() - } - }); - let quotas = futures::future::join_all(quota_reads).await; - for (account, quota) in accounts.iter_mut().zip(quotas) { - if let Some(mut quota) = quota { - quota.fill_missing_plan_type(&mut account.plan_type); - quota.apply_limit_reached_display(); - account.quota_used_percent = quota.representative_used_percent(); - account.quota_window = quota.representative_window().cloned(); - account.upstream = quota.upstream; - } - } - } - - /// 补充当前套餐展示名称,逐条尽力把可校验的总额升级为完整分解;单条脏数据(非法 Provider kind、 - /// 不支持的来源或费用规则失败)只保留该条已存的总额,不影响整页返回 - async fn enrich_list_records( - &self, - records: &mut [crate::model::observability::UsageListRecord], - ) { - let peers = self - .current_upstream_peers( - records - .iter() - .filter_map(|record| record.provider_account_ref.as_deref()), - ) - .await; - for record in records { - record.provider_account_upstream_peer = record - .provider_account_ref - .as_ref() - .and_then(|id| peers.get(id).copied()); - record.provider_account_plan_type_display = - record.provider_kind.as_deref().and_then(|provider| { - self.providers - .plan_type_display(provider, record.provider_account_plan_type.as_deref()) - }); - let Some(UsageBilling::Total { source, total }) = record.billing.as_ref() else { - continue; - }; - if !matches!(source.as_str(), "calculated" | "provider_reported") { - continue; - } - let (Some(provider), Some(upstream_model_id)) = ( - record.provider_kind.as_deref(), - record.upstream_model_id.as_ref(), - ) else { - continue; - }; - let Ok(provider_kind) = ProviderKind::new(provider.to_owned()) else { - continue; - }; - let input = ProviderBillingInput { - upstream_model_id: upstream_model_id.clone(), - service_tier: record.service_tier.clone(), - input_tokens: record.input_tokens, - output_tokens: record.output_tokens, - cached_input_tokens: record.cached_input_tokens, - cache_write_input_tokens: record.cache_write_input_tokens, - total: total.clone(), - }; - if let Ok(Some(breakdown)) = self.providers.calculated_billing(&provider_kind, &input) { - record.billing = Some(UsageBilling::Calculated(Box::new(breakdown))); - } - } - } - - fn enrich_detail_billing(&self, records: &mut [crate::model::observability::UsageRecord]) { - for record in records { - let Some(UsageBilling::Total { source, total }) = record.billing.as_ref() else { - continue; - }; - if !matches!(source.as_str(), "calculated" | "provider_reported") { - continue; - } - let (Some(provider), Some(upstream_model_id)) = ( - record.provider_kind.as_deref(), - record.upstream_model_id.as_ref(), - ) else { - continue; - }; - let Ok(provider_kind) = ProviderKind::new(provider.to_owned()) else { - continue; - }; - let input = ProviderBillingInput { - upstream_model_id: upstream_model_id.clone(), - service_tier: record.service_tier.clone(), - input_tokens: record.input_tokens, - output_tokens: record.output_tokens, - cached_input_tokens: record.cached_input_tokens, - cache_write_input_tokens: record.cache_write_input_tokens, - total: total.clone(), - }; - if let Ok(Some(breakdown)) = self.providers.calculated_billing(&provider_kind, &input) { - record.billing = Some(UsageBilling::Calculated(Box::new(breakdown))); - } - } - } -} - -/// 按部署时区的自然日计算 15 分钟健康桶,桶数随夏令时变化 -pub(super) fn health_timeline_at( - records: &[RequestMetricPoint], - now: DateTime, - timezone: gateway_core::time::DeploymentTimeZone, -) -> Result { - let start = timezone - .day_start(now) - .ok_or_else(|| AdminError::internal("时间超出支持范围"))?; - let end = timezone - .days_after(now, 1) - .ok_or_else(|| AdminError::internal("时间超出支持范围"))?; - let current_slot = start - + Duration::minutes( - (now - start) - .num_minutes() - .div_euclid(HEALTH_TIMELINE_SLOT_MINUTES) - * HEALTH_TIMELINE_SLOT_MINUTES, - ); - let slots = ((end - start).num_minutes() + HEALTH_TIMELINE_SLOT_MINUTES - 1) - / HEALTH_TIMELINE_SLOT_MINUTES; - let mut buckets = (0..slots) - .map(|index| { - ( - start + Duration::minutes(HEALTH_TIMELINE_SLOT_MINUTES * index), - RequestHealth::default(), - ) - }) - .collect::>(); - for record in records { - if record.bucket_start < start || record.bucket_start > now { - continue; - } - let record_slot = start - + Duration::minutes( - (record.bucket_start - start) - .num_minutes() - .div_euclid(HEALTH_TIMELINE_SLOT_MINUTES) - * HEALTH_TIMELINE_SLOT_MINUTES, - ); - if let Some((_, bucket)) = buckets - .iter_mut() - .find(|(bucket_start, _)| *bucket_start == record_slot) - { - bucket.add_metrics(&record.metrics); - } - } - - let totals = buckets - .iter() - .filter(|(bucket_start, _)| *bucket_start <= current_slot) - .fold(RequestHealth::default(), |mut totals, (_, bucket)| { - totals.add_window(*bucket); - totals - }); - Ok(HealthTimeline { - reliability_percent: health_reliability(totals), - status: health_status(totals, false), - success_requests: totals.success_requests, - failed_requests: totals.failed_requests, - cancelled_requests: totals.cancelled_requests, - incomplete_requests: totals.incomplete_requests, - caller_error_requests: totals.caller_error_requests, - points: buckets - .into_iter() - .map(|(bucket_start, bucket)| HealthTimelinePoint { - bucket_start, - status: health_status(bucket, bucket_start > current_slot), - reliability_percent: health_reliability(bucket), - success_requests: bucket.success_requests, - failed_requests: bucket.failed_requests, - cancelled_requests: bucket.cancelled_requests, - incomplete_requests: bucket.incomplete_requests, - caller_error_requests: bucket.caller_error_requests, - }) - .collect(), - }) -} - -fn trend( - kind: TrendKind, - points: Vec, - analytics: crate::model::analytics::AnalyticsMetadata, -) -> Result { - let mut metrics = RequestMetrics::default(); - let mut coverage = CostCoverage::default(); - let mut costs = BTreeMap::::new(); - for point in &points { - add_request_metrics(&mut metrics, &point.metrics); - coverage.provider_reported_count = coverage - .provider_reported_count - .saturating_add(point.cost_coverage.provider_reported_count); - coverage.calculated_count = coverage - .calculated_count - .saturating_add(point.cost_coverage.calculated_count); - coverage.partial_count = coverage - .partial_count - .saturating_add(point.cost_coverage.partial_count); - coverage.unavailable_count = coverage - .unavailable_count - .saturating_add(point.cost_coverage.unavailable_count); - coverage.not_billable_count = coverage - .not_billable_count - .saturating_add(point.cost_coverage.not_billable_count); - for cost in &point.costs { - if let Some(amount) = costs.get_mut(&cost.currency) { - *amount = amount - .checked_add(&cost.amount) - .ok_or_else(|| AdminError::internal("成本聚合结果超出数值范围"))?; - } else { - costs.insert(cost.currency.clone(), cost.amount.clone()); - } - } - } - let average_latency_ms = average(metrics.latency_sum_ms, metrics.latency_count); - let health = RequestHealth::from_metrics(&metrics); - let error_count = health.non_success_requests(); - let success_rate = health.success_ratio(); - let cache_hit_request_rate = ratio( - metrics.cache_hit_request_count, - metrics.cache_eligible_request_count, - ); - let peak_first_token_p95_ms = points - .iter() - .filter_map(|point| point.metrics.first_token_latency_percentiles.p95_ms) - .map(|value| value.as_f64()) - .reduce(f64::max); - let peak_latency_p95_ms = points - .iter() - .filter_map(|point| point.metrics.latency_percentiles.p95_ms) - .map(|value| value.as_f64()) - .reduce(f64::max); - let minimum_output_throughput_p50 = points - .iter() - .filter_map(|point| point.metrics.output_throughput_p50) - .min(); - Ok(Trend { - analytics, - kind, - points: points.into_iter().map(trend_point).collect(), - summary: TrendSummary { - request_count: metrics.request_count, - input_tokens: metrics.input_tokens, - output_tokens: metrics.output_tokens, - cached_input_tokens: metrics.cached_input_tokens, - total_tokens: metrics.total_tokens, - error_count, - average_latency_ms, - max_latency_ms: metrics.max_latency_ms, - min_latency_ms: metrics.min_latency_ms, - peak_first_token_p95_ms, - peak_latency_p95_ms, - minimum_output_throughput_p50, - success_rate, - cache_hit_request_rate, - costs: costs - .into_iter() - .map(|(currency, amount)| CurrencyCost { currency, amount }) - .collect(), - cost_coverage: coverage, - }, - }) -} - -fn trend_point(point: RequestMetricPoint) -> TrendPoint { - let health = RequestHealth::from_metrics(&point.metrics); - TrendPoint { - bucket_start: point.bucket_start, - granularity: point.granularity, - error_count: health.non_success_requests(), - average_latency_ms: average(point.metrics.latency_sum_ms, point.metrics.latency_count), - average_first_token_latency_ms: average( - point.metrics.first_token_latency_sum_ms, - point.metrics.first_token_latency_count, - ), - cached_token_rate: rate_or_zero( - point.metrics.cached_input_tokens, - point.metrics.input_tokens, - ), - cache_hit_request_rate: ratio( - point.metrics.cache_hit_request_count, - point.metrics.cache_eligible_request_count, - ), - success_rate: health.success_ratio(), - metrics: point.metrics, - cost_coverage: point.cost_coverage, - costs: point.costs, - } -} - -fn dashboard_period_metrics<'a>( - metrics: impl IntoIterator, -) -> DashboardPeriodMetrics { - let mut result = DashboardPeriodMetrics::default(); - for metrics in metrics { - result.request_count = result.request_count.saturating_add(metrics.request_count); - result.input_tokens = result.input_tokens.saturating_add(metrics.input_tokens); - result.output_tokens = result.output_tokens.saturating_add(metrics.output_tokens); - result.cached_input_tokens = result - .cached_input_tokens - .saturating_add(metrics.cached_input_tokens); - result.total_tokens = result.total_tokens.saturating_add(metrics.total_tokens); - } - result.cached_token_rate = rate_or_zero(result.cached_input_tokens, result.input_tokens); - result.observed_cached_token_rate = ratio(result.cached_input_tokens, result.input_tokens); - result -} - -fn add_request_metrics(total: &mut RequestMetrics, value: &RequestMetrics) { - total.request_count = total.request_count.saturating_add(value.request_count); - total.success_count = total.success_count.saturating_add(value.success_count); - total.failure_count = total.failure_count.saturating_add(value.failure_count); - total.cancelled_count = total.cancelled_count.saturating_add(value.cancelled_count); - total.incomplete_count = total - .incomplete_count - .saturating_add(value.incomplete_count); - total.caller_error_count = total - .caller_error_count - .saturating_add(value.caller_error_count); - total.input_tokens = total.input_tokens.saturating_add(value.input_tokens); - total.output_tokens = total.output_tokens.saturating_add(value.output_tokens); - total.cached_input_tokens = total - .cached_input_tokens - .saturating_add(value.cached_input_tokens); - total.cache_write_input_tokens = total - .cache_write_input_tokens - .saturating_add(value.cache_write_input_tokens); - total.reasoning_output_tokens = total - .reasoning_output_tokens - .saturating_add(value.reasoning_output_tokens); - total.total_tokens = total.total_tokens.saturating_add(value.total_tokens); - total.first_token_latency_sum_ms = total - .first_token_latency_sum_ms - .saturating_add(value.first_token_latency_sum_ms); - total.first_token_latency_count = total - .first_token_latency_count - .saturating_add(value.first_token_latency_count); - total.latency_sum_ms = total.latency_sum_ms.saturating_add(value.latency_sum_ms); - total.latency_count = total.latency_count.saturating_add(value.latency_count); - total.min_latency_ms = match (total.min_latency_ms, value.min_latency_ms) { - (Some(left), Some(right)) => Some(left.min(right)), - (left, right) => left.or(right), - }; - total.max_latency_ms = match (total.max_latency_ms, value.max_latency_ms) { - (Some(left), Some(right)) => Some(left.max(right)), - (left, right) => left.or(right), - }; - total.cache_eligible_request_count = total - .cache_eligible_request_count - .saturating_add(value.cache_eligible_request_count); - total.cache_hit_request_count = total - .cache_hit_request_count - .saturating_add(value.cache_hit_request_count); -} - -fn average(sum: u64, count: u64) -> Option { - (count > 0).then(|| sum / count) -} - -fn ratio(numerator: u64, denominator: u64) -> Option { - (denominator > 0).then(|| numerator as f64 / denominator as f64) -} - -fn rate_or_zero(numerator: u64, denominator: u64) -> f64 { - ratio(numerator, denominator).unwrap_or(0.0) -} - -fn health_status(bucket: RequestHealth, is_future: bool) -> HealthStatus { - let eligible_requests = bucket.eligible_requests(); - if is_future { - HealthStatus::Future - } else if eligible_requests == 0 { - HealthStatus::NoData - } else if bucket.success_requests == 0 - && bucket.non_success_requests() >= HEALTH_TIMELINE_UNAVAILABLE_FAILURE_THRESHOLD - { - HealthStatus::Unavailable - } else if eligible_requests < HEALTH_TIMELINE_MIN_SAMPLE_SIZE { - HealthStatus::LowSample - } else if health_reliability(bucket) - .is_some_and(|reliability| reliability < HEALTH_TIMELINE_STABLE_RELIABILITY) - { - HealthStatus::Unstable - } else { - HealthStatus::Stable - } -} - -fn health_reliability(bucket: RequestHealth) -> Option { - bucket.success_rate() -} diff --git a/backend/crates/gateway-admin/src/use_case/observability/service.rs b/backend/crates/gateway-admin/src/use_case/observability/service.rs new file mode 100644 index 000000000..10271aa70 --- /dev/null +++ b/backend/crates/gateway-admin/src/use_case/observability/service.rs @@ -0,0 +1,610 @@ +//! 观测查询与账号信息补充的用例协调 + +use super::billing::usd_cost; +use super::dashboard::{dashboard_period_metrics, health_timeline_at, trend}; +use super::insights::{insights_from_observation, select_usage_metric}; +use super::metrics::{average, rate_or_zero}; +use crate::model::AdminError; +use crate::model::observability::{ + DashboardAccountUsage, DashboardCapacity, DashboardQuery, DashboardResult, DiagnosticDimension, + DiagnosticsItem, DiagnosticsResult, Granularity, OpsErrorPage, OpsErrorQuery, + ProviderBillingInput, RequestHealth, TimeRange, Trend, TrendKind, UsageBilling, UsageDetail, + UsageFilter, UsageInsight, UsageInsightMetric, UsageInsights, UsagePage, UsageQuery, + UsageSummary, +}; +use crate::model::provider_credentials::ProviderQuotaRequest; +use crate::ports::provider::ProviderAdminRegistry; +use crate::ports::store::{AccountStore, ObservabilityStore, SettingsStore}; +use crate::use_case::map_store_error; +use async_trait::async_trait; +use chrono::{Duration, Utc}; +use futures::StreamExt as _; +use gateway_core::account::ProviderAccountId; +use gateway_core::routing::ProviderKind; +use std::collections::HashMap; +use std::sync::Arc; + +/// API 消费的观测控制面服务 +#[async_trait] +pub trait ObservabilityService: Send + Sync { + async fn dashboard_summary( + &self, + range: TimeRange, + kind: TrendKind, + ) -> Result; + async fn dashboard_trend(&self, range: TimeRange, kind: TrendKind) + -> Result; + async fn usage_records(&self, query: UsageQuery) -> Result; + async fn usage_record_detail(&self, request_id: &str) -> Result; + async fn client_key_statistics( + &self, + range: TimeRange, + id: &gateway_core::policy::ClientApiKeyId, + query: crate::model::observability::KeyUsageMetric, + ) -> Result; + + async fn client_key_models( + &self, + range: TimeRange, + id: &gateway_core::policy::ClientApiKeyId, + ) -> Result, AdminError>; + + async fn usage_summary( + &self, + range: TimeRange, + filter: UsageFilter, + ) -> Result; + async fn usage_insights( + &self, + range: TimeRange, + filter: UsageFilter, + ) -> Result; + async fn usage_metric( + &self, + range: TimeRange, + filter: UsageFilter, + metric: UsageInsightMetric, + ) -> Result; + async fn diagnostics( + &self, + range: TimeRange, + filter: UsageFilter, + dimension: DiagnosticDimension, + ) -> Result; + async fn ops_errors(&self, query: OpsErrorQuery) -> Result; + async fn export_diagnostics( + &self, + target: crate::model::diagnostics::DiagnosticTarget, + ) -> Result; +} + +pub(crate) struct DefaultObservabilityService { + pub(super) timezone: gateway_core::time::DeploymentTimeZone, + pub(super) store: Arc, + pub(super) accounts: Arc, + pub(super) settings: Arc, + pub(super) providers: ProviderAdminRegistry, + pub(super) system: Arc, + pub(super) upstream_info: Option>, +} + +impl DefaultObservabilityService { + #[must_use] + pub(crate) fn new( + store: Arc, + accounts: Arc, + settings: Arc, + providers: ProviderAdminRegistry, + timezone: gateway_core::time::DeploymentTimeZone, + system: Arc, + upstream_info: Option>, + ) -> Self { + Self { + timezone, + store, + accounts, + settings, + providers, + system, + upstream_info, + } + } + + async fn load_dashboard_summary( + &self, + range: TimeRange, + ) -> Result { + let observed_at = Utc::now(); + let query = DashboardQuery::new(range, self.timezone) + .map_err(|_| AdminError::internal("时间超出支持范围"))?; + let today_start = query.yesterday_range.end; + let (mut observation, settings) = futures::try_join!( + self.store.dashboard_summary(query, observed_at), + self.settings.load_runtime_settings(), + ) + .map_err(|error| map_store_error(error, "dashboard"))?; + let runtime_slots = observation.runtime_slots.as_ref(); + self.enrich_list_records(&mut observation.recent_requests) + .await; + self.enrich_dashboard_quotas(&mut observation.account_usage) + .await; + for account in &mut observation.account_usage { + account.plan_type_display = self + .providers + .plan_type_display(&account.provider_kind, account.plan_type.as_deref()); + } + let today = dashboard_period_metrics( + observation + .trend + .iter() + .filter(|point| { + point.bucket_start >= today_start && point.bucket_start < observation.range.end + }) + .map(|point| &point.metrics), + ); + let yesterday = dashboard_period_metrics(std::iter::once(&observation.yesterday)); + let total_billing_usd = observation.totals.billing_usd.clone(); + let total_cached_token_rate = rate_or_zero( + observation.totals.cached_input_tokens, + observation.totals.input_tokens, + ); + let (first_token_latency_sum_ms, first_token_latency_count) = observation + .trend + .iter() + .fold((0_u64, 0_u64), |(sum, count), point| { + ( + sum.saturating_add(point.metrics.first_token_latency_sum_ms), + count.saturating_add(point.metrics.first_token_latency_count), + ) + }); + let average_first_token_latency_ms = + average(first_token_latency_sum_ms, first_token_latency_count); + let trend = trend( + TrendKind::Usage, + observation.trend.clone(), + observation.analytics.clone(), + )?; + let health_timeline = + health_timeline_at(&observation.trend, observation.range.end, self.timezone)?; + let wire_profiles = self + .providers + .dashboard_wire_profiles(&settings.request_profiles); + let max_concurrent_per_account = u64::from(settings.values.max_concurrent_per_account); + let (mut inherited_accounts, mut overridden_slots) = runtime_slots + .map_or((observation.provider_accounts.normal, 0), |slots| { + (slots.inherited_accounts, slots.overridden_slots) + }); + if let (Some(peer), Some(slots)) = (&self.upstream_info, runtime_slots) { + let now = std::time::SystemTime::now(); + for version in &slots.inherited_versions { + if let Some(limit) = peer.observed_concurrency_limit(version, now) { + inherited_accounts -= 1; + overridden_slots = overridden_slots.saturating_add(u64::from(limit.get())); + } + } + } + let total_slots = (max_concurrent_per_account > 0 || inherited_accounts == 0).then(|| { + inherited_accounts + .saturating_mul(max_concurrent_per_account) + .saturating_add(overridden_slots) + }); + let used_slots = runtime_slots.and_then(|slots| slots.used_slots); + Ok(DashboardResult { + capacity: DashboardCapacity { + max_concurrent_per_account, + total_slots, + used_slots, + available_slots: used_slots + .zip(total_slots) + .map(|(used, total)| total.saturating_sub(used)), + }, + rotation_strategy: settings.rotation_strategy, + observation, + today, + yesterday, + total_billing_usd, + total_cached_token_rate, + average_first_token_latency_ms, + trend, + health_timeline, + wire_profiles, + }) + } +} + +#[async_trait] +impl ObservabilityService for DefaultObservabilityService { + async fn export_diagnostics( + &self, + target: crate::model::diagnostics::DiagnosticTarget, + ) -> Result { + self.collect_diagnostics(target).await + } + + async fn dashboard_summary( + &self, + range: TimeRange, + kind: TrendKind, + ) -> Result { + let mut result = self.load_dashboard_summary(range).await?; + result.trend = trend( + kind, + result.observation.trend.clone(), + result.observation.analytics.clone(), + )?; + Ok(result) + } + + async fn dashboard_trend( + &self, + range: TimeRange, + kind: TrendKind, + ) -> Result { + let observation = self + .store + .usage_insights_observation( + range, + UsageFilter::default(), + Granularity::for_range(range), + false, + ) + .await + .map_err(|error| map_store_error(error, "dashboard trend"))?; + trend(kind, observation.trend, observation.overview.analytics) + } + + async fn usage_records(&self, query: UsageQuery) -> Result { + let mut page = self + .store + .list_usage_records(query) + .await + .map_err(|error| map_store_error(error, "usage records"))?; + self.enrich_list_records(&mut page.items).await; + Ok(page) + } + + async fn usage_record_detail(&self, request_id: &str) -> Result { + if request_id.trim().is_empty() { + return Err(AdminError::invalid("用量记录 ID 不能为空")); + } + let mut detail = self + .store + .usage_record_detail(request_id) + .await + .map_err(|error| map_store_error(error, "usage record"))?; + self.enrich_detail_billing(std::slice::from_mut(&mut detail.request)); + Ok(detail) + } + + async fn client_key_statistics( + &self, + range: TimeRange, + id: &gateway_core::policy::ClientApiKeyId, + query: crate::model::observability::KeyUsageMetric, + ) -> Result { + self.store + .client_key_statistics(range, id, query) + .await + .map_err(|error| map_store_error(error, "client key statistics")) + } + + async fn client_key_models( + &self, + range: TimeRange, + id: &gateway_core::policy::ClientApiKeyId, + ) -> Result, AdminError> { + self.store + .client_key_models(range, id) + .await + .map_err(|error| map_store_error(error, "client key statistics")) + } + + async fn usage_summary( + &self, + range: TimeRange, + filter: UsageFilter, + ) -> Result { + let observation = self + .store + .usage_summary(range, filter) + .await + .map_err(|error| map_store_error(error, "usage summary"))?; + let average_latency_ms = average( + observation.requests.latency_sum_ms, + observation.requests.latency_count, + ); + Ok(UsageSummary { + observation, + average_latency_ms, + }) + } + + async fn usage_insights( + &self, + range: TimeRange, + filter: UsageFilter, + ) -> Result { + let granularity = Granularity::for_range(range); + let observation = self + .store + .usage_insights_observation(range, filter, granularity, true) + .await + .map_err(|error| map_store_error(error, "usage insights"))?; + insights_from_observation(observation) + } + + async fn usage_metric( + &self, + range: TimeRange, + filter: UsageFilter, + metric: UsageInsightMetric, + ) -> Result { + let observation = self + .store + .usage_metric_observation(range, filter, Granularity::for_range(range), metric) + .await + .map_err(|error| map_store_error(error, "usage metric"))?; + let insights = insights_from_observation(observation)?; + Ok(select_usage_metric(insights, metric)) + } + + async fn diagnostics( + &self, + range: TimeRange, + filter: UsageFilter, + dimension: DiagnosticDimension, + ) -> Result { + let observation = self + .store + .usage_diagnostics(range, filter, dimension, 100) + .await + .map_err(|error| map_store_error(error, "usage diagnostics"))?; + let peers = if dimension == DiagnosticDimension::Account { + self.current_upstream_peers(observation.items.iter().map(|item| item.key.as_str())) + .await + } else { + HashMap::new() + }; + let items = observation + .items + .into_iter() + .map(|item| { + let health = RequestHealth::from_counts( + item.success_count, + item.failure_count, + item.cancelled_count, + item.incomplete_count, + item.caller_error_count, + ); + let non_completion_count = + item.cancelled_count.saturating_add(item.incomplete_count); + let non_completion_rate = rate_or_zero(non_completion_count, item.request_count); + let retry_rate = rate_or_zero(item.retried_request_count, item.request_count); + DiagnosticsItem { + account_upstream_peer: peers.get(&item.key).copied(), + key: item.key, + name: item.name, + account_authentication_kind: item.account_authentication_kind, + account_plan_type_display: item.account_provider_kind.as_deref().and_then( + |provider| { + self.providers + .plan_type_display(provider, item.account_plan_type.as_deref()) + }, + ), + account_plan_type: item.account_plan_type, + request_count: item.request_count, + success_count: item.success_count, + error_count: health.non_success_requests(), + error_rate: health.error_ratio(), + request_share: rate_or_zero( + item.request_count, + observation.total_request_count, + ), + average_latency_ms: item.average_latency_ms, + latency_p95_ms: item.latency_p95_ms, + first_token_p95_ms: item.first_token_p95_ms, + non_completion_count, + non_completion_rate, + retry_count: item.retry_count, + retry_rate, + estimated_cost: usd_cost(&item.costs), + attempt_count: item.attempt_count, + total_tokens: item.total_tokens, + } + }) + .collect::>(); + Ok(DiagnosticsResult { + analytics: observation.analytics, + dimension, + items, + }) + } + + async fn ops_errors(&self, query: OpsErrorQuery) -> Result { + let mut page = self + .store + .list_ops_errors(query) + .await + .map_err(|error| map_store_error(error, "operations errors"))?; + for error in &mut page.items { + error.provider_account_plan_type_display = + error.provider_kind.as_deref().and_then(|provider| { + self.providers + .plan_type_display(provider, error.provider_account_plan_type.as_deref()) + }); + } + Ok(page) + } +} + +impl DefaultObservabilityService { + async fn current_upstream_peers<'a>( + &self, + ids: impl Iterator, + ) -> HashMap { + let Some(peer) = self.upstream_info.as_deref() else { + return HashMap::new(); + }; + let ids = ids + .map(str::to_owned) + .collect::>(); + // 同一页重复账号只读取一次摘要,单个账号不存在或读取失败不阻断历史记录 + futures::stream::iter(ids) + .map(|id: String| async move { + let account_id = ProviderAccountId::new(id.clone()).ok()?; + let upstream = peer.read_summary(&account_id).await.ok()??.upstream?; + Some((id, upstream.discovered && upstream.observed_at.is_some())) + }) + .buffer_unordered(8) + .filter_map(|value| async move { value }) + .collect() + .await + } + + async fn enrich_dashboard_quotas(&self, accounts: &mut [DashboardAccountUsage]) { + if accounts.is_empty() { + return; + } + let now = Utc::now(); + let ids = accounts + .iter() + .map(|account| account.account_id.clone()) + .collect::>(); + let mut rolling_usage = self + .accounts + .load_account_usage( + TimeRange { + start: now - Duration::hours(24), + end: now, + }, + &ids, + ) + .await + .unwrap_or_default() + .into_iter() + .map(|usage| (usage.account_id.clone(), usage)) + .collect::>(); + let providers = self.providers.clone(); + let peer = self.upstream_info.as_deref(); + let quota_reads = accounts.iter().map(|account| { + let rolling_usage = rolling_usage.remove(&account.account_id); + let account_id = ProviderAccountId::new(account.account_id.clone()).ok(); + let provider = ProviderKind::new(account.provider_kind.clone()) + .ok() + .and_then(|kind| providers.require(&kind).ok()); + async move { + let (Some(account_id), Some(provider)) = (account_id, provider) else { + return None; + }; + if let Some(peer) = peer + && let Ok(Some(quota)) = peer.read_summary(&account_id).await + { + return Some(quota); + } + provider + .quota(ProviderQuotaRequest { + account_id, + refresh: false, + rolling_usage, + }) + .await + .ok() + } + }); + let quotas = futures::future::join_all(quota_reads).await; + for (account, quota) in accounts.iter_mut().zip(quotas) { + if let Some(mut quota) = quota { + quota.fill_missing_plan_type(&mut account.plan_type); + quota.apply_limit_reached_display(); + account.quota_used_percent = quota.representative_used_percent(); + account.quota_window = quota.representative_window().cloned(); + account.upstream = quota.upstream; + } + } + } + + /// 补充当前套餐展示名称,逐条尽力把可校验的总额升级为完整分解;单条脏数据(非法 Provider kind、 + /// 不支持的来源或费用规则失败)只保留该条已存的总额,不影响整页返回 + async fn enrich_list_records( + &self, + records: &mut [crate::model::observability::UsageListRecord], + ) { + let peers = self + .current_upstream_peers( + records + .iter() + .filter_map(|record| record.provider_account_ref.as_deref()), + ) + .await; + for record in records { + record.provider_account_upstream_peer = record + .provider_account_ref + .as_ref() + .and_then(|id| peers.get(id).copied()); + record.provider_account_plan_type_display = + record.provider_kind.as_deref().and_then(|provider| { + self.providers + .plan_type_display(provider, record.provider_account_plan_type.as_deref()) + }); + let Some(UsageBilling::Total { source, total }) = record.billing.as_ref() else { + continue; + }; + if !matches!(source.as_str(), "calculated" | "provider_reported") { + continue; + } + let (Some(provider), Some(upstream_model_id)) = ( + record.provider_kind.as_deref(), + record.upstream_model_id.as_ref(), + ) else { + continue; + }; + let Ok(provider_kind) = ProviderKind::new(provider.to_owned()) else { + continue; + }; + let input = ProviderBillingInput { + upstream_model_id: upstream_model_id.clone(), + service_tier: record.service_tier.clone(), + input_tokens: record.input_tokens, + output_tokens: record.output_tokens, + cached_input_tokens: record.cached_input_tokens, + cache_write_input_tokens: record.cache_write_input_tokens, + total: total.clone(), + }; + if let Ok(Some(breakdown)) = self.providers.calculated_billing(&provider_kind, &input) { + record.billing = Some(UsageBilling::Calculated(Box::new(breakdown))); + } + } + } + + fn enrich_detail_billing(&self, records: &mut [crate::model::observability::UsageRecord]) { + for record in records { + let Some(UsageBilling::Total { source, total }) = record.billing.as_ref() else { + continue; + }; + if !matches!(source.as_str(), "calculated" | "provider_reported") { + continue; + } + let (Some(provider), Some(upstream_model_id)) = ( + record.provider_kind.as_deref(), + record.upstream_model_id.as_ref(), + ) else { + continue; + }; + let Ok(provider_kind) = ProviderKind::new(provider.to_owned()) else { + continue; + }; + let input = ProviderBillingInput { + upstream_model_id: upstream_model_id.clone(), + service_tier: record.service_tier.clone(), + input_tokens: record.input_tokens, + output_tokens: record.output_tokens, + cached_input_tokens: record.cached_input_tokens, + cache_write_input_tokens: record.cache_write_input_tokens, + total: total.clone(), + }; + if let Ok(Some(breakdown)) = self.providers.calculated_billing(&provider_kind, &input) { + record.billing = Some(UsageBilling::Calculated(Box::new(breakdown))); + } + } + } +} diff --git a/backend/crates/gateway-admin/src/use_case/peer_link/projection.rs b/backend/crates/gateway-admin/src/use_case/peer_link/projection.rs index 4e28da684..a216f4c3e 100644 --- a/backend/crates/gateway-admin/src/use_case/peer_link/projection.rs +++ b/backend/crates/gateway-admin/src/use_case/peer_link/projection.rs @@ -74,6 +74,23 @@ pub(super) async fn quota_and_models( let snapshot = client.snapshot(); let scope = client.policy().account_scope(); let mut observations = BTreeMap::<&str, ModelObservations>::new(); + let mut provider_facts = BTreeMap::new(); + for account in accounts { + let kind = &account.provider_kind; + if provider_facts.contains_key(kind) { + continue; + } + if let Ok(provider) = providers.require(kind) { + // 原生事实读取失败时保留未知,不能退回整号 Allowed 冒充各模型可用 + provider_facts.insert( + kind.clone(), + provider + .peer_model_facts(accounts) + .await + .unwrap_or_else(|_| Some(BTreeMap::new())), + ); + } + } let mut model_bytes = 0usize; let mut result = Vec::with_capacity(accounts.len()); for (index, account) in accounts.iter().enumerate() { @@ -94,9 +111,32 @@ pub(super) async fn quota_and_models( { continue; } - let eligible = provider - .as_ref() - .and_then(|provider| provider.peer_model_eligible(account, &upstream)); + let (eligible, observation) = match provider_facts + .get(&account.provider_kind) + .and_then(Option::as_ref) + { + Some(facts) => match facts + .get(&account.id) + .filter(|f| f.credential_revision.get() == account.credential_revision.get()) + { + Some(facts) => match facts.models.get(&upstream) { + Some(quota) => ( + Some(true), + quota.and_then(|quota| { + model_quota_observation(account, runtime, quota, now) + }), + ), + None => (Some(false), None), + }, + None => (None, None), + }, + None => ( + provider + .as_ref() + .and_then(|provider| provider.peer_model_eligible(account, &upstream)), + observation, + ), + }; if eligible == Some(false) { continue; } @@ -205,6 +245,32 @@ struct ModelObservation { expires_at: DateTime, } +fn model_quota_observation( + account: &AccountRecord, + runtime: &AccountRuntimeSnapshot, + quota: crate::ports::provider::ProviderPeerModelQuota, + now: DateTime, +) -> Option { + if !matches!( + status(account, runtime, now), + AccountStatus::Normal | AccountStatus::QuotaExhausted + ) { + return None; + } + let state = match quota.state.access() { + QuotaAccessState::Allowed => PeerModelState::Available, + QuotaAccessState::Exhausted => PeerModelState::Exhausted, + QuotaAccessState::Unknown => return None, + }; + let observed_at = DateTime::::from(quota.state.observed_at()?); + let expires_at = DateTime::::from(quota.valid_until).min(now + TimeDelta::minutes(5)); + (observed_at <= now && expires_at > now).then_some(ModelObservation { + state, + observed_at, + expires_at, + }) +} + #[derive(Default)] struct ModelObservations { incomplete: bool, diff --git a/backend/crates/gateway-admin/src/use_case/settings.rs b/backend/crates/gateway-admin/src/use_case/settings.rs index c72181a0b..7c2ee45ab 100644 --- a/backend/crates/gateway-admin/src/use_case/settings.rs +++ b/backend/crates/gateway-admin/src/use_case/settings.rs @@ -81,7 +81,7 @@ pub(crate) struct DefaultSettingsService { } impl DefaultSettingsService { - fn profile_provider( + fn registered_provider( &self, provider: &str, ) -> Result, AdminError> { @@ -89,7 +89,7 @@ impl DefaultSettingsService { .map_err(|_| AdminError::invalid("服务商无效"))?; self.providers .require(&kind) - .map_err(|error| super::map_provider_error(error, "client profile")) + .map_err(|error| super::map_provider_error(error, "provider registry")) } #[must_use] @@ -128,7 +128,7 @@ impl SettingsService for DefaultSettingsService { &self, request: gateway_core::settings::privacy::PrivacyPreviewRequest, ) -> Result { - self.profile_provider("openai")? + self.registered_provider("openai")? .preview_privacy_policy(request) .map_err(|error| { AdminError::invalid(format!( @@ -142,7 +142,9 @@ impl SettingsService for DefaultSettingsService { async fn preview_pricing_sync( &self, ) -> Result { - self.pricing_source.fetch().await + let scope = self.providers.pricing_source_scope(); + let prices = self.pricing_source.fetch(&scope).await?; + Ok(scope.project(prices)) } async fn sync_pricing( @@ -172,7 +174,7 @@ impl SettingsService for DefaultSettingsService { { return Err(AdminError::invalid("该服务商不支持价目管理")); } - let mut current = self.pricing_source.fetch().await?; + let mut current = self.preview_pricing_sync().await?; if current != command.preview { return Err(AdminError::invalid( "models.dev 价目已变化,请重新预览后确认", @@ -217,6 +219,7 @@ impl SettingsService for DefaultSettingsService { .await .map_err(|error| map_store_error(error, "model pricing"))?; Ok(crate::model::pricing::PricingCatalog { + supported_bands: self.providers.supported_pricing_bands(), defaults: self.providers.pricing_catalog(), overrides: stored.overrides, synced: stored.synced, @@ -231,8 +234,10 @@ impl SettingsService for DefaultSettingsService { ) -> Result<(), AdminError> { use crate::model::pricing::PricingChange; let catalog = self.pricing().await?; - if !catalog.defaults.contains_key(&command.provider) - || command.models.is_empty() + let Some(supported) = catalog.supported_bands.get(&command.provider) else { + return Err(AdminError::invalid("服务商、模型 ID 或批量数量不合法")); + }; + if command.models.is_empty() || command.models.len() > 500 || command.models.iter().any(|model| { model.is_empty() @@ -259,14 +264,7 @@ impl SettingsService for DefaultSettingsService { match &command.change { PricingChange::Replace(pricing) => { pricing.validate().map_err(AdminError::invalid)?; - if command.provider == "xai" - && pricing.bands.keys().any(|band| { - matches!( - band.as_str(), - "image" | "flex" | "long_flex" | "ultrafast" | "long_ultrafast" - ) - }) - { + if pricing.bands.keys().any(|band| !supported.contains(band)) { return Err(AdminError::invalid("当前平台不支持此价格档位")); } if !pricing.bands.contains_key("standard") @@ -307,7 +305,7 @@ impl SettingsService for DefaultSettingsService { &self, provider: &str, ) -> Result { - let profile_provider = self.profile_provider(provider)?; + let profile_provider = self.registered_provider(provider)?; let mut options = profile_provider .client_profile_options() .map_err(|error| super::map_provider_error(error, "client profile"))? @@ -331,7 +329,7 @@ impl SettingsService for DefaultSettingsService { provider: &str, configuration: Option<&gateway_core::account::OpaqueProviderData>, ) -> Result { - let profile_provider = self.profile_provider(provider)?; + let profile_provider = self.registered_provider(provider)?; let independent = configuration.filter(|key| { gateway_core::settings::request_profiles::inherited_fields(key).is_none() }); @@ -378,7 +376,7 @@ impl SettingsService for DefaultSettingsService { ) -> Result { validate_settings(&command)?; if command.values.codex_privacy_policy != Default::default() { - self.profile_provider("openai")? + self.registered_provider("openai")? .compile_privacy_policy(&command.values.codex_privacy_policy) .map_err(|error| { AdminError::invalid(format!( @@ -388,37 +386,30 @@ impl SettingsService for DefaultSettingsService { )) })?; } - if command - .request_profile_updates - .values() - .any(Option::is_some) - { + if !command.request_profile_updates.is_empty() { let current = self .store .load_runtime_settings() .await .map_err(|error| map_store_error(error, "runtime settings"))?; - command.request_profile_updates.retain(|provider, update| { - !update - .as_ref() - .is_some_and(|profile| current.request_profiles.get(provider) == Some(profile)) - }); - } - if command - .request_profile_updates - .values() - .any(Option::is_some) - { - let providers = &self.providers; - for (provider, profile) in &command.request_profile_updates { - let Some(profile) = profile else { - continue; - }; - providers - .require(provider) - .and_then(|provider| provider.preview_client_profile(profile)) + for (kind, update) in &command.request_profile_updates { + let provider = self + .providers + .require(kind) .map_err(|error| super::map_provider_error(error, "client profile"))?; + if let Some(profile) = update + && current.request_profiles.get(kind) != Some(profile) + { + provider + .preview_client_profile(profile) + .map_err(|error| super::map_provider_error(error, "client profile"))?; + } } + command.request_profile_updates.retain(|kind, update| { + update + .as_ref() + .is_none_or(|profile| current.request_profiles.get(kind) != Some(profile)) + }); } let settings = self .store diff --git a/backend/crates/gateway-admin/src/use_case/system/mod.rs b/backend/crates/gateway-admin/src/use_case/system/mod.rs new file mode 100644 index 000000000..5dea33202 --- /dev/null +++ b/backend/crates/gateway-admin/src/use_case/system/mod.rs @@ -0,0 +1,8 @@ +//! 系统管理用例与更新前置检查的模块门面 + +mod preflight; +mod service; + +pub(crate) use preflight::PluginSystemUpdatePreflight; +pub(crate) use service::DefaultSystemService; +pub use service::SystemService; diff --git a/backend/crates/gateway-admin/src/use_case/system_preflight.rs b/backend/crates/gateway-admin/src/use_case/system/preflight.rs similarity index 99% rename from backend/crates/gateway-admin/src/use_case/system_preflight.rs rename to backend/crates/gateway-admin/src/use_case/system/preflight.rs index bcf2e9112..0d383806e 100644 --- a/backend/crates/gateway-admin/src/use_case/system_preflight.rs +++ b/backend/crates/gateway-admin/src/use_case/system/preflight.rs @@ -19,7 +19,7 @@ use crate::{ }, }; -use super::plugins::official::{update_compatibility, validate_update_release}; +use super::super::plugins::official::{update_compatibility, validate_update_release}; /// 只读取启用实例及其固定包体,检查目标宿主合同;不准备或执行插件 pub(crate) struct PluginSystemUpdatePreflight { diff --git a/backend/crates/gateway-admin/src/use_case/system.rs b/backend/crates/gateway-admin/src/use_case/system/service.rs similarity index 98% rename from backend/crates/gateway-admin/src/use_case/system.rs rename to backend/crates/gateway-admin/src/use_case/system/service.rs index 5737fabf9..311ff349a 100644 --- a/backend/crates/gateway-admin/src/use_case/system.rs +++ b/backend/crates/gateway-admin/src/use_case/system/service.rs @@ -2,7 +2,7 @@ use std::sync::Arc; -use super::system_preflight::{ConfirmedPluginRestart, PluginSystemUpdatePreflight}; +use super::preflight::{ConfirmedPluginRestart, PluginSystemUpdatePreflight}; use crate::model::{MutationContext, system::SystemRestartPlan}; use async_trait::async_trait; diff --git a/backend/crates/gateway-admin/tests/backup/support.rs b/backend/crates/gateway-admin/tests/backup/support.rs index 79edb3b02..0ebf5978b 100644 --- a/backend/crates/gateway-admin/tests/backup/support.rs +++ b/backend/crates/gateway-admin/tests/backup/support.rs @@ -95,6 +95,7 @@ pub(crate) struct FakeBackupRepository { audits: Mutex>, settings: Mutex, settings_unavailable: AtomicBool, + rotate_before_verification: bool, records: Mutex>, } @@ -104,10 +105,16 @@ impl FakeBackupRepository { settings: Mutex::new(settings), audits: Mutex::new(Vec::new()), settings_unavailable: AtomicBool::new(false), + rotate_before_verification: false, records: Mutex::new(Vec::new()), } } + pub(crate) fn rotating_before_verification(mut self) -> Self { + self.rotate_before_verification = true; + self + } + pub(crate) fn audit_events(&self) -> Vec { self.audits.lock().expect("audits").clone() } @@ -206,6 +213,10 @@ impl BackupRepository for FakeBackupRepository { at: DateTime, ) -> AdminStoreResult { let mut settings = self.settings.lock().expect("settings"); + if self.rotate_before_verification { + settings.storage_revision += 1; + settings.last_verified_at = None; + } if settings.storage_revision != storage_revision { return Ok(false); } diff --git a/backend/crates/gateway-admin/tests/backup/task.rs b/backend/crates/gateway-admin/tests/backup/task.rs index 5fd1d2469..417bd8154 100644 --- a/backend/crates/gateway-admin/tests/backup/task.rs +++ b/backend/crates/gateway-admin/tests/backup/task.rs @@ -213,6 +213,7 @@ async fn retention_cleans_expired_scheduled_backups() { repository .update_schedule_settings( UpdateBackupScheduleCommand { + storage_revision: 1, schedule_enabled: false, cron_expression: "0 2 * * *".to_owned(), diff --git a/backend/crates/gateway-admin/tests/model/backup/contract.rs b/backend/crates/gateway-admin/tests/model/backup/contract.rs new file mode 100644 index 000000000..662a6ab7a --- /dev/null +++ b/backend/crates/gateway-admin/tests/model/backup/contract.rs @@ -0,0 +1,121 @@ +//! 跨模块行为合同测试 + +use super::*; + +#[test] +fn status_transition_accepts_every_legal_edge() { + let transitions = [ + (BackupStatus::Queued, BackupStatus::Dumping), + (BackupStatus::Queued, BackupStatus::Failed), + (BackupStatus::Dumping, BackupStatus::Uploading), + (BackupStatus::Dumping, BackupStatus::Failed), + (BackupStatus::Uploading, BackupStatus::Completed), + (BackupStatus::Uploading, BackupStatus::Failed), + (BackupStatus::Completed, BackupStatus::Deleting), + (BackupStatus::Failed, BackupStatus::Deleting), + ]; + assert!( + transitions + .into_iter() + .all(|(from, to)| { BackupStatusTransition::try_new(from, to).is_some() }) + ); +} + +#[test] +fn status_transition_rejects_invalid_edges() { + let transitions = [ + (BackupStatus::Queued, BackupStatus::Completed), + (BackupStatus::Completed, BackupStatus::Dumping), + (BackupStatus::Deleting, BackupStatus::Failed), + (BackupStatus::Deleting, BackupStatus::Completed), + ]; + assert!( + transitions + .into_iter() + .all(|(from, to)| { BackupStatusTransition::try_new(from, to).is_none() }) + ); +} + +#[test] +fn status_classification() { + assert!(BackupStatus::Queued.is_active()); + assert!(BackupStatus::Uploading.is_active()); + assert!(!BackupStatus::Completed.is_active()); + assert!(BackupStatus::Completed.can_be_deleted()); + assert!(BackupStatus::Failed.can_be_deleted()); + assert!(!BackupStatus::Queued.can_be_deleted()); +} + +#[test] +fn object_key_shape() { + let at = Utc.with_ymd_and_hms(2026, 8, 1, 12, 30, 0).unwrap(); + let key = build_object_key("production/backups", "backup_abc", at).unwrap(); + assert_eq!( + key, + "production/backups/2026/08/01/codex-proxy-rs_20260801_123000_abc.sql.gz" + ); +} + +#[test] +fn object_key_rejects_dangerous_prefixes() { + let at = Utc::now(); + assert!(build_object_key("/leading", "backup_x", at).is_err()); + assert!(build_object_key("a/../b", "backup_x", at).is_err()); + assert!(build_object_key("a\\b", "backup_x", at).is_err()); + assert!(build_object_key("a\u{0001}b", "backup_x", at).is_err()); + assert!(build_object_key("", "backup_x", at).is_err()); + assert!(build_object_key("trailing//", "backup_x", at).is_ok()); +} + +#[test] +fn trigger_and_status_roundtrip() { + for status in [ + BackupStatus::Queued, + BackupStatus::Dumping, + BackupStatus::Uploading, + BackupStatus::Completed, + BackupStatus::Failed, + BackupStatus::Deleting, + ] { + assert_eq!(BackupStatus::parse(status.as_str()), Some(status)); + } + assert_eq!( + BackupTriggerKind::parse("manual"), + Some(BackupTriggerKind::Manual) + ); + assert_eq!( + BackupTriggerKind::parse("scheduled"), + Some(BackupTriggerKind::Scheduled) + ); + assert_eq!(BackupTriggerKind::parse("unknown"), None); + assert_eq!(BackupStatus::parse("skipped"), None); + assert_eq!(BackupStatus::parse("deleted"), None); + assert_eq!(BackupStatus::parse("unknown"), None); +} + +#[test] +fn config_from_settings_redacts_secret_in_debug() { + let mut settings = BackupSettings { + storage_revision: 3, + endpoint: Some("https://example.com".to_owned()), + region: Some("auto".to_owned()), + bucket: Some("b".to_owned()), + access_key_id: Some("ak".to_owned()), + secret_access_key: Some(SecretString::from("sk-secret")), + prefix: Some("p".to_owned()), + force_path_style: false, + schedule_enabled: false, + cron_expression: None, + schedule_timezone: None, + retention_days: 0, + retention_count: 0, + next_run_at: None, + last_verified_at: None, + updated_at: Utc::now(), + }; + assert!(!format!("{:?}", settings).contains("sk-secret")); + let config = BackupStorageConfig::from_settings(&settings).unwrap(); + assert!(!format!("{config:?}").contains("sk-secret")); + settings.endpoint = None; + assert!(BackupStorageConfig::from_settings(&settings).is_none()); +} diff --git a/backend/crates/gateway-admin/tests/model/backup/mod.rs b/backend/crates/gateway-admin/tests/model/backup/mod.rs index 529473c10..53454047e 100644 --- a/backend/crates/gateway-admin/tests/model/backup/mod.rs +++ b/backend/crates/gateway-admin/tests/model/backup/mod.rs @@ -1,5 +1,6 @@ //! 备份领域模型(model/backup)的纯逻辑测试 +mod contract; use chrono::{TimeZone as _, Utc}; use secrecy::SecretString; @@ -7,121 +8,3 @@ use gateway_admin::model::backup::{ BackupSettings, BackupStatus, BackupStatusTransition, BackupStorageConfig, BackupTriggerKind, build_object_key, }; - -#[test] -fn status_transition_accepts_every_legal_edge() { - let transitions = [ - (BackupStatus::Queued, BackupStatus::Dumping), - (BackupStatus::Queued, BackupStatus::Failed), - (BackupStatus::Dumping, BackupStatus::Uploading), - (BackupStatus::Dumping, BackupStatus::Failed), - (BackupStatus::Uploading, BackupStatus::Completed), - (BackupStatus::Uploading, BackupStatus::Failed), - (BackupStatus::Completed, BackupStatus::Deleting), - (BackupStatus::Failed, BackupStatus::Deleting), - ]; - assert!( - transitions - .into_iter() - .all(|(from, to)| { BackupStatusTransition::try_new(from, to).is_some() }) - ); -} - -#[test] -fn status_transition_rejects_invalid_edges() { - let transitions = [ - (BackupStatus::Queued, BackupStatus::Completed), - (BackupStatus::Completed, BackupStatus::Dumping), - (BackupStatus::Deleting, BackupStatus::Failed), - (BackupStatus::Deleting, BackupStatus::Completed), - ]; - assert!( - transitions - .into_iter() - .all(|(from, to)| { BackupStatusTransition::try_new(from, to).is_none() }) - ); -} - -#[test] -fn status_classification() { - assert!(BackupStatus::Queued.is_active()); - assert!(BackupStatus::Uploading.is_active()); - assert!(!BackupStatus::Completed.is_active()); - assert!(BackupStatus::Completed.can_be_deleted()); - assert!(BackupStatus::Failed.can_be_deleted()); - assert!(!BackupStatus::Queued.can_be_deleted()); -} - -#[test] -fn object_key_shape() { - let at = Utc.with_ymd_and_hms(2026, 8, 1, 12, 30, 0).unwrap(); - let key = build_object_key("production/backups", "backup_abc", at).unwrap(); - assert_eq!( - key, - "production/backups/2026/08/01/codex-proxy-rs_20260801_123000_abc.sql.gz" - ); -} - -#[test] -fn object_key_rejects_dangerous_prefixes() { - let at = Utc::now(); - assert!(build_object_key("/leading", "backup_x", at).is_err()); - assert!(build_object_key("a/../b", "backup_x", at).is_err()); - assert!(build_object_key("a\\b", "backup_x", at).is_err()); - assert!(build_object_key("a\u{0001}b", "backup_x", at).is_err()); - assert!(build_object_key("", "backup_x", at).is_err()); - assert!(build_object_key("trailing//", "backup_x", at).is_ok()); -} - -#[test] -fn trigger_and_status_roundtrip() { - for status in [ - BackupStatus::Queued, - BackupStatus::Dumping, - BackupStatus::Uploading, - BackupStatus::Completed, - BackupStatus::Failed, - BackupStatus::Deleting, - ] { - assert_eq!(BackupStatus::parse(status.as_str()), Some(status)); - } - assert_eq!( - BackupTriggerKind::parse("manual"), - Some(BackupTriggerKind::Manual) - ); - assert_eq!( - BackupTriggerKind::parse("scheduled"), - Some(BackupTriggerKind::Scheduled) - ); - assert_eq!(BackupTriggerKind::parse("unknown"), None); - assert_eq!(BackupStatus::parse("skipped"), None); - assert_eq!(BackupStatus::parse("deleted"), None); - assert_eq!(BackupStatus::parse("unknown"), None); -} - -#[test] -fn config_from_settings_redacts_secret_in_debug() { - let mut settings = BackupSettings { - storage_revision: 3, - endpoint: Some("https://example.com".to_owned()), - region: Some("auto".to_owned()), - bucket: Some("b".to_owned()), - access_key_id: Some("ak".to_owned()), - secret_access_key: Some(SecretString::from("sk-secret")), - prefix: Some("p".to_owned()), - force_path_style: false, - schedule_enabled: false, - cron_expression: None, - schedule_timezone: None, - retention_days: 0, - retention_count: 0, - next_run_at: None, - last_verified_at: None, - updated_at: Utc::now(), - }; - assert!(!format!("{:?}", settings).contains("sk-secret")); - let config = BackupStorageConfig::from_settings(&settings).unwrap(); - assert!(!format!("{config:?}").contains("sk-secret")); - settings.endpoint = None; - assert!(BackupStorageConfig::from_settings(&settings).is_none()); -} diff --git a/backend/crates/gateway-admin/tests/model/mod.rs b/backend/crates/gateway-admin/tests/model/mod.rs index cadf813a1..190f119c2 100644 --- a/backend/crates/gateway-admin/tests/model/mod.rs +++ b/backend/crates/gateway-admin/tests/model/mod.rs @@ -8,5 +8,4 @@ mod observability; mod plugins; mod provider_credentials; mod quota_forecast; -mod quota_forecast_sampling; mod retention; diff --git a/backend/crates/gateway-admin/tests/model/plugins/contract.rs b/backend/crates/gateway-admin/tests/model/plugins/contract.rs new file mode 100644 index 000000000..57263eb8b --- /dev/null +++ b/backend/crates/gateway-admin/tests/model/plugins/contract.rs @@ -0,0 +1,93 @@ +//! 跨模块行为合同测试 + +use super::*; + +#[test] +fn metadata_ignores_unknown_fields_at_each_object_boundary() { + let mut original = metadata(); + original["icon"] = json!({"light": "light.svg", "dark": "dark.svg"}); + original["stateNamespaces"] = json!([{ + "namespace": "cache", "schemaVersion": 1, "schemaSha256": "b".repeat(64), + "schema": {}, "maximumRecords": 10, "maximumBytes": 1024, + "maximumValueBytes": 128, "migratesFrom": [] + }]); + let expected: PluginArtifactMetadata = serde_json::from_value(original.clone()).unwrap(); + for path in ["", "/contributes/middleware", "/icon", "/stateNamespaces/0"] { + let mut extended = original.clone(); + extended.pointer_mut(path).unwrap()["futureField"] = json!({"enabled": true}); + assert_eq!( + serde_json::from_value::(extended).unwrap(), + expected, + "unknown field at {path}" + ); + } +} + +#[test] +fn metadata_defaults_only_optional_fields() { + let original = metadata(); + let expected: PluginArtifactMetadata = serde_json::from_value(original.clone()).unwrap(); + let mut older = original; + for field in ["configurationSchema", "secretFields", "stateNamespaces"] { + older.as_object_mut().unwrap().remove(field); + } + for field in ["stages", "inputFormats", "outputFormats"] { + older["contributes"]["middleware"] + .as_object_mut() + .unwrap() + .remove(field); + } + assert_eq!( + serde_json::from_value::(older).unwrap(), + expected + ); +} + +#[test] +fn metadata_still_requires_identity_and_execution_facts() { + for field in [ + "pluginId", + "version", + "name", + "publisher", + "sha256", + "platforms", + "contributes", + ] { + let mut incomplete = metadata(); + incomplete.as_object_mut().unwrap().remove(field); + assert!( + serde_json::from_value::(incomplete).is_err(), + "missing {field}" + ); + } + for field in ["id", "version"] { + let mut incomplete = metadata(); + incomplete["contributes"]["middleware"] + .as_object_mut() + .unwrap() + .remove(field); + assert!( + serde_json::from_value::(incomplete).is_err(), + "missing contribution {field}" + ); + } +} + +#[test] +fn metadata_still_rejects_wrong_types_in_known_fields() { + for (path, value) in [ + ("/version", json!(1)), + ("/secretFields", json!(false)), + ("/stateNamespaces", json!({})), + ("/contributes/middleware/version", json!("3")), + ("/contributes/middleware/stages", json!("http")), + ] { + let mut invalid = metadata(); + *invalid.pointer_mut(path).unwrap() = value; + assert!( + serde_json::from_value::(invalid).is_err(), + "wrong type at {path}" + ); + } +} diff --git a/backend/crates/gateway-admin/tests/model/plugins/mod.rs b/backend/crates/gateway-admin/tests/model/plugins/mod.rs index 56cf18c83..67f68e483 100644 --- a/backend/crates/gateway-admin/tests/model/plugins/mod.rs +++ b/backend/crates/gateway-admin/tests/model/plugins/mod.rs @@ -1,5 +1,6 @@ //! 验证插件元数据兼容新增字段,同时保留已知字段的类型约束 +mod contract; use gateway_admin::model::plugins::PluginArtifactMetadata; use serde_json::{Value, json}; @@ -15,93 +16,3 @@ fn metadata() -> Value { "configurationSchema": {}, "secretFields": [], "stateNamespaces": [] }) } - -#[test] -fn metadata_ignores_unknown_fields_at_each_object_boundary() { - let mut original = metadata(); - original["icon"] = json!({"light": "light.svg", "dark": "dark.svg"}); - original["stateNamespaces"] = json!([{ - "namespace": "cache", "schemaVersion": 1, "schemaSha256": "b".repeat(64), - "schema": {}, "maximumRecords": 10, "maximumBytes": 1024, - "maximumValueBytes": 128, "migratesFrom": [] - }]); - let expected: PluginArtifactMetadata = serde_json::from_value(original.clone()).unwrap(); - for path in ["", "/contributes/middleware", "/icon", "/stateNamespaces/0"] { - let mut extended = original.clone(); - extended.pointer_mut(path).unwrap()["futureField"] = json!({"enabled": true}); - assert_eq!( - serde_json::from_value::(extended).unwrap(), - expected, - "unknown field at {path}" - ); - } -} - -#[test] -fn metadata_defaults_only_optional_fields() { - let original = metadata(); - let expected: PluginArtifactMetadata = serde_json::from_value(original.clone()).unwrap(); - let mut older = original; - for field in ["configurationSchema", "secretFields", "stateNamespaces"] { - older.as_object_mut().unwrap().remove(field); - } - for field in ["stages", "inputFormats", "outputFormats"] { - older["contributes"]["middleware"] - .as_object_mut() - .unwrap() - .remove(field); - } - assert_eq!( - serde_json::from_value::(older).unwrap(), - expected - ); -} - -#[test] -fn metadata_still_requires_identity_and_execution_facts() { - for field in [ - "pluginId", - "version", - "name", - "publisher", - "sha256", - "platforms", - "contributes", - ] { - let mut incomplete = metadata(); - incomplete.as_object_mut().unwrap().remove(field); - assert!( - serde_json::from_value::(incomplete).is_err(), - "missing {field}" - ); - } - for field in ["id", "version"] { - let mut incomplete = metadata(); - incomplete["contributes"]["middleware"] - .as_object_mut() - .unwrap() - .remove(field); - assert!( - serde_json::from_value::(incomplete).is_err(), - "missing contribution {field}" - ); - } -} - -#[test] -fn metadata_still_rejects_wrong_types_in_known_fields() { - for (path, value) in [ - ("/version", json!(1)), - ("/secretFields", json!(false)), - ("/stateNamespaces", json!({})), - ("/contributes/middleware/version", json!("3")), - ("/contributes/middleware/stages", json!("http")), - ] { - let mut invalid = metadata(); - *invalid.pointer_mut(path).unwrap() = value; - assert!( - serde_json::from_value::(invalid).is_err(), - "wrong type at {path}" - ); - } -} diff --git a/backend/crates/gateway-admin/tests/model/quota_forecast/mod.rs b/backend/crates/gateway-admin/tests/model/quota_forecast/mod.rs new file mode 100644 index 000000000..05fdbab50 --- /dev/null +++ b/backend/crates/gateway-admin/tests/model/quota_forecast/mod.rs @@ -0,0 +1,4 @@ +//! 额度预测投影与采样测试 + +mod projection; +mod sampling; diff --git a/backend/crates/gateway-admin/tests/model/quota_forecast.rs b/backend/crates/gateway-admin/tests/model/quota_forecast/projection.rs similarity index 99% rename from backend/crates/gateway-admin/tests/model/quota_forecast.rs rename to backend/crates/gateway-admin/tests/model/quota_forecast/projection.rs index 86c646058..cb5d5c07f 100644 --- a/backend/crates/gateway-admin/tests/model/quota_forecast.rs +++ b/backend/crates/gateway-admin/tests/model/quota_forecast/projection.rs @@ -6,7 +6,7 @@ use gateway_admin::model::{ observability::CostCoverage, provider_credentials::{ProviderQuota, ProviderQuotaWindow, QuotaLocalUsageAttribution}, quota_forecast::{AccountQuotaForecast, account_quota_forecasts}, - quota_forecast_sampling::{QuotaForecastMethod, QuotaForecastSample, QuotaForecastUsage}, + quota_forecast::{QuotaForecastMethod, QuotaForecastSample, QuotaForecastUsage}, }; fn now() -> DateTime { diff --git a/backend/crates/gateway-admin/tests/model/quota_forecast_sampling.rs b/backend/crates/gateway-admin/tests/model/quota_forecast/sampling.rs similarity index 99% rename from backend/crates/gateway-admin/tests/model/quota_forecast_sampling.rs rename to backend/crates/gateway-admin/tests/model/quota_forecast/sampling.rs index a0d3e2476..4401b725f 100644 --- a/backend/crates/gateway-admin/tests/model/quota_forecast_sampling.rs +++ b/backend/crates/gateway-admin/tests/model/quota_forecast/sampling.rs @@ -1,7 +1,7 @@ //! 验证额度预测采样的去重、回退处理与近期窗口选择 use chrono::{DateTime, Duration, Utc}; -use gateway_admin::model::quota_forecast_sampling::{ +use gateway_admin::model::quota_forecast::{ QuotaForecastMethod, QuotaForecastPoint, QuotaForecastSample, QuotaForecastUsage, select_forecast_sample, }; diff --git a/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs b/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs index 6d46cf709..bb92e64a0 100644 --- a/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs +++ b/backend/crates/gateway-admin/tests/use_case/accounts/mod.rs @@ -52,7 +52,7 @@ use gateway_admin::{ ProviderQuotaWindow, ProviderResetCreditResult, ProviderSubscription, QuotaLocalUsageAttribution, }, - quota_forecast_sampling::{QuotaForecastHistory, QuotaForecastUsage}, + quota_forecast::{QuotaForecastHistory, QuotaForecastUsage}, settings::{ AdminApiKey, AdminApiKeyMutation, ReplaceRuntimeSettings, RotationStrategy, RuntimeSettings, @@ -561,10 +561,10 @@ impl ProviderAdmin for FakeProviderAdmin { &self, document: &ProviderDocument, _: &ProviderQuotaWindow, - ) -> Option { + ) -> Option { let fields = document.expose_to_provider().expose_to_provider(); Some( - gateway_admin::model::quota_forecast_sampling::QuotaForecastObservation { + gateway_admin::model::quota_forecast::QuotaForecastObservation { used_percent: fields.get("percent")?.as_f64()?, reset_at: fields.get("reset")?.as_str()?.parse().ok()?, plan_type: fields.get("plan")?.as_str().map(str::to_owned), @@ -617,6 +617,7 @@ pub(super) struct FakeAccountStore { audit_requests: Mutex>, import_settings: Mutex>>, quota_window_usage: Mutex>, + rolling_usage: Mutex>, quota_window_queries: Mutex>, quota_forecast_history: Mutex, update_commands: Mutex>, @@ -640,6 +641,7 @@ impl FakeAccountStore { audit_requests: Mutex::new(Vec::new()), import_settings: Mutex::new(Vec::new()), quota_window_usage: Mutex::new(Vec::new()), + rolling_usage: Mutex::new(Vec::new()), quota_window_queries: Mutex::new(Vec::new()), quota_forecast_history: Mutex::new(QuotaForecastHistory::default()), update_commands: Mutex::new(Vec::new()), @@ -828,7 +830,7 @@ impl AccountStore for FakeAccountStore { _: TimeRange, _: &[String], ) -> AdminStoreResult> { - Ok(Vec::new()) + Ok(self.rolling_usage.lock().unwrap().clone()) } async fn load_account_usage_by_windows( @@ -1189,9 +1191,9 @@ impl SettingsStore for StaticSettingsStore { switch_account_on_queue_failure: false, max_retry_after_seconds: 240, openai_guardian_reserved_concurrency: 0, - openai_account_affinity: gateway_core::account::AccountAffinity::Relaxed, + account_affinity: gateway_core::account::AccountAffinity::Relaxed, max_account_rotations: 3, - openai_session_affinity_ttl_hours: 24, + session_affinity_ttl_hours: 24, responses_max_decompressed_body_bytes: 64 * 1024 * 1024, smart_scheduling: gateway_core::account::SmartSchedulingConfig::default(), quota_reset_window_weights: gateway_core::account::ResetWindowWeights::default(), @@ -1448,9 +1450,31 @@ async fn connection_test_should_preserve_disabled_account_status() { )); } +#[tokio::test] +async fn unsupported_account_export_stops_before_loading_credentials() { + let calls = events(); + let provider = FakeProviderAdmin::new("fixture", calls.clone()); + let store = FakeAccountStore::new("fixture", calls.clone()); + let id = ProviderAccountId::new(store.accounts.lock().unwrap()[0].id.clone()).unwrap(); + let services = accounts_service(provider, store).await; + let error = services + .accounts() + .export(&context("export-unsupported"), vec![id]) + .await + .unwrap_err(); + assert_eq!(error.kind(), gateway_admin::model::AdminErrorKind::Invalid); + assert!( + !calls + .lock() + .unwrap() + .contains(&"store.load_credentials_for_export") + ); +} + #[tokio::test] async fn accounts_export_should_pass_store_loaded_timestamps_and_material_to_provider() { let provider = FakeProviderAdmin::new("openai", events()); + provider.capabilities.lock().unwrap().credential_export = true; let store = FakeAccountStore::new("openai", events()); let expected = store.accounts.lock().expect("accounts")[0].clone(); accounts_service(provider.clone(), store) @@ -2517,7 +2541,7 @@ async fn quota_forecast_only_queries_the_two_selected_source_windows() { #[tokio::test] async fn quota_forecast_same_window_reversal_keeps_recorded_usage_in_the_report() { - use gateway_admin::model::quota_forecast_sampling::QuotaForecastHistoryPoint; + use gateway_admin::model::quota_forecast::QuotaForecastHistoryPoint; for (percents, tokens, expected_tokens, expected_usd) in [ ([32.0, 30.0, 35.0], [100, 120, 140], 400, 0.4), @@ -2608,7 +2632,7 @@ async fn quota_forecast_same_window_reversal_keeps_recorded_usage_in_the_report( #[tokio::test] async fn quota_forecast_keeps_cycle_totals_through_reset_jitter_and_restarts_after_a_reset() { - use gateway_admin::model::quota_forecast_sampling::QuotaForecastHistoryPoint; + use gateway_admin::model::quota_forecast::QuotaForecastHistoryPoint; let now = Utc::now(); let observed = now - TimeDelta::minutes(1); let reset = now + TimeDelta::days(1); @@ -2976,6 +3000,63 @@ async fn api_key_list_and_detail_should_accumulate_local_usage_without_subscript assert_eq!(store.quota_window_queries()[0].range.start, added_at); } +#[tokio::test] +async fn accounts_list_and_detail_keep_rolling_usage_separate_from_group_quotas() { + use gateway_admin::model::provider_credentials::AccountUsagePeriod; + + let provider = FakeProviderAdmin::new("antigravity", events()); + let store = FakeAccountStore::new("antigravity", events()); + let expected_usage = quota_local_usage("acct_test", 139); + *store.rolling_usage.lock().unwrap() = vec![expected_usage.clone()]; + let services = accounts_service(provider.clone(), store.clone()).await; + let grouped_window = ProviderQuotaWindow { + upstream: None, + key: "gemini-weekly".to_owned(), + group: "shortTerm".to_owned(), + label: "周额度".to_owned(), + limit_id: Some("gemini".to_owned()), + limit_name: Some("Gemini Models".to_owned()), + role: None, + local_usage_attribution: QuotaLocalUsageAttribution::Unavailable, + window_seconds: Some(604_800), + used_percent: Some(25.0), + reset_at: Some(Utc::now() + TimeDelta::days(6)), + limit_reached: false, + local_usage: None, + provider_data: None, + }; + for windows in [Vec::new(), vec![grouped_window]] { + provider.set_quota(ProviderQuota { + windows: windows.clone(), + ..empty_quota() + }); + let page = services + .accounts() + .list(AccountListQuery { + page: 1, + page_size: gateway_admin::model::PageSize::new(20).unwrap(), + provider_kind: None, + group_filter: None, + search: None, + status: None, + sort: None, + }) + .await + .unwrap(); + let detail = services + .accounts() + .quota(&ProviderAccountId::new("acct_test").unwrap(), false) + .await + .unwrap(); + for item in [&page.items[0], &detail] { + assert_eq!(item.quota.windows, windows); + assert_eq!(item.usage.as_ref(), Some(&expected_usage)); + assert_eq!(item.usage_period, Some(AccountUsagePeriod::Daily)); + } + assert!(store.quota_window_queries().is_empty()); + } +} + #[tokio::test] async fn accounts_list_should_attach_local_usage_to_quota_windows() { let provider = FakeProviderAdmin::new("openai", events()); diff --git a/backend/crates/gateway-admin/tests/use_case/backup.rs b/backend/crates/gateway-admin/tests/use_case/backup.rs index a288e8d8d..b749ddbed 100644 --- a/backend/crates/gateway-admin/tests/use_case/backup.rs +++ b/backend/crates/gateway-admin/tests/use_case/backup.rs @@ -115,6 +115,7 @@ async fn failed_delete_probe_does_not_refresh_verification() { for succeeds in [false, true] { let mut settings = configured_settings(); settings.last_verified_at = None; + let revision = settings.storage_revision; let repository = Arc::new(FakeBackupRepository::new(settings)); let auth = Arc::new(FakeAuthStore::new()); let store = FakeObjectStore::new(); @@ -132,9 +133,15 @@ async fn failed_delete_probe_does_not_refresh_verification() { )) .build() .await; + let stale = services + .backups() + .test_connection(&system_context(), revision + 1) + .await + .unwrap_err(); + assert_eq!(stale.kind(), gateway_admin::model::AdminErrorKind::Conflict); let result = services .backups() - .test_connection(&system_context()) + .test_connection(&system_context(), revision) .await .unwrap(); assert_eq!(result.ok, succeeds); @@ -156,3 +163,27 @@ async fn failed_delete_probe_does_not_refresh_verification() { ); } } + +#[tokio::test] +async fn successful_probe_of_replaced_storage_reports_a_conflict() { + use gateway_admin::ports::backup::BackupRepository as _; + + let settings = configured_settings(); + let revision = settings.storage_revision; + let repository = Arc::new(FakeBackupRepository::new(settings).rotating_before_verification()); + let services = AdminHarness::new() + .backup(BackupStorePorts::new( + repository.clone(), + Arc::new(FakeDumpPort::new()), + Arc::new(FakeObjectStore::new()), + )) + .build() + .await; + let error = services + .backups() + .test_connection(&system_context(), revision) + .await + .unwrap_err(); + assert_eq!(error.kind(), gateway_admin::model::AdminErrorKind::Conflict); + assert!(!repository.load_settings().await.unwrap().storage_verified()); +} diff --git a/backend/crates/gateway-admin/tests/use_case/client_keys.rs b/backend/crates/gateway-admin/tests/use_case/client_keys.rs index f1b119141..6a66c3cbd 100644 --- a/backend/crates/gateway-admin/tests/use_case/client_keys.rs +++ b/backend/crates/gateway-admin/tests/use_case/client_keys.rs @@ -587,3 +587,32 @@ async fn duplicate_group_ids_are_rejected_before_key_creation_or_update() { assert_eq!(updated.kind(), AdminErrorKind::Invalid); assert!(store.plaintexts.lock().unwrap().is_empty()); } + +#[tokio::test] +async fn clearing_an_unregistered_provider_profile_is_rejected_before_writing() { + let services = super::AdminHarness::new().build().await; + let command = UpdateClientKey { + id: ClientApiKeyId::new("key_existing").unwrap(), + name: "test".to_owned(), + label: None, + group_ids: Vec::new(), + limits: RateLimits::unlimited(), + daily_limit_usd: None, + weekly_limit_usd: None, + peer_sharing: None, + request_profile_override_updates: [( + gateway_core::routing::ProviderKind::new("unregistered").unwrap(), + None, + )] + .into(), + }; + assert_eq!( + services + .client_keys() + .update(&mutation_context(), command) + .await + .unwrap_err() + .kind(), + AdminErrorKind::Invalid + ); +} diff --git a/backend/crates/gateway-admin/tests/use_case/freeze_recovery.rs b/backend/crates/gateway-admin/tests/use_case/freeze_recovery.rs index a273dad07..4ac4cb7a6 100644 --- a/backend/crates/gateway-admin/tests/use_case/freeze_recovery.rs +++ b/backend/crates/gateway-admin/tests/use_case/freeze_recovery.rs @@ -48,9 +48,9 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings { switch_account_on_queue_failure: false, max_retry_after_seconds: 240, openai_guardian_reserved_concurrency: 0, - openai_account_affinity: gateway_core::account::AccountAffinity::Relaxed, + account_affinity: gateway_core::account::AccountAffinity::Relaxed, max_account_rotations: 3, - openai_session_affinity_ttl_hours: 24, + session_affinity_ttl_hours: 24, responses_max_decompressed_body_bytes: 64 * 1024 * 1024, smart_scheduling: gateway_core::account::SmartSchedulingConfig::default(), quota_reset_window_weights: gateway_core::account::ResetWindowWeights::default(), diff --git a/backend/crates/gateway-admin/tests/use_case/mod.rs b/backend/crates/gateway-admin/tests/use_case/mod.rs index fc3d4c7d5..b45d71f26 100644 --- a/backend/crates/gateway-admin/tests/use_case/mod.rs +++ b/backend/crates/gateway-admin/tests/use_case/mod.rs @@ -15,7 +15,6 @@ mod plugins; mod proxies; mod settings; mod system; -mod system_preflight; mod usage_data; use std::{ @@ -560,7 +559,7 @@ impl AccountStore for UnavailableStore { async fn load_quota_forecast_history( &self, _: &AccountUsageWindowQuery, - ) -> AdminStoreResult { + ) -> AdminStoreResult { Err(unavailable("quota forecast history")) } @@ -1012,6 +1011,8 @@ impl SettingsStore for UnavailableStore { } struct UnavailableProvider { + pricing_bands: &'static [&'static str], + pricing_references: std::collections::BTreeMap, peer_enabled: bool, kind: ProviderKind, dashboard_profile: Option, @@ -1023,6 +1024,7 @@ struct UnavailablePricingSource; impl gateway_admin::ports::pricing::PricingSource for UnavailablePricingSource { async fn fetch( &self, + _: &gateway_admin::ports::pricing::PricingSourceScope, ) -> Result { Err(gateway_admin::model::AdminError::internal( @@ -1036,6 +1038,8 @@ impl UnavailableProvider { Self { kind: ProviderKind::new(kind).expect("provider kind"), peer_enabled: false, + pricing_references: Default::default(), + pricing_bands: &["standard"], dashboard_profile: None, calculated_billing: None, } @@ -1048,6 +1052,31 @@ pub(super) fn test_provider(kind: &str) -> Arc { #[async_trait] impl ProviderAdmin for UnavailableProvider { + fn supported_pricing_bands(&self) -> &'static [&'static str] { + self.pricing_bands + } + + fn pricing_source(&self) -> gateway_admin::ports::pricing::PricingCatalogSource { + use gateway_admin::ports::pricing::PricingCatalogSource; + if self.pricing_references.is_empty() { + return PricingCatalogSource::Direct; + } + PricingCatalogSource::References( + self.pricing_references + .iter() + .map(|(model, (provider, source))| { + ( + model.clone(), + gateway_admin::ports::pricing::PricingSourceModel { + provider: provider.clone(), + model: source.clone(), + }, + ) + }) + .collect(), + ) + } + fn peer_authentication_kinds(&self) -> &[&str] { if self.peer_enabled { &["peer_test"] @@ -1158,6 +1187,8 @@ impl ProviderAdmin for UnavailableProvider { pub(super) fn dashboard_profile_provider() -> Arc { Arc::new(UnavailableProvider { + pricing_bands: &["standard"], + pricing_references: Default::default(), peer_enabled: false, kind: ProviderKind::new("openai").expect("provider kind"), dashboard_profile: Some(DashboardWireProfile { @@ -1202,6 +1233,8 @@ pub(super) fn calculated_billing_provider() -> Arc { .expect("test billing amount"), }; Arc::new(UnavailableProvider { + pricing_bands: &["standard"], + pricing_references: Default::default(), peer_enabled: false, kind: ProviderKind::new("openai").expect("provider kind"), dashboard_profile: None, diff --git a/backend/crates/gateway-admin/tests/use_case/observability/dashboard.rs b/backend/crates/gateway-admin/tests/use_case/observability/dashboard.rs new file mode 100644 index 000000000..3376cbf28 --- /dev/null +++ b/backend/crates/gateway-admin/tests/use_case/observability/dashboard.rs @@ -0,0 +1,571 @@ +//! 仪表盘指标、时间桶与账号聚合测试 + +use super::*; + +#[tokio::test] +async fn health_timeline_should_keep_exactly_china_day_quarter_hour_slots() { + let now = Utc::now(); + let day_start = gateway_core::time::DeploymentTimeZone::default() + .day_start(now) + .unwrap(); + let current_slot = quarter_hour_start(now); + let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); + store.replace_trend(vec![ + health_metric_point( + day_start - Duration::minutes(15), + RequestMetrics { + success_count: 100, + ..RequestMetrics::default() + }, + ), + health_metric_point( + current_slot, + RequestMetrics { + success_count: 2, + ..RequestMetrics::default() + }, + ), + health_metric_point( + current_slot + Duration::minutes(15), + RequestMetrics { + success_count: 100, + ..RequestMetrics::default() + }, + ), + ]); + let services = observability_services(store).await; + + let timeline = services + .observability() + .dashboard_summary(observation_range(now), TrendKind::Usage) + .await + .expect("dashboard summary") + .health_timeline; + + assert_eq!(timeline.points.len(), 96); + assert_eq!( + timeline.points.first().map(|point| point.bucket_start), + Some(day_start) + ); + assert_eq!( + timeline.points.last().map(|point| point.bucket_start), + Some(day_start + Duration::minutes(95 * 15)) + ); + assert_eq!(timeline.success_requests, 2); + assert_eq!( + timeline + .points + .iter() + .find(|point| point.bucket_start == current_slot) + .map(|point| point.status), + Some(HealthStatus::LowSample) + ); + assert!(timeline.points.iter().all(|point| { + point.bucket_start <= quarter_hour_start(Utc::now()) + || (point.status == HealthStatus::Future && point.success_requests == 0) + })); +} + +#[tokio::test] +async fn dashboard_summary_should_derive_first_token_average_from_trend() { + let now = Utc::now(); + let current_slot = quarter_hour_start(now); + let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); + store.replace_trend(vec![ + health_metric_point( + current_slot - Duration::minutes(15), + RequestMetrics { + first_token_latency_sum_ms: 120, + first_token_latency_count: 2, + ..RequestMetrics::default() + }, + ), + health_metric_point( + current_slot, + RequestMetrics { + first_token_latency_sum_ms: 180, + first_token_latency_count: 1, + ..RequestMetrics::default() + }, + ), + ]); + let services = observability_services(store).await; + + let summary = services + .observability() + .dashboard_summary(observation_range(now), TrendKind::Usage) + .await + .expect("dashboard summary"); + + assert_eq!(summary.average_first_token_latency_ms, Some(100)); +} + +#[test] +fn dashboard_comparison_should_follow_deployment_calendar_across_dst() { + let timezone = "America/New_York".parse().unwrap(); + for (end, previous_start, previous_end, hours) in [ + ( + "2026-03-09T16:00:00Z", + "2026-03-08T05:00:00Z", + "2026-03-09T04:00:00Z", + 23, + ), + ( + "2026-11-02T17:00:00Z", + "2026-11-01T04:00:00Z", + "2026-11-02T05:00:00Z", + 25, + ), + ( + "2026-11-02T05:00:00Z", + "2026-11-01T04:00:00Z", + "2026-11-02T05:00:00Z", + 25, + ), + ] { + let end = end.parse().unwrap(); + let range = TimeRange::calendar_at( + gateway_admin::model::observability::CalendarPeriod::Today, + end, + timezone, + ) + .unwrap(); + let query = DashboardQuery::new(range, timezone).unwrap(); + assert_eq!(query.range, range); + assert_eq!( + query.yesterday_range.start, + previous_start.parse::>().unwrap() + ); + assert_eq!( + query.yesterday_range.end, + previous_end.parse::>().unwrap() + ); + assert_eq!( + (query.yesterday_range.end - query.yesterday_range.start).num_hours(), + hours + ); + } +} + +#[tokio::test] +async fn dashboard_summary_should_compare_separate_yesterday_metrics_with_today_only_trend() { + let end: DateTime = "2026-10-18T04:00:00Z".parse().unwrap(); + let range = TimeRange::calendar_at( + gateway_admin::model::observability::CalendarPeriod::Today, + end, + Default::default(), + ) + .unwrap(); + let store = Arc::new(FixtureObservabilityStore::new(range)); + store.replace_trend(vec![health_metric_point( + range.start, + RequestMetrics { + request_count: 2, + input_tokens: 100, + cached_input_tokens: 20, + total_tokens: 120, + ..Default::default() + }, + )]); + *store.yesterday.lock().unwrap() = RequestMetrics { + request_count: 4, + input_tokens: 400, + cached_input_tokens: 200, + total_tokens: 500, + ..Default::default() + }; + let result = observability_services(store.clone()) + .await + .observability() + .dashboard_summary(range, TrendKind::Usage) + .await + .unwrap(); + assert_eq!(result.today.request_count, 2); + assert_eq!(result.today.total_tokens, 120); + assert_eq!(result.today.observed_cached_token_rate, Some(0.2)); + assert_eq!(result.yesterday.request_count, 4); + assert_eq!(result.yesterday.total_tokens, 500); + assert_eq!(result.yesterday.observed_cached_token_rate, Some(0.5)); + assert_eq!(result.observation.range, range); + assert_eq!(result.observation.trend.len(), 1); + assert_eq!(result.observation.trend[0].bucket_start, range.start); + assert_eq!( + store + .summary_query + .lock() + .unwrap() + .as_ref() + .unwrap() + .yesterday_range + .end, + range.start + ); +} + +#[tokio::test] +async fn dashboard_summary_should_keep_missing_yesterday_cache_rate_unknown() { + let range = observation_range(Utc::now()); + let store = Arc::new(FixtureObservabilityStore::new(range)); + let result = observability_services(store) + .await + .observability() + .dashboard_summary(range, TrendKind::Usage) + .await + .unwrap(); + assert_eq!(result.yesterday.request_count, 0); + assert_eq!(result.yesterday.total_tokens, 0); + assert_eq!(result.yesterday.observed_cached_token_rate, None); +} + +#[tokio::test] +async fn health_timeline_should_apply_status_precedence_and_thresholds() { + let now = Utc::now(); + let current_slot = quarter_hour_start(now); + let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); + let services = observability_services(store.clone()).await; + let fixtures = [ + ( + RequestMetrics { + failure_count: 1, + cancelled_count: 1, + caller_error_count: 1, + ..RequestMetrics::default() + }, + HealthStatus::NoData, + None, + ), + ( + RequestMetrics { + incomplete_count: 1, + ..RequestMetrics::default() + }, + HealthStatus::LowSample, + Some(0.0), + ), + ( + RequestMetrics { + incomplete_count: 3, + ..RequestMetrics::default() + }, + HealthStatus::Unavailable, + Some(0.0), + ), + ( + RequestMetrics { + failure_count: 3, + ..RequestMetrics::default() + }, + HealthStatus::Unavailable, + Some(0.0), + ), + ( + RequestMetrics { + success_count: 1, + failure_count: 1, + ..RequestMetrics::default() + }, + HealthStatus::LowSample, + Some(50.0), + ), + ( + RequestMetrics { + success_count: 94, + failure_count: 6, + ..RequestMetrics::default() + }, + HealthStatus::Unstable, + Some(94.0), + ), + ( + RequestMetrics { + success_count: 95, + incomplete_count: 5, + ..RequestMetrics::default() + }, + HealthStatus::Stable, + Some(95.0), + ), + ]; + + for (index, (metrics, expected_status, expected_reliability)) in + fixtures.into_iter().enumerate() + { + store.replace_trend(vec![health_metric_point(current_slot, metrics)]); + let range_end = + now + Duration::seconds(i64::try_from(index).expect("fixture index fits i64") * 2); + let timeline = services + .observability() + .dashboard_summary(observation_range(range_end), TrendKind::Usage) + .await + .expect("dashboard summary") + .health_timeline; + let point = timeline + .points + .iter() + .find(|point| point.bucket_start == current_slot) + .expect("current health slot"); + assert_eq!(point.status, expected_status); + assert_eq!(point.reliability_percent, expected_reliability); + } +} + +#[tokio::test] +async fn health_views_should_include_incomplete_and_keep_final_outcomes_separate() { + let now = Utc::now(); + let current_slot = quarter_hour_start(now); + let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); + let services = observability_services(store.clone()).await; + let fixtures = [ + (162, 0, 2, 0, 0, 0, Some(98.780_487_804_878_05)), + (297, 0, 2, 5, 0, 0, Some(99.331_103_678_929_76)), + (467, 1, 5, 0, 0, 0, Some(98.731_501_057_082_45)), + (95, 2, 3, 4, 1, 7, Some(95.0)), + (100, 0, 0, 0, 0, 0, Some(100.0)), + (0, 0, 0, 0, 0, 0, None), + (0, 0, 0, 4, 3, 2, None), + (0, 1, 2, 0, 0, 0, Some(0.0)), + ]; + + for ( + index, + (success, failed, incomplete, cancelled, caller_error, running, expected_percent), + ) in fixtures.into_iter().enumerate() + { + let range = observation_range( + now + Duration::seconds(i64::try_from(index).expect("fixture index fits i64") * 2), + ); + let metrics = RequestMetrics { + request_count: success + failed + incomplete + cancelled + caller_error + running, + success_count: success, + failure_count: failed + caller_error, + incomplete_count: incomplete, + cancelled_count: cancelled, + caller_error_count: caller_error, + ..RequestMetrics::default() + }; + store.replace_trend(vec![health_metric_point(current_slot, metrics.clone())]); + store.replace_overview(UsageOverview { + analytics: Default::default(), + range, + requests: metrics, + // 中间尝试失败不会增加最终失败请求数 + attempts: AttemptMetrics { + failure_count: 2, + ..AttemptMetrics::default() + }, + providers: Vec::new(), + }); + + let mut item = diagnostic( + "model", + success + failed + incomplete + cancelled + caller_error + running, + ); + item.success_count = success; + item.failure_count = failed + caller_error; + item.incomplete_count = incomplete; + item.cancelled_count = cancelled; + item.caller_error_count = caller_error; + store.replace_diagnostics(DiagnosticsObservation { + analytics: Default::default(), + total_request_count: item.request_count, + items: vec![item], + }); + let diagnostics = services + .observability() + .diagnostics(range, UsageFilter::default(), DiagnosticDimension::Model) + .await + .unwrap(); + assert_eq!(diagnostics.items[0].error_count, failed + incomplete); + + let dashboard = services + .observability() + .dashboard_summary(range, TrendKind::Usage) + .await + .expect("dashboard summary"); + let timeline = dashboard.health_timeline; + let point = timeline + .points + .iter() + .find(|point| point.bucket_start == current_slot) + .expect("current health slot"); + assert_eq!(dashboard.trend.summary.error_count, failed + incomplete); + assert_eq!(dashboard.trend.points[0].error_count, failed + incomplete); + assert_eq!(point.failed_requests, failed); + assert_eq!(point.incomplete_requests, incomplete); + assert_eq!(point.cancelled_requests, cancelled); + assert_eq!(point.caller_error_requests, caller_error); + + let insights = services + .observability() + .usage_insights(range, UsageFilter::default()) + .await + .expect("usage insights"); + assert_eq!(insights.health.failed_requests, failed); + assert_eq!(insights.health.incomplete_requests, incomplete); + for actual in [ + timeline.reliability_percent, + point.reliability_percent, + dashboard + .trend + .summary + .success_rate + .map(|rate| rate * 100.0), + dashboard.trend.points[0] + .success_rate + .map(|rate| rate * 100.0), + insights.health.success_rate.map(|rate| rate * 100.0), + insights.health.points[0] + .error_rate + .map(|rate| (1.0 - rate) * 100.0), + diagnostics.items[0] + .error_rate + .map(|rate| (1.0 - rate) * 100.0), + ] { + match (actual, expected_percent) { + (Some(actual), Some(expected)) => assert!((actual - expected).abs() < 1e-10), + (None, None) => {} + _ => panic!("unexpected rate: {actual:?}, expected {expected_percent:?}"), + } + } + } +} + +#[tokio::test] +async fn dashboard_summary_should_project_rebuildable_runtime_slots() { + let now = Utc::now(); + let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); + store.replace_runtime_slots(Some(DashboardRuntimeSlots { + inherited_versions: Vec::new(), + inherited_accounts: 2, + overridden_slots: 5, + used_slots: Some(2), + })); + let services = observability_services(store).await; + + let capacity = services + .observability() + .dashboard_summary(observation_range(now), TrendKind::Usage) + .await + .expect("dashboard summary") + .capacity; + + assert_eq!(capacity.total_slots, Some(7)); + assert_eq!(capacity.used_slots, Some(2)); + assert_eq!(capacity.available_slots, Some(5)); +} + +#[tokio::test] +async fn dashboard_capacity_distinguishes_unlimited_inheritance_finite_overrides_and_empty_pool() { + for (inherited_accounts, overridden_slots, expected_total, expected_available) in [ + (2, 5, None, None), + (0, 5, Some(5), Some(3)), + (0, 0, Some(0), Some(0)), + ] { + let now = Utc::now(); + let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); + store.replace_runtime_slots(Some(DashboardRuntimeSlots { + inherited_versions: Vec::new(), + inherited_accounts, + overridden_slots, + used_slots: Some(2), + })); + let services = crate::use_case::AdminHarness::new() + .observability(store) + .settings(Arc::new(FixtureSettingsStore { + max_concurrent_per_account: 0, + })) + .provider(crate::use_case::dashboard_profile_provider()) + .build() + .await; + let capacity = services + .observability() + .dashboard_summary(observation_range(now), TrendKind::Usage) + .await + .expect("dashboard") + .capacity; + assert_eq!(capacity.total_slots, expected_total); + assert_eq!(capacity.available_slots, expected_available); + assert_eq!(capacity.used_slots, Some(2)); + } +} + +#[tokio::test] +async fn dashboard_summary_should_observe_current_accounts_for_a_historical_range() { + let historical_end = Utc::now() - Duration::hours(1); + let store = Arc::new(FixtureObservabilityStore::new(observation_range( + historical_end, + ))); + let services = observability_services(store.clone()).await; + + services + .observability() + .dashboard_summary(observation_range(historical_end), TrendKind::Usage) + .await + .expect("dashboard summary"); + + let summary_observed_at = *store.summary_observed_at.lock().unwrap(); + assert!(summary_observed_at.is_some_and(|value| value > historical_end)); +} + +#[tokio::test] +async fn dashboard_should_preserve_provider_plan_names() { + let now = Utc::now(); + let range = observation_range(now); + let store = Arc::new(FixtureObservabilityStore::new(range)); + let plans = [("prolite", "ProLite"), ("pro", "Pro"), ("promax", "ProMax")]; + *store.account_usage.lock().unwrap() = plans + .iter() + .map(|(plan, _)| DashboardAccountUsage { + upstream: None, + account_id: format!("account-{plan}"), + provider_kind: "openai".to_owned(), + authentication_kind: "oauth".to_owned(), + name: (*plan).to_owned(), + email: None, + notes: None, + plan_type: Some((*plan).to_owned()), + plan_type_display: None, + request_count: 0, + success_count: 0, + input_tokens: None, + output_tokens: None, + cached_input_tokens: None, + cache_write_input_tokens: None, + reasoning_output_tokens: None, + image_input_tokens: None, + image_output_tokens: None, + image_request_count: 0, + image_request_failed_count: 0, + total_tokens: None, + cost_coverage: CostCoverage::default(), + costs: Vec::new(), + last_used_at: None, + request_buckets: Vec::new(), + quota_used_percent: None, + quota_window: None, + models: Vec::new(), + }) + .collect(); + let provider = crate::use_case::accounts::FakeProviderAdmin::new( + "openai", + Arc::new(Mutex::new(Vec::new())), + ); + let services = crate::use_case::AdminHarness::new() + .observability(store) + .settings(Arc::new(FixtureSettingsStore { + max_concurrent_per_account: 1, + })) + .provider(provider) + .build() + .await; + let result = services + .observability() + .dashboard_summary(range, TrendKind::Usage) + .await + .unwrap(); + assert_eq!(result.observation.account_usage.len(), plans.len()); + for (account, (raw, display)) in result.observation.account_usage.iter().zip(plans) { + assert_eq!(account.plan_type.as_deref(), Some(raw)); + assert_eq!(account.plan_type_display.as_deref(), Some(display)); + } +} diff --git a/backend/crates/gateway-admin/tests/use_case/observability/insights.rs b/backend/crates/gateway-admin/tests/use_case/observability/insights.rs new file mode 100644 index 000000000..dda67a9a4 --- /dev/null +++ b/backend/crates/gateway-admin/tests/use_case/observability/insights.rs @@ -0,0 +1,49 @@ +//! 用量洞察的指标聚合测试 + +use super::*; + +#[tokio::test] +async fn usage_insights_should_weight_concurrency_by_effective_bucket_duration() { + let bucket_start = DateTime::parse_from_rfc3339("2026-09-01T10:00:00Z") + .unwrap() + .with_timezone(&Utc); + let range = TimeRange::new( + bucket_start + Duration::minutes(5), + bucket_start + Duration::minutes(20), + ) + .unwrap(); + let store = Arc::new(FixtureObservabilityStore::new(range)); + store.replace_trend(vec![ + health_metric_point(bucket_start, RequestMetrics::default()), + health_metric_point( + bucket_start + Duration::minutes(15), + RequestMetrics::default(), + ), + ]); + *store.concurrency.lock().unwrap() = vec![ + UsageConcurrencyPoint { + bucket_start, + average_concurrency: 1.0, + peak_concurrency: 1, + }, + UsageConcurrencyPoint { + bucket_start: bucket_start + Duration::minutes(15), + average_concurrency: 3.0, + peak_concurrency: 4, + }, + ]; + + let insights = observability_services(store) + .await + .observability() + .usage_insights(range, UsageFilter::default()) + .await + .unwrap(); + + assert!((insights.performance.load.average_concurrency - 5.0 / 3.0).abs() < 1e-10); + assert_eq!(insights.performance.load.peak_concurrency, 4); + assert_eq!(insights.performance.points[0].load.average_concurrency, 1.0); + assert_eq!(insights.performance.points[0].load.peak_concurrency, 1); + assert_eq!(insights.performance.points[1].load.average_concurrency, 3.0); + assert_eq!(insights.performance.points[1].load.peak_concurrency, 4); +} diff --git a/backend/crates/gateway-admin/tests/use_case/observability/mod.rs b/backend/crates/gateway-admin/tests/use_case/observability/mod.rs index 07ea23a83..3e764784e 100644 --- a/backend/crates/gateway-admin/tests/use_case/observability/mod.rs +++ b/backend/crates/gateway-admin/tests/use_case/observability/mod.rs @@ -1,4 +1,4 @@ -//! 验证管理观测查询的时间范围、健康投影与运行态聚合 +//! 测试模块入口与共享夹具 use std::{ str::FromStr as _, @@ -36,1100 +36,6 @@ use gateway_admin::{ mod errors; -#[test] -fn external_observability_range_accepts_exactly_366_days() { - let end = Utc::now(); - let range = TimeRange::new(end - Duration::days(366), end) - .expect("366-day external range should be accepted"); - assert_eq!(range.end, end); -} - -#[test] -fn external_observability_range_rejects_over_366_days_and_reversed_range() { - let end = Utc::now(); - assert!(TimeRange::new(end - Duration::days(367), end).is_err()); - assert!(TimeRange::new(end, end).is_err()); - assert!(TimeRange::new(end + Duration::seconds(1), end).is_err()); -} - -#[tokio::test] -async fn health_timeline_should_keep_exactly_china_day_quarter_hour_slots() { - let now = Utc::now(); - let day_start = gateway_core::time::DeploymentTimeZone::default() - .day_start(now) - .unwrap(); - let current_slot = quarter_hour_start(now); - let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); - store.replace_trend(vec![ - health_metric_point( - day_start - Duration::minutes(15), - RequestMetrics { - success_count: 100, - ..RequestMetrics::default() - }, - ), - health_metric_point( - current_slot, - RequestMetrics { - success_count: 2, - ..RequestMetrics::default() - }, - ), - health_metric_point( - current_slot + Duration::minutes(15), - RequestMetrics { - success_count: 100, - ..RequestMetrics::default() - }, - ), - ]); - let services = observability_services(store).await; - - let timeline = services - .observability() - .dashboard_summary(observation_range(now), TrendKind::Usage) - .await - .expect("dashboard summary") - .health_timeline; - - assert_eq!(timeline.points.len(), 96); - assert_eq!( - timeline.points.first().map(|point| point.bucket_start), - Some(day_start) - ); - assert_eq!( - timeline.points.last().map(|point| point.bucket_start), - Some(day_start + Duration::minutes(95 * 15)) - ); - assert_eq!(timeline.success_requests, 2); - assert_eq!( - timeline - .points - .iter() - .find(|point| point.bucket_start == current_slot) - .map(|point| point.status), - Some(HealthStatus::LowSample) - ); - assert!(timeline.points.iter().all(|point| { - point.bucket_start <= quarter_hour_start(Utc::now()) - || (point.status == HealthStatus::Future && point.success_requests == 0) - })); -} - -#[tokio::test] -async fn dashboard_summary_should_derive_first_token_average_from_trend() { - let now = Utc::now(); - let current_slot = quarter_hour_start(now); - let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); - store.replace_trend(vec![ - health_metric_point( - current_slot - Duration::minutes(15), - RequestMetrics { - first_token_latency_sum_ms: 120, - first_token_latency_count: 2, - ..RequestMetrics::default() - }, - ), - health_metric_point( - current_slot, - RequestMetrics { - first_token_latency_sum_ms: 180, - first_token_latency_count: 1, - ..RequestMetrics::default() - }, - ), - ]); - let services = observability_services(store).await; - - let summary = services - .observability() - .dashboard_summary(observation_range(now), TrendKind::Usage) - .await - .expect("dashboard summary"); - - assert_eq!(summary.average_first_token_latency_ms, Some(100)); -} - -#[test] -fn dashboard_comparison_should_follow_deployment_calendar_across_dst() { - let timezone = "America/New_York".parse().unwrap(); - for (end, previous_start, previous_end, hours) in [ - ( - "2026-03-09T16:00:00Z", - "2026-03-08T05:00:00Z", - "2026-03-09T04:00:00Z", - 23, - ), - ( - "2026-11-02T17:00:00Z", - "2026-11-01T04:00:00Z", - "2026-11-02T05:00:00Z", - 25, - ), - ( - "2026-11-02T05:00:00Z", - "2026-11-01T04:00:00Z", - "2026-11-02T05:00:00Z", - 25, - ), - ] { - let end = end.parse().unwrap(); - let range = TimeRange::calendar_at( - gateway_admin::model::observability::CalendarPeriod::Today, - end, - timezone, - ) - .unwrap(); - let query = DashboardQuery::new(range, timezone).unwrap(); - assert_eq!(query.range, range); - assert_eq!( - query.yesterday_range.start, - previous_start.parse::>().unwrap() - ); - assert_eq!( - query.yesterday_range.end, - previous_end.parse::>().unwrap() - ); - assert_eq!( - (query.yesterday_range.end - query.yesterday_range.start).num_hours(), - hours - ); - } -} - -#[tokio::test] -async fn dashboard_summary_should_compare_separate_yesterday_metrics_with_today_only_trend() { - let end: DateTime = "2026-10-18T04:00:00Z".parse().unwrap(); - let range = TimeRange::calendar_at( - gateway_admin::model::observability::CalendarPeriod::Today, - end, - Default::default(), - ) - .unwrap(); - let store = Arc::new(FixtureObservabilityStore::new(range)); - store.replace_trend(vec![health_metric_point( - range.start, - RequestMetrics { - request_count: 2, - input_tokens: 100, - cached_input_tokens: 20, - total_tokens: 120, - ..Default::default() - }, - )]); - *store.yesterday.lock().unwrap() = RequestMetrics { - request_count: 4, - input_tokens: 400, - cached_input_tokens: 200, - total_tokens: 500, - ..Default::default() - }; - let result = observability_services(store.clone()) - .await - .observability() - .dashboard_summary(range, TrendKind::Usage) - .await - .unwrap(); - assert_eq!(result.today.request_count, 2); - assert_eq!(result.today.total_tokens, 120); - assert_eq!(result.today.observed_cached_token_rate, Some(0.2)); - assert_eq!(result.yesterday.request_count, 4); - assert_eq!(result.yesterday.total_tokens, 500); - assert_eq!(result.yesterday.observed_cached_token_rate, Some(0.5)); - assert_eq!(result.observation.range, range); - assert_eq!(result.observation.trend.len(), 1); - assert_eq!(result.observation.trend[0].bucket_start, range.start); - assert_eq!( - store - .summary_query - .lock() - .unwrap() - .as_ref() - .unwrap() - .yesterday_range - .end, - range.start - ); -} - -#[tokio::test] -async fn dashboard_summary_should_keep_missing_yesterday_cache_rate_unknown() { - let range = observation_range(Utc::now()); - let store = Arc::new(FixtureObservabilityStore::new(range)); - let result = observability_services(store) - .await - .observability() - .dashboard_summary(range, TrendKind::Usage) - .await - .unwrap(); - assert_eq!(result.yesterday.request_count, 0); - assert_eq!(result.yesterday.total_tokens, 0); - assert_eq!(result.yesterday.observed_cached_token_rate, None); -} - -#[tokio::test] -async fn health_timeline_should_apply_status_precedence_and_thresholds() { - let now = Utc::now(); - let current_slot = quarter_hour_start(now); - let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); - let services = observability_services(store.clone()).await; - let fixtures = [ - ( - RequestMetrics { - failure_count: 1, - cancelled_count: 1, - caller_error_count: 1, - ..RequestMetrics::default() - }, - HealthStatus::NoData, - None, - ), - ( - RequestMetrics { - incomplete_count: 1, - ..RequestMetrics::default() - }, - HealthStatus::LowSample, - Some(0.0), - ), - ( - RequestMetrics { - incomplete_count: 3, - ..RequestMetrics::default() - }, - HealthStatus::Unavailable, - Some(0.0), - ), - ( - RequestMetrics { - failure_count: 3, - ..RequestMetrics::default() - }, - HealthStatus::Unavailable, - Some(0.0), - ), - ( - RequestMetrics { - success_count: 1, - failure_count: 1, - ..RequestMetrics::default() - }, - HealthStatus::LowSample, - Some(50.0), - ), - ( - RequestMetrics { - success_count: 94, - failure_count: 6, - ..RequestMetrics::default() - }, - HealthStatus::Unstable, - Some(94.0), - ), - ( - RequestMetrics { - success_count: 95, - incomplete_count: 5, - ..RequestMetrics::default() - }, - HealthStatus::Stable, - Some(95.0), - ), - ]; - - for (index, (metrics, expected_status, expected_reliability)) in - fixtures.into_iter().enumerate() - { - store.replace_trend(vec![health_metric_point(current_slot, metrics)]); - let range_end = - now + Duration::seconds(i64::try_from(index).expect("fixture index fits i64") * 2); - let timeline = services - .observability() - .dashboard_summary(observation_range(range_end), TrendKind::Usage) - .await - .expect("dashboard summary") - .health_timeline; - let point = timeline - .points - .iter() - .find(|point| point.bucket_start == current_slot) - .expect("current health slot"); - assert_eq!(point.status, expected_status); - assert_eq!(point.reliability_percent, expected_reliability); - } -} - -#[tokio::test] -async fn health_views_should_include_incomplete_and_keep_final_outcomes_separate() { - let now = Utc::now(); - let current_slot = quarter_hour_start(now); - let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); - let services = observability_services(store.clone()).await; - let fixtures = [ - (162, 0, 2, 0, 0, 0, Some(98.780_487_804_878_05)), - (297, 0, 2, 5, 0, 0, Some(99.331_103_678_929_76)), - (467, 1, 5, 0, 0, 0, Some(98.731_501_057_082_45)), - (95, 2, 3, 4, 1, 7, Some(95.0)), - (100, 0, 0, 0, 0, 0, Some(100.0)), - (0, 0, 0, 0, 0, 0, None), - (0, 0, 0, 4, 3, 2, None), - (0, 1, 2, 0, 0, 0, Some(0.0)), - ]; - - for ( - index, - (success, failed, incomplete, cancelled, caller_error, running, expected_percent), - ) in fixtures.into_iter().enumerate() - { - let range = observation_range( - now + Duration::seconds(i64::try_from(index).expect("fixture index fits i64") * 2), - ); - let metrics = RequestMetrics { - request_count: success + failed + incomplete + cancelled + caller_error + running, - success_count: success, - failure_count: failed + caller_error, - incomplete_count: incomplete, - cancelled_count: cancelled, - caller_error_count: caller_error, - ..RequestMetrics::default() - }; - store.replace_trend(vec![health_metric_point(current_slot, metrics.clone())]); - store.replace_overview(UsageOverview { - analytics: Default::default(), - range, - requests: metrics, - // 中间尝试失败不会增加最终失败请求数 - attempts: AttemptMetrics { - failure_count: 2, - ..AttemptMetrics::default() - }, - providers: Vec::new(), - }); - - let mut item = diagnostic( - "model", - success + failed + incomplete + cancelled + caller_error + running, - ); - item.success_count = success; - item.failure_count = failed + caller_error; - item.incomplete_count = incomplete; - item.cancelled_count = cancelled; - item.caller_error_count = caller_error; - store.replace_diagnostics(DiagnosticsObservation { - analytics: Default::default(), - total_request_count: item.request_count, - items: vec![item], - }); - let diagnostics = services - .observability() - .diagnostics(range, UsageFilter::default(), DiagnosticDimension::Model) - .await - .unwrap(); - assert_eq!(diagnostics.items[0].error_count, failed + incomplete); - - let dashboard = services - .observability() - .dashboard_summary(range, TrendKind::Usage) - .await - .expect("dashboard summary"); - let timeline = dashboard.health_timeline; - let point = timeline - .points - .iter() - .find(|point| point.bucket_start == current_slot) - .expect("current health slot"); - assert_eq!(dashboard.trend.summary.error_count, failed + incomplete); - assert_eq!(dashboard.trend.points[0].error_count, failed + incomplete); - assert_eq!(point.failed_requests, failed); - assert_eq!(point.incomplete_requests, incomplete); - assert_eq!(point.cancelled_requests, cancelled); - assert_eq!(point.caller_error_requests, caller_error); - - let insights = services - .observability() - .usage_insights(range, UsageFilter::default()) - .await - .expect("usage insights"); - assert_eq!(insights.health.failed_requests, failed); - assert_eq!(insights.health.incomplete_requests, incomplete); - for actual in [ - timeline.reliability_percent, - point.reliability_percent, - dashboard - .trend - .summary - .success_rate - .map(|rate| rate * 100.0), - dashboard.trend.points[0] - .success_rate - .map(|rate| rate * 100.0), - insights.health.success_rate.map(|rate| rate * 100.0), - insights.health.points[0] - .error_rate - .map(|rate| (1.0 - rate) * 100.0), - diagnostics.items[0] - .error_rate - .map(|rate| (1.0 - rate) * 100.0), - ] { - match (actual, expected_percent) { - (Some(actual), Some(expected)) => assert!((actual - expected).abs() < 1e-10), - (None, None) => {} - _ => panic!("unexpected rate: {actual:?}, expected {expected_percent:?}"), - } - } - } -} - -#[tokio::test] -async fn dashboard_summary_should_project_rebuildable_runtime_slots() { - let now = Utc::now(); - let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); - store.replace_runtime_slots(Some(DashboardRuntimeSlots { - inherited_versions: Vec::new(), - inherited_accounts: 2, - overridden_slots: 5, - used_slots: Some(2), - })); - let services = observability_services(store).await; - - let capacity = services - .observability() - .dashboard_summary(observation_range(now), TrendKind::Usage) - .await - .expect("dashboard summary") - .capacity; - - assert_eq!(capacity.total_slots, Some(7)); - assert_eq!(capacity.used_slots, Some(2)); - assert_eq!(capacity.available_slots, Some(5)); -} - -#[tokio::test] -async fn dashboard_capacity_distinguishes_unlimited_inheritance_finite_overrides_and_empty_pool() { - for (inherited_accounts, overridden_slots, expected_total, expected_available) in [ - (2, 5, None, None), - (0, 5, Some(5), Some(3)), - (0, 0, Some(0), Some(0)), - ] { - let now = Utc::now(); - let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); - store.replace_runtime_slots(Some(DashboardRuntimeSlots { - inherited_versions: Vec::new(), - inherited_accounts, - overridden_slots, - used_slots: Some(2), - })); - let services = super::AdminHarness::new() - .observability(store) - .settings(Arc::new(FixtureSettingsStore { - max_concurrent_per_account: 0, - })) - .provider(super::dashboard_profile_provider()) - .build() - .await; - let capacity = services - .observability() - .dashboard_summary(observation_range(now), TrendKind::Usage) - .await - .expect("dashboard") - .capacity; - assert_eq!(capacity.total_slots, expected_total); - assert_eq!(capacity.available_slots, expected_available); - assert_eq!(capacity.used_slots, Some(2)); - } -} - -#[tokio::test] -async fn dashboard_summary_should_observe_current_accounts_for_a_historical_range() { - let historical_end = Utc::now() - Duration::hours(1); - let store = Arc::new(FixtureObservabilityStore::new(observation_range( - historical_end, - ))); - let services = observability_services(store.clone()).await; - - services - .observability() - .dashboard_summary(observation_range(historical_end), TrendKind::Usage) - .await - .expect("dashboard summary"); - - let summary_observed_at = *store.summary_observed_at.lock().unwrap(); - assert!(summary_observed_at.is_some_and(|value| value > historical_end)); -} - -#[tokio::test] -async fn dashboard_summary_should_keep_distinct_exact_ranges_in_one_short_window() { - let end_bucket = Utc::now().timestamp().div_euclid(2) * 2; - let first_end = DateTime::from_timestamp(end_bucket, 100_000_000).expect("first end"); - let second_end = DateTime::from_timestamp(end_bucket, 900_000_000).expect("second end"); - let first_range = TimeRange::new( - gateway_core::time::DeploymentTimeZone::default() - .day_start(first_end) - .unwrap(), - first_end, - ) - .expect("first range"); - let second_range = TimeRange::new( - gateway_core::time::DeploymentTimeZone::default() - .day_start(second_end) - .unwrap(), - second_end, - ) - .expect("second range"); - let store = Arc::new(FixtureObservabilityStore::new(first_range)); - store.set_dashboard_delay(StdDuration::from_millis(20)); - let services = observability_services(store.clone()).await; - let observability = services.observability(); - - let (first, second) = tokio::join!( - observability.dashboard_summary(first_range, TrendKind::Usage), - observability.dashboard_summary(second_range, TrendKind::Errors), - ); - - first.expect("first dashboard summary"); - second.expect("second dashboard summary"); - assert_eq!(store.dashboard_summary_calls(), 2); -} - -#[tokio::test] -async fn dashboard_summary_should_reload_after_the_short_window_changes() { - let end_bucket = Utc::now().timestamp().div_euclid(2) * 2; - let first_end = DateTime::from_timestamp(end_bucket, 100_000_000).expect("first end"); - let second_end = first_end + Duration::seconds(2); - let first_range = TimeRange::new( - gateway_core::time::DeploymentTimeZone::default() - .day_start(first_end) - .unwrap(), - first_end, - ) - .expect("first range"); - let second_range = TimeRange::new( - gateway_core::time::DeploymentTimeZone::default() - .day_start(second_end) - .unwrap(), - second_end, - ) - .expect("second range"); - let store = Arc::new(FixtureObservabilityStore::new(first_range)); - let services = observability_services(store.clone()).await; - let observability = services.observability(); - - observability - .dashboard_summary(first_range, TrendKind::Usage) - .await - .expect("first dashboard summary"); - observability - .dashboard_summary(second_range, TrendKind::Usage) - .await - .expect("second dashboard summary"); - - assert_eq!(store.dashboard_summary_calls(), 2); -} - -#[tokio::test] -async fn observability_services_should_calculate_usage_insights_and_diagnostic_shares() { - let now = Utc::now(); - let range = observation_range(now); - let store = Arc::new(FixtureObservabilityStore::new(range)); - let metrics = RequestMetrics { - request_count: 10, - success_count: 6, - failure_count: 4, - caller_error_count: 2, - input_tokens: 800, - output_tokens: 200, - total_tokens: 1_000, - latency_count: 5, - admission_decision_count: 10, - admission_decision_percentiles: LatencyPercentiles { - p50_ms: Some(PercentileMilliseconds::new(2.0).expect("admission P50")), - p95_ms: Some(PercentileMilliseconds::new(5.0).expect("admission P95")), - p99_ms: Some(PercentileMilliseconds::new(8.0).expect("admission P99")), - }, - account_selection_wait_count: 8, - account_selection_wait_percentiles: LatencyPercentiles { - p50_ms: Some(PercentileMilliseconds::new(10.0).expect("selection P50")), - p95_ms: Some(PercentileMilliseconds::new(40.0).expect("selection P95")), - p99_ms: Some(PercentileMilliseconds::new(70.0).expect("selection P99")), - }, - output_throughput_p10: Some(40), - output_throughput_p50: Some(50), - output_throughput_p90: Some(60), - capacity_sample_count: 8, - capacity_utilization_avg_basis_points: Some(6_500), - capacity_utilization_p95_basis_points: Some(8_000), - ..RequestMetrics::default() - }; - store.replace_overview(UsageOverview { - analytics: Default::default(), - range, - requests: metrics.clone(), - attempts: AttemptMetrics { - attempt_count: 12, - cost_coverage: CostCoverage { - calculated_count: 10, - ..CostCoverage::default() - }, - costs: vec![CurrencyCost { - currency: "USD".to_owned(), - amount: gateway_admin::model::observability::DecimalAmount::from_str("1.25") - .expect("USD cost"), - }], - ..AttemptMetrics::default() - }, - providers: Vec::new(), - }); - store.replace_trend(vec![RequestMetricPoint { - bucket_start: quarter_hour_start(now), - granularity: Granularity::FifteenMinutes, - metrics, - cost_coverage: CostCoverage::default(), - costs: vec![CurrencyCost { - currency: "USD".to_owned(), - amount: gateway_admin::model::observability::DecimalAmount::from_str("0.25") - .expect("bucket USD cost"), - }], - }]); - store.replace_projected_costs(vec![UsageProjectedCostPoint { - bucket_start: quarter_hour_start(now), - standard_amount: Some("1".parse().expect("standard cost")), - no_cache_amount: Some("1.25".parse().expect("no-cache cost")), - }]); - store.replace_diagnostics(DiagnosticsObservation { - analytics: Default::default(), - total_request_count: 4, - items: vec![diagnostic("openai", 3), diagnostic("xai", 1)], - }); - let services = observability_services_with_calculated_billing(store).await; - - let insights = services - .observability() - .usage_insights(range, UsageFilter::default()) - .await - .expect("usage insights"); - let diagnostics = services - .observability() - .diagnostics(range, UsageFilter::default(), DiagnosticDimension::Provider) - .await - .expect("usage diagnostics"); - - assert_eq!(insights.health.total_requests, 10); - assert_eq!(insights.health.failed_requests, 2); - assert_eq!(insights.health.success_rate, Some(0.75)); - assert_eq!(insights.health.completion_rate, 1.0); - assert_eq!(insights.granularity, Granularity::FifteenMinutes); - assert_eq!( - insights - .performance - .load - .admission_decision_p95_ms - .map(|value| value.as_f64()), - Some(5.0) - ); - assert_eq!( - insights - .performance - .load - .account_selection_wait_p95_ms - .map(|value| value.as_f64()), - Some(40.0) - ); - assert_eq!( - insights.performance.points[0].load, - insights.performance.load - ); - assert_eq!(insights.performance.output_throughput_p50, Some(50)); - assert_eq!(insights.cost.tokens_per_request, 100.0); - assert_eq!( - insights - .cost - .estimated_cost - .as_ref() - .map(gateway_admin::model::observability::DecimalAmount::as_str), - Some("1.25") - ); - assert_eq!( - insights - .cost - .cost_per_request - .as_ref() - .map(gateway_admin::model::observability::DecimalAmount::as_str), - Some("0.125") - ); - assert_eq!( - insights.cost.points[0] - .estimated_cost - .as_ref() - .map(gateway_admin::model::observability::DecimalAmount::as_str), - Some("0.25") - ); - assert_eq!( - insights - .cost - .standard_cost - .as_ref() - .map(gateway_admin::model::observability::DecimalAmount::as_str), - Some("1") - ); - assert_eq!( - insights.cost.points[0] - .standard_cost - .as_ref() - .map(gateway_admin::model::observability::DecimalAmount::as_str), - Some("1") - ); - assert_eq!( - insights - .cost - .no_cache_cost - .as_ref() - .map(gateway_admin::model::observability::DecimalAmount::as_str), - Some("1.25") - ); - assert_eq!( - insights - .cost - .tier_premium - .as_ref() - .map(gateway_admin::model::observability::DecimalAmount::as_str), - Some("0.25") - ); - assert_eq!(diagnostics.items[0].request_share, 0.75); - assert_eq!(diagnostics.items[1].request_share, 0.25); -} - -#[tokio::test] -async fn usage_insights_should_weight_concurrency_by_effective_bucket_duration() { - let bucket_start = DateTime::parse_from_rfc3339("2026-09-01T10:00:00Z") - .unwrap() - .with_timezone(&Utc); - let range = TimeRange::new( - bucket_start + Duration::minutes(5), - bucket_start + Duration::minutes(20), - ) - .unwrap(); - let store = Arc::new(FixtureObservabilityStore::new(range)); - store.replace_trend(vec![ - health_metric_point(bucket_start, RequestMetrics::default()), - health_metric_point( - bucket_start + Duration::minutes(15), - RequestMetrics::default(), - ), - ]); - *store.concurrency.lock().unwrap() = vec![ - UsageConcurrencyPoint { - bucket_start, - average_concurrency: 1.0, - peak_concurrency: 1, - }, - UsageConcurrencyPoint { - bucket_start: bucket_start + Duration::minutes(15), - average_concurrency: 3.0, - peak_concurrency: 4, - }, - ]; - - let insights = observability_services(store) - .await - .observability() - .usage_insights(range, UsageFilter::default()) - .await - .unwrap(); - - assert!((insights.performance.load.average_concurrency - 5.0 / 3.0).abs() < 1e-10); - assert_eq!(insights.performance.load.peak_concurrency, 4); - assert_eq!(insights.performance.points[0].load.average_concurrency, 1.0); - assert_eq!(insights.performance.points[0].load.peak_concurrency, 1); - assert_eq!(insights.performance.points[1].load.average_concurrency, 3.0); - assert_eq!(insights.performance.points[1].load.peak_concurrency, 4); -} - -#[tokio::test] -async fn diagnostics_should_preserve_request_order_when_a_small_sample_fails() { - let now = Utc::now(); - let range = observation_range(now); - let store = Arc::new(FixtureObservabilityStore::new(range)); - let success = diagnostic("popular", 100); - let mut failure = diagnostic("single_failure", 1); - failure.success_count = 0; - failure.failure_count = 1; - store.replace_diagnostics(DiagnosticsObservation { - analytics: Default::default(), - total_request_count: 101, - items: vec![success, failure], - }); - let services = observability_services_with_calculated_billing(store).await; - - let result = services - .observability() - .diagnostics(range, UsageFilter::default(), DiagnosticDimension::Model) - .await - .expect("diagnostics"); - - assert_eq!(result.items[0].key, "popular"); - assert_eq!(result.items[1].key, "single_failure"); - assert_eq!(result.items[0].error_count, 0); - assert_eq!(result.items[1].error_count, 1); - assert_eq!(result.items[1].error_rate, Some(1.0)); -} - -#[tokio::test] -async fn diagnostics_should_use_the_total_before_truncating_groups() { - let range = observation_range(Utc::now()); - let store = Arc::new(FixtureObservabilityStore::new(range)); - store.replace_diagnostics(DiagnosticsObservation { - analytics: Default::default(), - total_request_count: 200, - items: (0..100) - .map(|index| diagnostic(&format!("model-{index}"), 1)) - .collect(), - }); - let services = observability_services_with_calculated_billing(store).await; - - let result = services - .observability() - .diagnostics(range, UsageFilter::default(), DiagnosticDimension::Model) - .await - .expect("limited diagnostics"); - - assert!(result.items.iter().all(|item| item.request_share == 0.005)); -} - -#[tokio::test] -async fn diagnostics_should_count_each_retried_request_once() { - let range = observation_range(Utc::now()); - let store = Arc::new(FixtureObservabilityStore::new(range)); - let mut item = diagnostic("model", 8); - item.attempt_count = 14; - item.retry_count = 6; - item.retried_request_count = 2; - store.replace_diagnostics(DiagnosticsObservation { - analytics: Default::default(), - total_request_count: 8, - items: vec![item], - }); - let services = observability_services_with_calculated_billing(store).await; - - let result = services - .observability() - .diagnostics(range, UsageFilter::default(), DiagnosticDimension::Model) - .await - .expect("retry diagnostics"); - - assert_eq!( - (result.items[0].retry_count, result.items[0].retry_rate), - (6, 0.25) - ); -} - -#[tokio::test] -async fn diagnostics_should_preserve_empty_results() { - let range = observation_range(Utc::now()); - let store = Arc::new(FixtureObservabilityStore::new(range)); - let services = observability_services_with_calculated_billing(store).await; - - let result = services - .observability() - .diagnostics(range, UsageFilter::default(), DiagnosticDimension::Account) - .await - .expect("empty diagnostics"); - - assert!(result.items.is_empty()); -} - -#[tokio::test] -async fn usage_records_should_tolerate_records_that_fail_billing_enrichment() { - let now = Utc::now(); - let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); - let invalid_kind = "x".repeat(65); - store.replace_usage_records(vec![ - total_record( - "request_invalid_kind", - Some(&invalid_kind), - "calculated", - now, - ), - total_record( - "request_unregistered_kind", - Some("anthropic"), - "calculated", - now, - ), - total_record("request_enriched", Some("openai"), "calculated", now), - ]); - let services = observability_services_with_calculated_billing(store).await; - - let page = services - .observability() - .usage_records(usage_query(now)) - .await - .expect("one bad record must not fail the whole usage list"); - - assert_eq!(page.items.len(), 3); - assert!( - matches!(page.items[0].billing, Some(UsageBilling::Total { .. })), - "invalid Provider kind keeps the stored total" - ); - assert!( - matches!(page.items[1].billing, Some(UsageBilling::Total { .. })), - "unregistered Provider kind keeps the stored total" - ); - assert!( - matches!(page.items[2].billing, Some(UsageBilling::Calculated(_))), - "healthy record is still enriched" - ); -} - -#[tokio::test] -async fn usage_records_should_enrich_provider_reported_totals_when_pricing_matches() { - let now = Utc::now(); - let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); - store.replace_usage_records(vec![total_record( - "request_provider_reported", - Some("openai"), - "provider_reported", - now, - )]); - let services = observability_services_with_calculated_billing(store).await; - - let page = services - .observability() - .usage_records(usage_query(now)) - .await - .expect("usage records"); - - assert!(matches!( - page.items[0].billing, - Some(UsageBilling::Calculated(_)) - )); -} - -#[tokio::test] -async fn usage_insights_should_reject_partial_costs_when_insights_fail() { - let now = Utc::now(); - let range = observation_range(now); - let store = Arc::new(FixtureObservabilityStore::new(range)); - store.replace_projected_costs(vec![UsageProjectedCostPoint { - bucket_start: quarter_hour_start(now), - standard_amount: Some("1".parse().expect("standard cost")), - no_cache_amount: Some("1.25".parse().expect("no-cache cost")), - }]); - store.insights_fail.store(true, Ordering::SeqCst); - let services = observability_services_with_calculated_billing(store).await; - assert!( - services - .observability() - .usage_insights(range, UsageFilter::default()) - .await - .is_err() - ); -} - -#[tokio::test] -async fn dashboard_should_preserve_provider_plan_names() { - let now = Utc::now(); - let range = observation_range(now); - let store = Arc::new(FixtureObservabilityStore::new(range)); - let plans = [("prolite", "ProLite"), ("pro", "Pro"), ("promax", "ProMax")]; - *store.account_usage.lock().unwrap() = plans - .iter() - .map(|(plan, _)| DashboardAccountUsage { - upstream: None, - account_id: format!("account-{plan}"), - provider_kind: "openai".to_owned(), - authentication_kind: "oauth".to_owned(), - name: (*plan).to_owned(), - email: None, - notes: None, - plan_type: Some((*plan).to_owned()), - plan_type_display: None, - request_count: 0, - success_count: 0, - input_tokens: None, - output_tokens: None, - cached_input_tokens: None, - cache_write_input_tokens: None, - reasoning_output_tokens: None, - image_input_tokens: None, - image_output_tokens: None, - image_request_count: 0, - image_request_failed_count: 0, - total_tokens: None, - cost_coverage: CostCoverage::default(), - costs: Vec::new(), - last_used_at: None, - request_buckets: Vec::new(), - quota_used_percent: None, - quota_window: None, - models: Vec::new(), - }) - .collect(); - let provider = - super::accounts::FakeProviderAdmin::new("openai", Arc::new(Mutex::new(Vec::new()))); - let services = super::AdminHarness::new() - .observability(store) - .settings(Arc::new(FixtureSettingsStore { - max_concurrent_per_account: 1, - })) - .provider(provider) - .build() - .await; - let result = services - .observability() - .dashboard_summary(range, TrendKind::Usage) - .await - .unwrap(); - assert_eq!(result.observation.account_usage.len(), plans.len()); - for (account, (raw, display)) in result.observation.account_usage.iter().zip(plans) { - assert_eq!(account.plan_type.as_deref(), Some(raw)); - assert_eq!(account.plan_type_display.as_deref(), Some(display)); - } -} - -#[tokio::test] -async fn dashboard_and_usage_insights_keep_concurrency_cache_entries_separate() { - for dashboard_first in [true, false] { - let now = Utc::now(); - let range = observation_range(now); - let store = Arc::new(FixtureObservabilityStore::new(range)); - store - .concurrency - .lock() - .unwrap() - .push(UsageConcurrencyPoint { - bucket_start: range.start, - average_concurrency: 2.0, - peak_concurrency: 3, - }); - let services = observability_services(store.clone()).await; - for dashboard in [ - dashboard_first, - !dashboard_first, - dashboard_first, - !dashboard_first, - ] { - if dashboard { - services - .observability() - .dashboard_trend(range, TrendKind::Usage) - .await - .unwrap(); - } else { - let result = services - .observability() - .usage_insights(range, UsageFilter::default()) - .await - .unwrap(); - assert_eq!(result.performance.load.peak_concurrency, 3); - } - } - assert_eq!( - *store.concurrency_selections.lock().unwrap(), - vec![!dashboard_first, dashboard_first] - ); - } -} - struct FixtureObservabilityStore { yesterday: Mutex, trend: Mutex>, @@ -1446,9 +352,9 @@ impl SettingsStore for FixtureSettingsStore { switch_account_on_queue_failure: false, max_retry_after_seconds: 240, openai_guardian_reserved_concurrency: 0, - openai_account_affinity: gateway_core::account::AccountAffinity::Relaxed, + account_affinity: gateway_core::account::AccountAffinity::Relaxed, max_account_rotations: 3, - openai_session_affinity_ttl_hours: 24, + session_affinity_ttl_hours: 24, responses_max_decompressed_body_bytes: 64 * 1024 * 1024, smart_scheduling: gateway_core::account::SmartSchedulingConfig::default(), quota_reset_window_weights: gateway_core::account::ResetWindowWeights::default(), @@ -1654,284 +560,10 @@ fn quarter_hour_start(value: DateTime) -> DateTime { value - Duration::seconds(elapsed) - Duration::nanoseconds(i64::from(value.nanosecond())) } -#[tokio::test] -async fn admin_selects_dashboard_defaults_and_matching_usage_buckets_at_range_boundaries() { - let now = Utc::now(); - for (duration, expected) in [ - (Duration::days(2), Granularity::FifteenMinutes), - (Duration::days(2) + Duration::seconds(1), Granularity::Hour), - (Duration::days(31), Granularity::Hour), - (Duration::days(31) + Duration::seconds(1), Granularity::Day), - ] { - let range = TimeRange::new(now - duration, now).unwrap(); - let store = Arc::new(FixtureObservabilityStore::new(range)); - let services = observability_services(store.clone()).await; - services - .observability() - .dashboard_summary(range, TrendKind::Usage) - .await - .unwrap(); - let query = store.summary_query.lock().unwrap().clone().unwrap(); - assert_eq!(query.range, range); - assert_eq!(query.granularity, expected); - assert_eq!(query.account_limit, 4); - assert_eq!(query.recent_request_limit, 10); - assert_eq!( - query.recent_request_filter.outcome, - Some(gateway_admin::model::observability::RequestOutcome::Succeeded) - ); - services - .observability() - .usage_insights(range, UsageFilter::default()) - .await - .unwrap(); - assert_eq!(*store.usage_granularities.lock().unwrap(), vec![expected]); - } -} +mod service; -#[tokio::test] -async fn usage_summary_cache_should_coalesce_identical_queries_and_invalidate_deleted_generation() { - let range = observation_range(Utc::now()); - let store = Arc::new(FixtureObservabilityStore::new(range)); - store.set_dashboard_delay(StdDuration::from_millis(20)); - let services = observability_services(store.clone()).await; - let service = services.observability(); - let filter = UsageFilter { - client_api_key_ref: Some("deleted-key".to_owned()), - ..Default::default() - }; - let (first, second) = tokio::join!( - service.usage_summary(range, filter.clone()), - service.usage_summary(range, filter.clone()), - ); - first.expect("first summary"); - second.expect("coalesced summary"); - assert_eq!(store.usage_summary_filters.lock().unwrap().len(), 1); - { - let mut overview = store.overview.lock().unwrap(); - overview.analytics.generation = 1; - overview.requests.request_count = 7; - } - let refreshed = service - .usage_summary(range, filter) - .await - .expect("generation refresh"); - assert_eq!(refreshed.observation.analytics.generation, 1); - assert_eq!(refreshed.observation.requests.request_count, 7); - assert_eq!(store.usage_summary_filters.lock().unwrap().len(), 2); -} +mod dashboard; -#[tokio::test(start_paused = true)] -async fn usage_summary_cache_should_coalesce_when_generation_advances_during_the_first_load() { - let range = observation_range(Utc::now()); - let store = Arc::new(FixtureObservabilityStore::new(range)); - store.set_dashboard_delay(StdDuration::from_millis(20)); - let services = observability_services(store.clone()).await; - let service = services.observability(); - let (first, second, ()) = tokio::join!( - service.usage_summary(range, UsageFilter::default()), - service.usage_summary(range, UsageFilter::default()), - async { - tokio::time::sleep(StdDuration::from_millis(5)).await; - store.overview.lock().unwrap().analytics.generation = 1; - }, - ); - assert_eq!( - first - .expect("first summary") - .observation - .analytics - .generation, - 1 - ); - assert_eq!( - second - .expect("coalesced summary") - .observation - .analytics - .generation, - 1 - ); - assert_eq!(store.usage_summary_filters.lock().unwrap().len(), 1); -} +mod store_cache; -#[tokio::test] -async fn usage_summary_cache_should_isolate_key_identity_and_filters() { - let range = observation_range(Utc::now()); - let store = Arc::new(FixtureObservabilityStore::new(range)); - let services = observability_services(store.clone()).await; - let service = services.observability(); - for (key, model) in [ - ("key-a", None), - ("key-a", None), - ("key-b", None), - ("key-a", Some("model-a")), - ] { - service - .usage_summary( - range, - UsageFilter { - client_api_key_ref: Some(key.to_owned()), - model: model.map(str::to_owned), - ..Default::default() - }, - ) - .await - .expect("isolated summary"); - } - let calls = store.usage_summary_filters.lock().unwrap(); - assert_eq!(calls.len(), 3); - assert_eq!(calls[0].client_api_key_ref.as_deref(), Some("key-a")); - assert_eq!(calls[1].client_api_key_ref.as_deref(), Some("key-b")); - assert_eq!(calls[2].model.as_deref(), Some("model-a")); -} - -#[tokio::test(start_paused = true)] -async fn usage_summary_cache_should_bound_waiting_after_failed_refresh_and_allow_recovery() { - let range = observation_range(Utc::now()); - let store = Arc::new(FixtureObservabilityStore::new(range)); - store.set_dashboard_delay(store.query_timeout().mul_f64(0.7)); - store.summary_fail.store(true, Ordering::SeqCst); - let services = observability_services(store.clone()).await; - let service = services.observability(); - let started = tokio::time::Instant::now(); - let (first, second, third, fourth) = tokio::join!( - service.usage_summary(range, UsageFilter::default()), - service.usage_summary(range, UsageFilter::default()), - service.usage_summary(range, UsageFilter::default()), - service.usage_summary(range, UsageFilter::default()), - ); - assert!(first.is_err() && second.is_err() && third.is_err() && fourth.is_err()); - assert!( - started.elapsed() <= store.query_timeout(), - "同键失败不能使后续请求逐个等待完整数据库超时: {:?}", - started.elapsed() - ); - - store.summary_fail.store(false, Ordering::SeqCst); - store.set_dashboard_delay(StdDuration::ZERO); - service - .usage_summary(range, UsageFilter::default()) - .await - .expect("cancelled cache refresh releases its slot for recovery"); -} - -#[tokio::test(start_paused = true)] -async fn insights_cache_should_bound_stale_lifetime_without_renewing_failed_refreshes() { - let range = observation_range(Utc::now()); - let store = Arc::new(FixtureObservabilityStore::new(range)); - { - let mut overview = store.overview.lock().unwrap(); - overview.analytics.state = AnalyticsState::Ready; - overview.analytics.generated_at = Utc::now(); - overview.analytics.lag_seconds = 7; - overview.requests.request_count = 19; - } - let services = observability_services(store.clone()).await; - let service = services.observability(); - service - .usage_insights(range, UsageFilter::default()) - .await - .unwrap(); - store.insights_fail.store(true, Ordering::SeqCst); - tokio::time::advance(StdDuration::from_secs(16)).await; - let stale = service - .usage_insights(range, UsageFilter::default()) - .await - .unwrap(); - assert_eq!(stale.analytics.state, AnalyticsState::Stale); - assert!(stale.analytics.lag_seconds >= 7); - assert_eq!(stale.health.total_requests, 19); - tokio::time::advance(StdDuration::from_secs(45)).await; - assert!( - service - .usage_insights(range, UsageFilter::default()) - .await - .is_err() - ); -} - -#[tokio::test(start_paused = true)] -async fn insights_cache_should_reject_deleted_building_and_old_generation_times() { - for reason in ["deleted", "building", "generated-too-long-ago"] { - let range = observation_range(Utc::now()); - let store = Arc::new(FixtureObservabilityStore::new(range)); - { - let mut overview = store.overview.lock().unwrap(); - overview.analytics.state = if reason == "building" { - AnalyticsState::Building - } else { - AnalyticsState::Ready - }; - overview.analytics.generated_at = Utc::now() - - Duration::seconds(if reason == "generated-too-long-ago" { - 61 - } else { - 0 - }); - } - let services = observability_services(store.clone()).await; - let service = services.observability(); - service - .usage_insights(range, UsageFilter::default()) - .await - .unwrap(); - store.insights_fail.store(true, Ordering::SeqCst); - if reason == "deleted" { - store.overview.lock().unwrap().analytics.generation += 1; - } - tokio::time::advance(StdDuration::from_secs(16)).await; - assert!( - service - .usage_insights(range, UsageFilter::default()) - .await - .is_err(), - "{reason}" - ); - } -} - -#[tokio::test] -async fn usage_metric_cache_isolates_selections_and_filters() { - use gateway_admin::model::observability::UsageInsightMetric as Metric; - let range = observation_range(Utc::now()); - let store = Arc::new(FixtureObservabilityStore::new(range)); - let services = observability_services(store.clone()).await; - let metrics = [ - Metric::Health, - Metric::Latency, - Metric::FirstToken, - Metric::Throughput, - Metric::Load, - Metric::Cost, - Metric::Savings, - Metric::Cache, - ]; - for _ in 0..2 { - for metric in metrics { - services - .observability() - .usage_metric(range, UsageFilter::default(), metric) - .await - .unwrap(); - } - } - assert_eq!(*store.metric_selections.lock().unwrap(), metrics); - assert_eq!( - *store.concurrency_selections.lock().unwrap(), - vec![false, false, false, false, true, false, false, false] - ); - services - .observability() - .usage_metric( - range, - UsageFilter { - provider_kind: Some("openai".into()), - ..Default::default() - }, - Metric::Latency, - ) - .await - .unwrap(); - assert_eq!(store.metric_selections.lock().unwrap().len(), 9); -} +mod insights; diff --git a/backend/crates/gateway-admin/tests/use_case/observability/service.rs b/backend/crates/gateway-admin/tests/use_case/observability/service.rs new file mode 100644 index 000000000..e8d21f0a9 --- /dev/null +++ b/backend/crates/gateway-admin/tests/use_case/observability/service.rs @@ -0,0 +1,407 @@ +//! 观测查询协调、错误传播与费用补充测试 + +use super::*; + +#[test] +fn external_observability_range_accepts_exactly_366_days() { + let end = Utc::now(); + let range = TimeRange::new(end - Duration::days(366), end) + .expect("366-day external range should be accepted"); + assert_eq!(range.end, end); +} + +#[test] +fn external_observability_range_rejects_over_366_days_and_reversed_range() { + let end = Utc::now(); + assert!(TimeRange::new(end - Duration::days(367), end).is_err()); + assert!(TimeRange::new(end, end).is_err()); + assert!(TimeRange::new(end + Duration::seconds(1), end).is_err()); +} + +#[tokio::test] +async fn observability_services_should_calculate_usage_insights_and_diagnostic_shares() { + let now = Utc::now(); + let range = observation_range(now); + let store = Arc::new(FixtureObservabilityStore::new(range)); + let metrics = RequestMetrics { + request_count: 10, + success_count: 6, + failure_count: 4, + caller_error_count: 2, + input_tokens: 800, + output_tokens: 200, + total_tokens: 1_000, + latency_count: 5, + admission_decision_count: 10, + admission_decision_percentiles: LatencyPercentiles { + p50_ms: Some(PercentileMilliseconds::new(2.0).expect("admission P50")), + p95_ms: Some(PercentileMilliseconds::new(5.0).expect("admission P95")), + p99_ms: Some(PercentileMilliseconds::new(8.0).expect("admission P99")), + }, + account_selection_wait_count: 8, + account_selection_wait_percentiles: LatencyPercentiles { + p50_ms: Some(PercentileMilliseconds::new(10.0).expect("selection P50")), + p95_ms: Some(PercentileMilliseconds::new(40.0).expect("selection P95")), + p99_ms: Some(PercentileMilliseconds::new(70.0).expect("selection P99")), + }, + output_throughput_p10: Some(40), + output_throughput_p50: Some(50), + output_throughput_p90: Some(60), + capacity_sample_count: 8, + capacity_utilization_avg_basis_points: Some(6_500), + capacity_utilization_p95_basis_points: Some(8_000), + ..RequestMetrics::default() + }; + store.replace_overview(UsageOverview { + analytics: Default::default(), + range, + requests: metrics.clone(), + attempts: AttemptMetrics { + attempt_count: 12, + cost_coverage: CostCoverage { + calculated_count: 10, + ..CostCoverage::default() + }, + costs: vec![CurrencyCost { + currency: "USD".to_owned(), + amount: gateway_admin::model::observability::DecimalAmount::from_str("1.25") + .expect("USD cost"), + }], + ..AttemptMetrics::default() + }, + providers: Vec::new(), + }); + store.replace_trend(vec![RequestMetricPoint { + bucket_start: quarter_hour_start(now), + granularity: Granularity::FifteenMinutes, + metrics, + cost_coverage: CostCoverage::default(), + costs: vec![CurrencyCost { + currency: "USD".to_owned(), + amount: gateway_admin::model::observability::DecimalAmount::from_str("0.25") + .expect("bucket USD cost"), + }], + }]); + store.replace_projected_costs(vec![UsageProjectedCostPoint { + bucket_start: quarter_hour_start(now), + standard_amount: Some("1".parse().expect("standard cost")), + no_cache_amount: Some("1.25".parse().expect("no-cache cost")), + }]); + store.replace_diagnostics(DiagnosticsObservation { + analytics: Default::default(), + total_request_count: 4, + items: vec![diagnostic("openai", 3), diagnostic("xai", 1)], + }); + let services = observability_services_with_calculated_billing(store).await; + + let insights = services + .observability() + .usage_insights(range, UsageFilter::default()) + .await + .expect("usage insights"); + let diagnostics = services + .observability() + .diagnostics(range, UsageFilter::default(), DiagnosticDimension::Provider) + .await + .expect("usage diagnostics"); + + assert_eq!(insights.health.total_requests, 10); + assert_eq!(insights.health.failed_requests, 2); + assert_eq!(insights.health.success_rate, Some(0.75)); + assert_eq!(insights.health.completion_rate, 1.0); + assert_eq!(insights.granularity, Granularity::FifteenMinutes); + assert_eq!( + insights + .performance + .load + .admission_decision_p95_ms + .map(|value| value.as_f64()), + Some(5.0) + ); + assert_eq!( + insights + .performance + .load + .account_selection_wait_p95_ms + .map(|value| value.as_f64()), + Some(40.0) + ); + assert_eq!( + insights.performance.points[0].load, + insights.performance.load + ); + assert_eq!(insights.performance.output_throughput_p50, Some(50)); + assert_eq!(insights.cost.tokens_per_request, 100.0); + assert_eq!( + insights + .cost + .estimated_cost + .as_ref() + .map(gateway_admin::model::observability::DecimalAmount::as_str), + Some("1.25") + ); + assert_eq!( + insights + .cost + .cost_per_request + .as_ref() + .map(gateway_admin::model::observability::DecimalAmount::as_str), + Some("0.125") + ); + assert_eq!( + insights.cost.points[0] + .estimated_cost + .as_ref() + .map(gateway_admin::model::observability::DecimalAmount::as_str), + Some("0.25") + ); + assert_eq!( + insights + .cost + .standard_cost + .as_ref() + .map(gateway_admin::model::observability::DecimalAmount::as_str), + Some("1") + ); + assert_eq!( + insights.cost.points[0] + .standard_cost + .as_ref() + .map(gateway_admin::model::observability::DecimalAmount::as_str), + Some("1") + ); + assert_eq!( + insights + .cost + .no_cache_cost + .as_ref() + .map(gateway_admin::model::observability::DecimalAmount::as_str), + Some("1.25") + ); + assert_eq!( + insights + .cost + .tier_premium + .as_ref() + .map(gateway_admin::model::observability::DecimalAmount::as_str), + Some("0.25") + ); + assert_eq!(diagnostics.items[0].request_share, 0.75); + assert_eq!(diagnostics.items[1].request_share, 0.25); +} + +#[tokio::test] +async fn diagnostics_should_preserve_request_order_when_a_small_sample_fails() { + let now = Utc::now(); + let range = observation_range(now); + let store = Arc::new(FixtureObservabilityStore::new(range)); + let success = diagnostic("popular", 100); + let mut failure = diagnostic("single_failure", 1); + failure.success_count = 0; + failure.failure_count = 1; + store.replace_diagnostics(DiagnosticsObservation { + analytics: Default::default(), + total_request_count: 101, + items: vec![success, failure], + }); + let services = observability_services_with_calculated_billing(store).await; + + let result = services + .observability() + .diagnostics(range, UsageFilter::default(), DiagnosticDimension::Model) + .await + .expect("diagnostics"); + + assert_eq!(result.items[0].key, "popular"); + assert_eq!(result.items[1].key, "single_failure"); + assert_eq!(result.items[0].error_count, 0); + assert_eq!(result.items[1].error_count, 1); + assert_eq!(result.items[1].error_rate, Some(1.0)); +} + +#[tokio::test] +async fn diagnostics_should_use_the_total_before_truncating_groups() { + let range = observation_range(Utc::now()); + let store = Arc::new(FixtureObservabilityStore::new(range)); + store.replace_diagnostics(DiagnosticsObservation { + analytics: Default::default(), + total_request_count: 200, + items: (0..100) + .map(|index| diagnostic(&format!("model-{index}"), 1)) + .collect(), + }); + let services = observability_services_with_calculated_billing(store).await; + + let result = services + .observability() + .diagnostics(range, UsageFilter::default(), DiagnosticDimension::Model) + .await + .expect("limited diagnostics"); + + assert!(result.items.iter().all(|item| item.request_share == 0.005)); +} + +#[tokio::test] +async fn diagnostics_should_count_each_retried_request_once() { + let range = observation_range(Utc::now()); + let store = Arc::new(FixtureObservabilityStore::new(range)); + let mut item = diagnostic("model", 8); + item.attempt_count = 14; + item.retry_count = 6; + item.retried_request_count = 2; + store.replace_diagnostics(DiagnosticsObservation { + analytics: Default::default(), + total_request_count: 8, + items: vec![item], + }); + let services = observability_services_with_calculated_billing(store).await; + + let result = services + .observability() + .diagnostics(range, UsageFilter::default(), DiagnosticDimension::Model) + .await + .expect("retry diagnostics"); + + assert_eq!( + (result.items[0].retry_count, result.items[0].retry_rate), + (6, 0.25) + ); +} + +#[tokio::test] +async fn diagnostics_should_preserve_empty_results() { + let range = observation_range(Utc::now()); + let store = Arc::new(FixtureObservabilityStore::new(range)); + let services = observability_services_with_calculated_billing(store).await; + + let result = services + .observability() + .diagnostics(range, UsageFilter::default(), DiagnosticDimension::Account) + .await + .expect("empty diagnostics"); + + assert!(result.items.is_empty()); +} + +#[tokio::test] +async fn usage_records_should_tolerate_records_that_fail_billing_enrichment() { + let now = Utc::now(); + let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); + let invalid_kind = "x".repeat(65); + store.replace_usage_records(vec![ + total_record( + "request_invalid_kind", + Some(&invalid_kind), + "calculated", + now, + ), + total_record( + "request_unregistered_kind", + Some("anthropic"), + "calculated", + now, + ), + total_record("request_enriched", Some("openai"), "calculated", now), + ]); + let services = observability_services_with_calculated_billing(store).await; + + let page = services + .observability() + .usage_records(usage_query(now)) + .await + .expect("one bad record must not fail the whole usage list"); + + assert_eq!(page.items.len(), 3); + assert!( + matches!(page.items[0].billing, Some(UsageBilling::Total { .. })), + "invalid Provider kind keeps the stored total" + ); + assert!( + matches!(page.items[1].billing, Some(UsageBilling::Total { .. })), + "unregistered Provider kind keeps the stored total" + ); + assert!( + matches!(page.items[2].billing, Some(UsageBilling::Calculated(_))), + "healthy record is still enriched" + ); +} + +#[tokio::test] +async fn usage_records_should_enrich_provider_reported_totals_when_pricing_matches() { + let now = Utc::now(); + let store = Arc::new(FixtureObservabilityStore::new(observation_range(now))); + store.replace_usage_records(vec![total_record( + "request_provider_reported", + Some("openai"), + "provider_reported", + now, + )]); + let services = observability_services_with_calculated_billing(store).await; + + let page = services + .observability() + .usage_records(usage_query(now)) + .await + .expect("usage records"); + + assert!(matches!( + page.items[0].billing, + Some(UsageBilling::Calculated(_)) + )); +} + +#[tokio::test] +async fn usage_insights_should_reject_partial_costs_when_insights_fail() { + let now = Utc::now(); + let range = observation_range(now); + let store = Arc::new(FixtureObservabilityStore::new(range)); + store.replace_projected_costs(vec![UsageProjectedCostPoint { + bucket_start: quarter_hour_start(now), + standard_amount: Some("1".parse().expect("standard cost")), + no_cache_amount: Some("1.25".parse().expect("no-cache cost")), + }]); + store.insights_fail.store(true, Ordering::SeqCst); + let services = observability_services_with_calculated_billing(store).await; + assert!( + services + .observability() + .usage_insights(range, UsageFilter::default()) + .await + .is_err() + ); +} + +#[tokio::test] +async fn admin_selects_dashboard_defaults_and_matching_usage_buckets_at_range_boundaries() { + let now = Utc::now(); + for (duration, expected) in [ + (Duration::days(2), Granularity::FifteenMinutes), + (Duration::days(2) + Duration::seconds(1), Granularity::Hour), + (Duration::days(31), Granularity::Hour), + (Duration::days(31) + Duration::seconds(1), Granularity::Day), + ] { + let range = TimeRange::new(now - duration, now).unwrap(); + let store = Arc::new(FixtureObservabilityStore::new(range)); + let services = observability_services(store.clone()).await; + services + .observability() + .dashboard_summary(range, TrendKind::Usage) + .await + .unwrap(); + let query = store.summary_query.lock().unwrap().clone().unwrap(); + assert_eq!(query.range, range); + assert_eq!(query.granularity, expected); + assert_eq!(query.account_limit, 4); + assert_eq!(query.recent_request_limit, 10); + assert_eq!( + query.recent_request_filter.outcome, + Some(gateway_admin::model::observability::RequestOutcome::Succeeded) + ); + services + .observability() + .usage_insights(range, UsageFilter::default()) + .await + .unwrap(); + assert_eq!(*store.usage_granularities.lock().unwrap(), vec![expected]); + } +} diff --git a/backend/crates/gateway-admin/tests/use_case/observability/store_cache.rs b/backend/crates/gateway-admin/tests/use_case/observability/store_cache.rs new file mode 100644 index 000000000..b94e6f7f5 --- /dev/null +++ b/backend/crates/gateway-admin/tests/use_case/observability/store_cache.rs @@ -0,0 +1,363 @@ +//! 观测缓存的合并、隔离与失效测试 + +use super::*; + +#[tokio::test] +async fn dashboard_summary_should_keep_distinct_exact_ranges_in_one_short_window() { + let end_bucket = Utc::now().timestamp().div_euclid(2) * 2; + let first_end = DateTime::from_timestamp(end_bucket, 100_000_000).expect("first end"); + let second_end = DateTime::from_timestamp(end_bucket, 900_000_000).expect("second end"); + let first_range = TimeRange::new( + gateway_core::time::DeploymentTimeZone::default() + .day_start(first_end) + .unwrap(), + first_end, + ) + .expect("first range"); + let second_range = TimeRange::new( + gateway_core::time::DeploymentTimeZone::default() + .day_start(second_end) + .unwrap(), + second_end, + ) + .expect("second range"); + let store = Arc::new(FixtureObservabilityStore::new(first_range)); + store.set_dashboard_delay(StdDuration::from_millis(20)); + let services = observability_services(store.clone()).await; + let observability = services.observability(); + + let (first, second) = tokio::join!( + observability.dashboard_summary(first_range, TrendKind::Usage), + observability.dashboard_summary(second_range, TrendKind::Errors), + ); + + first.expect("first dashboard summary"); + second.expect("second dashboard summary"); + assert_eq!(store.dashboard_summary_calls(), 2); +} + +#[tokio::test] +async fn dashboard_summary_should_reload_after_the_short_window_changes() { + let end_bucket = Utc::now().timestamp().div_euclid(2) * 2; + let first_end = DateTime::from_timestamp(end_bucket, 100_000_000).expect("first end"); + let second_end = first_end + Duration::seconds(2); + let first_range = TimeRange::new( + gateway_core::time::DeploymentTimeZone::default() + .day_start(first_end) + .unwrap(), + first_end, + ) + .expect("first range"); + let second_range = TimeRange::new( + gateway_core::time::DeploymentTimeZone::default() + .day_start(second_end) + .unwrap(), + second_end, + ) + .expect("second range"); + let store = Arc::new(FixtureObservabilityStore::new(first_range)); + let services = observability_services(store.clone()).await; + let observability = services.observability(); + + observability + .dashboard_summary(first_range, TrendKind::Usage) + .await + .expect("first dashboard summary"); + observability + .dashboard_summary(second_range, TrendKind::Usage) + .await + .expect("second dashboard summary"); + + assert_eq!(store.dashboard_summary_calls(), 2); +} + +#[tokio::test] +async fn dashboard_and_usage_insights_keep_concurrency_cache_entries_separate() { + for dashboard_first in [true, false] { + let now = Utc::now(); + let range = observation_range(now); + let store = Arc::new(FixtureObservabilityStore::new(range)); + store + .concurrency + .lock() + .unwrap() + .push(UsageConcurrencyPoint { + bucket_start: range.start, + average_concurrency: 2.0, + peak_concurrency: 3, + }); + let services = observability_services(store.clone()).await; + for dashboard in [ + dashboard_first, + !dashboard_first, + dashboard_first, + !dashboard_first, + ] { + if dashboard { + services + .observability() + .dashboard_trend(range, TrendKind::Usage) + .await + .unwrap(); + } else { + let result = services + .observability() + .usage_insights(range, UsageFilter::default()) + .await + .unwrap(); + assert_eq!(result.performance.load.peak_concurrency, 3); + } + } + assert_eq!( + *store.concurrency_selections.lock().unwrap(), + vec![!dashboard_first, dashboard_first] + ); + } +} + +#[tokio::test] +async fn usage_summary_cache_should_coalesce_identical_queries_and_invalidate_deleted_generation() { + let range = observation_range(Utc::now()); + let store = Arc::new(FixtureObservabilityStore::new(range)); + store.set_dashboard_delay(StdDuration::from_millis(20)); + let services = observability_services(store.clone()).await; + let service = services.observability(); + let filter = UsageFilter { + client_api_key_ref: Some("deleted-key".to_owned()), + ..Default::default() + }; + let (first, second) = tokio::join!( + service.usage_summary(range, filter.clone()), + service.usage_summary(range, filter.clone()), + ); + first.expect("first summary"); + second.expect("coalesced summary"); + assert_eq!(store.usage_summary_filters.lock().unwrap().len(), 1); + { + let mut overview = store.overview.lock().unwrap(); + overview.analytics.generation = 1; + overview.requests.request_count = 7; + } + let refreshed = service + .usage_summary(range, filter) + .await + .expect("generation refresh"); + assert_eq!(refreshed.observation.analytics.generation, 1); + assert_eq!(refreshed.observation.requests.request_count, 7); + assert_eq!(store.usage_summary_filters.lock().unwrap().len(), 2); +} + +#[tokio::test(start_paused = true)] +async fn usage_summary_cache_should_coalesce_when_generation_advances_during_the_first_load() { + let range = observation_range(Utc::now()); + let store = Arc::new(FixtureObservabilityStore::new(range)); + store.set_dashboard_delay(StdDuration::from_millis(20)); + let services = observability_services(store.clone()).await; + let service = services.observability(); + let (first, second, ()) = tokio::join!( + service.usage_summary(range, UsageFilter::default()), + service.usage_summary(range, UsageFilter::default()), + async { + tokio::time::sleep(StdDuration::from_millis(5)).await; + store.overview.lock().unwrap().analytics.generation = 1; + }, + ); + assert_eq!( + first + .expect("first summary") + .observation + .analytics + .generation, + 1 + ); + assert_eq!( + second + .expect("coalesced summary") + .observation + .analytics + .generation, + 1 + ); + assert_eq!(store.usage_summary_filters.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn usage_summary_cache_should_isolate_key_identity_and_filters() { + let range = observation_range(Utc::now()); + let store = Arc::new(FixtureObservabilityStore::new(range)); + let services = observability_services(store.clone()).await; + let service = services.observability(); + for (key, model) in [ + ("key-a", None), + ("key-a", None), + ("key-b", None), + ("key-a", Some("model-a")), + ] { + service + .usage_summary( + range, + UsageFilter { + client_api_key_ref: Some(key.to_owned()), + model: model.map(str::to_owned), + ..Default::default() + }, + ) + .await + .expect("isolated summary"); + } + let calls = store.usage_summary_filters.lock().unwrap(); + assert_eq!(calls.len(), 3); + assert_eq!(calls[0].client_api_key_ref.as_deref(), Some("key-a")); + assert_eq!(calls[1].client_api_key_ref.as_deref(), Some("key-b")); + assert_eq!(calls[2].model.as_deref(), Some("model-a")); +} + +#[tokio::test(start_paused = true)] +async fn usage_summary_cache_should_bound_waiting_after_failed_refresh_and_allow_recovery() { + let range = observation_range(Utc::now()); + let store = Arc::new(FixtureObservabilityStore::new(range)); + store.set_dashboard_delay(store.query_timeout().mul_f64(0.7)); + store.summary_fail.store(true, Ordering::SeqCst); + let services = observability_services(store.clone()).await; + let service = services.observability(); + let started = tokio::time::Instant::now(); + let (first, second, third, fourth) = tokio::join!( + service.usage_summary(range, UsageFilter::default()), + service.usage_summary(range, UsageFilter::default()), + service.usage_summary(range, UsageFilter::default()), + service.usage_summary(range, UsageFilter::default()), + ); + assert!(first.is_err() && second.is_err() && third.is_err() && fourth.is_err()); + assert!( + started.elapsed() <= store.query_timeout(), + "同键失败不能使后续请求逐个等待完整数据库超时: {:?}", + started.elapsed() + ); + + store.summary_fail.store(false, Ordering::SeqCst); + store.set_dashboard_delay(StdDuration::ZERO); + service + .usage_summary(range, UsageFilter::default()) + .await + .expect("cancelled cache refresh releases its slot for recovery"); +} + +#[tokio::test(start_paused = true)] +async fn insights_cache_should_bound_stale_lifetime_without_renewing_failed_refreshes() { + let range = observation_range(Utc::now()); + let store = Arc::new(FixtureObservabilityStore::new(range)); + { + let mut overview = store.overview.lock().unwrap(); + overview.analytics.state = AnalyticsState::Ready; + overview.analytics.generated_at = Utc::now(); + overview.analytics.lag_seconds = 7; + overview.requests.request_count = 19; + } + let services = observability_services(store.clone()).await; + let service = services.observability(); + service + .usage_insights(range, UsageFilter::default()) + .await + .unwrap(); + store.insights_fail.store(true, Ordering::SeqCst); + tokio::time::advance(StdDuration::from_secs(16)).await; + let stale = service + .usage_insights(range, UsageFilter::default()) + .await + .unwrap(); + assert_eq!(stale.analytics.state, AnalyticsState::Stale); + assert!(stale.analytics.lag_seconds >= 7); + assert_eq!(stale.health.total_requests, 19); + tokio::time::advance(StdDuration::from_secs(45)).await; + assert!( + service + .usage_insights(range, UsageFilter::default()) + .await + .is_err() + ); +} + +#[tokio::test(start_paused = true)] +async fn insights_cache_should_reject_deleted_building_and_old_generation_times() { + for reason in ["deleted", "building", "generated-too-long-ago"] { + let range = observation_range(Utc::now()); + let store = Arc::new(FixtureObservabilityStore::new(range)); + { + let mut overview = store.overview.lock().unwrap(); + overview.analytics.state = if reason == "building" { + AnalyticsState::Building + } else { + AnalyticsState::Ready + }; + overview.analytics.generated_at = Utc::now() + - Duration::seconds(if reason == "generated-too-long-ago" { + 61 + } else { + 0 + }); + } + let services = observability_services(store.clone()).await; + let service = services.observability(); + service + .usage_insights(range, UsageFilter::default()) + .await + .unwrap(); + store.insights_fail.store(true, Ordering::SeqCst); + if reason == "deleted" { + store.overview.lock().unwrap().analytics.generation += 1; + } + tokio::time::advance(StdDuration::from_secs(16)).await; + assert!( + service + .usage_insights(range, UsageFilter::default()) + .await + .is_err(), + "{reason}" + ); + } +} + +#[tokio::test] +async fn usage_metric_cache_isolates_selections_and_filters() { + use gateway_admin::model::observability::UsageInsightMetric as Metric; + let range = observation_range(Utc::now()); + let store = Arc::new(FixtureObservabilityStore::new(range)); + let services = observability_services(store.clone()).await; + let metrics = [ + Metric::Health, + Metric::Latency, + Metric::FirstToken, + Metric::Throughput, + Metric::Load, + Metric::Cost, + Metric::Savings, + Metric::Cache, + ]; + for _ in 0..2 { + for metric in metrics { + services + .observability() + .usage_metric(range, UsageFilter::default(), metric) + .await + .unwrap(); + } + } + assert_eq!(*store.metric_selections.lock().unwrap(), metrics); + assert_eq!( + *store.concurrency_selections.lock().unwrap(), + vec![false, false, false, false, true, false, false, false] + ); + services + .observability() + .usage_metric( + range, + UsageFilter { + provider_kind: Some("openai".into()), + ..Default::default() + }, + Metric::Latency, + ) + .await + .unwrap(); + assert_eq!(store.metric_selections.lock().unwrap().len(), 9); +} diff --git a/backend/crates/gateway-admin/tests/use_case/settings.rs b/backend/crates/gateway-admin/tests/use_case/settings.rs index 10058c23f..536bd645e 100644 --- a/backend/crates/gateway-admin/tests/use_case/settings.rs +++ b/backend/crates/gateway-admin/tests/use_case/settings.rs @@ -23,6 +23,7 @@ struct UnusedSettingsStore; #[derive(Default)] struct PricingSettingsStore { + synced: Mutex>, updated: Mutex>, } @@ -101,19 +102,39 @@ async fn client_profile_preview_rejects_unknown_provider_before_loading_settings } #[tokio::test] -async fn pricing_accepts_ultrafast_for_openai_but_rejects_it_for_xai() { - for provider in ["openai", "xai"] { +async fn pricing_validates_the_bands_declared_by_the_registered_provider() { + for (provider, supported) in [ + ("text-provider", &["standard", "fast"][..]), + ("image-provider", &["standard", "image"][..]), + ] { let store = Arc::new(PricingSettingsStore::default()); let services = super::AdminHarness::new() .settings(store.clone()) - .provider(super::test_provider(provider)) + .provider(Arc::new(super::UnavailableProvider { + pricing_bands: supported, + ..super::UnavailableProvider::new(provider) + })) .build() .await; + assert_eq!( + services.settings().pricing().await.unwrap().supported_bands[provider], + supported + ); let context = MutationContext { actor: gateway_admin::model::MutationActor::System, - request_id: "request-ultrafast-pricing".to_owned(), + request_id: "request-band-pricing".to_owned(), }; - for band in ["ultrafast", "long_ultrafast"] { + for band in [ + "standard", + "fast", + "ultrafast", + "flex", + "long_standard", + "long_fast", + "long_ultrafast", + "long_flex", + "image", + ] { let pricing = serde_json::from_value(serde_json::json!({ "multiplierBps": 10000, "bands": { @@ -121,7 +142,7 @@ async fn pricing_accepts_ultrafast_for_openai_but_rejects_it_for_xai() { (band): {"input":"12", "output":"60", "cacheRead":"0.6", "cacheWrite":"15"} } })) - .expect("Ultrafast override"); + .expect("valid token price override"); let update = UpdatePricing { provider: provider.to_owned(), models: vec!["example-model".to_owned()], @@ -131,12 +152,14 @@ async fn pricing_accepts_ultrafast_for_openai_but_rejects_it_for_xai() { .settings() .update_pricing(&context, update.clone()) .await; - if provider == "openai" { - result.expect("OpenAI accepts Ultrafast overrides"); - assert_eq!(store.updated.lock().unwrap().as_ref(), Some(&update)); + if supported.contains(&band) { + result.expect("provider accepts its supported band"); + assert_eq!(store.updated.lock().unwrap().take(), Some(update)); } else { assert_eq!( - result.expect_err("xAI rejects Ultrafast").kind(), + result + .expect_err("provider rejects unsupported band") + .kind(), AdminErrorKind::Invalid ); assert!(store.updated.lock().unwrap().is_none()); @@ -259,10 +282,11 @@ impl SettingsStore for PricingSettingsStore { async fn sync_pricing( &self, - _: gateway_admin::model::pricing::PricingSyncChanges, + command: gateway_admin::model::pricing::PricingSyncChanges, _: &MutationContext, ) -> AdminStoreResult { - panic!("unexpected pricing sync") + *self.synced.lock().unwrap() = Some(command); + Ok(Revision::new(2).unwrap()) } async fn update_pricing( @@ -340,9 +364,9 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() { switch_account_on_queue_failure: false, max_retry_after_seconds: 240, openai_guardian_reserved_concurrency: 0, - openai_account_affinity: gateway_core::account::AccountAffinity::Relaxed, + account_affinity: gateway_core::account::AccountAffinity::Relaxed, max_account_rotations: 3, - openai_session_affinity_ttl_hours: 24, + session_affinity_ttl_hours: 24, responses_max_decompressed_body_bytes: 64 * 1024 * 1024, smart_scheduling: gateway_core::account::SmartSchedulingConfig::default(), quota_reset_window_weights: gateway_core::account::ResetWindowWeights::default( @@ -376,3 +400,89 @@ fn unused() -> AdminStoreError { "unused in this test", ) } + +struct ReferencePrices(Mutex); +#[async_trait] +impl gateway_admin::ports::pricing::PricingSource for ReferencePrices { + async fn fetch( + &self, + _: &gateway_admin::ports::pricing::PricingSourceScope, + ) -> Result { + Ok(self.0.lock().unwrap().clone()) + } +} + +#[tokio::test] +async fn external_reference_prices_project_to_exact_provider_ids_in_preview_and_sync() { + let price: gateway_core::metering::ModelPriceOverride = serde_json::from_value(serde_json::json!({"multiplierBps":10000,"bands":{"standard":{"input":"1","output":"2","cacheRead":"0.1","cacheWrite":"1"}}})).unwrap(); + let source = Arc::new(ReferencePrices(Mutex::new(PricingSyncPreview { + prices: BTreeMap::from([( + "google".into(), + BTreeMap::from([ + ("base-model".into(), price.clone()), + ("unmapped".into(), price), + ]), + )]), + skipped: vec!["google/missing".into(), "google/unrelated-image".into()], + }))); + let mut provider = super::UnavailableProvider::new("antigravity"); + provider.pricing_references = BTreeMap::from([ + ("ag-high".into(), ("google".into(), "base-model".into())), + ("ag-low".into(), ("google".into(), "base-model".into())), + ("ag-image".into(), ("google".into(), "missing".into())), + ]); + let store = Arc::new(PricingSettingsStore::default()); + let service = gateway_admin::initialize_settings( + store.clone(), + Arc::new(super::NoopSnapshot), + gateway_admin::ports::provider::ProviderAdminRegistry::new(vec![ + Arc::new(provider) as Arc + ]) + .unwrap(), + source.clone(), + ); + let preview = service.preview_pricing_sync().await.unwrap(); + assert_eq!( + preview.prices.keys().cloned().collect::>(), + ["antigravity"] + ); + assert_eq!( + preview.prices["antigravity"] + .keys() + .cloned() + .collect::>(), + ["ag-high", "ag-low"] + ); + assert_eq!(preview.skipped, ["antigravity/ag-image"]); + // 未登记外部型号的变化不会污染同步确认,但实际保存仍重新读取并校验投影价目 + source + .0 + .lock() + .unwrap() + .prices + .get_mut("google") + .unwrap() + .remove("unmapped"); + service + .sync_pricing( + &MutationContext { + actor: gateway_admin::model::MutationActor::System, + request_id: "reference-sync".into(), + }, + SyncPricing { + preview, + models: BTreeMap::from([( + "antigravity".into(), + BTreeSet::from(["ag-high".into()]), + )]), + }, + ) + .await + .unwrap(); + let saved = store.synced.lock().unwrap(); + let saved = saved.as_ref().unwrap(); + assert_eq!( + saved["antigravity"].keys().cloned().collect::>(), + ["ag-high"] + ); +} diff --git a/backend/crates/gateway-admin/tests/use_case/system/mod.rs b/backend/crates/gateway-admin/tests/use_case/system/mod.rs new file mode 100644 index 000000000..6f677e2cc --- /dev/null +++ b/backend/crates/gateway-admin/tests/use_case/system/mod.rs @@ -0,0 +1,4 @@ +//! 系统管理用例测试 + +mod preflight; +mod service; diff --git a/backend/crates/gateway-admin/tests/use_case/system_preflight.rs b/backend/crates/gateway-admin/tests/use_case/system/preflight.rs similarity index 97% rename from backend/crates/gateway-admin/tests/use_case/system_preflight.rs rename to backend/crates/gateway-admin/tests/use_case/system/preflight.rs index fdff13e02..f782614c5 100644 --- a/backend/crates/gateway-admin/tests/use_case/system_preflight.rs +++ b/backend/crates/gateway-admin/tests/use_case/system/preflight.rs @@ -327,7 +327,7 @@ impl SystemOperations for PreflightingSystem { #[tokio::test] async fn system_update_accepts_compatible_enabled_plugins_at_the_same_revision() { let fixture = Fixture::new(requirements("^1.0", "executor"), &[7]); - let services = super::AdminHarness::new() + let services = crate::use_case::AdminHarness::new() .plugins(fixture.clone(), fixture) .system(Arc::new(PreflightingSystem { candidate: candidate("executor"), @@ -345,7 +345,7 @@ async fn system_update_accepts_compatible_enabled_plugins_at_the_same_revision() #[tokio::test] async fn rollback_preserves_plugins_when_target_capability_is_missing() { let incompatible = Fixture::new(requirements("^1.0", "executor"), &[7]); - let services = super::AdminHarness::new() + let services = crate::use_case::AdminHarness::new() .plugins(incompatible.clone(), incompatible.clone()) .system(Arc::new(PreflightingSystem { candidate: candidate("models"), @@ -363,7 +363,7 @@ async fn rollback_preserves_plugins_when_target_capability_is_missing() { #[tokio::test] async fn system_update_rejects_revision_changes() { let stale = Fixture::new(requirements("^1.0", "executor"), &[7, 8]); - let services = super::AdminHarness::new() + let services = crate::use_case::AdminHarness::new() .plugins(stale.clone(), stale) .system(Arc::new(PreflightingSystem { candidate: candidate("executor"), @@ -392,7 +392,7 @@ async fn system_update_accepts_new_plugin_contracts_for_empty_disabled_and_enabl manifest["plugin_host"] = serde_json::json!({"schema_version": 99, "future_contract": true}); candidate.release_manifest = serde_json::to_vec(&manifest).unwrap().into(); - let services = super::AdminHarness::new() + let services = crate::use_case::AdminHarness::new() .plugins(fixture.clone(), fixture) .system(Arc::new(PreflightingSystem { candidate })) .build() @@ -420,7 +420,7 @@ async fn system_update_keeps_release_identity_validation_without_plugins() { serde_json::from_slice(&candidate.release_manifest).unwrap(); manifest[field] = value; candidate.release_manifest = serde_json::to_vec(&manifest).unwrap().into(); - let services = super::AdminHarness::new() + let services = crate::use_case::AdminHarness::new() .plugins(fixture.clone(), fixture) .system(Arc::new(PreflightingSystem { candidate })) .build() @@ -440,7 +440,7 @@ async fn system_update_keeps_release_identity_validation_without_plugins() { async fn system_update_still_rechecks_revision_without_plugins() { let mut fixture = Fixture::new(requirements("^1.0", "executor"), &[7, 8]); Arc::get_mut(&mut fixture).unwrap().instances.clear(); - let services = super::AdminHarness::new() + let services = crate::use_case::AdminHarness::new() .plugins(fixture.clone(), fixture) .system(Arc::new(PreflightingSystem { candidate: candidate("executor"), @@ -510,7 +510,7 @@ fn context() -> MutationContext { #[tokio::test] async fn incompatible_restart_requires_exact_confirmation_and_preserves_enabled_plugins() { let fixture = Fixture::new(requirements("^1.0", "executor"), &[7]); - let services = super::AdminHarness::new() + let services = crate::use_case::AdminHarness::new() .plugins(fixture.clone(), fixture.clone()) .system(Arc::new(PreflightingSystem { candidate: candidate("models"), @@ -563,7 +563,7 @@ async fn incompatible_restart_requires_exact_confirmation_and_preserves_enabled_ #[tokio::test] async fn compatible_restart_does_not_change_plugin_configuration() { let fixture = Fixture::new(requirements("^1.0", "executor"), &[7]); - let services = super::AdminHarness::new() + let services = crate::use_case::AdminHarness::new() .plugins(fixture.clone(), fixture.clone()) .system(Arc::new(PreflightingSystem { candidate: candidate("executor"), @@ -587,7 +587,7 @@ async fn compatible_restart_does_not_change_plugin_configuration() { #[tokio::test] async fn changed_configuration_after_restart_check_requires_a_new_confirmation() { let fixture = Fixture::new(requirements("^1.0", "executor"), &[7, 8]); - let services = super::AdminHarness::new() + let services = crate::use_case::AdminHarness::new() .plugins(fixture.clone(), fixture.clone()) .system(Arc::new(PreflightingSystem { candidate: candidate("models"), diff --git a/backend/crates/gateway-admin/tests/use_case/system.rs b/backend/crates/gateway-admin/tests/use_case/system/service.rs similarity index 96% rename from backend/crates/gateway-admin/tests/use_case/system.rs rename to backend/crates/gateway-admin/tests/use_case/system/service.rs index 86ecb4381..fcd4090c9 100644 --- a/backend/crates/gateway-admin/tests/use_case/system.rs +++ b/backend/crates/gateway-admin/tests/use_case/system/service.rs @@ -137,7 +137,10 @@ async fn system_failure_should_preserve_safe_message_source_and_redaction_marker ), ..RecordingSystemOperations::default() }); - let services = super::AdminHarness::new().system(operations).build().await; + let services = super::super::AdminHarness::new() + .system(operations) + .build() + .await; let error = services.system().version().await.expect_err("host failure"); assert_eq!( error.kind(), @@ -154,7 +157,7 @@ async fn system_failure_should_preserve_safe_message_source_and_redaction_marker #[tokio::test] async fn system_update_should_normalize_blank_target_to_latest() { let operations = std::sync::Arc::new(RecordingSystemOperations::default()); - let services = super::AdminHarness::new() + let services = super::super::AdminHarness::new() .system(operations.clone()) .build() .await; @@ -170,7 +173,7 @@ async fn system_update_should_normalize_blank_target_to_latest() { #[tokio::test] async fn system_update_should_forward_the_confirmed_channel() { let operations = std::sync::Arc::new(RecordingSystemOperations::default()); - let services = super::AdminHarness::new() + let services = super::super::AdminHarness::new() .system(operations.clone()) .build() .await; diff --git a/backend/crates/gateway-admin/tests/use_case/usage_data/contract.rs b/backend/crates/gateway-admin/tests/use_case/usage_data/contract.rs new file mode 100644 index 000000000..fe37e387e --- /dev/null +++ b/backend/crates/gateway-admin/tests/use_case/usage_data/contract.rs @@ -0,0 +1,108 @@ +//! 跨模块行为合同测试 + +use super::*; + +#[test] +fn counters_preserve_integer_precision_and_reject_json_numbers() { + assert_eq!( + serde_json::from_value::(json!(u64::MAX.to_string())) + .unwrap() + .get(), + u64::MAX + ); + assert_eq!( + serde_json::from_value::(json!(i64::MIN.to_string())) + .unwrap() + .get(), + i64::MIN + ); + for value in [json!(1), json!("1.5"), json!("+1")] { + assert!(serde_json::from_value::(value.clone()).is_err()); + assert!(serde_json::from_value::(value).is_err()); + } +} + +#[tokio::test] +async fn usage_mutations_require_a_trusted_actor() { + let admin = super::super::AdminHarness::new().build().await; + let registry = admin.public_services(); + let denied = registry + .call("usage.records.write", json!({"changes":[]})) + .await + .unwrap_err(); + assert!(denied.message.contains("trusted caller")); + assert!( + registry + .call( + "usage.records.write", + json!({"changes":[],"actor":{"kind":"system"}}) + ) + .await + .is_err() + ); +} + +#[test] +fn sdk_wire_types_match_host_contracts() { + use quote::ToTokens as _; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); + let items = |path: std::path::PathBuf| { + syn::parse_file(&std::fs::read_to_string(path).unwrap()) + .unwrap() + .items + .into_iter() + .filter(|item| { + matches!( + item, + syn::Item::Struct(_) + | syn::Item::Enum(_) + | syn::Item::Impl(_) + | syn::Item::Type(_) + ) + }) + .map(|item| item.into_token_stream().to_string()) + .collect::>() + }; + for name in [ + "value.rs", + "record.rs", + "query.rs", + "read.rs", + "aggregate.rs", + "pricing.rs", + "error.rs", + ] { + assert_eq!( + items(root.join("src/model/usage_data").join(name)), + items( + root.join("../gateway-plugin/sdk/src/call/services/usage") + .join(name) + ), + "{name}" + ); + } +} + +#[tokio::test] +async fn batch_and_wire_limits_fail_before_reaching_storage() { + let admin = super::super::AdminHarness::new().build().await; + let registry = admin.public_services(); + let changes = (0..501) + .map(|i| json!({"kind":"delete","id":format!("item_{i}")})) + .collect::>(); + let too_many = gateway_admin::public_service::scope_actor( + UsageActor::System, + registry.call("usage.records.write", json!({"changes":changes})), + ) + .await + .unwrap_err(); + assert_eq!(too_many.kind, "capacity_exceeded"); + let oversized = registry + .call( + "usage.records.get", + json!({"id":"x".repeat(USAGE_DATA_MAX_REQUEST_BYTES)}), + ) + .await + .unwrap_err(); + assert_eq!(oversized.kind, "capacity_exceeded"); +} diff --git a/backend/crates/gateway-admin/tests/use_case/usage_data/mod.rs b/backend/crates/gateway-admin/tests/use_case/usage_data/mod.rs index f5c9fe6f0..44d365b4d 100644 --- a/backend/crates/gateway-admin/tests/use_case/usage_data/mod.rs +++ b/backend/crates/gateway-admin/tests/use_case/usage_data/mod.rs @@ -1,105 +1,5 @@ //! 用量服务的 wire 精度、可信主体和独立 SDK 合同校验 use gateway_admin::model::usage_data::*; use serde_json::json; -#[test] -fn counters_preserve_integer_precision_and_reject_json_numbers() { - assert_eq!( - serde_json::from_value::(json!(u64::MAX.to_string())) - .unwrap() - .get(), - u64::MAX - ); - assert_eq!( - serde_json::from_value::(json!(i64::MIN.to_string())) - .unwrap() - .get(), - i64::MIN - ); - for value in [json!(1), json!("1.5"), json!("+1")] { - assert!(serde_json::from_value::(value.clone()).is_err()); - assert!(serde_json::from_value::(value).is_err()); - } -} -#[tokio::test] -async fn usage_mutations_require_a_trusted_actor() { - let admin = super::AdminHarness::new().build().await; - let registry = admin.public_services(); - let denied = registry - .call("usage.records.write", json!({"changes":[]})) - .await - .unwrap_err(); - assert!(denied.message.contains("trusted caller")); - assert!( - registry - .call( - "usage.records.write", - json!({"changes":[],"actor":{"kind":"system"}}) - ) - .await - .is_err() - ); -} -#[test] -fn sdk_wire_types_match_host_contracts() { - use quote::ToTokens as _; - let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); - let items = |path: std::path::PathBuf| { - syn::parse_file(&std::fs::read_to_string(path).unwrap()) - .unwrap() - .items - .into_iter() - .filter(|item| { - matches!( - item, - syn::Item::Struct(_) - | syn::Item::Enum(_) - | syn::Item::Impl(_) - | syn::Item::Type(_) - ) - }) - .map(|item| item.into_token_stream().to_string()) - .collect::>() - }; - for name in [ - "value.rs", - "record.rs", - "query.rs", - "read.rs", - "aggregate.rs", - "pricing.rs", - "error.rs", - ] { - assert_eq!( - items(root.join("src/model/usage_data").join(name)), - items( - root.join("../gateway-plugin/sdk/src/call/services/usage") - .join(name) - ), - "{name}" - ); - } -} -#[tokio::test] -async fn batch_and_wire_limits_fail_before_reaching_storage() { - let admin = super::AdminHarness::new().build().await; - let registry = admin.public_services(); - let changes = (0..501) - .map(|i| json!({"kind":"delete","id":format!("item_{i}")})) - .collect::>(); - let too_many = gateway_admin::public_service::scope_actor( - UsageActor::System, - registry.call("usage.records.write", json!({"changes":changes})), - ) - .await - .unwrap_err(); - assert_eq!(too_many.kind, "capacity_exceeded"); - let oversized = registry - .call( - "usage.records.get", - json!({"id":"x".repeat(USAGE_DATA_MAX_REQUEST_BYTES)}), - ) - .await - .unwrap_err(); - assert_eq!(oversized.kind, "capacity_exceeded"); -} +mod contract; diff --git a/backend/crates/gateway-api/src/admin/account_groups.rs b/backend/crates/gateway-api/src/admin/account_groups.rs index 22485a5fd..9ce3a3a68 100644 --- a/backend/crates/gateway-api/src/admin/account_groups.rs +++ b/backend/crates/gateway-api/src/admin/account_groups.rs @@ -1,6 +1,6 @@ //! 账号分组管理的 HTTP 数据合同与固定路由 -use crate::auth::SessionState; +use crate::SessionState; use std::collections::BTreeMap; diff --git a/backend/crates/gateway-api/src/admin/accounts/concurrency.rs b/backend/crates/gateway-api/src/admin/accounts/concurrency.rs index a9941ab3c..1ff181a2d 100644 --- a/backend/crates/gateway-api/src/admin/accounts/concurrency.rs +++ b/backend/crates/gateway-api/src/admin/accounts/concurrency.rs @@ -1,7 +1,7 @@ //! 账号普通池并发明细的有界实时查询 use super::*; -use crate::auth::SessionState; +use crate::SessionState; #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] diff --git a/backend/crates/gateway-api/src/admin/accounts/handlers.rs b/backend/crates/gateway-api/src/admin/accounts/handlers.rs index 556817b48..2c729edac 100644 --- a/backend/crates/gateway-api/src/admin/accounts/handlers.rs +++ b/backend/crates/gateway-api/src/admin/accounts/handlers.rs @@ -2,7 +2,7 @@ use gateway_core::engine::probe::AccountProbeTarget; -use crate::auth::SessionState; +use crate::SessionState; use super::*; diff --git a/backend/crates/gateway-api/src/admin/accounts/import_tasks.rs b/backend/crates/gateway-api/src/admin/accounts/import_tasks.rs index fd582a92c..b29b2ef57 100644 --- a/backend/crates/gateway-api/src/admin/accounts/import_tasks.rs +++ b/backend/crates/gateway-api/src/admin/accounts/import_tasks.rs @@ -7,7 +7,7 @@ use gateway_admin::model::import_tasks::{ use sha2::{Digest as _, Sha256}; use super::*; -use crate::auth::SessionState; +use crate::SessionState; pub(super) fn router() -> Router where diff --git a/backend/crates/gateway-api/src/admin/accounts/presenter.rs b/backend/crates/gateway-api/src/admin/accounts/presenter.rs index c149e46e1..80979ad34 100644 --- a/backend/crates/gateway-api/src/admin/accounts/presenter.rs +++ b/backend/crates/gateway-api/src/admin/accounts/presenter.rs @@ -73,6 +73,7 @@ pub(super) fn account_view( plan_type_display, projection, usage, + usage_period, quota, protection_rules, } = item; @@ -84,7 +85,6 @@ pub(super) fn account_view( .map(|value| time.rfc3339(value)); let added_at = time.rfc3339(&account.created_at); let updated_at = time.rfc3339(&account.updated_at); - let usage_period = quota.usage_window().map(|(_, period)| period); let mut usage = account_usage_view(usage, usage_period, now, time); if account.authentication_kind == "api_key" { usage.window_kind = if quota diff --git a/backend/crates/gateway-api/src/admin/accounts/wire.rs b/backend/crates/gateway-api/src/admin/accounts/wire.rs index 94317fe27..1a14dd6d8 100644 --- a/backend/crates/gateway-api/src/admin/accounts/wire.rs +++ b/backend/crates/gateway-api/src/admin/accounts/wire.rs @@ -301,6 +301,10 @@ pub struct AccountCapacityView { #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct AccountCapabilitiesView { + pub credential_refresh: bool, + pub reauthorize: bool, + pub credential_export: bool, + pub model_catalog_download: bool, pub quota_settings_supported: bool, pub quota_credits: bool, pub quota: bool, @@ -315,6 +319,10 @@ pub struct AccountCapabilitiesView { impl From for AccountCapabilitiesView { fn from(value: gateway_admin::model::accounts::ProviderAccountCapabilities) -> Self { Self { + credential_refresh: value.credential_refresh, + reauthorize: value.reauthorize, + credential_export: value.credential_export, + model_catalog_download: value.model_catalog_download, quota: value.quota, quota_refresh: value.quota_refresh, profile: value.profile, diff --git a/backend/crates/gateway-api/src/admin/auth.rs b/backend/crates/gateway-api/src/admin/auth.rs index fa853411b..30c6bf5df 100644 --- a/backend/crates/gateway-api/src/admin/auth.rs +++ b/backend/crates/gateway-api/src/admin/auth.rs @@ -7,7 +7,7 @@ use axum::{ use gateway_admin::model::auth::{AdminPrincipal, AdminRequestContext}; use tower_http::request_id::RequestId; -use crate::{auth::SessionState, session_cookie}; +use crate::{SessionState, session}; use super::{AdminError, wire::map_admin_service_error}; @@ -71,7 +71,7 @@ where match state .admin_services() .auth() - .resolve_admin_user_id(session_cookie::value(headers).as_deref()) + .resolve_admin_user_id(session::value(headers).as_deref()) .await { Ok(Some(admin_user_id)) => Ok(admin_user_id), diff --git a/backend/crates/gateway-api/src/admin/backups.rs b/backend/crates/gateway-api/src/admin/backups.rs index 2168ef4f3..b0ee680f9 100644 --- a/backend/crates/gateway-api/src/admin/backups.rs +++ b/backend/crates/gateway-api/src/admin/backups.rs @@ -3,7 +3,7 @@ //! //! 路径统一位于 `/api/admin/settings/backups/*`,内部由独立 `BackupService` 承担业务 -use crate::auth::SessionState; +use crate::SessionState; use axum::{ Router, @@ -17,7 +17,7 @@ use gateway_admin::model::backup::{ BackupRecord, BackupSettings, BackupStatus, BackupTriggerKind, ConnectionTestResult, UpdateBackupScheduleCommand, UpdateBackupStorageCommand, }; -use secrecy::{ExposeSecret as _, SecretString}; +use secrecy::SecretString; use serde::{Deserialize, Serialize}; use super::{ @@ -25,7 +25,7 @@ use super::{ PageMeta, wire::map_admin_service_error, }; -/// 备份设置视图;`secretAccessKey` 返回已保存的明文凭据,由前端掩码显示 +/// 读写响应只公开 Secret 的配置状态 #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct BackupSettingsView { @@ -34,7 +34,7 @@ pub struct BackupSettingsView { pub region: Option, pub bucket: Option, pub access_key_id: Option, - pub secret_access_key: Option, + pub secret_configured: bool, pub prefix: Option, pub force_path_style: bool, pub verified: bool, @@ -59,9 +59,7 @@ impl From<(BackupSettings, crate::time::TimePresenter)> for BackupSettingsView { region: settings.region, bucket: settings.bucket, access_key_id: settings.access_key_id, - secret_access_key: settings - .secret_access_key - .map(|secret| secret.expose_secret().to_owned()), + secret_configured: settings.secret_access_key.is_some(), prefix: settings.prefix, force_path_style: settings.force_path_style, verified, @@ -86,9 +84,10 @@ impl From<(BackupSettings, crate::time::TimePresenter)> for BackupSettingsView { } /// 更新 S3 存储配置请求;`secretAccessKey` 缺省表示保留旧值 -#[derive(Debug, Clone, Deserialize)] +#[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct UpdateBackupStorageRequest { + pub storage_revision: u64, pub endpoint: String, pub region: String, pub bucket: String, @@ -103,6 +102,7 @@ pub struct UpdateBackupStorageRequest { #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct UpdateBackupScheduleRequest { + pub storage_revision: u64, pub schedule_enabled: bool, pub cron_expression: String, pub retention_days: u32, @@ -206,19 +206,27 @@ impl From for DownloadUrlView { } } +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct TestBackupStorageRequest { + storage_revision: u64, +} + /// 连接测试响应 #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct ConnectionTestView { + pub storage_revision: u64, pub ok: bool, pub stage: String, pub code: Option, pub message: String, } -impl From for ConnectionTestView { - fn from(result: ConnectionTestResult) -> Self { +impl From<(u64, ConnectionTestResult)> for ConnectionTestView { + fn from((storage_revision, result): (u64, ConnectionTestResult)) -> Self { Self { + storage_revision, ok: result.ok, stage: result.stage.to_owned(), code: result.code.map(str::to_owned), @@ -294,6 +302,7 @@ where { let time = crate::time::TimePresenter::new(state.admin_services().timezone()); let command = UpdateBackupStorageCommand { + storage_revision: request.storage_revision, endpoint: request.endpoint, region: request.region, bucket: request.bucket, @@ -317,6 +326,7 @@ where async fn test_backup_storage( auth: AdminAuth, State(state): State, + AdminJson(request): AdminJson, ) -> Result where S: SessionState + Send + Sync, @@ -324,12 +334,12 @@ where let result = state .admin_services() .backups() - .test_connection(&auth.context().mutation_context()) + .test_connection(&auth.context().mutation_context(), request.storage_revision) .await .map_err(map_service_error)?; Ok(AdminResponse::new( StatusCode::OK, - AdminEnvelope::ok(ConnectionTestView::from(result)), + AdminEnvelope::ok(ConnectionTestView::from((request.storage_revision, result))), )) } @@ -343,6 +353,7 @@ where { let time = crate::time::TimePresenter::new(state.admin_services().timezone()); let command = UpdateBackupScheduleCommand { + storage_revision: request.storage_revision, schedule_enabled: request.schedule_enabled, cron_expression: request.cron_expression, retention_days: request.retention_days, diff --git a/backend/crates/gateway-api/src/admin/client_key_usage.rs b/backend/crates/gateway-api/src/admin/client_key_usage.rs index f94005292..7f29e5b21 100644 --- a/backend/crates/gateway-api/src/admin/client_key_usage.rs +++ b/backend/crates/gateway-api/src/admin/client_key_usage.rs @@ -17,7 +17,7 @@ use super::{ AdminAuth, AdminEnvelope, AdminError, AdminJson, AdminQuery, AdminResponse, client_keys::ClientBudgetView, wire::map_admin_service_error, }; -use crate::{auth::SessionState, time::TimePresenter}; +use crate::{SessionState, time::TimePresenter}; pub(super) fn router() -> Router { Router::new() diff --git a/backend/crates/gateway-api/src/admin/client_keys.rs b/backend/crates/gateway-api/src/admin/client_keys.rs index 63126bda0..2bf34a7ef 100644 --- a/backend/crates/gateway-api/src/admin/client_keys.rs +++ b/backend/crates/gateway-api/src/admin/client_keys.rs @@ -1,6 +1,6 @@ //! Client API Key 管理 wire contract -use crate::auth::SessionState; +use crate::SessionState; use std::{collections::BTreeMap, fmt}; @@ -748,9 +748,6 @@ fn normalize_request_profile_overrides( profiles .into_iter() .map(|(provider, profile)| { - if !matches!(provider.as_str(), "openai" | "xai") { - return Err(WireValidationError::new("providerRequestProfileOverrides")); - } validate_request_profile_size(&profile)?; Ok(( ProviderKind::new(provider) @@ -770,9 +767,6 @@ fn normalize_request_profile_override_updates( profiles .into_iter() .map(|(provider, profile)| { - if !matches!(provider.as_str(), "openai" | "xai") { - return Err(WireValidationError::new("providerRequestProfileOverrides")); - } if let Some(profile) = profile.as_ref() { validate_request_profile_size(profile)?; } diff --git a/backend/crates/gateway-api/src/admin/mod.rs b/backend/crates/gateway-api/src/admin/mod.rs index fd13637e0..7b3fb0791 100644 --- a/backend/crates/gateway-api/src/admin/mod.rs +++ b/backend/crates/gateway-api/src/admin/mod.rs @@ -1,6 +1,6 @@ //! 管理端 HTTP adapter、wire contract 与固定路由 -use crate::auth::SessionState; +use crate::SessionState; use axum::{ Router, diff --git a/backend/crates/gateway-api/src/admin/observability/export/mod.rs b/backend/crates/gateway-api/src/admin/observability/export/mod.rs index 396d8ea47..c7da642d5 100644 --- a/backend/crates/gateway-api/src/admin/observability/export/mod.rs +++ b/backend/crates/gateway-api/src/admin/observability/export/mod.rs @@ -11,7 +11,7 @@ use serde_json::{Value, json}; use super::{ AdminAuth, AdminError, AdminQuery, map_service_error, ops_error_view, usage_detail_view, }; -use crate::{auth::SessionState, time::TimePresenter}; +use crate::{SessionState, time::TimePresenter}; mod archive; mod privacy; diff --git a/backend/crates/gateway-api/src/admin/observability/routes.rs b/backend/crates/gateway-api/src/admin/observability/routes.rs index 930664b88..8b591933c 100644 --- a/backend/crates/gateway-api/src/admin/observability/routes.rs +++ b/backend/crates/gateway-api/src/admin/observability/routes.rs @@ -1,6 +1,6 @@ //! 固定 `/api/admin` 观测路由与 handler -use crate::auth::SessionState; +use crate::SessionState; use super::*; diff --git a/backend/crates/gateway-api/src/admin/plugins/artifacts.rs b/backend/crates/gateway-api/src/admin/plugins/artifacts.rs index 55ae5093b..0cb37d1ab 100644 --- a/backend/crates/gateway-api/src/admin/plugins/artifacts.rs +++ b/backend/crates/gateway-api/src/admin/plugins/artifacts.rs @@ -15,11 +15,11 @@ use gateway_admin::model::plugins::{ use serde::{Deserialize, Serialize}; use crate::{ + SessionState, admin::{ AdminAuth, AdminEnvelope, AdminError, AdminJson, AdminQuery, AdminResponse, wire::map_admin_service_error, }, - auth::SessionState, }; #[derive(Serialize)] diff --git a/backend/crates/gateway-api/src/admin/plugins/distribution.rs b/backend/crates/gateway-api/src/admin/plugins/distribution.rs index cd24a85a9..6455b0d29 100644 --- a/backend/crates/gateway-api/src/admin/plugins/distribution.rs +++ b/backend/crates/gateway-api/src/admin/plugins/distribution.rs @@ -15,11 +15,11 @@ use serde::Deserialize; use super::artifacts::{InstallResultView, VerifiedArtifactView}; use crate::{ + SessionState, admin::{ AdminAuth, AdminEnvelope, AdminError, AdminJson, AdminResponse, wire::map_admin_service_error, }, - auth::SessionState, }; pub(super) fn router() -> Router { diff --git a/backend/crates/gateway-api/src/admin/plugins/instances.rs b/backend/crates/gateway-api/src/admin/plugins/instances.rs index 161ae790a..5c6a40a2a 100644 --- a/backend/crates/gateway-api/src/admin/plugins/instances.rs +++ b/backend/crates/gateway-api/src/admin/plugins/instances.rs @@ -15,11 +15,11 @@ use gateway_admin::model::plugins::instances::{ use serde::{Deserialize, Serialize}; use crate::{ + SessionState, admin::{ AdminAuth, AdminEnvelope, AdminError, AdminJson, AdminResponse, wire::map_admin_service_error, }, - auth::SessionState, }; pub(super) fn router() -> Router { diff --git a/backend/crates/gateway-api/src/admin/plugins/management.rs b/backend/crates/gateway-api/src/admin/plugins/management.rs index c59fab581..572c4b986 100644 --- a/backend/crates/gateway-api/src/admin/plugins/management.rs +++ b/backend/crates/gateway-api/src/admin/plugins/management.rs @@ -1,7 +1,7 @@ //! 插件管理页面、资源、授权回调与页面模型请求的 HTTP 边界 -use crate::openai::generation::{ - GenerationHttpRequest, ResponseAuthorization, execute_prepared_generation, +use crate::data_plane::generation::{ + GenerationEndpoint, GenerationHttpRequest, ResponseAuthorization, execute_prepared_generation, }; use std::{net::SocketAddr, sync::Arc}; @@ -32,12 +32,12 @@ use sha2::{Digest as _, Sha256}; use crate::middleware::headers::{decode_headers, encode_headers}; use crate::{ + SessionState, admin::{ AdminAuth, AdminEnvelope, AdminError, AdminJson, AdminQuery, AdminResponse, wire::map_admin_service_error, }, - auth::SessionState, - openai::{ + data_plane::{ error::{gateway_error_response, protocol_error_response}, responses::decode_request_with_body, }, @@ -133,7 +133,7 @@ async fn model_responses( ))); } }; - let service = state.openai().clone(); + let service = state.data_plane().clone(); let execution = service.execution(); let prepared = match execution.prepare_plugin_execution(&client_key_id).await { Ok(prepared) => prepared, @@ -155,7 +155,7 @@ async fn model_responses( .cloned() .map(Extension), headers, - decoded, + input: GenerationEndpoint::Responses.input(decoded), middleware_body, }, Some(authorization), diff --git a/backend/crates/gateway-api/src/admin/plugins/mod.rs b/backend/crates/gateway-api/src/admin/plugins/mod.rs index 971141055..b17d8a2da 100644 --- a/backend/crates/gateway-api/src/admin/plugins/mod.rs +++ b/backend/crates/gateway-api/src/admin/plugins/mod.rs @@ -13,8 +13,7 @@ struct IdRequest { id: String, } -pub(super) fn router() --> axum::Router { +pub(super) fn router() -> axum::Router { artifacts::router() .merge(distribution::router()) .merge(instances::router()) diff --git a/backend/crates/gateway-api/src/admin/proxies.rs b/backend/crates/gateway-api/src/admin/proxies.rs index 945131e4b..1c1b1840a 100644 --- a/backend/crates/gateway-api/src/admin/proxies.rs +++ b/backend/crates/gateway-api/src/admin/proxies.rs @@ -1,6 +1,6 @@ //! 账号出站代理管理的 HTTP 请求校验、路由与展示投影 -use crate::auth::SessionState; +use crate::SessionState; use axum::{ Router, diff --git a/backend/crates/gateway-api/src/admin/settings.rs b/backend/crates/gateway-api/src/admin/settings.rs index d62011c00..265d71e5a 100644 --- a/backend/crates/gateway-api/src/admin/settings.rs +++ b/backend/crates/gateway-api/src/admin/settings.rs @@ -1,6 +1,6 @@ //! 管理端运行设置、模型定价与 Admin API Key 的 HTTP 接口 -use crate::auth::SessionState; +use crate::SessionState; use std::{collections::BTreeMap, fmt}; @@ -51,9 +51,9 @@ pub struct RuntimeSettingsFields { pub switch_account_on_queue_failure: bool, pub max_retry_after_seconds: u32, pub openai_guardian_reserved_concurrency: u32, - pub openai_account_affinity: gateway_core::account::AccountAffinity, + pub account_affinity: gateway_core::account::AccountAffinity, pub max_account_rotations: u32, - pub openai_session_affinity_ttl_hours: u32, + pub session_affinity_ttl_hours: u32, pub responses_max_decompressed_body_bytes: u64, pub smart_scheduling: gateway_core::account::SmartSchedulingConfig, pub quota_reset_window_weights: gateway_core::account::ResetWindowWeights, @@ -359,7 +359,7 @@ where Ok(AdminResponse::new( StatusCode::OK, AdminEnvelope::ok(serde_json::json!({ - "defaults": pricing.defaults, "overrides": pricing.overrides, + "supportedBands": pricing.supported_bands, "defaults": pricing.defaults, "overrides": pricing.overrides, "synced": pricing.synced, "syncedAt": pricing.synced_at, "syncedAtDisplay": pricing.synced_at.as_ref().map(|value| crate::time::TimePresenter::new(state.admin_services().timezone()).datetime(value)), })), @@ -601,9 +601,6 @@ fn normalize_request_profile_updates( profiles .into_iter() .map(|(provider, profile)| { - if !matches!(provider.as_str(), "openai" | "xai") { - return Err(WireValidationError::new("providerRequestProfiles")); - } let provider = gateway_core::routing::ProviderKind::new(provider) .map_err(|_| WireValidationError::new("providerRequestProfiles"))?; Ok(( @@ -728,9 +725,9 @@ impl RuntimeSettingsFields { switch_account_on_queue_failure: self.switch_account_on_queue_failure, max_retry_after_seconds: self.max_retry_after_seconds, openai_guardian_reserved_concurrency: self.openai_guardian_reserved_concurrency, - openai_account_affinity: self.openai_account_affinity, + account_affinity: self.account_affinity, max_account_rotations: self.max_account_rotations, - openai_session_affinity_ttl_hours: self.openai_session_affinity_ttl_hours, + session_affinity_ttl_hours: self.session_affinity_ttl_hours, responses_max_decompressed_body_bytes: self.responses_max_decompressed_body_bytes, smart_scheduling: self.smart_scheduling, quota_reset_window_weights: self.quota_reset_window_weights, @@ -774,9 +771,9 @@ impl From for RuntimeSett switch_account_on_queue_failure: settings.switch_account_on_queue_failure, max_retry_after_seconds: settings.max_retry_after_seconds, openai_guardian_reserved_concurrency: settings.openai_guardian_reserved_concurrency, - openai_account_affinity: settings.openai_account_affinity, + account_affinity: settings.account_affinity, max_account_rotations: settings.max_account_rotations, - openai_session_affinity_ttl_hours: settings.openai_session_affinity_ttl_hours, + session_affinity_ttl_hours: settings.session_affinity_ttl_hours, responses_max_decompressed_body_bytes: settings.responses_max_decompressed_body_bytes, smart_scheduling: settings.smart_scheduling, quota_reset_window_weights: settings.quota_reset_window_weights, @@ -815,9 +812,9 @@ fn settings_validation_error(field: &'static str) -> WireValidationError { "min_codex_cli_version" => "minCodexCliVersion", "min_codex_desktop_version" => "minCodexDesktopVersion", "openai_request_country" => "openaiRequestCountry", - "openai_account_affinity" => "openaiAccountAffinity", + "account_affinity" => "accountAffinity", "openai_guardian_reserved_concurrency" => "openaiGuardianReservedConcurrency", - "openai_session_affinity_ttl_hours" => "openaiSessionAffinityTtlHours", + "session_affinity_ttl_hours" => "sessionAffinityTtlHours", "ops_event_retention_days" => "opsEventRetentionDays", "refresh_concurrency" => "refreshConcurrency", "refresh_margin_seconds" => "refreshMarginSeconds", diff --git a/backend/crates/gateway-api/src/admin/system.rs b/backend/crates/gateway-api/src/admin/system.rs index 712fa451b..ddc3b22cc 100644 --- a/backend/crates/gateway-api/src/admin/system.rs +++ b/backend/crates/gateway-api/src/admin/system.rs @@ -3,7 +3,7 @@ //! //! 这里不依赖更新服务或进程控制;应用层通过窄端口提供系统操作事实 -use crate::auth::SessionState; +use crate::SessionState; use std::convert::Infallible; diff --git a/backend/crates/gateway-api/src/auth.rs b/backend/crates/gateway-api/src/auth.rs index b3c30d265..1e344be7b 100644 --- a/backend/crates/gateway-api/src/auth.rs +++ b/backend/crates/gateway-api/src/auth.rs @@ -1,5 +1,6 @@ //! 控制面统一登录、会话恢复与退出;身份由认证用例返回 +use crate::SessionState; use std::{fmt, net::SocketAddr}; use axum::{ @@ -10,22 +11,16 @@ use axum::{ response::{IntoResponse, Response}, routing::{any, get, post}, }; -use gateway_admin::{ - AdminServices, - model::auth::{AuthSession, ChangePassword, LoginCommand, LoginError, SessionSubject}, +use gateway_admin::model::auth::{ + AuthSession, ChangePassword, LoginCommand, LoginError, SessionSubject, }; use serde::{Deserialize, Serialize}; use crate::{ admin::{AdminEnvelope, AdminError, AdminJson, AdminResponse, wire::map_admin_service_error}, - session_cookie, + session, }; -/// 控制面 HTTP adapter 消费同一组用例;权限由各入口服务端校验 -pub trait SessionState { - fn admin_services(&self) -> &AdminServices; -} - #[derive(Deserialize)] #[serde(tag = "mode", rename_all = "camelCase", deny_unknown_fields)] pub enum LoginRequest { @@ -138,8 +133,8 @@ where .login( payload.into(), peer.ip(), - session_cookie::refresh_value(&headers) - .or_else(|| session_cookie::value(&headers)) + session::refresh_value(&headers) + .or_else(|| session::value(&headers)) .as_deref(), ) .await @@ -165,7 +160,7 @@ where let session = state .admin_services() .auth() - .session(session_cookie::value(&headers).as_deref()) + .session(session::value(&headers).as_deref()) .await .map_err(map_admin_service_error)?; Ok(session_response(session.as_ref())) @@ -182,8 +177,8 @@ where .admin_services() .auth() .renew_session( - session_cookie::refresh_value(&headers).as_deref(), - session_cookie::value(&headers).as_deref(), + session::refresh_value(&headers).as_deref(), + session::value(&headers).as_deref(), ) .await .map_err(map_admin_service_error)?; @@ -214,14 +209,14 @@ fn set_session_cookie( append_cookie( &mut response, headers, - session_cookie::NAME, + session::NAME, &grant.session_id, Some(grant.session.expires_at), )?; append_cookie( &mut response, headers, - session_cookie::REFRESH_NAME, + session::REFRESH_NAME, grant.refresh_token.as_deref().unwrap_or_default(), grant .session @@ -239,8 +234,8 @@ fn append_cookie( value: &str, expires_at: Option>, ) -> Result<(), AdminError> { - let attributes = session_cookie::attributes(headers); - let path = if name == session_cookie::REFRESH_NAME { + let attributes = session::attributes(headers); + let path = if name == session::REFRESH_NAME { "/api/auth" } else { "/" @@ -272,8 +267,7 @@ async fn logout(State(state): State, headers: HeaderMap) -> Result Result { - for name in [session_cookie::NAME, session_cookie::REFRESH_NAME] { + for name in [session::NAME, session::REFRESH_NAME] { append_cookie(&mut response, headers, name, "", None)?; } Ok(response) diff --git a/backend/crates/gateway-api/src/openai/auth.rs b/backend/crates/gateway-api/src/data_plane/auth.rs similarity index 99% rename from backend/crates/gateway-api/src/openai/auth.rs rename to backend/crates/gateway-api/src/data_plane/auth.rs index 0728deb6d..1013835c6 100644 --- a/backend/crates/gateway-api/src/openai/auth.rs +++ b/backend/crates/gateway-api/src/data_plane/auth.rs @@ -14,7 +14,7 @@ use super::{ client_version_rejection_response, missing_client_api_key_response, runtime_unavailable_response, }, - service::OpenAiService, + service::DataPlaneService, }; /// Client API key 鉴权失败原因 @@ -85,7 +85,7 @@ impl ClientApiKeyAuthError { } pub(crate) async fn authenticate_client( - service: &OpenAiService, + service: &DataPlaneService, headers: &HeaderMap, accepted: ClientKeyHeaders, ) -> Result { @@ -102,7 +102,7 @@ pub(crate) async fn authenticate_client( /// 复用数据面入口认证计划,但不记录 Key 使用事实或执行推理准入 pub(crate) async fn verify_client( - service: &OpenAiService, + service: &DataPlaneService, headers: &HeaderMap, ) -> Result { let request = client_authentication_request(headers, ClientKeyHeaders::Bearer)?; diff --git a/backend/crates/gateway-api/src/openai/responses/error.rs b/backend/crates/gateway-api/src/data_plane/body.rs similarity index 60% rename from backend/crates/gateway-api/src/openai/responses/error.rs rename to backend/crates/gateway-api/src/data_plane/body.rs index 5f45309cb..8239d2f05 100644 --- a/backend/crates/gateway-api/src/openai/responses/error.rs +++ b/backend/crates/gateway-api/src/data_plane/body.rs @@ -1,9 +1,11 @@ -//! OpenAI Responses adapter 的稳定错误 contract +//! 数据面请求正文的有界解压与解码错误 use crate::client_error::{ProtocolError, ProtocolErrorBody}; +use axum::http::HeaderMap; +use std::borrow::Cow; use thiserror::Error; -/// Responses 请求解码错误 +/// 请求解码错误 #[derive(Debug, Clone, PartialEq, Eq, Error)] pub enum RequestDecodeError { /// 请求不是合法 JSON @@ -152,31 +154,85 @@ impl RequestDecodeError { } } -/// OpenAI Responses 原生 wire 转发错误 -#[derive(Debug, Clone, PartialEq, Eq, Error)] -pub enum ResponseEncodeError { - /// 协议原生流缺少可返回的终态 response object - #[error("responses wire stream has no terminal response")] - MissingWireTerminal, - /// 缺少完整终态输出,已交付的完成项也存在缺项或冲突,不能伪造完整结果 - #[error("responses wire stream has inconsistent output items")] - InvalidOutputItems, - /// 终态 response object 无法序列化为完整 HTTP JSON 响应 - #[error("responses wire terminal serialization failed")] - Serialization, -} +/// zstd 回溯窗口独立于输出上限,调整设置不能放大解码器内部窗口分配 +const MAX_ZSTD_WINDOW_LOG: u32 = 26; -impl ResponseEncodeError { - /// 转换为不包含生成内容的 OpenAI 风格错误 payload - #[must_use] - pub fn protocol_body(&self) -> ProtocolErrorBody { - ProtocolErrorBody { - error: ProtocolError { - kind: "server_error", - code: "invalid_upstream_response", - message: "The gateway could not forward the upstream response.".to_owned(), - param: None, - }, +/// 按 `Content-Encoding` 解压下游请求体 +/// +/// 未压缩与 `identity` 借用原始正文;压缩正文在读取过程中限制展开大小, +/// 避免先完整分配再检查 +/// 只接受单一编码,重复头和叠加编码不能只解释第一项 +pub(in crate::data_plane) fn decompress_request_body<'a>( + body: &'a [u8], + headers: &HeaderMap, + max_decompressed_bytes: usize, +) -> Result, RequestDecodeError> { + let encoding = headers + .get_all(axum::http::header::CONTENT_ENCODING) + .iter() + .map(|value| { + value + .to_str() + .map_err(|_| RequestDecodeError::MalformedJson) + }) + .collect::, _>>()? + .join(","); + match encoding.trim().to_ascii_lowercase().as_str() { + "" | "identity" => Ok(Cow::Borrowed(body)), + "gzip" => { + let decoder = flate2::read::MultiGzDecoder::new(body); + read_bounded(decoder, max_decompressed_bytes).map(Cow::Owned) } + "deflate" => { + let decoder = flate2::read::ZlibDecoder::new(body); + read_bounded(decoder, max_decompressed_bytes).map(Cow::Owned) + } + "zstd" => { + let mut decoder = zstd::stream::read::Decoder::with_buffer(body) + .map_err(|_| RequestDecodeError::MalformedJson)?; + // 输出有界之外,也限制压缩帧声明的回溯窗口,防止解码器内部过量分配 + decoder + .window_log_max(MAX_ZSTD_WINDOW_LOG) + .map_err(|_| RequestDecodeError::MalformedJson)?; + read_bounded(decoder, max_decompressed_bytes).map(Cow::Owned) + } + other => Err(RequestDecodeError::UnsupportedContentEncoding { + encoding: other.to_owned(), + }), + } +} + +fn read_bounded( + mut reader: R, + max_decompressed_bytes: usize, +) -> Result, RequestDecodeError> { + let mut decoded = Vec::new(); + let mut chunk = [0; 8192]; + loop { + let remaining = max_decompressed_bytes - decoded.len(); + let read_limit = chunk.len().min(remaining.saturating_add(1)); + let read = reader + .read(&mut chunk[..read_limit]) + .map_err(|_| RequestDecodeError::MalformedJson)?; + if read == 0 { + return Ok(decoded); + } + if read > remaining { + return Err(RequestDecodeError::DecompressedBodyTooLarge { + limit_bytes: max_decompressed_bytes, + }); + } + // 默认 Vec 扩容和 read_to_end 的 EOF 探测可能突破输出上限; + // 容量增长也受相同边界约束,越界探测只使用栈上分块缓冲区 + let required = decoded.len() + read; + if required > decoded.capacity() { + let capacity = decoded + .capacity() + .saturating_mul(2) + .max(required) + .min(max_decompressed_bytes); + decoded.reserve_exact(capacity - decoded.len()); + } + decoded.extend_from_slice(&chunk[..read]); } } diff --git a/backend/crates/gateway-api/src/openai/chat_completions/delivery.rs b/backend/crates/gateway-api/src/data_plane/chat_completions/delivery.rs similarity index 99% rename from backend/crates/gateway-api/src/openai/chat_completions/delivery.rs rename to backend/crates/gateway-api/src/data_plane/chat_completions/delivery.rs index 5e602b6a4..4c908f42a 100644 --- a/backend/crates/gateway-api/src/openai/chat_completions/delivery.rs +++ b/backend/crates/gateway-api/src/data_plane/chat_completions/delivery.rs @@ -16,7 +16,7 @@ use gateway_protocol::openai::sse::{DONE_SSE_FRAME, SseEvent, SseEventDecoder, s use serde_json::Value; use crate::client_error::ProtocolErrorBody; -use crate::openai::middleware::error_response; +use crate::data_plane::middleware::error_response; use super::response::{ChatIdentity, ChatStreamEncoder, project_response}; diff --git a/backend/crates/gateway-api/src/openai/chat_completions/http.rs b/backend/crates/gateway-api/src/data_plane/chat_completions/http.rs similarity index 89% rename from backend/crates/gateway-api/src/openai/chat_completions/http.rs rename to backend/crates/gateway-api/src/data_plane/chat_completions/http.rs index 3ebbb81ad..d2218a109 100644 --- a/backend/crates/gateway-api/src/openai/chat_completions/http.rs +++ b/backend/crates/gateway-api/src/data_plane/chat_completions/http.rs @@ -10,14 +10,15 @@ use axum::{ }; use crate::ApiState; -use crate::openai::{ +use crate::data_plane::{ auth::{ClientKeyHeaders, authenticate_client, client_access_error_response}, + body::{RequestDecodeError, decompress_request_body}, error::{gateway_error_response, protocol_error_response}, generation::{ - DecodedGenerationRequest, GenerationHttpRequest, HttpResponseAdapter, + DecodedGenerationRequest, GenerationEndpoint, GenerationHttpRequest, HttpResponseAdapter, execute_prepared_generation, }, - responses::{RequestDecodeError, decode_request_with_headers, decompress_request_body}, + responses::decode_request_with_headers, router::CHAT_COMPLETIONS_PATH, }; @@ -27,14 +28,14 @@ use super::{ response::ChatIdentity, }; -pub(in crate::openai) async fn chat_completions( +pub(in crate::data_plane) async fn chat_completions( State(state): State, connect_info: Option>>, ingress_id: Option>, headers: HeaderMap, body: Bytes, ) -> Response { - let service = state.openai().clone(); + let service = state.data_plane().clone(); let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await { Ok(client) => client, Err(error) => return client_access_error_response(error), @@ -76,7 +77,7 @@ pub(in crate::openai) async fn chat_completions( peer_address: connect_info.map(|Extension(ConnectInfo(address))| address), ingress_id, headers, - decoded, + input: GenerationEndpoint::Responses.input(decoded), middleware_body, }, None, diff --git a/backend/crates/gateway-api/src/openai/chat_completions/mod.rs b/backend/crates/gateway-api/src/data_plane/chat_completions/mod.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/chat_completions/mod.rs rename to backend/crates/gateway-api/src/data_plane/chat_completions/mod.rs diff --git a/backend/crates/gateway-api/src/openai/chat_completions/request.rs b/backend/crates/gateway-api/src/data_plane/chat_completions/request.rs similarity index 98% rename from backend/crates/gateway-api/src/openai/chat_completions/request.rs rename to backend/crates/gateway-api/src/data_plane/chat_completions/request.rs index c4c0fa426..3e4b00ea2 100644 --- a/backend/crates/gateway-api/src/openai/chat_completions/request.rs +++ b/backend/crates/gateway-api/src/data_plane/chat_completions/request.rs @@ -4,14 +4,14 @@ use std::collections::HashSet; use serde_json::{Map, Value, json}; -use crate::openai::responses::RequestDecodeError; +use crate::data_plane::body::RequestDecodeError; -pub(in crate::openai) struct ConvertedChatRequest { - pub(in crate::openai) body: Map, - pub(in crate::openai) include_usage: bool, +pub(in crate::data_plane) struct ConvertedChatRequest { + pub(in crate::data_plane) body: Map, + pub(in crate::data_plane) include_usage: bool, } -pub(in crate::openai) fn convert_request( +pub(in crate::data_plane) fn convert_request( body: &[u8], ) -> Result { let value = serde_json::from_slice(body).map_err(|_| RequestDecodeError::MalformedJson)?; diff --git a/backend/crates/gateway-api/src/openai/chat_completions/response.rs b/backend/crates/gateway-api/src/data_plane/chat_completions/response.rs similarity index 98% rename from backend/crates/gateway-api/src/openai/chat_completions/response.rs rename to backend/crates/gateway-api/src/data_plane/chat_completions/response.rs index 93c939a2c..accb5c113 100644 --- a/backend/crates/gateway-api/src/openai/chat_completions/response.rs +++ b/backend/crates/gateway-api/src/data_plane/chat_completions/response.rs @@ -12,7 +12,7 @@ use sha2::{Digest as _, Sha256}; use crate::client_error::{ProtocolError, ProtocolErrorBody}; #[derive(Debug, Clone, Serialize)] -pub(in crate::openai) struct ChatIdentity { +pub(in crate::data_plane) struct ChatIdentity { pub id: String, pub created: u64, pub model: String, @@ -35,7 +35,7 @@ struct Envelope<'a> { } /// 输入已由现有 Responses collector 聚合,投影不再恢复或重建缺失的 output -pub(in crate::openai) fn project_response( +pub(in crate::data_plane) fn project_response( response: &Value, identity: &ChatIdentity, ) -> Result { @@ -211,7 +211,7 @@ enum Terminal { } /// 只保存身份关联与快照去重所需内容;终态帧由外层受管 body 决定何时交付 -pub(in crate::openai) struct ChatStreamEncoder { +pub(in crate::data_plane) struct ChatStreamEncoder { identity: ChatIdentity, include_usage: bool, role_sent: bool, @@ -221,7 +221,7 @@ pub(in crate::openai) struct ChatStreamEncoder { } impl ChatStreamEncoder { - pub(in crate::openai) fn new(identity: ChatIdentity, include_usage: bool) -> Self { + pub(in crate::data_plane) fn new(identity: ChatIdentity, include_usage: bool) -> Self { Self { identity, include_usage, @@ -232,15 +232,15 @@ impl ChatStreamEncoder { } } - pub(in crate::openai) fn is_completed(&self) -> bool { + pub(in crate::data_plane) fn is_completed(&self) -> bool { self.terminal == Some(Terminal::Completed) } - pub(in crate::openai) fn has_wire_failure(&self) -> bool { + pub(in crate::data_plane) fn has_wire_failure(&self) -> bool { self.terminal == Some(Terminal::Failed) } - pub(in crate::openai) fn push_event( + pub(in crate::data_plane) fn push_event( &mut self, event_type: Option<&str>, data: &Value, diff --git a/backend/crates/gateway-api/src/openai/error.rs b/backend/crates/gateway-api/src/data_plane/error.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/error.rs rename to backend/crates/gateway-api/src/data_plane/error.rs diff --git a/backend/crates/gateway-api/src/data_plane/genai/error.rs b/backend/crates/gateway-api/src/data_plane/genai/error.rs new file mode 100644 index 000000000..86c419d82 --- /dev/null +++ b/backend/crates/gateway-api/src/data_plane/genai/error.rs @@ -0,0 +1,71 @@ +//! Google RPC JSON 错误体和 SSE 失败帧,保留上游的原始错误详情 + +use axum::{ + body::{Body, Bytes, to_bytes}, + http::{HeaderValue, StatusCode, header}, + response::Response, +}; +use serde_json::{Value, json}; + +pub(super) fn payload(status: StatusCode, message: &str) -> Value { + let kind = match status.as_u16() { + 400 | 405 | 413 | 415 | 422 => "INVALID_ARGUMENT", + 401 => "UNAUTHENTICATED", + 403 => "PERMISSION_DENIED", + 404 => "NOT_FOUND", + 408 | 504 => "DEADLINE_EXCEEDED", + 409 => "ABORTED", + 429 => "RESOURCE_EXHAUSTED", + 499 => "CANCELLED", + 501 => "UNIMPLEMENTED", + 502 | 503 => "UNAVAILABLE", + _ => "INTERNAL", + }; + json!({"error": {"code": status.as_u16(), "status": kind, "message": message}}) +} + +pub(in crate::data_plane) async fn project_error_response(response: Response) -> Response { + if response.status().is_success() { + return response; + } + let (mut parts, body) = response.into_parts(); + let bytes = to_bytes(body, usize::MAX).await.unwrap_or_default(); + let value = serde_json::from_slice::(&bytes).unwrap_or(Value::Null); + if value.pointer("/error/code").is_some_and(Value::is_number) { + return Response::from_parts(parts, Body::from(bytes)); + } + let message = value + .pointer("/error/message") + .and_then(Value::as_str) + .unwrap_or_else(|| { + parts + .status + .canonical_reason() + .unwrap_or("The gateway could not complete the request.") + }); + let data = payload(parts.status, message); + parts.headers.remove(header::CONTENT_LENGTH); + parts.headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + Response::from_parts(parts, Body::from(data.to_string())) +} + +pub(in crate::data_plane) fn error_frame(status: StatusCode, message: &str) -> Bytes { + Bytes::from(format!("data: {}\n\n", payload(status, message))) +} + +pub(in crate::data_plane) fn stream_error(value: &Value) -> Bytes { + let error = value + .pointer("/response/error") + .or_else(|| value.get("error")); + if let Some(error) = error.filter(|error| error.get("code").is_some_and(Value::is_number)) { + return Bytes::from(format!("data: {}\n\n", json!({"error":error}))); + } + let message = error + .and_then(|e| e.get("message")) + .and_then(Value::as_str) + .unwrap_or("The gateway could not complete the request."); + error_frame(StatusCode::INTERNAL_SERVER_ERROR, message) +} diff --git a/backend/crates/gateway-api/src/data_plane/genai/mod.rs b/backend/crates/gateway-api/src/data_plane/genai/mod.rs new file mode 100644 index 000000000..a7befe4ed --- /dev/null +++ b/backend/crates/gateway-api/src/data_plane/genai/mod.rs @@ -0,0 +1,230 @@ +//! Google GenAI 原生 HTTP 入口,模型和生成方法取自 URL,业务正文进入通用执行链路 + +mod error; +mod models; +pub(super) use error::project_error_response; +pub(in crate::data_plane) use error::{error_frame, stream_error}; + +use std::{borrow::Cow, net::SocketAddr}; + +use axum::{ + Json, Router, + body::Bytes, + extract::{ConnectInfo, Extension, Path, RawQuery, State}, + http::{HeaderMap, StatusCode, header}, + response::{IntoResponse as _, Response}, + routing::{get, post}, +}; +use gateway_core::{ + error::{GatewayError, GatewayErrorKind}, + operation::{GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest}, +}; +use gateway_protocol::genai::GENAI_PROTOCOL; +use serde_json::{Map, Value, json}; + +use crate::{ + ApiState, + data_plane::{ + auth::{ + ClientKeyHeaders, authenticate_client, client_access_error_response, verify_client, + }, + body::decompress_request_body, + error::gateway_error_response, + generation::{ + ContinuationIntent, DecodedGenerationRequest, GenerationEndpoint, + GenerationHttpRequest, GenerationInput, GenerationRequestMetadata, + execute_prepared_generation, + }, + }, +}; + +pub(super) const MODEL_ACTION_PATH: &str = "/v1beta/models/{resource}"; +const METRICS_PATH: &str = "/v1beta:{method}"; + +pub(super) fn router() -> Router { + Router::new() + .route(models::MODELS_PATH, get(models::list)) + .route(MODEL_ACTION_PATH, post(generate).get(models::detail)) + .route(METRICS_PATH, post(metric)) + .layer(axum::middleware::map_response(project_error_response)) +} + +fn parse_route(resource: &str, query: Option<&str>) -> Result { + let invalid = |message| GatewayError::new(GatewayErrorKind::InvalidRequest, message); + let (model, method) = resource + .split_once(':') + .ok_or_else(|| invalid("A model action is required."))?; + if !valid_segment(model) { + return Err(invalid("Invalid model name.")); + } + let (endpoint, stream) = match method { + "generateContent" => (GenerationEndpoint::GenAi, false), + "streamGenerateContent" => (GenerationEndpoint::GenAi, true), + "countTokens" => (GenerationEndpoint::GenAiTokenCount, false), + _ => { + return Err(GatewayError::new( + GatewayErrorKind::ModelNotFound, + "Unknown model action.", + )); + } + }; + let mut formats = url::form_urlencoded::parse(query.unwrap_or_default().as_bytes()) + .filter_map(|(key, value)| (key == "alt").then_some(value)); + let format = formats.next(); + if formats.next().is_some() + || (stream && format.as_deref() != Some("sse")) + || (!stream && format.is_some_and(|value| value != "json")) + { + return Err(invalid( + "Invalid response format for the requested model action.", + )); + } + Ok(GenerationInput { + endpoint, + model: model.to_owned(), + stream, + }) +} + +pub(super) fn decode( + model: &str, + stream: bool, + endpoint: GenerationEndpoint, + body: Bytes, + headers: &HeaderMap, +) -> Result { + let mut context = Map::new(); + context.insert("stream".into(), Value::Bool(stream)); + let mut attribution = Map::new(); + for key in [ + "user-agent", + "x-goog-api-client", + "x-http-session-id", + "x-session-id", + ] { + let connection_option = headers + .get_all(header::CONNECTION) + .iter() + .filter_map(|value| value.to_str().ok()) + .flat_map(|value| value.split(',')) + .any(|value| key.eq_ignore_ascii_case(value.trim())); + if !connection_option && let Some(value) = headers.get(key).and_then(|v| v.to_str().ok()) { + attribution.insert(key.into(), json!(value)); + } + } + context.insert("headers".into(), Value::Object(attribution)); + let passthrough = crate::data_plane::responses::request::passthrough_headers(headers); + if !passthrough.is_empty() { + context.insert("opaque_request_headers".into(), Value::Array(passthrough)); + } + let payload = ProtocolPayload::from_json_bytes(GENAI_PROTOCOL, body.clone()) + .map_err(|_| { + GatewayError::new( + GatewayErrorKind::InvalidRequest, + "Request body must be a JSON object.", + ) + })? + .with_context(context); + let operation = if endpoint == GenerationEndpoint::GenAiTokenCount { + Operation::CountTokens( + TokenCountRequest::from_raw_json( + RawJsonPayload::new(GENAI_PROTOCOL, body) + .map_err(|_| { + GatewayError::new( + GatewayErrorKind::InvalidRequest, + "Invalid request protocol.", + ) + })? + .with_context(payload.context().clone()), + ) + .requiring_native_protocol(), + ) + } else { + Operation::Generate( + GenerateRequest::from_protocol_payload(payload).requiring_native_protocol(), + ) + }; + Ok(DecodedGenerationRequest { + operation, + metadata: GenerationRequestMetadata { + requested_model: model.to_owned(), + stream, + store: false, + continuation: ContinuationIntent::None, + client_ip: None, + user_agent: None, + }, + }) +} + +fn valid_segment(value: &str) -> bool { + !value.is_empty() + && value != "." + && value != ".." + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"._-@".contains(&byte)) +} + +async fn generate( + State(state): State, + connect_info: Option>>, + ingress_id: Option>, + Path(resource): Path, + RawQuery(query): RawQuery, + headers: HeaderMap, + body: Bytes, +) -> Response { + let service = state.data_plane().clone(); + let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await { + Ok(client) => client, + Err(error) => return client_access_error_response(error), + }; + let route = match parse_route(&resource, query.as_deref()) { + Ok(route) => route, + Err(error) => return gateway_error_response(&error), + }; + let body = match decompress_request_body( + &body, + &headers, + client.snapshot().responses_max_decompressed_body_bytes(), + ) { + Ok(Cow::Borrowed(_)) => body, + Ok(Cow::Owned(bytes)) => Bytes::from(bytes), + Err(error) => { + return ( + StatusCode::BAD_REQUEST, + Json(error::payload( + StatusCode::BAD_REQUEST, + &error.protocol_body().error.message, + )), + ) + .into_response(); + } + }; + let prepared = match service.execution().prepare_execution(client).await { + Ok(prepared) => prepared, + Err(error) => return gateway_error_response(&error), + }; + execute_prepared_generation( + service, + prepared, + GenerationHttpRequest { + peer_address: connect_info.map(|Extension(ConnectInfo(addr))| addr), + ingress_id, + headers, + input: route, + middleware_body: body, + }, + None, + None, + ) + .await +} + +async fn metric(State(state): State, headers: HeaderMap) -> Response { + match verify_client(state.data_plane(), &headers).await { + Ok(_) => Json(json!({})).into_response(), + Err(error) => client_access_error_response(error.into()), + } +} diff --git a/backend/crates/gateway-api/src/data_plane/genai/models.rs b/backend/crates/gateway-api/src/data_plane/genai/models.rs new file mode 100644 index 000000000..d655d0a8d --- /dev/null +++ b/backend/crates/gateway-api/src/data_plane/genai/models.rs @@ -0,0 +1,206 @@ +//! Gemini 模型目录复用冻结范围与原生协议能力,分页不扩大可见模型集合 + +use axum::{ + Json, + extract::{Path, Query, State}, + http::{HeaderMap, StatusCode}, + response::{IntoResponse, Response}, +}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use gateway_core::{ + engine::execution::AuthenticatedClient, + operation::{GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest}, +}; +use gateway_protocol::genai::GENAI_PROTOCOL; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value, json}; + +use crate::{ + ApiState, + data_plane::{ + auth::{ClientKeyHeaders, authenticate_client, client_access_error_response}, + middleware::{self, RequestInput}, + }, +}; + +pub(super) const MODELS_PATH: &str = "/v1beta/models"; + +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct ModelsQuery { + #[serde(alias = "page_size")] + page_size: Option, + #[serde(alias = "page_token")] + page_token: Option, +} + +#[derive(Deserialize, Serialize)] +struct Cursor { + after: String, + size: usize, +} + +pub(super) async fn list( + State(state): State, + Query(query): Query, + headers: HeaderMap, +) -> Response { + query_response(state, headers, None, query).await +} + +pub(super) async fn detail( + State(state): State, + Path(model): Path, + headers: HeaderMap, +) -> Response { + // action 路由只有 POST,不能让新增详情 GET 接管生成方法 + if model.contains(':') { + return error( + StatusCode::METHOD_NOT_ALLOWED, + "This model action requires POST.", + ); + } + if !super::valid_segment(&model) { + return error(StatusCode::BAD_REQUEST, "Invalid model name."); + } + query_response(state, headers, Some(model), ModelsQuery::default()).await +} + +async fn query_response( + state: ApiState, + headers: HeaderMap, + model: Option, + query: ModelsQuery, +) -> Response { + let service = state.data_plane(); + let client = match authenticate_client(service, &headers, ClientKeyHeaders::Bearer).await { + Ok(client) => client, + Err(err) => return client_access_error_response(err), + }; + let endpoint = if model.is_some() { + super::MODEL_ACTION_PATH + } else { + MODELS_PATH + }; + let mut input = RequestInput::query(endpoint.to_owned(), model.clone(), &headers); + input.protocol = GENAI_PROTOCOL.to_owned(); + middleware::query_response( + service.execution(), + client, + input, + move |client| async move { + match catalog(&client) { + Ok(models) => match model { + Some(model) => models + .into_iter() + .find(|value| value["name"] == format!("models/{model}")) + .map_or_else( + || error(StatusCode::NOT_FOUND, "Requested model was not found."), + success, + ), + None => paginate(models, query), + }, + Err(()) => error( + StatusCode::SERVICE_UNAVAILABLE, + "Model catalog is unavailable.", + ), + } + }, + ) + .await +} + +fn catalog(client: &AuthenticatedClient) -> Result, ()> { + let generate = Operation::Generate( + GenerateRequest::from_protocol_payload( + ProtocolPayload::json_object(GENAI_PROTOCOL, Map::new()).map_err(|_| ())?, + ) + .requiring_native_protocol(), + ); + let count = Operation::CountTokens( + TokenCountRequest::from_raw_json( + RawJsonPayload::new(GENAI_PROTOCOL, bytes::Bytes::from_static(b"{}")) + .map_err(|_| ())?, + ) + .requiring_native_protocol(), + ); + let snapshot = client.snapshot(); + let scope = client.policy().account_scope(); + let counted = snapshot.public_models_for_operation(scope, &count); + Ok(snapshot + .public_models_for_operation(scope, &generate) + .into_iter() + .filter(|model| super::valid_segment(model.as_str())) + .map(|model| { + let mut methods = vec!["generateContent", "streamGenerateContent"]; + if counted.binary_search(&model).is_ok() { + methods.push("countTokens"); + } + // 上游尚未提供完整 Gemini 元数据,未知版本与 Token 上限保持缺失 + json!({ + "name": format!("models/{}", model.as_str()), + "displayName": model.as_str(), + "supportedGenerationMethods": methods, + }) + }) + .collect()) +} + +fn paginate(models: Vec, query: ModelsQuery) -> Response { + let size = match query.page_size.unwrap_or(50) { + n if n < 0 => return error(StatusCode::BAD_REQUEST, "pageSize must not be negative."), + 0 => 50, + n => n.min(1000) as usize, + }; + let start = if let Some(token) = query.page_token.filter(|token| !token.is_empty()) { + let cursor = URL_SAFE_NO_PAD + .decode(token) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()); + let Some(cursor) = cursor.filter(|cursor| cursor.size == size) else { + return error( + StatusCode::BAD_REQUEST, + "Invalid pageToken or changed pageSize.", + ); + }; + let Some(index) = models + .iter() + .position(|model| model["name"] == cursor.after) + else { + return error( + StatusCode::BAD_REQUEST, + "pageToken is no longer in the model catalog.", + ); + }; + index + 1 + } else { + 0 + }; + let end = start.saturating_add(size).min(models.len()); + let mut body = json!({"models": &models[start..end]}); + if end < models.len() { + let cursor = Cursor { + after: models[end - 1]["name"] + .as_str() + .unwrap_or_default() + .to_owned(), + size, + }; + let Ok(bytes) = serde_json::to_vec(&cursor) else { + return error( + StatusCode::INTERNAL_SERVER_ERROR, + "Could not encode pageToken.", + ); + }; + body["nextPageToken"] = json!(URL_SAFE_NO_PAD.encode(bytes)); + } + success(body) +} + +fn success(value: Value) -> Response { + ([("cache-control", "private, no-store")], Json(value)).into_response() +} + +fn error(status: StatusCode, message: &str) -> Response { + (status, Json(super::error::payload(status, message))).into_response() +} diff --git a/backend/crates/gateway-api/src/openai/generation/http.rs b/backend/crates/gateway-api/src/data_plane/generation/http.rs similarity index 92% rename from backend/crates/gateway-api/src/openai/generation/http.rs rename to backend/crates/gateway-api/src/data_plane/generation/http.rs index efdac2cd8..c81a8cf4a 100644 --- a/backend/crates/gateway-api/src/openai/generation/http.rs +++ b/backend/crates/gateway-api/src/data_plane/generation/http.rs @@ -37,18 +37,18 @@ use gateway_protocol::openai::sse::response_failed_sse_event_with_id; use serde_json::Value; use tokio::time::Instant; -use crate::middleware::headers::encode_headers; -use crate::openai::error::{ +use crate::data_plane::error::{ engine_error_response, gateway_error_from_engine, protocol_error_response, }; -use crate::openai::middleware::{ +use crate::data_plane::middleware::{ ExpectedBody, PendingExecution, RequestInput, error_response, finalize_session, into_http_response, invoke_request, pending_execution_response, request_parts, }; -use crate::openai::service::OpenAiService; +use crate::data_plane::service::DataPlaneService; +use crate::middleware::headers::encode_headers; use super::{ - DecodedGenerationRequest, GenerationProtocol, + GenerationEndpoint, GenerationInput, response::GenerationEncoder, validation::{GenerationDeliveryValidator, GenerationValidationFacts}, }; @@ -65,7 +65,7 @@ pub(crate) struct GenerationHttpRequest { pub peer_address: Option, pub ingress_id: Option>, pub headers: HeaderMap, - pub decoded: DecodedGenerationRequest, + pub input: GenerationInput, pub middleware_body: Bytes, } @@ -77,7 +77,7 @@ pub(crate) struct HttpResponseAdapter { } pub(crate) async fn execute_prepared_generation( - service: OpenAiService, + service: DataPlaneService, prepared: PreparedRootExecution, request: GenerationHttpRequest, authorization: Option>, @@ -87,20 +87,18 @@ pub(crate) async fn execute_prepared_generation( peer_address, ingress_id, headers, - decoded, + input: generation, middleware_body, } = request; let (client_ip, user_agent) = request_client_context(&headers, peer_address); - let protocol = GenerationProtocol::from_request(&decoded); - let stream = decoded.metadata().stream(); + let protocol = generation.endpoint; + let stream = generation.stream; let transport = if stream { ClientTransport::HttpSse } else { ClientTransport::HttpJson }; - let model_hint = Some(decoded.metadata().requested_model().to_owned()); - // 终端会重新校验中间件改写后的正文,初步解码不必保留到响应交付 - drop(decoded); + let model_hint = Some(generation.model.clone()); let execution = service.execution(); let request_id = prepared.request_id().clone(); let cancellation = prepared.cancellation(); @@ -115,14 +113,11 @@ pub(crate) async fn execute_prepared_generation( middleware_headers.remove(CONTENT_LENGTH); let endpoint = adapter .as_ref() - .map_or(protocol.endpoint(), |adapter| adapter.endpoint); + .map_or(protocol.path(), |adapter| adapter.endpoint); let stream_error = adapter .as_ref() .map(|adapter| adapter.stream_error) - .or_else(|| { - (protocol != GenerationProtocol::Responses) - .then_some(crate::openai::messages::stream_error as fn(&Value) -> Bytes) - }); + .or_else(|| protocol.stream_error_encoder()); let input = RequestInput { endpoint: endpoint.to_owned(), protocol: protocol.wire().to_owned(), @@ -146,7 +141,7 @@ pub(crate) async fn execute_prepared_generation( if wire_protocol != protocol.wire() { return Err(MiddlewareError::Rejected); } - let decoded = protocol + let decoded = generation .decode( &request_body, &request_headers, @@ -154,8 +149,7 @@ pub(crate) async fn execute_prepared_generation( .client() .snapshot() .responses_max_decompressed_body_bytes(), - ) - .map_err(|_| MiddlewareError::Rejected)? + )? .with_client_context(client_ip, user_agent) .with_middleware_capabilities(&request)?; if decoded.metadata().stream() != stream { @@ -233,24 +227,20 @@ pub(crate) async fn execute_prepared_generation( } }; let response = if stream { - crate::openai::responses::keepalive::response_with_encoder( + super::keepalive::response_with_encoder( response, keepalive, stream_error, - protocol == GenerationProtocol::Responses, + protocol == GenerationEndpoint::Responses, ) .await } else { response.await }; - let response = if protocol == GenerationProtocol::Responses { - response - } else { - crate::openai::messages::project_error_response(response).await - }; + let response = protocol.project_error_response(response).await; // 预留 ID 没有对应执行记录,中间件提前返回时保留 HTTP 入口关联 ID if execution_entered.load(Ordering::Relaxed) { - crate::openai::with_model_request_id( + crate::data_plane::with_model_request_id( response, started_request_id.get().unwrap_or(&request_id), ) @@ -392,7 +382,7 @@ async fn execution_middleware_response( started: StartedExecution, connection_guard: Option>, validation: GenerationValidationFacts, - protocol: GenerationProtocol, + protocol: GenerationEndpoint, ) -> Result { let StartedExecution { stream, session, .. @@ -409,7 +399,7 @@ async fn execution_middleware_response( async fn buffered_execution_middleware_response( session: Box, validation: GenerationValidationFacts, - protocol: GenerationProtocol, + protocol: GenerationEndpoint, ) -> Result { let mut execution = PendingExecution::new(session); let collected = execution @@ -461,7 +451,7 @@ async fn streaming_execution_middleware_response( session: Box, connection_guard: Option>, validation: GenerationValidationFacts, - protocol: GenerationProtocol, + protocol: GenerationEndpoint, ) -> Result { let mut body = StreamingExecutionBody::new(session, connection_guard, validation, protocol); if let Err(error) = body.prime().await { @@ -487,8 +477,8 @@ async fn streaming_execution_middleware_response( pub async fn collect_execution_response(session: Box) -> Response { match buffered_execution_middleware_response( session, - GenerationValidationFacts::new(GenerationProtocol::Responses), - GenerationProtocol::Responses, + GenerationValidationFacts::new(GenerationEndpoint::Responses), + GenerationEndpoint::Responses, ) .await { @@ -506,13 +496,13 @@ pub async fn stream_execution_response( ) -> Response { let (admitted, keepalive) = tokio::sync::oneshot::channel(); let _ = admitted.send(session.response_commit()); - crate::openai::responses::keepalive::response( + super::keepalive::response( async move { match streaming_execution_middleware_response( session, connection_guard, - GenerationValidationFacts::new(GenerationProtocol::Responses), - GenerationProtocol::Responses, + GenerationValidationFacts::new(GenerationEndpoint::Responses), + GenerationEndpoint::Responses, ) .await { @@ -531,7 +521,7 @@ fn validated_middleware_response( response: MiddlewareResponse, facts: GenerationValidationFacts, streaming: bool, - protocol: GenerationProtocol, + protocol: GenerationEndpoint, ) -> MiddlewareResponse { if !(200..300).contains(&response.status_code()) { // 非成功响应沿用通用 SinglePayload 边界,不能套用成功 Responses 终态状态机 @@ -563,7 +553,7 @@ struct ValidatedGenerationBody { facts: GenerationValidationFacts, streaming: bool, validator: GenerationDeliveryValidator, - protocol: GenerationProtocol, + protocol: GenerationEndpoint, pending: VecDeque, committed: bool, } @@ -579,10 +569,9 @@ impl ValidatedGenerationBody { .map(str::to_owned) .or_else(|| self.facts.response_id()); self.pending.push_back(MiddlewareFrame::new( - if self.protocol == GenerationProtocol::Responses { - Bytes::from(response_failed_sse_event_with_id(response_id.as_deref(), "server_error", "middleware_failed", "Response middleware returned an invalid stream.")) - } else { - crate::openai::messages::stream_error(&serde_json::json!({"error":{"message":"Response middleware returned an invalid stream."}})) + match self.protocol.stream_error_encoder() { + Some(encode) => encode(&serde_json::json!({"error":{"message":"Response middleware returned an invalid stream."}})), + None => Bytes::from(response_failed_sse_event_with_id(response_id.as_deref(), "server_error", "middleware_failed", "Response middleware returned an invalid stream.")), }, MiddlewareFraming::SseEvent, false, @@ -680,7 +669,7 @@ async fn guarded_engine_error_response( execution: PendingExecution, error: &EngineError, response_headers: &[ProviderResponseHeader], - protocol: GenerationProtocol, + protocol: GenerationEndpoint, ) -> Result { guarded_http_response( execution, @@ -693,13 +682,9 @@ async fn guarded_engine_error_response( async fn guarded_http_response( execution: PendingExecution, response: Response, - protocol: GenerationProtocol, + protocol: GenerationEndpoint, ) -> Result { - let response = if protocol == GenerationProtocol::Responses { - response - } else { - crate::openai::messages::project_error_response(response).await - }; + let response = protocol.project_error_response(response).await; let (parts, body) = response.into_parts(); let bytes = axum::body::to_bytes(body, usize::MAX) .await @@ -744,9 +729,9 @@ fn apply_provider_response_headers( response_headers: &[ProviderResponseHeader], ) -> Response { let connection_options = - crate::openai::responses::response_connection_options(response_headers); + crate::data_plane::responses::response_connection_options(response_headers); for header in response_headers { - if !crate::openai::responses::response_header_is_forwardable( + if !crate::data_plane::responses::response_header_is_forwardable( header.name(), &connection_options, ) { @@ -768,7 +753,7 @@ fn response_headers( streaming: bool, ) -> Vec { let connection_options = - crate::openai::responses::response_connection_options(provider_headers); + crate::data_plane::responses::response_connection_options(provider_headers); let mut headers = Vec::new(); headers.push(MiddlewareHeader::new( CONTENT_TYPE.as_str(), @@ -779,7 +764,7 @@ fn response_headers( }), )); for header in provider_headers { - if !crate::openai::responses::response_header_is_forwardable( + if !crate::data_plane::responses::response_header_is_forwardable( header.name(), &connection_options, ) || header.name().eq_ignore_ascii_case(CONTENT_TYPE.as_str()) @@ -799,7 +784,7 @@ fn response_headers( struct StreamingExecutionBody { session: Option>, encoder: GenerationEncoder, - protocol: GenerationProtocol, + protocol: GenerationEndpoint, validation: GenerationValidationFacts, pending: VecDeque, awaiting_terminal_eof: bool, @@ -815,7 +800,7 @@ impl StreamingExecutionBody { session: Box, connection_guard: Option>, validation: GenerationValidationFacts, - protocol: GenerationProtocol, + protocol: GenerationEndpoint, ) -> Self { Self { session: Some(session), @@ -1058,7 +1043,7 @@ impl Drop for StreamingExecutionBody { } } -fn done_frame(protocol: GenerationProtocol) -> MiddlewareFrame { +fn done_frame(protocol: GenerationEndpoint) -> MiddlewareFrame { MiddlewareFrame::new(protocol.terminal_bytes(), MiddlewareFraming::SseEvent, true) } diff --git a/backend/crates/gateway-api/src/openai/responses/keepalive.rs b/backend/crates/gateway-api/src/data_plane/generation/keepalive.rs similarity index 95% rename from backend/crates/gateway-api/src/openai/responses/keepalive.rs rename to backend/crates/gateway-api/src/data_plane/generation/keepalive.rs index 3058df35f..18b4b526b 100644 --- a/backend/crates/gateway-api/src/openai/responses/keepalive.rs +++ b/backend/crates/gateway-api/src/data_plane/generation/keepalive.rs @@ -1,4 +1,4 @@ -//! 准入成功后覆盖 Responses 首帧等待;已发心跳的 HTTP 错误转为流内失败 +//! 准入成功后为流式生成发送首帧前心跳,按入口协议编码随后的失败 use std::future::Future; @@ -16,16 +16,16 @@ use gateway_protocol::openai::sse::{ use serde_json::Value; use tokio::sync::oneshot; -use crate::openai::middleware::{SSE_KEEPALIVE_FRAME, SSE_KEEPALIVE_INTERVAL}; +use crate::data_plane::middleware::{SSE_KEEPALIVE_FRAME, SSE_KEEPALIVE_INTERVAL}; -pub(in crate::openai) async fn response( +pub(in crate::data_plane) async fn response( response: impl Future + Send + 'static, admitted: oneshot::Receiver, ) -> Response { response_with_encoder(response, admitted, None, true).await } -pub(in crate::openai) async fn response_with_encoder( +pub(in crate::data_plane) async fn response_with_encoder( response: impl Future + Send + 'static, admitted: oneshot::Receiver, error_encoder: Option Bytes>, diff --git a/backend/crates/gateway-api/src/data_plane/generation/mod.rs b/backend/crates/gateway-api/src/data_plane/generation/mod.rs new file mode 100644 index 000000000..c41b4d37a --- /dev/null +++ b/backend/crates/gateway-api/src/data_plane/generation/mod.rs @@ -0,0 +1,97 @@ +//! 生成与计数协议共用的解码事实和 HTTP 执行边界 + +pub(crate) mod http; +mod keepalive; +mod request; +mod response; +mod validation; + +pub(crate) use http::{ + GenerationHttpRequest, HttpResponseAdapter, ResponseAuthorization, execute_prepared_generation, +}; +pub use request::{ContinuationIntent, DecodedGenerationRequest, GenerationRequestMetadata}; + +use axum::http::HeaderMap; +use gateway_core::operation::OperationKind; +use gateway_protocol::anthropic::ANTHROPIC_PROTOCOL; +use gateway_protocol::openai::OPENAI_PROTOCOL; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum GenerationEndpoint { + Responses, + Messages, + MessageTokenCount, + GenAi, + GenAiTokenCount, +} + +impl GenerationEndpoint { + pub(crate) fn input(self, request: DecodedGenerationRequest) -> GenerationInput { + GenerationInput { + endpoint: self, + model: request.metadata.requested_model, + stream: request.metadata.stream, + } + } + + pub(crate) const fn wire(self) -> &'static str { + match self { + Self::Responses => OPENAI_PROTOCOL, + Self::GenAi | Self::GenAiTokenCount => gateway_protocol::genai::GENAI_PROTOCOL, + Self::Messages | Self::MessageTokenCount => ANTHROPIC_PROTOCOL, + } + } + + pub(crate) const fn path(self) -> &'static str { + match self { + Self::Responses => super::router::RESPONSES_PATH, + Self::GenAi | Self::GenAiTokenCount => super::genai::MODEL_ACTION_PATH, + Self::Messages => super::router::MESSAGES_PATH, + Self::MessageTokenCount => super::router::MESSAGE_TOKENS_PATH, + } + } + + pub(crate) const fn operation(self) -> OperationKind { + match self { + Self::Responses | Self::Messages | Self::GenAi => OperationKind::Generate, + Self::MessageTokenCount | Self::GenAiTokenCount => OperationKind::CountTokens, + } + } +} + +pub(crate) struct GenerationInput { + pub(super) endpoint: GenerationEndpoint, + pub(super) model: String, + pub(super) stream: bool, +} + +impl GenerationInput { + fn decode( + &self, + body: &axum::body::Bytes, + headers: &HeaderMap, + maximum: usize, + ) -> Result { + use gateway_core::engine::middleware::MiddlewareError; + match self.endpoint { + GenerationEndpoint::GenAi | GenerationEndpoint::GenAiTokenCount => { + super::genai::decode( + &self.model, + self.stream, + self.endpoint, + body.clone(), + headers, + ) + .map_err(MiddlewareError::Gateway) + } + GenerationEndpoint::Responses => { + super::responses::decode_request_with_headers(body, headers, maximum) + .map_err(|_| MiddlewareError::Rejected) + } + GenerationEndpoint::Messages | GenerationEndpoint::MessageTokenCount => { + super::messages::decode_request(body, headers, maximum, self.endpoint) + .map_err(|_| MiddlewareError::Rejected) + } + } + } +} diff --git a/backend/crates/gateway-api/src/openai/generation/request.rs b/backend/crates/gateway-api/src/data_plane/generation/request.rs similarity index 90% rename from backend/crates/gateway-api/src/openai/generation/request.rs rename to backend/crates/gateway-api/src/data_plane/generation/request.rs index e860da227..931ca2e51 100644 --- a/backend/crates/gateway-api/src/openai/generation/request.rs +++ b/backend/crates/gateway-api/src/data_plane/generation/request.rs @@ -35,12 +35,12 @@ impl fmt::Debug for ContinuationIntent { /// Handler、Router 和 history owner 使用的请求元数据 #[derive(Clone, PartialEq, Eq)] pub struct GenerationRequestMetadata { - pub(in crate::openai) requested_model: String, - pub(in crate::openai) stream: bool, - pub(in crate::openai) store: bool, - pub(in crate::openai) continuation: ContinuationIntent, - pub(in crate::openai) client_ip: Option, - pub(in crate::openai) user_agent: Option, + pub(in crate::data_plane) requested_model: String, + pub(in crate::data_plane) stream: bool, + pub(in crate::data_plane) store: bool, + pub(in crate::data_plane) continuation: ContinuationIntent, + pub(in crate::data_plane) client_ip: Option, + pub(in crate::data_plane) user_agent: Option, } impl GenerationRequestMetadata { @@ -98,8 +98,8 @@ impl fmt::Debug for GenerationRequestMetadata { /// 一次成功解码的生成或计数请求 #[derive(Clone, PartialEq)] pub struct DecodedGenerationRequest { - pub(in crate::openai) operation: Operation, - pub(in crate::openai) metadata: GenerationRequestMetadata, + pub(in crate::data_plane) operation: Operation, + pub(in crate::data_plane) metadata: GenerationRequestMetadata, } impl DecodedGenerationRequest { diff --git a/backend/crates/gateway-api/src/openai/generation/response.rs b/backend/crates/gateway-api/src/data_plane/generation/response.rs similarity index 62% rename from backend/crates/gateway-api/src/openai/generation/response.rs rename to backend/crates/gateway-api/src/data_plane/generation/response.rs index 3ed3126ab..2eb6f02e0 100644 --- a/backend/crates/gateway-api/src/openai/generation/response.rs +++ b/backend/crates/gateway-api/src/data_plane/generation/response.rs @@ -11,8 +11,8 @@ use gateway_protocol::{ }; use serde_json::{Value, json}; -use super::GenerationProtocol; -use crate::openai::{ +use super::GenerationEndpoint; +use crate::data_plane::{ error::gateway_error_contract, messages, responses::{OpenAiResponsesEncoder, ResponseEncodeError}, @@ -20,6 +20,9 @@ use crate::openai::{ pub(super) enum GenerationEncoder { Responses(OpenAiResponsesEncoder), + GenAi { + failed: bool, + }, Messages { response_id: Option, completed: bool, @@ -28,10 +31,13 @@ pub(super) enum GenerationEncoder { } impl GenerationEncoder { - pub(super) fn new(protocol: GenerationProtocol) -> Self { + pub(super) fn new(protocol: GenerationEndpoint) -> Self { match protocol { - GenerationProtocol::Responses => Self::Responses(OpenAiResponsesEncoder::new()), - GenerationProtocol::Messages | GenerationProtocol::MessageTokenCount => { + GenerationEndpoint::Responses => Self::Responses(OpenAiResponsesEncoder::new()), + GenerationEndpoint::GenAi | GenerationEndpoint::GenAiTokenCount => { + Self::GenAi { failed: false } + } + GenerationEndpoint::Messages | GenerationEndpoint::MessageTokenCount => { Self::Messages { response_id: None, completed: false, @@ -44,6 +50,27 @@ impl GenerationEncoder { pub(super) fn push_sse(&mut self, event: &ProviderEvent) -> Vec { match self { Self::Responses(encoder) => encoder.push_sse(event), + Self::GenAi { failed } => { + let Some(wire) = event + .wire_event() + .filter(|wire| wire.protocol() == gateway_protocol::genai::GENAI_PROTOCOL) + else { + return Vec::new(); + }; + *failed |= wire.data().get("error").is_some_and(Value::is_object); + if let Some(raw) = wire.raw_sse_frame() { + return vec![raw.clone()]; + } + if !wire.has_json_data() { + return Vec::new(); + } + vec![Bytes::from(encode_sse_event_with_metadata( + wire.event_type().unwrap_or_default(), + &wire.data().to_string(), + wire.sse_id(), + wire.sse_retry(), + ))] + } Self::Messages { response_id, completed, @@ -114,6 +141,8 @@ impl GenerationEncoder { pub(super) fn is_completed(&self) -> bool { match self { Self::Responses(encoder) => encoder.is_completed(), + // 原生 GenAI 以 EOF 结束,finishReason 后仍可收到独立用量帧 + Self::GenAi { .. } => false, Self::Messages { completed, .. } => *completed, } } @@ -121,7 +150,7 @@ impl GenerationEncoder { pub(super) fn has_wire_failure(&self) -> bool { match self { Self::Responses(encoder) => encoder.has_wire_failure(), - Self::Messages { failed, .. } => *failed, + Self::Messages { failed, .. } | Self::GenAi { failed } => *failed, } } @@ -134,6 +163,9 @@ impl GenerationEncoder { crate::client_error::client_error_code(error.client_error_code().unwrap_or(code)), error.client_message(), )), + Self::GenAi { .. } => { + crate::data_plane::genai::error_frame(status, error.client_message()) + } Self::Messages { .. } => { let value = messages::error_payload( &json!({"error":{"message":error.client_message()}}), @@ -145,22 +177,77 @@ impl GenerationEncoder { } } -impl GenerationProtocol { +impl GenerationEndpoint { + pub(super) const fn stream_error_encoder(self) -> Option Bytes> { + match self { + Self::Responses => None, + Self::GenAi | Self::GenAiTokenCount => Some(crate::data_plane::genai::stream_error), + Self::Messages | Self::MessageTokenCount => Some(messages::stream_error), + } + } + + pub(super) async fn project_error_response( + self, + response: axum::response::Response, + ) -> axum::response::Response { + match self { + Self::Responses => response, + Self::GenAi | Self::GenAiTokenCount => { + crate::data_plane::genai::project_error_response(response).await + } + Self::Messages | Self::MessageTokenCount => { + messages::project_error_response(response).await + } + } + } + pub(super) fn terminal_bytes(self) -> Bytes { match self { Self::Responses => Bytes::from_static(DONE_SSE_FRAME.as_bytes()), // Messages 的 message_stop 已在 wire 中交付,空帧只确认宿主交付终结 - Self::Messages | Self::MessageTokenCount => Bytes::new(), + Self::Messages | Self::MessageTokenCount | Self::GenAi | Self::GenAiTokenCount => { + Bytes::new() + } } } pub(super) fn collect(self, events: &[ProviderEvent]) -> Result, ResponseEncodeError> { if self == Self::Responses { - return serde_json::to_vec(&crate::openai::responses::response::collect_response( + return serde_json::to_vec(&crate::data_plane::responses::response::collect_response( events, )?) .map_err(|_| ResponseEncodeError::Serialization); } + if matches!(self, Self::GenAi | Self::GenAiTokenCount) { + let mut wires = events + .iter() + .filter_map(ProviderEvent::wire_event) + .filter(|wire| wire.protocol() == self.wire()); + let wire = wires + .next() + .ok_or(ResponseEncodeError::MissingWireTerminal)?; + if wires.next().is_some() { + return Err(ResponseEncodeError::InvalidOutputItems); + } + if let Some(raw) = wire.raw_json_body() { + if self == Self::GenAiTokenCount { + super::validation::GenerationValidationFacts::new(self) + .validate_buffered(raw) + .map_err(|_| ResponseEncodeError::InvalidOutputItems)?; + } + return Ok(raw.to_vec()); + } + if self == Self::GenAiTokenCount + && wire + .data() + .get("totalTokens") + .and_then(Value::as_u64) + .is_none() + { + return Err(ResponseEncodeError::InvalidOutputItems); + } + return serde_json::to_vec(wire.data()).map_err(|_| ResponseEncodeError::Serialization); + } let mut accumulator = MessagesAccumulator::default(); let mut response = None; for wire in events diff --git a/backend/crates/gateway-api/src/openai/generation/validation.rs b/backend/crates/gateway-api/src/data_plane/generation/validation.rs similarity index 68% rename from backend/crates/gateway-api/src/openai/generation/validation.rs rename to backend/crates/gateway-api/src/data_plane/generation/validation.rs index ec085d3a6..3fa2a6976 100644 --- a/backend/crates/gateway-api/src/openai/generation/validation.rs +++ b/backend/crates/gateway-api/src/data_plane/generation/validation.rs @@ -2,12 +2,13 @@ use gateway_core::event::ProviderEvent; use gateway_protocol::anthropic::ANTHROPIC_PROTOCOL; +use gateway_protocol::genai::GenerateContentObservation; use gateway_protocol::openai::sse::parse_sse_events; use serde_json::Value; use std::sync::{Arc, Mutex}; -use super::GenerationProtocol; -use crate::openai::responses::validation::{ +use super::GenerationEndpoint; +use crate::data_plane::responses::validation::{ ResponseValidationFacts, ResponsesDeliveryValidator, validate_buffered_response, }; @@ -15,15 +16,18 @@ use crate::openai::responses::validation::{ pub(super) enum GenerationValidationFacts { Responses(ResponseValidationFacts), Messages(Arc>>), - Count, + Count(&'static str), + GenAi, } impl GenerationValidationFacts { - pub(super) fn new(protocol: GenerationProtocol) -> Self { + pub(super) fn new(protocol: GenerationEndpoint) -> Self { match protocol { - GenerationProtocol::Responses => Self::Responses(ResponseValidationFacts::default()), - GenerationProtocol::Messages => Self::Messages(Arc::default()), - GenerationProtocol::MessageTokenCount => Self::Count, + GenerationEndpoint::Responses => Self::Responses(ResponseValidationFacts::default()), + GenerationEndpoint::Messages => Self::Messages(Arc::default()), + GenerationEndpoint::MessageTokenCount => Self::Count("input_tokens"), + GenerationEndpoint::GenAiTokenCount => Self::Count("totalTokens"), + GenerationEndpoint::GenAi => Self::GenAi, } } @@ -44,7 +48,7 @@ impl GenerationValidationFacts { *id = Some(value.to_owned()); } } - Self::Count => {} + Self::Count(_) | Self::GenAi => {} } } @@ -69,7 +73,7 @@ impl GenerationValidationFacts { match self { Self::Responses(facts) => facts.response_id(), Self::Messages(id) => id.lock().ok().and_then(|id| id.clone()), - Self::Count => None, + Self::Count(_) | Self::GenAi => None, } } @@ -87,9 +91,21 @@ impl GenerationValidationFacts { } Ok(()) } - Self::Count => serde_json::from_slice::(bytes) + Self::GenAi => { + let value: Value = serde_json::from_slice(bytes).map_err(|_| ())?; + let mut observation = GenerateContentObservation::default(); + observation.observe(&value); + if value.get("error").is_some_and(Value::is_object) + || observation.finish().is_some() + { + Ok(()) + } else { + Err(()) + } + } + Self::Count(field) => serde_json::from_slice::(bytes) .ok() - .and_then(|value| value.get("input_tokens").and_then(Value::as_u64)) + .and_then(|value| value.get(*field).and_then(Value::as_u64)) .map(|_| ()) .ok_or(()), } @@ -98,13 +114,24 @@ impl GenerationValidationFacts { pub(super) enum GenerationDeliveryValidator { Responses(ResponsesDeliveryValidator), - Messages { id: Option, finished: bool }, + Messages { + id: Option, + finished: bool, + }, + GenAi { + observation: GenerateContentObservation, + failed: bool, + }, } impl GenerationDeliveryValidator { - pub(super) fn new(protocol: GenerationProtocol) -> Self { + pub(super) fn new(protocol: GenerationEndpoint) -> Self { match protocol { - GenerationProtocol::Responses => Self::Responses(ResponsesDeliveryValidator::default()), + GenerationEndpoint::Responses => Self::Responses(ResponsesDeliveryValidator::default()), + GenerationEndpoint::GenAi => Self::GenAi { + observation: GenerateContentObservation::default(), + failed: false, + }, _ => Self::Messages { id: None, finished: false, @@ -116,6 +143,7 @@ impl GenerationDeliveryValidator { match self { Self::Responses(validator) => validator.response_id(), Self::Messages { id, .. } => id.as_deref(), + Self::GenAi { .. } => None, } } @@ -129,6 +157,32 @@ impl GenerationDeliveryValidator { (Self::Responses(validator), GenerationValidationFacts::Responses(facts)) => validator .validate_frame(bytes, transformed, facts) .map_err(|_| ()), + ( + Self::GenAi { + observation, + failed, + }, + GenerationValidationFacts::GenAi, + ) => { + if bytes.is_empty() { + return if *failed || observation.finish().is_some() { + Ok(()) + } else { + Err(()) + }; + } + for event in + parse_sse_events(std::str::from_utf8(bytes).map_err(|_| ())?).map_err(|_| ())? + { + let value: Value = serde_json::from_str(&event.data).map_err(|_| ())?; + if !value.is_object() { + return Err(()); + } + *failed |= value.get("error").is_some_and(Value::is_object); + observation.observe(&value); + } + Ok(()) + } (Self::Messages { id, finished }, GenerationValidationFacts::Messages(_)) => { if bytes.is_empty() { return if *finished { Ok(()) } else { Err(()) }; @@ -182,6 +236,10 @@ impl GenerationDeliveryValidator { match self { Self::Responses(validator) => validator.finish_delivery().map_err(|_| ()), Self::Messages { finished: true, .. } => Ok(()), + Self::GenAi { + observation, + failed, + } if *failed || observation.finish().is_some() => Ok(()), _ => Err(()), } } diff --git a/backend/crates/gateway-api/src/openai/images/http.rs b/backend/crates/gateway-api/src/data_plane/images/http.rs similarity index 93% rename from backend/crates/gateway-api/src/openai/images/http.rs rename to backend/crates/gateway-api/src/data_plane/images/http.rs index 45330a292..7e0b2222e 100644 --- a/backend/crates/gateway-api/src/openai/images/http.rs +++ b/backend/crates/gateway-api/src/data_plane/images/http.rs @@ -1,5 +1,6 @@ //! Codex Images 非流式 HTTP adapter +use crate::request_context::request_client_context; use std::net::SocketAddr; use axum::{ @@ -17,14 +18,14 @@ use gateway_protocol::openai::OPENAI_PROTOCOL; use serde_json::Value; use crate::ApiState; -use crate::middleware::headers::encode_headers; -use crate::openai::middleware::RequestInput; -use crate::openai::{ +use crate::data_plane::middleware::RequestInput; +use crate::data_plane::{ auth::{ClientKeyHeaders, authenticate_client, client_access_error_response}, - endpoint::provider_endpoint_response, - responses::{OpenAiRequestHeaders, request_client_context}, + openai_endpoints::provider_endpoint_response, + responses::OpenAiRequestHeaders, router::{IMAGE_EDITS_PATH, IMAGE_GENERATIONS_PATH}, }; +use crate::middleware::headers::encode_headers; const IMAGE_TURN_ID_CONTEXT_KEY: &str = "image_turn_id"; @@ -72,7 +73,7 @@ async fn handle_image_request( kind: ImageRequestKind, endpoint: &'static str, ) -> Response { - let service = state.openai(); + let service = state.data_plane(); let client = match authenticate_client(service, &headers, ClientKeyHeaders::Bearer).await { Ok(client) => client, Err(error) => return client_access_error_response(error), diff --git a/backend/crates/gateway-api/src/openai/images/mod.rs b/backend/crates/gateway-api/src/data_plane/images/mod.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/images/mod.rs rename to backend/crates/gateway-api/src/data_plane/images/mod.rs diff --git a/backend/crates/gateway-api/src/openai/images/request.rs b/backend/crates/gateway-api/src/data_plane/images/request.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/images/request.rs rename to backend/crates/gateway-api/src/data_plane/images/request.rs diff --git a/backend/crates/gateway-api/src/openai/live/http.rs b/backend/crates/gateway-api/src/data_plane/live/http.rs similarity index 98% rename from backend/crates/gateway-api/src/openai/live/http.rs rename to backend/crates/gateway-api/src/data_plane/live/http.rs index 462d2aeac..fe5f1f976 100644 --- a/backend/crates/gateway-api/src/openai/live/http.rs +++ b/backend/crates/gateway-api/src/data_plane/live/http.rs @@ -1,5 +1,6 @@ //! Live 通话引导(`POST /v1/live`)与 hangup 的 HTTP adapter。 +use crate::request_context::request_client_context; use std::net::SocketAddr; use axum::{ @@ -23,11 +24,10 @@ use super::{ }; use crate::{ ApiState, - openai::{ + data_plane::{ auth::{ClientKeyHeaders, authenticate_client, client_access_error_response}, error::{engine_error_response, gateway_error_response}, middleware::PendingExecution, - responses::request_client_context, with_model_request_id, }, }; @@ -39,7 +39,7 @@ pub(crate) async fn live_call( headers: HeaderMap, request: Request, ) -> Response { - let service = state.openai(); + let service = state.data_plane(); let client = match authenticate_client(service, &headers, ClientKeyHeaders::Bearer).await { Ok(client) => client, Err(error) => return client_access_error_response(error), @@ -91,7 +91,7 @@ pub(crate) async fn live_call( }; let request_id = prepared.request_id().clone(); let started = match service - .start_prepared_provider_endpoint( + .start_openai_endpoint( prepared, Operation::ProviderHttp(operation), Some(upstream_model_id), @@ -113,7 +113,7 @@ pub(crate) async fn hangup( headers: HeaderMap, body: Bytes, ) -> Response { - let service = state.openai(); + let service = state.data_plane(); let client = match authenticate_client(service, &headers, ClientKeyHeaders::Bearer).await { Ok(client) => client, Err(error) => return client_access_error_response(error), diff --git a/backend/crates/gateway-api/src/openai/live/mod.rs b/backend/crates/gateway-api/src/data_plane/live/mod.rs similarity index 99% rename from backend/crates/gateway-api/src/openai/live/mod.rs rename to backend/crates/gateway-api/src/data_plane/live/mod.rs index 5293767cf..03964290c 100644 --- a/backend/crates/gateway-api/src/openai/live/mod.rs +++ b/backend/crates/gateway-api/src/data_plane/live/mod.rs @@ -23,7 +23,7 @@ use gateway_core::operation::{ use gateway_protocol::openai::OPENAI_PROTOCOL; use serde_json::{Value, json}; -use crate::openai::error::openai_error_response; +use crate::data_plane::error::openai_error_response; pub(crate) use http::{hangup, live_call}; pub(crate) use websocket::{realtime_get, sideband}; diff --git a/backend/crates/gateway-api/src/openai/live/websocket.rs b/backend/crates/gateway-api/src/data_plane/live/websocket.rs similarity index 99% rename from backend/crates/gateway-api/src/openai/live/websocket.rs rename to backend/crates/gateway-api/src/data_plane/live/websocket.rs index 6d8489229..2cc137a01 100644 --- a/backend/crates/gateway-api/src/openai/live/websocket.rs +++ b/backend/crates/gateway-api/src/data_plane/live/websocket.rs @@ -21,7 +21,7 @@ use gateway_core::live::{LiveClose, LiveFrame, LiveRelay, LiveSidebandRequest, L use super::LiveErrorShape; use crate::{ ApiState, - openai::{ + data_plane::{ auth::{ClientKeyHeaders, authenticate_client, client_access_error_response}, error::runtime_unavailable_response, live::{ @@ -109,7 +109,7 @@ async fn open_sideband( let Ok(upgrade) = upgrade else { return upgrade_required_response(); }; - let service = state.openai(); + let service = state.data_plane(); let client = match authenticate_client(service, &headers, ClientKeyHeaders::Bearer).await { Ok(client) => client, Err(error) => return client_access_error_response(error), diff --git a/backend/crates/gateway-api/src/openai/messages.rs b/backend/crates/gateway-api/src/data_plane/messages.rs similarity index 95% rename from backend/crates/gateway-api/src/openai/messages.rs rename to backend/crates/gateway-api/src/data_plane/messages.rs index f3c7d0021..0aba6437c 100644 --- a/backend/crates/gateway-api/src/openai/messages.rs +++ b/backend/crates/gateway-api/src/data_plane/messages.rs @@ -17,12 +17,13 @@ use serde_json::{Value, json}; use super::{ auth::{ClientKeyHeaders, authenticate_client, client_access_error_response}, + body::decompress_request_body, error::gateway_error_response, generation::{ - ContinuationIntent, DecodedGenerationRequest, GenerationHttpRequest, GenerationProtocol, + ContinuationIntent, DecodedGenerationRequest, GenerationEndpoint, GenerationHttpRequest, GenerationRequestMetadata, execute_prepared_generation, }, - responses::{OpenAiRequestHeaders, decompress_request_body}, + responses::OpenAiRequestHeaders, }; use crate::ApiState; @@ -39,7 +40,7 @@ pub(super) async fn messages( ingress_id, headers, body, - GenerationProtocol::Messages, + GenerationEndpoint::Messages, ) .await } @@ -57,7 +58,7 @@ pub(super) async fn count_tokens( ingress_id, headers, body, - GenerationProtocol::MessageTokenCount, + GenerationEndpoint::MessageTokenCount, ) .await } @@ -68,9 +69,9 @@ async fn execute( ingress_id: Option>, mut headers: HeaderMap, body: Bytes, - protocol: GenerationProtocol, + protocol: GenerationEndpoint, ) -> Response { - let service = state.openai().clone(); + let service = state.data_plane().clone(); let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Anthropic).await { Ok(client) => client, Err(error) => return project_error_response(client_access_error_response(error)).await, @@ -103,7 +104,7 @@ async fn execute( peer_address: connect_info.map(|Extension(ConnectInfo(address))| address), ingress_id, headers, - decoded, + input: protocol.input(decoded), middleware_body: body, }, None, @@ -116,7 +117,7 @@ pub(super) fn decode_request( body: &[u8], headers: &HeaderMap, maximum: usize, - protocol: GenerationProtocol, + protocol: GenerationEndpoint, ) -> Result { let invalid = |message| GatewayError::new(GatewayErrorKind::InvalidRequest, message); let body = decompress_request_body(body, headers, maximum) @@ -125,7 +126,7 @@ pub(super) fn decode_request( .ok() .and_then(|value| value.as_object().cloned()) .ok_or_else(|| invalid("Request body must be a JSON object."))?; - let counted = protocol == GenerationProtocol::MessageTokenCount; + let counted = protocol == GenerationEndpoint::MessageTokenCount; let validation = if counted { anthropic::validate_count_request(&object) } else { diff --git a/backend/crates/gateway-api/src/openai/middleware/http.rs b/backend/crates/gateway-api/src/data_plane/middleware/http.rs similarity index 99% rename from backend/crates/gateway-api/src/openai/middleware/http.rs rename to backend/crates/gateway-api/src/data_plane/middleware/http.rs index 6064cfe4f..ff7652a3a 100644 --- a/backend/crates/gateway-api/src/openai/middleware/http.rs +++ b/backend/crates/gateway-api/src/data_plane/middleware/http.rs @@ -1,9 +1,9 @@ //! 未提交响应的 HTTP 交付;只验证协议边界,不解释或重算 Core 的业务事实 -use crate::middleware::headers::{decode_headers, encode_headers}; -use crate::openai::error::{ +use crate::data_plane::error::{ gateway_error_from_engine, gateway_error_response, openai_error_response, }; +use crate::middleware::headers::{decode_headers, encode_headers}; use axum::{ body::Body, http::{HeaderMap, HeaderValue, StatusCode, header}, diff --git a/backend/crates/gateway-api/src/openai/middleware/mod.rs b/backend/crates/gateway-api/src/data_plane/middleware/mod.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/middleware/mod.rs rename to backend/crates/gateway-api/src/data_plane/middleware/mod.rs diff --git a/backend/crates/gateway-api/src/openai/middleware/request.rs b/backend/crates/gateway-api/src/data_plane/middleware/request.rs similarity index 99% rename from backend/crates/gateway-api/src/openai/middleware/request.rs rename to backend/crates/gateway-api/src/data_plane/middleware/request.rs index 3f72d811c..66fef228d 100644 --- a/backend/crates/gateway-api/src/openai/middleware/request.rs +++ b/backend/crates/gateway-api/src/data_plane/middleware/request.rs @@ -2,7 +2,7 @@ use crate::middleware::headers::{decode_headers, encode_headers}; -use crate::openai::error::gateway_error_response; +use crate::data_plane::error::gateway_error_response; use axum::{http::HeaderMap, response::Response}; use bytes::Bytes; use futures::future::BoxFuture; diff --git a/backend/crates/gateway-api/src/openai/middleware/session.rs b/backend/crates/gateway-api/src/data_plane/middleware/session.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/middleware/session.rs rename to backend/crates/gateway-api/src/data_plane/middleware/session.rs diff --git a/backend/crates/gateway-api/src/openai/mod.rs b/backend/crates/gateway-api/src/data_plane/mod.rs similarity index 89% rename from backend/crates/gateway-api/src/openai/mod.rs rename to backend/crates/gateway-api/src/data_plane/mod.rs index da031951f..267d78cb4 100644 --- a/backend/crates/gateway-api/src/openai/mod.rs +++ b/backend/crates/gateway-api/src/data_plane/mod.rs @@ -1,16 +1,19 @@ -//! OpenAI 客户端协议 adapter +//! 模型数据面的客户端入口、鉴权与协议交付 pub mod auth; +pub mod body; mod chat_completions; -mod endpoint; pub mod error; -pub(crate) mod generation; +pub(crate) mod genai; +pub mod generation; pub mod images; pub(crate) mod live; mod messages; pub(crate) mod middleware; pub mod models; +mod openai_endpoints; mod peer_link; +mod provider_endpoints; pub mod responses; pub mod router; pub mod search; diff --git a/backend/crates/gateway-api/src/openai/models.rs b/backend/crates/gateway-api/src/data_plane/models.rs similarity index 98% rename from backend/crates/gateway-api/src/openai/models.rs rename to backend/crates/gateway-api/src/data_plane/models.rs index aa7e8aa83..ceb73c5ba 100644 --- a/backend/crates/gateway-api/src/openai/models.rs +++ b/backend/crates/gateway-api/src/data_plane/models.rs @@ -16,7 +16,7 @@ use serde_json::{Value, json}; use crate::{ ApiState, - openai::middleware::{self, RequestInput}, + data_plane::middleware::{self, RequestInput}, }; use super::{ @@ -43,7 +43,7 @@ pub(crate) async fn models( headers: HeaderMap, ) -> Response { let anthropic = headers.contains_key("anthropic-version") || headers.contains_key("x-api-key"); - let service = state.openai(); + let service = state.data_plane(); let client = match authenticate_client(service, &headers, ClientKeyHeaders::Anthropic).await { Ok(client) => client, Err(error) => { @@ -68,7 +68,7 @@ async fn models_response( query: ModelsQuery, anthropic: bool, ) -> Response { - let service = state.openai(); + let service = state.data_plane(); if anthropic { return anthropic_models_response(service.public_models(&client), &query); @@ -166,7 +166,7 @@ pub(crate) async fn model_detail( Path(model_id): Path, ) -> Response { let anthropic = headers.contains_key("anthropic-version") || headers.contains_key("x-api-key"); - let service = state.openai(); + let service = state.data_plane(); let client = match authenticate_client(service, &headers, ClientKeyHeaders::Anthropic).await { Ok(client) => client, Err(error) => { @@ -197,7 +197,7 @@ fn model_detail_response( model_id: String, anthropic: bool, ) -> Response { - let service = state.openai(); + let service = state.data_plane(); let Ok(public_model) = PublicModelId::new(model_id) else { return model_not_found_response().into_response(); }; diff --git a/backend/crates/gateway-api/src/openai/endpoint.rs b/backend/crates/gateway-api/src/data_plane/openai_endpoints.rs similarity index 82% rename from backend/crates/gateway-api/src/openai/endpoint.rs rename to backend/crates/gateway-api/src/data_plane/openai_endpoints.rs index 1fa6bf03c..bce0fafe8 100644 --- a/backend/crates/gateway-api/src/openai/endpoint.rs +++ b/backend/crates/gateway-api/src/data_plane/openai_endpoints.rs @@ -16,30 +16,70 @@ use axum::{ }; use gateway_core::{ engine::{ - execution::{AuthenticatedClient, StartedExecution}, + execution::{ + AuthenticatedClient, ClientTransport, ExecutionRequestMetadata, PreparedRootExecution, + StartedExecution, + }, middleware::{MiddlewareError, MiddlewareFrame, MiddlewareFraming, MiddlewareResponse}, }, - error::GatewayError, + error::{GatewayError, GatewayErrorKind}, operation::Operation, + routing::{ProviderKind, UpstreamModelId}, }; use gateway_protocol::openai::OPENAI_PROTOCOL; use crate::client_error::{ProtocolError, ProtocolErrorBody}; -use crate::middleware::headers::encode_headers; -use crate::openai::middleware::{ +use crate::data_plane::middleware::{ ExpectedBody, PendingExecution, RequestInput, buffered_response, error_response, into_http_response, invoke_request, pending_execution_response, request_parts, }; +use crate::middleware::headers::encode_headers; use gateway_core::event::{ProviderEvent, ProviderResponseHeader}; use super::{ error::{engine_error_response, gateway_error_response, protocol_error_response}, - service::OpenAiService, + service::DataPlaneService, }; +impl DataPlaneService { + pub(super) async fn start_openai_endpoint( + &self, + prepared: PreparedRootExecution, + operation: gateway_core::operation::Operation, + upstream_model: Option, + client_ip: Option, + user_agent: Option, + endpoint: String, + ) -> Result { + let provider = ProviderKind::new("openai").map_err(|_| { + GatewayError::new( + GatewayErrorKind::Internal, + "OpenAI provider identifier is invalid.", + ) + })?; + self.execution() + .start_prepared_provider_endpoint( + prepared, + provider, + upstream_model, + operation, + ExecutionRequestMetadata { + protocol: OPENAI_PROTOCOL.to_owned(), + endpoint, + transport: ClientTransport::HttpJson, + stream: false, + client_ip, + user_agent, + previous_response_id: None, + }, + ) + .await + } +} + /// Provider 自有端点也先冻结身份,再通过统一请求链进入原有执行与结算路径 pub(super) async fn provider_endpoint_response( - service: OpenAiService, + service: DataPlaneService, client: AuthenticatedClient, input: RequestInput, client_ip: Option, @@ -72,7 +112,7 @@ where let operation = request.apply_capabilities(decode(body, headers).await?)?; terminal_entered.store(true, Ordering::Relaxed); let started = match service - .start_prepared_provider_endpoint( + .start_openai_endpoint( prepared, operation, // 原生端点的模型语义由 Provider 从正文提取并检查账号政策 None, client_ip, user_agent, endpoint, diff --git a/backend/crates/gateway-api/src/openai/peer_link/mod.rs b/backend/crates/gateway-api/src/data_plane/peer_link/mod.rs similarity index 94% rename from backend/crates/gateway-api/src/openai/peer_link/mod.rs rename to backend/crates/gateway-api/src/data_plane/peer_link/mod.rs index 495b4f153..a4790bf6b 100644 --- a/backend/crates/gateway-api/src/openai/peer_link/mod.rs +++ b/backend/crates/gateway-api/src/data_plane/peer_link/mod.rs @@ -21,9 +21,8 @@ use super::{ error::{missing_client_api_key_response, openai_error_response}, }; use crate::{ - ApiState, - auth::SessionState as _, - openai::middleware::{self as plugin_middleware, RequestInput}, + ApiState, SessionState as _, + data_plane::middleware::{self as plugin_middleware, RequestInput}, }; pub(super) fn router() -> Router { @@ -37,12 +36,12 @@ pub(super) fn router() -> Router { struct PeerQuery {} async fn peer_link(State(state): State, headers: HeaderMap, uri: Uri) -> Response { - let client = match verify_client(state.openai(), &headers).await { + let client = match verify_client(state.data_plane(), &headers).await { Ok(client) => client, Err(error) => return client_access_error_response(error.into()), }; plugin_middleware::query_response( - state.openai().execution(), + state.data_plane().execution(), client, RequestInput::query(super::router::PEER_LINK_PATH.to_owned(), None, &headers), move |client| peer_response(state, client, uri), diff --git a/backend/crates/gateway-api/src/openai/peer_link/wire.rs b/backend/crates/gateway-api/src/data_plane/peer_link/wire.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/peer_link/wire.rs rename to backend/crates/gateway-api/src/data_plane/peer_link/wire.rs diff --git a/backend/crates/gateway-api/src/provider.rs b/backend/crates/gateway-api/src/data_plane/provider_endpoints.rs similarity index 99% rename from backend/crates/gateway-api/src/provider.rs rename to backend/crates/gateway-api/src/data_plane/provider_endpoints.rs index 2032125ea..0654d0bec 100644 --- a/backend/crates/gateway-api/src/provider.rs +++ b/backend/crates/gateway-api/src/data_plane/provider_endpoints.rs @@ -1,5 +1,6 @@ //! Provider 自有操作的稳定 HTTP adapter +use crate::request_context::request_client_context; use std::net::SocketAddr; use axum::{ @@ -26,11 +27,10 @@ use gateway_core::{ use crate::{ ApiState, - openai::{ + data_plane::{ auth::{ClientKeyHeaders, authenticate_client, client_access_error_response}, error::{engine_error_response, gateway_error_response, openai_error_response}, middleware::PendingExecution, - responses::request_client_context, with_model_request_id, }, }; @@ -66,7 +66,7 @@ async fn count_tokens( headers: HeaderMap, body: Bytes, ) -> Response { - let service = state.openai(); + let service = state.data_plane(); let client = match authenticate_client(service, &headers, ClientKeyHeaders::Bearer).await { Ok(client) => client, Err(error) => return client_access_error_response(error), @@ -131,7 +131,7 @@ async fn provider_http( Method::POST => ProviderHttpMethod::Post, _ => return invalid_request("Provider HTTP method is unsupported."), }; - let service = state.openai(); + let service = state.data_plane(); let client = match authenticate_client(service, &headers, ClientKeyHeaders::Bearer).await { Ok(client) => client, Err(error) => return client_access_error_response(error), diff --git a/backend/crates/gateway-api/src/data_plane/responses/error.rs b/backend/crates/gateway-api/src/data_plane/responses/error.rs new file mode 100644 index 000000000..6eb135bc7 --- /dev/null +++ b/backend/crates/gateway-api/src/data_plane/responses/error.rs @@ -0,0 +1,33 @@ +//! OpenAI Responses adapter 的稳定错误 contract + +use crate::client_error::{ProtocolError, ProtocolErrorBody}; +use thiserror::Error; + +/// OpenAI Responses 原生 wire 转发错误 +#[derive(Debug, Clone, PartialEq, Eq, Error)] +pub enum ResponseEncodeError { + /// 协议原生流缺少可返回的终态 response object + #[error("responses wire stream has no terminal response")] + MissingWireTerminal, + /// 缺少完整终态输出,已交付的完成项也存在缺项或冲突,不能伪造完整结果 + #[error("responses wire stream has inconsistent output items")] + InvalidOutputItems, + /// 终态 response object 无法序列化为完整 HTTP JSON 响应 + #[error("responses wire terminal serialization failed")] + Serialization, +} + +impl ResponseEncodeError { + /// 转换为不包含生成内容的 OpenAI 风格错误 payload + #[must_use] + pub fn protocol_body(&self) -> ProtocolErrorBody { + ProtocolErrorBody { + error: ProtocolError { + kind: "server_error", + code: "invalid_upstream_response", + message: "The gateway could not forward the upstream response.".to_owned(), + param: None, + }, + } + } +} diff --git a/backend/crates/gateway-api/src/openai/responses/http.rs b/backend/crates/gateway-api/src/data_plane/responses/http.rs similarity index 89% rename from backend/crates/gateway-api/src/openai/responses/http.rs rename to backend/crates/gateway-api/src/data_plane/responses/http.rs index 49af3ede2..2f7900bcd 100644 --- a/backend/crates/gateway-api/src/openai/responses/http.rs +++ b/backend/crates/gateway-api/src/data_plane/responses/http.rs @@ -3,10 +3,10 @@ use super::request::decode_request_with_body; use crate::{ ApiState, - openai::{ + data_plane::{ auth::{ClientKeyHeaders, authenticate_client, client_access_error_response}, error::gateway_error_response, - generation::{GenerationHttpRequest, execute_prepared_generation}, + generation::{GenerationEndpoint, GenerationHttpRequest, execute_prepared_generation}, }, }; use axum::{ @@ -25,7 +25,7 @@ pub(crate) async fn responses( headers: HeaderMap, body: Bytes, ) -> Response { - let service = state.openai().clone(); + let service = state.data_plane().clone(); let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await { Ok(client) => client, Err(error) => return client_access_error_response(error), @@ -53,7 +53,7 @@ pub(crate) async fn responses( peer_address: connect_info.map(|Extension(ConnectInfo(address))| address), ingress_id, headers, - decoded, + input: GenerationEndpoint::Responses.input(decoded), middleware_body, }, None, diff --git a/backend/crates/gateway-api/src/openai/responses/mod.rs b/backend/crates/gateway-api/src/data_plane/responses/mod.rs similarity index 67% rename from backend/crates/gateway-api/src/openai/responses/mod.rs rename to backend/crates/gateway-api/src/data_plane/responses/mod.rs index e7366ea4b..00d9aa2b4 100644 --- a/backend/crates/gateway-api/src/openai/responses/mod.rs +++ b/backend/crates/gateway-api/src/data_plane/responses/mod.rs @@ -2,21 +2,17 @@ mod error; mod http; -pub(in crate::openai) mod keepalive; -pub(in crate::openai) mod request; -pub(in crate::openai) mod response; -pub(in crate::openai) mod validation; +pub(in crate::data_plane) mod request; +pub(in crate::data_plane) mod response; +pub(in crate::data_plane) mod validation; pub mod websocket; pub use crate::client_error::{ProtocolError, ProtocolErrorBody}; -pub use crate::openai::generation::http::{collect_execution_response, stream_execution_response}; -pub use crate::openai::generation::{ - ContinuationIntent, DecodedGenerationRequest, GenerationRequestMetadata, +pub use crate::data_plane::generation::http::{ + collect_execution_response, stream_execution_response, }; -pub(crate) use crate::request_context::request_client_context; -pub use error::{RequestDecodeError, ResponseEncodeError}; +pub use error::ResponseEncodeError; pub(crate) use http::responses; -pub(in crate::openai) use request::decompress_request_body; pub use request::{OpenAiRequestHeaders, decode_request_with_headers}; pub(crate) use request::{decode_request_with_body, passthrough_request_headers}; pub use response::OpenAiResponsesEncoder; diff --git a/backend/crates/gateway-api/src/openai/responses/request.rs b/backend/crates/gateway-api/src/data_plane/responses/request.rs similarity index 83% rename from backend/crates/gateway-api/src/openai/responses/request.rs rename to backend/crates/gateway-api/src/data_plane/responses/request.rs index c60fbb650..7ef0ff669 100644 --- a/backend/crates/gateway-api/src/openai/responses/request.rs +++ b/backend/crates/gateway-api/src/data_plane/responses/request.rs @@ -1,6 +1,6 @@ //! OpenAI Responses JSON 到 Core 路由事实与不透明 wire payload 的单一解码边界 -use std::borrow::Cow; +use crate::data_plane::body::decompress_request_body; use axum::http::{HeaderMap, HeaderName, HeaderValue}; use base64::{Engine as _, engine::general_purpose::STANDARD}; @@ -13,8 +13,8 @@ use gateway_protocol::openai::{ }; use serde_json::{Map, Value}; -use super::error::RequestDecodeError; -use crate::openai::generation::{ +use crate::data_plane::body::RequestDecodeError; +use crate::data_plane::generation::{ ContinuationIntent, DecodedGenerationRequest, GenerationRequestMetadata, }; @@ -252,89 +252,6 @@ pub(crate) fn decode_request_with_body( Ok((decoded, Bytes::copy_from_slice(&body))) } -/// zstd 回溯窗口独立于输出上限,调整设置不能放大解码器内部窗口分配 -const MAX_ZSTD_WINDOW_LOG: u32 = 26; - -/// 按 `Content-Encoding` 解压下游请求体 -/// -/// 未压缩与 `identity` 借用原始正文;压缩正文在读取过程中限制展开大小, -/// 避免先完整分配再检查 -/// 只接受单一编码,重复头和叠加编码不能只解释第一项 -pub(in crate::openai) fn decompress_request_body<'a>( - body: &'a [u8], - headers: &HeaderMap, - max_decompressed_bytes: usize, -) -> Result, RequestDecodeError> { - let encoding = headers - .get_all(axum::http::header::CONTENT_ENCODING) - .iter() - .map(|value| { - value - .to_str() - .map_err(|_| RequestDecodeError::MalformedJson) - }) - .collect::, _>>()? - .join(","); - match encoding.trim().to_ascii_lowercase().as_str() { - "" | "identity" => Ok(Cow::Borrowed(body)), - "gzip" => { - let decoder = flate2::read::MultiGzDecoder::new(body); - read_bounded(decoder, max_decompressed_bytes).map(Cow::Owned) - } - "deflate" => { - let decoder = flate2::read::ZlibDecoder::new(body); - read_bounded(decoder, max_decompressed_bytes).map(Cow::Owned) - } - "zstd" => { - let mut decoder = zstd::stream::read::Decoder::with_buffer(body) - .map_err(|_| RequestDecodeError::MalformedJson)?; - // 输出有界之外,也限制压缩帧声明的回溯窗口,防止解码器内部过量分配 - decoder - .window_log_max(MAX_ZSTD_WINDOW_LOG) - .map_err(|_| RequestDecodeError::MalformedJson)?; - read_bounded(decoder, max_decompressed_bytes).map(Cow::Owned) - } - other => Err(RequestDecodeError::UnsupportedContentEncoding { - encoding: other.to_owned(), - }), - } -} - -fn read_bounded( - mut reader: R, - max_decompressed_bytes: usize, -) -> Result, RequestDecodeError> { - let mut decoded = Vec::new(); - let mut chunk = [0; 8192]; - loop { - let remaining = max_decompressed_bytes - decoded.len(); - let read_limit = chunk.len().min(remaining.saturating_add(1)); - let read = reader - .read(&mut chunk[..read_limit]) - .map_err(|_| RequestDecodeError::MalformedJson)?; - if read == 0 { - return Ok(decoded); - } - if read > remaining { - return Err(RequestDecodeError::DecompressedBodyTooLarge { - limit_bytes: max_decompressed_bytes, - }); - } - // 默认 Vec 扩容和 read_to_end 的 EOF 探测可能突破输出上限; - // 容量增长也受相同边界约束,越界探测只使用栈上分块缓冲区 - let required = decoded.len() + read; - if required > decoded.capacity() { - let capacity = decoded - .capacity() - .saturating_mul(2) - .max(required) - .min(max_decompressed_bytes); - decoded.reserve_exact(capacity - decoded.len()); - } - decoded.extend_from_slice(&chunk[..read]); - } -} - pub(super) fn decode_request_inner( body: &[u8], request_headers: &OpenAiRequestHeaders, @@ -447,7 +364,7 @@ fn header_string(headers: &HeaderMap, name: &str) -> Option { .map(ToOwned::to_owned) } -fn passthrough_headers(headers: &HeaderMap) -> Vec { +pub(crate) fn passthrough_headers(headers: &HeaderMap) -> Vec { passthrough_request_headers(headers) .map(|(name, value)| { Value::Array(vec![ @@ -491,6 +408,7 @@ fn passthrough_header_name(name: &str, connection_headers: &[String]) -> bool { // 下游鉴权和账号 cookie 绝不能成为上游账号身份 "authorization" | "x-api-key" + | "x-goog-api-key" // Codex 的服务端托管认证标记只用于客户端能力判断,不代表上游身份 | "x-openai-actor-authorization" | "cookie" diff --git a/backend/crates/gateway-api/src/openai/responses/response.rs b/backend/crates/gateway-api/src/data_plane/responses/response.rs similarity index 99% rename from backend/crates/gateway-api/src/openai/responses/response.rs rename to backend/crates/gateway-api/src/data_plane/responses/response.rs index 0b80d0c0b..5954255a8 100644 --- a/backend/crates/gateway-api/src/openai/responses/response.rs +++ b/backend/crates/gateway-api/src/data_plane/responses/response.rs @@ -186,7 +186,7 @@ impl OpenAiResponsesEncoder { } /// 仅在非流式出口聚合同一响应的完成项,不让流式转发常驻保存输出内容 -pub(in crate::openai) fn collect_response( +pub(in crate::data_plane) fn collect_response( events: &[ProviderEvent], ) -> Result { let mut encoder = OpenAiResponsesEncoder::new(); diff --git a/backend/crates/gateway-api/src/openai/responses/validation.rs b/backend/crates/gateway-api/src/data_plane/responses/validation.rs similarity index 96% rename from backend/crates/gateway-api/src/openai/responses/validation.rs rename to backend/crates/gateway-api/src/data_plane/responses/validation.rs index 5affb8413..e10c15c69 100644 --- a/backend/crates/gateway-api/src/openai/responses/validation.rs +++ b/backend/crates/gateway-api/src/data_plane/responses/validation.rs @@ -15,7 +15,7 @@ const MAX_IDENTIFIER_BYTES: usize = 1_024; /// 插件输出不能安全投递为 OpenAI Responses 协议 #[derive(Debug, Clone, Copy)] -pub(in crate::openai) struct ResponseValidationError; +pub(in crate::data_plane) struct ResponseValidationError; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum TerminalKind { @@ -34,10 +34,10 @@ struct ExpectedResponseFacts { /// 仅保存最终协议复核所需的响应 ID 与终态类别,不缓存流正文 #[derive(Clone, Default)] -pub(in crate::openai) struct ResponseValidationFacts(Arc>); +pub(in crate::data_plane) struct ResponseValidationFacts(Arc>); impl ResponseValidationFacts { - pub(in crate::openai) fn observe_event(&self, event: &ProviderEvent) { + pub(in crate::data_plane) fn observe_event(&self, event: &ProviderEvent) { let mut facts = self .0 .lock() @@ -56,7 +56,11 @@ impl ResponseValidationFacts { } } - pub(in crate::openai) fn observe_buffered(&self, events: &[ProviderEvent], original: &[u8]) { + pub(in crate::data_plane) fn observe_buffered( + &self, + events: &[ProviderEvent], + original: &[u8], + ) { for event in events { self.observe_event(event); } @@ -82,7 +86,7 @@ impl ResponseValidationFacts { .clone() } - pub(in crate::openai) fn response_id(&self) -> Option { + pub(in crate::data_plane) fn response_id(&self) -> Option { self.snapshot().response_id } } @@ -147,7 +151,7 @@ impl ExpectedResponseFacts { } /// 只复核中间件确实改写过的完整 JSON;未经改写的原生快路保持原行为 -pub(in crate::openai) fn validate_buffered_response( +pub(in crate::data_plane) fn validate_buffered_response( facts: &ResponseValidationFacts, modified: &[u8], ) -> Result<(), ResponseValidationError> { @@ -177,7 +181,7 @@ pub(in crate::openai) fn validate_buffered_response( /// 原始前缀只旁路构建状态;直到插件首次改写或丢弃正文才启用严格拒绝,避免给 /// 无策略原生热路增加新的兼容性条件 #[derive(Debug, Default)] -pub(in crate::openai) struct ResponsesDeliveryValidator { +pub(in crate::data_plane) struct ResponsesDeliveryValidator { active: bool, invalid_prefix: bool, state: DeliveryState, @@ -185,7 +189,7 @@ pub(in crate::openai) struct ResponsesDeliveryValidator { impl ResponsesDeliveryValidator { /// 复核实际交付帧;只有宿主标记为已改写时才激活严格模式 - pub(in crate::openai) fn validate_frame( + pub(in crate::data_plane) fn validate_frame( &mut self, delivered: &[u8], transformed: bool, @@ -195,7 +199,7 @@ impl ResponsesDeliveryValidator { } /// WebSocket JSON message 与 SSE 共用同一响应顺序和关联校验 - pub(in crate::openai) fn validate_websocket_frame( + pub(in crate::data_plane) fn validate_websocket_frame( &mut self, delivered: &[u8], transformed: bool, @@ -264,11 +268,11 @@ impl ResponsesDeliveryValidator { self.state.apply(parsed) } - pub(in crate::openai) fn response_id(&self) -> Option<&str> { + pub(in crate::data_plane) fn response_id(&self) -> Option<&str> { self.state.response_id.as_deref() } - pub(in crate::openai) fn finish_delivery(&self) -> Result<(), ResponseValidationError> { + pub(in crate::data_plane) fn finish_delivery(&self) -> Result<(), ResponseValidationError> { if !self.active || self.state.done { Ok(()) } else { @@ -276,12 +280,12 @@ impl ResponsesDeliveryValidator { } } - pub(in crate::openai) fn completed_response_id(&self) -> Option<&str> { + pub(in crate::data_plane) fn completed_response_id(&self) -> Option<&str> { self.response_id() .filter(|_| self.state.terminal == Some(TerminalKind::Completed)) } - pub(in crate::openai) fn finish_websocket_delivery( + pub(in crate::data_plane) fn finish_websocket_delivery( &self, ) -> Result<(), ResponseValidationError> { if !self.active || self.state.terminal.is_some() { diff --git a/backend/crates/gateway-api/src/openai/responses/websocket/connection/frame.rs b/backend/crates/gateway-api/src/data_plane/responses/websocket/connection/frame.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/responses/websocket/connection/frame.rs rename to backend/crates/gateway-api/src/data_plane/responses/websocket/connection/frame.rs diff --git a/backend/crates/gateway-api/src/openai/responses/websocket/connection/handle.rs b/backend/crates/gateway-api/src/data_plane/responses/websocket/connection/handle.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/responses/websocket/connection/handle.rs rename to backend/crates/gateway-api/src/data_plane/responses/websocket/connection/handle.rs diff --git a/backend/crates/gateway-api/src/openai/responses/websocket/connection/middleware.rs b/backend/crates/gateway-api/src/data_plane/responses/websocket/connection/middleware.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/responses/websocket/connection/middleware.rs rename to backend/crates/gateway-api/src/data_plane/responses/websocket/connection/middleware.rs diff --git a/backend/crates/gateway-api/src/openai/responses/websocket/connection/mod.rs b/backend/crates/gateway-api/src/data_plane/responses/websocket/connection/mod.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/responses/websocket/connection/mod.rs rename to backend/crates/gateway-api/src/data_plane/responses/websocket/connection/mod.rs diff --git a/backend/crates/gateway-api/src/openai/responses/websocket/connection/pump.rs b/backend/crates/gateway-api/src/data_plane/responses/websocket/connection/pump.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/responses/websocket/connection/pump.rs rename to backend/crates/gateway-api/src/data_plane/responses/websocket/connection/pump.rs diff --git a/backend/crates/gateway-api/src/openai/responses/websocket/connection/state.rs b/backend/crates/gateway-api/src/data_plane/responses/websocket/connection/state.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/responses/websocket/connection/state.rs rename to backend/crates/gateway-api/src/data_plane/responses/websocket/connection/state.rs diff --git a/backend/crates/gateway-api/src/openai/responses/websocket/connection/transport.rs b/backend/crates/gateway-api/src/data_plane/responses/websocket/connection/transport.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/responses/websocket/connection/transport.rs rename to backend/crates/gateway-api/src/data_plane/responses/websocket/connection/transport.rs diff --git a/backend/crates/gateway-api/src/openai/responses/websocket/forward.rs b/backend/crates/gateway-api/src/data_plane/responses/websocket/forward.rs similarity index 98% rename from backend/crates/gateway-api/src/openai/responses/websocket/forward.rs rename to backend/crates/gateway-api/src/data_plane/responses/websocket/forward.rs index 787b3624e..25c24f3f8 100644 --- a/backend/crates/gateway-api/src/openai/responses/websocket/forward.rs +++ b/backend/crates/gateway-api/src/data_plane/responses/websocket/forward.rs @@ -1,5 +1,6 @@ //! Responses WebSocket 洋葱响应体与串行 transport 交付 +use crate::data_plane::generation::DecodedGenerationRequest; use std::collections::VecDeque; use std::sync::{Arc, Mutex}; @@ -18,12 +19,14 @@ use gateway_core::event::ProviderResponseHeader; use gateway_core::operation::ProviderSessionState; use gateway_protocol::openai::OPENAI_PROTOCOL; -use crate::openai::error::{gateway_error_contract, gateway_error_from_engine}; -use crate::openai::middleware::{PendingExecution, pending_execution_response}; -use crate::openai::responses::validation::{ResponseValidationFacts, ResponsesDeliveryValidator}; +use crate::data_plane::error::{gateway_error_contract, gateway_error_from_engine}; +use crate::data_plane::middleware::{PendingExecution, pending_execution_response}; +use crate::data_plane::responses::validation::{ + ResponseValidationFacts, ResponsesDeliveryValidator, +}; use super::{ - super::{DecodedGenerationRequest, OpenAiResponsesEncoder, ProtocolErrorBody}, + super::{OpenAiResponsesEncoder, ProtocolErrorBody}, connection::{ ConnectionEvent, FramePhase, ResponsesWebSocketConnection, WriteContext, WriteOutcome, }, diff --git a/backend/crates/gateway-api/src/openai/responses/websocket/interrupt.rs b/backend/crates/gateway-api/src/data_plane/responses/websocket/interrupt.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/responses/websocket/interrupt.rs rename to backend/crates/gateway-api/src/data_plane/responses/websocket/interrupt.rs diff --git a/backend/crates/gateway-api/src/openai/responses/websocket/mod.rs b/backend/crates/gateway-api/src/data_plane/responses/websocket/mod.rs similarity index 96% rename from backend/crates/gateway-api/src/openai/responses/websocket/mod.rs rename to backend/crates/gateway-api/src/data_plane/responses/websocket/mod.rs index a20cece7e..3ff586b05 100644 --- a/backend/crates/gateway-api/src/openai/responses/websocket/mod.rs +++ b/backend/crates/gateway-api/src/data_plane/responses/websocket/mod.rs @@ -5,6 +5,7 @@ mod forward; mod interrupt; mod protocol; +use crate::request_context::request_client_context; use std::{ net::{IpAddr, SocketAddr}, sync::Arc, @@ -31,17 +32,15 @@ use gateway_protocol::openai::OPENAI_PROTOCOL; use crate::middleware::headers::encode_headers; use crate::{ ApiState, - openai::middleware::{RequestInput, invoke_request, request_parts}, - openai::{ + data_plane::middleware::{RequestInput, invoke_request, request_parts}, + data_plane::{ auth::{ClientKeyHeaders, authenticate_client, client_access_error_response}, error::runtime_unavailable_response, - service::OpenAiService, + service::DataPlaneService, }, }; -use super::{ - request::OpenAiRequestHeaders, request_client_context, validation::ResponseValidationFacts, -}; +use super::{request::OpenAiRequestHeaders, validation::ResponseValidationFacts}; use connection::{ ConnectionEvent, FramePhase, ResponsesWebSocketConnection, Socket, Upgrade, WriteContext, }; @@ -65,7 +64,7 @@ pub(crate) async fn responses_websocket( headers: HeaderMap, websocket: Upgrade, ) -> Response { - let service = state.openai().clone(); + let service = state.data_plane().clone(); let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await { Ok(client) => client, Err(error) => return client_access_error_response(error), @@ -88,13 +87,13 @@ pub(crate) async fn responses_websocket( /// 已鉴权 Responses WebSocket 升级边界 #[derive(Clone)] pub(crate) struct ResponsesWebSocketAdapter { - service: OpenAiService, + service: DataPlaneService, } impl ResponsesWebSocketAdapter { /// 绑定应用提供的唯一 OpenAI 客户端服务端口 #[must_use] - pub const fn new(service: OpenAiService) -> Self { + pub const fn new(service: DataPlaneService) -> Self { Self { service } } @@ -116,7 +115,7 @@ impl ResponsesWebSocketAdapter { let connection_id = self.service.next_request_id().replacen("req_", "ws_", 1); TraceContext::new(&connection_id).headers( "client.connection.headers", - serde_json::json!({"transport": "websocket", "method": "GET", "path": crate::openai::router::RESPONSES_PATH}), + serde_json::json!({"transport": "websocket", "method": "GET", "path": crate::data_plane::router::RESPONSES_PATH}), raw_headers .iter() .map(|(name, value)| (name.as_str(), value.as_bytes())), @@ -141,7 +140,7 @@ impl ResponsesWebSocketAdapter { } struct ResponsesWebSocketSession { - service: OpenAiService, + service: DataPlaneService, client: AuthenticatedClient, connection_id: String, client_ip: Option, @@ -321,7 +320,7 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe let capture = new_replay_capture(); let validation = ResponseValidationFacts::default(); let input = RequestInput { - endpoint: crate::openai::router::RESPONSES_PATH.to_owned(), + endpoint: crate::data_plane::router::RESPONSES_PATH.to_owned(), protocol: OPENAI_PROTOCOL.to_owned(), operation: Some(OperationKind::Generate), transport: ClientTransport::WebSocket, @@ -373,7 +372,7 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe prepared, decoded, ClientTransport::WebSocket, - crate::openai::router::RESPONSES_PATH, + crate::data_plane::router::RESPONSES_PATH, ) .await .map_err(MiddlewareError::Gateway)?; diff --git a/backend/crates/gateway-api/src/openai/responses/websocket/protocol.rs b/backend/crates/gateway-api/src/data_plane/responses/websocket/protocol.rs similarity index 97% rename from backend/crates/gateway-api/src/openai/responses/websocket/protocol.rs rename to backend/crates/gateway-api/src/data_plane/responses/websocket/protocol.rs index a24b69ed6..48388b8a4 100644 --- a/backend/crates/gateway-api/src/openai/responses/websocket/protocol.rs +++ b/backend/crates/gateway-api/src/data_plane/responses/websocket/protocol.rs @@ -1,6 +1,8 @@ //! Responses WebSocket 入站请求与下行事件的纯协议映射 use crate::client_error::capacity_error_for_client; +use crate::data_plane::body::RequestDecodeError; +use crate::data_plane::generation::DecodedGenerationRequest; use axum::http::{HeaderName, HeaderValue, StatusCode}; use gateway_core::engine::EngineError; @@ -9,10 +11,10 @@ use gateway_core::event::ProviderResponseHeader; use serde_json::{Map, Value, json}; use thiserror::Error; -use crate::openai::error::{gateway_error_contract, gateway_error_from_engine}; +use crate::data_plane::error::{gateway_error_contract, gateway_error_from_engine}; use super::super::{ - DecodedGenerationRequest, ProtocolErrorBody, RequestDecodeError, + ProtocolErrorBody, request::{OpenAiRequestHeaders, RequestDecodeSource}, }; diff --git a/backend/crates/gateway-api/src/openai/router.rs b/backend/crates/gateway-api/src/data_plane/router.rs similarity index 51% rename from backend/crates/gateway-api/src/openai/router.rs rename to backend/crates/gateway-api/src/data_plane/router.rs index dd78faad0..d05bbf523 100644 --- a/backend/crates/gateway-api/src/openai/router.rs +++ b/backend/crates/gateway-api/src/data_plane/router.rs @@ -1,4 +1,4 @@ -//! OpenAI 客户端协议路由 +//! 模型数据面路由 use axum::{ Router, @@ -32,7 +32,7 @@ pub(super) const MODEL_DETAIL_PATH: &str = "/v1/models/{model_id}"; pub(super) const USAGE_PATH: &str = "/v1/usage"; pub(super) const PEER_LINK_PATH: &str = "/v1/cpr/link"; -/// 构造 OpenAI 客户端协议路由 +/// 构造模型数据面路由 pub(crate) fn router() -> Router { Router::new() .route(IMAGE_GENERATIONS_PATH, post(image_generations)) @@ -45,10 +45,64 @@ pub(crate) fn router() -> Router { .route(MODELS_PATH, get(models)) // 官方 OpenAI 模型详情合同使用 path ID;它不属于 Admin API 约束 .route(MODEL_DETAIL_PATH, get(model_detail)) + .merge(super::genai::router()) .merge(usage::router()) .merge(super::peer_link::router()) .merge(live::router()) - // OpenAI 数据面正文属于客户端/上游协议;代理不能用私有大小上限提前拒绝 + // 生成请求正文属于客户端/上游协议;代理不能用私有大小上限提前拒绝 // 上游本可接受的未来 payload .layer(DefaultBodyLimit::disable()) + .merge(super::provider_endpoints::router()) +} + +#[derive(Clone, Copy)] +pub(crate) enum DataPlaneNamespace { + V1, + GenAi, +} + +impl DataPlaneNamespace { + pub(crate) fn for_path(path: &str) -> Option { + if path == "/v1" || path.starts_with("/v1/") { + Some(Self::V1) + } else if path == "/v1beta" || path.starts_with("/v1beta/") || path.starts_with("/v1beta:") + { + Some(Self::GenAi) + } else { + None + } + } + + pub(crate) const fn unmatched_path(self) -> &'static str { + match self { + Self::V1 => "/v1/", + Self::GenAi => "/v1beta/", + } + } +} + +/// 模型数据面的未知路径由协议答复,其余未匹配路径交给静态资源服务 +pub(crate) async fn fallback( + request: axum::extract::Request, + next: axum::middleware::Next, +) -> axum::response::Response { + use crate::client_error::{ProtocolError, ProtocolErrorBody}; + let Some(namespace) = DataPlaneNamespace::for_path(request.uri().path()) else { + return next.run(request).await; + }; + let response = super::error::protocol_error_response( + axum::http::StatusCode::NOT_FOUND, + ProtocolErrorBody { + error: ProtocolError { + kind: "invalid_request_error", + code: "unknown_endpoint", + message: "The requested API endpoint does not exist.".into(), + param: None, + }, + }, + ); + match namespace { + DataPlaneNamespace::V1 => response, + DataPlaneNamespace::GenAi => super::genai::project_error_response(response).await, + } } diff --git a/backend/crates/gateway-api/src/openai/search/http.rs b/backend/crates/gateway-api/src/data_plane/search/http.rs similarity index 90% rename from backend/crates/gateway-api/src/openai/search/http.rs rename to backend/crates/gateway-api/src/data_plane/search/http.rs index 4782bc4a5..17fb66a35 100644 --- a/backend/crates/gateway-api/src/openai/search/http.rs +++ b/backend/crates/gateway-api/src/data_plane/search/http.rs @@ -1,5 +1,6 @@ //! Codex standalone search 非流式 HTTP adapter +use crate::request_context::request_client_context; use std::net::SocketAddr; use axum::{ @@ -14,14 +15,14 @@ use gateway_core::operation::{Operation, OperationKind, RawJsonPayload, Standalo use gateway_protocol::openai::OPENAI_PROTOCOL; use crate::ApiState; -use crate::middleware::headers::encode_headers; -use crate::openai::middleware::RequestInput; -use crate::openai::{ +use crate::data_plane::middleware::RequestInput; +use crate::data_plane::{ auth::{ClientKeyHeaders, authenticate_client, client_access_error_response}, - endpoint::provider_endpoint_response, - responses::{OpenAiRequestHeaders, request_client_context}, + openai_endpoints::provider_endpoint_response, + responses::OpenAiRequestHeaders, router::SEARCH_PATH, }; +use crate::middleware::headers::encode_headers; /// `POST /v1/alpha/search` pub(crate) async fn standalone_search( @@ -30,7 +31,7 @@ pub(crate) async fn standalone_search( headers: HeaderMap, body: Bytes, ) -> Response { - let service = state.openai(); + let service = state.data_plane(); let client = match authenticate_client(service, &headers, ClientKeyHeaders::Bearer).await { Ok(client) => client, Err(error) => return client_access_error_response(error), diff --git a/backend/crates/gateway-api/src/openai/search/mod.rs b/backend/crates/gateway-api/src/data_plane/search/mod.rs similarity index 100% rename from backend/crates/gateway-api/src/openai/search/mod.rs rename to backend/crates/gateway-api/src/data_plane/search/mod.rs diff --git a/backend/crates/gateway-api/src/openai/service.rs b/backend/crates/gateway-api/src/data_plane/service.rs similarity index 77% rename from backend/crates/gateway-api/src/openai/service.rs rename to backend/crates/gateway-api/src/data_plane/service.rs index af1a5a169..1e6af185e 100644 --- a/backend/crates/gateway-api/src/openai/service.rs +++ b/backend/crates/gateway-api/src/data_plane/service.rs @@ -1,6 +1,5 @@ -//! OpenAI wire adapter 到 Core 执行用例的唯一映射 +//! 模型数据面到 Core 执行用例的映射 -use std::net::IpAddr; use std::sync::Arc; use gateway_core::engine::authentication::ClientAuthenticationRequest; @@ -12,23 +11,20 @@ use gateway_core::engine::execution::{ }; use gateway_core::error::{GatewayError, GatewayErrorKind}; use gateway_core::lifecycle::{ConnectionDraining, ConnectionGuard, ConnectionLifecycle}; -use gateway_core::routing::{ - ProviderCatalogUnavailable, ProviderKind, PublicModelDescriptor, PublicModelId, UpstreamModelId, -}; -use gateway_protocol::openai::OPENAI_PROTOCOL; +use gateway_core::routing::{ProviderCatalogUnavailable, PublicModelDescriptor, PublicModelId}; use uuid::Uuid; use super::auth::ClientApiKeyAuthError; -use super::responses::{ContinuationIntent, DecodedGenerationRequest}; +use super::generation::{ContinuationIntent, DecodedGenerationRequest}; -/// OpenAI HTTP/WS adapter 共享的 Core 与连接生命周期能力 +/// 模型 HTTP 与 WS 入口共享的 Core 与连接生命周期能力 #[derive(Clone)] -pub(crate) struct OpenAiService { +pub(crate) struct DataPlaneService { execution: Arc, lifecycle: Arc, } -impl OpenAiService { +impl DataPlaneService { pub(crate) fn execution(&self) -> Arc { Arc::clone(&self.execution) } @@ -138,40 +134,6 @@ impl OpenAiService { .await } - pub(crate) async fn start_prepared_provider_endpoint( - &self, - prepared: PreparedRootExecution, - operation: gateway_core::operation::Operation, - upstream_model: Option, - client_ip: Option, - user_agent: Option, - endpoint: String, - ) -> Result { - let provider = ProviderKind::new("openai").map_err(|_| { - GatewayError::new( - GatewayErrorKind::Internal, - "OpenAI provider identifier is invalid.", - ) - })?; - self.execution - .start_prepared_provider_endpoint( - prepared, - provider, - upstream_model, - operation, - ExecutionRequestMetadata { - protocol: OPENAI_PROTOCOL.to_owned(), - endpoint, - transport: ClientTransport::HttpJson, - stream: false, - client_ip, - user_agent, - previous_response_id: None, - }, - ) - .await - } - pub(crate) async fn start_bound_provider_endpoint( &self, request: StartProviderExecution, diff --git a/backend/crates/gateway-api/src/openai/usage.rs b/backend/crates/gateway-api/src/data_plane/usage.rs similarity index 93% rename from backend/crates/gateway-api/src/openai/usage.rs rename to backend/crates/gateway-api/src/data_plane/usage.rs index cd1de6d64..11b9826cb 100644 --- a/backend/crates/gateway-api/src/openai/usage.rs +++ b/backend/crates/gateway-api/src/data_plane/usage.rs @@ -16,9 +16,8 @@ use serde::Deserialize; use serde_json::{Value, json}; use crate::{ - ApiState, - auth::SessionState as _, - openai::middleware::{self as plugin_middleware, RequestInput}, + ApiState, SessionState as _, + data_plane::middleware::{self as plugin_middleware, RequestInput}, }; use super::{ @@ -41,12 +40,12 @@ async fn usage( headers: HeaderMap, uri: axum::http::Uri, ) -> Response { - let client = match verify_client(state.openai(), &headers).await { + let client = match verify_client(state.data_plane(), &headers).await { Ok(client) => client, Err(error) => return client_access_error_response(error.into()), }; plugin_middleware::query_response( - state.openai().execution(), + state.data_plane().execution(), client, RequestInput::query(super::router::USAGE_PATH.to_owned(), None, &headers), move |client| usage_response(state, client, uri), diff --git a/backend/crates/gateway-api/src/diagnostics.rs b/backend/crates/gateway-api/src/diagnostics.rs index 20a23ea86..acc6ee747 100644 --- a/backend/crates/gateway-api/src/diagnostics.rs +++ b/backend/crates/gateway-api/src/diagnostics.rs @@ -18,16 +18,17 @@ use http_body::{Body as _, Frame, SizeHint}; use serde_json::json; use tower_http::request_id::RequestId; -use crate::client_error::{AccessRejection, ProtocolError, ProtocolErrorBody}; +use crate::client_error::{AccessRejection, ProtocolErrorBody}; +use crate::data_plane::router::DataPlaneNamespace; pub(crate) async fn record_ingress( State(diagnostics): State>, mut request: Request, next: Next, ) -> Response { - if request.uri().path() != "/v1" && !request.uri().path().starts_with("/v1/") { + let Some(namespace) = DataPlaneNamespace::for_path(request.uri().path()) else { return next.run(request).await; - } + }; let correlation_id = request .extensions() .get::() @@ -61,22 +62,7 @@ pub(crate) async fn record_ingress( } else { None }; - let mut response = if endpoint.is_none() { - // 数据面未知路径不能落入 SPA fallback,否则会把协议错误伪装成 HTML 成功 - crate::openai::error::protocol_error_response( - StatusCode::NOT_FOUND, - ProtocolErrorBody { - error: ProtocolError { - kind: "invalid_request_error", - code: "unknown_endpoint", - message: "The requested API endpoint does not exist.".into(), - param: None, - }, - }, - ) - } else { - next.run(request).await - }; + let mut response = next.run(request).await; let protocol = response.extensions_mut().remove::(); let gateway = response .extensions_mut() @@ -109,7 +95,7 @@ pub(crate) async fn record_ingress( byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'[' | b']') }) }); - let endpoint = endpoint.as_deref().unwrap_or("/v1/"); + let endpoint = endpoint.as_deref().unwrap_or(namespace.unmatched_path()); let model_request_id = execution_observed .then(|| { response diff --git a/backend/crates/gateway-api/src/key_usage/mod.rs b/backend/crates/gateway-api/src/key_usage/mod.rs index b1dea964b..e3f10b92b 100644 --- a/backend/crates/gateway-api/src/key_usage/mod.rs +++ b/backend/crates/gateway-api/src/key_usage/mod.rs @@ -10,9 +10,9 @@ use axum::{ }; use crate::{ + SessionState, admin::{AdminEnvelope, AdminError, AdminQuery, AdminResponse, wire::map_admin_service_error}, - auth::SessionState, - session_cookie, + session, }; mod presenter; @@ -44,7 +44,7 @@ where let version = state .admin_services() .key_usage() - .version(session_cookie::value(&headers).as_deref()) + .version(session::value(&headers).as_deref()) .await .map_err(map_admin_service_error)? .ok_or_else(AdminError::session_required)?; @@ -65,7 +65,7 @@ where let secret = state .admin_services() .key_usage() - .config(session_cookie::value(&headers).as_deref()) + .config(session::value(&headers).as_deref()) .await .map_err(map_admin_service_error)? .ok_or_else(AdminError::session_required)?; @@ -88,7 +88,7 @@ where .admin_services() .key_usage() .overview( - session_cookie::value(&headers).as_deref(), + session::value(&headers).as_deref(), query.into_domain(state.admin_services().timezone())?, ) .await @@ -113,7 +113,7 @@ where .admin_services() .key_usage() .records( - session_cookie::value(&headers).as_deref(), + session::value(&headers).as_deref(), query.into_domain(state.admin_services().timezone())?, ) .await diff --git a/backend/crates/gateway-api/src/lib.rs b/backend/crates/gateway-api/src/lib.rs index 394431e5b..7873e95f7 100644 --- a/backend/crates/gateway-api/src/lib.rs +++ b/backend/crates/gateway-api/src/lib.rs @@ -24,20 +24,20 @@ use url::Url; const WEB_DIST_ENV: &str = "CPR_WEB_DIST_DIR"; +use crate::data_plane::service::DataPlaneService; use crate::health::HealthStatus; -use crate::openai::service::OpenAiService; pub mod admin; pub mod auth; mod client_error; +pub mod data_plane; mod diagnostics; mod health; mod key_usage; mod middleware; -pub mod openai; -mod provider; mod request_context; -mod session_cookie; +mod session; +pub use session::SessionState; mod time; pub use time::{RequestBucketView, TimePresenter}; @@ -217,15 +217,14 @@ pub fn initialize( }; let state = ApiState { admin, - openai: OpenAiService::new(execution, lifecycle), + data_plane: DataPlaneService::new(execution, lifecycle), health: HealthStatus::new(probes, worker_health, diagnostics.clone()), }; let index = config.asset_directory.join("index.html"); let mut router = Router::new() .route("/readyz", get(health::readyz)) .route("/healthz", get(health::healthz)) - .merge(openai::router::router()) - .merge(provider::router()) + .merge(data_plane::router::router()) .merge(admin::router::()) .merge(admin::model_router()) .merge(auth::router::()) @@ -235,7 +234,8 @@ pub fn initialize( .fallback_service( ServeDir::new(config.asset_directory).fallback(ServeFile::new(index)), ) - .layer(axum::middleware::map_response(static_cache_control)), + .layer(axum::middleware::map_response(static_cache_control)) + .layer(axum::middleware::from_fn(data_plane::router::fallback)), ); if !config.cors_allowed_origins.is_empty() { let origins = config @@ -337,14 +337,14 @@ pub enum ApiError { #[derive(Clone)] pub(crate) struct ApiState { admin: AdminServices, - openai: OpenAiService, + data_plane: DataPlaneService, health: HealthStatus, } impl ApiState { #[must_use] - pub(crate) const fn openai(&self) -> &OpenAiService { - &self.openai + pub(crate) const fn data_plane(&self) -> &DataPlaneService { + &self.data_plane } #[must_use] @@ -353,7 +353,7 @@ impl ApiState { } } -impl auth::SessionState for ApiState { +impl SessionState for ApiState { fn admin_services(&self) -> &AdminServices { &self.admin } diff --git a/backend/crates/gateway-api/src/openai/generation/mod.rs b/backend/crates/gateway-api/src/openai/generation/mod.rs deleted file mode 100644 index afdd02cb6..000000000 --- a/backend/crates/gateway-api/src/openai/generation/mod.rs +++ /dev/null @@ -1,82 +0,0 @@ -//! 生成与计数协议共用的解码事实和 HTTP 执行边界 - -pub(crate) mod http; -mod request; -mod response; -mod validation; - -pub(crate) use http::{ - GenerationHttpRequest, HttpResponseAdapter, ResponseAuthorization, execute_prepared_generation, -}; -pub use request::{ContinuationIntent, DecodedGenerationRequest, GenerationRequestMetadata}; - -use axum::http::HeaderMap; -use gateway_core::{ - error::{GatewayError, GatewayErrorKind}, - operation::OperationKind, -}; -use gateway_protocol::anthropic::ANTHROPIC_PROTOCOL; -use gateway_protocol::openai::OPENAI_PROTOCOL; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum GenerationProtocol { - Responses, - Messages, - MessageTokenCount, -} - -impl GenerationProtocol { - pub(crate) fn from_request(request: &DecodedGenerationRequest) -> Self { - if request.operation().kind() == OperationKind::CountTokens { - Self::MessageTokenCount - } else if request.operation().protocol() == ANTHROPIC_PROTOCOL { - Self::Messages - } else { - Self::Responses - } - } - - pub(crate) const fn wire(self) -> &'static str { - match self { - Self::Responses => OPENAI_PROTOCOL, - Self::Messages | Self::MessageTokenCount => ANTHROPIC_PROTOCOL, - } - } - - pub(crate) const fn endpoint(self) -> &'static str { - match self { - Self::Responses => super::router::RESPONSES_PATH, - Self::Messages => super::router::MESSAGES_PATH, - Self::MessageTokenCount => super::router::MESSAGE_TOKENS_PATH, - } - } - - pub(crate) const fn operation(self) -> OperationKind { - match self { - Self::Responses | Self::Messages => OperationKind::Generate, - Self::MessageTokenCount => OperationKind::CountTokens, - } - } - - pub(crate) fn decode( - self, - body: &[u8], - headers: &HeaderMap, - maximum: usize, - ) -> Result { - match self { - Self::Responses => super::responses::decode_request_with_headers( - body, headers, maximum, - ) - .map_err(|_| { - GatewayError::new( - GatewayErrorKind::InvalidRequest, - "Request middleware produced an invalid Responses request.", - ) - }), - Self::Messages | Self::MessageTokenCount => { - super::messages::decode_request(body, headers, maximum, self) - } - } - } -} diff --git a/backend/crates/gateway-api/src/session_cookie.rs b/backend/crates/gateway-api/src/session/cookie.rs similarity index 100% rename from backend/crates/gateway-api/src/session_cookie.rs rename to backend/crates/gateway-api/src/session/cookie.rs diff --git a/backend/crates/gateway-api/src/session/mod.rs b/backend/crates/gateway-api/src/session/mod.rs new file mode 100644 index 000000000..7f9bdbb88 --- /dev/null +++ b/backend/crates/gateway-api/src/session/mod.rs @@ -0,0 +1,7 @@ +//! 控制面会话合同与 Cookie 解析入口 + +mod cookie; +mod state; + +pub(crate) use cookie::{NAME, REFRESH_NAME, attributes, refresh_value, value}; +pub use state::SessionState; diff --git a/backend/crates/gateway-api/src/session/state.rs b/backend/crates/gateway-api/src/session/state.rs new file mode 100644 index 000000000..ff1de5616 --- /dev/null +++ b/backend/crates/gateway-api/src/session/state.rs @@ -0,0 +1,8 @@ +//! 控制面会话入口共同消费的应用服务合同 + +use gateway_admin::AdminServices; + +/// 控制面 HTTP adapter 消费同一组用例;权限由各入口服务端校验 +pub trait SessionState { + fn admin_services(&self) -> &AdminServices; +} diff --git a/backend/crates/gateway-api/tests/admin/accounts/handlers.rs b/backend/crates/gateway-api/tests/admin/accounts/handlers.rs index fe50dac56..4d3451853 100644 --- a/backend/crates/gateway-api/tests/admin/accounts/handlers.rs +++ b/backend/crates/gateway-api/tests/admin/accounts/handlers.rs @@ -543,18 +543,18 @@ async fn account_usage_preserves_periods_cache_counts_and_missing_values() { (authentication_kind == "oauth").then(|| ProviderQuota { windows: vec![ProviderQuotaWindow { upstream: None, - key: "rolling-day".to_owned(), + key: "model-weekly".to_owned(), group: "shortTerm".to_owned(), - label: "日限额".to_owned(), - limit_id: None, + label: "周额度".to_owned(), + limit_id: Some("model-group".to_owned()), limit_name: None, role: None, - local_usage_attribution: QuotaLocalUsageAttribution::AccountWide, - window_seconds: Some(86_400), - used_percent: None, - reset_at: None, + local_usage_attribution: QuotaLocalUsageAttribution::Unavailable, + window_seconds: Some(604_800), + used_percent: Some(25.0), + reset_at: Some(now + chrono::TimeDelta::days(6)), limit_reached: false, - local_usage: Some(local_usage), + local_usage: None, provider_data: None, }], ..Default::default() @@ -595,14 +595,8 @@ async fn account_usage_preserves_periods_cache_counts_and_missing_values() { assert_eq!(usage["totalTokens"], 120); if authentication_kind == "oauth" { let window = &value["data"]["items"][0]["quota"]["windows"][0]; - assert_eq!(window["localUsage"]["requestCount"], 1); - assert_eq!( - window["localUsage"]["requestBuckets"] - .as_array() - .unwrap() - .len(), - 1 - ); + assert!(window["localUsage"].is_null()); + assert_eq!(window["usedPercent"], 25.0); } assert_eq!(usage["cachedInputTokens"], serde_json::json!(read)); assert_eq!(usage["cacheWriteInputTokens"], serde_json::json!(write)); diff --git a/backend/crates/gateway-api/tests/admin/client_keys.rs b/backend/crates/gateway-api/tests/admin/client_keys.rs index faa3b1314..865885331 100644 --- a/backend/crates/gateway-api/tests/admin/client_keys.rs +++ b/backend/crates/gateway-api/tests/admin/client_keys.rs @@ -52,7 +52,7 @@ fn batch_key_form_preserves_omissions_and_accepts_explicit_zero_false_and_inheri "installationSeed", json!("A3A4E0BDF84447068DF8BFF10DE95B3B"), ), - ("providerRequestProfileOverrides", json!({"unknown": null})), + ("providerRequestProfileOverrides", json!({"": null})), ] { let mut payload = json!({ "ids":["key_a"] }); payload[field] = value; @@ -146,7 +146,7 @@ async fn budget_reset_allows_admin_but_rejects_key_sessions_without_changing_usa record.budget.daily_used_usd = "1.25".parse().unwrap(); record.budget.weekly_used_usd = "4.5".parse().unwrap(); *fixture.client_key.lock().unwrap() = Some(record); - let app = crate::openai::api_router_with_admin(fixture.services.clone()); + let app = crate::data_plane::api_router_with_admin(fixture.services.clone()); let login = app .clone() .oneshot(json_request( @@ -629,7 +629,7 @@ async fn list_route_should_accept_the_full_nonzero_u16_page_size() { #[test] fn profile_override_distinguishes_omission_from_explicit_inheritance() { - for provider in ["openai", "xai"] { + for provider in ["openai", "xai", "antigravity"] { let decode = |body| { serde_json::from_value::(body) .unwrap() @@ -648,7 +648,8 @@ fn profile_override_distinguishes_omission_from_explicit_inheritance() { } #[test] -fn profile_overrides_accept_native_providers_and_reject_unknown_providers() { +fn profile_override_commands_preserve_valid_provider_identifiers() { + use gateway_core::routing::ProviderKind; let profile = json!({"preset":"desktop"}); let xai = json!({"preset":"managed"}); let request: CreateClientKeyRequest = serde_json::from_value(json!({ @@ -659,11 +660,12 @@ fn profile_overrides_accept_native_providers_and_reject_unknown_providers() { "providerRequestProfileOverrides": { "openai": profile, "xai": xai, + "antigravity": {"versionMode":"fixed","desktopVersion":"2.34.0"}, }, })) .unwrap(); let command = request.into_command().unwrap(); - assert_eq!(command.request_profile_overrides.len(), 2); + assert_eq!(command.request_profile_overrides.len(), 3); assert!( command .request_profile_overrides @@ -678,9 +680,12 @@ fn profile_overrides_accept_native_providers_and_reject_unknown_providers() { "providerRequestProfileOverrides": {"provider.example":{"preset":"managed"}}, })) .unwrap(); - assert_eq!( - unknown.into_command().unwrap_err().field(), - "providerRequestProfileOverrides" + assert!( + unknown + .into_command() + .unwrap() + .request_profile_overrides + .contains_key(&ProviderKind::new("provider.example").unwrap()) ); let unknown_clear: UpdateClientKeyRequest = serde_json::from_value(json!({ @@ -692,9 +697,12 @@ fn profile_overrides_accept_native_providers_and_reject_unknown_providers() { "providerRequestProfileOverrides": {"provider.example":null}, })) .unwrap(); - assert_eq!( - unknown_clear.into_command().unwrap_err().field(), - "providerRequestProfileOverrides" + assert!( + unknown_clear + .into_command() + .unwrap() + .request_profile_override_updates + .contains_key(&ProviderKind::new("provider.example").unwrap()) ); } diff --git a/backend/crates/gateway-api/tests/admin/compression.rs b/backend/crates/gateway-api/tests/admin/compression.rs index 43f548646..05fe6f7e6 100644 --- a/backend/crates/gateway-api/tests/admin/compression.rs +++ b/backend/crates/gateway-api/tests/admin/compression.rs @@ -17,7 +17,7 @@ use super::AdminTestFixture; async fn app() -> Router { let fixture = AdminTestFixture::new().await; fixture.auth.insert_session("valid-session"); - crate::openai::api_router_with_admin(fixture.services) + crate::data_plane::api_router_with_admin(fixture.services) } async fn get(router: Router, uri: &str, encoding: Option<&str>) -> Response { diff --git a/backend/crates/gateway-api/tests/admin/error_diagnostics.rs b/backend/crates/gateway-api/tests/admin/error_diagnostics.rs index f2be747e9..50639bc7a 100644 --- a/backend/crates/gateway-api/tests/admin/error_diagnostics.rs +++ b/backend/crates/gateway-api/tests/admin/error_diagnostics.rs @@ -12,7 +12,7 @@ async fn store_failure_is_recorded_once_with_the_incoming_request_id() { let fixture = super::AdminTestFixture::new().await; fixture.auth.insert_session("valid-session"); let diagnostics = Arc::new(crate::support::RecordingDiagnostics::default()); - let bundle = crate::openai::api_bundle_with_diagnostics( + let bundle = crate::data_plane::api_bundle_with_diagnostics( fixture.services, gateway_api::ApiConfig { asset_directory: std::env::temp_dir(), diff --git a/backend/crates/gateway-api/tests/admin/errors.rs b/backend/crates/gateway-api/tests/admin/errors.rs index 35a40e95c..dee04c78b 100644 --- a/backend/crates/gateway-api/tests/admin/errors.rs +++ b/backend/crates/gateway-api/tests/admin/errors.rs @@ -5,7 +5,7 @@ use axum::{ body::{Body, to_bytes}, http::{Method, Request, StatusCode, header}, }; -use gateway_api::auth::SessionState; +use gateway_api::SessionState; use serde_json::{Value, json}; use tower::ServiceExt as _; @@ -14,7 +14,7 @@ use super::{AdminTestFixture, AdminTestState}; const SESSION_COOKIE: &str = "cpr_session=valid-session"; fn app(state: AdminTestState) -> Router { - crate::openai::api_router_with_admin(state.admin_services().clone()).layer(axum::Extension( + crate::data_plane::api_router_with_admin(state.admin_services().clone()).layer(axum::Extension( axum::extract::ConnectInfo(std::net::SocketAddr::from(([127, 0, 0, 1], 41000))), )) } diff --git a/backend/crates/gateway-api/tests/admin/mod.rs b/backend/crates/gateway-api/tests/admin/mod.rs index a09024fc2..693b3975c 100644 --- a/backend/crates/gateway-api/tests/admin/mod.rs +++ b/backend/crates/gateway-api/tests/admin/mod.rs @@ -72,7 +72,7 @@ use gateway_admin::{ }, }, }; -use gateway_api::auth::SessionState; +use gateway_api::SessionState; use gateway_core::{ account::FastMode, account::{AccountStatusFacts, CredentialState, ProviderAccountId, QuotaState}, @@ -516,6 +516,7 @@ struct StaticPricingSource; impl gateway_admin::ports::pricing::PricingSource for StaticPricingSource { async fn fetch( &self, + _: &gateway_admin::ports::pricing::PricingSourceScope, ) -> Result { Ok(gateway_admin::model::pricing::PricingSyncPreview { @@ -1323,7 +1324,7 @@ impl AccountStore for UnusedStore { async fn load_quota_forecast_history( &self, _: &AccountUsageWindowQuery, - ) -> AdminStoreResult { + ) -> AdminStoreResult { Err(unavailable("quota forecast history")) } @@ -1734,6 +1735,17 @@ impl UnusedProvider { #[async_trait] impl ProviderAdmin for UnusedProvider { + fn account_capabilities( + &self, + _: &ProviderAccountId, + _: &str, + ) -> gateway_admin::model::accounts::ProviderAccountCapabilities { + gateway_admin::model::accounts::ProviderAccountCapabilities { + credential_export: true, + ..Default::default() + } + } + fn is_direct_account(&self, authentication_kind: &str) -> bool { authentication_kind == "oauth" } @@ -1975,9 +1987,9 @@ fn test_runtime_settings() -> RuntimeSettings { switch_account_on_queue_failure: false, max_retry_after_seconds: 240, openai_guardian_reserved_concurrency: 0, - openai_account_affinity: gateway_core::account::AccountAffinity::Relaxed, + account_affinity: gateway_core::account::AccountAffinity::Relaxed, max_account_rotations: 3, - openai_session_affinity_ttl_hours: 24, + session_affinity_ttl_hours: 24, responses_max_decompressed_body_bytes: 64 * 1024 * 1024, smart_scheduling: gateway_core::account::SmartSchedulingConfig::default(), quota_reset_window_weights: gateway_core::account::ResetWindowWeights::default(), diff --git a/backend/crates/gateway-api/tests/admin/observability/export/contract.rs b/backend/crates/gateway-api/tests/admin/observability/export/contract.rs new file mode 100644 index 000000000..2c0353e91 --- /dev/null +++ b/backend/crates/gateway-api/tests/admin/observability/export/contract.rs @@ -0,0 +1,393 @@ +//! 跨模块行为合同测试 + +use super::*; + +#[tokio::test] +async fn diagnostic_export_requires_admin_and_exactly_one_target() { + let fixture = AdminTestFixture::new().await; + fixture.auth.insert_session("valid-session"); + assert_eq!( + export(&fixture, "?errorId=missing", false).await.0, + StatusCode::UNAUTHORIZED + ); + for query in [ + "", + "?requestId=a&errorId=b", + "?requestId=", + "?errorId=a&payload=untrusted", + ] { + assert_eq!( + export(&fixture, query, true).await.0, + StatusCode::BAD_REQUEST, + "{query}" + ); + } + assert_eq!( + export(&fixture, "?errorId=missing", true).await.0, + StatusCode::NOT_FOUND + ); +} + +#[tokio::test] +async fn diagnostic_export_keeps_retry_evidence_and_original_errors_but_not_credentials() { + let fixture = AdminTestFixture::new().await; + fixture.auth.insert_session("valid-session"); + let mut error = ops_error_record(); + error.error_details = Some(json!({ + "causes": ["TLS certificate verification failed", "pool timeout after 5 seconds"], + "upstream": json!({"error": {"code": "unknown_vendor_failure", "message": "quota exhausted"}, + "headers": {"Authorization": "fixture-authorization", "set-cookie": "fixture-cookie"}, + "access_token": "fixture-access", "refreshToken": "fixture-refresh", + }).to_string(), + "endpoint": "postgres://fixture-user:fixture-password@database:5432/main", + "message": "connect failed: Bearer fixture-bearer, retry after 30 seconds", + }).to_string()); + let mut unrelated = error.clone(); + unrelated.request_id = Some("another-request".into()); + unrelated.message = "unrelated evidence must not leak".into(); + fixture + .ops_errors + .lock() + .unwrap() + .extend([error, unrelated]); + let trace = json!({"droppedEvents": 5, "droppedEvidenceEvents": 1, "stageCountOverflow": 2, + "stageCounts": {"provider.response.parse_gap": 1}, "events": [ + {"stage": "request.routed", "data": {"accountPolicy": {"maxAccountRotations": 3}}}, + {"stage": "account.selection", "data": {"candidates": [{"id": "acct_high", "weight": 2}, {"id": "acct_low", "weight": 1}]}}, + {"stage": "attempt.failed", "data": {"kind": "unavailable", "recovery": {"replaySafe": true}}}, + {"stage": "retry.decided", "data": {"phase": "execute", "retryable": false, "clientRetrySuppressed": true, "replayBarrierReached": false}}, + {"stage": "provider.response.parse_gap", "data": {"reason": "invalid_json"}}, + {"stage": "provider.request.input", "data": {"input": {"omittedItems": 10}}}, + {"stage": "upstream.event", "data": {"truncated": true, "jsonValid": false}}, + ]}); + fixture.usage_detail.lock().unwrap().replace(UsageDetail { + request: usage_record_with_account( + "req_err", + "acct_err", + "private name", + "fixture@example.invalid", + "api_key", + Utc::now(), + ), + attempts: Vec::new(), + trace: Some(trace.clone()), + related_requests: Vec::new(), + }); + let (status, headers, file) = export(&fixture, "?requestId=req_err", true).await; + assert_eq!(status, StatusCode::OK, "{file}"); + assert_eq!( + headers[header::CONTENT_DISPOSITION], + "attachment; filename=cpr-diagnostics-req_err.zip" + ); + assert_eq!(headers[header::CACHE_CONTROL], "private, no-store"); + assert_eq!(file["schemaVersion"], 5); + assert_eq!( + file["exportTruncated"], false, + "capture loss is distinct from export truncation" + ); + for reason in [ + "events_evicted", + "critical_evidence_evicted", + "stage_coverage_incomplete", + "response_parse_failed", + "input_prefix_sample_limited", + "event_data_truncated", + "json_parse_failed", + ] { + assert!( + file["availability"]["gaps"] + .as_array() + .unwrap() + .iter() + .any(|gap| gap["reason"] == reason), + "missing gap {reason}" + ); + } + assert_eq!(file["requests"][0]["evidence"]["trace"], trace); + assert_eq!( + file["requests"][0]["evidence"]["incidentConfiguration"]["revision"], + 1 + ); + let details = &file["requests"][0]["errors"][0]["errorDetails"]; + assert_eq!( + details["upstream"]["error"]["code"], + "unknown_vendor_failure" + ); + assert_eq!(details["causes"][0], "TLS certificate verification failed"); + assert_eq!(file["requests"][0]["errors"][0]["accountId"], "acct_err"); + assert!( + file["availability"]["gaps"] + .as_array() + .unwrap() + .iter() + .any(|gap| gap["section"] == "environment") + ); + let text = file.to_string(); + for marker in [ + "fixture-authorization", + "fixture-cookie", + "fixture-access", + "fixture-refresh", + "fixture-password", + "fixture-user", + "fixture-bearer", + "fixture@example.invalid", + "private name", + "unrelated evidence must not leak", + "203.0.113.8", + ] { + assert!(!text.contains(marker), "leaked {marker}"); + } + assert!(text.contains("retry after 30 seconds")); +} + +#[tokio::test] +async fn background_error_exports_without_fabricating_a_model_request() { + let fixture = AdminTestFixture::new().await; + fixture.auth.insert_session("valid-session"); + let mut error = ops_error_record(); + error.source = "ops_event".into(); + error.request_id = None; + error.component = "worker".into(); + error.error_details = + Some(json!({"causes": ["database connection refused"], "upstream": null}).to_string()); + fixture.ops_errors.lock().unwrap().push(error); + let (status, _, file) = export(&fixture, "?errorId=err_snapshot", true).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(file["requests"], json!([])); + assert_eq!(file["error"]["requestId"], Value::Null); + assert_eq!( + file["error"]["errorDetails"]["causes"][0], + "database connection refused" + ); +} + +#[tokio::test] +async fn error_survives_missing_request_and_nested_credentials_are_redacted() { + let fixture = AdminTestFixture::new().await; + fixture.auth.insert_session("valid-session"); + let mut error = ops_error_record(); + error.error_details = Some(json!({ + "cookies": "Cookie: a=fixture-cookie-a; b=fixture-cookie-b\nupstream timeout", + "uri": "https://provider.invalid/path?api_key=fixture-query&model=gpt-test", + "headers": [["Authorization", "fixture-tuple"], {"name": "Cookie", "value": "fixture-header"}], + }).to_string()); + fixture.ops_errors.lock().unwrap().push(error); + let (status, _, file) = export(&fixture, "?requestId=req_err", true).await; + assert_eq!(status, StatusCode::OK); + assert!(file["requests"][0]["evidence"].is_null()); + assert!( + file["availability"]["gaps"] + .as_array() + .unwrap() + .iter() + .any(|gap| gap["reason"] == "request_detail_unavailable") + ); + let text = file.to_string(); + for marker in [ + "fixture-cookie-a", + "fixture-cookie-b", + "fixture-query", + "fixture-tuple", + "fixture-header", + ] { + assert!(!text.contains(marker), "leaked {marker}"); + } + assert!(text.contains("upstream timeout")); + assert!(text.contains("model=gpt-test")); +} + +#[tokio::test] +async fn oversized_error_export_reports_truncation_instead_of_silent_loss() { + let fixture = AdminTestFixture::new().await; + fixture.auth.insert_session("valid-session"); + let mut error = ops_error_record(); + error.source = "ops_event".into(); + error.request_id = None; + error.message = "诊断文本".repeat(100_000); + fixture.ops_errors.lock().unwrap().push(error); + let (status, _, file) = export(&fixture, "?errorId=err_snapshot", true).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(file["exportTruncated"], true); + assert!(file["redaction"]["truncatedValues"].as_u64().unwrap() > 0); + assert!(file["error"]["message"]["omittedBytes"].as_u64().unwrap() > 0); +} + +#[tokio::test] +async fn related_read_failures_and_limits_keep_primary_evidence() { + let fixture = AdminTestFixture::new().await; + fixture.auth.insert_session("valid-session"); + let mut related = vec![json!({"requestId": "req_err", "relation": "recovers"})]; + related.extend( + (0..10).map( + |index| json!({"requestId": format!("missing_{index}"), "relation": "recovered_by"}), + ), + ); + fixture.usage_detail.lock().unwrap().replace(UsageDetail { + request: usage_record_with_account( + "req_err", + "acct_err", + "fixture", + "fixture@example.invalid", + "api_key", + Utc::now(), + ), + attempts: Vec::new(), + trace: None, + related_requests: related, + }); + fixture + .ops_errors + .lock() + .unwrap() + .extend((0..130).map(|index| { + let mut error = ops_error_record(); + error.event_id = format!("error_{index}"); + error + })); + let (status, _, file) = export(&fixture, "?requestId=req_err", true).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(file["requests"].as_array().unwrap().len(), 8); + assert_eq!(file["requests"][0]["errors"].as_array().unwrap().len(), 128); + assert_eq!( + file["requests"][0]["evidence"]["detail"]["requestId"], + "req_err" + ); + assert!(file["requests"][1]["evidence"].is_null()); + let gaps = file["availability"]["gaps"].as_array().unwrap(); + for reason in [ + "related_request_limit", + "error_record_limit", + "request_detail_unavailable", + "not_recorded_or_retained", + ] { + assert!( + gaps.iter().any(|gap| gap["reason"] == reason), + "missing {reason}" + ); + } +} + +#[tokio::test] +async fn credential_schemas_are_redacted_without_guessing_business_field_names() { + let fixture = AdminTestFixture::new().await; + fixture.auth.insert_session("valid-session"); + let mut error = ops_error_record(); + let business = json!({ + "token": {"input": 128, "output": 64}, + "credentials": {"status": "expired", "provider": "openai"}, + "secret": "tool argument name", "clientSecret": "business field description", + "accountId": "account-correlation", "userId": "user-correlation", + "planType": "plus", "status": "active", "accessTokenExpiresAt": "2026-10-16T00:00:00Z", + "error": {"code": "unknown_code", "message": "upstream capacity exceeded"}, + }); + error.error_details = Some(json!({ + "business": business, + "account": {"accessToken": "fixture-access", "refreshToken": "fixture-refresh", "idToken": "fixture-id"}, + "auth": {"OPENAI_API_KEY": "fixture-key", "personal_access_token": "fixture-pat", "tokens": { + "access_token": "fixture-official-access", "refresh_token": "fixture-official-refresh", + "id_token": "fixture-official-id", "account_id": "account-correlation", + }}, + }).to_string()); + fixture.ops_errors.lock().unwrap().push(error); + let (status, _, file) = export(&fixture, "?requestId=req_err", true).await; + assert_eq!(status, StatusCode::OK); + let details = &file["requests"][0]["errors"][0]["errorDetails"]; + assert_eq!(details["business"], business); + assert_eq!( + details["auth"]["tokens"]["account_id"], + "account-correlation" + ); + assert!(!file.to_string().contains("fixture-")); +} + +#[tokio::test] +async fn export_budget_keeps_format_target_and_existing_gap_records() { + let fixture = AdminTestFixture::new().await; + fixture.auth.insert_session("valid-session"); + fixture.usage_detail.lock().unwrap().replace(UsageDetail { + request: usage_record_with_account( + "req_err", + "acct_err", + "QA", + "qa@example.invalid", + "oauth", + Utc::now(), + ), + attempts: Vec::new(), + trace: Some(json!({"events": vec![vec![true; 32]; 3500]})), + related_requests: Vec::new(), + }); + let (status, _, file) = export(&fixture, "?requestId=req_err", true).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(file["schemaVersion"], 5); + assert_eq!(file["source"], "gateway.diagnostics"); + assert_eq!(file["target"]["requestId"], "req_err"); + assert_eq!(file["exportTruncated"], true); + let gaps = file["availability"]["gaps"].as_array().unwrap(); + assert!(gaps.iter().any(|gap| gap["reason"] == "export_size_limit")); + assert!( + gaps.iter() + .any(|gap| gap["reason"] == "incident_policy_not_recorded") + ); + assert!(serde_json::to_vec_pretty(&file).unwrap().len() < 16 * 1024 * 1024); +} + +#[tokio::test] +async fn selected_event_is_exported_once_and_shares_the_total_error_budget() { + let fixture = AdminTestFixture::new().await; + fixture.auth.insert_session("valid-session"); + let mut selected = ops_error_record(); + selected.source = "ops_event".into(); + let mut errors = vec![selected]; + errors.extend((0..129).map(|index| { + let mut error = ops_error_record(); + error.source = "ops_event".into(); + error.event_id = format!("related_{index}"); + error + })); + fixture.ops_errors.lock().unwrap().extend(errors); + let (status, _, file) = export(&fixture, "?errorId=err_snapshot", true).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(file["error"]["id"], "err_snapshot"); + let errors = file["requests"][0]["errors"].as_array().unwrap(); + assert_eq!(errors.len(), 127); + assert!(errors.iter().all(|error| error["id"] != "err_snapshot")); + assert!( + file["availability"]["gaps"] + .as_array() + .unwrap() + .iter() + .any(|gap| gap["reason"] == "error_record_limit") + ); +} + +#[tokio::test] +async fn inline_authentication_headers_are_redacted_without_losing_error_context() { + let fixture = AdminTestFixture::new().await; + fixture.auth.insert_session("valid-session"); + let mut error = ops_error_record(); + error.error_details = Some(json!({ + "headers": "x-api-key: fixture-api-key\nx-oai-is: fixture-session\nx-oai-is-update: fixture-update\nx-oai-attestation: fixture-attestation fixture-attestation-tail\nauthorization: Custom fixture-auth\nproxy-authorization: Custom fixture-proxy\nupstream timeout", + "message": "access-token=fixture-access; refresh-token=fixture-refresh; model=gpt-test", + }).to_string()); + fixture.ops_errors.lock().unwrap().push(error); + let (status, _, file) = export(&fixture, "?requestId=req_err", true).await; + assert_eq!(status, StatusCode::OK); + let text = file.to_string(); + for marker in [ + "fixture-api-key", + "fixture-session", + "fixture-update", + "fixture-attestation", + "fixture-attestation-tail", + "fixture-auth", + "fixture-proxy", + "fixture-access", + "fixture-refresh", + ] { + assert!(!text.contains(marker), "leaked {marker}"); + } + assert!(text.contains("upstream timeout")); + assert!(text.contains("model=gpt-test")); +} diff --git a/backend/crates/gateway-api/tests/admin/observability/export/mod.rs b/backend/crates/gateway-api/tests/admin/observability/export/mod.rs index ebf55d5f5..f4dd74c0b 100644 --- a/backend/crates/gateway-api/tests/admin/observability/export/mod.rs +++ b/backend/crates/gateway-api/tests/admin/observability/export/mod.rs @@ -1,5 +1,6 @@ //! 诊断下载的权限、证据完整性、脱敏与部分失败合同 +mod contract; use axum::{ body::{Body, to_bytes}, http::{Request, StatusCode, header}, @@ -64,393 +65,3 @@ async fn export( }; (status, headers, file) } - -#[tokio::test] -async fn diagnostic_export_requires_admin_and_exactly_one_target() { - let fixture = AdminTestFixture::new().await; - fixture.auth.insert_session("valid-session"); - assert_eq!( - export(&fixture, "?errorId=missing", false).await.0, - StatusCode::UNAUTHORIZED - ); - for query in [ - "", - "?requestId=a&errorId=b", - "?requestId=", - "?errorId=a&payload=untrusted", - ] { - assert_eq!( - export(&fixture, query, true).await.0, - StatusCode::BAD_REQUEST, - "{query}" - ); - } - assert_eq!( - export(&fixture, "?errorId=missing", true).await.0, - StatusCode::NOT_FOUND - ); -} - -#[tokio::test] -async fn diagnostic_export_keeps_retry_evidence_and_original_errors_but_not_credentials() { - let fixture = AdminTestFixture::new().await; - fixture.auth.insert_session("valid-session"); - let mut error = ops_error_record(); - error.error_details = Some(json!({ - "causes": ["TLS certificate verification failed", "pool timeout after 5 seconds"], - "upstream": json!({"error": {"code": "unknown_vendor_failure", "message": "quota exhausted"}, - "headers": {"Authorization": "fixture-authorization", "set-cookie": "fixture-cookie"}, - "access_token": "fixture-access", "refreshToken": "fixture-refresh", - }).to_string(), - "endpoint": "postgres://fixture-user:fixture-password@database:5432/main", - "message": "connect failed: Bearer fixture-bearer, retry after 30 seconds", - }).to_string()); - let mut unrelated = error.clone(); - unrelated.request_id = Some("another-request".into()); - unrelated.message = "unrelated evidence must not leak".into(); - fixture - .ops_errors - .lock() - .unwrap() - .extend([error, unrelated]); - let trace = json!({"droppedEvents": 5, "droppedEvidenceEvents": 1, "stageCountOverflow": 2, - "stageCounts": {"provider.response.parse_gap": 1}, "events": [ - {"stage": "request.routed", "data": {"accountPolicy": {"maxAccountRotations": 3}}}, - {"stage": "account.selection", "data": {"candidates": [{"id": "acct_high", "weight": 2}, {"id": "acct_low", "weight": 1}]}}, - {"stage": "attempt.failed", "data": {"kind": "unavailable", "recovery": {"replaySafe": true}}}, - {"stage": "retry.decided", "data": {"phase": "execute", "retryable": false, "clientRetrySuppressed": true, "replayBarrierReached": false}}, - {"stage": "provider.response.parse_gap", "data": {"reason": "invalid_json"}}, - {"stage": "provider.request.input", "data": {"input": {"omittedItems": 10}}}, - {"stage": "upstream.event", "data": {"truncated": true, "jsonValid": false}}, - ]}); - fixture.usage_detail.lock().unwrap().replace(UsageDetail { - request: usage_record_with_account( - "req_err", - "acct_err", - "private name", - "fixture@example.invalid", - "api_key", - Utc::now(), - ), - attempts: Vec::new(), - trace: Some(trace.clone()), - related_requests: Vec::new(), - }); - let (status, headers, file) = export(&fixture, "?requestId=req_err", true).await; - assert_eq!(status, StatusCode::OK, "{file}"); - assert_eq!( - headers[header::CONTENT_DISPOSITION], - "attachment; filename=cpr-diagnostics-req_err.zip" - ); - assert_eq!(headers[header::CACHE_CONTROL], "private, no-store"); - assert_eq!(file["schemaVersion"], 5); - assert_eq!( - file["exportTruncated"], false, - "capture loss is distinct from export truncation" - ); - for reason in [ - "events_evicted", - "critical_evidence_evicted", - "stage_coverage_incomplete", - "response_parse_failed", - "input_prefix_sample_limited", - "event_data_truncated", - "json_parse_failed", - ] { - assert!( - file["availability"]["gaps"] - .as_array() - .unwrap() - .iter() - .any(|gap| gap["reason"] == reason), - "missing gap {reason}" - ); - } - assert_eq!(file["requests"][0]["evidence"]["trace"], trace); - assert_eq!( - file["requests"][0]["evidence"]["incidentConfiguration"]["revision"], - 1 - ); - let details = &file["requests"][0]["errors"][0]["errorDetails"]; - assert_eq!( - details["upstream"]["error"]["code"], - "unknown_vendor_failure" - ); - assert_eq!(details["causes"][0], "TLS certificate verification failed"); - assert_eq!(file["requests"][0]["errors"][0]["accountId"], "acct_err"); - assert!( - file["availability"]["gaps"] - .as_array() - .unwrap() - .iter() - .any(|gap| gap["section"] == "environment") - ); - let text = file.to_string(); - for marker in [ - "fixture-authorization", - "fixture-cookie", - "fixture-access", - "fixture-refresh", - "fixture-password", - "fixture-user", - "fixture-bearer", - "fixture@example.invalid", - "private name", - "unrelated evidence must not leak", - "203.0.113.8", - ] { - assert!(!text.contains(marker), "leaked {marker}"); - } - assert!(text.contains("retry after 30 seconds")); -} - -#[tokio::test] -async fn background_error_exports_without_fabricating_a_model_request() { - let fixture = AdminTestFixture::new().await; - fixture.auth.insert_session("valid-session"); - let mut error = ops_error_record(); - error.source = "ops_event".into(); - error.request_id = None; - error.component = "worker".into(); - error.error_details = - Some(json!({"causes": ["database connection refused"], "upstream": null}).to_string()); - fixture.ops_errors.lock().unwrap().push(error); - let (status, _, file) = export(&fixture, "?errorId=err_snapshot", true).await; - assert_eq!(status, StatusCode::OK); - assert_eq!(file["requests"], json!([])); - assert_eq!(file["error"]["requestId"], Value::Null); - assert_eq!( - file["error"]["errorDetails"]["causes"][0], - "database connection refused" - ); -} - -#[tokio::test] -async fn error_survives_missing_request_and_nested_credentials_are_redacted() { - let fixture = AdminTestFixture::new().await; - fixture.auth.insert_session("valid-session"); - let mut error = ops_error_record(); - error.error_details = Some(json!({ - "cookies": "Cookie: a=fixture-cookie-a; b=fixture-cookie-b\nupstream timeout", - "uri": "https://provider.invalid/path?api_key=fixture-query&model=gpt-test", - "headers": [["Authorization", "fixture-tuple"], {"name": "Cookie", "value": "fixture-header"}], - }).to_string()); - fixture.ops_errors.lock().unwrap().push(error); - let (status, _, file) = export(&fixture, "?requestId=req_err", true).await; - assert_eq!(status, StatusCode::OK); - assert!(file["requests"][0]["evidence"].is_null()); - assert!( - file["availability"]["gaps"] - .as_array() - .unwrap() - .iter() - .any(|gap| gap["reason"] == "request_detail_unavailable") - ); - let text = file.to_string(); - for marker in [ - "fixture-cookie-a", - "fixture-cookie-b", - "fixture-query", - "fixture-tuple", - "fixture-header", - ] { - assert!(!text.contains(marker), "leaked {marker}"); - } - assert!(text.contains("upstream timeout")); - assert!(text.contains("model=gpt-test")); -} - -#[tokio::test] -async fn oversized_error_export_reports_truncation_instead_of_silent_loss() { - let fixture = AdminTestFixture::new().await; - fixture.auth.insert_session("valid-session"); - let mut error = ops_error_record(); - error.source = "ops_event".into(); - error.request_id = None; - error.message = "诊断文本".repeat(100_000); - fixture.ops_errors.lock().unwrap().push(error); - let (status, _, file) = export(&fixture, "?errorId=err_snapshot", true).await; - assert_eq!(status, StatusCode::OK); - assert_eq!(file["exportTruncated"], true); - assert!(file["redaction"]["truncatedValues"].as_u64().unwrap() > 0); - assert!(file["error"]["message"]["omittedBytes"].as_u64().unwrap() > 0); -} - -#[tokio::test] -async fn related_read_failures_and_limits_keep_primary_evidence() { - let fixture = AdminTestFixture::new().await; - fixture.auth.insert_session("valid-session"); - let mut related = vec![json!({"requestId": "req_err", "relation": "recovers"})]; - related.extend( - (0..10).map( - |index| json!({"requestId": format!("missing_{index}"), "relation": "recovered_by"}), - ), - ); - fixture.usage_detail.lock().unwrap().replace(UsageDetail { - request: usage_record_with_account( - "req_err", - "acct_err", - "fixture", - "fixture@example.invalid", - "api_key", - Utc::now(), - ), - attempts: Vec::new(), - trace: None, - related_requests: related, - }); - fixture - .ops_errors - .lock() - .unwrap() - .extend((0..130).map(|index| { - let mut error = ops_error_record(); - error.event_id = format!("error_{index}"); - error - })); - let (status, _, file) = export(&fixture, "?requestId=req_err", true).await; - assert_eq!(status, StatusCode::OK); - assert_eq!(file["requests"].as_array().unwrap().len(), 8); - assert_eq!(file["requests"][0]["errors"].as_array().unwrap().len(), 128); - assert_eq!( - file["requests"][0]["evidence"]["detail"]["requestId"], - "req_err" - ); - assert!(file["requests"][1]["evidence"].is_null()); - let gaps = file["availability"]["gaps"].as_array().unwrap(); - for reason in [ - "related_request_limit", - "error_record_limit", - "request_detail_unavailable", - "not_recorded_or_retained", - ] { - assert!( - gaps.iter().any(|gap| gap["reason"] == reason), - "missing {reason}" - ); - } -} - -#[tokio::test] -async fn credential_schemas_are_redacted_without_guessing_business_field_names() { - let fixture = AdminTestFixture::new().await; - fixture.auth.insert_session("valid-session"); - let mut error = ops_error_record(); - let business = json!({ - "token": {"input": 128, "output": 64}, - "credentials": {"status": "expired", "provider": "openai"}, - "secret": "tool argument name", "clientSecret": "business field description", - "accountId": "account-correlation", "userId": "user-correlation", - "planType": "plus", "status": "active", "accessTokenExpiresAt": "2026-10-16T00:00:00Z", - "error": {"code": "unknown_code", "message": "upstream capacity exceeded"}, - }); - error.error_details = Some(json!({ - "business": business, - "account": {"accessToken": "fixture-access", "refreshToken": "fixture-refresh", "idToken": "fixture-id"}, - "auth": {"OPENAI_API_KEY": "fixture-key", "personal_access_token": "fixture-pat", "tokens": { - "access_token": "fixture-official-access", "refresh_token": "fixture-official-refresh", - "id_token": "fixture-official-id", "account_id": "account-correlation", - }}, - }).to_string()); - fixture.ops_errors.lock().unwrap().push(error); - let (status, _, file) = export(&fixture, "?requestId=req_err", true).await; - assert_eq!(status, StatusCode::OK); - let details = &file["requests"][0]["errors"][0]["errorDetails"]; - assert_eq!(details["business"], business); - assert_eq!( - details["auth"]["tokens"]["account_id"], - "account-correlation" - ); - assert!(!file.to_string().contains("fixture-")); -} - -#[tokio::test] -async fn export_budget_keeps_format_target_and_existing_gap_records() { - let fixture = AdminTestFixture::new().await; - fixture.auth.insert_session("valid-session"); - fixture.usage_detail.lock().unwrap().replace(UsageDetail { - request: usage_record_with_account( - "req_err", - "acct_err", - "QA", - "qa@example.invalid", - "oauth", - Utc::now(), - ), - attempts: Vec::new(), - trace: Some(json!({"events": vec![vec![true; 32]; 3500]})), - related_requests: Vec::new(), - }); - let (status, _, file) = export(&fixture, "?requestId=req_err", true).await; - assert_eq!(status, StatusCode::OK); - assert_eq!(file["schemaVersion"], 5); - assert_eq!(file["source"], "gateway.diagnostics"); - assert_eq!(file["target"]["requestId"], "req_err"); - assert_eq!(file["exportTruncated"], true); - let gaps = file["availability"]["gaps"].as_array().unwrap(); - assert!(gaps.iter().any(|gap| gap["reason"] == "export_size_limit")); - assert!( - gaps.iter() - .any(|gap| gap["reason"] == "incident_policy_not_recorded") - ); - assert!(serde_json::to_vec_pretty(&file).unwrap().len() < 16 * 1024 * 1024); -} - -#[tokio::test] -async fn selected_event_is_exported_once_and_shares_the_total_error_budget() { - let fixture = AdminTestFixture::new().await; - fixture.auth.insert_session("valid-session"); - let mut selected = ops_error_record(); - selected.source = "ops_event".into(); - let mut errors = vec![selected]; - errors.extend((0..129).map(|index| { - let mut error = ops_error_record(); - error.source = "ops_event".into(); - error.event_id = format!("related_{index}"); - error - })); - fixture.ops_errors.lock().unwrap().extend(errors); - let (status, _, file) = export(&fixture, "?errorId=err_snapshot", true).await; - assert_eq!(status, StatusCode::OK); - assert_eq!(file["error"]["id"], "err_snapshot"); - let errors = file["requests"][0]["errors"].as_array().unwrap(); - assert_eq!(errors.len(), 127); - assert!(errors.iter().all(|error| error["id"] != "err_snapshot")); - assert!( - file["availability"]["gaps"] - .as_array() - .unwrap() - .iter() - .any(|gap| gap["reason"] == "error_record_limit") - ); -} - -#[tokio::test] -async fn inline_authentication_headers_are_redacted_without_losing_error_context() { - let fixture = AdminTestFixture::new().await; - fixture.auth.insert_session("valid-session"); - let mut error = ops_error_record(); - error.error_details = Some(json!({ - "headers": "x-api-key: fixture-api-key\nx-oai-is: fixture-session\nx-oai-is-update: fixture-update\nx-oai-attestation: fixture-attestation fixture-attestation-tail\nauthorization: Custom fixture-auth\nproxy-authorization: Custom fixture-proxy\nupstream timeout", - "message": "access-token=fixture-access; refresh-token=fixture-refresh; model=gpt-test", - }).to_string()); - fixture.ops_errors.lock().unwrap().push(error); - let (status, _, file) = export(&fixture, "?requestId=req_err", true).await; - assert_eq!(status, StatusCode::OK); - let text = file.to_string(); - for marker in [ - "fixture-api-key", - "fixture-session", - "fixture-update", - "fixture-attestation", - "fixture-attestation-tail", - "fixture-auth", - "fixture-proxy", - "fixture-access", - "fixture-refresh", - ] { - assert!(!text.contains(marker), "leaked {marker}"); - } - assert!(text.contains("upstream timeout")); - assert!(text.contains("model=gpt-test")); -} diff --git a/backend/crates/gateway-api/tests/admin/plugins/management.rs b/backend/crates/gateway-api/tests/admin/plugins/management.rs index 94b5e1cfd..099a2505a 100644 --- a/backend/crates/gateway-api/tests/admin/plugins/management.rs +++ b/backend/crates/gateway-api/tests/admin/plugins/management.rs @@ -83,7 +83,9 @@ impl ExecutionService for ModelExecution { assert_eq!(key.as_str(), "client-key"); Box::pin(async move { let prepared = self - .prepare_execution(crate::openai::authenticated_client("fixture-client-key")) + .prepare_execution(crate::data_plane::authenticated_client( + "fixture-client-key", + )) .await?; *self.cancellation.lock().unwrap() = Some(prepared.cancellation()); Ok(prepared) @@ -277,7 +279,7 @@ async fn management_calls_and_callbacks_preserve_headers_and_override_defaults() format!("/api/admin/plugins/extensions/{target}/api/echo"), format!("/plugins/callbacks/{target}/oauth?state=nonce"), ] { - let response = crate::openai::api_router_with_admin_and_execution( + let response = crate::data_plane::api_router_with_admin_and_execution( fixture.services.clone(), ModelExecution::new(ModelReply::Complete), ) @@ -337,10 +339,11 @@ async fn management_calls_and_callbacks_preserve_headers_and_override_defaults() async fn model_bridge_preserves_complete_request_and_response_headers() { let fixture = published_fixture().await; let execution = ModelExecution::new(ModelReply::Complete); - let response = crate::openai::api_router_with_admin_and_execution(fixture.services, execution) - .oneshot(model_request(false)) - .await - .unwrap(); + let response = + crate::data_plane::api_router_with_admin_and_execution(fixture.services, execution) + .oneshot(model_request(false)) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.headers()["set-cookie"], "fixture=value"); assert_eq!(response.headers()["www-authenticate"], "Bearer"); @@ -359,7 +362,7 @@ async fn model_bridge_preserves_complete_request_and_response_headers() { #[tokio::test] async fn model_bridge_distinguishes_host_authentication_from_plugin_session_errors() { let fixture = published_fixture().await; - let router = crate::openai::api_router_with_admin_and_execution( + let router = crate::data_plane::api_router_with_admin_and_execution( fixture.services, ModelExecution::new(ModelReply::SessionError), ); @@ -395,7 +398,7 @@ async fn model_bridge_revokes_while_waiting_for_the_first_response() { let fixture = published_fixture().await; let execution = ModelExecution::new(ModelReply::PendingResponse); let router = - crate::openai::api_router_with_admin_and_execution(fixture.services, execution.clone()); + crate::data_plane::api_router_with_admin_and_execution(fixture.services, execution.clone()); let request = tokio::spawn(router.oneshot(model_request(false))); tokio::time::timeout( std::time::Duration::from_secs(5), @@ -425,7 +428,7 @@ async fn model_bridge_revokes_and_closes_a_pending_stream() { let fixture = published_fixture().await; let execution = ModelExecution::new(ModelReply::PendingBody); let response = - crate::openai::api_router_with_admin_and_execution(fixture.services, execution.clone()) + crate::data_plane::api_router_with_admin_and_execution(fixture.services, execution.clone()) .oneshot(model_request(true)) .await .unwrap(); @@ -459,7 +462,7 @@ async fn model_bridge_authorization_rechecks_preserve_the_pending_frame_read() { .delayed_frame .store(true, Ordering::SeqCst); let response = - crate::openai::api_router_with_admin_and_execution(fixture.services, execution.clone()) + crate::data_plane::api_router_with_admin_and_execution(fixture.services, execution.clone()) .oneshot(model_request(true)) .await .unwrap(); @@ -564,7 +567,7 @@ async fn resource_request( for validator in validators { request = request.header("if-none-match", *validator); } - crate::openai::api_router_with_admin_and_execution( + crate::data_plane::api_router_with_admin_and_execution( fixture.services.clone(), ModelExecution::new(ModelReply::Complete), ) @@ -577,7 +580,7 @@ async fn resource_request( async fn large_html_resource_should_remain_uncompressed() { let fixture = published_fixture().await; let path = format!("ui/{}.html", "a".repeat(2048)); - let response = crate::openai::api_router_with_admin(fixture.services) + let response = crate::data_plane::api_router_with_admin(fixture.services) .oneshot( Request::builder() .uri(format!( @@ -756,7 +759,7 @@ async fn model_responses_requires_the_exact_authorized_target_before_execution() .unwrap() }; - let response = crate::openai::api_router_with_admin_and_execution( + let response = crate::data_plane::api_router_with_admin_and_execution( fixture.services.clone(), ModelExecution::new(ModelReply::Complete), ) @@ -773,7 +776,7 @@ async fn model_responses_requires_the_exact_authorized_target_before_execution() format!("plugin-instance-diagnostic/{}/8", "a".repeat(64)), format!("plugin-instance-diagnostic/{}/7", "b".repeat(64)), ] { - let response = crate::openai::api_router_with_admin_and_execution( + let response = crate::data_plane::api_router_with_admin_and_execution( fixture.services.clone(), ModelExecution::new(ModelReply::Complete), ) @@ -783,7 +786,7 @@ async fn model_responses_requires_the_exact_authorized_target_before_execution() assert_eq!(response.status(), StatusCode::CONFLICT); } - let response = crate::openai::api_router_with_admin_and_execution( + let response = crate::data_plane::api_router_with_admin_and_execution( fixture.services.clone(), ModelExecution::new(ModelReply::Complete), ) @@ -811,7 +814,7 @@ async fn protected_plugin_routes_require_admin_before_reading_bodies_but_public_ format!("{prefix}/models/responses?clientKeyId=client-key"), ), ] { - let response = crate::openai::api_router_with_admin_and_execution( + let response = crate::data_plane::api_router_with_admin_and_execution( fixture.services.clone(), ModelExecution::new(ModelReply::Complete), ) @@ -832,7 +835,7 @@ async fn protected_plugin_routes_require_admin_before_reading_bodies_but_public_ assert_eq!(response.status(), StatusCode::UNAUTHORIZED); assert_eq!(response.headers()["cache-control"], "no-store"); } - let response = crate::openai::api_router_with_admin_and_execution( + let response = crate::data_plane::api_router_with_admin_and_execution( fixture.services.clone(), ModelExecution::new(ModelReply::Complete), ) @@ -849,7 +852,7 @@ async fn protected_plugin_routes_require_admin_before_reading_bodies_but_public_ StatusCode::SERVICE_UNAVAILABLE, "公开资源仍要求可用的发布视图,不能绕过实例授权" ); - let response = crate::openai::api_router_with_admin_and_execution( + let response = crate::data_plane::api_router_with_admin_and_execution( fixture.services.clone(), ModelExecution::new(ModelReply::Complete), ) @@ -867,7 +870,7 @@ async fn protected_plugin_routes_require_admin_before_reading_bodies_but_public_ .unwrap(); assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE); - let response = crate::openai::api_router_with_admin_and_execution( + let response = crate::data_plane::api_router_with_admin_and_execution( fixture.services.clone(), ModelExecution::new(ModelReply::Complete), ) @@ -900,7 +903,7 @@ async fn public_callback_rejects_head_missing_duplicate_state_and_body_before_di // 合法 GET 没有管理 Cookie 仍进入服务;当前测试未发布视图,返回 503 而不是 401 ("GET", "state=one", "", StatusCode::SERVICE_UNAVAILABLE), ] { - let response = crate::openai::api_router_with_admin_and_execution( + let response = crate::data_plane::api_router_with_admin_and_execution( fixture.services.clone(), ModelExecution::new(ModelReply::Complete), ) diff --git a/backend/crates/gateway-api/tests/admin/settings.rs b/backend/crates/gateway-api/tests/admin/settings.rs index b87d44fa1..f9e7c38f4 100644 --- a/backend/crates/gateway-api/tests/admin/settings.rs +++ b/backend/crates/gateway-api/tests/admin/settings.rs @@ -37,6 +37,41 @@ async fn response_json(response: axum::response::Response) -> Value { serde_json::from_slice(&bytes).expect("parse response JSON") } +#[test] +fn backup_settings_report_secret_presence_without_serializing_the_secret() { + use gateway_admin::model::backup::BackupSettings; + use gateway_api::admin::backups::BackupSettingsView; + + for configured in [false, true] { + let settings = BackupSettings { + storage_revision: 1, + endpoint: None, + region: None, + bucket: None, + access_key_id: None, + secret_access_key: configured.then(|| secrecy::SecretString::from("fixture-secret")), + prefix: None, + force_path_style: false, + schedule_enabled: false, + cron_expression: None, + schedule_timezone: None, + retention_days: 0, + retention_count: 0, + next_run_at: None, + last_verified_at: None, + updated_at: chrono::Utc::now(), + }; + let response = serde_json::to_value(BackupSettingsView::from(( + settings, + gateway_api::TimePresenter::new(Default::default()), + ))) + .unwrap(); + assert_eq!(response["secretConfigured"], configured); + assert!(response.get("secretAccessKey").is_none()); + assert!(!response.to_string().contains("fixture-secret")); + } +} + fn update_body() -> Value { json!({ "configRevision": 7, @@ -55,9 +90,9 @@ fn update_body() -> Value { "maxWaitingPerKey": 0, "maxWaitingPerAccount": 0, "openaiGuardianReservedConcurrency": 0, - "openaiAccountAffinity": "relaxed", + "accountAffinity": "relaxed", "maxAccountRotations": 3, - "openaiSessionAffinityTtlHours": 24, + "sessionAffinityTtlHours": 24, "keyQueueTimeoutSeconds": 30, "accountQueueTimeoutSeconds": 30, "switchAccountOnQueueFailure": false, @@ -1027,6 +1062,10 @@ async fn pricing_routes_keep_manual_overrides_during_sync_and_reset_to_source() result["data"]["synced"]["openai"]["gpt-5.4"]["bands"]["standard"]["input"], "2.5" ); + assert_eq!( + result["data"]["supportedBands"]["openai"], + json!(["standard"]) + ); assert!(result["data"]["syncedAt"].is_string()); for _ in 0..2 { let response = app.clone().oneshot(request(Method::POST, "/api/admin/settings/pricing/update", Some(json!({ @@ -1567,9 +1606,9 @@ async fn account_affinity_and_rotation_budget_round_trip_and_reject_invalid_valu fixture.auth.insert_session("valid-session"); let mut body = update_body(); for (mode, rotations, ttl) in [("relaxed", 0, 1), ("preferred", 3, 24), ("strict", 31, 720)] { - body["openaiAccountAffinity"] = json!(mode); + body["accountAffinity"] = json!(mode); body["maxAccountRotations"] = json!(rotations); - body["openaiSessionAffinityTtlHours"] = json!(ttl); + body["sessionAffinityTtlHours"] = json!(ttl); let response = app(fixture.state()) .oneshot(request( Method::POST, @@ -1580,16 +1619,16 @@ async fn account_affinity_and_rotation_budget_round_trip_and_reject_invalid_valu .unwrap(); assert_eq!(response.status(), StatusCode::OK); let response = response_json(response).await; - assert_eq!(response["data"]["openaiAccountAffinity"], mode); + assert_eq!(response["data"]["accountAffinity"], mode); assert_eq!(response["data"]["maxAccountRotations"], rotations); - assert_eq!(response["data"]["openaiSessionAffinityTtlHours"], ttl); + assert_eq!(response["data"]["sessionAffinityTtlHours"], ttl); body["configRevision"] = response["data"]["configRevision"].clone(); } let saved = fixture.settings.settings.lock().unwrap().clone(); // 类型错误沿用 AdminJson 的 422,合法类型越界由字段校验返回 400 for (field, value, expected_status) in [ ( - "openaiAccountAffinity", + "accountAffinity", json!("unknown"), StatusCode::UNPROCESSABLE_ENTITY, ), @@ -1604,18 +1643,14 @@ async fn account_affinity_and_rotation_budget_round_trip_and_reject_invalid_valu json!(1.5), StatusCode::UNPROCESSABLE_ENTITY, ), + ("sessionAffinityTtlHours", json!(0), StatusCode::BAD_REQUEST), ( - "openaiSessionAffinityTtlHours", - json!(0), - StatusCode::BAD_REQUEST, - ), - ( - "openaiSessionAffinityTtlHours", + "sessionAffinityTtlHours", json!(721), StatusCode::BAD_REQUEST, ), ( - "openaiSessionAffinityTtlHours", + "sessionAffinityTtlHours", json!(1.5), StatusCode::UNPROCESSABLE_ENTITY, ), diff --git a/backend/crates/gateway-api/tests/admin/system.rs b/backend/crates/gateway-api/tests/admin/system.rs index e88182c07..a40a6883c 100644 --- a/backend/crates/gateway-api/tests/admin/system.rs +++ b/backend/crates/gateway-api/tests/admin/system.rs @@ -154,7 +154,7 @@ async fn update_detail_should_compress_json_starting_at_one_kib() { let fixture = AdminTestFixture::with_system(Arc::new(ProgressSystem { notes: Some(notes) })).await; fixture.auth.insert_session("valid-session"); - crate::openai::api_router_with_admin(fixture.services) + crate::data_plane::api_router_with_admin(fixture.services) .oneshot( Request::builder() .uri("/api/admin/system/update/detail") diff --git a/backend/crates/gateway-api/tests/openai/auth.rs b/backend/crates/gateway-api/tests/data_plane/auth.rs similarity index 99% rename from backend/crates/gateway-api/tests/openai/auth.rs rename to backend/crates/gateway-api/tests/data_plane/auth.rs index be72ab10d..81f91a4c9 100644 --- a/backend/crates/gateway-api/tests/openai/auth.rs +++ b/backend/crates/gateway-api/tests/data_plane/auth.rs @@ -11,7 +11,7 @@ use axum::http::{ }; use futures::future::BoxFuture; -use gateway_api::openai::auth::{ClientApiKeyAuthError, identify_codex_client}; +use gateway_api::data_plane::auth::{ClientApiKeyAuthError, identify_codex_client}; use gateway_core::{ engine::{ authentication::ClientAuthenticationRequest, diff --git a/backend/crates/gateway-api/tests/openai/chat_completions/http.rs b/backend/crates/gateway-api/tests/data_plane/chat_completions/http.rs similarity index 99% rename from backend/crates/gateway-api/tests/openai/chat_completions/http.rs rename to backend/crates/gateway-api/tests/data_plane/chat_completions/http.rs index e773b162e..aa2251b39 100644 --- a/backend/crates/gateway-api/tests/openai/chat_completions/http.rs +++ b/backend/crates/gateway-api/tests/data_plane/chat_completions/http.rs @@ -37,7 +37,7 @@ use serde_json::{Value, json}; use tower::ServiceExt as _; use super::{chat_request, completed, created, message}; -use crate::openai::{ +use crate::data_plane::{ api_router, authenticated_client, authenticated_client_for_provider_with_limit, middleware::{RequestMiddleware, ResponseFrameAction}, }; @@ -514,8 +514,8 @@ async fn early_middleware_failure_is_recorded_at_ingress_without_a_reserved_mode execution.clone(), admin.services, Vec::new(), - Arc::new(crate::openai::EmptyWorkerHealth), - Arc::new(crate::openai::TestLifecycle::default()), + Arc::new(crate::data_plane::EmptyWorkerHealth), + Arc::new(crate::data_plane::TestLifecycle::default()), diagnostics.clone(), ) .unwrap() diff --git a/backend/crates/gateway-api/tests/openai/chat_completions/mod.rs b/backend/crates/gateway-api/tests/data_plane/chat_completions/mod.rs similarity index 100% rename from backend/crates/gateway-api/tests/openai/chat_completions/mod.rs rename to backend/crates/gateway-api/tests/data_plane/chat_completions/mod.rs diff --git a/backend/crates/gateway-api/tests/openai/chat_completions/request.rs b/backend/crates/gateway-api/tests/data_plane/chat_completions/request.rs similarity index 100% rename from backend/crates/gateway-api/tests/openai/chat_completions/request.rs rename to backend/crates/gateway-api/tests/data_plane/chat_completions/request.rs diff --git a/backend/crates/gateway-api/tests/openai/chat_completions/response.rs b/backend/crates/gateway-api/tests/data_plane/chat_completions/response.rs similarity index 100% rename from backend/crates/gateway-api/tests/openai/chat_completions/response.rs rename to backend/crates/gateway-api/tests/data_plane/chat_completions/response.rs diff --git a/backend/crates/gateway-api/tests/openai/error.rs b/backend/crates/gateway-api/tests/data_plane/error.rs similarity index 99% rename from backend/crates/gateway-api/tests/openai/error.rs rename to backend/crates/gateway-api/tests/data_plane/error.rs index ee0fa7e3e..ea41dfe3f 100644 --- a/backend/crates/gateway-api/tests/openai/error.rs +++ b/backend/crates/gateway-api/tests/data_plane/error.rs @@ -8,7 +8,7 @@ use gateway_core::error::{ }; use gateway_core::upstream::UpstreamSendState; -use gateway_api::openai::error::{ +use gateway_api::data_plane::error::{ engine_error_response, gateway_error_contract, gateway_error_from_engine, gateway_error_response, openai_error_response, }; @@ -763,7 +763,7 @@ mod model_routing { use serde_json::{Value, json}; use tower::ServiceExt; - use crate::openai::{ + use crate::data_plane::{ IgnoredClientApiKeyUsage, UnusedAdmissions, UnusedContinuation, UnusedExecutionStore, }; @@ -781,7 +781,7 @@ mod model_routing { Arc::new(IgnoredClientApiKeyUsage), Arc::new(crate::support::RecordingDiagnostics::default()), ); - let response = crate::openai::api_router(Arc::new(execution)) + let response = crate::data_plane::api_router(Arc::new(execution)) .await .oneshot( Request::post("/v1/responses") @@ -816,7 +816,7 @@ mod model_routing { ), ] { for stream in [false, true] { - let snapshot = crate::openai::snapshot("sk_model_routing", "openai"); + let snapshot = crate::data_plane::snapshot("sk_model_routing", "openai"); let settings = snapshot .settings() .clone() @@ -856,7 +856,7 @@ async fn quota_recovery_http_response_uses_projection_without_replacing_upstream body.clone(), )); let error = EngineError::Provider(provider); - let response = gateway_api::openai::error::engine_error_response(&error); + let response = gateway_api::data_plane::error::engine_error_response(&error); assert_eq!(response.status(), StatusCode::BAD_REQUEST); assert_eq!(response.headers()["content-type"], "application/json"); assert!(!response.headers().contains_key("retry-after")); diff --git a/backend/crates/gateway-api/tests/data_plane/genai/contract.rs b/backend/crates/gateway-api/tests/data_plane/genai/contract.rs new file mode 100644 index 000000000..79aa0423a --- /dev/null +++ b/backend/crates/gateway-api/tests/data_plane/genai/contract.rs @@ -0,0 +1,340 @@ +//! 跨模块行为合同测试 + +use super::*; +use base64::{Engine as _, engine::general_purpose::STANDARD}; + +#[tokio::test] +async fn session_headers_reach_provider_context_except_when_declared_hop_by_hop() { + for connection in [None, Some("x-http-session-id")] { + let execution = Arc::new(Execution { + session: Mutex::new(Some(Session::new(vec![ProviderEvent::wire( + ProtocolWireEvent::raw_json( + GENAI_PROTOCOL, + Bytes::from_static(br#"{"candidates":[]}"#), + ) + .unwrap(), + )]))), + ..Default::default() + }); + let router = api_router(execution.clone()).await; + let mut req = request(&format!("{SHORT}:generateContent")); + req.headers_mut() + .insert("x-http-session-id", "native-session".parse().unwrap()); + req.headers_mut() + .insert("x-session-id", "fallback-session".parse().unwrap()); + if let Some(value) = connection { + req.headers_mut() + .insert("connection", value.parse().unwrap()); + } + let response = router.oneshot(req).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let captured = execution.seen.lock().unwrap().take().unwrap(); + let Operation::Generate(op) = captured.operation else { + panic!("generation") + }; + let headers = &op.protocol_payload().context()["headers"]; + assert_eq!( + headers.get("x-http-session-id").and_then(Value::as_str), + connection.is_none().then_some("native-session") + ); + assert_eq!(headers["x-session-id"], "fallback-session"); + } +} + +#[tokio::test] +async fn native_tool_call_and_client_replay_keep_the_original_wire() { + let raw = Bytes::from_static(br#"{ "candidates":[{"finishReason":"STOP","content":{"role":"model","parts":[{"functionCall":{"name":"read","args":{"id":42}},"thoughtSignature":"c2ln","futurePart":true}]}}],"futureResponse":1 }"#); + let event = + ProviderEvent::wire(ProtocolWireEvent::raw_json(GENAI_PROTOCOL, raw.clone()).unwrap()); + let execution = Arc::new(Execution { + session: Mutex::new(Some(Session::new(vec![event]))), + ..Default::default() + }); + let router = api_router(execution.clone()).await; + let response = router + .clone() + .oneshot(request(&format!("{SHORT}:generateContent"))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let first_body = to_bytes(response.into_body(), 2048).await.unwrap(); + assert_eq!(first_body, raw); + let captured = execution.seen.lock().unwrap().take().unwrap(); + assert_eq!(captured.public_model.as_str(), "model-a"); + let Operation::Generate(op) = captured.operation else { + panic!("expected model operation") + }; + let p = op.protocol_payload(); + assert_eq!(p.raw_json_body().unwrap().as_ref(), BODY.as_bytes()); + let context = json!({ + "stream": false, + "headers": {"user-agent": "fixture-client/1.0", "x-goog-api-client": "fixture-transport/1.0"}, + "opaque_request_headers": [ + ["x-goog-api-client", STANDARD.encode("fixture-transport/1.0")], + ["x-goog-user-project", STANDARD.encode("untrusted")] + ] + }); + assert_eq!(p.context(), context.as_object().unwrap()); + + let first: Value = serde_json::from_slice(&first_body).unwrap(); + let mut history: Value = serde_json::from_str(BODY).unwrap(); + history["contents"].as_array_mut().unwrap().extend([ + first["candidates"][0]["content"].clone(), + json!({"role":"user","parts":[{"functionResponse":{"name":"read","response":{"value":42}}}]}), + ]); + let followup = serde_json::to_vec_pretty(&history).unwrap(); + let reply = Bytes::from_static( + br#"{ "candidates":[{"finishReason":"STOP","content":{"parts":[{"text":"42"}]}}] }"#, + ); + *execution.session.lock().unwrap() = Some(Session::new(vec![ProviderEvent::wire( + ProtocolWireEvent::raw_json(GENAI_PROTOCOL, reply.clone()).unwrap(), + )])); + let mut next = request(&format!("{SHORT}:generateContent")); + *next.body_mut() = Body::from(followup.clone()); + let response = router.oneshot(next).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(to_bytes(response.into_body(), 2048).await.unwrap(), reply); + let captured = execution.seen.lock().unwrap().take().unwrap(); + assert_eq!( + captured.operation.middleware_body().unwrap().as_ref(), + followup + ); +} + +#[tokio::test] +async fn business_headers_keep_multi_value_bytes_without_credentials_or_hop_by_hop_fields() { + let execution = Arc::new(Execution { + session: Mutex::new(Some(Session::new(vec![ProviderEvent::wire( + ProtocolWireEvent::raw_json( + GENAI_PROTOCOL, + Bytes::from_static(br#"{"candidates":[]}"#), + ) + .unwrap(), + )]))), + ..Default::default() + }); + let router = api_router(execution.clone()).await; + let mut req = request(&format!("{SHORT}:generateContent")); + for (name, value) in [ + ("x-business", b"one\x80".as_slice()), + ("x-business", b"two"), + ("connection", b"x-hop"), + ("x-hop", b"private"), + ("cookie", b"private"), + ("x-goog-api-key", b"private"), + ("traceparent", b"original-trace"), + ] { + req.headers_mut() + .append(name, axum::http::HeaderValue::from_bytes(value).unwrap()); + } + assert_eq!(router.oneshot(req).await.unwrap().status(), StatusCode::OK); + let captured = execution.seen.lock().unwrap().take().unwrap(); + let Operation::Generate(op) = captured.operation else { + panic!("generation") + }; + let headers = op.protocol_payload().context()["opaque_request_headers"] + .as_array() + .unwrap(); + let values: Vec<_> = headers + .iter() + .filter(|pair| pair[0] == "x-business") + .map(|pair| STANDARD.decode(pair[1].as_str().unwrap()).unwrap()) + .collect(); + assert_eq!(values, vec![b"one\x80".to_vec(), b"two".to_vec()]); + for name in [ + "authorization", + "cookie", + "x-goog-api-key", + "connection", + "x-hop", + "x-request-id", + ] { + assert!( + !headers.iter().any(|pair| pair[0] == name), + "unexpected {name}" + ); + } + assert!( + headers + .iter() + .any(|pair| pair == &json!(["traceparent", STANDARD.encode("original-trace")])) + ); +} + +#[tokio::test] +async fn committed_stream_delivers_raw_error_once() { + let first = "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"hi\"}]}}]}\r\n\r\n"; + let last = "data: { \"error\":{\"code\":429,\"status\":\"RESOURCE_EXHAUSTED\",\"message\":\"slow down\"} }\r\n\r\n"; + let mut session = Session::new(vec![wire_frame(first), wire_frame(last)]); + session.finish = Finish::Error; + let execution = Arc::new(Execution { + session: Mutex::new(Some(session)), + ..Default::default() + }); + let response = api_router(execution) + .await + .oneshot(request(&format!("{SHORT}:streamGenerateContent?alt=sse"))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + to_bytes(response.into_body(), 2048).await.unwrap().as_ref(), + [first, last].concat().as_bytes() + ); +} + +#[tokio::test] +async fn stream_preserves_finish_and_later_usage_bytes_before_eof() { + let first = "data: { \"candidates\":[{\"finishReason\":\"STOP\"}], \"error\":null }\r\n\r\n"; + let last = "data: {\"usageMetadata\":{\"totalTokenCount\":7}}\r\n\r\n"; + let mut events = vec![wire_frame(first), wire_frame(last)]; + events.push(ProviderEvent::canonical(GatewayEvent::Completed( + ResponseMeta::new("id", "model-a"), + ))); + let session = Session::new(events); + let trace = session.trace.clone(); + let execution = Arc::new(Execution { + session: Mutex::new(Some(session)), + ..Default::default() + }); + let response = api_router(execution) + .await + .oneshot(request(&format!("{SHORT}:streamGenerateContent?alt=sse"))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + to_bytes(response.into_body(), 2048).await.unwrap().as_ref(), + [first, last].concat().as_bytes() + ); + assert_eq!(trace.commits.load(Ordering::SeqCst), 1); + assert!(trace.finalized.load(Ordering::SeqCst)); +} + +#[tokio::test] +async fn metric_validates_bearer_and_invalid_generation_never_starts_inference() { + let execution = Arc::new(Execution::default()); + let router = api_router(execution.clone()).await; + for (uri, authenticated, status) in [ + ( + "/v1beta:recordCodeAssistMetrics", + false, + StatusCode::UNAUTHORIZED, + ), + ("/v1beta:recordCodeAssistMetrics", true, StatusCode::OK), + ( + "/v1beta/models/model:streamGenerateContent?alt=json", + true, + StatusCode::BAD_REQUEST, + ), + ( + "/v1beta/models/a%2Fb:generateContent", + true, + StatusCode::BAD_REQUEST, + ), + ] { + let mut req = request(uri); + if !authenticated { + req.headers_mut().remove("authorization"); + } + let res = router.clone().oneshot(req).await.unwrap(); + assert_eq!(res.status(), status); + let value: Value = + serde_json::from_slice(&to_bytes(res.into_body(), 2048).await.unwrap()).unwrap(); + if status.is_success() { + assert_eq!(value, json!({})); + } else { + assert_eq!(value["error"]["code"], status.as_u16()); + } + } + assert!(execution.seen.lock().unwrap().is_none()); +} + +#[tokio::test] +async fn unknown_paths_and_methods_return_google_rpc_errors() { + let router = api_router(Arc::new(Execution::default())).await; + for (request, status, rpc_status) in [ + ( + request("/v1beta/does-not-exist"), + StatusCode::NOT_FOUND, + "NOT_FOUND", + ), + ( + Request::get(format!("{SHORT}:generateContent")) + .body(Body::empty()) + .unwrap(), + StatusCode::METHOD_NOT_ALLOWED, + "INVALID_ARGUMENT", + ), + ] { + let response = router.clone().oneshot(request).await.unwrap(); + assert_eq!(response.status(), status); + let bytes = to_bytes(response.into_body(), 1024).await.unwrap(); + let payload: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(payload["error"]["code"], status.as_u16()); + assert_eq!(payload["error"]["status"], rpc_status); + } +} + +#[tokio::test] +async fn count_preserves_native_wire_and_uses_url_model_without_streaming() { + let raw = Bytes::from_static(br#"{ "totalTokens":42,"cachedContentTokenCount":7 }"#); + let execution = Arc::new(Execution { + session: Mutex::new(Some(Session::new(vec![ProviderEvent::wire( + ProtocolWireEvent::raw_json(GENAI_PROTOCOL, raw.clone()).unwrap(), + )]))), + ..Default::default() + }); + let response = api_router(execution.clone()) + .await + .oneshot(request(&format!("{SHORT}:countTokens"))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(to_bytes(response.into_body(), 2048).await.unwrap(), raw); + let seen = execution.seen.lock().unwrap().take().unwrap(); + assert_eq!(seen.public_model.as_str(), "model-a"); + assert!(!seen.metadata.stream); + let Operation::CountTokens(count) = seen.operation else { + panic!("expected token count") + }; + assert!(count.requires_native_protocol()); + assert_eq!(count.payload().body().as_ref(), BODY.as_bytes()); +} + +#[tokio::test] +async fn invalid_count_result_is_not_a_successful_response() { + for raw in [ + br#"{}"#.as_slice(), + br#"{"totalTokens":-1}"#, + br#"{"totalTokens":"42"}"#, + ] { + let execution = Arc::new(Execution { + session: Mutex::new(Some(Session::new(vec![ProviderEvent::wire( + ProtocolWireEvent::raw_json(GENAI_PROTOCOL, Bytes::copy_from_slice(raw)).unwrap(), + )]))), + ..Default::default() + }); + let response = api_router(execution) + .await + .oneshot(request(&format!("{SHORT}:countTokens"))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR); + let body: Value = + serde_json::from_slice(&to_bytes(response.into_body(), 2048).await.unwrap()).unwrap(); + assert_eq!(body["error"]["code"], 500); + } +} + +#[tokio::test] +async fn count_rejects_sse_before_execution() { + let execution = Arc::new(Execution::default()); + let response = api_router(execution.clone()) + .await + .oneshot(request(&format!("{SHORT}:countTokens?alt=sse"))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert!(execution.seen.lock().unwrap().is_none()); +} diff --git a/backend/crates/gateway-api/tests/data_plane/genai/mod.rs b/backend/crates/gateway-api/tests/data_plane/genai/mod.rs new file mode 100644 index 000000000..b2e3c4315 --- /dev/null +++ b/backend/crates/gateway-api/tests/data_plane/genai/mod.rs @@ -0,0 +1,128 @@ +//! 核对 GenAI 原生路由、归属边界、原始字节及晚到用量的交付 + +mod contract; +mod models; +use std::sync::{Arc, Mutex, atomic::Ordering}; + +use axum::{ + body::{Body, Bytes, to_bytes}, + http::{Request, StatusCode}, +}; +use futures::future::BoxFuture; +use gateway_core::{ + engine::{ + authentication::ClientAuthenticationRequest, + execution::{ + AuthenticatedClient, ClientAuthenticationError, ExecutionService, + PreparedExecutionRequest, PreparedRootExecution, StartExecution, + StartProviderExecution, StartedExecution, + }, + }, + error::GatewayError, + event::{GatewayEvent, ProtocolWireEvent, ProviderEvent, ResponseMeta}, + operation::Operation, + routing::PublicModelId, +}; +use gateway_protocol::genai::GENAI_PROTOCOL; +use serde_json::{Value, json}; +use tower::ServiceExt as _; + +use super::{api_router, authenticated_client}; +use crate::support::generation::{Finish, Session}; + +const KEY: &str = "sk_genai_test"; +const SHORT: &str = "/v1beta/models/model-a"; +const BODY: &str = r#"{ "contents":[{"role":"user","parts":[{"text":"Read record 42"}]}],"tools":[{"functionDeclarations":[{"name":"read","parameters":{"type":"OBJECT"}}]}],"future":{"a":1} }"#; + +#[derive(Default)] +struct Execution { + client: Option, + session: Mutex>, + seen: Mutex>, +} + +impl ExecutionService for Execution { + fn authenticate(&self, key: &str) -> Result { + if key == KEY { + Ok(self + .client + .clone() + .unwrap_or_else(|| authenticated_client(key))) + } else { + Err(ClientAuthenticationError::InvalidKey) + } + } + fn verify_request( + &self, + request: ClientAuthenticationRequest, + ) -> BoxFuture<'_, Result> { + self.authenticate_request(request) + } + fn public_models(&self, _: &AuthenticatedClient) -> Vec { + vec![] + } + fn contains_public_model(&self, _: &AuthenticatedClient, _: &PublicModelId) -> bool { + true + } + fn start_prepared( + &self, + root: PreparedRootExecution, + request: PreparedExecutionRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + assert!(match &request.operation { + Operation::Generate(generate) => generate.requires_native_protocol(), + Operation::CountTokens(count) => count.requires_native_protocol(), + _ => false, + }); + let stream = request.metadata.stream; + *self.seen.lock().unwrap() = Some(request); + Ok(StartedExecution { + request_id: root.request_id().clone(), + created_at: std::time::SystemTime::now(), + stream, + session: Box::new( + self.session + .lock() + .unwrap() + .take() + .expect("expected inference"), + ), + }) + }) + } + fn start(&self, _: StartExecution) -> BoxFuture<'_, Result> { + panic!("GenAI requires prepared model admission"); + } + fn start_provider_endpoint( + &self, + _: StartProviderExecution, + ) -> BoxFuture<'_, Result> { + panic!("GenAI requires model authorization"); + } +} + +fn request(url: &str) -> Request { + Request::post(url) + .header("authorization", format!("Bearer {KEY}")) + .header("user-agent", "fixture-client/1.0") + .header("x-goog-api-client", "fixture-transport/1.0") + .header("x-goog-user-project", "untrusted") + .body(Body::from(BODY)) + .unwrap() +} + +fn wire_frame(frame: &'static str) -> ProviderEvent { + let value = serde_json::from_str(frame.strip_prefix("data: ").unwrap().trim()).unwrap(); + ProviderEvent::wire( + ProtocolWireEvent::json_with_raw_sse_metadata( + GENAI_PROTOCOL, + None, + value, + Bytes::from_static(frame.as_bytes()), + None, + None, + ) + .unwrap(), + ) +} diff --git a/backend/crates/gateway-api/tests/data_plane/genai/models.rs b/backend/crates/gateway-api/tests/data_plane/genai/models.rs new file mode 100644 index 000000000..c77797e8e --- /dev/null +++ b/backend/crates/gateway-api/tests/data_plane/genai/models.rs @@ -0,0 +1,125 @@ +//! 原生模型目录的分页、详情、鉴权与能力投影 + +use super::*; +use gateway_core::{ + operation::OperationKind, + routing::{ + ConfigRevision, ModelCapabilities, ProviderKind, ProviderModel, RuntimeSnapshot, + UpstreamModelId, + }, +}; + +fn client() -> AuthenticatedClient { + let source = authenticated_client(KEY); + let caps = ModelCapabilities::new( + [OperationKind::Generate, OperationKind::CountTokens].into(), + None, + ) + .with_generation_protocol(GENAI_PROTOCOL); + let provider = ProviderKind::new("openai").unwrap(); + let models = ["model-a", "model-b", "model-c", "unreachable/name"].map(|id| { + ProviderModel::new( + provider.clone(), + UpstreamModelId::new(id).unwrap(), + caps.clone(), + ) + }); + let snapshot = RuntimeSnapshot::new( + ConfigRevision::new(1).unwrap(), + source.snapshot().settings().clone(), + vec![provider], + models.into(), + vec![source.policy().clone()], + ) + .unwrap(); + super::super::authenticated_client_from_snapshot(KEY, snapshot) +} + +async fn query(router: &axum::Router, path: &str, authorized: bool) -> (StatusCode, Value) { + let mut request = Request::get(path); + if authorized { + request = request.header("authorization", format!("Bearer {KEY}")); + } + let response = router + .clone() + .oneshot(request.body(Body::empty()).unwrap()) + .await + .unwrap(); + let status = response.status(); + let value = + serde_json::from_slice(&to_bytes(response.into_body(), 8192).await.unwrap()).unwrap(); + (status, value) +} + +#[tokio::test] +async fn list_pages_and_details_expose_only_supported_native_models() { + let execution = Arc::new(Execution { + client: Some(client()), + ..Default::default() + }); + let router = api_router(execution.clone()).await; + let (status, first) = query(&router, "/v1beta/models?pageSize=2", true).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(first["models"].as_array().unwrap().len(), 2); + assert_eq!(first["models"][0]["name"], "models/model-a"); + assert_eq!( + first["models"][0]["supportedGenerationMethods"], + json!(["generateContent", "streamGenerateContent", "countTokens"]) + ); + assert!(first["models"][0].get("inputTokenLimit").is_none()); + let token = first["nextPageToken"].as_str().unwrap(); + let (_, second) = query( + &router, + &format!("/v1beta/models?pageSize=2&pageToken={token}"), + true, + ) + .await; + assert_eq!( + second["models"], + json!([{"name":"models/model-c","displayName":"model-c","supportedGenerationMethods":["generateContent","streamGenerateContent","countTokens"]}]) + ); + assert!(second.get("nextPageToken").is_none()); + let (status, _) = query( + &router, + &format!("/v1beta/models?pageSize=1&pageToken={token}"), + true, + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let (status, detail) = query(&router, "/v1beta/models/model-a", true).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(detail, first["models"][0]); + assert!(execution.seen.lock().unwrap().is_none()); + let (_, empty) = query( + &api_router(Arc::new(Execution::default())).await, + "/v1beta/models", + true, + ) + .await; + assert_eq!(empty, json!({"models":[]})); +} + +#[tokio::test] +async fn directory_errors_follow_google_rpc_and_require_authentication() { + let router = api_router(Arc::new(Execution { + client: Some(client()), + ..Default::default() + })) + .await; + for (path, authorized, status) in [ + ("/v1beta/models", false, StatusCode::UNAUTHORIZED), + ("/v1beta/models/model-a", false, StatusCode::UNAUTHORIZED), + ("/v1beta/models/unknown", true, StatusCode::NOT_FOUND), + ("/v1beta/models?pageSize=-1", true, StatusCode::BAD_REQUEST), + ( + "/v1beta/models?pageToken=bad", + true, + StatusCode::BAD_REQUEST, + ), + ("/v1beta/models?pageSize=abc", true, StatusCode::BAD_REQUEST), + ] { + let (actual, body) = query(&router, path, authorized).await; + assert_eq!(actual, status, "{path}"); + assert_eq!(body["error"]["code"], status.as_u16(), "{path}"); + } +} diff --git a/backend/crates/gateway-api/tests/openai/group_permissions.rs b/backend/crates/gateway-api/tests/data_plane/group_permissions.rs similarity index 100% rename from backend/crates/gateway-api/tests/openai/group_permissions.rs rename to backend/crates/gateway-api/tests/data_plane/group_permissions.rs diff --git a/backend/crates/gateway-api/tests/openai/images/mod.rs b/backend/crates/gateway-api/tests/data_plane/images/mod.rs similarity index 98% rename from backend/crates/gateway-api/tests/openai/images/mod.rs rename to backend/crates/gateway-api/tests/data_plane/images/mod.rs index 0ee9f056f..e7d7f94f3 100644 --- a/backend/crates/gateway-api/tests/openai/images/mod.rs +++ b/backend/crates/gateway-api/tests/data_plane/images/mod.rs @@ -51,7 +51,7 @@ struct ImageExecution { committed_statuses: Arc>>, error_statuses: Arc>>, fail_with_upstream_response: bool, - middleware: Option>, + middleware: Option>, } impl ImageExecution { @@ -264,7 +264,7 @@ impl ExecutionSession for ImageSession { #[tokio::test] async fn image_json_routes_should_preserve_both_directions_without_decoding() { let mut execution = ImageExecution::new(); - let middleware = Arc::new(crate::openai::middleware::RequestMiddleware { + let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware { expected_operation: Some(OperationKind::GenerateImage), committed_statuses: Some(execution.committed_statuses.clone()), ..Default::default() diff --git a/backend/crates/gateway-api/tests/openai/images/request.rs b/backend/crates/gateway-api/tests/data_plane/images/request.rs similarity index 99% rename from backend/crates/gateway-api/tests/openai/images/request.rs rename to backend/crates/gateway-api/tests/data_plane/images/request.rs index ca403cddc..0bb741b2e 100644 --- a/backend/crates/gateway-api/tests/openai/images/request.rs +++ b/backend/crates/gateway-api/tests/data_plane/images/request.rs @@ -324,7 +324,7 @@ async fn multipart_edit_should_not_inherit_the_default_extractor_size_limit() { #[tokio::test] async fn request_middleware_should_run_before_multipart_decoding() { let mut execution = ImageExecution::new(); - let middleware = Arc::new(crate::openai::middleware::RequestMiddleware { + let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware { expected_operation: Some(gateway_core::operation::OperationKind::GenerateImage), short_circuit_json: Some(bytes::Bytes::from_static(IMAGE_RESPONSE)), ..Default::default() diff --git a/backend/crates/gateway-api/tests/openai/live/mod.rs b/backend/crates/gateway-api/tests/data_plane/live/mod.rs similarity index 100% rename from backend/crates/gateway-api/tests/openai/live/mod.rs rename to backend/crates/gateway-api/tests/data_plane/live/mod.rs diff --git a/backend/crates/gateway-api/tests/openai/live/websocket.rs b/backend/crates/gateway-api/tests/data_plane/live/websocket.rs similarity index 99% rename from backend/crates/gateway-api/tests/openai/live/websocket.rs rename to backend/crates/gateway-api/tests/data_plane/live/websocket.rs index 65dcca64e..7606c77ad 100644 --- a/backend/crates/gateway-api/tests/openai/live/websocket.rs +++ b/backend/crates/gateway-api/tests/data_plane/live/websocket.rs @@ -162,7 +162,7 @@ async fn blocked_relay( execution, admin.services, Vec::new(), - Arc::new(crate::openai::EmptyWorkerHealth), + Arc::new(crate::data_plane::EmptyWorkerHealth), Arc::new(Lifecycle(trace.clone())), Arc::new(crate::support::RecordingDiagnostics::default()), ) diff --git a/backend/crates/gateway-api/tests/openai/messages.rs b/backend/crates/gateway-api/tests/data_plane/messages.rs similarity index 100% rename from backend/crates/gateway-api/tests/openai/messages.rs rename to backend/crates/gateway-api/tests/data_plane/messages.rs diff --git a/backend/crates/gateway-api/tests/openai/middleware/mod.rs b/backend/crates/gateway-api/tests/data_plane/middleware/fixture.rs similarity index 88% rename from backend/crates/gateway-api/tests/openai/middleware/mod.rs rename to backend/crates/gateway-api/tests/data_plane/middleware/fixture.rs index a61a3a182..f337f4942 100644 --- a/backend/crates/gateway-api/tests/openai/middleware/mod.rs +++ b/backend/crates/gateway-api/tests/data_plane/middleware/fixture.rs @@ -29,27 +29,27 @@ use gateway_core::routing::extensions::ExtensionSetReference; /// OpenAI API 入口共用的中间件夹具;授权和 RPC 由 Runtime 行为测试覆盖 #[derive(Debug, Default)] -pub(super) struct RequestMiddleware { - pub(super) endpoints: Mutex>, - pub(super) live_leases: Arc, - pub(super) expected_operation: Option, - pub(super) committed_statuses: Option>>>, - pub(super) response_actions: Mutex>, - pub(super) response_headers: Vec, - pub(super) short_circuit_json: Option, - pub(super) settings: +pub(in crate::data_plane) struct RequestMiddleware { + pub(in crate::data_plane) endpoints: Mutex>, + pub(in crate::data_plane) live_leases: Arc, + pub(in crate::data_plane) expected_operation: Option, + pub(in crate::data_plane) committed_statuses: Option>>>, + pub(in crate::data_plane) response_actions: Mutex>, + pub(in crate::data_plane) response_headers: Vec, + pub(in crate::data_plane) short_circuit_json: Option, + pub(in crate::data_plane) settings: Option, } #[derive(Debug, Clone)] -pub(super) enum ResponseFrameAction { +pub(in crate::data_plane) enum ResponseFrameAction { Continue, Replace(Bytes), Drop, } impl RequestMiddleware { - pub(super) fn frozen(self: &Arc) -> FrozenMiddlewarePlan { + pub(in crate::data_plane) fn frozen(self: &Arc) -> FrozenMiddlewarePlan { self.live_leases.fetch_add(1, Ordering::SeqCst); FrozenMiddlewarePlan::new( self.clone(), @@ -61,7 +61,10 @@ impl RequestMiddleware { } #[must_use] - pub(super) fn with_response_actions(self, actions: Vec) -> Self { + pub(in crate::data_plane) fn with_response_actions( + self, + actions: Vec, + ) -> Self { Self { response_actions: Mutex::new(actions.into()), ..self @@ -69,7 +72,10 @@ impl RequestMiddleware { } #[must_use] - pub(super) fn with_response_headers(self, headers: Vec) -> Self { + pub(in crate::data_plane) fn with_response_headers( + self, + headers: Vec, + ) -> Self { Self { response_headers: headers, ..self @@ -77,7 +83,7 @@ impl RequestMiddleware { } #[must_use] - pub(super) fn with_json_short_circuit(self, body: Bytes) -> Self { + pub(in crate::data_plane) fn with_json_short_circuit(self, body: Bytes) -> Self { Self { short_circuit_json: Some(body), ..self diff --git a/backend/crates/gateway-api/tests/data_plane/middleware/mod.rs b/backend/crates/gateway-api/tests/data_plane/middleware/mod.rs new file mode 100644 index 000000000..b20714f48 --- /dev/null +++ b/backend/crates/gateway-api/tests/data_plane/middleware/mod.rs @@ -0,0 +1,5 @@ +//! 数据面中间件的共享测试夹具入口 + +mod fixture; + +pub(super) use fixture::{RequestMiddleware, ResponseFrameAction}; diff --git a/backend/crates/gateway-api/tests/openai/mod.rs b/backend/crates/gateway-api/tests/data_plane/mod.rs similarity index 98% rename from backend/crates/gateway-api/tests/openai/mod.rs rename to backend/crates/gateway-api/tests/data_plane/mod.rs index f3967198a..fd5b66442 100644 --- a/backend/crates/gateway-api/tests/openai/mod.rs +++ b/backend/crates/gateway-api/tests/data_plane/mod.rs @@ -2,15 +2,17 @@ mod auth; mod chat_completions; -mod endpoint; mod error; +mod genai; mod group_permissions; mod images; mod live; mod messages; mod middleware; mod models; +mod openai_endpoints; mod peer_link; +mod provider_endpoints; mod responses; mod router; mod search; @@ -231,6 +233,13 @@ pub(super) fn authenticated_client_for_provider_with_limit( .clone() .with_responses_max_decompressed_body_bytes(bytes as u64); let snapshot = snapshot.with_settings(&settings).unwrap(); + authenticated_client_from_snapshot(plaintext, snapshot) +} + +pub(super) fn authenticated_client_from_snapshot( + plaintext: &str, + snapshot: RuntimeSnapshot, +) -> AuthenticatedClient { let source = DefaultExecutionService::new( RuntimeSnapshotHandle::new(snapshot), Arc::new(UnusedExecutionStore), diff --git a/backend/crates/gateway-api/tests/openai/models.rs b/backend/crates/gateway-api/tests/data_plane/models.rs similarity index 98% rename from backend/crates/gateway-api/tests/openai/models.rs rename to backend/crates/gateway-api/tests/data_plane/models.rs index c03160627..d352bdf1e 100644 --- a/backend/crates/gateway-api/tests/openai/models.rs +++ b/backend/crates/gateway-api/tests/data_plane/models.rs @@ -117,7 +117,7 @@ pub(super) struct ModelsExecution { presentation: Option, native: Option, ProviderCatalogUnavailable>>, requested_versions: Mutex>, - middleware: Option>, + middleware: Option>, } impl ModelsExecution { @@ -295,7 +295,7 @@ fn authorized_request(path: &str) -> Request { async fn request_settings_reach_query_terminal_without_mutating_authenticated_baseline() { let mut execution = ModelsExecution::new(); Arc::get_mut(&mut execution).unwrap().middleware = - Some(Arc::new(crate::openai::middleware::RequestMiddleware { + Some(Arc::new(crate::data_plane::middleware::RequestMiddleware { settings: Some(|settings| { let mut runtime = serde_json::to_value(&settings.runtime).unwrap(); runtime["model_mappings"] = serde_json::json!({"model-a":"plugin-model"}); @@ -334,7 +334,7 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba async fn model_queries_enter_the_same_chain_after_auth_and_hold_generation_until_body_end() { use std::sync::atomic::Ordering; - let middleware = Arc::new(crate::openai::middleware::RequestMiddleware::default()); + let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware::default()); let mut execution = ModelsExecution::new(); Arc::get_mut(&mut execution).unwrap().middleware = Some(middleware.clone()); let app = api_router(execution).await; @@ -371,7 +371,7 @@ async fn model_queries_enter_the_same_chain_after_auth_and_hold_generation_until #[tokio::test] async fn model_query_middleware_short_circuit_sets_json_content_type_without_calling_terminal() { let middleware = Arc::new( - crate::openai::middleware::RequestMiddleware::default().with_json_short_circuit( + crate::data_plane::middleware::RequestMiddleware::default().with_json_short_circuit( Bytes::from_static(br#"{"object":"list","data":[],"source":"middleware"}"#), ), ); diff --git a/backend/crates/gateway-api/tests/openai/endpoint.rs b/backend/crates/gateway-api/tests/data_plane/openai_endpoints.rs similarity index 100% rename from backend/crates/gateway-api/tests/openai/endpoint.rs rename to backend/crates/gateway-api/tests/data_plane/openai_endpoints.rs diff --git a/backend/crates/gateway-api/tests/openai/peer_link/catalog.rs b/backend/crates/gateway-api/tests/data_plane/peer_link/catalog.rs similarity index 100% rename from backend/crates/gateway-api/tests/openai/peer_link/catalog.rs rename to backend/crates/gateway-api/tests/data_plane/peer_link/catalog.rs diff --git a/backend/crates/gateway-api/tests/openai/peer_link/mod.rs b/backend/crates/gateway-api/tests/data_plane/peer_link/mod.rs similarity index 100% rename from backend/crates/gateway-api/tests/openai/peer_link/mod.rs rename to backend/crates/gateway-api/tests/data_plane/peer_link/mod.rs diff --git a/backend/crates/gateway-api/tests/provider.rs b/backend/crates/gateway-api/tests/data_plane/provider_endpoints.rs similarity index 96% rename from backend/crates/gateway-api/tests/provider.rs rename to backend/crates/gateway-api/tests/data_plane/provider_endpoints.rs index c1ac01534..3ceebbdc3 100644 --- a/backend/crates/gateway-api/tests/provider.rs +++ b/backend/crates/gateway-api/tests/data_plane/provider_endpoints.rs @@ -56,7 +56,7 @@ struct ProviderExecution { impl ProviderExecution { fn new() -> Arc { Arc::new(Self { - client: crate::openai::authenticated_client_for_provider( + client: crate::data_plane::authenticated_client_for_provider( "sk_provider_operation_test", "local-echo", ), @@ -273,7 +273,7 @@ impl ExecutionSession for ProviderSession { async fn token_count_should_bind_provider_model_and_preserve_exact_json() { let execution = ProviderExecution::new(); let request_body = Bytes::from_static(br#"{ "input":"one two", "future":9007199254740993 }"#); - let response = crate::openai::api_router(execution.clone()) + let response = crate::data_plane::api_router(execution.clone()) .await .oneshot( Request::post("/v1/providers/local-echo/models/local-echo/count_tokens") @@ -312,7 +312,7 @@ async fn token_count_should_bind_provider_model_and_preserve_exact_json() { async fn provider_http_should_strip_sensitive_headers_and_preserve_opaque_bytes() { let execution = ProviderExecution::new(); let request_body = Bytes::from_static(b"\x00input\xff"); - let response = crate::openai::api_router(execution.clone()) + let response = crate::data_plane::api_router(execution.clone()) .await .oneshot( Request::post("/v1/providers/local-echo/http/inspect?mode=future") @@ -369,7 +369,7 @@ async fn provider_http_should_strip_sensitive_headers_and_preserve_opaque_bytes( #[tokio::test] async fn provider_http_should_reject_head_and_get_bodies_before_execution() { let execution = ProviderExecution::new(); - let router = crate::openai::api_router(execution.clone()).await; + let router = crate::data_plane::api_router(execution.clone()).await; let head = router .clone() .oneshot( @@ -400,7 +400,7 @@ async fn provider_http_should_reject_head_and_get_bodies_before_execution() { #[tokio::test] async fn token_count_should_reject_invalid_json_before_execution() { let execution = ProviderExecution::new(); - let response = crate::openai::api_router(execution.clone()) + let response = crate::data_plane::api_router(execution.clone()) .await .oneshot( Request::post("/v1/providers/local-echo/models/local-echo/count_tokens") @@ -418,7 +418,7 @@ async fn token_count_should_reject_invalid_json_before_execution() { #[tokio::test] async fn provider_http_should_fail_closed_on_non_success_success_envelope() { let execution = ProviderExecution::new(); - let response = crate::openai::api_router(execution) + let response = crate::data_plane::api_router(execution) .await .oneshot( Request::get("/v1/providers/local-echo/http/redirect-fixture") @@ -435,7 +435,7 @@ async fn provider_http_should_fail_closed_on_non_success_success_envelope() { #[tokio::test] async fn provider_http_should_enforce_fragment_aggregate_and_body_presence_bounds() { - let empty = crate::openai::api_router(ProviderExecution::new()) + let empty = crate::data_plane::api_router(ProviderExecution::new()) .await .oneshot( Request::get("/v1/providers/local-echo/http/empty-body-fixture") @@ -460,7 +460,7 @@ async fn provider_http_should_enforce_fragment_aggregate_and_body_presence_bound "missing-body-fixture", ] { let execution = ProviderExecution::new(); - let response = crate::openai::api_router(execution) + let response = crate::data_plane::api_router(execution) .await .oneshot( Request::get(format!("/v1/providers/local-echo/http/{endpoint}")) diff --git a/backend/crates/gateway-api/tests/openai/responses/http.rs b/backend/crates/gateway-api/tests/data_plane/responses/http.rs similarity index 98% rename from backend/crates/gateway-api/tests/openai/responses/http.rs rename to backend/crates/gateway-api/tests/data_plane/responses/http.rs index 689264729..fedc74b7b 100644 --- a/backend/crates/gateway-api/tests/openai/responses/http.rs +++ b/backend/crates/gateway-api/tests/data_plane/responses/http.rs @@ -41,11 +41,11 @@ use gateway_core::upstream::{OpaqueUpstreamValue, UpstreamSendState}; use gateway_protocol::openai::sse::{encode_sse_event, parse_sse_events}; use serde_json::{Value, json}; -use gateway_api::openai::responses::{collect_execution_response, stream_execution_response}; +use gateway_api::data_plane::responses::{collect_execution_response, stream_execution_response}; use tower::ServiceExt; -use crate::openai::middleware::{RequestMiddleware, ResponseFrameAction}; -use crate::openai::{ +use crate::data_plane::middleware::{RequestMiddleware, ResponseFrameAction}; +use crate::data_plane::{ api_router, authenticated_client_for_provider, authenticated_client_with_min_versions, }; @@ -565,16 +565,17 @@ async fn http_requests_should_honor_stream_preference() { if let Some(stream) = stream { body["stream"] = json!(stream); } - let response = crate::openai::api_router_with_admin_and_execution(admin.clone(), execution) - .oneshot( - Request::post("/v1/responses") - .header(AUTHORIZATION, "Bearer sk_stream_test") - .header(CONTENT_TYPE, "application/json") - .body(Body::from(body.to_string())) - .unwrap(), - ) - .await - .unwrap(); + let response = + crate::data_plane::api_router_with_admin_and_execution(admin.clone(), execution) + .oneshot( + Request::post("/v1/responses") + .header(AUTHORIZATION, "Bearer sk_stream_test") + .header(CONTENT_TYPE, "application/json") + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK, "stream={stream:?}"); assert_eq!( @@ -3004,7 +3005,7 @@ async fn official_core_clients_should_be_version_checked_before_starting_respons )) .body(Body::from(json!({"model": "model-a", "input": "synthetic", "stream": true}).to_string())) .unwrap(); - let response = crate::openai::api_router_with_admin_and_execution( + let response = crate::data_plane::api_router_with_admin_and_execution( admin.clone(), execution.clone(), ) @@ -3072,7 +3073,7 @@ async fn chatgpt_remote_responses_should_only_skip_missing_desktop_versions() { if let Some(version) = version { request = request.header("version", version); } - let response = crate::openai::api_router_with_admin_and_execution( + let response = crate::data_plane::api_router_with_admin_and_execution( admin.clone(), execution.clone(), ) @@ -3203,7 +3204,7 @@ async fn response_with_middleware( session: Mutex::new(Some(Box::new(session))), middleware: middleware.map(|middleware| middleware.frozen()), }); - crate::openai::api_router_with_admin_and_execution(admin.clone(), execution) + crate::data_plane::api_router_with_admin_and_execution(admin.clone(), execution) .oneshot( Request::post("/v1/responses") .header(AUTHORIZATION, "Bearer sk_correlation_test") @@ -3383,22 +3384,23 @@ async fn compressed_http_request_above_default_limit_should_reach_execution_afte let observed = Arc::new(Mutex::new(None)); let execution = Arc::new(ContextCaptureExecution { observed: Arc::clone(&observed), - client: crate::openai::authenticated_client_for_provider_with_limit( + client: crate::data_plane::authenticated_client_for_provider_with_limit( "sk_context_test", "openai", limit, ), }); - let response = crate::openai::api_router_with_admin_and_execution(admin.clone(), execution) - .oneshot( - Request::post("/v1/responses") - .header(AUTHORIZATION, "Bearer sk_context_test") - .header(CONTENT_ENCODING, "zstd") - .body(Body::from(compressed.clone())) - .unwrap(), - ) - .await - .unwrap(); + let response = + crate::data_plane::api_router_with_admin_and_execution(admin.clone(), execution) + .oneshot( + Request::post("/v1/responses") + .header(AUTHORIZATION, "Bearer sk_context_test") + .header(CONTENT_ENCODING, "zstd") + .body(Body::from(compressed.clone())) + .unwrap(), + ) + .await + .unwrap(); if limit == 64 * 1024 * 1024 { assert_eq!(response.status(), StatusCode::BAD_REQUEST); assert!(observed.lock().unwrap().is_none()); diff --git a/backend/crates/gateway-api/tests/openai/responses/mod.rs b/backend/crates/gateway-api/tests/data_plane/responses/mod.rs similarity index 99% rename from backend/crates/gateway-api/tests/openai/responses/mod.rs rename to backend/crates/gateway-api/tests/data_plane/responses/mod.rs index 5ce071375..48f6e7135 100644 --- a/backend/crates/gateway-api/tests/openai/responses/mod.rs +++ b/backend/crates/gateway-api/tests/data_plane/responses/mod.rs @@ -7,10 +7,11 @@ mod websocket; use axum::http::{HeaderMap, HeaderValue}; use base64::{Engine as _, engine::general_purpose::STANDARD}; use bytes::Bytes; -use gateway_api::openai::responses::{ - ContinuationIntent, DecodedGenerationRequest, OpenAiRequestHeaders, OpenAiResponsesEncoder, - RequestDecodeError, ResponseCreateFrameError, ResponseEncodeError, decode_request_with_headers, - decode_response_create_with_context, +use gateway_api::data_plane::body::RequestDecodeError; +use gateway_api::data_plane::generation::{ContinuationIntent, DecodedGenerationRequest}; +use gateway_api::data_plane::responses::{ + OpenAiRequestHeaders, OpenAiResponsesEncoder, ResponseCreateFrameError, ResponseEncodeError, + decode_request_with_headers, decode_response_create_with_context, }; use gateway_core::{ event::{GatewayEvent, ProtocolWireEvent, ProviderEvent, ResponseMeta}, diff --git a/backend/crates/gateway-api/tests/openai/responses/request.rs b/backend/crates/gateway-api/tests/data_plane/responses/request.rs similarity index 98% rename from backend/crates/gateway-api/tests/openai/responses/request.rs rename to backend/crates/gateway-api/tests/data_plane/responses/request.rs index 431b8325f..58daddfca 100644 --- a/backend/crates/gateway-api/tests/openai/responses/request.rs +++ b/backend/crates/gateway-api/tests/data_plane/responses/request.rs @@ -1,9 +1,10 @@ //! 验证 Responses 请求解压、大小限制与原始字段保留 +use gateway_api::data_plane::body::RequestDecodeError; use std::io::{Read, Write, copy, repeat}; use axum::http::{HeaderMap, HeaderValue, header::CONTENT_ENCODING}; -use gateway_api::openai::responses::{RequestDecodeError, decode_request_with_headers}; +use gateway_api::data_plane::responses::decode_request_with_headers; use serde_json::json; use super::openai_wire_body; diff --git a/backend/crates/gateway-api/tests/openai/responses/websocket/connection/middleware.rs b/backend/crates/gateway-api/tests/data_plane/responses/websocket/connection/middleware.rs similarity index 97% rename from backend/crates/gateway-api/tests/openai/responses/websocket/connection/middleware.rs rename to backend/crates/gateway-api/tests/data_plane/responses/websocket/connection/middleware.rs index 984360fdd..73c1492bf 100644 --- a/backend/crates/gateway-api/tests/openai/responses/websocket/connection/middleware.rs +++ b/backend/crates/gateway-api/tests/data_plane/responses/websocket/connection/middleware.rs @@ -243,15 +243,15 @@ async fn turns_refresh_host_settings_and_key_identity_while_preserving_handshake Box::pin(async { Err(MiddlewareError::Rejected) }) } } - let initial = crate::openai::snapshot("sk_ws_settings", "openai"); + let initial = crate::data_plane::snapshot("sk_ws_settings", "openai"); let snapshots = RuntimeSnapshotHandle::new(initial.clone()); let execution = Arc::new(DefaultExecutionService::new( snapshots.clone(), - Arc::new(crate::openai::UnusedExecutionStore), + Arc::new(crate::data_plane::UnusedExecutionStore), ProviderRegistry::default(), - Arc::new(crate::openai::UnusedAdmissions), - Arc::new(crate::openai::UnusedContinuation), - Arc::new(crate::openai::IgnoredClientApiKeyUsage), + Arc::new(crate::data_plane::UnusedAdmissions), + Arc::new(crate::data_plane::UnusedContinuation), + Arc::new(crate::data_plane::IgnoredClientApiKeyUsage), Arc::new(crate::support::RecordingDiagnostics::default()), )); let admin = crate::admin::AdminTestFixture::new().await; @@ -274,8 +274,8 @@ async fn turns_refresh_host_settings_and_key_identity_while_preserving_handshake execution, admin.services, vec![], - Arc::new(crate::openai::EmptyWorkerHealth), - Arc::new(crate::openai::TestLifecycle::default()), + Arc::new(crate::data_plane::EmptyWorkerHealth), + Arc::new(crate::data_plane::TestLifecycle::default()), Arc::new(crate::support::RecordingDiagnostics::default()), ) .unwrap() @@ -303,7 +303,7 @@ async fn turns_refresh_host_settings_and_key_identity_while_preserving_handshake .unwrap(), ); } else if round == 2 { - snapshots.publish(crate::openai::snapshot("sk_replaced", "openai")); + snapshots.publish(crate::data_plane::snapshot("sk_replaced", "openai")); } socket .send(ClientMessage::Text( diff --git a/backend/crates/gateway-api/tests/openai/responses/websocket/connection/mod.rs b/backend/crates/gateway-api/tests/data_plane/responses/websocket/connection/mod.rs similarity index 99% rename from backend/crates/gateway-api/tests/openai/responses/websocket/connection/mod.rs rename to backend/crates/gateway-api/tests/data_plane/responses/websocket/connection/mod.rs index 109853f41..3d1ce7b86 100644 --- a/backend/crates/gateway-api/tests/openai/responses/websocket/connection/mod.rs +++ b/backend/crates/gateway-api/tests/data_plane/responses/websocket/connection/mod.rs @@ -45,7 +45,7 @@ use tokio_tungstenite::{ }; use super::{AtomicFailureExecution, AtomicFailureTrace}; -use crate::openai::{api_router, authenticated_client}; +use crate::data_plane::{api_router, authenticated_client}; #[derive(Default)] struct CrossingLimitTrace { @@ -228,7 +228,7 @@ fn crossing_limit_terminal_batch(reconnect: bool) -> CoordinatedEvent { .expect("terminal WebSocket batch") } -use gateway_api::openai::responses::websocket::connection::{ +use gateway_api::data_plane::responses::websocket::connection::{ ConnectionConfig, ConnectionEvent, ConnectionWriteError, FramePhase, PumpExitReason, ResponsesWebSocketConnection, WriteContext, spawn_connection, }; @@ -860,8 +860,8 @@ async fn start_active_response_with( execution, admin.services, Vec::new(), - Arc::new(crate::openai::EmptyWorkerHealth), - Arc::new(crate::openai::TestLifecycle::default()), + Arc::new(crate::data_plane::EmptyWorkerHealth), + Arc::new(crate::data_plane::TestLifecycle::default()), Arc::new(crate::support::RecordingDiagnostics::default()), ) .unwrap() diff --git a/backend/crates/gateway-api/tests/openai/responses/websocket/connection/transport.rs b/backend/crates/gateway-api/tests/data_plane/responses/websocket/connection/transport.rs similarity index 100% rename from backend/crates/gateway-api/tests/openai/responses/websocket/connection/transport.rs rename to backend/crates/gateway-api/tests/data_plane/responses/websocket/connection/transport.rs diff --git a/backend/crates/gateway-api/tests/openai/responses/websocket/forward.rs b/backend/crates/gateway-api/tests/data_plane/responses/websocket/forward.rs similarity index 99% rename from backend/crates/gateway-api/tests/openai/responses/websocket/forward.rs rename to backend/crates/gateway-api/tests/data_plane/responses/websocket/forward.rs index e21b1e0d1..3e2757920 100644 --- a/backend/crates/gateway-api/tests/openai/responses/websocket/forward.rs +++ b/backend/crates/gateway-api/tests/data_plane/responses/websocket/forward.rs @@ -29,7 +29,7 @@ use tokio_tungstenite::{ }; use super::{AtomicFailureExecution, AtomicFailureTrace}; -use crate::openai::{api_router, authenticated_client}; +use crate::data_plane::{api_router, authenticated_client}; type TestSocket = WebSocketStream>; diff --git a/backend/crates/gateway-api/tests/openai/responses/websocket/interrupt.rs b/backend/crates/gateway-api/tests/data_plane/responses/websocket/interrupt.rs similarity index 99% rename from backend/crates/gateway-api/tests/openai/responses/websocket/interrupt.rs rename to backend/crates/gateway-api/tests/data_plane/responses/websocket/interrupt.rs index 73b8dc29b..7a0508ff7 100644 --- a/backend/crates/gateway-api/tests/openai/responses/websocket/interrupt.rs +++ b/backend/crates/gateway-api/tests/data_plane/responses/websocket/interrupt.rs @@ -475,7 +475,7 @@ async fn connect( ) -> (TestSocket, Server) { let execution = Arc::new(DefaultExecutionService::new( RuntimeSnapshotHandle::new(if provider.fail_first { - crate::openai::snapshot_with_accounts( + crate::data_plane::snapshot_with_accounts( "sk_ws_interrupt", "openai", "key_api_test", diff --git a/backend/crates/gateway-api/tests/openai/responses/websocket/mod.rs b/backend/crates/gateway-api/tests/data_plane/responses/websocket/mod.rs similarity index 99% rename from backend/crates/gateway-api/tests/openai/responses/websocket/mod.rs rename to backend/crates/gateway-api/tests/data_plane/responses/websocket/mod.rs index 5cb2061af..554f07d19 100644 --- a/backend/crates/gateway-api/tests/openai/responses/websocket/mod.rs +++ b/backend/crates/gateway-api/tests/data_plane/responses/websocket/mod.rs @@ -5,6 +5,7 @@ mod forward; mod interrupt; mod protocol; +use gateway_api::data_plane::generation::DecodedGenerationRequest; use std::sync::{ Arc, Mutex, atomic::{AtomicBool, AtomicUsize, Ordering}, @@ -18,9 +19,8 @@ use axum::{ }; use bytes::Bytes; use futures::{SinkExt, StreamExt, future::BoxFuture}; -use gateway_api::openai::responses::{ - DecodedGenerationRequest, OpenAiRequestHeaders, ResponseCreateFrameError, - decode_response_create_with_context, +use gateway_api::data_plane::responses::{ + OpenAiRequestHeaders, ResponseCreateFrameError, decode_response_create_with_context, }; use gateway_core::account::ProviderAccountId; use gateway_core::engine::admission::{ @@ -61,7 +61,7 @@ use tokio_tungstenite::tungstenite::client::IntoClientRequest; use tower::ServiceExt; use super::decode_response_create; -use crate::openai::{ +use crate::data_plane::{ EmptyWorkerHealth, IgnoredClientApiKeyUsage, UnusedContinuation, api_router, authenticated_client, models::ModelsExecution, snapshot, }; diff --git a/backend/crates/gateway-api/tests/openai/responses/websocket/protocol.rs b/backend/crates/gateway-api/tests/data_plane/responses/websocket/protocol.rs similarity index 97% rename from backend/crates/gateway-api/tests/openai/responses/websocket/protocol.rs rename to backend/crates/gateway-api/tests/data_plane/responses/websocket/protocol.rs index 32e08913d..0302b659e 100644 --- a/backend/crates/gateway-api/tests/openai/responses/websocket/protocol.rs +++ b/backend/crates/gateway-api/tests/data_plane/responses/websocket/protocol.rs @@ -2,7 +2,9 @@ use axum::http::{HeaderMap, HeaderValue}; use base64::{Engine as _, engine::general_purpose::STANDARD}; -use gateway_api::openai::responses::{OpenAiRequestHeaders, decode_response_create_with_context}; +use gateway_api::data_plane::responses::{ + OpenAiRequestHeaders, decode_response_create_with_context, +}; use gateway_core::operation::Operation; use serde_json::json; diff --git a/backend/crates/gateway-api/tests/openai/router.rs b/backend/crates/gateway-api/tests/data_plane/router.rs similarity index 100% rename from backend/crates/gateway-api/tests/openai/router.rs rename to backend/crates/gateway-api/tests/data_plane/router.rs diff --git a/backend/crates/gateway-api/tests/data_plane/search/http.rs b/backend/crates/gateway-api/tests/data_plane/search/http.rs new file mode 100644 index 000000000..d0aa5b985 --- /dev/null +++ b/backend/crates/gateway-api/tests/data_plane/search/http.rs @@ -0,0 +1,142 @@ +//! 对应生产职责的行为测试 + +use super::*; + +#[tokio::test] +async fn search_route_should_preserve_request_and_success_response_bytes() { + let mut execution = SearchExecution::new(false); + let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware { + expected_operation: Some(OperationKind::Search), + committed_statuses: Some(execution.committed_statuses.clone()), + ..Default::default() + }); + Arc::get_mut(&mut execution).unwrap().middleware = Some(middleware.clone()); + let request_body = br#"{ "id":"search-session", "model":"gpt-future", "commands":{"search_query":[{"q":"private query"}]}, "future":1, "future":2 }"#; + let turn_metadata = + r#"{"session_id":"session","thread_id":"thread","turn_id":"turn","future":true}"#; + let response = api_router(execution.clone()) + .await + .oneshot( + Request::post("/v1/alpha/search") + .header(AUTHORIZATION, "Bearer sk_search_test") + .header("content-type", "application/json") + .header("x-codex-turn-metadata", turn_metadata) + .header("session-id", "root-session") + .header("thread-id", "child-thread") + .header("x-future-business", "first") + .header("x-future-business", "second") + .header("cookie", "client-secret") + .header("connection", "x-private-hop") + .header("x-private-hop", "client-hop") + .body(Body::from(request_body.to_vec())) + .expect("search request"), + ) + .await + .expect("search response"); + + assert_eq!(response.status(), StatusCode::CREATED); + assert_eq!(response.headers()["x-request-middleware"], "applied"); + assert_eq!( + *middleware.endpoints.lock().unwrap(), + vec!["/v1/alpha/search"] + ); + assert_eq!(response.headers()["x-request-id"], "req_search_test"); + assert_eq!( + response.headers()["x-gateway-request-id"], + "req_search_test" + ); + assert_eq!( + response.headers().get("x-search-rate-limit"), + Some(&"42".parse().expect("header value")) + ); + let response_body = to_bytes(response.into_body(), usize::MAX) + .await + .expect("read search response"); + assert_eq!(response_body.as_ref(), SEARCH_RESPONSE); + + let captured = execution.captured(); + assert_eq!(captured.len(), 1); + assert_eq!(captured[0].provider, "openai"); + assert_eq!(captured[0].endpoint, "/v1/alpha/search"); + assert_eq!(captured[0].transport, ClientTransport::HttpJson); + assert_eq!(captured[0].body.as_ref(), request_body); + let mut context = captured[0].context.clone(); + let headers = context + .as_object_mut() + .unwrap() + .remove("opaque_request_headers") + .unwrap(); + let headers: Vec<_> = headers + .as_array() + .unwrap() + .iter() + .map(|entry| { + ( + entry[0].as_str().unwrap(), + STANDARD.decode(entry[1].as_str().unwrap()).unwrap(), + ) + }) + .collect(); + assert_eq!( + headers + .iter() + .filter(|(name, _)| *name == "x-future-business") + .map(|(_, value)| value.as_slice()) + .collect::>(), + [b"first".as_slice(), b"second".as_slice()] + ); + assert!(!headers.iter().any(|(name, _)| matches!( + *name, + "authorization" | "cookie" | "connection" | "x-private-hop" + ))); + assert_eq!( + context, + json!({"turn_metadata": turn_metadata, "session_id": "root-session", "thread_id": "child-thread"}) + ); + assert_eq!( + *execution + .committed_statuses + .lock() + .expect("committed status lock"), + vec![StatusCode::CREATED.as_u16()] + ); +} + +#[tokio::test] +async fn search_route_should_return_the_exact_upstream_error_response() { + let response = api_router(SearchExecution::new(true)) + .await + .oneshot( + Request::post("/v1/alpha/search") + .header(AUTHORIZATION, "Bearer sk_search_test") + .header("content-type", "application/json") + .body(Body::from( + br#"{ "model":"gpt-future", "future_invalid":9007199254740993 }"#.to_vec(), + )) + .expect("search request"), + ) + .await + .expect("search response"); + + assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY); + assert_eq!(response.headers()["x-request-id"], "req_search_test"); + assert_eq!( + response.headers()["x-gateway-request-id"], + "req_search_test" + ); + assert_eq!( + response.headers().get("content-type"), + Some(&"application/problem+json".parse().expect("content type")) + ); + assert_eq!( + response.headers().get("x-future-search-error"), + Some(&"preserved".parse().expect("header value")) + ); + let body = to_bytes(response.into_body(), usize::MAX) + .await + .expect("read search response"); + assert_eq!( + body.as_ref(), + br#"{ "error":{"message":"future search validation"}, "future":9007199254740993 }"# + ); +} diff --git a/backend/crates/gateway-api/tests/openai/search/mod.rs b/backend/crates/gateway-api/tests/data_plane/search/mod.rs similarity index 52% rename from backend/crates/gateway-api/tests/openai/search/mod.rs rename to backend/crates/gateway-api/tests/data_plane/search/mod.rs index a1ff5016f..4540a001d 100644 --- a/backend/crates/gateway-api/tests/openai/search/mod.rs +++ b/backend/crates/gateway-api/tests/data_plane/search/mod.rs @@ -1,5 +1,6 @@ //! 独立搜索 HTTP 接口的请求传递、鉴权与响应交付测试 +mod http; use std::sync::{Arc, Mutex}; use std::time::SystemTime; @@ -25,7 +26,7 @@ use gateway_core::upstream::UpstreamSendState; use serde_json::{Value, json}; use tower::ServiceExt; -use super::endpoint::BufferedJsonSession; +use super::openai_endpoints::BufferedJsonSession; use super::{api_router, authenticated_client}; const SEARCH_RESPONSE: &[u8] = br#"{ "encrypted_output":"ciphertext", "output":"search result", "results":[{"type":"text_result","ref_id":"turn0search0","future":9007199254740993}] }"#; @@ -44,7 +45,7 @@ struct SearchExecution { captured: Mutex>, committed_statuses: Arc>>, fail_with_upstream_response: bool, - middleware: Option>, + middleware: Option>, } impl SearchExecution { @@ -160,142 +161,3 @@ impl ExecutionService for SearchExecution { }) } } - -#[tokio::test] -async fn search_route_should_preserve_request_and_success_response_bytes() { - let mut execution = SearchExecution::new(false); - let middleware = Arc::new(crate::openai::middleware::RequestMiddleware { - expected_operation: Some(OperationKind::Search), - committed_statuses: Some(execution.committed_statuses.clone()), - ..Default::default() - }); - Arc::get_mut(&mut execution).unwrap().middleware = Some(middleware.clone()); - let request_body = br#"{ "id":"search-session", "model":"gpt-future", "commands":{"search_query":[{"q":"private query"}]}, "future":1, "future":2 }"#; - let turn_metadata = - r#"{"session_id":"session","thread_id":"thread","turn_id":"turn","future":true}"#; - let response = api_router(execution.clone()) - .await - .oneshot( - Request::post("/v1/alpha/search") - .header(AUTHORIZATION, "Bearer sk_search_test") - .header("content-type", "application/json") - .header("x-codex-turn-metadata", turn_metadata) - .header("session-id", "root-session") - .header("thread-id", "child-thread") - .header("x-future-business", "first") - .header("x-future-business", "second") - .header("cookie", "client-secret") - .header("connection", "x-private-hop") - .header("x-private-hop", "client-hop") - .body(Body::from(request_body.to_vec())) - .expect("search request"), - ) - .await - .expect("search response"); - - assert_eq!(response.status(), StatusCode::CREATED); - assert_eq!(response.headers()["x-request-middleware"], "applied"); - assert_eq!( - *middleware.endpoints.lock().unwrap(), - vec!["/v1/alpha/search"] - ); - assert_eq!(response.headers()["x-request-id"], "req_search_test"); - assert_eq!( - response.headers()["x-gateway-request-id"], - "req_search_test" - ); - assert_eq!( - response.headers().get("x-search-rate-limit"), - Some(&"42".parse().expect("header value")) - ); - let response_body = to_bytes(response.into_body(), usize::MAX) - .await - .expect("read search response"); - assert_eq!(response_body.as_ref(), SEARCH_RESPONSE); - - let captured = execution.captured(); - assert_eq!(captured.len(), 1); - assert_eq!(captured[0].provider, "openai"); - assert_eq!(captured[0].endpoint, "/v1/alpha/search"); - assert_eq!(captured[0].transport, ClientTransport::HttpJson); - assert_eq!(captured[0].body.as_ref(), request_body); - let mut context = captured[0].context.clone(); - let headers = context - .as_object_mut() - .unwrap() - .remove("opaque_request_headers") - .unwrap(); - let headers: Vec<_> = headers - .as_array() - .unwrap() - .iter() - .map(|entry| { - ( - entry[0].as_str().unwrap(), - STANDARD.decode(entry[1].as_str().unwrap()).unwrap(), - ) - }) - .collect(); - assert_eq!( - headers - .iter() - .filter(|(name, _)| *name == "x-future-business") - .map(|(_, value)| value.as_slice()) - .collect::>(), - [b"first".as_slice(), b"second".as_slice()] - ); - assert!(!headers.iter().any(|(name, _)| matches!( - *name, - "authorization" | "cookie" | "connection" | "x-private-hop" - ))); - assert_eq!( - context, - json!({"turn_metadata": turn_metadata, "session_id": "root-session", "thread_id": "child-thread"}) - ); - assert_eq!( - *execution - .committed_statuses - .lock() - .expect("committed status lock"), - vec![StatusCode::CREATED.as_u16()] - ); -} - -#[tokio::test] -async fn search_route_should_return_the_exact_upstream_error_response() { - let response = api_router(SearchExecution::new(true)) - .await - .oneshot( - Request::post("/v1/alpha/search") - .header(AUTHORIZATION, "Bearer sk_search_test") - .header("content-type", "application/json") - .body(Body::from( - br#"{ "model":"gpt-future", "future_invalid":9007199254740993 }"#.to_vec(), - )) - .expect("search request"), - ) - .await - .expect("search response"); - - assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY); - assert_eq!(response.headers()["x-request-id"], "req_search_test"); - assert_eq!( - response.headers()["x-gateway-request-id"], - "req_search_test" - ); - assert_eq!( - response.headers().get("content-type"), - Some(&"application/problem+json".parse().expect("content type")) - ); - assert_eq!( - response.headers().get("x-future-search-error"), - Some(&"preserved".parse().expect("header value")) - ); - let body = to_bytes(response.into_body(), usize::MAX) - .await - .expect("read search response"); - assert_eq!( - body.as_ref(), - br#"{ "error":{"message":"future search validation"}, "future":9007199254740993 }"# - ); -} diff --git a/backend/crates/gateway-api/tests/openai/usage.rs b/backend/crates/gateway-api/tests/data_plane/usage.rs similarity index 98% rename from backend/crates/gateway-api/tests/openai/usage.rs rename to backend/crates/gateway-api/tests/data_plane/usage.rs index d7cac8c91..5247a7d60 100644 --- a/backend/crates/gateway-api/tests/openai/usage.rs +++ b/backend/crates/gateway-api/tests/data_plane/usage.rs @@ -113,7 +113,7 @@ struct FrontendUsageAuthentication { client: AuthenticatedClient, authentication_calls: AtomicUsize, verification_calls: AtomicUsize, - middleware: Arc, + middleware: Arc, } impl ExecutionService for FrontendUsageAuthentication { @@ -192,7 +192,7 @@ async fn usage_uses_the_entry_authentication_identity_without_recording_request_ client: super::authenticated_client("unused-native-key"), authentication_calls: AtomicUsize::new(0), verification_calls: AtomicUsize::new(0), - middleware: Arc::new(crate::openai::middleware::RequestMiddleware::default()), + middleware: Arc::new(crate::data_plane::middleware::RequestMiddleware::default()), }); let app = super::api_router_with_admin_and_execution(fixture.services.clone(), execution.clone()); diff --git a/backend/crates/gateway-api/tests/diagnostics.rs b/backend/crates/gateway-api/tests/diagnostics.rs index b91125999..291fc2c7e 100644 --- a/backend/crates/gateway-api/tests/diagnostics.rs +++ b/backend/crates/gateway-api/tests/diagnostics.rs @@ -14,7 +14,7 @@ use crate::support::RecordingDiagnostics; async fn fixture() -> (axum::Router, Arc) { let admin = crate::admin::AdminTestFixture::new().await; let diagnostics = Arc::new(RecordingDiagnostics::default()); - let router = crate::openai::api_bundle_with_diagnostics( + let router = crate::data_plane::api_bundle_with_diagnostics( admin.services, gateway_api::ApiConfig { asset_directory: env!("CARGO_MANIFEST_DIR").into(), diff --git a/backend/crates/gateway-api/tests/health.rs b/backend/crates/gateway-api/tests/health.rs index 673df075e..23a648ad6 100644 --- a/backend/crates/gateway-api/tests/health.rs +++ b/backend/crates/gateway-api/tests/health.rs @@ -26,7 +26,7 @@ use crate::support::RecordingDiagnostics; #[tokio::test] async fn healthz_should_return_no_content_when_all_inputs_are_healthy() { - let response = crate::openai::api_router(Arc::new(UnusedExecution)) + let response = crate::data_plane::api_router(Arc::new(UnusedExecution)) .await .oneshot( Request::builder() @@ -46,7 +46,7 @@ async fn healthz_should_ignore_provider_maintenance_worker_failure() { WorkerKind::QuotaCatalogHealth, WorkerRuntimeState::BackingOff, )]); - let response = crate::openai::api_router_with_worker_health( + let response = crate::data_plane::api_router_with_worker_health( Arc::new(UnusedExecution), Arc::new(worker_health), ) @@ -69,7 +69,7 @@ async fn healthz_should_reject_critical_worker_failure() { WorkerKind::RuntimeSnapshotReconciliation, WorkerRuntimeState::BackingOff, )]); - let response = crate::openai::api_router_with_worker_health( + let response = crate::data_plane::api_router_with_worker_health( Arc::new(UnusedExecution), Arc::new(worker_health), ) @@ -305,7 +305,7 @@ async fn health_router( admin.services, probes, Arc::new(StaticWorkerHealth(workers)), - Arc::new(crate::openai::TestLifecycle::default()), + Arc::new(crate::data_plane::TestLifecycle::default()), diagnostics, ) .unwrap() diff --git a/backend/crates/gateway-api/tests/key_usage/mod.rs b/backend/crates/gateway-api/tests/key_usage/mod.rs index 64cde8a21..0c2c752b4 100644 --- a/backend/crates/gateway-api/tests/key_usage/mod.rs +++ b/backend/crates/gateway-api/tests/key_usage/mod.rs @@ -57,7 +57,7 @@ async fn get(app: &Router, resource: &str, suffix: &str, cookie: &str) -> Respon #[tokio::test] async fn version_exposes_only_build_identifiers_for_key_sessions() { let fixture = fixtures::fixture().await; - let app = crate::openai::api_router_with_admin(fixture.services.clone()); + let app = crate::data_plane::api_router_with_admin(fixture.services.clone()); let cookie = login(&app, "key").await; let response = get(&app, "version", "", &cookie).await; assert_eq!(response.status(), StatusCode::OK); @@ -84,7 +84,7 @@ async fn version_exposes_only_build_identifiers_for_key_sessions() { #[tokio::test] async fn config_reveals_only_the_session_keys_name_and_plaintext() { let fixture = fixtures::fixture().await; - let app = crate::openai::api_router_with_admin(fixture.services.clone()); + let app = crate::data_plane::api_router_with_admin(fixture.services.clone()); let cookie = login(&app, "key").await; let response = get(&app, "config", "", &cookie).await; assert_eq!(response.status(), StatusCode::OK); @@ -108,7 +108,7 @@ async fn config_reveals_only_the_session_keys_name_and_plaintext() { #[tokio::test] async fn config_rejects_caller_selected_scope() { let fixture = fixtures::fixture().await; - let app = crate::openai::api_router_with_admin(fixture.services.clone()); + let app = crate::data_plane::api_router_with_admin(fixture.services.clone()); let cookie = login(&app, "key").await; for query in [ "?keyId=other", @@ -125,7 +125,7 @@ async fn config_rejects_caller_selected_scope() { #[tokio::test] async fn config_does_not_reveal_disabled_or_other_keys() { let fixture = fixtures::fixture().await; - let app = crate::openai::api_router_with_admin(fixture.services.clone()); + let app = crate::data_plane::api_router_with_admin(fixture.services.clone()); let cookie = login(&app, "key").await; { let mut key = fixture.client_key.lock().unwrap(); @@ -165,7 +165,7 @@ async fn overview_scopes_every_query_and_projects_only_key_visible_fields() { let fixture = fixtures::fixture().await; fixture.observations.lock().unwrap().trend.as_mut().unwrap()[0].bucket_start = "2026-09-01T04:30:00Z".parse().unwrap(); - let app = crate::openai::api_router_with_admin(fixture.services.clone()); + let app = crate::data_plane::api_router_with_admin(fixture.services.clone()); let cookie = login(&app, "key").await; let response = get(&app, "overview", "&model=%20coding%20", &cookie).await; assert_eq!(response.status(), StatusCode::OK); @@ -257,7 +257,7 @@ async fn overview_scopes_every_query_and_projects_only_key_visible_fields() { #[tokio::test] async fn records_keep_pagination_and_hide_admin_and_upstream_data() { let fixture = fixtures::fixture().await; - let app = crate::openai::api_router_with_admin(fixture.services.clone()); + let app = crate::data_plane::api_router_with_admin(fixture.services.clone()); let cookie = login(&app, "key").await; for (kind, outcome) in [ ("success", RequestOutcome::Succeeded), @@ -374,7 +374,7 @@ async fn failed_records_without_usage_keep_token_and_billing_details_unknown() { record.total_tokens = None; record.billing = None; } - let app = crate::openai::api_router_with_admin(fixture.services.clone()); + let app = crate::data_plane::api_router_with_admin(fixture.services.clone()); let cookie = login(&app, "key").await; let response = get(&app, "records", "&kind=error", &cookie).await; assert_eq!(response.status(), StatusCode::OK); @@ -389,7 +389,7 @@ async fn failed_records_without_usage_keep_token_and_billing_details_unknown() { #[tokio::test] async fn missing_admin_and_revoked_sessions_cannot_read_key_usage() { let fixture = fixtures::fixture().await; - let app = crate::openai::api_router_with_admin(fixture.services.clone()); + let app = crate::data_plane::api_router_with_admin(fixture.services.clone()); let admin = login(&app, "admin").await; let key = login(&app, "key").await; for resource in ["overview", "records", "config", "version"] { @@ -414,7 +414,7 @@ async fn missing_admin_and_revoked_sessions_cannot_read_key_usage() { #[tokio::test] async fn unknown_scope_fields_and_unbounded_queries_are_rejected() { let fixture = fixtures::fixture().await; - let app = crate::openai::api_router_with_admin(fixture.services.clone()); + let app = crate::data_plane::api_router_with_admin(fixture.services.clone()); let cookie = login(&app, "key").await; for resource in ["overview", "records"] { for extra in [ @@ -470,7 +470,7 @@ async fn unknown_scope_fields_and_unbounded_queries_are_rejected() { #[tokio::test] async fn empty_usage_has_zero_cost_but_unknown_pricing_stays_unknown() { let fixture = fixtures::fixture().await; - let app = crate::openai::api_router_with_admin(fixture.services.clone()); + let app = crate::data_plane::api_router_with_admin(fixture.services.clone()); let cookie = login(&app, "key").await; for requests in [0, 2] { { @@ -502,7 +502,7 @@ async fn empty_usage_has_zero_cost_but_unknown_pricing_stays_unknown() { #[tokio::test] async fn overview_does_not_mask_missing_keys_or_unavailable_observations() { let fixture = fixtures::fixture().await; - let app = crate::openai::api_router_with_admin(fixture.services.clone()); + let app = crate::data_plane::api_router_with_admin(fixture.services.clone()); let cookie = login(&app, "key").await; fixture.observations.lock().unwrap().summary = None; assert_eq!( @@ -519,7 +519,7 @@ async fn overview_does_not_mask_missing_keys_or_unavailable_observations() { #[tokio::test] async fn namespace_errors_remain_json_and_uncacheable() { let fixture = fixtures::fixture().await; - let app = crate::openai::api_router_with_admin(fixture.services); + let app = crate::data_plane::api_router_with_admin(fixture.services); for (method, path, status) in [ (Method::GET, "/api/key-usage/missing", StatusCode::NOT_FOUND), ( diff --git a/backend/crates/gateway-api/tests/main.rs b/backend/crates/gateway-api/tests/main.rs index e1455648a..ce55003fc 100644 --- a/backend/crates/gateway-api/tests/main.rs +++ b/backend/crates/gateway-api/tests/main.rs @@ -3,12 +3,11 @@ mod admin; mod architecture; mod auth; +mod data_plane; mod diagnostics; mod health; mod key_usage; mod middleware; -mod openai; -mod provider; mod support; #[tokio::test] @@ -53,7 +52,7 @@ async fn api_should_serve_resolved_assets_with_relative_environment_override() { .resolve_and_validate(&std::path::Path::new(&directory).join("deploy")) .expect("resolved API config"); let admin = admin::AdminTestFixture::new().await; - let router = openai::api_router_with_config(admin.services, config); + let router = data_plane::api_router_with_config(admin.services, config); let response = router .clone() .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap()) diff --git a/backend/crates/gateway-api/tests/middleware/mod.rs b/backend/crates/gateway-api/tests/middleware/mod.rs index 7eb307774..36a9ab6de 100644 --- a/backend/crates/gateway-api/tests/middleware/mod.rs +++ b/backend/crates/gateway-api/tests/middleware/mod.rs @@ -312,7 +312,7 @@ async fn router(mode: Mode, timeout: Option) -> (axum::Router, Arc) { Arc::new(Lease), ), ); - let router = crate::openai::api_bundle( + let router = crate::data_plane::api_bundle( admin.services, gateway_api::ApiConfig { asset_directory: std::env::temp_dir(), @@ -532,7 +532,7 @@ async fn internal_dispatch_uses_the_same_router_and_the_frozen_parent_context() Arc::new(Lease), ), ); - let bundle = crate::openai::api_bundle( + let bundle = crate::data_plane::api_bundle( admin.services, gateway_api::ApiConfig { asset_directory: std::env::temp_dir(), @@ -597,7 +597,7 @@ async fn parent_cancellation_wakes_a_pending_child_response_body() { Arc::new(Lease), ), ); - let bundle = crate::openai::api_bundle( + let bundle = crate::data_plane::api_bundle( admin.services, gateway_api::ApiConfig { asset_directory: std::env::temp_dir(), @@ -644,7 +644,7 @@ async fn parent_cancellation_wakes_a_pending_child_response_body() { #[tokio::test] async fn plugin_http_dispatch_uses_host_identity_without_client_credentials() { let admin = crate::admin::AdminTestFixture::new().await; - let bundle = crate::openai::api_bundle( + let bundle = crate::data_plane::api_bundle( admin.services, gateway_api::ApiConfig { asset_directory: std::env::temp_dir(), diff --git a/backend/crates/gateway-api/tests/support/mod.rs b/backend/crates/gateway-api/tests/support/mod.rs index 33f41b1db..b99ec9aec 100644 --- a/backend/crates/gateway-api/tests/support/mod.rs +++ b/backend/crates/gateway-api/tests/support/mod.rs @@ -28,7 +28,7 @@ pub(crate) const RAW_KEY: &str = "cpr_live_candidate_must_not_leak"; pub(crate) async fn auth_app() -> (axum::Router, Arc) { let fixture = key_fixture().await; ( - crate::openai::api_router_with_admin(fixture.services), + crate::data_plane::api_router_with_admin(fixture.services), fixture.auth, ) } diff --git a/backend/crates/gateway-core/src/account/selection.rs b/backend/crates/gateway-core/src/account/selection.rs index 7c5088002..535df312d 100644 --- a/backend/crates/gateway-core/src/account/selection.rs +++ b/backend/crates/gateway-core/src/account/selection.rs @@ -55,7 +55,7 @@ pub const MAX_ACCOUNT_ROTATIONS: u32 = 31; /// 会话绑定与轮次关联共用的保留时长上限,单位小时 pub const MAX_SESSION_AFFINITY_TTL_HOURS: u32 = 720; -/// OpenAI 会话账号亲和;请求身份和模式行为由 Provider 解释 +/// 通用会话账号亲和;请求身份和账号迁移资格由 Provider 解释 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum AccountAffinity { @@ -95,10 +95,10 @@ pub struct AccountSelectionPolicy { max_concurrent_per_account: AccountConcurrency, queue_policy: ConcurrencyQueuePolicy, openai_guardian_reserved_concurrency: u32, - openai_account_affinity: AccountAffinity, + account_affinity: AccountAffinity, switch_account_on_queue_failure: bool, max_account_rotations: u32, - openai_session_affinity_ttl: Duration, + session_affinity_ttl: Duration, } impl AccountSelectionPolicy { @@ -113,10 +113,10 @@ impl AccountSelectionPolicy { quota_reset_window_weights: ResetWindowWeights::default(), max_concurrent_per_account: max_concurrent_per_account.into(), openai_guardian_reserved_concurrency: 0, - openai_account_affinity: AccountAffinity::default(), + account_affinity: AccountAffinity::default(), switch_account_on_queue_failure: false, max_account_rotations: 3, - openai_session_affinity_ttl: Duration::from_secs(24 * 3600), + session_affinity_ttl: Duration::from_secs(24 * 3600), queue_policy: ConcurrencyQueuePolicy { max_waiting: 0, timeout: Duration::ZERO, @@ -136,14 +136,14 @@ impl AccountSelectionPolicy { } #[must_use] - pub const fn with_openai_account_affinity(mut self, affinity: AccountAffinity) -> Self { - self.openai_account_affinity = affinity; + pub const fn with_account_affinity(mut self, affinity: AccountAffinity) -> Self { + self.account_affinity = affinity; self } #[must_use] - pub const fn openai_account_affinity(self) -> AccountAffinity { - self.openai_account_affinity + pub const fn account_affinity(self) -> AccountAffinity { + self.account_affinity } #[must_use] @@ -197,14 +197,14 @@ impl AccountSelectionPolicy { } #[must_use] - pub const fn with_openai_session_affinity_ttl(mut self, ttl: Duration) -> Self { - self.openai_session_affinity_ttl = ttl; + pub const fn with_session_affinity_ttl(mut self, ttl: Duration) -> Self { + self.session_affinity_ttl = ttl; self } #[must_use] - pub const fn openai_session_affinity_ttl(self) -> Duration { - self.openai_session_affinity_ttl + pub const fn session_affinity_ttl(self) -> Duration { + self.session_affinity_ttl } /// 只传递冻结的运行设置,Guardian 分类与预留策略由 OpenAI Provider 解释 diff --git a/backend/crates/gateway-core/src/engine/coordinator.rs b/backend/crates/gateway-core/src/engine/coordinator.rs index 7b154cb97..1b6970d92 100644 --- a/backend/crates/gateway-core/src/engine/coordinator.rs +++ b/backend/crates/gateway-core/src/engine/coordinator.rs @@ -297,13 +297,13 @@ where "candidateCount": plan.candidates().len(), "accountPolicy": { "strategy": plan.account_selection_policy().strategy().as_str(), - "affinity": plan.account_selection_policy().openai_account_affinity().as_str(), + "affinity": plan.account_selection_policy().account_affinity().as_str(), "maxAccountRotations": plan.account_selection_policy().max_account_rotations(), "maxRoutingAttempts": plan.max_attempts().get(), "maxConcurrentPerAccount": plan.account_selection_policy().max_concurrent_per_account().get(), "queueMaxWaiting": plan.account_selection_policy().queue_policy().max_waiting, "queueTimeoutMs": plan.account_selection_policy().queue_policy().timeout.as_millis(), - "sessionAffinityTtlMs": plan.account_selection_policy().openai_session_affinity_ttl().as_millis(), + "sessionAffinityTtlMs": plan.account_selection_policy().session_affinity_ttl().as_millis(), "smartWeights": plan.account_selection_policy().smart_scheduling().weights(), }, "requiredAccount": account_selection.required_account().map(|account| account.as_str()), diff --git a/backend/crates/gateway-core/src/engine/execution/service.rs b/backend/crates/gateway-core/src/engine/execution/service.rs index c0daad18a..6840bf6f7 100644 --- a/backend/crates/gateway-core/src/engine/execution/service.rs +++ b/backend/crates/gateway-core/src/engine/execution/service.rs @@ -503,7 +503,7 @@ impl DefaultExecutionService { if !authorization.account_scope.provider_kinds().contains(&provider) { return Err(GatewayError::new( GatewayErrorKind::PolicyDenied, - "Nested provider is outside the frozen account scope.", + "Model provider is outside the frozen account scope.", )); } routing_context.required_provider = Some(provider); diff --git a/backend/crates/gateway-core/src/engine/provider.rs b/backend/crates/gateway-core/src/engine/provider.rs index 3495890b7..aea766852 100644 --- a/backend/crates/gateway-core/src/engine/provider.rs +++ b/backend/crates/gateway-core/src/engine/provider.rs @@ -239,6 +239,10 @@ pub trait NativeResponseTranslator: Send + 'static { &mut self, event: &crate::event::ProtocolWireEvent, ) -> Result, ProviderError>; + /// 上游以 EOF 而非原生终态帧结束时,在终结事实交付前刷新协议终态 + fn finish(&mut self) -> Result, ProviderError> { + Ok(Vec::new()) + } } const MAX_NATIVE_RESPONSE_EVENTS_PER_INPUT: usize = 64; @@ -453,15 +457,19 @@ impl ProviderStream { return Ok(vec![event]); }; let middleware_transformed = event.middleware_transformed(); - let Some(wire) = event.wire_event() else { + let had_wire = event.wire_event().is_some(); + let mut translated = if let Some(wire) = event.wire_event() { + if wire.protocol() != translator.source_protocol() { + return Err(native_response_protocol_error()); + } + translator.translate(wire)? + } else if terminal { + translator.finish()? + } else { return Ok(vec![event]); }; - if wire.protocol() != translator.source_protocol() { - return Err(native_response_protocol_error()); - } - let mut translated = translator.translate(wire)?; if translated.len() > MAX_NATIVE_RESPONSE_EVENTS_PER_INPUT - || (terminal && translated.is_empty()) + || (terminal && had_wire && translated.is_empty()) || translated .iter() .any(|wire| wire.protocol() != translator.target_protocol()) diff --git a/backend/crates/gateway-core/src/operation.rs b/backend/crates/gateway-core/src/operation.rs index 4e36d801f..b49397e75 100644 --- a/backend/crates/gateway-core/src/operation.rs +++ b/backend/crates/gateway-core/src/operation.rs @@ -216,6 +216,7 @@ impl fmt::Debug for ProviderSessionState { pub struct ProtocolPayload { protocol: String, body: Map, + raw_json_body: Option, context: Map, } @@ -236,10 +237,29 @@ impl ProtocolPayload { Ok(Self { protocol, body, + raw_json_body: None, context: Map::new(), }) } + /// 只解析一次入站正文,保证路由使用的字段和透传字节来自同一份请求 + pub fn from_json_bytes( + protocol: impl Into, + body: Bytes, + ) -> Result { + let object = serde_json::from_slice(&body).map_err(|_| OperationError::EmptyField { + field: "protocol_payload body", + })?; + let mut payload = Self::json_object(protocol, object)?; + payload.raw_json_body = Some(body); + Ok(payload) + } + + #[must_use] + pub fn raw_json_body(&self) -> Option<&Bytes> { + self.raw_json_body.as_ref() + } + /// 返回协议名称 #[must_use] pub fn protocol(&self) -> &str { @@ -420,6 +440,7 @@ pub struct GenerateRequest { #[derive(Clone, PartialEq)] struct GeneratePayload { + requires_native_protocol: bool, source_image_generation: bool, wire_facts: RequestFacts, protocol_payload: ProtocolPayload, @@ -464,6 +485,7 @@ impl GenerateRequest { pub fn from_protocol_payload(protocol_payload: ProtocolPayload) -> Self { Self { payload: Arc::new(GeneratePayload { + requires_native_protocol: false, source_image_generation: false, wire_facts: request_facts(protocol_payload.protocol(), protocol_payload.body()), protocol_payload, @@ -475,6 +497,18 @@ impl GenerateRequest { } } + /// 原生入口只接受模型目录明确声明的生成协议 + #[must_use] + pub fn requiring_native_protocol(mut self) -> Self { + Arc::make_mut(&mut self.payload).requires_native_protocol = true; + self + } + + #[must_use] + pub fn requires_native_protocol(&self) -> bool { + self.payload.requires_native_protocol + } + #[must_use] pub fn with_client_turn(mut self, client_turn: Option) -> Self { Arc::make_mut(&mut self.payload).client_turn = client_turn; @@ -673,12 +707,28 @@ impl fmt::Debug for StandaloneSearchRequest { #[derive(Clone, PartialEq, Eq)] pub struct TokenCountRequest { payload: RawJsonPayload, + requires_native_protocol: bool, } impl TokenCountRequest { #[must_use] pub const fn from_raw_json(payload: RawJsonPayload) -> Self { - Self { payload } + Self { + payload, + requires_native_protocol: false, + } + } + + /// 原生计数入口只接受目录明确声明的同协议模型 + #[must_use] + pub const fn requiring_native_protocol(mut self) -> Self { + self.requires_native_protocol = true; + self + } + + #[must_use] + pub const fn requires_native_protocol(&self) -> bool { + self.requires_native_protocol } #[must_use] @@ -890,6 +940,11 @@ impl Operation { /// 生成请求的 JSON object 无法编码时返回错误 pub fn middleware_body(&self) -> Result { match self { + Self::Generate(request) + if let Some(body) = request.protocol_payload().raw_json_body() => + { + Ok(body.clone()) + } Self::Generate(request) => serde_json::to_vec(request.protocol_payload().body()) .map(Bytes::from) .map_err(|_| OperationError::EmptyField { @@ -1001,7 +1056,7 @@ impl Operation { // 修改上下文不改变正文事实;只有新 wire 才需要重新扫描输入 let mut payload = Arc::unwrap_or_clone(request.payload); if let Some(body) = body { - let body = + let object = serde_json::from_slice::>(&body).map_err(|_| { OperationError::EmptyField { field: "protocol_payload body", @@ -1010,8 +1065,12 @@ impl Operation { if let Some(protocol) = target_protocol { payload.protocol_payload.protocol = protocol; } - payload.wire_facts = request_facts(payload.protocol_payload.protocol(), &body); - payload.protocol_payload.body = body; + payload.wire_facts = + request_facts(payload.protocol_payload.protocol(), &object); + if payload.protocol_payload.raw_json_body.is_some() { + payload.protocol_payload.raw_json_body = Some(body); + } + payload.protocol_payload.body = object; } payload.protocol_payload.context = context; // 跨协议转换不能抹去已识别的生图权限要求,也不解释目标私有协议 @@ -1049,6 +1108,7 @@ impl Operation { Self::CountTokens(request) => { let payload = request.payload; Ok(Self::CountTokens(TokenCountRequest { + requires_native_protocol: request.requires_native_protocol, payload: RawJsonPayload { protocol: target_protocol.unwrap_or(payload.protocol), body: body.unwrap_or(payload.body), diff --git a/backend/crates/gateway-core/src/provider_ports/mod.rs b/backend/crates/gateway-core/src/provider_ports/mod.rs index 03ded205d..942d930dd 100644 --- a/backend/crates/gateway-core/src/provider_ports/mod.rs +++ b/backend/crates/gateway-core/src/provider_ports/mod.rs @@ -9,11 +9,13 @@ pub use lease::{ ProviderRefreshLeaseRequest, ProviderSchedulingLeaseRequest, ProviderSchedulingState, }; mod affinity; +mod session_affinity; pub use affinity::{ ProviderAccountAdmission, ProviderSessionAffinityKey, ProviderSessionAffinityPort, ProviderSessionAlias, ProviderSessionBinding, ProviderSessionClaim, ProviderSessionExclusionPort, ProviderSessionExclusions, }; +pub use session_affinity::ProviderSessionAffinityState; mod catalog; pub use catalog::{ ProviderArtifactProfile, ProviderArtifactProfileCachePort, ProviderCatalogCacheKey, diff --git a/backend/crates/gateway-core/src/provider_ports/session_affinity.rs b/backend/crates/gateway-core/src/provider_ports/session_affinity.rs new file mode 100644 index 000000000..3b431b660 --- /dev/null +++ b/backend/crates/gateway-core/src/provider_ports/session_affinity.rs @@ -0,0 +1,97 @@ +//! 会话绑定的通用选号与认领规则,不解释协议身份或 Provider 账号资格 + +use super::{ProviderSessionAffinityKey, ProviderSessionBinding, ProviderSessionClaim}; +use crate::account::{ + AccountAffinity, AccountCandidate, AccountSelectionContext, AccountSelectionPolicy, + AccountSelector, ProviderAccountId, +}; + +/// 一次选号观察到的绑定;CAS 冲突后须释放租约并重新读取 +pub struct ProviderSessionAffinityState<'a> { + key: &'a ProviderSessionAffinityKey, + binding: Option, + policy: AccountSelectionPolicy, +} + +impl<'a> ProviderSessionAffinityState<'a> { + #[must_use] + pub const fn new( + key: &'a ProviderSessionAffinityKey, + binding: Option, + policy: AccountSelectionPolicy, + ) -> Self { + Self { + key, + binding, + policy, + } + } + + #[must_use] + pub fn bound_account(&self) -> Option<&ProviderAccountId> { + self.binding + .as_ref() + .map(ProviderSessionBinding::account_id) + } + + /// 原生续接的固定账号由调用方优先设置,不以软亲和覆盖 + pub fn apply_preference(&self, context: &mut AccountSelectionContext) { + if self.policy.account_affinity() != AccountAffinity::Relaxed + && context.preferred_account.is_none() + { + context.preferred_account = self.bound_account().cloned(); + context.preferred_account_overrides_weight = + self.policy.account_affinity() == AccountAffinity::Strict; + } + } + + /// Provider 先投影凭据、额度和模型资格,通用层只区分容量不足与资格失效 + #[must_use] + pub fn binding_eligible( + &self, + candidates: &[AccountCandidate], + context: &AccountSelectionContext, + ) -> bool { + self.bound_account().is_some_and(|bound| { + AccountSelector + .policy_candidates(candidates, context) + .iter() + .any(|candidate| candidate.account.id() == bound) + }) + } + + /// 严格模式允许有界排队;队列关闭或绑定已失去资格时按普通策略重选 + #[must_use] + pub fn wait_account( + &self, + candidates: &[AccountCandidate], + context: &AccountSelectionContext, + queue_enabled: bool, + ) -> Option<&ProviderAccountId> { + (queue_enabled + && self.policy.account_affinity() == AccountAffinity::Strict + && self.binding_eligible(candidates, context)) + .then(|| self.bound_account()) + .flatten() + } + + /// 优先模式的临时分流及原生固定账号请求不改写仍有效的主绑定 + #[must_use] + pub fn claim<'s>( + &'s self, + selected: &'s ProviderAccountId, + binding_eligible: bool, + pinned: bool, + ) -> ProviderSessionClaim<'s> { + let retained = (pinned + || (self.policy.account_affinity() == AccountAffinity::Preferred && binding_eligible)) + .then(|| self.bound_account()) + .flatten(); + ProviderSessionClaim { + key: self.key, + expected: self.binding.as_ref(), + account: retained.unwrap_or(selected), + ttl: self.policy.session_affinity_ttl(), + } + } +} diff --git a/backend/crates/gateway-core/src/routing/mod.rs b/backend/crates/gateway-core/src/routing/mod.rs index 33a4012b9..4a29b86e5 100644 --- a/backend/crates/gateway-core/src/routing/mod.rs +++ b/backend/crates/gateway-core/src/routing/mod.rs @@ -151,6 +151,8 @@ pub struct ModelCapabilities { features: BTreeMap, max_output_tokens: Option, upstream_validates_features: bool, + generation_protocol: Option<&'static str>, + translated_generation_protocols: BTreeSet<&'static str>, } /// Provider 为客户端模型目录提供的展示与交互能力 @@ -423,6 +425,8 @@ impl ModelCapabilities { features: BTreeMap::new(), max_output_tokens, upstream_validates_features: false, + generation_protocol: None, + translated_generation_protocols: BTreeSet::new(), } } @@ -439,6 +443,41 @@ impl ModelCapabilities { self } + /// 声明原生生成协议;额外转换入口须显式登记,其他操作沿用各自的能力约束 + #[must_use] + pub const fn with_generation_protocol(mut self, protocol: &'static str) -> Self { + self.generation_protocol = Some(protocol); + self + } + + /// 声明 Provider 已实现的跨协议生成入口,不改变原生入口的资格 + #[must_use] + pub fn with_translated_generation_protocols( + mut self, + protocols: impl IntoIterator, + ) -> Self { + self.translated_generation_protocols = protocols.into_iter().collect(); + self + } + + fn match_operation( + &self, + operation: &crate::operation::Operation, + requirements: &CapabilityRequirements, + ) -> Option> { + if matches!(operation, crate::operation::Operation::Generate(_)) + && self.generation_protocol.is_some_and(|protocol| { + protocol != operation.protocol() + && !self + .translated_generation_protocols + .contains(operation.protocol()) + }) + { + return None; + } + self.match_requirements(requirements) + } + #[must_use] pub fn match_requirements( &self, diff --git a/backend/crates/gateway-core/src/routing/snapshot.rs b/backend/crates/gateway-core/src/routing/snapshot.rs index 6c42f7f93..682fc063e 100644 --- a/backend/crates/gateway-core/src/routing/snapshot.rs +++ b/backend/crates/gateway-core/src/routing/snapshot.rs @@ -1061,6 +1061,27 @@ impl RuntimeSnapshot { .collect() } + /// 协议目录复用执行路由的能力与范围判断,不公布当前入口无法调用的模型 + #[must_use] + pub fn public_models_for_operation( + &self, + scope: &Arc, + operation: &Operation, + ) -> Vec { + self.public_models_for_scope(scope) + .into_iter() + .filter(|model| { + self.plan( + model, + operation, + Arc::clone(scope), + &RoutingContext::default(), + ) + .is_ok() + }) + .collect() + } + /// 合并冻结账号范围内实际存在 Provider 的公开模型画像 #[must_use] pub fn public_model_profiles_for_scope( @@ -1412,7 +1433,7 @@ impl RuntimeSnapshot { operation: &Operation, account_scope: Arc, context: &RoutingContext, - enforce_account_model_policy: bool, + enforce_routing_policy: bool, direct_model: Option<&UpstreamModelId>, ) -> Result { let requirements = operation.capability_requirements(); @@ -1440,8 +1461,7 @@ impl RuntimeSnapshot { } .map_err(|_| RoutingError::InvalidIdentifier)? }; - if enforce_account_model_policy - && account_scope.groups_deny_model(Some(upstream_model.as_str())) + if enforce_routing_policy && account_scope.groups_deny_model(Some(upstream_model.as_str())) { return Err(RoutingError::GroupModelDenied); } @@ -1476,7 +1496,7 @@ impl RuntimeSnapshot { continue; } // 强制 Provider 路由也不能扩大 Key 授权;管理诊断的目标账号由探测入口固定 - if enforce_account_model_policy + if enforce_routing_policy && !account_scope.allows_provider_model(provider, upstream_model.as_str()) { continue; @@ -1485,6 +1505,18 @@ impl RuntimeSnapshot { .provider_models .get(provider) .and_then(|models| models.get(&upstream_model)); + // 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派 + let native_protocol = match operation { + Operation::Generate(request) => request.requires_native_protocol(), + Operation::CountTokens(request) => request.requires_native_protocol(), + _ => false, + }; + if native_protocol + && capabilities.and_then(|model| model.generation_protocol) + != Some(operation.protocol()) + { + continue; + } // 直连模型需要原生能力,不能借用插件为同名模型声明的账号与能力。 if direct_model.is_some() && capabilities.is_none() { continue; @@ -1502,24 +1534,30 @@ impl RuntimeSnapshot { let emulated_features = if contributions.is_empty() { match capabilities { Some(capabilities) => { - let Some(emulated) = capabilities.match_requirements(&requirements) else { + let Some(emulated) = capabilities.match_operation(operation, &requirements) + else { continue; }; emulated } - None if known_model || self.exhaustive_provider_catalogs.contains(provider) => { + // 固定账号诊断由指定 Provider 向上游核实,停用账号可能从未出现在公开目录 + None if enforce_routing_policy + && (known_model + || self.exhaustive_provider_catalogs.contains(provider)) => + { continue; } None => BTreeSet::new(), } } else { - let native = capabilities.and_then(|value| value.match_requirements(&requirements)); + let native = + capabilities.and_then(|value| value.match_operation(operation, &requirements)); let capable_accounts: BTreeSet<_> = contributions .iter() .filter(|model| { model .capabilities - .match_requirements(&requirements) + .match_operation(operation, &requirements) .is_some() }) .flat_map(|model| model.accounts.iter()) @@ -1660,7 +1698,7 @@ impl RuntimeSnapshot { .and_then(|models| models.get(model)) { Some(capabilities) => capabilities - .match_requirements(&operation.capability_requirements()) + .match_operation(operation, &operation.capability_requirements()) .is_some(), None => !self.exhaustive_provider_catalogs.contains(provider), } diff --git a/backend/crates/gateway-core/src/settings/compiled.rs b/backend/crates/gateway-core/src/settings/compiled.rs index 5ff34c022..702d42609 100644 --- a/backend/crates/gateway-core/src/settings/compiled.rs +++ b/backend/crates/gateway-core/src/settings/compiled.rs @@ -77,7 +77,7 @@ impl CompiledSettings { settings.key_queue_timeout_seconds, settings.account_queue_timeout_seconds, settings.max_account_rotations, - settings.openai_session_affinity_ttl_hours, + settings.session_affinity_ttl_hours, ) .map_err(|_| InvalidSettings)?; let responses_max_decompressed_body_bytes = @@ -95,10 +95,10 @@ impl CompiledSettings { AccountConcurrency::new(settings.max_concurrent_per_account), ) .with_openai_guardian_reserved_concurrency(settings.openai_guardian_reserved_concurrency) - .with_openai_account_affinity(settings.openai_account_affinity) + .with_account_affinity(settings.account_affinity) .with_max_account_rotations(settings.max_account_rotations) - .with_openai_session_affinity_ttl(Duration::from_secs( - u64::from(settings.openai_session_affinity_ttl_hours) * 3600, + .with_session_affinity_ttl(Duration::from_secs( + u64::from(settings.session_affinity_ttl_hours) * 3600, )) .with_smart_scheduling(settings.smart_scheduling) .with_quota_reset_window_weights(settings.quota_reset_window_weights) diff --git a/backend/crates/gateway-core/src/settings/values.rs b/backend/crates/gateway-core/src/settings/values.rs index 0d585a13e..b936998a8 100644 --- a/backend/crates/gateway-core/src/settings/values.rs +++ b/backend/crates/gateway-core/src/settings/values.rs @@ -27,9 +27,9 @@ pub struct SettingsValues { pub(crate) openai_guardian_reserved_concurrency: u32, pub(crate) openai_oauth_guardian_review_model: bool, pub(crate) openai_request_country: crate::account::OpenAiRequestCountry, - pub(crate) openai_account_affinity: crate::account::AccountAffinity, + pub(crate) account_affinity: crate::account::AccountAffinity, pub(crate) max_account_rotations: u32, - pub(crate) openai_session_affinity_ttl_hours: u32, + pub(crate) session_affinity_ttl_hours: u32, pub(crate) responses_max_decompressed_body_bytes: u64, pub(crate) smart_scheduling: crate::account::SmartSchedulingConfig, #[serde(default)] @@ -77,17 +77,17 @@ impl SettingsValues { } #[must_use] - pub const fn with_openai_session_affinity_ttl_hours(mut self, hours: u32) -> Self { - self.openai_session_affinity_ttl_hours = hours; + pub const fn with_session_affinity_ttl_hours(mut self, hours: u32) -> Self { + self.session_affinity_ttl_hours = hours; self } #[must_use] - pub const fn with_openai_account_affinity( + pub const fn with_account_affinity( mut self, affinity: crate::account::AccountAffinity, ) -> Self { - self.openai_account_affinity = affinity; + self.account_affinity = affinity; self } @@ -236,9 +236,9 @@ impl SettingsValues { openai_guardian_reserved_concurrency: 0, openai_oauth_guardian_review_model: true, openai_request_country: Default::default(), - openai_account_affinity: crate::account::AccountAffinity::default(), + account_affinity: crate::account::AccountAffinity::default(), max_account_rotations: 3, - openai_session_affinity_ttl_hours: 24, + session_affinity_ttl_hours: 24, responses_max_decompressed_body_bytes: 64 * 1024 * 1024, smart_scheduling: crate::account::SmartSchedulingConfig::default(), quota_reset_window_weights: crate::account::ResetWindowWeights::default(), @@ -292,7 +292,7 @@ pub fn validate_request_limits( ), ( (1..=crate::account::MAX_SESSION_AFFINITY_TTL_HOURS).contains(&affinity_ttl_hours), - "openai_session_affinity_ttl_hours", + "session_affinity_ttl_hours", ), ] { if !valid { diff --git a/backend/crates/gateway-core/tests/engine/coordinator.rs b/backend/crates/gateway-core/tests/engine/coordinator.rs index 72e96babd..c2a8fbc34 100644 --- a/backend/crates/gateway-core/tests/engine/coordinator.rs +++ b/backend/crates/gateway-core/tests/engine/coordinator.rs @@ -1230,15 +1230,10 @@ fn plan_with_protection( .with_smart_scheduling(account_selection_policy.smart_scheduling()) .with_quota_reset_window_weights(account_selection_policy.quota_reset_window_weights()) .with_max_account_rotations(account_selection_policy.max_account_rotations()) - .with_openai_account_affinity(account_selection_policy.openai_account_affinity()) - .with_openai_session_affinity_ttl_hours( - u32::try_from( - account_selection_policy - .openai_session_affinity_ttl() - .as_secs() - / 3600, - ) - .unwrap(), + .with_account_affinity(account_selection_policy.account_affinity()) + .with_session_affinity_ttl_hours( + u32::try_from(account_selection_policy.session_affinity_ttl().as_secs() / 3600) + .unwrap(), ) .with_request_location(request_location, true) .with_account_error_protection(protection) @@ -7281,7 +7276,7 @@ fn configured_rotation_budget_limits_actual_account_changes() { &operation, AccountSelectionPolicy::new(RotationStrategy::Smart, NonZeroU32::new(2).unwrap()) .with_max_account_rotations(budget) - .with_openai_session_affinity_ttl(Duration::from_secs(168 * 3600)), + .with_session_affinity_ttl(Duration::from_secs(168 * 3600)), ); let (coordinator, store, provider) = coordinator( ROTATION_TEST_ACCOUNTS @@ -7311,9 +7306,7 @@ fn configured_rotation_budget_limits_actual_account_changes() { assert_eq!(contexts.len(), (budget + 1) as usize); assert!(contexts.iter().all(|context| { context.account_selection_policy().max_account_rotations() == budget - && context - .account_selection_policy() - .openai_session_affinity_ttl() + && context.account_selection_policy().session_affinity_ttl() == Duration::from_secs(168 * 3600) })); let state = store.state.lock().unwrap(); diff --git a/backend/crates/gateway-core/tests/engine/execution/mod.rs b/backend/crates/gateway-core/tests/engine/execution/mod.rs index beff2619b..f567fb3d3 100644 --- a/backend/crates/gateway-core/tests/engine/execution/mod.rs +++ b/backend/crates/gateway-core/tests/engine/execution/mod.rs @@ -3643,6 +3643,44 @@ fn diagnostic_probe_uses_global_profile_without_data_plane_account_model_policy( assert_eq!(error.source(), AccountProbeErrorSource::Provider); } +#[test] +fn fixed_account_probe_reaches_the_provider_for_a_model_absent_from_its_public_catalog() { + use gateway_core::error::RoutingError; + + let provider = ProviderKind::new("openai").unwrap(); + let account = ProviderAccountId::new("acct_probe").unwrap(); + let model = "unlisted-probe-model"; + let snapshot = probe_snapshot(); + let ordinary = snapshot.plan( + &PublicModelId::new(model).unwrap(), + &probe_operation(), + account_scope(&provider, account.as_str()), + &Default::default(), + ); + assert!(matches!(ordinary, Err(RoutingError::ModelNotFound { .. }))); + + let service = DefaultExecutionService::new( + RuntimeSnapshotHandle::new(snapshot), + Arc::new(TrackingExecutionStore::default()), + ProviderRegistry::new([Arc::new(LocalFailingProvider) as Arc]).unwrap(), + Arc::new(UnusedAdmissions), + Arc::new(UnusedContinuation), + Arc::new(RecordingClientApiKeyUsage::default()), + Arc::new(crate::RecordingDiagnostics::default()), + ); + let error = block_on(service.probe( + AccountProbeRequest { + target: AccountProbeTarget::ConnectionTest(account), + provider_kind: provider, + upstream_model: UpstreamModelId::new(model).unwrap(), + operation: probe_operation(), + }, + None, + )) + .expect_err("the fixed provider reports its own connection failure"); + assert_eq!(error.source(), AccountProbeErrorSource::Provider); +} + #[test] fn probe_observation_store_failure_preserves_the_provider_error() { let store = Arc::new(TrackingExecutionStore { @@ -5771,3 +5809,65 @@ fn cancelled_prepared_execution_records_rejection_without_admission_or_model_req assert!(store.requests.lock().unwrap().is_empty()); }); } + +struct EofResponseTranslator { + protocol: &'static str, +} + +impl NativeResponseTranslator for EofResponseTranslator { + fn source_protocol(&self) -> &str { + "native-test" + } + fn target_protocol(&self) -> &str { + "openai" + } + fn translate( + &mut self, + _: &ProtocolWireEvent, + ) -> Result, ProviderError> { + Ok(Vec::new()) + } + fn finish(&mut self) -> Result, ProviderError> { + Ok(vec![ + ProtocolWireEvent::json( + self.protocol, + None, + json!({"type":"response.output_item.done"}), + ) + .unwrap(), + ProtocolWireEvent::json(self.protocol, None, json!({"type":"response.completed"})) + .unwrap(), + ]) + } +} + +#[test] +fn eof_translation_preserves_terminal_facts_and_validates_output_protocol() { + for protocol in ["openai", "foreign"] { + let metadata = ProviderCallMetadata::new( + ProviderKind::new("fixture").unwrap(), + UpstreamModelId::new("model").unwrap(), + ProviderAccountId::new("acct_fixture").unwrap(), + UpstreamTransport::new("http").unwrap(), + ); + let mut stream = ProviderStream::new(metadata, futures::stream::empty(), ()) + .with_native_response_translator(EofResponseTranslator { protocol }); + let result = stream.translate_native_response( + ProviderEvent::canonical(GatewayEvent::Completed(ResponseMeta::new( + "response", "model", + ))), + true, + ); + if protocol == "foreign" { + assert!(result.is_err()); + continue; + } + let events = result.unwrap(); + assert_eq!(events.len(), 2); + assert!(events[0].canonical_facts().is_empty()); + assert!(matches!( + events[1].canonical_facts(), + [GatewayEvent::Completed(_)] + )); + } +} diff --git a/backend/crates/gateway-core/tests/error/contract.rs b/backend/crates/gateway-core/tests/error/contract.rs new file mode 100644 index 000000000..8771ca3e7 --- /dev/null +++ b/backend/crates/gateway-core/tests/error/contract.rs @@ -0,0 +1,261 @@ +//! 跨模块行为合同测试 + +use super::*; + +#[test] +fn provider_error_debug_should_not_expose_sensitive_context() { + let secret = "sk-do-not-log-this"; + let error = ProviderError::new(ProviderErrorKind::Unauthorized, UpstreamSendState::Sent) + .redact_sensitive_context(secret); + + assert!(!format!("{error:?}").contains(secret)); +} + +#[test] +fn provider_error_debug_should_not_print_classified_upstream_values() { + let diagnostic = "request-visible-only-through-explicit-accessor"; + let value = OpaqueUpstreamValue::new(diagnostic); + let error = ProviderError::new(ProviderErrorKind::Unavailable, UpstreamSendState::Sent) + .with_upstream_request_id(value); + + assert!(!format!("{error:?}").contains(diagnostic)); +} + +#[test] +fn classified_provider_diagnostic_survives_stable_snapshot_without_entering_debug() { + let message = "OpenAI WebSocket closed before terminal response (close code 1000)"; + let error = ProviderError::new(ProviderErrorKind::Transport, UpstreamSendState::Ambiguous) + .with_diagnostic( + ProviderDiagnostic::new(message) + .with_classification("receive", "closed_before_terminal"), + ); + let snapshot = error.stable_snapshot(); + let gateway = GatewayError::from_provider(&snapshot); + + assert_eq!( + gateway.diagnostic().map(ProviderDiagnostic::as_str), + Some(message) + ); + assert_eq!( + gateway.diagnostic().and_then(ProviderDiagnostic::stage), + Some("receive") + ); + assert_eq!( + gateway.diagnostic().and_then(ProviderDiagnostic::code), + Some("closed_before_terminal") + ); + assert!(!format!("{error:?}").contains(message)); + assert!(!format!("{gateway:?}").contains(message)); +} + +#[test] +fn io_diagnostic_keeps_os_cause_without_copying_custom_error_text() { + let os_error = std::fs::File::open( + std::env::temp_dir().join(format!("cpr-missing-ca-{}/missing.pem", std::process::id())), + ) + .unwrap_err(); + let diagnostic = ProviderDiagnostic::new("CA read failed") + .with_classification("prepare", "custom_ca_read_failed") + .with_io_cause(&os_error); + assert!(diagnostic.as_str().contains(&os_error.to_string())); + assert_eq!(diagnostic.stage(), Some("prepare")); + assert_eq!(diagnostic.code(), Some("io_not_found")); + + let private = std::io::Error::new( + std::io::ErrorKind::ConnectionRefused, + "PRIVATE_URL_AND_CREDENTIAL", + ); + let diagnostic = ProviderDiagnostic::new("Connect failed").with_io_cause(&private); + assert_eq!(diagnostic.code(), Some("connection_refused")); + assert!(!diagnostic.as_str().contains("PRIVATE_")); +} + +#[test] +fn raw_upstream_error_survives_stable_snapshot_without_entering_debug() { + let raw = r#"{"error":{"message":"verbatim upstream marker"}}"#; + let error = ProviderError::new(ProviderErrorKind::Unavailable, UpstreamSendState::Sent) + .with_raw_upstream_error(RawUpstreamError::new(raw)); + let snapshot = error.stable_snapshot(); + + assert_eq!( + snapshot.raw_upstream_error().map(RawUpstreamError::as_str), + Some(raw) + ); + assert!(!format!("{error:?}").contains("verbatim upstream marker")); +} + +#[test] +fn opaque_upstream_value_should_preserve_arbitrary_text_without_logging_it() { + let original = format!("\0{}\n", "x".repeat(9_000)); + let value = OpaqueUpstreamValue::new(original.clone()); + + assert_eq!(value.as_str(), original); + assert!(!format!("{value:?}").contains(&original)); +} + +#[test] +fn provider_error_replay_proof_should_default_to_false() { + let error = ProviderError::new(ProviderErrorKind::RateLimited, UpstreamSendState::Sent); + + assert!(!error.replay_is_safe()); +} + +#[test] +fn provider_error_replay_proof_should_be_explicit() { + let error = ProviderError::new(ProviderErrorKind::RateLimited, UpstreamSendState::Sent) + .with_replay_safe(); + + assert!(error.replay_is_safe()); +} + +#[test] +fn provider_error_atomic_client_events_should_be_take_only_and_debug_redacted() { + let marker = "atomic-wire-must-not-enter-debug"; + let event = ProviderEvent::wire( + ProtocolWireEvent::json( + "openai", + Some("response.failed".to_owned()), + json!({"type": "response.failed", "message": marker}), + ) + .expect("atomic wire"), + ); + let mut error = ProviderError::new(ProviderErrorKind::RateLimited, UpstreamSendState::Sent) + .with_atomic_client_events(vec![event]); + + assert!(error.has_atomic_client_events()); + assert!(!format!("{error:?}").contains(marker)); + assert_eq!(error.take_atomic_client_events().len(), 1); + assert!(!error.has_atomic_client_events()); +} + +#[test] +fn provider_error_stable_snapshot_should_drop_request_local_upstream_response() { + let marker = Bytes::from_static(b"raw-client-response-only"); + let error = ProviderError::new(ProviderErrorKind::RateLimited, UpstreamSendState::Sent) + .with_client_visible_upstream_response( + ClientVisibleUpstreamResponse::new( + 429, + Some(b"application/problem+json".to_vec()), + marker.clone(), + ) + .with_headers(vec![ProviderResponseHeader::new( + "x-future-error", + Bytes::from_static(b"opaque-header-value"), + )]), + ); + + let snapshot = error.stable_snapshot(); + + assert_eq!( + error + .client_visible_upstream_response() + .map(ClientVisibleUpstreamResponse::body), + Some(&marker) + ); + assert!(snapshot.client_visible_upstream_response().is_none()); + assert!(!format!("{error:?}").contains("raw-client-response-only")); + assert!(!format!("{error:?}").contains("opaque-header-value")); +} + +#[test] +fn provider_error_stable_snapshot_should_drop_atomic_client_events() { + let event = ProviderEvent::wire( + ProtocolWireEvent::json( + "openai", + Some("response.failed".to_owned()), + json!({"type": "response.failed"}), + ) + .expect("atomic wire"), + ); + let error = ProviderError::new(ProviderErrorKind::RateLimited, UpstreamSendState::Sent) + .with_atomic_client_events(vec![event]); + let snapshot = error.stable_snapshot(); + + assert!(error.has_atomic_client_events()); + assert!(!snapshot.has_atomic_client_events()); +} + +#[test] +fn gateway_error_should_keep_client_visible_upstream_fields_out_of_safe_diagnostics() { + let message = "Your Codex quota is exhausted"; + let error = ProviderError::new(ProviderErrorKind::QuotaExhausted, UpstreamSendState::Sent) + .with_client_visible_upstream_error(ClientVisibleUpstreamError::new( + message, + Some("quota_exhausted".to_owned()), + Some("rate_limit_error".to_owned()), + )); + let gateway = GatewayError::from_provider(&error); + + assert_eq!( + gateway.safe_message(), + "Upstream capacity is temporarily unavailable." + ); + assert_eq!(gateway.client_message(), message); + assert_eq!(gateway.client_error_code(), Some("quota_exhausted")); + assert_eq!(gateway.client_error_type(), Some("rate_limit_error")); + assert!(!format!("{gateway:?}").contains(message)); +} + +#[test] +fn continuation_recovery_should_keep_its_internal_classification_and_client_contract() { + let error = ProviderError::new( + ProviderErrorKind::ContinuationRecoveryRequired, + UpstreamSendState::NotSent, + ) + .with_client_visible_upstream_error(ClientVisibleUpstreamError::new( + "Previous response was not found. Retrying the full request.", + Some("previous_response_not_found".to_owned()), + Some("invalid_request_error".to_owned()), + )); + let gateway = GatewayError::from_provider(&error); + + assert_eq!(error.kind().as_str(), "continuation_recovery_required"); + assert_eq!( + gateway.safe_message(), + "Previous response unavailable. Resend the full conversation history." + ); + assert_eq!( + gateway.client_error_code(), + Some("previous_response_not_found") + ); +} + +#[test] +fn message_too_big_should_map_to_a_request_scoped_client_contract() { + let error = ProviderError::new( + ProviderErrorKind::MessageTooBig, + UpstreamSendState::Ambiguous, + ) + .with_client_visible_upstream_error(ClientVisibleUpstreamError::new( + "upstream websocket message too big", + Some("message_too_big".to_owned()), + Some("invalid_request_error".to_owned()), + )); + let gateway = GatewayError::from_provider(&error); + + assert_eq!(error.kind().as_str(), "message_too_big"); + assert_eq!(gateway.kind().as_str(), "message_too_big"); + assert_eq!( + gateway.safe_message(), + "Request too large. Reduce the input size." + ); + assert_eq!(gateway.client_error_code(), Some("message_too_big")); + assert_eq!(gateway.client_error_type(), Some("invalid_request_error")); +} + +#[test] +fn client_visible_upstream_error_should_preserve_opaque_structured_fields() { + let message = format!("\0{}\n", "m".repeat(9_000)); + let code = format!("\0{}", "c".repeat(300)); + let error_type = String::new(); + let detail = ClientVisibleUpstreamError::new( + message.clone(), + Some(code.clone()), + Some(error_type.clone()), + ); + + assert_eq!(detail.message(), message); + assert_eq!(detail.code(), Some(code.as_str())); + assert_eq!(detail.error_type(), Some(error_type.as_str())); + assert!(!format!("{detail:?}").contains(&message)); +} diff --git a/backend/crates/gateway-core/tests/error/details.rs b/backend/crates/gateway-core/tests/error/details.rs new file mode 100644 index 000000000..308691c96 --- /dev/null +++ b/backend/crates/gateway-core/tests/error/details.rs @@ -0,0 +1,79 @@ +//! 对应生产职责的行为测试 + +use super::*; + +#[test] +fn restricted_details_preserve_causes_and_verbatim_upstream_body_separately() { + let body = "{ \"error\": {\"code\":\"Vendor.Unknown\",\"message\":\"PRIVATE_BODY\"} }"; + let error = ProviderError::new(ProviderErrorKind::Unavailable, UpstreamSendState::Sent) + .with_source(std::io::Error::other("PRIVATE_CAUSE")) + .with_raw_upstream_error(RawUpstreamError::new(body)); + let details: serde_json::Value = serde_json::from_str(&error.error_details().unwrap()).unwrap(); + assert_eq!(details["upstream"], body); + assert_eq!(details["causes"]["messages"], json!(["PRIVATE_CAUSE"])); + assert_eq!(details["causes"]["truncated"], false); + assert!(!format!("{error:?} {error}").contains("PRIVATE_")); + assert!( + ProviderError::new(ProviderErrorKind::Cancelled, UpstreamSendState::NotSent) + .error_details() + .is_none() + ); +} + +#[test] +fn restricted_cause_snapshot_bounds_unicode_and_cycles_with_an_explicit_marker() { + let error = ProviderError::new(ProviderErrorKind::Protocol, UpstreamSendState::NotSent) + .with_source(std::io::Error::other("原始原因".repeat(20_000))); + let details: serde_json::Value = serde_json::from_str(&error.error_details().unwrap()).unwrap(); + assert_eq!(details["causes"]["truncated"], true); + assert!(details["causes"]["messages"][0].as_str().unwrap().len() <= 64 * 1024); + + #[derive(Debug)] + struct CyclicError; + impl std::fmt::Display for CyclicError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("cyclic source") + } + } + impl std::error::Error for CyclicError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(self) + } + } + let error = ProviderError::new(ProviderErrorKind::Protocol, UpstreamSendState::NotSent) + .with_source(CyclicError); + let details: serde_json::Value = serde_json::from_str(&error.error_details().unwrap()).unwrap(); + assert_eq!(details["causes"]["truncated"], true); + assert_eq!(details["causes"]["messages"].as_array().unwrap().len(), 32); +} + +#[test] +fn cleanup_failure_keeps_the_primary_cause_and_separate_bounded_details() { + use gateway_core::error::{ErrorDetails, ErrorSource}; + let primary = ErrorSource::new(std::io::Error::other("PRIMARY_NATIVE_FAILURE")); + let combined = primary.with_cleanup(std::io::Error::other("ROLLBACK_NATIVE_FAILURE")); + assert_eq!( + combined.source().unwrap().to_string(), + "PRIMARY_NATIVE_FAILURE" + ); + let details = ErrorDetails::capture(Some(&combined), None, false).unwrap(); + let value: serde_json::Value = serde_json::from_str(details.as_str()).unwrap(); + assert_eq!( + value["causes"]["messages"], + json!(["PRIMARY_NATIVE_FAILURE"]) + ); + assert_eq!( + value["causes"]["cleanup"][0]["messages"], + json!(["ROLLBACK_NATIVE_FAILURE"]) + ); + assert_eq!(value["causes"]["truncated"], false); + assert!(!format!("{combined:?} {details:?}").contains("NATIVE_FAILURE")); + + let oversized = ErrorSource::new(std::io::Error::other("界".repeat(24_000))) + .with_cleanup(std::io::Error::other("ROLLBACK_NATIVE_FAILURE")); + let details = ErrorDetails::capture(Some(&oversized), None, false).unwrap(); + let value: serde_json::Value = serde_json::from_str(details.as_str()).unwrap(); + assert_eq!(value["causes"]["truncated"], true); + assert_eq!(value["causes"]["cleanup"][0]["truncated"], true); + assert!(details.as_str().len() < 66_000); +} diff --git a/backend/crates/gateway-core/tests/error/mod.rs b/backend/crates/gateway-core/tests/error/mod.rs index 3ddc5f71d..9c9ba9d6c 100644 --- a/backend/crates/gateway-core/tests/error/mod.rs +++ b/backend/crates/gateway-core/tests/error/mod.rs @@ -1,5 +1,8 @@ //! 验证执行错误的敏感信息脱敏、稳定快照与请求局部数据边界 +mod contract; +mod details; +mod source; use bytes::Bytes; use gateway_core::error::{ ClientVisibleUpstreamError, ClientVisibleUpstreamResponse, GatewayError, OpaqueUpstreamValue, @@ -8,377 +11,3 @@ use gateway_core::error::{ use gateway_core::event::{ProtocolWireEvent, ProviderEvent, ProviderResponseHeader}; use gateway_core::upstream::UpstreamSendState; use serde_json::json; - -#[test] -fn source_chain_survives_domain_conversion_and_snapshot_without_entering_formatting() { - use gateway_core::error::{StoreError, StoreErrorKind}; - use gateway_core::provider_ports::{ProviderStoreError, ProviderStoreErrorKind}; - use std::error::Error as _; - - let store = StoreError::caused_by( - StoreErrorKind::Unavailable, - std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "PRIVATE_DB_CAUSE"), - ); - let port = - ProviderStoreError::caused_by(ProviderStoreErrorKind::Unavailable, "select account", store); - let error = ProviderError::new( - ProviderErrorKind::ProviderInfrastructureUnavailable, - UpstreamSendState::NotSent, - ) - .with_source(port); - let snapshot = error.stable_snapshot(); - drop(error); - - let port = snapshot - .source() - .unwrap() - .downcast_ref::() - .unwrap(); - let store = port.source().unwrap().downcast_ref::().unwrap(); - let original = store - .source() - .unwrap() - .downcast_ref::() - .unwrap(); - assert_eq!(original.kind(), std::io::ErrorKind::ConnectionRefused); - assert_eq!(original.to_string(), "PRIVATE_DB_CAUSE"); - assert!( - !format!("{snapshot:?} {snapshot} {port:?} {port} {store:?} {store}") - .contains("PRIVATE_DB_CAUSE") - ); - assert_eq!(snapshot.send_state(), UpstreamSendState::NotSent); -} - -#[test] -fn restricted_details_preserve_causes_and_verbatim_upstream_body_separately() { - let body = "{ \"error\": {\"code\":\"Vendor.Unknown\",\"message\":\"PRIVATE_BODY\"} }"; - let error = ProviderError::new(ProviderErrorKind::Unavailable, UpstreamSendState::Sent) - .with_source(std::io::Error::other("PRIVATE_CAUSE")) - .with_raw_upstream_error(RawUpstreamError::new(body)); - let details: serde_json::Value = serde_json::from_str(&error.error_details().unwrap()).unwrap(); - assert_eq!(details["upstream"], body); - assert_eq!(details["causes"]["messages"], json!(["PRIVATE_CAUSE"])); - assert_eq!(details["causes"]["truncated"], false); - assert!(!format!("{error:?} {error}").contains("PRIVATE_")); - assert!( - ProviderError::new(ProviderErrorKind::Cancelled, UpstreamSendState::NotSent) - .error_details() - .is_none() - ); -} - -#[test] -fn restricted_cause_snapshot_bounds_unicode_and_cycles_with_an_explicit_marker() { - let error = ProviderError::new(ProviderErrorKind::Protocol, UpstreamSendState::NotSent) - .with_source(std::io::Error::other("原始原因".repeat(20_000))); - let details: serde_json::Value = serde_json::from_str(&error.error_details().unwrap()).unwrap(); - assert_eq!(details["causes"]["truncated"], true); - assert!(details["causes"]["messages"][0].as_str().unwrap().len() <= 64 * 1024); - - #[derive(Debug)] - struct CyclicError; - impl std::fmt::Display for CyclicError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("cyclic source") - } - } - impl std::error::Error for CyclicError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - Some(self) - } - } - let error = ProviderError::new(ProviderErrorKind::Protocol, UpstreamSendState::NotSent) - .with_source(CyclicError); - let details: serde_json::Value = serde_json::from_str(&error.error_details().unwrap()).unwrap(); - assert_eq!(details["causes"]["truncated"], true); - assert_eq!(details["causes"]["messages"].as_array().unwrap().len(), 32); -} - -#[test] -fn provider_error_debug_should_not_expose_sensitive_context() { - let secret = "sk-do-not-log-this"; - let error = ProviderError::new(ProviderErrorKind::Unauthorized, UpstreamSendState::Sent) - .redact_sensitive_context(secret); - - assert!(!format!("{error:?}").contains(secret)); -} - -#[test] -fn provider_error_debug_should_not_print_classified_upstream_values() { - let diagnostic = "request-visible-only-through-explicit-accessor"; - let value = OpaqueUpstreamValue::new(diagnostic); - let error = ProviderError::new(ProviderErrorKind::Unavailable, UpstreamSendState::Sent) - .with_upstream_request_id(value); - - assert!(!format!("{error:?}").contains(diagnostic)); -} - -#[test] -fn classified_provider_diagnostic_survives_stable_snapshot_without_entering_debug() { - let message = "OpenAI WebSocket closed before terminal response (close code 1000)"; - let error = ProviderError::new(ProviderErrorKind::Transport, UpstreamSendState::Ambiguous) - .with_diagnostic( - ProviderDiagnostic::new(message) - .with_classification("receive", "closed_before_terminal"), - ); - let snapshot = error.stable_snapshot(); - let gateway = GatewayError::from_provider(&snapshot); - - assert_eq!( - gateway.diagnostic().map(ProviderDiagnostic::as_str), - Some(message) - ); - assert_eq!( - gateway.diagnostic().and_then(ProviderDiagnostic::stage), - Some("receive") - ); - assert_eq!( - gateway.diagnostic().and_then(ProviderDiagnostic::code), - Some("closed_before_terminal") - ); - assert!(!format!("{error:?}").contains(message)); - assert!(!format!("{gateway:?}").contains(message)); -} - -#[test] -fn io_diagnostic_keeps_os_cause_without_copying_custom_error_text() { - let os_error = std::fs::File::open( - std::env::temp_dir().join(format!("cpr-missing-ca-{}/missing.pem", std::process::id())), - ) - .unwrap_err(); - let diagnostic = ProviderDiagnostic::new("CA read failed") - .with_classification("prepare", "custom_ca_read_failed") - .with_io_cause(&os_error); - assert!(diagnostic.as_str().contains(&os_error.to_string())); - assert_eq!(diagnostic.stage(), Some("prepare")); - assert_eq!(diagnostic.code(), Some("io_not_found")); - - let private = std::io::Error::new( - std::io::ErrorKind::ConnectionRefused, - "PRIVATE_URL_AND_CREDENTIAL", - ); - let diagnostic = ProviderDiagnostic::new("Connect failed").with_io_cause(&private); - assert_eq!(diagnostic.code(), Some("connection_refused")); - assert!(!diagnostic.as_str().contains("PRIVATE_")); -} - -#[test] -fn raw_upstream_error_survives_stable_snapshot_without_entering_debug() { - let raw = r#"{"error":{"message":"verbatim upstream marker"}}"#; - let error = ProviderError::new(ProviderErrorKind::Unavailable, UpstreamSendState::Sent) - .with_raw_upstream_error(RawUpstreamError::new(raw)); - let snapshot = error.stable_snapshot(); - - assert_eq!( - snapshot.raw_upstream_error().map(RawUpstreamError::as_str), - Some(raw) - ); - assert!(!format!("{error:?}").contains("verbatim upstream marker")); -} - -#[test] -fn opaque_upstream_value_should_preserve_arbitrary_text_without_logging_it() { - let original = format!("\0{}\n", "x".repeat(9_000)); - let value = OpaqueUpstreamValue::new(original.clone()); - - assert_eq!(value.as_str(), original); - assert!(!format!("{value:?}").contains(&original)); -} - -#[test] -fn provider_error_replay_proof_should_default_to_false() { - let error = ProviderError::new(ProviderErrorKind::RateLimited, UpstreamSendState::Sent); - - assert!(!error.replay_is_safe()); -} - -#[test] -fn provider_error_replay_proof_should_be_explicit() { - let error = ProviderError::new(ProviderErrorKind::RateLimited, UpstreamSendState::Sent) - .with_replay_safe(); - - assert!(error.replay_is_safe()); -} - -#[test] -fn provider_error_atomic_client_events_should_be_take_only_and_debug_redacted() { - let marker = "atomic-wire-must-not-enter-debug"; - let event = ProviderEvent::wire( - ProtocolWireEvent::json( - "openai", - Some("response.failed".to_owned()), - json!({"type": "response.failed", "message": marker}), - ) - .expect("atomic wire"), - ); - let mut error = ProviderError::new(ProviderErrorKind::RateLimited, UpstreamSendState::Sent) - .with_atomic_client_events(vec![event]); - - assert!(error.has_atomic_client_events()); - assert!(!format!("{error:?}").contains(marker)); - assert_eq!(error.take_atomic_client_events().len(), 1); - assert!(!error.has_atomic_client_events()); -} - -#[test] -fn provider_error_stable_snapshot_should_drop_request_local_upstream_response() { - let marker = Bytes::from_static(b"raw-client-response-only"); - let error = ProviderError::new(ProviderErrorKind::RateLimited, UpstreamSendState::Sent) - .with_client_visible_upstream_response( - ClientVisibleUpstreamResponse::new( - 429, - Some(b"application/problem+json".to_vec()), - marker.clone(), - ) - .with_headers(vec![ProviderResponseHeader::new( - "x-future-error", - Bytes::from_static(b"opaque-header-value"), - )]), - ); - - let snapshot = error.stable_snapshot(); - - assert_eq!( - error - .client_visible_upstream_response() - .map(ClientVisibleUpstreamResponse::body), - Some(&marker) - ); - assert!(snapshot.client_visible_upstream_response().is_none()); - assert!(!format!("{error:?}").contains("raw-client-response-only")); - assert!(!format!("{error:?}").contains("opaque-header-value")); -} - -#[test] -fn provider_error_stable_snapshot_should_drop_atomic_client_events() { - let event = ProviderEvent::wire( - ProtocolWireEvent::json( - "openai", - Some("response.failed".to_owned()), - json!({"type": "response.failed"}), - ) - .expect("atomic wire"), - ); - let error = ProviderError::new(ProviderErrorKind::RateLimited, UpstreamSendState::Sent) - .with_atomic_client_events(vec![event]); - let snapshot = error.stable_snapshot(); - - assert!(error.has_atomic_client_events()); - assert!(!snapshot.has_atomic_client_events()); -} - -#[test] -fn gateway_error_should_keep_client_visible_upstream_fields_out_of_safe_diagnostics() { - let message = "Your Codex quota is exhausted"; - let error = ProviderError::new(ProviderErrorKind::QuotaExhausted, UpstreamSendState::Sent) - .with_client_visible_upstream_error(ClientVisibleUpstreamError::new( - message, - Some("quota_exhausted".to_owned()), - Some("rate_limit_error".to_owned()), - )); - let gateway = GatewayError::from_provider(&error); - - assert_eq!( - gateway.safe_message(), - "Upstream capacity is temporarily unavailable." - ); - assert_eq!(gateway.client_message(), message); - assert_eq!(gateway.client_error_code(), Some("quota_exhausted")); - assert_eq!(gateway.client_error_type(), Some("rate_limit_error")); - assert!(!format!("{gateway:?}").contains(message)); -} - -#[test] -fn continuation_recovery_should_keep_its_internal_classification_and_client_contract() { - let error = ProviderError::new( - ProviderErrorKind::ContinuationRecoveryRequired, - UpstreamSendState::NotSent, - ) - .with_client_visible_upstream_error(ClientVisibleUpstreamError::new( - "Previous response was not found. Retrying the full request.", - Some("previous_response_not_found".to_owned()), - Some("invalid_request_error".to_owned()), - )); - let gateway = GatewayError::from_provider(&error); - - assert_eq!(error.kind().as_str(), "continuation_recovery_required"); - assert_eq!( - gateway.safe_message(), - "Previous response unavailable. Resend the full conversation history." - ); - assert_eq!( - gateway.client_error_code(), - Some("previous_response_not_found") - ); -} - -#[test] -fn message_too_big_should_map_to_a_request_scoped_client_contract() { - let error = ProviderError::new( - ProviderErrorKind::MessageTooBig, - UpstreamSendState::Ambiguous, - ) - .with_client_visible_upstream_error(ClientVisibleUpstreamError::new( - "upstream websocket message too big", - Some("message_too_big".to_owned()), - Some("invalid_request_error".to_owned()), - )); - let gateway = GatewayError::from_provider(&error); - - assert_eq!(error.kind().as_str(), "message_too_big"); - assert_eq!(gateway.kind().as_str(), "message_too_big"); - assert_eq!( - gateway.safe_message(), - "Request too large. Reduce the input size." - ); - assert_eq!(gateway.client_error_code(), Some("message_too_big")); - assert_eq!(gateway.client_error_type(), Some("invalid_request_error")); -} - -#[test] -fn client_visible_upstream_error_should_preserve_opaque_structured_fields() { - let message = format!("\0{}\n", "m".repeat(9_000)); - let code = format!("\0{}", "c".repeat(300)); - let error_type = String::new(); - let detail = ClientVisibleUpstreamError::new( - message.clone(), - Some(code.clone()), - Some(error_type.clone()), - ); - - assert_eq!(detail.message(), message); - assert_eq!(detail.code(), Some(code.as_str())); - assert_eq!(detail.error_type(), Some(error_type.as_str())); - assert!(!format!("{detail:?}").contains(&message)); -} - -#[test] -fn cleanup_failure_keeps_the_primary_cause_and_separate_bounded_details() { - use gateway_core::error::{ErrorDetails, ErrorSource}; - let primary = ErrorSource::new(std::io::Error::other("PRIMARY_NATIVE_FAILURE")); - let combined = primary.with_cleanup(std::io::Error::other("ROLLBACK_NATIVE_FAILURE")); - assert_eq!( - combined.source().unwrap().to_string(), - "PRIMARY_NATIVE_FAILURE" - ); - let details = ErrorDetails::capture(Some(&combined), None, false).unwrap(); - let value: serde_json::Value = serde_json::from_str(details.as_str()).unwrap(); - assert_eq!( - value["causes"]["messages"], - json!(["PRIMARY_NATIVE_FAILURE"]) - ); - assert_eq!( - value["causes"]["cleanup"][0]["messages"], - json!(["ROLLBACK_NATIVE_FAILURE"]) - ); - assert_eq!(value["causes"]["truncated"], false); - assert!(!format!("{combined:?} {details:?}").contains("NATIVE_FAILURE")); - - let oversized = ErrorSource::new(std::io::Error::other("界".repeat(24_000))) - .with_cleanup(std::io::Error::other("ROLLBACK_NATIVE_FAILURE")); - let details = ErrorDetails::capture(Some(&oversized), None, false).unwrap(); - let value: serde_json::Value = serde_json::from_str(details.as_str()).unwrap(); - assert_eq!(value["causes"]["truncated"], true); - assert_eq!(value["causes"]["cleanup"][0]["truncated"], true); - assert!(details.as_str().len() < 66_000); -} diff --git a/backend/crates/gateway-core/tests/error/source.rs b/backend/crates/gateway-core/tests/error/source.rs new file mode 100644 index 000000000..f555f2681 --- /dev/null +++ b/backend/crates/gateway-core/tests/error/source.rs @@ -0,0 +1,43 @@ +//! 对应生产职责的行为测试 + +use super::*; + +#[test] +fn source_chain_survives_domain_conversion_and_snapshot_without_entering_formatting() { + use gateway_core::error::{StoreError, StoreErrorKind}; + use gateway_core::provider_ports::{ProviderStoreError, ProviderStoreErrorKind}; + use std::error::Error as _; + + let store = StoreError::caused_by( + StoreErrorKind::Unavailable, + std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "PRIVATE_DB_CAUSE"), + ); + let port = + ProviderStoreError::caused_by(ProviderStoreErrorKind::Unavailable, "select account", store); + let error = ProviderError::new( + ProviderErrorKind::ProviderInfrastructureUnavailable, + UpstreamSendState::NotSent, + ) + .with_source(port); + let snapshot = error.stable_snapshot(); + drop(error); + + let port = snapshot + .source() + .unwrap() + .downcast_ref::() + .unwrap(); + let store = port.source().unwrap().downcast_ref::().unwrap(); + let original = store + .source() + .unwrap() + .downcast_ref::() + .unwrap(); + assert_eq!(original.kind(), std::io::ErrorKind::ConnectionRefused); + assert_eq!(original.to_string(), "PRIVATE_DB_CAUSE"); + assert!( + !format!("{snapshot:?} {snapshot} {port:?} {port} {store:?} {store}") + .contains("PRIVATE_DB_CAUSE") + ); + assert_eq!(snapshot.send_state(), UpstreamSendState::NotSent); +} diff --git a/backend/crates/gateway-core/tests/operation.rs b/backend/crates/gateway-core/tests/operation.rs index 4feba7733..067e32e88 100644 --- a/backend/crates/gateway-core/tests/operation.rs +++ b/backend/crates/gateway-core/tests/operation.rs @@ -16,6 +16,27 @@ fn generate(body: Value) -> GenerateRequest { ) } +#[test] +fn raw_generate_body_tracks_the_document_used_for_permissions_after_middleware() { + let original = Bytes::from_static(br#"{ "tools": [], "contents": [] }"#); + let payload = ProtocolPayload::from_json_bytes("genai", original.clone()).unwrap(); + let request = Operation::Generate(GenerateRequest::from_protocol_payload(payload)); + let request = request.replace_protocol_wire(None, Map::new()).unwrap(); + assert_eq!(request.middleware_body().unwrap(), original); + + let replaced = Bytes::from_static(br#"{ "tools": [{"functionDeclarations":[{"name":"f"}]}] }"#); + let request = request + .replace_protocol_wire(Some(replaced.clone()), Map::new()) + .unwrap(); + assert!( + request + .capability_requirements() + .features() + .contains(&Feature::Tools) + ); + assert_eq!(request.middleware_body().unwrap(), replaced); +} + fn image(kind: ImageRequestKind, body: Value) -> ImageRequest { ImageRequest::from_raw_json( kind, diff --git a/backend/crates/gateway-core/tests/policy/client_version.rs b/backend/crates/gateway-core/tests/policy/client_version.rs new file mode 100644 index 000000000..b76754078 --- /dev/null +++ b/backend/crates/gateway-core/tests/policy/client_version.rs @@ -0,0 +1,67 @@ +//! 对应生产职责的行为测试 + +use super::*; + +#[test] +fn client_version_should_require_strict_semver() { + assert!(CodexClientVersion::parse("0.152.0").is_ok()); + assert!(CodexClientVersion::parse("v0.152.0").is_err()); + assert!(CodexClientVersion::parse("0.152").is_err()); + assert!(CodexClientVersion::parse(" 0.152.0").is_err()); + assert!(CodexClientVersion::parse("18446744073709551616.0.0").is_err()); +} + +#[test] +fn min_client_versions_should_reject_missing_and_old_recognized_clients() { + let min = CodexClientVersion::parse("0.40.0").expect("min version"); + let policy = CodexClientMinVersions::new(None, Some(min.clone())); + let old = CodexClientVersion::parse("0.39.0").expect("old version"); + let current = CodexClientVersion::parse("0.40.0").expect("current version"); + + assert_eq!( + policy.enforce(CodexClientKind::Cli, None), + Err(ClientVersionRejection::Unavailable { + kind: CodexClientKind::Cli, + min: min.clone(), + }) + ); + assert_eq!( + policy.enforce(CodexClientKind::Cli, Some(&old)), + Err(ClientVersionRejection::TooOld { + kind: CodexClientKind::Cli, + current: old, + min, + }) + ); + assert_eq!(policy.enforce(CodexClientKind::Cli, Some(¤t)), Ok(())); + assert_eq!(policy.enforce(CodexClientKind::Desktop, None), Ok(())); +} + +#[test] +fn min_client_versions_should_follow_semver_precedence() { + for (minimum, current, allowed) in [ + ("1.0.0", "1.0.0-rc.1", false), + ("1.0.0", "1.0.0", true), + ("1.0.0", "1.0.1", true), + ("1.0.0-rc.2", "1.0.0-rc.1", false), + ("1.0.0-rc.2", "1.0.0-rc.10", true), + ("1.0.0+build.2", "1.0.0", true), + ("1.0.0", "1.0.0+build.2", true), + ("1.0.0+build.2", "1.0.0+build.1", true), + ("1.0.0-rc.2+build.2", "1.0.0-rc.2+build.1", true), + ("1.0.0+build.1", "1.0.0-rc.1+build.9", false), + ("1.0.1+build.1", "1.0.0+build.9", false), + ] { + let minimum_version = CodexClientVersion::parse(minimum).unwrap(); + let current_version = CodexClientVersion::parse(current).unwrap(); + let policy = + CodexClientMinVersions::new(Some(minimum_version.clone()), Some(minimum_version)); + for kind in [CodexClientKind::Cli, CodexClientKind::Desktop] { + assert_eq!( + policy.enforce(kind, Some(¤t_version)).is_ok(), + allowed, + "{kind:?}: {current} >= {minimum}" + ); + } + } +} diff --git a/backend/crates/gateway-core/tests/policy/contract.rs b/backend/crates/gateway-core/tests/policy/contract.rs new file mode 100644 index 000000000..4d40fe563 --- /dev/null +++ b/backend/crates/gateway-core/tests/policy/contract.rs @@ -0,0 +1,66 @@ +//! 跨模块行为合同测试 + +use super::*; + +#[test] +fn disabled_client_key_should_be_denied() { + let policy = ClientPolicy::new( + ClientApiKeyId::new("key_disabled").expect("valid key ID"), + plaintext("sk_disabled_secret"), + account_scope(), + false, + RateLimits::unlimited(), + ); + + assert!(policy.authorize().is_err()); +} + +#[test] +fn enabled_client_key_should_be_authorized() { + let policy = ClientPolicy::new( + ClientApiKeyId::new("key_enabled").expect("valid key ID"), + plaintext("sk_enabled_secret"), + account_scope(), + true, + RateLimits::unlimited(), + ); + + assert!(policy.authorize().is_ok()); +} + +#[test] +fn zero_rate_limits_should_mean_unlimited() { + assert_eq!(RateLimits::unlimited().requests_per_minute, 0); +} + +#[test] +fn plaintext_client_key_debug_should_be_redacted() { + let key = plaintext("sk_must_not_appear"); + + let debug = format!("{key:?}"); + assert!(!debug.contains("must_not_appear")); + assert_eq!(key.expose_for_auth(), "sk_must_not_appear"); +} + +#[test] +fn migrated_client_keys_keep_their_exact_value_without_prefix_or_length_limits() { + for value in [ + "q".to_owned(), + "legacy-!@#$%^&*()[]{}:;,.?/+=~|\\".to_owned(), + "x".repeat(8192), + ] { + assert_eq!(plaintext(&value).expose_for_auth(), value); + } + for value in [ + "", + " ", + " key", + "key ", + "key\n", + "key\tvalue", + "key\u{7f}", + "密钥", + ] { + assert!(PlaintextClientApiKey::new(value).is_err()); + } +} diff --git a/backend/crates/gateway-core/tests/policy/mod.rs b/backend/crates/gateway-core/tests/policy/mod.rs index a2c19d1aa..52a273249 100644 --- a/backend/crates/gateway-core/tests/policy/mod.rs +++ b/backend/crates/gateway-core/tests/policy/mod.rs @@ -1,5 +1,7 @@ //! 验证 Client Key 准入、限额、凭据保护与客户端版本策略 +mod client_version; +mod contract; use std::sync::Arc; use gateway_core::policy::{ @@ -18,130 +20,3 @@ fn account_scope() -> Arc { ClientRoutingScope::all_accounts(), )) } - -#[test] -fn disabled_client_key_should_be_denied() { - let policy = ClientPolicy::new( - ClientApiKeyId::new("key_disabled").expect("valid key ID"), - plaintext("sk_disabled_secret"), - account_scope(), - false, - RateLimits::unlimited(), - ); - - assert!(policy.authorize().is_err()); -} - -#[test] -fn enabled_client_key_should_be_authorized() { - let policy = ClientPolicy::new( - ClientApiKeyId::new("key_enabled").expect("valid key ID"), - plaintext("sk_enabled_secret"), - account_scope(), - true, - RateLimits::unlimited(), - ); - - assert!(policy.authorize().is_ok()); -} - -#[test] -fn zero_rate_limits_should_mean_unlimited() { - assert_eq!(RateLimits::unlimited().requests_per_minute, 0); -} - -#[test] -fn plaintext_client_key_debug_should_be_redacted() { - let key = plaintext("sk_must_not_appear"); - - let debug = format!("{key:?}"); - assert!(!debug.contains("must_not_appear")); - assert_eq!(key.expose_for_auth(), "sk_must_not_appear"); -} - -#[test] -fn migrated_client_keys_keep_their_exact_value_without_prefix_or_length_limits() { - for value in [ - "q".to_owned(), - "legacy-!@#$%^&*()[]{}:;,.?/+=~|\\".to_owned(), - "x".repeat(8192), - ] { - assert_eq!(plaintext(&value).expose_for_auth(), value); - } - for value in [ - "", - " ", - " key", - "key ", - "key\n", - "key\tvalue", - "key\u{7f}", - "密钥", - ] { - assert!(PlaintextClientApiKey::new(value).is_err()); - } -} - -#[test] -fn client_version_should_require_strict_semver() { - assert!(CodexClientVersion::parse("0.152.0").is_ok()); - assert!(CodexClientVersion::parse("v0.152.0").is_err()); - assert!(CodexClientVersion::parse("0.152").is_err()); - assert!(CodexClientVersion::parse(" 0.152.0").is_err()); - assert!(CodexClientVersion::parse("18446744073709551616.0.0").is_err()); -} - -#[test] -fn min_client_versions_should_reject_missing_and_old_recognized_clients() { - let min = CodexClientVersion::parse("0.40.0").expect("min version"); - let policy = CodexClientMinVersions::new(None, Some(min.clone())); - let old = CodexClientVersion::parse("0.39.0").expect("old version"); - let current = CodexClientVersion::parse("0.40.0").expect("current version"); - - assert_eq!( - policy.enforce(CodexClientKind::Cli, None), - Err(ClientVersionRejection::Unavailable { - kind: CodexClientKind::Cli, - min: min.clone(), - }) - ); - assert_eq!( - policy.enforce(CodexClientKind::Cli, Some(&old)), - Err(ClientVersionRejection::TooOld { - kind: CodexClientKind::Cli, - current: old, - min, - }) - ); - assert_eq!(policy.enforce(CodexClientKind::Cli, Some(¤t)), Ok(())); - assert_eq!(policy.enforce(CodexClientKind::Desktop, None), Ok(())); -} - -#[test] -fn min_client_versions_should_follow_semver_precedence() { - for (minimum, current, allowed) in [ - ("1.0.0", "1.0.0-rc.1", false), - ("1.0.0", "1.0.0", true), - ("1.0.0", "1.0.1", true), - ("1.0.0-rc.2", "1.0.0-rc.1", false), - ("1.0.0-rc.2", "1.0.0-rc.10", true), - ("1.0.0+build.2", "1.0.0", true), - ("1.0.0", "1.0.0+build.2", true), - ("1.0.0+build.2", "1.0.0+build.1", true), - ("1.0.0-rc.2+build.2", "1.0.0-rc.2+build.1", true), - ("1.0.0+build.1", "1.0.0-rc.1+build.9", false), - ("1.0.1+build.1", "1.0.0+build.9", false), - ] { - let minimum_version = CodexClientVersion::parse(minimum).unwrap(); - let current_version = CodexClientVersion::parse(current).unwrap(); - let policy = - CodexClientMinVersions::new(Some(minimum_version.clone()), Some(minimum_version)); - for kind in [CodexClientKind::Cli, CodexClientKind::Desktop] { - assert_eq!( - policy.enforce(kind, Some(¤t_version)).is_ok(), - allowed, - "{kind:?}: {current} >= {minimum}" - ); - } - } -} diff --git a/backend/crates/gateway-core/tests/provider_ports/affinity.rs b/backend/crates/gateway-core/tests/provider_ports/affinity.rs new file mode 100644 index 000000000..fa20434d5 --- /dev/null +++ b/backend/crates/gateway-core/tests/provider_ports/affinity.rs @@ -0,0 +1,10 @@ +//! 对应生产职责的行为测试 + +use super::*; + +#[test] +fn provider_session_affinity_key_debug_is_opaque() { + let key = ProviderSessionAffinityKey::try_new("opaque-session-key").expect("valid key"); + + assert_eq!(format!("{key:?}"), "ProviderSessionAffinityKey([OPAQUE])"); +} diff --git a/backend/crates/gateway-core/tests/provider_ports/lease.rs b/backend/crates/gateway-core/tests/provider_ports/lease.rs new file mode 100644 index 000000000..bf551e505 --- /dev/null +++ b/backend/crates/gateway-core/tests/provider_ports/lease.rs @@ -0,0 +1,33 @@ +//! 对应生产职责的行为测试 + +use super::*; + +#[test] +fn scheduling_state_preserves_provider_neutral_signals() { + let account = ProviderAccountId::new("acct_fixture").expect("valid account"); + let signals = BTreeMap::from([( + account.clone(), + AccountRuntimeSignals { + in_flight: 2, + last_started_at: None, + quota_reset_at: None, + quota_reset_windows: None, + quota_remaining_rank: Some(7), + cooldown: None, + failure_rate_basis_points: Some(125), + first_output_latency_ms: Some(250), + }, + )]); + let state = ProviderSchedulingState::new(signals, 9); + + assert_eq!(state.signals()[&account].in_flight, 2); + assert_eq!( + state.signals()[&account].failure_rate_basis_points, + Some(125) + ); + assert_eq!(state.round_robin_cursor(), 9); + assert_eq!( + CredentialRevision::new(1).expect("positive revision").get(), + 1 + ); +} diff --git a/backend/crates/gateway-core/tests/provider_ports/mod.rs b/backend/crates/gateway-core/tests/provider_ports/mod.rs index 3cf2b9fd7..9336cb996 100644 --- a/backend/crates/gateway-core/tests/provider_ports/mod.rs +++ b/backend/crates/gateway-core/tests/provider_ports/mod.rs @@ -1,5 +1,11 @@ //! 验证 Provider 协调端口的敏感值保护、有效期与刷新边界 +mod affinity; +mod lease; +mod oauth; +mod refresh; +mod runtime_policy; +mod session_affinity; use std::collections::{BTreeMap, BTreeSet}; use std::num::NonZeroU32; use std::time::{Duration, SystemTime}; @@ -12,298 +18,3 @@ use gateway_core::provider_ports::{ ProviderSessionAffinityKey, ProviderStoreErrorKind, }; use gateway_core::routing::ProviderKind; - -#[test] -fn oauth_pending_binding_debug_redacts_raw_value() { - let binding = OAuthPendingBinding::try_new("must-not-appear").expect("valid binding"); - - assert_eq!(format!("{binding:?}"), "OAuthPendingBinding([REDACTED])"); -} - -#[test] -fn provider_session_affinity_key_debug_is_opaque() { - let key = ProviderSessionAffinityKey::try_new("opaque-session-key").expect("valid key"); - - assert_eq!(format!("{key:?}"), "ProviderSessionAffinityKey([OPAQUE])"); -} - -#[test] -fn oauth_pending_ttl_rejects_zero_and_more_than_thirty_minutes() { - let provider = ProviderKind::new("fixture").expect("valid provider"); - let flow = OAuthPendingBinding::try_new("flow").expect("valid flow"); - let owner = OAuthPendingBinding::try_new("owner").expect("valid owner"); - let payload = OpaqueProviderData::new(serde_json::Map::new()); - - for ttl in [Duration::ZERO, Duration::from_secs(30 * 60 + 1)] { - let error = NewOAuthPendingFlow::try_new( - provider.clone(), - flow.clone(), - owner.clone(), - ttl, - payload.clone(), - ) - .expect_err("invalid TTL must fail"); - assert_eq!(error.kind(), ProviderStoreErrorKind::InvalidData); - } -} - -#[test] -fn refresh_policy_requires_a_positive_margin() { - let error = ProviderRefreshPolicy::try_new( - Duration::ZERO, - NonZeroU32::new(1).expect("positive concurrency"), - ) - .expect_err("zero margin must fail"); - - assert_eq!(error.kind(), ProviderStoreErrorKind::InvalidData); -} - -#[test] -fn refresh_policy_should_mark_tokens_due_at_the_exact_configured_margin() { - let policy = ProviderRefreshPolicy::try_new( - Duration::from_secs(3_600), - NonZeroU32::new(2).expect("positive concurrency"), - ) - .expect("valid policy"); - let observed_at = SystemTime::UNIX_EPOCH + Duration::from_secs(10_000); - let expires_at = observed_at + Duration::from_secs(7_200); - - assert!(!policy.is_refresh_due(expires_at, observed_at)); - assert!(policy.is_refresh_due(observed_at + Duration::from_secs(3_600), observed_at)); -} - -#[test] -fn refresh_policy_should_mark_expired_tokens_due() { - let policy = ProviderRefreshPolicy::try_new( - Duration::from_secs(3_600), - NonZeroU32::new(1).expect("positive concurrency"), - ) - .expect("valid policy"); - let observed_at = SystemTime::UNIX_EPOCH + Duration::from_secs(10_000); - - assert!(policy.is_refresh_due(observed_at - Duration::from_secs(1), observed_at)); -} - -#[test] -fn refresh_stagger_is_stable_and_bounded_by_the_margin() { - let policy = ProviderRefreshPolicy::try_new( - Duration::from_secs(300), - NonZeroU32::new(1).expect("positive concurrency"), - ) - .expect("valid policy"); - let account = ProviderAccountId::new("acct_stagger").expect("valid account"); - - let first = policy.refresh_stagger(&account); - for _ in 0..10 { - assert_eq!(policy.refresh_stagger(&account), first); - } - assert!(first <= policy.margin()); - // 偏移随 margin 缩放,不超出新窗口。 - let widened = ProviderRefreshPolicy::try_new( - Duration::from_secs(3_600), - NonZeroU32::new(1).expect("positive concurrency"), - ) - .expect("valid policy"); - assert!(widened.refresh_stagger(&account) <= widened.margin()); -} - -#[test] -fn refresh_stagger_should_spread_accounts_across_the_margin() { - let policy = ProviderRefreshPolicy::try_new( - Duration::from_secs(300), - NonZeroU32::new(1).expect("positive concurrency"), - ) - .expect("valid policy"); - let staggers = (0..64) - .map(|index| { - let account = - ProviderAccountId::new(format!("acct_spread_{index}")).expect("valid account"); - let stagger = policy.refresh_stagger(&account); - assert!(stagger <= policy.margin()); - stagger - }) - .collect::>(); - - // 确定性哈希下的分散性:64 个账号在 301 个可能取值中覆盖足够多的档位。 - let distinct = staggers.iter().collect::>().len(); - assert!( - distinct >= 24, - "stagger values are too concentrated: {staggers:?}" - ); -} - -#[test] -fn refresh_policy_staggered_due_boundaries() { - let policy = ProviderRefreshPolicy::try_new( - Duration::from_secs(300), - NonZeroU32::new(2).expect("positive concurrency"), - ) - .expect("valid policy"); - let observed_at = SystemTime::UNIX_EPOCH + Duration::from_secs(10_000); - - for index in 0..8 { - let account = - ProviderAccountId::new(format!("acct_boundary_{index}")).expect("valid account"); - // 恰好 margin:任何偏移下都到期;2×margin+1 秒:任何偏移下都未到期。 - assert!(policy.is_refresh_due_staggered( - &account, - observed_at + Duration::from_secs(300), - observed_at, - )); - assert!(!policy.is_refresh_due_staggered( - &account, - observed_at + Duration::from_secs(601), - observed_at, - )); - // 已过期账号不受偏移影响,恒到期。 - assert!(policy.is_refresh_due_staggered( - &account, - observed_at - Duration::from_secs(1), - observed_at, - )); - } -} - -#[test] -fn refresh_policy_staggered_due_matches_margin_plus_stagger() { - let policy = ProviderRefreshPolicy::try_new( - Duration::from_secs(300), - NonZeroU32::new(1).expect("positive concurrency"), - ) - .expect("valid policy"); - let observed_at = SystemTime::UNIX_EPOCH + Duration::from_secs(10_000); - - for index in 0..4 { - let account = - ProviderAccountId::new(format!("acct_compose_{index}")).expect("valid account"); - let staggered_margin = policy.margin() + policy.refresh_stagger(&account); - for remaining_secs in [299, 300, 301, 400, 450, 500, 599, 600, 601] { - assert_eq!( - policy.is_refresh_due_staggered( - &account, - observed_at + Duration::from_secs(remaining_secs), - observed_at, - ), - Duration::from_secs(remaining_secs) <= staggered_margin, - "remaining {remaining_secs}s" - ); - } - } -} - -#[test] -fn scheduling_state_preserves_provider_neutral_signals() { - let account = ProviderAccountId::new("acct_fixture").expect("valid account"); - let signals = BTreeMap::from([( - account.clone(), - AccountRuntimeSignals { - in_flight: 2, - last_started_at: None, - quota_reset_at: None, - quota_reset_windows: None, - quota_remaining_rank: Some(7), - cooldown: None, - failure_rate_basis_points: Some(125), - first_output_latency_ms: Some(250), - }, - )]); - let state = ProviderSchedulingState::new(signals, 9); - - assert_eq!(state.signals()[&account].in_flight, 2); - assert_eq!( - state.signals()[&account].failure_rate_basis_points, - Some(125) - ); - assert_eq!(state.round_robin_cursor(), 9); - assert_eq!( - CredentialRevision::new(1).expect("positive revision").get(), - 1 - ); -} - -#[test] -fn warmup_cron_validation_and_calendar_matching() { - use chrono::NaiveDate; - use gateway_core::provider_ports::{ProviderWarmupPolicy, valid_warmup_cron}; - - for value in [ - "0 8 * * *", - "*/15 8-18 * * MON-FRI", - "0 8,13 * * MON-FRI", - "0 0 29 FEB *", - ] { - assert!(valid_warmup_cron(value), "{value}"); - } - for value in [ - "", - "08:00", - "08:00,13:00", - "60 8 * * *", - "0 24 * * *", - "0 8 * *", - "0 0 8 * * *", - "0 8 * * * *", - "@daily", - "0 8 * * *\n30 13 * * *", - "0 8 * * *\r\n30 13 * * *", - "0 8 * * *\t", - " 0 8 * * *", - "0 8 * * *\n", - ] { - assert!(!valid_warmup_cron(value), "{value:?}"); - } - let policy = - ProviderWarmupPolicy::try_new(true, "0 8,13 * * MON-FRI", Some("test-model".to_owned())) - .unwrap(); - assert!(policy.enabled()); - assert_eq!(policy.model(), Some("test-model")); - for (day, hour, minute, expected) in [ - (9, 8, 0, true), - (9, 13, 0, true), - (9, 8, 30, false), - (9, 13, 30, false), - (14, 8, 0, false), - (14, 13, 30, false), - ] { - let slot = NaiveDate::from_ymd_opt(2026, 11, day) - .unwrap() - .and_hms_opt(hour, minute, 0) - .unwrap(); - assert_eq!(policy.matches_slot(slot), expected, "{slot}"); - } - assert!(ProviderWarmupPolicy::try_new(false, "", None).is_ok()); - assert!(ProviderWarmupPolicy::try_new(true, "", Some("test-model".to_owned())).is_err()); - assert!(ProviderWarmupPolicy::try_new(false, "08:00", None).is_err()); - assert!(!valid_warmup_cron(&format!("0{}8 * * *", " ".repeat(256)))); - let leap = ProviderWarmupPolicy::try_new(false, "0 0 29 FEB *", None).unwrap(); - let slot = NaiveDate::from_ymd_opt(2028, 2, 29) - .unwrap() - .and_hms_opt(0, 0, 0) - .unwrap(); - assert!(leap.matches_slot(slot)); - assert!(!leap.matches_slot(slot + chrono::Duration::days(1))); - assert!(ProviderWarmupPolicy::try_new(true, "invalid", None).is_err()); - assert!(ProviderWarmupPolicy::try_new(true, "0 8 * * *", None).is_err()); -} - -#[test] -fn warmup_matches_only_the_scheduled_hour_and_minute_pairs() { - use chrono::NaiveDate; - use gateway_core::provider_ports::ProviderWarmupPolicy; - - let policy = ProviderWarmupPolicy::try_new( - true, - "58 5 * * *;59 10 * * *;0 16 * * *;1 21 * * *;0 16 * * MON-FRI", - Some("test-model".to_owned()), - ) - .unwrap(); - let date = NaiveDate::from_ymd_opt(2026, 11, 13).unwrap(); - for minute in 0..1440 { - let slot = date.and_hms_opt(minute / 60, minute % 60, 0).unwrap(); - assert_eq!( - policy.matches_slot(slot), - [358, 659, 960, 1261].contains(&minute), - "{slot}" - ); - } -} diff --git a/backend/crates/gateway-core/tests/provider_ports/oauth.rs b/backend/crates/gateway-core/tests/provider_ports/oauth.rs new file mode 100644 index 000000000..392f404b8 --- /dev/null +++ b/backend/crates/gateway-core/tests/provider_ports/oauth.rs @@ -0,0 +1,30 @@ +//! 对应生产职责的行为测试 + +use super::*; + +#[test] +fn oauth_pending_binding_debug_redacts_raw_value() { + let binding = OAuthPendingBinding::try_new("must-not-appear").expect("valid binding"); + + assert_eq!(format!("{binding:?}"), "OAuthPendingBinding([REDACTED])"); +} + +#[test] +fn oauth_pending_ttl_rejects_zero_and_more_than_thirty_minutes() { + let provider = ProviderKind::new("fixture").expect("valid provider"); + let flow = OAuthPendingBinding::try_new("flow").expect("valid flow"); + let owner = OAuthPendingBinding::try_new("owner").expect("valid owner"); + let payload = OpaqueProviderData::new(serde_json::Map::new()); + + for ttl in [Duration::ZERO, Duration::from_secs(30 * 60 + 1)] { + let error = NewOAuthPendingFlow::try_new( + provider.clone(), + flow.clone(), + owner.clone(), + ttl, + payload.clone(), + ) + .expect_err("invalid TTL must fail"); + assert_eq!(error.kind(), ProviderStoreErrorKind::InvalidData); + } +} diff --git a/backend/crates/gateway-core/tests/provider_ports/refresh.rs b/backend/crates/gateway-core/tests/provider_ports/refresh.rs new file mode 100644 index 000000000..32ab41cc5 --- /dev/null +++ b/backend/crates/gateway-core/tests/provider_ports/refresh.rs @@ -0,0 +1,147 @@ +//! 对应生产职责的行为测试 + +use super::*; + +#[test] +fn refresh_policy_requires_a_positive_margin() { + let error = ProviderRefreshPolicy::try_new( + Duration::ZERO, + NonZeroU32::new(1).expect("positive concurrency"), + ) + .expect_err("zero margin must fail"); + + assert_eq!(error.kind(), ProviderStoreErrorKind::InvalidData); +} + +#[test] +fn refresh_policy_should_mark_tokens_due_at_the_exact_configured_margin() { + let policy = ProviderRefreshPolicy::try_new( + Duration::from_secs(3_600), + NonZeroU32::new(2).expect("positive concurrency"), + ) + .expect("valid policy"); + let observed_at = SystemTime::UNIX_EPOCH + Duration::from_secs(10_000); + let expires_at = observed_at + Duration::from_secs(7_200); + + assert!(!policy.is_refresh_due(expires_at, observed_at)); + assert!(policy.is_refresh_due(observed_at + Duration::from_secs(3_600), observed_at)); +} + +#[test] +fn refresh_policy_should_mark_expired_tokens_due() { + let policy = ProviderRefreshPolicy::try_new( + Duration::from_secs(3_600), + NonZeroU32::new(1).expect("positive concurrency"), + ) + .expect("valid policy"); + let observed_at = SystemTime::UNIX_EPOCH + Duration::from_secs(10_000); + + assert!(policy.is_refresh_due(observed_at - Duration::from_secs(1), observed_at)); +} + +#[test] +fn refresh_stagger_is_stable_and_bounded_by_the_margin() { + let policy = ProviderRefreshPolicy::try_new( + Duration::from_secs(300), + NonZeroU32::new(1).expect("positive concurrency"), + ) + .expect("valid policy"); + let account = ProviderAccountId::new("acct_stagger").expect("valid account"); + + let first = policy.refresh_stagger(&account); + for _ in 0..10 { + assert_eq!(policy.refresh_stagger(&account), first); + } + assert!(first <= policy.margin()); + // 偏移随 margin 缩放,不超出新窗口。 + let widened = ProviderRefreshPolicy::try_new( + Duration::from_secs(3_600), + NonZeroU32::new(1).expect("positive concurrency"), + ) + .expect("valid policy"); + assert!(widened.refresh_stagger(&account) <= widened.margin()); +} + +#[test] +fn refresh_stagger_should_spread_accounts_across_the_margin() { + let policy = ProviderRefreshPolicy::try_new( + Duration::from_secs(300), + NonZeroU32::new(1).expect("positive concurrency"), + ) + .expect("valid policy"); + let staggers = (0..64) + .map(|index| { + let account = + ProviderAccountId::new(format!("acct_spread_{index}")).expect("valid account"); + let stagger = policy.refresh_stagger(&account); + assert!(stagger <= policy.margin()); + stagger + }) + .collect::>(); + + // 确定性哈希下的分散性:64 个账号在 301 个可能取值中覆盖足够多的档位。 + let distinct = staggers.iter().collect::>().len(); + assert!( + distinct >= 24, + "stagger values are too concentrated: {staggers:?}" + ); +} + +#[test] +fn refresh_policy_staggered_due_boundaries() { + let policy = ProviderRefreshPolicy::try_new( + Duration::from_secs(300), + NonZeroU32::new(2).expect("positive concurrency"), + ) + .expect("valid policy"); + let observed_at = SystemTime::UNIX_EPOCH + Duration::from_secs(10_000); + + for index in 0..8 { + let account = + ProviderAccountId::new(format!("acct_boundary_{index}")).expect("valid account"); + // 恰好 margin:任何偏移下都到期;2×margin+1 秒:任何偏移下都未到期。 + assert!(policy.is_refresh_due_staggered( + &account, + observed_at + Duration::from_secs(300), + observed_at, + )); + assert!(!policy.is_refresh_due_staggered( + &account, + observed_at + Duration::from_secs(601), + observed_at, + )); + // 已过期账号不受偏移影响,恒到期。 + assert!(policy.is_refresh_due_staggered( + &account, + observed_at - Duration::from_secs(1), + observed_at, + )); + } +} + +#[test] +fn refresh_policy_staggered_due_matches_margin_plus_stagger() { + let policy = ProviderRefreshPolicy::try_new( + Duration::from_secs(300), + NonZeroU32::new(1).expect("positive concurrency"), + ) + .expect("valid policy"); + let observed_at = SystemTime::UNIX_EPOCH + Duration::from_secs(10_000); + + for index in 0..4 { + let account = + ProviderAccountId::new(format!("acct_compose_{index}")).expect("valid account"); + let staggered_margin = policy.margin() + policy.refresh_stagger(&account); + for remaining_secs in [299, 300, 301, 400, 450, 500, 599, 600, 601] { + assert_eq!( + policy.is_refresh_due_staggered( + &account, + observed_at + Duration::from_secs(remaining_secs), + observed_at, + ), + Duration::from_secs(remaining_secs) <= staggered_margin, + "remaining {remaining_secs}s" + ); + } + } +} diff --git a/backend/crates/gateway-core/tests/provider_ports/runtime_policy.rs b/backend/crates/gateway-core/tests/provider_ports/runtime_policy.rs new file mode 100644 index 000000000..111bad29a --- /dev/null +++ b/backend/crates/gateway-core/tests/provider_ports/runtime_policy.rs @@ -0,0 +1,88 @@ +//! 对应生产职责的行为测试 + +#[test] +fn warmup_cron_validation_and_calendar_matching() { + use chrono::NaiveDate; + use gateway_core::provider_ports::{ProviderWarmupPolicy, valid_warmup_cron}; + + for value in [ + "0 8 * * *", + "*/15 8-18 * * MON-FRI", + "0 8,13 * * MON-FRI", + "0 0 29 FEB *", + ] { + assert!(valid_warmup_cron(value), "{value}"); + } + for value in [ + "", + "08:00", + "08:00,13:00", + "60 8 * * *", + "0 24 * * *", + "0 8 * *", + "0 0 8 * * *", + "0 8 * * * *", + "@daily", + "0 8 * * *\n30 13 * * *", + "0 8 * * *\r\n30 13 * * *", + "0 8 * * *\t", + " 0 8 * * *", + "0 8 * * *\n", + ] { + assert!(!valid_warmup_cron(value), "{value:?}"); + } + let policy = + ProviderWarmupPolicy::try_new(true, "0 8,13 * * MON-FRI", Some("test-model".to_owned())) + .unwrap(); + assert!(policy.enabled()); + assert_eq!(policy.model(), Some("test-model")); + for (day, hour, minute, expected) in [ + (9, 8, 0, true), + (9, 13, 0, true), + (9, 8, 30, false), + (9, 13, 30, false), + (14, 8, 0, false), + (14, 13, 30, false), + ] { + let slot = NaiveDate::from_ymd_opt(2026, 11, day) + .unwrap() + .and_hms_opt(hour, minute, 0) + .unwrap(); + assert_eq!(policy.matches_slot(slot), expected, "{slot}"); + } + assert!(ProviderWarmupPolicy::try_new(false, "", None).is_ok()); + assert!(ProviderWarmupPolicy::try_new(true, "", Some("test-model".to_owned())).is_err()); + assert!(ProviderWarmupPolicy::try_new(false, "08:00", None).is_err()); + assert!(!valid_warmup_cron(&format!("0{}8 * * *", " ".repeat(256)))); + let leap = ProviderWarmupPolicy::try_new(false, "0 0 29 FEB *", None).unwrap(); + let slot = NaiveDate::from_ymd_opt(2028, 2, 29) + .unwrap() + .and_hms_opt(0, 0, 0) + .unwrap(); + assert!(leap.matches_slot(slot)); + assert!(!leap.matches_slot(slot + chrono::Duration::days(1))); + assert!(ProviderWarmupPolicy::try_new(true, "invalid", None).is_err()); + assert!(ProviderWarmupPolicy::try_new(true, "0 8 * * *", None).is_err()); +} + +#[test] +fn warmup_matches_only_the_scheduled_hour_and_minute_pairs() { + use chrono::NaiveDate; + use gateway_core::provider_ports::ProviderWarmupPolicy; + + let policy = ProviderWarmupPolicy::try_new( + true, + "58 5 * * *;59 10 * * *;0 16 * * *;1 21 * * *;0 16 * * MON-FRI", + Some("test-model".to_owned()), + ) + .unwrap(); + let date = NaiveDate::from_ymd_opt(2026, 11, 13).unwrap(); + for minute in 0..1440 { + let slot = date.and_hms_opt(minute / 60, minute % 60, 0).unwrap(); + assert_eq!( + policy.matches_slot(slot), + [358, 659, 960, 1261].contains(&minute), + "{slot}" + ); + } +} diff --git a/backend/crates/gateway-core/tests/provider_ports/session_affinity.rs b/backend/crates/gateway-core/tests/provider_ports/session_affinity.rs new file mode 100644 index 000000000..8703c3d30 --- /dev/null +++ b/backend/crates/gateway-core/tests/provider_ports/session_affinity.rs @@ -0,0 +1,159 @@ +//! 通用亲和策略只影响选号和绑定,不覆盖资格或固定续接账号 + +use gateway_core::{ + account::{ + AccountAffinity, AccountCandidate, AccountEligibilityPolicy, AccountRuntimeSignals, + AccountSelectionContext, AccountSelectionPolicy, AccountSelector, CredentialRevision, + CredentialState, ProviderAccount, ProviderAccountId, QuotaState, RotationStrategy, + }, + provider_ports::{ + ProviderSessionAffinityKey, ProviderSessionAffinityState, ProviderSessionBinding, + }, + routing::ProviderKind, +}; +use std::{ + num::NonZeroU32, + time::{Duration, SystemTime}, +}; + +fn candidate(id: &str, busy: bool) -> AccountCandidate { + AccountCandidate { + account: ProviderAccount::new( + ProviderAccountId::new(id).unwrap(), + ProviderKind::new("antigravity").unwrap(), + id.into(), + None, + "oauth".into(), + CredentialRevision::new(1).unwrap(), + None, + ) + .with_account_facts( + true, + CredentialState::Ready, + QuotaState::unknown(), + None, + None, + ), + inherited_concurrency: None, + signals: AccountRuntimeSignals { + in_flight: u32::from(busy), + last_started_at: None, + quota_reset_at: None, + quota_reset_windows: None, + quota_remaining_rank: None, + cooldown: None, + failure_rate_basis_points: None, + first_output_latency_ms: None, + }, + } +} + +fn context(mode: AccountAffinity) -> AccountSelectionContext { + AccountSelectionContext { + policy: AccountSelectionPolicy::new(RotationStrategy::RoundRobin, NonZeroU32::MIN) + .with_account_affinity(mode) + .with_session_affinity_ttl(Duration::from_secs(7200)), + now: SystemTime::now(), + excluded_accounts: Default::default(), + busy_accounts: Default::default(), + preferred_account: None, + preferred_account_overrides_weight: false, + round_robin_cursor: 0, + eligibility: AccountEligibilityPolicy::Enforce, + account_scope: None, + reserved_concurrency: 0, + } +} + +fn binding() -> ProviderSessionBinding { + ProviderSessionBinding::new( + ProviderAccountId::new("acct_primary").unwrap(), + "a".repeat(32), + ) + .unwrap() +} + +#[test] +fn strict_waits_only_while_primary_remains_eligible_and_queuing_is_enabled() { + let key = ProviderSessionAffinityKey::try_new("session").unwrap(); + let mut context = context(AccountAffinity::Strict); + let state = ProviderSessionAffinityState::new(&key, Some(binding()), context.policy); + let candidates = [ + candidate("acct_primary", true), + candidate("acct_backup", false), + ]; + state.apply_preference(&mut context); + assert_eq!( + state.wait_account(&candidates, &context, true), + state.bound_account() + ); + assert!(state.wait_account(&candidates, &context, false).is_none()); + context + .excluded_accounts + .insert(ProviderAccountId::new("acct_primary").unwrap()); + assert!(state.wait_account(&candidates, &context, true).is_none()); +} + +#[test] +fn preferred_spillover_renews_primary_but_ineligible_binding_can_migrate() { + let key = ProviderSessionAffinityKey::try_new("session").unwrap(); + let mut context = context(AccountAffinity::Preferred); + let state = ProviderSessionAffinityState::new(&key, Some(binding()), context.policy); + let candidates = [ + candidate("acct_primary", true), + candidate("acct_backup", false), + ]; + state.apply_preference(&mut context); + let selected = AccountSelector + .select(&candidates, &context) + .unwrap() + .candidate() + .account + .id(); + let claim = state.claim( + selected, + state.binding_eligible(&candidates, &context), + false, + ); + assert_eq!(claim.account, state.bound_account().unwrap()); + assert_eq!(claim.ttl, Duration::from_secs(7200)); + context + .excluded_accounts + .insert(ProviderAccountId::new("acct_primary").unwrap()); + assert_eq!( + state + .claim( + selected, + state.binding_eligible(&candidates, &context), + false + ) + .account, + selected + ); +} + +#[test] +fn relaxed_does_not_prefer_primary_and_admits_the_scheduled_account() { + let key = ProviderSessionAffinityKey::try_new("session").unwrap(); + let mut context = context(AccountAffinity::Relaxed); + let state = ProviderSessionAffinityState::new(&key, Some(binding()), context.policy); + state.apply_preference(&mut context); + assert!(context.preferred_account.is_none()); + let selected = ProviderAccountId::new("acct_backup").unwrap(); + assert_eq!(state.claim(&selected, true, false).account, &selected); +} + +#[test] +fn native_pinned_account_keeps_its_preference_and_does_not_replace_primary() { + let key = ProviderSessionAffinityKey::try_new("session").unwrap(); + let mut context = context(AccountAffinity::Strict); + let state = ProviderSessionAffinityState::new(&key, Some(binding()), context.policy); + let pinned = ProviderAccountId::new("acct_native_owner").unwrap(); + context.preferred_account = Some(pinned.clone()); + state.apply_preference(&mut context); + assert_eq!(context.preferred_account.as_ref(), Some(&pinned)); + assert_eq!( + state.claim(&pinned, false, true).account, + state.bound_account().unwrap() + ); +} diff --git a/backend/crates/gateway-core/tests/routing/mod.rs b/backend/crates/gateway-core/tests/routing/mod.rs index 54d4a0e21..274c3b5d4 100644 --- a/backend/crates/gateway-core/tests/routing/mod.rs +++ b/backend/crates/gateway-core/tests/routing/mod.rs @@ -899,3 +899,143 @@ fn account_model_access_filters_catalog_and_aliases_using_the_whole_frozen_pool( "a new policy must not alter an existing request scope" ); } + +#[test] +fn generation_routes_only_to_models_that_accept_the_wire_and_the_key() { + for translated in [false, true] { + let provider = |name| ProviderKind::new(name).unwrap(); + let snapshot = RuntimeSnapshot::new( + ConfigRevision::new(1).unwrap(), + settings(), + vec![provider("openai"), provider("xai")], + vec![ + model("openai", "shared", capabilities()), + model( + "xai", + "shared", + capabilities() + .with_generation_protocol("native-test") + .with_translated_generation_protocols(if translated { + vec!["openai"] + } else { + Vec::new() + }), + ), + ], + vec![], + ) + .unwrap() + .with_account_directory(account_directory()); + let public = PublicModelId::new("shared").unwrap(); + let native = Operation::Generate( + GenerateRequest::from_protocol_payload( + ProtocolPayload::json_object("native-test", Default::default()).unwrap(), + ) + .requiring_native_protocol(), + ); + for (request, expected) in [ + ( + operation(), + if translated { + vec!["openai", "xai"] + } else { + vec!["openai"] + }, + ), + (native.clone(), vec!["xai"]), + ] { + let plan = snapshot + .plan( + &public, + &request, + account_scope(), + &RoutingContext::default(), + ) + .unwrap(); + let actual: Vec<_> = plan + .candidates() + .iter() + .map(|c| c.provider().as_str()) + .collect(); + assert_eq!(actual, expected); + } + let restricted = Arc::new( + account_scope().restricted_to(&[provider("openai")].into(), &Default::default()), + ); + assert!( + snapshot + .plan(&public, &native, restricted, &RoutingContext::default()) + .is_err() + ); + assert!( + snapshot + .plan( + &PublicModelId::new("unknown").unwrap(), + &native, + account_scope(), + &RoutingContext::default() + ) + .is_err() + ); + } +} + +#[test] +fn native_count_catalog_and_execution_do_not_fall_back_to_another_protocol() { + let caps = ModelCapabilities::new( + BTreeSet::from([OperationKind::Generate, OperationKind::CountTokens]), + None, + ); + let snapshot = RuntimeSnapshot::new( + ConfigRevision::new(1).unwrap(), + settings(), + vec![ + ProviderKind::new("openai").unwrap(), + ProviderKind::new("xai").unwrap(), + ], + vec![ + model("openai", "shared", caps.clone()), + model("xai", "shared", caps.with_generation_protocol("genai")), + ], + vec![], + ) + .unwrap() + .with_account_directory(account_directory()); + let original = Operation::CountTokens( + TokenCountRequest::from_raw_json( + RawJsonPayload::new("genai", Bytes::from_static(b"{}")).unwrap(), + ) + .requiring_native_protocol(), + ); + let operation = original + .replace_protocol_wire( + Some(Bytes::from_static(b"{\"contents\":[]}")), + Default::default(), + ) + .unwrap(); + assert!(matches!(&operation,Operation::CountTokens(count) if count.requires_native_protocol())); + let public = PublicModelId::new("shared").unwrap(); + let plan = snapshot + .plan( + &public, + &operation, + account_scope(), + &RoutingContext::default(), + ) + .unwrap(); + assert_eq!(plan.candidates().len(), 1); + assert_eq!(plan.candidates()[0].provider().as_str(), "xai"); + assert_eq!( + snapshot.public_models_for_operation(&account_scope(), &operation), + vec![public] + ); + let restricted = Arc::new(account_scope().restricted_to( + &[ProviderKind::new("openai").unwrap()].into(), + &Default::default(), + )); + assert!( + snapshot + .public_models_for_operation(&restricted, &operation) + .is_empty() + ); +} diff --git a/backend/crates/gateway-core/tests/routing/request_settings.rs b/backend/crates/gateway-core/tests/routing/request_settings.rs index 1e3750775..98a7df85d 100644 --- a/backend/crates/gateway-core/tests/routing/request_settings.rs +++ b/backend/crates/gateway-core/tests/routing/request_settings.rs @@ -236,7 +236,7 @@ fn affinity_and_rotation_settings_are_validated_without_mutating_the_snapshot() use gateway_core::account::AccountAffinity; let original = snapshot(1, "host"); let facts = serde_json::to_value(original.settings()).unwrap(); - assert_eq!(facts["openai_account_affinity"], "strict"); + assert_eq!(facts["account_affinity"], "strict"); assert_eq!(facts["max_account_rotations"], 3); for (mode, rotations) in [ (AccountAffinity::Relaxed, 0), @@ -248,13 +248,13 @@ fn affinity_and_rotation_settings_are_validated_without_mutating_the_snapshot() &original .settings() .clone() - .with_openai_account_affinity(mode) + .with_account_affinity(mode) .with_max_account_rotations(rotations), ) .unwrap(); let changed = serde_json::to_value(changed.settings()).unwrap(); assert_eq!(changed["max_account_rotations"], rotations); - assert_eq!(changed["openai_account_affinity"], mode.as_str()); + assert_eq!(changed["account_affinity"], mode.as_str()); } assert!( original @@ -268,7 +268,7 @@ fn affinity_and_rotation_settings_are_validated_without_mutating_the_snapshot() fn session_affinity_ttl_rejects_unbounded_or_empty_retention() { let original = snapshot(1, "host"); assert_eq!( - serde_json::to_value(original.settings()).unwrap()["openai_session_affinity_ttl_hours"], + serde_json::to_value(original.settings()).unwrap()["session_affinity_ttl_hours"], 24 ); for hours in [1, 168, 720] { @@ -278,7 +278,7 @@ fn session_affinity_ttl_rejects_unbounded_or_empty_retention() { &original .settings() .clone() - .with_openai_session_affinity_ttl_hours(hours) + .with_session_affinity_ttl_hours(hours) ) .is_ok() ); @@ -290,7 +290,7 @@ fn session_affinity_ttl_rejects_unbounded_or_empty_retention() { &original .settings() .clone() - .with_openai_session_affinity_ttl_hours(hours) + .with_session_affinity_ttl_hours(hours) ) .is_err() ); diff --git a/backend/crates/gateway-host/src/pricing.rs b/backend/crates/gateway-host/src/pricing.rs index a846ac778..53a67dead 100644 --- a/backend/crates/gateway-host/src/pricing.rs +++ b/backend/crates/gateway-host/src/pricing.rs @@ -3,7 +3,7 @@ use async_trait::async_trait; use gateway_admin::{ model::{AdminError, pricing::PricingSyncPreview}, - ports::pricing::PricingSource, + ports::pricing::{PricingSource, PricingSourceScope}, }; use gateway_core::metering::{ModelPriceOverride, TokenPrice, TokenPriceOverride}; use serde_json::Value; @@ -16,7 +16,7 @@ pub struct ModelsDevPricing; #[async_trait] impl PricingSource for ModelsDevPricing { - async fn fetch(&self) -> Result { + async fn fetch(&self, scope: &PricingSourceScope) -> Result { let client = gateway_egress::http_client(None) .map_err(|_| source_error())? .https_only(true) @@ -39,7 +39,7 @@ impl PricingSource for ModelsDevPricing { } body.extend_from_slice(&chunk); } - decode_catalog(&body) + decode_catalog(&body, scope) } } @@ -47,19 +47,27 @@ fn source_error() -> AdminError { AdminError::bad_gateway("无法读取 models.dev 价目,现有价格不变") } -/// 只接受当前网关 Provider 的文本 Token 价格;不猜测缺失字段或模态换算 -pub fn decode_catalog(body: &[u8]) -> Result { +/// 读取文本参考价;外部模型如何对应网关模型由 Provider 登记 +pub fn decode_catalog( + body: &[u8], + scope: &PricingSourceScope, +) -> Result { let catalog: Value = serde_json::from_slice(body).map_err(|_| source_error())?; let mut result = PricingSyncPreview { prices: BTreeMap::new(), skipped: Vec::new(), }; - for provider in ["openai", "xai"] { - let models = catalog + for provider in scope.vendors() { + let Some(models) = catalog .get(provider) .and_then(|p| p.get("models")) .and_then(Value::as_object) - .ok_or_else(source_error)?; + else { + if scope.requires_catalog(provider) { + return Err(source_error()); + } + continue; + }; let mut prices = BTreeMap::new(); for (model, value) in models { if model.is_empty() @@ -91,13 +99,18 @@ fn model_price(provider: &str, model: &Value) -> Option { return None; } let cost = model.get("cost")?; - // 独立 reasoning/audio 价格无法用当前 Token 用量拆分,不能静默吞掉 + // Google 参考价只含文本单价,消费方须跳过无法据此拆分计费的音频请求 if ["reasoning", "input_audio", "output_audio"] .iter() - .any(|key| cost.get(key).is_some()) + .any(|key| cost.get(key).is_some() && !(provider == "google" && *key == "input_audio")) { return None; } + let long_context_threshold = if provider == "openai" { + 272_000 + } else { + 200_000 + }; let mut bands = BTreeMap::from([("standard".to_owned(), rates(cost)?)]); if let Some(tiers) = cost.get("tiers") { let tiers = tiers.as_array()?; @@ -105,14 +118,13 @@ fn model_price(provider: &str, model: &Value) -> Option { return None; } if let Some(tier) = tiers.first() { - let expected = if provider == "xai" { 200_000 } else { 272_000 }; - if tier.pointer("/tier/size")?.as_u64()? != expected { + if tier.pointer("/tier/size")?.as_u64()? != long_context_threshold { return None; } bands.insert("long_standard".to_owned(), rates(tier)?); } } else if let Some(long) = cost.get("context_over_200k") { - if provider != "xai" { + if long_context_threshold != 200_000 { return None; } bands.insert("long_standard".to_owned(), rates(long)?); diff --git a/backend/crates/gateway-host/src/system_update/mod.rs b/backend/crates/gateway-host/src/system_update/mod.rs index d34b4f0f1..1899ebca3 100644 --- a/backend/crates/gateway-host/src/system_update/mod.rs +++ b/backend/crates/gateway-host/src/system_update/mod.rs @@ -14,7 +14,6 @@ mod process; mod release; mod state; mod swap; -mod swap_paths; pub use config::SystemUpdateConfig; pub use operations::ProcessSystemOperations; diff --git a/backend/crates/gateway-host/src/system_update/swap/mod.rs b/backend/crates/gateway-host/src/system_update/swap/mod.rs new file mode 100644 index 000000000..c4cc2ea57 --- /dev/null +++ b/backend/crates/gateway-host/src/system_update/swap/mod.rs @@ -0,0 +1,9 @@ +//! 发行物交换与失败补偿的模块门面 + +mod paths; +mod release; + +pub(crate) use release::{ + backup_path_for, remove_dir_all, replace_release_files, rollback_official_plugins_dir, + rollback_release, +}; diff --git a/backend/crates/gateway-host/src/system_update/swap_paths.rs b/backend/crates/gateway-host/src/system_update/swap/paths.rs similarity index 100% rename from backend/crates/gateway-host/src/system_update/swap_paths.rs rename to backend/crates/gateway-host/src/system_update/swap/paths.rs diff --git a/backend/crates/gateway-host/src/system_update/swap.rs b/backend/crates/gateway-host/src/system_update/swap/release.rs similarity index 98% rename from backend/crates/gateway-host/src/system_update/swap.rs rename to backend/crates/gateway-host/src/system_update/swap/release.rs index f73e80632..70610bd3a 100644 --- a/backend/crates/gateway-host/src/system_update/swap.rs +++ b/backend/crates/gateway-host/src/system_update/swap/release.rs @@ -7,8 +7,8 @@ use std::path::{Path, PathBuf}; use gateway_core::error::ErrorSource; -use super::archive::ExtractedRelease; -use super::{OperationError, SystemUpdateConfig, conflict, internal}; +use super::super::archive::ExtractedRelease; +use super::super::{OperationError, SystemUpdateConfig, conflict, internal}; pub(crate) fn replace_release_files( executable: &Path, @@ -224,7 +224,7 @@ fn swap_file(current: &Path, backup: &Path) -> io::Result<()> { if swap.exists() { fs::remove_file(&swap)?; } - super::swap_paths::swap_paths(current, backup, &swap, move_file) + super::paths::swap_paths(current, backup, &swap, move_file) } fn swap_dir(current: &Path, backup: &Path) -> io::Result<()> { @@ -238,7 +238,7 @@ fn swap_dir(current: &Path, backup: &Path) -> io::Result<()> { if swap.exists() { remove_dir_all(&swap)?; } - super::swap_paths::swap_paths(current, backup, &swap, move_dir) + super::paths::swap_paths(current, backup, &swap, move_dir) } fn restore_dir(current: &Path, backup: &Path) -> io::Result<()> { diff --git a/backend/crates/gateway-host/tests/pricing.rs b/backend/crates/gateway-host/tests/pricing.rs index a9ec945e7..850203f73 100644 --- a/backend/crates/gateway-host/tests/pricing.rs +++ b/backend/crates/gateway-host/tests/pricing.rs @@ -1,8 +1,46 @@ //! 验证外部价格源的 Provider 选择、免费价格与无效文档拒绝 -use gateway_host::pricing::decode_catalog; +use gateway_admin::ports::pricing::{PricingCatalogSource, PricingSourceModel, PricingSourceScope}; +use gateway_host::pricing; use serde_json::json; +fn decode_catalog( + body: &[u8], +) -> Result { + pricing::decode_catalog( + body, + &scope( + &["openai", "xai"], + &["google", "google-vertex", "anthropic"], + ), + ) +} + +fn scope(direct: &[&str], references: &[&str]) -> PricingSourceScope { + let mut sources: std::collections::BTreeMap<_, _> = direct + .iter() + .map(|vendor| (vendor.to_string(), PricingCatalogSource::Direct)) + .collect(); + sources.insert( + "mapped-provider".into(), + PricingCatalogSource::References( + references + .iter() + .map(|vendor| { + ( + vendor.to_string(), + PricingSourceModel { + provider: vendor.to_string(), + model: "example".into(), + }, + ) + }) + .collect(), + ), + ); + PricingSourceScope { catalogs: sources } +} + #[test] fn source_selects_supported_providers_and_preserves_free_prices() { let catalog = json!({ @@ -41,3 +79,55 @@ fn source_rejects_empty_partial_or_malformed_documents() { } assert!(decode_catalog(b"not json").is_err()); } + +#[test] +fn source_exposes_google_anthropic_and_vertex_reference_prices_with_supported_context_tiers() { + let source = json!({ + "openai":{"models":{}}, "xai":{"models":{}}, + "google":{"models":{ + "flash":{"modalities":{"output":["text"]},"cost":{"input":0.3,"output":2.5,"input_audio":1}}, + "pro":{"modalities":{"output":["text"]},"cost":{"input":1.25,"output":10,"tiers":[{"tier":{"type":"context","size":200000},"input":2.5,"output":15}]}}, + "image":{"modalities":{"output":["text","image"]},"cost":{"input":0.5,"output":3}} + }}, + "anthropic":{"models":{"sonnet":{"modalities":{"output":["text"]},"cost":{"input":2,"output":10,"cache_write":2.5,"cache_read":0.1}}}}, + "google-vertex":{"models":{"openai/gpt-oss-120b-maas":{"modalities":{"output":["text"]},"cost":{"input":0.09,"output":0.36}}}} + }); + let result = decode_catalog(&serde_json::to_vec(&source).unwrap()).unwrap(); + assert_eq!( + result.prices["google"]["flash"].bands["standard"] + .input + .ticks_per_token(), + 3000 + ); + assert_eq!( + result.prices["google"]["pro"].bands["long_standard"] + .output + .ticks_per_token(), + 150000 + ); + assert_eq!( + result.prices["anthropic"]["sonnet"].bands["standard"] + .cache_write + .ticks_per_token(), + 25000 + ); + assert_eq!( + result.prices["google-vertex"]["openai/gpt-oss-120b-maas"].bands["standard"] + .output + .ticks_per_token(), + 3600 + ); + assert_eq!(result.skipped, ["google/image"]); +} + +#[test] +fn source_reads_the_registered_scope_without_a_host_allowlist() { + let price = json!({"modalities":{"output":["text"]},"cost":{"input":1,"output":2}}); + let source = serde_json::to_vec( + &json!({"custom-vendor":{"models":{"v1":price}}, "other":{"models":{"v1":price}}}), + ) + .unwrap(); + let scope = scope(&["custom-vendor"], &["missing-reference"]); + let preview = pricing::decode_catalog(&source, &scope).unwrap(); + assert_eq!(preview.prices.keys().collect::>(), ["custom-vendor"]); +} diff --git a/backend/crates/gateway-host/tests/system_update/mod.rs b/backend/crates/gateway-host/tests/system_update/mod.rs index f679a7296..ca8ab163a 100644 --- a/backend/crates/gateway-host/tests/system_update/mod.rs +++ b/backend/crates/gateway-host/tests/system_update/mod.rs @@ -8,7 +8,7 @@ mod installation; mod operations; mod release; mod state; -mod swap_paths; +mod swap; use std::fs; use std::path::PathBuf; diff --git a/backend/crates/gateway-host/tests/system_update/swap/mod.rs b/backend/crates/gateway-host/tests/system_update/swap/mod.rs new file mode 100644 index 000000000..d6c8f400d --- /dev/null +++ b/backend/crates/gateway-host/tests/system_update/swap/mod.rs @@ -0,0 +1,3 @@ +//! 发行物交换与补偿测试 + +mod paths; diff --git a/backend/crates/gateway-host/tests/system_update/swap_paths.rs b/backend/crates/gateway-host/tests/system_update/swap/paths.rs similarity index 98% rename from backend/crates/gateway-host/tests/system_update/swap_paths.rs rename to backend/crates/gateway-host/tests/system_update/swap/paths.rs index af8b81e3c..de270325c 100644 --- a/backend/crates/gateway-host/tests/system_update/swap_paths.rs +++ b/backend/crates/gateway-host/tests/system_update/swap/paths.rs @@ -1,6 +1,6 @@ //! 对真实暂存文件注入移动双故障,验证恢复次序和人工恢复线索 -#[path = "../../src/system_update/swap_paths.rs"] +#[path = "../../../src/system_update/swap/paths.rs"] mod implementation; use std::{fs, io}; diff --git a/backend/crates/gateway-plugin/runtime/src/adapter/middleware/http.rs b/backend/crates/gateway-plugin/runtime/src/adapter/middleware/http.rs index fa5a0aa13..9eefa581f 100644 --- a/backend/crates/gateway-plugin/runtime/src/adapter/middleware/http.rs +++ b/backend/crates/gateway-plugin/runtime/src/adapter/middleware/http.rs @@ -13,7 +13,7 @@ use http_body::Frame; use http_body_util::{BodyExt as _, StreamBody}; use super::MiddlewareEntry; -use crate::callback::http_middleware::{Invocation, headers}; +use crate::callback::http::middleware::{Invocation, headers}; pub(super) async fn invoke( entry: Arc, diff --git a/backend/crates/gateway-plugin/runtime/src/adapter/upstream_adapter/mod.rs b/backend/crates/gateway-plugin/runtime/src/adapter/upstream_adapter/mod.rs index 61fadf460..891c3dc03 100644 --- a/backend/crates/gateway-plugin/runtime/src/adapter/upstream_adapter/mod.rs +++ b/backend/crates/gateway-plugin/runtime/src/adapter/upstream_adapter/mod.rs @@ -5,7 +5,6 @@ mod execution; mod failure; mod observation; mod registration; -pub(crate) mod target; use std::{fmt, sync::Arc}; @@ -22,7 +21,7 @@ use gateway_core::{ use gateway_plugin_sdk::call::upstream_adapter::UpstreamAdapterDeclaration; use super::scope::BindingScope; -use crate::{RpcSession, callback::PluginCallbacks}; +use crate::{RpcSession, callback::PluginCallbacks, upstream_target::UpstreamTarget}; pub(crate) use registration::{prepare, unavailable_entries, validate_bindings}; @@ -55,7 +54,7 @@ pub(crate) struct PluginUpstreamAdapter { instance_id: String, contribution_id: String, declaration: UpstreamAdapterDeclaration, - target: Arc, + target: Arc, session: Arc, callbacks: Arc, connections: Arc, diff --git a/backend/crates/gateway-plugin/runtime/src/adapter/upstream_adapter/registration.rs b/backend/crates/gateway-plugin/runtime/src/adapter/upstream_adapter/registration.rs index 0e93b0141..004a38f0f 100644 --- a/backend/crates/gateway-plugin/runtime/src/adapter/upstream_adapter/registration.rs +++ b/backend/crates/gateway-plugin/runtime/src/adapter/upstream_adapter/registration.rs @@ -11,8 +11,11 @@ use gateway_plugin_sdk::{ call::upstream_adapter::{REGISTER_METHOD, UpstreamAdapterRegistration}, }; -use super::{AdapterEntry, PluginUpstreamAdapter, target::UpstreamTarget}; -use crate::{RpcSession, adapter::scope::BindingScope, callback::PluginCallbacks}; +use super::{AdapterEntry, PluginUpstreamAdapter}; +use crate::{ + RpcSession, adapter::scope::BindingScope, callback::PluginCallbacks, + upstream_target::UpstreamTarget, +}; pub(crate) fn validate_bindings( manifest: &Manifest, diff --git a/backend/crates/gateway-plugin/runtime/src/callback/call_resources.rs b/backend/crates/gateway-plugin/runtime/src/callback/call_resources.rs index 745f7074b..8c618e9c8 100644 --- a/backend/crates/gateway-plugin/runtime/src/callback/call_resources.rs +++ b/backend/crates/gateway-plugin/runtime/src/callback/call_resources.rs @@ -1,6 +1,6 @@ //! 单次宿主回调的资源状态、流式预算与统一终结 -use super::{CallbackScope, MiddlewareCallback, denied, http_middleware, model}; +use super::{CallbackScope, MiddlewareCallback, denied, http::middleware, model}; use gateway_core::lifecycle::CancellationToken; use gateway_host::outbound::HttpBody; use gateway_plugin_sdk::{CallContext, ErrorCode, PluginFault, client::CallDeadline}; @@ -15,7 +15,7 @@ pub(super) struct CallResources { operation_timeout: Duration, pub(super) cancellation: CancellationToken, pub(super) scope: Arc, - pub(super) http_resources: Arc, + pub(super) http_resources: Arc, pub(super) client_identities: tokio::sync::Mutex>, pub(super) state: Mutex, diff --git a/backend/crates/gateway-plugin/runtime/src/callback/dispatch.rs b/backend/crates/gateway-plugin/runtime/src/callback/dispatch.rs index 6b53c1948..b4874c0ab 100644 --- a/backend/crates/gateway-plugin/runtime/src/callback/dispatch.rs +++ b/backend/crates/gateway-plugin/runtime/src/callback/dispatch.rs @@ -9,7 +9,7 @@ use gateway_plugin_sdk::{ client::CallDeadline, }; -use super::{CallResources, CallbackScope, PluginCallbacks, denied, http, http_dispatch, upstream}; +use super::{CallResources, CallbackScope, PluginCallbacks, denied, http, upstream}; use crate::{CallbackHandler, RpcReply}; impl CallbackHandler for PluginCallbacks { @@ -139,7 +139,7 @@ impl CallbackHandler for PluginCallbacks { return tokio::select! { biased; () = call.cancellation.cancelled() => Err(PluginFault::new(ErrorCode::Cancelled, "HTTP callback cancelled")), - result = http_dispatch::call(&services, &context, &call, &method, params, payload, maximum_payload) => result, + result = http::call(&services, &context, &call, &method, params, payload, maximum_payload) => result, }; } if let Some(middleware) = middleware { diff --git a/backend/crates/gateway-plugin/runtime/src/callback/http_dispatch.rs b/backend/crates/gateway-plugin/runtime/src/callback/http/dispatch.rs similarity index 86% rename from backend/crates/gateway-plugin/runtime/src/callback/http_dispatch.rs rename to backend/crates/gateway-plugin/runtime/src/callback/http/dispatch.rs index bfaa1d9f2..cd97af48e 100644 --- a/backend/crates/gateway-plugin/runtime/src/callback/http_dispatch.rs +++ b/backend/crates/gateway-plugin/runtime/src/callback/http/dispatch.rs @@ -1,10 +1,10 @@ //! 主动 HTTP 子调用只进入 API 分派端口,正文复用当前 RPC 的资源池 -use super::{CallResources, http_middleware, invalid, services::ServicePorts}; use crate::RpcReply; +use crate::callback::{CallResources, http::middleware, invalid, services::ServicePorts}; use gateway_core::engine::middleware::http as core; use gateway_plugin_sdk::{CallContext, PluginFault, call::middleware::http as wire}; -pub(super) async fn call( +pub(in crate::callback) async fn call( services: &ServicePorts, context: &CallContext, call: &CallResources, @@ -25,12 +25,12 @@ pub(super) async fn call( if uri.scheme().is_some() || uri.authority().is_some() || !uri.path().starts_with('/') { return Err(invalid()); } - let headers = http_middleware::headers(request.headers)?; + let headers = middleware::headers(request.headers)?; let dispatcher = services.http()?; let settings = call .request_settings() .or_else(|| dispatcher.request_settings()); - let settings = http_middleware::resolve_settings( + let settings = middleware::resolve_settings( settings, request.settings, request.timeout_ms, @@ -59,12 +59,12 @@ pub(super) async fn call( *http.method_mut() = method; *http.uri_mut() = uri; *http.headers_mut() = headers; - *http.version_mut() = http_middleware::version(request.version); + *http.version_mut() = middleware::version(request.version); http.extensions_mut().insert(settings); call.observe_dispatch()?; let response = dispatcher .dispatch(child, http) .await - .map_err(|error| super::error::middleware(&error))?; + .map_err(|error| crate::callback::error::middleware(&error))?; call.http_resources.response(response) } diff --git a/backend/crates/gateway-plugin/runtime/src/callback/http_middleware/mod.rs b/backend/crates/gateway-plugin/runtime/src/callback/http/middleware/mod.rs similarity index 98% rename from backend/crates/gateway-plugin/runtime/src/callback/http_middleware/mod.rs rename to backend/crates/gateway-plugin/runtime/src/callback/http/middleware/mod.rs index e06fc05dd..12797b703 100644 --- a/backend/crates/gateway-plugin/runtime/src/callback/http_middleware/mod.rs +++ b/backend/crates/gateway-plugin/runtime/src/callback/http/middleware/mod.rs @@ -16,8 +16,8 @@ use gateway_plugin_sdk::{ }; use http::{HeaderMap, HeaderName, HeaderValue, Version}; -use super::MiddlewareCallback; use crate::RpcReply; +use crate::callback::MiddlewareCallback; pub(crate) struct Invocation { instance_id: String, @@ -136,7 +136,7 @@ impl Invocation { let response = next .run(core::Request::from_parts(parts, body)) .await - .map_err(|error| super::error::middleware(&error))?; + .map_err(|error| crate::callback::error::middleware(&error))?; self.resources.response(response) } diff --git a/backend/crates/gateway-plugin/runtime/src/callback/http_middleware/resources.rs b/backend/crates/gateway-plugin/runtime/src/callback/http/middleware/resources.rs similarity index 100% rename from backend/crates/gateway-plugin/runtime/src/callback/http_middleware/resources.rs rename to backend/crates/gateway-plugin/runtime/src/callback/http/middleware/resources.rs diff --git a/backend/crates/gateway-plugin/runtime/src/callback/http_middleware/websocket.rs b/backend/crates/gateway-plugin/runtime/src/callback/http/middleware/websocket.rs similarity index 100% rename from backend/crates/gateway-plugin/runtime/src/callback/http_middleware/websocket.rs rename to backend/crates/gateway-plugin/runtime/src/callback/http/middleware/websocket.rs diff --git a/backend/crates/gateway-plugin/runtime/src/callback/http/mod.rs b/backend/crates/gateway-plugin/runtime/src/callback/http/mod.rs new file mode 100644 index 000000000..f1068d552 --- /dev/null +++ b/backend/crates/gateway-plugin/runtime/src/callback/http/mod.rs @@ -0,0 +1,8 @@ +//! 插件 HTTP 出站、API 分派与中间件正文资源入口 + +mod dispatch; +pub(crate) mod middleware; +mod outbound; + +pub(super) use dispatch::call; +pub(super) use outbound::{HttpCallbacks, http_error}; diff --git a/backend/crates/gateway-plugin/runtime/src/callback/http.rs b/backend/crates/gateway-plugin/runtime/src/callback/http/outbound.rs similarity index 90% rename from backend/crates/gateway-plugin/runtime/src/callback/http.rs rename to backend/crates/gateway-plugin/runtime/src/callback/http/outbound.rs index dd2a4ebe7..f495d6142 100644 --- a/backend/crates/gateway-plugin/runtime/src/callback/http.rs +++ b/backend/crates/gateway-plugin/runtime/src/callback/http/outbound.rs @@ -7,21 +7,21 @@ use gateway_host::outbound::{HttpClient, HttpError, HttpErrorKind, HttpRequest, use gateway_plugin_sdk::{ErrorCode, PluginFault, SendState, call::host as wire}; use serde::de::DeserializeOwned; -use super::{CallResources, CallbackScope, HttpStream, denied, invalid}; use crate::RpcReply; +use crate::callback::{CallResources, CallbackScope, HttpStream, denied, invalid}; /// 回调的公共网络外层;账号鉴权只装饰请求,发送、读流和回收共用同一终端 -pub(super) struct HttpCallbacks<'a> { - pub(super) client: &'a HttpClient, - pub(super) network: &'a NetworkPolicy, - pub(super) scope: &'a Arc, - pub(super) call: &'a CallResources, - pub(super) maximum_payload: usize, - pub(super) request_limits: &'a super::request_limits::RequestLimits, +pub(in crate::callback) struct HttpCallbacks<'a> { + pub(in crate::callback) client: &'a HttpClient, + pub(in crate::callback) network: &'a NetworkPolicy, + pub(in crate::callback) scope: &'a Arc, + pub(in crate::callback) call: &'a CallResources, + pub(in crate::callback) maximum_payload: usize, + pub(in crate::callback) request_limits: &'a crate::callback::request_limits::RequestLimits, } impl HttpCallbacks<'_> { - pub(super) fn body_limit(&self, body: &[u8]) -> Result { + pub(in crate::callback) fn body_limit(&self, body: &[u8]) -> Result { // 空正文不占请求预算,也允许尚未发布设置的注册阶段执行无正文查询 if body.is_empty() { return Ok(0); @@ -29,9 +29,9 @@ impl HttpCallbacks<'_> { self.request_limits.body_bytes(self.call) } - pub(super) async fn account( + pub(in crate::callback) async fn account( &self, - accounts: &super::accounts::PluginAccounts, + accounts: &crate::callback::accounts::PluginAccounts, params: serde_json::Value, payload: Vec, ) -> Result { @@ -55,9 +55,9 @@ impl HttpCallbacks<'_> { .await } - pub(super) async fn proxy( + pub(in crate::callback) async fn proxy( &self, - proxies: &super::PluginProxyPortSlot, + proxies: &crate::callback::PluginProxyPortSlot, params: serde_json::Value, payload: Vec, ) -> Result { @@ -79,7 +79,7 @@ impl HttpCallbacks<'_> { .await } - pub(super) async fn send( + pub(in crate::callback) async fn send( &self, request: HttpRequest, streaming: bool, @@ -94,7 +94,7 @@ impl HttpCallbacks<'_> { .. } = *self; if request.body.len() > request.maximum_body_bytes { - return Err(super::request_limits::too_large()); + return Err(crate::callback::request_limits::too_large()); } let timeout = call.timeout()?; let attempt = call.start_upstream(upstream_purpose)?; @@ -156,7 +156,7 @@ impl HttpCallbacks<'_> { }) } - pub(super) async fn dispatch( + pub(in crate::callback) async fn dispatch( &self, method: &str, params: serde_json::Value, @@ -257,7 +257,7 @@ fn sent_fault(code: ErrorCode, message: &'static str) -> PluginFault { error } -pub(super) fn http_error(error: HttpError) -> PluginFault { +pub(in crate::callback) fn http_error(error: HttpError) -> PluginFault { tracing::warn!( reason = error.reason(), kind = ?error.kind(), diff --git a/backend/crates/gateway-plugin/runtime/src/callback/middleware/mod.rs b/backend/crates/gateway-plugin/runtime/src/callback/middleware/mod.rs index d3792438d..ddcc30878 100644 --- a/backend/crates/gateway-plugin/runtime/src/callback/middleware/mod.rs +++ b/backend/crates/gateway-plugin/runtime/src/callback/middleware/mod.rs @@ -11,7 +11,7 @@ pub(crate) trait MiddlewareCallback: Send + Sync { None } - fn http_resources(&self) -> Option> { + fn http_resources(&self) -> Option> { None } diff --git a/backend/crates/gateway-plugin/runtime/src/callback/mod.rs b/backend/crates/gateway-plugin/runtime/src/callback/mod.rs index 137abf3b8..9da4ac9e6 100644 --- a/backend/crates/gateway-plugin/runtime/src/callback/mod.rs +++ b/backend/crates/gateway-plugin/runtime/src/callback/mod.rs @@ -9,9 +9,7 @@ mod data; mod dispatch; pub(crate) mod error; mod facts; -mod http; -mod http_dispatch; -pub(crate) mod http_middleware; +pub(crate) mod http; mod invocation; mod keys; mod log; diff --git a/backend/crates/gateway-plugin/runtime/src/callback/upstream/mod.rs b/backend/crates/gateway-plugin/runtime/src/callback/upstream/mod.rs index c76c0a69d..03f2f53c6 100644 --- a/backend/crates/gateway-plugin/runtime/src/callback/upstream/mod.rs +++ b/backend/crates/gateway-plugin/runtime/src/callback/upstream/mod.rs @@ -24,7 +24,7 @@ use gateway_plugin_sdk::{ }; use super::{denied, http::HttpCallbacks, invalid}; -use crate::{RpcReply, adapter::upstream_adapter::target::UpstreamTarget}; +use crate::{RpcReply, upstream_target::UpstreamTarget}; pub(crate) use sessions::{ConnectionOwner, ConnectionPool}; diff --git a/backend/crates/gateway-plugin/runtime/src/lib.rs b/backend/crates/gateway-plugin/runtime/src/lib.rs index 6d78903aa..6e35fd1b5 100644 --- a/backend/crates/gateway-plugin/runtime/src/lib.rs +++ b/backend/crates/gateway-plugin/runtime/src/lib.rs @@ -7,6 +7,7 @@ mod deprecation; mod generation; mod package; mod rpc; +mod upstream_target; pub use adapter::command_line::{PluginCommandError, PluginCommandOutput, PluginCommandSession}; pub use generation::{PluginRestartCircuitConfig, PluginRuntime, PluginRuntimeConfig}; diff --git a/backend/crates/gateway-plugin/runtime/src/adapter/upstream_adapter/target.rs b/backend/crates/gateway-plugin/runtime/src/upstream_target.rs similarity index 91% rename from backend/crates/gateway-plugin/runtime/src/adapter/upstream_adapter/target.rs rename to backend/crates/gateway-plugin/runtime/src/upstream_target.rs index 91ec9adc5..ba1fee8f0 100644 --- a/backend/crates/gateway-plugin/runtime/src/adapter/upstream_adapter/target.rs +++ b/backend/crates/gateway-plugin/runtime/src/upstream_target.rs @@ -1,4 +1,4 @@ -//! 保存插件上游基址与路径用途,解析受管请求目标 +//! 上游适配声明与受管回调共用的不可变请求目标 use std::collections::BTreeMap; @@ -15,7 +15,7 @@ pub(crate) struct UpstreamTarget { } impl UpstreamTarget { - pub(super) fn compile(declaration: &UpstreamAdapterDeclaration) -> Result { + pub(crate) fn compile(declaration: &UpstreamAdapterDeclaration) -> Result { let base = Url::parse(&declaration.base_url) .map_err(|_| AdminError::invalid("上游 Base URL 无效"))?; let paths = declaration diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/policy/facts/contract.rs b/backend/crates/gateway-plugin/runtime/tests/generation/policy/facts/contract.rs new file mode 100644 index 000000000..3ae363b42 --- /dev/null +++ b/backend/crates/gateway-plugin/runtime/tests/generation/policy/facts/contract.rs @@ -0,0 +1,286 @@ +//! 跨模块行为合同测试 + +use super::*; + +#[tokio::test] +async fn reading_websocket_facts_preserves_original_text_and_opaque_messages() { + let records = tempfile::tempdir().unwrap(); + let marker = records.path().join("facts.jsonl"); + let worker = std::fs::read(env!("CARGO_BIN_EXE_gateway-plugin-test-middleware")).unwrap(); + let package = crate::support::package_with_contributions( + &worker, + Contributions::from([crate::support::contribution( + Capability::Middleware, + vec![Stage::Attempt], + vec!["openai".into()], + vec!["openai".into()], + )]), + ); + let (_cache, runtime) = setup_package(vec![InstanceFixture { + id: "facts-reader", + configuration: serde_json::json!({"mode":"facts", "attempt":true, "facts_marker":marker}), + bindings: vec![binding(MIDDLEWARE_CONTRIBUTION, "attempt", 0, PluginFailurePolicy::Reject)], + }], package).await; + let generation = prepare(&runtime).await; + let plan = runtime + .execution_registry() + .middleware(&generation) + .unwrap(); + let messages = [ + "{ \"type\" : \"future.event\", \"number\" : 1e3, \"text\" : \"\\u0061\" }".to_owned(), + format!( + "{{\"type\":\"future.deep\",\"value\":{}0{}}}", + "[".repeat(140), + "]".repeat(140) + ), + "future non-JSON text".to_owned(), + ]; + let events: Vec<_> = messages + .iter() + .map(|raw| { + let wire = match serde_json::from_str::(raw) { + Ok(data) => ProtocolWireEvent::json("openai", None, data) + .unwrap() + .with_raw_websocket_message(raw.as_str()), + Err(_) => ProtocolWireEvent::raw_websocket("openai", raw.as_str()).unwrap(), + }; + Ok(ProviderEvent::wire(wire)) + }) + .collect(); + let mut stream = execute_attempt_middleware( + Some(&plan), + attempt_middleware_context_for_transport(Arc::default(), ClientTransport::WebSocket), + operation(), + ClientTransport::WebSocket, + Box::new(move |_, _| { + Box::pin(async move { + Ok(ProviderStream::new( + ProviderCallMetadata::new( + ProviderKind::new("openai").unwrap(), + UpstreamModelId::new("native-model").unwrap(), + ProviderAccountId::new("acct_original").unwrap(), + UpstreamTransport::new("websocket").unwrap(), + ), + futures::stream::iter(events), + (), + )) + }) + }), + ) + .await + .unwrap(); + let mut delivered = Vec::new(); + while let Some(event) = stream.next().await { + let event = event.unwrap(); + assert!(!event.middleware_transformed()); + delivered.push( + event + .wire_event() + .unwrap() + .raw_websocket_message() + .unwrap() + .to_owned(), + ); + } + assert_eq!(delivered, messages); + let snapshots = marker_lines(&marker, 4).await; + for (snapshot, original) in snapshots[1..].iter().zip(&messages) { + let event: gateway_plugin_sdk::call::model::ExecutionEvent = + serde_json::from_value(snapshot.clone()).unwrap(); + let gateway_plugin_sdk::call::model::WirePayload::WebSocket { data, message, .. } = + event.wire.unwrap().payload + else { + panic!("WebSocket facts must retain their original transport"); + }; + assert_eq!(message, original.as_bytes()); + assert_eq!( + data.is_some(), + serde_json::from_str::(original).is_ok() + ); + } + drop(stream); + runtime.shutdown().await; +} + +#[tokio::test] +async fn facts_are_readable_without_replacing_or_duplicating_the_original_execution() { + let records = tempfile::tempdir().unwrap(); + let marker = records.path().join("facts.jsonl"); + let worker = std::fs::read(env!("CARGO_BIN_EXE_gateway-plugin-test-middleware")).unwrap(); + let package = crate::support::package_with_contributions( + &worker, + Contributions::from([crate::support::contribution( + Capability::Middleware, + vec![Stage::Attempt], + vec!["openai".into()], + vec!["openai".into()], + )]), + ); + let (_cache, runtime) = setup_package(vec![InstanceFixture { + id: "facts-reader", + configuration: serde_json::json!({"mode":"facts", "attempt":true, "facts_marker":marker}), + bindings: vec![binding(MIDDLEWARE_CONTRIBUTION, "attempt", 0, PluginFailurePolicy::Reject)], + }], package).await; + let generation = prepare(&runtime).await; + let plan = runtime + .execution_registry() + .middleware(&generation) + .unwrap(); + let metadata = ProviderCallMetadata::new( + ProviderKind::new("openai").unwrap(), + UpstreamModelId::new("native-model").unwrap(), + ProviderAccountId::new("acct_original").unwrap(), + UpstreamTransport::new("http").unwrap(), + ) + .with_upstream_request_id(OpaqueUpstreamValue::new("upstream-original")) + .with_selection_observation(ProviderSelectionObservation::new(17, None)); + let amount = Money::new( + Decimal::from_scaled(123).unwrap(), + gateway_core::metering::CurrencyCode::new("USD").unwrap(), + ); + let breakdown = CalculatedCostBreakdown::new( + CalculatedCostAmounts::new(amount, amount, amount, amount, amount, amount), + CalculatedCostRates::new(amount, amount, amount, amount), + Some("priority".into()), + 125, + ) + .with_long_context_billing(true); + let started = ProviderEvent::canonical(GatewayEvent::Started(ResponseMeta::new( + "response-original", + "native-model", + ))); + let mut completed = ProviderEvent::canonical_with_wire( + vec![ + GatewayEvent::Usage(Usage { + input_tokens: Some(7), + output_tokens: Some(2), + ..Usage::default() + }), + GatewayEvent::CalculatedCost(breakdown.calculated_cost()), + GatewayEvent::ProviderCost(ProviderReportedCost::from_usd_ticks(456).unwrap()), + GatewayEvent::Completed( + ResponseMeta::new("response-original", "native-model") + .with_finish_reason(FinishReason::Stop), + ), + ], + ProtocolWireEvent::raw_json("openai", Bytes::from_static(br#"{ "output": [] }"#)).unwrap(), + ); + completed.attach_observation( + ProviderResponseObservation::new(UpstreamTransport::new("http").unwrap()) + .with_status_code(200) + .with_request_id(OpaqueUpstreamValue::new("response-request-id")) + .with_service_tier_if_valid("priority") + .with_client_headers(vec![ProviderResponseHeader::new( + "set-cookie", + Bytes::from_static(b"fixture=secret"), + )]) + .with_provider_metadata( + ProviderResponseMetadata::new("{\"private_field\":\"kept\"}".into()).unwrap(), + ) + .with_timings(ProviderResponseTimings { + headers_ms: Some(19), + upstream_response_ms: Some(7_000), + upstream_engine_ms: Some(2.450638), + ..Default::default() + }), + ); + completed.attach_session_update( + ProviderSessionState::new( + "openai", + serde_json::json!({"cursor":"private-cursor"}) + .as_object() + .unwrap() + .clone(), + ) + .unwrap() + .with_extension_owner(ExtensionSessionOwner { + instance_id: "owner".into(), + contribution_id: "owner.adapter".into(), + adapter_id: "adapter".into(), + generation: 7, + incarnation: "incarnation".into(), + connection_local: true, + }), + ); + let mut stream = execute_attempt_middleware( + Some(&plan), + attempt_middleware_context(Arc::default()), + operation(), + ClientTransport::HttpJson, + Box::new(move |_, _| { + Box::pin(async move { + Ok(ProviderStream::new( + metadata, + futures::stream::iter([Ok(started), Ok(completed)]), + (), + )) + }) + }), + ) + .await + .unwrap(); + assert_eq!( + stream.metadata().provider_account_id().as_str(), + "acct_original" + ); + let mut events = Vec::new(); + while let Some(event) = stream.next().await { + events.push(event.unwrap()); + } + assert_eq!(events.len(), 2); + let costs = events + .iter() + .flat_map(ProviderEvent::canonical_facts) + .filter(|fact| { + matches!( + fact, + GatewayEvent::CalculatedCost(_) | GatewayEvent::ProviderCost(_) + ) + }) + .count(); + assert_eq!( + costs, 2, + "reading and modifying snapshots must not change original cost facts" + ); + let snapshots = marker_lines(&marker, 3).await; + assert_eq!(snapshots[0]["provider_account_id"], "acct_original"); + assert_eq!(snapshots[0]["upstream_request_id"], "upstream-original"); + assert_eq!( + snapshots[0]["selection_observation"]["account_selection_wait_ms"], + 17 + ); + assert_eq!(snapshots[1]["facts"][0]["type"], "started"); + let facts = &snapshots[2]["host"]; + assert_eq!(facts["costs"][0]["total"]["amount"], "0.0000000123"); + assert_eq!( + facts["costs"][0]["breakdown"]["long_context_billing_applied"], + true + ); + assert_eq!(facts["costs"][1]["total"]["amount"], "0.0000000456"); + assert_eq!( + facts["observation"]["client_headers"][0]["value"], + serde_json::json!(b"fixture=secret".to_vec()) + ); + assert_eq!( + facts["observation"]["provider_metadata"], + "{\"private_field\":\"kept\"}" + ); + assert_eq!(facts["observation"]["timings"]["headers_ms"], 19); + assert_eq!( + facts["observation"]["timings"]["upstream_engine_ms"], + 2.450638 + ); + assert_eq!( + facts["observation"]["timings"]["upstream_response_ms"], + 7_000 + ); + assert_eq!( + facts["session_update"]["payload"]["cursor"], + "private-cursor" + ); + assert_eq!(facts["session_update"]["extension_owner"]["generation"], 7); + assert_eq!(facts["middleware_transformed"], false); + assert!(facts["middleware_origin_wire"].is_null()); + drop(stream); + runtime.shutdown().await; +} diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/policy/facts/mod.rs b/backend/crates/gateway-plugin/runtime/tests/generation/policy/facts/mod.rs index e09db0542..37184d9d9 100644 --- a/backend/crates/gateway-plugin/runtime/tests/generation/policy/facts/mod.rs +++ b/backend/crates/gateway-plugin/runtime/tests/generation/policy/facts/mod.rs @@ -1,5 +1,6 @@ //! 验证插件可读取执行事实而不替换或重复原始执行 +mod contract; use super::*; use futures::StreamExt; use gateway_core::{ @@ -20,286 +21,3 @@ use gateway_core::{ routing::UpstreamModelId, upstream::{OpaqueUpstreamValue, UpstreamTransport}, }; - -#[tokio::test] -async fn reading_websocket_facts_preserves_original_text_and_opaque_messages() { - let records = tempfile::tempdir().unwrap(); - let marker = records.path().join("facts.jsonl"); - let worker = std::fs::read(env!("CARGO_BIN_EXE_gateway-plugin-test-middleware")).unwrap(); - let package = crate::support::package_with_contributions( - &worker, - Contributions::from([crate::support::contribution( - Capability::Middleware, - vec![Stage::Attempt], - vec!["openai".into()], - vec!["openai".into()], - )]), - ); - let (_cache, runtime) = setup_package(vec![InstanceFixture { - id: "facts-reader", - configuration: serde_json::json!({"mode":"facts", "attempt":true, "facts_marker":marker}), - bindings: vec![binding(MIDDLEWARE_CONTRIBUTION, "attempt", 0, PluginFailurePolicy::Reject)], - }], package).await; - let generation = prepare(&runtime).await; - let plan = runtime - .execution_registry() - .middleware(&generation) - .unwrap(); - let messages = [ - "{ \"type\" : \"future.event\", \"number\" : 1e3, \"text\" : \"\\u0061\" }".to_owned(), - format!( - "{{\"type\":\"future.deep\",\"value\":{}0{}}}", - "[".repeat(140), - "]".repeat(140) - ), - "future non-JSON text".to_owned(), - ]; - let events: Vec<_> = messages - .iter() - .map(|raw| { - let wire = match serde_json::from_str::(raw) { - Ok(data) => ProtocolWireEvent::json("openai", None, data) - .unwrap() - .with_raw_websocket_message(raw.as_str()), - Err(_) => ProtocolWireEvent::raw_websocket("openai", raw.as_str()).unwrap(), - }; - Ok(ProviderEvent::wire(wire)) - }) - .collect(); - let mut stream = execute_attempt_middleware( - Some(&plan), - attempt_middleware_context_for_transport(Arc::default(), ClientTransport::WebSocket), - operation(), - ClientTransport::WebSocket, - Box::new(move |_, _| { - Box::pin(async move { - Ok(ProviderStream::new( - ProviderCallMetadata::new( - ProviderKind::new("openai").unwrap(), - UpstreamModelId::new("native-model").unwrap(), - ProviderAccountId::new("acct_original").unwrap(), - UpstreamTransport::new("websocket").unwrap(), - ), - futures::stream::iter(events), - (), - )) - }) - }), - ) - .await - .unwrap(); - let mut delivered = Vec::new(); - while let Some(event) = stream.next().await { - let event = event.unwrap(); - assert!(!event.middleware_transformed()); - delivered.push( - event - .wire_event() - .unwrap() - .raw_websocket_message() - .unwrap() - .to_owned(), - ); - } - assert_eq!(delivered, messages); - let snapshots = marker_lines(&marker, 4).await; - for (snapshot, original) in snapshots[1..].iter().zip(&messages) { - let event: gateway_plugin_sdk::call::model::ExecutionEvent = - serde_json::from_value(snapshot.clone()).unwrap(); - let gateway_plugin_sdk::call::model::WirePayload::WebSocket { data, message, .. } = - event.wire.unwrap().payload - else { - panic!("WebSocket facts must retain their original transport"); - }; - assert_eq!(message, original.as_bytes()); - assert_eq!( - data.is_some(), - serde_json::from_str::(original).is_ok() - ); - } - drop(stream); - runtime.shutdown().await; -} - -#[tokio::test] -async fn facts_are_readable_without_replacing_or_duplicating_the_original_execution() { - let records = tempfile::tempdir().unwrap(); - let marker = records.path().join("facts.jsonl"); - let worker = std::fs::read(env!("CARGO_BIN_EXE_gateway-plugin-test-middleware")).unwrap(); - let package = crate::support::package_with_contributions( - &worker, - Contributions::from([crate::support::contribution( - Capability::Middleware, - vec![Stage::Attempt], - vec!["openai".into()], - vec!["openai".into()], - )]), - ); - let (_cache, runtime) = setup_package(vec![InstanceFixture { - id: "facts-reader", - configuration: serde_json::json!({"mode":"facts", "attempt":true, "facts_marker":marker}), - bindings: vec![binding(MIDDLEWARE_CONTRIBUTION, "attempt", 0, PluginFailurePolicy::Reject)], - }], package).await; - let generation = prepare(&runtime).await; - let plan = runtime - .execution_registry() - .middleware(&generation) - .unwrap(); - let metadata = ProviderCallMetadata::new( - ProviderKind::new("openai").unwrap(), - UpstreamModelId::new("native-model").unwrap(), - ProviderAccountId::new("acct_original").unwrap(), - UpstreamTransport::new("http").unwrap(), - ) - .with_upstream_request_id(OpaqueUpstreamValue::new("upstream-original")) - .with_selection_observation(ProviderSelectionObservation::new(17, None)); - let amount = Money::new( - Decimal::from_scaled(123).unwrap(), - gateway_core::metering::CurrencyCode::new("USD").unwrap(), - ); - let breakdown = CalculatedCostBreakdown::new( - CalculatedCostAmounts::new(amount, amount, amount, amount, amount, amount), - CalculatedCostRates::new(amount, amount, amount, amount), - Some("priority".into()), - 125, - ) - .with_long_context_billing(true); - let started = ProviderEvent::canonical(GatewayEvent::Started(ResponseMeta::new( - "response-original", - "native-model", - ))); - let mut completed = ProviderEvent::canonical_with_wire( - vec![ - GatewayEvent::Usage(Usage { - input_tokens: Some(7), - output_tokens: Some(2), - ..Usage::default() - }), - GatewayEvent::CalculatedCost(breakdown.calculated_cost()), - GatewayEvent::ProviderCost(ProviderReportedCost::from_usd_ticks(456).unwrap()), - GatewayEvent::Completed( - ResponseMeta::new("response-original", "native-model") - .with_finish_reason(FinishReason::Stop), - ), - ], - ProtocolWireEvent::raw_json("openai", Bytes::from_static(br#"{ "output": [] }"#)).unwrap(), - ); - completed.attach_observation( - ProviderResponseObservation::new(UpstreamTransport::new("http").unwrap()) - .with_status_code(200) - .with_request_id(OpaqueUpstreamValue::new("response-request-id")) - .with_service_tier_if_valid("priority") - .with_client_headers(vec![ProviderResponseHeader::new( - "set-cookie", - Bytes::from_static(b"fixture=secret"), - )]) - .with_provider_metadata( - ProviderResponseMetadata::new("{\"private_field\":\"kept\"}".into()).unwrap(), - ) - .with_timings(ProviderResponseTimings { - headers_ms: Some(19), - upstream_response_ms: Some(7_000), - upstream_engine_ms: Some(2.450638), - ..Default::default() - }), - ); - completed.attach_session_update( - ProviderSessionState::new( - "openai", - serde_json::json!({"cursor":"private-cursor"}) - .as_object() - .unwrap() - .clone(), - ) - .unwrap() - .with_extension_owner(ExtensionSessionOwner { - instance_id: "owner".into(), - contribution_id: "owner.adapter".into(), - adapter_id: "adapter".into(), - generation: 7, - incarnation: "incarnation".into(), - connection_local: true, - }), - ); - let mut stream = execute_attempt_middleware( - Some(&plan), - attempt_middleware_context(Arc::default()), - operation(), - ClientTransport::HttpJson, - Box::new(move |_, _| { - Box::pin(async move { - Ok(ProviderStream::new( - metadata, - futures::stream::iter([Ok(started), Ok(completed)]), - (), - )) - }) - }), - ) - .await - .unwrap(); - assert_eq!( - stream.metadata().provider_account_id().as_str(), - "acct_original" - ); - let mut events = Vec::new(); - while let Some(event) = stream.next().await { - events.push(event.unwrap()); - } - assert_eq!(events.len(), 2); - let costs = events - .iter() - .flat_map(ProviderEvent::canonical_facts) - .filter(|fact| { - matches!( - fact, - GatewayEvent::CalculatedCost(_) | GatewayEvent::ProviderCost(_) - ) - }) - .count(); - assert_eq!( - costs, 2, - "reading and modifying snapshots must not change original cost facts" - ); - let snapshots = marker_lines(&marker, 3).await; - assert_eq!(snapshots[0]["provider_account_id"], "acct_original"); - assert_eq!(snapshots[0]["upstream_request_id"], "upstream-original"); - assert_eq!( - snapshots[0]["selection_observation"]["account_selection_wait_ms"], - 17 - ); - assert_eq!(snapshots[1]["facts"][0]["type"], "started"); - let facts = &snapshots[2]["host"]; - assert_eq!(facts["costs"][0]["total"]["amount"], "0.0000000123"); - assert_eq!( - facts["costs"][0]["breakdown"]["long_context_billing_applied"], - true - ); - assert_eq!(facts["costs"][1]["total"]["amount"], "0.0000000456"); - assert_eq!( - facts["observation"]["client_headers"][0]["value"], - serde_json::json!(b"fixture=secret".to_vec()) - ); - assert_eq!( - facts["observation"]["provider_metadata"], - "{\"private_field\":\"kept\"}" - ); - assert_eq!(facts["observation"]["timings"]["headers_ms"], 19); - assert_eq!( - facts["observation"]["timings"]["upstream_engine_ms"], - 2.450638 - ); - assert_eq!( - facts["observation"]["timings"]["upstream_response_ms"], - 7_000 - ); - assert_eq!( - facts["session_update"]["payload"]["cursor"], - "private-cursor" - ); - assert_eq!(facts["session_update"]["extension_owner"]["generation"], 7); - assert_eq!(facts["middleware_transformed"], false); - assert!(facts["middleware_origin_wire"].is_null()); - drop(stream); - runtime.shutdown().await; -} diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/policy/http/websocket/contract.rs b/backend/crates/gateway-plugin/runtime/tests/generation/policy/http/websocket/contract.rs new file mode 100644 index 000000000..1d90d1f5d --- /dev/null +++ b/backend/crates/gateway-plugin/runtime/tests/generation/policy/http/websocket/contract.rs @@ -0,0 +1,354 @@ +//! 跨模块行为合同测试 + +use super::*; + +#[tokio::test] +async fn session_model_and_network_callbacks_outlive_handshake_and_each_execution_has_its_own_budget() + { + let Some(mut environment) = Environment::create_command().await else { + return; + }; + let account = environment.account(None).await; + let key = format!("key_{}", uuid::Uuid::new_v4().simple()); + environment.client_key(&key, "sk-session-fixture").await; + environment + .install_plugin( + serde_json::json!({"http":true,"mode":"callbacks", "call_budgets_ms":{"http":500}}), + ) + .await; + let (runtime, bundle) = environment.runtime_with_limits(RpcLimits::default()).await; + environment.store.start_command_line_writes().unwrap(); + let snapshot = bundle.snapshots().snapshot_for_diagnostics().unwrap(); + let plan = runtime + .execution_registry() + .middleware(snapshot.extensions().unwrap()) + .unwrap(); + let (send, incoming) = tokio::sync::mpsc::channel(1); + let (outgoing, mut receive) = tokio::sync::mpsc::channel(1); + let dropped = Arc::new(AtomicBool::new(false)); + let transport = Arc::new(Transport { + incoming: tokio::sync::Mutex::new(incoming), + outgoing, + dropped: dropped.clone(), + }); + let mut request = ::http::Request::builder() + .uri("/custom/session") + .body(core::empty_body()) + .unwrap(); + request + .extensions_mut() + .insert(Arc::new(Upgrade(transport)) as Arc); + let cancellation = CancellationToken::new(); + let mut response = plan + .handle_http( + core::Context { + plugin_instance_id: None, + call_id: "http-call".into(), + parent_call_id: None, + extensions: Default::default(), + request_id: "session-models".into(), + plan: Some(plan.clone()), + cancellation: cancellation.clone(), + }, + request, + compose(Vec::new(), |_| { + Box::pin(async { panic!("custom session owns transport") }) + }), + ) + .await + .unwrap(); + let task = tokio::spawn( + response + .extensions_mut() + .remove::() + .unwrap() + .take_task() + .unwrap(), + ); + drop(response); + assert_eq!(receive.recv().await.unwrap().payload, "ready"); + tokio::time::sleep(Duration::from_millis(700)).await; + let server = MockServer::start().await; + Mock::given(any()) + .respond_with(ResponseTemplate::new(200).set_body_string("network reply")) + .expect(1) + .mount(&server) + .await; + let call = |command| ws::Message { + kind: ws::Kind::Text, + payload: Bytes::from(serde_json::to_vec(&command).unwrap()), + }; + send.send(call(serde_json::json!({"method":"host.http.do","params":{"method":"GET","url":server.uri(),"headers":[]}}))).await.unwrap(); + let reply = tokio::time::timeout(Duration::from_secs(5), receive.recv()) + .await + .unwrap() + .unwrap(); + let reply: serde_json::Value = serde_json::from_slice(&reply.payload).unwrap(); + assert_eq!(reply["result"]["status"], 200); + assert_eq!(reply["payload_bytes"], 13); + // 超过单个子调用图的 16 次预算,连接仍可承载新的独立执行 + let mut requests = BTreeSet::new(); + for _ in 0..18 { + send.send(call(serde_json::json!({"method":"host.model.execute","params":{ + "client_key_id":key,"model":crate::support::native::MODEL,"protocol":"openai","operation":"generate","provider":"openai","account_id":account.as_str() + },"body":{"model":crate::support::native::MODEL,"input":"session request"}}))).await.unwrap(); + let reply = tokio::time::timeout(Duration::from_secs(5), receive.recv()) + .await + .unwrap() + .expect("model callback reply"); + let reply: serde_json::Value = serde_json::from_slice(&reply.payload).unwrap(); + assert!(reply["result"]["events"].as_u64().unwrap() > 0); + assert!(requests.insert(reply["result"]["request_id"].as_str().unwrap().to_owned())); + } + assert_eq!( + environment + .wait_for_bound_model_requests(&key, 18) + .await + .len(), + 18 + ); + cancellation.cancel(); + assert!( + tokio::time::timeout(Duration::from_secs(5), task) + .await + .unwrap() + .unwrap() + .is_err() + ); + assert!(dropped.load(Ordering::SeqCst)); + drop(plan); + drop(snapshot); + drop(bundle); + runtime.shutdown().await; + environment + .store + .shutdown_command_line_writes() + .await + .unwrap(); + environment.close().await; +} + +#[tokio::test] +async fn real_plugin_controls_upgrade_and_concurrent_duplex_with_large_binary_frames() { + let (_cache, runtime, generation, plan) = http_plugin_with_configuration( + serde_json::json!({"http":true,"mode":"upgrade", "call_budgets_ms":{"http":500}}), + RpcLimits::default(), + PluginFailurePolicy::Reject, + ) + .await; + let (send, incoming) = tokio::sync::mpsc::channel(1); + let (outgoing, mut receive) = tokio::sync::mpsc::channel(1); + let dropped = Arc::new(AtomicBool::new(false)); + let transport = Arc::new(Transport { + incoming: tokio::sync::Mutex::new(incoming), + outgoing, + dropped: dropped.clone(), + }); + let mut request = ::http::Request::builder() + .uri("/custom/session") + .body(core::empty_body()) + .unwrap(); + request + .extensions_mut() + .insert(Arc::new(Upgrade(transport)) as Arc); + let cancellation = CancellationToken::new(); + let mut response = plan + .handle_http( + core::Context { + plugin_instance_id: None, + call_id: "http-call".into(), + parent_call_id: None, + extensions: Default::default(), + request_id: "session-test".into(), + plan: Some(plan.clone()), + cancellation, + }, + request, + compose(Vec::new(), |_| { + Box::pin(async { panic!("custom session must not call the native router") }) + }), + ) + .await + .unwrap(); + assert_eq!(response.status(), 101); + let upgraded = response + .extensions_mut() + .remove::() + .unwrap(); + let task = tokio::spawn(upgraded.take_task().unwrap()); + drop(response); + tokio::time::timeout(Duration::from_secs(5), async { + assert_eq!(receive.recv().await.unwrap().payload, "ready"); + tokio::time::sleep(Duration::from_millis(700)).await; + assert!( + !dropped.load(Ordering::SeqCst), + "会话不能在初始调用期限结束时关闭" + ); + let payload = Bytes::from(vec![0x81; 20 * 1024 * 1024]); + send.send(ws::Message { + kind: ws::Kind::Binary, + payload: payload.clone(), + }) + .await + .unwrap(); + let echoed = receive.recv().await.unwrap(); + assert_eq!(echoed.kind, ws::Kind::Binary); + assert_eq!(echoed.payload, payload); + for index in 0..32 { + let payload = Bytes::from(format!("message {index}")); + send.send(ws::Message { + kind: ws::Kind::Text, + payload: payload.clone(), + }) + .await + .unwrap(); + assert_eq!(receive.recv().await.unwrap().payload, payload); + } + let close = receive.recv().await.unwrap(); + assert_eq!(close.kind, ws::Kind::Close { code: Some(1000) }); + assert_eq!(close.payload, "done"); + task.await.unwrap().unwrap(); + while !dropped.load(Ordering::SeqCst) { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + drop(plan); + drop(generation); + runtime.shutdown().await; +} + +#[tokio::test] +async fn dropping_an_uncommitted_upgrade_or_cancelling_a_session_reclaims_its_socket() { + for active in [false, true] { + let (_cache, runtime, generation, plan) = http_plugin("upgrade").await; + let (_send, incoming) = tokio::sync::mpsc::channel(1); + let (outgoing, mut receive) = tokio::sync::mpsc::channel(1); + let dropped = Arc::new(AtomicBool::new(false)); + let transport = Arc::new(Transport { + incoming: tokio::sync::Mutex::new(incoming), + outgoing, + dropped: dropped.clone(), + }); + let mut request = ::http::Request::builder() + .uri("/custom/session") + .body(core::empty_body()) + .unwrap(); + request + .extensions_mut() + .insert(Arc::new(Upgrade(transport)) as Arc); + let cancellation = CancellationToken::new(); + let mut response = plan + .handle_http( + core::Context { + plugin_instance_id: None, + call_id: "http-call".into(), + parent_call_id: None, + extensions: Default::default(), + request_id: "cancel-session".into(), + plan: None, + cancellation: cancellation.clone(), + }, + request, + compose(Vec::new(), |_| { + Box::pin(async { panic!("no native route") }) + }), + ) + .await + .unwrap(); + if active { + let task = tokio::spawn( + response + .extensions_mut() + .remove::() + .unwrap() + .take_task() + .unwrap(), + ); + assert_eq!( + tokio::time::timeout(Duration::from_secs(5), receive.recv()) + .await + .unwrap() + .unwrap() + .payload, + "ready" + ); + cancellation.cancel(); + assert!(task.await.unwrap().is_err()); + } + drop(response); + tokio::time::timeout(Duration::from_secs(5), async { + while !dropped.load(Ordering::SeqCst) { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + drop(plan); + drop(generation); + runtime.shutdown().await; + } +} + +#[tokio::test] +async fn upgraded_plugin_business_failure_reaches_terminal_owner_with_safe_classification() { + for mode in ["session-error", "session-cancelled"] { + let (_cache, runtime, generation, plan) = http_plugin(mode).await; + let (_send, incoming) = tokio::sync::mpsc::channel(1); + let (outgoing, _receive) = tokio::sync::mpsc::channel(1); + let transport = Arc::new(Transport { + incoming: tokio::sync::Mutex::new(incoming), + outgoing, + dropped: Arc::default(), + }); + let mut request = ::http::Request::builder() + .uri("/custom/session") + .body(core::empty_body()) + .unwrap(); + request + .extensions_mut() + .insert(Arc::new(Upgrade(transport)) as Arc); + let mut response = plan + .handle_http( + core::Context { + plugin_instance_id: None, + request_id: "session-failure".into(), + call_id: "http-call".into(), + parent_call_id: None, + extensions: Default::default(), + plan: Some(plan.clone()), + cancellation: CancellationToken::new(), + }, + request, + compose(Vec::new(), |_| { + Box::pin(async { panic!("session owns its response") }) + }), + ) + .await + .unwrap(); + assert_eq!(response.status(), 101); + let task = response + .extensions_mut() + .remove::() + .unwrap() + .take_task() + .unwrap(); + let error = tokio::time::timeout(Duration::from_secs(5), task) + .await + .unwrap() + .unwrap_err(); + if mode == "session-error" { + assert!( + matches!(error, upgrade::SessionError::Failed { kind: "permission_denied", plugin_instance_id: Some(ref id) } if id == "http-plugin") + ); + } else { + assert!(matches!(error, upgrade::SessionError::Cancelled)); + } + assert!(!format!("{error:?}").contains("private-plugin-error")); + drop(response); + drop(plan); + drop(generation); + runtime.shutdown().await; + } +} diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/policy/http/websocket/mod.rs b/backend/crates/gateway-plugin/runtime/tests/generation/policy/http/websocket/mod.rs index 93f7b1be6..3fc7f8713 100644 --- a/backend/crates/gateway-plugin/runtime/tests/generation/policy/http/websocket/mod.rs +++ b/backend/crates/gateway-plugin/runtime/tests/generation/policy/http/websocket/mod.rs @@ -1,5 +1,6 @@ //! 验证真实插件 WebSocket 升级、双向大帧与会话资源生命周期 +mod contract; use super::*; use futures::FutureExt as _; use gateway_core::engine::middleware::{http::upgrade, websocket as ws}; @@ -53,354 +54,3 @@ impl upgrade::WebSocketUpgrade for Upgrade { }) } } - -#[tokio::test] -async fn session_model_and_network_callbacks_outlive_handshake_and_each_execution_has_its_own_budget() - { - let Some(mut environment) = Environment::create_command().await else { - return; - }; - let account = environment.account(None).await; - let key = format!("key_{}", uuid::Uuid::new_v4().simple()); - environment.client_key(&key, "sk-session-fixture").await; - environment - .install_plugin( - serde_json::json!({"http":true,"mode":"callbacks", "call_budgets_ms":{"http":500}}), - ) - .await; - let (runtime, bundle) = environment.runtime_with_limits(RpcLimits::default()).await; - environment.store.start_command_line_writes().unwrap(); - let snapshot = bundle.snapshots().snapshot_for_diagnostics().unwrap(); - let plan = runtime - .execution_registry() - .middleware(snapshot.extensions().unwrap()) - .unwrap(); - let (send, incoming) = tokio::sync::mpsc::channel(1); - let (outgoing, mut receive) = tokio::sync::mpsc::channel(1); - let dropped = Arc::new(AtomicBool::new(false)); - let transport = Arc::new(Transport { - incoming: tokio::sync::Mutex::new(incoming), - outgoing, - dropped: dropped.clone(), - }); - let mut request = ::http::Request::builder() - .uri("/custom/session") - .body(core::empty_body()) - .unwrap(); - request - .extensions_mut() - .insert(Arc::new(Upgrade(transport)) as Arc); - let cancellation = CancellationToken::new(); - let mut response = plan - .handle_http( - core::Context { - plugin_instance_id: None, - call_id: "http-call".into(), - parent_call_id: None, - extensions: Default::default(), - request_id: "session-models".into(), - plan: Some(plan.clone()), - cancellation: cancellation.clone(), - }, - request, - compose(Vec::new(), |_| { - Box::pin(async { panic!("custom session owns transport") }) - }), - ) - .await - .unwrap(); - let task = tokio::spawn( - response - .extensions_mut() - .remove::() - .unwrap() - .take_task() - .unwrap(), - ); - drop(response); - assert_eq!(receive.recv().await.unwrap().payload, "ready"); - tokio::time::sleep(Duration::from_millis(700)).await; - let server = MockServer::start().await; - Mock::given(any()) - .respond_with(ResponseTemplate::new(200).set_body_string("network reply")) - .expect(1) - .mount(&server) - .await; - let call = |command| ws::Message { - kind: ws::Kind::Text, - payload: Bytes::from(serde_json::to_vec(&command).unwrap()), - }; - send.send(call(serde_json::json!({"method":"host.http.do","params":{"method":"GET","url":server.uri(),"headers":[]}}))).await.unwrap(); - let reply = tokio::time::timeout(Duration::from_secs(5), receive.recv()) - .await - .unwrap() - .unwrap(); - let reply: serde_json::Value = serde_json::from_slice(&reply.payload).unwrap(); - assert_eq!(reply["result"]["status"], 200); - assert_eq!(reply["payload_bytes"], 13); - // 超过单个子调用图的 16 次预算,连接仍可承载新的独立执行 - let mut requests = BTreeSet::new(); - for _ in 0..18 { - send.send(call(serde_json::json!({"method":"host.model.execute","params":{ - "client_key_id":key,"model":crate::support::native::MODEL,"protocol":"openai","operation":"generate","provider":"openai","account_id":account.as_str() - },"body":{"model":crate::support::native::MODEL,"input":"session request"}}))).await.unwrap(); - let reply = tokio::time::timeout(Duration::from_secs(5), receive.recv()) - .await - .unwrap() - .expect("model callback reply"); - let reply: serde_json::Value = serde_json::from_slice(&reply.payload).unwrap(); - assert!(reply["result"]["events"].as_u64().unwrap() > 0); - assert!(requests.insert(reply["result"]["request_id"].as_str().unwrap().to_owned())); - } - assert_eq!( - environment - .wait_for_bound_model_requests(&key, 18) - .await - .len(), - 18 - ); - cancellation.cancel(); - assert!( - tokio::time::timeout(Duration::from_secs(5), task) - .await - .unwrap() - .unwrap() - .is_err() - ); - assert!(dropped.load(Ordering::SeqCst)); - drop(plan); - drop(snapshot); - drop(bundle); - runtime.shutdown().await; - environment - .store - .shutdown_command_line_writes() - .await - .unwrap(); - environment.close().await; -} - -#[tokio::test] -async fn real_plugin_controls_upgrade_and_concurrent_duplex_with_large_binary_frames() { - let (_cache, runtime, generation, plan) = http_plugin_with_configuration( - serde_json::json!({"http":true,"mode":"upgrade", "call_budgets_ms":{"http":500}}), - RpcLimits::default(), - PluginFailurePolicy::Reject, - ) - .await; - let (send, incoming) = tokio::sync::mpsc::channel(1); - let (outgoing, mut receive) = tokio::sync::mpsc::channel(1); - let dropped = Arc::new(AtomicBool::new(false)); - let transport = Arc::new(Transport { - incoming: tokio::sync::Mutex::new(incoming), - outgoing, - dropped: dropped.clone(), - }); - let mut request = ::http::Request::builder() - .uri("/custom/session") - .body(core::empty_body()) - .unwrap(); - request - .extensions_mut() - .insert(Arc::new(Upgrade(transport)) as Arc); - let cancellation = CancellationToken::new(); - let mut response = plan - .handle_http( - core::Context { - plugin_instance_id: None, - call_id: "http-call".into(), - parent_call_id: None, - extensions: Default::default(), - request_id: "session-test".into(), - plan: Some(plan.clone()), - cancellation, - }, - request, - compose(Vec::new(), |_| { - Box::pin(async { panic!("custom session must not call the native router") }) - }), - ) - .await - .unwrap(); - assert_eq!(response.status(), 101); - let upgraded = response - .extensions_mut() - .remove::() - .unwrap(); - let task = tokio::spawn(upgraded.take_task().unwrap()); - drop(response); - tokio::time::timeout(Duration::from_secs(5), async { - assert_eq!(receive.recv().await.unwrap().payload, "ready"); - tokio::time::sleep(Duration::from_millis(700)).await; - assert!( - !dropped.load(Ordering::SeqCst), - "会话不能在初始调用期限结束时关闭" - ); - let payload = Bytes::from(vec![0x81; 20 * 1024 * 1024]); - send.send(ws::Message { - kind: ws::Kind::Binary, - payload: payload.clone(), - }) - .await - .unwrap(); - let echoed = receive.recv().await.unwrap(); - assert_eq!(echoed.kind, ws::Kind::Binary); - assert_eq!(echoed.payload, payload); - for index in 0..32 { - let payload = Bytes::from(format!("message {index}")); - send.send(ws::Message { - kind: ws::Kind::Text, - payload: payload.clone(), - }) - .await - .unwrap(); - assert_eq!(receive.recv().await.unwrap().payload, payload); - } - let close = receive.recv().await.unwrap(); - assert_eq!(close.kind, ws::Kind::Close { code: Some(1000) }); - assert_eq!(close.payload, "done"); - task.await.unwrap().unwrap(); - while !dropped.load(Ordering::SeqCst) { - tokio::task::yield_now().await; - } - }) - .await - .unwrap(); - drop(plan); - drop(generation); - runtime.shutdown().await; -} - -#[tokio::test] -async fn dropping_an_uncommitted_upgrade_or_cancelling_a_session_reclaims_its_socket() { - for active in [false, true] { - let (_cache, runtime, generation, plan) = http_plugin("upgrade").await; - let (_send, incoming) = tokio::sync::mpsc::channel(1); - let (outgoing, mut receive) = tokio::sync::mpsc::channel(1); - let dropped = Arc::new(AtomicBool::new(false)); - let transport = Arc::new(Transport { - incoming: tokio::sync::Mutex::new(incoming), - outgoing, - dropped: dropped.clone(), - }); - let mut request = ::http::Request::builder() - .uri("/custom/session") - .body(core::empty_body()) - .unwrap(); - request - .extensions_mut() - .insert(Arc::new(Upgrade(transport)) as Arc); - let cancellation = CancellationToken::new(); - let mut response = plan - .handle_http( - core::Context { - plugin_instance_id: None, - call_id: "http-call".into(), - parent_call_id: None, - extensions: Default::default(), - request_id: "cancel-session".into(), - plan: None, - cancellation: cancellation.clone(), - }, - request, - compose(Vec::new(), |_| { - Box::pin(async { panic!("no native route") }) - }), - ) - .await - .unwrap(); - if active { - let task = tokio::spawn( - response - .extensions_mut() - .remove::() - .unwrap() - .take_task() - .unwrap(), - ); - assert_eq!( - tokio::time::timeout(Duration::from_secs(5), receive.recv()) - .await - .unwrap() - .unwrap() - .payload, - "ready" - ); - cancellation.cancel(); - assert!(task.await.unwrap().is_err()); - } - drop(response); - tokio::time::timeout(Duration::from_secs(5), async { - while !dropped.load(Ordering::SeqCst) { - tokio::task::yield_now().await; - } - }) - .await - .unwrap(); - drop(plan); - drop(generation); - runtime.shutdown().await; - } -} - -#[tokio::test] -async fn upgraded_plugin_business_failure_reaches_terminal_owner_with_safe_classification() { - for mode in ["session-error", "session-cancelled"] { - let (_cache, runtime, generation, plan) = http_plugin(mode).await; - let (_send, incoming) = tokio::sync::mpsc::channel(1); - let (outgoing, _receive) = tokio::sync::mpsc::channel(1); - let transport = Arc::new(Transport { - incoming: tokio::sync::Mutex::new(incoming), - outgoing, - dropped: Arc::default(), - }); - let mut request = ::http::Request::builder() - .uri("/custom/session") - .body(core::empty_body()) - .unwrap(); - request - .extensions_mut() - .insert(Arc::new(Upgrade(transport)) as Arc); - let mut response = plan - .handle_http( - core::Context { - plugin_instance_id: None, - request_id: "session-failure".into(), - call_id: "http-call".into(), - parent_call_id: None, - extensions: Default::default(), - plan: Some(plan.clone()), - cancellation: CancellationToken::new(), - }, - request, - compose(Vec::new(), |_| { - Box::pin(async { panic!("session owns its response") }) - }), - ) - .await - .unwrap(); - assert_eq!(response.status(), 101); - let task = response - .extensions_mut() - .remove::() - .unwrap() - .take_task() - .unwrap(); - let error = tokio::time::timeout(Duration::from_secs(5), task) - .await - .unwrap() - .unwrap_err(); - if mode == "session-error" { - assert!( - matches!(error, upgrade::SessionError::Failed { kind: "permission_denied", plugin_instance_id: Some(ref id) } if id == "http-plugin") - ); - } else { - assert!(matches!(error, upgrade::SessionError::Cancelled)); - } - assert!(!format!("{error:?}").contains("private-plugin-error")); - drop(response); - drop(plan); - drop(generation); - runtime.shutdown().await; - } -} diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/policy/service/contract.rs b/backend/crates/gateway-plugin/runtime/tests/generation/policy/service/contract.rs new file mode 100644 index 000000000..b228b6e09 --- /dev/null +++ b/backend/crates/gateway-plugin/runtime/tests/generation/policy/service/contract.rs @@ -0,0 +1,544 @@ +//! 跨模块行为合同测试 + +use super::*; + +#[tokio::test] +async fn plugin_error_details_survive_public_service_composition() { + let Some(environment) = Environment::create().await else { + return; + }; + let (runtime, core) = environment + .plugin(json!({"service":true,"mode":"fault"})) + .await; + let admin = environment.bind_admin_accounts(&runtime, &core).await; + let services = admin.services(); + runtime.bind_services(&services.public_services()).unwrap(); + let error = services + .public_services() + .call("settings.load", json!(null)) + .await + .unwrap_err(); + assert_eq!(error.message, "service plugin fixture error"); + let details = error.details.unwrap(); + assert_eq!(details["code"], "capacity"); + assert_eq!( + details["details"], + json!({"opaque":"unfiltered","empty":"","zero":0,"disabled":false,"missing":null}) + ); + runtime.shutdown().await; +} + +#[tokio::test] +async fn explicit_service_dispatch_composes_once_and_preserves_native_transactions() { + let Some(environment) = Environment::create().await else { + return; + }; + let records = environment.directory.path().join("services.jsonl"); + let (runtime, core) = environment + .plugin(json!({"service":true,"mode":"rewrite","records":records})) + .await; + let admin = environment.bind_admin_accounts(&runtime, &core).await; + let services = admin.services(); + runtime.bind_services(&services.public_services()).unwrap(); + + let original = environment + .store + .admin_ports() + .settings() + .load_runtime_settings() + .await + .unwrap(); + let visible = services.settings().load().await.unwrap(); + assert_eq!( + visible.values.refresh_margin_seconds, + original.values.refresh_margin_seconds + ); + assert_eq!(visible.config_revision, original.config_revision); + let through_registry = services + .public_services() + .call("settings.load", json!(null)) + .await + .unwrap(); + let typed: gateway_plugin_sdk::call::services::settings::RuntimeSettings = + serde_json::from_value(through_registry).unwrap(); + assert_eq!(typed.refresh_margin_seconds, 4321); + // 返回层改写不是持久化写入;原 owner 保留真实配置事实 + assert_eq!( + environment + .store + .admin_ports() + .settings() + .load_runtime_settings() + .await + .unwrap() + .values + .refresh_margin_seconds, + original.values.refresh_margin_seconds + ); + + let mut command = ReplaceRuntimeSettings::from(original); + command.values.refresh_margin_seconds = 999; + command.values.openai_oauth_guardian_review_model = false; + command.values.openai_request_country = gateway_core::account::OpenAiRequestCountry::Custom { + country: "CA".into(), + }; + for field in [ + "openai_oauth_guardian_review_model", + "openai_request_country", + ] { + let mut args = serde_json::to_value((mutation(), &command)).unwrap(); + args[1].as_object_mut().unwrap().remove(field); + assert!( + services + .public_services() + .call("settings.replace", args) + .await + .is_err(), + "{field}" + ); + } + let saved = services + .public_services() + .call( + "settings.replace", + serde_json::to_value((mutation(), command.clone())).unwrap(), + ) + .await + .unwrap(); + let saved: gateway_admin::model::settings::RuntimeSettings = + serde_json::from_value(saved).unwrap(); + assert_eq!(saved.values.refresh_margin_seconds, 1234); + assert!(saved.config_revision > command.expected_revision); + let current = environment + .store + .admin_ports() + .settings() + .load_runtime_settings() + .await + .unwrap(); + assert_eq!(current.values.refresh_margin_seconds, 1234); + assert!(!current.values.openai_oauth_guardian_review_model); + assert_eq!( + current.values.openai_request_country, + command.values.openai_request_country + ); + assert_eq!( + core.snapshots() + .snapshot_for_diagnostics() + .unwrap() + .revision() + .get(), + saved.config_revision.get() + ); + let error = services + .settings() + .replace(&mutation(), command.clone()) + .await + .unwrap_err(); + assert_eq!(error.kind(), AdminErrorKind::Conflict); + let error = services + .public_services() + .call( + "settings.replace", + serde_json::to_value((mutation(), command)).unwrap(), + ) + .await + .unwrap_err(); + assert_eq!(error.kind, "conflict"); + assert!(!error.message.is_empty()); + + // 组合位于主动调用入口;内部 pricing 不重复进入插件链 + let error = services + .public_services() + .call( + "settings.update_pricing", + serde_json::to_value(( + mutation(), + gateway_admin::model::pricing::UpdatePricing { + provider: "missing-provider".into(), + models: vec!["model".into()], + change: gateway_admin::model::pricing::PricingChange::Reset, + }, + )) + .unwrap(), + ) + .await + .unwrap_err(); + assert_eq!(error.kind, "invalid"); + let records: Vec = std::fs::read_to_string(&records) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + assert_eq!( + records + .iter() + .filter(|record| record["operation"] == "settings.update_pricing") + .count(), + 1 + ); + assert!( + !records + .iter() + .any(|record| record["operation"] == "settings.pricing") + ); + + drop(services); + drop(admin); + drop(core); + runtime.shutdown().await; + environment.close().await; +} + +#[tokio::test] +async fn service_middleware_can_recover_a_native_error_without_changing_the_default_service() { + let Some(environment) = Environment::create().await else { + return; + }; + let (runtime, core) = environment + .plugin(json!({"service":true,"mode":"recover"})) + .await; + let admin = environment.bind_admin_accounts(&runtime, &core).await; + let services = admin.services(); + runtime.bind_services(&services.public_services()).unwrap(); + assert!( + services + .settings() + .preview_client_profile("missing-provider", None) + .await + .is_err() + ); + let recovered = services + .public_services() + .call( + "settings.preview_client_profile", + json!(["missing-provider", null]), + ) + .await + .unwrap(); + assert_eq!(recovered, json!({})); + assert_eq!( + services + .public_services() + .call("settings.admin_api_key_exists", json!(null)) + .await + .unwrap(), + true + ); + assert!(!services.settings().admin_api_key_exists().await.unwrap()); + assert!( + !environment + .store + .admin_ports() + .settings() + .admin_api_key_exists() + .await + .unwrap() + ); + assert!( + services + .public_services() + .call("settings.unknown", json!(null)) + .await + .is_err() + ); + drop(services); + drop(admin); + drop(core); + runtime.shutdown().await; + environment.close().await; +} + +#[tokio::test] +async fn cancelling_explicit_service_call_releases_plugin_handler_before_shutdown() { + let Some(environment) = Environment::create().await else { + return; + }; + let records = environment.directory.path().join("blocked.jsonl"); + let (runtime, core) = environment + .plugin(json!({"service":true,"mode":"block","records":records})) + .await; + let admin = environment.bind_admin_accounts(&runtime, &core).await; + let services = admin.services(); + runtime.bind_services(&services.public_services()).unwrap(); + let registry = services.public_services(); + let task = tokio::spawn(async move { registry.call("settings.load", json!(null)).await }); + let wait_for = |path: std::path::PathBuf| async move { + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while !path.exists() { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .expect("plugin lifecycle signal"); + }; + wait_for(records.clone()).await; + task.abort(); + assert!(task.await.unwrap_err().is_cancelled()); + wait_for(records.with_extension("closed")).await; + drop(services); + drop(admin); + drop(core); + runtime.shutdown().await; + environment.close().await; +} + +#[tokio::test] +async fn cli_service_callback_uses_the_same_public_settings_and_plugin_chain() { + use std::sync::Arc; + struct Pricing; + #[async_trait::async_trait] + impl gateway_admin::ports::pricing::PricingSource for Pricing { + async fn fetch( + &self, + _: &gateway_admin::ports::pricing::PricingSourceScope, + ) -> Result< + gateway_admin::model::pricing::PricingSyncPreview, + gateway_admin::model::AdminError, + > { + unreachable!("reading settings does not fetch external pricing") + } + } + let Some(environment) = Environment::create_command().await else { + return; + }; + environment.install_plugin(json!({ + "plugin_id":"test.command-source", + "command_registration":{"commands":[{"name":"settings","description":"Read public settings"}]}, + "command_service_request":{"operation":"settings.load","input":null}, + })).await; + environment + .install_plugin(json!({"service":true,"mode":"rewrite"})) + .await; + let (runtime, core) = environment.command_plane().await; + let settings = gateway_admin::initialize_settings( + environment.store.admin_ports().settings(), + core.snapshot_control(), + crate::support::native::admin_registry(), + Arc::new(Pricing), + ); + let mut registry = gateway_admin::public_service::Registry::new({ + let snapshots = core.snapshots(); + let middleware = runtime.execution_registry(); + Arc::new(move || middleware.middleware(snapshots.snapshot_for_diagnostics()?.extensions()?)) + }); + registry.register_settings(&settings).unwrap(); + let registry = Arc::new(registry); + runtime.bind_services(®istry).unwrap(); + let instances = environment + .store + .admin_ports() + .plugins() + .load_instances() + .await + .unwrap(); + let command = instances + .instances + .iter() + .find(|instance| instance.configuration.get("command_registration").is_some()) + .unwrap(); + let commands = runtime.prepare_command_line().await.unwrap(); + let output = commands + .execute(&command.id, "settings", &[]) + .await + .unwrap(); + let result: gateway_plugin_sdk::call::services::Response = + serde_json::from_str(&output.stdout).unwrap(); + let returned: gateway_plugin_sdk::call::services::settings::RuntimeSettings = + serde_json::from_value(result.unwrap()).unwrap(); + assert_eq!(returned.refresh_margin_seconds, 4321); + assert_ne!( + environment + .store + .admin_ports() + .settings() + .load_runtime_settings() + .await + .unwrap() + .values + .refresh_margin_seconds, + 4321 + ); + commands.shutdown().await; + drop(core); + runtime.shutdown().await; + environment.close().await; +} + +#[tokio::test] +async fn service_chain_preserves_onion_order_parent_scope_and_native_results_without_a_database() { + use super::super::*; + use gateway_core::{engine::middleware::service as core, middleware::compose}; + + let directory = tempfile::tempdir().unwrap(); + let records = directory.path().join("onion.jsonl"); + let worker = std::fs::read(env!("CARGO_BIN_EXE_gateway-plugin-test-middleware")).unwrap(); + let package = crate::support::package_with_contributions( + &worker, + Contributions::from([crate::support::contribution( + Capability::Middleware, + vec![Stage::Service], + vec!["service".into()], + vec!["service".into()], + )]), + ); + let (cache, runtime) = setup_package( + [("inner", 20), ("ancestor", 0), ("outer", 10)] + .into_iter() + .map(|(id, order)| InstanceFixture { + id, + configuration: json!({"service":true,"mode":"onion","records":records}), + bindings: vec![binding( + MIDDLEWARE_CONTRIBUTION, + "service", + order, + PluginFailurePolicy::Reject, + )], + }) + .collect(), + package, + ) + .await; + let generation = prepare(&runtime).await; + let plan = runtime + .execution_registry() + .middleware(&generation) + .unwrap(); + let calls = Arc::new(AtomicUsize::new(0)); + let input = json!({"opaque":[null,false,0,""]}); + for reject in [false, true] { + let observed = calls.clone(); + let expected_input = input.clone(); + let expected = if reject { + Err(core::Error { + kind: "fixture".into(), + message: "native error".into(), + details: Some(input.clone()), + }) + } else { + Ok(input.clone()) + }; + let result = expected.clone(); + let actual = plan + .handle_service( + core::Context { + operation: "fixture.echo", + request_id: "request".into(), + call_id: "child".into(), + parent_call_id: Some("parent".into()), + cancellation: CancellationToken::new(), + extensions: ExtensionCallScope::default() + .extending("ancestor".into()) + .unwrap(), + plan: plan.clone(), + }, + input.clone(), + compose(Vec::new(), move |input| { + Box::pin(async move { + observed.fetch_add(1, Ordering::SeqCst); + assert_eq!(input, expected_input); + result + }) + }), + ) + .await; + assert_eq!(actual, expected); + } + assert_eq!(calls.load(Ordering::SeqCst), 2); + let events = std::fs::read_to_string(records) + .unwrap() + .lines() + .map(|line| serde_json::from_str::(line).unwrap()) + .collect::>(); + assert_eq!(events.len(), 8); + for round in events.as_chunks::<4>().0 { + let phases = round + .iter() + .map(|event| { + ( + event["instance"].as_str().unwrap(), + event["phase"].as_str().unwrap(), + ) + }) + .collect::>(); + assert_eq!( + phases, + [ + ("outer", "enter"), + ("inner", "enter"), + ("inner", "exit"), + ("outer", "exit") + ] + ); + for event in round { + assert_eq!(event["operation"], "fixture.echo"); + assert_eq!(event["request_id"], "request"); + assert_eq!(event["call_id"], "child"); + assert_eq!(event["parent_call_id"], "parent"); + } + } + drop(plan); + drop(generation); + runtime.shutdown().await; + drop(cache); +} + +#[tokio::test] +async fn usage_sdk_calls_preserve_exact_counts_and_write_actor() { + use gateway_admin::model::usage_data::*; + let Some(environment) = Environment::create().await else { + return; + }; + let (runtime, core) = environment + .plugin(json!({"service":true,"mode":"usage_data"})) + .await; + let admin = environment.bind_admin_accounts(&runtime, &core).await; + let services = admin.services(); + runtime.bind_services(&services.public_services()).unwrap(); + runtime.bind_usage_queries(&services.usage_data()).unwrap(); + environment.prepare_empty_analytics().await; + assert_eq!( + services + .public_services() + .call("settings.admin_api_key_exists", json!(null)) + .await + .unwrap(), + json!(true) + ); + let row = services + .usage_data() + .get_record(GetUsageRecord { + id: "sdk-usage".into(), + }) + .await + .unwrap(); + assert_eq!( + row.data.tokens.total_tokens, + Some(UsageCount(9_007_199_254_740_993)) + ); + assert!(matches!(row.data.cost, UsageCost::Known { .. })); + let actors = environment.audit_actor_refs("usage.put").await; + assert!(!actors.is_empty()); + assert!( + actors + .iter() + .all(|actor| actor.starts_with("plugin:test/example:")) + ); + + runtime.shutdown().await; +} + +#[tokio::test] +async fn usage_reader_is_released_when_parent_call_is_cancelled() { + usage_reader_lifecycle("cancel").await; +} + +#[tokio::test] +async fn disabled_instance_keeps_inflight_usage_read_until_parent_completion() { + usage_reader_lifecycle("disable").await; +} + +#[tokio::test] +async fn quiescing_instance_releases_inflight_usage_read() { + usage_reader_lifecycle("quiesce").await; +} diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/policy/service/mod.rs b/backend/crates/gateway-plugin/runtime/tests/generation/policy/service/mod.rs index 88a76a752..aa2d40b70 100644 --- a/backend/crates/gateway-plugin/runtime/tests/generation/policy/service/mod.rs +++ b/backend/crates/gateway-plugin/runtime/tests/generation/policy/service/mod.rs @@ -1,549 +1,10 @@ //! 验证插件服务中间件的组合、错误恢复、事务与取消边界 +mod contract; use crate::support::environment::{Environment, mutation}; use gateway_admin::model::{AdminErrorKind, settings::ReplaceRuntimeSettings}; use serde_json::json; -#[tokio::test] -async fn plugin_error_details_survive_public_service_composition() { - let Some(environment) = Environment::create().await else { - return; - }; - let (runtime, core) = environment - .plugin(json!({"service":true,"mode":"fault"})) - .await; - let admin = environment.bind_admin_accounts(&runtime, &core).await; - let services = admin.services(); - runtime.bind_services(&services.public_services()).unwrap(); - let error = services - .public_services() - .call("settings.load", json!(null)) - .await - .unwrap_err(); - assert_eq!(error.message, "service plugin fixture error"); - let details = error.details.unwrap(); - assert_eq!(details["code"], "capacity"); - assert_eq!( - details["details"], - json!({"opaque":"unfiltered","empty":"","zero":0,"disabled":false,"missing":null}) - ); - runtime.shutdown().await; -} - -#[tokio::test] -async fn explicit_service_dispatch_composes_once_and_preserves_native_transactions() { - let Some(environment) = Environment::create().await else { - return; - }; - let records = environment.directory.path().join("services.jsonl"); - let (runtime, core) = environment - .plugin(json!({"service":true,"mode":"rewrite","records":records})) - .await; - let admin = environment.bind_admin_accounts(&runtime, &core).await; - let services = admin.services(); - runtime.bind_services(&services.public_services()).unwrap(); - - let original = environment - .store - .admin_ports() - .settings() - .load_runtime_settings() - .await - .unwrap(); - let visible = services.settings().load().await.unwrap(); - assert_eq!( - visible.values.refresh_margin_seconds, - original.values.refresh_margin_seconds - ); - assert_eq!(visible.config_revision, original.config_revision); - let through_registry = services - .public_services() - .call("settings.load", json!(null)) - .await - .unwrap(); - let typed: gateway_plugin_sdk::call::services::settings::RuntimeSettings = - serde_json::from_value(through_registry).unwrap(); - assert_eq!(typed.refresh_margin_seconds, 4321); - // 返回层改写不是持久化写入;原 owner 保留真实配置事实 - assert_eq!( - environment - .store - .admin_ports() - .settings() - .load_runtime_settings() - .await - .unwrap() - .values - .refresh_margin_seconds, - original.values.refresh_margin_seconds - ); - - let mut command = ReplaceRuntimeSettings::from(original); - command.values.refresh_margin_seconds = 999; - command.values.openai_oauth_guardian_review_model = false; - command.values.openai_request_country = gateway_core::account::OpenAiRequestCountry::Custom { - country: "CA".into(), - }; - for field in [ - "openai_oauth_guardian_review_model", - "openai_request_country", - ] { - let mut args = serde_json::to_value((mutation(), &command)).unwrap(); - args[1].as_object_mut().unwrap().remove(field); - assert!( - services - .public_services() - .call("settings.replace", args) - .await - .is_err(), - "{field}" - ); - } - let saved = services - .public_services() - .call( - "settings.replace", - serde_json::to_value((mutation(), command.clone())).unwrap(), - ) - .await - .unwrap(); - let saved: gateway_admin::model::settings::RuntimeSettings = - serde_json::from_value(saved).unwrap(); - assert_eq!(saved.values.refresh_margin_seconds, 1234); - assert!(saved.config_revision > command.expected_revision); - let current = environment - .store - .admin_ports() - .settings() - .load_runtime_settings() - .await - .unwrap(); - assert_eq!(current.values.refresh_margin_seconds, 1234); - assert!(!current.values.openai_oauth_guardian_review_model); - assert_eq!( - current.values.openai_request_country, - command.values.openai_request_country - ); - assert_eq!( - core.snapshots() - .snapshot_for_diagnostics() - .unwrap() - .revision() - .get(), - saved.config_revision.get() - ); - let error = services - .settings() - .replace(&mutation(), command.clone()) - .await - .unwrap_err(); - assert_eq!(error.kind(), AdminErrorKind::Conflict); - let error = services - .public_services() - .call( - "settings.replace", - serde_json::to_value((mutation(), command)).unwrap(), - ) - .await - .unwrap_err(); - assert_eq!(error.kind, "conflict"); - assert!(!error.message.is_empty()); - - // 组合位于主动调用入口;内部 pricing 不重复进入插件链 - let error = services - .public_services() - .call( - "settings.update_pricing", - serde_json::to_value(( - mutation(), - gateway_admin::model::pricing::UpdatePricing { - provider: "missing-provider".into(), - models: vec!["model".into()], - change: gateway_admin::model::pricing::PricingChange::Reset, - }, - )) - .unwrap(), - ) - .await - .unwrap_err(); - assert_eq!(error.kind, "invalid"); - let records: Vec = std::fs::read_to_string(&records) - .unwrap() - .lines() - .map(|line| serde_json::from_str(line).unwrap()) - .collect(); - assert_eq!( - records - .iter() - .filter(|record| record["operation"] == "settings.update_pricing") - .count(), - 1 - ); - assert!( - !records - .iter() - .any(|record| record["operation"] == "settings.pricing") - ); - - drop(services); - drop(admin); - drop(core); - runtime.shutdown().await; - environment.close().await; -} - -#[tokio::test] -async fn service_middleware_can_recover_a_native_error_without_changing_the_default_service() { - let Some(environment) = Environment::create().await else { - return; - }; - let (runtime, core) = environment - .plugin(json!({"service":true,"mode":"recover"})) - .await; - let admin = environment.bind_admin_accounts(&runtime, &core).await; - let services = admin.services(); - runtime.bind_services(&services.public_services()).unwrap(); - assert!( - services - .settings() - .preview_client_profile("missing-provider", None) - .await - .is_err() - ); - let recovered = services - .public_services() - .call( - "settings.preview_client_profile", - json!(["missing-provider", null]), - ) - .await - .unwrap(); - assert_eq!(recovered, json!({})); - assert_eq!( - services - .public_services() - .call("settings.admin_api_key_exists", json!(null)) - .await - .unwrap(), - true - ); - assert!(!services.settings().admin_api_key_exists().await.unwrap()); - assert!( - !environment - .store - .admin_ports() - .settings() - .admin_api_key_exists() - .await - .unwrap() - ); - assert!( - services - .public_services() - .call("settings.unknown", json!(null)) - .await - .is_err() - ); - drop(services); - drop(admin); - drop(core); - runtime.shutdown().await; - environment.close().await; -} - -#[tokio::test] -async fn cancelling_explicit_service_call_releases_plugin_handler_before_shutdown() { - let Some(environment) = Environment::create().await else { - return; - }; - let records = environment.directory.path().join("blocked.jsonl"); - let (runtime, core) = environment - .plugin(json!({"service":true,"mode":"block","records":records})) - .await; - let admin = environment.bind_admin_accounts(&runtime, &core).await; - let services = admin.services(); - runtime.bind_services(&services.public_services()).unwrap(); - let registry = services.public_services(); - let task = tokio::spawn(async move { registry.call("settings.load", json!(null)).await }); - let wait_for = |path: std::path::PathBuf| async move { - tokio::time::timeout(std::time::Duration::from_secs(5), async { - while !path.exists() { - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - } - }) - .await - .expect("plugin lifecycle signal"); - }; - wait_for(records.clone()).await; - task.abort(); - assert!(task.await.unwrap_err().is_cancelled()); - wait_for(records.with_extension("closed")).await; - drop(services); - drop(admin); - drop(core); - runtime.shutdown().await; - environment.close().await; -} - -#[tokio::test] -async fn cli_service_callback_uses_the_same_public_settings_and_plugin_chain() { - use std::sync::Arc; - struct Pricing; - #[async_trait::async_trait] - impl gateway_admin::ports::pricing::PricingSource for Pricing { - async fn fetch( - &self, - ) -> Result< - gateway_admin::model::pricing::PricingSyncPreview, - gateway_admin::model::AdminError, - > { - unreachable!("reading settings does not fetch external pricing") - } - } - let Some(environment) = Environment::create_command().await else { - return; - }; - environment.install_plugin(json!({ - "plugin_id":"test.command-source", - "command_registration":{"commands":[{"name":"settings","description":"Read public settings"}]}, - "command_service_request":{"operation":"settings.load","input":null}, - })).await; - environment - .install_plugin(json!({"service":true,"mode":"rewrite"})) - .await; - let (runtime, core) = environment.command_plane().await; - let settings = gateway_admin::initialize_settings( - environment.store.admin_ports().settings(), - core.snapshot_control(), - crate::support::native::admin_registry(), - Arc::new(Pricing), - ); - let mut registry = gateway_admin::public_service::Registry::new({ - let snapshots = core.snapshots(); - let middleware = runtime.execution_registry(); - Arc::new(move || middleware.middleware(snapshots.snapshot_for_diagnostics()?.extensions()?)) - }); - registry.register_settings(&settings).unwrap(); - let registry = Arc::new(registry); - runtime.bind_services(®istry).unwrap(); - let instances = environment - .store - .admin_ports() - .plugins() - .load_instances() - .await - .unwrap(); - let command = instances - .instances - .iter() - .find(|instance| instance.configuration.get("command_registration").is_some()) - .unwrap(); - let commands = runtime.prepare_command_line().await.unwrap(); - let output = commands - .execute(&command.id, "settings", &[]) - .await - .unwrap(); - let result: gateway_plugin_sdk::call::services::Response = - serde_json::from_str(&output.stdout).unwrap(); - let returned: gateway_plugin_sdk::call::services::settings::RuntimeSettings = - serde_json::from_value(result.unwrap()).unwrap(); - assert_eq!(returned.refresh_margin_seconds, 4321); - assert_ne!( - environment - .store - .admin_ports() - .settings() - .load_runtime_settings() - .await - .unwrap() - .values - .refresh_margin_seconds, - 4321 - ); - commands.shutdown().await; - drop(core); - runtime.shutdown().await; - environment.close().await; -} - -#[tokio::test] -async fn service_chain_preserves_onion_order_parent_scope_and_native_results_without_a_database() { - use super::*; - use gateway_core::{engine::middleware::service as core, middleware::compose}; - - let directory = tempfile::tempdir().unwrap(); - let records = directory.path().join("onion.jsonl"); - let worker = std::fs::read(env!("CARGO_BIN_EXE_gateway-plugin-test-middleware")).unwrap(); - let package = crate::support::package_with_contributions( - &worker, - Contributions::from([crate::support::contribution( - Capability::Middleware, - vec![Stage::Service], - vec!["service".into()], - vec!["service".into()], - )]), - ); - let (cache, runtime) = setup_package( - [("inner", 20), ("ancestor", 0), ("outer", 10)] - .into_iter() - .map(|(id, order)| InstanceFixture { - id, - configuration: json!({"service":true,"mode":"onion","records":records}), - bindings: vec![binding( - MIDDLEWARE_CONTRIBUTION, - "service", - order, - PluginFailurePolicy::Reject, - )], - }) - .collect(), - package, - ) - .await; - let generation = prepare(&runtime).await; - let plan = runtime - .execution_registry() - .middleware(&generation) - .unwrap(); - let calls = Arc::new(AtomicUsize::new(0)); - let input = json!({"opaque":[null,false,0,""]}); - for reject in [false, true] { - let observed = calls.clone(); - let expected_input = input.clone(); - let expected = if reject { - Err(core::Error { - kind: "fixture".into(), - message: "native error".into(), - details: Some(input.clone()), - }) - } else { - Ok(input.clone()) - }; - let result = expected.clone(); - let actual = plan - .handle_service( - core::Context { - operation: "fixture.echo", - request_id: "request".into(), - call_id: "child".into(), - parent_call_id: Some("parent".into()), - cancellation: CancellationToken::new(), - extensions: ExtensionCallScope::default() - .extending("ancestor".into()) - .unwrap(), - plan: plan.clone(), - }, - input.clone(), - compose(Vec::new(), move |input| { - Box::pin(async move { - observed.fetch_add(1, Ordering::SeqCst); - assert_eq!(input, expected_input); - result - }) - }), - ) - .await; - assert_eq!(actual, expected); - } - assert_eq!(calls.load(Ordering::SeqCst), 2); - let events = std::fs::read_to_string(records) - .unwrap() - .lines() - .map(|line| serde_json::from_str::(line).unwrap()) - .collect::>(); - assert_eq!(events.len(), 8); - for round in events.as_chunks::<4>().0 { - let phases = round - .iter() - .map(|event| { - ( - event["instance"].as_str().unwrap(), - event["phase"].as_str().unwrap(), - ) - }) - .collect::>(); - assert_eq!( - phases, - [ - ("outer", "enter"), - ("inner", "enter"), - ("inner", "exit"), - ("outer", "exit") - ] - ); - for event in round { - assert_eq!(event["operation"], "fixture.echo"); - assert_eq!(event["request_id"], "request"); - assert_eq!(event["call_id"], "child"); - assert_eq!(event["parent_call_id"], "parent"); - } - } - drop(plan); - drop(generation); - runtime.shutdown().await; - drop(cache); -} - -#[tokio::test] -async fn usage_sdk_calls_preserve_exact_counts_and_write_actor() { - use gateway_admin::model::usage_data::*; - let Some(environment) = Environment::create().await else { - return; - }; - let (runtime, core) = environment - .plugin(json!({"service":true,"mode":"usage_data"})) - .await; - let admin = environment.bind_admin_accounts(&runtime, &core).await; - let services = admin.services(); - runtime.bind_services(&services.public_services()).unwrap(); - runtime.bind_usage_queries(&services.usage_data()).unwrap(); - environment.prepare_empty_analytics().await; - assert_eq!( - services - .public_services() - .call("settings.admin_api_key_exists", json!(null)) - .await - .unwrap(), - json!(true) - ); - let row = services - .usage_data() - .get_record(GetUsageRecord { - id: "sdk-usage".into(), - }) - .await - .unwrap(); - assert_eq!( - row.data.tokens.total_tokens, - Some(UsageCount(9_007_199_254_740_993)) - ); - assert!(matches!(row.data.cost, UsageCost::Known { .. })); - let actors = environment.audit_actor_refs("usage.put").await; - assert!(!actors.is_empty()); - assert!( - actors - .iter() - .all(|actor| actor.starts_with("plugin:test/example:")) - ); - - runtime.shutdown().await; -} - -#[tokio::test] -async fn usage_reader_is_released_when_parent_call_is_cancelled() { - usage_reader_lifecycle("cancel").await; -} - -#[tokio::test] -async fn disabled_instance_keeps_inflight_usage_read_until_parent_completion() { - usage_reader_lifecycle("disable").await; -} - -#[tokio::test] -async fn quiescing_instance_releases_inflight_usage_read() { - usage_reader_lifecycle("quiesce").await; -} - async fn usage_reader_lifecycle(ending: &str) { use gateway_admin::ports::plugins::PluginStateLifecycle; use std::time::Duration; diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/policy/websocket/contract.rs b/backend/crates/gateway-plugin/runtime/tests/generation/policy/websocket/contract.rs new file mode 100644 index 000000000..b12dc6968 --- /dev/null +++ b/backend/crates/gateway-plugin/runtime/tests/generation/policy/websocket/contract.rs @@ -0,0 +1,89 @@ +//! 跨模块行为合同测试 + +use super::*; + +#[tokio::test] +async fn real_plugin_passes_large_binary_messages_by_handle_in_both_directions() { + let (_cache, runtime, generation, plan) = websocket_plugin("passthrough").await; + for direction in [core::Direction::Incoming, core::Direction::Outgoing] { + let payload = Bytes::from(vec![255; 20 * 1024 * 1024]); + let pointer = payload.as_ptr(); + let message = core::Message { + kind: core::Kind::Binary, + payload, + }; + let result = plan + .handle_websocket( + context(direction, Arc::default()), + message, + compose(Vec::new(), |message| Box::pin(async { Ok(Some(message)) })), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(result.kind, core::Kind::Binary); + assert_eq!(result.payload.len(), 20 * 1024 * 1024); + assert_eq!( + result.payload.as_ptr(), + pointer, + "unread payload stays in the host" + ); + } + drop(plan); + drop(generation); + runtime.shutdown().await; +} + +#[tokio::test] +async fn real_plugin_consumes_unknown_control_and_sends_a_binary_reply() { + let (_cache, runtime, generation, plan) = websocket_plugin("control").await; + let sender = Arc::new(Sender::default()); + let result = plan + .handle_websocket( + context(core::Direction::Incoming, sender.clone()), + core::Message { + kind: core::Kind::Text, + payload: Bytes::from_static(b"custom.control"), + }, + compose(Vec::new(), |_| { + Box::pin(async { panic!("consumed control must not reach protocol parser") }) + }), + ) + .await + .unwrap(); + assert!(result.is_none()); + { + let sent = sender.0.lock().unwrap(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].payload.as_ref(), &[0, 255, 1]); + } + drop(plan); + drop(generation); + runtime.shutdown().await; +} + +#[tokio::test] +async fn real_plugin_rewrites_payload_before_next() { + let (_cache, runtime, generation, plan) = websocket_plugin("map").await; + let result = plan + .handle_websocket( + context(core::Direction::Outgoing, Arc::default()), + core::Message { + kind: core::Kind::Text, + payload: Bytes::from_static(b"opaque output"), + }, + compose(Vec::new(), |message: core::Message| { + Box::pin(async { + assert_eq!(message.payload, "OPAQUE OUTPUT"); + Ok(Some(message)) + }) + }), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(result.payload, "OPAQUE OUTPUT"); + drop(plan); + drop(generation); + runtime.shutdown().await; +} diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/policy/websocket/mod.rs b/backend/crates/gateway-plugin/runtime/tests/generation/policy/websocket/mod.rs index 6b34a75fd..872717b76 100644 --- a/backend/crates/gateway-plugin/runtime/tests/generation/policy/websocket/mod.rs +++ b/backend/crates/gateway-plugin/runtime/tests/generation/policy/websocket/mod.rs @@ -1,5 +1,6 @@ //! 验证真实插件 WebSocket 消息转发、改写与控制消息处理 +mod contract; use super::*; use gateway_core::{engine::middleware::websocket as core, middleware::compose}; @@ -67,86 +68,3 @@ fn context(direction: core::Direction, sender: Arc) -> core::Context { sender, } } -#[tokio::test] -async fn real_plugin_passes_large_binary_messages_by_handle_in_both_directions() { - let (_cache, runtime, generation, plan) = websocket_plugin("passthrough").await; - for direction in [core::Direction::Incoming, core::Direction::Outgoing] { - let payload = Bytes::from(vec![255; 20 * 1024 * 1024]); - let pointer = payload.as_ptr(); - let message = core::Message { - kind: core::Kind::Binary, - payload, - }; - let result = plan - .handle_websocket( - context(direction, Arc::default()), - message, - compose(Vec::new(), |message| Box::pin(async { Ok(Some(message)) })), - ) - .await - .unwrap() - .unwrap(); - assert_eq!(result.kind, core::Kind::Binary); - assert_eq!(result.payload.len(), 20 * 1024 * 1024); - assert_eq!( - result.payload.as_ptr(), - pointer, - "unread payload stays in the host" - ); - } - drop(plan); - drop(generation); - runtime.shutdown().await; -} -#[tokio::test] -async fn real_plugin_consumes_unknown_control_and_sends_a_binary_reply() { - let (_cache, runtime, generation, plan) = websocket_plugin("control").await; - let sender = Arc::new(Sender::default()); - let result = plan - .handle_websocket( - context(core::Direction::Incoming, sender.clone()), - core::Message { - kind: core::Kind::Text, - payload: Bytes::from_static(b"custom.control"), - }, - compose(Vec::new(), |_| { - Box::pin(async { panic!("consumed control must not reach protocol parser") }) - }), - ) - .await - .unwrap(); - assert!(result.is_none()); - { - let sent = sender.0.lock().unwrap(); - assert_eq!(sent.len(), 1); - assert_eq!(sent[0].payload.as_ref(), &[0, 255, 1]); - } - drop(plan); - drop(generation); - runtime.shutdown().await; -} -#[tokio::test] -async fn real_plugin_rewrites_payload_before_next() { - let (_cache, runtime, generation, plan) = websocket_plugin("map").await; - let result = plan - .handle_websocket( - context(core::Direction::Outgoing, Arc::default()), - core::Message { - kind: core::Kind::Text, - payload: Bytes::from_static(b"opaque output"), - }, - compose(Vec::new(), |message: core::Message| { - Box::pin(async { - assert_eq!(message.payload, "OPAQUE OUTPUT"); - Ok(Some(message)) - }) - }), - ) - .await - .unwrap() - .unwrap(); - assert_eq!(result.payload, "OPAQUE OUTPUT"); - drop(plan); - drop(generation); - runtime.shutdown().await; -} diff --git a/backend/crates/gateway-plugin/runtime/tests/support/environment.rs b/backend/crates/gateway-plugin/runtime/tests/support/environment.rs index 796482126..0dde907b7 100644 --- a/backend/crates/gateway-plugin/runtime/tests/support/environment.rs +++ b/backend/crates/gateway-plugin/runtime/tests/support/environment.rs @@ -940,7 +940,10 @@ impl PluginDistribution for UnusedAdminRuntime { #[async_trait] impl PricingSource for UnusedAdminRuntime { - async fn fetch(&self) -> Result { + async fn fetch( + &self, + _: &gateway_admin::ports::pricing::PricingSourceScope, + ) -> Result { Err(AdminError::unavailable("unused pricing source")) } } diff --git a/backend/crates/gateway-plugin/sdk/docs/capabilities.md b/backend/crates/gateway-plugin/sdk/docs/capabilities.md index 12fe3f562..f0bd859da 100644 --- a/backend/crates/gateway-plugin/sdk/docs/capabilities.md +++ b/backend/crates/gateway-plugin/sdk/docs/capabilities.md @@ -491,6 +491,7 @@ let plugin = PluginBuilder::from_json(manifest_json)? attempt 中间件在此基线上继续改写,终端不再应用 Fast 策略。 request 与 attempt 阶段通过 `append_header` 添加的请求头会进入上游请求,不适合存放插件内部标记或仅供下游读取的信息。 OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字段覆盖基线,同名多值按插件顺序保留;不存在按认证、Cookie 或会话名称划分的保护列表。 +CPR 中间件添加的 HTTP 扩展头在发往 Antigravity 时经过该 Provider 的过滤:账号身份、客户端画像和 HTTP 传输字段由网关生成,明确换号时清理已识别的追踪头,其余头保留多值字节,具体范围见 [AGY 请求合同](../../../../../docs/api.md#antigravity-客户端原生生成)。 实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造 request 阶段 `request.head.settings` 是本次调用的有效设置对象,包含 `runtime`、`fast_mode`、`client_limits` 和 `timeout_ms`。 diff --git a/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs b/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs index b094a852f..ee88c02a6 100644 --- a/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs +++ b/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs @@ -151,9 +151,9 @@ pub struct RuntimeSettings { pub switch_account_on_queue_failure: bool, pub max_retry_after_seconds: u32, pub openai_guardian_reserved_concurrency: u32, - pub openai_account_affinity: AccountAffinity, + pub account_affinity: AccountAffinity, pub max_account_rotations: u32, - pub openai_session_affinity_ttl_hours: u32, + pub session_affinity_ttl_hours: u32, pub responses_max_decompressed_body_bytes: u64, pub smart_scheduling: SmartSchedulingConfig, pub quota_reset_window_weights: ResetWindowWeights, @@ -193,9 +193,9 @@ pub struct ReplaceRuntimeSettings { pub switch_account_on_queue_failure: bool, pub max_retry_after_seconds: u32, pub openai_guardian_reserved_concurrency: u32, - pub openai_account_affinity: AccountAffinity, + pub account_affinity: AccountAffinity, pub max_account_rotations: u32, - pub openai_session_affinity_ttl_hours: u32, + pub session_affinity_ttl_hours: u32, pub responses_max_decompressed_body_bytes: u64, pub smart_scheduling: SmartSchedulingConfig, pub quota_reset_window_weights: ResetWindowWeights, @@ -294,6 +294,7 @@ pub struct ModelPriceOverride { } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct PricingCatalog { + pub supported_bands: BTreeMap>, pub defaults: PricingOverrides, pub overrides: PricingOverrides, pub synced: PricingOverrides, @@ -414,9 +415,9 @@ impl From for ReplaceRuntimeSettings { switch_account_on_queue_failure: settings.switch_account_on_queue_failure, max_retry_after_seconds: settings.max_retry_after_seconds, openai_guardian_reserved_concurrency: settings.openai_guardian_reserved_concurrency, - openai_account_affinity: settings.openai_account_affinity, + account_affinity: settings.account_affinity, max_account_rotations: settings.max_account_rotations, - openai_session_affinity_ttl_hours: settings.openai_session_affinity_ttl_hours, + session_affinity_ttl_hours: settings.session_affinity_ttl_hours, responses_max_decompressed_body_bytes: settings.responses_max_decompressed_body_bytes, smart_scheduling: settings.smart_scheduling, quota_reset_window_weights: settings.quota_reset_window_weights, diff --git a/backend/crates/gateway-protocol/src/anthropic/content.rs b/backend/crates/gateway-protocol/src/anthropic/content.rs index d739f67f4..78a88c2e4 100644 --- a/backend/crates/gateway-protocol/src/anthropic/content.rs +++ b/backend/crates/gateway-protocol/src/anthropic/content.rs @@ -4,6 +4,7 @@ use serde_json::{Value, json}; const ANTHROPIC_CARRIER: &str = "cpr:anthropic:v1:"; const OPENAI_CARRIER: &str = "cpr:openai:v1:"; +pub(crate) const GENAI_CARRIER: &str = "cpr:genai:v1:"; const REDACTED_CARRIER: &str = "claude-redacted-thinking:"; pub(super) fn text(value: &Value) -> String { diff --git a/backend/crates/gateway-protocol/src/anthropic/mod.rs b/backend/crates/gateway-protocol/src/anthropic/mod.rs index 33b284bad..8e8c84648 100644 --- a/backend/crates/gateway-protocol/src/anthropic/mod.rs +++ b/backend/crates/gateway-protocol/src/anthropic/mod.rs @@ -11,6 +11,8 @@ mod thinking; mod tools; mod usage; +pub(crate) use content::GENAI_CARRIER; + pub use capabilities::MessagesModelCapabilities; pub use error::TranslationError; pub use request::{ diff --git a/backend/crates/gateway-protocol/src/anthropic/request.rs b/backend/crates/gateway-protocol/src/anthropic/request.rs index 3bffea602..02103a41d 100644 --- a/backend/crates/gateway-protocol/src/anthropic/request.rs +++ b/backend/crates/gateway-protocol/src/anthropic/request.rs @@ -9,7 +9,7 @@ use super::{ tools::{ToolSet, messages_tools}, }; -/// 原生 Messages 上游不能消费本网关封装的 OpenAI 思考,仅删除已知外来源载荷 +/// 原生 Messages 上游不能消费本网关封装的外来源思考,仅删除已知载荷 pub fn strip_foreign_thinking_for_messages(request: &mut Map) { let Some(messages) = request.get_mut("messages").and_then(Value::as_array_mut) else { return; @@ -19,7 +19,16 @@ pub fn strip_foreign_thinking_for_messages(request: &mut Map) { return true; }; let previous_len = blocks.len(); - blocks.retain(|block| !content::is_openai_carrier(block)); + blocks.retain(|block| { + !content::is_openai_carrier(block) + && !(block["type"] == "thinking" + && block + .get("signature") + .and_then(Value::as_str) + .is_some_and(|signature| { + signature.starts_with(super::content::GENAI_CARRIER) + })) + }); blocks.len() == previous_len || !blocks.is_empty() }); } diff --git a/backend/crates/gateway-protocol/src/capabilities.rs b/backend/crates/gateway-protocol/src/capabilities.rs new file mode 100644 index 000000000..c7618c981 --- /dev/null +++ b/backend/crates/gateway-protocol/src/capabilities.rs @@ -0,0 +1,20 @@ +//! 协议解码与请求聚合共同使用的能力事实,不依赖协议分派 + +/// 请求正文表达的能力要求 +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct RequestFacts { + /// 显式输出预算 + pub max_output_tokens: Option, + /// 工具声明 + pub tools: bool, + /// 图片输入 + pub vision: bool, + /// 图片生成工具声明 + pub image_generation: bool, + /// 推理配置 + pub reasoning: bool, + /// JSON Schema 输出 + pub json_schema: bool, + /// 原生服务端续接 + pub native_continuation: bool, +} diff --git a/backend/crates/gateway-protocol/src/genai/messages.rs b/backend/crates/gateway-protocol/src/genai/messages.rs new file mode 100644 index 000000000..2c9d7ac60 --- /dev/null +++ b/backend/crates/gateway-protocol/src/genai/messages.rs @@ -0,0 +1,238 @@ +//! Messages 内容到 GenAI 的纯协议映射,签名载荷只按明确来源恢复 + +use crate::anthropic::{GENAI_CARRIER as SIGNATURE_PREFIX, TranslationError}; +use serde_json::{Map, Value, json}; +use std::{borrow::Cow, collections::BTreeMap}; + +fn invalid() -> TranslationError { + TranslationError::InvalidRequest( + "The request contains content unsupported by the GenAI adapter.", + ) +} + +/// 转换 Messages 请求;不支持的内容返回错误,避免静默丢失客户端输入 +pub fn messages_to_genai_request( + request: &Map, +) -> Result, TranslationError> { + let mut result = Map::new(); + if let Some(system) = request.get("system") { + result.insert( + "systemInstruction".into(), + json!({"parts":plain_parts(system)?}), + ); + } + let mut calls = BTreeMap::new(); + let mut contents = Vec::new(); + for message in request + .get("messages") + .and_then(Value::as_array) + .ok_or_else(invalid)? + { + let blocks = match &message["content"] { + Value::String(text) => Cow::Owned(vec![json!({"type":"text","text":text})]), + Value::Array(blocks) => Cow::Borrowed(blocks.as_slice()), + _ => return Err(invalid()), + }; + // 空内容消息不承载对话;客户端的空占位不应进入上游历史 + if blocks.is_empty() { + continue; + } + let role = match message["role"].as_str() { + Some("assistant") => "model", + Some("user") => "user", + _ => return Err(invalid()), + }; + let mut parts: Vec = Vec::new(); + let mut pending_signature = None; + for block in blocks.iter() { + let mut part = match block["type"].as_str() { + Some("text") => json!({"text":block["text"]}), + Some("image" | "document") => media(&block["source"])?, + Some("thinking") => { + if let Some(raw) = block["signature"] + .as_str() + .and_then(|s| s.strip_prefix(SIGNATURE_PREFIX)) + { + let carrier: Value = serde_json::from_str(raw).map_err(|_| invalid())?; + match carrier["target"].as_str() { + Some("previous") => { + let last = parts.last_mut().ok_or_else(invalid)?; + last["thoughtSignature"] = carrier["signature"].clone(); + continue; + } + Some("next") => { + pending_signature = Some(carrier["signature"].clone()); + continue; + } + Some("thinking") => { + json!({"text":block["thinking"],"thought":true,"thoughtSignature":carrier["signature"]}) + } + _ => return Err(invalid()), + } + } else { + // 没有本协议签名的思考不作为可验证历史回放 + continue; + } + } + Some("redacted_thinking") => continue, + Some("tool_use") => { + let id = block["id"].as_str().ok_or_else(invalid)?; + let name = block["name"].as_str().ok_or_else(invalid)?; + calls.insert(id.to_owned(), name.to_owned()); + if !block["input"].is_object() { + return Err(invalid()); + } + json!({"functionCall":{"id":id,"name":name,"args":block["input"]}}) + } + Some("tool_result") => { + let id = block["tool_use_id"].as_str().ok_or_else(invalid)?; + let name = calls.get(id).ok_or_else(invalid)?; + let output = &block["content"]; + let mut response = + json!({"functionResponse":{"id":id,"name":name,"response":{}}}); + let key = if block["is_error"] == true { + "error" + } else { + "output" + }; + response["functionResponse"]["response"][key] = output.clone(); + response + } + _ => return Err(invalid()), + }; + if part.get("thoughtSignature").is_some_and(Value::is_null) { + part.as_object_mut() + .ok_or_else(invalid)? + .remove("thoughtSignature"); + } + if let Some(signature) = pending_signature.take() { + part["thoughtSignature"] = signature; + } + // Google 为外部历史提供的兜底值;真实签名优先,Chat 等无签名合同无需服务端缓存 + // https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking/thought-signatures + if part.get("functionCall").is_some() && part.get("thoughtSignature").is_none() { + part["thoughtSignature"] = json!("skip_thought_signature_validator"); + } + parts.push(part); + } + if pending_signature.is_some() { + return Err(invalid()); + } + // Chat 工具轮次可带空 content;签名已附着后再删除无内容且无签名的占位 + parts.retain(|part| part["text"] != "" || part.get("thoughtSignature").is_some()); + if !parts.is_empty() { + contents.push(json!({"role":role,"parts":parts})); + } + } + result.insert("contents".into(), json!(contents)); + let mut generation = Map::new(); + for (from, to) in [ + ("max_tokens", "maxOutputTokens"), + ("temperature", "temperature"), + ("top_p", "topP"), + ("top_k", "topK"), + ("stop_sequences", "stopSequences"), + ] { + if let Some(value) = request.get(from) { + generation.insert(to.into(), value.clone()); + } + } + if let Some(thinking) = request.get("thinking") { + match thinking["type"].as_str() { + Some("disabled") => { + generation.insert("thinkingConfig".into(), json!({"thinkingBudget":0})); + } + Some("enabled") => { + generation.insert( + "thinkingConfig".into(), + json!({"thinkingBudget":thinking["budget_tokens"],"includeThoughts":true}), + ); + } + Some("adaptive" | "auto") => { + generation.insert( + "thinkingConfig".into(), + json!({"thinkingBudget":-1,"includeThoughts":true}), + ); + } + _ => return Err(invalid()), + } + } + if let Some(format) = request.get("output_config").and_then(|c| c.get("format")) { + if format["type"] != "json_schema" { + return Err(invalid()); + } + generation.insert("responseMimeType".into(), json!("application/json")); + generation.insert("responseSchema".into(), format["schema"].clone()); + } + result.insert("generationConfig".into(), Value::Object(generation)); + if let Some(tools) = request.get("tools").and_then(Value::as_array) { + let declarations = tools + .iter() + .map(|tool| { + if tool + .get("type") + .and_then(Value::as_str) + .is_some_and(|t| t != "custom") + || !tool["input_schema"].is_object() + { + return Err(invalid()); + } + let mut declaration = + json!({"name":tool["name"],"parametersJsonSchema":tool["input_schema"]}); + if let Some(description) = tool.get("description") { + declaration["description"] = description.clone(); + } + Ok(declaration) + }) + .collect::, _>>()?; + result.insert( + "tools".into(), + json!([{"functionDeclarations":declarations}]), + ); + } + if let Some(choice) = request.get("tool_choice") { + let mode = match choice["type"].as_str() { + Some("auto") => "AUTO", + Some("any" | "tool") => "ANY", + Some("none") => "NONE", + _ => return Err(invalid()), + }; + let mut config = json!({"mode":mode}); + if choice["type"] == "tool" { + config["allowedFunctionNames"] = json!([choice["name"]]); + } + result.insert("toolConfig".into(), json!({"functionCallingConfig":config})); + } + Ok(result) +} + +fn plain_parts(value: &Value) -> Result, TranslationError> { + if let Some(text) = value.as_str() { + return Ok(vec![json!({"text":text})]); + } + value + .as_array() + .ok_or_else(invalid)? + .iter() + .map(|block| { + if block["type"] != "text" { + return Err(invalid()); + } + Ok(json!({"text":block["text"]})) + }) + .collect() +} + +fn media(source: &Value) -> Result { + match source["type"].as_str() { + Some("base64") => { + Ok(json!({"inlineData":{"mimeType":source["media_type"],"data":source["data"]}})) + } + Some("text") => Ok(json!({"text":source["data"]})), + // URL 文件需有明确 MIME 类型;不替客户端下载未知资源 + Some("url") if source["media_type"].is_string() => { + Ok(json!({"fileData":{"mimeType":source["media_type"],"fileUri":source["url"]}})) + } + _ => Err(invalid()), + } +} diff --git a/backend/crates/gateway-protocol/src/genai/mod.rs b/backend/crates/gateway-protocol/src/genai/mod.rs new file mode 100644 index 000000000..ab04a10eb --- /dev/null +++ b/backend/crates/gateway-protocol/src/genai/mod.rs @@ -0,0 +1,20 @@ +//! Google 原生生成协议的请求与响应事实 + +mod request; +mod response; + +pub(crate) use request::{request_facts, thinking_level}; +pub use response::{ + GenerateContentObservation, GenerationFinish, UsageMetadata, has_finish_signal, + primary_text_parts, +}; + +/// Google 原生请求与响应使用同一 wire 标识 +pub const GENAI_PROTOCOL: &str = "genai"; + +mod messages; +mod stream; +mod tokens; +pub use messages::messages_to_genai_request; +pub use stream::GenAiToMessagesStream; +pub use tokens::{count_tokens_request, count_tokens_to_messages}; diff --git a/backend/crates/gateway-protocol/src/genai/request.rs b/backend/crates/gateway-protocol/src/genai/request.rs new file mode 100644 index 000000000..37e3b114c --- /dev/null +++ b/backend/crates/gateway-protocol/src/genai/request.rs @@ -0,0 +1,82 @@ +//! Google 原生请求的能力与思考配置 + +use serde_json::{Map, Value}; + +use crate::capabilities::RequestFacts; + +pub(crate) fn request_facts(body: &Map, facts: &mut RequestFacts) { + let config = generation_config(body); + let formats = field(config, "responseFormat", "response_format").and_then(Value::as_array); + facts.max_output_tokens = + field(config, "maxOutputTokens", "max_output_tokens").and_then(Value::as_u64); + facts.reasoning = thinking_config(body).is_some_and(Value::is_object); + facts.json_schema = field(config, "responseSchema", "response_schema") + .is_some_and(Value::is_object) + || field(config, "responseJsonSchema", "response_json_schema") + .is_some_and(|v| !v.is_null()) + || formats.is_some_and(|formats| { + formats + .iter() + .any(|format| format.pointer("/text/schema").is_some_and(|v| !v.is_null())) + }); + facts.image_generation = field(config, "responseModalities", "response_modalities") + .and_then(Value::as_array) + .is_some_and(|modes| { + modes + .iter() + .any(|mode| mode.as_str() == Some("IMAGE") || mode.as_u64() == Some(2)) + }) + || field(config, "imageConfig", "image_config").is_some_and(Value::is_object) + || formats.is_some_and(|formats| { + formats + .iter() + .any(|format| format.get("image").is_some_and(Value::is_object)) + }); + facts.vision = body + .get("contents") + .and_then(Value::as_array) + .is_some_and(|contents| { + contents + .iter() + .filter_map(|content| content.get("parts")?.as_array()) + .flatten() + .any(|part| { + part_has_image(part) + || field(Some(part), "functionResponse", "function_response") + .and_then(|response| response.get("parts")?.as_array()) + .is_some_and(|parts| parts.iter().any(part_has_image)) + }) + }); +} + +pub(crate) fn thinking_level(body: &Map) -> Option<&str> { + field(thinking_config(body), "thinkingLevel", "thinking_level")? + .as_str() + .map(str::trim) + .filter(|level| !level.is_empty()) +} + +fn generation_config(body: &Map) -> Option<&Value> { + body.get("generationConfig") + .or_else(|| body.get("generation_config")) +} + +fn thinking_config(body: &Map) -> Option<&Value> { + field(generation_config(body), "thinkingConfig", "thinking_config") +} + +fn part_has_image(part: &Value) -> bool { + let blob = field(Some(part), "inlineData", "inline_data") + .or_else(|| field(Some(part), "fileData", "file_data")); + field(blob, "mimeType", "mime_type") + .and_then(Value::as_str) + .is_some_and(|mime| { + mime.get(..6) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case("image/")) + }) +} + +fn field<'a>(value: Option<&'a Value>, json: &str, proto: &str) -> Option<&'a Value> { + let object = value?.as_object()?; + object.get(json).or_else(|| object.get(proto)) +} diff --git a/backend/crates/gateway-protocol/src/genai/response.rs b/backend/crates/gateway-protocol/src/genai/response.rs new file mode 100644 index 000000000..ea5133f47 --- /dev/null +++ b/backend/crates/gateway-protocol/src/genai/response.rs @@ -0,0 +1,186 @@ +//! Google 生成候选的完成条件与累计用量 + +use serde_json::Value; +use std::collections::BTreeMap; + +/// 候选的显式结束原因,proto 默认枚举表示仍未结束 +fn candidate_finish_reason(candidate: &Value) -> Option<&str> { + candidate + .get("finishReason")? + .as_str() + .filter(|reason| !matches!(*reason, "" | "FINISH_REASON_UNSPECIFIED")) +} + +/// 提示在生成首个候选前已被阻止 +fn prompt_is_blocked(value: &Value) -> bool { + value + .pointer("/promptFeedback/blockReason") + .and_then(Value::as_str) + .is_some_and(|reason| !matches!(reason, "" | "BLOCKED_REASON_UNSPECIFIED")) +} + +/// 当前帧携带终止依据时,响应中间件的改写需保留该语义 +/// 整条流能否结束仍由所有候选及 EOF 共同决定 +pub fn has_finish_signal(value: &Value) -> bool { + value.get("error").is_some_and(Value::is_object) + || prompt_is_blocked(value) + || value + .get("candidates") + .and_then(Value::as_array) + .is_some_and(|candidates| { + candidates + .iter() + .any(|candidate| candidate_finish_reason(candidate).is_some()) + }) +} + +/// 管理探测展示第一候选的可见文本,工具参数和思考内容仍只属于原生响应 +pub fn primary_text_parts(value: &Value) -> impl Iterator { + value + .get("candidates") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter(|candidate| { + candidate + .get("index") + .and_then(Value::as_u64) + .unwrap_or_default() + == 0 + }) + .filter_map(|candidate| candidate.pointer("/content/parts")?.as_array()) + .flatten() + .filter(|part| part.get("thought").and_then(Value::as_bool) != Some(true)) + .filter_map(|part| part.get("text")?.as_str()) + .filter(|text| !text.is_empty()) +} + +/// 单个生成请求共有的候选状态与增量用量,不持有消息、签名或工具参数 +#[derive(Default)] +pub struct GenerateContentObservation { + candidates: BTreeMap, + blocked: bool, + usage: UsageMetadata, +} + +#[derive(Default)] +struct Candidate { + tool_call: bool, + reason: Option, +} + +/// Google 的提示阻断和候选完成都能使请求完整结束 +#[derive(Debug, PartialEq, Eq)] +pub enum GenerationFinish<'a> { + Blocked, + Candidate { reason: &'a str, tool_call: bool }, +} + +impl GenerateContentObservation { + /// 更新候选状态,只在本帧提供用量时返回新的累计快照 + pub fn observe(&mut self, value: &Value) -> Option<&UsageMetadata> { + self.blocked |= prompt_is_blocked(value); + for candidate in value + .get("candidates") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + // proto3 允许省略值为零的第一个候选索引 + let index = candidate + .get("index") + .and_then(Value::as_u64) + .unwrap_or_default(); + let state = self.candidates.entry(index).or_default(); + state.tool_call |= candidate + .pointer("/content/parts") + .and_then(Value::as_array) + .is_some_and(|parts| { + parts + .iter() + .any(|part| part.get("functionCall").is_some_and(Value::is_object)) + }); + if let Some(reason) = candidate_finish_reason(candidate) { + state.reason = Some(reason.to_owned()); + } + } + let metadata = value.get("usageMetadata")?.as_object()?; + self.usage.merge(metadata); + Some(&self.usage) + } + + /// 仅在完整 JSON 已读完或 SSE 正常 EOF 时调用 + pub fn finish(&self) -> Option> { + if self.blocked && self.candidates.is_empty() { + return Some(GenerationFinish::Blocked); + } + if self.candidates.values().any(|c| c.reason.is_none()) { + return None; + } + let (_, primary) = self.candidates.first_key_value()?; + Some(GenerationFinish::Candidate { + reason: primary.reason.as_deref()?, + tool_call: primary.tool_call, + }) + } +} + +/// 同一次请求中每个 Google 计数字段均以最近一次显式上报为准 +#[derive(Debug, Default)] +pub struct UsageMetadata { + prompt: Option, + tool_input: Option, + candidates: Option, + prompt_image: Option, + tool_image: Option, + pub thoughts: Option, + pub cached: Option, + pub candidate_image: Option, + pub total: Option, +} + +impl UsageMetadata { + fn merge(&mut self, metadata: &serde_json::Map) { + let count = |key: &str| metadata.get(key).and_then(Value::as_u64); + let images = |key: &str| { + metadata + .get(key)? + .as_array()? + .iter() + .find(|entry| entry.get("modality").and_then(Value::as_str) == Some("IMAGE"))? + .get("tokenCount")? + .as_u64() + }; + + self.prompt = count("promptTokenCount").or(self.prompt); + self.tool_input = count("toolUsePromptTokenCount").or(self.tool_input); + self.candidates = count("candidatesTokenCount").or(self.candidates); + self.thoughts = count("thoughtsTokenCount").or(self.thoughts); + self.cached = count("cachedContentTokenCount").or(self.cached); + self.total = count("totalTokenCount").or(self.total); + self.prompt_image = images("promptTokensDetails").or(self.prompt_image); + self.tool_image = images("toolUsePromptTokensDetails").or(self.tool_image); + self.candidate_image = images("candidatesTokensDetails").or(self.candidate_image); + } + + /// prompt 已包含缓存,工具执行返回的输入另列 + pub fn input_tokens(&self) -> Option { + combined(self.prompt, self.tool_input) + } + + /// Google 将思考与候选输出单独计数 + pub fn output_tokens(&self) -> Option { + combined(self.candidates, self.thoughts) + } + + pub fn image_input_tokens(&self) -> Option { + combined(self.prompt_image, self.tool_image) + } +} + +fn combined(a: Option, b: Option) -> Option { + match (a, b) { + (Some(a), Some(b)) => a.checked_add(b), + _ => a.or(b), + } +} diff --git a/backend/crates/gateway-protocol/src/genai/stream.rs b/backend/crates/gateway-protocol/src/genai/stream.rs new file mode 100644 index 000000000..23cfb7e19 --- /dev/null +++ b/backend/crates/gateway-protocol/src/genai/stream.rs @@ -0,0 +1,203 @@ +//! GenAI 增量帧转为 Messages 事件,终态在上游 EOF 后输出 + +use super::{GenerateContentObservation, GenerationFinish}; +use crate::anthropic::GENAI_CARRIER as SIGNATURE_PREFIX; +use crate::anthropic::TranslationError; +use serde_json::{Value, json}; + +/// 每条上游流独占转换状态;同一文本块跨帧延续,签名和尾部用量不会提前丢弃 +#[derive(Default)] +pub struct GenAiToMessagesStream { + observation: GenerateContentObservation, + model: String, + started: bool, + finished: bool, + index: usize, + usage: Value, + active_thinking: Option, + pending_empty: Option, +} + +impl GenAiToMessagesStream { + /// 上游首帧未附模型版本时使用请求模型,避免交付 null 模型字段 + pub fn new(model: impl Into) -> Self { + Self { + model: model.into(), + ..Self::default() + } + } + + /// 消费已解开 Cloud Code 外层的原生响应 + pub fn push(&mut self, value: &Value) -> Result, TranslationError> { + if self.finished { + return Err(TranslationError::InvalidEvent( + "The GenAI stream has already ended.", + )); + } + let mut events = Vec::new(); + if !self.started { + self.started = true; + let id = value["responseId"] + .as_str() + .map(str::to_owned) + .unwrap_or_else(|| format!("msg_{}", uuid::Uuid::new_v4())); + events.push(json!({"type":"message_start","message":{"id":id,"type":"message","role":"assistant","model":value["modelVersion"].as_str().unwrap_or(&self.model),"content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}}})); + } + if let Some(usage) = self.observation.observe(value) { + self.usage = json!({"input_tokens":usage.input_tokens().unwrap_or_default().saturating_sub(usage.cached.unwrap_or_default()),"cache_read_input_tokens":usage.cached.unwrap_or_default(),"output_tokens":usage.output_tokens().unwrap_or_default()}); + } + for candidate in value["candidates"].as_array().into_iter().flatten() { + if candidate["index"].as_u64().unwrap_or_default() != 0 { + return Err(TranslationError::InvalidEvent( + "Multiple GenAI candidates cannot be translated to a single message.", + )); + } + for part in candidate["content"]["parts"] + .as_array() + .into_iter() + .flatten() + { + self.part(part, &mut events)?; + } + } + Ok(events) + } + + fn part(&mut self, part: &Value, events: &mut Vec) -> Result<(), TranslationError> { + let signature = part.get("thoughtSignature"); + if let Some(call) = part.get("functionCall") { + self.pending_empty = None; + self.close(None, events); + if let Some(signature) = signature { + self.carrier(signature, "next", events); + } + let id = call["id"] + .as_str() + .map(str::to_owned) + .unwrap_or_else(|| format!("call_{}", uuid::Uuid::new_v4())); + let index = self.index; + self.index += 1; + events.push(json!({"type":"content_block_start","index":index,"content_block":{"type":"tool_use","id":id,"name":call["name"],"input":{}}})); + events.push(json!({"type":"content_block_delta","index":index,"delta":{"type":"input_json_delta","partial_json":call.get("args").unwrap_or(&json!({})).to_string()}})); + events.push(json!({"type":"content_block_stop","index":index})); + } else if let Some(text) = part.get("text").and_then(Value::as_str) { + let thinking = part["thought"] == true; + if text.is_empty() && signature.is_none() { + // 空占位仅在后续携带签名时保留,避免 Claude 历史回放被空 text 拒绝 + if self.active_thinking.is_none() { + self.pending_empty = Some(thinking); + } + return Ok(()); + } + self.pending_empty = None; + self.text(thinking, text, events); + if let Some(signature) = signature { + self.signature(signature, events); + } + } else if let Some(signature) = signature { + if self.active_thinking.is_none() + && let Some(thinking) = self.pending_empty.take() + { + self.text(thinking, "", events); + } + self.signature(signature, events); + } else { + return Err(TranslationError::InvalidEvent( + "The GenAI response contains unsupported content.", + )); + } + Ok(()) + } + + fn text(&mut self, thinking: bool, text: &str, events: &mut Vec) { + if self + .active_thinking + .is_some_and(|active| active != thinking) + { + self.close(None, events); + } + if self.active_thinking.is_none() { + let block = if thinking { + json!({"type":"thinking","thinking":"","signature":""}) + } else { + json!({"type":"text","text":""}) + }; + events.push( + json!({"type":"content_block_start","index":self.index,"content_block":block}), + ); + self.index += 1; + self.active_thinking = Some(thinking); + } + if !text.is_empty() { + let mut delta = json!({"type":if thinking {"thinking_delta"} else {"text_delta"}}); + delta[if thinking { "thinking" } else { "text" }] = json!(text); + events.push(json!({"type":"content_block_delta","index":self.index-1,"delta":delta})); + } + } + + fn signature(&mut self, signature: &Value, events: &mut Vec) { + match self.active_thinking { + Some(true) => self.close(Some(signature), events), + // 普通文本签名不强制回传;追加空思考载体或拆分正文会使 Claude Code + // 的最终 result 为空或只有末段;保持正文连续,原生入口仍完整透传签名 + Some(false) => {} + None => self.carrier(signature, "previous", events), + } + } + + fn close(&mut self, signature: Option<&Value>, events: &mut Vec) { + let Some(thinking) = self.active_thinking.take() else { + return; + }; + let index = self.index - 1; + if thinking { + events.push(json!({"type":"content_block_delta","index":index,"delta":{"type":"signature_delta","signature":carrier(signature.unwrap_or(&Value::Null),"thinking")}})); + } + events.push(json!({"type":"content_block_stop","index":index})); + } + + /// 只有上游正常 EOF 且存在完成信号时才发出完成事件 + pub fn finish(&mut self) -> Result, TranslationError> { + if self.finished { + return Err(TranslationError::IncompleteStream); + } + let reason = match self + .observation + .finish() + .ok_or(TranslationError::IncompleteStream)? + { + GenerationFinish::Blocked => "refusal", + GenerationFinish::Candidate { + reason: "MAX_TOKENS", + .. + } => "max_tokens", + GenerationFinish::Candidate { + reason: "STOP" | "OTHER", + tool_call: true, + } => "tool_use", + GenerationFinish::Candidate { reason: "STOP", .. } => "end_turn", + GenerationFinish::Candidate { .. } => "refusal", + }; + self.finished = true; + let mut events = Vec::new(); + self.close(None, &mut events); + events.push(json!({"type":"message_delta","delta":{"stop_reason":reason,"stop_sequence":null},"usage":self.usage})); + events.push(json!({"type":"message_stop"})); + Ok(events) + } + + fn carrier(&mut self, signature: &Value, target: &str, events: &mut Vec) { + let index = self.index; + self.index += 1; + events.push(json!({"type":"content_block_start","index":index,"content_block":{"type":"thinking","thinking":"","signature":""}})); + events.push(json!({"type":"content_block_delta","index":index,"delta":{"type":"signature_delta","signature":carrier(signature,target)}})); + events.push(json!({"type":"content_block_stop","index":index})); + } +} + +fn carrier(signature: &Value, target: &str) -> String { + format!( + "{SIGNATURE_PREFIX}{}", + json!({"signature":signature,"target":target}) + ) +} diff --git a/backend/crates/gateway-protocol/src/genai/tokens.rs b/backend/crates/gateway-protocol/src/genai/tokens.rs new file mode 100644 index 000000000..e042159b6 --- /dev/null +++ b/backend/crates/gateway-protocol/src/genai/tokens.rs @@ -0,0 +1,27 @@ +//! GenAI 输入计数的请求封装和跨协议结果投影 + +use crate::anthropic::TranslationError; +use serde_json::{Map, Value, json}; + +/// 完整生成请求存在时,以它作为计数输入,外层 contents 不参与计数 +pub fn count_tokens_request( + request: &Map, +) -> Result<&Map, TranslationError> { + match request + .get("generateContentRequest") + .or_else(|| request.get("generate_content_request")) + { + Some(value) => value.as_object().ok_or(TranslationError::InvalidRequest( + "generateContentRequest must be a JSON object.", + )), + None => Ok(request), + } +} + +/// 只投影上游明确给出的计数,不把缺失或无效结果当作零 +pub fn count_tokens_to_messages(response: &Value) -> Result { + let tokens = response.get("totalTokens").and_then(Value::as_u64).ok_or( + TranslationError::InvalidEvent("The upstream token count is invalid."), + )?; + Ok(json!({"input_tokens":tokens})) +} diff --git a/backend/crates/gateway-protocol/src/lib.rs b/backend/crates/gateway-protocol/src/lib.rs index c4f7b02c8..b32f21c9e 100644 --- a/backend/crates/gateway-protocol/src/lib.rs +++ b/backend/crates/gateway-protocol/src/lib.rs @@ -2,9 +2,14 @@ //! //! 本 crate 只处理 wire contract,不包含 Provider 认证、路由、重试或传输策略 +mod capabilities; + /// OpenAI wire contract pub mod openai; +/// Google GenAI 原生生成协议 +pub mod genai; + /// Anthropic Messages 与 Responses 的线协议转换 pub mod anthropic; diff --git a/backend/crates/gateway-protocol/src/request.rs b/backend/crates/gateway-protocol/src/request.rs index e673cc16b..54797a52e 100644 --- a/backend/crates/gateway-protocol/src/request.rs +++ b/backend/crates/gateway-protocol/src/request.rs @@ -2,7 +2,10 @@ use serde_json::{Map, Value}; +pub use crate::capabilities::RequestFacts; + use crate::anthropic::{ANTHROPIC_PROTOCOL, messages_request_effort}; +use crate::genai::{self, GENAI_PROTOCOL}; use crate::openai::{OPENAI_PROTOCOL, codex_responses_request_semantics_with_turn_metadata}; /// 与执行 Provider 无关的逻辑请求观测 @@ -47,29 +50,14 @@ pub fn request_observation( reasoning_effort: messages_request_effort(body).map(str::to_owned), ..RequestObservation::default() }, + GENAI_PROTOCOL => RequestObservation { + reasoning_effort: genai::thinking_level(body).map(str::to_ascii_lowercase), + ..RequestObservation::default() + }, _ => RequestObservation::default(), } } -/// 请求正文表达的能力要求 -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct RequestFacts { - /// 显式输出预算 - pub max_output_tokens: Option, - /// 工具声明 - pub tools: bool, - /// 图片输入 - pub vision: bool, - /// 图片生成工具声明 - pub image_generation: bool, - /// 推理配置 - pub reasoning: bool, - /// JSON Schema 输出 - pub json_schema: bool, - /// 原生服务端续接 - pub native_continuation: bool, -} - /// 按协议提取能力事实,未知协议保留空事实供其 owner 补齐 #[must_use] pub fn request_facts(protocol: &str, body: &Map) -> RequestFacts { @@ -115,6 +103,7 @@ pub fn request_facts(protocol: &str, body: &Map) -> RequestFacts .and_then(Value::as_str) == Some("json_schema"); } + GENAI_PROTOCOL => genai::request_facts(body, &mut facts), _ => {} } facts diff --git a/backend/crates/gateway-protocol/tests/genai/messages.rs b/backend/crates/gateway-protocol/tests/genai/messages.rs new file mode 100644 index 000000000..39ab8705f --- /dev/null +++ b/backend/crates/gateway-protocol/tests/genai/messages.rs @@ -0,0 +1,238 @@ +//! 验证转换路径的工具往返、多模态输入和签名来源 + +use gateway_protocol::{ + anthropic::{ + MessagesAccumulator, MessagesModelCapabilities, MessagesToResponsesStream, + responses_to_messages_request, + }, + genai::{GenAiToMessagesStream, messages_to_genai_request}, +}; +use serde_json::{Value, json}; + +#[test] +fn signed_tool_roundtrip_preserves_custom_identity_and_final_usage() { + let original = + json!({"model":"fixture","input":"Use patch","tools":[{"type":"custom","name":"patch"}]}); + let mut native = GenAiToMessagesStream::default(); + let mut responses = MessagesToResponsesStream::new(original.as_object().unwrap()); + let first = json!({"responseId":"r","candidates":[{"content":{"parts":[{"functionCall":{"name":"patch","args":{"input":"abc"}},"thoughtSignature":"opaque-signature"}]},"finishReason":"STOP"}]}); + let mut emitted = Vec::new(); + for event in native.push(&first).unwrap() { + emitted.extend(responses.push(&event).unwrap()); + } + assert!(!emitted.iter().any(|e| e["type"] == "response.completed")); + for event in native.push(&json!({"usageMetadata":{"promptTokenCount":10,"cachedContentTokenCount":4,"candidatesTokenCount":3,"thoughtsTokenCount":2}})).unwrap().into_iter().chain(native.finish().unwrap()) { + emitted.extend(responses.push(&event).unwrap()); + } + let response = &emitted.last().unwrap()["response"]; + assert_eq!(response["usage"]["input_tokens"], 10); + assert_eq!(response["usage"]["output_tokens"], 5); + let mut input = response["output"].as_array().unwrap().clone(); + let call = input + .iter() + .find(|e| e["type"] == "custom_tool_call") + .unwrap(); + assert_eq!(call["input"], "abc"); + let call_id = call["call_id"].clone(); + input.push(json!({"type":"custom_tool_call_output","call_id":call_id,"output":"done"})); + let next = json!({"model":"fixture","input":input,"tools":original["tools"]}); + let messages = responses_to_messages_request( + next.as_object().unwrap(), + &MessagesModelCapabilities::default(), + ) + .unwrap(); + let request = messages_to_genai_request(&messages).unwrap(); + let call = &request["contents"][0]["parts"][0]; + assert_eq!(call["thoughtSignature"], "opaque-signature"); + assert_eq!(call["functionCall"]["name"], "patch"); + assert_eq!( + request["contents"][1]["parts"][0]["functionResponse"]["name"], + "patch" + ); +} + +#[test] +fn messages_replay_keeps_late_signatures_and_rejects_incomplete_stream() { + let mut native = GenAiToMessagesStream::default(); + let mut messages = MessagesAccumulator::default(); + for frame in [ + json!({"candidates":[{"content":{"parts":[{"text":"reason","thought":true}]}}]}), + json!({"candidates":[{"content":{"parts":[{"thoughtSignature":"late"},{"text":"answer"}]},"finishReason":"STOP"}]}), + ] { + for event in native.push(&frame).unwrap() { + messages.push(&event).unwrap(); + } + } + let mut complete = None; + for event in native.finish().unwrap() { + complete = messages.push(&event).unwrap().or(complete); + } + let complete = complete.unwrap(); + let request = json!({"messages":[{"role":"assistant","content":complete["content"]}]}); + let body = messages_to_genai_request(request.as_object().unwrap()).unwrap(); + assert_eq!(body["contents"][0]["parts"][0]["thoughtSignature"], "late"); + assert_eq!(body["contents"][0]["parts"][0]["text"], "reason"); + let mut incomplete = GenAiToMessagesStream::default(); + incomplete + .push(&json!({"candidates":[{"content":{"parts":[{"text":"partial"}]}}]})) + .unwrap(); + assert!(incomplete.finish().is_err()); +} + +#[test] +fn maps_system_images_schema_and_forced_tools_without_dropping_unknown_content() { + let request = json!({"system":"system","messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"image"}}]}],"tools":[{"name":"lookup","input_schema":{"type":"object"}}],"tool_choice":{"type":"tool","name":"lookup"},"output_config":{"format":{"type":"json_schema","schema":{"type":"object"}}}}); + let body = messages_to_genai_request(request.as_object().unwrap()).unwrap(); + assert_eq!( + body["contents"][0]["parts"][0]["inlineData"]["mimeType"], + "image/png" + ); + assert_eq!( + body["toolConfig"]["functionCallingConfig"]["allowedFunctionNames"], + json!(["lookup"]) + ); + assert_eq!( + body["generationConfig"]["responseMimeType"], + "application/json" + ); + assert_eq!( + body["generationConfig"]["responseSchema"], + json!({"type":"object"}) + ); + let invalid = json!({"messages":[{"role":"user","content":[{"type":"unknown"}]}]}); + assert!(messages_to_genai_request(invalid.as_object().unwrap()).is_err()); + let _: Value = request; +} + +#[test] +fn merges_text_frames_and_omits_unsigned_empty_tool_placeholders() { + let mut stream = GenAiToMessagesStream::default(); + let mut messages = MessagesAccumulator::default(); + for frame in [ + json!({"candidates":[{"content":{"parts":[{"text":"first "}]}}]}), + json!({"candidates":[{"content":{"parts":[{"text":"second"},{"thoughtSignature":"text-signature"},{"text":""}]}}]}), + json!({"candidates":[{"content":{"parts":[{"functionCall":{"id":"call","name":"lookup","args":{}}},{"text":""}]},"finishReason":"OTHER"}]}), + ] { + for event in stream.push(&frame).unwrap() { + messages.push(&event).unwrap(); + } + } + let mut complete = None; + for event in stream.finish().unwrap() { + complete = messages.push(&event).unwrap().or(complete); + } + let complete = complete.unwrap(); + assert_eq!(complete["stop_reason"], "tool_use"); + assert_eq!(complete["content"][0]["text"], "first second"); + let request = json!({"messages":[{"role":"assistant","content":complete["content"]}]}); + let native = messages_to_genai_request(request.as_object().unwrap()).unwrap(); + let parts = native["contents"][0]["parts"].as_array().unwrap(); + assert_eq!(parts.len(), 2); + assert!(parts[0].get("thoughtSignature").is_none()); + assert_eq!(parts[1]["functionCall"]["name"], "lookup"); +} + +#[test] +fn visible_text_streams_as_one_block_without_a_trailing_signature_carrier() { + for late in [false, true] { + let mut stream = GenAiToMessagesStream::default(); + let mut accumulator = MessagesAccumulator::default(); + let mut events = stream + .push(&json!({"candidates":[{"content":{"parts":[{"text":"first "}]}}]})) + .unwrap(); + assert!( + events + .iter() + .any(|event| event["delta"]["text"] == "first ") + ); + let mut part = json!({"text":"answer"}); + if !late { + part["thoughtSignature"] = json!("opaque"); + } + events.extend( + stream + .push(&json!({"candidates":[{"content":{"parts":[part]}}]})) + .unwrap(), + ); + if late { + events.extend(stream.push(&json!({"candidates":[{"content":{"parts":[{"thoughtSignature":"opaque"}]}}]})).unwrap()); + } + events.extend( + stream + .push(&json!({"candidates":[{"finishReason":"STOP"}]})) + .unwrap(), + ); + events.extend(stream.finish().unwrap()); + let mut complete = None; + for event in events { + complete = accumulator.push(&event).unwrap().or(complete); + } + let complete = complete.unwrap(); + assert_eq!( + complete["content"], + json!([{"type":"text","text":"first answer"}]) + ); + let request = json!({"messages":[{"role":"assistant","content":complete["content"]}]}); + let native = messages_to_genai_request(request.as_object().unwrap()).unwrap(); + assert_eq!( + native["contents"][0]["parts"], + json!([{"text":"first answer"}]) + ); + } +} + +#[test] +fn native_signature_carriers_do_not_reach_anthropic_upstreams() { + let mut request = json!({"messages":[{"role":"assistant","content":[ + {"type":"thinking","thinking":"private","signature":"cpr:genai:v1:{}"}, + {"type":"thinking","thinking":"native","signature":"anthropic-signature"}, + {"type":"text","text":"visible"} + ]}]}) + .as_object() + .unwrap() + .clone(); + gateway_protocol::anthropic::strip_foreign_thinking_for_messages(&mut request); + assert_eq!( + request["messages"][0]["content"].as_array().unwrap().len(), + 2 + ); + assert_eq!( + request["messages"][0]["content"][0]["signature"], + "anthropic-signature" + ); +} + +#[test] +fn unsigned_tool_history_uses_documented_fallback_without_a_signature_cache() { + let request = json!({"messages":[ + {"role":"assistant","content":[{"type":"text","text":""},{"type":"tool_use","id":"call","name":"lookup","input":{}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"call","content":"value"}]} + ]}); + let native = messages_to_genai_request(request.as_object().unwrap()).unwrap(); + assert_eq!( + native["contents"][0]["parts"][0]["thoughtSignature"], + "skip_thought_signature_validator" + ); + assert_eq!( + native["contents"][1]["parts"][0]["functionResponse"]["id"], + "call" + ); +} + +#[test] +fn empty_client_placeholders_do_not_change_message_roles_or_system_content() { + let request = json!({"system":"instructions","messages":[ + {"role":"user","content":"hello"},{"role":"system","content":[]} + ]}); + let native = messages_to_genai_request(request.as_object().unwrap()).unwrap(); + assert_eq!( + native["contents"], + json!([{"role":"user","parts":[{"text":"hello"}]}]) + ); + assert_eq!( + native["systemInstruction"]["parts"][0]["text"], + "instructions" + ); + let invalid = json!({"messages":[{"role":"system","content":"instructions"}]}); + assert!(messages_to_genai_request(invalid.as_object().unwrap()).is_err()); +} diff --git a/backend/crates/gateway-protocol/tests/genai/mod.rs b/backend/crates/gateway-protocol/tests/genai/mod.rs new file mode 100644 index 000000000..344dd193b --- /dev/null +++ b/backend/crates/gateway-protocol/tests/genai/mod.rs @@ -0,0 +1,6 @@ +//! 验证 Google 原生响应语义 + +mod response; +mod tokens; + +mod messages; diff --git a/backend/crates/gateway-protocol/tests/genai/response.rs b/backend/crates/gateway-protocol/tests/genai/response.rs new file mode 100644 index 000000000..b5066da78 --- /dev/null +++ b/backend/crates/gateway-protocol/tests/genai/response.rs @@ -0,0 +1,112 @@ +//! 验证生成响应、多候选 SSE 以及计量尾帧的真实协议语义 + +use gateway_protocol::{ + genai::{GenerateContentObservation, GenerationFinish, has_finish_signal, primary_text_parts}, + openai::sse::SseEventDecoder, +}; +use serde_json::{Value, json}; + +#[test] +fn json_generation_counts_cached_and_thought_tokens_once() { + let response = json!({ + "candidates": [{"finishReason": "MAX_TOKENS"}], + "usageMetadata": { + "promptTokenCount": 100, "cachedContentTokenCount": 40, "toolUsePromptTokenCount": 7, + "thoughtsTokenCount": 9, "candidatesTokenCount": 11, "totalTokenCount": 127, + "promptTokensDetails": [{"modality": "IMAGE", "tokenCount": 8}], + "toolUsePromptTokensDetails": [{"modality": "IMAGE", "tokenCount": 5}] + } + }); + let mut observation = GenerateContentObservation::default(); + let usage = observation.observe(&response).expect("响应携带用量"); + assert_eq!( + ( + usage.input_tokens(), + usage.cached, + usage.image_input_tokens() + ), + (Some(107), Some(40), Some(13)) + ); + assert_eq!( + (usage.output_tokens(), usage.thoughts, usage.total), + (Some(20), Some(9), Some(127)) + ); + assert_eq!( + observation.finish(), + Some(GenerationFinish::Candidate { + reason: "MAX_TOKENS", + tool_call: false + }) + ); +} + +#[test] +fn clean_stream_keeps_tool_signature_and_usage_after_both_candidates_finish() { + let frames: &[&[u8]] = &[ + b":heartbeat\r\n\r\n", + br#"data: { "candidates": [{"content":{"parts":[{"functionCall":{"name":"lookup","args":{}},"thoughtSignature":"AA=="}]}},{"index":1,"content":{"parts":[{"text":"hi"}]}}],"usageMetadata":{"thoughtsTokenCount":3} } + +"#, + b"data: {\"candidates\":[{\"finishReason\":\"STOP\"}]}\n\n", + b"data: {\"candidates\":[{\"index\":1,\"finishReason\":\"MAX_TOKENS\"}]}\n\n", + b"data: {\"usageMetadata\":{\"candidatesTokenCount\":7,\"totalTokenCount\":10}}\n\n", + ]; + let bytes = frames.concat(); + let mut decoder = SseEventDecoder::default(); + let mut observation = GenerateContentObservation::default(); + let mut delivered = Vec::new(); + let mut last_total = None; + for frame in bytes.chunks(7).flat_map(|bytes| decoder.push_frames(bytes)) { + delivered.extend_from_slice(frame.raw()); + for event in frame.events() { + let value: Value = serde_json::from_str(&event.data).expect("原生 SSE JSON"); + if let Some(usage) = observation.observe(&value) { + last_total = Some((usage.output_tokens(), usage.total)); + } + if value + .pointer("/candidates/0/finishReason") + .and_then(Value::as_str) + == Some("STOP") + { + assert_eq!(observation.finish(), None, "第二个候选尚未结束"); + } + } + } + assert!(decoder.finish_frames().is_empty()); + assert_eq!(delivered, bytes); + assert_eq!(last_total, Some((Some(10), Some(10)))); + assert_eq!( + observation.finish(), + Some(GenerationFinish::Candidate { + reason: "STOP", + tool_call: true + }) + ); +} + +#[test] +fn incomplete_candidates_and_blocked_prompts_have_different_outcomes() { + let mut incomplete = GenerateContentObservation::default(); + incomplete.observe(&json!({"candidates":[{"content":{"parts":[{"text":"partial"}]},"finishReason":"FINISH_REASON_UNSPECIFIED"},{"index":1,"finishReason":"STOP"}]})); + assert_eq!(incomplete.finish(), None); + let mut blocked = GenerateContentObservation::default(); + let response = json!({"promptFeedback":{"blockReason":"SAFETY"}}); + blocked.observe(&response); + assert!(has_finish_signal(&response)); + assert_eq!(blocked.finish(), Some(GenerationFinish::Blocked)); + assert!(!has_finish_signal( + &json!({"usageMetadata":{"totalTokenCount":2}}) + )); + assert!(has_finish_signal( + &json!({"error":{"code":429,"message":"Throttled."}}) + )); +} + +#[test] +fn probe_shows_visible_primary_text_without_leaking_thoughts_or_tool_payloads() { + let response = json!({"candidates":[ + {"content":{"parts":[{"thought":true,"text":"private"},{"text":"P"},{"functionCall":{"args":{"text":"private"}},"thoughtSignature":"AA=="},{"text":"ONG"}]}}, + {"index":1,"content":{"parts":[{"text":"alternative"}]}} + ]}); + assert_eq!(primary_text_parts(&response).collect::(), "PONG"); +} diff --git a/backend/crates/gateway-protocol/tests/genai/tokens.rs b/backend/crates/gateway-protocol/tests/genai/tokens.rs new file mode 100644 index 000000000..b3bd83842 --- /dev/null +++ b/backend/crates/gateway-protocol/tests/genai/tokens.rs @@ -0,0 +1,38 @@ +//! 原生完整请求优先级和 Messages 计数投影合同 + +use gateway_protocol::genai::{count_tokens_request, count_tokens_to_messages}; +use serde_json::json; + +#[test] +fn full_request_wins_over_outer_contents_and_keeps_tools() { + let full = json!({"model":"models/gemini","contents":[],"systemInstruction":{"parts":[{"text":"identity"}]},"tools":[{"functionDeclarations":[]} ]}); + for key in ["generateContentRequest", "generate_content_request"] { + let body = json!({key:full,"contents":[{"parts":[{"text":"ignored"}]}]}); + assert_eq!( + count_tokens_request(body.as_object().unwrap()).unwrap(), + full.as_object().unwrap() + ); + } + assert!( + count_tokens_request(json!({"generateContentRequest":null}).as_object().unwrap()).is_err() + ); +} + +#[test] +fn messages_count_never_estimates_or_invents_zero() { + assert_eq!( + count_tokens_to_messages(&json!({"totalTokens":0})).unwrap(), + json!({"input_tokens":0}) + ); + assert_eq!( + count_tokens_to_messages(&json!({"totalTokens":77,"future":true})).unwrap(), + json!({"input_tokens":77}) + ); + for invalid in [ + json!({}), + json!({"totalTokens":-1}), + json!({"totalTokens":"77"}), + ] { + assert!(count_tokens_to_messages(&invalid).is_err()); + } +} diff --git a/backend/crates/gateway-protocol/tests/main.rs b/backend/crates/gateway-protocol/tests/main.rs index 7ce8120df..1ac5d8eec 100644 --- a/backend/crates/gateway-protocol/tests/main.rs +++ b/backend/crates/gateway-protocol/tests/main.rs @@ -1,5 +1,6 @@ //! 共享协议解析与编码的测试入口 mod anthropic; +mod genai; mod openai; mod request; diff --git a/backend/crates/gateway-protocol/tests/request.rs b/backend/crates/gateway-protocol/tests/request.rs index c3b277578..d1bad20ad 100644 --- a/backend/crates/gateway-protocol/tests/request.rs +++ b/backend/crates/gateway-protocol/tests/request.rs @@ -94,3 +94,42 @@ fn messages_request_observation_preserves_explicit_effort_without_inventing_defa ); } } + +#[test] +fn genai_native_fields_preserve_tool_arguments_and_separate_vision_from_image_generation() { + let body = json!({ + "tools": [{"functionDeclarations": [{"name": "lookup"}]}], + "contents": [{"role": "user", "parts": [{ + "functionResponse": { + "parts": [{"inlineData": {"mimeType": "image/png", "data": "AA=="}}], + "response": {"responseFormat": [{"image": {}}]} + } + }]}], + "generationConfig": { + "maxOutputTokens": 128, + "responseFormat": [{"text":{"schema":{"type":"object"}}}], + "thinkingConfig": {"thinkingLevel":"HIGH"} + } + }); + let body = body.as_object().expect("请求正文"); + let facts = request_facts("genai", body); + assert_eq!(facts.max_output_tokens, Some(128)); + assert!(facts.tools && facts.vision && facts.reasoning && facts.json_schema); + assert!(!facts.image_generation && !facts.native_continuation); + assert_eq!( + request_observation("genai", body, &Map::new(), None) + .reasoning_effort + .as_deref(), + Some("high") + ); + + for config in [ + json!({"response_modalities": ["TEXT", "IMAGE"]}), + json!({"responseModalities": [2]}), + json!({"response_format":[{"image":{}}]}), + json!({"image_config":{}}), + ] { + let body = json!({"generation_config": config}); + assert!(request_facts("genai", body.as_object().expect("请求正文")).image_generation); + } +} diff --git a/backend/crates/gateway-store/src/admin_adapter.rs b/backend/crates/gateway-store/src/admin_adapter.rs index adf986251..fa7724f11 100644 --- a/backend/crates/gateway-store/src/admin_adapter.rs +++ b/backend/crates/gateway-store/src/admin_adapter.rs @@ -110,9 +110,9 @@ impl SettingsStore for AdminSettingsStoreAdapter { "openai_guardian_reserved_concurrency".to_owned(), "openai_oauth_guardian_review_model".to_owned(), "openai_request_country".to_owned(), - "openai_account_affinity".to_owned(), + "account_affinity".to_owned(), "max_account_rotations".to_owned(), - "openai_session_affinity_ttl_hours".to_owned(), + "session_affinity_ttl_hours".to_owned(), "responses_max_decompressed_body_bytes".to_owned(), "rotation_strategy".to_owned(), "smart_scheduling_json".to_owned(), diff --git a/backend/crates/gateway-store/src/postgres/backup.rs b/backend/crates/gateway-store/src/postgres/backup.rs index e2b11b749..53a0d2bc1 100644 --- a/backend/crates/gateway-store/src/postgres/backup.rs +++ b/backend/crates/gateway-store/src/postgres/backup.rs @@ -60,6 +60,10 @@ impl BackupRepository for PgBackupRepository { })?; let result: AdminStoreResult<_> = async { let current = lock_settings_in_transaction(&mut transaction).await?; + require_storage_revision(¤t, command.storage_revision)?; + if current.secret_access_key.is_none() && command.secret_access_key.is_none() { + return Err(store_invalid("missing backup storage secret")); + } let mut changed = storage_changed_fields(¤t, &command); if changed.is_empty() { let revision: i64 = @@ -162,6 +166,17 @@ impl BackupRepository for PgBackupRepository { store_unavailable("begin backup schedule update").with_source(source) })?; let result = async { + if command.schedule_enabled { + let current = lock_settings_in_transaction(&mut transaction).await?; + require_storage_revision(¤t, command.storage_revision)?; + if !current.storage_verified() { + return Err(AdminStoreError::new( + AdminStoreErrorKind::Conflict, + "backup storage", + "storage has not been verified", + )); + } + } sqlx::query( "update backup_settings set schedule_enabled = $1, @@ -830,6 +845,17 @@ async fn ensure_storage_identity_stable( Ok(()) } +fn require_storage_revision(current: &BackupSettings, expected: u64) -> AdminStoreResult<()> { + if current.storage_revision != expected { + return Err(AdminStoreError::new( + AdminStoreErrorKind::StaleRevision, + "backup storage", + "storage revision changed", + )); + } + Ok(()) +} + fn storage_changed_fields( current: &BackupSettings, command: &UpdateBackupStorageCommand, diff --git a/backend/crates/gateway-store/src/postgres/client_budget_buffer.rs b/backend/crates/gateway-store/src/postgres/client_budgets/buffer.rs similarity index 99% rename from backend/crates/gateway-store/src/postgres/client_budget_buffer.rs rename to backend/crates/gateway-store/src/postgres/client_budgets/buffer.rs index 9ddc7c2bf..316e9c47f 100644 --- a/backend/crates/gateway-store/src/postgres/client_budget_buffer.rs +++ b/backend/crates/gateway-store/src/postgres/client_budgets/buffer.rs @@ -17,7 +17,7 @@ use gateway_core::{ }; use tokio::sync::Notify; -use super::{PgClientBudgetStore, client_budgets::unavailable}; +use super::{PgClientBudgetStore, store::unavailable}; const DEFAULT_PENDING_CAPACITY: NonZeroUsize = NonZeroUsize::new(4_096).expect("non-zero queue capacity"); diff --git a/backend/crates/gateway-store/src/postgres/client_budgets/mod.rs b/backend/crates/gateway-store/src/postgres/client_budgets/mod.rs new file mode 100644 index 000000000..7116a7b75 --- /dev/null +++ b/backend/crates/gateway-store/src/postgres/client_budgets/mod.rs @@ -0,0 +1,9 @@ +//! 客户端预算的持久化、窗口变更与有界结算队列入口 + +mod buffer; +mod store; +pub(super) mod windows; + +pub use buffer::{BufferedClientBudgetStore, ClientBudgetWriter}; +pub use store::PgClientBudgetStore; +pub(super) use store::{load_client_key_budgets, read_client_key_budgets, reset_client_key_budget}; diff --git a/backend/crates/gateway-store/src/postgres/client_budgets.rs b/backend/crates/gateway-store/src/postgres/client_budgets/store.rs similarity index 97% rename from backend/crates/gateway-store/src/postgres/client_budgets.rs rename to backend/crates/gateway-store/src/postgres/client_budgets/store.rs index 924d61323..91ff43b98 100644 --- a/backend/crates/gateway-store/src/postgres/client_budgets.rs +++ b/backend/crates/gateway-store/src/postgres/client_budgets/store.rs @@ -23,7 +23,7 @@ use sqlx::{PgPool, Postgres, Row, Transaction, postgres::PgRow}; use crate::{StoreError, StoreResult, mutation_audit, postgres_unavailable}; -pub(super) async fn reset_client_key_budget( +pub(in crate::postgres) async fn reset_client_key_budget( pool: &PgPool, command: ResetClientKeyBudget, origin: ClientKeyBudgetMutationOrigin, @@ -37,7 +37,7 @@ pub(super) async fn reset_client_key_budget( ) })?, ClientKeyBudgetMutationOrigin::Plugin(owner) => { - super::plugins::begin_plugin_mutation(pool, owner).await? + crate::postgres::plugins::begin_plugin_mutation(pool, owner).await? } }; reset_client_key_budget_in_transaction(&mut tx, &command, context) @@ -117,7 +117,7 @@ async fn reset_client_key_budget_in_transaction( "weekly_end".to_owned(), ]); } - super::append_admin_audit_event_in_transaction( + crate::postgres::append_admin_audit_event_in_transaction( tx, mutation_audit( context, @@ -151,7 +151,7 @@ impl PgClientBudgetStore { self } - pub(super) async fn admit_with_pending( + pub(in crate::postgres) async fn admit_with_pending( &self, key_id: ClientApiKeyId, pending: &[ClientBudgetCharge], @@ -311,7 +311,7 @@ impl PgClientBudgetStore { Ok(()) } - pub(super) async fn settle_charges( + pub(in crate::postgres) async fn settle_charges( &self, charges: &[ClientBudgetCharge], ) -> Result<(), ClientBudgetError> { @@ -447,9 +447,9 @@ async fn advance_windows( Ok(()) } -pub(super) async fn load_client_key_budgets( +pub(in crate::postgres) async fn load_client_key_budgets( pool: &PgPool, - records: &mut [super::ClientApiKeyRecord], + records: &mut [crate::postgres::ClientApiKeyRecord], ) -> StoreResult<()> { if records.is_empty() { return Ok(()); @@ -472,7 +472,7 @@ pub(super) async fn load_client_key_budgets( Ok(()) } -pub(super) async fn read_client_key_budgets( +pub(in crate::postgres) async fn read_client_key_budgets( pool: &PgPool, ids: &[&str], ) -> StoreResult> { @@ -525,7 +525,7 @@ pub(super) async fn read_client_key_budgets( Ok(budgets) } -pub(super) fn stored_window( +pub(in crate::postgres) fn stored_window( row: &PgRow, start: &str, end: &str, @@ -538,7 +538,7 @@ pub(super) fn stored_window( }) } -pub(super) fn unavailable() -> GatewayError { +pub(in crate::postgres) fn unavailable() -> GatewayError { GatewayError::new( GatewayErrorKind::ProviderInfrastructureUnavailable, "Client budget service is temporarily unavailable.", diff --git a/backend/crates/gateway-store/src/postgres/client_budget_windows.rs b/backend/crates/gateway-store/src/postgres/client_budgets/windows.rs similarity index 96% rename from backend/crates/gateway-store/src/postgres/client_budget_windows.rs rename to backend/crates/gateway-store/src/postgres/client_budgets/windows.rs index 8a2a7f736..47b57a883 100644 --- a/backend/crates/gateway-store/src/postgres/client_budget_windows.rs +++ b/backend/crates/gateway-store/src/postgres/client_budgets/windows.rs @@ -25,7 +25,7 @@ fn unavailable(source: impl Into) -> AdminStor .with_source(source) } -pub(super) async fn get( +pub(in crate::postgres) async fn get( pool: &PgPool, id: &ClientApiKeyId, period: ClientKeyBudgetWindowPeriod, @@ -39,7 +39,7 @@ pub(super) async fn get( from client_api_keys k left join client_api_key_budget_windows w on w.client_api_key_id=k.id where k.id=$1" ))).bind(id.as_str()).fetch_optional(pool).await.map_err(unavailable)? .ok_or_else(|| AdminStoreError::new(AdminStoreErrorKind::NotFound, "client API key", "API Key 不存在"))?; - let window = super::client_budgets::stored_window(&row, "start", "finish", "explicit") + let window = super::store::stored_window(&row, "start", "finish", "explicit") .filter(|w| w.visible_at(std::time::SystemTime::now())); Ok(ClientKeyBudgetWindow { revision: row.get::("revision") as u64, @@ -56,7 +56,7 @@ pub(super) async fn get( }) } -pub(super) async fn set( +pub(in crate::postgres) async fn set( pool: &PgPool, command: SetClientKeyBudgetWindow, origin: ClientKeyBudgetMutationOrigin, @@ -65,7 +65,7 @@ pub(super) async fn set( let mut tx = match &origin { ClientKeyBudgetMutationOrigin::Admin => pool.begin().await.map_err(unavailable)?, ClientKeyBudgetMutationOrigin::Plugin(owner) => { - super::plugins::begin_plugin_mutation(pool, owner).await? + crate::postgres::plugins::begin_plugin_mutation(pool, owner).await? } }; let exists = sqlx::query("select id from client_api_keys where id=$1 for update") @@ -166,7 +166,7 @@ pub(super) async fn set( .map_err(unavailable)? } }; - super::append_admin_audit_event_in_transaction( + crate::postgres::append_admin_audit_event_in_transaction( &mut tx, mutation_audit( context, diff --git a/backend/crates/gateway-store/src/postgres/client_keys.rs b/backend/crates/gateway-store/src/postgres/client_keys.rs index 8ccf21efc..87b152b0d 100644 --- a/backend/crates/gateway-store/src/postgres/client_keys.rs +++ b/backend/crates/gateway-store/src/postgres/client_keys.rs @@ -801,7 +801,7 @@ impl ClientKeyStore for PgAdminClientKeyStore { id: &ClientApiKeyId, period: gateway_admin::model::client_keys::ClientKeyBudgetWindowPeriod, ) -> AdminStoreResult { - super::client_budget_windows::get(&self.keys.pool, id, period).await + super::client_budgets::windows::get(&self.keys.pool, id, period).await } async fn set_client_key_budget_window( @@ -810,7 +810,7 @@ impl ClientKeyStore for PgAdminClientKeyStore { origin: gateway_admin::model::client_keys::ClientKeyBudgetMutationOrigin, context: &MutationContext, ) -> AdminStoreResult { - super::client_budget_windows::set(&self.keys.pool, command, origin, context).await + super::client_budgets::windows::set(&self.keys.pool, command, origin, context).await } async fn update_client_key_budget_limits( diff --git a/backend/crates/gateway-store/src/postgres/control_plane.rs b/backend/crates/gateway-store/src/postgres/control_plane.rs index bc79ee7b8..848c93f88 100644 --- a/backend/crates/gateway-store/src/postgres/control_plane.rs +++ b/backend/crates/gateway-store/src/postgres/control_plane.rs @@ -101,14 +101,16 @@ impl ControlPlaneRepository for PgControlPlaneRepository { postgres_unavailable("begin control plane replacement", source) })?; let result: StoreResult<_> = async { - // 锁住所有配置写入共同使用的行,版本检查与修改不能被其他事务穿插 - let current = sqlx::query_scalar::<_, i64>( - "select config_revision from runtime_settings where id = 1 for update", + // 草稿可以跨过其他资源的发布,但不能覆盖读取之后的运行设置写入。 + let (last_settings_write, current) = sqlx::query_as::<_, (i64, i64)>( + "select settings_revision, config_revision from runtime_settings where id = 1 for update", ) .fetch_one(&mut *transaction) .await .map_err(|source| postgres_unavailable("lock control plane revision", source))?; - if u64::try_from(current).ok() != Some(replacement.expected_revision.get()) { + if !i64::try_from(replacement.expected_revision.get()) + .is_ok_and(|read| (last_settings_write..=current).contains(&read)) + { return Err(StoreError::Conflict { source: None, entity: "runtime settings", diff --git a/backend/crates/gateway-store/src/postgres/mod.rs b/backend/crates/gateway-store/src/postgres/mod.rs index b7358c73a..40fd8f3e6 100644 --- a/backend/crates/gateway-store/src/postgres/mod.rs +++ b/backend/crates/gateway-store/src/postgres/mod.rs @@ -4,8 +4,6 @@ mod account_groups; mod admin_security_audit; mod admission_recovery; mod backup; -mod client_budget_buffer; -mod client_budget_windows; mod client_budgets; mod client_keys; mod connection; @@ -29,8 +27,7 @@ pub use account_groups::*; pub use admin_security_audit::*; pub use admission_recovery::*; pub use backup::*; -pub use client_budget_buffer::{BufferedClientBudgetStore, ClientBudgetWriter}; -pub use client_budgets::PgClientBudgetStore; +pub use client_budgets::{BufferedClientBudgetStore, ClientBudgetWriter, PgClientBudgetStore}; pub use client_keys::*; pub use connection::connect_and_migrate; pub(crate) use connection::connect_read_only; diff --git a/backend/crates/gateway-store/src/postgres/observability/analytics/forecast.rs b/backend/crates/gateway-store/src/postgres/observability/analytics/forecast.rs index eb5bb3f74..29e412323 100644 --- a/backend/crates/gateway-store/src/postgres/observability/analytics/forecast.rs +++ b/backend/crates/gateway-store/src/postgres/observability/analytics/forecast.rs @@ -2,7 +2,7 @@ use super::*; use gateway_admin::model::provider_credentials::ProviderDocument; -use gateway_admin::model::quota_forecast_sampling::{ +use gateway_admin::model::quota_forecast::{ MAX_FORECAST_HISTORY_POINTS, QuotaForecastHistory, QuotaForecastHistoryPoint, QuotaForecastUsage, }; diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/admin_adapter.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/admin_adapter.rs index 3705ae9cf..60906e2cb 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/admin_adapter.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/admin_adapter.rs @@ -464,7 +464,7 @@ impl AccountStore for PgAdminAccountStore { range: gateway_admin::model::observability::TimeRange, before: Option<&gateway_admin::model::quota_history::QuotaHistoryCursor>, ) -> AdminStoreResult { - super::quota_history::documents( + super::quota::documents( &self.pool, &self.query_budget, account, @@ -479,8 +479,8 @@ impl AccountStore for PgAdminAccountStore { async fn load_quota_forecast_history( &self, window: &AccountUsageWindowQuery, - ) -> AdminStoreResult { - super::quota_forecast::load_history(&self.pool, &self.query_budget, window).await + ) -> AdminStoreResult { + super::quota::load_history(&self.pool, &self.query_budget, window).await } async fn credential_details( diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/mod.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/mod.rs index 824a01677..f7528c40e 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/mod.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/mod.rs @@ -60,9 +60,6 @@ mod core_adapter; mod mapping; mod model_catalogs; mod quota; -mod quota_forecast; -mod quota_history; -mod quota_warmup; mod repository; mod reset_credit_automation; mod rows; diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/quota.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/quota/document.rs similarity index 91% rename from backend/crates/gateway-store/src/postgres/provider_accounts/quota.rs rename to backend/crates/gateway-store/src/postgres/provider_accounts/quota/document.rs index 51a6b8e71..c5388470a 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/quota.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/quota/document.rs @@ -1,9 +1,9 @@ //! 额度快照的轻量版本读取与连接校验,不解释额度正文 -use super::*; +use super::super::*; use gateway_core::account::{QuotaObservationVersion, UpstreamConnection}; -pub(super) async fn versions( +pub(in crate::postgres::provider_accounts) async fn versions( repository: &PgProviderAccountRepository, accounts: &[CoreProviderAccountId], ) -> Result, CoreStoreError> { @@ -14,12 +14,12 @@ pub(super) async fn versions( let rows = sqlx::query("select id, credential_revision, quota_observed_at from provider_accounts where id = any($1) and quota_observed_at is not null") .bind(ids).fetch_all(&repository.pool).await.map_err(database_error)?; rows.iter() - .filter_map(|row| super::quota_version_from_row(row).transpose()) + .filter_map(|row| super::super::quota_version_from_row(row).transpose()) .collect::>>() .map_err(crate::core_store_error) } -pub(super) async fn write( +pub(in crate::postgres::provider_accounts) async fn write( repository: &PgProviderAccountRepository, observation: QuotaObservation, ) -> Result { @@ -60,7 +60,7 @@ pub(super) async fn write( if !account.enabled() || UpstreamConnection::for_account(&account) != *expected { return Ok(QuotaWriteOutcome::Conflict); } - let updated = super::repository::write_quota( + let updated = super::super::repository::write_quota( &mut *transaction, observation.account_id.as_str(), revision, @@ -72,7 +72,7 @@ pub(super) async fn write( transaction.commit().await.map_err(database_error)?; updated } else { - super::repository::write_quota( + super::super::repository::write_quota( &repository.pool, observation.account_id.as_str(), revision, diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/quota_forecast.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/quota/forecast.rs similarity index 80% rename from backend/crates/gateway-store/src/postgres/provider_accounts/quota_forecast.rs rename to backend/crates/gateway-store/src/postgres/provider_accounts/quota/forecast.rs index a59fb184c..ce731f3da 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/quota_forecast.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/quota/forecast.rs @@ -1,12 +1,12 @@ //! 预测只读采样:先聚合数值、再读取有界的 Provider 文档,不扫描模型排行维度 -use gateway_admin::model::quota_forecast_sampling::QuotaForecastHistory; +use gateway_admin::model::quota_forecast::QuotaForecastHistory; -use super::*; +use super::super::*; -pub(super) async fn load_history( +pub(in crate::postgres::provider_accounts) async fn load_history( pool: &PgPool, - budget: &super::super::ObservabilityQueryBudget, + budget: &crate::postgres::ObservabilityQueryBudget, window: &AccountUsageWindowQuery, ) -> AdminStoreResult { validate_admin_account_ids(std::slice::from_ref(&window.account_id)) @@ -26,7 +26,7 @@ pub(super) async fn load_history( "load quota forecast history", |mut connection| async move { let mut snapshot = - super::super::observability::AnalyticsSnapshot::new_for_accounts( + crate::postgres::observability::AnalyticsSnapshot::new_for_accounts( &mut connection, ) .await?; diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/quota_history.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/quota/history.rs similarity index 97% rename from backend/crates/gateway-store/src/postgres/provider_accounts/quota_history.rs rename to backend/crates/gateway-store/src/postgres/provider_accounts/quota/history.rs index 2f037c529..dd997f3f5 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/quota_history.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/quota/history.rs @@ -3,9 +3,9 @@ use futures::TryStreamExt as _; use gateway_admin::model::quota_history::{QuotaDocumentPage, QuotaHistoryCursor}; -use super::*; +use super::super::*; -pub(super) async fn documents( +pub(in crate::postgres::provider_accounts) async fn documents( pool: &PgPool, budget: &crate::postgres::ObservabilityQueryBudget, account: &CoreProviderAccountId, diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/quota/mod.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/quota/mod.rs new file mode 100644 index 000000000..46ae44873 --- /dev/null +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/quota/mod.rs @@ -0,0 +1,10 @@ +//! Provider 额度文档、历史采样与预热状态的持久化入口 + +mod document; +mod forecast; +mod history; +mod warmup; + +pub(super) use document::{versions, write}; +pub(super) use forecast::load_history; +pub(super) use history::documents; diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/quota_warmup.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/quota/warmup.rs similarity index 94% rename from backend/crates/gateway-store/src/postgres/provider_accounts/quota_warmup.rs rename to backend/crates/gateway-store/src/postgres/provider_accounts/quota/warmup.rs index 1736de043..c45b9644f 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/quota_warmup.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/quota/warmup.rs @@ -1,10 +1,10 @@ //! 额度桶预热进度的版本读取和原子领取 -use super::*; +use super::super::*; use gateway_core::account::{QuotaWarmupState, QuotaWarmupStateUpdate}; impl PgProviderAccountRepository { - pub(super) async fn load_warmup_state( + pub(in crate::postgres::provider_accounts) async fn load_warmup_state( &self, account: &CoreProviderAccount, ) -> StoreResult> { @@ -36,7 +36,7 @@ impl PgProviderAccountRepository { .transpose() } - pub(super) async fn write_warmup_state( + pub(in crate::postgres::provider_accounts) async fn write_warmup_state( &self, update: QuotaWarmupStateUpdate<'_>, ) -> StoreResult { diff --git a/backend/crates/gateway-store/src/postgres/runtime_settings.rs b/backend/crates/gateway-store/src/postgres/runtime_settings.rs index 1d179b3e0..6c0e18f4c 100644 --- a/backend/crates/gateway-store/src/postgres/runtime_settings.rs +++ b/backend/crates/gateway-store/src/postgres/runtime_settings.rs @@ -155,7 +155,7 @@ pub(crate) async fn load_runtime_settings_from_pool(pool: &PgPool) -> StoreResul refresh_concurrency, max_concurrent_per_account, rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days, audit_retention_days, min_codex_desktop_version, - min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_oauth_guardian_review_model, openai_request_country_json, openai_account_affinity, max_account_rotations, openai_session_affinity_ttl_hours, + min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_oauth_guardian_review_model, openai_request_country_json, account_affinity, max_account_rotations, session_affinity_ttl_hours, account_error_protection_json, account_error_protection_revision, account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota from runtime_settings where id = 1", @@ -232,6 +232,7 @@ impl ProviderRuntimePolicyPort for PgRuntimeSettingsRepository { "update runtime_settings set provider_request_profiles_json = case when provider_request_profiles_json ? $1 then provider_request_profiles_json else jsonb_set(provider_request_profiles_json, array[$1], $2) end, + settings_revision = case when provider_request_profiles_json ? $1 then settings_revision else config_revision + 1 end, config_revision = config_revision + case when provider_request_profiles_json ? $1 then 0 else 1 end where id = 1 returning provider_request_profiles_json -> $1" ) @@ -335,7 +336,7 @@ pub(crate) async fn load_runtime_settings_in_transaction( refresh_concurrency, max_concurrent_per_account, rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days, audit_retention_days, min_codex_desktop_version, - min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_oauth_guardian_review_model, openai_request_country_json, openai_account_affinity, max_account_rotations, openai_session_affinity_ttl_hours, + min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_oauth_guardian_review_model, openai_request_country_json, account_affinity, max_account_rotations, session_affinity_ttl_hours, account_error_protection_json, account_error_protection_revision, account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota from runtime_settings where id = 1", @@ -385,6 +386,7 @@ pub(crate) async fn update_runtime_settings_in_transaction( let next = sqlx::query_scalar::<_, i64>( "update runtime_settings set config_revision = config_revision + 1, + settings_revision = config_revision + 1, refresh_margin_seconds = $1, refresh_concurrency = $2, max_concurrent_per_account = $3, @@ -409,9 +411,9 @@ pub(crate) async fn update_runtime_settings_in_transaction( account_warmup_model = $22, smart_scheduling_json = $23, openai_guardian_reserved_concurrency = $24, - openai_account_affinity = $25, + account_affinity = $25, max_account_rotations = $26, - openai_session_affinity_ttl_hours = $27, + session_affinity_ttl_hours = $27, codex_privacy_policy_json = $28, reset_credit_lead_minutes = $29, reset_credit_max_weekly_remaining_percent = $30, @@ -458,9 +460,9 @@ pub(crate) async fn update_runtime_settings_in_transaction( .bind(update.values.account_warmup_model.as_deref()) .bind(sqlx::types::Json(update.values.smart_scheduling)) .bind(i64::from(update.values.openai_guardian_reserved_concurrency)) - .bind(update.values.openai_account_affinity.as_str()) + .bind(update.values.account_affinity.as_str()) .bind(i64::from(update.values.max_account_rotations)) - .bind(i64::from(update.values.openai_session_affinity_ttl_hours)) + .bind(i64::from(update.values.session_affinity_ttl_hours)) .bind(sqlx::types::Json(&update.values.codex_privacy_policy)) .bind(i64::from(update.values.reset_credit_lead_minutes)) .bind(update.values.reset_credit_max_weekly_remaining_percent.map(i64::from)) @@ -566,9 +568,9 @@ struct RuntimeSettingsRow { openai_guardian_reserved_concurrency: i64, openai_oauth_guardian_review_model: bool, openai_request_country_json: sqlx::types::Json, - openai_account_affinity: String, + account_affinity: String, max_account_rotations: i64, - openai_session_affinity_ttl_hours: i64, + session_affinity_ttl_hours: i64, responses_max_decompressed_body_bytes: i64, account_error_protection_revision: i64, account_error_protection_json: sqlx::types::Json, @@ -631,16 +633,14 @@ fn runtime_settings_from_row(row: RuntimeSettingsRow) -> StoreResult, - openai_account_affinity: String, + account_affinity: String, max_account_rotations: i64, - openai_session_affinity_ttl_hours: i64, + session_affinity_ttl_hours: i64, request_location_json: sqlx::types::Json, codex_privacy_policy_json: sqlx::types::Json, @@ -255,7 +255,7 @@ async fn load_settings( transaction: &mut Transaction<'_, Postgres>, ) -> StoreResult<(Revision, SettingsValues)> { let row = sqlx::query_as::<_, SnapshotSettingsRow>( - "select config_revision, account_error_protection_revision, account_error_protection_json, max_concurrent_per_account, rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, min_codex_desktop_version, min_codex_cli_version, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_oauth_guardian_review_model, openai_request_country_json, openai_account_affinity, max_account_rotations, openai_session_affinity_ttl_hours, request_location_json, request_location_enabled, codex_privacy_policy_json, responses_max_decompressed_body_bytes, provider_request_profiles_json, pricing_overrides_json, pricing_synced_json from runtime_settings where id = 1", + "select config_revision, account_error_protection_revision, account_error_protection_json, max_concurrent_per_account, rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, min_codex_desktop_version, min_codex_cli_version, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_oauth_guardian_review_model, openai_request_country_json, account_affinity, max_account_rotations, session_affinity_ttl_hours, request_location_json, request_location_enabled, codex_privacy_policy_json, responses_max_decompressed_body_bytes, provider_request_profiles_json, pricing_overrides_json, pricing_synced_json from runtime_settings where id = 1", ) .fetch_optional(&mut **transaction) .await @@ -282,13 +282,13 @@ async fn load_settings( )?) .with_openai_oauth_guardian_review_model(row.openai_oauth_guardian_review_model) .with_openai_request_country(row.openai_request_country_json.0) - .with_openai_account_affinity( - gateway_core::account::AccountAffinity::parse(&row.openai_account_affinity) + .with_account_affinity( + gateway_core::account::AccountAffinity::parse(&row.account_affinity) .ok_or_else(|| invalid("invalid account affinity"))?, ) .with_max_account_rotations(to_u32(row.max_account_rotations)?) .with_max_retry_after_seconds(to_u32(row.max_retry_after_seconds)?) - .with_openai_session_affinity_ttl_hours(to_u32(row.openai_session_affinity_ttl_hours)?) + .with_session_affinity_ttl_hours(to_u32(row.session_affinity_ttl_hours)?) .with_smart_scheduling(row.smart_scheduling_json.0) .with_quota_reset_window_weights(row.quota_reset_window_weights_json.0) .with_request_profiles(decode_request_profiles( diff --git a/backend/crates/gateway-store/tests/postgres/backup.rs b/backend/crates/gateway-store/tests/postgres/backup.rs index 17b9b8fc6..611c3a5cc 100644 --- a/backend/crates/gateway-store/tests/postgres/backup.rs +++ b/backend/crates/gateway-store/tests/postgres/backup.rs @@ -40,8 +40,9 @@ fn transition(from: BackupStatus, to: BackupStatus) -> BackupStatusTransition { BackupStatusTransition::try_new(from, to).expect("legal backup status transition") } -fn storage_command(endpoint: &str) -> UpdateBackupStorageCommand { +fn storage_command(endpoint: &str, storage_revision: u64) -> UpdateBackupStorageCommand { UpdateBackupStorageCommand { + storage_revision, endpoint: endpoint.to_owned(), region: "auto".to_owned(), bucket: "backup-bucket".to_owned(), @@ -54,7 +55,7 @@ fn storage_command(endpoint: &str) -> UpdateBackupStorageCommand { async fn enable_verified_schedule(repository: &PgBackupRepository) -> BackupSettings { let (settings, _) = repository - .update_storage_settings(storage_command("https://one.example.com"), &context()) + .update_storage_settings(storage_command("https://one.example.com", 1), &context()) .await .expect("configure storage"); repository @@ -64,6 +65,7 @@ async fn enable_verified_schedule(repository: &PgBackupRepository) -> BackupSett repository .update_schedule_settings( UpdateBackupScheduleCommand { + storage_revision: settings.storage_revision, schedule_enabled: true, cron_expression: "0 2 * * *".to_owned(), @@ -142,7 +144,7 @@ async fn storage_rotation_pauses_schedule_and_rejects_stale_verification() { }; let repository = PgBackupRepository::new(db.pool.clone()); let before = enable_verified_schedule(&repository).await; - let mut command = storage_command("https://one.example.com"); + let mut command = storage_command("https://one.example.com", before.storage_revision); command.secret_access_key = Some(SecretString::from("rotated-secret")); let (after, _) = repository .update_storage_settings(command, &context()) @@ -159,6 +161,39 @@ async fn storage_rotation_pauses_schedule_and_rejects_stale_verification() { .await .expect("stale verification is ignored") ); + let mut stale_save = storage_command("https://one.example.com", before.storage_revision); + stale_save.secret_access_key = None; + assert_eq!( + repository + .update_storage_settings(stale_save, &context()) + .await + .unwrap_err() + .kind(), + AdminStoreErrorKind::StaleRevision, + ); + let mut enable = UpdateBackupScheduleCommand { + storage_revision: before.storage_revision, + schedule_enabled: true, + cron_expression: "0 2 * * *".into(), + retention_days: 7, + retention_count: 5, + }; + for expected in [ + AdminStoreErrorKind::StaleRevision, + AdminStoreErrorKind::Conflict, + ] { + let failure = repository + .update_schedule_settings( + enable.clone(), + Some(Utc::now()), + &context(), + Default::default(), + ) + .await + .unwrap_err(); + assert_eq!(failure.kind(), expected); + enable.storage_revision = after.storage_revision; + } let changed: Vec = sqlx::query_scalar( "select changed_fields from admin_audit_events where action = 'backup.s3_config_updated' and 'schedule_enabled' = any(changed_fields)", @@ -196,7 +231,7 @@ async fn unchanged_storage_preserves_verification_schedule_and_revision() { .await .expect("current audit count"); for include_secret in [true, false] { - let mut command = storage_command("https://one.example.com"); + let mut command = storage_command("https://one.example.com", before.storage_revision); if !include_secret { command.secret_access_key = None; } @@ -419,18 +454,14 @@ async fn storage_identity_is_locked_once_records_exist() { }; let repository = PgBackupRepository::new(db.pool.clone()); - repository - .update_storage_settings(storage_command("https://one.example.com"), &context()) + let (first, _) = repository + .update_storage_settings(storage_command("https://one.example.com", 1), &context()) .await .expect("configure storage with no records"); - let changed_endpoint = { - let mut command = storage_command("https://two.example.com"); - command.endpoint = "https://two.example.com".to_owned(); - command - }; + let changed_endpoint = storage_command("https://two.example.com", first.storage_revision); // 尚无记录时允许切换 endpoint - repository + let (second, _) = repository .update_storage_settings(changed_endpoint, &context()) .await .expect("endpoint change allowed with no records"); @@ -444,14 +475,17 @@ async fn storage_identity_is_locked_once_records_exist() { .expect("insert queued"); let locked = repository - .update_storage_settings(storage_command("https://three.example.com"), &context()) + .update_storage_settings( + storage_command("https://three.example.com", second.storage_revision), + &context(), + ) .await .expect_err("endpoint change must be rejected with records"); assert_eq!(locked.kind(), AdminStoreErrorKind::Conflict); // 只轮换凭据与修改 prefix 仍然允许 let rotation = { - let mut command = storage_command("https://two.example.com"); + let mut command = storage_command("https://two.example.com", second.storage_revision); command.access_key_id = "new-ak".to_owned(); command.secret_access_key = Some(SecretString::from("new-sk")); command.prefix = "codex/production".to_owned(); @@ -474,7 +508,7 @@ async fn schedule_update_persists_cursor_and_clears_on_disable() { // 启用计划前必须先配置存储并通过连接测试(DB 约束要求) repository - .update_storage_settings(storage_command("https://one.example.com"), &context()) + .update_storage_settings(storage_command("https://one.example.com", 1), &context()) .await .expect("configure storage"); let settings = repository.load_settings().await.expect("load settings"); @@ -486,6 +520,7 @@ async fn schedule_update_persists_cursor_and_clears_on_disable() { let enabled = repository .update_schedule_settings( UpdateBackupScheduleCommand { + storage_revision: settings.storage_revision, schedule_enabled: true, cron_expression: "0 2 * * *".to_owned(), @@ -504,6 +539,7 @@ async fn schedule_update_persists_cursor_and_clears_on_disable() { let disabled = repository .update_schedule_settings( UpdateBackupScheduleCommand { + storage_revision: settings.storage_revision, schedule_enabled: false, cron_expression: "0 2 * * *".to_owned(), diff --git a/backend/crates/gateway-store/tests/postgres/client_budget_buffer.rs b/backend/crates/gateway-store/tests/postgres/client_budgets/buffer.rs similarity index 99% rename from backend/crates/gateway-store/tests/postgres/client_budget_buffer.rs rename to backend/crates/gateway-store/tests/postgres/client_budgets/buffer.rs index ed6739caa..36d996eaf 100644 --- a/backend/crates/gateway-store/tests/postgres/client_budget_buffer.rs +++ b/backend/crates/gateway-store/tests/postgres/client_budgets/buffer.rs @@ -17,10 +17,8 @@ use gateway_store::postgres::{ BufferedClientBudgetStore, ClientBudgetWriter, PgAdminClientKeyStore, PgClientBudgetStore, }; -use super::{ - TestDatabase, - client_budgets::{charge, context, key_id, seed, status}, -}; +use super::super::TestDatabase; +use super::{charge, context, key_id, seed, status}; fn buffered(pool: sqlx::PgPool) -> (BufferedClientBudgetStore, Arc) { let (store, writer) = BufferedClientBudgetStore::new( diff --git a/backend/crates/gateway-store/tests/postgres/client_budgets/mod.rs b/backend/crates/gateway-store/tests/postgres/client_budgets/mod.rs new file mode 100644 index 000000000..c210a80f9 --- /dev/null +++ b/backend/crates/gateway-store/tests/postgres/client_budgets/mod.rs @@ -0,0 +1,133 @@ +//! 测试模块入口与共享夹具 + +use std::{collections::BTreeMap, time::SystemTime}; + +use chrono::{DateTime, Utc}; +use gateway_admin::{ + model::{ + MutationActor, MutationContext, Revision, + client_keys::{ + ClientKeyBudgetMutationOrigin, ClientKeyBudgetPeriod, DeleteClientKey, NewClientKey, + ResetClientKeyBudget, UpdateClientKey, UpdateClientKeyBudgetLimits, + }, + plugin_resources::PluginResourceOwner, + plugins::{PluginSource, instances::PluginInstance}, + }, + ports::{ + plugins::PluginStore as _, + store::{AdminStoreErrorKind, ClientKeyStore as _}, + }, +}; +use gateway_core::{ + engine::{ + ModelRequestId, + budget::{ClientBudgetCharge, ClientBudgetPort, ClientBudgetStatus}, + }, + error::GatewayErrorKind, + policy::{ClientApiKeyId, RateLimits}, +}; +use gateway_store::postgres::{ + ClientApiKeyRepository as _, PgAdminClientKeyStore, PgClientApiKeyRepository, + PgClientBudgetStore, PgPluginStore, +}; + +use super::TestDatabase; + +pub(super) fn key_id(key: &str) -> ClientApiKeyId { + ClientApiKeyId::new(key).unwrap() +} + +pub(super) fn charge(key: &str, request: &str, amount: &str) -> ClientBudgetCharge { + ClientBudgetCharge { + key_id: key_id(key), + request_id: ModelRequestId::new(format!("req_{request}")).unwrap(), + amount_usd: amount.parse().unwrap(), + completed_at: SystemTime::now(), + } +} + +pub(super) async fn seed(database: &TestDatabase, key: &str, daily: &str, weekly: &str) { + sqlx::query( + "insert into client_api_keys (id, name, key, daily_limit_usd, weekly_limit_usd, created_at, updated_at) + values ($1, $1, $2, $3::text::numeric, $4::text::numeric, now(), now())", + ) + .bind(key) + .bind(format!("sk_{key:a<43}")) + .bind(daily) + .bind(weekly) + .execute(&database.pool) + .await + .unwrap(); +} + +pub(super) async fn status(database: &TestDatabase, key: &str) -> ClientBudgetStatus { + PgClientApiKeyRepository::new(database.pool.clone()) + .get_client_api_key(key) + .await + .unwrap() + .unwrap() + .budget +} + +pub(super) fn context() -> MutationContext { + MutationContext { + actor: MutationActor::System, + request_id: "budget-test".to_owned(), + } +} + +async fn plugin_reset_owner(database: &TestDatabase) -> PluginResourceOwner { + super::plugins::artifacts::initialize_revision(database).await; + let store = PgPluginStore::new(database.pool.clone()); + let package = super::plugins::artifacts::artifact('b', &["linux-x86_64"]); + let installed = store + .install_artifact(package, PluginSource::Upload, &context()) + .await + .unwrap(); + let accepted = store + .accept_artifact(&installed.artifact.metadata.sha256, &context()) + .await + .unwrap(); + let instance = store + .save_instance( + PluginInstance { + id: uuid::Uuid::now_v7().to_string(), + name: "budget reset".into(), + artifact_sha256: installed.artifact.metadata.sha256, + enabled: true, + trusted_process: true, + configuration: serde_json::json!({}), + secrets: BTreeMap::new(), + + bindings: vec![], + revision: Revision::new(1).unwrap(), + }, + accepted.config_revision, + &context(), + ) + .await + .unwrap() + .instance; + PluginResourceOwner { + instance_id: instance.id, + artifact_sha256: instance.artifact_sha256, + revision: instance.revision, + } +} + +fn budget_update( + key: &str, + daily: Option<&str>, + weekly: Option<&str>, +) -> UpdateClientKeyBudgetLimits { + UpdateClientKeyBudgetLimits { + id: key_id(key), + daily_limit_usd: daily.map(|value| value.parse().unwrap()), + weekly_limit_usd: weekly.map(|value| value.parse().unwrap()), + } +} + +mod buffer; +mod windows; + +mod store; diff --git a/backend/crates/gateway-store/tests/postgres/client_budgets.rs b/backend/crates/gateway-store/tests/postgres/client_budgets/store.rs similarity index 92% rename from backend/crates/gateway-store/tests/postgres/client_budgets.rs rename to backend/crates/gateway-store/tests/postgres/client_budgets/store.rs index 5e2b271a7..23c3f80c8 100644 --- a/backend/crates/gateway-store/tests/postgres/client_budgets.rs +++ b/backend/crates/gateway-store/tests/postgres/client_budgets/store.rs @@ -1,80 +1,6 @@ -//! 验证 Key 预算重置、在途结算、时间窗口与审计事务 +//! 预算持久化、幂等结算与审计事务测试 -use std::{collections::BTreeMap, time::SystemTime}; - -use chrono::{DateTime, Utc}; -use gateway_admin::{ - model::{ - MutationActor, MutationContext, Revision, - client_keys::{ - ClientKeyBudgetMutationOrigin, ClientKeyBudgetPeriod, DeleteClientKey, NewClientKey, - ResetClientKeyBudget, UpdateClientKey, UpdateClientKeyBudgetLimits, - }, - plugin_resources::PluginResourceOwner, - plugins::{PluginSource, instances::PluginInstance}, - }, - ports::{ - plugins::PluginStore as _, - store::{AdminStoreErrorKind, ClientKeyStore as _}, - }, -}; -use gateway_core::{ - engine::{ - ModelRequestId, - budget::{ClientBudgetCharge, ClientBudgetPort, ClientBudgetStatus}, - }, - error::GatewayErrorKind, - policy::{ClientApiKeyId, RateLimits}, -}; -use gateway_store::postgres::{ - ClientApiKeyRepository as _, PgAdminClientKeyStore, PgClientApiKeyRepository, - PgClientBudgetStore, PgPluginStore, -}; - -use super::TestDatabase; - -pub(super) fn key_id(key: &str) -> ClientApiKeyId { - ClientApiKeyId::new(key).unwrap() -} - -pub(super) fn charge(key: &str, request: &str, amount: &str) -> ClientBudgetCharge { - ClientBudgetCharge { - key_id: key_id(key), - request_id: ModelRequestId::new(format!("req_{request}")).unwrap(), - amount_usd: amount.parse().unwrap(), - completed_at: SystemTime::now(), - } -} - -pub(super) async fn seed(database: &TestDatabase, key: &str, daily: &str, weekly: &str) { - sqlx::query( - "insert into client_api_keys (id, name, key, daily_limit_usd, weekly_limit_usd, created_at, updated_at) - values ($1, $1, $2, $3::text::numeric, $4::text::numeric, now(), now())", - ) - .bind(key) - .bind(format!("sk_{key:a<43}")) - .bind(daily) - .bind(weekly) - .execute(&database.pool) - .await - .unwrap(); -} - -pub(super) async fn status(database: &TestDatabase, key: &str) -> ClientBudgetStatus { - PgClientApiKeyRepository::new(database.pool.clone()) - .get_client_api_key(key) - .await - .unwrap() - .unwrap() - .budget -} - -pub(super) fn context() -> MutationContext { - MutationContext { - actor: MutationActor::System, - request_id: "budget-test".to_owned(), - } -} +use super::*; #[tokio::test] async fn open_budget_windows_only_write_for_new_charges() { @@ -889,45 +815,6 @@ async fn budget_database_outage_fails_closed() { database.close().await; } -async fn plugin_reset_owner(database: &TestDatabase) -> PluginResourceOwner { - super::plugins::artifacts::initialize_revision(database).await; - let store = PgPluginStore::new(database.pool.clone()); - let package = super::plugins::artifacts::artifact('b', &["linux-x86_64"]); - let installed = store - .install_artifact(package, PluginSource::Upload, &context()) - .await - .unwrap(); - let accepted = store - .accept_artifact(&installed.artifact.metadata.sha256, &context()) - .await - .unwrap(); - let instance = store - .save_instance( - PluginInstance { - id: uuid::Uuid::now_v7().to_string(), - name: "budget reset".into(), - artifact_sha256: installed.artifact.metadata.sha256, - enabled: true, - trusted_process: true, - configuration: serde_json::json!({}), - secrets: BTreeMap::new(), - - bindings: vec![], - revision: Revision::new(1).unwrap(), - }, - accepted.config_revision, - &context(), - ) - .await - .unwrap() - .instance; - PluginResourceOwner { - instance_id: instance.id, - artifact_sha256: instance.artifact_sha256, - revision: instance.revision, - } -} - #[tokio::test] async fn plugin_resets_share_the_native_ledger_and_each_call_resets_again() { let Some(database) = TestDatabase::create("plugin_budget_reset").await else { @@ -1135,18 +1022,6 @@ async fn plugin_reset_rolls_back_with_audit_and_serializes_with_late_settlement( database.close().await; } -fn budget_update( - key: &str, - daily: Option<&str>, - weekly: Option<&str>, -) -> UpdateClientKeyBudgetLimits { - UpdateClientKeyBudgetLimits { - id: key_id(key), - daily_limit_usd: daily.map(|value| value.parse().unwrap()), - weekly_limit_usd: weekly.map(|value| value.parse().unwrap()), - } -} - #[tokio::test] async fn plugin_budget_limits_preserve_consumption_and_unrelated_configuration_and_control_admission() { diff --git a/backend/crates/gateway-store/tests/postgres/client_budget_windows.rs b/backend/crates/gateway-store/tests/postgres/client_budgets/windows.rs similarity index 99% rename from backend/crates/gateway-store/tests/postgres/client_budget_windows.rs rename to backend/crates/gateway-store/tests/postgres/client_budgets/windows.rs index 6dbd16ea1..67b6dd79c 100644 --- a/backend/crates/gateway-store/tests/postgres/client_budget_windows.rs +++ b/backend/crates/gateway-store/tests/postgres/client_budgets/windows.rs @@ -1,9 +1,7 @@ //! 显式窗口的事务、重试和结算边界 -use super::{ - TestDatabase, - client_budgets::{charge, context, key_id, seed, status}, -}; +use super::super::TestDatabase; +use super::{charge, context, key_id, seed, status}; use chrono::{Duration, Utc}; use gateway_admin::{ model::client_keys::{ diff --git a/backend/crates/gateway-store/tests/postgres/control_plane.rs b/backend/crates/gateway-store/tests/postgres/control_plane.rs index 4c1e5545c..0e4183e28 100644 --- a/backend/crates/gateway-store/tests/postgres/control_plane.rs +++ b/backend/crates/gateway-store/tests/postgres/control_plane.rs @@ -72,30 +72,30 @@ async fn control_plane_replacement_commits_one_writer_per_revision_and_preserves .await .unwrap(); assert_eq!(audit_count, 1); - // API Key 更新也推进相同版本,旧设置快照不能复活已经替换的 Key + // 轮换密钥后仍可提交原设置草稿,同时保留新密钥。 let mut key_audit = replacement("key", 3600).audit; key_audit.action = "settings.admin_key".into(); repository .replace_admin_api_key(Some("new-test-key".into()), key_audit) .await .unwrap(); - let mut stale = replacement("stale", 3600); - stale.expected_revision = saved.config_revision; + let mut draft = replacement("after-key", 3600); + draft.expected_revision = saved.config_revision; + let committed = repository + .replace_control_plane(draft.clone()) + .await + .unwrap(); + assert_eq!( + committed.settings.config_revision.get(), + saved.config_revision.get() + 2 + ); assert!(matches!( - repository.replace_control_plane(stale).await, + repository.replace_control_plane(draft).await, Err(StoreError::Conflict { kind: ConflictKind::StaleRevision, .. }) )); - let mut fresh = replacement("fresh", 3600); - fresh.expected_revision = repository - .load_control_plane() - .await - .unwrap() - .settings - .config_revision; - repository.replace_control_plane(fresh).await.unwrap(); assert_eq!( repository .load_control_plane() diff --git a/backend/crates/gateway-store/tests/postgres/mod.rs b/backend/crates/gateway-store/tests/postgres/mod.rs index 653f95cab..788f81b9c 100644 --- a/backend/crates/gateway-store/tests/postgres/mod.rs +++ b/backend/crates/gateway-store/tests/postgres/mod.rs @@ -20,8 +20,6 @@ mod analytics_buckets; mod analytics_reset; mod backup; mod backup_export; -mod client_budget_buffer; -mod client_budget_windows; mod client_budgets; mod client_keys; mod connection; diff --git a/backend/crates/gateway-store/tests/postgres/pricing.rs b/backend/crates/gateway-store/tests/postgres/pricing.rs index 4cf191ef2..b8e3f9890 100644 --- a/backend/crates/gateway-store/tests/postgres/pricing.rs +++ b/backend/crates/gateway-store/tests/postgres/pricing.rs @@ -41,6 +41,7 @@ async fn concurrent_price_edits_preserve_other_models_and_sync_preserves_manual_ actor: MutationActor::System, request_id: "pricing-test".to_owned(), }; + let draft = settings.load_runtime_settings().await.unwrap(); let pricing: ModelPriceOverride = serde_json::from_value(json!({ "multiplierBps":12500, "bands":{"standard":{"input":"2","output":"10","cacheRead":"0","cacheWrite":"1"}} @@ -62,6 +63,10 @@ async fn concurrent_price_edits_preserve_other_models_and_sync_preserves_manual_ ), ); assert_ne!(first.unwrap(), second.unwrap()); + settings + .replace_runtime_settings(draft.into(), &context) + .await + .expect("pricing edits preserve the runtime settings draft"); let stored = settings.load_pricing().await.unwrap(); assert_eq!(stored.overrides["openai"].len(), 2); diff --git a/backend/crates/gateway-store/tests/postgres/provider_accounts/mod.rs b/backend/crates/gateway-store/tests/postgres/provider_accounts/mod.rs index c9ea55e2e..1dc176035 100644 --- a/backend/crates/gateway-store/tests/postgres/provider_accounts/mod.rs +++ b/backend/crates/gateway-store/tests/postgres/provider_accounts/mod.rs @@ -12,8 +12,6 @@ mod core_adapter; mod deletion; mod protection_revision; mod quota; -mod quota_forecast; -mod quota_history; mod timestamps; mod usage_projection; diff --git a/backend/crates/gateway-store/tests/postgres/provider_accounts/quota.rs b/backend/crates/gateway-store/tests/postgres/provider_accounts/quota/document.rs similarity index 83% rename from backend/crates/gateway-store/tests/postgres/provider_accounts/quota.rs rename to backend/crates/gateway-store/tests/postgres/provider_accounts/quota/document.rs index 7d8b7bb89..562f32813 100644 --- a/backend/crates/gateway-store/tests/postgres/provider_accounts/quota.rs +++ b/backend/crates/gateway-store/tests/postgres/provider_accounts/quota/document.rs @@ -1,7 +1,6 @@ -//! 共用额度存储的连接隔离、版本读取与大快照生命周期 +//! 额度文档的连接隔离与乐观写入测试 use super::*; -use gateway_core::account::UpstreamConnection; #[tokio::test] async fn connection_changes_reject_in_flight_quota_writes() { @@ -420,68 +419,3 @@ async fn managed_proxy_changes_clear_snapshots_and_reject_old_connections() { assert!(repository.get_quotas(&[id]).await.unwrap().is_empty()); database.close().await; } - -#[tokio::test] -async fn quota_warmup_claim_is_persistent_and_fenced_by_configuration_usage_and_account_state() { - use gateway_core::account::QuotaWarmupStateUpdate; - let Some(database) = TestDatabase::create("quota_warmup_claim").await else { - return; - }; - let repository = PgProviderAccountRepository::new(database.pool.clone()); - repository - .insert_provider_account(account("acct_warmup", "fixture")) - .await - .unwrap(); - let id = ProviderAccountId::new("acct_warmup").unwrap(); - let current = repository.get_account(&id).await.unwrap().unwrap(); - let initial = repository - .load_quota_warmup_state(¤t) - .await - .unwrap() - .unwrap(); - assert_eq!(initial.version, 0); - let claim = || QuotaWarmupStateUpdate { - account: ¤t, - expected_version: 0, - expected_quota_observed_at: None, - data: json!({"claimed": true}).as_object().unwrap().clone(), - }; - let (one, two) = tokio::join!( - repository.compare_and_swap_quota_warmup_state(claim()), - repository.compare_and_swap_quota_warmup_state(claim()) - ); - assert_ne!(one.unwrap(), two.unwrap()); - let reloaded = PgProviderAccountRepository::new(database.pool.clone()); - let state = reloaded - .load_quota_warmup_state(¤t) - .await - .unwrap() - .unwrap(); - assert_eq!(state.version, 1); - assert_eq!(state.data["claimed"], true); - for mutation in [ - "update provider_accounts set quota_settings = '{\"codex:604800s\":{\"warmup\":{\"model\":\"test-model\"}}}' where id = 'acct_warmup'", - "update provider_accounts set quota_observed_at = now(), updated_at = now(), provider_quota_json = '{}' where id = 'acct_warmup'", - "update provider_accounts set enabled = false where id = 'acct_warmup'", - "update provider_accounts set credential_state = 'invalid' where id = 'acct_warmup'", - "update provider_accounts set credential_revision = credential_revision + 1 where id = 'acct_warmup'", - ] { - sqlx::query(sqlx::AssertSqlSafe(mutation)) - .execute(&database.pool) - .await - .unwrap(); - assert!( - !reloaded - .compare_and_swap_quota_warmup_state(QuotaWarmupStateUpdate { - expected_version: 1, - ..claim() - }) - .await - .unwrap() - ); - sqlx::query("update provider_accounts set quota_settings = '{}', quota_observed_at = null, provider_quota_json = null, enabled = true, credential_state = $1, credential_revision = $2 where id = 'acct_warmup'") - .bind(current.credential_state().as_str()).bind(i64::try_from(current.revision().get()).unwrap()) - .execute(&database.pool).await.unwrap(); - } - database.close().await; -} diff --git a/backend/crates/gateway-store/tests/postgres/provider_accounts/quota_forecast.rs b/backend/crates/gateway-store/tests/postgres/provider_accounts/quota/forecast.rs similarity index 98% rename from backend/crates/gateway-store/tests/postgres/provider_accounts/quota_forecast.rs rename to backend/crates/gateway-store/tests/postgres/provider_accounts/quota/forecast.rs index aa432ad92..76ba7f041 100644 --- a/backend/crates/gateway-store/tests/postgres/provider_accounts/quota_forecast.rs +++ b/backend/crates/gateway-store/tests/postgres/provider_accounts/quota/forecast.rs @@ -2,8 +2,8 @@ use gateway_admin::model::observability as admin_observability; -use super::*; -use gateway_admin::model::quota_forecast_sampling::MAX_FORECAST_HISTORY_POINTS; +use super::super::*; +use gateway_admin::model::quota_forecast::MAX_FORECAST_HISTORY_POINTS; use gateway_store::postgres::{ ObservabilityPageSize, ObservabilityRange, ProviderAccountUsageQuery, UsageRecordFilter, UsageRecordQuery, @@ -130,8 +130,8 @@ async fn quota_forecast_excludes_openai_prewarm_but_preserves_inference_and_audi assert_eq!(history.points.len(), 1); assert_eq!(history.points[0].usage, history.usage); - super::super::drain_analytics(&database.pool).await; - let repository = super::super::observability_repository(&database.pool); + crate::postgres::drain_analytics(&database.pool).await; + let repository = crate::postgres::observability_repository(&database.pool); let range = ObservabilityRange::new(start, end).unwrap(); let account_usage = repository .provider_account_usage( @@ -478,8 +478,8 @@ async fn quota_forecast_carries_unsampled_usage_between_document_points() { #[tokio::test] async fn quota_forecast_summaries_match_source_during_moves_deletes_and_rebuilds() { - use super::super::drain_analytics; - use gateway_admin::model::quota_forecast_sampling::QuotaForecastHistory; + use crate::postgres::drain_analytics; + use gateway_admin::model::quota_forecast::QuotaForecastHistory; fn assert_same(actual: &QuotaForecastHistory, expected: &QuotaForecastHistory) { assert_eq!(actual.usage, expected.usage); diff --git a/backend/crates/gateway-store/tests/postgres/provider_accounts/quota_history.rs b/backend/crates/gateway-store/tests/postgres/provider_accounts/quota/history.rs similarity index 99% rename from backend/crates/gateway-store/tests/postgres/provider_accounts/quota_history.rs rename to backend/crates/gateway-store/tests/postgres/provider_accounts/quota/history.rs index f271c9387..441740f88 100644 --- a/backend/crates/gateway-store/tests/postgres/provider_accounts/quota_history.rs +++ b/backend/crates/gateway-store/tests/postgres/provider_accounts/quota/history.rs @@ -2,7 +2,7 @@ use gateway_admin::model::quota_history::{QuotaHistoryPage, QuotaHistoryQuery, QuotaReading}; -use super::*; +use super::super::*; #[tokio::test] async fn quota_history_pages_sparse_tied_observations_through_the_nearest_baseline() { diff --git a/backend/crates/gateway-store/tests/postgres/provider_accounts/quota/mod.rs b/backend/crates/gateway-store/tests/postgres/provider_accounts/quota/mod.rs new file mode 100644 index 000000000..66badcdd7 --- /dev/null +++ b/backend/crates/gateway-store/tests/postgres/provider_accounts/quota/mod.rs @@ -0,0 +1,11 @@ +//! 测试模块入口与共享夹具 + +use super::*; +use gateway_core::account::UpstreamConnection; + +mod forecast; +mod history; + +mod document; + +mod warmup; diff --git a/backend/crates/gateway-store/tests/postgres/provider_accounts/quota/warmup.rs b/backend/crates/gateway-store/tests/postgres/provider_accounts/quota/warmup.rs new file mode 100644 index 000000000..f32543d3f --- /dev/null +++ b/backend/crates/gateway-store/tests/postgres/provider_accounts/quota/warmup.rs @@ -0,0 +1,68 @@ +//! 额度预热声明的持久化与版本隔离测试 + +use super::*; + +#[tokio::test] +async fn quota_warmup_claim_is_persistent_and_fenced_by_configuration_usage_and_account_state() { + use gateway_core::account::QuotaWarmupStateUpdate; + let Some(database) = TestDatabase::create("quota_warmup_claim").await else { + return; + }; + let repository = PgProviderAccountRepository::new(database.pool.clone()); + repository + .insert_provider_account(account("acct_warmup", "fixture")) + .await + .unwrap(); + let id = ProviderAccountId::new("acct_warmup").unwrap(); + let current = repository.get_account(&id).await.unwrap().unwrap(); + let initial = repository + .load_quota_warmup_state(¤t) + .await + .unwrap() + .unwrap(); + assert_eq!(initial.version, 0); + let claim = || QuotaWarmupStateUpdate { + account: ¤t, + expected_version: 0, + expected_quota_observed_at: None, + data: json!({"claimed": true}).as_object().unwrap().clone(), + }; + let (one, two) = tokio::join!( + repository.compare_and_swap_quota_warmup_state(claim()), + repository.compare_and_swap_quota_warmup_state(claim()) + ); + assert_ne!(one.unwrap(), two.unwrap()); + let reloaded = PgProviderAccountRepository::new(database.pool.clone()); + let state = reloaded + .load_quota_warmup_state(¤t) + .await + .unwrap() + .unwrap(); + assert_eq!(state.version, 1); + assert_eq!(state.data["claimed"], true); + for mutation in [ + "update provider_accounts set quota_settings = '{\"codex:604800s\":{\"warmup\":{\"model\":\"test-model\"}}}' where id = 'acct_warmup'", + "update provider_accounts set quota_observed_at = now(), updated_at = now(), provider_quota_json = '{}' where id = 'acct_warmup'", + "update provider_accounts set enabled = false where id = 'acct_warmup'", + "update provider_accounts set credential_state = 'invalid' where id = 'acct_warmup'", + "update provider_accounts set credential_revision = credential_revision + 1 where id = 'acct_warmup'", + ] { + sqlx::query(sqlx::AssertSqlSafe(mutation)) + .execute(&database.pool) + .await + .unwrap(); + assert!( + !reloaded + .compare_and_swap_quota_warmup_state(QuotaWarmupStateUpdate { + expected_version: 1, + ..claim() + }) + .await + .unwrap() + ); + sqlx::query("update provider_accounts set quota_settings = '{}', quota_observed_at = null, provider_quota_json = null, enabled = true, credential_state = $1, credential_revision = $2 where id = 'acct_warmup'") + .bind(current.credential_state().as_str()).bind(i64::try_from(current.revision().get()).unwrap()) + .execute(&database.pool).await.unwrap(); + } + database.close().await; +} diff --git a/backend/crates/gateway-store/tests/postgres/runtime_settings.rs b/backend/crates/gateway-store/tests/postgres/runtime_settings.rs index e10f395f9..c13ce435e 100644 --- a/backend/crates/gateway-store/tests/postgres/runtime_settings.rs +++ b/backend/crates/gateway-store/tests/postgres/runtime_settings.rs @@ -37,9 +37,9 @@ pub(super) fn settings_with_margin(refresh_margin_seconds: u64) -> RuntimeSettin switch_account_on_queue_failure: false, max_retry_after_seconds: 240, openai_guardian_reserved_concurrency: 0, - openai_account_affinity: gateway_core::account::AccountAffinity::Relaxed, + account_affinity: gateway_core::account::AccountAffinity::Relaxed, max_account_rotations: 3, - openai_session_affinity_ttl_hours: 24, + session_affinity_ttl_hours: 24, responses_max_decompressed_body_bytes: 64 * 1024 * 1024, smart_scheduling: gateway_core::account::SmartSchedulingConfig::default(), quota_reset_window_weights: gateway_core::account::ResetWindowWeights::default(), @@ -1258,26 +1258,23 @@ async fn account_affinity_defaults_and_updates_reach_the_snapshot() { }; let repository = PgRuntimeSettingsRepository::new(database.pool.clone()); let before = repository.load_runtime_settings().await.unwrap(); - assert_eq!( - before.values.openai_account_affinity, - AccountAffinity::Strict - ); + assert_eq!(before.values.account_affinity, AccountAffinity::Strict); assert_eq!(before.values.max_account_rotations, 3); - assert_eq!(before.values.openai_session_affinity_ttl_hours, 24); + assert_eq!(before.values.session_affinity_ttl_hours, 24); for (mode, budget, ttl) in [ (AccountAffinity::Preferred, 3, 24), (AccountAffinity::Strict, 31, 168), (AccountAffinity::Relaxed, 0, 720), ] { let mut update = settings_with_margin(3600); - update.values.openai_account_affinity = mode; + update.values.account_affinity = mode; update.values.max_account_rotations = budget; - update.values.openai_session_affinity_ttl_hours = ttl; + update.values.session_affinity_ttl_hours = ttl; repository.update_runtime_settings(update).await.unwrap(); let loaded = repository.load_runtime_settings().await.unwrap(); assert_eq!( ( - loaded.values.openai_account_affinity, + loaded.values.account_affinity, loaded.values.max_account_rotations ), (mode, budget) @@ -1290,7 +1287,7 @@ async fn account_affinity_defaults_and_updates_reach_the_snapshot() { assert_eq!( ( serde_json::from_value::( - snapshot_values["openai_account_affinity"].clone() + snapshot_values["account_affinity"].clone() ) .unwrap(), snapshot_values["max_account_rotations"].as_u64().unwrap() @@ -1298,18 +1295,18 @@ async fn account_affinity_defaults_and_updates_reach_the_snapshot() { (mode, u64::from(budget)) ); assert!(snapshot.config_revision > before.config_revision); - assert_eq!(loaded.values.openai_session_affinity_ttl_hours, ttl); - assert_eq!(snapshot_values["openai_session_affinity_ttl_hours"], ttl); + assert_eq!(loaded.values.session_affinity_ttl_hours, ttl); + assert_eq!(snapshot_values["session_affinity_ttl_hours"], ttl); } let mut invalid = settings_with_margin(3600); invalid.values.max_account_rotations = 32; assert!(repository.update_runtime_settings(invalid).await.is_err()); for sql in [ - "update runtime_settings set openai_session_affinity_ttl_hours = 0 where id = 1", - "update runtime_settings set openai_session_affinity_ttl_hours = 721 where id = 1", + "update runtime_settings set session_affinity_ttl_hours = 0 where id = 1", + "update runtime_settings set session_affinity_ttl_hours = 721 where id = 1", "update runtime_settings set max_account_rotations = 32 where id = 1", "update runtime_settings set max_account_rotations = -1 where id = 1", - "update runtime_settings set openai_account_affinity = 'unknown' where id = 1", + "update runtime_settings set account_affinity = 'unknown' where id = 1", ] { assert!(sqlx::query(sql).execute(&database.pool).await.is_err()); } diff --git a/backend/crates/providers/antigravity/Cargo.toml b/backend/crates/providers/antigravity/Cargo.toml new file mode 100644 index 000000000..c4e4cfd05 --- /dev/null +++ b/backend/crates/providers/antigravity/Cargo.toml @@ -0,0 +1,50 @@ +[package] +name = "provider-antigravity" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true +rust-version.workspace = true +autotests = false + +[dependencies] +async-compression = { version = "0.4.52", features = ["tokio", "gzip"] } +async-stream = "0.3.6" +async-trait = "0.1.89" +base64 = "0.23.0" +bytes = "1.11.1" +chrono = { version = "0.4.45", features = ["clock", "serde"] } +gateway-admin = { path = "../../gateway-admin" } +gateway-core = { path = "../../gateway-core" } +gateway-egress = { path = "../../gateway-egress" } +gateway-protocol = { path = "../../gateway-protocol" } +futures = "0.3.32" +flate2 = "1.1.9" +getrandom = "0.4.3" +hex = "0.4.3" +http = "1.5.0" +http-body-util = "0.1.5" +reqwest = { version = "=0.12.28", default-features = false, features = ["json", "rustls-tls-native-roots", "socks", "stream"] } +serde = { version = "1.0.228", features = ["derive"] } +serde_json = { version = "1.0.150", features = ["raw_value"] } +sha2 = "0.11.0" +tar = { version = "0.4.46", default-features = false } +tempfile = "3.27.0" +thiserror = "2.0.18" +tracing = "0.1.44" +tokio = { version = "=1.53.3", features = ["fs", "io-util", "macros", "time"] } +tokio-util = { version = "0.7.20", features = ["io"] } +url = { version = "2.5.8", features = ["serde"] } +uuid = { version = "1.23.3", features = ["v7"] } +zip = { version = "9.8.0", default-features = false, features = ["deflate-flate2"] } + +[dev-dependencies] +wiremock = "0.6.5" +tokio = { version = "=1.53.3", features = ["rt-multi-thread"] } + +[[test]] +name = "main" +path = "tests/main.rs" + +[lints] +workspace = true diff --git a/backend/crates/providers/antigravity/src/admin/mod.rs b/backend/crates/providers/antigravity/src/admin/mod.rs new file mode 100644 index 000000000..328d75313 --- /dev/null +++ b/backend/crates/providers/antigravity/src/admin/mod.rs @@ -0,0 +1,5 @@ +//! Antigravity 管理边界的模块门面 + +mod provider; + +pub(crate) use provider::AntigravityAdmin; diff --git a/backend/crates/providers/antigravity/src/admin/provider.rs b/backend/crates/providers/antigravity/src/admin/provider.rs new file mode 100644 index 000000000..187da20c0 --- /dev/null +++ b/backend/crates/providers/antigravity/src/admin/provider.rs @@ -0,0 +1,228 @@ +//! 管理端账号操作与客户端画像的适配入口 + +use crate::credential::catalog::CatalogService; +use crate::{ + credential::{AuthorizationService, CredentialService, oauth::error}, + profile::ReleaseService, +}; +use async_trait::async_trait; +use gateway_admin::{ + model::{ + observability::{CalculatedBillingBreakdown, DashboardWireProfile, ProviderBillingInput}, + provider_credentials::{ + AuthorizationStarted, CompleteAuthorization, PendingAuthorizationMutation, + PrepareCredentialImport, PrepareCredentialRefresh, PrepareCredentialRotation, + PreparedAuthorizationCommit, PreparedCredentialImport, PreparedCredentialRotation, + ProviderExport, ProviderExportCredentialInput, ProviderModels, ProviderQuota, + ProviderQuotaRequest, + }, + }, + ports::provider::{ProviderAdmin, ProviderAdminError, ProviderAdminErrorKind as Kind}, +}; +use gateway_core::{ + account::{OpaqueProviderData, ProviderAccountId}, + operation::Operation, + routing::{ProviderKind, UpstreamModelId}, +}; +use std::sync::Arc; + +pub(crate) struct AntigravityAdmin { + pub(crate) kind: ProviderKind, + pub(crate) credentials: Arc, + pub(crate) authorization: AuthorizationService, + pub(crate) catalog: Arc, + pub(crate) release: Arc, + pub(crate) quota: Arc, +} + +#[async_trait] +impl ProviderAdmin for AntigravityAdmin { + fn is_direct_account(&self, authentication_kind: &str) -> bool { + authentication_kind == "oauth" + } + async fn peer_model_facts( + &self, + accounts: &[gateway_admin::model::accounts::AccountRecord], + ) -> Result< + Option< + std::collections::BTreeMap< + String, + gateway_admin::ports::provider::ProviderPeerAccountModels, + >, + >, + ProviderAdminError, + > { + self.quota.peer_model_facts(accounts).await.map(Some) + } + fn account_capabilities( + &self, + _: &ProviderAccountId, + authentication_kind: &str, + ) -> gateway_admin::model::accounts::ProviderAccountCapabilities { + let oauth = authentication_kind == "oauth"; + gateway_admin::model::accounts::ProviderAccountCapabilities { + credential_refresh: oauth, + reauthorize: oauth, + credential_export: oauth, + quota: oauth, + quota_refresh: oauth, + ..Default::default() + } + } + fn plan_type_display(&self, plan: &str) -> String { + match plan { + "g1-pro-tier" => "Google AI Pro", + "free-tier" => "Antigravity", + _ => plan, + } + .to_owned() + } + fn supported_pricing_bands(&self) -> &'static [&'static str] { + crate::billing::SUPPORTED_PRICING_BANDS + } + + fn pricing_catalog(&self) -> gateway_admin::model::pricing::ProviderPricingCatalog { + crate::billing::defaults().clone() + } + fn pricing_source(&self) -> gateway_admin::ports::pricing::PricingCatalogSource { + gateway_admin::ports::pricing::PricingCatalogSource::References( + crate::billing::source_models(), + ) + } + fn evaluate_usage_pricing( + &self, + input: &gateway_admin::ports::provider::ProviderUsagePricingInput, + pricing: Option<&gateway_core::metering::ModelPriceOverride>, + ) -> Result, ProviderAdminError> { + Ok(crate::billing::calculate( + &input.upstream_model_id, + &input.usage, + pricing, + )) + } + fn provider_kind(&self) -> &ProviderKind { + &self.kind + } + async fn account_unavailable(&self, _: &ProviderAccountId) { + self.catalog.invalidate(); + } + async fn account_facts_changed(&self, ids: &[ProviderAccountId]) { + self.catalog.invalidate(); + for id in ids { + let _ = self.catalog.account_models(id, false).await; + } + } + fn dashboard_wire_profile(&self) -> Option { + Some(crate::profile::dashboard( + &crate::profile::Selection::default(), + &self.release, + )) + } + fn configured_wire_profile( + &self, + configuration: &OpaqueProviderData, + ) -> Option { + Some(crate::profile::dashboard( + &crate::profile::Selection::parse(configuration).ok()?, + &self.release, + )) + } + fn default_client_profile(&self) -> Option { + Some(crate::profile::Selection::default().configuration()) + } + fn client_profile_options(&self) -> Result { + Ok(crate::profile::options()) + } + fn preview_client_profile( + &self, + configuration: &OpaqueProviderData, + ) -> Result { + crate::profile::preview(configuration, &self.release) + } + fn calculated_billing( + &self, + _: &ProviderBillingInput, + ) -> Result, ProviderAdminError> { + // 此历史接口没有请求当时的价格快照,不能用当前人工价重算历史费用 + Ok(None) + } + + async fn start_authorization( + &self, + pending: PendingAuthorizationMutation, + ) -> Result { + self.authorization.start(pending).await + } + async fn complete_authorization( + &self, + command: CompleteAuthorization, + ) -> Result { + self.authorization.complete(command).await + } + async fn prepare_refresh( + &self, + command: PrepareCredentialRefresh, + ) -> Result { + let id = ProviderAccountId::new(command.account.id).map_err(|_| error(Kind::Invalid))?; + let current = self.credentials.current(&id).await?; + if command.account.provider_kind != self.kind + || current.account.revision().get() != command.account.credential_revision.get() + { + return Err(error(Kind::Conflict)); + } + self.credentials.refresh_current(¤t).await + } + + async fn prepare_import( + &self, + command: PrepareCredentialImport, + ) -> Result { + self.credentials.prepare_import(command).await + } + async fn prepare_rotation( + &self, + command: PrepareCredentialRotation, + ) -> Result { + self.credentials.prepare_rotation(command).await + } + async fn models( + &self, + id: &ProviderAccountId, + refresh: bool, + ) -> Result { + self.catalog.account_models(id, refresh).await + } + async fn connection_test_operation( + &self, + _: &UpstreamModelId, + input: &str, + ) -> Result { + let body = serde_json::to_vec( + &serde_json::json!({"contents":[{"role":"user","parts":[{"text":input}]}]}), + ) + .map_err(|_| error(Kind::Internal))?; + let payload = gateway_core::operation::ProtocolPayload::from_json_bytes( + gateway_protocol::genai::GENAI_PROTOCOL, + body.into(), + ) + .map_err(|_| error(Kind::Invalid))?; + Ok(Operation::Generate( + gateway_core::operation::GenerateRequest::from_protocol_payload(payload), + )) + } + async fn quota( + &self, + request: ProviderQuotaRequest, + ) -> Result { + if request.refresh { + self.quota.refresh(&request.account_id).await?; + } + self.quota.read(&request.account_id).await + } + async fn export_credentials( + &self, + credentials: Vec, + ) -> Result { + self.credentials.export_credentials(credentials) + } +} diff --git a/backend/crates/providers/antigravity/src/billing/calculate.rs b/backend/crates/providers/antigravity/src/billing/calculate.rs new file mode 100644 index 000000000..b489ffefe --- /dev/null +++ b/backend/crates/providers/antigravity/src/billing/calculate.rs @@ -0,0 +1,183 @@ +//! 使用公开 API 参考价与请求冻结的配置估算费用;不将订阅额度解释为现金账单 + +use super::catalog::defaults; + +use gateway_core::metering::{ + CalculatedCostAmounts, CalculatedCostBreakdown, CalculatedCostRates, CurrencyCode, Decimal, + ImageCostBreakdown, ModelPriceOverride, Money, TokenPriceOverride, Usage, +}; + +pub(crate) fn calculate( + model: &str, + usage: &Usage, + pricing: Option<&ModelPriceOverride>, +) -> Option { + let builtin = defaults().get(model); + let band = |name| { + pricing + .and_then(|p| p.bands.get(name)) + .or_else(|| builtin.and_then(|p| p.bands.get(name))) + }; + let input = usage.input_tokens?; + let output = usage.output_tokens?; + let long = input > 200_000 && band("long_standard").is_some(); + let rates = band(if long { "long_standard" } else { "standard" })?; + let image_rates = band("image"); + // 图片模型必须报告输出模态数量,避免把图片误按文本单价计费 + let image_output = if image_rates.is_some() { + usage.image_output_tokens? + } else { + usage.image_output_tokens.unwrap_or_default() + }; + let text_output = output.checked_sub(image_output)?; + let output_ticks = u128::from(text_output) + .checked_mul(rates.output.ticks_per_token())? + .checked_add(u128::from(image_output).checked_mul(if image_output == 0 { + 0 + } else { + image_rates?.output.ticks_per_token() + })?)?; + let (input, cached, image) = split_image_input(usage, rates, image_rates)?; + let written = usage.cache_write_input_tokens.unwrap_or_default(); + let uncached = input.checked_sub(cached)?.checked_sub(written)?; + // 原生用量已经把 thoughts 合入 output;缓存也是 input 的子集,不能重复收费 + let input_amount = usd(u128::from(uncached).checked_mul(rates.input.ticks_per_token())?)?; + let output_amount = usd(output_ticks)?; + let cache_read_amount = + usd(u128::from(cached).checked_mul(rates.cache_read.ticks_per_token())?)?; + let cache_write_amount = + usd(u128::from(written).checked_mul(rates.cache_write.ticks_per_token())?)?; + let mut total = input_amount + .checked_add(output_amount)? + .checked_add(cache_read_amount)? + .checked_add(cache_write_amount)?; + if let Some(image) = &image { + total = total + .checked_add(image.input_amount)? + .checked_add(image.cache_read_amount)?; + } + let mut breakdown = CalculatedCostBreakdown::new( + CalculatedCostAmounts::new( + input_amount, + output_amount, + cache_read_amount, + cache_write_amount, + total, + total, + ), + CalculatedCostRates::new( + usd(rates.input.ticks_per_token().checked_mul(1_000_000)?)?, + // 混合输出展示加权单价,费用直接按各模态整数 Token 计算 + usd(if output == 0 { + rates.output.ticks_per_token().checked_mul(1_000_000)? + } else { + output_ticks + .checked_mul(1_000_000)? + .checked_div(u128::from(output))? + })?, + usd(rates.cache_read.ticks_per_token().checked_mul(1_000_000)?)?, + usd(rates.cache_write.ticks_per_token().checked_mul(1_000_000)?)?, + ), + None, + 100, + ) + .with_long_context_billing(long); + if let Some(image) = image { + breakdown = breakdown.with_image(image); + } + breakdown.with_custom_multiplier(pricing.map_or(10_000, |p| p.multiplier_bps)) +} + +/// 输入模态同价时直接计总量;异价且缓存只给总量时,只接受能唯一拆分的情况 +fn split_image_input( + usage: &Usage, + text: &TokenPriceOverride, + image: Option<&TokenPriceOverride>, +) -> Option<(u64, u64, Option)> { + let input = usage.input_tokens?; + let cached = usage.cached_input_tokens.unwrap_or_default(); + let Some(image) = image.filter(|image| { + image.input != text.input + || image.cache_read != text.cache_read + || image.cache_write != text.cache_write + }) else { + return Some((input, cached, None)); + }; + let image_input = usage.image_input_tokens?; + let text_input = input.checked_sub(image_input)?; + if image_input == 0 { + return Some((input, cached, None)); + } + if usage.cache_write_input_tokens.unwrap_or_default() != 0 { + return None; + } + let image_cached = match (text_input, cached) { + (_, 0) => 0, + (0, cached) => cached, + (_, cached) if cached == input => image_input, + _ => return None, + }; + Some(( + text_input, + cached.checked_sub(image_cached)?, + Some(ImageCostBreakdown { + input_tokens: image_input, + cached_input_tokens: image_cached, + input_amount: usd(u128::from(image_input.checked_sub(image_cached)?) + .checked_mul(image.input.ticks_per_token())?)?, + cache_read_amount: usd( + u128::from(image_cached).checked_mul(image.cache_read.ticks_per_token())? + )?, + input_price_per_million: usd(image.input.ticks_per_token().checked_mul(1_000_000)?)?, + cache_read_price_per_million: usd(image + .cache_read + .ticks_per_token() + .checked_mul(1_000_000)?)?, + }), + )) +} + +fn usd(ticks: u128) -> Option { + Some(Money::new( + Decimal::from_scaled(ticks).ok()?, + CurrencyCode::new("USD").ok()?, + )) +} + +/// 在请求开始时冻结内置、同步和人工价,随后不再读取可变设置 +pub(crate) fn effective_pricing( + model: &str, + custom: Option<&ModelPriceOverride>, +) -> Option { + let mut result = defaults().get(model).cloned().or_else(|| custom.cloned())?; + if let Some(custom) = custom { + result.bands.extend(custom.bands.clone()); + result.multiplier_bps = custom.multiplier_bps; + } + Some(result) +} + +/// 现有用量合同没有音频子计数;含音视频的请求不能按文本参考单价估算 +pub(crate) fn supports_pricing(value: &serde_json::Value) -> bool { + match value { + serde_json::Value::Object(fields) => supports_pricing_fields(fields), + serde_json::Value::Array(values) => values.iter().all(supports_pricing), + _ => true, + } +} + +pub(crate) fn supports_pricing_fields(fields: &serde_json::Map) -> bool { + fields.iter().all(|(key, value)| { + if matches!(key.as_str(), "mimeType" | "mime_type") + && value + .as_str() + .is_some_and(|mime| mime.starts_with("audio/") || mime.starts_with("video/")) + { + return false; + } + if key == "modality" && value.as_str() == Some("AUDIO") { + return false; + } + supports_pricing(value) + }) +} diff --git a/backend/crates/providers/antigravity/src/billing/catalog.rs b/backend/crates/providers/antigravity/src/billing/catalog.rs new file mode 100644 index 000000000..3661703fa --- /dev/null +++ b/backend/crates/providers/antigravity/src/billing/catalog.rs @@ -0,0 +1,230 @@ +//! 内置参考价与外部来源映射共用一份明确的模型登记 +// 2026-11-24 核验,USD / 百万 Token: +// https://aistudio.google.com/docs/pricing +// https://platform.claude.com/docs/en/about-claude/pricing +// https://cloud.google.com/model-garden/partner-models/pricing +// 仅登记公开基础模型及其思考档位;Tab、sonar、tiered 等内部型号不猜测对应关系 + +pub(crate) const SUPPORTED_PRICING_BANDS: &[&str] = &["standard", "long_standard", "image"]; + +use gateway_admin::ports::pricing::PricingSourceModel; +use gateway_core::metering::{ModelPriceOverride, TokenPriceOverride}; +use std::{collections::BTreeMap, sync::LazyLock}; + +struct Family { + provider: &'static str, + source: &'static str, + models: &'static [&'static str], + standard: [&'static str; 4], + long: Option<[&'static str; 4]>, + image: Option<[&'static str; 4]>, +} + +const FAMILIES: &[Family] = &[ + Family { + provider: "anthropic", + source: "claude-opus-5-5", + models: &[ + "claude-opus-5-5-low", + "claude-opus-5-5-medium", + "claude-opus-5-5-high", + ], + standard: ["4", "20", "0.2", "5"], + long: None, + image: None, + }, + Family { + provider: "anthropic", + source: "claude-sonnet-5-5", + models: &[ + "claude-sonnet-5-5-low", + "claude-sonnet-5-5-medium", + "claude-sonnet-5-5-high", + ], + standard: ["2", "10", "0.1", "2.5"], + long: None, + image: None, + }, + Family { + provider: "google", + source: "gemini-2.5-flash", + models: &["gemini-2.5-flash", "gemini-2.5-flash-thinking"], + standard: ["0.3", "2.5", "0.03", "0.3"], + long: None, + image: None, + }, + Family { + provider: "google", + source: "gemini-2.5-flash-lite", + models: &["gemini-2.5-flash-lite"], + standard: ["0.1", "0.4", "0.01", "0.1"], + long: None, + image: None, + }, + Family { + provider: "google", + source: "gemini-2.5-pro", + models: &["gemini-2.5-pro"], + standard: ["1.25", "10", "0.125", "1.25"], + long: Some(["2.5", "15", "0.25", "2.5"]), + image: None, + }, + Family { + provider: "google", + source: "gemini-3-flash-preview", + models: &["gemini-3-flash"], + standard: ["0.5", "3", "0.05", "0.5"], + long: None, + image: None, + }, + Family { + provider: "google", + source: "gemini-3.1-flash-lite", + models: &["gemini-3.1-flash-lite"], + standard: ["0.25", "1.5", "0.025", "0.25"], + long: None, + image: None, + }, + Family { + provider: "google", + source: "gemini-3.5-flash-lite", + models: &["gemini-3.5-flash-lite"], + standard: ["0.3", "2.5", "0.03", "0.3"], + long: None, + image: None, + }, + Family { + provider: "google", + source: "gemini-3.8-flash", + models: &[ + "gemini-3.8-flash-low", + "gemini-3.8-flash-medium", + "gemini-3.8-flash-high", + ], + standard: ["0.75", "3.75", "0.075", "0.75"], + long: None, + image: None, + }, + Family { + provider: "google", + source: "gemini-4-argon", + models: &[ + "gemini-4-argon-low", + "gemini-4-argon-medium", + "gemini-4-argon-high", + ], + standard: ["2", "10", "0.1", "2"], + long: None, + image: None, + }, + Family { + provider: "google", + source: "gemini-4-carbon", + models: &[ + "gemini-4-carbon-low", + "gemini-4-carbon-medium", + "gemini-4-carbon-high", + ], + standard: ["2", "10", "0.1", "2"], + long: None, + image: None, + }, + Family { + provider: "google", + source: "gemini-4-hydrogen", + models: &[ + "gemini-4-hydrogen-low", + "gemini-4-hydrogen-medium", + "gemini-4-hydrogen-high", + "gemini-4-hydrogen-xhigh", + ], + standard: ["1.5", "7.5", "0.075", "1.5"], + long: None, + image: None, + }, + Family { + provider: "google", + source: "gemini-4-neon", + models: &[ + "gemini-4-neon-low", + "gemini-4-neon-medium", + "gemini-4-neon-high", + "gemini-4-neon-xhigh", + ], + standard: ["3", "15", "0.15", "3"], + long: None, + image: None, + }, + Family { + provider: "google", + source: "gemini-3.1-flash-image", + models: &["gemini-3.1-flash-image"], + standard: ["0.5", "3", "0.5", "0.5"], + long: None, + image: Some(["0.5", "60", "0.5", "0.5"]), + }, + Family { + provider: "google-vertex", + source: "openai/gpt-oss-120b-maas", + models: &["gpt-oss-120b-medium"], + standard: ["0.09", "0.36", "0.09", "0.09"], + long: None, + image: None, + }, +]; + +pub(crate) fn defaults() -> &'static BTreeMap { + static CATALOG: LazyLock> = LazyLock::new(|| { + let mut result = BTreeMap::new(); + for family in FAMILIES { + let mut bands = BTreeMap::from([("standard".to_owned(), rates(family.standard))]); + if let Some(long) = family.long { + bands.insert("long_standard".to_owned(), rates(long)); + } + if let Some(image) = family.image { + bands.insert("image".to_owned(), rates(image)); + } + let price = ModelPriceOverride { + multiplier_bps: 10_000, + bands, + }; + for model in family.models { + result.insert((*model).to_owned(), price.clone()); + } + } + result + }); + &CATALOG +} + +pub(crate) fn source_models() -> BTreeMap { + FAMILIES + .iter() + .flat_map(|family| { + family.models.iter().map(|model| { + ( + (*model).to_owned(), + PricingSourceModel { + provider: family.provider.to_owned(), + model: family.source.to_owned(), + }, + ) + }) + }) + .collect() +} + +fn rates([input, output, cache_read, cache_write]: [&str; 4]) -> TokenPriceOverride { + let price = |value: &str| { + value + .to_owned() + .try_into() + .expect("valid builtin token price") + }; + TokenPriceOverride { + input: price(input), + output: price(output), + cache_read: price(cache_read), + cache_write: price(cache_write), + } +} diff --git a/backend/crates/providers/antigravity/src/billing/mod.rs b/backend/crates/providers/antigravity/src/billing/mod.rs new file mode 100644 index 000000000..21fc1ad52 --- /dev/null +++ b/backend/crates/providers/antigravity/src/billing/mod.rs @@ -0,0 +1,10 @@ +//! Antigravity 参考价目与本地费用估算入口 + +mod calculate; +mod catalog; + +pub(crate) use calculate::{ + calculate, effective_pricing, supports_pricing, supports_pricing_fields, +}; +pub(crate) use catalog::SUPPORTED_PRICING_BANDS; +pub(crate) use catalog::{defaults, source_models}; diff --git a/backend/crates/providers/antigravity/src/credential/authorization.rs b/backend/crates/providers/antigravity/src/credential/authorization.rs new file mode 100644 index 000000000..caf41dcb2 --- /dev/null +++ b/backend/crates/providers/antigravity/src/credential/authorization.rs @@ -0,0 +1,210 @@ +//! 绑定管理员与 OAuth 注册的短期授权流程,由 Admin 在账号事务提交后消费 + +use async_trait::async_trait; +use chrono::Utc; +use gateway_admin::{ + model::{ + AdminError, + provider_credentials::{ + AuthorizationCommitGuard, AuthorizationMutationTarget, AuthorizationOwner, + AuthorizationOwnerBinding, AuthorizationStarted, CompleteAuthorization, + PendingAuthorizationMutation, PreparedAuthorizationCommit, + }, + }, + ports::provider::{ProviderAdminError, ProviderAdminErrorKind as Kind}, +}; +use gateway_core::{ + account::OpaqueProviderData, + provider_ports::{ + NewOAuthPendingFlow, OAuthPendingBinding, OAuthPendingClaimOutcome, + OAuthPendingConsumeOutcome, OAuthPendingFlowPort, OAuthPendingPutOutcome, + OAuthPendingReleaseOutcome, + }, + routing::ProviderKind, +}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::{sync::Arc, time::Duration}; + +use crate::credential::{ + CredentialService, + oauth::{GoogleOAuth, error, random_value}, +}; + +const FLOW_TTL: Duration = Duration::from_secs(600); + +#[derive(Serialize, Deserialize)] +struct Pending { + registration: String, + state: String, + verifier: String, + mutation: Value, +} + +struct Claim { + store: Arc, + kind: ProviderKind, + flow: OAuthPendingBinding, + owner: OAuthPendingBinding, + claim: OAuthPendingBinding, +} + +fn binding(value: String) -> Result { + OAuthPendingBinding::try_new(value).map_err(|_| error(Kind::Invalid)) +} + +fn owner_binding( + owner: &AuthorizationOwnerBinding, +) -> Result { + binding(match owner.owner() { + AuthorizationOwner::AdminSession { admin_user_id } => { + format!("admin-session/{admin_user_id}") + } + AuthorizationOwner::System => "system".into(), + AuthorizationOwner::AdminApiKey => "admin-api-key".into(), + }) +} + +#[async_trait] +impl AuthorizationCommitGuard for Claim { + async fn commit(self: Box) -> Result<(), AdminError> { + match self + .store + .consume_claim(&self.kind, &self.flow, &self.owner, &self.claim) + .await + { + Ok(OAuthPendingConsumeOutcome::Consumed) => Ok(()), + Ok(_) => Err(AdminError::conflict("授权状态已变更,请核对账号状态")), + Err(_) => Err(AdminError::unavailable("无法结算授权流程")), + } + } + async fn abort(self: Box) -> Result<(), AdminError> { + match self + .store + .release_claim(&self.kind, &self.flow, &self.owner, &self.claim) + .await + { + Ok(OAuthPendingReleaseOutcome::Released) => Ok(()), + _ => Err(AdminError::unavailable("无法释放授权流程")), + } + } +} + +pub(crate) struct AuthorizationService { + pub(crate) kind: ProviderKind, + pub(crate) credentials: Arc, + pub(crate) oauth: Arc, + pub(crate) store: Arc, +} + +impl AuthorizationService { + pub(crate) async fn start( + &self, + mutation: PendingAuthorizationMutation, + ) -> Result { + let oauth = &self.oauth; + if mutation.provider_kind() != &self.kind { + return Err(error(Kind::Invalid)); + } + if let AuthorizationMutationTarget::Reauthorize { account_id } = mutation.target() { + self.credentials.current(account_id).await?; + } + let flow_id = random_value()?; + let state = random_value()?; + let verifier = random_value()?; + let authorization_url = oauth.authorize_url(&state, &verifier)?; + let stored = Pending { + state, + verifier, + registration: oauth.registration(), + mutation: Value::Object(mutation.to_storage_v1()), + }; + let Value::Object(payload) = + serde_json::to_value(stored).map_err(|_| error(Kind::Internal))? + else { + return Err(error(Kind::Internal)); + }; + let record = NewOAuthPendingFlow::try_new( + self.kind.clone(), + binding(flow_id.clone())?, + owner_binding(mutation.owner_binding())?, + FLOW_TTL, + OpaqueProviderData::new(payload), + ) + .map_err(|_| error(Kind::Internal))?; + let expires_at = Utc::now() + FLOW_TTL; + match self.store.clone().put_if_absent(record).await { + Ok(OAuthPendingPutOutcome::Stored) => Ok(AuthorizationStarted { + flow_id, + authorization_url, + expires_at, + }), + _ => Err(error(Kind::Unavailable)), + } + } + + pub(crate) async fn complete( + &self, + command: CompleteAuthorization, + ) -> Result { + let owner = AuthorizationOwnerBinding::from_context(&command.context); + let guard = Box::new(Claim { + store: self.store.clone(), + kind: self.kind.clone(), + flow: binding(command.flow_id)?, + owner: owner_binding(&owner)?, + claim: binding(random_value()?)?, + }); + let payload = match guard + .store + .claim_if_owner( + &guard.kind, + &guard.flow, + &guard.owner, + &guard.claim, + Duration::from_secs(120), + ) + .await + .map_err(|_| error(Kind::Unavailable))? + { + OAuthPendingClaimOutcome::Claimed(payload) => payload, + OAuthPendingClaimOutcome::InProgress => return Err(error(Kind::Conflict)), + OAuthPendingClaimOutcome::NotFound | OAuthPendingClaimOutcome::OwnerMismatch => { + return Err(error(Kind::NotFound)); + } + }; + let result = async { + let pending: Pending = serde_json::from_value(Value::Object(payload.into_inner())) + .map_err(|_| error(Kind::Internal))?; + let mutation = PendingAuthorizationMutation::from_storage_v1(pending.mutation) + .map_err(|_| error(Kind::Internal))?; + let oauth = &self.oauth; + if mutation.provider_kind() != &self.kind + || mutation.owner_binding().owner() != owner.owner() + || pending.registration != oauth.registration() + { + return Err(error(Kind::Conflict)); + } + let code = oauth.callback_code(&command.callback_url, &pending.state)?; + let profile = self.credentials.request_profile().await?; + let grant = oauth + .exchange( + &code, + &pending.verifier, + mutation.outbound_proxy(), + &profile, + ) + .await?; + let credential = self.credentials.prepare_grant(&mutation, grant).await?; + Ok(PreparedAuthorizationCommit::new(mutation, credential)) + } + .await; + match result { + Ok(prepared) => Ok(prepared.with_authorization_guard(guard)), + Err(e) => { + guard.abort().await.map_err(|_| error(Kind::Unavailable))?; + Err(e) + } + } + } +} diff --git a/backend/crates/providers/antigravity/src/credential/catalog.rs b/backend/crates/providers/antigravity/src/credential/catalog.rs new file mode 100644 index 000000000..f80ecd4ea --- /dev/null +++ b/backend/crates/providers/antigravity/src/credential/catalog.rs @@ -0,0 +1,370 @@ +//! 将资源服务确认的项目与模型绑定到授权注册和账号凭据版本 + +use crate::{ + credential::{CredentialService, oauth::error}, + profile::ReleaseService, + transport::{Catalog, CloudCodeClient, unsent}, +}; +use gateway_admin::{ + model::provider_credentials::{ProviderModel, ProviderModels}, + ports::provider::{ProviderAdminError, ProviderAdminErrorKind as AdminKind}, +}; +use gateway_core::{ + account::{AccountCatalogObservation, ProviderAccountId, StoredAccountCatalog}, + error::{ProviderError, ProviderErrorKind as Kind}, + operation::OperationKind, + routing::{ModelCapabilities, ProviderModelCapabilities, UpstreamModelId}, +}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::{ + Arc, Mutex, + atomic::{AtomicU64, AtomicUsize, Ordering}, + }, + time::{Duration, SystemTime}, +}; + +pub(crate) struct CatalogService { + credentials: Arc, + kind: gateway_core::routing::ProviderKind, + accounts: Arc, + registration: String, + pub(crate) release: Arc, + pub(crate) origin: url::Url, + pub(crate) generation: AtomicU64, + observed: + Mutex>, + refresh_cursor: AtomicUsize, +} + +pub(crate) struct RefreshCatalog { + observation: AccountCatalogObservation, + document: bytes::Bytes, +} + +impl CatalogService { + pub(crate) async fn capture_refresh_catalogs( + &self, + candidates: &[gateway_core::account::LoadedCredential], + ) -> Result, ProviderAdminError> { + let candidates: BTreeMap<_, _> = candidates + .iter() + .map(|loaded| (loaded.account.id(), &loaded.account)) + .collect(); + let stored = self + .accounts + .load_account_catalogs(&self.kind) + .await + .map_err(|e| error(AdminKind::Unavailable).with_source(e))?; + let mut snapshots = BTreeMap::new(); + for catalog in stored { + for observation in catalog.accounts { + if candidates + .get(&observation.account_id) + .is_some_and(|account| { + account.revision() == observation.revision + && account.plan_type() == observation.plan.as_deref() + && observation.etag.as_ref() == Some(&self.registration) + }) + { + snapshots.insert( + observation.account_id.clone(), + RefreshCatalog { + observation, + document: catalog.document.clone(), + }, + ); + } + } + } + Ok(snapshots) + } + + pub(crate) async fn after_credential_refresh( + &self, + account_id: &ProviderAccountId, + revision: gateway_core::account::CredentialRevision, + snapshot: Option, + ) -> Result<(), ProviderAdminError> { + if let Some(mut snapshot) = snapshot { + // OAuth 续期已核对同一身份;沿用观测时间,存储仍校验新 revision 和原套餐 + snapshot.observation.revision = revision; + if self + .accounts + .save_account_catalog(&snapshot.observation, &snapshot.document) + .await + .map_err(|e| error(AdminKind::Unavailable).with_source(e))? + { + self.invalidate(); + return Ok(()); + } + } + // 401 过期账号不会进入旧目录读取;新 AT 提交后立即尝试恢复,失败再由目录任务重试 + self.account_models(account_id, false).await.map(|_| ()) + } + + pub(crate) fn new( + kind: gateway_core::routing::ProviderKind, + accounts: Arc, + credentials: Arc, + registration: String, + origin: url::Url, + release: Arc, + ) -> Self { + Self { + kind, + accounts, + credentials, + registration, + origin, + release, + generation: AtomicU64::new(0), + observed: Mutex::default(), + refresh_cursor: AtomicUsize::new(0), + } + } + + pub(crate) fn invalidate(&self) { + self.generation.fetch_add(1, Ordering::Relaxed); + } + pub(crate) async fn catalogs( + &self, + ) -> Result, Catalog)>, ProviderError> { + let registration = &self.registration; + let docs = self + .accounts + .load_account_catalogs(&self.kind) + .await + .map_err(|e| unsent(Kind::ProviderInfrastructureUnavailable).with_source(e))?; + let mut result = Vec::new(); + for StoredAccountCatalog { accounts, document } in docs { + let accounts: Vec<_> = accounts + .into_iter() + .filter(|a| a.etag.as_ref() == Some(registration)) + .collect(); + if !accounts.is_empty() { + let catalog = serde_json::from_slice(&document) + .map_err(|e| unsent(Kind::ProviderInfrastructureUnavailable).with_source(e))?; + result.push((accounts, catalog)); + } + } + let observations = result + .iter() + .flat_map(|(accounts, _)| accounts.iter()) + .map(|a| (a.account_id.clone(), (a.revision, a.observed_at))) + .collect(); + let mut observed = self + .observed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if *observed != observations { + *observed = observations; + self.invalidate(); + } + Ok(result) + } + + pub(crate) async fn capabilities( + &self, + ) -> Result, ProviderError> { + let mut models: BTreeMap> = BTreeMap::new(); + for (accounts, catalog) in self.catalogs().await? { + for key in catalog.models.into_keys() { + let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?; + models + .entry(id) + .or_default() + .extend(accounts.iter().map(|a| a.account_id.clone())); + } + } + Ok(models + .into_iter() + .map(|(model, accounts)| { + ProviderModelCapabilities::new( + model, + ModelCapabilities::new( + [OperationKind::Generate, OperationKind::CountTokens].into(), + None, + ) + .with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL) + .with_translated_generation_protocols([ + gateway_protocol::openai::OPENAI_PROTOCOL, + gateway_protocol::anthropic::ANTHROPIC_PROTOCOL, + ]) + .with_upstream_feature_validation(), + ) + .with_catalog_accounts(accounts) + }) + .collect()) + } + + pub(crate) async fn account_models( + &self, + id: &ProviderAccountId, + refresh: bool, + ) -> Result { + let current = self.credentials.current(id).await?; + if !refresh { + for (accounts, cat) in self + .catalogs() + .await + .map_err(|e| error(AdminKind::Unavailable).with_source(e))? + { + if let Some(a) = accounts + .iter() + .find(|a| &a.account_id == id && a.revision == current.account.revision()) + { + return admin_models(cat, a.observed_at); + } + } + } + let material = self + .credentials + .material(¤t) + .map_err(|e| error(AdminKind::CredentialRefreshRequired).with_source(e))?; + let client = CloudCodeClient::new( + &self.origin, + current.account.outbound_proxy(), + &crate::profile::default_profile(&self.release), + ) + .map_err(|e| error(AdminKind::Unavailable).with_source(e))?; + let observed_at = SystemTime::now(); + let catalog = client + .catalog(&material.access_token) + .await + .map_err(|e| match e.kind() { + Kind::Unauthorized => error(AdminKind::CredentialRefreshRequired).with_source(e), + _ => error(AdminKind::Unavailable) + .with_public_message("Antigravity 项目或模型目录查询失败") + .with_source(e), + })?; + self.publish( + ¤t.account, + current.account.plan_type().map(str::to_owned), + catalog, + observed_at, + ) + .await + } + + pub(crate) async fn publish( + &self, + account: &gateway_core::account::ProviderAccount, + plan: Option, + mut catalog: Catalog, + observed_at: SystemTime, + ) -> Result { + // 模型目录只拥有能力事实,易变的额度由独立快照保存 + for model in catalog.models.values_mut() { + model.quota = None; + } + let observed = AccountCatalogObservation { + account_id: account.id().clone(), + revision: account.revision(), + plan, + etag: Some(self.registration.clone()), + observed_at, + }; + let body = serde_json::to_vec(&catalog).map_err(|_| error(AdminKind::Internal))?; + if !self + .accounts + .save_account_catalog(&observed, &body) + .await + .map_err(|e| error(AdminKind::Unavailable).with_source(e))? + { + return Err(error(AdminKind::Conflict)); + } + self.generation.fetch_add(1, Ordering::Relaxed); + admin_models(catalog, observed_at) + } +} + +fn admin_models( + catalog: Catalog, + observed: SystemTime, +) -> Result { + let models = catalog + .models + .into_iter() + .map(|(id, m)| { + Ok(ProviderModel { + name: if m.name.is_empty() { + id.clone() + } else { + m.name + }, + id: UpstreamModelId::new(id).map_err(|_| error(AdminKind::Invalid))?, + }) + }) + .collect::>()?; + Ok(ProviderModels { + models, + observed_at: Some(observed.into()), + }) +} + +pub(crate) struct CatalogTask(pub(crate) Arc); +impl gateway_core::task::ScheduledTask for CatalogTask { + fn run_cycle( + &self, + context: gateway_core::task::WorkerCycleContext, + ) -> futures::future::BoxFuture<'_, Result<(), gateway_core::task::WorkerTaskError>> { + Box::pin(async move { self.0.reconcile(context.cancellation()).await }) + } +} +impl CatalogService { + pub(crate) async fn reconcile( + &self, + cancellation: &gateway_core::lifecycle::CancellationToken, + ) -> Result<(), gateway_core::task::WorkerTaskError> { + use futures::{StreamExt, stream}; + use gateway_core::task::WorkerTaskError; + let catalogs = self + .catalogs() + .await + .map_err(|e| WorkerTaskError::safe("读取 Antigravity 目录失败").with_source(e))?; + let observations: BTreeMap<_, _> = catalogs + .into_iter() + .flat_map(|(accounts, _)| accounts) + .map(|a| (a.account_id.clone(), a)) + .collect(); + let mut due = self + .accounts + .list_for_provider(&self.kind, false) + .await + .map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?; + due.retain(|account| { + account.authentication_kind() == "oauth" + && observations.get(account.id()).is_none_or(|observation| { + observation.revision != account.revision() + || observation.observed_at.elapsed().unwrap_or_default() + >= Duration::from_secs(3600) + }) + }); + if due.is_empty() { + return Ok(()); + } + due.sort_by(|a, b| a.id().cmp(b.id())); + // 固定大小轮转批次,持续失败的账号不能阻塞后面的目录修复 + let offset = self.refresh_cursor.fetch_add(32, Ordering::Relaxed) % due.len(); + due.rotate_left(offset); + due.truncate(32); + let mut updates=stream::iter(due).map(|account|async move { + tokio::select! {biased;_=cancellation.cancelled()=>Ok(()),result=self.account_models(account.id(),true)=>result.map(|_|())} + }).buffer_unordered(4); + let mut first_error = None; + while let Some(result) = updates.next().await { + if let Err(error) = result + && !matches!( + error.kind(), + AdminKind::Conflict | AdminKind::CredentialRefreshRequired + ) + { + first_error.get_or_insert(error); + } + } + first_error.map_or(Ok(()), |error| { + Err(WorkerTaskError::safe("部分 Antigravity 模型目录刷新失败").with_source(error)) + }) + } +} diff --git a/backend/crates/providers/antigravity/src/credential/documents.rs b/backend/crates/providers/antigravity/src/credential/documents.rs new file mode 100644 index 000000000..fb3cb07e5 --- /dev/null +++ b/backend/crates/providers/antigravity/src/credential/documents.rs @@ -0,0 +1,189 @@ +//! CPR 原生账号文件包含可续期凭据与已存观测,导入重新验证身份与权限 + +use super::{ + CredentialService, Material, + oauth::{error, valid_token}, +}; +use chrono::{DateTime, Utc}; +use gateway_admin::{ + model::provider_credentials::{ + PrepareCredentialImport, PrepareCredentialRotation, PreparedCredentialImport, + PreparedCredentialRotation, ProviderDocument, ProviderExport, + ProviderExportCredentialInput, + }, + ports::provider::{ProviderAdminError, ProviderAdminErrorKind as Kind}, +}; +use gateway_core::account::{OpaqueProviderData, ProviderAccountId}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::HashSet; + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct AccountFile { + provider: String, + version: u32, + accounts: Vec, +} + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AccountEntry { + #[serde(default, skip_serializing_if = "String::is_empty")] + label: String, + refresh_token: String, + // 以下为导出时的已有观测,导入仍以 Google 刷新及身份查询的结果为准 + #[serde(skip_serializing_if = "Option::is_none")] + access_token: Option, + #[serde(skip_serializing_if = "Option::is_none")] + access_token_expires_at: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + email: Option, + #[serde(skip_serializing_if = "Option::is_none")] + user_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + scopes: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + plan_type: Option, + #[serde(skip_serializing_if = "Option::is_none")] + created_at: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + updated_at: Option>, +} + +impl CredentialService { + pub(crate) async fn prepare_import( + &self, + input: PrepareCredentialImport, + ) -> Result { + let file: AccountFile = serde_json::from_value(Value::Object( + input.document.into_provider_data().into_inner(), + )) + .map_err(|_| error(Kind::Invalid))?; + if file.provider != self.kind.as_str() || file.version != 1 || file.accounts.is_empty() { + return Err(error(Kind::Invalid)); + } + let mut tokens = HashSet::new(); + // 全部本地格式检查先于任何可能轮换 RT 的上游请求 + for entry in &file.accounts { + if entry.label.chars().any(char::is_control) + || !valid_token(&entry.refresh_token) + || !tokens.insert(entry.refresh_token.as_str()) + { + return Err(error(Kind::Invalid)); + } + } + let mut credentials = Vec::with_capacity(file.accounts.len()); + let mut subjects = HashSet::new(); + let profile = self.request_profile().await?; + for entry in file.accounts { + let grant = self + .oauth + .verify_import( + &entry.refresh_token, + input.default_outbound_proxy.as_ref(), + &profile, + ) + .await?; + if !subjects.insert(grant.material.subject.clone()) { + return Err( + error(Kind::Conflict).with_public_message("导入文件包含重复的 Google 账号") + ); + } + credentials.push(self.prepare_create( + entry.label, + grant, + input.default_outbound_proxy.clone(), + )?); + } + Ok(PreparedCredentialImport { + provider_kind: self.kind.clone(), + credentials, + }) + } + + pub(crate) async fn prepare_rotation( + &self, + input: PrepareCredentialRotation, + ) -> Result { + if input.account.provider_kind != self.kind || input.account.authentication_kind != "oauth" + { + return Err(error(Kind::Invalid)); + } + let account_id = + ProviderAccountId::new(input.account.id).map_err(|_| error(Kind::Invalid))?; + let current = self.current(&account_id).await?; + if current.account.revision().get() != input.account.credential_revision.get() { + return Err(error(Kind::Conflict)); + } + let entry: AccountEntry = serde_json::from_value(Value::Object( + input.provider_material.into_provider_data().into_inner(), + )) + .map_err(|_| error(Kind::Invalid))?; + let guards = self.lock_rotation(¤t.account).await?; + let profile = self.request_profile().await?; + let grant = self + .oauth + .verify_import( + &entry.refresh_token, + current.account.outbound_proxy(), + &profile, + ) + .await?; + // 同一 subject 的更新保持本地名称;另一账号只能作为新账号导入 + self.rotation(¤t.account, grant, guards) + } + + pub(crate) fn export_credentials( + &self, + credentials: Vec, + ) -> Result { + let mut account_ids = Vec::with_capacity(credentials.len()); + let mut accounts = Vec::with_capacity(credentials.len()); + for input in credentials { + if input.account.provider_kind != self.kind + || input.account.authentication_kind != "oauth" + { + return Err(error(Kind::Invalid)); + } + let material: Material = serde_json::from_value(Value::Object( + input.provider_material.into_provider_data().into_inner(), + )) + .map_err(|_| error(Kind::Invalid))?; + if material.registration != self.oauth.registration() + || input.account.upstream_user_id.as_deref() != Some(material.subject.as_str()) + || !valid_token(&material.refresh_token) + { + return Err(error(Kind::Invalid)); + } + account_ids + .push(ProviderAccountId::new(input.account.id).map_err(|_| error(Kind::Invalid))?); + accounts.push(AccountEntry { + label: input.account.name, + refresh_token: material.refresh_token, + access_token: Some(material.access_token), + access_token_expires_at: input.account.access_token_expires_at, + email: input.account.email, + user_id: Some(material.subject), + scopes: Some(material.scopes), + plan_type: input.account.plan_type, + created_at: Some(input.account.created_at), + updated_at: Some(input.account.updated_at), + }); + } + let Value::Object(document) = serde_json::to_value(AccountFile { + provider: self.kind.as_str().to_owned(), + version: 1, + accounts, + }) + .map_err(|_| error(Kind::Internal))? + else { + return Err(error(Kind::Internal)); + }; + Ok(ProviderExport { + provider_kind: self.kind.clone(), + account_ids, + document: ProviderDocument::new(OpaqueProviderData::new(document)), + }) + } +} diff --git a/backend/crates/providers/antigravity/src/credential/mod.rs b/backend/crates/providers/antigravity/src/credential/mod.rs new file mode 100644 index 000000000..579d05312 --- /dev/null +++ b/backend/crates/providers/antigravity/src/credential/mod.rs @@ -0,0 +1,12 @@ +//! OAuth 流程、账号凭据与文件导入导出 + +mod authorization; +pub(crate) mod catalog; +mod documents; +pub(crate) mod oauth; +pub(crate) mod quota; +mod refresh; +mod service; +pub(crate) use authorization::AuthorizationService; +pub(crate) use oauth::{GoogleOAuth, Material}; +pub(crate) use service::CredentialService; diff --git a/backend/crates/providers/antigravity/src/credential/oauth.rs b/backend/crates/providers/antigravity/src/credential/oauth.rs new file mode 100644 index 000000000..67fe83ff5 --- /dev/null +++ b/backend/crates/providers/antigravity/src/credential/oauth.rs @@ -0,0 +1,515 @@ +//! Provider 的 OAuth 客户端、PKCE 及 Google 身份校验 + +use std::{fmt, time::Duration}; + +use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; +use chrono::{DateTime, Utc}; +use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind}; +use gateway_core::account::OutboundProxy; +use reqwest::{Client, RequestBuilder}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use sha2::{Digest, Sha256}; +use url::Url; + +use crate::ConfigError; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct OAuthRegistration { + client_id: String, + client_secret: String, + redirect_uri: String, + resource_scopes: Vec, + resource_origin: Url, +} + +impl fmt::Debug for OAuthRegistration { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("OAuthRegistration([REDACTED])") + } +} + +impl OAuthRegistration { + pub(super) fn validate(&self) -> Result<(), ConfigError> { + let url = Url::parse(&self.redirect_uri).map_err(|_| ConfigError)?; + let loopback = matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")); + let origin = &self.resource_origin; + let local = matches!(origin.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")); + if origin.host().is_none() + || !(origin.scheme() == "https" || local && origin.scheme() == "http") + || !origin.username().is_empty() + || origin.password().is_some() + || origin.path() != "/" + || origin.query().is_some() + || origin.fragment().is_some() + { + return Err(ConfigError); + } + if !(url.scheme() == "https" || (url.scheme() == "http" && loopback)) + || url.host().is_none() + || !url.username().is_empty() + || url.password().is_some() + || url.fragment().is_some() + || url.query().is_some() + || !valid_token(&self.client_id) + || !valid_token(&self.client_secret) + || self.resource_scopes.is_empty() + || self.resource_scopes.iter().any(|scope| { + !valid_token(scope) + || matches!( + scope.as_str(), + "openid" + | "email" + | "profile" + | "https://www.googleapis.com/auth/userinfo.email" + | "https://www.googleapis.com/auth/userinfo.profile" + ) + }) + { + return Err(ConfigError); + } + Ok(()) + } +} + +pub(crate) fn error(kind: ProviderAdminErrorKind) -> ProviderAdminError { + ProviderAdminError::new(kind) +} + +fn invalid() -> ProviderAdminError { + error(ProviderAdminErrorKind::Invalid) +} +fn unavailable() -> ProviderAdminError { + error(ProviderAdminErrorKind::Unavailable) +} +pub(super) fn valid_token(s: &str) -> bool { + !s.is_empty() && s.len() <= 16384 && s.bytes().all(|b| b.is_ascii_graphic()) +} + +pub(super) fn random_value() -> Result { + let mut bytes = [0; 32]; + getrandom::fill(&mut bytes).map_err(|_| unavailable())?; + Ok(URL_SAFE_NO_PAD.encode(bytes)) +} + +pub(crate) struct GoogleOAuth { + config: OAuthRegistration, + token_endpoint: String, + identity_endpoint: String, + token_info_endpoint: String, +} + +enum GrantSource<'a> { + Authorization, + Refresh(&'a Material), + Import(&'a str), +} + +#[derive(Deserialize)] +pub(super) struct TokenResponse { + access_token: String, + refresh_token: Option, + token_type: String, + expires_in: u32, + scope: Option, +} + +#[derive(Deserialize)] +struct UserInfo { + id: String, + email: Option, + #[serde(default)] + verified_email: bool, +} + +#[derive(Deserialize)] +struct TokenInfo { + scope: String, +} + +#[derive(Serialize, Deserialize)] +pub(crate) struct Material { + pub(super) registration: String, + pub(super) subject: String, + pub(crate) access_token: String, + pub(super) refresh_token: String, + pub(super) scopes: Vec, +} + +pub(super) struct VerifiedGrant { + pub(super) material: Material, + pub(super) email: Option, + pub(super) expires_at: DateTime, +} + +impl TokenResponse { + /// 首次授权须明确获授业务范围;刷新只允许从同一注册已验证的凭据继承省略项 + pub(super) fn resolve_grant( + &mut self, + required_scopes: &[String], + previous: Option<&Material>, + ) -> Result<(Vec, String), ProviderAdminError> { + if !self.token_type.eq_ignore_ascii_case("Bearer") + || !valid_token(&self.access_token) + || self.expires_in == 0 + { + return Err(invalid()); + } + // Google 可在刷新响应中省略原范围和 refresh token,显式收窄的范围始终优先 + let scopes = self + .scope + .as_deref() + .map(|s| { + s.split_ascii_whitespace() + .map(str::to_owned) + .collect::>() + }) + .or_else(|| previous.map(|p| p.scopes.clone())) + .ok_or_else(invalid)?; + if !required_scopes.iter().all(|s| scopes.contains(s)) { + return Err(error(if previous.is_some() { + ProviderAdminErrorKind::CredentialRefreshRequired + } else { + ProviderAdminErrorKind::Invalid + }) + .with_public_message("Google 未授予该客户端配置的权限范围")); + } + let refresh_token = self + .refresh_token + .take() + .or_else(|| previous.map(|p| p.refresh_token.clone())) + .filter(|s| valid_token(s)) + .ok_or_else(|| invalid().with_public_message("未取得可续期凭据,请重新授权"))?; + Ok((scopes, refresh_token)) + } +} + +impl GoogleOAuth { + pub(crate) fn for_provider() -> Result { + // 注册参数来自 Antigravity Desktop 2.34.0 的个人账号客户端 + // client secret 随桌面制品公开分发,不是用户账号凭据 + let registration = OAuthRegistration { + client_id: "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com" + .into(), + client_secret: "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".into(), + redirect_uri: "http://localhost:8085/auth/callback".into(), + resource_scopes: [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cclog", + "https://www.googleapis.com/auth/experimentsandconfigs", + "https://www.googleapis.com/auth/aicode", + ] + .map(str::to_owned) + .into(), + resource_origin: Url::parse("https://daily-cloudcode-pa.googleapis.com") + .map_err(|_| ConfigError)?, + }; + registration.validate()?; + Ok(Self::new(registration)) + } + + pub(super) fn new(config: OAuthRegistration) -> Self { + Self::with_endpoints( + config, + "https://oauth2.googleapis.com/token", + "https://www.googleapis.com/oauth2/v2/userinfo", + "https://www.googleapis.com/oauth2/v3/tokeninfo", + ) + } + + pub(super) fn with_endpoints( + config: OAuthRegistration, + token_endpoint: &str, + identity_endpoint: &str, + token_info_endpoint: &str, + ) -> Self { + Self { + config, + token_endpoint: token_endpoint.into(), + identity_endpoint: identity_endpoint.into(), + token_info_endpoint: token_info_endpoint.into(), + } + } + + pub(crate) fn resource_origin(&self) -> &Url { + &self.config.resource_origin + } + + pub(crate) fn registration(&self) -> String { + // 密钥轮换不改变注册身份;更换客户端、回调或申请范围需要重新授权 + let mut digest = Sha256::new(); + let mut scopes: Vec<_> = self + .config + .resource_scopes + .iter() + .map(String::as_str) + .collect(); + scopes.sort_unstable(); + scopes.dedup(); + for part in [ + self.config.client_id.as_str(), + self.config.redirect_uri.as_str(), + self.config.resource_origin.as_str(), + ] + .into_iter() + .chain(scopes) + { + digest.update(part.as_bytes()); + digest.update([0]); + } + URL_SAFE_NO_PAD.encode(digest.finalize()) + } + + pub(super) fn authorize_url( + &self, + state: &str, + verifier: &str, + ) -> Result { + let mut url = + Url::parse("https://accounts.google.com/o/oauth2/auth").map_err(|_| unavailable())?; + let scopes = [ + "https://www.googleapis.com/auth/userinfo.email", + "https://www.googleapis.com/auth/userinfo.profile", + ] + .into_iter() + .chain(self.config.resource_scopes.iter().map(String::as_str)) + .collect::>() + .join(" "); + url.query_pairs_mut().extend_pairs([ + ("response_type", "code"), + ("client_id", &self.config.client_id), + ("redirect_uri", &self.config.redirect_uri), + ("scope", &scopes), + ("state", state), + ( + "code_challenge", + &URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())), + ), + ("code_challenge_method", "S256"), + ("access_type", "offline"), + ("prompt", "consent"), + ]); + Ok(url.into()) + } + + pub(super) fn callback_code( + &self, + callback: &str, + state: &str, + ) -> Result { + let mut url = Url::parse(callback).map_err(|_| invalid())?; + if url.fragment().is_some() { + return Err(invalid()); + } + let mut code = None; + let mut returned_state = None; + for (name, value) in url.query_pairs() { + match name.as_ref() { + "error" => return Err(invalid()), + "state" if returned_state.is_none() => returned_state = Some(value.into_owned()), + "code" if code.is_none() && valid_token(&value) => code = Some(value.into_owned()), + "state" | "code" => return Err(invalid()), + _ => {} + } + } + url.set_query(None); + if returned_state.as_deref() != Some(state) + || url != Url::parse(&self.config.redirect_uri).map_err(|_| invalid())? + { + return Err(invalid()); + } + code.ok_or_else(invalid) + } + + pub(super) async fn exchange( + &self, + code: &str, + verifier: &str, + proxy: Option<&OutboundProxy>, + profile: &crate::profile::ClientProfile, + ) -> Result { + self.request( + &[ + ("grant_type", "authorization_code"), + ("code", code), + ("code_verifier", verifier), + ("redirect_uri", &self.config.redirect_uri), + ], + GrantSource::Authorization, + proxy, + profile, + ) + .await + } + + pub(super) async fn refresh( + &self, + previous: &Material, + proxy: Option<&OutboundProxy>, + profile: &crate::profile::ClientProfile, + ) -> Result { + if self.registration() != previous.registration || !valid_token(&previous.refresh_token) { + return Err(error(ProviderAdminErrorKind::CredentialRefreshRequired)); + } + self.request( + &[ + ("grant_type", "refresh_token"), + ("refresh_token", &previous.refresh_token), + ], + GrantSource::Refresh(previous), + proxy, + profile, + ) + .await + } + + pub(super) async fn verify_import( + &self, + refresh_token: &str, + proxy: Option<&OutboundProxy>, + profile: &crate::profile::ClientProfile, + ) -> Result { + if !valid_token(refresh_token) { + return Err(invalid()); + } + self.request( + &[ + ("grant_type", "refresh_token"), + ("refresh_token", refresh_token), + ], + GrantSource::Import(refresh_token), + proxy, + profile, + ) + .await + } + + async fn request( + &self, + fields: &[(&str, &str)], + source: GrantSource<'_>, + proxy: Option<&OutboundProxy>, + profile: &crate::profile::ClientProfile, + ) -> Result { + let client: Client = gateway_egress::http_client(proxy) + .map_err(|_| invalid())? + .use_rustls_tls() + // OAuth 整轮请求冻结系统 AGY 画像,沿用 Desktop 的 HTTP/1.1 传输 + .http1_only() + .http1_title_case_headers() + .user_agent(profile.user_agent()) + .redirect(reqwest::redirect::Policy::none()) + .retry(reqwest::retry::never()) + .timeout(Duration::from_secs(15)) + .build() + .map_err(|_| unavailable())?; + let mut form = fields.to_vec(); + form.extend([ + ("client_id", self.config.client_id.as_str()), + ("client_secret", self.config.client_secret.as_str()), + ]); + let mut token: TokenResponse = read_json( + client.post(&self.token_endpoint).form(&form), + !matches!(source, GrantSource::Authorization), + ) + .await?; + let previous = match source { + GrantSource::Refresh(previous) => Some(previous), + GrantSource::Authorization => None, + GrantSource::Import(refresh_token) => { + // Google 已用当前注册验证 RT,但文件中的身份和权限不可作为继承来源 + token + .refresh_token + .get_or_insert_with(|| refresh_token.to_owned()); + None + } + }; + // Desktop 通过 tokeninfo 查询实际获授范围;新凭据不能从导入文件继承权限 + if previous.is_none() && token.scope.is_none() { + let info: TokenInfo = read_json( + client + .get(&self.token_info_endpoint) + .query(&[("access_token", &token.access_token)]), + false, + ) + .await?; + token.scope = Some(info.scope); + } + let (scopes, refresh_token) = + token.resolve_grant(&self.config.resource_scopes, previous)?; + // 刷新凭据属于已验证的注册与 subject。RT 可能发生轮换,拿到新 RT 后直接提交, + // 避免后续资料查询失败令新旧凭据同时丢失。新的授权码及文件导入必须重新查验身份 + let (subject, email) = if let Some(previous) = previous { + (previous.subject.clone(), None) + } else { + let user: UserInfo = read_json( + client + .get(&self.identity_endpoint) + .bearer_auth(&token.access_token), + false, + ) + .await?; + if user.id.len() > 255 || !valid_token(&user.id) { + return Err(invalid()); + } + ( + user.id, + user.email.filter(|s| { + user.verified_email + && !s.is_empty() + && s.len() <= 320 + && !s.chars().any(char::is_control) + }), + ) + }; + Ok(VerifiedGrant { + email, + expires_at: Utc::now() + chrono::Duration::seconds(i64::from(token.expires_in)), + material: Material { + registration: self.registration(), + subject, + access_token: token.access_token, + refresh_token, + scopes, + }, + }) + } +} + +async fn read_json( + request: RequestBuilder, + refresh: bool, +) -> Result { + let mut response = request + .send() + .await + .map_err(|e| unavailable().with_source(e.without_url()))?; + let status = response.status(); + let mut data = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(|_| unavailable())? { + if data.len().saturating_add(chunk.len()) > 65536 { + return Err(invalid()); + } + data.extend_from_slice(&chunk); + } + if !status.is_success() { + #[derive(Deserialize)] + struct OAuthFailure { + error: String, + } + if refresh + && status == reqwest::StatusCode::BAD_REQUEST + && serde_json::from_slice::(&data) + .is_ok_and(|body| body.error == "invalid_grant") + { + return Err(error(ProviderAdminErrorKind::CredentialRefreshRequired) + .with_public_message("Google 已撤销刷新授权,请重新授权")); + } + return Err(if status.is_server_error() || status.as_u16() == 429 { + unavailable() + } else { + invalid() + }); + } + serde_json::from_slice(&data).map_err(|_| invalid()) +} diff --git a/backend/crates/providers/antigravity/src/credential/quota/document.rs b/backend/crates/providers/antigravity/src/credential/quota/document.rs new file mode 100644 index 000000000..de92b0357 --- /dev/null +++ b/backend/crates/providers/antigravity/src/credential/quota/document.rs @@ -0,0 +1,164 @@ +//! 套餐、独立额度桶及模型额度的持久事实与公共投影 + +use crate::transport::account::{ModelQuota, QuotaSummary, Tier}; +use chrono::{DateTime, Utc}; +use gateway_admin::model::provider_credentials::{ + ProviderQuota, ProviderQuotaWindow, QuotaLocalUsageAttribution, +}; +use gateway_core::account::{AccountQuotaSignals, QuotaEvidence, QuotaState}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::BTreeMap, + time::{Duration, SystemTime}, +}; + +#[derive(Serialize, Deserialize)] +pub(super) struct Document { + pub(super) tier: Option, + pub(super) summary: QuotaSummary, + pub(super) models: BTreeMap, +} + +impl ModelQuota { + pub(crate) fn remaining(&self) -> Option { + self.remaining_fraction + .as_ref() + .and_then(serde_json::Number::as_f64) + .filter(|v| v.is_finite() && (0.0..=1.0).contains(v)) + } + + fn current(&self, now: SystemTime) -> bool { + self.reset_time + .is_none_or(|reset| SystemTime::from(reset) > now) + } +} + +impl Document { + pub(super) fn model_observation( + &self, + model: &str, + observed_at: SystemTime, + now: SystemTime, + ) -> Option { + let quota = self.models.get(model)?; + let valid_until = observed_at.checked_add(Duration::from_secs(600))?; + let valid_until = quota + .reset_time + .map(SystemTime::from) + .map_or(valid_until, |reset| reset.min(valid_until)); + if observed_at > now || valid_until <= now { + return None; + } + let state = if quota.remaining()? == 0.0 { + QuotaState::exhausted( + QuotaEvidence::UsageLimitReached, + observed_at, + quota.reset_time.map(SystemTime::from), + ) + } else { + QuotaState::allowed(observed_at) + }; + Some(gateway_admin::ports::provider::ProviderPeerModelQuota { state, valid_until }) + } + pub(super) fn plan_type(&self) -> Option { + self.tier + .as_ref() + .map(|tier| tier.id.trim()) + .filter(|id| !id.is_empty()) + .map(str::to_owned) + } + + pub(super) fn access(&self, now: SystemTime) -> QuotaState { + // 独立模型桶不能直接升级为整个账号耗尽,只有全部已知模型都明确耗尽才阻断账号 + if self + .models + .values() + .any(|quota| quota.current(now) && quota.remaining().is_some_and(|v| v > 0.0)) + { + QuotaState::allowed(now) + } else if !self.models.is_empty() + && self + .models + .values() + .all(|quota| quota.current(now) && quota.remaining() == Some(0.0)) + { + QuotaState::exhausted( + QuotaEvidence::UsageLimitReached, + now, + self.models + .values() + .filter_map(|q| q.reset_time.map(SystemTime::from)) + .min(), + ) + } else { + QuotaState::observed_unknown(now) + } + } + + pub(super) fn model_signals( + &self, + model: &str, + observed: SystemTime, + now: SystemTime, + ) -> (bool, Option) { + // 过时或已过重置点的百分比交回上游判定,避免旧快照永久挡住可用模型 + if now.duration_since(observed).unwrap_or_default() > Duration::from_secs(600) { + return (false, None); + } + let Some(quota) = self.models.get(model).filter(|q| q.current(now)) else { + return (false, None); + }; + let remaining = quota.remaining(); + let reset = quota.reset_time.map(SystemTime::from); + ( + remaining == Some(0.0), + Some(AccountQuotaSignals::new( + reset, + remaining.map(|v| (v * 10_000.0).round() as u64), + )), + ) + } + + pub(super) fn project(&self, observed: SystemTime) -> ProviderQuota { + let mut windows = Vec::new(); + for group in &self.summary.groups { + let group_id = group.buckets.first().map(|b| { + b.bucket_id + .strip_suffix(&format!("-{}", b.window)) + .unwrap_or(&b.bucket_id) + .to_owned() + }); + for bucket in &group.buckets { + let (seconds, label, kind) = match bucket.window.as_str() { + "5h" => (Some(18_000), "5 小时额度", "shortTerm"), + "weekly" => (Some(604_800), "周额度", "shortTerm"), + _ => (None, bucket.display_name.as_str(), "other"), + }; + let used = bucket.quota.remaining().map(|v| (1.0 - v) * 100.0); + windows.push(ProviderQuotaWindow { + upstream: None, + key: bucket.bucket_id.clone(), + group: kind.into(), + label: label.into(), + limit_id: group_id.clone(), + limit_name: Some(group.display_name.clone()), + role: None, + local_usage_attribution: QuotaLocalUsageAttribution::Unavailable, + window_seconds: seconds, + used_percent: used, + reset_at: bucket.quota.reset_time, + limit_reached: used == Some(100.0), + local_usage: None, + provider_data: None, + }); + } + } + ProviderQuota { + limit_reached: self.access(observed).is_exhausted(), + plan_type: self.plan_type(), + observed_at: Some(DateTime::::from(observed)), + windows, + ..Default::default() + } + } +} diff --git a/backend/crates/providers/antigravity/src/credential/quota/mod.rs b/backend/crates/providers/antigravity/src/credential/quota/mod.rs new file mode 100644 index 000000000..fdbc12520 --- /dev/null +++ b/backend/crates/providers/antigravity/src/credential/quota/mod.rs @@ -0,0 +1,6 @@ +//! Antigravity 账号额度文档、刷新与调度投影入口 + +mod document; +mod service; + +pub(crate) use service::{QuotaService, QuotaTask}; diff --git a/backend/crates/providers/antigravity/src/credential/quota/service.rs b/backend/crates/providers/antigravity/src/credential/quota/service.rs new file mode 100644 index 000000000..4ba255507 --- /dev/null +++ b/backend/crates/providers/antigravity/src/credential/quota/service.rs @@ -0,0 +1,335 @@ +//! AGY 额度刷新、持久观测与选号投影,凭据版本和观察时间由 Store 隔离 + +use super::document::Document; +use crate::{ + credential::catalog::CatalogService, + credential::{CredentialService, oauth::error}, + profile::ReleaseService, + transport::CloudCodeClient, +}; +use futures::{StreamExt, stream}; +use gateway_admin::{ + model::provider_credentials::ProviderQuota, + ports::provider::{ProviderAdminError, ProviderAdminErrorKind as Kind}, +}; +use gateway_core::{ + account::{ + AccountQuotaSignals, OpaqueProviderData, ProviderAccount, ProviderAccountId, + ProviderAccountStore, QuotaObservation, QuotaWriteOutcome, + }, + lifecycle::CancellationToken, + routing::ProviderKind, + task::{ScheduledTask, WorkerCycleContext, WorkerTaskError}, +}; +use std::{ + collections::BTreeMap, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, + time::{Duration, SystemTime}, +}; + +pub(crate) struct QuotaService { + kind: ProviderKind, + accounts: Arc, + credentials: Arc, + catalog: Arc, + release: Arc, + origin: url::Url, + cursor: AtomicUsize, +} + +impl QuotaService { + pub(crate) async fn peer_model_facts( + &self, + accounts: &[gateway_admin::model::accounts::AccountRecord], + ) -> Result< + BTreeMap, + ProviderAdminError, + > { + let authorized: BTreeMap<_, _> = accounts + .iter() + .filter(|a| a.provider_kind == self.kind && a.authentication_kind == "oauth") + .map(|a| (a.id.as_str(), a.credential_revision.get())) + .collect(); + let ids = authorized + .keys() + .map(|id| ProviderAccountId::new(*id).map_err(|_| error(Kind::Invalid))) + .collect::, _>>()?; + let quotas: BTreeMap<_, _> = self + .accounts + .get_quotas(&ids) + .await + .map_err(unavailable)? + .into_iter() + .map(|q| (q.account_id.clone(), q)) + .collect(); + let catalogs = self + .catalog + .catalogs() + .await + .map_err(|e| error(Kind::Unavailable).with_source(e))?; + let mut facts = BTreeMap::new(); + let now = SystemTime::now(); + for (owners, catalog) in catalogs { + for owner in owners { + if authorized.get(owner.account_id.as_str()) != Some(&owner.revision.get()) { + continue; + } + let observation = quotas + .get(&owner.account_id) + .filter(|q| q.expected_revision == owner.revision); + let document = observation.map(parse).transpose()?; + let models = catalog + .models + .keys() + .map(|model| { + let quota = observation + .zip(document.as_ref()) + .and_then(|(o, d)| d.model_observation(model, o.observed_at, now)); + (model.clone(), quota) + }) + .collect(); + facts.insert( + owner.account_id.as_str().to_owned(), + gateway_admin::ports::provider::ProviderPeerAccountModels { + credential_revision: owner.revision, + models, + }, + ); + } + } + Ok(facts) + } + pub(crate) fn new( + kind: ProviderKind, + accounts: Arc, + credentials: Arc, + catalog: Arc, + release: Arc, + origin: url::Url, + ) -> Self { + Self { + kind, + accounts, + credentials, + catalog, + release, + origin, + cursor: AtomicUsize::new(0), + } + } + + pub(crate) async fn read( + &self, + id: &ProviderAccountId, + ) -> Result { + let account = self + .accounts + .get_account(id) + .await + .map_err(unavailable)? + .filter(|a| a.provider() == &self.kind) + .ok_or_else(|| error(Kind::NotFound))?; + let observations = self + .accounts + .get_quotas(std::slice::from_ref(id)) + .await + .map_err(unavailable)?; + if let Some(observation) = observations + .into_iter() + .find(|o| &o.account_id == id && o.expected_revision == account.revision()) + { + let doc = parse(&observation)?; + return Ok(doc.project(observation.observed_at)); + } + Ok(ProviderQuota::default()) + } + + pub(crate) async fn refresh(&self, id: &ProviderAccountId) -> Result<(), ProviderAdminError> { + let current = self.credentials.current(id).await?; + let material = self + .credentials + .material(¤t) + .map_err(|e| error(Kind::CredentialRefreshRequired).with_source(e))?; + let client = CloudCodeClient::new( + &self.origin, + current.account.outbound_proxy(), + &crate::profile::default_profile(&self.release), + ) + .map_err(upstream)?; + // 用查询开始时间隔离交错返回的旧结果,失败不覆盖已有快照 + let observed_at = SystemTime::now(); + let info = client + .account_info(&material.access_token) + .await + .map_err(upstream)?; + let (catalog, summary) = tokio::try_join!( + client.catalog_for_project(&material.access_token, info.project.clone()), + client.quota_summary(&material.access_token, &info.project), + ) + .map_err(upstream)?; + let doc = Document { + tier: info.paid_tier.or(info.current_tier), + summary, + models: catalog + .models + .iter() + .map(|(id, model)| { + ( + id.clone(), + model + .quota + .clone() + .unwrap_or(crate::transport::account::ModelQuota { + remaining_fraction: None, + reset_time: None, + }), + ) + }) + .collect(), + }; + let plan = doc.plan_type(); + let quota = serde_json::to_value(&doc).map_err(|e| error(Kind::Internal).with_source(e))?; + let observation = QuotaObservation { + quota_pause: None, + expected_connection: Some(gateway_core::account::UpstreamConnection::for_account( + ¤t.account, + )), + account_id: id.clone(), + expected_revision: current.account.revision(), + quota: OpaqueProviderData::new( + quota + .as_object() + .cloned() + .ok_or_else(|| error(Kind::Internal))?, + ), + plan_type: plan.clone(), + observed_at, + state: doc.access(observed_at), + }; + if self + .accounts + .compare_and_swap_quota(observation) + .await + .map_err(unavailable)? + == QuotaWriteOutcome::Conflict + { + return Err(error(Kind::Conflict)); + } + // 套餐与目录来自同次查询,保存当前套餐的目录避免新套餐短暂失去路由资格 + self.catalog + .publish( + ¤t.account, + plan.or_else(|| current.account.plan_type().map(str::to_owned)), + catalog, + observed_at, + ) + .await?; + Ok(()) + } + + pub(crate) async fn scheduling( + &self, + accounts: &[ProviderAccount], + model: &str, + ) -> Result)>, ProviderAdminError> + { + let revisions: BTreeMap<_, _> = accounts + .iter() + .map(|a| (a.id().clone(), a.revision())) + .collect(); + let ids: Vec<_> = revisions.keys().cloned().collect(); + let observations = self.accounts.get_quotas(&ids).await.map_err(unavailable)?; + let now = SystemTime::now(); + observations + .into_iter() + .filter(|o| revisions.get(&o.account_id) == Some(&o.expected_revision)) + .map(|o| { + let result = parse(&o)?.model_signals(model, o.observed_at, now); + Ok((o.account_id, result)) + }) + .collect() + } + + pub(crate) async fn reconcile( + &self, + cancel: &CancellationToken, + ) -> Result<(), WorkerTaskError> { + let mut accounts = self + .accounts + .list_for_provider(&self.kind, false) + .await + .map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?; + let ids: Vec<_> = accounts.iter().map(|a| a.id().clone()).collect(); + let observations: BTreeMap<_, _> = self + .accounts + .get_quota_versions(&ids) + .await + .map_err(|e| WorkerTaskError::safe("读取 Antigravity 额度版本失败").with_source(e))? + .into_iter() + .map(|o| (o.account_id.clone(), o)) + .collect(); + accounts.retain(|a| { + a.enabled() + && a.authentication_kind() == "oauth" + && observations.get(a.id()).is_none_or(|o| { + o.credential_revision != a.revision() + || o.observed_at.elapsed().unwrap_or_default() >= Duration::from_secs(300) + || (a.quota().is_exhausted() + && a.quota() + .reset_at() + .is_some_and(|reset| reset <= SystemTime::now())) + }) + }); + if accounts.is_empty() { + return Ok(()); + } + accounts.sort_by(|a, b| a.id().cmp(b.id())); + let offset = self.cursor.fetch_add(32, Ordering::Relaxed) % accounts.len(); + accounts.rotate_left(offset); + accounts.truncate(32); + let mut results = stream::iter(accounts).map(|a| async move { tokio::select! { biased; _ = cancel.cancelled() => Ok(()), result = self.refresh(a.id()) => result } }).buffer_unordered(4); + let mut failure = None; + while let Some(result) = results.next().await { + if let Err(e) = result + && !matches!(e.kind(), Kind::Conflict | Kind::CredentialRefreshRequired) + { + failure.get_or_insert(e); + } + } + failure.map_or(Ok(()), |e| { + Err(WorkerTaskError::safe("部分 Antigravity 额度刷新失败").with_source(e)) + }) + } +} + +fn parse(observation: &QuotaObservation) -> Result { + serde_json::from_value(serde_json::Value::Object( + observation.quota.expose_to_provider().clone(), + )) + .map_err(|e| error(Kind::Internal).with_source(e)) +} +fn unavailable(e: gateway_core::error::StoreError) -> ProviderAdminError { + error(Kind::Unavailable).with_source(e) +} +fn upstream(e: gateway_core::error::ProviderError) -> ProviderAdminError { + if e.kind() == gateway_core::error::ProviderErrorKind::Unauthorized { + error(Kind::CredentialRefreshRequired).with_source(e) + } else { + error(Kind::Unavailable) + .with_public_message("Antigravity 套餐或额度查询失败") + .with_source(e) + } +} + +pub(crate) struct QuotaTask(pub(crate) Arc); +impl ScheduledTask for QuotaTask { + fn run_cycle( + &self, + context: WorkerCycleContext, + ) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> { + Box::pin(async move { self.0.reconcile(context.cancellation()).await }) + } +} diff --git a/backend/crates/providers/antigravity/src/credential/refresh.rs b/backend/crates/providers/antigravity/src/credential/refresh.rs new file mode 100644 index 000000000..19f9dff97 --- /dev/null +++ b/backend/crates/providers/antigravity/src/credential/refresh.rs @@ -0,0 +1,137 @@ +//! 复用网关刷新策略、账号租约及凭据版本提交后台续期 + +use super::{oauth::error, service::CredentialService}; +use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind as Kind}; +use gateway_core::{ + account::{ + CredentialCasOutcome, CredentialCasUpdate, CredentialRevision, CredentialState, + LoadedCredential, PlaintextCredential, ProviderAccountUpdate, ProviderRefreshQuery, + }, + provider_ports::provider_refresh_backoff_at, + task::WorkerTaskError, +}; +use std::{ + num::NonZeroU32, + time::{Duration, SystemTime}, +}; + +fn update( + loaded: &LoadedCredential, + material: PlaintextCredential, + expires: Option, + next: Option, +) -> Result { + let a = &loaded.account; + let profile = ProviderAccountUpdate { + account_id: a.id().clone(), + name: a.name().into(), + email: a.email().map(str::to_owned), + plan_type: a.plan_type().map(str::to_owned), + }; + CredentialCasUpdate::new( + a.id().clone(), + a.revision(), + profile, + material, + true, + expires, + next, + ) + .map(CredentialCasUpdate::preserving_profile) + .map_err(|_| error(Kind::Internal)) +} + +impl CredentialService { + pub(crate) async fn refresh_candidates( + &self, + ) -> Result<(Vec, usize), WorkerTaskError> { + let policy = self + .runtime_policy + .load_refresh_policy() + .await + .map_err(|e| WorkerTaskError::safe("无法读取 OAuth 刷新策略").with_source(e))?; + let now = SystemTime::now(); + let query = ProviderRefreshQuery::new( + self.kind.clone(), + now.checked_add(policy.margin()).unwrap_or(now), + SystemTime::UNIX_EPOCH, + now, + Vec::new(), + NonZeroU32::new(64).unwrap_or(NonZeroU32::MIN), + ); + let candidates = self + .accounts + .list_refresh_candidates(query) + .await + .map_err(|e| WorkerTaskError::safe("无法读取到期 OAuth 账号").with_source(e))?; + Ok((candidates, policy.concurrency().get() as usize)) + } + + pub(crate) async fn refresh_due( + &self, + loaded: &LoadedCredential, + ) -> Result { + let (facts, guard) = self.refresh_current(loaded).await?.into_parts(); + let material = + PlaintextCredential::new(facts.provider_material.into_provider_data().into_inner()); + let record = update( + loaded, + material, + facts.access_token_expires_at.map(Into::into), + None, + )? + .with_account_state(CredentialState::Ready, SystemTime::now(), None, None); + match self + .accounts + .compare_and_swap_credential(record) + .await + .map_err(|e| error(Kind::Unavailable).with_source(e))? + { + CredentialCasOutcome::Updated(revision) => { + guard.finish(); + if self + .credential_state + .clear_refresh_backoff(loaded.account.id()) + .await + .is_err() + { + // 凭据已经提交,清理可丢失退避失败不能丢掉新 revision 的目录续接 + tracing::warn!("Antigravity 续期后清理退避状态失败"); + } + Ok(revision) + } + CredentialCasOutcome::Conflict => Err(error(Kind::Conflict)), + } + } + + pub(super) async fn defer_refresh( + &self, + loaded: &LoadedCredential, + ) -> Result<(), ProviderAdminError> { + let id = loaded.account.id(); + let attempt = self + .credential_state + .record_refresh_backoff(id, Duration::from_secs(86400)) + .await + .map_err(|e| error(Kind::Unavailable).with_source(e))?; + let retry = + provider_refresh_backoff_at(id, SystemTime::now(), attempt, "antigravity_oauth") + .map_err(|e| error(Kind::Unavailable).with_source(e))?; + let record = update( + loaded, + loaded.credential.clone(), + loaded.account.access_token_expires_at(), + Some(retry), + )? + .preserving_access_token_expiry(); + match self + .accounts + .compare_and_swap_credential(record) + .await + .map_err(|e| error(Kind::Unavailable).with_source(e))? + { + CredentialCasOutcome::Updated(_) => Ok(()), + CredentialCasOutcome::Conflict => Err(error(Kind::Conflict)), + } + } +} diff --git a/backend/crates/providers/antigravity/src/credential/service.rs b/backend/crates/providers/antigravity/src/credential/service.rs new file mode 100644 index 000000000..82259cb1e --- /dev/null +++ b/backend/crates/providers/antigravity/src/credential/service.rs @@ -0,0 +1,301 @@ +//! 账号身份、凭据校验与带租约的授权轮换 + +use super::oauth::{GoogleOAuth, Material, VerifiedGrant, error}; +use crate::transport::unsent; +use chrono::Utc; +use gateway_admin::{ + model::{ + Revision, + provider_credentials::{ + AuthorizationMutationTarget, CredentialCommitGuard, PendingAuthorizationMutation, + PreparedAuthorizationCredential, PreparedCredentialCreate, PreparedCredentialRotation, + PreparedCredentialRotationFacts, ProviderDocument, + }, + }, + ports::provider::{ProviderAdminError, ProviderAdminErrorKind as Kind}, +}; +use gateway_core::{ + account::{ + AccountErrorReason, AccountStateChange, CredentialState, LoadedCredential, + OpaqueProviderData, OutboundProxy, ProviderAccount, ProviderAccountId, + ProviderAccountStore, + }, + error::{ProviderError, ProviderErrorKind, StoreErrorKind}, + provider_ports::{ + ProviderCredentialStatePort, ProviderLeaseAcquisition, ProviderLeaseGuard, + ProviderLeasePort, ProviderLeaseRequest, ProviderRefreshCapacityRequest, + ProviderRefreshLeaseRequest, ProviderRuntimePolicyPort, + }, + routing::ProviderKind, +}; +use serde_json::Value; +use std::{sync::Arc, time::SystemTime}; +use uuid::Uuid; + +pub(crate) struct CredentialService { + pub(super) kind: ProviderKind, + pub(super) accounts: Arc, + pub(super) leases: Arc, + pub(super) runtime_policy: Arc, + pub(super) credential_state: Arc, + pub(super) oauth: Arc, + pub(super) release: Arc, +} +impl CredentialService { + pub(crate) fn new( + kind: ProviderKind, + ports: &gateway_core::provider_ports::ProviderStorePorts, + oauth: Arc, + release: Arc, + ) -> Self { + Self { + kind, + accounts: ports.accounts(), + leases: ports.leases(), + runtime_policy: ports.runtime_policy(), + credential_state: ports.credential_state(), + oauth, + release, + } + } + pub(super) async fn request_profile( + &self, + ) -> Result { + let configuration = self + .runtime_policy + .load_request_profile(&self.kind) + .await + .map_err(|e| error(Kind::Unavailable).with_source(e))?; + match configuration { + Some(configuration) => crate::profile::resolve(&configuration, &self.release), + None => Ok(crate::profile::default_profile(&self.release)), + } + } + pub(crate) fn material(&self, current: &LoadedCredential) -> Result { + let material: Material = serde_json::from_value(serde_json::Value::Object( + current.credential.expose_to_provider().clone(), + )) + .map_err(|_| unsent(ProviderErrorKind::ProviderInfrastructureUnavailable))?; + if material.registration != self.oauth.registration() + || current.account.upstream_user_id() != Some(material.subject.as_str()) + || current + .account + .access_token_expires_at() + .is_some_and(|t| t <= SystemTime::now()) + { + return Err(unsent(ProviderErrorKind::Unauthorized)); + } + Ok(material) + } +} +pub(super) struct RefreshGuards { + _account: Box, + _capacity: Box, +} + +impl CredentialCommitGuard for RefreshGuards { + fn finish(self: Box) {} +} + +fn document(material: Material) -> Result { + match serde_json::to_value(material) { + Ok(Value::Object(map)) => Ok(ProviderDocument::new(OpaqueProviderData::new(map))), + _ => Err(error(Kind::Internal)), + } +} + +impl CredentialService { + pub(crate) async fn current( + &self, + id: &ProviderAccountId, + ) -> Result { + let loaded = self + .accounts + .load_current_credential(id) + .await + .map_err(|e| { + error(match e.kind() { + StoreErrorKind::InvalidData | StoreErrorKind::InvalidState => Kind::NotFound, + StoreErrorKind::Unavailable => Kind::Unavailable, + StoreErrorKind::Conflict => Kind::Conflict, + _ => Kind::Internal, + }) + .with_source(e) + })?; + if loaded.account.provider() != &self.kind + || loaded.account.authentication_kind() != "oauth" + { + return Err(error(Kind::NotFound)); + } + Ok(loaded) + } + + pub(super) async fn lock_rotation( + &self, + account: &ProviderAccount, + ) -> Result { + let policy = self + .runtime_policy + .load_refresh_policy() + .await + .map_err(|e| error(Kind::Unavailable).with_source(e))?; + let leases = self.leases.clone(); + let acquire = |request| { + let leases = leases.clone(); + async move { + match leases + .try_acquire(request) + .await + .map_err(|e| error(Kind::Unavailable).with_source(e))? + { + ProviderLeaseAcquisition::Acquired(guard) => Ok(guard), + ProviderLeaseAcquisition::Busy { .. } => Err(error(Kind::Conflict)), + } + } + }; + let capacity = acquire(ProviderLeaseRequest::RefreshCapacity( + ProviderRefreshCapacityRequest::new(policy.concurrency()), + )) + .await?; + let guard = acquire(ProviderLeaseRequest::Refresh( + ProviderRefreshLeaseRequest::new(account.id().clone(), account.revision()), + )) + .await?; + // 租约可在初次读取之后才可用,发送会轮换 RT 的请求之前再次核实 revision + if self + .accounts + .get_account(account.id()) + .await + .map_err(|e| error(Kind::Unavailable).with_source(e))? + .is_none_or(|a| a.revision() != account.revision()) + { + return Err(error(Kind::Conflict)); + } + Ok(RefreshGuards { + _account: guard, + _capacity: capacity, + }) + } + + pub(super) async fn prepare_grant( + &self, + pending: &PendingAuthorizationMutation, + grant: VerifiedGrant, + ) -> Result { + match pending.target() { + AuthorizationMutationTarget::Create { name } => { + let account = + self.prepare_create(name.clone(), grant, pending.outbound_proxy().cloned())?; + Ok(PreparedAuthorizationCredential::Create(Box::new(account))) + } + AuthorizationMutationTarget::Reauthorize { account_id } => { + let loaded = self.current(account_id).await?; + let guards = self.lock_rotation(&loaded.account).await?; + Ok(PreparedAuthorizationCredential::Reauthorize(Box::new( + self.rotation(&loaded.account, grant, guards)?, + ))) + } + } + } + + pub(super) fn prepare_create( + &self, + name: String, + grant: VerifiedGrant, + outbound_proxy: Option, + ) -> Result { + let account_id = ProviderAccountId::new(format!("acct_{}", Uuid::now_v7().simple())) + .map_err(|_| error(Kind::Internal))?; + Ok(PreparedCredentialCreate { + account_id, + provider_kind: self.kind.clone(), + name, + email: grant.email, + upstream_user_id: Some(grant.material.subject.clone()), + upstream_account_id: None, + plan_type: None, + authentication_kind: "oauth".into(), + provider_material: document(grant.material)?, + has_refresh_token: true, + access_token_expires_at: Some(grant.expires_at), + next_refresh_at: None, + enabled: true, + credential_state: CredentialState::Ready, + credential_observed_at: Utc::now(), + model_access: None, + outbound_proxy, + }) + } + + pub(crate) async fn refresh_current( + &self, + current: &LoadedCredential, + ) -> Result { + let guards = self.lock_rotation(¤t.account).await?; + let previous: Material = serde_json::from_value(Value::Object( + current.credential.expose_to_provider().clone(), + )) + .map_err(|_| error(Kind::Internal))?; + if current.account.upstream_user_id() != Some(previous.subject.as_str()) { + return Err(error(Kind::Conflict)); + } + let profile = self.request_profile().await?; + let grant = match self + .oauth + .refresh(&previous, current.account.outbound_proxy(), &profile) + .await + { + Err(failure) if failure.kind() == Kind::CredentialRefreshRequired => { + self.accounts + .apply_state_change(AccountStateChange { + account_id: current.account.id().clone(), + expected_revision: current.account.revision(), + credential_state: CredentialState::Invalid, + observed_at: std::time::SystemTime::now(), + error_reason: Some(AccountErrorReason::CredentialInvalid), + message: Some("凭据需要重新授权".into()), + }) + .await + .map_err(|e| error(Kind::Unavailable).with_source(e))?; + return Err(failure); + } + Err(failure) => { + self.defer_refresh(current).await?; + return Err(failure); + } + Ok(grant) => grant, + }; + self.rotation(¤t.account, grant, guards) + } + + pub(super) fn rotation( + &self, + account: &ProviderAccount, + grant: VerifiedGrant, + guards: RefreshGuards, + ) -> Result { + if account.upstream_user_id() != Some(grant.material.subject.as_str()) { + return Err( + error(Kind::Conflict).with_public_message("授权的 Google 账号与原账号不一致") + ); + } + let facts = PreparedCredentialRotationFacts { + account_id: account.id().clone(), + provider_kind: self.kind.clone(), + expected_credential_revision: Revision::new(account.revision().get()) + .map_err(|_| error(Kind::Internal))?, + replacement_identity: None, + name: account.name().to_owned(), + email: grant.email, + plan_type: None, + preserve_profile: true, + preserve_credential_state: false, + preserve_access_token_expiry: false, + provider_material: document(grant.material)?, + has_refresh_token: true, + access_token_expires_at: Some(grant.expires_at), + next_refresh_at: None, + }; + Ok(PreparedCredentialRotation::new(facts, Box::new(guards))) + } +} diff --git a/backend/crates/providers/antigravity/src/lib.rs b/backend/crates/providers/antigravity/src/lib.rs new file mode 100644 index 000000000..9c318a5a1 --- /dev/null +++ b/backend/crates/providers/antigravity/src/lib.rs @@ -0,0 +1,74 @@ +//! Antigravity Provider 的装配与宿主注册门面 + +mod admin; +mod billing; +mod credential; +mod profile; +mod provider; +mod transport; + +use gateway_admin::ports::provider::ProviderBundle; +use gateway_core::{provider_ports::ProviderStorePorts, routing::ProviderKind}; +use std::sync::Arc; + +#[derive(Debug, thiserror::Error)] +#[error("Antigravity Provider 初始化失败")] +pub struct ConfigError; + +pub fn initialize(ports: ProviderStorePorts) -> Result { + let kind = ProviderKind::new("antigravity").map_err(|_| ConfigError)?; + let oauth = Arc::new(credential::GoogleOAuth::for_provider()?); + let origin = oauth.resource_origin().clone(); + let release = Arc::new(profile::ReleaseService::new(ports.artifact_profiles())?); + let credentials = Arc::new(credential::CredentialService::new( + kind.clone(), + &ports, + oauth.clone(), + release.clone(), + )); + let catalog = Arc::new(credential::catalog::CatalogService::new( + kind.clone(), + ports.accounts(), + credentials.clone(), + oauth.registration(), + origin.clone(), + release.clone(), + )); + let quota = Arc::new(credential::quota::QuotaService::new( + kind.clone(), + ports.accounts(), + credentials.clone(), + catalog.clone(), + release.clone(), + origin.clone(), + )); + let core = Arc::new(provider::AntigravityProvider::new( + kind.clone(), + &ports, + credentials.clone(), + catalog.clone(), + quota.clone(), + release.clone(), + origin, + )); + let admin = Arc::new(admin::AntigravityAdmin { + kind: kind.clone(), + credentials: credentials.clone(), + authorization: credential::AuthorizationService { + kind, + credentials: credentials.clone(), + oauth, + store: ports.oauth_pending(), + }, + catalog: catalog.clone(), + release: release.clone(), + quota: quota.clone(), + }); + let workers = provider::workers::contributions(credentials, catalog, release, quota) + .map_err(|_| ConfigError)?; + Ok(ProviderBundle { + core, + admin, + workers, + }) +} diff --git a/backend/crates/providers/antigravity/src/profile/archive.rs b/backend/crates/providers/antigravity/src/profile/archive.rs new file mode 100644 index 000000000..2a134dadc --- /dev/null +++ b/backend/crates/providers/antigravity/src/profile/archive.rs @@ -0,0 +1,322 @@ +//! 官方制品的有界下载与 ZIP 按需读取,使用 ETag 约束分段读取的一致性 + +use bytes::Bytes; +use gateway_core::lifecycle::CancellationToken; +use gateway_core::task::WorkerTaskError; +use reqwest::{Client, StatusCode, header}; +use sha2::{Digest, Sha512}; +use std::io::{self, Read, Seek, SeekFrom}; +use std::time::Duration; +use tokio::io::AsyncWriteExt; + +const MAX_ARTIFACT_BYTES: u64 = 512 * 1024 * 1024; +const MAX_RANGE_BYTES: u64 = 16 * 1024 * 1024; +const ZIP_DIRECTORY_BYTES: u64 = 1024 * 1024; + +pub(crate) struct ParseGuard(CancellationToken); +impl Drop for ParseGuard { + fn drop(&mut self) { + self.0.cancel(); + } +} + +pub(crate) struct CancellableFile { + file: std::fs::File, + cancellation: CancellationToken, +} +impl CancellableFile { + pub(crate) fn new(file: std::fs::File) -> (Self, ParseGuard) { + let cancellation = CancellationToken::new(); + ( + Self { + file, + cancellation: cancellation.clone(), + }, + ParseGuard(cancellation), + ) + } +} +impl Read for CancellableFile { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + if self.cancellation.is_cancelled() { + return Err(io::Error::other("制品解析已取消")); + } + self.file.read(buffer) + } +} + +pub(crate) fn invalid() -> WorkerTaskError { + WorkerTaskError::safe("Antigravity 发布包核验失败") +} + +fn network(error: reqwest::Error) -> WorkerTaskError { + invalid().with_source(error.without_url()) +} + +pub(crate) struct RemoteArtifact<'a> { + client: &'a Client, + url: String, + size: u64, + etag: header::HeaderValue, +} + +impl<'a> RemoteArtifact<'a> { + pub(crate) async fn open(client: &'a Client, url: String) -> Result { + let response = client.head(&url).send().await.map_err(network)?; + if response.status() != StatusCode::OK { + return Err(invalid()); + } + // HEAD 没有响应体,reqwest 的 body 长度为零;制品长度来自 Content-Length + let size: u64 = response + .headers() + .get(header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse().ok()) + .ok_or_else(invalid)?; + if size == 0 || size > MAX_ARTIFACT_BYTES { + return Err(invalid()); + } + let etag = response + .headers() + .get(header::ETAG) + .cloned() + .ok_or_else(invalid)?; + if etag.as_bytes().starts_with(b"W/") { + return Err(invalid()); + } + Ok(Self { + client, + url, + size, + etag, + }) + } + + pub(crate) async fn read(&self, start: u64, length: u64) -> Result { + let end = start + .checked_add(length) + .filter(|end| *end <= self.size) + .ok_or_else(invalid)?; + if length == 0 || length > MAX_RANGE_BYTES { + return Err(invalid()); + } + let mut response = self + .client + .get(&self.url) + .header(header::ACCEPT_ENCODING, "identity") + .header(header::IF_MATCH, self.etag.clone()) + .header(header::RANGE, format!("bytes={start}-{}", end - 1)) + .send() + .await + .map_err(network)?; + if response.status() != StatusCode::PARTIAL_CONTENT + || response + .headers() + .get(header::CONTENT_RANGE) + .and_then(|v| v.to_str().ok()) + != Some(format!("bytes {start}-{}/{}", end - 1, self.size).as_str()) + || response.headers().get(header::ETAG) != Some(&self.etag) + { + return Err(invalid()); + } + let mut body = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(network)? { + if body.len() as u64 + chunk.len() as u64 > length { + return Err(invalid()); + } + body.extend_from_slice(&chunk); + } + if body.len() as u64 != length { + return Err(invalid()); + } + Ok(body.into()) + } + + pub(crate) async fn prefix(&self, maximum: u64) -> Result { + self.read(0, self.size.min(maximum)).await + } +} + +/// 只缓存目录和所需条目,未下载的区间不能被当作零填充数据读取 +struct Segments { + size: u64, + position: u64, + chunks: Vec<(u64, Bytes)>, +} +impl Read for Segments { + fn read(&mut self, out: &mut [u8]) -> io::Result { + if out.is_empty() || self.position == self.size { + return Ok(0); + } + for (start, bytes) in &self.chunks { + if let Some(offset) = self.position.checked_sub(*start) + && offset < bytes.len() as u64 + { + let offset = offset as usize; + let count = out.len().min(bytes.len() - offset); + out[..count].copy_from_slice(&bytes[offset..offset + count]); + self.position += count as u64; + return Ok(count); + } + } + Err(io::ErrorKind::UnexpectedEof.into()) + } +} +impl Seek for Segments { + fn seek(&mut self, from: SeekFrom) -> io::Result { + let position = match from { + SeekFrom::Start(n) => i128::from(n), + SeekFrom::End(n) => i128::from(self.size) + i128::from(n), + SeekFrom::Current(n) => i128::from(self.position) + i128::from(n), + }; + self.position = u64::try_from(position).map_err(|_| io::ErrorKind::InvalidInput)?; + Ok(self.position) + } +} + +pub(crate) struct RemoteZip<'a> { + artifact: RemoteArtifact<'a>, + tail: Bytes, +} +impl<'a> RemoteZip<'a> { + pub(crate) async fn open(client: &'a Client, url: String) -> Result { + let artifact = RemoteArtifact::open(client, url).await?; + let length = artifact.size.min(ZIP_DIRECTORY_BYTES); + let tail = artifact.read(artifact.size - length, length).await?; + validate_directory(&tail, artifact.size)?; + Ok(Self { artifact, tail }) + } + + fn archive( + &self, + member: Option<(u64, Bytes)>, + ) -> Result, WorkerTaskError> { + let mut chunks = vec![( + self.artifact.size - self.tail.len() as u64, + self.tail.clone(), + )]; + chunks.extend(member); + zip::ZipArchive::new(Segments { + size: self.artifact.size, + position: 0, + chunks, + }) + .map_err(|e| invalid().with_source(e)) + } + + pub(crate) async fn read( + &self, + name: &str, + maximum: usize, + ) -> Result, WorkerTaskError> { + let archive = self.archive(None)?; + let index = archive.index_for_name(name).ok_or_else(invalid)?; + let entry = archive + .by_index_data(index) + .map_err(|e| invalid().with_source(e))?; + if entry.size() > maximum as u64 || entry.is_dir() || entry.is_symlink() { + return Err(invalid()); + } + let start = entry.header_start(); + // local header 的两个变长字段都是 u16,读取预算覆盖它们而不信任压缩比 + let length = entry + .compressed_size() + .checked_add(30 + 2 * u64::from(u16::MAX)) + .ok_or_else(invalid)? + .min(self.artifact.size.checked_sub(start).ok_or_else(invalid)?); + let member = self.artifact.read(start, length).await?; + let mut archive = self.archive(Some((start, member)))?; + let file = archive + .by_name(name) + .map_err(|e| invalid().with_source(e))?; + bounded(file, maximum) + } +} + +fn validate_directory(tail: &[u8], size: u64) -> Result<(), WorkerTaskError> { + let offset = tail + .windows(22) + .rposition(|header| header.starts_with(b"PK\x05\x06")) + .ok_or_else(invalid)?; + let header = &tail[offset..offset + 22]; + let word = |offset| u16::from_le_bytes([header[offset], header[offset + 1]]); + let dword = |offset| { + u32::from_le_bytes([ + header[offset], + header[offset + 1], + header[offset + 2], + header[offset + 3], + ]) + }; + let directory_size = u64::from(dword(12)); + let directory_start = u64::from(dword(16)); + // 官方安装包小于 512 MiB,不接受分卷或 ZIP64,也不让目录计数触发无界分配 + if word(4) != 0 + || word(6) != 0 + || word(8) != word(10) + || word(10) > 16_384 + || offset + 22 + usize::from(word(20)) != tail.len() + || directory_start < size - tail.len() as u64 + || directory_size > ZIP_DIRECTORY_BYTES + || directory_start + directory_size != size - tail.len() as u64 + offset as u64 + { + return Err(invalid()); + } + Ok(()) +} + +pub(crate) fn bounded(reader: impl Read, maximum: usize) -> Result, WorkerTaskError> { + let mut body = Vec::new(); + reader + .take(maximum as u64 + 1) + .read_to_end(&mut body) + .map_err(|e| invalid().with_source(e))?; + if body.len() > maximum { + return Err(invalid()); + } + Ok(body) +} + +pub(crate) async fn download( + client: &Client, + url: &str, + sha512: Option<&str>, +) -> Result { + let mut response = client + .get(url) + .header(header::ACCEPT_ENCODING, "identity") + .timeout(Duration::from_secs(120)) + .send() + .await + .map_err(network)?; + if response.status() != StatusCode::OK + || response + .content_length() + .is_some_and(|size| size > MAX_ARTIFACT_BYTES) + { + return Err(invalid()); + } + let file = tempfile::tempfile().map_err(|e| invalid().with_source(e))?; + let mut file = tokio::fs::File::from_std(file); + let mut count = 0u64; + let mut digest = Sha512::new(); + while let Some(chunk) = response.chunk().await.map_err(network)? { + count += chunk.len() as u64; + if count > MAX_ARTIFACT_BYTES { + return Err(invalid()); + } + digest.update(&chunk); + file.write_all(&chunk) + .await + .map_err(|e| invalid().with_source(e))?; + } + if let Some(expected) = sha512 + && hex::encode(digest.finalize()) != expected + { + return Err(invalid()); + } + file.flush().await.map_err(|e| invalid().with_source(e))?; + let mut file = file.into_std().await; + file.rewind().map_err(|e| invalid().with_source(e))?; + Ok(file) +} diff --git a/backend/crates/providers/antigravity/src/profile/artifact.rs b/backend/crates/providers/antigravity/src/profile/artifact.rs new file mode 100644 index 000000000..c17ff1052 --- /dev/null +++ b/backend/crates/providers/antigravity/src/profile/artifact.rs @@ -0,0 +1,295 @@ +//! 从官方发布包核对版本和目标平台,不执行下载的程序或发起模型请求 + +use super::archive::{CancellableFile, RemoteArtifact, RemoteZip, bounded, download, invalid}; +use super::selection::{Architecture, ClientKind, Platform, ReleaseTarget}; +use gateway_core::task::WorkerTaskError; +use std::io::Read; + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct Release { + pub(crate) version: String, + pub(crate) build: Option, + pub(crate) url: String, + pub(crate) sha512: Option, +} + +const MAX_ASAR_BYTES: usize = 16 * 1024 * 1024; +const MAX_BINARY_BYTES: u64 = 512 * 1024 * 1024; + +pub(crate) async fn verify( + client: &reqwest::Client, + target: ReleaseTarget, + version: &str, + url: &str, + sha512: Option<&str>, +) -> Result<(), WorkerTaskError> { + match (target.client, target.platform) { + (ClientKind::Desktop, Platform::Macos) => { + let url = url.strip_suffix(".dmg").ok_or_else(invalid)?; + let archive = RemoteZip::open(client, format!("{url}.zip")).await?; + let asar = archive + .read( + "Antigravity.app/Contents/Resources/app.asar", + MAX_ASAR_BYTES, + ) + .await?; + if asar_version(&asar)? != version { + return Err(invalid()); + } + let executable = archive + .read("Antigravity.app/Contents/MacOS/Antigravity", 1024 * 1024) + .await?; + architecture(&executable, target) + } + (ClientKind::Desktop, Platform::Windows) => { + let artifact = RemoteArtifact::open(client, url.to_owned()).await?; + let header = artifact.prefix(1024 * 1024).await?; + let (offset, size) = pe_resources(&header)?; + let resources = artifact.read(offset, size).await?; + windows_version(&resources, version) + } + _ => { + let file = download(client, url, sha512).await?; + // 取消 worker 时同步中止阻塞解包,临时文件由解析任务退出时关闭 + let (file, _guard) = CancellableFile::new(file); + let version = version.to_owned(); + tokio::task::spawn_blocking(move || { + if target.client == ClientKind::Cli && target.platform == Platform::Windows { + verify_binary(file, target, &version) + } else { + verify_tar(file, target, &version) + } + }) + .await + .map_err(|e| invalid().with_source(e))? + } + } +} + +pub(crate) fn asar_version(body: &[u8]) -> Result { + let header_length = u32_at(body, 4)? as usize; + let json_length = u32_at(body, 12)? as usize; + let data_start = header_length.checked_add(8).ok_or_else(invalid)?; + if json_length > MAX_ASAR_BYTES || json_length.checked_add(16).is_none_or(|n| n > data_start) { + return Err(invalid()); + } + let header: serde_json::Value = + serde_json::from_slice(body.get(16..16 + json_length).ok_or_else(invalid)?) + .map_err(|e| invalid().with_source(e))?; + let package = &header["files"]["package.json"]; + let offset: usize = package["offset"] + .as_str() + .ok_or_else(invalid)? + .parse() + .map_err(|_| invalid())?; + let size = package["size"] + .as_u64() + .filter(|n| *n <= 64 * 1024) + .ok_or_else(invalid)? as usize; + let start = data_start.checked_add(offset).ok_or_else(invalid)?; + let end = start.checked_add(size).ok_or_else(invalid)?; + let package: serde_json::Value = + serde_json::from_slice(body.get(start..end).ok_or_else(invalid)?) + .map_err(|e| invalid().with_source(e))?; + if package["name"] != "antigravity" { + return Err(invalid()); + } + package["version"] + .as_str() + .filter(|v| super::selection::valid_version(v)) + .map(str::to_owned) + .ok_or_else(invalid) +} + +pub(crate) fn architecture(body: &[u8], target: ReleaseTarget) -> Result<(), WorkerTaskError> { + let arm = target.arch == Architecture::Arm64; + let matches = match target.platform { + Platform::Macos => { + body.starts_with(&[0xcf, 0xfa, 0xed, 0xfe]) + && u32_at(body, 4)? == if arm { 0x0100_000c } else { 0x0100_0007 } + } + Platform::Linux => { + body.starts_with(b"\x7fELF\x02\x01") && u16_at(body, 18)? == if arm { 183 } else { 62 } + } + Platform::Windows => { + let pe = pe_offset(body)?; + u16_at(body, pe + 4)? == if arm { 0xaa64 } else { 0x8664 } + } + }; + if matches { Ok(()) } else { Err(invalid()) } +} + +pub(crate) fn verify_tar( + file: impl Read, + target: ReleaseTarget, + version: &str, +) -> Result<(), WorkerTaskError> { + let decoder = flate2::read::GzDecoder::new(file); + let mut archive = tar::Archive::new(decoder.take(2 * 1024 * 1024 * 1024)); + let mut found_version = false; + let mut found_executable = false; + for (index, entry) in archive + .entries() + .map_err(|e| invalid().with_source(e))? + .enumerate() + { + if index >= 16_384 { + return Err(invalid()); + } + let mut entry = entry.map_err(|e| invalid().with_source(e))?; + if !entry.header().entry_type().is_file() { + continue; + } + let path = entry + .path() + .map_err(|e| invalid().with_source(e))? + .into_owned(); + let name = path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or_default(); + if target.client == ClientKind::Cli && matches!(name, "antigravity" | "antigravity.exe") { + if found_executable || entry.size() > MAX_BINARY_BYTES { + return Err(invalid()); + } + verify_binary(&mut entry, target, version)?; + found_version = true; + found_executable = true; + } else if target.client == ClientKind::Desktop { + if path.ends_with("resources/app.asar") { + if found_version || asar_version(&bounded(&mut entry, MAX_ASAR_BYTES)?)? != version + { + return Err(invalid()); + } + found_version = true; + } else if name == "antigravity" { + if found_executable { + return Err(invalid()); + } + let mut header = [0; 64]; + entry + .read_exact(&mut header) + .map_err(|e| invalid().with_source(e))?; + architecture(&header, target)?; + found_executable = true; + } + } + } + if found_version && found_executable { + Ok(()) + } else { + Err(invalid()) + } +} + +pub(crate) fn verify_binary( + mut reader: impl Read, + target: ReleaseTarget, + version: &str, +) -> Result<(), WorkerTaskError> { + let mut header = [0; 1024]; + reader + .read_exact(&mut header) + .map_err(|e| invalid().with_source(e))?; + architecture(&header, target)?; + // 官方 CLI 把版本文件嵌入 Go 制品,保留其换行与终止字节避免匹配依赖版本 + let marker = format!("\0{version}\n\0").into_bytes(); + let mut tail = header.to_vec(); + let mut chunk = [0; 64 * 1024]; + let mut count = 1024u64; + let mut found = false; + loop { + if tail.windows(marker.len()).any(|v| v == marker) { + found = true; + } + let keep = tail.len().saturating_sub(marker.len()); + tail.drain(..keep); + let size = reader + .read(&mut chunk) + .map_err(|e| invalid().with_source(e))?; + if size == 0 { + break; + } + count += size as u64; + if count > MAX_BINARY_BYTES { + return Err(invalid()); + } + tail.extend_from_slice(&chunk[..size]); + } + if found { Ok(()) } else { Err(invalid()) } +} + +fn pe_offset(body: &[u8]) -> Result { + if !body.starts_with(b"MZ") { + return Err(invalid()); + } + let offset = u32_at(body, 0x3c)? as usize; + if body.get(offset..offset + 4) != Some(b"PE\0\0") { + return Err(invalid()); + } + Ok(offset) +} + +pub(crate) fn pe_resources(body: &[u8]) -> Result<(u64, u64), WorkerTaskError> { + let pe = pe_offset(body)?; + let count = u16_at(body, pe + 6)? as usize; + let start = pe + 24 + u16_at(body, pe + 20)? as usize; + for i in 0..count.min(96) { + let section = start + i * 40; + if body.get(section..section + 8) == Some(b".rsrc\0\0\0") { + return Ok(( + u64::from(u32_at(body, section + 20)?), + u64::from(u32_at(body, section + 16)?), + )); + } + } + Err(invalid()) +} + +pub(crate) fn windows_version(body: &[u8], version: &str) -> Result<(), WorkerTaskError> { + let parts: Vec = version + .split('.') + .map(str::parse) + .collect::>() + .map_err(|_| invalid())?; + if parts.len() != 3 { + return Err(invalid()); + } + let high = u32::from(parts[0]) << 16 | u32::from(parts[1]); + let low = u32::from(parts[2]) << 16; + let mut found = false; + for (offset, bytes) in body.windows(8).enumerate() { + // 官方 Windows 安装器的 dwStrucVersion 为零,也接受标准的 0x00010000 + if bytes.starts_with(b"\xbd\x04\xef\xfe") + && matches!(u32_at(body, offset + 4)?, 0 | 0x0001_0000) + { + if u32_at(body, offset + 8)? != high + || u32_at(body, offset + 12)? != low + || u32_at(body, offset + 16)? != high + || u32_at(body, offset + 20)? != low + { + return Err(invalid()); + } + found = true; + } + } + if found { Ok(()) } else { Err(invalid()) } +} + +fn u16_at(body: &[u8], offset: usize) -> Result { + Ok(u16::from_le_bytes( + body.get(offset..offset + 2) + .ok_or_else(invalid)? + .try_into() + .map_err(|_| invalid())?, + )) +} +fn u32_at(body: &[u8], offset: usize) -> Result { + Ok(u32::from_le_bytes( + body.get(offset..offset + 4) + .ok_or_else(invalid)? + .try_into() + .map_err(|_| invalid())?, + )) +} diff --git a/backend/crates/providers/antigravity/src/profile/mod.rs b/backend/crates/providers/antigravity/src/profile/mod.rs new file mode 100644 index 000000000..6f09c5cb5 --- /dev/null +++ b/backend/crates/providers/antigravity/src/profile/mod.rs @@ -0,0 +1,33 @@ +//! 画像配置、已冻结的出站身份与发布资料的本地解析入口 + +pub(crate) mod archive; +pub(crate) mod artifact; +pub(crate) mod release; +pub(crate) mod selection; +pub(crate) mod verification; +mod view; +use gateway_admin::ports::provider::ProviderAdminError; +use gateway_core::account::OpaqueProviderData; +pub(crate) use release::{ReleaseService, ReleaseTask}; +pub(crate) use selection::{ClientKind, ClientProfile, Platform, Selection, VersionMode, object}; +pub(crate) use view::{dashboard, options, preview}; + +pub(crate) fn resolve( + configuration: &OpaqueProviderData, + releases: &ReleaseService, +) -> Result { + let selection = Selection::parse(configuration)?; + Ok(selection.resolve( + releases + .snapshot(selection.target()) + .version(selection.client), + )) +} +pub(crate) fn default_profile(releases: &ReleaseService) -> ClientProfile { + let selection = Selection::default(); + selection.resolve( + releases + .snapshot(selection.target()) + .version(selection.client), + ) +} diff --git a/backend/crates/providers/antigravity/src/profile/release.rs b/backend/crates/providers/antigravity/src/profile/release.rs new file mode 100644 index 000000000..e9b88c9c6 --- /dev/null +++ b/backend/crates/providers/antigravity/src/profile/release.rs @@ -0,0 +1,359 @@ +//! 按客户端、平台与架构刷新官方发布资料,失败时保留上次成功结果 + +pub(crate) use super::artifact::Release; +use super::selection::{Architecture, ClientKind, Platform, ReleaseTarget, valid_version}; +use super::verification::{VerificationCache, VerifiedArtifact}; +use crate::ConfigError; +use chrono::{DateTime, Utc}; +use futures::{StreamExt, future::BoxFuture, stream}; +use gateway_core::task::{ScheduledTask, WorkerCycleContext, WorkerTaskError}; +use gateway_core::{provider_ports::ProviderArtifactProfileCachePort, routing::ProviderKind}; +use serde::Deserialize; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::{Arc, Mutex, RwLock}, + time::Duration, +}; + +const DOWNLOAD_PAGE: &str = "https://antigravity.google/download"; +const DESKTOP_PREFIX: &str = "https://storage.googleapis.com/antigravity-public/antigravity-hub/"; +const CLI_MANIFESTS: &str = + "https://antigravity-cli-auto-updater-974169037036.us-central1.run.app/manifests"; +const MAX_RELEASE_BYTES: usize = 2 * 1024 * 1024; + +#[derive(Clone, Default)] +pub(crate) struct ReleaseSnapshot { + pub(crate) release: Option, + pub(crate) checked: Option>, + pub(crate) failed: bool, + verified: Option, +} +impl ReleaseSnapshot { + pub(crate) fn verified_at(&self, version: &str) -> Option> { + self.verified + .as_ref() + .filter(|verified| { + verified.release.version == version + && self.release.as_ref() == Some(&verified.release) + }) + .map(|v| v.verified_at) + } + pub(crate) fn version(&self, client: ClientKind) -> &str { + self.release + .as_ref() + .map_or(client.baseline().version, |release| { + release.version.as_str() + }) + } +} +pub(crate) struct ReleaseService { + client: reqwest::Client, + state: RwLock>, + requested: Mutex>, + verification: VerificationCache, +} +impl ReleaseService { + pub(crate) fn new( + cache: Arc, + ) -> Result { + let client = gateway_egress::http_client(None) + .map_err(|_| ConfigError)? + .https_only(true) + .redirect(reqwest::redirect::Policy::none()) + .timeout(Duration::from_secs(20)) + .build() + .map_err(|_| ConfigError)?; + Ok(Self { + client, + state: RwLock::default(), + requested: Mutex::new(BTreeSet::from([super::Selection::default().target()])), + verification: VerificationCache::new( + ProviderKind::new("antigravity").map_err(|_| ConfigError)?, + cache, + ), + }) + } + pub(crate) fn snapshot(&self, target: ReleaseTarget) -> ReleaseSnapshot { + self.requested + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert(target); + self.state + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(&target) + .cloned() + .unwrap_or_default() + } + pub(crate) fn publish(&self, target: ReleaseTarget, result: Option) { + let mut state = self + .state + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let entry = state.entry(target).or_default(); + entry.checked = Some(Utc::now()); + entry.failed = result.is_none(); + if let Some(release) = result { + entry.release = Some(release); + } + } + async fn fetch(&self, url: &str) -> Result, WorkerTaskError> { + let mut response = self + .client + .get(url) + .send() + .await + .map_err(|e| { + WorkerTaskError::safe("读取 Antigravity 发布资料失败").with_source(e.without_url()) + })? + .error_for_status() + .map_err(|e| { + WorkerTaskError::safe("Antigravity 发布资料返回错误状态") + .with_source(e.without_url()) + })?; + let mut body = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(|e| { + WorkerTaskError::safe("读取 Antigravity 发布资料失败").with_source(e.without_url()) + })? { + if body.len().saturating_add(chunk.len()) > MAX_RELEASE_BYTES { + return Err(WorkerTaskError::safe("Antigravity 发布资料超出大小限制")); + } + body.extend_from_slice(&chunk); + } + Ok(body) + } + pub(crate) async fn update(&self) -> Result<(), WorkerTaskError> { + let due = { + let state = self + .state + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner); + state.is_empty() + || state.values().any(|s| { + s.failed + || s.checked + .is_none_or(|at| (Utc::now() - at).num_seconds() >= 86400) + }) + }; + let mut first_error = if due { + self.refresh().await.err() + } else { + None + }; + let targets: Vec<_> = self + .requested + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .iter() + .copied() + .collect(); + let mut verification = stream::iter(targets) + .map(|target| async move { + let snapshot = self.snapshot(target); + let Some(release) = snapshot.release.as_ref() else { + return Ok(()); + }; + let verified = self + .verification + .verify(&self.client, target, release, snapshot.verified.as_ref()) + .await?; + let mut state = self + .state + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(current) = state.get_mut(&target) + && current.release.as_ref() == Some(&verified.release) + { + current.verified = Some(verified); + } + Ok::<_, WorkerTaskError>(()) + }) + .buffer_unordered(2); + while let Some(result) = verification.next().await { + if let Err(error) = result { + first_error.get_or_insert(error); + } + } + first_error.map_or(Ok(()), Err) + } + async fn refresh(&self) -> Result<(), WorkerTaskError> { + let page = self.fetch(DOWNLOAD_PAGE).await; + let mut first_error = None; + for platform in [Platform::Macos, Platform::Linux, Platform::Windows] { + for arch in [Architecture::Arm64, Architecture::Amd64] { + let target = ReleaseTarget { + client: ClientKind::Desktop, + platform, + arch, + }; + let release = page + .as_ref() + .ok() + .and_then(|page| std::str::from_utf8(page).ok()) + .and_then(|page| parse_desktop(page, target)); + if release.is_none() { + first_error = Some(WorkerTaskError::safe( + "无法解析 Antigravity Desktop 发布资料", + )); + } + self.publish(target, release); + } + } + if let Err(error) = page { + first_error = Some(error); + } + let targets = [Platform::Macos, Platform::Linux, Platform::Windows] + .into_iter() + .flat_map(|platform| { + [Architecture::Arm64, Architecture::Amd64].map(move |arch| ReleaseTarget { + client: ClientKind::Cli, + platform, + arch, + }) + }); + let mut updates = stream::iter(targets) + .map(|target| async move { + let url = format!( + "{CLI_MANIFESTS}/{}_{}.json", + target.platform.os_type(), + target.arch.label() + ); + let result = self + .fetch(&url) + .await + .and_then(|body| parse_cli(&body, target)); + self.publish(target, result.as_ref().ok().cloned()); + result + }) + .buffer_unordered(3); + while let Some(result) = updates.next().await { + if let Err(error) = result { + first_error.get_or_insert(error); + } + } + first_error.map_or(Ok(()), Err) + } +} +pub(crate) fn parse_desktop(page: &str, target: ReleaseTarget) -> Option { + let (platform, filename) = match target.platform { + Platform::Macos => ("darwin", "Antigravity.dmg"), + Platform::Linux => ("linux", "Antigravity.tar.gz"), + Platform::Windows => ( + "windows", + match target.arch { + Architecture::Arm64 => "Antigravity-arm64.exe", + Architecture::Amd64 => "Antigravity-x64.exe", + }, + ), + }; + let arch = match target.arch { + Architecture::Arm64 => "arm", + Architecture::Amd64 => "x64", + }; + let suffix = format!("/{platform}-{arch}/{filename}"); + let mut found = None; + for quoted in page.split("href=").skip(1) { + let Some(quote) = quoted.chars().next() else { + continue; + }; + if !matches!(quote, '"' | '\'') { + continue; + } + let Some((href, _)) = quoted[1..].split_once(quote) else { + continue; + }; + let Some((version, build)) = href + .strip_prefix(DESKTOP_PREFIX) + .and_then(|s| s.strip_suffix(&suffix)) + .and_then(|s| s.split_once('-')) + else { + continue; + }; + if !valid_version(version) + || build.is_empty() + || build.len() > 20 + || !build.bytes().all(|c| c.is_ascii_digit()) + { + continue; + } + let release = Release { + version: version.into(), + build: Some(build.into()), + url: href.into(), + sha512: None, + }; + if found.as_ref().is_some_and(|current| current != &release) { + return None; + } + found = Some(release); + } + found +} +pub(crate) fn parse_cli(body: &[u8], target: ReleaseTarget) -> Result { + #[derive(Deserialize)] + struct Manifest { + version: String, + url: String, + sha512: String, + } + let manifest: Manifest = serde_json::from_slice(body) + .map_err(|e| WorkerTaskError::safe("无法解析 Antigravity CLI 发布资料").with_source(e))?; + let prefix = format!( + "https://storage.googleapis.com/antigravity-public/antigravity-cli/{}-", + manifest.version + ); + let build = manifest + .url + .strip_prefix(&prefix) + .and_then(|s| s.split_once('/')) + .map(|(build, _)| build.to_owned()); + let directory_arch = match target.arch { + Architecture::Arm64 => "arm", + Architecture::Amd64 => "x64", + }; + let file_arch = match target.arch { + Architecture::Arm64 => "arm64", + Architecture::Amd64 => "x64", + }; + let file_platform = match target.platform { + Platform::Macos => "mac", + Platform::Linux => "linux", + Platform::Windows => "windows", + }; + let extension = if target.platform == Platform::Windows { + "exe" + } else { + "tar.gz" + }; + let suffix = format!( + "/{}-{directory_arch}/cli_{file_platform}_{file_arch}.{extension}", + target.platform.os_type() + ); + if !valid_version(&manifest.version) + || target.client != ClientKind::Cli + || build + .as_ref() + .is_some_and(|build| manifest.url != format!("{prefix}{build}{suffix}")) + || manifest.sha512.len() != 128 + || !manifest.sha512.bytes().all(|c| c.is_ascii_hexdigit()) + || build + .as_ref() + .is_none_or(|v| v.is_empty() || v.len() > 20 || !v.bytes().all(|c| c.is_ascii_digit())) + { + return Err(WorkerTaskError::safe("Antigravity CLI 发布资料无效")); + } + Ok(Release { + version: manifest.version, + build, + url: manifest.url, + sha512: Some(manifest.sha512.to_ascii_lowercase()), + }) +} +pub(crate) struct ReleaseTask(pub(crate) Arc); +impl ScheduledTask for ReleaseTask { + fn run_cycle(&self, ctx: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> { + Box::pin(async move { + tokio::select! {_=ctx.cancellation().cancelled()=>Ok(()),result=self.0.update()=>result} + }) + } +} diff --git a/backend/crates/providers/antigravity/src/profile/selection.rs b/backend/crates/providers/antigravity/src/profile/selection.rs new file mode 100644 index 000000000..7f083cfee --- /dev/null +++ b/backend/crates/providers/antigravity/src/profile/selection.rs @@ -0,0 +1,258 @@ +//! 客户端选择与冻结身份,不读取网络或运行时设置 + +use chrono::{DateTime, TimeZone, Utc}; +use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind}; +use gateway_core::account::OpaqueProviderData; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum ClientKind { + Desktop, + Cli, +} +pub(crate) struct ClientBuild { + pub(crate) version: &'static str, + changelist: u64, +} +impl ClientKind { + pub(crate) const fn product(self) -> &'static str { + match self { + Self::Desktop => "Antigravity Desktop", + Self::Cli => "Antigravity CLI", + } + } + pub(crate) const fn baseline(self) -> ClientBuild { + // 版本与 CL 成对取自官方二进制及已认证请求,下载目录的编号不是 CL + match self { + Self::Desktop => ClientBuild { + version: "2.34.0", + changelist: 1_026_637_980, + }, + Self::Cli => ClientBuild { + version: "1.5.15", + changelist: 1_027_820_220, + }, + } + } + const fn subclient(self) -> &'static str { + match self { + Self::Desktop => "hub", + Self::Cli => "cli", + } + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum Platform { + Macos, + Linux, + Windows, +} +impl Platform { + pub(crate) const fn os_type(self) -> &'static str { + match self { + Self::Macos => "darwin", + Self::Linux => "linux", + Self::Windows => "windows", + } + } + pub(crate) const fn label(self) -> &'static str { + match self { + Self::Macos => "macOS", + Self::Linux => "Linux", + Self::Windows => "Windows", + } + } + pub(crate) const fn default_arch(self) -> Architecture { + match self { + Self::Macos => Architecture::Arm64, + _ => Architecture::Amd64, + } + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum Architecture { + Arm64, + Amd64, +} +impl Architecture { + pub(crate) const fn label(self) -> &'static str { + match self { + Self::Arm64 => "arm64", + Self::Amd64 => "amd64", + } + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum VersionMode { + Latest, + Fixed, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct Selection { + pub(crate) client: ClientKind, + pub(crate) platform: Platform, + pub(crate) version_mode: VersionMode, + pub(crate) client_version: Option, + pub(crate) arch: Option, + pub(crate) system_prompt: Option, +} +impl Default for Selection { + fn default() -> Self { + Self { + client: ClientKind::Desktop, + platform: Platform::Macos, + version_mode: VersionMode::Latest, + client_version: None, + arch: None, + system_prompt: None, + } + } +} +impl Selection { + pub(crate) fn parse(value: &OpaqueProviderData) -> Result { + let mut selection: Self = + serde_json::from_value(Value::Object(value.expose_to_provider().clone())) + .map_err(|e| invalid().with_source(e))?; + if let Some(prompt) = &selection.system_prompt { + validate_system_prompt(prompt)?; + if prompt.trim().is_empty() { + selection.system_prompt = None; + } + } + match (&selection.version_mode, &selection.client_version) { + (VersionMode::Latest, None) => Ok(selection), + (VersionMode::Fixed, Some(version)) if valid_version(version) => Ok(selection), + _ => Err(invalid()), + } + } + pub(crate) fn configuration(&self) -> OpaqueProviderData { + object(json!(self)) + } + pub(crate) fn target(&self) -> ReleaseTarget { + ReleaseTarget { + client: self.client, + platform: self.platform, + arch: self.arch.unwrap_or_else(|| self.platform.default_arch()), + } + } + pub(crate) fn resolve(&self, latest: &str) -> ClientProfile { + let version = self.client_version.as_deref().unwrap_or(latest); + let baseline = self.client.baseline(); + ClientProfile { + client: self.client, + platform: self.platform, + arch: self.target().arch, + client_version: version.into(), + // 发布资料只有版本号;未知版本不沿用另一个版本的构建号 + changelist: (version == baseline.version).then_some(baseline.changelist), + system_prompt: self + .system_prompt + .as_deref() + .unwrap_or(DEFAULT_SYSTEM_PROMPT) + .to_owned(), + } + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct ReleaseTarget { + pub(crate) client: ClientKind, + pub(crate) platform: Platform, + pub(crate) arch: Architecture, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct ClientProfile { + pub(crate) client: ClientKind, + pub(crate) platform: Platform, + pub(crate) arch: Architecture, + pub(crate) client_version: String, + changelist: Option, + pub(crate) system_prompt: String, +} +impl ClientProfile { + pub(crate) fn from_frozen(value: &OpaqueProviderData) -> Result { + let profile: Self = + serde_json::from_value(Value::Object(value.expose_to_provider().clone())) + .map_err(|e| invalid().with_source(e))?; + if !valid_version(&profile.client_version) || profile.changelist == Some(0) { + return Err(invalid()); + } + validate_system_prompt(&profile.system_prompt)?; + Ok(profile) + } + pub(crate) fn frozen(&self) -> OpaqueProviderData { + object(json!(self)) + } + pub(crate) fn verified_at(&self) -> Option> { + let baseline = self.client.baseline(); + if self.client != ClientKind::Desktop + || self.platform != Platform::Macos + || self.arch != Architecture::Arm64 + || self.client_version != baseline.version + || self.changelist != Some(baseline.changelist) + { + return None; + } + // Desktop 完整 UA 已实测;CLI 的 ACP 采样不足以核验普通交互入口的完整画像 + // 核验时间独立于官方发布资料的轮询时间 + Utc.with_ymd_and_hms(2026, 11, 23, 11, 11, 15).single() + } + pub(crate) fn client_identifier(&self) -> String { + format!( + "antigravity/{}/{}", + self.client.subclient(), + self.client_version + ) + } + pub(crate) fn user_agent(&self) -> String { + let mut user_agent = format!( + "{} (aidev_client; os_type={}; arch={}", + self.client_identifier(), + self.platform.os_type(), + self.arch.label() + ); + if let Some(changelist) = self.changelist { + user_agent.push_str(&format!("; cl={changelist}")); + } + if self.client == ClientKind::Cli { + // CLI 的个人 OAuth 身份携带此字段;Desktop 的已认证请求未携带 + user_agent.push_str("; auth_method=consumer"); + } + user_agent.push(')'); + user_agent + } +} +pub(crate) fn valid_version(version: &str) -> bool { + let parts = version.split('.'); + parts.clone().count() == 3 + && parts + .into_iter() + .all(|v| !v.is_empty() && v.len() <= 9 && v.bytes().all(|c| c.is_ascii_digit())) +} +pub(crate) fn object(value: Value) -> OpaqueProviderData { + OpaqueProviderData::new(value.as_object().cloned().unwrap_or_default()) +} +fn invalid() -> ProviderAdminError { + ProviderAdminError::new(ProviderAdminErrorKind::Invalid) + .with_public_message("Antigravity 客户端配置无效;固定版本须为三段数字") +} + +// AGY CLI 1.5.15 内置身份模板的默认交互分支;工具和工作区模板由各客户端管理 +pub(crate) const DEFAULT_SYSTEM_PROMPT: &str = "You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.\nYou are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question."; + +fn validate_system_prompt(prompt: &str) -> Result<(), ProviderAdminError> { + if prompt.len() > 16 * 1024 || prompt.contains('\0') { + return Err(ProviderAdminError::new(ProviderAdminErrorKind::Invalid) + .with_public_message("Antigravity 系统提示词不得超过 16 KiB 或包含空字符")); + } + Ok(()) +} diff --git a/backend/crates/providers/antigravity/src/profile/verification.rs b/backend/crates/providers/antigravity/src/profile/verification.rs new file mode 100644 index 000000000..0f45caddc --- /dev/null +++ b/backend/crates/providers/antigravity/src/profile/verification.rs @@ -0,0 +1,163 @@ +//! 复用共享制品缓存,核验事实必须绑定完整发布资料和目标平台 + +use super::{ + artifact::{self, Release}, + selection::ReleaseTarget, +}; +use chrono::{DateTime, Utc}; +use gateway_core::{ + account::OpaqueProviderData, + provider_ports::{ProviderArtifactProfile, ProviderArtifactProfileCachePort}, + routing::ProviderKind, + task::WorkerTaskError, +}; +use serde::{Deserialize, Serialize}; +use std::{ + sync::Arc, + time::{Duration, Instant}, +}; + +const CACHE_TTL: Duration = Duration::from_secs(30 * 86400); +const RENEW_INTERVAL: Duration = Duration::from_secs(86400); + +#[derive(Clone)] +pub(crate) struct VerifiedArtifact { + pub(crate) release: Release, + pub(crate) verified_at: DateTime, + renewed_at: Instant, +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Payload { + target: ReleaseTarget, + release: Release, +} + +pub(crate) struct VerificationCache { + provider: ProviderKind, + cache: Arc, +} +impl VerificationCache { + pub(crate) fn new( + provider: ProviderKind, + cache: Arc, + ) -> Self { + Self { provider, cache } + } + + pub(crate) async fn verify( + &self, + client: &reqwest::Client, + target: ReleaseTarget, + release: &Release, + previous: Option<&VerifiedArtifact>, + ) -> Result { + let sequence = sequence(&release.version)?; + if let Some(previous) = previous.filter(|previous| previous.release == *release) + && previous.renewed_at.elapsed() < RENEW_INTERVAL + { + return Ok(previous.clone()); + } + let key = key(target); + let cached = self + .cache + .read(&self.provider, &key) + .await + .map_err(|e| error().with_source(e))?; + let verified_at = if let Some(cached) = cached { + let payload: Payload = serde_json::from_value(serde_json::Value::Object( + cached.profile().expose_to_provider().clone(), + )) + .map_err(|e| error().with_source(e))?; + if cached.provider_kind() != &self.provider + || cached.artifact_key() != key + || payload.target != target + || cached.artifact_sequence() != self::sequence(&payload.release.version)? + { + return Err(error()); + } + if cached.artifact_sequence() > sequence + || (cached.artifact_sequence() == sequence && payload.release != *release) + { + return Err(error()); + } + (payload.release == *release).then(|| DateTime::::from(cached.verified_at())) + } else { + None + }; + let verified_at = match verified_at.or_else(|| { + previous + .filter(|v| v.release == *release) + .map(|v| v.verified_at) + }) { + Some(at) => at, + None => { + artifact::verify( + client, + target, + &release.version, + &release.url, + release.sha512.as_deref(), + ) + .await?; + Utc::now() + } + }; + let payload = serde_json::to_value(Payload { + target, + release: release.clone(), + }) + .map_err(|e| error().with_source(e))?; + let serde_json::Value::Object(payload) = payload else { + return Err(error()); + }; + let profile = ProviderArtifactProfile::new( + self.provider.clone(), + key, + sequence, + verified_at.into(), + OpaqueProviderData::new(payload), + ); + if !self + .cache + .replace_if_newer(profile, CACHE_TTL) + .await + .map_err(|e| error().with_source(e))? + { + return Err(error()); + } + Ok(VerifiedArtifact { + release: release.clone(), + verified_at, + renewed_at: Instant::now(), + }) + } +} + +pub(crate) fn key(target: ReleaseTarget) -> String { + let client = match target.client { + super::selection::ClientKind::Desktop => "desktop", + super::selection::ClientKind::Cli => "cli", + }; + format!( + "{client}-{}-{}", + target.platform.os_type(), + target.arch.label() + ) +} + +pub(crate) fn sequence(version: &str) -> Result { + let parts: Vec = version + .split('.') + .map(str::parse) + .collect::>() + .map_err(|_| error())?; + if parts.len() != 3 { + return Err(error()); + } + Ok(u64::from(parts[0]) << 32 | u64::from(parts[1]) << 16 | u64::from(parts[2])) +} +fn error() -> WorkerTaskError { + WorkerTaskError::safe("Antigravity 已核验发布包缓存无效或不可用") +} diff --git a/backend/crates/providers/antigravity/src/profile/view.rs b/backend/crates/providers/antigravity/src/profile/view.rs new file mode 100644 index 000000000..f8b048cab --- /dev/null +++ b/backend/crates/providers/antigravity/src/profile/view.rs @@ -0,0 +1,85 @@ +//! 管理端画像预览与仪表盘投影,不参与出站身份解析 + +use super::{ClientKind, Platform, ReleaseService, Selection, VersionMode, object}; +use gateway_admin::{ + model::observability::{ + DashboardDesktopRelease, DashboardWireAttribute, DashboardWireProfile, DashboardWireTarget, + DesktopReleaseStatus, + }, + ports::provider::ProviderAdminError, +}; +use gateway_core::account::OpaqueProviderData; +use serde_json::{Value, json}; + +pub(crate) fn options() -> OpaqueProviderData { + let presets=[Platform::Macos,Platform::Linux,Platform::Windows].into_iter().flat_map(|platform|[ClientKind::Desktop,ClientKind::Cli].map(move|client|json!({"configuration":Selection {client,platform,..Selection::default()},"automaticAvailable":true,"reason":null}))).collect::>(); + object( + json!({"defaults":Selection::default(),"presets":presets,"defaultSystemPrompt":super::selection::DEFAULT_SYSTEM_PROMPT,"systemPromptSource":"Antigravity CLI 1.5.15"}), + ) +} +pub(crate) fn dashboard(selection: &Selection, releases: &ReleaseService) -> DashboardWireProfile { + let snapshot = releases.snapshot(selection.target()); + let profile = selection.resolve(snapshot.version(selection.client)); + let fixed = selection.version_mode == VersionMode::Fixed; + let release = (!fixed).then(|| DashboardDesktopRelease { + status: if snapshot.failed { + DesktopReleaseStatus::Failed + } else if snapshot.release.is_none() { + DesktopReleaseStatus::Unchecked + } else { + DesktopReleaseStatus::Current + }, + checked_at: snapshot.checked, + latest_version: snapshot.release.as_ref().map(|r| r.version.clone()), + latest_build: snapshot.release.as_ref().and_then(|r| r.build.clone()), + download_url: snapshot.release.as_ref().map(|r| r.url.clone()), + published_at: None, + minimum_system_version: None, + hardware_requirements: None, + download_size: None, + signature_present: None, + error: snapshot + .failed + .then(|| "无法读取 Google 官方客户端版本".into()), + }); + DashboardWireProfile { + provider: "antigravity".into(), + product: profile.client.product().into(), + version: profile.client_version.clone(), + build: None, + target: DashboardWireTarget { + os_type: profile.platform.label().into(), + os_version: String::new(), + arch: profile.arch.label().into(), + terminal: String::new(), + }, + attributes: vec![ + DashboardWireAttribute { + key: "client_identifier".into(), + value: profile.client_identifier(), + }, + DashboardWireAttribute { + key: "version_policy".into(), + value: if fixed { "fixed" } else { "latest" }.into(), + }, + ], + user_agent: profile.user_agent(), + release, + verified_at: snapshot + .verified_at(&profile.client_version) + .or_else(|| profile.verified_at()), + } +} +pub(crate) fn preview( + configuration: &OpaqueProviderData, + releases: &ReleaseService, +) -> Result { + let selection = Selection::parse(configuration)?; + let view = dashboard(&selection, releases); + let fixed = selection.version_mode == VersionMode::Fixed; + let checked = view.release.as_ref().and_then(|r| r.checked_at); + let error = view.release.as_ref().and_then(|r| r.error.as_ref()); + Ok(object( + json!({"configuration":Value::Object(selection.configuration().into_inner()),"versionSource":if fixed {"custom"} else {"official"},"product":view.product,"osType":view.target.os_type,"arch":view.target.arch,"clientVersion":view.version,"userAgent":view.user_agent,"checkedAt":checked,"verifiedAt":view.verified_at,"error":error}), + )) +} diff --git a/backend/crates/providers/antigravity/src/provider/affinity.rs b/backend/crates/providers/antigravity/src/provider/affinity.rs new file mode 100644 index 000000000..c31a159bc --- /dev/null +++ b/backend/crates/providers/antigravity/src/provider/affinity.rs @@ -0,0 +1,74 @@ +//! 在协议转换前识别会话,按 Client Key 和模型隔离账号绑定 + +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use gateway_core::{ + operation::Operation, policy::ClientApiKeyId, provider_ports::ProviderSessionAffinityKey, + routing::UpstreamModelId, +}; +use gateway_protocol::{anthropic, genai, openai}; +use serde_json::{Map, Value}; +use sha2::{Digest as _, Sha256}; + +pub(super) fn session_key( + operation: &Operation, + client: &ClientApiKeyId, + model: &UpstreamModelId, +) -> Option { + let Operation::Generate(generate) = operation else { + return None; + }; + let payload = generate.protocol_payload(); + let session = match payload.protocol() { + openai::OPENAI_PROTOCOL => { + openai::codex_account_session_id(payload.body(), payload.context()) + } + anthropic::ANTHROPIC_PROTOCOL => anthropic::claude_session_id( + payload.body(), + header(payload.context(), "x-claude-code-session-id").as_deref(), + ), + genai::GENAI_PROTOCOL => header(payload.context(), "x-http-session-id") + .or_else(|| header(payload.context(), "x-session-id")) + .or_else(|| { + payload + .body() + .get("sessionId") + .or_else(|| payload.body().get("session_id")) + .and_then(Value::as_str) + .map(str::to_owned) + }), + _ => None, + }?; + let session = session.trim(); + if session.is_empty() || session.len() > 1024 || session.chars().any(char::is_control) { + return None; + } + let mut hash = Sha256::new(); + hash.update(b"antigravity-session-affinity-v1\0"); + // 长度前缀隔离各字段,不把正文或不同租户的同名会话混为一体 + for part in [client.as_str(), model.as_str(), payload.protocol(), session] { + hash.update((part.len() as u64).to_be_bytes()); + hash.update(part.as_bytes()); + } + ProviderSessionAffinityKey::try_new(hex::encode(hash.finalize())).ok() +} + +fn header(context: &Map, name: &str) -> Option { + context + .get("headers") + .and_then(|headers| headers.get(name)) + .and_then(Value::as_str) + .map(str::to_owned) + .or_else(|| { + context + .get("opaque_request_headers")? + .as_array()? + .iter() + .find_map(|entry| { + let pair = entry.as_array()?; + if !pair.first()?.as_str()?.eq_ignore_ascii_case(name) { + return None; + } + String::from_utf8(STANDARD.decode(pair.get(1)?.as_str()?).ok()?).ok() + }) + }) +} diff --git a/backend/crates/providers/antigravity/src/provider/candidates.rs b/backend/crates/providers/antigravity/src/provider/candidates.rs new file mode 100644 index 000000000..51d296bb6 --- /dev/null +++ b/backend/crates/providers/antigravity/src/provider/candidates.rs @@ -0,0 +1,194 @@ +//! 从本地目录、凭据版本、额度和租约信号构建本轮候选 + +use super::AntigravityProvider; +use crate::transport::unsent; +use gateway_core::{ + account::{ + AccountCandidate, AccountSelectionContext, AccountStatus, CredentialRevision, + ProviderAccountId, + }, + engine::AttemptContext, + error::{ProviderError, ProviderErrorKind as Kind}, + provider_ports::{ProviderConcurrencyPool, ProviderCooldownScope}, + routing::UpstreamModelId, +}; +use std::{collections::BTreeMap, time::SystemTime}; + +pub(super) enum Project { + Catalog(String), + Discover, +} + +pub(super) struct CandidatePool { + pub(super) accounts: Vec, + pub(super) projects: BTreeMap, + pub(super) selection: AccountSelectionContext, +} + +impl AntigravityProvider { + pub(super) async fn load_candidates( + &self, + model: &UpstreamModelId, + ctx: &AttemptContext, + ) -> Result { + let required = ctx.required_account(); + let diagnostic = ctx.is_diagnostic_required_account(); + let (accounts, projects) = if diagnostic { + let id = required.ok_or_else(|| unsent(Kind::NoEligibleAccount))?; + let account = self + .accounts + .get_account(id) + .await + .map_err(super::unavailable)? + .filter(|account| account.provider() == &self.kind) + .ok_or_else(|| unsent(Kind::NoEligibleAccount))?; + let projects = BTreeMap::from([(id.clone(), (account.revision(), Project::Discover))]); + (vec![account], projects) + } else { + let projects = self.catalog_projects(model, ctx).await?; + let ids: Vec<_> = projects.keys().cloned().collect(); + if ids.is_empty() { + return Err(unsent(Kind::NoEligibleAccount)); + } + let accounts = self + .accounts + .list_for_provider_accounts(&self.kind, &ids) + .await + .map_err(super::unavailable)?; + (accounts, projects) + }; + let ids: Vec<_> = accounts + .iter() + .map(|account| account.id().clone()) + .collect(); + let mut quota = if diagnostic { + BTreeMap::new() + } else { + self.quota + .scheduling(&accounts, model.as_str()) + .await + .map_err(super::unavailable)? + }; + let scheduling = self + .leases + .load_state( + ctx.client_api_key_ref(), + &self.kind, + &ids, + ProviderConcurrencyPool::Shared, + ) + .await + .map_err(super::unavailable)?; + let mut excluded = ctx.excluded_accounts().clone(); + if ctx.account_scope().is_some() { + let scope = ProviderCooldownScope::upstream_model(model.clone()); + let (account_cooldowns, model_cooldowns) = tokio::join!( + self.cooldowns.read_many(&ids), + self.cooldowns.read_scoped_many(&ids, &scope) + ); + let now = SystemTime::now(); + for ((account, local), model_cooldown) in + accounts.iter().zip(account_cooldowns).zip(model_cooldowns) + { + let revision = account.revision(); + let local = local.map_err(super::unavailable)?; + let model_cooldown = model_cooldown.map_err(super::unavailable)?; + if local.is_some_and(|cooldown| { + cooldown.credential_revision() == revision + && cooldown.scheduling_state().is_active(now) + }) || model_cooldown.is_some_and(|cooldown| { + cooldown.credential_revision() == revision && cooldown.until() > now + }) { + excluded.insert(account.id().clone()); + } + } + } + let now = SystemTime::now(); + let mut candidates = Vec::new(); + let mut model_exhausted = false; + for account in accounts { + let (exhausted, quota_signals) = quota.remove(account.id()).unwrap_or_default(); + if projects + .get(account.id()) + .is_none_or(|(revision, _)| *revision != account.revision()) + || (!diagnostic && !account.model_access().allows(model.as_str())) + || ctx.excludes_proxy(account.outbound_proxy()) + { + continue; + } + if exhausted { + model_exhausted |= !excluded.contains(account.id()) + && matches!( + account.status_projection(now, None).status, + AccountStatus::Normal | AccountStatus::QuotaExhausted + ); + continue; + } + let (failure_rate, first_output_latency) = + self.feedback.scheduling_signals(&self.kind, account.id()); + let signals = scheduling + .signals() + .get(account.id()) + .cloned() + .ok_or_else(|| unsent(Kind::ProviderInfrastructureUnavailable))? + .with_runtime_health(failure_rate, first_output_latency) + .with_provider_quota(quota_signals); + candidates.push(AccountCandidate { + account, + signals, + inherited_concurrency: None, + }); + } + if candidates.is_empty() && model_exhausted { + return Err(unsent(Kind::QuotaExhausted)); + } + let selection = AccountSelectionContext { + policy: ctx.account_selection_policy(), + now, + excluded_accounts: excluded, + busy_accounts: Default::default(), + preferred_account: required.cloned(), + preferred_account_overrides_weight: false, + round_robin_cursor: scheduling.round_robin_cursor(), + eligibility: ctx.account_eligibility(), + account_scope: ctx.account_scope().cloned(), + reserved_concurrency: 0, + }; + Ok(CandidatePool { + accounts: candidates, + projects, + selection, + }) + } + + async fn catalog_projects( + &self, + model: &UpstreamModelId, + ctx: &AttemptContext, + ) -> Result, ProviderError> { + let required = ctx.required_account(); + let mut projects = BTreeMap::new(); + for (observations, catalog) in self.catalog.catalogs().await? { + if !catalog.models.contains_key(model.as_str()) { + continue; + } + for observation in observations { + let account_id = observation.account_id; + if required.is_none_or(|id| id == &account_id) + && ctx.account_scope().map_or(required.is_some(), |scope| { + scope.allows_model(&account_id, model.as_str()) + }) + { + projects.insert( + account_id, + ( + observation.revision, + Project::Catalog(catalog.project.clone()), + ), + ); + } + } + } + Ok(projects) + } +} diff --git a/backend/crates/providers/antigravity/src/provider/execution.rs b/backend/crates/providers/antigravity/src/provider/execution.rs new file mode 100644 index 000000000..38d8e0301 --- /dev/null +++ b/backend/crates/providers/antigravity/src/provider/execution.rs @@ -0,0 +1,164 @@ +//! 冻结账号事实后返回惰性出站流,等待 Core 完成范围检查再发送 + +use super::{AntigravityProvider, candidates::Project}; +use crate::transport::unsent; +use futures::StreamExt; +use gateway_core::{ + account::AccountHistorySnapshot, + engine::{ + AttemptContext, + provider::{ + ProviderCallMetadata, ProviderRequest, ProviderSelectionObservation, ProviderStream, + }, + }, + error::{ProviderError, ProviderErrorKind as Kind}, + operation::Operation, + upstream::{UpstreamSendState, UpstreamTransport}, +}; +use gateway_protocol::genai::GENAI_PROTOCOL; +use std::{sync::Arc, time::Instant}; + +impl AntigravityProvider { + pub(super) async fn execute_native( + self: Arc, + request: ProviderRequest, + ctx: AttemptContext, + ) -> Result { + if !matches!( + request.operation().protocol(), + GENAI_PROTOCOL + | "token-count" + | gateway_protocol::openai::OPENAI_PROTOCOL + | gateway_protocol::anthropic::ANTHROPIC_PROTOCOL + ) { + return Err(unsent(Kind::Unsupported)); + } + let model = request + .candidate() + .upstream_model() + .cloned() + .ok_or_else(|| unsent(Kind::InvalidRequest))?; + let started = Instant::now(); + let affinity = + super::affinity::session_key(request.operation(), ctx.client_api_key_ref(), &model); + let selected = self.select_account(&model, &ctx, affinity.as_ref()).await?; + let selection = ProviderSelectionObservation::new( + u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX), + selected.capacity, + ); + let profile = ctx + .request_profile() + .map(crate::profile::ClientProfile::from_frozen) + .transpose() + .map_err(|e| unsent(Kind::ProviderInfrastructureUnavailable).with_source(e))? + .unwrap_or_else(|| crate::profile::default_profile(&self.release)); + let resource = self + .clients + .client(&self.origin, &selected.account, &profile)?; + let metadata = ProviderCallMetadata::new( + self.kind.clone(), + model.clone(), + selected.account.id().clone(), + UpstreamTransport::new("http") + .map_err(|_| unsent(Kind::ProviderInfrastructureUnavailable))?, + ) + .with_credential_revision(selected.account.revision()) + .with_selection_observation(selection) + .with_account_snapshot(Some(AccountHistorySnapshot::from_account( + &selected.account, + ))); + let cancellation = ctx.cancellation().clone(); + let deadline = ctx.deadline(); + let started_at = ctx.timing_started_at(); + let records_account_feedback = ctx + .account_eligibility() + .allows_account_state_mutation(selected.account.enabled()); + let stats = records_account_feedback.then(|| self.feedback.clone()); + let feedback = self.clone(); + let pricing = crate::billing::effective_pricing( + model.as_str(), + ctx.pricing() + .get(self.kind.as_str()) + .and_then(|models| models.get(model.as_str())), + ); + ctx.execute_middleware( + request.operation().clone(), + self.kind.clone(), + Some(model.as_str().to_owned()), + selected.account.id().clone(), + Box::new(move |operation, headers| Box::pin(async move { + let (operation, translator) = super::translation::prepare(operation)?; + let headers = crate::transport::request_headers(&operation, headers, selected.account_switch); + if operation.protocol() != GENAI_PROTOCOL { + return Err(unsent(Kind::Unsupported)); + } + let (counted, stream, pricing) = match &operation { + Operation::Generate(generate) => { + let payload = generate.protocol_payload(); + (false, payload.context().get("stream").and_then(serde_json::Value::as_bool).unwrap_or(false), + pricing.filter(|_| crate::billing::supports_pricing_fields(payload.body()))) + } + Operation::CountTokens(_) => (true, false, None), + _ => return Err(unsent(Kind::Unsupported)), + }; + let body = operation.middleware_body().map_err(|_| unsent(Kind::InvalidRequest))?; + let events = async_stream::try_stream! { + if cancellation.is_cancelled() { + Err(unsent(Kind::Cancelled))?; + } + if deadline.is_elapsed() { + Err(unsent(Kind::Timeout))?; + } + let record_failure = async |error| { + feedback.record_failure(&selected.account, &model, records_account_feedback, error).await + }; + let response = tokio::select! { + biased; + _ = cancellation.cancelled() => Err(ProviderError::new(Kind::Cancelled, UpstreamSendState::Ambiguous)), + _ = deadline.wait() => Err(ProviderError::new(Kind::Timeout, UpstreamSendState::Ambiguous)), + response = async { + let token = &selected.material.access_token; + if counted { + return resource.count_tokens(token, &body, &headers).await; + } + let project = match selected.project { + Project::Catalog(project) => project, + // 固定探测使用该账号实际授权的项目,包括尚无公开目录的停用账号 + Project::Discover => resource.account_info(token).await?.project, + }; + resource.generate(&project, model.as_str(), token, &body, stream, &headers).await + } => response, + }; + let response = match response { + Ok(response) => response, + Err(error) => Err(record_failure(error).await)?, + }; + let context = crate::transport::ResponseContext { + stream, model: model.clone(), deadline, cancel: cancellation, + token: selected.material.access_token, pricing, started_at, + }; + let mut events: gateway_core::engine::provider::EventStream = if counted { + Box::pin(crate::transport::count_events(response, context)) + } else { + Box::pin(crate::transport::events(response, context)) + }; + while let Some(event) = events.next().await { + match event { + Ok(event) => yield event, + Err(error) => Err(record_failure(error).await)?, + } + } + }; + let stream = ProviderStream::new(metadata, Box::pin(events), selected.lease); + let stream = match translator { + Some(translator) => stream.with_native_response_translator(translator), + None => stream, + }; + Ok(match stats { + Some(stats) => stream.with_account_feedback(stats), + None => stream, + }) + })), + ).await + } +} diff --git a/backend/crates/providers/antigravity/src/provider/feedback.rs b/backend/crates/providers/antigravity/src/provider/feedback.rs new file mode 100644 index 000000000..daca8e371 --- /dev/null +++ b/backend/crates/providers/antigravity/src/provider/feedback.rs @@ -0,0 +1,68 @@ +//! 按实际发送状态记录账号失败和模型冷却 + +use super::AntigravityProvider; +use gateway_core::{ + account::ProviderAccount, + error::{ProviderError, ProviderErrorKind as Kind}, + provider_ports::{ProviderCooldownScope, ProviderScopedCooldown}, + routing::UpstreamModelId, + upstream::UpstreamSendState, +}; +use std::time::{Duration, SystemTime}; + +impl AntigravityProvider { + pub(super) async fn record_failure( + &self, + account: &ProviderAccount, + model: &UpstreamModelId, + records_account_feedback: bool, + error: ProviderError, + ) -> ProviderError { + if error.send_state() != UpstreamSendState::Sent + || !matches!(error.kind(), Kind::Unauthorized | Kind::RateLimited) + { + return error; + } + // 明确拒绝没有生成结果;换号仍受 Core 的交付屏障、范围与预算约束 + let error = error.with_replay_safe().with_pre_delivery_retry(); + if !records_account_feedback { + return error; + } + let feedback = async { + match error.kind() { + Kind::Unauthorized => { + // 资源服务拒绝 AT 不能证明 RT 失效,续期仍由已有 OAuth worker 负责 + self.accounts + .expire_access_token(account, SystemTime::now()) + .await + .map_err(|_| ())?; + } + Kind::RateLimited => { + if let Some(until) = error + .retry_after() + .and_then(|delay| SystemTime::now().checked_add(delay)) + { + self.cooldowns + .put_scoped_if_later(ProviderScopedCooldown::new( + account.id().clone(), + account.revision(), + ProviderCooldownScope::upstream_model(model.clone()), + until, + )) + .await + .map_err(|_| ())?; + } + } + _ => {} + } + Ok::<(), ()>(()) + }; + if !matches!( + tokio::time::timeout(Duration::from_millis(100), feedback).await, + Ok(Ok(())) + ) { + tracing::warn!("Antigravity 失败反馈未能写入共享状态"); + } + error + } +} diff --git a/backend/crates/providers/antigravity/src/provider/mod.rs b/backend/crates/providers/antigravity/src/provider/mod.rs new file mode 100644 index 000000000..10613a719 --- /dev/null +++ b/backend/crates/providers/antigravity/src/provider/mod.rs @@ -0,0 +1,130 @@ +//! Core Provider 的能力投影和单次请求执行 + +mod affinity; +mod candidates; +mod execution; +mod feedback; +mod selection; +mod translation; +pub(crate) mod workers; + +use crate::{ + credential::CredentialService, credential::catalog::CatalogService, + credential::quota::QuotaService, profile::ReleaseService, +}; +use async_trait::async_trait; +use gateway_core::{ + account::{AccountFeedbackStats, ProviderAccountId, ProviderAccountStore}, + concurrency::ConcurrencyWaitQueue, + engine::{ + AttemptContext, + provider::{Provider, ProviderRequest, ProviderStream}, + }, + error::{ErrorSource, ProviderError, ProviderErrorKind}, + provider_ports::{ + ProviderCooldownPort, ProviderLeasePort, ProviderSessionAffinityPort, ProviderStorePorts, + }, + routing::{ProviderCatalogGeneration, ProviderKind, ProviderModelCapabilities}, +}; +use std::sync::Arc; + +pub(crate) struct AntigravityProvider { + kind: ProviderKind, + credentials: Arc, + quota: Arc, + accounts: Arc, + leases: Arc, + cooldowns: Arc, + session_affinity: Arc, + waiting: ConcurrencyWaitQueue, + catalog: Arc, + release: Arc, + origin: url::Url, + clients: crate::transport::ClientPool, + feedback: Arc, +} + +impl AntigravityProvider { + pub(crate) fn new( + kind: ProviderKind, + ports: &ProviderStorePorts, + credentials: Arc, + catalog: Arc, + quota: Arc, + release: Arc, + origin: url::Url, + ) -> Self { + Self { + credentials, + quota, + accounts: ports.accounts(), + leases: ports.leases(), + cooldowns: ports.cooldowns(), + session_affinity: ports.session_affinity(), + waiting: Default::default(), + kind, + catalog, + release, + origin, + clients: Default::default(), + feedback: ports.account_feedback(), + } + } +} + +#[async_trait] +impl Provider for AntigravityProvider { + fn is_direct_account(&self, authentication_kind: &str) -> bool { + authentication_kind == "oauth" + } + + fn default_request_profile( + &self, + ) -> Result, ProviderError> { + Ok(Some( + crate::profile::default_profile(&self.release).frozen(), + )) + } + + fn resolve_request_profile( + &self, + configuration: &gateway_core::account::OpaqueProviderData, + ) -> Result { + crate::profile::resolve(configuration, &self.release) + .map(|profile| profile.frozen()) + .map_err(|_| { + crate::transport::unsent(gateway_core::error::ProviderErrorKind::InvalidRequest) + }) + } + + fn name(&self) -> &str { + self.kind.as_str() + } + + fn catalog_generation(&self) -> ProviderCatalogGeneration { + ProviderCatalogGeneration::new( + self.catalog + .generation + .load(std::sync::atomic::Ordering::Relaxed), + ) + } + + async fn query_model_capabilities( + &self, + ) -> Result, ProviderError> { + self.catalog.capabilities().await + } + + async fn execute( + self: Arc, + request: ProviderRequest, + context: AttemptContext, + ) -> Result { + self.execute_native(request, context).await + } +} + +fn unavailable(error: impl Into) -> ProviderError { + crate::transport::unsent(ProviderErrorKind::ProviderInfrastructureUnavailable) + .with_source(error) +} diff --git a/backend/crates/providers/antigravity/src/provider/selection.rs b/backend/crates/providers/antigravity/src/provider/selection.rs new file mode 100644 index 000000000..7ffff286e --- /dev/null +++ b/backend/crates/providers/antigravity/src/provider/selection.rs @@ -0,0 +1,336 @@ +//! 协调 Antigravity 账号选择、并发排队和租约,取得租约后复核凭据 + +use super::{ + AntigravityProvider, + candidates::{CandidatePool, Project}, +}; +use crate::{credential::Material, transport::unsent}; +use gateway_core::{ + account::{ + AccountCapacitySnapshot, AccountSelector, PreferredAccountSelection, ProviderAccount, + RotationStrategy, + }, + concurrency::{CapacityWait, ConcurrencyQueuePolicy, QueueRejection}, + engine::{ + AttemptContext, + policy::{AccountPolicyError, AccountScheduleOwnership}, + }, + error::{ProviderDiagnostic, ProviderError, ProviderErrorKind as Kind}, + provider_ports::{ + ProviderAccountAdmission, ProviderLeaseAcquisition, ProviderLeaseGuard, + ProviderLeaseRequest, ProviderSchedulingLeaseRequest, ProviderSessionAffinityKey, + ProviderSessionAffinityState, + }, + routing::UpstreamModelId, +}; +use std::time::Duration; + +pub(super) struct SelectedAccount { + pub(super) account: ProviderAccount, + pub(super) capacity: Option, + pub(super) material: Material, + pub(super) project: Project, + pub(super) lease: Box, + pub(super) account_switch: bool, +} + +#[derive(Debug, thiserror::Error)] +enum SelectionError { + #[error(transparent)] + Queue(#[from] QueueRejection), + #[error(transparent)] + Provider(#[from] ProviderError), +} + +impl AntigravityProvider { + pub(super) async fn select_account( + &self, + model: &UpstreamModelId, + ctx: &AttemptContext, + affinity_key: Option<&ProviderSessionAffinityKey>, + ) -> Result { + let policy = ctx.account_selection_policy(); + let select = |queue| self.select_with_queue(model, ctx, queue, affinity_key); + let result = match select(policy.queue_policy()).await { + Err(SelectionError::Queue(reason)) if ctx.required_account().is_none() => { + policy + .reselect_after_queue_rejection( + reason, + ctx.deadline().remaining(), + select, + |error| match error { + SelectionError::Provider(error) => matches!( + error.kind(), + Kind::NoEligibleAccount | Kind::AccountCapacityUnavailable + ), + SelectionError::Queue(_) => false, + }, + ) + .await + } + result => result, + }; + result.map_err(|error| match error { + SelectionError::Queue(reason) => unsent(reason.provider_kind()), + SelectionError::Provider(error) => error, + }) + } + + async fn select_with_queue( + &self, + model: &UpstreamModelId, + ctx: &AttemptContext, + queue: ConcurrencyQueuePolicy, + affinity_key: Option<&ProviderSessionAffinityKey>, + ) -> Result { + let mut waiting = CapacityWait::new( + &self.waiting, + queue, + ctx.deadline().at(), + ctx.concurrency_wait_budget(), + ) + .with_periodic_recheck(ctx.required_account().is_none()); + 'refresh: loop { + if ctx.cancellation().is_cancelled() { + return Err(unsent(Kind::Cancelled).into()); + } + if ctx.deadline().is_elapsed() { + return Err(unsent(Kind::Timeout).into()); + } + let CandidatePool { + accounts, + mut projects, + mut selection, + } = self.load_candidates(model, ctx).await?; + let affinity = match affinity_key.filter(|_| !ctx.is_diagnostic_required_account()) { + Some(key) => Some(ProviderSessionAffinityState::new( + key, + self.session_affinity + .load(&self.kind, key) + .await + .map_err(super::unavailable)?, + ctx.account_selection_policy(), + )), + None => None, + }; + if let Some(affinity) = &affinity { + affinity.apply_preference(&mut selection); + } + for candidate in &accounts { + if !waiting.can_try(candidate.account.id()) { + selection + .busy_accounts + .insert(candidate.account.id().clone()); + } + } + let binding_eligible = affinity + .as_ref() + .is_some_and(|affinity| affinity.binding_eligible(&accounts, &selection)); + // 分配游标只读,排队重查和亲和命中不消耗新分配的位置 + let assignment_cursor = if selection.policy.strategy() == RotationStrategy::RoundRobin + && ctx.required_account().is_none() + { + let cursor = self + .session_affinity + .round_robin_cursor(&self.kind, ctx.client_api_key_ref()) + .await + .map_err(super::unavailable)?; + selection.round_robin_cursor = cursor; + Some(cursor) + } else { + None + }; + let excluded = std::mem::take(&mut selection.excluded_accounts); + let mut retry_after: Option = None; + loop { + // 每次策略求值都从相同的授权、冷却和重试排除集合开始 + selection.excluded_accounts.clone_from(&excluded); + let selected = ctx + .select_account( + &self.kind, + Some(model.as_str()), + &accounts, + &mut selection, + AccountScheduleOwnership { + bound_account: affinity + .as_ref() + .and_then(ProviderSessionAffinityState::bound_account), + pinned_account: ctx.required_account(), + ..Default::default() + }, + ) + .await; + let choice = match selected { + Ok(Some(selected)) => { + if !selected.is_policy_choice() + && ctx.required_account().is_none() + && affinity + .as_ref() + .and_then(|affinity| { + affinity.wait_account( + &accounts, + &selection, + queue.max_waiting > 0, + ) + }) + .is_some_and(|bound| bound != selected.candidate().account.id()) + { + break; + } + selected + } + Ok(None) => break, + Err(AccountPolicyError::StaleCandidate) => continue 'refresh, + Err(AccountPolicyError::Filtered) => { + return Err(unsent(Kind::RequestPolicyDenied) + .with_diagnostic( + ProviderDiagnostic::new(AccountPolicyError::Filtered.to_string()) + .with_classification( + "account_selection", + "account_policy_filtered", + ), + ) + .into()); + } + Err(AccountPolicyError::Rejected) => { + return Err(unsent(Kind::RequestPolicyDenied).into()); + } + Err(AccountPolicyError::Fault) => { + return Err(unsent(Kind::ProviderInfrastructureUnavailable).into()); + } + }; + let candidate = choice.candidate(); + let account = &candidate.account; + let acquire = ProviderSchedulingLeaseRequest::new( + self.kind.clone(), + account.id().clone(), + account.revision(), + selection.concurrency_limit(candidate), + ctx.deadline(), + ) + .with_metadata(ctx.lease_metadata()) + .with_cancellation(ctx.cancellation().clone()); + match self + .leases + .try_acquire(ProviderLeaseRequest::Scheduling(acquire)) + .await + .map_err(super::unavailable)? + { + ProviderLeaseAcquisition::Acquired(lease) => { + let (_, project) = projects + .remove(account.id()) + .ok_or_else(|| unsent(Kind::NoEligibleAccount))?; + let capacity = AccountSelector + .capacity_snapshot(&accounts, &selection) + .map(AccountCapacitySnapshot::with_acquired_request); + // 在认领迁移前保留原绑定事实,临时分流也按实际出站账号判断 + let account_switch = affinity + .as_ref() + .and_then(ProviderSessionAffinityState::bound_account) + .is_some_and(|bound| bound != account.id()) + || ctx + .account_state_owner() + .is_some_and(|owner| !owner.matches(&self.kind, account.id())); + let selected = self + .load_selected(account, project, lease, capacity, account_switch, ctx) + .await?; + let claim = affinity.as_ref().map(|affinity| { + affinity.claim( + account.id(), + binding_eligible, + ctx.required_account().is_some(), + ) + }); + // 保留主绑定的临时分流、亲和命中和插件显式选号均不占轮询位置 + let admission = match assignment_cursor { + Some(cursor) + if !choice.is_policy_choice() + && choice.preferred() != PreferredAccountSelection::Hit + && claim.is_none_or(|claim| claim.account == account.id()) => + { + Some(ProviderAccountAdmission::RoundRobin { + client_key: ctx.client_api_key_ref(), + cursor, + session: claim, + }) + } + _ => claim.map(ProviderAccountAdmission::Session), + }; + if let Some(admission) = admission + && !self + .session_affinity + .admit_account(&self.kind, admission) + .await + .map_err(super::unavailable)? + { + selected.lease.release().await.map_err(super::unavailable)?; + tokio::task::yield_now().await; + continue 'refresh; + } + return Ok(selected); + } + ProviderLeaseAcquisition::Busy { retry_after: delay } => { + if let Some(delay) = delay { + retry_after = + Some(retry_after.map_or(delay, |current| current.min(delay))); + } + selection.busy_accounts.insert(account.id().clone()); + } + } + } + let mut keys = AccountSelector.wait_candidates(&accounts, &selection); + if ctx.required_account().is_none() + && let Some(bound) = affinity.as_ref().and_then(|affinity| { + affinity.wait_account(&accounts, &selection, queue.max_waiting > 0) + }) + { + keys.retain(|account| account == bound); + } + if keys.is_empty() { + return Err(unsent(Kind::NoEligibleAccount).into()); + } + if queue.max_waiting == 0 || ctx.is_diagnostic_required_account() { + let mut error = unsent(Kind::AccountCapacityUnavailable); + if let Some(delay) = retry_after { + error = error.with_retry_after(delay); + } + return Err(error.into()); + } + tokio::select! { + biased; + () = ctx.cancellation().cancelled() => return Err(unsent(Kind::Cancelled).into()), + result = AccountSelector.wait_for_capacity(&mut waiting, &keys, &accounts, &selection) => result?, + } + } + } + + async fn load_selected( + &self, + account: &ProviderAccount, + project: Project, + lease: Box, + capacity: Option, + account_switch: bool, + ctx: &AttemptContext, + ) -> Result { + let current = self + .credentials + .current(account.id()) + .await + .map_err(super::unavailable)?; + if current.account.revision() != account.revision() + || ctx.excludes_proxy(current.account.outbound_proxy()) + { + return Err(unsent(Kind::NoEligibleAccount)); + } + let material = self.credentials.material(¤t)?; + Ok(SelectedAccount { + account: current.account, + capacity, + material, + project, + lease, + account_switch, + }) + } +} diff --git a/backend/crates/providers/antigravity/src/provider/translation.rs b/backend/crates/providers/antigravity/src/provider/translation.rs new file mode 100644 index 000000000..720fb15c0 --- /dev/null +++ b/backend/crates/providers/antigravity/src/provider/translation.rs @@ -0,0 +1,213 @@ +//! 跨协议请求使用共享转换器,原生响应转换在 Core 中间件阶段之间执行 + +use crate::transport::{sent, unsent}; +use gateway_core::{ + engine::provider::NativeResponseTranslator, + error::{ProviderError, ProviderErrorKind}, + event::ProtocolWireEvent, + operation::Operation, +}; +use gateway_protocol::{ + anthropic::{ + ANTHROPIC_PROTOCOL, MessagesModelCapabilities, MessagesToResponsesStream, + responses_to_messages_request, + }, + genai::{GENAI_PROTOCOL, GenAiToMessagesStream, messages_to_genai_request}, + openai::OPENAI_PROTOCOL, +}; +use serde_json::{Value, json}; +use std::borrow::Cow; + +pub(super) fn prepare( + operation: Operation, +) -> Result<(Operation, Option), ProviderError> { + if matches!(operation, Operation::CountTokens(_)) { + return prepare_count(operation); + } + let Operation::Generate(generate) = &operation else { + return Err(unsent(ProviderErrorKind::Unsupported)); + }; + let payload = generate.protocol_payload(); + let source = payload.protocol(); + if source == GENAI_PROTOCOL { + return Ok((operation, None)); + } + if !matches!(source, OPENAI_PROTOCOL | ANTHROPIC_PROTOCOL) { + return Err(unsent(ProviderErrorKind::Unsupported)); + } + let original = payload.body(); + if original + .get("previous_response_id") + .is_some_and(|v| !v.is_null()) + { + return Err(unsent(ProviderErrorKind::InvalidRequest)); + } + let responses = if source == OPENAI_PROTOCOL { + Some(MessagesToResponsesStream::new(original)) + } else { + None + }; + let mut messages = if source == OPENAI_PROTOCOL { + Cow::Owned( + responses_to_messages_request(original, &MessagesModelCapabilities::default()) + .map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?, + ) + } else { + Cow::Borrowed(original) + }; + // Messages 的必填输出上限不能成为 GenAI 的隐式默认值 + if source == OPENAI_PROTOCOL && !original.contains_key("max_output_tokens") { + messages.to_mut().remove("max_tokens"); + } + let model = original + .get("model") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(); + let body = messages_to_genai_request(&messages) + .map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?; + let mut context = payload.context().clone(); + // 转换路径统一请求 SSE,JSON 客户端沿已有交付层聚合 + context.insert("stream".into(), json!(true)); + let bytes = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?; + let operation = operation + .replace_protocol_wire(None, context) + .and_then(|operation| operation.translate_protocol_wire(GENAI_PROTOCOL, bytes.into())) + .map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?; + Ok(( + operation, + Some(Translator::Generate(Box::new(GenerationTranslator { + genai: GenAiToMessagesStream::new(model), + responses, + }))), + )) +} + +pub(super) enum Translator { + Generate(Box), + Count(&'static str), +} + +pub(super) struct GenerationTranslator { + genai: GenAiToMessagesStream, + responses: Option, +} + +impl GenerationTranslator { + fn target_protocol(&self) -> &'static str { + if self.responses.is_some() { + OPENAI_PROTOCOL + } else { + ANTHROPIC_PROTOCOL + } + } + + fn events(&mut self, events: Vec) -> Result, ProviderError> { + let mut wire = Vec::new(); + for event in events { + let events = if let Some(responses) = &mut self.responses { + responses + .push(&event) + .map_err(|e| sent(ProviderErrorKind::Protocol).with_source(e))? + } else { + vec![event] + }; + for event in events { + wire.push( + ProtocolWireEvent::json( + self.target_protocol(), + event["type"].as_str().map(str::to_owned), + event, + ) + .map_err(|_| sent(ProviderErrorKind::Protocol))?, + ); + } + } + Ok(wire) + } +} + +impl NativeResponseTranslator for Translator { + fn source_protocol(&self) -> &str { + GENAI_PROTOCOL + } + fn target_protocol(&self) -> &str { + match self { + Self::Generate(translator) => translator.target_protocol(), + Self::Count(protocol) => protocol, + } + } + fn translate( + &mut self, + event: &ProtocolWireEvent, + ) -> Result, ProviderError> { + let Self::Generate(translator) = self else { + let value = match event.raw_json_body() { + Some(raw) => Cow::Owned( + serde_json::from_slice(raw).map_err(|_| sent(ProviderErrorKind::Protocol))?, + ), + None => Cow::Borrowed(event.data()), + }; + let body = if self.target_protocol() == ANTHROPIC_PROTOCOL { + gateway_protocol::genai::count_tokens_to_messages(&value) + .map_err(|e| sent(ProviderErrorKind::Protocol).with_source(e))? + } else { + value.into_owned() + }; + return Ok(vec![ + ProtocolWireEvent::json(self.target_protocol(), None, body) + .map_err(|_| sent(ProviderErrorKind::Protocol))?, + ]); + }; + let events = translator + .genai + .push(event.data()) + .map_err(|e| sent(ProviderErrorKind::Protocol).with_source(e))?; + translator.events(events) + } + fn finish(&mut self) -> Result, ProviderError> { + let Self::Generate(translator) = self else { + return Ok(Vec::new()); + }; + let events = translator + .genai + .finish() + .map_err(|e| sent(ProviderErrorKind::Protocol).with_source(e))?; + translator.events(events) + } +} + +fn prepare_count(operation: Operation) -> Result<(Operation, Option), ProviderError> { + let Operation::CountTokens(request) = &operation else { + return Err(unsent(ProviderErrorKind::Unsupported)); + }; + let source = request.payload().protocol(); + let body: serde_json::Map = serde_json::from_slice(request.payload().body()) + .map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?; + let body = match source { + ANTHROPIC_PROTOCOL => { + gateway_protocol::anthropic::validate_count_request(&body) + .map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?; + messages_to_genai_request(&body).map(Cow::Owned) + } + GENAI_PROTOCOL | "token-count" => { + gateway_protocol::genai::count_tokens_request(&body).map(Cow::Borrowed) + } + _ => return Err(unsent(ProviderErrorKind::Unsupported)), + } + .map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?; + let translator = match source { + ANTHROPIC_PROTOCOL => Some(Translator::Count(ANTHROPIC_PROTOCOL)), + "token-count" => Some(Translator::Count("token-count")), + _ => None, + }; + let bytes = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?; + let operation = if source == GENAI_PROTOCOL { + let context = request.payload().context().clone(); + operation.replace_protocol_wire(Some(bytes.into()), context) + } else { + operation.translate_protocol_wire(GENAI_PROTOCOL, bytes.into()) + } + .map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?; + Ok((operation, translator)) +} diff --git a/backend/crates/providers/antigravity/src/provider/workers.rs b/backend/crates/providers/antigravity/src/provider/workers.rs new file mode 100644 index 000000000..2af3ad712 --- /dev/null +++ b/backend/crates/providers/antigravity/src/provider/workers.rs @@ -0,0 +1,149 @@ +//! 一次性装配凭据续期、目录修复与本地发布资料检查任务 + +use crate::credential::catalog::{CatalogService, CatalogTask}; +use crate::{ + credential::CredentialService, + profile::{ReleaseService, ReleaseTask}, +}; +use futures::{StreamExt, future::BoxFuture, stream}; +use gateway_admin::ports::provider::ProviderAdminErrorKind as Kind; +use gateway_core::task::{ScheduledTask, WorkerCycleContext, WorkerTaskError}; +use gateway_core::task::{ + WorkerContribution, WorkerDefinitionError, WorkerId, WorkerKind, WorkerLeaseRequest, + WorkerRegistration, WorkerRunnable, WorkerSchedule, +}; +use std::{sync::Arc, time::Duration}; + +pub(crate) fn contributions( + credentials: Arc, + catalog: Arc, + release: Arc, + quota: Arc, +) -> Result, WorkerDefinitionError> { + let refresh_id = WorkerId::try_new(WorkerKind::OAuthRefresh, "antigravity")?; + let ttl = Duration::from_secs(900); + let refresh = WorkerRegistration::try_new( + refresh_id.clone(), + WorkerRunnable::Scheduled { + schedule: WorkerSchedule::try_new( + Duration::from_secs(30), + Duration::from_secs(1), + Duration::from_secs(60), + ttl, + Duration::from_secs(300), + )?, + lease: Some(WorkerLeaseRequest::try_new(refresh_id, ttl)?), + task: Box::new(RefreshTask { + credentials, + catalog: catalog.clone(), + }), + }, + )?; + // 发布资料由各实例本地冻结,不共享账号级租约 + let release = WorkerRegistration::try_new( + WorkerId::try_new( + WorkerKind::QuotaCatalogHealth, + "antigravity-client-releases", + )?, + WorkerRunnable::Scheduled { + schedule: WorkerSchedule::try_new( + Duration::from_secs(60), + Duration::from_secs(5), + Duration::from_secs(300), + ttl, + Duration::from_secs(300), + )?, + lease: None, + task: Box::new(ReleaseTask(release)), + }, + )?; + // 每个实例也读取共享目录的观测变化,更新本地代次;目录请求不占 OAuth 刷新租约 + let catalog = WorkerRegistration::try_new( + WorkerId::try_new(WorkerKind::QuotaCatalogHealth, "antigravity-model-catalog")?, + WorkerRunnable::Scheduled { + schedule: WorkerSchedule::try_new( + Duration::from_secs(30), + Duration::from_secs(2), + Duration::from_secs(60), + ttl, + Duration::from_secs(300), + )?, + lease: None, + task: Box::new(CatalogTask(catalog)), + }, + )?; + let quota_id = WorkerId::try_new(WorkerKind::QuotaCatalogHealth, "antigravity-quota")?; + let quota = WorkerRegistration::try_new( + quota_id.clone(), + WorkerRunnable::Scheduled { + schedule: WorkerSchedule::try_new( + Duration::from_secs(30), + Duration::from_secs(3), + Duration::from_secs(60), + ttl, + Duration::from_secs(300), + )?, + lease: Some(WorkerLeaseRequest::try_new(quota_id, ttl)?), + task: Box::new(crate::credential::quota::QuotaTask(quota)), + }, + )?; + Ok(vec![ + WorkerContribution::Registration(quota), + WorkerContribution::Registration(refresh), + WorkerContribution::Registration(catalog), + WorkerContribution::Registration(release), + ]) +} + +struct RefreshTask { + credentials: Arc, + catalog: Arc, +} + +impl ScheduledTask for RefreshTask { + fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> { + Box::pin(async move { + let (candidates, concurrency) = self.credentials.refresh_candidates().await?; + if candidates.is_empty() || context.cancellation().is_cancelled() { + return Ok(()); + } + let mut catalogs = self + .catalog + .capture_refresh_catalogs(&candidates) + .await + .unwrap_or_else(|_| { + tracing::warn!("Antigravity 目录读取失败,凭据续期后重新查询目录"); + Default::default() + }); + let mut updates = stream::iter(candidates) + .map(|loaded| { + let cancellation = context.cancellation(); + let catalog = catalogs.remove(loaded.account.id()); + async move { + if cancellation.is_cancelled() { + return Ok(()); + } + let revision = self.credentials.refresh_due(&loaded).await?; + self.catalog + .after_credential_refresh(loaded.account.id(), revision, catalog) + .await + } + }) + .buffer_unordered(concurrency); + // 取消时停止发起新请求,已交换的 refresh token 仍要等 CAS 完成 + let mut first_error = None; + while let Some(result) = updates.next().await { + if let Err(e) = result + && !matches!(e.kind(), Kind::Conflict | Kind::CredentialRefreshRequired) + { + first_error.get_or_insert(e); + } + } + if let Some(error) = first_error { + Err(WorkerTaskError::safe("部分 Antigravity 账号续期失败").with_source(error)) + } else { + Ok(()) + } + }) + } +} diff --git a/backend/crates/providers/antigravity/src/transport/account.rs b/backend/crates/providers/antigravity/src/transport/account.rs new file mode 100644 index 000000000..44bbaa55e --- /dev/null +++ b/backend/crates/providers/antigravity/src/transport/account.rs @@ -0,0 +1,81 @@ +//! Cloud Code 账号套餐、分组额度与模型额度的原生合同 + +use super::{CloudCodeClient, client::control, failure::sent}; +use gateway_core::error::{ProviderError, ProviderErrorKind}; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct AccountInfo { + #[serde(rename = "cloudaicompanionProject")] + pub(crate) project: String, + pub(crate) paid_tier: Option, + pub(crate) current_tier: Option, +} + +#[derive(Clone, Serialize, Deserialize)] +pub(crate) struct Tier { + pub(crate) id: String, + #[serde(default)] + pub(crate) name: String, +} + +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct ModelQuota { + pub(crate) remaining_fraction: Option, + pub(crate) reset_time: Option>, +} + +#[derive(Clone, Serialize, Deserialize)] +pub(crate) struct QuotaSummary { + pub(crate) groups: Vec, +} + +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct QuotaGroup { + pub(crate) display_name: String, + pub(crate) buckets: Vec, +} + +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct QuotaBucket { + pub(crate) bucket_id: String, + pub(crate) display_name: String, + pub(crate) window: String, + #[serde(flatten)] + pub(crate) quota: ModelQuota, +} + +impl CloudCodeClient { + pub(crate) async fn account_info(&self, token: &str) -> Result { + let info: AccountInfo = control( + self.post("loadCodeAssist", token) + .json(&json!({"metadata":{}})), + token, + ) + .await?; + let project = &info.project; + if project.trim().is_empty() || project.len() > 255 || project.chars().any(char::is_control) + { + return Err(sent(ProviderErrorKind::Protocol)); + } + Ok(info) + } + + pub(crate) async fn quota_summary( + &self, + token: &str, + project: &str, + ) -> Result { + control( + self.post("retrieveUserQuotaSummary", token) + .json(&json!({"project":project})), + token, + ) + .await + } +} diff --git a/backend/crates/providers/antigravity/src/transport/client.rs b/backend/crates/providers/antigravity/src/transport/client.rs new file mode 100644 index 000000000..19be52eab --- /dev/null +++ b/backend/crates/providers/antigravity/src/transport/client.rs @@ -0,0 +1,285 @@ +//! 已注册资源服务的项目发现、模型查询和原生 HTTP 请求 + +use bytes::Bytes; +use gateway_core::{ + account::OutboundProxy, + error::{ProviderError, ProviderErrorKind as Kind}, +}; +use reqwest::{Client, Response}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use serde_json::{json, value::RawValue}; +use std::{collections::BTreeMap, time::Duration}; +use url::Url; + +use super::failure::{network, sent, successful, unsent}; +use crate::profile::ClientProfile; +use gateway_core::engine::middleware::MiddlewareHeader; +const MAX_CONTROL_RESPONSE_BYTES: usize = 8 * 1024 * 1024; + +#[derive(Serialize, Deserialize)] +pub(crate) struct Catalog { + pub(crate) project: String, + pub(crate) models: BTreeMap, +} + +#[derive(Serialize, Deserialize)] +pub(crate) struct Model { + #[serde(rename = "displayName", default)] + pub(crate) name: String, + #[serde(rename = "quotaInfo", default)] + pub(crate) quota: Option, +} + +pub(crate) struct CloudCodeClient { + client: Client, + origin: Url, + system_instruction: Box, +} + +impl CloudCodeClient { + pub(crate) fn new( + origin: &Url, + proxy: Option<&OutboundProxy>, + profile: &ClientProfile, + ) -> Result { + Self::with_client(origin, Self::build_client(proxy, profile)?, profile) + } + + pub(super) fn build_client( + proxy: Option<&OutboundProxy>, + profile: &ClientProfile, + ) -> Result { + gateway_egress::http_client(proxy) + .map_err(|e| unsent(Kind::ProviderInfrastructureUnavailable).with_source(e))? + // 官方 AGY 使用 HTTP/1.1;显式选择 TLS 后端,避免工作区 feature 合并切到系统 TLS + .use_rustls_tls() + .http1_only() + .http1_title_case_headers() + .redirect(reqwest::redirect::Policy::none()) + .retry(reqwest::retry::never()) + .user_agent(profile.user_agent()) + .build() + .map_err(|e| { + unsent(Kind::ProviderInfrastructureUnavailable).with_source(e.without_url()) + }) + } + + pub(super) fn with_client( + origin: &Url, + client: Client, + profile: &ClientProfile, + ) -> Result { + Ok(Self { + client, + origin: origin.clone(), + system_instruction: RawValue::from_string( + json!({"parts":[{"text":profile.system_prompt}]}).to_string(), + ) + .map_err(|e| unsent(Kind::ProviderInfrastructureUnavailable).with_source(e))?, + }) + } + + pub(super) fn post(&self, action: &str, token: &str) -> reqwest::RequestBuilder { + let mut url = self.origin.clone(); + url.set_path(&format!("/v1internal:{action}")); + self.client + .post(url) + .bearer_auth(token) + .header(reqwest::header::ACCEPT_ENCODING, "gzip") + } + + pub(crate) async fn catalog(&self, token: &str) -> Result { + let project = self.account_info(token).await?.project; + self.catalog_for_project(token, project).await + } + + pub(crate) async fn catalog_for_project( + &self, + token: &str, + project: String, + ) -> Result { + #[derive(Deserialize)] + struct Models { + models: BTreeMap, + } + let models: Models = control( + self.post("fetchAvailableModels", token) + .json(&json!({"project":project})), + token, + ) + .await?; + if models + .models + .keys() + .any(|id| gateway_core::routing::UpstreamModelId::new(id).is_err()) + { + return Err(sent(Kind::Protocol)); + } + Ok(Catalog { + project, + models: models.models, + }) + } + + pub(crate) async fn generate( + &self, + project: &str, + model: &str, + token: &str, + body: &[u8], + stream: bool, + headers: &[MiddlewareHeader], + ) -> Result { + #[derive(Serialize)] + struct Envelope<'a> { + project: &'a str, + model: &'a str, + request: BTreeMap, + } + let request = self.request_body(body)?; + let (send, media) = if stream { + ( + self.post("streamGenerateContent", token) + .query(&[("alt", "sse")]), + "text/event-stream", + ) + } else { + (self.post("generateContent", token), "application/json") + }; + self.send( + send.json(&Envelope { + project, + model, + request, + }), + token, + headers, + media, + ) + .await + } + + pub(crate) async fn count_tokens( + &self, + token: &str, + body: &[u8], + headers: &[MiddlewareHeader], + ) -> Result { + let mut request = self.request_body(body)?; + // Desktop 的计数封套只接受 Vertex CountTokensRequest,没有项目和生成控制字段 + for field in [ + "model", + "safetySettings", + "safety_settings", + "toolConfig", + "tool_config", + "labels", + "sessionId", + "session_id", + ] { + request.remove(field); + } + self.send( + self.post("countTokens", token) + .json(&json!({"request":request})), + token, + headers, + "application/json", + ) + .await + } + + fn request_body<'a>( + &'a self, + body: &'a [u8], + ) -> Result, ProviderError> { + let mut request: BTreeMap = serde_json::from_slice(body) + .map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?; + // 生成和计数共享同一身份策略,其他字段保留原始 JSON 表达 + request.remove("system_instruction"); + request.insert("systemInstruction".to_owned(), &self.system_instruction); + Ok(request) + } + + async fn send( + &self, + mut send: reqwest::RequestBuilder, + token: &str, + headers: &[MiddlewareHeader], + media: &str, + ) -> Result { + for header in headers { + if super::headers::managed_header(header.name()) { + continue; + } + let name = reqwest::header::HeaderName::from_bytes(header.name().as_bytes()) + .map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?; + let value = reqwest::header::HeaderValue::from_bytes(header.value()) + .map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?; + send = send.header(name, value); + } + let response = send.send().await.map_err(network)?; + let response = successful(super::response::decode(response), token).await?; + if !response + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.split(';').next()) + .is_some_and(|v| v.trim().eq_ignore_ascii_case(media)) + { + return Err(sent(Kind::Protocol)); + } + Ok(response) + } +} + +pub(super) async fn control( + request: reqwest::RequestBuilder, + token: &str, +) -> Result { + let mut response = successful( + super::response::decode( + request + .timeout(Duration::from_secs(15)) + .send() + .await + .map_err(network)?, + ), + token, + ) + .await?; + let mut data = Vec::new(); + while let Some(chunk) = response + .chunk() + .await + .map_err(|e| sent(Kind::Transport).with_source(e.without_url()))? + { + if data.len().saturating_add(chunk.len()) > MAX_CONTROL_RESPONSE_BYTES { + return Err(sent(Kind::MessageTooBig)); + } + data.extend_from_slice(&chunk); + } + serde_json::from_slice(&data).map_err(|e| sent(Kind::Protocol).with_source(e)) +} + +#[derive(Deserialize)] +struct Reply<'a> { + #[serde(borrow)] + response: Option<&'a RawValue>, + #[serde(borrow)] + error: Option<&'a RawValue>, +} + +pub(crate) fn unwrap_frame(data: &str) -> Result { + let envelope: Reply = + serde_json::from_str(data).map_err(|e| sent(Kind::Protocol).with_source(e))?; + match (envelope.response, envelope.error) { + (None, Some(err)) if err.get().starts_with('{') => { + Ok(Bytes::copy_from_slice(data.as_bytes())) + } + (Some(body), None) if body.get().starts_with('{') => { + Ok(Bytes::copy_from_slice(body.get().as_bytes())) + } + _ => Err(sent(Kind::Protocol)), + } +} diff --git a/backend/crates/providers/antigravity/src/transport/count.rs b/backend/crates/providers/antigravity/src/transport/count.rs new file mode 100644 index 000000000..2486c8718 --- /dev/null +++ b/backend/crates/providers/antigravity/src/transport/count.rs @@ -0,0 +1,57 @@ +//! 原生计数响应保留独立 wire,不产生生成用量或费用 + +use super::{ResponseContext, sent}; +use futures::Stream; +use gateway_core::{ + error::{ProviderError, ProviderErrorKind as Kind}, + event::{ + FinishReason, GatewayEvent, ProtocolWireEvent, ProviderEvent, ProviderResponseObservation, + ProviderResponseTimings, ResponseMeta, + }, + upstream::UpstreamTransport, +}; +use gateway_protocol::{genai::GENAI_PROTOCOL, openai::sse::MAX_SSE_EVENT_BUFFER_BYTES}; +use serde_json::Value; + +pub(crate) fn count_events( + mut response: reqwest::Response, + context: ResponseContext, +) -> impl Stream> + Send + 'static { + let headers_ms = u64::try_from(context.started_at.elapsed().as_millis()).unwrap_or(u64::MAX); + async_stream::try_stream! { + let status = response.status().as_u16(); + let mut body = Vec::new(); + loop { + let chunk = tokio::select! { + biased; + _ = context.cancel.cancelled() => Err(sent(Kind::Cancelled)), + _ = context.deadline.wait() => Err(sent(Kind::Timeout)), + result = response.chunk() => result.map_err(|e| sent(Kind::Transport).with_source(e.without_url())), + }?; + let Some(chunk) = chunk else { break; }; + if body.len().saturating_add(chunk.len()) > MAX_SSE_EVENT_BUFFER_BYTES { + Err(sent(Kind::MessageTooBig))?; + } + body.extend_from_slice(&chunk); + } + let value: Value = serde_json::from_slice(&body).map_err(|_| sent(Kind::Protocol))?; + // Cloud Code 的 protobuf JSON 会省略零值;公开计数接口显式交付 totalTokens + if value.as_object().is_some_and(serde_json::Map::is_empty) { + body = br#"{"totalTokens":0}"#.to_vec(); + } else if value.get("totalTokens").and_then(Value::as_u64).is_none() { + Err(sent(Kind::Protocol))?; + } + let observation = ProviderResponseObservation::new( + UpstreamTransport::new("http").map_err(|_| sent(Kind::ProviderInfrastructureUnavailable))?, + ).with_status_code(status).with_timings(ProviderResponseTimings { + headers_ms: Some(headers_ms), ..Default::default() + }); + let meta = ResponseMeta::new(uuid::Uuid::now_v7().to_string(), context.model.as_str()); + let wire = ProtocolWireEvent::raw_json(GENAI_PROTOCOL, body.into()).map_err(|_| sent(Kind::Protocol))?; + let mut event = ProviderEvent::wire(wire) + .with_fact(GatewayEvent::Started(meta.clone())) + .with_fact(GatewayEvent::Completed(meta.with_finish_reason(FinishReason::Stop))); + event.attach_observation(observation); + yield event; + } +} diff --git a/backend/crates/providers/antigravity/src/transport/failure.rs b/backend/crates/providers/antigravity/src/transport/failure.rs new file mode 100644 index 000000000..2c464304f --- /dev/null +++ b/backend/crates/providers/antigravity/src/transport/failure.rs @@ -0,0 +1,153 @@ +//! 保留上游错误事实与本地来源,敏感凭据不得进入运维正文 + +use gateway_core::{ + error::{ProviderError, ProviderErrorKind as Kind, RawUpstreamError}, + upstream::UpstreamSendState, +}; +use reqwest::{Response, StatusCode}; +use std::time::{Duration, SystemTime}; + +const MAX_ERROR_BYTES: usize = 64 * 1024; +pub(crate) fn unsent(kind: Kind) -> ProviderError { + ProviderError::new(kind, UpstreamSendState::NotSent) +} +pub(crate) fn sent(kind: Kind) -> ProviderError { + ProviderError::new(kind, UpstreamSendState::Sent) +} +pub(super) fn network(error: reqwest::Error) -> ProviderError { + let kind = if error.is_timeout() { + Kind::Timeout + } else { + Kind::Transport + }; + let state = if error.is_connect() { + UpstreamSendState::NotSent + } else { + UpstreamSendState::Ambiguous + }; + ProviderError::new(kind, state).with_source(error.without_url()) +} +fn status_kind(status: StatusCode) -> Kind { + match status { + StatusCode::UNAUTHORIZED => Kind::Unauthorized, + StatusCode::FORBIDDEN => Kind::PermissionDenied, + StatusCode::TOO_MANY_REQUESTS => Kind::RateLimited, + StatusCode::REQUEST_TIMEOUT | StatusCode::GATEWAY_TIMEOUT => Kind::Timeout, + StatusCode::PAYLOAD_TOO_LARGE => Kind::MessageTooBig, + s if s.is_server_error() => Kind::Unavailable, + s if s.is_client_error() => Kind::InvalidRequest, + _ => Kind::Protocol, + } +} +pub(super) fn body_error(status: Option, body: &str, token: &str) -> ProviderError { + let status = status.and_then(|code| StatusCode::from_u16(code).ok()); + let error = sent(status.map_or(Kind::Unavailable, status_kind)); + let error = if let Some(status) = status { + error.with_status(status.as_u16()) + } else { + error + }; + attach_body(error, body, token) +} +fn attach_body(error: ProviderError, body: &str, token: &str) -> ProviderError { + let error = if let Some(delay) = retry_info(body) { + let delay = error + .retry_after() + .map_or(delay, |header| header.max(delay)); + error.with_retry_after(delay) + } else { + error + }; + if !token.is_empty() && body.contains(token) { + return error.redact_sensitive_context(body); + } + if body.is_empty() { + return error; + } + let end = body.floor_char_boundary(MAX_ERROR_BYTES.min(body.len())); + let text = if end < body.len() { + format!("{}\n[truncated]", &body[..end]) + } else { + body.to_owned() + }; + error.with_raw_upstream_error(RawUpstreamError::new(text)) +} + +fn retry_info(body: &str) -> Option { + let document: serde_json::Value = serde_json::from_str(body).ok()?; + let error = document + .get("error") + .or_else(|| document.pointer("/response/error"))?; + let detail = error.get("details")?.as_array()?.iter().find(|detail| { + detail.get("@type").and_then(serde_json::Value::as_str) + == Some("type.googleapis.com/google.rpc.RetryInfo") + })?; + let delay = detail.get("retryDelay")?.as_str()?.strip_suffix('s')?; + let (seconds, fraction) = delay.split_once('.').unwrap_or((delay, "")); + if seconds.is_empty() + || !seconds.bytes().all(|byte| byte.is_ascii_digit()) + || fraction.len() > 9 + || !fraction.bytes().all(|byte| byte.is_ascii_digit()) + { + return None; + } + let nanos = if fraction.is_empty() { + 0 + } else { + fraction + .parse::() + .ok()? + .checked_mul(10_u32.pow(9 - u32::try_from(fraction.len()).ok()?))? + }; + Some(Duration::new(seconds.parse().ok()?, nanos)) +} + +fn retry_after(value: &str) -> Option { + if let Ok(seconds) = value.parse::() { + return Some(Duration::from_secs(seconds)); + } + let until: SystemTime = chrono::DateTime::parse_from_rfc2822(value).ok()?.into(); + Some(until.duration_since(SystemTime::now()).unwrap_or_default()) +} +pub(super) async fn successful( + mut response: Response, + token: &str, +) -> Result { + let status = response.status(); + if status.is_success() { + return Ok(response); + } + let retry_after = response + .headers() + .get(reqwest::header::RETRY_AFTER) + .and_then(|v| v.to_str().ok()) + .and_then(retry_after); + let mut error = sent(status_kind(status)).with_status(status.as_u16()); + if let Some(delay) = retry_after { + error = error.with_retry_after(delay); + } + let mut body = Vec::new(); + let mut truncated = false; + let read = tokio::time::timeout(Duration::from_secs(10), async { + while let Some(chunk) = response.chunk().await? { + let remaining = MAX_ERROR_BYTES.saturating_sub(body.len()); + body.extend_from_slice(&chunk[..chunk.len().min(remaining)]); + if chunk.len() > remaining { + truncated = true; + break; + } + } + Ok::<_, reqwest::Error>(()) + }) + .await; + match read { + Ok(Ok(())) => {} + Ok(Err(source)) => error = error.with_source(source.without_url()), + Err(source) => error = error.with_source(source), + } + let text = String::from_utf8_lossy(&body).into_owned(); + if truncated { + return Err(error.redact_sensitive_context(&text)); + } + Err(attach_body(error, &text, token)) +} diff --git a/backend/crates/providers/antigravity/src/transport/headers.rs b/backend/crates/providers/antigravity/src/transport/headers.rs new file mode 100644 index 000000000..9f20bbd17 --- /dev/null +++ b/backend/crates/providers/antigravity/src/transport/headers.rs @@ -0,0 +1,70 @@ +//! 业务头保留多值字节,账号身份与切号追踪边界只作用于本次出站副本 + +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use gateway_core::{engine::middleware::MiddlewareHeader, operation::Operation}; +use gateway_protocol::openai::is_transport_managed_request_header; +use serde_json::Value; + +pub(crate) fn request_headers( + operation: &Operation, + middleware: Vec, + account_switch: bool, +) -> Vec { + let context = match operation { + Operation::Generate(request) => request.protocol_payload().context(), + Operation::CountTokens(request) => request.payload().context(), + _ => return middleware, + }; + let mut headers = Vec::new(); + if let Some(entries) = context + .get("opaque_request_headers") + .and_then(Value::as_array) + { + for entry in entries { + let Some(pair) = entry.as_array().filter(|pair| pair.len() == 2) else { + continue; + }; + let Some(name) = pair[0].as_str() else { + continue; + }; + let Some(value) = pair[1] + .as_str() + .and_then(|value| STANDARD.decode(value).ok()) + else { + continue; + }; + // 与其他 Provider 一致,忽略损坏的不透明上下文,不改写合法头的原始值 + if http::HeaderName::from_bytes(name.as_bytes()).is_ok() + && http::HeaderValue::from_bytes(&value).is_ok() + { + headers.push(MiddlewareHeader::new(name, value.into())); + } + } + } + headers.extend(middleware); + if account_switch { + headers.retain(|header| { + !matches!( + header.name().to_ascii_lowercase().as_str(), + "traceparent" | "tracestate" | "sentry-trace" | "baggage" + ) + }); + } + headers +} + +pub(super) fn managed_header(name: &str) -> bool { + let name = name.to_ascii_lowercase(); + is_transport_managed_request_header(&name) + || matches!( + name.as_str(), + "authorization" | "cookie" | "cookie2" | "content-type" | "accept" + | "user-agent" | "x-api-key" | "x-goog-api-key" | "x-goog-user-project" + | "x-goog-api-client" + // 跨协议入口的账号身份不能成为 AGY 账号或客户端身份 + | "chatgpt-account-id" | "chatgpt-project-id" | "openai-organization" + | "openai-project" | "x-openai-actor-authorization" | "x-codex-installation-id" + | "x-oai-attestation" | "x-oai-is" | "x-oai-is-update" + | "originator" | "version" + ) +} diff --git a/backend/crates/providers/antigravity/src/transport/mod.rs b/backend/crates/providers/antigravity/src/transport/mod.rs new file mode 100644 index 000000000..6b4226160 --- /dev/null +++ b/backend/crates/providers/antigravity/src/transport/mod.rs @@ -0,0 +1,15 @@ +//! Cloud Code 上游 HTTP、响应解包与错误事实 + +mod client; +mod count; +mod failure; +mod headers; +mod pool; +mod response; +pub(crate) use client::{Catalog, CloudCodeClient, unwrap_frame}; +pub(crate) use count::count_events; +pub(crate) use failure::{sent, unsent}; +pub(crate) use headers::request_headers; +pub(crate) use pool::ClientPool; +pub(crate) use response::{ResponseContext, events}; +pub(crate) mod account; diff --git a/backend/crates/providers/antigravity/src/transport/pool.rs b/backend/crates/providers/antigravity/src/transport/pool.rs new file mode 100644 index 000000000..084397bed --- /dev/null +++ b/backend/crates/providers/antigravity/src/transport/pool.rs @@ -0,0 +1,64 @@ +//! 有界复用账号隔离的 HTTP 客户端;令牌、项目与系统指令仍按本次请求构造 + +use std::{collections::VecDeque, sync::Mutex}; + +use gateway_core::{ + account::{CredentialRevision, OutboundProxy, ProviderAccount, ProviderAccountId}, + error::{ProviderError, ProviderErrorKind}, +}; +use reqwest::Client; +use url::Url; + +use super::{CloudCodeClient, unsent}; +use crate::profile::ClientProfile; + +const MAX_CACHED_CLIENTS: usize = 64; + +#[derive(PartialEq, Eq)] +struct Identity { + account: ProviderAccountId, + revision: CredentialRevision, + proxy: Option, + user_agent: String, +} + +#[derive(Default)] +pub(crate) struct ClientPool { + clients: Mutex>, +} + +impl ClientPool { + pub(crate) fn client( + &self, + origin: &Url, + account: &ProviderAccount, + profile: &ClientProfile, + ) -> Result { + let identity = Identity { + account: account.id().clone(), + revision: account.revision(), + proxy: account.outbound_proxy().cloned(), + user_agent: profile.user_agent(), + }; + let mut clients = self + .clients + .lock() + .map_err(|_| unsent(ProviderErrorKind::ProviderInfrastructureUnavailable))?; + let existing = clients + .iter() + .position(|(key, _)| key == &identity) + .and_then(|index| clients.remove(index)); + let client = if let Some((_, client)) = existing { + client + } else { + CloudCodeClient::build_client(account.outbound_proxy(), profile)? + }; + clients.push_back((identity, client.clone())); + if clients.len() > MAX_CACHED_CLIENTS { + clients.pop_front(); + } + drop(clients); + // 系统提示不缓存,画像只修改提示词时也立即使用本次冻结值 + CloudCodeClient::with_client(origin, client, profile) + } +} diff --git a/backend/crates/providers/antigravity/src/transport/response.rs b/backend/crates/providers/antigravity/src/transport/response.rs new file mode 100644 index 000000000..8e58de03d --- /dev/null +++ b/backend/crates/providers/antigravity/src/transport/response.rs @@ -0,0 +1,255 @@ +//! 去除资源服务响应外层,协议正文与候选完成、用量观测独立处理 + +use crate::transport::{sent, unwrap_frame}; +use bytes::Bytes; +use futures::{Stream, TryStreamExt}; +use gateway_core::{ + error::{ProviderError, ProviderErrorKind as Kind}, + event::{ + ContentItem, ContentKind, FinishReason, GatewayEvent, ProtocolWireEvent, ProviderEvent, + ProviderResponseObservation, ProviderResponseTimings, ResponseMeta, TextDelta, + }, + lifecycle::{CancellationToken, Deadline}, + metering::{ModelPriceOverride, Usage}, + routing::UpstreamModelId, + upstream::UpstreamTransport, +}; +use gateway_protocol::{ + genai::{GENAI_PROTOCOL, GenerateContentObservation, GenerationFinish, primary_text_parts}, + openai::sse::{ + MAX_SSE_EVENT_BUFFER_BYTES, SseEvent, SseEventDecoder, encode_sse_event_with_metadata, + }, +}; +use reqwest::Response; +use serde_json::Value; +use std::time::Instant; + +/// 仅 AGY 声明 gzip,解压后的字节继续受各消费方的大小限制和取消约束 +pub(super) fn decode(response: Response) -> Response { + use http_body_util::BodyExt; + if response + .headers() + .get(reqwest::header::CONTENT_ENCODING) + .is_none_or(|value| value != "gzip") + { + return response; + } + // 不启用 reqwest 全局 gzip feature,避免 Cargo 特性合并改变其他 Provider 的请求画像 + let response: http::Response = response.into(); + let (mut parts, body) = response.into_parts(); + parts.headers.remove(reqwest::header::CONTENT_ENCODING); + parts.headers.remove(reqwest::header::CONTENT_LENGTH); + let stream = body.into_data_stream().map_err(std::io::Error::other); + let reader = tokio_util::io::StreamReader::new(stream); + let mut decoder = async_compression::tokio::bufread::GzipDecoder::new(reader); + decoder.multiple_members(true); + let body = reqwest::Body::wrap_stream(tokio_util::io::ReaderStream::new(decoder)); + http::Response::from_parts(parts, body).into() +} + +pub(crate) struct ResponseContext { + pub(crate) stream: bool, + pub(crate) model: UpstreamModelId, + pub(crate) deadline: Deadline, + pub(crate) cancel: CancellationToken, + pub(crate) token: String, + pub(crate) pricing: Option, + pub(crate) started_at: Instant, +} + +pub(crate) fn events( + mut response: Response, + context: ResponseContext, +) -> impl Stream> + Send + 'static { + let ResponseContext { + stream, + model, + deadline, + cancel, + token, + pricing, + started_at, + } = context; + let headers_ms = elapsed_ms(started_at); + async_stream::try_stream! { + let mut timings = ProviderResponseTimings { headers_ms: Some(headers_ms), ..Default::default() }; + let observation = ProviderResponseObservation::new( + UpstreamTransport::new("http").map_err(|_| sent(Kind::ProviderInfrastructureUnavailable))?, + ).with_status_code(response.status().as_u16()); + let mut decoder = SseEventDecoder::default(); + let mut json_body = Vec::new(); + let mut observed = GenerateContentObservation::default(); + let mut started = None; + let mut text_started = false; + let mut calculated_cost = None; + let mut priceable = pricing.is_some(); + loop { + let chunk = tokio::select! { + biased; + _ = cancel.cancelled() => Err(sent(Kind::Cancelled)), + _ = deadline.wait() => Err(sent(Kind::Timeout)), + result = response.chunk() => result.map_err(|e| sent(Kind::Transport).with_source(e.without_url())), + }?; + let eof = chunk.is_none(); + let frames = if stream { + match chunk { + Some(bytes) => decoder.push(&bytes), + None => decoder.finish(), + }.map_err(|_| sent(Kind::Protocol))? + } else if let Some(bytes) = chunk { + if json_body.len().saturating_add(bytes.len()) > MAX_SSE_EVENT_BUFFER_BYTES { + Err(sent(Kind::MessageTooBig))?; + } + json_body.extend_from_slice(&bytes); + Vec::new() + } else { + let data = String::from_utf8(std::mem::take(&mut json_body)) + .map_err(|_| sent(Kind::Protocol))?; + vec![SseEvent { event: None, data, id: None, retry: None }] + }; + for frame in frames { + let inner = unwrap_frame(&frame.data)?; + let value: Value = serde_json::from_slice(&inner).map_err(|_| sent(Kind::Protocol))?; + if value.get("error").is_some_and(Value::is_object) { + let status=value.get("error").and_then(|e|e.get("code")).and_then(Value::as_u64).and_then(|code|u16::try_from(code).ok()); + Err(super::failure::body_error(status,&frame.data,&token))?; + } + priceable &= crate::billing::supports_pricing(&value); + if !priceable { calculated_cost = None; } + let first_frame = started.is_none(); + let meta = started.get_or_insert_with(|| { + let id = value.get("responseId").and_then(Value::as_str) + .map_or_else(|| uuid::Uuid::now_v7().to_string(), str::to_owned); + let model = value.get("modelVersion").and_then(Value::as_str).unwrap_or(model.as_str()); + ResponseMeta::new(id, model) + }); + let usage = observed.observe(&value).map(usage); + let text = primary_text_parts(&value).collect::(); + let previous_timings = timings; + observe_timings(&mut timings, &value, elapsed_ms(started_at)); + let wire = if stream { + let data = std::str::from_utf8(&inner).map_err(|_| sent(Kind::Protocol))?; + let raw = encode_sse_event_with_metadata( + frame.event.as_deref().unwrap_or(""), data, frame.id.as_deref(), frame.retry, + ); + ProtocolWireEvent::json_with_raw_sse_metadata( + GENAI_PROTOCOL, frame.event, value, Bytes::from(raw), frame.id, frame.retry, + ) + } else { + ProtocolWireEvent::raw_json(GENAI_PROTOCOL, inner) + }.map_err(|_| sent(Kind::Protocol))?; + let mut event = ProviderEvent::wire(wire); + if timings != previous_timings { + event.attach_observation(observation.clone().with_timings(timings)); + } + // 首批必须含可交付的协议帧,开始事实随首帧一起提交 + if first_frame { + event = event.with_fact(GatewayEvent::Started(meta.clone())); + } + // 探测与首输出观测使用通用文本事实,协议正文仍由原生帧完整交付 + if !text.is_empty() { + if !text_started { + event = event.with_fact(GatewayEvent::ContentAdded(ContentItem::new( + 0, ContentKind::Text, + ))); + text_started = true; + } + event = event.with_fact(GatewayEvent::TextDelta(TextDelta { + content_index: 0, + text, + })); + } + if let Some(usage) = usage { + calculated_cost = if priceable { crate::billing::calculate(model.as_str(), &usage, pricing.as_ref()) } else { None }; + event = event.with_fact(GatewayEvent::Usage(usage)); + } + yield event; + } + if eof { + break; + } + } + let ending = observed.finish().ok_or_else(|| sent(Kind::Protocol))?; + let meta = started.ok_or_else(|| sent(Kind::Protocol))?; + if let Some(breakdown) = calculated_cost { + yield ProviderEvent::canonical(GatewayEvent::CalculatedCost(breakdown.calculated_cost())); + } + yield ProviderEvent::canonical(GatewayEvent::Completed(meta.with_finish_reason(finish_reason(ending)))); + } +} + +fn elapsed_ms(started_at: Instant) -> u64 { + u64::try_from(started_at.elapsed().as_millis()).unwrap_or(u64::MAX) +} + +fn observe_timings(timings: &mut ProviderResponseTimings, frame: &Value, elapsed: u64) { + timings.first_event_ms.get_or_insert(elapsed); + for part in frame + .get("candidates") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter(|candidate| { + candidate + .get("index") + .and_then(Value::as_u64) + .unwrap_or_default() + == 0 + }) + .filter_map(|candidate| { + candidate + .pointer("/content/parts") + .and_then(Value::as_array) + }) + .flatten() + { + // 空占位、签名及用量帧不算首字,工具调用本身属于可交付输出 + if part + .get("text") + .and_then(Value::as_str) + .is_some_and(|text| !text.is_empty()) + { + let first = if part.get("thought").and_then(Value::as_bool) == Some(true) { + &mut timings.first_reasoning_ms + } else { + &mut timings.first_text_ms + }; + first.get_or_insert(elapsed); + timings.first_token_ms.get_or_insert(elapsed); + } else if part.get("functionCall").is_some_and(Value::is_object) { + timings.first_token_ms.get_or_insert(elapsed); + } + } +} + +fn usage(facts: &gateway_protocol::genai::UsageMetadata) -> Usage { + let mut usage = Usage::new(); + usage.input_tokens = facts.input_tokens(); + usage.cached_input_tokens = facts.cached; + usage.output_tokens = facts.output_tokens(); + usage.reasoning_output_tokens = facts.thoughts; + usage.total_tokens = facts.total; + usage.image_input_tokens = facts.image_input_tokens(); + usage.image_output_tokens = facts.candidate_image; + usage +} + +fn finish_reason(ending: GenerationFinish<'_>) -> FinishReason { + match ending { + GenerationFinish::Blocked => FinishReason::ContentFilter, + GenerationFinish::Candidate { + reason: "MAX_TOKENS", + .. + } => FinishReason::Length, + GenerationFinish::Candidate { + reason: "STOP" | "OTHER", + tool_call: true, + } => FinishReason::ToolCall, + GenerationFinish::Candidate { reason: "STOP", .. } => FinishReason::Stop, + GenerationFinish::Candidate { + reason: "SAFETY" | "BLOCKLIST" | "PROHIBITED_CONTENT" | "SPII" | "RECITATION", + .. + } => FinishReason::ContentFilter, + _ => FinishReason::Other, + } +} diff --git a/backend/crates/providers/antigravity/tests/billing/calculate.rs b/backend/crates/providers/antigravity/tests/billing/calculate.rs new file mode 100644 index 000000000..8deb568bd --- /dev/null +++ b/backend/crates/providers/antigravity/tests/billing/calculate.rs @@ -0,0 +1,219 @@ +//! 人工单价、缓存子集、思考输出及金额精度的计费合同 + +use gateway_core::metering::{ModelPriceOverride, Usage}; +use serde_json::json; + +pub(crate) fn pricing() -> ModelPriceOverride { + serde_json::from_value(json!({ + "multiplierBps": 15000, + "bands": {"standard": { + "input": "2", "output": "8", "cacheRead": "0.5", "cacheWrite": "3" + }} + })) + .unwrap() +} + +#[test] +fn cached_input_and_thinking_output_are_billed_once_with_the_frozen_multiplier() { + let usage = Usage { + input_tokens: Some(100), + output_tokens: Some(40), + cached_input_tokens: Some(20), + cache_write_input_tokens: Some(10), + reasoning_output_tokens: Some(30), + ..Usage::new() + }; + let cost = crate::billing::calculate("unknown-model", &usage, Some(&pricing())).unwrap(); + assert_eq!( + [ + cost.input_amount().amount().canonical(), + cost.output_amount().amount().canonical(), + cost.cache_read_amount().amount().canonical(), + cost.cache_write_amount().amount().canonical(), + cost.standard_amount().amount().canonical(), + cost.total_amount().amount().canonical(), + ], + [ + "0.00021", "0.00048", "0.000015", "0.000045", "0.00075", "0.00075" + ] + ); + assert_eq!(cost.custom_multiplier_bps(), 15000); +} + +#[test] +fn absent_prices_or_usage_do_not_fabricate_free_requests() { + let usage = Usage { + input_tokens: Some(100), + output_tokens: Some(40), + ..Usage::new() + }; + assert!(crate::billing::calculate("unknown-model", &usage, None).is_none()); + let mut multiplier_only = pricing(); + multiplier_only.bands.clear(); + assert!(crate::billing::calculate("unknown-model", &usage, Some(&multiplier_only)).is_none()); + assert!(crate::billing::calculate("unknown-model", &Usage::new(), Some(&pricing())).is_none()); +} + +#[test] +fn invalid_cache_subsets_and_out_of_range_amounts_are_not_billed() { + let usage = Usage { + input_tokens: Some(5), + output_tokens: Some(1), + cached_input_tokens: Some(4), + cache_write_input_tokens: Some(2), + ..Usage::new() + }; + assert!(crate::billing::calculate("unknown-model", &usage, Some(&pricing())).is_none()); + let usage = Usage { + input_tokens: Some(u64::MAX), + output_tokens: Some(u64::MAX), + ..Usage::new() + }; + assert!(crate::billing::calculate("unknown-model", &usage, Some(&pricing())).is_none()); +} + +#[test] +fn explicit_zero_multiplier_remains_an_observed_zero_cost() { + let mut pricing = pricing(); + pricing.multiplier_bps = 0; + let usage = Usage { + input_tokens: Some(1), + output_tokens: Some(1), + ..Usage::new() + }; + let cost = crate::billing::calculate("unknown-model", &usage, Some(&pricing)).unwrap(); + assert_eq!(cost.total_amount().amount().canonical(), "0"); +} + +#[test] +fn builtin_prices_cover_public_models_and_reference_mappings_without_prefix_guessing() { + let defaults = crate::billing::defaults(); + assert_eq!(defaults.len(), 32); + assert_eq!(crate::billing::source_models().len(), defaults.len()); + for (model, price) in defaults { + price.validate().unwrap(); + assert_eq!(price.multiplier_bps, 10_000); + let mut usage = Usage { + input_tokens: Some(1_000_000), + output_tokens: Some(1_000_000), + image_output_tokens: Some(0), + ..Usage::new() + }; + if model == "gemini-2.5-pro" { + usage.input_tokens = Some(100_000); + } + assert!( + crate::billing::calculate(model, &usage, None).is_some(), + "{model}" + ); + } + for model in [ + "tab_flash_lite_preview", + "gemini-4-hydrogen-sonar", + "gemini-4-hydrogen-tiered-high", + "gemini-3.8-flash-tiered", + "claude-opus-5-5-unknown", + "gemini-4-neon-future", + ] { + assert!(!defaults.contains_key(model)); + assert!(!crate::billing::source_models().contains_key(model)); + } + assert_eq!( + crate::billing::source_models()["gemini-3-flash"].model, + "gemini-3-flash-preview" + ); + assert_eq!( + crate::billing::source_models()["gpt-oss-120b-medium"].provider, + "google-vertex" + ); +} + +#[test] +fn builtin_prices_are_used_without_manual_configuration_and_preserve_multiplier_only_overrides() { + let usage = Usage { + input_tokens: Some(100), + output_tokens: Some(40), + cached_input_tokens: Some(20), + reasoning_output_tokens: Some(30), + ..Usage::new() + }; + let cost = crate::billing::calculate("gemini-2.5-flash", &usage, None).unwrap(); + assert_eq!(cost.total_amount().amount().canonical(), "0.0001246"); + let override_price = ModelPriceOverride { + multiplier_bps: 20_000, + bands: Default::default(), + }; + let frozen = + crate::billing::effective_pricing("gemini-2.5-flash", Some(&override_price)).unwrap(); + assert_eq!( + crate::billing::calculate("gemini-2.5-flash", &usage, Some(&frozen)) + .unwrap() + .total_amount() + .amount() + .canonical(), + "0.0002492" + ); +} + +#[test] +fn gemini_pro_switches_all_rates_only_above_200k_input_tokens() { + for (input, long, total) in [(200_000, false, "0.25"), (200_001, true, "0.5000025")] { + let usage = Usage { + input_tokens: Some(input), + output_tokens: Some(0), + ..Usage::new() + }; + let cost = crate::billing::calculate("gemini-2.5-pro", &usage, None).unwrap(); + assert_eq!(cost.long_context_billing_applied(), long); + assert_eq!(cost.total_amount().amount().canonical(), total); + } +} + +#[test] +fn image_output_and_thinking_use_distinct_prices_and_require_modality_counts() { + let mut usage = Usage { + input_tokens: Some(10), + output_tokens: Some(100), + image_output_tokens: Some(80), + reasoning_output_tokens: Some(20), + ..Usage::new() + }; + let cost = crate::billing::calculate("gemini-3.1-flash-image", &usage, None).unwrap(); + assert_eq!(cost.total_amount().amount().canonical(), "0.004865"); + assert_eq!(cost.output_price_per_million().amount().canonical(), "48.6"); + usage.image_output_tokens = None; + assert!(crate::billing::calculate("gemini-3.1-flash-image", &usage, None).is_none()); + usage.image_output_tokens = Some(101); + assert!(crate::billing::calculate("gemini-3.1-flash-image", &usage, None).is_none()); +} + +#[test] +fn custom_image_input_price_respects_image_breakdown_and_ambiguous_cached_subsets() { + let mut price = crate::billing::defaults()["gemini-3.1-flash-image"].clone(); + price.bands.get_mut("image").unwrap().input = "1".to_owned().try_into().unwrap(); + let mut usage = Usage { + input_tokens: Some(10), + output_tokens: Some(0), + image_input_tokens: Some(4), + image_output_tokens: Some(0), + ..Usage::new() + }; + let cost = crate::billing::calculate("gemini-3.1-flash-image", &usage, Some(&price)).unwrap(); + assert_eq!(cost.total_amount().amount().canonical(), "0.000007"); + usage.cached_input_tokens = Some(2); + assert!(crate::billing::calculate("gemini-3.1-flash-image", &usage, Some(&price)).is_none()); +} + +#[test] +fn audio_and_video_requests_or_observed_audio_are_not_priced_as_text() { + for value in [ + json!({"contents":[{"parts":[{"inlineData":{"mimeType":"audio/wav"}}]}]}), + json!({"contents":[{"parts":[{"fileData":{"mimeType":"video/mp4"}}]}]}), + json!({"usageMetadata":{"promptTokensDetails":[{"modality":"AUDIO","tokenCount":2}]}}), + ] { + assert!(!crate::billing::supports_pricing(&value)); + } + assert!(crate::billing::supports_pricing( + &json!({"contents":[{"parts":[{"text":"hello"},{"inlineData":{"mimeType":"image/png"}}]}]}) + )); +} diff --git a/backend/crates/providers/antigravity/tests/billing/mod.rs b/backend/crates/providers/antigravity/tests/billing/mod.rs new file mode 100644 index 000000000..ff858c4d2 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/billing/mod.rs @@ -0,0 +1,5 @@ +//! Antigravity 计价测试入口 + +mod calculate; + +pub(crate) use calculate::pricing; diff --git a/backend/crates/providers/antigravity/tests/credential/catalog.rs b/backend/crates/providers/antigravity/tests/credential/catalog.rs new file mode 100644 index 000000000..4e28821e7 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/credential/catalog.rs @@ -0,0 +1,178 @@ +//! 首次目录查询失败后的周期恢复与能力发布 + +use crate::support::Fixture; +use gateway_core::{engine::provider::Provider, lifecycle::CancellationToken}; +use serde_json::json; +use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path}; + +#[tokio::test] +async fn missing_catalog_is_retried_and_published_after_transient_failure() { + let upstream = MockServer::start().await; + let fixture = Fixture::new(&upstream.uri()); + *fixture.store.primary().catalog.lock().unwrap() = None; + let failed = Mock::given(path("/v1internal:loadCodeAssist")) + .respond_with(ResponseTemplate::new(500)) + .expect(1) + .mount_as_scoped(&upstream) + .await; + assert!( + fixture + .catalog + .reconcile(&CancellationToken::new()) + .await + .is_err() + ); + assert!( + fixture + .provider + .query_model_capabilities() + .await + .unwrap() + .is_empty() + ); + drop(failed); + Mock::given(path("/v1internal:loadCodeAssist")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(json!({"cloudaicompanionProject":"fixture-project"})), + ) + .expect(1) + .mount(&upstream) + .await; + Mock::given(path("/v1internal:fetchAvailableModels")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(json!({"models":{"fixture-model":{"displayName":"Fixture Model"}}})), + ) + .expect(1) + .mount(&upstream) + .await; + let generation = fixture.provider.catalog_generation(); + fixture + .catalog + .reconcile(&CancellationToken::new()) + .await + .unwrap(); + assert_eq!( + fixture + .provider + .query_model_capabilities() + .await + .unwrap() + .len(), + 1 + ); + assert_ne!(fixture.provider.catalog_generation(), generation); + fixture + .catalog + .reconcile(&CancellationToken::new()) + .await + .unwrap(); +} + +#[tokio::test] +async fn credential_revision_change_replaces_the_cached_catalog() { + use gateway_core::account::{CredentialRevision, CredentialState, ProviderAccount, QuotaState}; + let upstream = MockServer::start().await; + let fixture = Fixture::new(&upstream.uri()); + fixture + .catalog + .reconcile(&CancellationToken::new()) + .await + .unwrap(); + assert!(upstream.received_requests().await.unwrap().is_empty()); + let generation = fixture.provider.catalog_generation(); + { + let mut loaded = fixture.store.primary().loaded.lock().unwrap(); + let account = &loaded.account; + loaded.account = ProviderAccount::new( + account.id().clone(), + account.provider().clone(), + account.name().into(), + account.upstream_user_id().map(str::to_owned), + "oauth".into(), + CredentialRevision::new(2).unwrap(), + account.access_token_expires_at(), + ) + .with_account_facts( + true, + CredentialState::Ready, + QuotaState::unknown(), + None, + None, + ); + } + Mock::given(path("/v1internal:loadCodeAssist")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(json!({"cloudaicompanionProject":"rotated-project"})), + ) + .expect(1) + .mount(&upstream) + .await; + Mock::given(path("/v1internal:fetchAvailableModels")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(json!({"models":{"rotated-model":{"displayName":"Rotated Model"}}})), + ) + .expect(1) + .mount(&upstream) + .await; + fixture + .catalog + .reconcile(&CancellationToken::new()) + .await + .unwrap(); + assert_ne!(fixture.provider.catalog_generation(), generation); + { + let stored = fixture.store.primary().catalog.lock().unwrap(); + let (observation, catalog) = stored.as_ref().unwrap(); + assert_eq!(observation.revision, CredentialRevision::new(2).unwrap()); + let catalog: serde_json::Value = serde_json::from_slice(catalog).unwrap(); + assert_eq!(catalog["project"], "rotated-project"); + assert!(catalog["models"].get("rotated-model").is_some()); + assert!(catalog["models"].get("fixture-model").is_none()); + } + fixture + .catalog + .reconcile(&CancellationToken::new()) + .await + .unwrap(); +} + +#[tokio::test] +async fn renewed_identity_rebinds_catalog_without_waiting_for_another_upstream_query() { + let upstream = MockServer::start().await; + let fixture = Fixture::new(&upstream.uri()); + let old = fixture.store.primary().loaded.lock().unwrap().clone(); + let mut captured = fixture + .catalog + .capture_refresh_catalogs(std::slice::from_ref(&old)) + .await + .unwrap(); + let revision = gateway_core::account::CredentialRevision::new(2).unwrap(); + fixture.store.primary().loaded.lock().unwrap().account = + gateway_core::account::ProviderAccount::new( + old.account.id().clone(), + old.account.provider().clone(), + old.account.name().into(), + old.account.upstream_user_id().map(str::to_owned), + "oauth".into(), + revision, + old.account.access_token_expires_at(), + ); + assert!(fixture.catalog.catalogs().await.unwrap().is_empty()); + fixture + .catalog + .after_credential_refresh( + old.account.id(), + revision, + captured.remove(old.account.id()), + ) + .await + .unwrap(); + let catalogs = fixture.catalog.catalogs().await.unwrap(); + assert_eq!(catalogs[0].0[0].revision, revision); + assert!(catalogs[0].1.models.contains_key("fixture-model")); + assert!(upstream.received_requests().await.unwrap().is_empty()); +} diff --git a/backend/crates/providers/antigravity/tests/credential/documents.rs b/backend/crates/providers/antigravity/tests/credential/documents.rs new file mode 100644 index 000000000..43d2c61b6 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/credential/documents.rs @@ -0,0 +1,489 @@ +//! 导入使用真实 OAuth 交换边界,导出可重导入且凭据轮换保持租约与主体约束 + +use super::{ + CredentialService, + oauth::{GoogleOAuth, OAuthRegistration}, +}; +use crate::support::account_record as account; +use crate::support::{Fixture, MemoryPorts}; +use chrono::{Duration, Utc}; +use gateway_admin::{ + model::{ + Revision, + accounts::AccountRecord, + provider_credentials::{ + PrepareCredentialImport, PrepareCredentialRotation, ProviderDocument, + ProviderExportCredentialInput, + }, + }, + ports::provider::ProviderAdminErrorKind as Kind, +}; +use gateway_core::{ + account::{CredentialState, OpaqueProviderData, QuotaState}, + routing::ProviderKind, +}; +use serde_json::{Value, json}; +use std::sync::Arc; +use wiremock::{ + Mock, MockServer, ResponseTemplate, + matchers::{body_string_contains, header, method, path, query_param}, +}; + +async fn fixture() -> (MockServer, CredentialService, Arc) { + let server = MockServer::start().await; + let origin = server.uri(); + let config: OAuthRegistration = serde_json::from_value(json!({ + "client_id":"fixture-client", "client_secret":"fixture-secret", + "redirect_uri":"http://127.0.0.1:8020/callback", + "resource_scopes":["fixture-resource"], "resource_origin":origin, + })) + .unwrap(); + let store = Fixture::new(&origin).store; + let credentials = CredentialService { + kind: ProviderKind::new("antigravity").unwrap(), + accounts: store.clone(), + leases: store.clone(), + runtime_policy: store.clone(), + credential_state: store.clone(), + release: Arc::new( + crate::profile::ReleaseService::new(crate::support::profile::cache()).unwrap(), + ), + oauth: Arc::new(GoogleOAuth::with_endpoints( + config, + &format!("{origin}/token"), + &format!("{origin}/userinfo"), + &format!("{origin}/tokeninfo"), + )), + }; + (server, credentials, store) +} + +fn document(value: Value) -> ProviderDocument { + ProviderDocument::new(OpaqueProviderData::new(value.as_object().unwrap().clone())) +} + +fn import(document: ProviderDocument) -> PrepareCredentialImport { + PrepareCredentialImport { + default_outbound_proxy: None, + document, + } +} + +fn file() -> Value { + json!({"provider":"antigravity","version":1,"accounts":[{"label":"Local name","refreshToken":"fixture-refresh"}]}) +} + +async fn token(server: &MockServer, response: Value) { + Mock::given(method("POST")) + .and(path("/token")) + .and(body_string_contains("grant_type=refresh_token")) + .and(body_string_contains("client_id=fixture-client")) + .and(body_string_contains("client_secret=fixture-secret")) + .respond_with(ResponseTemplate::new(200).set_body_json(response)) + .expect(1) + .mount(server) + .await; +} + +async fn identity(server: &MockServer, subject: &str) { + Mock::given(method("GET")) + .and(path("/userinfo")) + .and(header("authorization", "Bearer fresh-access")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "id":subject, "email":"verified@example.org", "verified_email":true, + }))) + .expect(1) + .mount(server) + .await; +} + +fn token_response() -> Value { + json!({"access_token":"fresh-access","token_type":"Bearer","expires_in":3600,"scope":"email fixture-resource"}) +} + +#[tokio::test] +async fn expired_access_exports_as_refreshable_file_and_reimports_with_local_name() { + let (server, credentials, _) = fixture().await; + let mut record = account(); + record.access_token_expires_at = Some(Utc::now() - Duration::days(1)); + record.email = Some("previous@example.org".into()); + record.plan_type = Some("Google AI Pro".into()); + let material = document(json!({ + "registration":credentials.oauth.registration(), "subject":"fixture-subject", + "access_token":"expired-access", "refresh_token":"fixture-refresh", "scopes":["untrusted-scope"], + })); + let exported = credentials + .export_credentials(vec![ProviderExportCredentialInput { + account: record.clone(), + provider_material: material, + }]) + .unwrap(); + assert!(!format!("{exported:?}").contains("fixture-refresh")); + assert!(!format!("{exported:?}").contains("expired-access")); + let mut exported_file = Value::Object(exported.document.into_provider_data().into_inner()); + let entry = &exported_file["accounts"][0]; + assert_eq!(entry["label"], record.name); + assert_eq!(entry["accessToken"], "expired-access"); + assert_eq!(entry["refreshToken"], "fixture-refresh"); + assert_eq!( + entry["accessTokenExpiresAt"], + json!(record.access_token_expires_at) + ); + assert_eq!(entry["email"], "previous@example.org"); + assert_eq!(entry["userId"], "fixture-subject"); + assert_eq!(entry["planType"], "Google AI Pro"); + assert_eq!(entry["scopes"], json!(["untrusted-scope"])); + assert_eq!(entry["createdAt"], json!(record.created_at)); + assert_eq!(entry["updatedAt"], json!(record.updated_at)); + // 文件中的历史观测不能替代本次导入的身份、权限和有效期验证 + exported_file["accounts"][0]["userId"] = json!("forged-subject"); + exported_file["accounts"][0]["accessTokenExpiresAt"] = json!(Utc::now() + Duration::days(90)); + token(&server, token_response()).await; + identity(&server, "fixture-subject").await; + let result = credentials + .prepare_import(import(document(exported_file))) + .await + .unwrap(); + let loaded = &result.credentials[0]; + assert_eq!(loaded.name, "Local name"); + assert_eq!(loaded.email.as_deref(), Some("verified@example.org")); + assert_eq!(loaded.upstream_user_id.as_deref(), Some("fixture-subject")); + assert!(loaded.has_refresh_token && loaded.access_token_expires_at.unwrap() > Utc::now()); + assert!(loaded.access_token_expires_at.unwrap() < Utc::now() + Duration::hours(2)); + assert_eq!(loaded.plan_type, None); + let stored = loaded + .provider_material + .clone() + .into_provider_data() + .into_inner(); + assert_eq!(stored["access_token"], "fresh-access"); + assert_eq!(stored["refresh_token"], "fixture-refresh"); + assert_eq!(stored["scopes"], json!(["email", "fixture-resource"])); +} + +#[tokio::test] +async fn unnamed_account_exports_and_reimports_with_verified_identity() { + let (server, credentials, _) = fixture().await; + let mut unnamed = account(); + unnamed.name.clear(); + let exported = credentials + .export_credentials(vec![ProviderExportCredentialInput { + account: unnamed, + provider_material: document(json!({ + "registration":credentials.oauth.registration(), "subject":"fixture-subject", + "access_token":"expired-access", "refresh_token":"fixture-refresh", "scopes":[], + })), + }]) + .unwrap(); + assert!( + exported.document.expose_to_provider().expose_to_provider()["accounts"][0] + .get("label") + .is_none() + ); + token(&server, token_response()).await; + identity(&server, "fixture-subject").await; + let imported = credentials + .prepare_import(import(exported.document)) + .await + .unwrap(); + assert_eq!(imported.credentials[0].name, ""); + assert_eq!( + imported.credentials[0].email.as_deref(), + Some("verified@example.org") + ); + assert!(imported.credentials[0].has_refresh_token); +} + +#[tokio::test] +async fn malformed_files_fail_before_any_refresh() { + let (server, credentials, _) = fixture().await; + let mut inputs = vec![]; + for (key, value) in [ + ("provider", json!("openai")), + ("version", json!(2)), + ("accounts", json!([])), + ] { + let mut input = file(); + input[key] = value; + inputs.push(input); + } + let mut unknown = file(); + unknown["accounts"][0]["unknownField"] = json!(true); + inputs.push(unknown); + for (key, value) in [ + ("accessTokenExpiresAt", json!("not-a-timestamp")), + ("scopes", json!("not-an-array")), + ("userId", json!({})), + ] { + let mut malformed = file(); + malformed["accounts"][0][key] = value; + inputs.push(malformed); + } + let mut duplicate = file(); + duplicate["accounts"] + .as_array_mut() + .unwrap() + .push(file()["accounts"][0].clone()); + inputs.push(duplicate); + let mut missing_offline = file(); + missing_offline["accounts"][0]["refreshToken"] = json!(""); + inputs.push(missing_offline); + for input in inputs { + assert_eq!( + credentials + .prepare_import(import(document(input))) + .await + .unwrap_err() + .kind(), + Kind::Invalid + ); + } + assert!(server.received_requests().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn imported_grants_cannot_inherit_missing_or_reduced_scopes() { + let (server, credentials, _) = fixture().await; + let mut input = file(); + input["accounts"][0]["scopes"] = json!(["email", "fixture-resource"]); + for scope in [Value::Null, json!("openid email")] { + server.reset().await; + let mut response = token_response(); + response["scope"] = scope; + token(&server, response).await; + Mock::given(method("GET")) + .and(path("/tokeninfo")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"scope":"email"}))) + .mount(&server) + .await; + assert_eq!( + credentials + .prepare_import(import(document(input.clone()))) + .await + .unwrap_err() + .kind(), + Kind::Invalid + ); + assert!( + server + .received_requests() + .await + .unwrap() + .iter() + .all(|r| r.url.path() != "/userinfo") + ); + } +} + +#[tokio::test] +async fn import_resolves_scopes_and_freezes_global_profile_until_the_next_refresh() { + let (server, credentials, store) = fixture().await; + *store.request_profile.lock().unwrap() = Some(crate::profile::object(json!({ + "client":"cli", "platform":"windows", "versionMode":"fixed", "clientVersion":"1.5.15", + }))); + let mut response = token_response(); + response.as_object_mut().unwrap().remove("scope"); + let policy = store.clone(); + Mock::given(method("POST")) + .and(path("/token")) + .respond_with(move |_: &wiremock::Request| { + *policy.request_profile.lock().unwrap() = Some(crate::profile::object(json!({ + "client":"desktop", "platform":"linux", "versionMode":"fixed", "clientVersion":"9.8.7", + }))); + ResponseTemplate::new(200).set_body_json(response.clone()) + }) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/tokeninfo")) + .and(query_param("access_token", "fresh-access")) + .respond_with( + ResponseTemplate::new(200).set_body_json(json!({"scope":"email fixture-resource"})), + ) + .expect(1) + .mount(&server) + .await; + identity(&server, "fixture-subject").await; + let imported = credentials + .prepare_import(import(document(file()))) + .await + .unwrap(); + let stored = imported.credentials[0] + .provider_material + .clone() + .into_provider_data() + .into_inner(); + assert_eq!(stored["scopes"], json!(["email", "fixture-resource"])); + assert_eq!(stored["refresh_token"], "fixture-refresh"); + assert_eq!( + imported.credentials[0].upstream_user_id.as_deref(), + Some("fixture-subject") + ); + let requests = server.received_requests().await.unwrap(); + assert_eq!(requests.len(), 3); + for request in requests { + assert_eq!( + request.headers["user-agent"], + "antigravity/cli/1.5.15 (aidev_client; os_type=windows; arch=amd64; cl=1027820220; auth_method=consumer)" + ); + } + server.verify().await; + server.reset().await; + token( + &server, + json!({"access_token":"renewed-access","token_type":"Bearer","expires_in":3600}), + ) + .await; + let current = { + let mut current = store.primary().loaded.lock().unwrap(); + current.credential = gateway_core::account::PlaintextCredential::new(stored); + current.clone() + }; + let refreshed = credentials.refresh_current(¤t).await.unwrap(); + assert_eq!( + refreshed + .facts() + .provider_material + .clone() + .into_provider_data() + .expose_to_provider()["access_token"], + "renewed-access" + ); + let requests = server.received_requests().await.unwrap(); + assert_eq!(requests.len(), 1); + assert_eq!( + requests[0].headers["user-agent"], + "antigravity/hub/9.8.7 (aidev_client; os_type=linux; arch=amd64)" + ); + let (_, guard) = refreshed.into_parts(); + guard.finish(); + assert_eq!(store.active_leases(), 0); +} + +#[tokio::test] +async fn upstream_identity_failure_does_not_prepare_an_import() { + let (server, credentials, _) = fixture().await; + token(&server, token_response()).await; + Mock::given(method("GET")) + .and(path("/userinfo")) + .respond_with(ResponseTemplate::new(503)) + .expect(1) + .mount(&server) + .await; + assert_eq!( + credentials + .prepare_import(import(document(file()))) + .await + .unwrap_err() + .kind(), + Kind::Unavailable + ); +} + +#[tokio::test] +async fn a_later_failed_grant_rejects_the_whole_import_without_exposing_tokens() { + let (server, credentials, _) = fixture().await; + let mut input = file(); + input["accounts"].as_array_mut().unwrap().push(json!({ + "label":"Second account", "refreshToken":"revoked-refresh", + })); + Mock::given(method("POST")) + .and(path("/token")) + .and(body_string_contains("refresh_token=fixture-refresh")) + .respond_with(ResponseTemplate::new(200).set_body_json(token_response())) + .expect(1) + .mount(&server) + .await; + identity(&server, "fixture-subject").await; + Mock::given(method("POST")) + .and(path("/token")) + .and(body_string_contains("refresh_token=revoked-refresh")) + .respond_with(ResponseTemplate::new(400).set_body_json(json!({ + "error":"invalid_grant", "error_description":"sensitive-response-marker", + }))) + .expect(1) + .mount(&server) + .await; + let error = credentials + .prepare_import(import(document(input))) + .await + .unwrap_err(); + assert_eq!(error.kind(), Kind::CredentialRefreshRequired); + assert!(!format!("{error:?}").contains("sensitive-response-marker")); + assert!(!format!("{error:?}").contains("revoked-refresh")); +} + +#[tokio::test] +async fn different_refresh_tokens_cannot_import_the_same_google_subject_twice() { + let (server, credentials, _) = fixture().await; + let mut input = file(); + input["accounts"].as_array_mut().unwrap().push(json!({ + "label":"Duplicate account", "refreshToken":"another-refresh", + })); + Mock::given(method("POST")) + .and(path("/token")) + .respond_with(ResponseTemplate::new(200).set_body_json(token_response())) + .expect(2) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/userinfo")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"id":"same-subject"}))) + .expect(2) + .mount(&server) + .await; + assert_eq!( + credentials + .prepare_import(import(document(input))) + .await + .unwrap_err() + .kind(), + Kind::Conflict + ); +} + +#[tokio::test] +async fn rotation_keeps_subject_and_holds_leases_until_commit() { + let (server, credentials, store) = fixture().await; + token(&server, token_response()).await; + identity(&server, "another-subject").await; + let request = || PrepareCredentialRotation { + account: account(), + provider_material: document(file()["accounts"][0].clone()), + }; + assert_eq!( + credentials + .prepare_rotation(request()) + .await + .unwrap_err() + .kind(), + Kind::Conflict + ); + assert_eq!(store.active_leases(), 0); + server.reset().await; + let mut response = token_response(); + response["refresh_token"] = json!("rotated-refresh"); + token(&server, response).await; + identity(&server, "fixture-subject").await; + let prepared = credentials.prepare_rotation(request()).await.unwrap(); + assert_eq!(store.active_leases(), 2); + assert_eq!(prepared.facts().name, "Fixture"); + let (_, guard) = prepared.into_parts(); + guard.finish(); + assert_eq!(store.active_leases(), 0); +} + +#[tokio::test] +async fn export_rejects_foreign_registration_or_mismatched_subject() { + let (_, credentials, _) = fixture().await; + for (registration, subject) in [ + ("wrong-client".to_owned(), "fixture-subject"), + (credentials.oauth.registration(), "wrong-subject"), + ] { + let result = credentials.export_credentials(vec![ProviderExportCredentialInput { + account: account(), provider_material: document(json!({"registration":registration,"subject":subject,"access_token":"access","refresh_token":"refresh","scopes":[]})), + }]); + assert_eq!(result.unwrap_err().kind(), Kind::Invalid); + } +} diff --git a/backend/crates/providers/antigravity/tests/credential/fixture.rs b/backend/crates/providers/antigravity/tests/credential/fixture.rs new file mode 100644 index 000000000..e50ced3c6 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/credential/fixture.rs @@ -0,0 +1,76 @@ +//! 为原生传输回归准备经过真实授权交换和旋转刷新的测试凭据 + +use super::oauth::{GoogleOAuth, OAuthRegistration}; +use serde_json::json; +use url::Url; +use wiremock::{ + Mock, MockServer, ResponseTemplate, + matchers::{header, method, path}, +}; + +pub(crate) async fn refreshed_credential(server: &MockServer) -> (Url, String) { + let origin = server.uri(); + let profile = crate::profile::Selection::default().resolve("2.34.0"); + let config:OAuthRegistration=serde_json::from_value(json!({"client_id":"fixture-cpr","client_secret":"fixture-secret","redirect_uri":"http://127.0.0.1:8020/callback","resource_scopes":["fixture-resource"],"resource_origin":origin})).unwrap(); + config.validate().unwrap(); + let oauth = GoogleOAuth::with_endpoints( + config, + &format!("{origin}/token"), + &format!("{origin}/userinfo"), + &format!("{origin}/tokeninfo"), + ); + let link = oauth.authorize_url("fixture-state", "verifier").unwrap(); + assert!(link.contains("code_challenge_method=S256")); + let code = oauth + .callback_code( + "http://127.0.0.1:8020/callback?code=fixture-code&state=fixture-state", + "fixture-state", + ) + .unwrap(); + let token = |access, refresh| { + ResponseTemplate::new(200).set_body_json(json!({"token_type":"Bearer","access_token":access,"refresh_token":refresh,"expires_in":3600,"scope":"openid email fixture-resource"})) + }; + Mock::given(method("POST")) + .and(path("/token")) + .and(|r: &wiremock::Request| { + String::from_utf8_lossy(&r.body).contains("grant_type=authorization_code") + }) + .respond_with(token("initial-access", "initial-refresh")) + .expect(1) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path("/userinfo")) + .and(header("authorization", "Bearer initial-access")) + .respond_with( + ResponseTemplate::new(200).set_body_json( + json!({"id":"user-1","email":"test@example.org","verified_email":true}), + ), + ) + .expect(1) + .mount(server) + .await; + let grant = oauth + .exchange(&code, "verifier", None, &profile) + .await + .unwrap(); + assert_eq!(grant.email.as_deref(), Some("test@example.org")); + Mock::given(method("POST")) + .and(path("/token")) + .and(|r: &wiremock::Request| { + String::from_utf8_lossy(&r.body).contains("refresh_token=initial-refresh") + }) + .respond_with(token("renewed-access", "rotated-refresh")) + .expect(1) + .mount(server) + .await; + let updated = oauth + .refresh(&grant.material, None, &profile) + .await + .unwrap(); + assert_eq!(updated.material.refresh_token, "rotated-refresh"); + ( + oauth.resource_origin().clone(), + updated.material.access_token, + ) +} diff --git a/backend/crates/providers/antigravity/tests/credential/mod.rs b/backend/crates/providers/antigravity/tests/credential/mod.rs new file mode 100644 index 000000000..5928b9e03 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/credential/mod.rs @@ -0,0 +1,31 @@ +//! 在凭据模块内验证 OAuth 叶子边界,并复用真实授权与刷新服务 + +#[path = "../../src/credential/authorization.rs"] +mod authorization; +#[path = "../../src/credential/documents.rs"] +mod documents; +#[path = "../../src/credential/oauth.rs"] +pub(crate) mod oauth; +#[path = "../../src/credential/refresh.rs"] +mod refresh; +#[path = "../../src/credential/service.rs"] +mod service; +pub(crate) use authorization::AuthorizationService; +pub(crate) use oauth::{GoogleOAuth, Material}; +pub(crate) use service::CredentialService; + +#[path = "documents.rs"] +mod documents_tests; +mod fixture; +#[path = "oauth.rs"] +mod oauth_tests; +pub(crate) use fixture::refreshed_credential; + +#[path = "../../src/credential/catalog.rs"] +pub(crate) mod catalog; +#[path = "catalog.rs"] +mod catalog_tests; +#[path = "../../src/credential/quota/mod.rs"] +pub(crate) mod quota; +#[path = "quota/mod.rs"] +mod quota_tests; diff --git a/backend/crates/providers/antigravity/tests/credential/oauth.rs b/backend/crates/providers/antigravity/tests/credential/oauth.rs new file mode 100644 index 000000000..da7e5548e --- /dev/null +++ b/backend/crates/providers/antigravity/tests/credential/oauth.rs @@ -0,0 +1,266 @@ +//! 验证 OAuth 注册、PKCE、回调与离线授权边界 + +use super::oauth::{self, GoogleOAuth, OAuthRegistration}; +use serde_json::json; +use url::Url; + +fn registration() -> serde_json::Value { + json!({"client_id":"fixture-client","client_secret":"fixture-secret","redirect_uri":"http://127.0.0.1:8020/callback","resource_scopes":["fixture-resource"],"resource_origin":"https://resource.example/"}) +} + +#[test] +fn authorization_link_separates_secret_state_and_pkce() { + let config: OAuthRegistration = serde_json::from_value(registration()).unwrap(); + assert!(config.validate().is_ok()); + assert!(!format!("{config:?}").contains("fixture-secret")); + let oauth = GoogleOAuth::for_provider().unwrap(); + let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; + let url = Url::parse(&oauth.authorize_url("state", verifier).unwrap()).unwrap(); + let fields = url + .query_pairs() + .collect::>(); + assert_eq!(url.host_str(), Some("accounts.google.com")); + assert_eq!(url.path(), "/o/oauth2/auth"); + assert_eq!( + fields["client_id"], + "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com" + ); + assert_eq!( + fields["redirect_uri"], + "http://localhost:8085/auth/callback" + ); + assert_eq!(fields["code_challenge_method"], "S256"); + assert_eq!(fields["response_type"], "code"); + assert_eq!(fields["access_type"], "offline"); + assert_eq!(fields["prompt"], "consent"); + assert_eq!( + fields["code_challenge"], + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + ); + assert_eq!(fields["state"], "state"); + assert_eq!( + fields["scope"] + .split_ascii_whitespace() + .collect::>(), + [ + "https://www.googleapis.com/auth/userinfo.email", + "https://www.googleapis.com/auth/userinfo.profile", + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cclog", + "https://www.googleapis.com/auth/experimentsandconfigs", + "https://www.googleapis.com/auth/aicode", + ] + .into() + ); + assert!(!fields.contains_key("client_secret") && !url.as_str().contains(verifier)); + assert_eq!( + oauth.resource_origin().as_str(), + "https://daily-cloudcode-pa.googleapis.com/" + ); + assert_eq!( + oauth + .callback_code( + "http://localhost:8085/auth/callback?state=state&code=code", + "state" + ) + .unwrap(), + "code" + ); +} + +#[tokio::test] +async fn exchange_and_refresh_preserve_verified_identity_and_offline_grant() { + use wiremock::{ + Mock, MockServer, ResponseTemplate, + matchers::{body_string_contains, header, method, path}, + }; + + let server = MockServer::start().await; + let profile = crate::profile::Selection::default().resolve("2.34.0"); + let oauth = GoogleOAuth::with_endpoints( + serde_json::from_value(registration()).unwrap(), + &format!("{}/token", server.uri()), + &format!("{}/userinfo", server.uri()), + &format!("{}/tokeninfo", server.uri()), + ); + Mock::given(method("POST")) + .and(path("/token")) + .and(body_string_contains("grant_type=authorization_code")) + .and(header("user-agent", profile.user_agent())) + .and(body_string_contains("client_id=fixture-client")) + .and(body_string_contains("client_secret=fixture-secret")) + .and(body_string_contains("code=code")) + .and(body_string_contains("code_verifier=verifier")) + .and(body_string_contains( + "redirect_uri=http%3A%2F%2F127.0.0.1%3A8020%2Fcallback", + )) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "access_token": "access", "refresh_token": "refresh", "token_type": "Bearer", + "expires_in": 3600, "scope": "fixture-resource" + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/userinfo")) + .and(header("authorization", "Bearer access")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "id": "subject", "email": "account@example.com", "verified_email": true + }))) + .expect(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/token")) + .and(body_string_contains("grant_type=refresh_token")) + .and(header("user-agent", profile.user_agent())) + .and(body_string_contains("client_id=fixture-client")) + .and(body_string_contains("client_secret=fixture-secret")) + .and(body_string_contains("refresh_token=refresh")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "access_token": "new-access", "refresh_token": "new-refresh", + "token_type": "Bearer", "expires_in": 3600 + }))) + .expect(1) + .mount(&server) + .await; + + let grant = oauth + .exchange("code", "verifier", None, &profile) + .await + .unwrap(); + assert_eq!(grant.email.as_deref(), Some("account@example.com")); + assert_eq!(grant.material.subject, "subject"); + assert_eq!(grant.material.registration, oauth.registration()); + let refreshed = oauth + .refresh(&grant.material, None, &profile) + .await + .unwrap(); + assert_eq!(refreshed.material.subject, grant.material.subject); + assert_eq!(refreshed.material.scopes, grant.material.scopes); + assert_eq!(refreshed.material.access_token, "new-access"); + assert_eq!(refreshed.material.refresh_token, "new-refresh"); + assert!(refreshed.expires_at > chrono::Utc::now()); + server.verify().await; +} + +#[test] +fn callback_requires_exact_redirect_and_one_pair() { + let oauth = GoogleOAuth::new(serde_json::from_value(registration()).unwrap()); + let base = "http://127.0.0.1:8020/callback"; + assert_eq!( + oauth + .callback_code(&format!("{base}?state=s&code=c"), "s") + .unwrap(), + "c" + ); + for wrong in [ + "?code=c", + "?state=wrong&code=c", + "?state=s&code=c&code=b", + "?state=s&code=c&state=s", + "?error=access_denied&code=c&state=s", + "?state=s&code=c#fragment", + "/other?state=s&code=c", + ] { + assert!(oauth.callback_code(&format!("{base}{wrong}"), "s").is_err()); + } + assert!( + oauth + .callback_code("http://127.0.0.1:8021/callback?state=s&code=c", "s") + .is_err() + ); + assert!(oauth.callback_code("c", "s").is_err()); +} + +#[test] +fn registration_fences_client_scope_and_redirect_while_allowing_secret_rotation() { + let initial = registration(); + let fingerprint = |v| GoogleOAuth::new(serde_json::from_value(v).unwrap()).registration(); + let expected = fingerprint(initial.clone()); + for (key, value) in [ + ("client_id", json!("second")), + ("resource_origin", json!("https://another.example/")), + ("resource_scopes", json!(["second"])), + ("redirect_uri", json!("https://example.org/callback")), + ] { + let mut config = initial.clone(); + config[key] = value; + assert_ne!(expected, fingerprint(config)); + } + let mut rotated = initial; + rotated["client_secret"] = json!("new-secret"); + assert_eq!(expected, fingerprint(rotated)); +} + +#[test] +fn invalid_registration_cannot_request_identity_only_or_use_unsafe_redirect() { + for (key, value) in [ + ("resource_scopes", json!(["openid", "email"])), + ( + "resource_scopes", + json!(["https://www.googleapis.com/auth/userinfo.email"]), + ), + ("resource_scopes", json!([])), + ("client_secret", json!("")), + ("resource_origin", json!("http://example.org/")), + ("redirect_uri", json!("http://example.org/callback")), + ("redirect_uri", json!("https://user@example.org/callback")), + ( + "redirect_uri", + json!("http://127.0.0.1/callback?something=secret"), + ), + ] { + let mut v = registration(); + v[key] = value; + let config: OAuthRegistration = serde_json::from_value(v).unwrap(); + assert!(config.validate().is_err(), "{key}"); + } +} + +#[test] +fn new_grants_require_offline_access_and_explicit_resource_scope() { + let required = vec!["fixture-resource".to_owned()]; + let response = json!({"access_token":"access","refresh_token":"refresh","token_type":"Bearer","expires_in":3600,"scope":"fixture-resource"}); + let mut token: oauth::TokenResponse = serde_json::from_value(response.clone()).unwrap(); + assert_eq!(token.resolve_grant(&required, None).unwrap().1, "refresh"); + for (key, value) in [ + ("refresh_token", json!(null)), + ("scope", json!(null)), + ("scope", json!("openid email")), + ("expires_in", json!(0)), + ("token_type", json!("unknown")), + ] { + let mut input = response.clone(); + input[key] = value; + let mut token: oauth::TokenResponse = serde_json::from_value(input).unwrap(); + assert!(token.resolve_grant(&required, None).is_err(), "{key}"); + } +} + +#[test] +fn refresh_handles_rotation_inheritance_and_reduced_grants() { + let previous:oauth::Material=serde_json::from_value(json!({"registration":"client","subject":"sub","access_token":"old-at","refresh_token":"old-rt","scopes":["openid","fixture-resource"]})).unwrap(); + let required = vec!["fixture-resource".to_owned()]; + let response = json!({"access_token":"new-at","expires_in":3600,"token_type":"bearer"}); + let mut token: oauth::TokenResponse = serde_json::from_value(response.clone()).unwrap(); + let (scopes, rt) = token.resolve_grant(&required, Some(&previous)).unwrap(); + assert_eq!(scopes, previous.scopes); + assert_eq!(rt, "old-rt"); + let mut input = response; + input["refresh_token"] = json!("new-rt"); + let mut token: oauth::TokenResponse = serde_json::from_value(input.clone()).unwrap(); + assert_eq!( + token.resolve_grant(&required, Some(&previous)).unwrap().1, + "new-rt" + ); + input["scope"] = json!("openid email"); + let mut token: oauth::TokenResponse = serde_json::from_value(input).unwrap(); + assert_eq!( + token + .resolve_grant(&required, Some(&previous)) + .unwrap_err() + .kind(), + gateway_admin::ports::provider::ProviderAdminErrorKind::CredentialRefreshRequired + ); +} diff --git a/backend/crates/providers/antigravity/tests/credential/quota/mod.rs b/backend/crates/providers/antigravity/tests/credential/quota/mod.rs new file mode 100644 index 000000000..74e5b8257 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/credential/quota/mod.rs @@ -0,0 +1,3 @@ +//! Antigravity 账号额度测试入口 + +mod service; diff --git a/backend/crates/providers/antigravity/tests/credential/quota/service.rs b/backend/crates/providers/antigravity/tests/credential/quota/service.rs new file mode 100644 index 000000000..fca21b7fe --- /dev/null +++ b/backend/crates/providers/antigravity/tests/credential/quota/service.rs @@ -0,0 +1,236 @@ +//! 真实分组额度投影、模型独立调度与迟到观测隔离 + +use crate::support::Fixture; +use gateway_core::{ + account::{CredentialRevision, CredentialState, ProviderAccount, QuotaState}, + lifecycle::CancellationToken, +}; +use serde_json::json; +use std::time::{Duration, SystemTime}; +use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path}; + +async fn upstream(server: &MockServer, remaining: serde_json::Value, delay: Duration) { + Mock::given(path("/v1internal:loadCodeAssist")).respond_with(ResponseTemplate::new(200).set_body_json(json!({"cloudaicompanionProject":"p","currentTier":{"id":"free-tier","name":"Antigravity"},"paidTier":{"id":"g1-pro-tier","name":"Google AI Pro"}}))).mount(server).await; + Mock::given(path("/v1internal:fetchAvailableModels")).respond_with(ResponseTemplate::new(200).set_body_json(json!({"models":{"fixture-model":{"displayName":"Gemini","quotaInfo":{"remainingFraction":remaining,"resetTime":"2099-01-01T00:00:00Z"}},"other-model":{"displayName":"Claude","quotaInfo":{"remainingFraction":0.8,"resetTime":"2099-01-01T00:00:00Z"}}}}))).mount(server).await; + Mock::given(path("/v1internal:retrieveUserQuotaSummary")).respond_with(ResponseTemplate::new(200).set_delay(delay).set_body_json(json!({"groups":[{"displayName":"Gemini Models","buckets":[{"bucketId":"gemini-weekly","displayName":"Weekly","window":"weekly","remainingFraction":0.9,"resetTime":"2099-01-01T00:00:00Z"},{"bucketId":"gemini-5h","displayName":"Five hour","window":"5h","remainingFraction":remaining,"resetTime":"2099-01-01T00:00:00Z"}]},{"displayName":"Claude and GPT models","buckets":[{"bucketId":"3p-weekly","displayName":"Weekly","window":"weekly","remainingFraction":0.8,"resetTime":"2099-01-01T00:00:00Z"}]}]}))).mount(server).await; +} + +#[tokio::test] +async fn quota_refresh_projects_paid_plan_without_exhausting_other_models() { + let server = MockServer::start().await; + upstream(&server, json!(0.0), Duration::ZERO).await; + let f = Fixture::new(&server.uri()); + let account = f.store.primary().loaded.lock().unwrap().account.clone(); + f.quota.refresh(account.id()).await.unwrap(); + let view = f.quota.read(account.id()).await.unwrap(); + assert_eq!(view.plan_type.as_deref(), Some("g1-pro-tier")); + assert_eq!(view.windows.len(), 3); + assert!( + view.windows + .iter() + .all(|window| window.local_usage.is_none()) + ); + assert_eq!(view.windows[1].used_percent, Some(100.0)); + assert!(!view.limit_reached); + assert_eq!( + f.store + .primary() + .quota + .lock() + .unwrap() + .as_ref() + .unwrap() + .state + .access(), + gateway_core::account::QuotaAccessState::Allowed + ); + let gemini = f + .quota + .scheduling(std::slice::from_ref(&account), "fixture-model") + .await + .unwrap(); + let claude = f + .quota + .scheduling(std::slice::from_ref(&account), "other-model") + .await + .unwrap(); + assert!(gemini[account.id()].0); + assert!(!claude[account.id()].0); + assert_eq!( + claude[account.id()].1.as_ref().unwrap().remaining_rank(), + Some(8000) + ); + { + let mut old = f.store.primary().quota.lock().unwrap(); + old.as_mut().unwrap().observed_at = SystemTime::now() - Duration::from_secs(601); + } + let expired = f + .quota + .scheduling(std::slice::from_ref(&account), "fixture-model") + .await + .unwrap(); + assert!(!expired[account.id()].0); + assert!(expired[account.id()].1.is_none()); +} + +#[tokio::test] +async fn unknown_quota_preserves_only_observed_windows_without_inventing_percentages() { + let server = MockServer::start().await; + upstream(&server, json!(null), Duration::ZERO).await; + let f = Fixture::new(&server.uri()); + let account = f.store.primary().loaded.lock().unwrap().account.clone(); + let empty = f.quota.read(account.id()).await.unwrap(); + assert!(empty.windows.is_empty()); + f.quota.refresh(account.id()).await.unwrap(); + let view = f.quota.read(account.id()).await.unwrap(); + assert_eq!(view.windows[1].used_percent, None); + assert!( + !f.quota + .scheduling(std::slice::from_ref(&account), "fixture-model") + .await + .unwrap()[account.id()] + .0 + ); +} + +#[tokio::test] +async fn failed_or_stale_refresh_preserves_persisted_quota() { + let server = MockServer::start().await; + upstream(&server, json!(0.5), Duration::ZERO).await; + let f = Fixture::new(&server.uri()); + let account = f.store.primary().loaded.lock().unwrap().account.clone(); + f.quota.refresh(account.id()).await.unwrap(); + let first = f.store.primary().quota.lock().unwrap().clone().unwrap(); + server.reset().await; + Mock::given(path("/v1internal:loadCodeAssist")) + .respond_with(ResponseTemplate::new(500)) + .mount(&server) + .await; + assert!(f.quota.refresh(account.id()).await.is_err()); + assert_eq!( + f.store.primary().quota.lock().unwrap().clone().unwrap(), + first + ); + server.reset().await; + upstream(&server, json!(0.0), Duration::from_millis(150)).await; + let service = f.quota.clone(); + let id = account.id().clone(); + let pending = tokio::spawn(async move { service.refresh(&id).await }); + for _ in 0..100 { + if server + .received_requests() + .await + .unwrap() + .iter() + .any(|r| r.url.path() == "/v1internal:retrieveUserQuotaSummary") + { + break; + } + tokio::time::sleep(Duration::from_millis(2)).await; + } + f.store.primary().loaded.lock().unwrap().account = ProviderAccount::new( + account.id().clone(), + account.provider().clone(), + "Fixture".into(), + account.upstream_user_id().map(str::to_owned), + "oauth".into(), + CredentialRevision::new(2).unwrap(), + account.access_token_expires_at(), + ) + .with_account_facts( + true, + CredentialState::Ready, + QuotaState::unknown(), + None, + None, + ); + assert!(pending.await.unwrap().is_err()); + assert_eq!( + f.store.primary().quota.lock().unwrap().clone().unwrap(), + first + ); + assert!( + f.quota + .read(account.id()) + .await + .unwrap() + .plan_type + .is_none() + ); + let cancelled = CancellationToken::new(); + cancelled.cancel(); + f.quota.reconcile(&cancelled).await.unwrap(); +} + +#[tokio::test] +async fn peer_model_facts_keep_membership_quota_and_revision_separate() { + use gateway_core::{ + account::QuotaAccessState, engine::provider::Provider, error::ProviderErrorKind, + }; + let server = MockServer::start().await; + upstream(&server, json!(0.0), Duration::ZERO).await; + let f = Fixture::new(&server.uri()); + let account = crate::support::account_record(); + let id = f + .store + .primary() + .loaded + .lock() + .unwrap() + .account + .id() + .clone(); + f.quota.refresh(&id).await.unwrap(); + let facts = f + .quota + .peer_model_facts(std::slice::from_ref(&account)) + .await + .unwrap(); + let models = &facts[&account.id].models; + assert_eq!( + models["fixture-model"].unwrap().state.access(), + QuotaAccessState::Exhausted + ); + assert_eq!( + models["other-model"].unwrap().state.access(), + QuotaAccessState::Allowed + ); + assert!(!models.contains_key("unavailable-model")); + let result = f + .provider + .clone() + .execute( + crate::support::request(false), + crate::support::context( + crate::profile::Selection::default() + .resolve("2.34.0") + .frozen(), + CancellationToken::new(), + ), + ) + .await; + assert!(matches!(result, Err(e) if e.kind() == ProviderErrorKind::QuotaExhausted)); + f.store + .primary() + .quota + .lock() + .unwrap() + .as_mut() + .unwrap() + .observed_at = SystemTime::now() - Duration::from_secs(601); + let stale = f + .quota + .peer_model_facts(std::slice::from_ref(&account)) + .await + .unwrap(); + assert!(stale[&account.id].models["fixture-model"].is_none()); + let mut changed = account; + changed.credential_revision = gateway_admin::model::Revision::new(2).unwrap(); + assert!( + f.quota + .peer_model_facts(&[changed]) + .await + .unwrap() + .is_empty() + ); +} diff --git a/backend/crates/providers/antigravity/tests/main.rs b/backend/crates/providers/antigravity/tests/main.rs new file mode 100644 index 000000000..7e489bcf9 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/main.rs @@ -0,0 +1,27 @@ +//! 验证 Antigravity 授权、画像、目录、执行与传输合同 + +use provider_antigravity::ConfigError; +#[path = "../src/billing/mod.rs"] +#[allow(dead_code, unused_imports)] +mod billing; +#[path = "billing/mod.rs"] +mod billing_tests; +#[path = "credential/mod.rs"] +#[allow(dead_code, unused_imports)] +mod credential; +#[path = "../src/profile/mod.rs"] +#[allow(dead_code, unused_imports)] +mod profile; +#[path = "profile/mod.rs"] +mod profile_tests; +#[path = "../src/provider/mod.rs"] +#[allow(dead_code, unused_imports)] +mod provider; +#[path = "provider/mod.rs"] +mod provider_tests; +mod support; +#[path = "../src/transport/mod.rs"] +#[allow(dead_code, unused_imports)] +mod transport; +#[path = "transport/mod.rs"] +mod transport_tests; diff --git a/backend/crates/providers/antigravity/tests/profile/archive.rs b/backend/crates/providers/antigravity/tests/profile/archive.rs new file mode 100644 index 000000000..ea6b6f878 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/profile/archive.rs @@ -0,0 +1,124 @@ +//! 分段下载必须匹配对象版本、范围和长度,完整下载核对清单摘要 + +use crate::profile::archive::{RemoteZip, download}; +use sha2::{Digest, Sha512}; +use std::io::Read; +use wiremock::{Mock, MockServer, Request, ResponseTemplate, matchers::any}; + +pub(super) async fn serve(body: Vec, fault: &'static str) -> MockServer { + let server = MockServer::start().await; + Mock::given(any()) + .respond_with(move |request: &Request| { + let response = ResponseTemplate::new(200).insert_header("etag", "\"artifact-1\""); + if request.method.as_str() == "HEAD" { + return response.insert_header("content-length", body.len().to_string()); + } + if let Some(range) = request.headers.get("range") { + assert_eq!(request.headers.get("if-match").unwrap(), "\"artifact-1\""); + let (start, end) = range + .to_str() + .unwrap() + .strip_prefix("bytes=") + .unwrap() + .split_once('-') + .unwrap(); + let start: usize = start.parse().unwrap(); + let end: usize = end.parse().unwrap(); + let mut response = + ResponseTemplate::new(if fault == "ignored" { 200 } else { 206 }) + .insert_header( + "etag", + if fault == "changed" { + "\"artifact-2\"" + } else { + "\"artifact-1\"" + }, + ) + .insert_header( + "content-range", + format!("bytes {start}-{end}/{}", body.len()), + ); + if fault == "range" { + response = response.insert_header("content-range", "bytes 0-1/2"); + } + return response.set_body_bytes( + body[start..=if fault == "truncated" { end - 1 } else { end }].to_vec(), + ); + } + response.set_body_bytes(body.clone()) + }) + .mount(&server) + .await; + server +} + +#[tokio::test] +async fn zip_reads_only_members_from_a_consistent_object() { + let server = serve(super::artifact::desktop_zip("2.35.1"), "").await; + let client = reqwest::Client::new(); + let zip = RemoteZip::open(&client, format!("{}/Antigravity.zip", server.uri())) + .await + .unwrap(); + let asar = zip + .read("Antigravity.app/Contents/Resources/app.asar", 1024) + .await + .unwrap(); + assert_eq!( + crate::profile::artifact::asar_version(&asar).unwrap(), + "2.35.1" + ); + assert!( + zip.read("Antigravity.app/Contents/Resources/app.asar", 1) + .await + .is_err() + ); + assert!(zip.read("absent", 1024).await.is_err()); +} + +#[tokio::test] +async fn zip_rejects_ignored_changed_invalid_or_truncated_ranges() { + for fault in ["ignored", "changed", "range", "truncated"] { + let server = serve(super::artifact::desktop_zip("2.35.1"), fault).await; + assert!( + RemoteZip::open(&reqwest::Client::new(), server.uri()) + .await + .is_err(), + "{fault}" + ); + } + let mut body = super::artifact::desktop_zip("2.35.1"); + let offset = body.len() - 22; + body[offset + 8..offset + 12].fill(0xff); + let server = serve(body, "").await; + assert!( + RemoteZip::open(&reqwest::Client::new(), server.uri()) + .await + .is_err() + ); +} + +#[tokio::test] +async fn complete_download_requires_the_manifest_digest() { + let body = b"official artifact fixture"; + let server = serve(body.to_vec(), "").await; + let client = reqwest::Client::new(); + let digest = hex::encode(Sha512::digest(body)); + let file = download(&client, &server.uri(), Some(&digest)) + .await + .unwrap(); + assert_eq!(file.metadata().unwrap().len(), body.len() as u64); + assert!( + download(&client, &server.uri(), Some(&"0".repeat(128))) + .await + .is_err() + ); +} + +#[test] +fn cancelled_parser_stops_reading_its_temporary_file() { + let (mut file, guard) = + crate::profile::archive::CancellableFile::new(tempfile::tempfile().unwrap()); + assert_eq!(file.read(&mut [0]).unwrap(), 0); + drop(guard); + assert!(file.read(&mut [0]).is_err()); +} diff --git a/backend/crates/providers/antigravity/tests/profile/artifact.rs b/backend/crates/providers/antigravity/tests/profile/artifact.rs new file mode 100644 index 000000000..b025d2703 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/profile/artifact.rs @@ -0,0 +1,153 @@ +//! 发布包元数据与可执行文件的版本、边界和平台校验 + +use crate::profile::{ + artifact, + selection::{Architecture, ClientKind, Platform, ReleaseTarget}, +}; +use std::io::{Cursor, Write}; + +pub(super) fn asar(version: &str) -> Vec { + let package = + serde_json::to_vec(&serde_json::json!({"name":"antigravity","version":version})).unwrap(); + let json = serde_json::to_vec( + &serde_json::json!({"files":{"package.json":{"offset":"0","size":package.len()}}}), + ) + .unwrap(); + let mut bytes = vec![0; 16]; + bytes[4..8].copy_from_slice(&(json.len() as u32 + 8).to_le_bytes()); + bytes[12..16].copy_from_slice(&(json.len() as u32).to_le_bytes()); + bytes.extend(json); + bytes.extend(package); + bytes +} + +pub(super) fn executable(target: ReleaseTarget, version: &str) -> Vec { + let mut bytes = vec![0; 65_536]; + let arm = target.arch == Architecture::Arm64; + match target.platform { + Platform::Macos => { + bytes[..4].copy_from_slice(&[0xcf, 0xfa, 0xed, 0xfe]); + bytes[4..8].copy_from_slice( + &(if arm { 0x0100_000cu32 } else { 0x0100_0007u32 }).to_le_bytes(), + ); + } + Platform::Linux => { + bytes[..6].copy_from_slice(b"\x7fELF\x02\x01"); + bytes[18..20].copy_from_slice(&(if arm { 183u16 } else { 62u16 }).to_le_bytes()); + } + Platform::Windows => { + bytes[..2].copy_from_slice(b"MZ"); + bytes[60..64].copy_from_slice(&128u32.to_le_bytes()); + bytes[128..132].copy_from_slice(b"PE\0\0"); + bytes[132..134] + .copy_from_slice(&(if arm { 0xaa64u16 } else { 0x8664u16 }).to_le_bytes()); + } + } + // 把版本放在扫描块边界上,覆盖跨块字符串识别 + bytes.extend_from_slice(format!("{version}\n\0").as_bytes()); + bytes +} + +pub(super) fn desktop_zip(version: &str) -> Vec { + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated); + zip.start_file("Antigravity.app/Contents/Resources/app.asar", options) + .unwrap(); + zip.write_all(&asar(version)).unwrap(); + zip.start_file("Antigravity.app/Contents/MacOS/Antigravity", options) + .unwrap(); + zip.write_all(&executable( + crate::profile::Selection::default().target(), + version, + )) + .unwrap(); + zip.finish().unwrap().into_inner() +} + +#[test] +fn asar_rejects_wrong_package_truncation_and_invalid_offsets() { + let valid = asar("2.35.1"); + assert_eq!(artifact::asar_version(&valid).unwrap(), "2.35.1"); + for end in [0, 15, valid.len() - 1] { + assert!(artifact::asar_version(&valid[..end]).is_err()); + } + let mut invalid = valid.clone(); + invalid[4..8].copy_from_slice(&0u32.to_le_bytes()); + assert!(artifact::asar_version(&invalid).is_err()); + let invalid = String::from_utf8_lossy(&valid) + .replace("antigravity", "otherproduct") + .into_bytes(); + assert!(artifact::asar_version(&invalid).is_err()); +} + +#[test] +fn cli_binary_requires_target_architecture_and_exact_embedded_version() { + for platform in [Platform::Macos, Platform::Linux, Platform::Windows] { + for arch in [Architecture::Arm64, Architecture::Amd64] { + let target = ReleaseTarget { + client: ClientKind::Cli, + platform, + arch, + }; + let binary = executable(target, "1.5.16"); + assert!(artifact::verify_binary(binary.as_slice(), target, "1.5.16").is_ok()); + assert!(artifact::verify_binary(binary.as_slice(), target, "1.5.15").is_err()); + let other = ReleaseTarget { + arch: if arch == Architecture::Arm64 { + Architecture::Amd64 + } else { + Architecture::Arm64 + }, + ..target + }; + assert!(artifact::verify_binary(binary.as_slice(), other, "1.5.16").is_err()); + } + } +} + +#[test] +fn windows_resource_requires_consistent_file_and_product_versions() { + let mut resource = b"\xbd\x04\xef\xfe\0\0\x01\0".to_vec(); + for word in [2u32 << 16 | 35, 1 << 16, 2 << 16 | 35, 1 << 16] { + resource.extend(word.to_le_bytes()); + } + assert!(artifact::windows_version(&resource, "2.35.1").is_ok()); + resource[4..8].fill(0); + assert!(artifact::windows_version(&resource, "2.35.1").is_ok()); + assert!(artifact::windows_version(&resource, "2.35.2").is_err()); + resource[16] ^= 1; + assert!(artifact::windows_version(&resource, "2.35.1").is_err()); +} + +#[test] +fn tar_requires_both_package_and_executable_and_rejects_wrong_version() { + let target = ReleaseTarget { + client: ClientKind::Desktop, + platform: Platform::Linux, + arch: Architecture::Amd64, + }; + let make = |include_executable: bool| { + let mut builder = tar::Builder::new(flate2::write::GzEncoder::new( + Vec::new(), + flate2::Compression::fast(), + )); + let mut files = vec![("Antigravity/resources/app.asar", asar("2.35.1"))]; + if include_executable { + files.push(("Antigravity/antigravity", executable(target, "2.35.1"))); + } + for (path, body) in files { + let mut header = tar::Header::new_gnu(); + header.set_size(body.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + builder + .append_data(&mut header, path, body.as_slice()) + .unwrap(); + } + builder.into_inner().unwrap().finish().unwrap() + }; + assert!(artifact::verify_tar(make(true).as_slice(), target, "2.35.1").is_ok()); + assert!(artifact::verify_tar(make(true).as_slice(), target, "2.35.2").is_err()); + assert!(artifact::verify_tar(make(false).as_slice(), target, "2.35.1").is_err()); +} diff --git a/backend/crates/providers/antigravity/tests/profile/mod.rs b/backend/crates/providers/antigravity/tests/profile/mod.rs new file mode 100644 index 000000000..0949b9736 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/profile/mod.rs @@ -0,0 +1,7 @@ +//! 客户端选择与官方发布资料测试 + +mod archive; +mod artifact; +mod release; +mod selection; +mod verification; diff --git a/backend/crates/providers/antigravity/tests/profile/release.rs b/backend/crates/providers/antigravity/tests/profile/release.rs new file mode 100644 index 000000000..eea98b982 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/profile/release.rs @@ -0,0 +1,52 @@ +//! 官方发布资料的来源、目标制品与歧义校验 + +use crate::profile::{ + Selection, release, + selection::{ClientKind, Platform}, +}; + +#[test] +fn desktop_release_selects_only_matching_official_artifact() { + let prefix = "https://storage.googleapis.com/antigravity-public/antigravity-hub"; + let mac = format!("{prefix}/2.34.0-5887025308631040/darwin-arm/Antigravity.dmg"); + let page = format!( + r#""# + ); + let target = Selection::default().target(); + let release = release::parse_desktop(&page, target).unwrap(); + assert_eq!(release.version, "2.34.0"); + assert_eq!(release.build.as_deref(), Some("5887025308631040")); + assert!( + release::parse_desktop( + &format!(r#"{page}"#), + target + ) + .is_none() + ); + assert!(release::parse_desktop(&page.replace(&mac, ""), target).is_none()); +} + +#[test] +fn cli_manifest_requires_official_origin_and_matching_version() { + for url in [ + "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.15-123/linux-x64/cli_linux_x64.tar.gz", + "https://other.invalid/antigravity-cli/1.5.15-123/linux-x64/cli_linux_x64.tar.gz", + "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.14-123/linux-x64/cli_linux_x64.tar.gz", + ] { + let body = serde_json::to_vec( + &serde_json::json!({"version":"1.5.15", "url":url,"sha512":"a".repeat(128)}), + ) + .unwrap(); + let target = Selection { + client: ClientKind::Cli, + platform: Platform::Linux, + ..Selection::default() + } + .target(); + let release = release::parse_cli(&body, target); + assert_eq!( + release.is_ok(), + url.contains("googleapis.com") && url.contains("1.5.15-123") + ); + } +} diff --git a/backend/crates/providers/antigravity/tests/profile/selection.rs b/backend/crates/providers/antigravity/tests/profile/selection.rs new file mode 100644 index 000000000..fa161f1a9 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/profile/selection.rs @@ -0,0 +1,77 @@ +//! 三平台客户端身份、冻结版本与非法配置边界 + +use crate::profile::{ClientProfile, Selection, object}; +use serde_json::json; + +#[test] +fn client_presets_resolve_platform_and_frozen_version() { + for (platform, os, arch) in [ + ("macos", "darwin", "arm64"), + ("linux", "linux", "amd64"), + ("windows", "windows", "amd64"), + ] { + for (client, subclient, auth) in [ + ("desktop", "hub", ""), + ("cli", "cli", "; auth_method=consumer"), + ] { + let selection = Selection::parse(&object(json!({"client":client,"platform":platform,"versionMode":"latest","clientVersion":null,"arch":null}))).unwrap(); + let initial = selection + .resolve(selection.client.baseline().version) + .frozen(); + let frozen = selection.resolve("2.35.0").frozen(); + let profile = ClientProfile::from_frozen(&frozen).unwrap(); + // 发布版本变化后不混入旧 CL,也不把未知版本标记为实测画像 + assert!(profile.verified_at().is_none()); + assert_eq!( + profile.user_agent(), + format!( + "antigravity/{subclient}/2.35.0 (aidev_client; os_type={os}; arch={arch}{auth})" + ) + ); + let original = ClientProfile::from_frozen(&initial).unwrap(); + assert!(original.user_agent().contains("; cl=")); + assert_eq!( + original.verified_at().is_some(), + client == "desktop" && platform == "macos" + ); + assert_ne!(original.user_agent(), profile.user_agent()); + } + } +} + +#[test] +fn fixed_version_rejects_header_injection_and_incomplete_selection() { + for value in [ + json!({"client":"desktop","platform":"macos","versionMode":"fixed","clientVersion":"1.0.0\r\nother","arch":null}), + json!({"client":"desktop","platform":"macos","versionMode":"fixed","clientVersion":null,"arch":null}), + json!({"client":"desktop","platform":"macos","versionMode":"latest","clientVersion":"1.0.0","arch":null}), + ] { + assert!(Selection::parse(&object(value)).is_err()); + } + let selected = Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.15","arch":"arm64"}))).unwrap(); + assert_eq!( + selected.resolve("9.9.9").user_agent(), + "antigravity/cli/1.5.15 (aidev_client; os_type=linux; arch=arm64; cl=1027820220; auth_method=consumer)" + ); +} + +#[test] +fn system_prompt_defaults_and_customization_are_frozen_with_the_profile() { + let mut selection = Selection::default(); + let default = selection.resolve("1.5.15"); + assert!(default.system_prompt.starts_with("You are Antigravity,")); + selection.system_prompt = Some("Use the fixture instruction.".into()); + let frozen = selection.resolve("1.5.15").frozen(); + selection.system_prompt = Some("New configuration.".into()); + assert_eq!( + ClientProfile::from_frozen(&frozen).unwrap().system_prompt, + "Use the fixture instruction." + ); + selection.system_prompt = Some(" \n".into()); + let reset = Selection::parse(&selection.configuration()).unwrap(); + assert_eq!(reset.resolve("1.5.15").system_prompt, default.system_prompt); + for prompt in ["x".repeat(16 * 1024 + 1), "\0".into()] { + selection.system_prompt = Some(prompt); + assert!(Selection::parse(&selection.configuration()).is_err()); + } +} diff --git a/backend/crates/providers/antigravity/tests/profile/verification.rs b/backend/crates/providers/antigravity/tests/profile/verification.rs new file mode 100644 index 000000000..7b9b279cd --- /dev/null +++ b/backend/crates/providers/antigravity/tests/profile/verification.rs @@ -0,0 +1,163 @@ +//! 缓存恢复保留事实时间,制品、目标或缓存变化不能借用旧核验结果 + +use crate::{ + profile::{ReleaseService, Selection, artifact::Release, verification::VerificationCache}, + support::profile::cache, +}; +use gateway_core::{provider_ports::ProviderArtifactProfile, routing::ProviderKind}; +use std::sync::atomic::Ordering; + +fn provider() -> ProviderKind { + ProviderKind::new("antigravity").unwrap() +} +fn release(server: &wiremock::MockServer, version: &str) -> Release { + Release { + version: version.into(), + build: Some("123".into()), + url: format!("{}/Antigravity.dmg", server.uri()), + sha512: None, + } +} + +#[tokio::test] +async fn cache_restore_and_renewal_preserve_verification_without_downloading_again() { + let server = super::archive::serve(super::artifact::desktop_zip("2.35.1"), "").await; + let cache = cache(); + let service = VerificationCache::new(provider(), cache.clone()); + let client = reqwest::Client::new(); + let target = Selection::default().target(); + let release = release(&server, "2.35.1"); + let first = service + .verify(&client, target, &release, None) + .await + .unwrap(); + let requests = server.received_requests().await.unwrap().len(); + let same = service + .verify(&client, target, &release, Some(&first)) + .await + .unwrap(); + assert_eq!(same.verified_at, first.verified_at); + assert_eq!(cache.writes.load(Ordering::SeqCst), 1); + let restarted = VerificationCache::new(provider(), cache.clone()); + let restored = restarted + .verify(&client, target, &release, None) + .await + .unwrap(); + assert_eq!(restored.verified_at, first.verified_at); + assert_eq!(cache.writes.load(Ordering::SeqCst), 2); + assert_eq!(server.received_requests().await.unwrap().len(), requests); + + let releases = ReleaseService::new(cache).unwrap(); + releases.publish(target, Some(release.clone())); + releases.update().await.unwrap(); + assert_eq!( + crate::profile::dashboard(&Selection::default(), &releases).verified_at, + Some(first.verified_at) + ); + let new_release = Release { + version: "2.36.0".into(), + ..release + }; + releases.publish(target, Some(new_release)); + assert!(releases.update().await.is_err()); + assert!( + crate::profile::dashboard(&Selection::default(), &releases) + .verified_at + .is_none() + ); +} + +#[tokio::test] +async fn changed_artifact_or_target_and_failed_cache_do_not_publish_verification() { + let server = super::archive::serve(super::artifact::desktop_zip("2.35.1"), "").await; + let cache = cache(); + let service = VerificationCache::new(provider(), cache.clone()); + let client = reqwest::Client::new(); + let target = Selection::default().target(); + let release = release(&server, "2.35.1"); + service + .verify(&client, target, &release, None) + .await + .unwrap(); + let original = cache + .profiles + .lock() + .unwrap() + .values() + .next() + .unwrap() + .clone(); + let changed = Release { + build: Some("124".into()), + ..release.clone() + }; + assert!( + service + .verify(&client, target, &changed, None) + .await + .is_err() + ); + cache.fail.store(true, Ordering::SeqCst); + assert!( + service + .verify(&client, target, &release, None) + .await + .is_err() + ); + cache.fail.store(false, Ordering::SeqCst); + let corrupted = ProviderArtifactProfile::new( + ProviderKind::new("openai").unwrap(), + original.artifact_key().into(), + original.artifact_sequence(), + original.verified_at(), + original.profile().clone(), + ); + cache + .profiles + .lock() + .unwrap() + .insert(original.artifact_key().into(), corrupted); + assert!( + service + .verify(&client, target, &release, None) + .await + .is_err() + ); +} + +#[tokio::test] +async fn version_disagreement_leaves_the_previous_cache_intact() { + let server = super::archive::serve(super::artifact::desktop_zip("2.35.1"), "").await; + let cache = cache(); + let service = VerificationCache::new(provider(), cache.clone()); + let client = reqwest::Client::new(); + let target = Selection::default().target(); + let release = release(&server, "2.35.1"); + let first = service + .verify(&client, target, &release, None) + .await + .unwrap(); + let newer = Release { + version: "2.36.0".into(), + ..release + }; + assert!( + service + .verify(&client, target, &newer, Some(&first)) + .await + .is_err() + ); + assert_eq!(cache.writes.load(Ordering::SeqCst), 1); + let old = cache + .profiles + .lock() + .unwrap() + .values() + .next() + .unwrap() + .clone(); + assert_eq!( + chrono::DateTime::::from(old.verified_at()), + first.verified_at + ); +} diff --git a/backend/crates/providers/antigravity/tests/provider/affinity.rs b/backend/crates/providers/antigravity/tests/provider/affinity.rs new file mode 100644 index 000000000..7aa7d661a --- /dev/null +++ b/backend/crates/providers/antigravity/tests/provider/affinity.rs @@ -0,0 +1,531 @@ +//! 验证三种入站协议的会话绑定、租户隔离与发送前原子认领 + +use crate::support::{Fixture, context_with_policy, context_with_scope, request}; +use futures::TryStreamExt; +use gateway_core::{ + account::{ + AccountAffinity, AccountSelectionPolicy, ProviderAccountId, ProviderAccountStore, + RotationStrategy, + }, + concurrency::ConcurrencyQueuePolicy, + engine::{ + AccountAttemptContext, AttemptContext, ModelRequestId, ProviderAccountStateOwner, + RequestAttemptContext, + provider::{Provider, ProviderRequest, ProviderStream}, + }, + lifecycle::CancellationToken, + operation::{GenerateRequest, Operation, ProtocolPayload}, + policy::ClientApiKeyId, + routing::ProviderKind, +}; +use serde_json::{Value, json}; +use std::{ + collections::BTreeSet, + num::NonZeroU32, + sync::atomic::Ordering, + time::{Duration, SystemTime}, +}; +use wiremock::{ + Mock, MockServer, ResponseTemplate, + matchers::{body_partial_json, header, path}, +}; + +pub(super) fn session_request(protocol: &str, body: Value, context: Value) -> ProviderRequest { + ProviderRequest::new( + Operation::Generate(GenerateRequest::from_protocol_payload( + ProtocolPayload::json_object(protocol, body.as_object().unwrap().clone()) + .unwrap() + .with_context(context.as_object().unwrap().clone()), + )), + request(false).candidate().clone(), + ) +} + +fn context(key: &str, ttl: u64) -> gateway_core::engine::AttemptContext { + context_with_policy( + RequestAttemptContext::new( + ModelRequestId::new("req_affinity").unwrap(), + ClientApiKeyId::new(key).unwrap(), + ), + AccountSelectionPolicy::new(RotationStrategy::Smart, std::num::NonZeroU32::MIN) + .with_account_affinity(AccountAffinity::Strict) + .with_session_affinity_ttl(Duration::from_secs(ttl)), + CancellationToken::new(), + ) +} + +#[tokio::test] +async fn each_inbound_protocol_reuses_its_explicit_session_and_renews_ttl() { + let fixture = Fixture::new("http://127.0.0.1:1"); + for (protocol, body, metadata) in [ + ( + gateway_protocol::genai::GENAI_PROTOCOL, + json!({"contents": []}), + json!({"headers":{"x-http-session-id":"session-a"}}), + ), + ( + gateway_protocol::openai::OPENAI_PROTOCOL, + json!({"input":[], "client_metadata":{"session_id":"session-a"}}), + json!({}), + ), + ( + gateway_protocol::anthropic::ANTHROPIC_PROTOCOL, + json!({"messages":[]}), + json!({"opaque_request_headers":[["x-claude-code-session-id","c2Vzc2lvbi1h"]]}), + ), + ] { + for ttl in [7200, 3600] { + let stream = fixture + .provider + .clone() + .execute( + session_request(protocol, body.clone(), metadata.clone()), + context("key_one", ttl), + ) + .await + .unwrap(); + assert_eq!( + stream.metadata().provider_account_id().as_str(), + "acct_fixture" + ); + drop(stream); + } + } + let bindings = fixture.store.bindings.lock().unwrap(); + assert_eq!( + bindings.len(), + 3, + "each protocol has an independent identity namespace" + ); + assert!( + bindings + .values() + .all(|(_, ttl)| *ttl == Duration::from_secs(3600)) + ); +} + +#[tokio::test] +async fn same_session_is_isolated_between_client_keys() { + let fixture = Fixture::new("http://127.0.0.1:1"); + for key in ["key_one", "key_two"] { + drop( + fixture + .provider + .clone() + .execute( + session_request( + gateway_protocol::genai::GENAI_PROTOCOL, + json!({"contents":[]}), + json!({"headers":{"x-session-id":"shared"}}), + ), + context(key, 3600), + ) + .await + .unwrap(), + ); + } + assert_eq!(fixture.store.bindings.lock().unwrap().len(), 2); +} + +async fn select_genai_session( + fixture: &Fixture, + client_key: &str, + body: Value, + metadata: Value, +) -> ProviderStream { + fixture + .provider + .clone() + .execute( + session_request(gateway_protocol::genai::GENAI_PROTOCOL, body, metadata), + context_with_scope( + RequestAttemptContext::new( + ModelRequestId::new("req_body_affinity").unwrap(), + ClientApiKeyId::new(client_key).unwrap(), + ), + AccountSelectionPolicy::new(RotationStrategy::RoundRobin, NonZeroU32::MIN) + .with_account_affinity(AccountAffinity::Strict), + CancellationToken::new(), + fixture.store.account_scope(), + ), + ) + .await + .unwrap() +} + +#[tokio::test] +async fn genai_body_session_aliases_keep_the_primary_and_share_one_binding() { + let fixture = Fixture::with_two_accounts("http://127.0.0.1:1"); + for body in [ + json!({"contents": [], "sessionId": "session-a"}), + json!({"contents": [], "session_id": " session-a "}), + json!({"contents": [], "sessionId": "session-a", "session_id": "other-body"}), + ] { + let stream = select_genai_session(&fixture, "key_one", body, json!({})).await; + assert_eq!( + stream.metadata().provider_account_id().as_str(), + "acct_fixture" + ); + drop(stream); + } + assert_eq!(fixture.store.bindings.lock().unwrap().len(), 1); + let other = select_genai_session( + &fixture, + "key_one", + json!({"contents": [], "sessionId": "session-b"}), + json!({}), + ) + .await; + assert_eq!( + other.metadata().provider_account_id().as_str(), + "acct_standby", + "affinity hits must leave the next account for a new session" + ); + drop(other); + assert_eq!(fixture.store.active_leases(), 0); +} + +#[tokio::test] +async fn genai_body_session_is_isolated_between_client_keys() { + let fixture = Fixture::with_two_accounts("http://127.0.0.1:1"); + let body = json!({"contents": [], "sessionId": "shared"}); + let first = select_genai_session(&fixture, "key_one", body.clone(), json!({})).await; + let second = select_genai_session(&fixture, "key_two", body, json!({})).await; + assert_ne!( + first.metadata().provider_account_id(), + second.metadata().provider_account_id() + ); + assert_eq!(fixture.store.bindings.lock().unwrap().len(), 2); + drop((first, second)); + assert_eq!(fixture.store.active_leases(), 0); +} + +#[tokio::test] +async fn genai_session_headers_take_precedence_over_body_aliases() { + for metadata in [ + json!({"headers": {"x-http-session-id": "header-session", "x-session-id": "other-header"}}), + json!({"headers": {"x-session-id": "header-session"}}), + json!({"opaque_request_headers": [["X-Http-Session-Id", "aGVhZGVyLXNlc3Npb24="]]}), + ] { + let fixture = Fixture::with_two_accounts("http://127.0.0.1:1"); + for body in [ + json!({"contents": [], "sessionId": "body-session", "session_id": "other-body"}), + json!({"contents": []}), + ] { + let stream = select_genai_session(&fixture, "key_one", body, metadata.clone()).await; + assert_eq!( + stream.metadata().provider_account_id().as_str(), + "acct_fixture" + ); + drop(stream); + } + assert_eq!(fixture.store.bindings.lock().unwrap().len(), 1); + } +} + +#[tokio::test] +async fn invalid_genai_body_sessions_do_not_create_affinity_bindings() { + let fixture = Fixture::with_two_accounts("http://127.0.0.1:1"); + for field in ["sessionId", "session_id"] { + for session in [ + Value::Null, + json!(42), + json!(true), + json!([]), + json!({}), + json!(""), + json!(" "), + json!("session\n-a"), + json!("x".repeat(1025)), + ] { + drop( + select_genai_session( + &fixture, + "key_one", + json!({"contents": [], field: session}), + json!({}), + ) + .await, + ); + } + } + assert!(fixture.store.bindings.lock().unwrap().is_empty()); + assert_eq!(fixture.store.active_leases(), 0); +} + +#[tokio::test] +async fn invalid_genai_session_header_does_not_fall_back_to_body_identity() { + let fixture = Fixture::with_two_accounts("http://127.0.0.1:1"); + drop( + select_genai_session( + &fixture, + "key_one", + json!({"contents": [], "sessionId": "body-session"}), + json!({"headers": {"x-http-session-id": " "}}), + ) + .await, + ); + assert!(fixture.store.bindings.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn requests_without_session_do_not_create_bindings() { + let fixture = Fixture::new("http://127.0.0.1:1"); + drop( + fixture + .provider + .clone() + .execute(request(false), context("key_one", 3600)) + .await + .unwrap(), + ); + assert_eq!(fixture.store.claims.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn binding_conflict_releases_the_lease_before_reselection() { + let fixture = Fixture::new("http://127.0.0.1:1"); + fixture + .store + .reject_next_claim + .store(true, Ordering::SeqCst); + let stream = fixture + .provider + .clone() + .execute( + session_request( + gateway_protocol::genai::GENAI_PROTOCOL, + json!({"contents":[]}), + json!({"headers":{"x-http-session-id":"session-a"}}), + ), + context("key_one", 3600), + ) + .await + .unwrap(); + assert_eq!(fixture.store.claims.load(Ordering::SeqCst), 2); + assert_eq!(fixture.store.active_leases(), 1); + drop(stream); + assert_eq!(fixture.store.active_leases(), 0); +} + +async fn select_session(fixture: &Fixture, session: &str, mode: AccountAffinity) -> ProviderStream { + let policy = AccountSelectionPolicy::new(RotationStrategy::Smart, NonZeroU32::MIN) + .with_account_affinity(mode) + .with_queue(ConcurrencyQueuePolicy { + max_waiting: 1, + timeout: Duration::from_secs(2), + }); + let ctx = context_with_scope( + RequestAttemptContext::new( + ModelRequestId::new("req_affinity").unwrap(), + ClientApiKeyId::new("key_fixture").unwrap(), + ), + policy, + CancellationToken::new(), + fixture.store.account_scope(), + ); + fixture + .provider + .clone() + .execute( + session_request( + gateway_protocol::genai::GENAI_PROTOCOL, + json!({"contents":[{"parts":[{"text":"hello"}]}]}), + json!({ + "headers":{"x-http-session-id":session}, + "opaque_request_headers":[["traceparent", "Zml4dHVyZS10cmFjZQ=="]], + }), + ), + ctx, + ) + .await + .unwrap() +} + +#[tokio::test] +async fn strict_session_waits_for_its_primary_while_another_session_uses_the_spare() { + let fixture = Fixture::with_two_accounts("http://127.0.0.1:1"); + let select = |session| select_session(&fixture, session, AccountAffinity::Strict); + let holder = select("session-a").await; + let primary = holder.metadata().provider_account_id().clone(); + let waiting = select("session-a"); + tokio::pin!(waiting); + assert!(futures::poll!(&mut waiting).is_pending()); + + let other = select("session-b").await; + assert_ne!(other.metadata().provider_account_id(), &primary); + assert_eq!(fixture.store.active_leases(), 2); + drop(holder); + + let resumed = waiting.await; + assert_eq!(resumed.metadata().provider_account_id(), &primary); + drop((resumed, other)); + assert_eq!(fixture.store.active_leases(), 0); +} + +#[tokio::test] +async fn preferred_session_can_send_with_the_spare_then_returns_to_its_primary() { + let upstream = MockServer::start().await; + for name in ["fixture", "standby"] { + Mock::given(path("/v1internal:generateContent")) + .and(header("authorization", format!("Bearer {name}-access"))) + .and(body_partial_json(json!({"project": format!("{name}-project")}))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "response": {"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}]} + }))) + .expect(1) + .mount(&upstream) + .await; + } + let fixture = Fixture::with_two_accounts(&upstream.uri()); + let select = || select_session(&fixture, "session-a", AccountAffinity::Preferred); + let holder = select().await; + let primary = holder.metadata().provider_account_id().clone(); + + let overflow = select().await; + assert_ne!(overflow.metadata().provider_account_id(), &primary); + assert!( + overflow + .try_collect::>() + .await + .unwrap() + .iter() + .any(|event| event.has_client_event()) + ); + assert_eq!( + fixture + .store + .bindings + .lock() + .unwrap() + .values() + .next() + .unwrap() + .0 + .account_id(), + &primary + ); + + drop(holder); + let recovered = select().await; + assert_eq!(recovered.metadata().provider_account_id(), &primary); + assert!( + recovered + .try_collect::>() + .await + .unwrap() + .iter() + .any(|event| event.has_client_event()) + ); + upstream.verify().await; + let sent = upstream.received_requests().await.unwrap(); + assert!(sent[0].headers.get("traceparent").is_none()); + assert_eq!(sent[1].headers["traceparent"], "fixture-trace"); + assert_eq!(fixture.store.active_leases(), 0); +} + +#[tokio::test] +async fn disabled_primary_migrates_the_session_binding() { + let upstream = MockServer::start().await; + Mock::given(path("/v1internal:generateContent")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "response": {"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}]} + }))) + .expect(2) + .mount(&upstream) + .await; + let fixture = Fixture::with_two_accounts(&upstream.uri()); + let select = || select_session(&fixture, "session-a", AccountAffinity::Strict); + let first = select().await; + let primary = first.metadata().provider_account_id().clone(); + drop(first); + + fixture.store.set_enabled(&primary, false).await.unwrap(); + let replacement = select().await; + let account = replacement.metadata().provider_account_id().clone(); + assert_ne!(account, primary); + replacement.try_collect::>().await.unwrap(); + + fixture.store.set_enabled(&primary, true).await.unwrap(); + let same_account = select().await; + assert_eq!(same_account.metadata().provider_account_id(), &account); + same_account.try_collect::>().await.unwrap(); + assert_eq!( + fixture + .store + .bindings + .lock() + .unwrap() + .values() + .next() + .unwrap() + .0 + .account_id(), + &account + ); + let sent = upstream.received_requests().await.unwrap(); + assert!(sent[0].headers.get("traceparent").is_none()); + assert_eq!(sent[1].headers["traceparent"], "fixture-trace"); + upstream.verify().await; + assert_eq!(fixture.store.active_leases(), 0); +} + +#[tokio::test] +async fn sessionless_retry_strips_trace_only_for_a_different_known_state_owner() { + let upstream = MockServer::start().await; + Mock::given(path("/v1internal:generateContent")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "response": {"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}]} + }))) + .expect(3) + .mount(&upstream) + .await; + let fixture = Fixture::new(&upstream.uri()); + for owner in [None, Some("acct_fixture"), Some("acct_standby")] { + let ctx = AttemptContext::new( + RequestAttemptContext::new( + ModelRequestId::new("req_retry_trace").unwrap(), + ClientApiKeyId::new("key_fixture").unwrap(), + ), + NonZeroU32::MIN, + SystemTime::now() + Duration::from_secs(30), + AccountSelectionPolicy::new(RotationStrategy::Smart, NonZeroU32::MIN), + AccountAttemptContext::new( + BTreeSet::new(), + None, + owner.map(|account| { + ProviderAccountStateOwner::new( + ProviderKind::new("antigravity").unwrap(), + ProviderAccountId::new(account).unwrap(), + ) + }), + ) + .with_account_scope(fixture.store.account_scope()), + None, + CancellationToken::new(), + ); + fixture + .provider + .clone() + .execute( + session_request( + gateway_protocol::genai::GENAI_PROTOCOL, + json!({"contents": []}), + json!({"opaque_request_headers":[["traceparent", "Zml4dHVyZS10cmFjZQ=="]]}), + ), + ctx, + ) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + } + let sent = upstream.received_requests().await.unwrap(); + assert_eq!(sent[0].headers["traceparent"], "fixture-trace"); + assert_eq!(sent[1].headers["traceparent"], "fixture-trace"); + assert!(sent[2].headers.get("traceparent").is_none()); + assert!(fixture.store.bindings.lock().unwrap().is_empty()); + assert_eq!(fixture.store.active_leases(), 0); + upstream.verify().await; +} diff --git a/backend/crates/providers/antigravity/tests/provider/execution.rs b/backend/crates/providers/antigravity/tests/provider/execution.rs new file mode 100644 index 000000000..4a95ba61f --- /dev/null +++ b/backend/crates/providers/antigravity/tests/provider/execution.rs @@ -0,0 +1,533 @@ +//! 真实 Provider 的发送时机、画像、取消与错误诊断合同 + +use crate::{ + profile::{Selection, object}, + support::{Fixture, context, request}, +}; +use futures::{StreamExt, TryStreamExt}; +use gateway_core::{ + account::{ + AccountSelectionPolicy, CredentialState, OpaqueProviderData, QuotaState, RotationStrategy, + }, + engine::{ + AccountAttemptContext, AttemptContext, ModelRequestId, RequestAttemptContext, + probe::AccountProbeTarget, provider::Provider, + }, + error::ProviderErrorKind, + lifecycle::CancellationToken, + policy::ClientApiKeyId, + routing::ProviderKind, + upstream::UpstreamSendState, +}; +use serde_json::json; +use std::{ + num::NonZeroU32, + sync::atomic::Ordering, + time::{Duration, SystemTime}, +}; +use wiremock::{ + Mock, MockServer, ResponseTemplate, + matchers::{body_partial_json, header, method, path}, +}; + +fn frozen_profile() -> OpaqueProviderData { + Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.14","arch":null}))).unwrap().resolve("9.9.9").frozen() +} + +async fn released(fixture: &Fixture) { + tokio::time::timeout(Duration::from_secs(1), async { + while fixture.store.active_leases() != 0 { + tokio::task::yield_now().await; + } + }) + .await + .expect("stream releases its account lease"); +} + +#[tokio::test] +async fn returning_and_dropping_unpolled_stream_never_sends_and_releases_lease() { + let upstream = MockServer::start().await; + let fixture = Fixture::new(&upstream.uri()); + let stream = fixture + .provider + .clone() + .execute( + request(false), + context(frozen_profile(), CancellationToken::new()), + ) + .await + .unwrap(); + assert_eq!(fixture.store.active_leases(), 1); + assert!(upstream.received_requests().await.unwrap().is_empty()); + drop(stream); + released(&fixture).await; + assert!(upstream.received_requests().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn polling_sends_the_frozen_profile_and_authorized_credential() { + let upstream = MockServer::start().await; + Mock::given(method("POST")).and(path("/v1internal:generateContent")) + .and(header("authorization", "Bearer fixture-access")) + .and(header("user-agent", "antigravity/cli/1.5.14 (aidev_client; os_type=linux; arch=amd64; auth_method=consumer)")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":{"responseId":"fixture-response","candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}]}}))) + .expect(1).mount(&upstream).await; + let fixture = Fixture::new(&upstream.uri()); + let stream = fixture + .provider + .clone() + .execute( + request(false), + context(frozen_profile(), CancellationToken::new()), + ) + .await + .unwrap(); + assert!(upstream.received_requests().await.unwrap().is_empty()); + let events = stream.try_collect::>().await.unwrap(); + assert!(events.iter().any(|event| event.has_client_event())); + released(&fixture).await; +} + +#[tokio::test] +async fn cancellation_before_poll_does_not_send_or_leak_the_lease() { + let upstream = MockServer::start().await; + let fixture = Fixture::new(&upstream.uri()); + let cancellation = CancellationToken::new(); + let mut stream = fixture + .provider + .clone() + .execute( + request(false), + context(frozen_profile(), cancellation.clone()), + ) + .await + .unwrap(); + cancellation.cancel(); + let error = stream.next().await.unwrap().expect_err("cancelled stream"); + assert_eq!(error.kind(), ProviderErrorKind::Cancelled); + assert_eq!(error.send_state(), UpstreamSendState::NotSent); + drop(stream); + released(&fixture).await; + assert!(upstream.received_requests().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn upstream_rejections_preserve_status_without_exposing_sensitive_diagnostics() { + for (status, kind, body, has_details) in [ + ( + 401, + ProviderErrorKind::Unauthorized, + "upstream-sensitive rejection", + true, + ), + ( + 429, + ProviderErrorKind::RateLimited, + "upstream-sensitive throttle", + true, + ), + ( + 429, + ProviderErrorKind::RateLimited, + "access_token=fixture-access", + false, + ), + ] { + let upstream = MockServer::start().await; + Mock::given(path("/v1internal:generateContent")) + .respond_with(ResponseTemplate::new(status).set_body_string(body)) + .expect(1) + .mount(&upstream) + .await; + let fixture = Fixture::new(&upstream.uri()); + let stream = fixture + .provider + .clone() + .execute( + request(false), + context(frozen_profile(), CancellationToken::new()), + ) + .await + .unwrap(); + let error = stream + .try_collect::>() + .await + .expect_err("upstream rejection"); + assert_eq!(error.kind(), kind); + assert_eq!(fixture.store.expired.load(Ordering::SeqCst), status == 401); + assert_eq!(error.upstream_status(), Some(status)); + assert_eq!(error.send_state(), UpstreamSendState::Sent); + let ordinary = format!("{error:?} {error}"); + assert!(!ordinary.contains("upstream-sensitive")); + assert!(!ordinary.contains("fixture-access")); + let details = error.error_details().unwrap_or_default(); + assert_eq!(details.contains("upstream-sensitive"), has_details); + assert!(!details.contains("fixture-access")); + released(&fixture).await; + } +} + +fn diagnostic_context(target: AccountProbeTarget) -> AttemptContext { + let request_context = RequestAttemptContext::new( + ModelRequestId::new("req_probe").unwrap(), + ClientApiKeyId::new("key_probe").unwrap(), + ); + AttemptContext::new( + request_context, + NonZeroU32::MIN, + SystemTime::now() + Duration::from_secs(5), + AccountSelectionPolicy::new(RotationStrategy::Smart, NonZeroU32::MIN), + AccountAttemptContext::diagnostic(Default::default(), target, None), + None, + CancellationToken::new(), + ) +} + +async fn mock_project(upstream: &MockServer) { + Mock::given(path("/v1internal:loadCodeAssist")) + .and(header("authorization", "Bearer fixture-access")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(json!({"cloudaicompanionProject":"probe-project"})), + ) + .expect(1) + .mount(upstream) + .await; +} + +#[tokio::test] +async fn disabled_account_probe_discovers_its_own_project_on_first_poll() { + let upstream = MockServer::start().await; + mock_project(&upstream).await; + Mock::given(path("/v1internal:generateContent")) + .and(header("authorization", "Bearer fixture-access")) + .and(body_partial_json(json!({"model":"fixture-model","project":"probe-project"}))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":{"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}]}}))) + .expect(1).mount(&upstream).await; + let fixture = Fixture::new(&upstream.uri()); + let selected = { + let mut loaded = fixture.store.primary().loaded.lock().unwrap(); + loaded.account = loaded.account.clone().with_account_facts( + false, + CredentialState::Ready, + QuotaState::unknown(), + None, + None, + ); + loaded.account.id().clone() + }; + fixture.store.primary().catalog.lock().unwrap().take(); + assert!( + fixture + .provider + .query_model_capabilities() + .await + .unwrap() + .is_empty() + ); + let ordinary = fixture + .provider + .clone() + .execute( + request(false), + context(frozen_profile(), CancellationToken::new()), + ) + .await; + assert!(matches!(ordinary, Err(error) if error.kind() == ProviderErrorKind::NoEligibleAccount)); + + let stream = fixture + .provider + .clone() + .execute( + request(false), + diagnostic_context(AccountProbeTarget::ConnectionTest(selected.clone())), + ) + .await + .unwrap(); + assert_eq!(stream.metadata().provider_account_id(), &selected); + assert_eq!(fixture.store.active_leases(), 1); + assert!(upstream.received_requests().await.unwrap().is_empty()); + let events = stream.try_collect::>().await.unwrap(); + assert!(events.iter().any(|event| event.has_client_event())); + released(&fixture).await; +} + +#[tokio::test] +async fn recovery_probe_does_not_mutate_credentials_cooldowns_or_scheduling_feedback() { + for (status, kind) in [ + (401, ProviderErrorKind::Unauthorized), + (429, ProviderErrorKind::RateLimited), + ] { + let upstream = MockServer::start().await; + mock_project(&upstream).await; + Mock::given(path("/v1internal:generateContent")) + .and(body_partial_json(json!({"project":"probe-project"}))) + .respond_with(ResponseTemplate::new(status).insert_header("retry-after", "30")) + .expect(1) + .mount(&upstream) + .await; + let fixture = Fixture::new(&upstream.uri()); + let account = fixture + .store + .primary() + .loaded + .lock() + .unwrap() + .account + .id() + .clone(); + let probe = diagnostic_context(AccountProbeTarget::FreezeRecovery(account.clone())); + let stream = fixture + .provider + .clone() + .execute(request(false), probe) + .await + .unwrap(); + let error = stream.try_collect::>().await.unwrap_err(); + assert_eq!(error.kind(), kind); + assert_eq!(error.upstream_status(), Some(status)); + assert!(!fixture.store.expired.load(Ordering::SeqCst)); + assert!(fixture.store.cooldowns.lock().unwrap().is_empty()); + assert_eq!( + fixture + .feedback + .scheduling_signals(&ProviderKind::new("antigravity").unwrap(), &account), + (None, None) + ); + released(&fixture).await; + } +} + +#[tokio::test] +async fn native_json_and_sse_meter_final_usage_with_requested_model_prices() { + use gateway_core::{ + engine::{ModelRequestId, RequestAttemptContext}, + event::{EventSequenceValidator, GatewayEvent}, + policy::ClientApiKeyId, + }; + use std::{collections::BTreeMap, sync::Arc}; + + for streaming in [false, true] { + let upstream = MockServer::start().await; + let response = json!({ + "modelVersion": "different-returned-version", + "candidates": [{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}], + "usageMetadata": { + "promptTokenCount":100,"toolUsePromptTokenCount":10, + "cachedContentTokenCount":20,"candidatesTokenCount":10, + "thoughtsTokenCount":30,"totalTokenCount":150 + } + }); + let (route, body, content_type) = if streaming { + ( + "/v1internal:streamGenerateContent", + format!( + "data: {}\n\ndata: {}\n\n", + json!({"response":{"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":6,"thoughtsTokenCount":10}}}), + json!({"response":response}) + ), + "text/event-stream", + ) + } else { + ( + "/v1internal:generateContent", + json!({"response":response}).to_string(), + "application/json", + ) + }; + Mock::given(path(route)) + .respond_with(ResponseTemplate::new(200).set_body_raw(body, content_type)) + .expect(1) + .mount(&upstream) + .await; + let fixture = Fixture::new(&upstream.uri()); + let attempt = RequestAttemptContext::new( + ModelRequestId::new("req_fixture").unwrap(), + ClientApiKeyId::new("key_fixture").unwrap(), + ) + .with_request_profile(Some(frozen_profile())) + .with_pricing(Arc::new(BTreeMap::from([( + "antigravity".into(), + BTreeMap::from([("fixture-model".into(), crate::billing_tests::pricing())]), + )]))); + let events = fixture + .provider + .clone() + .execute( + request(streaming), + crate::support::context_with_request(attempt, CancellationToken::new()), + ) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let mut validator = EventSequenceValidator::default(); + let mut costs = Vec::new(); + let mut observed = None; + for fact in events.iter().flat_map(|event| event.canonical_facts()) { + validator.observe(fact).unwrap(); + match fact { + GatewayEvent::CalculatedCost(cost) => costs.push(cost), + GatewayEvent::Usage(usage) => observed = Some(usage), + _ => {} + } + } + assert_eq!(costs.len(), 1); + assert_eq!(costs[0].total().amount().canonical(), "0.000765"); + let recalculated = crate::billing::calculate( + "unknown-model", + observed.unwrap(), + Some(&crate::billing_tests::pricing()), + ) + .unwrap(); + assert_eq!(costs[0].total(), recalculated.total_amount()); + assert_eq!(observed.unwrap().reasoning_output_tokens, Some(30)); + assert_eq!(observed.unwrap().output_tokens, Some(40)); + released(&fixture).await; + } +} + +#[tokio::test] +async fn rate_limit_feedback_uses_model_scope_and_the_full_upstream_retry_delay() { + let upstream = MockServer::start().await; + Mock::given(path("/v1internal:generateContent")).respond_with(ResponseTemplate::new(429) + .insert_header("retry-after", "2") + .set_body_json(json!({"error":{"code":429,"status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"90000.125s"}]}}))) + .expect(1).mount(&upstream).await; + let fixture = Fixture::new(&upstream.uri()); + let started = std::time::SystemTime::now(); + let stream = fixture + .provider + .clone() + .execute( + request(false), + context(frozen_profile(), CancellationToken::new()), + ) + .await + .unwrap(); + let error = stream.try_collect::>().await.unwrap_err(); + assert_eq!(error.retry_after(), Some(Duration::from_millis(90_000_125))); + { + let values = fixture.store.cooldowns.lock().unwrap(); + assert_eq!(values.len(), 1); + assert_eq!( + values[0].scope(), + &gateway_core::provider_ports::ProviderCooldownScope::upstream_model( + gateway_core::routing::UpstreamModelId::new("fixture-model").unwrap() + ) + ); + assert!(values[0].until() >= started + Duration::from_secs(90_000)); + } + released(&fixture).await; + assert!(!fixture.store.expired.load(Ordering::SeqCst)); + let blocked = fixture + .provider + .clone() + .execute( + request(false), + context(frozen_profile(), CancellationToken::new()), + ) + .await; + assert!(matches!(blocked, Err(e) if e.kind() == ProviderErrorKind::NoEligibleAccount)); +} + +#[tokio::test] +async fn translated_generation_delivers_terminal_wire_after_tail_usage() { + use gateway_core::{ + engine::provider::ProviderRequest, + event::GatewayEvent, + operation::{GenerateRequest, Operation, ProtocolPayload}, + }; + let upstream = MockServer::start().await; + Mock::given(method("POST")).and(path("/v1internal:streamGenerateContent")) + .and(header("user-agent", "antigravity/cli/1.5.14 (aidev_client; os_type=linux; arch=amd64; auth_method=consumer)")) + .and(body_partial_json(json!({"request":{"contents":[{"role":"user","parts":[{"text":"hello"}]}]}}))) + .respond_with(ResponseTemplate::new(200).set_body_raw(concat!( + "data: {\"response\":{\"responseId\":\"r\",\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"ok\"}]},\"finishReason\":\"STOP\"}]}}\n\n", + "data: {\"response\":{\"usageMetadata\":{\"promptTokenCount\":7,\"candidatesTokenCount\":2}}}\n\n" + ),"text/event-stream")).expect(2).mount(&upstream).await; + for (protocol, body) in [ + ( + "openai", + json!({"model":"fixture-model","input":"hello","max_output_tokens":100,"reasoning":{"effort":"none"},"text":{"format":{"type":"json_schema","schema":{"type":"object"}}}}), + ), + ( + "anthropic", + json!({"model":"fixture-model","messages":[{"role":"user","content":"hello"}],"max_tokens":100}), + ), + ] { + let fixture = Fixture::new(&upstream.uri()); + let operation = Operation::Generate(GenerateRequest::from_protocol_payload( + ProtocolPayload::json_object(protocol, body.as_object().unwrap().clone()).unwrap(), + )); + let request = ProviderRequest::new(operation, request(false).candidate().clone()); + let mut profile = crate::profile::ClientProfile::from_frozen(&frozen_profile()).unwrap(); + profile.system_prompt = "Frozen AGY prompt".into(); + let mut stream = fixture + .provider + .clone() + .execute(request, context(profile.frozen(), CancellationToken::new())) + .await + .unwrap(); + let mut output = Vec::new(); + while let Some(event) = stream.next().await { + let event = event.unwrap(); + let terminal = event + .canonical_facts() + .iter() + .any(|f| matches!(f, GatewayEvent::Completed(_))); + output.extend(stream.translate_native_response(event, terminal).unwrap()); + } + let last = output.last().unwrap(); + assert!( + last.canonical_facts() + .iter() + .any(|f| matches!(f, GatewayEvent::Completed(_))) + ); + let sent = upstream.received_requests().await.unwrap(); + let body: serde_json::Value = serde_json::from_slice(&sent.last().unwrap().body).unwrap(); + assert_eq!(body["request"]["generationConfig"]["maxOutputTokens"], 100); + assert_eq!( + body["request"]["systemInstruction"]["parts"][0]["text"], + "Frozen AGY prompt" + ); + assert!( + output + .iter() + .filter_map(|event| event.response_observation()) + .any(|observation| observation.timings().first_token_ms.is_some()) + ); + if protocol == "openai" { + assert_eq!( + body["request"]["generationConfig"]["thinkingConfig"]["thinkingBudget"], + 0 + ); + assert_eq!( + body["request"]["generationConfig"]["responseSchema"], + json!({"type":"object"}) + ); + } else { + assert_eq!( + output[0].wire_event().unwrap().data()["message"]["model"], + "fixture-model" + ); + } + let wire = last.wire_event().unwrap(); + assert_eq!(wire.protocol(), protocol); + if protocol == "openai" { + assert_eq!(wire.data()["type"], "response.completed"); + assert_eq!(wire.data()["response"]["usage"]["input_tokens"], 7); + } else { + assert_eq!(wire.data()["type"], "message_stop"); + assert!( + output + .iter() + .filter_map(|e| e.wire_event()) + .any(|w| w.data()["usage"]["input_tokens"] == 7) + ); + } + drop(stream); + released(&fixture).await; + } +} diff --git a/backend/crates/providers/antigravity/tests/provider/headers.rs b/backend/crates/providers/antigravity/tests/provider/headers.rs new file mode 100644 index 000000000..ad3f6d99e --- /dev/null +++ b/backend/crates/providers/antigravity/tests/provider/headers.rs @@ -0,0 +1,141 @@ +//! 实际上游请求保留业务头的多值字节,账号和传输字段由 AGY 重新构造 + +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use futures::TryStreamExt; +use gateway_core::{ + engine::provider::{Provider, ProviderRequest}, + operation::{Operation, RawJsonPayload, TokenCountRequest}, +}; +use serde_json::json; +use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path}; + +use crate::support::{Fixture, context, request}; + +#[tokio::test] +async fn native_and_translated_requests_forward_business_headers_with_account_identity() { + let server = MockServer::start().await; + let fixture = Fixture::new(&server.uri()); + let profile = crate::profile::default_profile( + &crate::profile::ReleaseService::new(crate::support::profile::cache()).unwrap(), + ) + .frozen(); + let ctx = || { + context( + profile.clone(), + gateway_core::lifecycle::CancellationToken::new(), + ) + }; + let reply = json!({"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}]}}); + for (route, body, media) in [ + ("generateContent", reply.to_string(), "application/json"), + ( + "streamGenerateContent", + format!("data: {reply}\n\n"), + "text/event-stream", + ), + ( + "countTokens", + json!({"totalTokens":2}).to_string(), + "application/json", + ), + ] { + Mock::given(path(format!("/v1internal:{route}"))) + .respond_with(ResponseTemplate::new(200).set_body_raw(body, media)) + .mount(&server) + .await; + } + let forbidden = [ + "authorization", + "cookie", + "cookie2", + "user-agent", + "x-goog-api-key", + "x-goog-user-project", + "x-goog-api-client", + "content-encoding", + "content-length", + "x-request-id", + "chatgpt-account-id", + "x-oai-attestation", + ]; + let mut headers: Vec<_> = forbidden + .iter() + .map(|name| json!([name, STANDARD.encode("forbidden")])) + .collect(); + headers.extend([ + json!(["x-business-extension", STANDARD.encode(b"first\x80")]), + json!(["x-business-extension", STANDARD.encode("second")]), + json!(["traceparent", STANDARD.encode("original-trace")]), + ]); + let metadata = json!({"opaque_request_headers":headers}); + for (protocol, body) in [ + ( + gateway_protocol::genai::GENAI_PROTOCOL, + json!({"contents":[]}), + ), + ( + gateway_protocol::openai::OPENAI_PROTOCOL, + json!({"input":[]}), + ), + ( + gateway_protocol::anthropic::ANTHROPIC_PROTOCOL, + json!({"messages":[]}), + ), + ] { + let input = super::affinity::session_request(protocol, body, metadata.clone()); + fixture + .provider + .clone() + .execute(input, ctx()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + } + let input = ProviderRequest::new( + Operation::CountTokens(TokenCountRequest::from_raw_json( + RawJsonPayload::new( + gateway_protocol::genai::GENAI_PROTOCOL, + br#"{"contents":[]}"#.as_slice().into(), + ) + .unwrap() + .with_context(metadata.as_object().unwrap().clone()), + )), + request(false).candidate().clone(), + ); + fixture + .provider + .clone() + .execute(input, ctx()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let requests = server.received_requests().await.unwrap(); + assert_eq!(requests.len(), 4); + for request in requests { + let values: Vec<_> = request + .headers + .get_all("x-business-extension") + .iter() + .map(|value| value.as_bytes()) + .collect(); + assert_eq!(values, vec![b"first\x80".as_slice(), b"second"]); + assert_eq!(request.headers["traceparent"], "original-trace"); + assert_eq!(request.headers["authorization"], "Bearer fixture-access"); + assert_eq!(request.headers["content-type"], "application/json"); + assert!( + request.headers["user-agent"] + .to_str() + .unwrap() + .starts_with("antigravity/hub/") + ); + for name in forbidden { + if !matches!(name, "authorization" | "user-agent" | "content-length") { + assert!(!request.headers.contains_key(name), "unexpected {name}"); + } + } + } +} diff --git a/backend/crates/providers/antigravity/tests/provider/middleware.rs b/backend/crates/providers/antigravity/tests/provider/middleware.rs new file mode 100644 index 000000000..5dd89bc10 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/provider/middleware.rs @@ -0,0 +1,135 @@ +//! Attempt 中间件业务头不得替换认证或冻结身份,也不能使上游业务提前发送 + +use bytes::Bytes; +use futures::{StreamExt, TryStreamExt, future::BoxFuture}; +use gateway_core::{ + engine::{ + ModelRequestId, RequestAttemptContext, + execution::ClientTransport, + middleware::{ + FrozenMiddlewarePlan, MiddlewareContext, MiddlewareError, MiddlewareHeader, + MiddlewareNext, MiddlewarePlan, MiddlewareRequest, MiddlewareResponse, + }, + provider::Provider, + }, + error::ProviderErrorKind, + lifecycle::CancellationToken, + policy::ClientApiKeyId, + routing::extensions::{ExtensionSetId, ExtensionSetLease, ExtensionSetReference}, + upstream::UpstreamSendState, +}; +use serde_json::json; +use std::sync::Arc; +use wiremock::{ + Mock, MockServer, ResponseTemplate, + matchers::{header, path}, +}; + +use crate::{ + profile::{self, ReleaseService, Selection}, + support::{Fixture, context_with_request, request}, +}; + +#[derive(Debug)] +struct Headers; + +impl ExtensionSetLease for Headers { + fn is_ready(&self) -> bool { + true + } +} + +impl MiddlewarePlan for Headers { + fn handle( + &self, + _context: MiddlewareContext, + request: MiddlewareRequest, + next: MiddlewareNext, + ) -> BoxFuture<'static, Result> { + let protocol = request.protocol().to_owned(); + let body = request.body().clone(); + let headers = vec![ + MiddlewareHeader::new("x-fixture-business", Bytes::from_static(b"preserved")), + MiddlewareHeader::new("Authorization", Bytes::from_static(b"Bearer forbidden")), + MiddlewareHeader::new("User-Agent", Bytes::from_static(b"forbidden-agent")), + ]; + next.run( + request + .replace_parts(protocol, headers, body, None) + .unwrap(), + ) + } +} + +#[tokio::test] +async fn middleware_business_headers_survive_without_overriding_frozen_authentication() { + let upstream = MockServer::start().await; + let fixture = Fixture::new(&upstream.uri()); + let profile = profile::resolve( + &Selection::default().configuration(), + &ReleaseService::new(crate::support::profile::cache()).unwrap(), + ) + .unwrap(); + Mock::given(path("/v1internal:generateContent")) + .and(header("x-fixture-business", "preserved")) + .and(header("authorization", "Bearer fixture-access")) + .and(header("user-agent", profile.user_agent().as_str())) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}]}}))) + .expect(1) + .mount(&upstream).await; + let middleware = Arc::new(Headers); + let plan = FrozenMiddlewarePlan::new( + middleware.clone(), + ExtensionSetReference::new(ExtensionSetId::new("fixture".into()).unwrap(), middleware), + ); + let request_context = RequestAttemptContext::new( + ModelRequestId::new("req_fixture").unwrap(), + ClientApiKeyId::new("key_fixture").unwrap(), + ) + .with_request_profile(Some(profile.frozen())) + .with_middleware( + Some(plan), + Arc::from([]), + "/v1beta/models/fixture-model:generateContent".into(), + ClientTransport::HttpSse, + ); + let stream = fixture + .provider + .clone() + .execute( + request(false), + context_with_request(request_context.clone(), CancellationToken::new()), + ) + .await + .unwrap(); + assert!(upstream.received_requests().await.unwrap().is_empty()); + drop(stream); + assert!(upstream.received_requests().await.unwrap().is_empty()); + let cancellation = CancellationToken::new(); + let mut stream = fixture + .provider + .clone() + .execute( + request(false), + context_with_request(request_context.clone(), cancellation.clone()), + ) + .await + .unwrap(); + cancellation.cancel(); + let error = stream.next().await.unwrap().unwrap_err(); + assert_eq!(error.kind(), ProviderErrorKind::Cancelled); + assert_eq!(error.send_state(), UpstreamSendState::NotSent); + drop(stream); + assert!(upstream.received_requests().await.unwrap().is_empty()); + let stream = fixture + .provider + .clone() + .execute( + request(false), + context_with_request(request_context, CancellationToken::new()), + ) + .await + .unwrap(); + let events: Vec<_> = stream.try_collect().await.unwrap(); + assert!(events.iter().any(|event| event.has_client_event())); +} diff --git a/backend/crates/providers/antigravity/tests/provider/mod.rs b/backend/crates/providers/antigravity/tests/provider/mod.rs new file mode 100644 index 000000000..bfa9dfcfe --- /dev/null +++ b/backend/crates/providers/antigravity/tests/provider/mod.rs @@ -0,0 +1,8 @@ +//! Provider 真实执行合同测试 + +mod affinity; +mod execution; +mod headers; +mod middleware; +mod round_robin; +mod selection; diff --git a/backend/crates/providers/antigravity/tests/provider/round_robin.rs b/backend/crates/providers/antigravity/tests/provider/round_robin.rs new file mode 100644 index 000000000..257d8a9c2 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/provider/round_robin.rs @@ -0,0 +1,370 @@ +//! 验证轮询分配与亲和认领的原子性,以及排队、分流和插件选号的游标边界 + +use super::affinity::session_request; +use crate::support::{Fixture, context_with_scope, request}; +use futures::future::BoxFuture; +use gateway_core::{ + account::{ + AccountAffinity, AccountSelectionPolicy, PlaintextCredential, ProviderAccountId, + ProviderAccountStore, RotationStrategy, + }, + concurrency::ConcurrencyQueuePolicy, + engine::{ + AttemptContext, ModelRequestId, RequestAttemptContext, + policy::{ + AccountScheduleDecision, AccountScheduleInput, ModelRouteDecision, ModelRouteInput, + RequestPolicyContext, RequestPolicyFault, RequestPolicyPlan, + }, + provider::{Provider, ProviderRequest, ProviderStream}, + }, + error::ProviderErrorKind, + lifecycle::CancellationToken, + policy::ClientApiKeyId, + routing::extensions::{ExtensionSetId, ExtensionSetLease, ExtensionSetReference}, +}; +use serde_json::json; +use std::{ + num::NonZeroU32, + sync::{Arc, atomic::Ordering}, + time::Duration, +}; + +fn context(fixture: &Fixture, mode: AccountAffinity, max_concurrent: u32) -> AttemptContext { + context_with_scope( + RequestAttemptContext::new( + ModelRequestId::new("req_round_robin").unwrap(), + ClientApiKeyId::new("key_fixture").unwrap(), + ), + AccountSelectionPolicy::new( + RotationStrategy::RoundRobin, + NonZeroU32::new(max_concurrent).unwrap(), + ) + .with_account_affinity(mode) + .with_queue(ConcurrencyQueuePolicy { + max_waiting: 1, + timeout: Duration::from_secs(3), + }), + CancellationToken::new(), + fixture.store.account_scope(), + ) +} + +fn session(session: Option<&str>) -> ProviderRequest { + session.map_or_else( + || request(false), + |session| { + session_request( + gateway_protocol::genai::GENAI_PROTOCOL, + json!({"contents":[{"parts":[{"text":"hello"}]}]}), + json!({"headers":{"x-http-session-id":session}}), + ) + }, + ) +} + +async fn select(fixture: &Fixture, key: Option<&str>, mode: AccountAffinity) -> ProviderStream { + fixture + .provider + .clone() + .execute(session(key), context(fixture, mode, 1)) + .await + .unwrap() +} + +fn cursor(fixture: &Fixture) -> u64 { + fixture + .store + .assignment_cursors + .lock() + .unwrap() + .get(&ClientApiKeyId::new("key_fixture").unwrap()) + .copied() + .unwrap_or_default() +} + +#[tokio::test] +async fn affinity_hits_leave_the_next_new_session_its_turn() { + for mode in [AccountAffinity::Strict, AccountAffinity::Preferred] { + let fixture = Fixture::with_two_accounts("http://127.0.0.1:1"); + for _ in 0..4 { + let stream = select(&fixture, Some("session-a"), mode).await; + assert_eq!( + stream.metadata().provider_account_id().as_str(), + "acct_fixture" + ); + drop(stream); + assert_eq!(cursor(&fixture), 1); + } + let next = select(&fixture, Some("session-b"), mode).await; + assert_eq!( + next.metadata().provider_account_id().as_str(), + "acct_standby" + ); + assert_eq!(cursor(&fixture), 2); + drop(next); + assert_eq!(fixture.store.active_leases(), 0); + } +} + +#[tokio::test] +async fn preferred_spillover_keeps_the_cursor_and_migration_advances_it() { + let fixture = Fixture::with_two_accounts("http://127.0.0.1:1"); + let mode = AccountAffinity::Preferred; + let holder = select(&fixture, Some("session-a"), mode).await; + let primary = holder.metadata().provider_account_id().clone(); + let overflow = select(&fixture, Some("session-a"), mode).await; + let spare = overflow.metadata().provider_account_id().clone(); + assert_ne!(spare, primary); + assert_eq!(cursor(&fixture), 1); + drop((holder, overflow)); + assert_eq!( + select(&fixture, Some("session-a"), mode) + .await + .metadata() + .provider_account_id(), + &primary + ); + assert_eq!(cursor(&fixture), 1); + + fixture.store.set_enabled(&primary, false).await.unwrap(); + assert_eq!( + select(&fixture, Some("session-a"), mode) + .await + .metadata() + .provider_account_id(), + &spare + ); + assert_eq!(cursor(&fixture), 2); + fixture.store.set_enabled(&primary, true).await.unwrap(); + assert_eq!( + select(&fixture, Some("session-a"), mode) + .await + .metadata() + .provider_account_id(), + &spare + ); + assert_eq!(cursor(&fixture), 2); + assert_eq!(fixture.store.active_leases(), 0); +} + +#[tokio::test] +async fn queue_rechecks_do_not_advance_until_a_new_assignment_is_admitted() { + for bound in [false, true] { + let fixture = Fixture::with_two_accounts("http://127.0.0.1:1"); + let mode = AccountAffinity::Strict; + let holder = select(&fixture, Some("session-a"), mode).await; + let spare = select(&fixture, Some("session-b"), mode).await; + let reads = fixture.store.scheduling_reads.load(Ordering::SeqCst); + let waiting = select( + &fixture, + Some(if bound { "session-a" } else { "session-c" }), + mode, + ); + tokio::pin!(waiting); + assert!( + tokio::time::timeout(Duration::from_millis(350), &mut waiting) + .await + .is_err() + ); + assert!(fixture.store.scheduling_reads.load(Ordering::SeqCst) > reads + 1); + assert_eq!(cursor(&fixture), 2); + drop(holder); + let resumed = waiting.await; + assert_eq!( + resumed.metadata().provider_account_id().as_str(), + "acct_fixture" + ); + assert_eq!(cursor(&fixture), if bound { 2 } else { 3 }); + drop((resumed, spare)); + assert_eq!(fixture.store.active_leases(), 0); + } +} + +#[tokio::test] +async fn concurrent_first_claims_commit_only_the_winning_snapshot() { + for same_session in [true, false] { + let fixture = Fixture::with_two_accounts("http://127.0.0.1:1"); + *fixture.store.admission_barrier.lock().unwrap() = + Some(Arc::new(tokio::sync::Barrier::new(2))); + let execute = |key| { + fixture.provider.clone().execute( + session(Some(key)), + context(&fixture, AccountAffinity::Strict, 2), + ) + }; + let (first, second) = tokio::time::timeout(Duration::from_secs(3), async { + tokio::join!( + execute("session-a"), + execute(if same_session { + "session-a" + } else { + "session-b" + }) + ) + }) + .await + .unwrap(); + let first = first.unwrap(); + let second = second.unwrap(); + assert_eq!( + first.metadata().provider_account_id() == second.metadata().provider_account_id(), + same_session + ); + let assignments = if same_session { 1 } else { 2 }; + assert_eq!(cursor(&fixture), assignments); + assert_eq!( + fixture.store.bindings.lock().unwrap().len() as u64, + assignments + ); + assert_eq!(fixture.store.claims.load(Ordering::SeqCst), 3); + assert_eq!(fixture.store.active_leases(), 2); + drop((first, second)); + assert_eq!(fixture.store.active_leases(), 0); + } +} + +#[tokio::test] +async fn relaxed_and_sessionless_requests_rotate_only_after_admission() { + for key in [None, Some("session-a")] { + let fixture = Fixture::with_two_accounts("http://127.0.0.1:1"); + fixture + .store + .reject_next_claim + .store(true, Ordering::SeqCst); + for (index, expected) in ["acct_fixture", "acct_standby", "acct_fixture"] + .iter() + .enumerate() + { + let stream = select(&fixture, key, AccountAffinity::Relaxed).await; + assert_eq!(stream.metadata().provider_account_id().as_str(), *expected); + assert_eq!(cursor(&fixture), index as u64 + 1); + drop(stream); + } + assert_eq!(fixture.store.claims.load(Ordering::SeqCst), 4); + assert_eq!( + fixture.store.bindings.lock().unwrap().len(), + usize::from(key.is_some()) + ); + assert_eq!(fixture.store.active_leases(), 0); + } +} + +#[tokio::test] +async fn credential_validation_failure_releases_the_lease_without_committing() { + let fixture = Fixture::with_two_accounts("http://127.0.0.1:1"); + let original = { + let mut loaded = fixture.store.primary().loaded.lock().unwrap(); + std::mem::replace( + &mut loaded.credential, + PlaintextCredential::new(Default::default()), + ) + }; + let error = fixture + .provider + .clone() + .execute( + session(Some("session-a")), + context(&fixture, AccountAffinity::Strict, 1), + ) + .await + .err() + .unwrap(); + assert_eq!( + error.kind(), + ProviderErrorKind::ProviderInfrastructureUnavailable + ); + assert_eq!(fixture.store.claims.load(Ordering::SeqCst), 0); + assert!(fixture.store.bindings.lock().unwrap().is_empty()); + assert_eq!(cursor(&fixture), 0); + assert_eq!(fixture.store.active_leases(), 0); + + fixture.store.primary().loaded.lock().unwrap().credential = original; + let stream = select(&fixture, Some("session-a"), AccountAffinity::Strict).await; + assert_eq!( + stream.metadata().provider_account_id().as_str(), + "acct_fixture" + ); + assert_eq!(cursor(&fixture), 1); + drop(stream); + assert_eq!(fixture.store.active_leases(), 0); +} + +#[derive(Debug)] +struct SelectionPolicy(bool); + +impl ExtensionSetLease for SelectionPolicy { + fn is_ready(&self) -> bool { + true + } +} + +impl RequestPolicyPlan for SelectionPolicy { + fn route_model( + &self, + _: ModelRouteInput, + ) -> BoxFuture<'static, Result> { + unreachable!("unused routing hook") + } + + fn schedule_account( + &self, + _: AccountScheduleInput, + ) -> BoxFuture<'static, Result> { + let decision = if self.0 { + AccountScheduleDecision::Pick(ProviderAccountId::new("acct_standby").unwrap()) + } else { + AccountScheduleDecision::Delegate + }; + Box::pin(async move { Ok(decision) }) + } +} + +#[tokio::test] +async fn explicit_plugin_selection_keeps_the_cursor_while_delegation_rotates() { + for explicit in [true, false] { + let fixture = Fixture::with_two_accounts("http://127.0.0.1:1"); + let plan = Arc::new(SelectionPolicy(explicit)); + let id = ModelRequestId::new("req_round_robin").unwrap(); + let key = ClientApiKeyId::new("key_fixture").unwrap(); + let policy = RequestPolicyContext::new( + plan.clone(), + ExtensionSetReference::new(ExtensionSetId::new("fixture".into()).unwrap(), plan), + id.clone(), + key.clone(), + vec![], + ); + let ctx = context_with_scope( + RequestAttemptContext::new(id, key).with_request_policy(Some(policy)), + AccountSelectionPolicy::new(RotationStrategy::RoundRobin, NonZeroU32::MIN), + CancellationToken::new(), + fixture.store.account_scope(), + ); + let stream = fixture + .provider + .clone() + .execute(session(Some("session-a")), ctx) + .await + .unwrap(); + assert_eq!( + stream.metadata().provider_account_id().as_str(), + if explicit { + "acct_standby" + } else { + "acct_fixture" + } + ); + assert_eq!(cursor(&fixture), u64::from(!explicit)); + drop(stream); + let next = select(&fixture, Some("session-b"), AccountAffinity::Strict).await; + assert_eq!( + next.metadata().provider_account_id().as_str(), + if explicit { + "acct_fixture" + } else { + "acct_standby" + } + ); + drop(next); + assert_eq!(fixture.store.active_leases(), 0); + } +} diff --git a/backend/crates/providers/antigravity/tests/provider/selection.rs b/backend/crates/providers/antigravity/tests/provider/selection.rs new file mode 100644 index 000000000..5aa131582 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/provider/selection.rs @@ -0,0 +1,224 @@ +//! 验证并发已满的账号参与有界排队,取消或超时后归还队位 + +use crate::support::{Fixture, context_with_policy, context_with_request, request}; +use futures::future::BoxFuture; +use gateway_core::{ + account::{AccountSelectionPolicy, RotationStrategy}, + concurrency::{ConcurrencyQueuePolicy, ConcurrencyWaitBudget}, + engine::{ + ModelRequestId, RequestAttemptContext, + policy::{ + AccountScheduleDecision, AccountScheduleInput, ModelRouteDecision, ModelRouteInput, + RequestPolicyContext, RequestPolicyFault, RequestPolicyPlan, + }, + provider::{Provider, ProviderStream}, + }, + error::{ProviderError, ProviderErrorKind}, + lifecycle::CancellationToken, + policy::ClientApiKeyId, + routing::extensions::{ExtensionSetId, ExtensionSetLease, ExtensionSetReference}, + upstream::UpstreamSendState, +}; +use std::{num::NonZeroU32, sync::Arc, time::Duration}; + +async fn acquire( + fixture: &Fixture, + max_waiting: u32, + timeout: Duration, + budget: ConcurrencyWaitBudget, + cancellation: CancellationToken, +) -> Result { + let policy = AccountSelectionPolicy::new(RotationStrategy::Smart, NonZeroU32::MIN).with_queue( + ConcurrencyQueuePolicy { + max_waiting, + timeout, + }, + ); + let attempt = RequestAttemptContext::new( + ModelRequestId::new("req_fixture").unwrap(), + ClientApiKeyId::new("key_fixture").unwrap(), + ) + .with_concurrency_wait_budget(budget); + fixture + .provider + .clone() + .execute( + request(false), + context_with_policy(attempt, policy, cancellation), + ) + .await +} + +#[tokio::test] +async fn saturated_account_reports_capacity_and_releases_cancelled_queue_position() { + let fixture = Fixture::new("http://127.0.0.1:1"); + let attempt = |max_waiting, cancellation| { + acquire( + &fixture, + max_waiting, + Duration::from_secs(2), + Default::default(), + cancellation, + ) + }; + let holder = attempt(0, CancellationToken::new()).await.unwrap(); + let error = attempt(0, CancellationToken::new()).await.err().unwrap(); + assert_eq!(error.kind(), ProviderErrorKind::AccountCapacityUnavailable); + assert_eq!(error.send_state(), UpstreamSendState::NotSent); + + let cancelled = CancellationToken::new(); + let waiter = attempt(1, cancelled.clone()); + tokio::pin!(waiter); + assert!(futures::poll!(&mut waiter).is_pending()); + let full = attempt(1, CancellationToken::new()).await.err().unwrap(); + assert_eq!(full.kind(), ProviderErrorKind::ConcurrencyQueueFull); + cancelled.cancel(); + assert_eq!( + waiter.await.err().unwrap().kind(), + ProviderErrorKind::Cancelled + ); + + let next = attempt(1, CancellationToken::new()); + tokio::pin!(next); + assert!(futures::poll!(&mut next).is_pending()); + drop(holder); + let newcomer = attempt(0, CancellationToken::new()).await.err().unwrap(); + assert_eq!( + newcomer.kind(), + ProviderErrorKind::AccountCapacityUnavailable + ); + let stream = next.await.unwrap(); + let observation = stream.metadata().selection_observation().unwrap(); + assert!(observation.account_selection_wait_ms() > 0); + let capacity = observation.capacity().unwrap(); + assert_eq!((capacity.used_slots(), capacity.total_slots()), (1, 1)); +} + +#[tokio::test] +async fn repeated_selection_uses_the_original_account_wait_deadline() { + let fixture = Fixture::new("http://127.0.0.1:1"); + let holder = acquire( + &fixture, + 0, + Duration::ZERO, + Default::default(), + CancellationToken::new(), + ) + .await + .unwrap(); + let budget = ConcurrencyWaitBudget::default(); + let queued = |duration| { + acquire( + &fixture, + 1, + duration, + budget.clone(), + CancellationToken::new(), + ) + }; + let first = queued(Duration::from_millis(15)).await.err().unwrap(); + assert_eq!(first.kind(), ProviderErrorKind::ConcurrencyQueueTimeout); + let second = tokio::time::timeout(Duration::from_secs(1), queued(Duration::from_secs(30))) + .await + .expect("an expired wait budget cannot restart") + .err() + .unwrap(); + assert_eq!(second.kind(), ProviderErrorKind::ConcurrencyQueueTimeout); + drop(holder); +} + +#[derive(Debug)] +struct FilterAll; + +impl ExtensionSetLease for FilterAll { + fn is_ready(&self) -> bool { + true + } +} + +impl RequestPolicyPlan for FilterAll { + fn route_model( + &self, + _: ModelRouteInput, + ) -> BoxFuture<'static, Result> { + unreachable!("unused routing hook") + } + + fn schedule_account( + &self, + input: AccountScheduleInput, + ) -> BoxFuture<'static, Result> { + Box::pin(async move { + let excluded = input + .candidates() + .iter() + .map(|candidate| candidate.account_id().clone()) + .collect(); + Ok(AccountScheduleDecision::DelegateFiltered(excluded)) + }) + } +} + +#[tokio::test] +async fn policy_filtering_a_busy_account_returns_the_policy_diagnostic() { + let fixture = Fixture::new("http://127.0.0.1:1"); + let holder = acquire( + &fixture, + 0, + Duration::ZERO, + Default::default(), + CancellationToken::new(), + ) + .await + .unwrap(); + let filter = Arc::new(FilterAll); + let id = ModelRequestId::new("req_fixture").unwrap(); + let key = ClientApiKeyId::new("key_fixture").unwrap(); + let policy = RequestPolicyContext::new( + filter.clone(), + ExtensionSetReference::new(ExtensionSetId::new("fixture".into()).unwrap(), filter), + id.clone(), + key.clone(), + vec![], + ); + let attempt = RequestAttemptContext::new(id, key).with_request_policy(Some(policy)); + let error = fixture + .provider + .clone() + .execute( + request(false), + context_with_request(attempt, CancellationToken::new()), + ) + .await + .err() + .unwrap(); + assert_eq!(error.kind(), ProviderErrorKind::RequestPolicyDenied); + assert_eq!( + error.diagnostic().unwrap().code(), + Some("account_policy_filtered") + ); + drop(holder); +} + +#[tokio::test] +async fn wakeup_rechecks_model_access_before_issuing_a_lease() { + let fixture = Fixture::new("http://127.0.0.1:1"); + let attempt = |max_waiting| { + acquire( + &fixture, + max_waiting, + Duration::from_secs(2), + Default::default(), + CancellationToken::new(), + ) + }; + let holder = attempt(0).await.unwrap(); + let waiter = attempt(1); + tokio::pin!(waiter); + assert!(futures::poll!(&mut waiter).is_pending()); + fixture.store.primary().catalog.lock().unwrap().take(); + drop(holder); + let error = waiter.await.err().unwrap(); + assert_eq!(error.kind(), ProviderErrorKind::NoEligibleAccount); + assert_eq!(error.send_state(), UpstreamSendState::NotSent); +} diff --git a/backend/crates/providers/antigravity/tests/support/mod.rs b/backend/crates/providers/antigravity/tests/support/mod.rs new file mode 100644 index 000000000..051cbe24d --- /dev/null +++ b/backend/crates/providers/antigravity/tests/support/mod.rs @@ -0,0 +1,397 @@ +//! 共享内存账号、目录、租约与原生请求上下文 + +mod ports; +pub(crate) mod profile; + +use crate::{ + credential::catalog::CatalogService, + credential::{CredentialService, GoogleOAuth}, + profile::ReleaseService, + provider::AntigravityProvider, +}; +use futures::future::BoxFuture; +use gateway_core::{ + account::{ + AccountCatalogObservation, AccountSelectionPolicy, CredentialRevision, CredentialState, + LoadedCredential, OpaqueProviderData, PlaintextCredential, ProviderAccount, + ProviderAccountId, QuotaState, RotationStrategy, + }, + engine::{ + AccountAttemptContext, AttemptContext, ModelRequestId, RequestAttemptContext, + provider::ProviderRequest, + }, + lifecycle::CancellationToken, + operation::{GenerateRequest, Operation, ProtocolPayload}, + policy::ClientApiKeyId, + provider_ports::{ProviderLeaseGuard, ProviderStoreError, ProviderStorePorts}, + routing::{ + ClientRoutingScope, ConfigRevision, FrozenAccountScope, ModelCapabilities, ProviderKind, + ProviderModel, PublicModelId, RoutingContext, RuntimeAccount, RuntimeAccountDirectory, + RuntimeSnapshot, UpstreamModelId, + }, + settings::SettingsValues, +}; +use gateway_protocol::genai::GENAI_PROTOCOL; +use serde_json::json; +use std::{ + collections::{BTreeMap, BTreeSet}, + num::NonZeroU32, + sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, + }, + time::{Duration, SystemTime}, +}; + +const PRIMARY_ACCOUNT: &str = "acct_fixture"; + +pub(crate) struct MemoryPorts { + pub(crate) bindings: Mutex< + BTreeMap< + gateway_core::provider_ports::ProviderSessionAffinityKey, + ( + gateway_core::provider_ports::ProviderSessionBinding, + Duration, + ), + >, + >, + pub(crate) reject_next_claim: std::sync::atomic::AtomicBool, + pub(crate) claims: AtomicUsize, + pub(crate) scheduling_reads: AtomicUsize, + pub(crate) assignment_cursors: Mutex>, + pub(crate) admission_barrier: Mutex>>, + pub(crate) request_profile: Mutex>, + accounts: BTreeMap, + refresh_leases: Arc, + pub(crate) cooldowns: Mutex>, + pub(crate) expired: std::sync::atomic::AtomicBool, +} + +pub(crate) struct MemoryAccount { + pub(crate) loaded: Mutex, + pub(crate) catalog: Mutex>, + active_leases: Arc, + pub(crate) quota: Mutex>, +} + +impl MemoryPorts { + pub(crate) fn primary(&self) -> &MemoryAccount { + &self.accounts[&ProviderAccountId::new(PRIMARY_ACCOUNT).unwrap()] + } + + pub(crate) fn active_leases(&self) -> usize { + self.refresh_leases.load(Ordering::SeqCst) + + self + .accounts + .values() + .map(|account| account.active_leases.load(Ordering::SeqCst)) + .sum::() + } + + pub(crate) fn account_scope(&self) -> Arc { + account_scope(self.accounts.keys().cloned()) + } +} + +struct Lease(Arc); +impl Drop for Lease { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::SeqCst); + } +} +impl ProviderLeaseGuard for Lease { + fn release(self: Box) -> BoxFuture<'static, Result<(), ProviderStoreError>> { + Box::pin(async move { + drop(self); + Ok(()) + }) + } +} + +pub(crate) struct Fixture { + pub(crate) provider: Arc, + pub(crate) catalog: Arc, + pub(crate) store: Arc, + pub(crate) feedback: Arc, + pub(crate) quota: Arc, +} + +impl Fixture { + pub(crate) fn new(origin: &str) -> Self { + Self::with_accounts(origin, &["fixture"]) + } + + pub(crate) fn with_two_accounts(origin: &str) -> Self { + Self::with_accounts(origin, &["fixture", "standby"]) + } + + fn with_accounts(origin: &str, names: &[&str]) -> Self { + let kind = ProviderKind::new("antigravity").unwrap(); + let oauth = Arc::new(GoogleOAuth::for_provider().unwrap()); + let accounts = names + .iter() + .map(|name| { + let id = ProviderAccountId::new(format!("acct_{name}")).unwrap(); + let subject = format!("{name}-subject"); + let account = ProviderAccount::new( + id.clone(), + kind.clone(), + "Fixture".into(), + Some(subject.clone()), + "oauth".into(), + CredentialRevision::new(1).unwrap(), + Some(SystemTime::now() + Duration::from_secs(3600)), + ) + .with_account_facts( + true, + CredentialState::Ready, + QuotaState::unknown(), + None, + None, + ); + let observation = AccountCatalogObservation { + account_id: id.clone(), + revision: account.revision(), + plan: None, + etag: Some(oauth.registration()), + observed_at: SystemTime::now(), + }; + let material = json!({ + "registration": oauth.registration(), + "subject": subject, + "access_token": format!("{name}-access"), + "refresh_token": format!("{name}-refresh"), + "scopes": ["fixture-resource"] + }); + let catalog = json!({ + "project": format!("{name}-project"), + "models": {"fixture-model": {"displayName": "Fixture Model"}} + }); + ( + id, + MemoryAccount { + loaded: Mutex::new(LoadedCredential { + account, + credential: PlaintextCredential::new( + material.as_object().unwrap().clone(), + ), + }), + catalog: Mutex::new(Some(( + observation, + bytes::Bytes::from(serde_json::to_vec(&catalog).unwrap()), + ))), + active_leases: Arc::new(AtomicUsize::new(0)), + quota: Mutex::new(None), + }, + ) + }) + .collect(); + let store = Arc::new(MemoryPorts { + bindings: Mutex::new(BTreeMap::new()), + reject_next_claim: Default::default(), + claims: AtomicUsize::new(0), + scheduling_reads: AtomicUsize::new(0), + assignment_cursors: Mutex::new(BTreeMap::new()), + admission_barrier: Mutex::new(None), + request_profile: Mutex::new(None), + accounts, + refresh_leases: Arc::new(AtomicUsize::new(0)), + cooldowns: Mutex::new(Vec::new()), + expired: Default::default(), + }); + let ports = ProviderStorePorts::new( + store.clone(), + store.clone(), + store.clone(), + store.clone(), + store.clone(), + store.clone(), + store.clone(), + store.clone(), + store.clone(), + store.clone(), + store.clone(), + ); + let release = Arc::new(ReleaseService::new(crate::support::profile::cache()).unwrap()); + let credentials = Arc::new(CredentialService::new( + kind.clone(), + &ports, + oauth.clone(), + release.clone(), + )); + let origin: url::Url = origin.parse().unwrap(); + let catalog = Arc::new(CatalogService::new( + kind.clone(), + store.clone(), + credentials.clone(), + oauth.registration(), + origin.clone(), + release.clone(), + )); + let quota = Arc::new(crate::credential::quota::QuotaService::new( + kind.clone(), + store.clone(), + credentials.clone(), + catalog.clone(), + release.clone(), + origin.clone(), + )); + let provider = Arc::new(AntigravityProvider::new( + kind, + &ports, + credentials, + catalog.clone(), + quota.clone(), + release, + origin, + )); + Self { + provider, + catalog, + store, + feedback: ports.account_feedback(), + quota, + } + } +} + +fn account_scope(accounts: impl IntoIterator) -> Arc { + let kind = ProviderKind::new("antigravity").unwrap(); + Arc::new(FrozenAccountScope::new( + Arc::new(RuntimeAccountDirectory::new( + accounts + .into_iter() + .map(|id| (id, RuntimeAccount::new(kind.clone(), BTreeSet::new()))) + .collect(), + )), + ClientRoutingScope::all_accounts(), + )) +} + +fn primary_scope() -> Arc { + account_scope([ProviderAccountId::new(PRIMARY_ACCOUNT).unwrap()]) +} + +pub(crate) fn request(stream: bool) -> ProviderRequest { + let operation = Operation::Generate(GenerateRequest::from_protocol_payload( + ProtocolPayload::json_object( + GENAI_PROTOCOL, + json!({"contents":[{"parts":[{"text":"hello"}]}]}) + .as_object() + .unwrap() + .clone(), + ) + .unwrap() + .with_context(json!({"stream":stream}).as_object().unwrap().clone()), + )); + let kind = ProviderKind::new("antigravity").unwrap(); + let model = ProviderModel::new( + kind.clone(), + UpstreamModelId::new("fixture-model").unwrap(), + ModelCapabilities::new(BTreeSet::from([operation.kind()]), None) + .with_upstream_feature_validation(), + ); + let snapshot = RuntimeSnapshot::new( + ConfigRevision::new(1).unwrap(), + SettingsValues::new(2, "smart", Default::default(), None, None), + vec![kind], + vec![model], + Vec::new(), + ) + .unwrap(); + let plan = snapshot + .plan( + &PublicModelId::new("fixture-model").unwrap(), + &operation, + primary_scope(), + &RoutingContext::default(), + ) + .unwrap(); + ProviderRequest::new(operation, plan.candidates()[0].clone()) +} + +pub(crate) fn context( + profile: OpaqueProviderData, + cancellation: CancellationToken, +) -> AttemptContext { + context_with_request( + RequestAttemptContext::new( + ModelRequestId::new("req_fixture").unwrap(), + ClientApiKeyId::new("key_fixture").unwrap(), + ) + .with_request_profile(Some(profile)), + cancellation, + ) +} + +pub(crate) fn context_with_request( + request: RequestAttemptContext, + cancellation: CancellationToken, +) -> AttemptContext { + context_with_policy( + request, + AccountSelectionPolicy::new(RotationStrategy::Smart, NonZeroU32::MIN), + cancellation, + ) +} + +pub(crate) fn context_with_policy( + request: RequestAttemptContext, + policy: AccountSelectionPolicy, + cancellation: CancellationToken, +) -> AttemptContext { + context_with_scope(request, policy, cancellation, primary_scope()) +} + +pub(crate) fn context_with_scope( + request: RequestAttemptContext, + policy: AccountSelectionPolicy, + cancellation: CancellationToken, + scope: Arc, +) -> AttemptContext { + AttemptContext::new( + request, + NonZeroU32::MIN, + SystemTime::now() + Duration::from_secs(30), + policy, + AccountAttemptContext::new(BTreeSet::new(), None, None).with_account_scope(scope), + None, + cancellation, + ) +} + +pub(crate) fn account_record() -> gateway_admin::model::accounts::AccountRecord { + gateway_admin::model::accounts::AccountRecord { + quota_paused: false, + quota_settings: Default::default(), + auto_use_quota_credits: false, + id: "acct_fixture".into(), + provider_kind: ProviderKind::new("antigravity").unwrap(), + groups: vec![], + name: "Local name".into(), + notes: None, + email: None, + upstream_user_id: Some("fixture-subject".into()), + upstream_account_id: None, + plan_type: None, + authentication_kind: "oauth".into(), + credential_revision: gateway_admin::model::Revision::new(1).unwrap(), + has_refresh_token: true, + access_token_expires_at: Some(chrono::Utc::now() - chrono::Duration::hours(1)), + next_refresh_at: None, + enabled: true, + concurrency_limit: None, + weight: Default::default(), + model_access: Default::default(), + outbound_proxy_id: None, + outbound_proxy: None, + outbound_proxy_enabled: true, + credential_state: CredentialState::Ready, + credential_observed_at: chrono::Utc::now(), + quota: QuotaState::unknown(), + last_error_reason: None, + last_error_message: None, + created_at: chrono::Utc::now(), + updated_at: chrono::Utc::now(), + } +} diff --git a/backend/crates/providers/antigravity/tests/support/ports.rs b/backend/crates/providers/antigravity/tests/support/ports.rs new file mode 100644 index 000000000..91bd7c3a9 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/support/ports.rs @@ -0,0 +1,648 @@ +//! 执行测试的最小内存端口,未使用的能力在被意外调用时失败 + +use super::{Lease, MemoryPorts}; +use async_trait::async_trait; +use futures::future::BoxFuture; +use gateway_core::{ + account::*, + error::{StoreError, StoreErrorKind}, + policy::ClientApiKeyId, + provider_ports::*, + routing::ProviderKind, +}; +use std::{ + sync::atomic::Ordering, + time::{Duration, SystemTime}, +}; + +impl ProviderLeasePort for MemoryPorts { + fn load_state<'a>( + &'a self, + _client_api_key_id: &'a ClientApiKeyId, + _provider_kind: &'a ProviderKind, + accounts: &'a [ProviderAccountId], + _pool: ProviderConcurrencyPool, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + Ok(ProviderSchedulingState::new( + accounts + .iter() + .map(|id| { + ( + id.clone(), + AccountRuntimeSignals { + in_flight: self.accounts[id].active_leases.load(Ordering::SeqCst) + as u32, + last_started_at: None, + quota_reset_at: None, + quota_reset_windows: None, + quota_remaining_rank: None, + cooldown: None, + failure_rate_basis_points: None, + first_output_latency_ms: None, + }, + ) + }) + .collect(), + self.scheduling_reads.fetch_add(1, Ordering::SeqCst) as u64, + )) + }) + } + fn try_acquire( + &self, + request: ProviderLeaseRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + let (leases, limit) = match request { + ProviderLeaseRequest::Scheduling(request) => ( + &self.accounts[request.account_id()].active_leases, + request.max_concurrent().limit(), + ), + ProviderLeaseRequest::Refresh(_) | ProviderLeaseRequest::RefreshCapacity(_) => { + (&self.refresh_leases, None) + } + }; + if leases + .try_update(Ordering::SeqCst, Ordering::SeqCst, |active| { + limit + .is_none_or(|limit| active < limit.get() as usize) + .then_some(active + 1) + }) + .is_err() + { + return Ok(ProviderLeaseAcquisition::Busy { retry_after: None }); + } + Ok(ProviderLeaseAcquisition::Acquired(Box::new(Lease( + leases.clone(), + )))) + }) + } +} + +impl ProviderCatalogCachePort for MemoryPorts { + fn replace<'a>( + &'a self, + _key: &'a ProviderCatalogCacheKey, + _catalog: &'a OpaqueProviderData, + _ttl: Duration, + ) -> BoxFuture<'a, Result<(), ProviderStoreError>> { + unreachable!("unused fixture port: ProviderCatalogCachePort::replace") + } + fn read<'a>( + &'a self, + _key: &'a ProviderCatalogCacheKey, + ) -> BoxFuture<'a, Result, ProviderStoreError>> { + unreachable!("unused fixture port: ProviderCatalogCachePort::read") + } +} + +impl ProviderArtifactProfileCachePort for MemoryPorts { + fn replace_if_newer( + &self, + _profile: ProviderArtifactProfile, + _ttl: Duration, + ) -> BoxFuture<'_, Result> { + unreachable!("unused fixture port: ProviderArtifactProfileCachePort::replace_if_newer") + } + fn read<'a>( + &'a self, + _provider_kind: &'a ProviderKind, + _artifact_key: &'a str, + ) -> BoxFuture<'a, Result, ProviderStoreError>> { + unreachable!("unused fixture port: ProviderArtifactProfileCachePort::read") + } +} + +impl ProviderCredentialStatePort for MemoryPorts { + fn replace( + &self, + _state: ProviderCredentialState, + ) -> BoxFuture<'_, Result<(), ProviderStoreError>> { + unreachable!("unused fixture port: ProviderCredentialStatePort::replace") + } + fn read<'a>( + &'a self, + _account_id: &'a ProviderAccountId, + ) -> BoxFuture<'a, Result, ProviderStoreError>> { + unreachable!("unused fixture port: ProviderCredentialStatePort::read") + } + fn clear<'a>( + &'a self, + _account_id: &'a ProviderAccountId, + ) -> BoxFuture<'a, Result> { + unreachable!("unused fixture port: ProviderCredentialStatePort::clear") + } + fn record_refresh_backoff<'a>( + &'a self, + _account_id: &'a ProviderAccountId, + _window: Duration, + ) -> BoxFuture<'a, Result> { + unreachable!("unused fixture port: ProviderCredentialStatePort::record_refresh_backoff") + } + fn clear_refresh_backoff<'a>( + &'a self, + _account_id: &'a ProviderAccountId, + ) -> BoxFuture<'a, Result<(), ProviderStoreError>> { + unreachable!("unused fixture port: ProviderCredentialStatePort::clear_refresh_backoff") + } +} + +impl ProviderRuntimePolicyPort for MemoryPorts { + fn load_request_profile<'a>( + &'a self, + provider: &'a ProviderKind, + ) -> BoxFuture<'a, Result, ProviderStoreError>> { + Box::pin(async move { + assert_eq!(provider.as_str(), "antigravity"); + Ok(self.request_profile.lock().unwrap().clone()) + }) + } + + fn load_refresh_policy( + &self, + ) -> BoxFuture<'_, Result> { + Box::pin(async { + Ok(ProviderRefreshPolicy::try_new( + Duration::from_secs(300), + std::num::NonZeroU32::new(2).unwrap(), + ) + .unwrap()) + }) + } +} + +impl OAuthPendingFlowPort for MemoryPorts { + fn put_if_absent( + &self, + _flow: NewOAuthPendingFlow, + ) -> BoxFuture<'_, Result> { + unreachable!("unused fixture port: OAuthPendingFlowPort::put_if_absent") + } + fn claim_if_owner<'a>( + &'a self, + _provider_kind: &'a ProviderKind, + _flow: &'a OAuthPendingBinding, + _owner: &'a OAuthPendingBinding, + _claim: &'a OAuthPendingBinding, + _claim_ttl: Duration, + ) -> BoxFuture<'a, Result> { + unreachable!("unused fixture port: OAuthPendingFlowPort::claim_if_owner") + } + fn release_claim<'a>( + &'a self, + _provider_kind: &'a ProviderKind, + _flow: &'a OAuthPendingBinding, + _owner: &'a OAuthPendingBinding, + _claim: &'a OAuthPendingBinding, + ) -> BoxFuture<'a, Result> { + unreachable!("unused fixture port: OAuthPendingFlowPort::release_claim") + } + fn consume_claim<'a>( + &'a self, + _provider_kind: &'a ProviderKind, + _flow: &'a OAuthPendingBinding, + _owner: &'a OAuthPendingBinding, + _claim: &'a OAuthPendingBinding, + ) -> BoxFuture<'a, Result> { + unreachable!("unused fixture port: OAuthPendingFlowPort::consume_claim") + } +} + +impl ProviderSessionAffinityPort for MemoryPorts { + fn load<'a>( + &'a self, + provider: &'a ProviderKind, + key: &'a ProviderSessionAffinityKey, + ) -> BoxFuture<'a, Result, ProviderStoreError>> { + Box::pin(async move { + assert_eq!(provider.as_str(), "antigravity"); + Ok(self + .bindings + .lock() + .unwrap() + .get(key) + .map(|(binding, _)| binding.clone())) + }) + } + fn round_robin_cursor<'a>( + &'a self, + provider: &'a ProviderKind, + client_key: &'a ClientApiKeyId, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + assert_eq!(provider.as_str(), "antigravity"); + Ok(self + .assignment_cursors + .lock() + .unwrap() + .get(client_key) + .copied() + .unwrap_or_default()) + }) + } + fn admit_account<'a>( + &'a self, + provider: &'a ProviderKind, + admission: ProviderAccountAdmission<'a>, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + assert_eq!(provider.as_str(), "antigravity"); + let count = self.claims.fetch_add(1, Ordering::SeqCst) + 1; + if self.reject_next_claim.swap(false, Ordering::SeqCst) { + return Ok(false); + } + let barrier = self.admission_barrier.lock().unwrap().clone(); + if let Some(barrier) = barrier { + barrier.wait().await; + self.admission_barrier.lock().unwrap().take(); + } + let mut bindings = self.bindings.lock().unwrap(); + let mut cursors = self.assignment_cursors.lock().unwrap(); + let claim = admission.session(); + if claim.is_some_and(|claim| { + bindings.get(claim.key).map(|(binding, _)| binding) != claim.expected + }) { + return Ok(false); + } + if let ProviderAccountAdmission::RoundRobin { + client_key, cursor, .. + } = admission + && cursors.get(client_key).copied().unwrap_or_default() != cursor + { + return Ok(false); + } + if let Some(claim) = claim { + let binding = match claim + .expected + .filter(|bound| bound.account_id() == claim.account) + { + Some(bound) => bound.clone(), + None => { + ProviderSessionBinding::new(claim.account.clone(), format!("{count:032x}"))? + } + }; + bindings.insert(claim.key.clone(), (binding, claim.ttl)); + } + if let ProviderAccountAdmission::RoundRobin { + client_key, cursor, .. + } = admission + { + cursors.insert(client_key.clone(), cursor.wrapping_add(1)); + } + Ok(true) + }) + } + fn load_alias<'a>( + &'a self, + _provider: &'a ProviderKind, + _alias: &'a ProviderSessionAffinityKey, + ) -> BoxFuture<'a, Result, ProviderStoreError>> { + unreachable!("unused fixture port: ProviderSessionAffinityPort::load_alias") + } + fn bind_alias<'a>( + &'a self, + _provider: &'a ProviderKind, + _alias: &'a ProviderSessionAffinityKey, + _session: &'a ProviderSessionAlias, + _ttl: Duration, + ) -> BoxFuture<'a, Result> { + unreachable!("unused fixture port: ProviderSessionAffinityPort::bind_alias") + } +} + +impl ProviderSessionExclusionPort for MemoryPorts { + fn load<'a>( + &'a self, + _provider_kind: &'a ProviderKind, + _key: &'a ProviderSessionAffinityKey, + ) -> BoxFuture<'a, Result, ProviderStoreError>> { + unreachable!("unused fixture port: ProviderSessionExclusionPort::load") + } + fn record_failure<'a>( + &'a self, + _provider_kind: &'a ProviderKind, + _key: &'a ProviderSessionAffinityKey, + _account_id: &'a ProviderAccountId, + _ttl: Duration, + ) -> BoxFuture<'a, Result> { + unreachable!("unused fixture port: ProviderSessionExclusionPort::record_failure") + } + fn clear<'a>( + &'a self, + _provider_kind: &'a ProviderKind, + _key: &'a ProviderSessionAffinityKey, + _expected_revision: &'a str, + ) -> BoxFuture<'a, Result> { + unreachable!("unused fixture port: ProviderSessionExclusionPort::clear") + } +} + +impl ProviderCooldownPort for MemoryPorts { + fn put_if_later( + &self, + _cooldown: ProviderCooldown, + ) -> BoxFuture<'_, Result> { + unreachable!("unused fixture port: ProviderCooldownPort::put_if_later") + } + fn read<'a>( + &'a self, + _account_id: &'a ProviderAccountId, + ) -> BoxFuture<'a, Result, ProviderStoreError>> { + unreachable!("unused fixture port: ProviderCooldownPort::read") + } + fn read_many<'a>( + &'a self, + account_ids: &'a [ProviderAccountId], + ) -> BoxFuture<'a, Vec, ProviderStoreError>>> { + Box::pin(async move { account_ids.iter().map(|_| Ok(None)).collect() }) + } + fn clear<'a>( + &'a self, + _account_id: &'a ProviderAccountId, + _through_revision: CredentialRevision, + ) -> BoxFuture<'a, Result> { + unreachable!("unused fixture port: ProviderCooldownPort::clear") + } + fn put_scoped_if_later( + &self, + cooldown: ProviderScopedCooldown, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + self.cooldowns.lock().unwrap().push(cooldown); + Ok(true) + }) + } + fn read_scoped<'a>( + &'a self, + _account_id: &'a ProviderAccountId, + _scope: &'a ProviderCooldownScope, + ) -> BoxFuture<'a, Result, ProviderStoreError>> { + unreachable!("unused fixture port: ProviderCooldownPort::read_scoped") + } + fn read_scoped_many<'a>( + &'a self, + account_ids: &'a [ProviderAccountId], + scope: &'a ProviderCooldownScope, + ) -> BoxFuture<'a, Vec, ProviderStoreError>>> { + Box::pin(async move { + let values = self.cooldowns.lock().unwrap(); + account_ids + .iter() + .map(|id| { + Ok(values + .iter() + .find(|c| c.account_id() == id && c.scope() == scope) + .cloned()) + }) + .collect() + }) + } + fn clear_scoped<'a>( + &'a self, + _account_id: &'a ProviderAccountId, + _scope: &'a ProviderCooldownScope, + _through_revision: CredentialRevision, + ) -> BoxFuture<'a, Result> { + unreachable!("unused fixture port: ProviderCooldownPort::clear_scoped") + } + fn clear_all<'a>( + &'a self, + _account_id: &'a ProviderAccountId, + ) -> BoxFuture<'a, Result> { + unreachable!("unused fixture port: ProviderCooldownPort::clear_all") + } + fn clear_after_success<'a>( + &'a self, + _account_id: &'a ProviderAccountId, + _through_revision: CredentialRevision, + ) -> BoxFuture<'a, Result<(), ProviderStoreError>> { + unreachable!("unused fixture port: ProviderCooldownPort::clear_after_success") + } +} + +#[async_trait] +impl ProviderAccountStore for MemoryPorts { + async fn expire_access_token( + &self, + account: &ProviderAccount, + _: SystemTime, + ) -> Result { + let matches = self.accounts.get(account.id()).is_some_and(|stored| { + stored.loaded.lock().unwrap().account.revision() == account.revision() + }); + if matches { + self.expired.store(true, Ordering::SeqCst); + } + Ok(matches) + } + + async fn load_account_catalogs( + &self, + _provider: &ProviderKind, + ) -> Result, StoreError> { + Ok(self + .accounts + .values() + .filter_map(|account| { + let loaded = account.loaded.lock().unwrap(); + let catalog = account.catalog.lock().unwrap(); + let (observation, document) = catalog.as_ref()?; + (loaded.account.enabled() + && observation.revision == loaded.account.revision() + && observation.plan.as_deref() == loaded.account.plan_type()) + .then(|| StoredAccountCatalog { + accounts: vec![observation.clone()], + document: document.clone(), + }) + }) + .collect()) + } + async fn save_account_catalog( + &self, + observation: &AccountCatalogObservation, + document: &[u8], + ) -> Result { + let Some(account) = self.accounts.get(&observation.account_id) else { + return Ok(false); + }; + let loaded = account.loaded.lock().unwrap(); + if observation.revision != loaded.account.revision() + || observation.plan.as_deref() != loaded.account.plan_type() + { + return Ok(false); + } + *account.catalog.lock().unwrap() = + Some((observation.clone(), bytes::Bytes::copy_from_slice(document))); + Ok(true) + } + async fn create_account(&self, _account: NewProviderAccount) -> Result<(), StoreError> { + unreachable!("unused fixture port: ProviderAccountStore::create_account") + } + async fn get_account( + &self, + account: &ProviderAccountId, + ) -> Result, StoreError> { + Ok(self + .accounts + .get(account) + .map(|account| account.loaded.lock().unwrap().account.clone())) + } + async fn list_accounts(&self) -> Result, StoreError> { + Ok(self + .accounts + .values() + .map(|account| account.loaded.lock().unwrap().account.clone()) + .collect()) + } + async fn list_for_provider( + &self, + provider: &ProviderKind, + include_disabled: bool, + ) -> Result, StoreError> { + Ok(self + .list_accounts() + .await? + .into_iter() + .filter(|account| { + account.provider() == provider && (include_disabled || account.enabled()) + }) + .collect()) + } + async fn list_for_provider_accounts( + &self, + _provider: &ProviderKind, + account_ids: &[ProviderAccountId], + ) -> Result, StoreError> { + Ok(self + .list_accounts() + .await? + .into_iter() + .filter(|account| account.enabled() && account_ids.contains(account.id())) + .collect()) + } + async fn list_refresh_candidates( + &self, + _query: ProviderRefreshQuery, + ) -> Result, StoreError> { + unreachable!("unused fixture port: ProviderAccountStore::list_refresh_candidates") + } + async fn load_credential( + &self, + account: &ProviderAccountId, + expected_revision: CredentialRevision, + ) -> Result { + let loaded = self.load_current_credential(account).await?; + assert_eq!(loaded.account.revision(), expected_revision); + Ok(loaded) + } + async fn load_current_credential( + &self, + account: &ProviderAccountId, + ) -> Result { + let account = self + .accounts + .get(account) + .ok_or_else(|| StoreError::new(StoreErrorKind::InvalidState))?; + Ok(account.loaded.lock().unwrap().clone()) + } + async fn compare_and_swap_credential( + &self, + _update: CredentialCasUpdate, + ) -> Result { + unreachable!("unused fixture port: ProviderAccountStore::compare_and_swap_credential") + } + async fn get_quotas( + &self, + accounts: &[ProviderAccountId], + ) -> Result, StoreError> { + Ok(accounts + .iter() + .filter_map(|id| self.accounts.get(id)?.quota.lock().unwrap().clone()) + .collect()) + } + async fn compare_and_swap_quota( + &self, + observation: QuotaObservation, + ) -> Result { + let Some(account) = self.accounts.get(&observation.account_id) else { + return Ok(QuotaWriteOutcome::Conflict); + }; + let mut current = account.loaded.lock().unwrap(); + let mut quota = account.quota.lock().unwrap(); + if current.account.revision() != observation.expected_revision + || quota + .as_ref() + .is_some_and(|q| q.observed_at > observation.observed_at) + { + return Ok(QuotaWriteOutcome::Conflict); + } + current.account = current + .account + .clone() + .with_profile( + current.account.email().map(str::to_owned), + current.account.upstream_account_id().map(str::to_owned), + observation.plan_type.clone(), + ) + .with_account_facts( + current.account.enabled(), + current.account.credential_state(), + observation.state, + None, + None, + ); + *quota = Some(observation); + Ok(QuotaWriteOutcome::Updated) + } + async fn touch_quota_observation( + &self, + _touch: QuotaObservationTouch, + ) -> Result { + unreachable!("unused fixture port: ProviderAccountStore::touch_quota_observation") + } + async fn apply_quota_access( + &self, + _change: QuotaAccessChange, + ) -> Result { + unreachable!("unused fixture port: ProviderAccountStore::apply_quota_access") + } + async fn apply_state_change(&self, _change: AccountStateChange) -> Result<(), StoreError> { + unreachable!("unused fixture port: ProviderAccountStore::apply_state_change") + } + async fn update_account(&self, _update: ProviderAccountUpdate) -> Result<(), StoreError> { + unreachable!("unused fixture port: ProviderAccountStore::update_account") + } + async fn set_enabled( + &self, + account: &ProviderAccountId, + enabled: bool, + ) -> Result<(), StoreError> { + let entry = self + .accounts + .get(account) + .ok_or_else(|| StoreError::new(StoreErrorKind::InvalidState))?; + let mut loaded = entry.loaded.lock().unwrap(); + let account = &loaded.account; + loaded.account = account.clone().with_account_facts( + enabled, + account.credential_state(), + account.quota(), + None, + None, + ); + Ok(()) + } + async fn delete_account(&self, _account: &ProviderAccountId) -> Result<(), StoreError> { + unreachable!("unused fixture port: ProviderAccountStore::delete_account") + } +} + +#[async_trait] +impl gateway_core::diagnostics::OperationalDiagnostics for MemoryPorts { + async fn record_failure( + &self, + _: gateway_core::diagnostics::OperationalFailure, + ) -> Result<(), StoreError> { + Ok(()) + } +} diff --git a/backend/crates/providers/antigravity/tests/support/profile.rs b/backend/crates/providers/antigravity/tests/support/profile.rs new file mode 100644 index 000000000..80585cf38 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/support/profile.rs @@ -0,0 +1,77 @@ +//! 发布包缓存的 CAS 与失败夹具,不依赖账号或认证资料 + +use futures::future::BoxFuture; +use gateway_core::{ + provider_ports::{ + ProviderArtifactProfile, ProviderArtifactProfileCachePort, ProviderStoreError, + ProviderStoreErrorKind, + }, + routing::ProviderKind, +}; +use std::{ + collections::BTreeMap, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + time::Duration, +}; + +#[derive(Default)] +pub struct ArtifactCache { + pub profiles: Mutex>, + pub fail: AtomicBool, + pub writes: AtomicUsize, +} +pub fn cache() -> Arc { + Arc::new(ArtifactCache::default()) +} + +impl ProviderArtifactProfileCachePort for ArtifactCache { + fn replace_if_newer( + &self, + profile: ProviderArtifactProfile, + _: Duration, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + if self.fail.load(Ordering::SeqCst) { + return Err(ProviderStoreError::new( + ProviderStoreErrorKind::Unavailable, + "artifact cache", + )); + } + let mut profiles = self.profiles.lock().unwrap(); + if let Some(old) = profiles.get(profile.artifact_key()) { + if old.artifact_sequence() > profile.artifact_sequence() { + return Ok(false); + } + if old.artifact_sequence() == profile.artifact_sequence() + && old.profile() != profile.profile() + { + return Err(ProviderStoreError::new( + ProviderStoreErrorKind::Conflict, + "artifact cache", + )); + } + } + profiles.insert(profile.artifact_key().into(), profile); + self.writes.fetch_add(1, Ordering::SeqCst); + Ok(true) + }) + } + fn read<'a>( + &'a self, + _: &'a ProviderKind, + key: &'a str, + ) -> BoxFuture<'a, Result, ProviderStoreError>> { + Box::pin(async move { + if self.fail.load(Ordering::SeqCst) { + return Err(ProviderStoreError::new( + ProviderStoreErrorKind::Unavailable, + "artifact cache", + )); + } + Ok(self.profiles.lock().unwrap().get(key).cloned()) + }) + } +} diff --git a/backend/crates/providers/antigravity/tests/transport/client.rs b/backend/crates/providers/antigravity/tests/transport/client.rs new file mode 100644 index 000000000..6d3885f55 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/transport/client.rs @@ -0,0 +1,391 @@ +//! 通过回环 HTTP 验证授权凭据、原生请求与响应透传 + +use crate::{ + credential::refreshed_credential, + profile::{self, ReleaseService}, + transport::{self, CloudCodeClient}, +}; +use futures::{StreamExt, TryStreamExt}; +use gateway_core::{ + event::{EventSequenceValidator, GatewayEvent}, + lifecycle::{CancellationToken, Deadline}, + routing::UpstreamModelId, +}; +use serde_json::json; +use wiremock::{ + Mock, MockServer, ResponseTemplate, + matchers::{header, method, path, query_param}, +}; + +#[tokio::test] +async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_payload() { + let server = MockServer::start().await; + let (origin, access_token) = refreshed_credential(&server).await; + let profile = + profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap()); + // 官方 macOS arm64 Desktop 2.34.0 在默认参数下实际发送的已认证请求头 + let user_agent = + "antigravity/hub/2.34.0 (aidev_client; os_type=darwin; arch=arm64; cl=1026637980)"; + let client = CloudCodeClient::new(&origin, None, &profile).unwrap(); + let post = |p| { + Mock::given(method("POST")) + .and(path(p)) + .and(header("authorization", "Bearer renewed-access")) + .and(header("user-agent", user_agent)) + .and(header("accept", "*/*")) + .and(header("accept-encoding", "gzip")) + }; + post("/v1internal:loadCodeAssist") + .respond_with( + compressed_response( + 200, + br#"{"cloudaicompanionProject":"project-1"}"#, + "application/json", + ) + .await, + ) + .expect(1) + .mount(&server) + .await; + post("/v1internal:fetchAvailableModels") + .and(wiremock::matchers::body_json( + json!({"project":"project-1"}), + )) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(json!({"models":{"fixture-model":{"displayName":"Fixture Model"}}})), + ) + .expect(1) + .mount(&server) + .await; + let catalog = client.catalog(&access_token).await.unwrap(); + assert_eq!(catalog.models["fixture-model"].name, "Fixture Model"); + let body=br#"{ "contents":[{"parts":[{"functionResponse":{"name":"lookup","response":{"x":1}},"thoughtSignature":"opaque"}]}],"unknown":98765432109876543210987654,"systemInstruction":{"parts":[{"text":"You are Claude Code."}]},"system_instruction":{"parts":[{"text":"old"}]} }"#; + let reply = r#"{ "responseId":"r","candidates":[{"content":{"parts":[{"text":"hidden","thought":true},{"text":"ok"},{"functionCall":{"name":"lookup","args":{"text":"not output"}}}]},"finishReason":"STOP"},{"index":1,"content":{"parts":[{"text":"other candidate"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":4,"candidatesTokenCount":2},"extra":98765432109876543210987654 }"#; + let received_body = move |r: &wiremock::Request| { + let envelope: std::collections::BTreeMap = + serde_json::from_slice(&r.body).unwrap(); + let request: std::collections::BTreeMap = + serde_json::from_str(envelope["request"].get()).unwrap(); + let original: std::collections::BTreeMap = + serde_json::from_slice(body).unwrap(); + let system: serde_json::Value = + serde_json::from_str(request["systemInstruction"].get()).unwrap(); + request["contents"].get() == original["contents"].get() + && request["unknown"].get() == original["unknown"].get() + && !request.contains_key("system_instruction") + && system["parts"][0]["text"] + .as_str() + .unwrap() + .starts_with("You are Antigravity,") + && !system.to_string().contains("Claude Code") + }; + post("/v1internal:generateContent") + .and(received_body) + .respond_with( + compressed_response( + 200, + format!(r#"{{"response":{reply}}}"#).as_bytes(), + "application/json", + ) + .await, + ) + .expect(1) + .mount(&server) + .await; + post("/v1internal:streamGenerateContent") + .and(query_param("alt", "sse")) + .and(received_body) + .respond_with( + compressed_response( + 200, + format!("id: evt-1\ndata: {{\"response\":{reply}}}\n\n").as_bytes(), + "text/event-stream", + ) + .await, + ) + .expect(1) + .mount(&server) + .await; + for stream in [false, true] { + let res = client + .generate( + &catalog.project, + "fixture-model", + &access_token, + body, + stream, + &[], + ) + .await + .unwrap(); + let events = transport::events( + res, + transport::ResponseContext { + stream, + model: UpstreamModelId::new("fixture-model").unwrap(), + deadline: Deadline::default(), + cancel: CancellationToken::new(), + token: access_token.clone(), + pricing: None, + started_at: std::time::Instant::now(), + }, + ) + .try_collect::>() + .await + .unwrap(); + let facts: Vec<_> = events + .iter() + .flat_map(|event| event.canonical_facts()) + .collect(); + let mut validator = EventSequenceValidator::default(); + for fact in &facts { + validator.observe(fact).unwrap(); + } + assert!(matches!(facts.first(), Some(GatewayEvent::Started(_)))); + assert!(facts.iter().any(|fact| matches!(fact, GatewayEvent::Usage(u) if u.input_tokens == Some(4) && u.output_tokens == Some(2)))); + let text: String = facts + .iter() + .filter_map(|fact| match fact { + GatewayEvent::TextDelta(delta) => Some(delta.text.as_str()), + _ => None, + }) + .collect(); + assert_eq!(text, "ok"); + assert!(matches!( + events.last().unwrap().canonical_facts(), + [GatewayEvent::Completed(_)] + )); + let wire = events[0].wire_event().unwrap(); + if stream { + assert!( + std::str::from_utf8(wire.raw_sse_frame().unwrap()) + .unwrap() + .contains(&format!("id: evt-1\ndata: {reply}\n\n")) + ); + } else { + assert_eq!(wire.raw_json_body().unwrap().as_ref(), reply.as_bytes()); + } + } +} + +#[tokio::test] +async fn streamed_text_is_projected_once_across_native_frames() { + let server = MockServer::start().await; + let profile = + profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap()); + let client = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap(); + let frames = [ + json!({"candidates":[{"content":{"parts":[{"text":""}]}}]}), + json!({"responseId":"r","candidates":[{"content":{"parts":[{"text":"hidden","thought":true}]}}]}), + json!({"candidates":[{"index":1,"content":{"parts":[{"text":"other"}]},"finishReason":"STOP"},{"index":0,"content":{"parts":[{"text":"O"}]}}]}), + json!({"candidates":[{"index":0,"content":{"parts":[{"text":"K"}]},"finishReason":"STOP"}]}), + json!({"usageMetadata":{"promptTokenCount":4,"candidatesTokenCount":2}}), + ]; + let body: String = frames + .iter() + .map(|frame| format!("data: {{\"response\":{frame}}}\n\n")) + .collect(); + Mock::given(path("/v1internal:streamGenerateContent")) + .respond_with(ResponseTemplate::new(200).set_body_raw(body, "text/event-stream")) + .expect(1) + .mount(&server) + .await; + let response = client + .generate("p", "m", "fixture", b"{}", true, &[]) + .await + .unwrap(); + let events = transport::events( + response, + transport::ResponseContext { + stream: true, + model: UpstreamModelId::new("m").unwrap(), + deadline: Deadline::default(), + cancel: CancellationToken::new(), + token: "fixture".into(), + pricing: None, + started_at: std::time::Instant::now(), + }, + ) + .try_collect::>() + .await + .unwrap(); + let mut validator = EventSequenceValidator::default(); + let mut text = String::new(); + let mut content_count = 0; + for fact in events.iter().flat_map(|event| event.canonical_facts()) { + validator.observe(fact).unwrap(); + match fact { + GatewayEvent::ContentAdded(_) => content_count += 1, + GatewayEvent::TextDelta(delta) => text.push_str(&delta.text), + _ => {} + } + } + assert_eq!(content_count, 1); + assert_eq!(text, "OK"); + let timings: Vec<_> = events + .iter() + .filter_map(|event| event.response_observation()) + .map(|observation| observation.timings()) + .collect(); + assert!(timings[0].headers_ms.is_some()); + assert!(timings[0].first_event_ms.is_some()); + assert!(timings[0].first_token_ms.is_none()); + assert!(timings[1].first_reasoning_ms.is_some()); + assert!(timings[1].first_text_ms.is_none()); + assert!(timings[2].first_text_ms.is_some()); + let wire: Vec<_> = events + .iter() + .filter_map(|event| event.wire_event()) + .collect(); + assert_eq!(wire.len(), frames.len()); + for (wire, frame) in wire.iter().zip(frames) { + assert_eq!( + wire.raw_sse_frame().unwrap().as_ref(), + format!("data: {frame}\n\n").as_bytes() + ); + } +} + +#[tokio::test] +async fn incomplete_native_stream_and_redirect_are_rejected() { + let server = MockServer::start().await; + let profile = + profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap()); + let client = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap(); + Mock::given(path("/v1internal:streamGenerateContent")).respond_with(ResponseTemplate::new(200).set_body_raw("data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"partial\"}]}}]}}\n\n","text/event-stream")).mount(&server).await; + let res = client + .generate("p", "m", "fixture", b"{}", true, &[]) + .await + .unwrap(); + let result = transport::events( + res, + transport::ResponseContext { + stream: true, + model: UpstreamModelId::new("m").unwrap(), + deadline: Deadline::default(), + cancel: CancellationToken::new(), + token: "fixture".into(), + pricing: None, + started_at: std::time::Instant::now(), + }, + ) + .try_collect::>() + .await; + assert_eq!( + result.unwrap_err().kind(), + gateway_core::error::ProviderErrorKind::Protocol + ); + let other = MockServer::start().await; + Mock::given(path("/v1internal:generateContent")) + .respond_with(ResponseTemplate::new(307).insert_header("Location", other.uri())) + .mount(&server) + .await; + assert!( + client + .generate("p", "m", "fixture", b"{}", false, &[]) + .await + .is_err() + ); + assert!(other.received_requests().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn incomplete_stream_never_emits_a_calculated_cost() { + let server = MockServer::start().await; + let frame = json!({"response":{ + "candidates":[{"content":{"parts":[{"text":"partial"}]}}], + "usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":20} + }}); + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200) + .set_body_raw(format!("data: {frame}\n\n"), "text/event-stream"), + ) + .mount(&server) + .await; + let response = reqwest::get(server.uri()).await.unwrap(); + let events = transport::events( + response, + transport::ResponseContext { + stream: true, + model: UpstreamModelId::new("fixture-model").unwrap(), + deadline: Deadline::default(), + cancel: CancellationToken::new(), + token: "fixture".into(), + pricing: Some(crate::billing_tests::pricing()), + started_at: std::time::Instant::now(), + }, + ) + .collect::>() + .await; + assert_eq!( + events.last().unwrap().as_ref().unwrap_err().kind(), + gateway_core::error::ProviderErrorKind::Protocol + ); + assert!( + !events + .iter() + .filter_map(|event| event.as_ref().ok()) + .flat_map(|event| event.canonical_facts()) + .any(|fact| matches!(fact, GatewayEvent::CalculatedCost(_))) + ); +} + +async fn compressed_response(status: u16, body: &[u8], media: &str) -> ResponseTemplate { + use tokio::io::AsyncWriteExt; + let mut compressed = Vec::new(); + // 覆盖多个 gzip member,后半段包含协议完成与用量,不能被解码器提前截断 + for part in body.chunks(body.len().div_ceil(2)) { + let mut encoder = async_compression::tokio::write::GzipEncoder::new(Vec::new()); + encoder.write_all(part).await.unwrap(); + encoder.shutdown().await.unwrap(); + compressed.extend(encoder.into_inner()); + } + ResponseTemplate::new(status) + .insert_header("content-encoding", "gzip") + .set_body_raw(compressed, media) +} + +#[tokio::test] +async fn compressed_control_responses_keep_errors_and_decoded_size_limits() { + use gateway_core::error::ProviderErrorKind; + let server = MockServer::start().await; + let profile = + profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap()); + let client = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap(); + Mock::given(path("/v1internal:loadCodeAssist")) + .respond_with( + compressed_response( + 429, + br#"{"error":{"message":"fixture quota"}}"#, + "application/json", + ) + .await, + ) + .mount(&server) + .await; + let error = client.catalog("fixture").await.err().unwrap(); + assert_eq!(error.kind(), ProviderErrorKind::RateLimited); + assert_eq!(error.upstream_status(), Some(429)); + server.reset().await; + Mock::given(path("/v1internal:loadCodeAssist")) + .respond_with( + compressed_response(200, &vec![b' '; 8 * 1024 * 1024 + 1], "application/json").await, + ) + .mount(&server) + .await; + let error = client.catalog("fixture").await.err().unwrap(); + assert_eq!(error.kind(), ProviderErrorKind::MessageTooBig); + server.reset().await; + Mock::given(path("/v1internal:loadCodeAssist")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("content-encoding", "gzip") + .set_body_raw("invalid gzip", "application/json"), + ) + .mount(&server) + .await; + let error = client.catalog("fixture").await.err().unwrap(); + assert_eq!(error.kind(), ProviderErrorKind::Transport); +} diff --git a/backend/crates/providers/antigravity/tests/transport/count.rs b/backend/crates/providers/antigravity/tests/transport/count.rs new file mode 100644 index 000000000..bf90612fe --- /dev/null +++ b/backend/crates/providers/antigravity/tests/transport/count.rs @@ -0,0 +1,210 @@ +//! 计数使用独立上游、共享身份策略并保留错误与资源生命周期 + +use crate::{ + profile::{Selection, object}, + support::{Fixture, context, request}, +}; +use futures::{StreamExt, TryStreamExt}; +use gateway_core::{ + account::OpaqueProviderData, + engine::provider::Provider, + error::ProviderErrorKind, + event::GatewayEvent, + lifecycle::CancellationToken, + operation::{Operation, RawJsonPayload, TokenCountRequest}, + upstream::UpstreamSendState, +}; +use serde_json::{Value, json}; +use std::time::Duration; +use wiremock::{ + Mock, MockServer, ResponseTemplate, + matchers::{header, method, path}, +}; + +fn profile() -> OpaqueProviderData { + Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.14","arch":null,"systemPrompt":"count identity"}))).unwrap().resolve("9.9.9").frozen() +} + +fn counted(protocol: &str, body: Value) -> gateway_core::engine::provider::ProviderRequest { + let request = request(false); + let operation = Operation::CountTokens(TokenCountRequest::from_raw_json( + RawJsonPayload::new(protocol, serde_json::to_vec(&body).unwrap().into()).unwrap(), + )); + gateway_core::engine::provider::ProviderRequest::new(operation, request.candidate().clone()) +} + +async fn released(fixture: &Fixture) { + tokio::time::timeout(Duration::from_secs(1), async { + while fixture.store.active_leases() != 0 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn native_and_messages_count_share_identity_and_never_generate_usage() { + for (protocol, body, expected) in [ + ( + "genai", + json!({"generateContentRequest":{"model":"models/ignored","contents":[{"role":"user","parts":[{"text":"hello"}]}],"systemInstruction":{"parts":[{"text":"client identity"}]},"tools":[{"functionDeclarations":[{"name":"read"}]}],"toolConfig":{},"safetySettings":[]}}), + json!({"totalTokens":42}), + ), + ( + "anthropic", + json!({"model":"fixture-model","messages":[{"role":"user","content":"hello"}],"system":"client identity","tools":[{"name":"read","input_schema":{"type":"object"}}]}), + json!({"input_tokens":42}), + ), + ] { + let upstream = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v1internal:countTokens")) + .and(header("authorization", "Bearer fixture-access")) + .and(header("user-agent", "antigravity/cli/1.5.14 (aidev_client; os_type=linux; arch=amd64; auth_method=consumer)")) + .and(header("accept-encoding", "gzip")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"totalTokens":42}))) + .expect(1) + .mount(&upstream) + .await; + let fixture = Fixture::new(&upstream.uri()); + let stream = fixture + .provider + .clone() + .execute( + counted(protocol, body), + context(profile(), CancellationToken::new()), + ) + .await + .unwrap(); + assert!(upstream.received_requests().await.unwrap().is_empty()); + let mut stream = stream; + let mut events = Vec::new(); + while let Some(event) = stream.next().await { + let event = event.unwrap(); + let terminal = event + .canonical_facts() + .iter() + .any(|fact| matches!(fact, GatewayEvent::Completed(_))); + events.extend(stream.translate_native_response(event, terminal).unwrap()); + } + drop(stream); + assert!(events.iter().any(|event| { + event.wire_event().is_some_and(|wire| { + wire.protocol() == protocol + && wire.raw_json_body().map_or_else( + || wire.data().clone(), + |raw| serde_json::from_slice::(raw).unwrap(), + ) == expected + }) + })); + assert!( + !events + .iter() + .flat_map(|event| event.canonical_facts()) + .any(|fact| matches!( + fact, + GatewayEvent::Usage(_) | GatewayEvent::CalculatedCost(_) + )) + ); + let sent = upstream.received_requests().await.unwrap(); + let sent: Value = sent[0].body_json().unwrap(); + assert_eq!(sent.as_object().unwrap().len(), 1); + assert_eq!( + sent["request"]["systemInstruction"]["parts"][0]["text"], + "count identity" + ); + assert_eq!(sent["request"]["contents"][0]["parts"][0]["text"], "hello"); + assert_eq!( + sent["request"]["tools"][0]["functionDeclarations"][0]["name"], + "read" + ); + assert!(sent["request"].get("model").is_none()); + assert!(sent["request"].get("toolConfig").is_none()); + assert!(sent["request"].get("safetySettings").is_none()); + released(&fixture).await; + } +} + +#[tokio::test] +async fn count_cancellation_before_poll_does_not_send_or_leak() { + let upstream = MockServer::start().await; + let fixture = Fixture::new(&upstream.uri()); + let cancellation = CancellationToken::new(); + let mut stream = fixture + .provider + .clone() + .execute( + counted("genai", json!({"contents":[]})), + context(profile(), cancellation.clone()), + ) + .await + .unwrap(); + cancellation.cancel(); + let err = stream.next().await.unwrap().unwrap_err(); + assert_eq!(err.kind(), ProviderErrorKind::Cancelled); + assert_eq!(err.send_state(), UpstreamSendState::NotSent); + drop(stream); + released(&fixture).await; + assert!(upstream.received_requests().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn upstream_count_failure_has_no_local_estimate() { + for (status, body, kind) in [ + ( + 400, + json!({"error":{"message":"invalid contents"}}), + ProviderErrorKind::InvalidRequest, + ), + (200, json!({"totalTokens":-1}), ProviderErrorKind::Protocol), + ] { + let upstream = MockServer::start().await; + Mock::given(path("/v1internal:countTokens")) + .respond_with(ResponseTemplate::new(status).set_body_json(body)) + .expect(1) + .mount(&upstream) + .await; + let fixture = Fixture::new(&upstream.uri()); + let stream = fixture + .provider + .clone() + .execute( + counted("genai", json!({"contents":[]})), + context(profile(), CancellationToken::new()), + ) + .await + .unwrap(); + let err = stream.try_collect::>().await.unwrap_err(); + assert_eq!(err.kind(), kind); + assert_eq!(err.send_state(), UpstreamSendState::Sent); + released(&fixture).await; + } +} + +#[tokio::test] +async fn empty_protobuf_count_response_is_an_explicit_zero() { + let upstream = MockServer::start().await; + Mock::given(path("/v1internal:countTokens")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({}))) + .expect(1) + .mount(&upstream) + .await; + let fixture = Fixture::new(&upstream.uri()); + let events = fixture + .provider + .clone() + .execute( + counted("genai", json!({"contents":[]})), + context(profile(), CancellationToken::new()), + ) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let wire = events[0].wire_event().unwrap(); + let value: Value = serde_json::from_slice(wire.raw_json_body().unwrap()).unwrap(); + assert_eq!(value, json!({"totalTokens":0})); + released(&fixture).await; +} diff --git a/backend/crates/providers/antigravity/tests/transport/mod.rs b/backend/crates/providers/antigravity/tests/transport/mod.rs new file mode 100644 index 000000000..17a74518f --- /dev/null +++ b/backend/crates/providers/antigravity/tests/transport/mod.rs @@ -0,0 +1,5 @@ +//! Cloud Code HTTP 与原生协议合同测试 + +mod client; +mod count; +mod pool; diff --git a/backend/crates/providers/antigravity/tests/transport/pool.rs b/backend/crates/providers/antigravity/tests/transport/pool.rs new file mode 100644 index 000000000..880ab852c --- /dev/null +++ b/backend/crates/providers/antigravity/tests/transport/pool.rs @@ -0,0 +1,284 @@ +//! 用回环保活连接验证账号隔离、当前请求材料与客户端缓存淘汰 + +use crate::{ + profile::{ClientProfile, Selection}, + transport::ClientPool, +}; +use gateway_core::{ + account::{CredentialRevision, OutboundProxy, ProviderAccount, ProviderAccountId}, + routing::ProviderKind, +}; +use serde_json::{Value, json}; +use std::{ + collections::BTreeMap, + sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, + }, + time::Duration, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, + task::{JoinHandle, JoinSet}, +}; +use url::Url; + +struct RecordedRequest { + connection: usize, + headers: BTreeMap, + body: Value, +} + +struct KeepAlivePeer { + origin: Url, + connections: Arc, + requests: Arc>>, + task: JoinHandle<()>, +} + +impl KeepAlivePeer { + async fn start() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()) + .parse() + .unwrap(); + let connections = Arc::new(AtomicUsize::new(0)); + let requests = Arc::new(Mutex::new(Vec::new())); + let count = connections.clone(); + let recorded = requests.clone(); + let task = tokio::spawn(async move { + let mut handlers = JoinSet::new(); + while let Ok((socket, _)) = listener.accept().await { + let connection = count.fetch_add(1, Ordering::SeqCst); + handlers.spawn(serve_connection(socket, connection, recorded.clone())); + } + }); + Self { + origin, + connections, + requests, + task, + } + } + + fn connection_count(&self) -> usize { + self.connections.load(Ordering::SeqCst) + } +} + +impl Drop for KeepAlivePeer { + fn drop(&mut self) { + self.task.abort(); + } +} + +async fn serve_connection( + mut socket: TcpStream, + connection: usize, + requests: Arc>>, +) { + loop { + let mut raw = Vec::new(); + while !raw.ends_with(b"\r\n\r\n") { + let mut byte = [0; 1]; + if !matches!(socket.read(&mut byte).await, Ok(1)) { + return; + } + raw.push(byte[0]); + assert!(raw.len() < 65536); + } + let raw = String::from_utf8(raw).unwrap(); + let headers = raw + .lines() + .skip(1) + .filter_map(|line| line.split_once(':')) + .map(|(key, value)| (key.to_ascii_lowercase(), value.trim().to_owned())) + .collect::>(); + let length = headers["content-length"].parse().unwrap(); + let mut body = vec![0; length]; + if socket.read_exact(&mut body).await.is_err() { + return; + } + requests.lock().unwrap().push(RecordedRequest { + connection, + headers, + body: serde_json::from_slice(&body).unwrap(), + }); + let body = br#"{"response":{"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}]}}"#; + let headers = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: keep-alive\r\n\r\n", + body.len() + ); + if socket.write_all(headers.as_bytes()).await.is_err() + || socket.write_all(body).await.is_err() + || socket.flush().await.is_err() + { + return; + } + } +} + +fn account(id: &str, revision: u64) -> ProviderAccount { + ProviderAccount::new( + ProviderAccountId::new(id).unwrap(), + ProviderKind::new("antigravity").unwrap(), + id.into(), + None, + "oauth".into(), + CredentialRevision::new(revision).unwrap(), + None, + ) +} + +async fn generate( + pool: &ClientPool, + origin: &Url, + account: &ProviderAccount, + profile: &ClientProfile, + project: &str, + token: &str, +) { + let client = pool.client(origin, account, profile).unwrap(); + tokio::time::timeout(Duration::from_secs(3), async { + client + .generate( + project, + "fixture-model", + token, + br#"{"contents":[{"parts":[{"text":"ping","thoughtSignature":"fixture-signature"}]}]}"#, + false, + &[], + ) + .await + .unwrap() + .bytes() + .await + .unwrap(); + }) + .await + .expect("local keep-alive peer must respond"); +} + +#[tokio::test] +async fn repeated_account_reuses_tcp_without_caching_token_project_or_prompt() { + let peer = KeepAlivePeer::start().await; + let pool = ClientPool::default(); + let account = account("acct_one", 1); + let mut profile = Selection::default().resolve("2.34.0"); + for index in 0..5 { + profile.system_prompt = format!("fixture prompt {index}"); + generate( + &pool, + &peer.origin, + &account, + &profile, + &format!("fixture-project-{index}"), + &format!("fixture-token-{index}"), + ) + .await; + } + assert_eq!(peer.connection_count(), 1); + let sent = peer.requests.lock().unwrap(); + assert_eq!(sent.len(), 5); + for (index, request) in sent.iter().enumerate() { + assert_eq!( + request.headers["authorization"], + format!("Bearer fixture-token-{index}") + ); + assert_eq!(request.body["project"], format!("fixture-project-{index}")); + assert_eq!( + request.body["request"]["systemInstruction"], + json!({"parts": [{"text": format!("fixture prompt {index}")}]}), + ); + assert_eq!( + request.body["request"]["contents"][0]["parts"][0]["thoughtSignature"], + "fixture-signature" + ); + } +} + +#[tokio::test] +async fn account_revision_and_user_agent_isolate_connection_pools() { + let peer = KeepAlivePeer::start().await; + let pool = ClientPool::default(); + let profile = Selection::default().resolve("2.34.0"); + let changed_profile = Selection::default().resolve("2.35.0"); + for (id, revision, profile) in [ + ("acct_one", 1, &profile), + ("acct_two", 1, &profile), + ("acct_one", 2, &profile), + ("acct_one", 1, &changed_profile), + ("acct_one", 1, &profile), + ] { + generate( + &pool, + &peer.origin, + &account(id, revision), + profile, + "fixture-project", + "fixture-token", + ) + .await; + } + assert_eq!(peer.connection_count(), 4); + let sent = peer.requests.lock().unwrap(); + assert_eq!(sent[0].connection, sent[4].connection); + assert_ne!(sent[0].headers["user-agent"], sent[3].headers["user-agent"]); +} + +#[tokio::test] +async fn proxy_routes_keep_independent_pools_and_preserve_the_direct_pool() { + let direct = KeepAlivePeer::start().await; + let first_proxy = KeepAlivePeer::start().await; + let second_proxy = KeepAlivePeer::start().await; + let pool = ClientPool::default(); + let profile = Selection::default().resolve("2.34.0"); + for proxy in [ + None, + Some(&first_proxy.origin), + Some(&second_proxy.origin), + None, + ] { + let account = account("acct_one", 1) + .with_outbound_proxy(proxy.map(|url| OutboundProxy::parse(url.as_str()).unwrap())); + generate( + &pool, + &direct.origin, + &account, + &profile, + "fixture-project", + "fixture-token", + ) + .await; + } + assert_eq!(direct.connection_count(), 1); + assert_eq!(first_proxy.connection_count(), 1); + assert_eq!(second_proxy.connection_count(), 1); + assert_eq!(direct.requests.lock().unwrap().len(), 2); + assert_eq!(first_proxy.requests.lock().unwrap().len(), 1); + assert_eq!(second_proxy.requests.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn cache_evicts_the_least_recently_used_client_after_sixty_four_identities() { + let peer = KeepAlivePeer::start().await; + let pool = ClientPool::default(); + let profile = Selection::default().resolve("2.34.0"); + for index in (0..64).chain([0, 64, 0, 1]) { + generate( + &pool, + &peer.origin, + &account(&format!("acct_{index}"), 1), + &profile, + "fixture-project", + "fixture-token", + ) + .await; + } + let sent = peer.requests.lock().unwrap(); + assert_eq!(sent[0].connection, sent[64].connection); + assert_eq!(sent[0].connection, sent[66].connection); + assert_ne!(sent[1].connection, sent[67].connection); + assert_eq!(peer.connection_count(), 66); +} diff --git a/backend/crates/providers/openai/src/admin/credentials.rs b/backend/crates/providers/openai/src/admin/credentials.rs new file mode 100644 index 000000000..3e147eef6 --- /dev/null +++ b/backend/crates/providers/openai/src/admin/credentials.rs @@ -0,0 +1,183 @@ +//! 账号资料和凭据准备结果到管理合同的转换 + +use super::error::provider_admin_error; +use crate::credential::CodexOAuthSecret; +use chrono::{DateTime, Utc}; +use gateway_admin::model::Revision; +use gateway_admin::model::accounts::AccountRecord; +use gateway_admin::model::provider_credentials::{ + CredentialCommitGuard, PreparedCredentialCreate, PreparedCredentialRotation, + PreparedCredentialRotationFacts, ProviderDocument, +}; +use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind}; +use gateway_core::account::{ + CredentialCasUpdateParts, CredentialRevision, NewProviderAccount, OpaqueProviderData, + ProviderAccount, ProviderAccountId, +}; +use gateway_core::routing::ProviderKind; +use secrecy::SecretString; +use serde::Deserialize; +use serde_json::Value; +use std::time::SystemTime; + +const PROVIDER_NAME: &str = "openai"; +struct OpenAiCredentialCommitGuard { + _guard: crate::credential::PreparedCodexCredentialRotationGuard, +} + +impl CredentialCommitGuard for OpenAiCredentialCommitGuard { + fn finish(self: Box) {} +} + +pub(super) fn prepared_create( + prepared: NewProviderAccount, + observed_at: DateTime, +) -> Result { + let NewProviderAccount { + account, + model_access, + credential, + } = prepared; + Ok(PreparedCredentialCreate { + model_access, + outbound_proxy: account.outbound_proxy().cloned(), + account_id: account.id().clone(), + provider_kind: account.provider().clone(), + name: account.name().to_owned(), + email: account.email().map(str::to_owned), + upstream_user_id: account.upstream_user_id().map(str::to_owned), + upstream_account_id: account.upstream_account_id().map(str::to_owned), + plan_type: account.plan_type().map(str::to_owned), + authentication_kind: account.authentication_kind().to_owned(), + provider_material: ProviderDocument::new(OpaqueProviderData::new(credential.into_inner())), + has_refresh_token: account.has_refresh_token(), + access_token_expires_at: account.access_token_expires_at().map(DateTime::::from), + next_refresh_at: account.next_refresh_at().map(DateTime::::from), + enabled: account.enabled(), + credential_state: account.credential_state(), + credential_observed_at: observed_at, + }) +} + +pub(super) fn prepared_rotation( + prepared: crate::credential::PreparedCodexCredentialRotation, + provider_kind: ProviderKind, +) -> Result { + let (profile, credential, replacement_identity, guard) = prepared.into_parts(); + let CredentialCasUpdateParts { + account_id, + expected_revision, + profile: credential_profile, + preserve_profile, + preserve_access_token_expiry, + credential, + has_refresh_token, + access_token_expires_at, + next_refresh_at, + account_state: _, + } = credential.into_parts(); + if profile != credential_profile || profile.account_id != account_id { + return Err(provider_admin_error(ProviderAdminErrorKind::Internal)); + } + let expected_credential_revision = Revision::new(expected_revision.get()) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Internal))?; + Ok(PreparedCredentialRotation::new( + PreparedCredentialRotationFacts { + account_id, + provider_kind, + expected_credential_revision, + replacement_identity, + name: profile.name, + email: profile.email, + plan_type: profile.plan_type, + preserve_profile, + preserve_credential_state: false, + preserve_access_token_expiry, + provider_material: ProviderDocument::new(OpaqueProviderData::new( + credential.into_inner(), + )), + has_refresh_token, + access_token_expires_at: access_token_expires_at.map(DateTime::::from), + next_refresh_at: next_refresh_at.map(DateTime::::from), + }, + Box::new(OpenAiCredentialCommitGuard { _guard: guard }), + )) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RotationDocument { + access_token: String, + refresh_token: Option, + id_token: Option, +} + +pub(super) fn rotation_secret( + document: ProviderDocument, +) -> Result { + let document: RotationDocument = + serde_json::from_value(Value::Object(document.into_provider_data().into_inner())) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; + Ok(CodexOAuthSecret { + access_token: SecretString::from(document.access_token), + refresh_token: document.refresh_token.map(SecretString::from), + id_token: document.id_token.map(SecretString::from), + }) +} + +pub(super) fn validate_account_record( + account: &AccountRecord, + provider_kind: &ProviderKind, +) -> Result<(), ProviderAdminError> { + if &account.provider_kind != provider_kind || provider_kind.as_str() != PROVIDER_NAME { + return Err(provider_admin_error(ProviderAdminErrorKind::Invalid)); + } + ProviderAccountId::new(account.id.clone()) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; + Ok(()) +} + +pub(super) fn account_from_record( + account: &AccountRecord, +) -> Result { + let account_id = ProviderAccountId::new(account.id.clone()) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; + let revision = CredentialRevision::new(account.credential_revision.get()) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; + Ok(ProviderAccount::new( + account_id, + account.provider_kind.clone(), + account.name.clone(), + account.upstream_user_id.clone(), + account.authentication_kind.clone(), + revision, + account.access_token_expires_at.map(SystemTime::from), + ) + .with_auto_use_quota_credits(account.auto_use_quota_credits) + .with_outbound_proxy(account.outbound_proxy.clone()) + .with_notes(account.notes.clone()) + .with_profile( + account.email.clone(), + account.upstream_account_id.clone(), + account.plan_type.clone(), + ) + .with_account_facts( + account.enabled, + account.credential_state, + account.quota, + account.last_error_reason, + account.last_error_message.clone(), + ) + .with_model_access(account.model_access.clone()) + .with_refresh_schedule( + account.has_refresh_token, + account.next_refresh_at.map(SystemTime::from), + )) +} +pub(super) fn account_matches_record(account: &ProviderAccount, record: &AccountRecord) -> bool { + account.id().as_str() == record.id + && account.provider() == &record.provider_kind + && account.upstream_user_id() == record.upstream_user_id.as_deref() + && account.upstream_account_id() == record.upstream_account_id.as_deref() + && account.authentication_kind() == record.authentication_kind +} diff --git a/backend/crates/providers/openai/src/admin/error.rs b/backend/crates/providers/openai/src/admin/error.rs new file mode 100644 index 000000000..385e16656 --- /dev/null +++ b/backend/crates/providers/openai/src/admin/error.rs @@ -0,0 +1,377 @@ +//! Provider 错误到管理合同的唯一映射 + +use crate::credential::{ + CodexCredentialAdminError, CodexCredentialCatalogError, CodexCredentialQuotaError, + CodexOAuthAdminError, CodexProfileAvatarError, CodexProfileStatisticsError, + CodexResetCreditsError, +}; +use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind}; +use gateway_core::error::StoreErrorKind; + +pub(super) fn provider_admin_error(kind: ProviderAdminErrorKind) -> ProviderAdminError { + ProviderAdminError::new(kind) +} +pub(super) fn map_store_error(error: gateway_core::error::StoreError) -> ProviderAdminError { + provider_admin_error(match error.kind() { + StoreErrorKind::Conflict => ProviderAdminErrorKind::Conflict, + StoreErrorKind::InvalidData | StoreErrorKind::InvalidState => { + ProviderAdminErrorKind::NotFound + } + StoreErrorKind::Unavailable => ProviderAdminErrorKind::Unavailable, + _ => ProviderAdminErrorKind::Internal, + }) + .with_source(error) +} + +pub(super) fn map_credential_admin_error(error: CodexCredentialAdminError) -> ProviderAdminError { + use crate::credential::token_client::PersonalAccessTokenError; + use CodexCredentialAdminError as Error; + use ProviderAdminErrorKind as Kind; + let upstream_message = error.upstream_message().map(ToOwned::to_owned); + let (kind, public_message) = match error { + Error::PersonalAccessToken(error) => match error { + PersonalAccessTokenError::InvalidToken => ( + Kind::Invalid, + "请输入完整 PAT,以 at- 开头且不含空白或控制字符", + ), + PersonalAccessTokenError::Rejected => (Kind::Invalid, "PAT 被拒绝,请检查令牌和权限"), + PersonalAccessTokenError::Unavailable => (Kind::Unavailable, "PAT 验证服务暂不可用"), + PersonalAccessTokenError::InvalidResponse => (Kind::BadGateway, "PAT 身份信息无效"), + }, + Error::InvalidInput => (Kind::Invalid, "账号数据格式无效"), + Error::InvalidCredential => (Kind::Invalid, "凭据无效,请更正或重新授权"), + Error::MissingRefreshToken => (Kind::Invalid, "账号没有刷新令牌,请重新授权"), + Error::RefreshRejected { code, .. } => ( + Kind::Invalid, + refresh_rejection_message(code.as_deref()).unwrap_or("刷新令牌已失效,请重新授权"), + ), + Error::AccountBanned { .. } => (Kind::Invalid, "上游账号已停用"), + Error::NotFound => (Kind::NotFound, "账号不存在,请刷新列表"), + Error::RefreshLeaseUnavailable => (Kind::Conflict, "令牌刷新繁忙,请稍后重试"), + Error::RefreshUnavailable => (Kind::Unavailable, "令牌刷新服务暂不可用"), + Error::RefreshUpstream { status, code, .. } => ( + Kind::BadGateway, + refresh_rejection_message(code.as_deref()).unwrap_or(match status { + 401 | 403 => "令牌刷新被拒绝,请检查账号授权", + 429 => "令牌刷新过于频繁,请稍后重试", + 500..=599 => "令牌刷新服务异常,请稍后重试", + _ => "令牌刷新失败", + }), + ), + Error::RefreshAmbiguous { .. } => (Kind::Ambiguous, "刷新结果未知,核对账号状态前请勿重试"), + }; + let error = provider_admin_error(kind).with_public_message(public_message); + match upstream_message { + Some(message) => error.with_message(message), + None => error, + } +} + +fn refresh_rejection_message(code: Option<&str>) -> Option<&'static str> { + // 与官方 Codex 的失败原因对齐;只解释管理提示,不改动 Worker 的终态/退避判定 + match code.map(str::to_ascii_lowercase).as_deref() { + Some("refresh_token_expired") => Some("刷新令牌已过期,请重新授权"), + Some("refresh_token_reused") => Some("刷新令牌已被使用,请重新授权"), + Some("refresh_token_invalidated") => Some("刷新令牌已被撤销,请重新授权"), + // token_expired 也用于 RT 校验失败,不据此断言具体到期原因 + Some("token_expired") => Some("刷新令牌不可用,请重新授权"), + Some("invalid_grant") => Some("刷新令牌无效,请重新授权"), + _ => None, + } +} + +pub(super) const fn credential_admin_error_code(error: &CodexCredentialAdminError) -> &'static str { + match error { + CodexCredentialAdminError::PersonalAccessToken(_) => { + "personal_access_token_validation_failed" + } + CodexCredentialAdminError::InvalidInput => "invalid_input", + CodexCredentialAdminError::InvalidCredential => "invalid_credential", + CodexCredentialAdminError::NotFound => "not_found", + CodexCredentialAdminError::MissingRefreshToken => "missing_refresh_token", + CodexCredentialAdminError::RefreshLeaseUnavailable => "refresh_lease_unavailable", + CodexCredentialAdminError::RefreshRejected { .. } => "refresh_rejected", + CodexCredentialAdminError::AccountBanned { .. } => "account_banned", + CodexCredentialAdminError::RefreshUnavailable => "refresh_unavailable", + CodexCredentialAdminError::RefreshUpstream { .. } => "refresh_upstream_failed", + CodexCredentialAdminError::RefreshAmbiguous { .. } => "refresh_ambiguous", + } +} + +pub(super) const fn provider_admin_error_code(kind: ProviderAdminErrorKind) -> &'static str { + match kind { + ProviderAdminErrorKind::Invalid => "invalid", + ProviderAdminErrorKind::Unsupported => "unsupported", + ProviderAdminErrorKind::NotFound => "not_found", + ProviderAdminErrorKind::Conflict => "conflict", + ProviderAdminErrorKind::Ambiguous => "ambiguous", + ProviderAdminErrorKind::Unavailable => "unavailable", + ProviderAdminErrorKind::CredentialRefreshRequired => "credential_refresh_required", + ProviderAdminErrorKind::BadGateway => "bad_gateway", + ProviderAdminErrorKind::Internal => "internal", + } +} + +pub(super) fn log_import_failure(stage: &'static str, error: &'static str) { + tracing::warn!( + import_stage = stage, + import_error = error, + "OpenAI credential import preparation failed" + ); +} + +pub(super) fn map_oauth_error(error: CodexOAuthAdminError) -> ProviderAdminError { + use crate::credential::token_client::AuthorizationCodeExchangeError as Exchange; + use CodexOAuthAdminError as Error; + use ProviderAdminErrorKind as Kind; + let (kind, message) = match &error { + Error::InvalidInput => (Kind::Invalid, "授权参数无效,请重新授权"), + Error::CallbackRejected => (Kind::Invalid, "授权回调校验失败,请重新授权"), + Error::TokenRejected | Error::Exchange(Exchange::Rejected) => { + (Kind::Invalid, "授权码被拒绝,请重新授权") + } + Error::Credential => (Kind::Invalid, "授权返回的凭据无效"), + Error::NotFound | Error::FlowExpired => (Kind::NotFound, "授权流程已失效,请重新授权"), + Error::Conflict => (Kind::Conflict, "授权状态冲突,请核对账号状态"), + Error::Exchange(Exchange::Ambiguous { .. }) => { + (Kind::Ambiguous, "授权结果未知,核对账号状态前请勿重试") + } + Error::Exchange(Exchange::Connection { + timed_out: true, .. + }) => (Kind::Unavailable, "连接授权服务超时,请检查出站连接"), + Error::Exchange(Exchange::Connection { + timed_out: false, .. + }) => (Kind::Unavailable, "无法连接授权服务,请检查出站连接"), + Error::Exchange(Exchange::Unavailable) => (Kind::Unavailable, "授权服务暂不可用"), + Error::StorageUnavailable => (Kind::Unavailable, "授权状态存储暂不可用"), + }; + provider_admin_error(kind) + .with_public_message(message) + .with_source(error) +} + +pub(super) const fn oauth_error_code(error: &CodexOAuthAdminError) -> &'static str { + use crate::credential::token_client::AuthorizationCodeExchangeError as Exchange; + match error { + CodexOAuthAdminError::InvalidInput => "invalid_input", + CodexOAuthAdminError::NotFound => "not_found", + CodexOAuthAdminError::Conflict => "conflict", + CodexOAuthAdminError::FlowExpired => "flow_expired", + CodexOAuthAdminError::CallbackRejected => "callback_rejected", + CodexOAuthAdminError::TokenRejected + | CodexOAuthAdminError::Exchange(Exchange::Rejected) => "token_rejected", + CodexOAuthAdminError::Exchange(Exchange::Unavailable) => "upstream_unavailable", + CodexOAuthAdminError::Exchange(Exchange::Connection { + timed_out: true, .. + }) => "connect_timeout", + CodexOAuthAdminError::Exchange(Exchange::Connection { + timed_out: false, .. + }) => "connect_failed", + CodexOAuthAdminError::Exchange(Exchange::Ambiguous { .. }) => "ambiguous", + CodexOAuthAdminError::StorageUnavailable => "storage_unavailable", + CodexOAuthAdminError::Credential => "credential", + } +} + +pub(super) fn map_quota_error(error: CodexCredentialQuotaError) -> ProviderAdminError { + use CodexCredentialQuotaError as Error; + use ProviderAdminErrorKind as Kind; + let (kind, public_message, upstream_message) = match error { + Error::Profile(source) => { + return provider_admin_error(Kind::Unavailable) + .with_public_message("预热客户端身份不可用") + .with_source(source); + } + Error::InvalidCredentialData => (Kind::Invalid, "凭据或额度数据无效", None), + Error::NotFound => (Kind::NotFound, "账号不存在", None), + Error::RevisionConflict => (Kind::Conflict, "凭据已更新,请刷新账号列表", None), + Error::CredentialRefreshRequired => (Kind::Unavailable, "请先刷新令牌", None), + Error::Repository(_) | Error::Store { .. } => (Kind::Unavailable, "额度查询暂不可用", None), + Error::Upstream { + status, + code, + detail, + } => { + // 公开提示只使用已知状态和错误码,原始上游材料留在内部诊断 + let (kind, public_message) = match (status, code.as_deref()) { + (Some(401), Some("token_revoked")) => { + (Kind::BadGateway, "访问令牌已撤销,请刷新令牌或重新授权") + } + (Some(401), _) => (Kind::BadGateway, "账号认证失败,请检查授权状态"), + (Some(403), _) => (Kind::BadGateway, "额度查询被拒绝,请检查账号权限"), + (Some(429), _) => (Kind::BadGateway, "额度查询过于频繁,请稍后重试"), + (Some(500..=599), _) => (Kind::BadGateway, "额度服务异常,请稍后重试"), + _ => (Kind::Unavailable, "额度查询失败"), + }; + let upstream_message = + format!("OpenAI 额度查询失败:上游 HTTP {status:?},code = {code:?}:{detail}"); + (kind, public_message, Some(upstream_message)) + } + }; + let error = provider_admin_error(kind).with_public_message(public_message); + match upstream_message { + Some(message) => error.with_message(message), + None => error, + } +} + +pub(super) fn map_profile_statistics_error( + error: CodexProfileStatisticsError, +) -> ProviderAdminError { + use CodexProfileStatisticsError as Error; + + match error { + Error::InvalidCredentialData => provider_admin_error(ProviderAdminErrorKind::Invalid), + Error::NotFound => provider_admin_error(ProviderAdminErrorKind::NotFound), + Error::Store { .. } | Error::TransportUnavailable => { + provider_admin_error(ProviderAdminErrorKind::Unavailable) + } + Error::CredentialRefreshRequired { upstream_body } => { + let mut error = provider_admin_error(ProviderAdminErrorKind::CredentialRefreshRequired) + .with_public_message("请先刷新令牌"); + if let Some(body) = upstream_body { + error = error.with_message(format!( + "OpenAI profile-statistics upstream returned HTTP 401: {}", + bounded_upstream_body(&body) + )); + } + error + } + Error::Upstream { + status, + body, + retry_after_seconds, + } => { + let retry_after = retry_after_seconds + .map(|seconds| format!("; retry-after={seconds}s")) + .unwrap_or_default(); + provider_admin_error(ProviderAdminErrorKind::BadGateway) + .with_public_message("资料查询失败") + .with_message(format!( + "OpenAI profile-statistics upstream returned HTTP {status}{retry_after}: {}", + bounded_upstream_body(&body) + )) + } + } +} + +pub(super) fn map_profile_avatar_error(error: CodexProfileAvatarError) -> ProviderAdminError { + match error { + CodexProfileAvatarError::ProfileStatistics(error) => map_profile_statistics_error(error), + CodexProfileAvatarError::Missing => provider_admin_error(ProviderAdminErrorKind::NotFound), + CodexProfileAvatarError::InvalidSource | CodexProfileAvatarError::Upstream { .. } => { + provider_admin_error(ProviderAdminErrorKind::BadGateway) + } + CodexProfileAvatarError::TransportUnavailable => { + provider_admin_error(ProviderAdminErrorKind::Unavailable) + } + } +} + +pub(super) fn map_reset_credits_error(error: CodexResetCreditsError) -> ProviderAdminError { + use CodexResetCreditsError as Error; + + match error { + Error::InvalidCredentialData => provider_admin_error(ProviderAdminErrorKind::Invalid), + Error::NotFound => provider_admin_error(ProviderAdminErrorKind::NotFound), + Error::Store { .. } | Error::TransportUnavailable => { + provider_admin_error(ProviderAdminErrorKind::Unavailable) + } + Error::CredentialRefreshRequired { upstream_body } => { + let mut error = + provider_admin_error(ProviderAdminErrorKind::CredentialRefreshRequired); + if let Some(body) = upstream_body { + error = error.with_message(format!( + "OpenAI reset-credit upstream returned HTTP 401: {}", + bounded_upstream_body(&body) + )); + } + error + } + Error::Upstream { + status, + body, + retry_after_seconds, + } => { + let retry_after = retry_after_seconds + .map(|seconds| format!("; retry-after={seconds}s")) + .unwrap_or_default(); + provider_admin_error(ProviderAdminErrorKind::BadGateway).with_message(format!( + "OpenAI reset-credit upstream returned HTTP {status}{retry_after}: {}", + bounded_upstream_body(&body) + )) + } + Error::ConsumeResultUnknown => provider_admin_error(ProviderAdminErrorKind::Ambiguous) + .with_message( + "OpenAI reset-credit consume result is unknown; refresh the credit list before retrying", + ), + } +} + +fn bounded_upstream_body(body: &str) -> String { + const MAX_ADMIN_UPSTREAM_BODY_BYTES: usize = 8 * 1024; + if body.len() <= MAX_ADMIN_UPSTREAM_BODY_BYTES { + return body.to_owned(); + } + let mut end = MAX_ADMIN_UPSTREAM_BODY_BYTES; + while !body.is_char_boundary(end) { + end -= 1; + } + body[..end].to_owned() +} + +pub(super) fn map_catalog_error(error: CodexCredentialCatalogError) -> ProviderAdminError { + use crate::credential::CredentialRepositoryError; + use CodexCredentialCatalogError as Error; + use ProviderAdminErrorKind as Kind; + let (kind, message) = match error { + Error::Credential(source) => { + let (kind, message) = match &source { + CredentialRepositoryError::InvalidCredentialData(_) => { + (Kind::Invalid, "查询模型的凭据无效,请检查账号授权") + } + CredentialRepositoryError::RevisionConflict(_) => { + (Kind::Conflict, "账号已更新,请重新查询模型") + } + CredentialRepositoryError::Store(_) => (Kind::Unavailable, "账号存储暂不可用"), + }; + return provider_admin_error(kind) + .with_public_message(message) + .with_source(source); + } + Error::InvalidEtag => (Kind::Invalid, "模型目录版本无效,请重新查询"), + Error::NoEligibleCredential => (Kind::NotFound, "没有可查询模型的账号"), + Error::ConcurrentUpdate => (Kind::Conflict, "模型目录正在更新,请稍后重试"), + Error::Upstream { .. } => (Kind::Unavailable, "模型查询失败"), + Error::Cache => (Kind::Unavailable, "模型目录缓存暂不可用"), + Error::Profile(source) => { + return provider_admin_error(Kind::Unavailable) + .with_public_message("模型目录客户端身份不可用") + .with_source(source); + } + }; + provider_admin_error(kind).with_public_message(message) +} + +pub(super) fn map_client_profile_error( + error: crate::profile::selection::ClientProfileError, +) -> ProviderAdminError { + use crate::profile::selection::ClientProfileError; + let message = match error { + ClientProfileError::Invalid => "客户端身份字段或版本组合不合法", + ClientProfileError::InvalidInstallationSeed => "安装身份种子必须是带连字符的 UUID", + ClientProfileError::InvalidUserAgent => { + "User-Agent 必须是 1 至 4096 字节的单行 ASCII 文本,且首尾不能含空白" + } + ClientProfileError::CompanionHeadersRequired => { + "无法识别 User-Agent,请补充 originator 和有效的 Core version" + } + ClientProfileError::CompanionHeadersConflict => { + "originator 或 Core version 与 User-Agent 不一致" + } + ClientProfileError::ReleaseUnavailable => { + "此客户端、平台与架构尚无已核验发布版本,请选择固定版本或稍后重试" + } + }; + provider_admin_error(ProviderAdminErrorKind::Invalid).with_public_message(message) +} diff --git a/backend/crates/providers/openai/src/admin/mod.rs b/backend/crates/providers/openai/src/admin/mod.rs index 11f5649de..83a3a59db 100644 --- a/backend/crates/providers/openai/src/admin/mod.rs +++ b/backend/crates/providers/openai/src/admin/mod.rs @@ -1,2131 +1,11 @@ -//! OpenAI 管理边界:Provider preparation 与 Redis OAuth pending 适配 +//! OpenAI 管理边界的模块门面 +mod credentials; +mod error; +mod pending; +mod profile; +mod provider; mod quota; -use std::collections::BTreeMap; -use std::sync::Arc; -use std::time::SystemTime; - -use async_trait::async_trait; -use bytes::Bytes; -use chrono::{DateTime, Utc}; -use futures::TryStreamExt as _; -use gateway_admin::model::Revision; -use gateway_admin::model::accounts::AccountRecord; -use gateway_admin::model::observability::{ - CalculatedBillingBreakdown, CurrencyCost, DashboardDesktopRelease, DashboardWireAttribute, - DashboardWireProfile, DashboardWireTarget, DecimalAmount, DesktopReleaseStatus, - ProviderBillingInput, -}; -use gateway_admin::model::provider_credentials::{ - AuthorizationMutationTarget, AuthorizationOwnerBinding, AuthorizationStarted, - CompleteAuthorization, ConsumeProviderResetCredit, CredentialCommitGuard, - PendingAuthorizationMutation, PrepareCredentialImport, PrepareCredentialRefresh, - PrepareCredentialRotation, PreparedAuthorizationCommit, PreparedAuthorizationCredential, - PreparedCredentialCreate, PreparedCredentialImport, PreparedCredentialRotation, - PreparedCredentialRotationFacts, ProviderDocument, ProviderExport, - ProviderExportCredentialInput, ProviderModel, ProviderModelCatalogDocument, ProviderModels, - ProviderProfileActivityInsights, ProviderProfileAvatar, ProviderProfileAvatarStreamError, - ProviderProfileDailyUsage, ProviderProfileInvocation, ProviderProfileStatistics, - ProviderProfileStatisticsSummary, ProviderQuota, ProviderQuotaCredits, - ProviderQuotaReadRequest, ProviderQuotaRequest, ProviderQuotaWindow, ProviderQuotaWindowRole, - ProviderResetCredit, ProviderResetCreditResult, ProviderResetCredits, ProviderSubscription, - QuotaLocalUsageAttribution, -}; -use gateway_admin::model::quota_forecast_sampling::QuotaForecastObservation; -use gateway_admin::ports::provider::{ProviderAdmin, ProviderAdminError, ProviderAdminErrorKind}; -use gateway_core::account::{ - CredentialCasUpdateParts, CredentialRevision, LoadedCredential, NewProviderAccount, - OpaqueProviderData, PlaintextCredential, ProviderAccount, ProviderAccountId, - ProviderAccountStore, -}; -use gateway_core::error::StoreErrorKind; -use gateway_core::metering::Money; -use gateway_core::operation::{GenerateRequest, Operation, ProtocolPayload, RawJsonPayload}; -use gateway_core::provider_ports::{ - NewOAuthPendingFlow, OAuthPendingBinding, OAuthPendingClaimOutcome, OAuthPendingConsumeOutcome, - OAuthPendingFlowPort, OAuthPendingPutOutcome, OAuthPendingReleaseOutcome, ProviderStoreError, - ProviderStoreErrorKind, -}; -use gateway_core::routing::{ProviderKind, UpstreamModelId}; -use gateway_protocol::openai::OPENAI_PROTOCOL; -use secrecy::{ExposeSecret as _, SecretString}; -use serde::Deserialize; -use serde_json::{Map, Number, Value}; - -use crate::credential::{ - CodexAccountQuotaSnapshot, CodexCredentialAdmin, CodexCredentialAdminError, - CodexCredentialAdminService, CodexCredentialCatalogError, CodexCredentialCatalogService, - CodexCredentialProfileService, CodexCredentialQuotaError, CodexCredentialQuotaService, - CodexOAuthAdmin, CodexOAuthAdminError, CodexOAuthPendingClaimOutcome, CodexOAuthPendingStore, - CodexOAuthPendingStoreError, CodexPendingAuthorization, CodexProfileAvatarError, - CodexProfileStatisticsError, CodexQuotaWindow, CodexQuotaWindowKind, CodexQuotaWindowRole, - CodexResetCreditsError, CompleteCodexOAuthAuthorization, CompletedCodexOAuthCredential, - ExportManagedCodexCredential, StartCodexOAuthAuthorization, StoredCodexPendingAuthorization, -}; -use crate::credential::{ - CodexCredentialCodec, CodexOAuthSecret, oauth_owner_ref, parse_access_token_expiration, -}; -use crate::transport::CodexWebSocketPool; -use crate::transport::profile::{ - CodexDesktopReleaseSnapshot, CodexDesktopReleaseStatus, CodexWireProfile, CodexWireProfileState, -}; -use crate::transport::{ - CodexProfileAvatar, CodexProfileStatistics, OpenAiBillingUsage, openai_billing_breakdown, -}; - -const PROVIDER_NAME: &str = "openai"; -const PENDING_DOCUMENT_SCHEMA_VERSION: u64 = 3; - -/// OpenAI 对终态 Admin port 的唯一实现 -pub(crate) struct OpenAiAdminProvider { - provider_kind: ProviderKind, - profile: CodexWireProfileState, - accounts: Arc, - credentials: Arc, - oauth: Arc, - profile_statistics: Arc, - quota: Arc, - catalog: Arc, - websocket_pool: Arc, - desktop_release: CodexDesktopReleaseStatus, -} - -pub(crate) struct OpenAiAdminServices { - pub(crate) credentials: Arc, - pub(crate) oauth: Arc, - pub(crate) profile_statistics: Arc, - pub(crate) quota: Arc, - pub(crate) catalog: Arc, -} - -impl OpenAiAdminProvider { - #[must_use] - pub(crate) fn new( - provider_kind: ProviderKind, - profile: CodexWireProfileState, - accounts: Arc, - services: OpenAiAdminServices, - websocket_pool: Arc, - desktop_release: CodexDesktopReleaseStatus, - ) -> Self { - Self { - provider_kind, - profile, - accounts, - credentials: services.credentials, - oauth: services.oauth, - profile_statistics: services.profile_statistics, - quota: services.quota, - catalog: services.catalog, - websocket_pool, - desktop_release, - } - } - - async fn account( - &self, - account_id: &ProviderAccountId, - ) -> Result { - self.accounts - .get_account(account_id) - .await - .map_err(map_store_error)? - .filter(|account| account.provider() == &self.provider_kind) - .ok_or_else(|| provider_admin_error(ProviderAdminErrorKind::NotFound)) - } - - async fn preserve_existing_installation_id( - &self, - mut incoming: NewProviderAccount, - ) -> Result { - let Some(existing) = self - .accounts - .get_account(incoming.account.id()) - .await - .map_err(map_store_error)? - else { - return Ok(incoming); - }; - if existing.provider() != incoming.account.provider() - || existing.upstream_user_id() != incoming.account.upstream_user_id() - || existing.upstream_account_id() != incoming.account.upstream_account_id() - { - return Ok(incoming); - } - let current = self - .accounts - .load_current_credential(existing.id()) - .await - .map_err(map_store_error)?; - incoming.credential = CodexCredentialCodec::preserve_installation_id( - &incoming.credential, - ¤t.credential, - ) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; - Ok(incoming) - } -} - -#[async_trait] -impl ProviderAdmin for OpenAiAdminProvider { - fn is_direct_account(&self, authentication_kind: &str) -> bool { - crate::credential::is_direct_account_kind(authentication_kind) - } - - fn peer_model_eligible(&self, account: &AccountRecord, model: &str) -> Option { - account_from_record(account).ok().map(|account| { - crate::credential::CodexSelectionModel::Requested(model).allows_account(&account) - }) - } - - fn compile_privacy_policy( - &self, - policy: &gateway_core::settings::privacy::CodexPrivacyPolicy, - ) -> Result< - Arc, - gateway_core::settings::privacy::PrivacyError, - > { - crate::transport::privacy::compile(policy) - } - - fn preview_privacy_policy( - &self, - request: gateway_core::settings::privacy::PrivacyPreviewRequest, - ) -> Result< - gateway_core::settings::privacy::PrivacyPreviewResult, - gateway_core::settings::privacy::PrivacyError, - > { - crate::transport::privacy::preview(request) - } - - fn account_capabilities( - &self, - _account_id: &ProviderAccountId, - authentication_kind: &str, - ) -> gateway_admin::model::accounts::ProviderAccountCapabilities { - let oauth = authentication_kind == crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH; - gateway_admin::model::accounts::ProviderAccountCapabilities { - quota_settings_supported: oauth, - quota_credits: oauth, - quota: oauth, - quota_refresh: oauth, - profile: oauth, - subscription: oauth, - avatar: oauth, - reset_credits: oauth, - consume_reset_credit: oauth, - } - } - - fn pricing_catalog(&self) -> gateway_admin::model::pricing::ProviderPricingCatalog { - crate::transport::usage::pricing_catalog() - } - - fn client_profile_options( - &self, - ) -> Result { - self.profile - .selection_options() - .map_err(map_client_profile_error) - } - - fn preview_client_profile( - &self, - configuration: &gateway_core::account::OpaqueProviderData, - ) -> Result { - if configuration - .expose_to_provider() - .contains_key("installationSeed") - || gateway_core::settings::request_profiles::inherited_fields(configuration).is_some() - { - return Err(provider_admin_error(ProviderAdminErrorKind::Invalid) - .with_public_message("安装身份种子只能在 API 密钥中设置")); - } - self.profile - .preview_selection(configuration) - .map_err(map_client_profile_error) - } - - fn preview_key_client_profile( - &self, - key: &gateway_core::account::OpaqueProviderData, - global: Option<&gateway_core::account::OpaqueProviderData>, - ) -> Result { - crate::transport::profile::identity::inherited_identity_fields(key) - .map_err(map_client_profile_error)?; - let profile = gateway_core::settings::request_profiles::resolve_key_profile(key, global); - self.profile - .preview_selection(&profile) - .map_err(map_client_profile_error) - } - - fn merge_batch_key_profile( - &self, - current: Option<&gateway_core::account::OpaqueProviderData>, - update: Option<&Option>, - installation_seed: Option, - ) -> Result, ProviderAdminError> { - crate::transport::profile::identity::merge_batch_key_profile( - current, - update, - installation_seed, - ) - .map_err(map_client_profile_error) - } - - fn provider_kind(&self) -> &ProviderKind { - &self.provider_kind - } - - fn plan_type_display(&self, plan_type: &str) -> String { - // Pro 三档沿用管理端短名,其余已知套餐使用 Codex /status 的名称 - match plan_type.to_ascii_lowercase().as_str() { - "free" => "Free", - "go" => "Go", - "plus" => "Plus", - "pro" => "Pro", - "prolite" => "ProLite", - "promax" => "ProMax", - "team" | "self_serve_business_usage_based" => "Business", - "self_serve_business_prolite" => "Business Premium", - "business" | "ent26" | "enterprise" | "hc" | "enterprise_cbp_usage_based" => { - "Enterprise" - } - "enterprise_cbp_automation" => "Enterprise (Automation)", - "edu" | "education" => "Edu", - "edu_plus" => "Edu Plus", - "edu_pro" => "Edu Pro", - "sci" => "Academic Researchers", - "sci_plus" => "Academic Researchers Plus", - _ => plan_type, - } - .to_owned() - } - - async fn account_unavailable(&self, account_id: &ProviderAccountId) { - self.websocket_pool.evict_account(account_id.as_str()).await; - } - - async fn account_facts_changed(&self, account_ids: &[ProviderAccountId]) { - if account_ids.is_empty() { - return; - } - self.quota.invalidate_scheduling(account_ids); - if let Err(error) = self.catalog.invalidate_accounts(account_ids).await { - tracing::warn!( - account_count = account_ids.len(), - error = %error, - "OpenAI model catalog invalidation failed after account commit" - ); - } - } - - async fn connection_test_operation( - &self, - upstream_model: &UpstreamModelId, - input_text: &str, - ) -> Result { - build_connection_test_operation(upstream_model, input_text) - } - - fn dashboard_wire_profile(&self) -> Option { - let profile = self.profile.snapshot(); - let release = self.desktop_release.snapshot(); - let user_agent = profile.user_agent(); - let client_identity = format!("{}; {}", profile.originator, profile.desktop_version); - let release = dashboard_desktop_release(&profile, release); - Some(DashboardWireProfile { - provider: self.provider_kind.as_str().to_owned(), - product: profile.originator, - version: profile.codex_version, - build: None, - target: DashboardWireTarget { - os_type: profile.os_type, - os_version: profile.os_version, - arch: profile.arch, - terminal: profile.terminal, - }, - user_agent, - attributes: vec![DashboardWireAttribute { - key: "client_identifier".to_owned(), - value: client_identity, - }], - verified_at: Some(profile.verified_at), - release: Some(release), - }) - } - - fn configured_wire_profile( - &self, - configuration: &OpaqueProviderData, - ) -> Option { - use crate::transport::profile::identity::RequestProfileSelection; - use crate::transport::profile::selection::{ClientKind, ClientPlatform, VersionMode}; - let selection = RequestProfileSelection::parse(configuration).ok()?; - let profile = selection.resolve(&self.profile).ok()?; - let custom = selection.version_mode() == VersionMode::Fixed; - let release = selection.preset().and_then(|selection| { - let (checked_at, error) = self.profile.client_release_status( - selection.client, - selection.platform, - selection.architecture(), - ); - if custom { - None - } else if selection.client == ClientKind::Desktop - && selection.platform == ClientPlatform::Macos - { - Some(dashboard_desktop_release( - &profile, - self.desktop_release.snapshot(), - )) - } else { - Some(DashboardDesktopRelease { - status: if error.is_some() { - DesktopReleaseStatus::Failed - } else if checked_at.is_some() { - DesktopReleaseStatus::Current - } else { - DesktopReleaseStatus::Unchecked - }, - checked_at, - latest_version: Some(profile.codex_version.clone()), - latest_build: None, - published_at: None, - minimum_system_version: None, - hardware_requirements: None, - download_url: None, - download_size: None, - signature_present: None, - error, - }) - } - }); - Some(DashboardWireProfile { - provider: self.provider_kind.as_str().to_owned(), - product: profile.originator.clone(), - version: profile.codex_version.clone(), - build: None, - user_agent: profile.user_agent(), - target: DashboardWireTarget { - os_type: profile.os_type, - os_version: profile.os_version, - arch: profile.arch, - terminal: profile.terminal, - }, - attributes: vec![ - DashboardWireAttribute { - key: "client_identifier".to_owned(), - value: if profile.client_kind == ClientKind::Desktop { - format!("{}; {}", profile.originator, profile.desktop_version) - } else { - profile.originator - }, - }, - DashboardWireAttribute { - key: "version_policy".to_owned(), - value: if custom { "fixed" } else { "latest" }.to_owned(), - }, - ], - verified_at: (!custom && profile.verified_at != chrono::DateTime::UNIX_EPOCH) - .then_some(profile.verified_at), - release, - }) - } - - fn calculated_billing( - &self, - input: &ProviderBillingInput, - ) -> Result, ProviderAdminError> { - let (Some(input_tokens), Some(output_tokens)) = (input.input_tokens, input.output_tokens) - else { - return Ok(None); - }; - let Some(breakdown) = openai_billing_breakdown( - &input.upstream_model_id, - OpenAiBillingUsage::new( - input_tokens, - output_tokens, - input.cached_input_tokens.unwrap_or_default(), - input.cache_write_input_tokens.unwrap_or_default(), - ), - input.service_tier.as_deref(), - ) else { - return Ok(None); - }; - let total_amount = currency_cost(breakdown.total_amount())?; - if total_amount != input.total { - return Ok(None); - } - Ok(Some(CalculatedBillingBreakdown { - // 历史总额只能核对费用拆分,不能证明当时保存过长上下文标记 - long_context_billing_applied: false, - image: None, - custom_multiplier_bps: breakdown.custom_multiplier_bps(), - input_amount: currency_cost(breakdown.input_amount())?, - output_amount: currency_cost(breakdown.output_amount())?, - cache_read_amount: currency_cost(breakdown.cache_read_amount())?, - cache_write_amount: currency_cost(breakdown.cache_write_amount())?, - standard_amount: currency_cost(breakdown.standard_amount())?, - total_amount, - input_price_per_million: currency_cost(breakdown.input_price_per_million())?, - output_price_per_million: currency_cost(breakdown.output_price_per_million())?, - cache_read_price_per_million: currency_cost(breakdown.cache_read_price_per_million())?, - cache_write_price_per_million: currency_cost( - breakdown.cache_write_price_per_million(), - )?, - service_tier: breakdown.service_tier().map(str::to_owned), - multiplier_percent: breakdown.multiplier_percent(), - })) - } - - fn evaluate_usage_pricing( - &self, - input: &gateway_admin::ports::provider::ProviderUsagePricingInput, - pricing: Option<&gateway_core::metering::ModelPriceOverride>, - ) -> Result, ProviderAdminError> { - let (Some(input_tokens), Some(output_tokens), Some(cached), Some(written)) = ( - input.usage.input_tokens, - input.usage.output_tokens, - input.usage.cached_input_tokens, - input.usage.cache_write_input_tokens, - ) else { - return Ok(None); - }; - if input.usage.image_input_tokens != Some(0) || input.usage.image_output_tokens != Some(0) { - return Ok(None); - } - let usage = OpenAiBillingUsage::new(input_tokens, output_tokens, cached, written); - Ok( - crate::transport::usage::openai_billing_breakdown_with_override( - &input.upstream_model_id, - usage, - input.service_tier.as_deref(), - pricing, - ), - ) - } - - async fn prepare_import( - &self, - command: PrepareCredentialImport, - ) -> Result { - let prepared = self - .credentials - .prepare_import_document_with_proxy( - Value::Object(command.document.into_provider_data().into_inner()), - command.default_outbound_proxy.as_ref(), - ) - .await - .inspect_err(|error| { - log_import_failure("prepare_document", credential_admin_error_code(error)); - }) - .map_err(map_credential_admin_error)?; - let observed_at = Utc::now(); - let mut credentials = Vec::with_capacity(prepared.accounts().len()); - for account in prepared.into_accounts() { - let account = self - .preserve_existing_installation_id(account) - .await - .inspect_err(|error| { - log_import_failure( - "preserve_installation_id", - provider_admin_error_code(error.kind()), - ); - })?; - credentials.push(prepared_create(account, observed_at)?); - } - Ok(PreparedCredentialImport { - provider_kind: self.provider_kind.clone(), - credentials, - }) - } - - async fn start_authorization( - &self, - pending: gateway_admin::model::provider_credentials::PendingAuthorizationMutation, - ) -> Result { - if pending.provider_kind() != &self.provider_kind { - return Err(provider_admin_error(ProviderAdminErrorKind::Invalid)); - } - if let gateway_admin::model::provider_credentials::AuthorizationMutationTarget::Reauthorize { account_id } = pending.target() - && self.account(account_id).await?.authentication_kind() != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH { - return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); - } - let started = self - .oauth - .start_authorization(StartCodexOAuthAuthorization { mutation: pending }) - .await - .map_err(map_oauth_error)?; - Ok(AuthorizationStarted { - flow_id: started.flow_id, - authorization_url: started.authorization_url, - expires_at: started.expires_at, - }) - } - - async fn complete_authorization( - &self, - command: CompleteAuthorization, - ) -> Result { - let request_id = command.context.request_id.clone(); - let binding = AuthorizationOwnerBinding::from_context(&command.context); - let completed = self - .oauth - .complete_authorization(CompleteCodexOAuthAuthorization { - owner_ref: oauth_owner_ref(binding.owner()), - flow_id: command.flow_id, - callback_url: SecretString::from(command.callback_url), - }) - .await - .inspect_err(|error| { - tracing::warn!( - request_id = %request_id, - oauth_stage = "complete_authorization", - oauth_error = oauth_error_code(error), - "OpenAI OAuth authorization completion failed" - ); - }) - .map_err(map_oauth_error)?; - let (mutation, completed_credential, authorization_guard) = completed.into_parts(); - let credential = match (mutation.target(), completed_credential) { - ( - AuthorizationMutationTarget::Create { .. }, - CompletedCodexOAuthCredential::Create(credential), - ) => prepared_create(*credential, Utc::now()) - .map(|credential| PreparedAuthorizationCredential::Create(Box::new(credential))), - ( - AuthorizationMutationTarget::Reauthorize { .. }, - CompletedCodexOAuthCredential::Reauthorize(credential), - ) => { - prepared_rotation(*credential, mutation.provider_kind().clone()).map(|credential| { - PreparedAuthorizationCredential::Reauthorize(Box::new(credential)) - }) - } - _ => Err(provider_admin_error(ProviderAdminErrorKind::Internal)), - }; - let credential = match credential { - Ok(credential) => credential, - Err(error) => { - if let Err(settlement_error) = authorization_guard.abort().await { - tracing::warn!( - request_id = %request_id, - settlement_error = %settlement_error, - "OpenAI OAuth claim release failed after credential preparation" - ); - return Err(provider_admin_error(ProviderAdminErrorKind::Unavailable)); - } - return Err(error); - } - }; - Ok(PreparedAuthorizationCommit::new(mutation, credential) - .with_authorization_guard(authorization_guard)) - } - - async fn prepare_rotation( - &self, - command: PrepareCredentialRotation, - ) -> Result { - validate_account_record(&command.account, &self.provider_kind)?; - let account_id = ProviderAccountId::new(command.account.id.clone()) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; - let current = self - .accounts - .load_current_credential(&account_id) - .await - .map_err(map_store_error)?; - if !account_matches_record(¤t.account, &command.account) { - return Err(provider_admin_error(ProviderAdminErrorKind::Conflict) - .with_public_message("凭据已更新,请刷新账号列表")); - } - if current.account.authentication_kind() - == crate::credential::CODEX_AUTHENTICATION_KIND_API_KEY - { - let prepared = CodexCredentialAdmin - .prepare_api_key_rotation( - current, - Value::Object(command.provider_material.into_provider_data().into_inner()), - ) - .map_err(map_credential_admin_error)?; - return prepared_rotation(prepared, command.account.provider_kind); - } - if command - .provider_material - .expose_to_provider() - .expose_to_provider() - .contains_key("transport") - { - let prepared = CodexCredentialAdmin - .prepare_transport_update( - current, - Value::Object(command.provider_material.into_provider_data().into_inner()), - ) - .map_err(map_credential_admin_error)?; - return prepared_rotation(prepared, command.account.provider_kind) - .map(PreparedCredentialRotation::preserving_credential_state); - } - let mut secret = rotation_secret(command.provider_material)?; - if secret.id_token.is_none() { - let runtime = CodexCredentialCodec::decode(¤t.credential) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; - secret.id_token = runtime - .authentication - .oauth() - .and_then(|oauth| oauth.id_token.clone()); - } - let access_token_expires_at = - parse_access_token_expiration(secret.access_token.expose_secret()); - let prepared = CodexCredentialAdmin - .prepare_oauth_rotation(current, secret, None, access_token_expires_at, None) - .map_err(map_credential_admin_error)?; - prepared_rotation(prepared, command.account.provider_kind) - } - - async fn prepare_refresh( - &self, - command: PrepareCredentialRefresh, - ) -> Result { - if command.account.authentication_kind != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH - { - return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); - } - validate_account_record(&command.account, &self.provider_kind)?; - let account_id = ProviderAccountId::new(command.account.id.clone()) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; - let current = self - .accounts - .load_current_credential(&account_id) - .await - .map_err(map_store_error)?; - if !account_matches_record(¤t.account, &command.account) { - return Err(provider_admin_error(ProviderAdminErrorKind::Conflict) - .with_public_message("凭据已更新,请刷新账号列表")); - } - let prepared = self - .credentials - .manual_refresh(current) - .await - .map_err(map_credential_admin_error)?; - prepared_rotation(prepared, command.account.provider_kind) - } - - async fn account_configuration( - &self, - account_id: &ProviderAccountId, - ) -> Result, ProviderAdminError> { - self.account(account_id).await?; - let current = self - .accounts - .load_current_credential(account_id) - .await - .map_err(map_store_error)?; - let data = CodexCredentialCodec::decode_complete(¤t.credential) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; - let value = match data { - crate::credential::CodexCredentialData::ApiKey(data) => { - serde_json::to_value(data.configuration()) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Internal))? - } - crate::credential::CodexCredentialData::OAuth(data) => { - serde_json::json!({"transport": data.transport}) - } - }; - let object = value - .as_object() - .cloned() - .ok_or_else(|| provider_admin_error(ProviderAdminErrorKind::Internal))?; - Ok(Some(ProviderDocument::new( - gateway_core::account::OpaqueProviderData::new(object), - ))) - } - - async fn quota( - &self, - request: ProviderQuotaRequest, - ) -> Result { - let ProviderQuotaRequest { - account_id, - refresh, - rolling_usage: _, - } = request; - let mut account = self.account(&account_id).await?; - if account.authentication_kind() == crate::credential::CODEX_AUTHENTICATION_KIND_API_KEY { - if refresh { - return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); - } - return Ok(empty_quota()); - } - let snapshot = if refresh { - let snapshot = Some( - self.quota - .refresh_account(&account_id) - .await - .map_err(map_quota_error)?, - ); - account = self.account(&account_id).await?; - snapshot - } else { - self.quota - .read_snapshot_for(&account) - .await - .map_err(map_quota_error)? - }; - Ok(project_quota( - snapshot, - account.quota().is_exhausted(), - account.quota_settings(), - )) - } - - async fn read_quotas( - &self, - requests: &[ProviderQuotaReadRequest<'_>], - ) -> Vec> { - self.read_quota_snapshots(requests).await - } - - fn peer_authentication_kinds(&self) -> &[&str] { - &[crate::credential::CODEX_AUTHENTICATION_KIND_API_KEY] - } - - fn peer_connection( - &self, - loaded: &gateway_core::account::LoadedCredential, - ) -> Result, ProviderAdminError> { - if loaded.account.provider() != &self.provider_kind - || !self.supports_peer_connection(loaded.account.authentication_kind()) - { - return Ok(None); - } - let credential = CodexCredentialCodec::decode(&loaded.credential) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; - match credential.authentication { - crate::credential::CodexRuntimeAuthentication::ApiKey(authentication) => { - Ok(Some(gateway_admin::ports::peer::PeerConnection { - base_url: authentication.configuration.base_url, - bearer_token: authentication.secret, - })) - } - crate::credential::CodexRuntimeAuthentication::OAuth(_) => Ok(None), - } - } - - fn quota_history_parser( - &self, - ) -> Option { - Some(quota::history_reading) - } - - fn quota_forecast_observation( - &self, - document: &ProviderDocument, - window: &ProviderQuotaWindow, - ) -> Option { - if window.local_usage_attribution != QuotaLocalUsageAttribution::AccountWide { - return None; - } - let (observed, plan_type) = quota::history_window(document, &window.key)?; - if Some(observed.source()) != window.limit_id.as_deref() - || Some(quota_role(observed.role())) != window.role - || observed.window_seconds()? != window.window_seconds? - { - return None; - } - Some(QuotaForecastObservation { - used_percent: observed.used_percent()?, - reset_at: observed.reset_at()?, - plan_type, - }) - } - - async fn subscription( - &self, - account_id: &ProviderAccountId, - ) -> Result, ProviderAdminError> { - if self.account(account_id).await?.authentication_kind() - != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH - { - return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); - } - self.profile_statistics - .subscription(account_id) - .await - .map(|subscription| { - subscription.map(|subscription| ProviderSubscription { - starts_at: subscription.starts_at, - expires_at: subscription.expires_at, - will_renew: subscription.will_renew, - billing_period: subscription.billing_period, - billing_currency: subscription.billing_currency, - observed_at: subscription.observed_at, - }) - }) - .map_err(map_profile_statistics_error) - } - - async fn profile_statistics( - &self, - account_id: &ProviderAccountId, - ) -> Result { - if self.account(account_id).await?.authentication_kind() - != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH - { - return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); - } - let statistics = self - .profile_statistics - .profile_statistics(account_id) - .await - .map_err(map_profile_statistics_error)?; - Ok(project_profile_statistics(statistics)) - } - - async fn profile_avatar( - &self, - account_id: &ProviderAccountId, - ) -> Result { - if self.account(account_id).await?.authentication_kind() - != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH - { - return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); - } - self.profile_statistics - .profile_avatar(account_id) - .await - .map(project_profile_avatar) - .map_err(map_profile_avatar_error) - } - - async fn reset_credits( - &self, - account_id: &ProviderAccountId, - ) -> Result { - if self.account(account_id).await?.authentication_kind() - != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH - { - return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); - } - self.quota - .list_reset_credits(account_id) - .await - .map(project_reset_credits) - .map_err(map_reset_credits_error) - } - - async fn consume_reset_credit( - &self, - command: ConsumeProviderResetCredit, - ) -> Result { - if self - .account(&command.account_id) - .await? - .authentication_kind() - != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH - { - return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); - } - self.quota - .consume_reset_credit( - &command.account_id, - command.credit_id.as_deref(), - command.redeem_request_id, - ) - .await - .map(|result| ProviderResetCreditResult { - code: result.code, - credit: result.credit.map(project_reset_credit), - }) - .map_err(map_reset_credits_error) - } - - async fn models( - &self, - account_id: &ProviderAccountId, - refresh: bool, - ) -> Result { - let account = self.account(account_id).await?; - let catalog = if refresh { - self.catalog - .refresh_account_catalog(account_id) - .await - .map_err(map_catalog_error)? - } else { - self.catalog - .cached_or_refresh_account_catalog(&account) - .await - .map_err(map_catalog_error)? - }; - let models = catalog - .models() - .iter() - .cloned() - .map(|model| { - let id = UpstreamModelId::new(model.clone()) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Internal))?; - Ok(ProviderModel { id, name: model }) - }) - .collect::, ProviderAdminError>>()?; - Ok(ProviderModels { - models, - observed_at: Some(catalog.observed_at()), - }) - } - - async fn model_catalog_document( - &self, - account_id: &ProviderAccountId, - ) -> Result { - let account = self.account(account_id).await?; - let (models, observed_at) = self - .catalog - .account_catalog_documents(&account) - .await - .map_err(map_catalog_error)?; - // 只有 Codex 原生对象带齐推理强度、上下文窗口等元数据;API 目录只有模型 ID, - // 拼出来的文件不满足 Codex `model_catalog_json` 的加载要求,这里直接拒绝而不降格 - let mut entries = Vec::with_capacity(models.len()); - for model in &models { - if model.document().protocol() != "codex" { - return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported) - .with_public_message("该账号没有可导出的模型目录")); - } - let entry: serde_json::Value = serde_json::from_slice(model.document().body()) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Internal))?; - entries.push(entry); - } - let model_count = entries.len(); - let body = serde_json::to_vec(&serde_json::json!({ "models": entries })) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Internal))?; - let document = RawJsonPayload::new("codex", Bytes::from(body)) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Internal))?; - Ok(ProviderModelCatalogDocument { - document, - model_count, - observed_at: DateTime::::from(observed_at), - }) - } - - async fn export_credentials( - &self, - credentials: Vec, - ) -> Result { - let mut account_ids = Vec::with_capacity(credentials.len()); - let mut items = Vec::with_capacity(credentials.len()); - for input in credentials { - validate_account_record(&input.account, &self.provider_kind)?; - let current = LoadedCredential { - account: account_from_record(&input.account)?, - credential: PlaintextCredential::new( - input.provider_material.into_provider_data().into_inner(), - ), - }; - account_ids.push(current.account.id().clone()); - items.push(ExportManagedCodexCredential { - current, - added_at: input.account.created_at, - updated_at: input.account.updated_at, - }); - } - let document = CodexCredentialAdmin - .format_cpr_export(items) - .and_then(|document| document.into_json()) - .map_err(map_credential_admin_error)?; - let Value::Object(document) = document else { - return Err(provider_admin_error(ProviderAdminErrorKind::Internal)); - }; - Ok(ProviderExport { - provider_kind: self.provider_kind.clone(), - account_ids, - document: ProviderDocument::new(OpaqueProviderData::new(document)), - }) - } -} - -struct OpenAiCredentialCommitGuard { - _guard: crate::credential::PreparedCodexCredentialRotationGuard, -} - -impl CredentialCommitGuard for OpenAiCredentialCommitGuard { - fn finish(self: Box) {} -} - -fn prepared_create( - prepared: NewProviderAccount, - observed_at: DateTime, -) -> Result { - let NewProviderAccount { - account, - model_access, - credential, - } = prepared; - Ok(PreparedCredentialCreate { - model_access, - outbound_proxy: account.outbound_proxy().cloned(), - account_id: account.id().clone(), - provider_kind: account.provider().clone(), - name: account.name().to_owned(), - email: account.email().map(str::to_owned), - upstream_user_id: account.upstream_user_id().map(str::to_owned), - upstream_account_id: account.upstream_account_id().map(str::to_owned), - plan_type: account.plan_type().map(str::to_owned), - authentication_kind: account.authentication_kind().to_owned(), - provider_material: ProviderDocument::new(OpaqueProviderData::new(credential.into_inner())), - has_refresh_token: account.has_refresh_token(), - access_token_expires_at: account.access_token_expires_at().map(DateTime::::from), - next_refresh_at: account.next_refresh_at().map(DateTime::::from), - enabled: account.enabled(), - credential_state: account.credential_state(), - credential_observed_at: observed_at, - }) -} - -fn prepared_rotation( - prepared: crate::credential::PreparedCodexCredentialRotation, - provider_kind: ProviderKind, -) -> Result { - let (profile, credential, replacement_identity, guard) = prepared.into_parts(); - let CredentialCasUpdateParts { - account_id, - expected_revision, - profile: credential_profile, - preserve_profile, - preserve_access_token_expiry, - credential, - has_refresh_token, - access_token_expires_at, - next_refresh_at, - account_state: _, - } = credential.into_parts(); - if profile != credential_profile || profile.account_id != account_id { - return Err(provider_admin_error(ProviderAdminErrorKind::Internal)); - } - let expected_credential_revision = Revision::new(expected_revision.get()) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Internal))?; - Ok(PreparedCredentialRotation::new( - PreparedCredentialRotationFacts { - account_id, - provider_kind, - expected_credential_revision, - replacement_identity, - name: profile.name, - email: profile.email, - plan_type: profile.plan_type, - preserve_profile, - preserve_credential_state: false, - preserve_access_token_expiry, - provider_material: ProviderDocument::new(OpaqueProviderData::new( - credential.into_inner(), - )), - has_refresh_token, - access_token_expires_at: access_token_expires_at.map(DateTime::::from), - next_refresh_at: next_refresh_at.map(DateTime::::from), - }, - Box::new(OpenAiCredentialCommitGuard { _guard: guard }), - )) -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct RotationDocument { - access_token: String, - refresh_token: Option, - id_token: Option, -} - -fn rotation_secret(document: ProviderDocument) -> Result { - let document: RotationDocument = - serde_json::from_value(Value::Object(document.into_provider_data().into_inner())) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; - Ok(CodexOAuthSecret { - access_token: SecretString::from(document.access_token), - refresh_token: document.refresh_token.map(SecretString::from), - id_token: document.id_token.map(SecretString::from), - }) -} - -fn validate_account_record( - account: &AccountRecord, - provider_kind: &ProviderKind, -) -> Result<(), ProviderAdminError> { - if &account.provider_kind != provider_kind || provider_kind.as_str() != PROVIDER_NAME { - return Err(provider_admin_error(ProviderAdminErrorKind::Invalid)); - } - ProviderAccountId::new(account.id.clone()) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; - Ok(()) -} - -fn account_from_record(account: &AccountRecord) -> Result { - let account_id = ProviderAccountId::new(account.id.clone()) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; - let revision = CredentialRevision::new(account.credential_revision.get()) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; - Ok(ProviderAccount::new( - account_id, - account.provider_kind.clone(), - account.name.clone(), - account.upstream_user_id.clone(), - account.authentication_kind.clone(), - revision, - account.access_token_expires_at.map(SystemTime::from), - ) - .with_auto_use_quota_credits(account.auto_use_quota_credits) - .with_outbound_proxy(account.outbound_proxy.clone()) - .with_notes(account.notes.clone()) - .with_profile( - account.email.clone(), - account.upstream_account_id.clone(), - account.plan_type.clone(), - ) - .with_account_facts( - account.enabled, - account.credential_state, - account.quota, - account.last_error_reason, - account.last_error_message.clone(), - ) - .with_model_access(account.model_access.clone()) - .with_refresh_schedule( - account.has_refresh_token, - account.next_refresh_at.map(SystemTime::from), - )) -} - -fn dashboard_desktop_release( - profile: &CodexWireProfile, - snapshot: CodexDesktopReleaseSnapshot, -) -> DashboardDesktopRelease { - let status = if snapshot.checked_at.is_none() { - DesktopReleaseStatus::Unchecked - } else if snapshot.last_error.is_some() { - DesktopReleaseStatus::Failed - } else if snapshot.latest.as_ref().is_some_and(|latest| { - latest.version == profile.desktop_version && latest.build == profile.desktop_build - }) { - DesktopReleaseStatus::Current - } else if snapshot.latest.is_some() { - DesktopReleaseStatus::UpdateAvailable - } else { - DesktopReleaseStatus::Failed - }; - let latest = snapshot.latest; - DashboardDesktopRelease { - status, - checked_at: snapshot.checked_at, - latest_version: latest.as_ref().map(|release| release.version.clone()), - latest_build: latest.as_ref().map(|release| release.build.clone()), - published_at: latest.as_ref().and_then(|release| release.published_at), - minimum_system_version: latest - .as_ref() - .and_then(|release| release.minimum_system_version.clone()), - hardware_requirements: latest - .as_ref() - .and_then(|release| release.hardware_requirements.clone()), - download_url: latest - .as_ref() - .and_then(|release| release.download_url.clone()), - download_size: latest.as_ref().and_then(|release| release.download_size), - signature_present: latest.as_ref().map(|release| release.signature_present), - error: snapshot.last_error, - } -} - -fn account_matches_record(account: &ProviderAccount, record: &AccountRecord) -> bool { - account.id().as_str() == record.id - && account.provider() == &record.provider_kind - && account.upstream_user_id() == record.upstream_user_id.as_deref() - && account.upstream_account_id() == record.upstream_account_id.as_deref() - && account.authentication_kind() == record.authentication_kind -} - -fn empty_quota() -> ProviderQuota { - ProviderQuota { - paused_windows: Vec::new(), - upstream: None, - credits: None, - plan_type: None, - observed_at: None, - refresh_token_expires_at: None, - windows: Vec::new(), - limit_reached: false, - provider_data: None, - } -} - -fn project_quota( - snapshot: Option, - limit_reached: bool, - limits: &gateway_core::account::AccountQuotaSettings, -) -> ProviderQuota { - let mut quota = snapshot - .map(|s| project_quota_snapshot(s, limits)) - .unwrap_or_else(empty_quota); - quota.limit_reached = limit_reached; - quota -} - -fn project_quota_snapshot( - snapshot: CodexAccountQuotaSnapshot, - limits: &gateway_core::account::AccountQuotaSettings, -) -> ProviderQuota { - let mut provider_data = Map::new(); - provider_data.insert( - "remaining_percent".to_owned(), - snapshot - .fact() - .remaining_percent() - .map_or(Value::Null, |value| Value::Number(Number::from(value))), - ); - provider_data.insert( - "exhausted".to_owned(), - Value::Bool(snapshot.quota().is_exhausted()), - ); - let windows: Vec = snapshot - .windows() - .iter() - .filter(|window| should_project_quota_window(window)) - .map(|window| ProviderQuotaWindow { - upstream: None, - key: window.key().to_owned(), - group: quota_group(window.kind()).to_owned(), - label: codex_quota_window_label(window.kind(), window.role(), window.window_seconds()), - limit_id: Some(window.source().to_owned()), - limit_name: window.limit_name().map(str::to_owned), - role: Some(quota_role(window.role())), - local_usage_attribution: if window.is_account_wide() { - QuotaLocalUsageAttribution::AccountWide - } else { - QuotaLocalUsageAttribution::Unavailable - }, - window_seconds: window.window_seconds(), - used_percent: window.used_percent(), - reset_at: window.reset_at(), - limit_reached: window.limit_reached(), - local_usage: None, - provider_data: None, - }) - .collect(); - // 快照级 limit_reached 只看滚动后的窗口触顶:顶层标记是观测事实,不能 - // 在窗口全部过期后继续维持限流 - let limit_reached = quota_windows_limit_reached(&windows); - ProviderQuota { - paused_windows: snapshot - .limit_usage() - .filter(|(key, used)| limits.reached(key, Some(*used))) - .map(|(key, _)| key.to_owned()) - .collect(), - upstream: None, - plan_type: snapshot.plan_type().map(str::to_owned), - observed_at: Some(DateTime::::from(snapshot.observed_at())), - refresh_token_expires_at: None, - windows, - credits: snapshot.credits().map(|credits| ProviderQuotaCredits { - has_credits: credits.has_credits, - unlimited: credits.unlimited, - balance: credits.balance.clone(), - }), - limit_reached, - provider_data: Some(ProviderDocument::new(OpaqueProviderData::new( - provider_data, - ))), - } -} - -fn project_profile_statistics(statistics: CodexProfileStatistics) -> ProviderProfileStatistics { - ProviderProfileStatistics { - display_name: statistics.display_name, - username: statistics.username, - image_url: statistics.image_url, - has_stats_error: statistics.has_stats_error, - summary: ProviderProfileStatisticsSummary { - total_text_tokens: statistics.summary.total_text_tokens, - peak_tokens: statistics.summary.peak_tokens, - longest_task_duration_ms: statistics.summary.longest_task_duration_ms, - current_streak_days: statistics.summary.current_streak_days, - longest_streak_days: statistics.summary.longest_streak_days, - }, - daily_usage: statistics.daily_usage.map(|daily| { - daily - .into_iter() - .map(|entry| ProviderProfileDailyUsage { - date: entry.date, - tokens: entry.tokens, - }) - .collect() - }), - activity_insights: ProviderProfileActivityInsights { - fast_mode_percent: statistics.activity_insights.fast_mode_percent, - reasoning_effort: statistics.activity_insights.reasoning_effort, - reasoning_effort_percent: statistics.activity_insights.reasoning_effort_percent, - skills_explored: statistics.activity_insights.skills_explored, - total_skills_used: statistics.activity_insights.total_skills_used, - total_threads: statistics.activity_insights.total_threads, - invocations: statistics.activity_insights.invocations.map(|invocations| { - invocations - .into_iter() - .map(|invocation| ProviderProfileInvocation { - invocation_type: invocation.invocation_type, - plugin_id: invocation.plugin_id, - plugin_name: invocation.plugin_name, - skill_id: invocation.skill_id, - skill_name: invocation.skill_name, - usage_count: invocation.usage_count, - }) - .collect() - }), - }, - } -} - -fn project_profile_avatar(avatar: CodexProfileAvatar) -> ProviderProfileAvatar { - ProviderProfileAvatar { - content_type: avatar.content_type, - content_length: avatar.content_length, - etag: avatar.etag, - body: Box::pin(avatar.body.map_err(|_| ProviderProfileAvatarStreamError)), - } -} - -fn project_reset_credits( - credits: crate::transport::CodexRateLimitResetCredits, -) -> ProviderResetCredits { - ProviderResetCredits { - available_count: credits.available_count, - credits: credits - .credits - .into_iter() - .map(project_reset_credit) - .collect(), - } -} - -fn project_reset_credit( - credit: crate::transport::CodexRateLimitResetCredit, -) -> ProviderResetCredit { - ProviderResetCredit { - id: credit.id, - status: credit.status, - title: credit.title, - expires_at: credit.expires_at, - reset_type: credit.reset_type, - } -} - -/// `secondary_window` 有时只是上游的空占位:没有时长、重置时间,也没有用量 -/// 它不能被可靠翻译成 5 小时或周额度,因此不应占用账号面板;带有实际事实的 -/// 次级窗口(时长、重置、非零用量或触顶)仍完整保留 -fn should_project_quota_window(window: &CodexQuotaWindow) -> bool { - window.role() != CodexQuotaWindowRole::Secondary - || window.window_seconds().is_some() - || window.reset_at().is_some() - || window.used_percent().is_some_and(|used| used > 0.0) - || window.limit_reached() -} - -fn quota_windows_limit_reached(windows: &[ProviderQuotaWindow]) -> bool { - windows.iter().any(|window| window.limit_reached) -} - -const fn quota_group(kind: CodexQuotaWindowKind) -> &'static str { - match kind { - CodexQuotaWindowKind::Monthly => "monthly", - CodexQuotaWindowKind::ShortTerm | CodexQuotaWindowKind::Weekly => "shortTerm", - CodexQuotaWindowKind::Other => "other", - } -} - -const fn quota_role(role: CodexQuotaWindowRole) -> ProviderQuotaWindowRole { - match role { - CodexQuotaWindowRole::Primary => ProviderQuotaWindowRole::Primary, - CodexQuotaWindowRole::Secondary => ProviderQuotaWindowRole::Secondary, - CodexQuotaWindowRole::Monthly => ProviderQuotaWindowRole::Monthly, - } -} - -/// 按窗口时长显示汉化额度名;额度桶名称通过独立字段投影 -fn codex_quota_window_label( - kind: CodexQuotaWindowKind, - role: CodexQuotaWindowRole, - window_seconds: Option, -) -> String { - match kind { - CodexQuotaWindowKind::Monthly => "月额度".to_owned(), - CodexQuotaWindowKind::Weekly => "周额度".to_owned(), - CodexQuotaWindowKind::ShortTerm => "5小时额度".to_owned(), - CodexQuotaWindowKind::Other => custom_quota_window_label(window_seconds, role), - } -} - -fn custom_quota_window_label(window_seconds: Option, role: CodexQuotaWindowRole) -> String { - let Some(seconds) = window_seconds.filter(|seconds| *seconds > 0) else { - // 与官方客户端一致:没有时长时不臆测为 5 小时或周额度;保留 - // primary/secondary 语义,让用户知道这是上游未标明时长的独立窗口 - return match role { - CodexQuotaWindowRole::Primary => "主额度".to_owned(), - CodexQuotaWindowRole::Secondary => "次级额度".to_owned(), - CodexQuotaWindowRole::Monthly => "月额度".to_owned(), - }; - }; - if seconds % 86_400 == 0 { - format!("{}日额度", seconds / 86_400) - } else if seconds % 3_600 == 0 { - format!("{}小时额度", seconds / 3_600) - } else { - format!("{}分钟额度", seconds.div_ceil(60)) - } -} - -/// 将 Provider-owned PKCE/OIDC 状态保存到 Store 提供的 Redis 原子端口 -pub(crate) struct OpenAiOAuthPendingStore { - port: Arc, - provider_kind: ProviderKind, -} - -impl OpenAiOAuthPendingStore { - pub(crate) const fn new( - port: Arc, - provider_kind: ProviderKind, - ) -> Self { - Self { - port, - provider_kind, - } - } -} - -#[async_trait] -impl CodexOAuthPendingStore for OpenAiOAuthPendingStore { - async fn create( - &self, - pending: &CodexPendingAuthorization, - ) -> Result<(), CodexOAuthPendingStoreError> { - let now = Utc::now(); - let ttl = (pending.expires_at() - now) - .to_std() - .map_err(|_| CodexOAuthPendingStoreError::InvalidValue)?; - let flow = NewOAuthPendingFlow::try_new( - self.provider_kind.clone(), - binding(pending.flow_id())?, - binding(pending.owner_ref())?, - ttl, - OpaqueProviderData::new(encode_pending(pending)), - ) - .map_err(map_pending_store_error)?; - match self - .port - .put_if_absent(flow) - .await - .map_err(map_pending_store_error)? - { - OAuthPendingPutOutcome::Stored => Ok(()), - OAuthPendingPutOutcome::AlreadyExists => Err(CodexOAuthPendingStoreError::Conflict), - } - } - - async fn claim( - &self, - owner_ref: &str, - flow_id: &str, - claim_ref: &str, - claim_ttl: std::time::Duration, - ) -> Result { - let flow = binding(flow_id)?; - let owner = binding(owner_ref)?; - let claim = binding(claim_ref)?; - let outcome = self - .port - .claim_if_owner(&self.provider_kind, &flow, &owner, &claim, claim_ttl) - .await - .map_err(map_pending_store_error)?; - match outcome { - OAuthPendingClaimOutcome::Claimed(payload) => match decode_pending(payload) { - Ok(pending) => Ok(CodexOAuthPendingClaimOutcome::Claimed(Box::new(pending))), - Err(error) => match self - .port - .release_claim(&self.provider_kind, &flow, &owner, &claim) - .await - .map_err(map_pending_store_error)? - { - OAuthPendingReleaseOutcome::Released => Err(error), - OAuthPendingReleaseOutcome::NotFound - | OAuthPendingReleaseOutcome::OwnerMismatch - | OAuthPendingReleaseOutcome::ClaimMismatch => { - Err(CodexOAuthPendingStoreError::Unavailable) - } - }, - }, - OAuthPendingClaimOutcome::NotFound | OAuthPendingClaimOutcome::OwnerMismatch => { - Ok(CodexOAuthPendingClaimOutcome::NotFound) - } - OAuthPendingClaimOutcome::InProgress => Ok(CodexOAuthPendingClaimOutcome::InProgress), - } - } - - async fn release_claim( - &self, - owner_ref: &str, - flow_id: &str, - claim_ref: &str, - ) -> Result { - let flow = binding(flow_id)?; - let owner = binding(owner_ref)?; - let claim = binding(claim_ref)?; - match self - .port - .release_claim(&self.provider_kind, &flow, &owner, &claim) - .await - .map_err(map_pending_store_error)? - { - OAuthPendingReleaseOutcome::Released => Ok(true), - OAuthPendingReleaseOutcome::NotFound - | OAuthPendingReleaseOutcome::OwnerMismatch - | OAuthPendingReleaseOutcome::ClaimMismatch => Ok(false), - } - } - - async fn consume_claim( - &self, - owner_ref: &str, - flow_id: &str, - claim_ref: &str, - ) -> Result { - let flow = binding(flow_id)?; - let owner = binding(owner_ref)?; - let claim = binding(claim_ref)?; - match self - .port - .consume_claim(&self.provider_kind, &flow, &owner, &claim) - .await - .map_err(map_pending_store_error)? - { - OAuthPendingConsumeOutcome::Consumed => Ok(true), - OAuthPendingConsumeOutcome::NotFound - | OAuthPendingConsumeOutcome::OwnerMismatch - | OAuthPendingConsumeOutcome::ClaimMismatch => Ok(false), - } - } -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct PendingDocument { - flow_id: String, - owner_ref: String, - started_request_ref: String, - name: String, - expires_at: DateTime, - state: String, - nonce: String, - code_verifier: String, - installation_id: String, - reauthorization_account_id: Option, - mutation: Map, -} - -fn encode_pending(pending: &CodexPendingAuthorization) -> Map { - let mut document = Map::new(); - document.insert( - "flow_id".to_owned(), - Value::String(pending.flow_id().to_owned()), - ); - document.insert( - "owner_ref".to_owned(), - Value::String(pending.owner_ref().to_owned()), - ); - document.insert( - "started_request_ref".to_owned(), - Value::String(pending.started_request_ref().to_owned()), - ); - document.insert("name".to_owned(), Value::String(pending.name().to_owned())); - document.insert( - "expires_at".to_owned(), - Value::String(pending.expires_at().to_rfc3339()), - ); - document.insert( - "state".to_owned(), - Value::String(pending.state().expose_secret().to_owned()), - ); - document.insert( - "nonce".to_owned(), - Value::String(pending.nonce().expose_secret().to_owned()), - ); - document.insert( - "code_verifier".to_owned(), - Value::String(pending.code_verifier().expose_secret().to_owned()), - ); - document.insert( - "installation_id".to_owned(), - Value::String(pending.installation_id().to_owned()), - ); - document.insert( - "reauthorization_account_id".to_owned(), - pending - .reauthorization() - .map_or(Value::Null, |target| Value::String(target.to_string())), - ); - document.insert( - "mutation".to_owned(), - Value::Object(encode_mutation(pending.mutation())), - ); - document -} - -fn encode_mutation(mutation: &PendingAuthorizationMutation) -> Map { - let mut document = mutation.to_storage_v1(); - document.insert( - "schema_version".to_owned(), - Value::Number(Number::from(PENDING_DOCUMENT_SCHEMA_VERSION)), - ); - document -} - -fn decode_pending( - payload: OpaqueProviderData, -) -> Result { - let document: PendingDocument = serde_json::from_value(Value::Object(payload.into_inner())) - .map_err(|_| CodexOAuthPendingStoreError::InvalidValue)?; - CodexPendingAuthorization::from_stored(StoredCodexPendingAuthorization { - flow_id: document.flow_id, - owner_ref: document.owner_ref, - started_request_ref: document.started_request_ref, - name: document.name, - expires_at: document.expires_at, - state: SecretString::from(document.state), - nonce: SecretString::from(document.nonce), - code_verifier: SecretString::from(document.code_verifier), - installation_id: document.installation_id, - reauthorization_account_id: document.reauthorization_account_id, - mutation: decode_mutation(document.mutation)?, - }) -} - -fn decode_mutation( - mut document: Map, -) -> Result { - if document - .remove("schema_version") - .and_then(|value| value.as_u64()) - != Some(PENDING_DOCUMENT_SCHEMA_VERSION) - { - return Err(CodexOAuthPendingStoreError::InvalidValue); - } - PendingAuthorizationMutation::from_storage_v1(Value::Object(document)) - .map_err(|_| CodexOAuthPendingStoreError::InvalidValue) -} - -fn binding(value: &str) -> Result { - OAuthPendingBinding::try_new(value.to_owned()).map_err(map_pending_store_error) -} - -fn provider_admin_error(kind: ProviderAdminErrorKind) -> ProviderAdminError { - ProviderAdminError::new(kind) -} - -fn build_connection_test_operation( - upstream_model: &UpstreamModelId, - input_text: &str, -) -> Result { - let mut body = Map::new(); - body.insert( - "model".to_owned(), - Value::String(upstream_model.as_str().to_owned()), - ); - body.insert( - "input".to_owned(), - serde_json::json!([{ - "type": "message", - "role": "user", - "content": [{"type": "input_text", "text": input_text}] - }]), - ); - body.insert("stream".to_owned(), Value::Bool(true)); - body.insert("store".to_owned(), Value::Bool(false)); - let payload = ProtocolPayload::json_object(OPENAI_PROTOCOL, body) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; - Ok(Operation::Generate(GenerateRequest::from_protocol_payload( - payload, - ))) -} - -fn currency_cost(money: Money) -> Result { - Ok(CurrencyCost { - currency: money.currency().as_str().to_owned(), - amount: money - .amount() - .to_string() - .parse::() - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Internal))?, - }) -} - -fn map_pending_store_error(error: ProviderStoreError) -> CodexOAuthPendingStoreError { - match error.kind() { - ProviderStoreErrorKind::InvalidData => CodexOAuthPendingStoreError::InvalidValue, - ProviderStoreErrorKind::Conflict => CodexOAuthPendingStoreError::Conflict, - ProviderStoreErrorKind::Unavailable => CodexOAuthPendingStoreError::Unavailable, - } -} - -fn map_store_error(error: gateway_core::error::StoreError) -> ProviderAdminError { - provider_admin_error(match error.kind() { - StoreErrorKind::Conflict => ProviderAdminErrorKind::Conflict, - StoreErrorKind::InvalidData | StoreErrorKind::InvalidState => { - ProviderAdminErrorKind::NotFound - } - StoreErrorKind::Unavailable => ProviderAdminErrorKind::Unavailable, - _ => ProviderAdminErrorKind::Internal, - }) - .with_source(error) -} - -fn map_credential_admin_error(error: CodexCredentialAdminError) -> ProviderAdminError { - use crate::credential::token_client::PersonalAccessTokenError; - use CodexCredentialAdminError as Error; - use ProviderAdminErrorKind as Kind; - let upstream_message = error.upstream_message().map(ToOwned::to_owned); - let (kind, public_message) = match error { - Error::PersonalAccessToken(error) => match error { - PersonalAccessTokenError::InvalidToken => ( - Kind::Invalid, - "请输入完整 PAT,以 at- 开头且不含空白或控制字符", - ), - PersonalAccessTokenError::Rejected => (Kind::Invalid, "PAT 被拒绝,请检查令牌和权限"), - PersonalAccessTokenError::Unavailable => (Kind::Unavailable, "PAT 验证服务暂不可用"), - PersonalAccessTokenError::InvalidResponse => (Kind::BadGateway, "PAT 身份信息无效"), - }, - Error::InvalidInput => (Kind::Invalid, "账号数据格式无效"), - Error::InvalidCredential => (Kind::Invalid, "凭据无效,请更正或重新授权"), - Error::MissingRefreshToken => (Kind::Invalid, "账号没有刷新令牌,请重新授权"), - Error::RefreshRejected { code, .. } => ( - Kind::Invalid, - refresh_rejection_message(code.as_deref()).unwrap_or("刷新令牌已失效,请重新授权"), - ), - Error::AccountBanned { .. } => (Kind::Invalid, "上游账号已停用"), - Error::NotFound => (Kind::NotFound, "账号不存在,请刷新列表"), - Error::RefreshLeaseUnavailable => (Kind::Conflict, "令牌刷新繁忙,请稍后重试"), - Error::RefreshUnavailable => (Kind::Unavailable, "令牌刷新服务暂不可用"), - Error::RefreshUpstream { status, code, .. } => ( - Kind::BadGateway, - refresh_rejection_message(code.as_deref()).unwrap_or(match status { - 401 | 403 => "令牌刷新被拒绝,请检查账号授权", - 429 => "令牌刷新过于频繁,请稍后重试", - 500..=599 => "令牌刷新服务异常,请稍后重试", - _ => "令牌刷新失败", - }), - ), - Error::RefreshAmbiguous { .. } => (Kind::Ambiguous, "刷新结果未知,核对账号状态前请勿重试"), - }; - let error = provider_admin_error(kind).with_public_message(public_message); - match upstream_message { - Some(message) => error.with_message(message), - None => error, - } -} - -fn refresh_rejection_message(code: Option<&str>) -> Option<&'static str> { - // 与官方 Codex 的失败原因对齐;只解释管理提示,不改动 Worker 的终态/退避判定 - match code.map(str::to_ascii_lowercase).as_deref() { - Some("refresh_token_expired") => Some("刷新令牌已过期,请重新授权"), - Some("refresh_token_reused") => Some("刷新令牌已被使用,请重新授权"), - Some("refresh_token_invalidated") => Some("刷新令牌已被撤销,请重新授权"), - // token_expired 也用于 RT 校验失败,不据此断言具体到期原因 - Some("token_expired") => Some("刷新令牌不可用,请重新授权"), - Some("invalid_grant") => Some("刷新令牌无效,请重新授权"), - _ => None, - } -} - -const fn credential_admin_error_code(error: &CodexCredentialAdminError) -> &'static str { - match error { - CodexCredentialAdminError::PersonalAccessToken(_) => { - "personal_access_token_validation_failed" - } - CodexCredentialAdminError::InvalidInput => "invalid_input", - CodexCredentialAdminError::InvalidCredential => "invalid_credential", - CodexCredentialAdminError::NotFound => "not_found", - CodexCredentialAdminError::MissingRefreshToken => "missing_refresh_token", - CodexCredentialAdminError::RefreshLeaseUnavailable => "refresh_lease_unavailable", - CodexCredentialAdminError::RefreshRejected { .. } => "refresh_rejected", - CodexCredentialAdminError::AccountBanned { .. } => "account_banned", - CodexCredentialAdminError::RefreshUnavailable => "refresh_unavailable", - CodexCredentialAdminError::RefreshUpstream { .. } => "refresh_upstream_failed", - CodexCredentialAdminError::RefreshAmbiguous { .. } => "refresh_ambiguous", - } -} - -const fn provider_admin_error_code(kind: ProviderAdminErrorKind) -> &'static str { - match kind { - ProviderAdminErrorKind::Invalid => "invalid", - ProviderAdminErrorKind::Unsupported => "unsupported", - ProviderAdminErrorKind::NotFound => "not_found", - ProviderAdminErrorKind::Conflict => "conflict", - ProviderAdminErrorKind::Ambiguous => "ambiguous", - ProviderAdminErrorKind::Unavailable => "unavailable", - ProviderAdminErrorKind::CredentialRefreshRequired => "credential_refresh_required", - ProviderAdminErrorKind::BadGateway => "bad_gateway", - ProviderAdminErrorKind::Internal => "internal", - } -} - -fn log_import_failure(stage: &'static str, error: &'static str) { - tracing::warn!( - import_stage = stage, - import_error = error, - "OpenAI credential import preparation failed" - ); -} - -fn map_oauth_error(error: CodexOAuthAdminError) -> ProviderAdminError { - use crate::credential::token_client::AuthorizationCodeExchangeError as Exchange; - use CodexOAuthAdminError as Error; - use ProviderAdminErrorKind as Kind; - let (kind, message) = match &error { - Error::InvalidInput => (Kind::Invalid, "授权参数无效,请重新授权"), - Error::CallbackRejected => (Kind::Invalid, "授权回调校验失败,请重新授权"), - Error::TokenRejected | Error::Exchange(Exchange::Rejected) => { - (Kind::Invalid, "授权码被拒绝,请重新授权") - } - Error::Credential => (Kind::Invalid, "授权返回的凭据无效"), - Error::NotFound | Error::FlowExpired => (Kind::NotFound, "授权流程已失效,请重新授权"), - Error::Conflict => (Kind::Conflict, "授权状态冲突,请核对账号状态"), - Error::Exchange(Exchange::Ambiguous { .. }) => { - (Kind::Ambiguous, "授权结果未知,核对账号状态前请勿重试") - } - Error::Exchange(Exchange::Connection { - timed_out: true, .. - }) => (Kind::Unavailable, "连接授权服务超时,请检查出站连接"), - Error::Exchange(Exchange::Connection { - timed_out: false, .. - }) => (Kind::Unavailable, "无法连接授权服务,请检查出站连接"), - Error::Exchange(Exchange::Unavailable) => (Kind::Unavailable, "授权服务暂不可用"), - Error::StorageUnavailable => (Kind::Unavailable, "授权状态存储暂不可用"), - }; - provider_admin_error(kind) - .with_public_message(message) - .with_source(error) -} - -const fn oauth_error_code(error: &CodexOAuthAdminError) -> &'static str { - use crate::credential::token_client::AuthorizationCodeExchangeError as Exchange; - match error { - CodexOAuthAdminError::InvalidInput => "invalid_input", - CodexOAuthAdminError::NotFound => "not_found", - CodexOAuthAdminError::Conflict => "conflict", - CodexOAuthAdminError::FlowExpired => "flow_expired", - CodexOAuthAdminError::CallbackRejected => "callback_rejected", - CodexOAuthAdminError::TokenRejected - | CodexOAuthAdminError::Exchange(Exchange::Rejected) => "token_rejected", - CodexOAuthAdminError::Exchange(Exchange::Unavailable) => "upstream_unavailable", - CodexOAuthAdminError::Exchange(Exchange::Connection { - timed_out: true, .. - }) => "connect_timeout", - CodexOAuthAdminError::Exchange(Exchange::Connection { - timed_out: false, .. - }) => "connect_failed", - CodexOAuthAdminError::Exchange(Exchange::Ambiguous { .. }) => "ambiguous", - CodexOAuthAdminError::StorageUnavailable => "storage_unavailable", - CodexOAuthAdminError::Credential => "credential", - } -} - -fn map_quota_error(error: CodexCredentialQuotaError) -> ProviderAdminError { - use CodexCredentialQuotaError as Error; - use ProviderAdminErrorKind as Kind; - let (kind, public_message, upstream_message) = match error { - Error::Profile(source) => { - return provider_admin_error(Kind::Unavailable) - .with_public_message("预热客户端身份不可用") - .with_source(source); - } - Error::InvalidCredentialData => (Kind::Invalid, "凭据或额度数据无效", None), - Error::NotFound => (Kind::NotFound, "账号不存在", None), - Error::RevisionConflict => (Kind::Conflict, "凭据已更新,请刷新账号列表", None), - Error::CredentialRefreshRequired => (Kind::Unavailable, "请先刷新令牌", None), - Error::Repository(_) | Error::Store { .. } => (Kind::Unavailable, "额度查询暂不可用", None), - Error::Upstream { - status, - code, - detail, - } => { - // 公开提示只使用已知状态和错误码,原始上游材料留在内部诊断 - let (kind, public_message) = match (status, code.as_deref()) { - (Some(401), Some("token_revoked")) => { - (Kind::BadGateway, "访问令牌已撤销,请刷新令牌或重新授权") - } - (Some(401), _) => (Kind::BadGateway, "账号认证失败,请检查授权状态"), - (Some(403), _) => (Kind::BadGateway, "额度查询被拒绝,请检查账号权限"), - (Some(429), _) => (Kind::BadGateway, "额度查询过于频繁,请稍后重试"), - (Some(500..=599), _) => (Kind::BadGateway, "额度服务异常,请稍后重试"), - _ => (Kind::Unavailable, "额度查询失败"), - }; - let upstream_message = - format!("OpenAI 额度查询失败:上游 HTTP {status:?},code = {code:?}:{detail}"); - (kind, public_message, Some(upstream_message)) - } - }; - let error = provider_admin_error(kind).with_public_message(public_message); - match upstream_message { - Some(message) => error.with_message(message), - None => error, - } -} - -fn map_profile_statistics_error(error: CodexProfileStatisticsError) -> ProviderAdminError { - use CodexProfileStatisticsError as Error; - - match error { - Error::InvalidCredentialData => provider_admin_error(ProviderAdminErrorKind::Invalid), - Error::NotFound => provider_admin_error(ProviderAdminErrorKind::NotFound), - Error::Store { .. } | Error::TransportUnavailable => { - provider_admin_error(ProviderAdminErrorKind::Unavailable) - } - Error::CredentialRefreshRequired { upstream_body } => { - let mut error = provider_admin_error(ProviderAdminErrorKind::CredentialRefreshRequired) - .with_public_message("请先刷新令牌"); - if let Some(body) = upstream_body { - error = error.with_message(format!( - "OpenAI profile-statistics upstream returned HTTP 401: {}", - bounded_upstream_body(&body) - )); - } - error - } - Error::Upstream { - status, - body, - retry_after_seconds, - } => { - let retry_after = retry_after_seconds - .map(|seconds| format!("; retry-after={seconds}s")) - .unwrap_or_default(); - provider_admin_error(ProviderAdminErrorKind::BadGateway) - .with_public_message("资料查询失败") - .with_message(format!( - "OpenAI profile-statistics upstream returned HTTP {status}{retry_after}: {}", - bounded_upstream_body(&body) - )) - } - } -} - -fn map_profile_avatar_error(error: CodexProfileAvatarError) -> ProviderAdminError { - match error { - CodexProfileAvatarError::ProfileStatistics(error) => map_profile_statistics_error(error), - CodexProfileAvatarError::Missing => provider_admin_error(ProviderAdminErrorKind::NotFound), - CodexProfileAvatarError::InvalidSource | CodexProfileAvatarError::Upstream { .. } => { - provider_admin_error(ProviderAdminErrorKind::BadGateway) - } - CodexProfileAvatarError::TransportUnavailable => { - provider_admin_error(ProviderAdminErrorKind::Unavailable) - } - } -} - -fn map_reset_credits_error(error: CodexResetCreditsError) -> ProviderAdminError { - use CodexResetCreditsError as Error; - - match error { - Error::InvalidCredentialData => provider_admin_error(ProviderAdminErrorKind::Invalid), - Error::NotFound => provider_admin_error(ProviderAdminErrorKind::NotFound), - Error::Store { .. } | Error::TransportUnavailable => { - provider_admin_error(ProviderAdminErrorKind::Unavailable) - } - Error::CredentialRefreshRequired { upstream_body } => { - let mut error = - provider_admin_error(ProviderAdminErrorKind::CredentialRefreshRequired); - if let Some(body) = upstream_body { - error = error.with_message(format!( - "OpenAI reset-credit upstream returned HTTP 401: {}", - bounded_upstream_body(&body) - )); - } - error - } - Error::Upstream { - status, - body, - retry_after_seconds, - } => { - let retry_after = retry_after_seconds - .map(|seconds| format!("; retry-after={seconds}s")) - .unwrap_or_default(); - provider_admin_error(ProviderAdminErrorKind::BadGateway).with_message(format!( - "OpenAI reset-credit upstream returned HTTP {status}{retry_after}: {}", - bounded_upstream_body(&body) - )) - } - Error::ConsumeResultUnknown => provider_admin_error(ProviderAdminErrorKind::Ambiguous) - .with_message( - "OpenAI reset-credit consume result is unknown; refresh the credit list before retrying", - ), - } -} - -fn bounded_upstream_body(body: &str) -> String { - const MAX_ADMIN_UPSTREAM_BODY_BYTES: usize = 8 * 1024; - if body.len() <= MAX_ADMIN_UPSTREAM_BODY_BYTES { - return body.to_owned(); - } - let mut end = MAX_ADMIN_UPSTREAM_BODY_BYTES; - while !body.is_char_boundary(end) { - end -= 1; - } - body[..end].to_owned() -} - -fn map_catalog_error(error: CodexCredentialCatalogError) -> ProviderAdminError { - use crate::credential::CredentialRepositoryError; - use CodexCredentialCatalogError as Error; - use ProviderAdminErrorKind as Kind; - let (kind, message) = match error { - Error::Credential(source) => { - let (kind, message) = match &source { - CredentialRepositoryError::InvalidCredentialData(_) => { - (Kind::Invalid, "查询模型的凭据无效,请检查账号授权") - } - CredentialRepositoryError::RevisionConflict(_) => { - (Kind::Conflict, "账号已更新,请重新查询模型") - } - CredentialRepositoryError::Store(_) => (Kind::Unavailable, "账号存储暂不可用"), - }; - return provider_admin_error(kind) - .with_public_message(message) - .with_source(source); - } - Error::InvalidEtag => (Kind::Invalid, "模型目录版本无效,请重新查询"), - Error::NoEligibleCredential => (Kind::NotFound, "没有可查询模型的账号"), - Error::ConcurrentUpdate => (Kind::Conflict, "模型目录正在更新,请稍后重试"), - Error::Upstream { .. } => (Kind::Unavailable, "模型查询失败"), - Error::Cache => (Kind::Unavailable, "模型目录缓存暂不可用"), - Error::Profile(source) => { - return provider_admin_error(Kind::Unavailable) - .with_public_message("模型目录客户端身份不可用") - .with_source(source); - } - }; - provider_admin_error(kind).with_public_message(message) -} - -fn map_client_profile_error( - error: crate::transport::profile::selection::ClientProfileError, -) -> ProviderAdminError { - use crate::transport::profile::selection::ClientProfileError; - let message = match error { - ClientProfileError::Invalid => "客户端身份字段或版本组合不合法", - ClientProfileError::InvalidInstallationSeed => "安装身份种子必须是带连字符的 UUID", - ClientProfileError::InvalidUserAgent => { - "User-Agent 必须是 1 至 4096 字节的单行 ASCII 文本,且首尾不能含空白" - } - ClientProfileError::CompanionHeadersRequired => { - "无法识别 User-Agent,请补充 originator 和有效的 Core version" - } - ClientProfileError::CompanionHeadersConflict => { - "originator 或 Core version 与 User-Agent 不一致" - } - ClientProfileError::ReleaseUnavailable => { - "此客户端、平台与架构尚无已核验发布版本,请选择固定版本或稍后重试" - } - }; - provider_admin_error(ProviderAdminErrorKind::Invalid).with_public_message(message) -} +pub(crate) use pending::OpenAiOAuthPendingStore; +pub(crate) use provider::{OpenAiAdminProvider, OpenAiAdminServices}; diff --git a/backend/crates/providers/openai/src/admin/pending.rs b/backend/crates/providers/openai/src/admin/pending.rs new file mode 100644 index 000000000..9fae811b8 --- /dev/null +++ b/backend/crates/providers/openai/src/admin/pending.rs @@ -0,0 +1,270 @@ +//! OAuth pending 的原子存储适配与提交守卫 + +use crate::credential::{ + CodexOAuthPendingClaimOutcome, CodexOAuthPendingStore, CodexOAuthPendingStoreError, + CodexPendingAuthorization, StoredCodexPendingAuthorization, +}; +use async_trait::async_trait; +use chrono::{DateTime, Utc}; +use gateway_admin::model::provider_credentials::PendingAuthorizationMutation; +use gateway_core::account::OpaqueProviderData; +use gateway_core::provider_ports::{ + NewOAuthPendingFlow, OAuthPendingBinding, OAuthPendingClaimOutcome, OAuthPendingConsumeOutcome, + OAuthPendingFlowPort, OAuthPendingPutOutcome, OAuthPendingReleaseOutcome, ProviderStoreError, + ProviderStoreErrorKind, +}; +use gateway_core::routing::ProviderKind; +use secrecy::{ExposeSecret as _, SecretString}; +use serde::Deserialize; +use serde_json::{Map, Number, Value}; +use std::sync::Arc; + +const PENDING_DOCUMENT_SCHEMA_VERSION: u64 = 3; +/// 将 Provider-owned PKCE/OIDC 状态保存到 Store 提供的 Redis 原子端口 +pub(crate) struct OpenAiOAuthPendingStore { + port: Arc, + provider_kind: ProviderKind, +} + +impl OpenAiOAuthPendingStore { + pub(crate) const fn new( + port: Arc, + provider_kind: ProviderKind, + ) -> Self { + Self { + port, + provider_kind, + } + } +} + +#[async_trait] +impl CodexOAuthPendingStore for OpenAiOAuthPendingStore { + async fn create( + &self, + pending: &CodexPendingAuthorization, + ) -> Result<(), CodexOAuthPendingStoreError> { + let now = Utc::now(); + let ttl = (pending.expires_at() - now) + .to_std() + .map_err(|_| CodexOAuthPendingStoreError::InvalidValue)?; + let flow = NewOAuthPendingFlow::try_new( + self.provider_kind.clone(), + binding(pending.flow_id())?, + binding(pending.owner_ref())?, + ttl, + OpaqueProviderData::new(encode_pending(pending)), + ) + .map_err(map_pending_store_error)?; + match self + .port + .put_if_absent(flow) + .await + .map_err(map_pending_store_error)? + { + OAuthPendingPutOutcome::Stored => Ok(()), + OAuthPendingPutOutcome::AlreadyExists => Err(CodexOAuthPendingStoreError::Conflict), + } + } + + async fn claim( + &self, + owner_ref: &str, + flow_id: &str, + claim_ref: &str, + claim_ttl: std::time::Duration, + ) -> Result { + let flow = binding(flow_id)?; + let owner = binding(owner_ref)?; + let claim = binding(claim_ref)?; + let outcome = self + .port + .claim_if_owner(&self.provider_kind, &flow, &owner, &claim, claim_ttl) + .await + .map_err(map_pending_store_error)?; + match outcome { + OAuthPendingClaimOutcome::Claimed(payload) => match decode_pending(payload) { + Ok(pending) => Ok(CodexOAuthPendingClaimOutcome::Claimed(Box::new(pending))), + Err(error) => match self + .port + .release_claim(&self.provider_kind, &flow, &owner, &claim) + .await + .map_err(map_pending_store_error)? + { + OAuthPendingReleaseOutcome::Released => Err(error), + OAuthPendingReleaseOutcome::NotFound + | OAuthPendingReleaseOutcome::OwnerMismatch + | OAuthPendingReleaseOutcome::ClaimMismatch => { + Err(CodexOAuthPendingStoreError::Unavailable) + } + }, + }, + OAuthPendingClaimOutcome::NotFound | OAuthPendingClaimOutcome::OwnerMismatch => { + Ok(CodexOAuthPendingClaimOutcome::NotFound) + } + OAuthPendingClaimOutcome::InProgress => Ok(CodexOAuthPendingClaimOutcome::InProgress), + } + } + + async fn release_claim( + &self, + owner_ref: &str, + flow_id: &str, + claim_ref: &str, + ) -> Result { + let flow = binding(flow_id)?; + let owner = binding(owner_ref)?; + let claim = binding(claim_ref)?; + match self + .port + .release_claim(&self.provider_kind, &flow, &owner, &claim) + .await + .map_err(map_pending_store_error)? + { + OAuthPendingReleaseOutcome::Released => Ok(true), + OAuthPendingReleaseOutcome::NotFound + | OAuthPendingReleaseOutcome::OwnerMismatch + | OAuthPendingReleaseOutcome::ClaimMismatch => Ok(false), + } + } + + async fn consume_claim( + &self, + owner_ref: &str, + flow_id: &str, + claim_ref: &str, + ) -> Result { + let flow = binding(flow_id)?; + let owner = binding(owner_ref)?; + let claim = binding(claim_ref)?; + match self + .port + .consume_claim(&self.provider_kind, &flow, &owner, &claim) + .await + .map_err(map_pending_store_error)? + { + OAuthPendingConsumeOutcome::Consumed => Ok(true), + OAuthPendingConsumeOutcome::NotFound + | OAuthPendingConsumeOutcome::OwnerMismatch + | OAuthPendingConsumeOutcome::ClaimMismatch => Ok(false), + } + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PendingDocument { + flow_id: String, + owner_ref: String, + started_request_ref: String, + name: String, + expires_at: DateTime, + state: String, + nonce: String, + code_verifier: String, + installation_id: String, + reauthorization_account_id: Option, + mutation: Map, +} + +fn encode_pending(pending: &CodexPendingAuthorization) -> Map { + let mut document = Map::new(); + document.insert( + "flow_id".to_owned(), + Value::String(pending.flow_id().to_owned()), + ); + document.insert( + "owner_ref".to_owned(), + Value::String(pending.owner_ref().to_owned()), + ); + document.insert( + "started_request_ref".to_owned(), + Value::String(pending.started_request_ref().to_owned()), + ); + document.insert("name".to_owned(), Value::String(pending.name().to_owned())); + document.insert( + "expires_at".to_owned(), + Value::String(pending.expires_at().to_rfc3339()), + ); + document.insert( + "state".to_owned(), + Value::String(pending.state().expose_secret().to_owned()), + ); + document.insert( + "nonce".to_owned(), + Value::String(pending.nonce().expose_secret().to_owned()), + ); + document.insert( + "code_verifier".to_owned(), + Value::String(pending.code_verifier().expose_secret().to_owned()), + ); + document.insert( + "installation_id".to_owned(), + Value::String(pending.installation_id().to_owned()), + ); + document.insert( + "reauthorization_account_id".to_owned(), + pending + .reauthorization() + .map_or(Value::Null, |target| Value::String(target.to_string())), + ); + document.insert( + "mutation".to_owned(), + Value::Object(encode_mutation(pending.mutation())), + ); + document +} + +fn encode_mutation(mutation: &PendingAuthorizationMutation) -> Map { + let mut document = mutation.to_storage_v1(); + document.insert( + "schema_version".to_owned(), + Value::Number(Number::from(PENDING_DOCUMENT_SCHEMA_VERSION)), + ); + document +} + +fn decode_pending( + payload: OpaqueProviderData, +) -> Result { + let document: PendingDocument = serde_json::from_value(Value::Object(payload.into_inner())) + .map_err(|_| CodexOAuthPendingStoreError::InvalidValue)?; + CodexPendingAuthorization::from_stored(StoredCodexPendingAuthorization { + flow_id: document.flow_id, + owner_ref: document.owner_ref, + started_request_ref: document.started_request_ref, + name: document.name, + expires_at: document.expires_at, + state: SecretString::from(document.state), + nonce: SecretString::from(document.nonce), + code_verifier: SecretString::from(document.code_verifier), + installation_id: document.installation_id, + reauthorization_account_id: document.reauthorization_account_id, + mutation: decode_mutation(document.mutation)?, + }) +} + +fn decode_mutation( + mut document: Map, +) -> Result { + if document + .remove("schema_version") + .and_then(|value| value.as_u64()) + != Some(PENDING_DOCUMENT_SCHEMA_VERSION) + { + return Err(CodexOAuthPendingStoreError::InvalidValue); + } + PendingAuthorizationMutation::from_storage_v1(Value::Object(document)) + .map_err(|_| CodexOAuthPendingStoreError::InvalidValue) +} + +pub(super) fn binding(value: &str) -> Result { + OAuthPendingBinding::try_new(value.to_owned()).map_err(map_pending_store_error) +} +fn map_pending_store_error(error: ProviderStoreError) -> CodexOAuthPendingStoreError { + match error.kind() { + ProviderStoreErrorKind::InvalidData => CodexOAuthPendingStoreError::InvalidValue, + ProviderStoreErrorKind::Conflict => CodexOAuthPendingStoreError::Conflict, + ProviderStoreErrorKind::Unavailable => CodexOAuthPendingStoreError::Unavailable, + } +} diff --git a/backend/crates/providers/openai/src/admin/profile.rs b/backend/crates/providers/openai/src/admin/profile.rs new file mode 100644 index 000000000..3ab2d9197 --- /dev/null +++ b/backend/crates/providers/openai/src/admin/profile.rs @@ -0,0 +1,131 @@ +//! 客户端版本与账号资料的管理展示投影 + +use crate::profile::{CodexDesktopReleaseSnapshot, CodexWireProfile}; +use crate::transport::{CodexProfileAvatar, CodexProfileStatistics}; +use futures::TryStreamExt as _; +use gateway_admin::model::observability::{DashboardDesktopRelease, DesktopReleaseStatus}; +use gateway_admin::model::provider_credentials::{ + ProviderProfileActivityInsights, ProviderProfileAvatar, ProviderProfileAvatarStreamError, + ProviderProfileDailyUsage, ProviderProfileInvocation, ProviderProfileStatistics, + ProviderProfileStatisticsSummary, ProviderResetCredit, ProviderResetCredits, +}; + +pub(super) fn dashboard_desktop_release( + profile: &CodexWireProfile, + snapshot: CodexDesktopReleaseSnapshot, +) -> DashboardDesktopRelease { + let status = if snapshot.checked_at.is_none() { + DesktopReleaseStatus::Unchecked + } else if snapshot.last_error.is_some() { + DesktopReleaseStatus::Failed + } else if snapshot.latest.as_ref().is_some_and(|latest| { + latest.version == profile.desktop_version && latest.build == profile.desktop_build + }) { + DesktopReleaseStatus::Current + } else if snapshot.latest.is_some() { + DesktopReleaseStatus::UpdateAvailable + } else { + DesktopReleaseStatus::Failed + }; + let latest = snapshot.latest; + DashboardDesktopRelease { + status, + checked_at: snapshot.checked_at, + latest_version: latest.as_ref().map(|release| release.version.clone()), + latest_build: latest.as_ref().map(|release| release.build.clone()), + published_at: latest.as_ref().and_then(|release| release.published_at), + minimum_system_version: latest + .as_ref() + .and_then(|release| release.minimum_system_version.clone()), + hardware_requirements: latest + .as_ref() + .and_then(|release| release.hardware_requirements.clone()), + download_url: latest + .as_ref() + .and_then(|release| release.download_url.clone()), + download_size: latest.as_ref().and_then(|release| release.download_size), + signature_present: latest.as_ref().map(|release| release.signature_present), + error: snapshot.last_error, + } +} +pub(super) fn project_profile_statistics( + statistics: CodexProfileStatistics, +) -> ProviderProfileStatistics { + ProviderProfileStatistics { + display_name: statistics.display_name, + username: statistics.username, + image_url: statistics.image_url, + has_stats_error: statistics.has_stats_error, + summary: ProviderProfileStatisticsSummary { + total_text_tokens: statistics.summary.total_text_tokens, + peak_tokens: statistics.summary.peak_tokens, + longest_task_duration_ms: statistics.summary.longest_task_duration_ms, + current_streak_days: statistics.summary.current_streak_days, + longest_streak_days: statistics.summary.longest_streak_days, + }, + daily_usage: statistics.daily_usage.map(|daily| { + daily + .into_iter() + .map(|entry| ProviderProfileDailyUsage { + date: entry.date, + tokens: entry.tokens, + }) + .collect() + }), + activity_insights: ProviderProfileActivityInsights { + fast_mode_percent: statistics.activity_insights.fast_mode_percent, + reasoning_effort: statistics.activity_insights.reasoning_effort, + reasoning_effort_percent: statistics.activity_insights.reasoning_effort_percent, + skills_explored: statistics.activity_insights.skills_explored, + total_skills_used: statistics.activity_insights.total_skills_used, + total_threads: statistics.activity_insights.total_threads, + invocations: statistics.activity_insights.invocations.map(|invocations| { + invocations + .into_iter() + .map(|invocation| ProviderProfileInvocation { + invocation_type: invocation.invocation_type, + plugin_id: invocation.plugin_id, + plugin_name: invocation.plugin_name, + skill_id: invocation.skill_id, + skill_name: invocation.skill_name, + usage_count: invocation.usage_count, + }) + .collect() + }), + }, + } +} + +pub(super) fn project_profile_avatar(avatar: CodexProfileAvatar) -> ProviderProfileAvatar { + ProviderProfileAvatar { + content_type: avatar.content_type, + content_length: avatar.content_length, + etag: avatar.etag, + body: Box::pin(avatar.body.map_err(|_| ProviderProfileAvatarStreamError)), + } +} + +pub(super) fn project_reset_credits( + credits: crate::transport::CodexRateLimitResetCredits, +) -> ProviderResetCredits { + ProviderResetCredits { + available_count: credits.available_count, + credits: credits + .credits + .into_iter() + .map(project_reset_credit) + .collect(), + } +} + +pub(super) fn project_reset_credit( + credit: crate::transport::CodexRateLimitResetCredit, +) -> ProviderResetCredit { + ProviderResetCredit { + id: credit.id, + status: credit.status, + title: credit.title, + expires_at: credit.expires_at, + reset_type: credit.reset_type, + } +} diff --git a/backend/crates/providers/openai/src/admin/provider.rs b/backend/crates/providers/openai/src/admin/provider.rs new file mode 100644 index 000000000..87436ef7d --- /dev/null +++ b/backend/crates/providers/openai/src/admin/provider.rs @@ -0,0 +1,1139 @@ +//! 管理端口的唯一实现与 Provider 服务协调 + +use super::credentials::{ + account_from_record, account_matches_record, prepared_create, prepared_rotation, + rotation_secret, validate_account_record, +}; +use super::error::{ + credential_admin_error_code, log_import_failure, map_catalog_error, map_client_profile_error, + map_credential_admin_error, map_oauth_error, map_profile_avatar_error, + map_profile_statistics_error, map_quota_error, map_reset_credits_error, map_store_error, + oauth_error_code, provider_admin_error, provider_admin_error_code, +}; +use super::profile::{ + dashboard_desktop_release, project_profile_avatar, project_profile_statistics, + project_reset_credit, project_reset_credits, +}; +use super::quota; +use super::quota::{empty_quota, project_quota, quota_role}; +use crate::billing::{OpenAiBillingUsage, openai_billing_breakdown}; +use crate::credential::{ + CodexCredentialAdmin, CodexCredentialAdminService, CodexCredentialCatalogService, + CodexCredentialCodec, CodexCredentialProfileService, CodexCredentialQuotaService, + CodexOAuthAdmin, CompleteCodexOAuthAuthorization, CompletedCodexOAuthCredential, + ExportManagedCodexCredential, StartCodexOAuthAuthorization, oauth_owner_ref, + parse_access_token_expiration, +}; +use crate::profile::{CodexDesktopReleaseStatus, CodexWireProfileState}; +use crate::transport::CodexWebSocketPool; +use async_trait::async_trait; +use bytes::Bytes; +use chrono::{DateTime, Utc}; +use gateway_admin::model::accounts::AccountRecord; +use gateway_admin::model::observability::{ + CalculatedBillingBreakdown, CurrencyCost, DashboardDesktopRelease, DashboardWireAttribute, + DashboardWireProfile, DashboardWireTarget, DecimalAmount, DesktopReleaseStatus, + ProviderBillingInput, +}; +use gateway_admin::model::provider_credentials::{ + AuthorizationMutationTarget, AuthorizationOwnerBinding, AuthorizationStarted, + CompleteAuthorization, ConsumeProviderResetCredit, PrepareCredentialImport, + PrepareCredentialRefresh, PrepareCredentialRotation, PreparedAuthorizationCommit, + PreparedAuthorizationCredential, PreparedCredentialImport, PreparedCredentialRotation, + ProviderDocument, ProviderExport, ProviderExportCredentialInput, ProviderModel, + ProviderModelCatalogDocument, ProviderModels, ProviderProfileAvatar, ProviderProfileStatistics, + ProviderQuota, ProviderQuotaReadRequest, ProviderQuotaRequest, ProviderQuotaWindow, + ProviderResetCreditResult, ProviderResetCredits, ProviderSubscription, + QuotaLocalUsageAttribution, +}; +use gateway_admin::model::quota_forecast::QuotaForecastObservation; +use gateway_admin::ports::provider::{ProviderAdmin, ProviderAdminError, ProviderAdminErrorKind}; +use gateway_core::account::{ + CredentialRevision, LoadedCredential, NewProviderAccount, OpaqueProviderData, + PlaintextCredential, ProviderAccount, ProviderAccountId, ProviderAccountStore, +}; +use gateway_core::metering::Money; +use gateway_core::operation::{GenerateRequest, Operation, ProtocolPayload, RawJsonPayload}; +use gateway_core::routing::{ProviderKind, UpstreamModelId}; +use gateway_protocol::openai::OPENAI_PROTOCOL; +use secrecy::{ExposeSecret as _, SecretString}; +use serde_json::{Map, Value}; +use std::collections::BTreeMap; +use std::sync::Arc; + +/// OpenAI 对终态 Admin port 的唯一实现 +pub(crate) struct OpenAiAdminProvider { + provider_kind: ProviderKind, + profile: CodexWireProfileState, + accounts: Arc, + credentials: Arc, + oauth: Arc, + profile_statistics: Arc, + quota: Arc, + catalog: Arc, + websocket_pool: Arc, + desktop_release: CodexDesktopReleaseStatus, +} + +pub(crate) struct OpenAiAdminServices { + pub(crate) credentials: Arc, + pub(crate) oauth: Arc, + pub(crate) profile_statistics: Arc, + pub(crate) quota: Arc, + pub(crate) catalog: Arc, +} + +impl OpenAiAdminProvider { + #[must_use] + pub(crate) fn new( + provider_kind: ProviderKind, + profile: CodexWireProfileState, + accounts: Arc, + services: OpenAiAdminServices, + websocket_pool: Arc, + desktop_release: CodexDesktopReleaseStatus, + ) -> Self { + Self { + provider_kind, + profile, + accounts, + credentials: services.credentials, + oauth: services.oauth, + profile_statistics: services.profile_statistics, + quota: services.quota, + catalog: services.catalog, + websocket_pool, + desktop_release, + } + } + + async fn account( + &self, + account_id: &ProviderAccountId, + ) -> Result { + self.accounts + .get_account(account_id) + .await + .map_err(map_store_error)? + .filter(|account| account.provider() == &self.provider_kind) + .ok_or_else(|| provider_admin_error(ProviderAdminErrorKind::NotFound)) + } + + async fn preserve_existing_installation_id( + &self, + mut incoming: NewProviderAccount, + ) -> Result { + let Some(existing) = self + .accounts + .get_account(incoming.account.id()) + .await + .map_err(map_store_error)? + else { + return Ok(incoming); + }; + if existing.provider() != incoming.account.provider() + || existing.upstream_user_id() != incoming.account.upstream_user_id() + || existing.upstream_account_id() != incoming.account.upstream_account_id() + { + return Ok(incoming); + } + let current = self + .accounts + .load_current_credential(existing.id()) + .await + .map_err(map_store_error)?; + incoming.credential = CodexCredentialCodec::preserve_installation_id( + &incoming.credential, + ¤t.credential, + ) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; + Ok(incoming) + } +} + +#[async_trait] +impl ProviderAdmin for OpenAiAdminProvider { + fn is_direct_account(&self, authentication_kind: &str) -> bool { + crate::credential::is_direct_account_kind(authentication_kind) + } + + fn peer_model_eligible(&self, account: &AccountRecord, model: &str) -> Option { + account_from_record(account).ok().map(|account| { + crate::credential::CodexSelectionModel::Requested(model).allows_account(&account) + }) + } + + fn compile_privacy_policy( + &self, + policy: &gateway_core::settings::privacy::CodexPrivacyPolicy, + ) -> Result< + Arc, + gateway_core::settings::privacy::PrivacyError, + > { + crate::transport::privacy::compile(policy) + } + + fn preview_privacy_policy( + &self, + request: gateway_core::settings::privacy::PrivacyPreviewRequest, + ) -> Result< + gateway_core::settings::privacy::PrivacyPreviewResult, + gateway_core::settings::privacy::PrivacyError, + > { + crate::transport::privacy::preview(request) + } + + fn account_capabilities( + &self, + _account_id: &ProviderAccountId, + authentication_kind: &str, + ) -> gateway_admin::model::accounts::ProviderAccountCapabilities { + let oauth = authentication_kind == crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH; + gateway_admin::model::accounts::ProviderAccountCapabilities { + credential_refresh: oauth, + reauthorize: oauth, + credential_export: oauth + || authentication_kind == crate::credential::CODEX_AUTHENTICATION_KIND_API_KEY, + model_catalog_download: oauth, + quota_settings_supported: oauth, + quota_credits: oauth, + quota: oauth, + quota_refresh: oauth, + profile: oauth, + subscription: oauth, + avatar: oauth, + reset_credits: oauth, + consume_reset_credit: oauth, + } + } + + fn supported_pricing_bands(&self) -> &'static [&'static str] { + crate::billing::SUPPORTED_PRICING_BANDS + } + + fn pricing_catalog(&self) -> gateway_admin::model::pricing::ProviderPricingCatalog { + crate::billing::pricing_catalog() + } + + fn client_profile_options( + &self, + ) -> Result { + self.profile + .selection_options() + .map_err(map_client_profile_error) + } + + fn preview_client_profile( + &self, + configuration: &gateway_core::account::OpaqueProviderData, + ) -> Result { + if configuration + .expose_to_provider() + .contains_key("installationSeed") + || gateway_core::settings::request_profiles::inherited_fields(configuration).is_some() + { + return Err(provider_admin_error(ProviderAdminErrorKind::Invalid) + .with_public_message("安装身份种子只能在 API 密钥中设置")); + } + self.profile + .preview_selection(configuration) + .map_err(map_client_profile_error) + } + + fn preview_key_client_profile( + &self, + key: &gateway_core::account::OpaqueProviderData, + global: Option<&gateway_core::account::OpaqueProviderData>, + ) -> Result { + crate::profile::identity::inherited_identity_fields(key) + .map_err(map_client_profile_error)?; + let profile = gateway_core::settings::request_profiles::resolve_key_profile(key, global); + self.profile + .preview_selection(&profile) + .map_err(map_client_profile_error) + } + + fn merge_batch_key_profile( + &self, + current: Option<&gateway_core::account::OpaqueProviderData>, + update: Option<&Option>, + installation_seed: Option, + ) -> Result, ProviderAdminError> { + crate::profile::identity::merge_batch_key_profile(current, update, installation_seed) + .map_err(map_client_profile_error) + } + + fn provider_kind(&self) -> &ProviderKind { + &self.provider_kind + } + + fn plan_type_display(&self, plan_type: &str) -> String { + // Pro 三档沿用管理端短名,其余已知套餐使用 Codex /status 的名称 + match plan_type.to_ascii_lowercase().as_str() { + "free" => "Free", + "go" => "Go", + "plus" => "Plus", + "pro" => "Pro", + "prolite" => "ProLite", + "promax" => "ProMax", + "team" | "self_serve_business_usage_based" => "Business", + "self_serve_business_prolite" => "Business Premium", + "business" | "ent26" | "enterprise" | "hc" | "enterprise_cbp_usage_based" => { + "Enterprise" + } + "enterprise_cbp_automation" => "Enterprise (Automation)", + "edu" | "education" => "Edu", + "edu_plus" => "Edu Plus", + "edu_pro" => "Edu Pro", + "sci" => "Academic Researchers", + "sci_plus" => "Academic Researchers Plus", + _ => plan_type, + } + .to_owned() + } + + async fn account_unavailable(&self, account_id: &ProviderAccountId) { + self.websocket_pool.evict_account(account_id.as_str()).await; + } + + async fn account_facts_changed(&self, account_ids: &[ProviderAccountId]) { + if account_ids.is_empty() { + return; + } + self.quota.invalidate_scheduling(account_ids); + if let Err(error) = self.catalog.invalidate_accounts(account_ids).await { + tracing::warn!( + account_count = account_ids.len(), + error = %error, + "OpenAI model catalog invalidation failed after account commit" + ); + } + } + + async fn connection_test_operation( + &self, + upstream_model: &UpstreamModelId, + input_text: &str, + ) -> Result { + build_connection_test_operation(upstream_model, input_text) + } + + fn dashboard_wire_profile(&self) -> Option { + let profile = self.profile.snapshot(); + let release = self.desktop_release.snapshot(); + let user_agent = profile.user_agent(); + let client_identity = format!("{}; {}", profile.originator, profile.desktop_version); + let release = dashboard_desktop_release(&profile, release); + Some(DashboardWireProfile { + provider: self.provider_kind.as_str().to_owned(), + product: profile.originator, + version: profile.codex_version, + build: None, + target: DashboardWireTarget { + os_type: profile.os_type, + os_version: profile.os_version, + arch: profile.arch, + terminal: profile.terminal, + }, + user_agent, + attributes: vec![DashboardWireAttribute { + key: "client_identifier".to_owned(), + value: client_identity, + }], + verified_at: Some(profile.verified_at), + release: Some(release), + }) + } + + fn configured_wire_profile( + &self, + configuration: &OpaqueProviderData, + ) -> Option { + use crate::profile::identity::RequestProfileSelection; + use crate::profile::selection::{ClientKind, ClientPlatform, VersionMode}; + let selection = RequestProfileSelection::parse(configuration).ok()?; + let profile = selection.resolve(&self.profile).ok()?; + let custom = selection.version_mode() == VersionMode::Fixed; + let release = selection.preset().and_then(|selection| { + let (checked_at, error) = self.profile.client_release_status( + selection.client, + selection.platform, + selection.architecture(), + ); + if custom { + None + } else if selection.client == ClientKind::Desktop + && selection.platform == ClientPlatform::Macos + { + Some(dashboard_desktop_release( + &profile, + self.desktop_release.snapshot(), + )) + } else { + Some(DashboardDesktopRelease { + status: if error.is_some() { + DesktopReleaseStatus::Failed + } else if checked_at.is_some() { + DesktopReleaseStatus::Current + } else { + DesktopReleaseStatus::Unchecked + }, + checked_at, + latest_version: Some(profile.codex_version.clone()), + latest_build: None, + published_at: None, + minimum_system_version: None, + hardware_requirements: None, + download_url: None, + download_size: None, + signature_present: None, + error, + }) + } + }); + Some(DashboardWireProfile { + provider: self.provider_kind.as_str().to_owned(), + product: profile.originator.clone(), + version: profile.codex_version.clone(), + build: None, + user_agent: profile.user_agent(), + target: DashboardWireTarget { + os_type: profile.os_type, + os_version: profile.os_version, + arch: profile.arch, + terminal: profile.terminal, + }, + attributes: vec![ + DashboardWireAttribute { + key: "client_identifier".to_owned(), + value: if profile.client_kind == ClientKind::Desktop { + format!("{}; {}", profile.originator, profile.desktop_version) + } else { + profile.originator + }, + }, + DashboardWireAttribute { + key: "version_policy".to_owned(), + value: if custom { "fixed" } else { "latest" }.to_owned(), + }, + ], + verified_at: (!custom && profile.verified_at != chrono::DateTime::UNIX_EPOCH) + .then_some(profile.verified_at), + release, + }) + } + + fn calculated_billing( + &self, + input: &ProviderBillingInput, + ) -> Result, ProviderAdminError> { + let (Some(input_tokens), Some(output_tokens)) = (input.input_tokens, input.output_tokens) + else { + return Ok(None); + }; + let Some(breakdown) = openai_billing_breakdown( + &input.upstream_model_id, + OpenAiBillingUsage::new( + input_tokens, + output_tokens, + input.cached_input_tokens.unwrap_or_default(), + input.cache_write_input_tokens.unwrap_or_default(), + ), + input.service_tier.as_deref(), + ) else { + return Ok(None); + }; + let total_amount = currency_cost(breakdown.total_amount())?; + if total_amount != input.total { + return Ok(None); + } + Ok(Some(CalculatedBillingBreakdown { + // 历史总额只能核对费用拆分,不能证明当时保存过长上下文标记 + long_context_billing_applied: false, + image: None, + custom_multiplier_bps: breakdown.custom_multiplier_bps(), + input_amount: currency_cost(breakdown.input_amount())?, + output_amount: currency_cost(breakdown.output_amount())?, + cache_read_amount: currency_cost(breakdown.cache_read_amount())?, + cache_write_amount: currency_cost(breakdown.cache_write_amount())?, + standard_amount: currency_cost(breakdown.standard_amount())?, + total_amount, + input_price_per_million: currency_cost(breakdown.input_price_per_million())?, + output_price_per_million: currency_cost(breakdown.output_price_per_million())?, + cache_read_price_per_million: currency_cost(breakdown.cache_read_price_per_million())?, + cache_write_price_per_million: currency_cost( + breakdown.cache_write_price_per_million(), + )?, + service_tier: breakdown.service_tier().map(str::to_owned), + multiplier_percent: breakdown.multiplier_percent(), + })) + } + + fn evaluate_usage_pricing( + &self, + input: &gateway_admin::ports::provider::ProviderUsagePricingInput, + pricing: Option<&gateway_core::metering::ModelPriceOverride>, + ) -> Result, ProviderAdminError> { + let (Some(input_tokens), Some(output_tokens), Some(cached), Some(written)) = ( + input.usage.input_tokens, + input.usage.output_tokens, + input.usage.cached_input_tokens, + input.usage.cache_write_input_tokens, + ) else { + return Ok(None); + }; + if input.usage.image_input_tokens != Some(0) || input.usage.image_output_tokens != Some(0) { + return Ok(None); + } + let usage = OpenAiBillingUsage::new(input_tokens, output_tokens, cached, written); + Ok(crate::billing::openai_billing_breakdown_with_override( + &input.upstream_model_id, + usage, + input.service_tier.as_deref(), + pricing, + )) + } + + async fn prepare_import( + &self, + command: PrepareCredentialImport, + ) -> Result { + let prepared = self + .credentials + .prepare_import_document_with_proxy( + Value::Object(command.document.into_provider_data().into_inner()), + command.default_outbound_proxy.as_ref(), + ) + .await + .inspect_err(|error| { + log_import_failure("prepare_document", credential_admin_error_code(error)); + }) + .map_err(map_credential_admin_error)?; + let observed_at = Utc::now(); + let mut credentials = Vec::with_capacity(prepared.accounts().len()); + for account in prepared.into_accounts() { + let account = self + .preserve_existing_installation_id(account) + .await + .inspect_err(|error| { + log_import_failure( + "preserve_installation_id", + provider_admin_error_code(error.kind()), + ); + })?; + credentials.push(prepared_create(account, observed_at)?); + } + Ok(PreparedCredentialImport { + provider_kind: self.provider_kind.clone(), + credentials, + }) + } + + async fn start_authorization( + &self, + pending: gateway_admin::model::provider_credentials::PendingAuthorizationMutation, + ) -> Result { + if pending.provider_kind() != &self.provider_kind { + return Err(provider_admin_error(ProviderAdminErrorKind::Invalid)); + } + if let gateway_admin::model::provider_credentials::AuthorizationMutationTarget::Reauthorize { account_id } = pending.target() + && self.account(account_id).await?.authentication_kind() != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH { + return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); + } + let started = self + .oauth + .start_authorization(StartCodexOAuthAuthorization { mutation: pending }) + .await + .map_err(map_oauth_error)?; + Ok(AuthorizationStarted { + flow_id: started.flow_id, + authorization_url: started.authorization_url, + expires_at: started.expires_at, + }) + } + + async fn complete_authorization( + &self, + command: CompleteAuthorization, + ) -> Result { + let request_id = command.context.request_id.clone(); + let binding = AuthorizationOwnerBinding::from_context(&command.context); + let completed = self + .oauth + .complete_authorization(CompleteCodexOAuthAuthorization { + owner_ref: oauth_owner_ref(binding.owner()), + flow_id: command.flow_id, + callback_url: SecretString::from(command.callback_url), + }) + .await + .inspect_err(|error| { + tracing::warn!( + request_id = %request_id, + oauth_stage = "complete_authorization", + oauth_error = oauth_error_code(error), + "OpenAI OAuth authorization completion failed" + ); + }) + .map_err(map_oauth_error)?; + let (mutation, completed_credential, authorization_guard) = completed.into_parts(); + let credential = match (mutation.target(), completed_credential) { + ( + AuthorizationMutationTarget::Create { .. }, + CompletedCodexOAuthCredential::Create(credential), + ) => prepared_create(*credential, Utc::now()) + .map(|credential| PreparedAuthorizationCredential::Create(Box::new(credential))), + ( + AuthorizationMutationTarget::Reauthorize { .. }, + CompletedCodexOAuthCredential::Reauthorize(credential), + ) => { + prepared_rotation(*credential, mutation.provider_kind().clone()).map(|credential| { + PreparedAuthorizationCredential::Reauthorize(Box::new(credential)) + }) + } + _ => Err(provider_admin_error(ProviderAdminErrorKind::Internal)), + }; + let credential = match credential { + Ok(credential) => credential, + Err(error) => { + if let Err(settlement_error) = authorization_guard.abort().await { + tracing::warn!( + request_id = %request_id, + settlement_error = %settlement_error, + "OpenAI OAuth claim release failed after credential preparation" + ); + return Err(provider_admin_error(ProviderAdminErrorKind::Unavailable)); + } + return Err(error); + } + }; + Ok(PreparedAuthorizationCommit::new(mutation, credential) + .with_authorization_guard(authorization_guard)) + } + + async fn prepare_rotation( + &self, + command: PrepareCredentialRotation, + ) -> Result { + validate_account_record(&command.account, &self.provider_kind)?; + let account_id = ProviderAccountId::new(command.account.id.clone()) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; + let current = self + .accounts + .load_current_credential(&account_id) + .await + .map_err(map_store_error)?; + if !account_matches_record(¤t.account, &command.account) { + return Err(provider_admin_error(ProviderAdminErrorKind::Conflict) + .with_public_message("凭据已更新,请刷新账号列表")); + } + if current.account.authentication_kind() + == crate::credential::CODEX_AUTHENTICATION_KIND_API_KEY + { + let prepared = CodexCredentialAdmin + .prepare_api_key_rotation( + current, + Value::Object(command.provider_material.into_provider_data().into_inner()), + ) + .map_err(map_credential_admin_error)?; + return prepared_rotation(prepared, command.account.provider_kind); + } + if command + .provider_material + .expose_to_provider() + .expose_to_provider() + .contains_key("transport") + { + let prepared = CodexCredentialAdmin + .prepare_transport_update( + current, + Value::Object(command.provider_material.into_provider_data().into_inner()), + ) + .map_err(map_credential_admin_error)?; + return prepared_rotation(prepared, command.account.provider_kind) + .map(PreparedCredentialRotation::preserving_credential_state); + } + let mut secret = rotation_secret(command.provider_material)?; + if secret.id_token.is_none() { + let runtime = CodexCredentialCodec::decode(¤t.credential) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; + secret.id_token = runtime + .authentication + .oauth() + .and_then(|oauth| oauth.id_token.clone()); + } + let access_token_expires_at = + parse_access_token_expiration(secret.access_token.expose_secret()); + let prepared = CodexCredentialAdmin + .prepare_oauth_rotation(current, secret, None, access_token_expires_at, None) + .map_err(map_credential_admin_error)?; + prepared_rotation(prepared, command.account.provider_kind) + } + + async fn prepare_refresh( + &self, + command: PrepareCredentialRefresh, + ) -> Result { + if command.account.authentication_kind != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH + { + return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); + } + validate_account_record(&command.account, &self.provider_kind)?; + let account_id = ProviderAccountId::new(command.account.id.clone()) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; + let current = self + .accounts + .load_current_credential(&account_id) + .await + .map_err(map_store_error)?; + if !account_matches_record(¤t.account, &command.account) { + return Err(provider_admin_error(ProviderAdminErrorKind::Conflict) + .with_public_message("凭据已更新,请刷新账号列表")); + } + let prepared = self + .credentials + .manual_refresh(current) + .await + .map_err(map_credential_admin_error)?; + prepared_rotation(prepared, command.account.provider_kind) + } + + async fn account_configuration( + &self, + account_id: &ProviderAccountId, + ) -> Result, ProviderAdminError> { + self.account(account_id).await?; + let current = self + .accounts + .load_current_credential(account_id) + .await + .map_err(map_store_error)?; + let data = CodexCredentialCodec::decode_complete(¤t.credential) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; + let value = match data { + crate::credential::CodexCredentialData::ApiKey(data) => { + serde_json::to_value(data.configuration()) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Internal))? + } + crate::credential::CodexCredentialData::OAuth(data) => { + serde_json::json!({"transport": data.transport}) + } + }; + let object = value + .as_object() + .cloned() + .ok_or_else(|| provider_admin_error(ProviderAdminErrorKind::Internal))?; + Ok(Some(ProviderDocument::new( + gateway_core::account::OpaqueProviderData::new(object), + ))) + } + + async fn quota( + &self, + request: ProviderQuotaRequest, + ) -> Result { + let ProviderQuotaRequest { + account_id, + refresh, + rolling_usage: _, + } = request; + let mut account = self.account(&account_id).await?; + if account.authentication_kind() == crate::credential::CODEX_AUTHENTICATION_KIND_API_KEY { + if refresh { + return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); + } + return Ok(empty_quota()); + } + let snapshot = if refresh { + let snapshot = Some( + self.quota + .refresh_account(&account_id) + .await + .map_err(map_quota_error)?, + ); + account = self.account(&account_id).await?; + snapshot + } else { + self.quota + .read_snapshot_for(&account) + .await + .map_err(map_quota_error)? + }; + Ok(project_quota( + snapshot, + account.quota().is_exhausted(), + account.quota_settings(), + )) + } + + async fn read_quotas( + &self, + requests: &[ProviderQuotaReadRequest<'_>], + ) -> Vec> { + self.read_quota_snapshots(requests).await + } + + fn peer_authentication_kinds(&self) -> &[&str] { + &[crate::credential::CODEX_AUTHENTICATION_KIND_API_KEY] + } + + fn peer_connection( + &self, + loaded: &gateway_core::account::LoadedCredential, + ) -> Result, ProviderAdminError> { + if loaded.account.provider() != &self.provider_kind + || !self.supports_peer_connection(loaded.account.authentication_kind()) + { + return Ok(None); + } + let credential = CodexCredentialCodec::decode(&loaded.credential) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; + match credential.authentication { + crate::credential::CodexRuntimeAuthentication::ApiKey(authentication) => { + Ok(Some(gateway_admin::ports::peer::PeerConnection { + base_url: authentication.configuration.base_url, + bearer_token: authentication.secret, + })) + } + crate::credential::CodexRuntimeAuthentication::OAuth(_) => Ok(None), + } + } + + fn quota_history_parser( + &self, + ) -> Option { + Some(quota::history_reading) + } + + fn quota_forecast_observation( + &self, + document: &ProviderDocument, + window: &ProviderQuotaWindow, + ) -> Option { + if window.local_usage_attribution != QuotaLocalUsageAttribution::AccountWide { + return None; + } + let (observed, plan_type) = quota::history_window(document, &window.key)?; + if Some(observed.source()) != window.limit_id.as_deref() + || Some(quota_role(observed.role())) != window.role + || observed.window_seconds()? != window.window_seconds? + { + return None; + } + Some(QuotaForecastObservation { + used_percent: observed.used_percent()?, + reset_at: observed.reset_at()?, + plan_type, + }) + } + + async fn subscription( + &self, + account_id: &ProviderAccountId, + ) -> Result, ProviderAdminError> { + if self.account(account_id).await?.authentication_kind() + != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH + { + return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); + } + self.profile_statistics + .subscription(account_id) + .await + .map(|subscription| { + subscription.map(|subscription| ProviderSubscription { + starts_at: subscription.starts_at, + expires_at: subscription.expires_at, + will_renew: subscription.will_renew, + billing_period: subscription.billing_period, + billing_currency: subscription.billing_currency, + observed_at: subscription.observed_at, + }) + }) + .map_err(map_profile_statistics_error) + } + + async fn profile_statistics( + &self, + account_id: &ProviderAccountId, + ) -> Result { + if self.account(account_id).await?.authentication_kind() + != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH + { + return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); + } + let statistics = self + .profile_statistics + .profile_statistics(account_id) + .await + .map_err(map_profile_statistics_error)?; + Ok(project_profile_statistics(statistics)) + } + + async fn profile_avatar( + &self, + account_id: &ProviderAccountId, + ) -> Result { + if self.account(account_id).await?.authentication_kind() + != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH + { + return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); + } + self.profile_statistics + .profile_avatar(account_id) + .await + .map(project_profile_avatar) + .map_err(map_profile_avatar_error) + } + + async fn reset_credits( + &self, + account_id: &ProviderAccountId, + ) -> Result { + if self.account(account_id).await?.authentication_kind() + != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH + { + return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); + } + self.quota + .list_reset_credits(account_id) + .await + .map(project_reset_credits) + .map_err(map_reset_credits_error) + } + + async fn consume_reset_credit( + &self, + command: ConsumeProviderResetCredit, + ) -> Result { + if self + .account(&command.account_id) + .await? + .authentication_kind() + != crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH + { + return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported)); + } + self.quota + .consume_reset_credit( + &command.account_id, + command.credit_id.as_deref(), + command.redeem_request_id, + ) + .await + .map(|result| ProviderResetCreditResult { + code: result.code, + credit: result.credit.map(project_reset_credit), + }) + .map_err(map_reset_credits_error) + } + + async fn models( + &self, + account_id: &ProviderAccountId, + refresh: bool, + ) -> Result { + let account = self.account(account_id).await?; + let catalog = if refresh { + self.catalog + .refresh_account_catalog(account_id) + .await + .map_err(map_catalog_error)? + } else { + self.catalog + .cached_or_refresh_account_catalog(&account) + .await + .map_err(map_catalog_error)? + }; + let models = catalog + .models() + .iter() + .cloned() + .map(|model| { + let id = UpstreamModelId::new(model.clone()) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Internal))?; + Ok(ProviderModel { id, name: model }) + }) + .collect::, ProviderAdminError>>()?; + Ok(ProviderModels { + models, + observed_at: Some(catalog.observed_at()), + }) + } + + async fn model_catalog_document( + &self, + account_id: &ProviderAccountId, + ) -> Result { + let account = self.account(account_id).await?; + let (models, observed_at) = self + .catalog + .account_catalog_documents(&account) + .await + .map_err(map_catalog_error)?; + // 只有 Codex 原生对象带齐推理强度、上下文窗口等元数据;API 目录只有模型 ID, + // 拼出来的文件不满足 Codex `model_catalog_json` 的加载要求,这里直接拒绝而不降格 + let mut entries = Vec::with_capacity(models.len()); + for model in &models { + if model.document().protocol() != "codex" { + return Err(provider_admin_error(ProviderAdminErrorKind::Unsupported) + .with_public_message("该账号没有可导出的模型目录")); + } + let entry: serde_json::Value = serde_json::from_slice(model.document().body()) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Internal))?; + entries.push(entry); + } + let model_count = entries.len(); + let body = serde_json::to_vec(&serde_json::json!({ "models": entries })) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Internal))?; + let document = RawJsonPayload::new("codex", Bytes::from(body)) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Internal))?; + Ok(ProviderModelCatalogDocument { + document, + model_count, + observed_at: DateTime::::from(observed_at), + }) + } + + async fn export_credentials( + &self, + credentials: Vec, + ) -> Result { + let mut account_ids = Vec::with_capacity(credentials.len()); + let mut items = Vec::with_capacity(credentials.len()); + for input in credentials { + validate_account_record(&input.account, &self.provider_kind)?; + let current = LoadedCredential { + account: account_from_record(&input.account)?, + credential: PlaintextCredential::new( + input.provider_material.into_provider_data().into_inner(), + ), + }; + account_ids.push(current.account.id().clone()); + items.push(ExportManagedCodexCredential { + current, + created_at: input.account.created_at, + updated_at: input.account.updated_at, + }); + } + let document = CodexCredentialAdmin + .format_cpr_export(items) + .and_then(|document| document.into_json()) + .map_err(map_credential_admin_error)?; + let Value::Object(document) = document else { + return Err(provider_admin_error(ProviderAdminErrorKind::Internal)); + }; + Ok(ProviderExport { + provider_kind: self.provider_kind.clone(), + account_ids, + document: ProviderDocument::new(OpaqueProviderData::new(document)), + }) + } +} +fn build_connection_test_operation( + upstream_model: &UpstreamModelId, + input_text: &str, +) -> Result { + let mut body = Map::new(); + body.insert( + "model".to_owned(), + Value::String(upstream_model.as_str().to_owned()), + ); + body.insert( + "input".to_owned(), + serde_json::json!([{ + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": input_text}] + }]), + ); + body.insert("stream".to_owned(), Value::Bool(true)); + body.insert("store".to_owned(), Value::Bool(false)); + let payload = ProtocolPayload::json_object(OPENAI_PROTOCOL, body) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; + Ok(Operation::Generate(GenerateRequest::from_protocol_payload( + payload, + ))) +} + +fn currency_cost(money: Money) -> Result { + Ok(CurrencyCost { + currency: money.currency().as_str().to_owned(), + amount: money + .amount() + .to_string() + .parse::() + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Internal))?, + }) +} + +impl OpenAiAdminProvider { + pub(super) async fn read_quota_snapshots( + &self, + requests: &[ProviderQuotaReadRequest<'_>], + ) -> Vec> { + let identities = requests + .iter() + .map(|request| { + if request.account.provider_kind != self.provider_kind { + return Err(provider_admin_error(ProviderAdminErrorKind::NotFound)); + } + let id = ProviderAccountId::new(request.account.id.clone()) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; + let revision = + CredentialRevision::new(request.account.credential_revision.get()) + .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; + Ok((id, revision)) + }) + .collect::>(); + let ids = requests + .iter() + .zip(&identities) + .filter(|(request, _)| { + request.account.authentication_kind + != crate::credential::CODEX_AUTHENTICATION_KIND_API_KEY + }) + .filter_map(|(_, identity)| identity.as_ref().ok().map(|(id, _)| id.clone())) + .collect::>(); + let observations = if ids.is_empty() { + Ok(BTreeMap::new()) + } else { + self.accounts + .get_quotas(&ids) + .await + .map_err(|error| map_quota_error(error.into())) + .map(|values| { + values + .into_iter() + .map(|observation| (observation.account_id.clone(), observation)) + .collect::>() + }) + }; + requests + .iter() + .zip(identities) + .map(|(request, identity)| { + let (id, revision) = identity?; + let snapshot = if request.account.authentication_kind + == crate::credential::CODEX_AUTHENTICATION_KIND_API_KEY + { + return Ok(empty_quota()); + } else { + observations + .as_ref() + .map_err(Clone::clone)? + .get(&id) + .map(|observation| { + self.quota.project_observation(&id, revision, observation) + }) + .transpose() + .map_err(map_quota_error)? + .flatten() + }; + Ok(project_quota( + snapshot, + request.account.quota.is_exhausted(), + &request.account.quota_settings, + )) + }) + .collect() + } +} diff --git a/backend/crates/providers/openai/src/admin/quota.rs b/backend/crates/providers/openai/src/admin/quota.rs index d4f1625ec..33a8fab0e 100644 --- a/backend/crates/providers/openai/src/admin/quota.rs +++ b/backend/crates/providers/openai/src/admin/quota.rs @@ -1,77 +1,169 @@ //! 管理端额度快照与历史请求观测的只读投影 -use super::*; +use crate::credential::{ + CodexAccountQuotaSnapshot, CodexQuotaWindow, CodexQuotaWindowKind, CodexQuotaWindowRole, +}; +use chrono::{DateTime, Utc}; +use gateway_admin::model::provider_credentials::{ + ProviderDocument, ProviderQuota, ProviderQuotaCredits, ProviderQuotaWindow, + ProviderQuotaWindowRole, QuotaLocalUsageAttribution, +}; +use gateway_core::account::OpaqueProviderData; +use serde_json::{Map, Number, Value}; -impl OpenAiAdminProvider { - pub(super) async fn read_quota_snapshots( - &self, - requests: &[ProviderQuotaReadRequest<'_>], - ) -> Vec> { - let identities = requests - .iter() - .map(|request| { - if request.account.provider_kind != self.provider_kind { - return Err(provider_admin_error(ProviderAdminErrorKind::NotFound)); - } - let id = ProviderAccountId::new(request.account.id.clone()) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; - let revision = - CredentialRevision::new(request.account.credential_revision.get()) - .map_err(|_| provider_admin_error(ProviderAdminErrorKind::Invalid))?; - Ok((id, revision)) - }) - .collect::>(); - let ids = requests - .iter() - .zip(&identities) - .filter(|(request, _)| { - request.account.authentication_kind - != crate::credential::CODEX_AUTHENTICATION_KIND_API_KEY - }) - .filter_map(|(_, identity)| identity.as_ref().ok().map(|(id, _)| id.clone())) - .collect::>(); - let observations = if ids.is_empty() { - Ok(BTreeMap::new()) - } else { - self.accounts - .get_quotas(&ids) - .await - .map_err(|error| map_quota_error(error.into())) - .map(|values| { - values - .into_iter() - .map(|observation| (observation.account_id.clone(), observation)) - .collect::>() - }) +pub(super) fn empty_quota() -> ProviderQuota { + ProviderQuota { + paused_windows: Vec::new(), + upstream: None, + credits: None, + plan_type: None, + observed_at: None, + refresh_token_expires_at: None, + windows: Vec::new(), + limit_reached: false, + provider_data: None, + } +} + +pub(super) fn project_quota( + snapshot: Option, + limit_reached: bool, + limits: &gateway_core::account::AccountQuotaSettings, +) -> ProviderQuota { + let mut quota = snapshot + .map(|s| project_quota_snapshot(s, limits)) + .unwrap_or_else(empty_quota); + quota.limit_reached = limit_reached; + quota +} + +fn project_quota_snapshot( + snapshot: CodexAccountQuotaSnapshot, + limits: &gateway_core::account::AccountQuotaSettings, +) -> ProviderQuota { + let mut provider_data = Map::new(); + provider_data.insert( + "remaining_percent".to_owned(), + snapshot + .fact() + .remaining_percent() + .map_or(Value::Null, |value| Value::Number(Number::from(value))), + ); + provider_data.insert( + "exhausted".to_owned(), + Value::Bool(snapshot.quota().is_exhausted()), + ); + let windows: Vec = snapshot + .windows() + .iter() + .filter(|window| should_project_quota_window(window)) + .map(|window| ProviderQuotaWindow { + upstream: None, + key: window.key().to_owned(), + group: quota_group(window.kind()).to_owned(), + label: codex_quota_window_label(window.kind(), window.role(), window.window_seconds()), + limit_id: Some(window.source().to_owned()), + limit_name: window.limit_name().map(str::to_owned), + role: Some(quota_role(window.role())), + local_usage_attribution: if window.is_account_wide() { + QuotaLocalUsageAttribution::AccountWide + } else { + QuotaLocalUsageAttribution::Unavailable + }, + window_seconds: window.window_seconds(), + used_percent: window.used_percent(), + reset_at: window.reset_at(), + limit_reached: window.limit_reached(), + local_usage: None, + provider_data: None, + }) + .collect(); + // 快照级 limit_reached 只看滚动后的窗口触顶:顶层标记是观测事实,不能 + // 在窗口全部过期后继续维持限流 + let limit_reached = quota_windows_limit_reached(&windows); + ProviderQuota { + paused_windows: snapshot + .limit_usage() + .filter(|(key, used)| limits.reached(key, Some(*used))) + .map(|(key, _)| key.to_owned()) + .collect(), + upstream: None, + plan_type: snapshot.plan_type().map(str::to_owned), + observed_at: Some(DateTime::::from(snapshot.observed_at())), + refresh_token_expires_at: None, + windows, + credits: snapshot.credits().map(|credits| ProviderQuotaCredits { + has_credits: credits.has_credits, + unlimited: credits.unlimited, + balance: credits.balance.clone(), + }), + limit_reached, + provider_data: Some(ProviderDocument::new(OpaqueProviderData::new( + provider_data, + ))), + } +} +/// `secondary_window` 有时只是上游的空占位:没有时长、重置时间,也没有用量 +/// 它不能被可靠翻译成 5 小时或周额度,因此不应占用账号面板;带有实际事实的 +/// 次级窗口(时长、重置、非零用量或触顶)仍完整保留 +fn should_project_quota_window(window: &CodexQuotaWindow) -> bool { + window.role() != CodexQuotaWindowRole::Secondary + || window.window_seconds().is_some() + || window.reset_at().is_some() + || window.used_percent().is_some_and(|used| used > 0.0) + || window.limit_reached() +} + +fn quota_windows_limit_reached(windows: &[ProviderQuotaWindow]) -> bool { + windows.iter().any(|window| window.limit_reached) +} + +const fn quota_group(kind: CodexQuotaWindowKind) -> &'static str { + match kind { + CodexQuotaWindowKind::Monthly => "monthly", + CodexQuotaWindowKind::ShortTerm | CodexQuotaWindowKind::Weekly => "shortTerm", + CodexQuotaWindowKind::Other => "other", + } +} + +pub(super) const fn quota_role(role: CodexQuotaWindowRole) -> ProviderQuotaWindowRole { + match role { + CodexQuotaWindowRole::Primary => ProviderQuotaWindowRole::Primary, + CodexQuotaWindowRole::Secondary => ProviderQuotaWindowRole::Secondary, + CodexQuotaWindowRole::Monthly => ProviderQuotaWindowRole::Monthly, + } +} + +/// 按窗口时长显示汉化额度名;额度桶名称通过独立字段投影 +fn codex_quota_window_label( + kind: CodexQuotaWindowKind, + role: CodexQuotaWindowRole, + window_seconds: Option, +) -> String { + match kind { + CodexQuotaWindowKind::Monthly => "月额度".to_owned(), + CodexQuotaWindowKind::Weekly => "周额度".to_owned(), + CodexQuotaWindowKind::ShortTerm => "5小时额度".to_owned(), + CodexQuotaWindowKind::Other => custom_quota_window_label(window_seconds, role), + } +} + +fn custom_quota_window_label(window_seconds: Option, role: CodexQuotaWindowRole) -> String { + let Some(seconds) = window_seconds.filter(|seconds| *seconds > 0) else { + // 与官方客户端一致:没有时长时不臆测为 5 小时或周额度;保留 + // primary/secondary 语义,让用户知道这是上游未标明时长的独立窗口 + return match role { + CodexQuotaWindowRole::Primary => "主额度".to_owned(), + CodexQuotaWindowRole::Secondary => "次级额度".to_owned(), + CodexQuotaWindowRole::Monthly => "月额度".to_owned(), }; - requests - .iter() - .zip(identities) - .map(|(request, identity)| { - let (id, revision) = identity?; - let snapshot = if request.account.authentication_kind - == crate::credential::CODEX_AUTHENTICATION_KIND_API_KEY - { - return Ok(empty_quota()); - } else { - observations - .as_ref() - .map_err(Clone::clone)? - .get(&id) - .map(|observation| { - self.quota.project_observation(&id, revision, observation) - }) - .transpose() - .map_err(map_quota_error)? - .flatten() - }; - Ok(project_quota( - snapshot, - request.account.quota.is_exhausted(), - &request.account.quota_settings, - )) - }) - .collect() + }; + if seconds % 86_400 == 0 { + format!("{}日额度", seconds / 86_400) + } else if seconds % 3_600 == 0 { + format!("{}小时额度", seconds / 3_600) + } else { + format!("{}分钟额度", seconds.div_ceil(60)) } } diff --git a/backend/crates/providers/openai/src/transport/automatic_context.rs b/backend/crates/providers/openai/src/automatic_context.rs similarity index 94% rename from backend/crates/providers/openai/src/transport/automatic_context.rs rename to backend/crates/providers/openai/src/automatic_context.rs index 6c7f5979b..8265bfc10 100644 --- a/backend/crates/providers/openai/src/transport/automatic_context.rs +++ b/backend/crates/providers/openai/src/automatic_context.rs @@ -2,21 +2,21 @@ use serde_json::Value; -pub(super) struct ContextTarget { - pub(super) path: String, +pub(crate) struct ContextTarget { + pub(crate) path: String, open: &'static str, close: &'static str, - pub(super) identified: bool, + pub(crate) identified: bool, } impl ContextTarget { - pub(super) fn is_complete(&self, text: &str) -> bool { + pub(crate) fn is_complete(&self, text: &str) -> bool { let trimmed = text.trim(); trimmed.starts_with(self.open) && trimmed.ends_with(self.close) } } -pub(super) fn locate_contexts( +pub(crate) fn locate_contexts( body: &Value, desktop: bool, mut visit: impl FnMut() -> Result<(), &'static str>, @@ -80,7 +80,7 @@ pub(super) fn locate_contexts( Ok(targets) } -pub(super) fn rewrite_git_context( +pub(crate) fn rewrite_git_context( text: &mut String, max_bytes: usize, edit: impl FnOnce(&mut Value) -> Result, @@ -134,7 +134,7 @@ pub(super) fn rewrite_git_context( Ok(count) } -pub(super) fn parse_xml(text: &str) -> Result, &'static str> { +pub(crate) fn parse_xml(text: &str) -> Result, &'static str> { roxmltree::Document::parse_with_options( text, roxmltree::ParsingOptions { diff --git a/backend/crates/providers/openai/src/billing/calculate.rs b/backend/crates/providers/openai/src/billing/calculate.rs new file mode 100644 index 000000000..87cd91e8d --- /dev/null +++ b/backend/crates/providers/openai/src/billing/calculate.rs @@ -0,0 +1,406 @@ +//! OpenAI Token、缓存、托管工具和服务档位的费用计算 + +use gateway_core::metering::{ + CalculatedCostAmounts, CalculatedCostBreakdown, CalculatedCostRates, CurrencyCode, Decimal, + Money, +}; +use gateway_protocol::openai::events::TokenUsage; +use serde_json::Value; + +use super::catalog::{ + ModelPricing, PricingTier, TokenRates, cache_write_rate, model_matches_rule, model_pricing, + normalize_model_name, pricing_model_name, +}; + +const LONG_CONTEXT_THRESHOLD: u64 = 272_000; +const WEB_SEARCH_CALL_TICKS: u128 = 100_000_000; +const WEB_SEARCH_PREVIEW_NON_REASONING_CALL_TICKS: u128 = 250_000_000; +const FILE_SEARCH_CALL_TICKS: u128 = 25_000_000; + +/// OpenAI 公开 Token 价格计算所需的单次用量事实 +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(crate) struct OpenAiBillingUsage { + input_tokens: u64, + output_tokens: u64, + cached_input_tokens: u64, + cache_write_input_tokens: u64, + image_input_tokens: u64, + image_output_tokens: u64, + web_search_calls: u64, + file_search_calls: u64, + web_search_pricing: Option, +} + +impl OpenAiBillingUsage { + /// 构造不含托管工具费用的 Token 用量 + #[must_use] + pub(crate) const fn new( + input_tokens: u64, + output_tokens: u64, + cached_input_tokens: u64, + cache_write_input_tokens: u64, + ) -> Self { + Self { + input_tokens, + output_tokens, + cached_input_tokens, + cache_write_input_tokens, + image_input_tokens: 0, + image_output_tokens: 0, + web_search_calls: 0, + file_search_calls: 0, + web_search_pricing: None, + } + } + + pub(crate) const fn with_web_search_calls( + mut self, + calls: u64, + pricing: Option, + ) -> Self { + self.web_search_calls = calls; + self.web_search_pricing = pricing; + self + } + + pub(crate) const fn with_file_search_calls(mut self, calls: u64) -> Self { + self.file_search_calls = calls; + self + } +} + +impl From for OpenAiBillingUsage { + fn from(usage: TokenUsage) -> Self { + Self { + input_tokens: usage.input_tokens, + output_tokens: usage.output_tokens, + cached_input_tokens: usage.cached_input_tokens, + cache_write_input_tokens: usage.cache_write_input_tokens, + image_input_tokens: usage.image_input_tokens, + image_output_tokens: usage.image_output_tokens, + web_search_calls: 0, + file_search_calls: 0, + web_search_pricing: None, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum WebSearchPricing { + Standard, + PreviewNonReasoning, +} + +impl WebSearchPricing { + const fn price_per_call_ticks(self) -> u128 { + match self { + Self::Standard => WEB_SEARCH_CALL_TICKS, + Self::PreviewNonReasoning => WEB_SEARCH_PREVIEW_NON_REASONING_CALL_TICKS, + } + } +} + +#[derive(Clone, Copy)] +pub(super) struct TokenAmounts { + pub(super) input_ticks: u128, + pub(super) output_ticks: u128, + pub(super) cache_read_ticks: u128, + pub(super) cache_write_ticks: u128, + pub(super) total_ticks: u128, +} + +/// 按 OpenAI Provider 当前受控价格规则计算费用明细 +#[must_use] +pub(crate) fn openai_billing_breakdown( + model: &str, + usage: OpenAiBillingUsage, + service_tier: Option<&str>, +) -> Option { + token_billing_breakdown_with_context( + model_pricing(model), + usage, + service_tier, + usage.input_tokens > LONG_CONTEXT_THRESHOLD, + None, + ) +} + +/// 使用请求开始时冻结的价格覆盖,不读取管理存储 +#[must_use] +pub(crate) fn openai_billing_breakdown_with_override( + model: &str, + usage: OpenAiBillingUsage, + service_tier: Option<&str>, + pricing: Option<&gateway_core::metering::ModelPriceOverride>, +) -> Option { + token_billing_breakdown_with_context( + model_pricing(model), + usage, + service_tier, + usage.input_tokens > LONG_CONTEXT_THRESHOLD, + pricing, + ) +} + +/// 其他 API 协议仅使用明确配置的标准 Token 单价,不继承 OpenAI 型号与档位规则 +pub(crate) fn configured_token_billing_breakdown( + usage: OpenAiBillingUsage, + pricing: &gateway_core::metering::ModelPriceOverride, +) -> Option { + token_billing_breakdown_with_context(None, usage, None, false, Some(pricing)) +} + +fn token_billing_breakdown_with_context( + pricing: Option, + usage: OpenAiBillingUsage, + service_tier: Option<&str>, + long_context: bool, + custom: Option<&gateway_core::metering::ModelPriceOverride>, +) -> Option { + if usage + .cached_input_tokens + .checked_add(usage.cache_write_input_tokens)? + > usage.input_tokens + || usage.image_input_tokens > 0 + || usage.image_output_tokens > 0 + { + return None; + } + let tool_ticks = web_search_amount_ticks(usage)? + .checked_add(u128::from(usage.file_search_calls).checked_mul(FILE_SEARCH_CALL_TICKS)?)?; + let normalized_tier = normalize_service_tier(service_tier); + let tier = pricing_tier(normalized_tier.as_deref())?; + let (standard_rates, _) = + effective_rates(pricing, custom, PricingTier::Standard, long_context)?; + let (selected_rates, long_context_billing_applied) = + effective_rates(pricing, custom, tier, long_context)?; + let cache_write_percent = pricing.map_or(0, |pricing| pricing.cache_write_percent); + let mut standard = token_amounts( + standard_rates, + cache_write_percent, + usage.input_tokens, + usage.output_tokens, + usage.cached_input_tokens, + usage.cache_write_input_tokens, + )?; + let mut selected = token_amounts( + selected_rates, + cache_write_percent, + usage.input_tokens, + usage.output_tokens, + usage.cached_input_tokens, + usage.cache_write_input_tokens, + )?; + standard.total_ticks = standard.total_ticks.checked_add(tool_ticks)?; + selected.total_ticks = selected.total_ticks.checked_add(tool_ticks)?; + let multiplier_percent = + effective_multiplier_percent(selected.total_ticks, standard.total_ticks)?; + let cache_write_rate = cache_write_rate(selected_rates, cache_write_percent)?; + + CalculatedCostBreakdown::new( + CalculatedCostAmounts::new( + usd_money(selected.input_ticks)?, + usd_money(selected.output_ticks)?, + usd_money(selected.cache_read_ticks)?, + usd_money(selected.cache_write_ticks)?, + usd_money(standard.total_ticks)?, + usd_money(selected.total_ticks)?, + ), + CalculatedCostRates::new( + usd_price_per_million(selected_rates.input_ticks)?, + usd_price_per_million(selected_rates.output_ticks)?, + usd_price_per_million(selected_rates.cache_read_ticks)?, + usd_price_per_million(cache_write_rate)?, + ), + Some(normalized_tier.unwrap_or_else(|| "default".to_owned())), + multiplier_percent, + ) + .with_long_context_billing(long_context_billing_applied) + .with_custom_multiplier(custom.map_or(10_000, |pricing| pricing.multiplier_bps)) +} + +fn effective_rates( + default: Option, + custom: Option<&gateway_core::metering::ModelPriceOverride>, + tier: PricingTier, + long_context: bool, +) -> Option<(TokenRates, bool)> { + let long_band = match tier { + PricingTier::Standard => "long_standard", + PricingTier::Fast => "long_fast", + PricingTier::Flex => "long_flex", + PricingTier::Ultrafast => "long_ultrafast", + }; + let uses_long = long_context + && (default.is_some_and(|p| p.long_standard.is_configured() || p.unpriced_long_context) + || custom.is_some_and(|p| p.bands.contains_key(long_band))); + let band = match (tier, uses_long) { + (PricingTier::Standard, false) => "standard", + (PricingTier::Fast, false) => "fast", + (PricingTier::Flex, false) => "flex", + (PricingTier::Ultrafast, false) => "ultrafast", + (PricingTier::Standard, true) => "long_standard", + (PricingTier::Fast, true) => "long_fast", + (PricingTier::Flex, true) => "long_flex", + (PricingTier::Ultrafast, true) => "long_ultrafast", + }; + if let Some(rates) = custom.and_then(|p| p.bands.get(band)) { + return Some(( + TokenRates { + input_ticks: rates.input.ticks_per_token(), + output_ticks: rates.output.ticks_per_token(), + cache_read_ticks: rates.cache_read.ticks_per_token(), + cache_write_ticks: Some(rates.cache_write.ticks_per_token()), + explicit_cache: true, + }, + uses_long, + )); + } + let default = default?; + Some(( + default.rates(tier, long_context)?, + long_context && default.long_standard.is_configured(), + )) +} + +pub(crate) fn web_search_pricing(model: &str, tools: Option<&[Value]>) -> Option { + let mut standard = false; + let mut preview = false; + for tool_type in tools + .into_iter() + .flatten() + .filter_map(|tool| tool.get("type").and_then(Value::as_str)) + { + if tool_type == "web_search_preview" || tool_type.starts_with("web_search_preview_") { + preview = true; + } else if tool_type == "web_search" || tool_type.starts_with("web_search_") { + standard = true; + } + } + match (standard, preview) { + // 这两个模型将非预览搜索内容按固定 8K 输入块计费 + // 响应缺少足够明细,无法排除与普通输入重复计费,因此保留为未定价 + (true, false) if fixed_block_web_search_model(model) => None, + (true, false) => Some(WebSearchPricing::Standard), + (false, true) if reasoning_model(model) => Some(WebSearchPricing::Standard), + (false, true) => Some(WebSearchPricing::PreviewNonReasoning), + (false, false) | (true, true) => None, + } +} + +fn fixed_block_web_search_model(model: &str) -> bool { + let normalized = normalize_model_name(model); + ["gpt-4o-mini", "gpt-4.1-mini"] + .iter() + .any(|rule| model_matches_rule(&normalized, rule)) +} + +fn reasoning_model(model: &str) -> bool { + let normalized = normalize_model_name(model); + let model = pricing_model_name(&normalized); + model.starts_with("gpt-5") + || matches!( + model, + "gpt-6.2-astra" + | "gpt-6.2-sol" + | "gpt-6-astra" + | "gpt-6.1-sol" + | "gpt-6.1-terra" + | "gpt-6-sol" + | "gpt-6-luna" + ) + || model.starts_with("o1") + || model.starts_with("o3") + || model.starts_with("o4") +} + +fn pricing_tier(service_tier: Option<&str>) -> Option { + match service_tier { + None | Some("default" | "standard") => Some(PricingTier::Standard), + Some("flex") => Some(PricingTier::Flex), + Some("fast" | "priority") => Some(PricingTier::Fast), + Some("ultrafast") => Some(PricingTier::Ultrafast), + Some(_) => None, + } +} + +fn web_search_amount_ticks(usage: OpenAiBillingUsage) -> Option { + if usage.web_search_calls == 0 { + return Some(0); + } + u128::from(usage.web_search_calls).checked_mul(usage.web_search_pricing?.price_per_call_ticks()) +} + +pub(super) fn token_amounts( + rates: TokenRates, + cache_write_percent: u32, + input_tokens: u64, + output_tokens: u64, + cached_input_tokens: u64, + cache_write_input_tokens: u64, +) -> Option { + if cached_input_tokens.checked_add(cache_write_input_tokens)? > input_tokens { + return None; + } + let billed_cache_read = if rates.explicit_cache || rates.cache_read_ticks > 0 { + cached_input_tokens + } else { + 0 + }; + let cache_write_rate = cache_write_rate(rates, cache_write_percent)?; + let billed_cache_write = if rates.explicit_cache || cache_write_rate > 0 { + cache_write_input_tokens + } else { + 0 + }; + let uncached_input = input_tokens + .checked_sub(billed_cache_read)? + .checked_sub(billed_cache_write)?; + let input_ticks = u128::from(uncached_input).checked_mul(rates.input_ticks)?; + let output_ticks = u128::from(output_tokens).checked_mul(rates.output_ticks)?; + let cache_read_ticks = u128::from(billed_cache_read).checked_mul(rates.cache_read_ticks)?; + let cache_write_ticks = u128::from(billed_cache_write).checked_mul(cache_write_rate)?; + let total_ticks = input_ticks + .checked_add(output_ticks)? + .checked_add(cache_read_ticks)? + .checked_add(cache_write_ticks)?; + Some(TokenAmounts { + input_ticks, + output_ticks, + cache_read_ticks, + cache_write_ticks, + total_ticks, + }) +} + +fn effective_multiplier_percent(total: u128, standard: u128) -> Option { + if standard == 0 { + return Some(100); + } + let rounded = total + .checked_mul(100)? + .checked_add(standard / 2)? + .checked_div(standard)?; + u32::try_from(rounded).ok() +} + +/// 规范化请求或响应携带的服务档位,供观测与计费共用 +pub(crate) fn normalize_service_tier(service_tier: Option<&str>) -> Option { + service_tier + .map(str::trim) + .filter(|value| { + !value.is_empty() && value.len() <= 64 && !value.chars().any(char::is_control) + }) + .map(str::to_ascii_lowercase) +} + +pub(super) fn usd_money(ticks: u128) -> Option { + Some(Money::new( + Decimal::from_scaled(ticks).ok()?, + CurrencyCode::new("USD").ok()?, + )) +} + +pub(super) fn usd_price_per_million(per_token_ticks: u128) -> Option { + usd_money(per_token_ticks.checked_mul(1_000_000)?) +} diff --git a/backend/crates/providers/openai/src/billing/catalog.rs b/backend/crates/providers/openai/src/billing/catalog.rs new file mode 100644 index 000000000..ecbf9c945 --- /dev/null +++ b/backend/crates/providers/openai/src/billing/catalog.rs @@ -0,0 +1,624 @@ +//! OpenAI 内置价目、型号匹配、服务档位和管理价目投影 + +pub(crate) const SUPPORTED_PRICING_BANDS: &[&str] = &[ + "standard", + "fast", + "ultrafast", + "flex", + "long_standard", + "long_fast", + "long_ultrafast", + "long_flex", + "image", +]; + +use gateway_core::metering::Decimal; + +#[derive(Clone, Copy)] +pub(super) struct TokenRates { + pub(super) explicit_cache: bool, + pub(super) cache_write_ticks: Option, + pub(super) input_ticks: u128, + pub(super) output_ticks: u128, + pub(super) cache_read_ticks: u128, +} + +impl TokenRates { + const ZERO: Self = Self::new(0, 0, 0); + + /// 参数单位为 USD / 1M Token 的万分之一,数值也恰好等于单 Token 的 USD ticks + pub(super) const fn new(input_ticks: u128, output_ticks: u128, cache_read_ticks: u128) -> Self { + Self { + input_ticks, + output_ticks, + cache_read_ticks, + explicit_cache: false, + cache_write_ticks: None, + } + } + + pub(super) const fn is_configured(self) -> bool { + self.explicit_cache + || self.input_ticks > 0 + || self.output_ticks > 0 + || self.cache_read_ticks > 0 + } +} + +#[derive(Clone, Copy)] +pub(super) struct ModelPricing { + standard: TokenRates, + flex: TokenRates, + fast: TokenRates, + ultrafast: TokenRates, + pub(super) long_standard: TokenRates, + long_flex: TokenRates, + long_fast: TokenRates, + long_ultrafast: TokenRates, + pub(super) cache_write_percent: u32, + pub(super) unpriced_long_context: bool, +} + +impl ModelPricing { + const fn new(input: u128, output: u128, cache_read: u128) -> Self { + Self { + standard: TokenRates::new(input, output, cache_read), + flex: TokenRates::ZERO, + fast: TokenRates::ZERO, + ultrafast: TokenRates::ZERO, + long_standard: TokenRates::ZERO, + long_flex: TokenRates::ZERO, + long_fast: TokenRates::ZERO, + long_ultrafast: TokenRates::ZERO, + cache_write_percent: 0, + unpriced_long_context: false, + } + } + + const fn with_flex(mut self, input: u128, output: u128, cache_read: u128) -> Self { + self.flex = TokenRates::new(input, output, cache_read); + self + } + + const fn with_fast(mut self, input: u128, output: u128, cache_read: u128) -> Self { + self.fast = TokenRates::new(input, output, cache_read); + self + } + + const fn with_ultrafast(mut self, input: u128, output: u128, cache_read: u128) -> Self { + self.ultrafast = TokenRates::new(input, output, cache_read); + self + } + + const fn with_long(mut self, input: u128, output: u128, cache_read: u128) -> Self { + self.long_standard = TokenRates::new(input, output, cache_read); + self + } + + const fn with_long_flex(mut self, input: u128, output: u128, cache_read: u128) -> Self { + self.long_flex = TokenRates::new(input, output, cache_read); + self + } + + const fn with_long_fast(mut self, input: u128, output: u128, cache_read: u128) -> Self { + self.long_fast = TokenRates::new(input, output, cache_read); + self + } + + const fn with_long_ultrafast(mut self, input: u128, output: u128, cache_read: u128) -> Self { + self.long_ultrafast = TokenRates::new(input, output, cache_read); + self + } + + const fn with_cache_write(mut self, percent: u32) -> Self { + self.cache_write_percent = percent; + self + } + + const fn with_unpriced_long_context(mut self) -> Self { + self.unpriced_long_context = true; + self + } + + pub(super) fn rates(self, tier: PricingTier, long_context: bool) -> Option { + if long_context && self.unpriced_long_context { + return None; + } + // 只有公布长上下文价格的模型才在阈值处切换费率 + // 若短上下文价格覆盖全部支持范围,长上下文栏的横线不代表额外的不可用档位 + let uses_long_rates = long_context && self.long_standard.is_configured(); + let rates = match (tier, uses_long_rates) { + (PricingTier::Standard, false) => self.standard, + (PricingTier::Flex, false) => self.flex, + (PricingTier::Fast, false) => self.fast, + (PricingTier::Ultrafast, false) => self.ultrafast, + (PricingTier::Standard, true) => self.long_standard, + (PricingTier::Flex, true) => self.long_flex, + (PricingTier::Fast, true) => self.long_fast, + (PricingTier::Ultrafast, true) => self.long_ultrafast, + }; + rates.is_configured().then_some(rates) + } +} + +#[derive(Clone, Copy)] +pub(super) enum PricingTier { + Standard, + Flex, + Fast, + Ultrafast, +} + +#[derive(Clone, Copy)] +struct PricingRule { + model: &'static str, + pricing: ModelPricing, +} + +// 价格来源:https://developers.openai.com/api/docs/pricing +// 只登记已核验的常规价格及服务档位;临时优惠不写入内置价目 +// 原有规则于 2026-09-09 核验,GPT-6.1 Sol 于 2026-09-29 核验,其余新增型号见对应条目 +// Astra 与 GPT-6.1 Sol 的 Ultrafast 档位于 2026-10-12 对照官方价目表核验 +// 已按 https://developers.openai.com/api/docs/deprecations 核验至 2026-09-13, +// 移除已关闭的型号;仅宣布弃用但尚未到关闭日期的型号继续保留 +const PRICING_RULES: &[PricingRule] = &[ + // GPT-6.2 的 Ultrafast 使用官方价目表中的 6 倍常规价,核验日期 2026-11-18 + PricingRule { + model: "gpt-6.2-astra", + pricing: ModelPricing::new(80_000, 400_000, 4_000) + .with_cache_write(125) + .with_fast(160_000, 800_000, 8_000) + .with_ultrafast(480_000, 2_400_000, 24_000) + .with_long(160_000, 600_000, 8_000) + .with_long_fast(320_000, 1_200_000, 16_000) + .with_long_ultrafast(960_000, 3_600_000, 48_000), + }, + PricingRule { + model: "gpt-6.2-sol", + pricing: ModelPricing::new(20_000, 100_000, 1_000) + .with_cache_write(125) + .with_fast(40_000, 200_000, 2_000) + .with_ultrafast(120_000, 600_000, 6_000) + .with_long(40_000, 150_000, 2_000) + .with_long_fast(80_000, 300_000, 4_000) + .with_long_ultrafast(240_000, 900_000, 12_000), + }, + // Astra:https://developers.openai.com/api/docs/models/gpt-6-astra + // 已于 2026-09-09 对照官方价目表核验 + PricingRule { + model: "gpt-6-astra", + pricing: ModelPricing::new(100_000, 500_000, 10_000) + .with_cache_write(125) + .with_flex(50_000, 250_000, 5_000) + .with_fast(200_000, 1_000_000, 20_000) + .with_ultrafast(600_000, 3_000_000, 60_000) + .with_long(200_000, 750_000, 20_000) + .with_long_flex(100_000, 375_000, 10_000) + .with_long_fast(400_000, 1_500_000, 40_000) + .with_long_ultrafast(1_200_000, 4_500_000, 120_000), + }, + PricingRule { + model: "gpt-6.1-sol", + pricing: ModelPricing::new(20_000, 100_000, 1_000) + .with_cache_write(125) + .with_flex(10_000, 50_000, 500) + .with_fast(40_000, 200_000, 2_000) + .with_ultrafast(120_000, 600_000, 6_000) + .with_long(40_000, 150_000, 2_000) + .with_long_flex(20_000, 75_000, 1_000) + .with_long_fast(80_000, 300_000, 4_000) + .with_long_ultrafast(240_000, 900_000, 12_000), + }, + // https://developers.openai.com/api/docs/models/gpt-6.1-terra,核验日期 2026-10-27 + PricingRule { + model: "gpt-6.1-terra", + pricing: ModelPricing::new(10_000, 50_000, 500) + .with_cache_write(125) + .with_flex(5_000, 25_000, 250) + .with_fast(20_000, 100_000, 1_000) + .with_long(20_000, 75_000, 1_000) + .with_long_flex(10_000, 37_500, 500) + .with_long_fast(40_000, 150_000, 2_000), + }, + // https://developers.openai.com/api/docs/models/gpt-6-sol,核验日期 2026-09-24 + PricingRule { + model: "gpt-6-sol", + pricing: ModelPricing::new(20_000, 100_000, 2_000) + .with_cache_write(125) + .with_flex(10_000, 50_000, 1_000) + .with_fast(40_000, 200_000, 4_000) + .with_long(40_000, 150_000, 4_000) + .with_long_flex(20_000, 75_000, 2_000) + .with_long_fast(80_000, 300_000, 8_000), + }, + // https://developers.openai.com/api/docs/models/gpt-6-luna,核验日期 2026-09-24 + PricingRule { + model: "gpt-6-luna", + pricing: ModelPricing::new(1_000, 5_000, 100) + .with_cache_write(125) + .with_flex(500, 2_500, 50) + .with_fast(2_000, 10_000, 200) + .with_long(2_000, 7_500, 200) + .with_long_flex(1_000, 3_750, 100) + .with_long_fast(4_000, 15_000, 400), + }, + PricingRule { + model: "gpt-5.6-sol", + pricing: ModelPricing::new(50_000, 300_000, 5_000) + .with_cache_write(125) + .with_flex(25_000, 150_000, 2_500) + .with_fast(100_000, 600_000, 10_000) + .with_long(100_000, 450_000, 10_000) + .with_long_flex(50_000, 225_000, 5_000) + .with_long_fast(200_000, 900_000, 20_000), + }, + PricingRule { + model: "gpt-5.6-terra", + pricing: ModelPricing::new(20_000, 120_000, 2_000) + .with_cache_write(125) + .with_flex(10_000, 60_000, 1_000) + .with_fast(40_000, 240_000, 4_000) + .with_long(40_000, 180_000, 4_000) + .with_long_flex(20_000, 90_000, 2_000) + .with_long_fast(80_000, 360_000, 8_000), + }, + PricingRule { + model: "gpt-5.6-luna", + pricing: ModelPricing::new(2_000, 12_000, 200) + .with_cache_write(125) + .with_flex(1_000, 6_000, 100) + .with_fast(4_000, 24_000, 400) + .with_long(4_000, 18_000, 400) + .with_long_flex(2_000, 9_000, 200) + .with_long_fast(8_000, 36_000, 800), + }, + PricingRule { + model: "gpt-5.6", + pricing: ModelPricing::new(50_000, 300_000, 5_000) + .with_cache_write(125) + .with_flex(25_000, 150_000, 2_500) + .with_fast(100_000, 600_000, 10_000) + .with_long(100_000, 450_000, 10_000) + .with_long_flex(50_000, 225_000, 5_000) + .with_long_fast(200_000, 900_000, 20_000), + }, + PricingRule { + model: "gpt-5.5-pro", + pricing: ModelPricing::new(300_000, 1_800_000, 0) + .with_flex(150_000, 900_000, 0) + .with_long(600_000, 2_700_000, 0), + }, + PricingRule { + model: "gpt-5.5", + pricing: ModelPricing::new(50_000, 300_000, 5_000) + .with_flex(25_000, 150_000, 2_500) + .with_fast(125_000, 750_000, 12_500) + .with_long(100_000, 450_000, 10_000) + .with_long_flex(50_000, 225_000, 5_000), + }, + PricingRule { + model: "gpt-5.4-mini", + pricing: ModelPricing::new(7_500, 45_000, 750) + .with_flex(3_750, 22_500, 375) + .with_fast(15_000, 90_000, 1_500), + }, + PricingRule { + model: "gpt-5.4-nano", + pricing: ModelPricing::new(2_000, 12_500, 200).with_flex(1_000, 6_250, 100), + }, + PricingRule { + model: "gpt-5.4-pro", + pricing: ModelPricing::new(300_000, 1_800_000, 0) + .with_flex(150_000, 900_000, 0) + .with_long(600_000, 2_700_000, 0) + .with_long_flex(300_000, 1_350_000, 0), + }, + PricingRule { + model: "gpt-5.4", + pricing: ModelPricing::new(25_000, 150_000, 2_500) + .with_flex(12_500, 75_000, 1_300) + .with_fast(50_000, 300_000, 5_000) + .with_long(50_000, 225_000, 5_000) + .with_long_flex(25_000, 112_500, 2_500), + }, + PricingRule { + model: "gpt-5.3-codex", + pricing: ModelPricing::new(17_500, 140_000, 1_750).with_fast(35_000, 280_000, 3_500), + }, + PricingRule { + model: "gpt-5.2-pro", + pricing: ModelPricing::new(210_000, 1_680_000, 0), + }, + PricingRule { + model: "gpt-5.2", + pricing: ModelPricing::new(17_500, 140_000, 1_750) + .with_flex(8_750, 70_000, 875) + .with_fast(35_000, 280_000, 3_500), + }, + PricingRule { + model: "gpt-5.1", + pricing: ModelPricing::new(12_500, 100_000, 1_250) + .with_flex(6_250, 50_000, 625) + .with_fast(25_000, 200_000, 2_500), + }, + PricingRule { + model: "gpt-5-mini", + pricing: ModelPricing::new(2_500, 20_000, 250) + .with_flex(1_250, 10_000, 125) + .with_fast(4_500, 36_000, 450), + }, + PricingRule { + model: "gpt-5-nano", + pricing: ModelPricing::new(500, 4_000, 50).with_flex(250, 2_000, 25), + }, + PricingRule { + model: "gpt-5-pro", + pricing: ModelPricing::new(150_000, 1_200_000, 0), + }, + PricingRule { + model: "gpt-5", + pricing: ModelPricing::new(12_500, 100_000, 1_250) + .with_flex(6_250, 50_000, 625) + .with_fast(25_000, 200_000, 2_500), + }, + PricingRule { + model: "gpt-4.1-mini", + pricing: ModelPricing::new(4_000, 16_000, 1_000).with_fast(7_000, 28_000, 1_750), + }, + PricingRule { + model: "gpt-4.1-nano", + pricing: ModelPricing::new(1_000, 4_000, 250).with_fast(2_000, 8_000, 500), + }, + PricingRule { + model: "gpt-4.1", + pricing: ModelPricing::new(20_000, 80_000, 5_000).with_fast(35_000, 140_000, 8_750), + }, + PricingRule { + model: "gpt-4o-2024-05-13", + pricing: ModelPricing::new(50_000, 150_000, 0).with_fast(87_500, 262_500, 0), + }, + PricingRule { + model: "gpt-4o-mini", + pricing: ModelPricing::new(1_500, 6_000, 750).with_fast(2_500, 10_000, 1_250), + }, + PricingRule { + model: "gpt-4o", + pricing: ModelPricing::new(25_000, 100_000, 12_500).with_fast(42_500, 170_000, 21_250), + }, + PricingRule { + model: "o1-pro", + pricing: ModelPricing::new(1_500_000, 6_000_000, 0), + }, + PricingRule { + model: "o1", + pricing: ModelPricing::new(150_000, 600_000, 75_000), + }, + PricingRule { + model: "o3-pro", + pricing: ModelPricing::new(200_000, 800_000, 0), + }, + PricingRule { + model: "o3-mini", + pricing: ModelPricing::new(11_000, 44_000, 5_500), + }, + PricingRule { + model: "o3", + pricing: ModelPricing::new(20_000, 80_000, 5_000) + .with_flex(10_000, 40_000, 2_500) + .with_fast(35_000, 140_000, 8_750), + }, + PricingRule { + model: "o4-mini", + pricing: ModelPricing::new(11_000, 44_000, 2_750) + .with_flex(5_500, 22_000, 1_380) + .with_fast(20_000, 80_000, 5_000), + }, + PricingRule { + model: "gpt-4-turbo", + pricing: ModelPricing::new(100_000, 300_000, 0), + }, + PricingRule { + model: "gpt-4", + pricing: ModelPricing::new(300_000, 600_000, 0), + }, + PricingRule { + model: "gpt-3.5-turbo-instruct", + pricing: ModelPricing::new(15_000, 20_000, 0), + }, + PricingRule { + model: "gpt-3.5-turbo-1106", + pricing: ModelPricing::new(10_000, 20_000, 0), + }, + PricingRule { + model: "gpt-3.5-turbo", + pricing: ModelPricing::new(5_000, 15_000, 0), + }, + // 各变体独立采用已公开的价格与档位,不能继承父型号的所有档位 + // Cyber 长上下文的官方来源存在差异,该区间暂不估价 + PricingRule { + model: "gpt-5.6-cyber", + pricing: ModelPricing::new(125_000, 750_000, 12_500) + .with_cache_write(125) + .with_unpriced_long_context(), + }, + PricingRule { + model: "gpt-5.5-cyber", + pricing: ModelPricing::new(125_000, 750_000, 12_500).with_unpriced_long_context(), + }, + PricingRule { + model: "chat-latest", + pricing: ModelPricing::new(50_000, 300_000, 5_000), + }, +]; + +pub(super) const IMAGE_MODELS: &[&str] = &[ + "gpt-image-2", + "gpt-image-2-2026-04-21", + "gpt-image-2.5-sunburst", + "gpt-image-2.5-sunburst-2026-09-08", + "gpt-image-2.5-flare", + "gpt-image-2.5-flare-2026-09-08", +]; +pub(super) const IMAGE_TEXT_RATES: TokenRates = TokenRates::new(50_000, 0, 12_500); +pub(super) const IMAGE_TOKEN_RATES: TokenRates = TokenRates::new(80_000, 300_000, 20_000); + +pub(super) fn model_pricing(model: &str) -> Option { + let normalized = normalize_model_name(model); + let model = pricing_model_name(&normalized); + PRICING_RULES + .iter() + .find(|rule| model == rule.model) + .map(|rule| rule.pricing) +} + +pub(super) fn normalize_model_name(model: &str) -> String { + model + .trim() + .trim_start_matches('/') + .rsplit('/') + .next() + .unwrap_or_default() + .to_ascii_lowercase() +} + +// 仅已核验的别名和快照可以共用价格;未知后缀、未来日期和微调模型 +// 不得直接继承父型号的价格 +pub(super) fn pricing_model_name(model: &str) -> &str { + match model { + "gpt-3.5-turbo-0125" => "gpt-3.5-turbo", + "gpt-4-0613" => "gpt-4", + "gpt-4-turbo-2024-04-09" => "gpt-4-turbo", + "gpt-4.1-2025-04-14" => "gpt-4.1", + "gpt-4.1-mini-2025-04-14" => "gpt-4.1-mini", + "gpt-4.1-nano-2025-04-14" => "gpt-4.1-nano", + "gpt-4o-2024-08-06" => "gpt-4o", + "gpt-4o-2024-11-20" => "gpt-4o", + "gpt-4o-mini-2024-07-18" => "gpt-4o-mini", + "gpt-5-2025-08-07" => "gpt-5", + "gpt-5-mini-2025-08-07" => "gpt-5-mini", + "gpt-5-nano-2025-08-07" => "gpt-5-nano", + "gpt-5-pro-2025-10-06" => "gpt-5-pro", + "gpt-5.1-2025-11-13" => "gpt-5.1", + "gpt-5.2-2025-12-11" => "gpt-5.2", + "gpt-5.2-pro-2025-12-11" => "gpt-5.2-pro", + "gpt-5.4-2026-03-05" => "gpt-5.4", + "gpt-5.4-mini-2026-03-17" => "gpt-5.4-mini", + "gpt-5.4-nano-2026-03-17" => "gpt-5.4-nano", + "gpt-5.4-pro-2026-03-05" => "gpt-5.4-pro", + "gpt-5.5-2026-04-23" => "gpt-5.5", + "gpt-5.5-pro-2026-04-23" => "gpt-5.5-pro", + "gpt-daybreak-blue-latest" => "gpt-5.6-sol", + "gpt-daybreak-red-latest" => "gpt-5.6-cyber", + "o1-2024-12-17" => "o1", + "o1-pro-2025-03-19" => "o1-pro", + "o3-2025-04-16" => "o3", + "o3-mini-2025-01-31" => "o3-mini", + "o3-pro-2025-06-10" => "o3-pro", + "o4-mini-2025-04-16" => "o4-mini", + _ => model, + } +} + +pub(super) fn model_matches_rule(model: &str, rule: &str) -> bool { + pricing_model_name(model) == rule +} + +pub(super) fn cache_write_rate(rates: TokenRates, percent: u32) -> Option { + if let Some(ticks) = rates.cache_write_ticks { + return Some(ticks); + } + if percent == 0 { + return Some(0); + } + apply_percent(rates.input_ticks, percent) +} + +fn apply_percent(value: u128, percent: u32) -> Option { + value + .checked_mul(u128::from(percent))? + .checked_add(50) + .map(|scaled| scaled / 100) +} + +pub(crate) fn pricing_catalog() +-> std::collections::BTreeMap { + use gateway_core::metering::{ModelPriceOverride, TokenPrice, TokenPriceOverride}; + let price = |ticks: u128| -> Option { + Decimal::from_scaled(ticks.checked_mul(1_000_000)?) + .ok()? + .canonical() + .try_into() + .ok() + }; + let mut catalog: std::collections::BTreeMap<_, _> = PRICING_RULES + .iter() + .map(|rule| { + let pricing = rule.pricing; + let bands = [ + ("standard", pricing.standard), + ("fast", pricing.fast), + ("ultrafast", pricing.ultrafast), + ("flex", pricing.flex), + ("long_standard", pricing.long_standard), + ("long_fast", pricing.long_fast), + ("long_ultrafast", pricing.long_ultrafast), + ("long_flex", pricing.long_flex), + ] + .into_iter() + .filter(|(_, rates)| rates.is_configured()) + .filter_map(|(name, rates)| { + Some(( + name.to_owned(), + TokenPriceOverride { + input: price(rates.input_ticks)?, + output: price(rates.output_ticks)?, + cache_read: price(if rates.cache_read_ticks == 0 { + rates.input_ticks + } else { + rates.cache_read_ticks + })?, + // 内置表没有独立缓存写入费时,这部分 Token 原本按输入计费 + // 管理页复制来源档位不能把它改成显式免费 + cache_write: price(if pricing.cache_write_percent == 0 { + rates.input_ticks + } else { + cache_write_rate(rates, pricing.cache_write_percent)? + })?, + }, + )) + }) + .collect(); + ( + rule.model.to_owned(), + ModelPriceOverride { + multiplier_bps: 10_000, + bands, + }, + ) + }) + .collect(); + for model in IMAGE_MODELS { + let bands = [("standard", IMAGE_TEXT_RATES), ("image", IMAGE_TOKEN_RATES)] + .into_iter() + .map(|(band, rates)| { + ( + band.to_owned(), + TokenPriceOverride { + input: price(rates.input_ticks).expect("内置图像价格合法"), + output: price(rates.output_ticks).expect("内置图像价格合法"), + cache_read: price(rates.cache_read_ticks).expect("内置图像价格合法"), + cache_write: price(0).expect("零价格合法"), + }, + ) + }) + .collect(); + catalog.insert( + (*model).to_owned(), + ModelPriceOverride { + multiplier_bps: 10_000, + bands, + }, + ); + } + catalog +} diff --git a/backend/crates/providers/openai/src/billing/images.rs b/backend/crates/providers/openai/src/billing/images.rs new file mode 100644 index 000000000..2ae457030 --- /dev/null +++ b/backend/crates/providers/openai/src/billing/images.rs @@ -0,0 +1,110 @@ +//! OpenAI Images 用量的模态校验与费用计算 + +use gateway_core::metering::{ + CalculatedCost, CalculatedCostAmounts, CalculatedCostBreakdown, CalculatedCostRates, +}; +use serde_json::Value; + +use super::calculate::{token_amounts, usd_money, usd_price_per_million}; +use super::catalog::{IMAGE_MODELS, IMAGE_TEXT_RATES, IMAGE_TOKEN_RATES, TokenRates}; + +/// 独立 Images 端点按公开标准 API 单价估算;不是 ChatGPT 账号实际扣费 +pub(crate) fn image_calculated_cost( + request_body: &[u8], + usage: &Value, + prices: &gateway_core::metering::PricingOverrides, +) -> Option { + #[derive(serde::Deserialize)] + struct ImageModel { + model: String, + } + // 只读取模型,跳过编辑请求中可能很大的 base64 图片 + let request = serde_json::from_slice::(request_body).ok()?; + let custom = prices + .get("openai") + .and_then(|models| models.get(&request.model)); + let known = IMAGE_MODELS.contains(&request.model.as_str()); + let rates = |band, builtin| { + custom + .and_then(|p| p.bands.get(band)) + .map(|p| TokenRates { + input_ticks: p.input.ticks_per_token(), + output_ticks: p.output.ticks_per_token(), + cache_read_ticks: p.cache_read.ticks_per_token(), + cache_write_ticks: Some(p.cache_write.ticks_per_token()), + explicit_cache: true, + }) + .or_else(|| known.then_some(builtin)) + }; + let text_rates = rates("standard", IMAGE_TEXT_RATES)?; + let image_rates = rates("image", IMAGE_TOKEN_RATES)?; + let input = usage.get("input_tokens")?.as_u64()?; + let output = usage.get("output_tokens")?.as_u64()?; + let details = usage.get("input_tokens_details")?; + let text_input = details.get("text_tokens")?.as_u64()?; + let image_input = details.get("image_tokens")?.as_u64()?; + if text_input.checked_add(image_input)? != input { + return None; + } + if let Some(total) = usage.get("total_tokens") + && total.as_u64()? != input.checked_add(output)? + { + return None; + } + // 此模型仅输出图片;上游如报告其他输出模态,不能套用图片单价 + if let Some(details) = usage.get("output_tokens_details") + && (details.get("image_tokens")?.as_u64()? != output + || details.get("text_tokens")?.as_u64()? != 0) + { + return None; + } + let cached = match details.get("cached_tokens") { + None => 0, + Some(value) => value.as_u64()?, + }; + if cached > input { + return None; + } + // 缓存只给总量时,混合输入无法判定应套用哪种缓存单价 + let (cached_text, cached_image) = match (text_input, image_input, cached) { + (_, _, 0) => (0, 0), + (_, 0, cached) => (cached, 0), + (0, _, cached) => (0, cached), + (_, _, cached) if cached == input => (text_input, image_input), + _ => return None, + }; + // 价格来源:https://developers.openai.com/api/docs/pricing,核验日期 2026-09-09 + // GPT Image 2 和两个 2.5 型号按相同的 token 单价计费,不使用按张估价 + // 每百万 token 的美元单价:文本 5 / 缓存 1.25;图片 8 / 缓存 2 / 输出 30 + let text = token_amounts(text_rates, 0, text_input, 0, cached_text, 0)?; + let image = token_amounts(image_rates, 0, image_input, output, cached_image, 0)?; + let total = usd_money(text.total_ticks.checked_add(image.total_ticks)?)?; + let breakdown = CalculatedCostBreakdown::new( + CalculatedCostAmounts::new( + usd_money(text.input_ticks)?, + usd_money(image.output_ticks)?, + usd_money(text.cache_read_ticks)?, + usd_money(0)?, + total, + total, + ), + CalculatedCostRates::new( + usd_price_per_million(text_rates.input_ticks)?, + usd_price_per_million(image_rates.output_ticks)?, + usd_price_per_million(text_rates.cache_read_ticks)?, + usd_money(0)?, + ), + Some("default".to_owned()), + 100, + ) + .with_image(gateway_core::metering::ImageCostBreakdown { + input_tokens: image_input, + cached_input_tokens: cached_image, + input_amount: usd_money(image.input_ticks)?, + cache_read_amount: usd_money(image.cache_read_ticks)?, + input_price_per_million: usd_price_per_million(image_rates.input_ticks)?, + cache_read_price_per_million: usd_price_per_million(image_rates.cache_read_ticks)?, + }) + .with_custom_multiplier(custom.map_or(10_000, |p| p.multiplier_bps))?; + Some(breakdown.calculated_cost()) +} diff --git a/backend/crates/providers/openai/src/billing/mod.rs b/backend/crates/providers/openai/src/billing/mod.rs new file mode 100644 index 000000000..7761b0839 --- /dev/null +++ b/backend/crates/providers/openai/src/billing/mod.rs @@ -0,0 +1,14 @@ +//! OpenAI 内置价目与本地费用估算入口 + +mod calculate; +mod catalog; +mod images; + +pub(crate) use calculate::{ + OpenAiBillingUsage, WebSearchPricing, configured_token_billing_breakdown, + normalize_service_tier, openai_billing_breakdown, openai_billing_breakdown_with_override, + web_search_pricing, +}; +pub(crate) use catalog::SUPPORTED_PRICING_BANDS; +pub(crate) use catalog::pricing_catalog; +pub(crate) use images::image_calculated_cost; diff --git a/backend/crates/providers/openai/src/credential/admin.rs b/backend/crates/providers/openai/src/credential/admin.rs index 2bf7ab18f..13ce9dc1e 100644 --- a/backend/crates/providers/openai/src/credential/admin.rs +++ b/backend/crates/providers/openai/src/credential/admin.rs @@ -174,7 +174,7 @@ impl fmt::Debug for ParsedCodexImportAccount { /// 时间必须由 App 从 `provider_accounts` 原行机械传入;Provider 不伪造时间 pub struct ExportManagedCodexCredential { pub current: LoadedCredential, - pub added_at: DateTime, + pub created_at: DateTime, pub updated_at: DateTime, } @@ -184,7 +184,7 @@ impl fmt::Debug for ExportManagedCodexCredential { .debug_struct("ExportManagedCodexCredential") .field("account_id", &self.current.account.id()) .field("credential", &"") - .field("added_at", &self.added_at) + .field("created_at", &self.created_at) .field("updated_at", &self.updated_at) .finish() } @@ -233,10 +233,11 @@ struct CodexCprExportCommon { email: Option, account_id: Option, user_id: Option, - label: Option, + #[serde(skip_serializing_if = "String::is_empty")] + label: String, plan_type: Option, status: &'static str, - added_at: String, + created_at: String, updated_at: String, #[serde(skip_serializing_if = "Option::is_none")] outbound_proxy_url: Option, @@ -647,7 +648,7 @@ impl CodexCredentialAdmin { for item in items { let account = item.current.account; if account.provider().as_str() != PROVIDER_NAME - || item.added_at > item.updated_at + || item.created_at > item.updated_at || !ids.insert(account.id().clone()) { return Err(CodexCredentialAdminError::InvalidInput); @@ -660,10 +661,10 @@ impl CodexCredentialAdmin { email: account.email().map(str::to_owned), account_id: account.upstream_account_id().map(str::to_owned), user_id: account.upstream_user_id().map(str::to_owned), - label: Some(account.name().to_owned()), + label: account.name().to_owned(), plan_type: account.plan_type().map(str::to_owned), status: cpr_status(&account), - added_at: item.added_at.to_rfc3339(), + created_at: item.created_at.to_rfc3339(), updated_at: item.updated_at.to_rfc3339(), outbound_proxy_url: account .outbound_proxy() diff --git a/backend/crates/providers/openai/src/credential/catalog/mod.rs b/backend/crates/providers/openai/src/credential/catalog/mod.rs index fef389324..343b3bf6f 100644 --- a/backend/crates/providers/openai/src/credential/catalog/mod.rs +++ b/backend/crates/providers/openai/src/credential/catalog/mod.rs @@ -28,7 +28,7 @@ use tokio::sync::Notify; use uuid::Uuid; use super::repository::{CodexCredentialRepository, CredentialRepositoryError}; -use crate::transport::profile::CodexWireProfileState; +use crate::profile::CodexWireProfileState; use crate::transport::{CodexBackendClient, CodexCatalogModel, CodexRequestContext}; const MAX_RESPONSE_ETAG_BYTES: usize = 256; diff --git a/backend/crates/providers/openai/src/credential/mod.rs b/backend/crates/providers/openai/src/credential/mod.rs index fa5aea69c..40d2de330 100644 --- a/backend/crates/providers/openai/src/credential/mod.rs +++ b/backend/crates/providers/openai/src/credential/mod.rs @@ -76,7 +76,6 @@ pub use selector::{ SelectCodexCredential, }; pub(crate) use selector::{CodexCyberPolicyScope, SelectCodexProviderEndpointCredential}; -pub(crate) use types::oauth_identity_key; pub use types::{ CODEX_AUTHENTICATION_KIND_OAUTH, CodexAccountProfile, CodexCookie, CodexCookieCaptureOutcome, CodexCredentialData, CodexCredentialPrincipal, CodexOAuthCredentialData, CodexOAuthSecret, diff --git a/backend/crates/providers/openai/src/credential/oauth.rs b/backend/crates/providers/openai/src/credential/oauth.rs index 0c7828aa6..a7dd88d09 100644 --- a/backend/crates/providers/openai/src/credential/oauth.rs +++ b/backend/crates/providers/openai/src/credential/oauth.rs @@ -32,7 +32,7 @@ use super::token_client::{ OFFICIAL_CODEX_OAUTH_CLIENT_ID, OFFICIAL_CODEX_REDIRECT_URI, }; use super::types::{parse_access_token_expiration, parse_chatgpt_jwt_claims}; -use crate::transport::profile::CodexWireProfileState; +use crate::profile::CodexWireProfileState; const AUTHORIZATION_ENDPOINT: &str = "https://auth.openai.com/oauth/authorize"; const DESKTOP_AUTH_ENDPOINT: &str = "https://chatgpt.com/codex/desktop-auth"; diff --git a/backend/crates/providers/openai/src/credential/profile_statistics.rs b/backend/crates/providers/openai/src/credential/profile_statistics.rs index 0da94ac5f..c80b81d64 100644 --- a/backend/crates/providers/openai/src/credential/profile_statistics.rs +++ b/backend/crates/providers/openai/src/credential/profile_statistics.rs @@ -12,7 +12,7 @@ use secrecy::{ExposeSecret as _, SecretString}; use thiserror::Error; use uuid::Uuid; -use crate::transport::profile::CodexWireProfileState; +use crate::profile::CodexWireProfileState; use crate::transport::subscription::CodexSubscription; use crate::transport::{ CodexBackendClient, CodexClientError, CodexProfileAvatar, CodexProfileAvatarFetchError, @@ -210,7 +210,7 @@ impl CodexCredentialProfileService { .await .map_err(map_client_error)?; self.remember_avatar_source( - super::oauth_identity_key(account), + crate::request_identity::oauth_identity_key(account), statistics.image_url.as_deref(), ); Ok(statistics) @@ -268,7 +268,9 @@ impl CodexCredentialProfileService { ) -> Result { let (authorization, upstream_account_id, account) = self.account_authentication(account_id).await?; - let source = match self.cached_avatar_source(&super::oauth_identity_key(&account)) { + let source = match self + .cached_avatar_source(&crate::request_identity::oauth_identity_key(&account)) + { Some(source) => source, None => self .fetch_profile_statistics(&authorization, upstream_account_id.as_deref(), &account) diff --git a/backend/crates/providers/openai/src/credential/quota/mod.rs b/backend/crates/providers/openai/src/credential/quota/mod.rs index c86667c60..ab0ef63ef 100644 --- a/backend/crates/providers/openai/src/credential/quota/mod.rs +++ b/backend/crates/providers/openai/src/credential/quota/mod.rs @@ -52,7 +52,7 @@ use thiserror::Error; use tokio::sync::Mutex; use uuid::Uuid; -use crate::transport::profile::CodexWireProfileState; +use crate::profile::CodexWireProfileState; use crate::transport::protocol::responses::CodexResponsesRequest; use crate::transport::{ CodexBackendClient, CodexBackendStreamingResponse, CodexClientError, diff --git a/backend/crates/providers/openai/src/credential/selector.rs b/backend/crates/providers/openai/src/credential/selector.rs index 6a315d0fe..b997af8fe 100644 --- a/backend/crates/providers/openai/src/credential/selector.rs +++ b/backend/crates/providers/openai/src/credential/selector.rs @@ -449,7 +449,7 @@ impl CodexCredentialSelector { key: affinity.key(), expected: current.as_ref(), account: &selected_account, - ttl: policy.openai_session_affinity_ttl(), + ttl: policy.session_affinity_ttl(), })) .await? { @@ -502,7 +502,7 @@ impl CodexCredentialSelector { ) -> Result { let policy = request.attempt.account_selection_policy(); let follow_only = !request.attempt.is_diagnostic_required_account() - && policy.openai_account_affinity() == AccountAffinity::Strict + && policy.account_affinity() == AccountAffinity::Strict && request .session_affinity_observation .is_some_and(CodexSessionAffinity::follow_only); @@ -719,7 +719,7 @@ impl CodexCredentialSelector { let affinity_mode = request .attempt .account_selection_policy() - .openai_account_affinity(); + .account_affinity(); if follow_only { // 关闭普通账号排队不能放开后代线程换号,沿用队列时间设置并保留有界人数 queue_policy.max_waiting = if queue_policy.max_waiting == 0 { @@ -1545,7 +1545,7 @@ impl CodexCredentialSelector { key, expected: binding.as_ref(), account: binding_account, - ttl: policy.openai_session_affinity_ttl(), + ttl: policy.session_affinity_ttl(), }); // 插件委托与普通内置选号共享轮询,显式选择、亲和命中及等待不消耗位置 let admission = match assignment_cursor { diff --git a/backend/crates/providers/openai/src/credential/token_client.rs b/backend/crates/providers/openai/src/credential/token_client.rs index 524149291..8770731fe 100644 --- a/backend/crates/providers/openai/src/credential/token_client.rs +++ b/backend/crates/providers/openai/src/credential/token_client.rs @@ -1,10 +1,10 @@ //! OpenAI OAuth token exchange 与 Codex PAT 验证的 Reqwest 适配器 use super::types::CodexOAuthMetadata; +use crate::profile::CodexWireProfileState; use crate::transport::{ headers::build_codex_profile_headers, - profile::CodexWireProfileState, tls::{build_reqwest_client_with_custom_ca, ensure_rustls_provider}, }; use async_trait::async_trait; diff --git a/backend/crates/providers/openai/src/credential/types.rs b/backend/crates/providers/openai/src/credential/types.rs index 266f441da..67de15ddf 100644 --- a/backend/crates/providers/openai/src/credential/types.rs +++ b/backend/crates/providers/openai/src/credential/types.rs @@ -8,22 +8,6 @@ use secrecy::{ExposeSecret, SecretString}; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use url::Url; -/// 复用上游会话与账号资料时绑定本地记录和真实 OAuth 身份,正常续期不改变归属 -pub(crate) fn oauth_identity_key(account: &gateway_core::account::ProviderAccount) -> String { - use sha2::{Digest, Sha256}; - - let mut hash = Sha256::new(); - for part in [ - account.id().as_str(), - account.upstream_user_id().unwrap_or_default(), - account.upstream_account_id().unwrap_or_default(), - ] { - hash.update((part.len() as u64).to_le_bytes()); - hash.update(part.as_bytes()); - } - hex::encode(hash.finalize()) -} - /// OAuth AT/RT/ID Token;`Debug` 永不输出明文 #[derive(Clone)] pub struct CodexOAuthSecret { diff --git a/backend/crates/providers/openai/src/lib.rs b/backend/crates/providers/openai/src/lib.rs index 4aef89b19..e71d84af2 100644 --- a/backend/crates/providers/openai/src/lib.rs +++ b/backend/crates/providers/openai/src/lib.rs @@ -1,9 +1,12 @@ //! OpenAI Provider 专属能力 mod admin; +mod automatic_context; +mod billing; mod compat; pub mod config; mod jitter; +pub mod profile; mod provider; mod request_identity; mod session_transport; @@ -13,12 +16,10 @@ pub(crate) const CODEX_AUTHENTICATION_KIND_API_KEY: &str = "api_key"; use std::sync::Arc; -use gateway_admin::ports::provider::ProviderAdmin; +use gateway_admin::ports::provider::ProviderBundle; use gateway_core::account::ProviderAccountStore; -use gateway_core::engine::provider::Provider; use gateway_core::provider_ports::ProviderStorePorts; use gateway_core::routing::ProviderKind; -use gateway_core::task::WorkerContribution; use crate::admin::{OpenAiAdminProvider, OpenAiAdminServices, OpenAiOAuthPendingStore}; use crate::credential::token_client::{AuthorizationCodeExchanger, TokenRefresher}; @@ -28,7 +29,7 @@ use crate::credential::{ CodexCredentialRefreshService, CodexCredentialRepository, CodexCredentialSelector, CodexOAuthAdmin, CodexOAuthAdminService, }; -use crate::transport::profile::{ +use crate::profile::{ CodexArtifactProfileCache, CodexDesktopReleaseService, OfficialCodexDesktopReleaseTransport, }; use crate::transport::{CodexWebSocketPool, build_reqwest_client}; @@ -49,17 +50,9 @@ pub mod transport; pub use transport::endpoints::{OFFICIAL_CODEX_BASE_PATH, OFFICIAL_CODEX_BASE_URL}; pub use transport::tls::{build_reqwest_client_with_custom_ca, ensure_rustls_provider}; pub use transport::{ - CodexCanonicalDecoder, CodexCanonicalError, CodexRequestEncodeError, OpenAiBillingUsage, - encode_generate_request, openai_billing_breakdown, + CodexCanonicalDecoder, CodexCanonicalError, CodexRequestEncodeError, encode_generate_request, }; -/// OpenAI 初始化后交给组装根的最小能力集 -pub struct ProviderBundle { - core_provider: Arc, - admin_provider: Arc, - worker_contributions: Vec, -} - /// 构造 OpenAI 数据面、Provider-owned 后台任务与 Redis OAuth pending owner pub async fn initialize( config: OpenAiConfig, @@ -74,22 +67,21 @@ pub async fn initialize( let session_exclusions = ports.session_exclusions(); let account_feedback = ports.account_feedback(); let runtime_policy = ports.runtime_policy(); - let initial_profile = transport::profile::selection::ClientProfileSelection::default() + let initial_profile = profile::selection::ClientProfileSelection::default() .document() .map_err(|_| OpenAiInitializeError::RuntimePolicy)?; let configured_profile = runtime_policy .initialize_request_profile(&provider_kind, initial_profile) .await .map_err(|_| OpenAiInitializeError::RuntimePolicy)?; - transport::profile::identity::RequestProfileSelection::parse(&configured_profile) + profile::identity::RequestProfileSelection::parse(&configured_profile) .map_err(|_| OpenAiInitializeError::RuntimePolicy)?; let credential_state = ports.credential_state(); - let profile = - transport::profile::CodexWireProfileState::new(transport::profile::CodexWireProfile { - residency: config.residency.clone(), - account_routing_override: config.account_routing_override.clone(), - ..Default::default() - }); + let profile = profile::CodexWireProfileState::new(profile::CodexWireProfile { + residency: config.residency.clone(), + account_routing_override: config.account_routing_override.clone(), + ..Default::default() + }); let artifact_cache = CodexArtifactProfileCache::new(provider_kind.clone(), ports.artifact_profiles()); let configured_build = profile.snapshot().desktop_build.parse::().ok(); @@ -122,7 +114,7 @@ pub async fn initialize( )); let desktop_release_status = desktop_release.status(); let cli_release = Arc::new( - transport::profile::cli_release::CliReleaseService::new( + profile::cli_release::CliReleaseService::new( provider_kind.clone(), profile.clone(), ports.artifact_profiles(), @@ -131,12 +123,12 @@ pub async fn initialize( ); cli_release.restore().await; let platform_releases = Arc::new( - transport::profile::platform_release::PlatformDesktopReleaseService::new( + profile::platform_release::PlatformDesktopReleaseService::new( provider_kind.clone(), profile.clone(), ports.artifact_profiles(), Arc::new( - transport::profile::platform_release::OfficialDesktopArtifactTransport::new() + profile::platform_release::OfficialDesktopArtifactTransport::new() .map_err(|_| OpenAiInitializeError::DesktopRelease)?, ), ), @@ -184,7 +176,7 @@ pub async fn initialize( CodexCookiePolicy::official().map_err(|_| OpenAiInitializeError::CookiePolicy)?, upstream_info, )); - let core_provider: Arc = Arc::new( + let core = Arc::new( CodexProvider::new( selector, Arc::clone(&catalog), @@ -241,7 +233,7 @@ pub async fn initialize( ) .with_oauth_client_id(config.oauth_client_id()), ); - let admin_provider: Arc = Arc::new(OpenAiAdminProvider::new( + let admin = Arc::new(OpenAiAdminProvider::new( provider_kind, profile, accounts, @@ -255,14 +247,14 @@ pub async fn initialize( websocket_pool, desktop_release_status, )); - let worker_contributions = provider::worker_contributions( + let workers = provider::workers::contributions( config.timezone, refresh, quota, catalog, config.quota_refresh_policy(), config.oauth_refresh_enabled(), - provider::ClientReleaseServices { + provider::workers::ClientReleaseServices { desktop: desktop_release, cli: cli_release, platforms: platform_releases, @@ -271,29 +263,12 @@ pub async fn initialize( .map_err(|_| OpenAiInitializeError::Worker)?; Ok(ProviderBundle { - core_provider, - admin_provider, - worker_contributions, + core, + admin, + workers, }) } -impl ProviderBundle { - #[must_use] - pub fn core_provider(&self) -> Arc { - Arc::clone(&self.core_provider) - } - - #[must_use] - pub fn admin_provider(&self) -> Arc { - Arc::clone(&self.admin_provider) - } - - /// 一次性移交 Host 任务计划,防止同一 owner 被重复注册 - pub fn take_worker_contributions(&mut self) -> Vec { - std::mem::take(&mut self.worker_contributions) - } -} - /// OpenAI 初始化失败的脱敏分类 #[derive(Debug, thiserror::Error)] pub enum OpenAiInitializeError { diff --git a/backend/crates/providers/openai/src/transport/profile/baseline.rs b/backend/crates/providers/openai/src/profile/baseline.rs similarity index 100% rename from backend/crates/providers/openai/src/transport/profile/baseline.rs rename to backend/crates/providers/openai/src/profile/baseline.rs diff --git a/backend/crates/providers/openai/src/transport/profile/cli_release.rs b/backend/crates/providers/openai/src/profile/cli_release.rs similarity index 100% rename from backend/crates/providers/openai/src/transport/profile/cli_release.rs rename to backend/crates/providers/openai/src/profile/cli_release.rs diff --git a/backend/crates/providers/openai/src/transport/profile/context.rs b/backend/crates/providers/openai/src/profile/context.rs similarity index 96% rename from backend/crates/providers/openai/src/transport/profile/context.rs rename to backend/crates/providers/openai/src/profile/context.rs index 1374ffb55..2df60a6a6 100644 --- a/backend/crates/providers/openai/src/transport/profile/context.rs +++ b/backend/crates/providers/openai/src/profile/context.rs @@ -3,7 +3,7 @@ use serde_json::Value; use super::{CodexWireProfile, selection::ClientKind}; -use crate::transport::automatic_context::{locate_contexts, rewrite_git_context}; +use crate::automatic_context::{locate_contexts, rewrite_git_context}; impl CodexWireProfile { pub(crate) fn apply_context_versions(&self, body: &mut Value) { diff --git a/backend/crates/providers/openai/src/transport/profile/desktop_artifact.rs b/backend/crates/providers/openai/src/profile/desktop_artifact.rs similarity index 100% rename from backend/crates/providers/openai/src/transport/profile/desktop_artifact.rs rename to backend/crates/providers/openai/src/profile/desktop_artifact.rs diff --git a/backend/crates/providers/openai/src/transport/profile/identity.rs b/backend/crates/providers/openai/src/profile/identity.rs similarity index 97% rename from backend/crates/providers/openai/src/transport/profile/identity.rs rename to backend/crates/providers/openai/src/profile/identity.rs index 5020f40ce..d9279ab81 100644 --- a/backend/crates/providers/openai/src/transport/profile/identity.rs +++ b/backend/crates/providers/openai/src/profile/identity.rs @@ -14,6 +14,9 @@ use super::selection::{ }; use super::{CodexWireProfile, CodexWireProfileState}; +pub(super) const USER_AGENT_PRODUCTS: [&str; 4] = + ["Codex Desktop", "codex-tui", "codex_exec", "codex_cli_rs"]; + impl CodexWireProfileState { /// 后台模型操作没有 Client Key,按当前全局选择冻结整套身份 pub(crate) async fn resolve_global_request_profile( @@ -250,14 +253,9 @@ impl ExactIdentity { if !safe_header(user_agent, 4096) { return Err(ClientProfileError::InvalidUserAgent); } - let known = ["Codex Desktop", "codex-tui", "codex_exec", "codex_cli_rs"] - .into_iter() - .find_map(|name| { - user_agent - .strip_prefix(name) - .and_then(|rest| rest.strip_prefix('/')) - .map(|rest| (name, rest)) - }); + let known = user_agent + .split_once('/') + .filter(|(name, _)| USER_AGENT_PRODUCTS.contains(name)); let (originator, codex_version, recognized) = if let Some((name, rest)) = known { let version = rest.split_once(' ').map_or(rest, |(version, _)| version); parse_core_version(version)?; diff --git a/backend/crates/providers/openai/src/profile/mod.rs b/backend/crates/providers/openai/src/profile/mod.rs new file mode 100644 index 000000000..7e453720e --- /dev/null +++ b/backend/crates/providers/openai/src/profile/mod.rs @@ -0,0 +1,24 @@ +//! OpenAI 请求画像、版本选择与官方发行资料入口 + +mod baseline; +pub mod cli_release; +mod context; +pub mod desktop_artifact; +pub mod identity; +pub mod platform_release; +pub mod selection; + +mod release; +mod state; + +pub use gateway_core::account::RequestLocation as CodexRequestLocation; +pub use release::{ + APPCAST_POLL_INTERVAL, CODEX_DESKTOP_APPCAST_URL, CodexArtifactProfileCache, + CodexBundledReleaseProfile, CodexDesktopRelease, CodexDesktopReleaseError, + CodexDesktopReleaseService, CodexDesktopReleaseSnapshot, CodexDesktopReleaseStatus, + CodexDesktopReleaseTransport, OfficialCodexDesktopReleaseTransport, parse_desktop_release, +}; +use release::{ + ARTIFACT_PROFILE_CACHE_RENEW_INTERVAL, ARTIFACT_PROFILE_CACHE_TTL, numeric_dotted_version, +}; +pub use state::{CodexWireProfile, CodexWireProfileState}; diff --git a/backend/crates/providers/openai/src/transport/profile/platform_release/artifact.rs b/backend/crates/providers/openai/src/profile/platform_release/artifact.rs similarity index 100% rename from backend/crates/providers/openai/src/transport/profile/platform_release/artifact.rs rename to backend/crates/providers/openai/src/profile/platform_release/artifact.rs diff --git a/backend/crates/providers/openai/src/transport/profile/platform_release/mod.rs b/backend/crates/providers/openai/src/profile/platform_release/mod.rs similarity index 100% rename from backend/crates/providers/openai/src/transport/profile/platform_release/mod.rs rename to backend/crates/providers/openai/src/profile/platform_release/mod.rs diff --git a/backend/crates/providers/openai/src/transport/profile/platform_release/range.rs b/backend/crates/providers/openai/src/profile/platform_release/range.rs similarity index 100% rename from backend/crates/providers/openai/src/transport/profile/platform_release/range.rs rename to backend/crates/providers/openai/src/profile/platform_release/range.rs diff --git a/backend/crates/providers/openai/src/transport/profile/platform_release/xz.rs b/backend/crates/providers/openai/src/profile/platform_release/xz.rs similarity index 100% rename from backend/crates/providers/openai/src/transport/profile/platform_release/xz.rs rename to backend/crates/providers/openai/src/profile/platform_release/xz.rs diff --git a/backend/crates/providers/openai/src/transport/profile/mod.rs b/backend/crates/providers/openai/src/profile/release.rs similarity index 65% rename from backend/crates/providers/openai/src/transport/profile/mod.rs rename to backend/crates/providers/openai/src/profile/release.rs index 3034631a2..feda4d457 100644 --- a/backend/crates/providers/openai/src/transport/profile/mod.rs +++ b/backend/crates/providers/openai/src/profile/release.rs @@ -1,12 +1,10 @@ -//! Codex Desktop 上游请求画像 +//! OpenAI Desktop 发行解析、制品缓存与刷新服务 -use std::collections::{BTreeMap, VecDeque}; use std::sync::{Arc, RwLock}; use std::time::Duration; use chrono::{DateTime, Utc}; use futures::{StreamExt as _, future::BoxFuture}; -use gateway_core::account::OpaqueProviderData; use gateway_core::provider_ports::{ ProviderArtifactProfile, ProviderArtifactProfileCachePort, ProviderStoreError, }; @@ -14,21 +12,15 @@ use gateway_core::routing::ProviderKind; use reqwest::Client; use reqwest::redirect::Policy; use roxmltree::{Document, Node}; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; use serde_json::{Map, Value}; use url::Url; -use self::desktop_artifact::{CodexDesktopArtifactError, fetch_codex_core_version}; +use super::desktop_artifact::{self, CodexDesktopArtifactError, fetch_codex_core_version}; -mod baseline; -pub mod cli_release; -mod context; -pub mod desktop_artifact; -pub mod identity; -pub mod platform_release; -pub mod selection; - -use selection::{ClientKind, ClientPlatform, ClientRelease}; +use super::CodexWireProfileState; +use super::selection::{ClientKind, ClientPlatform, ClientRelease}; +use gateway_core::account::OpaqueProviderData; /// Codex Desktop 官方 appcast 地址 pub const CODEX_DESKTOP_APPCAST_URL: &str = @@ -38,318 +30,11 @@ pub const APPCAST_POLL_INTERVAL: Duration = Duration::from_secs(60 * 60); const APPCAST_TIMEOUT: Duration = Duration::from_secs(30); const MAX_APPCAST_BYTES: usize = 1024 * 1024; -const ARTIFACT_PROFILE_CACHE_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60); -const ARTIFACT_PROFILE_CACHE_RENEW_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60); +pub(super) const ARTIFACT_PROFILE_CACHE_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60); +pub(super) const ARTIFACT_PROFILE_CACHE_RENEW_INTERVAL: Duration = + Duration::from_secs(24 * 60 * 60); const ARTIFACT_PROFILE_SCHEMA_VERSION: u64 = 1; -/// 保留已有配置类型入口;位置规则由出口领域统一维护 -pub use gateway_core::account::RequestLocation as CodexRequestLocation; - -/// Codex 上游请求身份快照 -/// -/// 预设按官方配套版本生成 UA;自定义身份保留完整 UA 及其配套请求头 -/// 官方制品核验只更新独立的基线与预设资料,不改写已冻结的请求身份 -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct CodexWireProfile { - pub client_kind: ClientKind, - /// `originator` 请求头及 User-Agent 产品名 - pub originator: String, - /// Core 版本,用于模型请求的 version 和 client_version - pub codex_version: String, - /// Desktop 应用版本,用于 app-server `clientInfo.version` 对应的 UA 后缀 - pub desktop_version: String, - /// Desktop 制品构建号,仅用于发布对齐诊断 - pub desktop_build: String, - /// Codex Core UA 中的目标操作系统类型 - pub os_type: String, - /// Codex Core UA 中的目标操作系统版本 - pub os_version: String, - /// Codex Core UA 中的目标架构 - pub arch: String, - /// Codex Core UA 中的终端标记 - pub terminal: String, - /// 入口专属或自定义的完整值;存在时不得用默认预设重新拼接 - #[serde(default, skip_serializing_if = "Option::is_none")] - pub exact_user_agent: Option, - /// Key 的安装身份种子,仅在本地按 Key 与账号派生出站身份 - #[serde(default, skip_serializing_if = "Option::is_none")] - pub installation_seed: Option, - /// 未配置时不发送 residency 头;不随制品版本更新而改变 - pub residency: Option, - /// 部署指定的账号路由头;未配置时不发送,不随客户端身份选择改变 - pub account_routing_override: Option, - /// 版本元组最后一次经制品核验的时间;不表示 TLS 传输已重新核验 - pub verified_at: DateTime, -} - -impl Default for CodexWireProfile { - fn default() -> Self { - let release = baseline::MACOS_RELEASE; - let environment = baseline::MACOS_ENVIRONMENT; - Self { - client_kind: ClientKind::Desktop, - originator: baseline::DESKTOP_ORIGINATOR.to_owned(), - codex_version: release.core.version.to_owned(), - desktop_version: release.version.to_owned(), - desktop_build: release.build.to_owned(), - os_type: environment.os_type.to_owned(), - os_version: environment.os_version.to_owned(), - arch: environment.arch.to_owned(), - terminal: baseline::TERMINAL.to_owned(), - exact_user_agent: None, - installation_seed: None, - residency: None, - account_routing_override: None, - verified_at: release.core.verified_at(), - } - } -} - -impl CodexWireProfile { - /// 原样返回已解析的完整 UA;默认预设按 bundled Core app-server 格式生成 - pub fn user_agent(&self) -> String { - if let Some(user_agent) = &self.exact_user_agent { - return user_agent.clone(); - } - if self.client_kind == ClientKind::Cli { - return format!( - "{}/{} ({} {}; {}) {}", - self.originator, - self.codex_version, - self.os_type, - self.os_version, - self.arch, - self.terminal - ); - } - format!( - "{}/{} ({} {}; {}) {} ({}; {})", - self.originator, - self.codex_version, - self.os_type, - self.os_version, - self.arch, - self.terminal, - self.originator, - self.desktop_version, - ) - } - - /// 按 Codex Desktop 暴露的稳定桌面 surface 格式构造 User-Agent - /// - /// Electron 网络栈会为 renderer 请求附加运行时 User-Agent;非 Electron transport - /// 使用同一官方包中 `getDesktopUserAgent` 的稳定格式 - /// 它与 bundled Core 请求使用的 - /// 复合 User-Agent 是两个独立 surface - #[must_use] - pub fn desktop_user_agent(&self) -> String { - format!( - "{}/{} ({}; {})", - self.originator, self.desktop_version, self.os_type, self.arch - ) - } -} - -/// 跨 Codex 上游请求共享的运行时请求画像 -#[derive(Debug, Clone)] -pub struct CodexWireProfileState { - profile: Arc>, - releases: Arc>, -} - -type ClientReleases = BTreeMap<(ClientKind, ClientPlatform, String), ClientReleaseObservation>; - -/// 每渠道保留的发布观察深度:当前版本加上全部滞后档位。 -const RELEASE_HISTORY_CAPACITY: usize = selection::MAX_VERSION_LAG as usize + 1; - -#[derive(Debug, Clone, Default)] -struct ClientReleaseObservation { - release: Option, - /// 本渠道倒序观察到的发布序列(含当前版本),仅进程内存;重启后从种子与缓存重新积累。 - history: VecDeque, - checked_at: Option>, - error: Option, -} - -/// 观察到的发布进入历史:同版本刷新队首,新版本压入队首;超出深度丢弃最旧一项。 -fn observe_release(history: &mut VecDeque, release: ClientRelease) { - if history - .front() - .is_some_and(|front| front.same_identity(&release)) - { - history[0] = release; - } else { - history.push_front(release); - } - while history.len() > RELEASE_HISTORY_CAPACITY { - history.pop_back(); - } -} - -impl CodexWireProfileState { - /// 从启动画像创建运行时状态 - pub fn new(profile: CodexWireProfile) -> Self { - let state = Self { - profile: Arc::new(RwLock::new(profile)), - releases: Arc::default(), - }; - // macOS arm64 的当前发布来自初始画像(默认快照或恢复缓存);补齐观察表项, - // 让滞后档位在首次 appcast 检查前也有历史可解析。 - let initial = state.snapshot(); - state.seed_client_release( - ClientKind::Desktop, - ClientPlatform::Macos, - "arm64", - ClientRelease { - codex_version: initial.codex_version, - desktop_version: Some(initial.desktop_version), - desktop_build: Some(initial.desktop_build), - verified_at: Some(initial.verified_at), - }, - ); - cli_release::seed_releases(&state); - platform_release::seed_releases(&state); - state - } - - pub(crate) fn effective_installation_id( - &self, - client_key_id: &gateway_core::policy::ClientApiKeyId, - account_id: &gateway_core::account::ProviderAccountId, - account_installation_id: &str, - ) -> String { - self.profile - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .effective_installation_id(client_key_id, account_id, account_installation_id) - } - - /// 返回当前画像的独立快照,避免持锁执行网络请求 - pub fn snapshot(&self) -> CodexWireProfile { - self.profile - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone() - } - - /// 原子发布同一 Desktop ZIP 中核验出的完整版本元组 - pub fn update_bundled_release(&self, release: &CodexBundledReleaseProfile) { - let mut profile = self - .profile - .write() - .unwrap_or_else(std::sync::PoisonError::into_inner); - profile.codex_version.clone_from(&release.codex_version); - profile.desktop_version.clone_from(&release.desktop_version); - profile.desktop_build.clone_from(&release.desktop_build); - profile.verified_at = release.verified_at; - } - - pub fn client_release( - &self, - client: ClientKind, - platform: ClientPlatform, - arch: &str, - ) -> Option { - if client == ClientKind::Desktop && platform == ClientPlatform::Macos && arch == "arm64" { - let profile = self.snapshot(); - return Some(ClientRelease { - codex_version: profile.codex_version, - desktop_version: Some(profile.desktop_version), - desktop_build: Some(profile.desktop_build), - verified_at: Some(profile.verified_at), - }); - } - self.releases - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .get(&(client, platform, arch.to_owned())) - .and_then(|state| state.release.clone()) - } - - /// 按滞后档位解析发布:取观察历史的第 `lag` 项,历史不足时回退最旧一项。 - /// - /// 滞后档位不引入新的失败模式:历史缺失时调用方回退到当前发布。 - pub fn lagged_client_release( - &self, - client: ClientKind, - platform: ClientPlatform, - arch: &str, - lag: u32, - ) -> Option { - self.releases - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .get(&(client, platform, arch.to_owned())) - .and_then(|state| { - state - .history - .get(lag as usize) - .or_else(|| state.history.back()) - .cloned() - }) - } - - pub fn client_release_status( - &self, - client: ClientKind, - platform: ClientPlatform, - arch: &str, - ) -> (Option>, Option) { - self.releases - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .get(&(client, platform, arch.to_owned())) - .map_or((None, None), |state| { - (state.checked_at, state.error.clone()) - }) - } - - fn seed_client_release( - &self, - client: ClientKind, - platform: ClientPlatform, - arch: &str, - release: ClientRelease, - ) { - let mut states = self - .releases - .write() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let state = states - .entry((client, platform, arch.to_owned())) - .or_default(); - // 种子与缓存恢复同样构成观察:更晚恢复的版本会排在种子之前,形成启动历史。 - observe_release(&mut state.history, release.clone()); - state.release = Some(release); - } - - pub(crate) fn record_client_release( - &self, - client: ClientKind, - platform: ClientPlatform, - arch: &str, - result: Result, - ) { - let mut states = self - .releases - .write() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let state = states - .entry((client, platform, arch.to_owned())) - .or_default(); - state.checked_at = Some(Utc::now()); - match result { - Ok(release) => { - state.release = Some(release.clone()); - state.error = None; - observe_release(&mut state.history, release); - } - // 失败观察只更新状态,不改动发布历史。 - Err(error) => state.error = Some(error), - } - } -} - /// 同一个官方 Desktop ZIP 中核验出的原子版本元组 #[derive(Debug, Clone, PartialEq, Eq)] pub struct CodexBundledReleaseProfile { @@ -898,7 +583,7 @@ fn local_attribute(node: Option>, local_name: &str) -> Option bool { +pub(super) fn numeric_dotted_version(value: &str) -> bool { let mut parts = value.split('.'); let valid = parts .by_ref() diff --git a/backend/crates/providers/openai/src/transport/profile/selection.rs b/backend/crates/providers/openai/src/profile/selection.rs similarity index 98% rename from backend/crates/providers/openai/src/transport/profile/selection.rs rename to backend/crates/providers/openai/src/profile/selection.rs index 36e7cc67e..173b36878 100644 --- a/backend/crates/providers/openai/src/transport/profile/selection.rs +++ b/backend/crates/providers/openai/src/profile/selection.rs @@ -373,7 +373,11 @@ impl CodexWireProfileState { })); } } - object(&json!({ "presets": presets, "maxVersionLag": MAX_VERSION_LAG })) + object(&json!({ + "presets": presets, + "maxVersionLag": MAX_VERSION_LAG, + "recognizedUserAgentPrefixes": super::identity::USER_AGENT_PRODUCTS.map(|product| format!("{product}/")), + })) } } diff --git a/backend/crates/providers/openai/src/profile/state.rs b/backend/crates/providers/openai/src/profile/state.rs new file mode 100644 index 000000000..f860f6902 --- /dev/null +++ b/backend/crates/providers/openai/src/profile/state.rs @@ -0,0 +1,313 @@ +//! OpenAI 请求身份快照与发行历史状态 + +use super::selection::{ClientKind, ClientPlatform, ClientRelease}; +use super::{CodexBundledReleaseProfile, baseline, cli_release, platform_release, selection}; +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, VecDeque}; +use std::sync::{Arc, RwLock}; + +/// Codex 上游请求身份快照 +/// +/// 预设按官方配套版本生成 UA;自定义身份保留完整 UA 及其配套请求头 +/// 官方制品核验只更新独立的基线与预设资料,不改写已冻结的请求身份 +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CodexWireProfile { + pub client_kind: ClientKind, + /// `originator` 请求头及 User-Agent 产品名 + pub originator: String, + /// Core 版本,用于模型请求的 version 和 client_version + pub codex_version: String, + /// Desktop 应用版本,用于 app-server `clientInfo.version` 对应的 UA 后缀 + pub desktop_version: String, + /// Desktop 制品构建号,仅用于发布对齐诊断 + pub desktop_build: String, + /// Codex Core UA 中的目标操作系统类型 + pub os_type: String, + /// Codex Core UA 中的目标操作系统版本 + pub os_version: String, + /// Codex Core UA 中的目标架构 + pub arch: String, + /// Codex Core UA 中的终端标记 + pub terminal: String, + /// 入口专属或自定义的完整值;存在时不得用默认预设重新拼接 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exact_user_agent: Option, + /// Key 的安装身份种子,仅在本地按 Key 与账号派生出站身份 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub installation_seed: Option, + /// 未配置时不发送 residency 头;不随制品版本更新而改变 + pub residency: Option, + /// 部署指定的账号路由头;未配置时不发送,不随客户端身份选择改变 + pub account_routing_override: Option, + /// 版本元组最后一次经制品核验的时间;不表示 TLS 传输已重新核验 + pub verified_at: DateTime, +} + +impl Default for CodexWireProfile { + fn default() -> Self { + let release = baseline::MACOS_RELEASE; + let environment = baseline::MACOS_ENVIRONMENT; + Self { + client_kind: ClientKind::Desktop, + originator: baseline::DESKTOP_ORIGINATOR.to_owned(), + codex_version: release.core.version.to_owned(), + desktop_version: release.version.to_owned(), + desktop_build: release.build.to_owned(), + os_type: environment.os_type.to_owned(), + os_version: environment.os_version.to_owned(), + arch: environment.arch.to_owned(), + terminal: baseline::TERMINAL.to_owned(), + exact_user_agent: None, + installation_seed: None, + residency: None, + account_routing_override: None, + verified_at: release.core.verified_at(), + } + } +} + +impl CodexWireProfile { + /// 原样返回已解析的完整 UA;默认预设按 bundled Core app-server 格式生成 + pub fn user_agent(&self) -> String { + if let Some(user_agent) = &self.exact_user_agent { + return user_agent.clone(); + } + if self.client_kind == ClientKind::Cli { + return format!( + "{}/{} ({} {}; {}) {}", + self.originator, + self.codex_version, + self.os_type, + self.os_version, + self.arch, + self.terminal + ); + } + format!( + "{}/{} ({} {}; {}) {} ({}; {})", + self.originator, + self.codex_version, + self.os_type, + self.os_version, + self.arch, + self.terminal, + self.originator, + self.desktop_version, + ) + } + + /// 按 Codex Desktop 暴露的稳定桌面 surface 格式构造 User-Agent + /// + /// Electron 网络栈会为 renderer 请求附加运行时 User-Agent;非 Electron transport + /// 使用同一官方包中 `getDesktopUserAgent` 的稳定格式 + /// 它与 bundled Core 请求使用的 + /// 复合 User-Agent 是两个独立 surface + #[must_use] + pub fn desktop_user_agent(&self) -> String { + format!( + "{}/{} ({}; {})", + self.originator, self.desktop_version, self.os_type, self.arch + ) + } +} + +/// 跨 Codex 上游请求共享的运行时请求画像 +#[derive(Debug, Clone)] +pub struct CodexWireProfileState { + profile: Arc>, + releases: Arc>, +} + +type ClientReleases = BTreeMap<(ClientKind, ClientPlatform, String), ClientReleaseObservation>; + +/// 每渠道保留的发布观察深度:当前版本加上全部滞后档位。 +const RELEASE_HISTORY_CAPACITY: usize = selection::MAX_VERSION_LAG as usize + 1; + +#[derive(Debug, Clone, Default)] +struct ClientReleaseObservation { + release: Option, + /// 本渠道倒序观察到的发布序列(含当前版本),仅进程内存;重启后从种子与缓存重新积累。 + history: VecDeque, + checked_at: Option>, + error: Option, +} + +/// 观察到的发布进入历史:同版本刷新队首,新版本压入队首;超出深度丢弃最旧一项。 +fn observe_release(history: &mut VecDeque, release: ClientRelease) { + if history + .front() + .is_some_and(|front| front.same_identity(&release)) + { + history[0] = release; + } else { + history.push_front(release); + } + while history.len() > RELEASE_HISTORY_CAPACITY { + history.pop_back(); + } +} + +impl CodexWireProfileState { + /// 从启动画像创建运行时状态 + pub fn new(profile: CodexWireProfile) -> Self { + let state = Self { + profile: Arc::new(RwLock::new(profile)), + releases: Arc::default(), + }; + // macOS arm64 的当前发布来自初始画像(默认快照或恢复缓存);补齐观察表项, + // 让滞后档位在首次 appcast 检查前也有历史可解析。 + let initial = state.snapshot(); + state.seed_client_release( + ClientKind::Desktop, + ClientPlatform::Macos, + "arm64", + ClientRelease { + codex_version: initial.codex_version, + desktop_version: Some(initial.desktop_version), + desktop_build: Some(initial.desktop_build), + verified_at: Some(initial.verified_at), + }, + ); + cli_release::seed_releases(&state); + platform_release::seed_releases(&state); + state + } + + pub(crate) fn effective_installation_id( + &self, + client_key_id: &gateway_core::policy::ClientApiKeyId, + account_id: &gateway_core::account::ProviderAccountId, + account_installation_id: &str, + ) -> String { + self.profile + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .effective_installation_id(client_key_id, account_id, account_installation_id) + } + + /// 返回当前画像的独立快照,避免持锁执行网络请求 + pub fn snapshot(&self) -> CodexWireProfile { + self.profile + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } + + /// 原子发布同一 Desktop ZIP 中核验出的完整版本元组 + pub fn update_bundled_release(&self, release: &CodexBundledReleaseProfile) { + let mut profile = self + .profile + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); + profile.codex_version.clone_from(&release.codex_version); + profile.desktop_version.clone_from(&release.desktop_version); + profile.desktop_build.clone_from(&release.desktop_build); + profile.verified_at = release.verified_at; + } + + pub fn client_release( + &self, + client: ClientKind, + platform: ClientPlatform, + arch: &str, + ) -> Option { + if client == ClientKind::Desktop && platform == ClientPlatform::Macos && arch == "arm64" { + let profile = self.snapshot(); + return Some(ClientRelease { + codex_version: profile.codex_version, + desktop_version: Some(profile.desktop_version), + desktop_build: Some(profile.desktop_build), + verified_at: Some(profile.verified_at), + }); + } + self.releases + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(&(client, platform, arch.to_owned())) + .and_then(|state| state.release.clone()) + } + + /// 按滞后档位解析发布:取观察历史的第 `lag` 项,历史不足时回退最旧一项。 + /// + /// 滞后档位不引入新的失败模式:历史缺失时调用方回退到当前发布。 + pub fn lagged_client_release( + &self, + client: ClientKind, + platform: ClientPlatform, + arch: &str, + lag: u32, + ) -> Option { + self.releases + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(&(client, platform, arch.to_owned())) + .and_then(|state| { + state + .history + .get(lag as usize) + .or_else(|| state.history.back()) + .cloned() + }) + } + + pub fn client_release_status( + &self, + client: ClientKind, + platform: ClientPlatform, + arch: &str, + ) -> (Option>, Option) { + self.releases + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(&(client, platform, arch.to_owned())) + .map_or((None, None), |state| { + (state.checked_at, state.error.clone()) + }) + } + + pub(super) fn seed_client_release( + &self, + client: ClientKind, + platform: ClientPlatform, + arch: &str, + release: ClientRelease, + ) { + let mut states = self + .releases + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let state = states + .entry((client, platform, arch.to_owned())) + .or_default(); + // 种子与缓存恢复同样构成观察:更晚恢复的版本会排在种子之前,形成启动历史。 + observe_release(&mut state.history, release.clone()); + state.release = Some(release); + } + + pub(crate) fn record_client_release( + &self, + client: ClientKind, + platform: ClientPlatform, + arch: &str, + result: Result, + ) { + let mut states = self + .releases + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let state = states + .entry((client, platform, arch.to_owned())) + .or_default(); + state.checked_at = Some(Utc::now()); + match result { + Ok(release) => { + state.release = Some(release.clone()); + state.error = None; + observe_release(&mut state.history, release); + } + // 失败观察只更新状态,不改动发布历史。 + Err(error) => state.error = Some(error), + } + } +} diff --git a/backend/crates/providers/openai/src/provider/execution.rs b/backend/crates/providers/openai/src/provider/execution.rs index 8b5f44856..405a50027 100644 --- a/backend/crates/providers/openai/src/provider/execution.rs +++ b/backend/crates/providers/openai/src/provider/execution.rs @@ -316,9 +316,7 @@ impl CodexProvider { .remember_turn( turn, affinity, - context - .account_selection_policy() - .openai_session_affinity_ttl(), + context.account_selection_policy().session_affinity_ttl(), ) .await .map_err(map_selection_error)?; @@ -797,7 +795,7 @@ fn image_response_metering( .and_then(Value::as_u64); // 总量是上游独立报告的事实;图片明细是总输入/输出的子集,不能再次相加 usage.total_tokens = raw.get("total_tokens").and_then(Value::as_u64); - let cost = crate::transport::usage::image_calculated_cost(request_body, &raw, prices); + let cost = crate::billing::image_calculated_cost(request_body, &raw, prices); (usage != Usage::default()).then_some((usage, cost)) } diff --git a/backend/crates/providers/openai/src/provider/failure.rs b/backend/crates/providers/openai/src/provider/failure.rs index 2e5428ef1..7f2dee25b 100644 --- a/backend/crates/providers/openai/src/provider/failure.rs +++ b/backend/crates/providers/openai/src/provider/failure.rs @@ -1208,9 +1208,9 @@ pub(super) fn client_diagnostic( } pub(super) fn profile_diagnostic( - error: &crate::transport::profile::selection::ClientProfileError, + error: &crate::profile::selection::ClientProfileError, ) -> ProviderDiagnostic { - use crate::transport::profile::selection::ClientProfileError; + use crate::profile::selection::ClientProfileError; let code = match error { ClientProfileError::Invalid => "request_profile_invalid", ClientProfileError::InvalidInstallationSeed => "request_profile_installation_seed_invalid", diff --git a/backend/crates/providers/openai/src/provider/guardian.rs b/backend/crates/providers/openai/src/provider/guardian.rs index f6ec61ccf..97252907e 100644 --- a/backend/crates/providers/openai/src/provider/guardian.rs +++ b/backend/crates/providers/openai/src/provider/guardian.rs @@ -133,7 +133,7 @@ fn parent_key( response_id: &str, ) -> [u8; 32] { let mut hash = Sha256::new(); - let identity = crate::credential::oauth_identity_key(account); + let identity = crate::request_identity::oauth_identity_key(account); for part in [client_key.as_str(), &identity, response_id] { hash.update(part.len().to_le_bytes()); hash.update(part.as_bytes()); diff --git a/backend/crates/providers/openai/src/provider/live.rs b/backend/crates/providers/openai/src/provider/live.rs index 96fc10c35..15dcd1629 100644 --- a/backend/crates/providers/openai/src/provider/live.rs +++ b/backend/crates/providers/openai/src/provider/live.rs @@ -35,8 +35,8 @@ use crate::credential::{ CODEX_AUTHENTICATION_KIND_OAUTH, CodexCredentialRepository, CodexSelectionModel, SelectCodexProviderEndpointCredential, }; +use crate::profile::CodexWireProfile; use crate::transport::headers::websocket_header_pairs; -use crate::transport::profile::CodexWireProfile; use crate::transport::websocket::{connect_live_sideband, into_live_relay}; use crate::transport::{CODEX_REALTIME_CALLS_PATH, CodexRequestContext}; diff --git a/backend/crates/providers/openai/src/provider/messages/stream.rs b/backend/crates/providers/openai/src/provider/messages/stream.rs index 1bf29d3fc..d159b7f57 100644 --- a/backend/crates/providers/openai/src/provider/messages/stream.rs +++ b/backend/crates/providers/openai/src/provider/messages/stream.rs @@ -12,8 +12,8 @@ use gateway_protocol::{ }; use super::*; +use crate::billing::{OpenAiBillingUsage, configured_token_billing_breakdown}; use crate::provider::observation::insert_first_timing; -use crate::transport::usage::{OpenAiBillingUsage, configured_token_billing_breakdown}; // 非流式上游需要完整解码后才能交付;流式交付不受此总长限制 const MAX_MESSAGES_JSON_BYTES: usize = 16 * 1024 * 1024; diff --git a/backend/crates/providers/openai/src/provider/mod.rs b/backend/crates/providers/openai/src/provider/mod.rs index 20f8b7b80..037b33eb4 100644 --- a/backend/crates/providers/openai/src/provider/mod.rs +++ b/backend/crates/providers/openai/src/provider/mod.rs @@ -55,6 +55,7 @@ use serde_json::{Map, Value, json}; use url::Url; use uuid::Uuid; +use crate::billing::normalize_service_tier; use crate::credential::{ CodexAccountFailure, CodexCredentialCatalogError, CodexCredentialCatalogService, CodexCredentialLease, CodexCredentialQuotaService, CodexCredentialRefreshOutcome, @@ -66,6 +67,7 @@ use crate::credential::{ derive_codex_transport_key, derive_endpoint_affinity_with_headers, derive_live_session_affinity, derive_previous_response_id_hash, derive_turn_alias, }; +use crate::profile::{APPCAST_POLL_INTERVAL, CodexDesktopReleaseService, CodexWireProfileState}; use crate::request_identity::{account_session_with_headers, turn_id_with_headers}; use crate::session_transport::CodexSessionTransportRecovery; use crate::transport::canonical::{ @@ -77,9 +79,6 @@ use crate::transport::catalog::{ use crate::transport::diagnostics::{ CodexFailureCategory, CodexUpstreamFailure, CodexUpstreamSendPhase, }; -use crate::transport::profile::{ - APPCAST_POLL_INTERVAL, CodexDesktopReleaseService, CodexWireProfileState, -}; use crate::transport::protocol::responses::{ CodexResponsesRequest, PREVIOUS_RESPONSE_NOT_FOUND_CODE, PREVIOUS_RESPONSE_NOT_FOUND_MESSAGE, PreviousResponseScope, ResponseEventSignals, TransportRequirement, fast_policy_tier, @@ -90,7 +89,6 @@ use crate::transport::request::{ apply_codex_request_country, encode_generate_payload, scope_request_to_account, }; use crate::transport::session::CodexSessionIdentity; -use crate::transport::usage::normalize_service_tier; use crate::transport::websocket::{ CodexWebSocketExchangeError, PreviousResponseUnavailableReason, WEBSOCKET_CLOSE_MESSAGE_TOO_BIG, }; @@ -110,16 +108,14 @@ mod live; mod messages; mod observation; mod upstream_adapter; -mod workers; +pub(crate) mod workers; pub(crate) use live::{CodexLiveGateway, CodexLiveRegistry}; -pub(crate) use workers::ClientReleaseServices; use execution::*; #[doc(hidden)] pub use failure::openai_failure_affects_account_score; use failure::*; use observation::*; -pub(crate) use workers::worker_contributions; const PROVIDER_NAME: &str = "openai"; const HTTP_SSE_TRANSPORT: &str = "http_sse"; @@ -289,9 +285,7 @@ impl CodexProvider { .remember_turn( &turn, affinity, - context - .account_selection_policy() - .openai_session_affinity_ttl(), + context.account_selection_policy().session_affinity_ttl(), ) .await .map_err(map_selection_error)?; @@ -443,7 +437,7 @@ impl Provider for CodexProvider { return Ok(true); }; let payload = generate.protocol_payload(); - if policy.openai_account_affinity() != AccountAffinity::Strict + if policy.account_affinity() != AccountAffinity::Strict || !crate::request_identity::follows_session_with_headers( payload.body(), payload.context(), @@ -480,22 +474,21 @@ impl Provider for CodexProvider { &self, configuration: &gateway_core::account::OpaqueProviderData, ) -> Result { - let selection = - crate::transport::profile::identity::RequestProfileSelection::parse(configuration) - .map_err(|error| { - provider_error( - ProviderErrorKind::InvalidRequest, - UpstreamSendState::NotSent, - ) - .with_diagnostic(profile_diagnostic(&error)) - })?; + let selection = crate::profile::identity::RequestProfileSelection::parse(configuration) + .map_err(|error| { + provider_error( + ProviderErrorKind::InvalidRequest, + UpstreamSendState::NotSent, + ) + .with_diagnostic(profile_diagnostic(&error)) + })?; let profile = selection .resolve(self.client.profile_state()) .map_err(|error| { provider_error(ProviderErrorKind::Unavailable, UpstreamSendState::NotSent) .with_diagnostic(profile_diagnostic(&error)) })?; - crate::transport::profile::selection::object(&profile).map_err(|error| { + crate::profile::selection::object(&profile).map_err(|error| { provider_error(ProviderErrorKind::Protocol, UpstreamSendState::NotSent) .with_diagnostic(profile_diagnostic(&error)) }) @@ -718,7 +711,7 @@ impl Provider for CodexProvider { .filter(|prepared| { prepared.session_affinity.is_none() && prepared.previous_session.is_none() - && context.account_selection_policy().openai_account_affinity() + && context.account_selection_policy().account_affinity() != AccountAffinity::Relaxed && context.continuation_attempt() == ContinuationAttempt::None && !guardian @@ -749,7 +742,7 @@ impl Provider for CodexProvider { ); if context.continuation_attempt() == ContinuationAttempt::RotateForClientReplay && (selection_session_affinity.is_none() - || context.account_selection_policy().openai_account_affinity() + || context.account_selection_policy().account_affinity() == AccountAffinity::Relaxed) { // 没有可持续的会话绑定就无法保证完整历史使用替代账号,交回原始容量错误 @@ -996,7 +989,7 @@ impl CodexProvider { lease.authentication(), crate::credential::CodexRuntimeAuthentication::OAuth(_) ) - .then(|| crate::credential::oauth_identity_key(lease.account())); + .then(|| crate::request_identity::oauth_identity_key(lease.account())); let native_owner = context.continuation().and_then(ContinuationBinding::pinned); let state_owner_cross_account = native_owner .is_some_and(|owner| !owner.matches(&provider_kind, lease.account_id())) diff --git a/backend/crates/providers/openai/src/provider/upstream_adapter.rs b/backend/crates/providers/openai/src/provider/upstream_adapter.rs index 856a49bde..c082026b6 100644 --- a/backend/crates/providers/openai/src/provider/upstream_adapter.rs +++ b/backend/crates/providers/openai/src/provider/upstream_adapter.rs @@ -1,10 +1,10 @@ //! 插件只替换业务 wire;账号租约、凭据解释与费用来源仍属于 OpenAI use super::*; -use crate::credential::{ApiKeyProtocol, CodexRuntimeAuthentication}; -use crate::transport::usage::{ +use crate::billing::{ OpenAiBillingUsage, configured_token_billing_breakdown, openai_billing_breakdown_with_override, }; +use crate::credential::{ApiKeyProtocol, CodexRuntimeAuthentication}; use gateway_core::{ account::{CredentialRevision, OutboundProxy, ProviderAccountId}, engine::upstream_adapter::{ diff --git a/backend/crates/providers/openai/src/provider/workers.rs b/backend/crates/providers/openai/src/provider/workers.rs index 3ba133b3c..91ee23ffd 100644 --- a/backend/crates/providers/openai/src/provider/workers.rs +++ b/backend/crates/providers/openai/src/provider/workers.rs @@ -1,8 +1,8 @@ //! OpenAI Provider 向 Host 贡献的后台 worker use super::*; -use crate::transport::profile::cli_release::CliReleaseService; -use crate::transport::profile::platform_release::PlatformDesktopReleaseService; +use crate::profile::cli_release::CliReleaseService; +use crate::profile::platform_release::PlatformDesktopReleaseService; use gateway_core::task::WorkerDaemonContext; pub(crate) struct ClientReleaseServices { @@ -23,7 +23,7 @@ pub(super) const MODEL_CATALOG_WORKER_OWNER: &str = "openai-model-catalog"; pub(super) const WARMUP_WORKER_OWNER: &str = "openai-account-warmup"; pub(super) const WARMUP_CHECK_INTERVAL: Duration = Duration::from_secs(30); -pub(crate) fn worker_contributions( +pub(crate) fn contributions( timezone: gateway_core::time::DeploymentTimeZone, refresh: Arc, quota: Arc, diff --git a/backend/crates/providers/openai/src/request_identity.rs b/backend/crates/providers/openai/src/request_identity.rs index b7fe88ec6..d7990ec94 100644 --- a/backend/crates/providers/openai/src/request_identity.rs +++ b/backend/crates/providers/openai/src/request_identity.rs @@ -1,9 +1,25 @@ -//! 请求正文与最终头部的会话身份解释,供账号亲和与传输编码共用 +//! 请求会话与账号身份解释,供账号亲和、连接隔离和资料缓存共用 use std::borrow::Cow; use serde_json::{Map, Value}; +/// 复用上游会话与账号资料时绑定本地记录和真实 OAuth 身份,正常续期不改变归属 +pub(crate) fn oauth_identity_key(account: &gateway_core::account::ProviderAccount) -> String { + use sha2::{Digest, Sha256}; + + let mut hash = Sha256::new(); + for part in [ + account.id().as_str(), + account.upstream_user_id().unwrap_or_default(), + account.upstream_account_id().unwrap_or_default(), + ] { + hash.update((part.len() as u64).to_le_bytes()); + hash.update(part.as_bytes()); + } + hex::encode(hash.finalize()) +} + /// 只有能识别出的后代线程禁止迁移会话;没有身份的普通客户端沿用现有调度 pub(crate) fn follows_session_with_headers( body: &Map, diff --git a/backend/crates/providers/openai/src/transport/canonical.rs b/backend/crates/providers/openai/src/transport/canonical.rs index 5b2040e8f..7919d8d65 100644 --- a/backend/crates/providers/openai/src/transport/canonical.rs +++ b/backend/crates/providers/openai/src/transport/canonical.rs @@ -24,7 +24,7 @@ use super::protocol::responses::{ ResponseEventSignals, ResponseTimingMetrics, ResponsesSseFailure, response_duration_ms, response_event_signals, }; -use super::usage::{ +use crate::billing::{ OpenAiBillingUsage, WebSearchPricing, normalize_service_tier, web_search_pricing, }; @@ -996,7 +996,7 @@ impl CodexCanonicalDecoder { .filter(|usage| billable_usage_is_complete(response, *usage)) .and_then(|usage| { let (web_search_calls, file_search_calls) = tool_calls?; - super::usage::openai_billing_breakdown_with_override( + crate::billing::openai_billing_breakdown_with_override( &self.upstream_model, OpenAiBillingUsage::from(usage) .with_web_search_calls(web_search_calls, self.web_search_pricing) diff --git a/backend/crates/providers/openai/src/transport/client.rs b/backend/crates/providers/openai/src/transport/client/backend.rs similarity index 88% rename from backend/crates/providers/openai/src/transport/client.rs rename to backend/crates/providers/openai/src/transport/client/backend.rs index b9ec06dc7..3159eb96c 100644 --- a/backend/crates/providers/openai/src/transport/client.rs +++ b/backend/crates/providers/openai/src/transport/client/backend.rs @@ -8,7 +8,7 @@ use std::{ time::{Duration, SystemTime, UNIX_EPOCH}, }; -use crate::transport::profile::CodexWireProfileState; +use crate::profile::CodexWireProfileState; use bytes::Bytes; use futures::{Stream, StreamExt}; use gateway_core::engine::middleware::MiddlewareHeader; @@ -28,10 +28,14 @@ use crate::transport::protocol::responses::{ CodexResponsesRequest, TransportRequirement, X_CODEX_TURN_STATE_CLIENT_METADATA_KEY, }; -use super::diagnostics::{CodexUpstreamDiagnostics, CodexUpstreamFailure, CodexUpstreamSendPhase}; -use super::response_meta::CodexResponseMetadata; -use super::tls::{CustomCaError, build_reqwest_client_with_custom_ca, custom_ca_env_cache_key}; -use super::websocket::{ +use super::super::diagnostics::{ + CodexUpstreamDiagnostics, CodexUpstreamFailure, CodexUpstreamSendPhase, +}; +use super::super::response_meta::CodexResponseMetadata; +use super::super::tls::{ + CustomCaError, build_reqwest_client_with_custom_ca, custom_ca_env_cache_key, +}; +use super::super::websocket::{ CodexWebSocketExchangeError, CodexWebSocketPool, CodexWebSocketPoolKey, CodexWebSocketRateLimitUpdates, CodexWebSocketRequest, CodexWebSocketResponseMetadataUpdates, PreparedWebSocket, WebSocketOriginBreaker, WebSocketPoolDecision, @@ -42,8 +46,8 @@ use super::websocket::{ // --------------------------------------------------------------------------- const UPSTREAM_CONNECT_TIMEOUT: Duration = Duration::from_secs(15); -pub(super) const UPSTREAM_STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(5 * 60); -pub(super) const X_CODEX_WS_STREAM_REQUEST_START_MS_CLIENT_METADATA_KEY: &str = +pub(in crate::transport) const UPSTREAM_STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(5 * 60); +pub(in crate::transport) const X_CODEX_WS_STREAM_REQUEST_START_MS_CLIENT_METADATA_KEY: &str = "x-codex-ws-stream-request-start-ms"; type ReqwestClientCacheKey = (Option, String, Duration); type ReqwestClientCache = Mutex>; @@ -60,12 +64,12 @@ pub fn build_account_http_client( build_account_http_client_with_timeout(account_id, proxy, UPSTREAM_CONNECT_TIMEOUT) } -pub(super) fn build_account_http_client_with_timeout( +pub(in crate::transport) fn build_account_http_client_with_timeout( account_id: &str, proxy: Option<&gateway_core::account::OutboundProxy>, timeout: Duration, ) -> Result { - super::tls::ensure_rustls_provider(); + super::super::tls::ensure_rustls_provider(); let cache_key = ( custom_ca_env_cache_key(), egress_key(account_id, proxy), @@ -86,7 +90,7 @@ pub(super) fn build_account_http_client_with_timeout( .map_err(|_| CustomCaError::ProxyConfiguration)? .redirect(reqwest::redirect::Policy::none()) .connect_timeout(timeout) - .connector_layer(super::connection::ConnectionLayer); + .connector_layer(super::super::connection::ConnectionLayer); let client = build_reqwest_client_with_custom_ca(builder)?; let mut clients = cache .lock() @@ -131,7 +135,7 @@ pub(crate) struct CodexClientVisibleUpstreamResponseParts { } impl CodexClientVisibleUpstreamResponse { - pub(super) fn new( + pub(in crate::transport) fn new( status: StatusCode, content_type: Option>, client_headers: Vec<(String, Bytes)>, @@ -225,7 +229,7 @@ pub enum CodexClientError { InvalidSse(#[from] SseError), /// 模型目录不是一个完整、安全的官方快照 #[error("invalid Codex model catalog: {0}")] - ModelCatalog(#[from] super::catalog::CodexModelCatalogError), + ModelCatalog(#[from] super::super::catalog::CodexModelCatalogError), /// HTTP/SSE 上游在空闲窗口内没有发送任何数据 #[error("upstream HTTP/SSE stream idle for {timeout:?}")] StreamIdleTimeout { @@ -617,7 +621,7 @@ pub type CodexResponseMetadataUpdates = CodexWebSocketResponseMetadataUpdates; /// Codex Responses 上游流式响应 pub struct CodexBackendStreamingResponse { - pub(crate) routing_affinity: Option, + pub(crate) routing_affinity: Option, /// HTTP 为 SSE 字节块,WebSocket 为完整 UTF-8 文本消息 pub body: CodexBackendSseStream, /// 实际使用的上游传输 @@ -667,16 +671,16 @@ pub struct CodexBackendJsonResponse { // --------------------------------------------------------------------------- #[derive(Clone, Copy, PartialEq, Eq)] -pub(super) enum OpenAiUpstreamProtocol { +pub(in crate::transport) enum OpenAiUpstreamProtocol { Codex, ResponsesApi, MessagesApi, } impl OpenAiUpstreamProtocol { - pub(super) const fn responses_path(self) -> &'static str { + pub(in crate::transport) const fn responses_path(self) -> &'static str { match self { - Self::Codex => super::endpoints::CODEX_RESPONSES_PATH, + Self::Codex => super::super::endpoints::CODEX_RESPONSES_PATH, Self::ResponsesApi => "/responses", Self::MessagesApi => "/messages", } @@ -687,27 +691,30 @@ impl OpenAiUpstreamProtocol { #[derive(Clone)] pub struct CodexBackendClient { pub(crate) peer_route: Option, - pub(super) routing_affinity: Option, - pub(super) privacy: Option<( + pub(in crate::transport) routing_affinity: + Option, + pub(in crate::transport) privacy: Option<( Arc, gateway_core::lifecycle::CancellationToken, )>, - pub(super) timezone: gateway_core::time::DeploymentTimeZone, - pub(super) connection_budget: Option, - pub(super) client: Client, - pub(super) default_client: Client, - pub(super) base_url: String, - pub(super) official_base_url: String, - pub(super) protocol: OpenAiUpstreamProtocol, - pub(super) fedramp_routing: bool, - pub(super) profile: CodexWireProfileState, - pub(super) websocket_pool: Option>, - pub(super) websocket_origin_breaker: WebSocketOriginBreaker, - pub(super) websocket_origin_key: String, - pub(super) outbound_proxy: Option, - pub(super) egress_key: String, - pub(super) middleware_headers: Vec, - pub(super) outbound_middleware: Option, + pub(in crate::transport) timezone: gateway_core::time::DeploymentTimeZone, + pub(in crate::transport) connection_budget: + Option, + pub(in crate::transport) client: Client, + pub(in crate::transport) default_client: Client, + pub(in crate::transport) base_url: String, + pub(in crate::transport) official_base_url: String, + pub(in crate::transport) protocol: OpenAiUpstreamProtocol, + pub(in crate::transport) fedramp_routing: bool, + pub(in crate::transport) profile: CodexWireProfileState, + pub(in crate::transport) websocket_pool: Option>, + pub(in crate::transport) websocket_origin_breaker: WebSocketOriginBreaker, + pub(in crate::transport) websocket_origin_key: String, + pub(in crate::transport) outbound_proxy: Option, + pub(in crate::transport) egress_key: String, + pub(in crate::transport) middleware_headers: Vec, + pub(in crate::transport) outbound_middleware: + Option, } impl CodexBackendClient { @@ -716,7 +723,7 @@ impl CodexBackendClient { } /// 请求只持有自己的画像副本;连接池和 HTTP client 继续共享既有资源 - pub fn with_request_profile(mut self, profile: super::profile::CodexWireProfile) -> Self { + pub fn with_request_profile(mut self, profile: crate::profile::CodexWireProfile) -> Self { self.profile = CodexWireProfileState::new(profile); self } @@ -742,7 +749,7 @@ impl CodexBackendClient { middleware_headers: Vec::new(), outbound_middleware: None, base_url, - official_base_url: super::endpoints::OFFICIAL_CODEX_BASE_URL.to_owned(), + official_base_url: super::super::endpoints::OFFICIAL_CODEX_BASE_URL.to_owned(), protocol: OpenAiUpstreamProtocol::Codex, fedramp_routing: false, profile, @@ -776,7 +783,7 @@ impl CodexBackendClient { pub(crate) fn with_routing_affinity( mut self, - affinity: Option, + affinity: Option, ) -> Self { self.routing_affinity = affinity; self @@ -799,7 +806,9 @@ impl CodexBackendClient { self } - pub(super) fn connection_opening(&self) -> Result, CodexClientError> { + pub(in crate::transport) fn connection_opening( + &self, + ) -> Result, CodexClientError> { self.connection_budget.as_ref().map_or(Ok(None), |budget| { budget .begin() @@ -807,7 +816,7 @@ impl CodexBackendClient { }) } - pub(super) fn http_opening_client(&self) -> Result { + pub(in crate::transport) fn http_opening_client(&self) -> Result { let Some(remaining) = self.connection_opening()? else { return Ok(self.client.clone()); }; @@ -834,7 +843,7 @@ impl CodexBackendClient { } /// 自定义账号路由明确不存在时才回退一次;调用方继续解释最后一次响应 - pub(super) async fn send_account_request( + pub(in crate::transport) async fn send_account_request( &self, request: reqwest::RequestBuilder, fallback: reqwest::RequestBuilder, @@ -891,7 +900,7 @@ impl CodexBackendClient { } else { client .egress_key - .push_str(&crate::credential::oauth_identity_key(account)); + .push_str(&crate::request_identity::oauth_identity_key(account)); } client.websocket_origin_key = format!( "{}:{}", @@ -909,26 +918,26 @@ impl CodexBackendClient { /// 已完成账号级 opening 准备、但尚未发送 payload 的 transport pub(crate) struct PreparedResponseTransport { - pub(super) requirement: TransportRequirement, - pub(super) route: PreparedResponseRoute, - pub(super) metrics: CodexTransportMetrics, + pub(in crate::transport) requirement: TransportRequirement, + pub(in crate::transport) route: PreparedResponseRoute, + pub(in crate::transport) metrics: CodexTransportMetrics, } -pub(super) enum PreparedResponseRoute { +pub(in crate::transport) enum PreparedResponseRoute { Http, WebSocket(Box), } -pub(super) struct PreparedWebSocketRoute { - pub(super) request: CodexWebSocketRequest, - pub(super) prepared: PreparedWebSocket, +pub(in crate::transport) struct PreparedWebSocketRoute { + pub(in crate::transport) request: CodexWebSocketRequest, + pub(in crate::transport) prepared: PreparedWebSocket, } // --------------------------------------------------------------------------- // 响应辅助函数 // --------------------------------------------------------------------------- -pub(super) fn log_websocket_pool_decision( +pub(in crate::transport) fn log_websocket_pool_decision( context: CodexRequestContext<'_>, pool_account_id: Option<&str>, pool_context: Option<&WebSocketPoolLogContext>, @@ -953,13 +962,13 @@ pub(super) fn log_websocket_pool_decision( } #[derive(Debug, Clone)] -pub(super) struct WebSocketPoolLogContext { +pub(in crate::transport) struct WebSocketPoolLogContext { conversation_id_hash: String, pool_key_hash: String, } impl WebSocketPoolLogContext { - pub(super) fn from_key(key: &CodexWebSocketPoolKey) -> Self { + pub(in crate::transport) fn from_key(key: &CodexWebSocketPoolKey) -> Self { Self { conversation_id_hash: key.conversation_id_hash(), pool_key_hash: key.stable_hash(), @@ -967,7 +976,10 @@ impl WebSocketPoolLogContext { } } -pub(super) fn retry_after_seconds(headers: &HeaderMap, body: Option<&str>) -> Option { +pub(in crate::transport) fn retry_after_seconds( + headers: &HeaderMap, + body: Option<&str>, +) -> Option { headers .get(RETRY_AFTER) .and_then(|value| value.to_str().ok()) @@ -975,26 +987,26 @@ pub(super) fn retry_after_seconds(headers: &HeaderMap, body: Option<&str>) -> Op .or_else(|| body.and_then(retry_after_seconds_from_body)) } -pub(super) fn truncate_for_error(body: &str) -> String { +pub(in crate::transport) fn truncate_for_error(body: &str) -> String { body.chars().take(200).collect() } -pub(super) struct CappedResponseBody { +pub(in crate::transport) struct CappedResponseBody { bytes: Vec, limit_exceeded: bool, } impl CappedResponseBody { - pub(super) const fn limit_exceeded(&self) -> bool { + pub(in crate::transport) const fn limit_exceeded(&self) -> bool { self.limit_exceeded } - pub(super) fn into_string(self) -> String { + pub(in crate::transport) fn into_string(self) -> String { String::from_utf8_lossy_owned(self.bytes) } } -pub(super) async fn read_capped_response_body( +pub(in crate::transport) async fn read_capped_response_body( response: ReqwestResponse, max_bytes: usize, ) -> Result { @@ -1032,29 +1044,29 @@ pub(super) async fn read_capped_response_body( }) } -pub(super) async fn read_error_response_body( +pub(in crate::transport) async fn read_error_response_body( response: ReqwestResponse, ) -> Result { response.bytes().await } /// JSON 与 Live 的非成功响应保留同一份原始正文、诊断和账号侧观测 -pub(super) async fn http_json_upstream_error( +pub(in crate::transport) async fn http_json_upstream_error( response: ReqwestResponse, trace: &gateway_core::diagnostics::TraceContext, transport_metrics: CodexTransportMetrics, ) -> CodexClientError { let status = response.status(); let headers = response.headers(); - let diagnostics = super::response_meta::diagnostics(Some(status.as_u16()), headers) + let diagnostics = super::super::response_meta::diagnostics(Some(status.as_u16()), headers) .with_response_origin(Some(response.url().clone())); - let set_cookie_headers = super::response_meta::set_cookie_headers(headers); - let rate_limit_headers = super::response_meta::rate_limit_headers(headers); + let set_cookie_headers = super::super::response_meta::set_cookie_headers(headers); + let rate_limit_headers = super::super::response_meta::rate_limit_headers(headers); let retry_after_seconds = retry_after_seconds(headers, None); let content_type = headers .get(reqwest::header::CONTENT_TYPE) .map(|value| value.as_bytes().to_vec()); - let client_headers = super::response_meta::client_headers(headers); + let client_headers = super::super::response_meta::client_headers(headers); let raw_body = match read_error_response_body(response).await { Ok(body) => body, Err(source) => { @@ -1091,7 +1103,7 @@ pub(super) async fn http_json_upstream_error( // 请求辅助函数 // --------------------------------------------------------------------------- -pub(super) fn websocket_upstream_request( +pub(in crate::transport) fn websocket_upstream_request( request: &CodexResponsesRequest, start_ms: &str, ) -> CodexResponsesRequest { @@ -1136,14 +1148,16 @@ fn project_websocket_client_metadata(request: &mut CodexResponsesRequest, start_ request.set_client_metadata(Some(Value::Object(metadata))); } -pub(super) fn now_unix_timestamp_millis() -> u128 { +pub(in crate::transport) fn now_unix_timestamp_millis() -> u128 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|duration| duration.as_millis()) .unwrap_or_default() } -pub(super) fn openai_subagent_from_metadata(client_metadata: Option<&Value>) -> Option { +pub(in crate::transport) fn openai_subagent_from_metadata( + client_metadata: Option<&Value>, +) -> Option { Some( client_metadata? .as_object()? @@ -1157,7 +1171,7 @@ pub(super) fn openai_subagent_from_metadata(client_metadata: Option<&Value>) -> // 错误转换辅助函数 // --------------------------------------------------------------------------- -pub(super) fn websocket_exchange_error_to_client_error( +pub(in crate::transport) fn websocket_exchange_error_to_client_error( error: CodexWebSocketExchangeError, ) -> CodexClientError { match error { @@ -1181,7 +1195,7 @@ pub(super) fn websocket_exchange_error_to_client_error( } } -pub(super) fn websocket_success_decision( +pub(in crate::transport) fn websocket_success_decision( requirement: TransportRequirement, prepared: &PreparedWebSocket, ) -> CodexTransportDecision { @@ -1195,7 +1209,7 @@ pub(super) fn websocket_success_decision( } } -pub(super) fn local_http_fallback_decision( +pub(in crate::transport) fn local_http_fallback_decision( error: &CodexWebSocketExchangeError, ) -> Option { if crate::transport::connection::is_admission_failure(error) { @@ -1213,7 +1227,7 @@ pub(super) fn local_http_fallback_decision( } } -pub(super) fn merge_preparation_metrics( +pub(in crate::transport) fn merge_preparation_metrics( response: &mut CodexTransportMetrics, preparation: CodexTransportMetrics, ) { @@ -1222,13 +1236,13 @@ pub(super) fn merge_preparation_metrics( response.transport_decision_wait_ms = preparation.transport_decision_wait_ms; } -pub(super) fn elapsed_duration_millis(duration: Duration) -> i64 { +pub(in crate::transport) fn elapsed_duration_millis(duration: Duration) -> i64 { i64::try_from(duration.as_millis()) .unwrap_or(i64::MAX) .max(1) } -pub(super) fn http_version_name(version: reqwest::Version) -> &'static str { +pub(in crate::transport) fn http_version_name(version: reqwest::Version) -> &'static str { match version { reqwest::Version::HTTP_09 => "HTTP/0.9", reqwest::Version::HTTP_10 => "HTTP/1.0", @@ -1239,7 +1253,7 @@ pub(super) fn http_version_name(version: reqwest::Version) -> &'static str { } } -pub(super) fn websocket_origin_key(base_url: &str) -> String { +pub(in crate::transport) fn websocket_origin_key(base_url: &str) -> String { let origin = reqwest::Url::parse(base_url) .ok() .and_then(|url| { diff --git a/backend/crates/providers/openai/src/transport/client_catalog.rs b/backend/crates/providers/openai/src/transport/client/catalog.rs similarity index 83% rename from backend/crates/providers/openai/src/transport/client_catalog.rs rename to backend/crates/providers/openai/src/transport/client/catalog.rs index cd11fd620..5a681aa9e 100644 --- a/backend/crates/providers/openai/src/transport/client_catalog.rs +++ b/backend/crates/providers/openai/src/transport/client/catalog.rs @@ -1,16 +1,17 @@ //! 上游模型目录读取;Codex 版本协商与 Messages 分页各自遵循原生合同 +use crate::profile::CodexWireProfile; use gateway_protocol::openai::events::retry_after_seconds_from_body; -use super::{ +use super::backend::{ + CodexBackendClient, CodexBackendTransport, CodexClientError, CodexClientResult, + CodexRequestContext, OpenAiUpstreamProtocol, retry_after_seconds, +}; + +use super::super::{ catalog::{CodexModelCatalogSnapshot, catalog_etag, parse_codex_model_catalog}, - client::{ - CodexBackendClient, CodexBackendTransport, CodexClientError, CodexClientResult, - CodexRequestContext, OpenAiUpstreamProtocol, retry_after_seconds, - }, diagnostics::CodexUpstreamSendPhase, endpoints::endpoint_url, - profile::CodexWireProfile, response_meta, }; @@ -41,25 +42,27 @@ impl CodexBackendClient { }; match self.protocol { OpenAiUpstreamProtocol::Codex => Ok(parse_codex_model_catalog(&body, etag.as_deref())?), - OpenAiUpstreamProtocol::ResponsesApi => Ok(super::catalog::parse_api_model_catalog( - &body, - etag.as_deref(), - self.protocol, - )?), + OpenAiUpstreamProtocol::ResponsesApi => { + Ok(super::super::catalog::parse_api_model_catalog( + &body, + etag.as_deref(), + self.protocol, + )?) + } OpenAiUpstreamProtocol::MessagesApi => { let mut page = body; let mut models = Vec::new(); let mut cursors = std::collections::BTreeSet::new(); loop { let mut value: serde_json::Value = serde_json::from_slice(&page) - .map_err(|_| super::CodexModelCatalogError::InvalidWire)?; + .map_err(|_| super::super::CodexModelCatalogError::InvalidWire)?; let data = value .get_mut("data") .and_then(serde_json::Value::as_array_mut) - .ok_or(super::CodexModelCatalogError::InvalidWire)?; + .ok_or(super::super::CodexModelCatalogError::InvalidWire)?; models.append(data); - if models.len() > super::catalog::MAX_CATALOG_MODELS { - return Err(super::CodexModelCatalogError::TooManyModels.into()); + if models.len() > super::super::catalog::MAX_CATALOG_MODELS { + return Err(super::super::CodexModelCatalogError::TooManyModels.into()); } if value.get("has_more").and_then(serde_json::Value::as_bool) != Some(true) { break; @@ -68,17 +71,17 @@ impl CodexBackendClient { .get("last_id") .and_then(serde_json::Value::as_str) .filter(|value| !value.is_empty()) - .ok_or(super::CodexModelCatalogError::InvalidWire)?; + .ok_or(super::super::CodexModelCatalogError::InvalidWire)?; if !cursors.insert(cursor.to_owned()) { - return Err(super::CodexModelCatalogError::InvalidWire.into()); + return Err(super::super::CodexModelCatalogError::InvalidWire.into()); } (page, _) = self .fetch_models_page(context, &profile, &[query, ("after_id", cursor)]) .await?; } let body = serde_json::to_vec(&serde_json::json!({"data":models})) - .map_err(|_| super::CodexModelCatalogError::InvalidWire)?; - Ok(super::catalog::parse_api_model_catalog( + .map_err(|_| super::super::CodexModelCatalogError::InvalidWire)?; + Ok(super::super::catalog::parse_api_model_catalog( &body, etag.as_deref(), self.protocol, diff --git a/backend/crates/providers/openai/src/transport/client_json.rs b/backend/crates/providers/openai/src/transport/client/json.rs similarity index 87% rename from backend/crates/providers/openai/src/transport/client_json.rs rename to backend/crates/providers/openai/src/transport/client/json.rs index c47d6a078..c3c755195 100644 --- a/backend/crates/providers/openai/src/transport/client_json.rs +++ b/backend/crates/providers/openai/src/transport/client/json.rs @@ -5,11 +5,12 @@ use std::time::Instant; use bytes::Bytes; use reqwest::header::{CONTENT_TYPE, HeaderValue}; -use super::{ - client::{ - CodexBackendClient, CodexBackendJsonResponse, CodexClientError, CodexClientResult, - CodexRequestContext, CodexTransportMetrics, elapsed_duration_millis, http_version_name, - }, +use super::backend::{ + CodexBackendClient, CodexBackendJsonResponse, CodexClientError, CodexClientResult, + CodexRequestContext, CodexTransportMetrics, elapsed_duration_millis, http_version_name, +}; + +use super::super::{ endpoints::endpoint_url, headers::{insert_optional_header, insert_optional_protocol_header}, response_meta, @@ -25,13 +26,13 @@ impl CodexBackendClient { image_turn_id: Option<&str>, context: CodexRequestContext<'_>, ) -> CodexClientResult { - let body = if endpoint_path == super::endpoints::CODEX_ALPHA_SEARCH_PATH { - super::correlation::scope_search_body(body, context.installation_id) + let body = if endpoint_path == super::super::endpoints::CODEX_ALPHA_SEARCH_PATH { + super::super::correlation::scope_search_body(body, context.installation_id) } else { body }; // Provider 端点以 Codex 路径标识;API Key 在自己的 API 前缀下使用对应相对路径 - let endpoint_path = if self.protocol == super::client::OpenAiUpstreamProtocol::ResponsesApi + let endpoint_path = if self.protocol == super::backend::OpenAiUpstreamProtocol::ResponsesApi { endpoint_path .strip_prefix("/codex") @@ -46,7 +47,7 @@ impl CodexBackendClient { "x-codex-installation-id", context.installation_id, )?; - super::headers::append_passthrough_headers(&mut headers, passthrough_headers); + super::super::headers::append_passthrough_headers(&mut headers, passthrough_headers); // 独立端点没有 Responses 原连接归属,续接状态不能跨账号继承 // turn metadata 随后仅使用当前 lease 已处理的值 headers.remove("x-codex-turn-state"); @@ -59,7 +60,7 @@ impl CodexBackendClient { context.turn_metadata, ); self.append_middleware_headers(&mut headers)?; - super::correlation::scope_headers(&mut headers, context.installation_id); + super::super::correlation::scope_headers(&mut headers, context.installation_id); let body = if self.privacy.is_some() { let mut value: serde_json::Value = serde_json::from_slice(&body).map_err(CodexClientError::RequestBodyEncode)?; @@ -126,7 +127,7 @@ impl CodexBackendClient { }; if !status.is_success() { - return Err(super::client::http_json_upstream_error( + return Err(super::backend::http_json_upstream_error( response, &trace, transport_metrics, diff --git a/backend/crates/providers/openai/src/transport/client_live.rs b/backend/crates/providers/openai/src/transport/client/live.rs similarity index 94% rename from backend/crates/providers/openai/src/transport/client_live.rs rename to backend/crates/providers/openai/src/transport/client/live.rs index 4ba48427a..936b66e95 100644 --- a/backend/crates/providers/openai/src/transport/client_live.rs +++ b/backend/crates/providers/openai/src/transport/client/live.rs @@ -12,11 +12,12 @@ use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; use crate::compat::is_non_codex_request_header; -use super::{ - client::{ - CodexBackendClient, CodexClientError, CodexClientResult, CodexRequestContext, - CodexTransportMetrics, elapsed_duration_millis, http_version_name, retry_after_seconds, - }, +use super::backend::{ + CodexBackendClient, CodexClientError, CodexClientResult, CodexRequestContext, + CodexTransportMetrics, elapsed_duration_millis, http_version_name, retry_after_seconds, +}; + +use super::super::{ diagnostics::CodexUpstreamDiagnostics, endpoints::endpoint_url, headers::{insert_optional_header, is_managed_model_header}, @@ -54,10 +55,10 @@ impl CodexBackendClient { .installation_id .zip(std::str::from_utf8(header.value()).ok()) .and_then(|(installation_id, raw)| { - super::request::scope_turn_metadata( + super::super::request::scope_turn_metadata( raw, installation_id, - super::request::RequestAccountScope::Different, + super::super::request::RequestAccountScope::Different, ) }) else { @@ -76,7 +77,7 @@ impl CodexBackendClient { ); } self.append_middleware_headers(&mut headers)?; - super::correlation::scope_headers(&mut headers, context.installation_id); + super::super::correlation::scope_headers(&mut headers, context.installation_id); Ok(headers) } @@ -176,7 +177,7 @@ impl CodexBackendClient { }; if !status.is_success() { - return Err(super::client::http_json_upstream_error( + return Err(super::backend::http_json_upstream_error( response, &trace, transport_metrics, diff --git a/backend/crates/providers/openai/src/transport/client_messages.rs b/backend/crates/providers/openai/src/transport/client/messages.rs similarity index 91% rename from backend/crates/providers/openai/src/transport/client_messages.rs rename to backend/crates/providers/openai/src/transport/client/messages.rs index 677773d69..e7cfd2587 100644 --- a/backend/crates/providers/openai/src/transport/client_messages.rs +++ b/backend/crates/providers/openai/src/transport/client/messages.rs @@ -6,10 +6,11 @@ use bytes::Bytes; use futures::StreamExt; use reqwest::header::{ACCEPT, CONTENT_TYPE, HeaderMap, HeaderValue}; -use super::{ +use super::backend::{elapsed_duration_millis, http_json_upstream_error, http_version_name}; + +use super::super::{ CodexBackendClient, CodexBackendSseStream, CodexClientError, CodexClientResult, CodexRequestContext, CodexTransportMetrics, CodexUpstreamDiagnostics, - client::{elapsed_duration_millis, http_json_upstream_error, http_version_name}, response_meta::{self, CodexResponseMetadata}, }; @@ -30,7 +31,7 @@ impl CodexBackendClient { context: CodexRequestContext<'_>, ) -> CodexClientResult { let mut headers = self.model_request_headers(&self.profile.snapshot(), context)?; - super::headers::append_passthrough_headers(&mut headers, passthrough_headers); + super::super::headers::append_passthrough_headers(&mut headers, passthrough_headers); headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); headers.insert( ACCEPT, @@ -51,7 +52,11 @@ impl CodexBackendClient { .unwrap_or_default() .exchange("messages_http"); let request = self - .prepare_http_request(super::endpoint_url(&self.base_url, endpoint), headers, body) + .prepare_http_request( + super::super::endpoint_url(&self.base_url, endpoint), + headers, + body, + ) .await?; trace.headers( "upstream.request.headers", diff --git a/backend/crates/providers/openai/src/transport/client/mod.rs b/backend/crates/providers/openai/src/transport/client/mod.rs new file mode 100644 index 000000000..1e3a1aae3 --- /dev/null +++ b/backend/crates/providers/openai/src/transport/client/mod.rs @@ -0,0 +1,21 @@ +//! Codex 上游客户端的模块门面 + +mod backend; +mod catalog; +mod json; +mod live; +mod messages; +mod stream; + +pub use backend::{ + CodexAccountSelectionTelemetry, CodexBackendClient, CodexBackendJsonResponse, + CodexBackendSseStream, CodexBackendStreamingResponse, CodexBackendTransport, CodexClientError, + CodexClientResult, CodexClientVisibleUpstreamResponse, CodexRateLimitUpdates, + CodexRequestContext, CodexResponseMetadataUpdates, CodexTransportDecision, + CodexTransportMetrics, build_account_http_client, build_reqwest_client, +}; +pub(super) use backend::{ + OpenAiUpstreamProtocol, openai_subagent_from_metadata, read_capped_response_body, + retry_after_seconds, truncate_for_error, +}; +pub use live::CodexLiveCallResponse; diff --git a/backend/crates/providers/openai/src/transport/client_stream.rs b/backend/crates/providers/openai/src/transport/client/stream.rs similarity index 97% rename from backend/crates/providers/openai/src/transport/client_stream.rs rename to backend/crates/providers/openai/src/transport/client/stream.rs index e999376e6..4621eb0b0 100644 --- a/backend/crates/providers/openai/src/transport/client_stream.rs +++ b/backend/crates/providers/openai/src/transport/client/stream.rs @@ -44,7 +44,18 @@ use crate::transport::{ }, }; -use super::client::*; +use super::backend::{ + CodexBackendClient, CodexBackendSseStream, CodexBackendStreamingResponse, + CodexBackendTransport, CodexClientError, CodexClientResult, CodexClientVisibleUpstreamResponse, + CodexRateLimitUpdates, CodexRequestContext, CodexTransportDecision, CodexTransportMetrics, + OpenAiUpstreamProtocol, PreparedResponseRoute, PreparedResponseTransport, + PreparedWebSocketRoute, UPSTREAM_STREAM_IDLE_TIMEOUT, WebSocketPoolLogContext, + X_CODEX_WS_STREAM_REQUEST_START_MS_CLIENT_METADATA_KEY, elapsed_duration_millis, + http_version_name, local_http_fallback_decision, log_websocket_pool_decision, + merge_preparation_metrics, now_unix_timestamp_millis, read_error_response_body, + retry_after_seconds, websocket_exchange_error_to_client_error, websocket_origin_key, + websocket_success_decision, websocket_upstream_request, +}; impl CodexBackendClient { /// 发送 Responses SSE 请求并返回 live SSE 流(HTTP SSE fallback) @@ -84,7 +95,7 @@ impl CodexBackendClient { headers.insert(CONTENT_ENCODING, HeaderValue::from_static("zstd")); } profile.apply_context_versions(&mut upstream_body); - super::correlation::scope_request( + super::super::correlation::scope_request( &mut upstream_body, &mut headers, context.installation_id, @@ -101,7 +112,7 @@ impl CodexBackendClient { .unwrap_or_default() .exchange("http_sse"); if let Some(body) = upstream_body.as_object() { - super::diagnostics::evidence::record_request( + super::super::diagnostics::evidence::record_request( &trace, if self.outbound_middleware.is_some() { "provider.request.native" @@ -283,7 +294,7 @@ impl CodexBackendClient { } let mut body = serde_json::Value::Object(std::mem::take(websocket_request.body_mut())); profile.apply_context_versions(&mut body); - super::correlation::scope_request( + super::super::correlation::scope_request( &mut body, &mut headers, context.installation_id, @@ -305,7 +316,7 @@ impl CodexBackendClient { *websocket_request.body_mut() = body; let trace = context.trace.cloned().unwrap_or_default(); let record_body = |stage, request: &CodexResponsesRequest| { - super::diagnostics::evidence::record_request( + super::super::diagnostics::evidence::record_request( &trace, stage, request.body(), diff --git a/backend/crates/providers/openai/src/transport/correlation.rs b/backend/crates/providers/openai/src/transport/correlation.rs index 18b132194..6cb33861b 100644 --- a/backend/crates/providers/openai/src/transport/correlation.rs +++ b/backend/crates/providers/openai/src/transport/correlation.rs @@ -5,8 +5,8 @@ use reqwest::header::{HeaderMap, HeaderValue}; use serde_json::{Map, Value}; use sha2::{Digest, Sha256}; -use super::automatic_context::{locate_contexts, rewrite_git_context}; use super::request::serialize_ascii_turn_metadata; +use crate::automatic_context::{locate_contexts, rewrite_git_context}; // 轮次及父子轮次引用保留客户端原值,避免改变官方轮次身份与 UUIDv7 语义 const ID_FIELDS: &[&str] = &[ diff --git a/backend/crates/providers/openai/src/transport/headers.rs b/backend/crates/providers/openai/src/transport/headers.rs index f3b47ca7e..9cebddc09 100644 --- a/backend/crates/providers/openai/src/transport/headers.rs +++ b/backend/crates/providers/openai/src/transport/headers.rs @@ -11,8 +11,8 @@ use super::client::{ CodexBackendClient, CodexClientResult, CodexRequestContext, OpenAiUpstreamProtocol, openai_subagent_from_metadata, }; -use super::profile::CodexWireProfile; use super::protocol::responses::CodexResponsesRequest; +use crate::profile::CodexWireProfile; /// 不透传下游携带的认证、账号及相关身份字段,避免影响网关选定的上游身份 /// 上游需要的官方身份头由网关构造;这里也包含通用认证和 Cookie 字段 diff --git a/backend/crates/providers/openai/src/transport/mod.rs b/backend/crates/providers/openai/src/transport/mod.rs index f73617f66..4978a6d7a 100644 --- a/backend/crates/providers/openai/src/transport/mod.rs +++ b/backend/crates/providers/openai/src/transport/mod.rs @@ -1,21 +1,14 @@ //! Codex HTTP/SSE/WebSocket 上游 transport -mod automatic_context; pub mod canonical; pub mod catalog; pub mod client; -mod client_catalog; -mod client_json; -mod client_live; -mod client_messages; -mod client_stream; pub(crate) mod connection; mod correlation; pub mod diagnostics; pub mod endpoints; pub mod headers; mod outbound; -pub mod profile; pub mod profile_avatar; pub mod profile_statistics; pub mod protocol; @@ -37,6 +30,7 @@ pub use self::{ CodexCatalogMetadata, CodexCatalogModel, CodexCatalogVisibility, CodexModelCatalogError, CodexModelCatalogSnapshot, parse_codex_model_catalog, }, + client::CodexLiveCallResponse, client::{ CodexAccountSelectionTelemetry, CodexBackendClient, CodexBackendJsonResponse, CodexBackendSseStream, CodexBackendStreamingResponse, CodexBackendTransport, @@ -44,7 +38,6 @@ pub use self::{ CodexResponseMetadataUpdates, CodexTransportDecision, CodexTransportMetrics, build_reqwest_client, }, - client_live::CodexLiveCallResponse, diagnostics::{CodexUpstreamDiagnostics, CodexUpstreamSendPhase}, endpoints::{ CODEX_ALPHA_SEARCH_PATH, CODEX_IMAGE_EDITS_PATH, CODEX_IMAGE_GENERATIONS_PATH, @@ -68,10 +61,7 @@ pub use self::{ CodexRateLimitResetCreditsConsumeResult, MAX_CODEX_RESET_CREDITS_BODY_BYTES, }, response_meta::CodexResponseMetadata, - usage::{ - MAX_CODEX_USAGE_BODY_BYTES, OpenAiBillingUsage, openai_billing_breakdown, - openai_billing_breakdown_with_override, - }, + usage::MAX_CODEX_USAGE_BODY_BYTES, websocket::{ CodexWebSocketPool, CodexWebSocketPoolConfig, CodexWebSocketPoolKey, WebSocketPoolDecision, }, diff --git a/backend/crates/providers/openai/src/transport/privacy/carrier.rs b/backend/crates/providers/openai/src/transport/privacy/carrier.rs index 3b1e43968..ac0f4f3ec 100644 --- a/backend/crates/providers/openai/src/transport/privacy/carrier.rs +++ b/backend/crates/providers/openai/src/transport/privacy/carrier.rs @@ -5,9 +5,7 @@ use reqwest::header::{HeaderMap, HeaderValue}; use serde_json::Value; use super::{Budget, changes::BodyChanges, rule::CompiledStep}; -use crate::transport::automatic_context::{ - ContextTarget, locate_contexts, parse_xml, rewrite_git_context, -}; +use crate::automatic_context::{ContextTarget, locate_contexts, parse_xml, rewrite_git_context}; const METADATA_KEYS: &[&str] = &["turnMetadata", "turn_metadata", "x-codex-turn-metadata"]; diff --git a/backend/crates/providers/openai/src/transport/profile_avatar.rs b/backend/crates/providers/openai/src/transport/profile_avatar.rs index ca7bf3c54..f4c08b8b2 100644 --- a/backend/crates/providers/openai/src/transport/profile_avatar.rs +++ b/backend/crates/providers/openai/src/transport/profile_avatar.rs @@ -1,5 +1,6 @@ //! Codex 官方个人资料头像的固定来源流式 transport +use crate::profile::CodexWireProfile; use std::{pin::Pin, time::Duration}; use async_stream::try_stream; @@ -12,9 +13,7 @@ use reqwest::{ use tokio::time::timeout; use super::endpoints::endpoint_url; -use super::{ - CodexRequestContext, headers::build_codex_download_headers, profile::CodexWireProfile, -}; +use super::{CodexRequestContext, headers::build_codex_download_headers}; const OFFICIAL_AVATAR_ORIGIN: &str = "https://chatgpt.com"; const OFFICIAL_AVATAR_PATH_PREFIX: &str = "/backend-api/estuary/public_content/enc/"; diff --git a/backend/crates/providers/openai/src/transport/request.rs b/backend/crates/providers/openai/src/transport/request.rs index 2be2d0416..ab86123b3 100644 --- a/backend/crates/providers/openai/src/transport/request.rs +++ b/backend/crates/providers/openai/src/transport/request.rs @@ -15,8 +15,8 @@ use serde_json::{Map, Value, json}; use sha2::{Digest, Sha256}; use crate::compat::{is_non_codex_request_header, normalize_codex_request_body}; +use crate::profile::CodexRequestLocation; use crate::transport::headers::is_managed_identity_header; -use crate::transport::profile::CodexRequestLocation; use crate::transport::protocol::responses::{ CodexResponsesRequest, X_CODEX_TURN_STATE_CLIENT_METADATA_KEY, }; diff --git a/backend/crates/providers/openai/src/transport/usage.rs b/backend/crates/providers/openai/src/transport/usage.rs index 1aca5fb74..a08008a18 100644 --- a/backend/crates/providers/openai/src/transport/usage.rs +++ b/backend/crates/providers/openai/src/transport/usage.rs @@ -1,10 +1,6 @@ -//! OpenAI 用量解析、模型价格匹配与费用明细计算 +//! Codex 账号 usage 查询、响应体限制与错误处理 -use gateway_core::metering::{ - CalculatedCost, CalculatedCostAmounts, CalculatedCostBreakdown, CalculatedCostRates, - CurrencyCode, Decimal, Money, -}; -use gateway_protocol::openai::events::{TokenUsage, retry_after_seconds_from_body}; +use gateway_protocol::openai::events::retry_after_seconds_from_body; use reqwest::StatusCode; use serde_json::Value; @@ -15,1109 +11,6 @@ use super::{ response_meta, }; -const LONG_CONTEXT_THRESHOLD: u64 = 272_000; -const WEB_SEARCH_CALL_TICKS: u128 = 100_000_000; -const WEB_SEARCH_PREVIEW_NON_REASONING_CALL_TICKS: u128 = 250_000_000; -const FILE_SEARCH_CALL_TICKS: u128 = 25_000_000; - -/// OpenAI 公开 Token 价格计算所需的单次用量事实 -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct OpenAiBillingUsage { - input_tokens: u64, - output_tokens: u64, - cached_input_tokens: u64, - cache_write_input_tokens: u64, - image_input_tokens: u64, - image_output_tokens: u64, - web_search_calls: u64, - file_search_calls: u64, - web_search_pricing: Option, -} - -impl OpenAiBillingUsage { - /// 构造不含托管工具费用的 Token 用量 - #[must_use] - pub const fn new( - input_tokens: u64, - output_tokens: u64, - cached_input_tokens: u64, - cache_write_input_tokens: u64, - ) -> Self { - Self { - input_tokens, - output_tokens, - cached_input_tokens, - cache_write_input_tokens, - image_input_tokens: 0, - image_output_tokens: 0, - web_search_calls: 0, - file_search_calls: 0, - web_search_pricing: None, - } - } - - pub(crate) const fn with_web_search_calls( - mut self, - calls: u64, - pricing: Option, - ) -> Self { - self.web_search_calls = calls; - self.web_search_pricing = pricing; - self - } - - pub(crate) const fn with_file_search_calls(mut self, calls: u64) -> Self { - self.file_search_calls = calls; - self - } -} - -impl From for OpenAiBillingUsage { - fn from(usage: TokenUsage) -> Self { - Self { - input_tokens: usage.input_tokens, - output_tokens: usage.output_tokens, - cached_input_tokens: usage.cached_input_tokens, - cache_write_input_tokens: usage.cache_write_input_tokens, - image_input_tokens: usage.image_input_tokens, - image_output_tokens: usage.image_output_tokens, - web_search_calls: 0, - file_search_calls: 0, - web_search_pricing: None, - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum WebSearchPricing { - Standard, - PreviewNonReasoning, -} - -impl WebSearchPricing { - const fn price_per_call_ticks(self) -> u128 { - match self { - Self::Standard => WEB_SEARCH_CALL_TICKS, - Self::PreviewNonReasoning => WEB_SEARCH_PREVIEW_NON_REASONING_CALL_TICKS, - } - } -} - -#[derive(Clone, Copy)] -struct TokenRates { - explicit_cache: bool, - cache_write_ticks: Option, - input_ticks: u128, - output_ticks: u128, - cache_read_ticks: u128, -} - -impl TokenRates { - const ZERO: Self = Self::new(0, 0, 0); - - /// 参数单位为 USD / 1M Token 的万分之一,数值也恰好等于单 Token 的 USD ticks - const fn new(input_ticks: u128, output_ticks: u128, cache_read_ticks: u128) -> Self { - Self { - input_ticks, - output_ticks, - cache_read_ticks, - explicit_cache: false, - cache_write_ticks: None, - } - } - - const fn is_configured(self) -> bool { - self.explicit_cache - || self.input_ticks > 0 - || self.output_ticks > 0 - || self.cache_read_ticks > 0 - } -} - -#[derive(Clone, Copy)] -struct ModelPricing { - standard: TokenRates, - flex: TokenRates, - fast: TokenRates, - ultrafast: TokenRates, - long_standard: TokenRates, - long_flex: TokenRates, - long_fast: TokenRates, - long_ultrafast: TokenRates, - cache_write_percent: u32, - unpriced_long_context: bool, -} - -impl ModelPricing { - const fn new(input: u128, output: u128, cache_read: u128) -> Self { - Self { - standard: TokenRates::new(input, output, cache_read), - flex: TokenRates::ZERO, - fast: TokenRates::ZERO, - ultrafast: TokenRates::ZERO, - long_standard: TokenRates::ZERO, - long_flex: TokenRates::ZERO, - long_fast: TokenRates::ZERO, - long_ultrafast: TokenRates::ZERO, - cache_write_percent: 0, - unpriced_long_context: false, - } - } - - const fn with_flex(mut self, input: u128, output: u128, cache_read: u128) -> Self { - self.flex = TokenRates::new(input, output, cache_read); - self - } - - const fn with_fast(mut self, input: u128, output: u128, cache_read: u128) -> Self { - self.fast = TokenRates::new(input, output, cache_read); - self - } - - const fn with_ultrafast(mut self, input: u128, output: u128, cache_read: u128) -> Self { - self.ultrafast = TokenRates::new(input, output, cache_read); - self - } - - const fn with_long(mut self, input: u128, output: u128, cache_read: u128) -> Self { - self.long_standard = TokenRates::new(input, output, cache_read); - self - } - - const fn with_long_flex(mut self, input: u128, output: u128, cache_read: u128) -> Self { - self.long_flex = TokenRates::new(input, output, cache_read); - self - } - - const fn with_long_fast(mut self, input: u128, output: u128, cache_read: u128) -> Self { - self.long_fast = TokenRates::new(input, output, cache_read); - self - } - - const fn with_long_ultrafast(mut self, input: u128, output: u128, cache_read: u128) -> Self { - self.long_ultrafast = TokenRates::new(input, output, cache_read); - self - } - - const fn with_cache_write(mut self, percent: u32) -> Self { - self.cache_write_percent = percent; - self - } - - const fn with_unpriced_long_context(mut self) -> Self { - self.unpriced_long_context = true; - self - } - - fn rates(self, tier: PricingTier, long_context: bool) -> Option { - if long_context && self.unpriced_long_context { - return None; - } - // 只有公布长上下文价格的模型才在阈值处切换费率 - // 若短上下文价格覆盖全部支持范围,长上下文栏的横线不代表额外的不可用档位 - let uses_long_rates = long_context && self.long_standard.is_configured(); - let rates = match (tier, uses_long_rates) { - (PricingTier::Standard, false) => self.standard, - (PricingTier::Flex, false) => self.flex, - (PricingTier::Fast, false) => self.fast, - (PricingTier::Ultrafast, false) => self.ultrafast, - (PricingTier::Standard, true) => self.long_standard, - (PricingTier::Flex, true) => self.long_flex, - (PricingTier::Fast, true) => self.long_fast, - (PricingTier::Ultrafast, true) => self.long_ultrafast, - }; - rates.is_configured().then_some(rates) - } -} - -#[derive(Clone, Copy)] -enum PricingTier { - Standard, - Flex, - Fast, - Ultrafast, -} - -#[derive(Clone, Copy)] -struct PricingRule { - model: &'static str, - pricing: ModelPricing, -} - -// 价格来源:https://developers.openai.com/api/docs/pricing -// 只登记已核验的常规价格及服务档位;临时优惠不写入内置价目 -// 原有规则于 2026-09-09 核验,GPT-6.1 Sol 于 2026-09-29 核验,其余新增型号见对应条目 -// Astra 与 GPT-6.1 Sol 的 Ultrafast 档位于 2026-10-12 对照官方价目表核验 -// 已按 https://developers.openai.com/api/docs/deprecations 核验至 2026-09-13, -// 移除已关闭的型号;仅宣布弃用但尚未到关闭日期的型号继续保留 -const PRICING_RULES: &[PricingRule] = &[ - // GPT-6.2 的 Ultrafast 使用官方价目表中的 6 倍常规价,核验日期 2026-11-18 - PricingRule { - model: "gpt-6.2-astra", - pricing: ModelPricing::new(80_000, 400_000, 4_000) - .with_cache_write(125) - .with_fast(160_000, 800_000, 8_000) - .with_ultrafast(480_000, 2_400_000, 24_000) - .with_long(160_000, 600_000, 8_000) - .with_long_fast(320_000, 1_200_000, 16_000) - .with_long_ultrafast(960_000, 3_600_000, 48_000), - }, - PricingRule { - model: "gpt-6.2-sol", - pricing: ModelPricing::new(20_000, 100_000, 1_000) - .with_cache_write(125) - .with_fast(40_000, 200_000, 2_000) - .with_ultrafast(120_000, 600_000, 6_000) - .with_long(40_000, 150_000, 2_000) - .with_long_fast(80_000, 300_000, 4_000) - .with_long_ultrafast(240_000, 900_000, 12_000), - }, - // Astra:https://developers.openai.com/api/docs/models/gpt-6-astra - // 已于 2026-09-09 对照官方价目表核验 - PricingRule { - model: "gpt-6-astra", - pricing: ModelPricing::new(100_000, 500_000, 10_000) - .with_cache_write(125) - .with_flex(50_000, 250_000, 5_000) - .with_fast(200_000, 1_000_000, 20_000) - .with_ultrafast(600_000, 3_000_000, 60_000) - .with_long(200_000, 750_000, 20_000) - .with_long_flex(100_000, 375_000, 10_000) - .with_long_fast(400_000, 1_500_000, 40_000) - .with_long_ultrafast(1_200_000, 4_500_000, 120_000), - }, - PricingRule { - model: "gpt-6.1-sol", - pricing: ModelPricing::new(20_000, 100_000, 1_000) - .with_cache_write(125) - .with_flex(10_000, 50_000, 500) - .with_fast(40_000, 200_000, 2_000) - .with_ultrafast(120_000, 600_000, 6_000) - .with_long(40_000, 150_000, 2_000) - .with_long_flex(20_000, 75_000, 1_000) - .with_long_fast(80_000, 300_000, 4_000) - .with_long_ultrafast(240_000, 900_000, 12_000), - }, - // https://developers.openai.com/api/docs/models/gpt-6.1-terra,核验日期 2026-10-27 - PricingRule { - model: "gpt-6.1-terra", - pricing: ModelPricing::new(10_000, 50_000, 500) - .with_cache_write(125) - .with_flex(5_000, 25_000, 250) - .with_fast(20_000, 100_000, 1_000) - .with_long(20_000, 75_000, 1_000) - .with_long_flex(10_000, 37_500, 500) - .with_long_fast(40_000, 150_000, 2_000), - }, - // https://developers.openai.com/api/docs/models/gpt-6-sol,核验日期 2026-09-24 - PricingRule { - model: "gpt-6-sol", - pricing: ModelPricing::new(20_000, 100_000, 2_000) - .with_cache_write(125) - .with_flex(10_000, 50_000, 1_000) - .with_fast(40_000, 200_000, 4_000) - .with_long(40_000, 150_000, 4_000) - .with_long_flex(20_000, 75_000, 2_000) - .with_long_fast(80_000, 300_000, 8_000), - }, - // https://developers.openai.com/api/docs/models/gpt-6-luna,核验日期 2026-09-24 - PricingRule { - model: "gpt-6-luna", - pricing: ModelPricing::new(1_000, 5_000, 100) - .with_cache_write(125) - .with_flex(500, 2_500, 50) - .with_fast(2_000, 10_000, 200) - .with_long(2_000, 7_500, 200) - .with_long_flex(1_000, 3_750, 100) - .with_long_fast(4_000, 15_000, 400), - }, - PricingRule { - model: "gpt-5.6-sol", - pricing: ModelPricing::new(50_000, 300_000, 5_000) - .with_cache_write(125) - .with_flex(25_000, 150_000, 2_500) - .with_fast(100_000, 600_000, 10_000) - .with_long(100_000, 450_000, 10_000) - .with_long_flex(50_000, 225_000, 5_000) - .with_long_fast(200_000, 900_000, 20_000), - }, - PricingRule { - model: "gpt-5.6-terra", - pricing: ModelPricing::new(20_000, 120_000, 2_000) - .with_cache_write(125) - .with_flex(10_000, 60_000, 1_000) - .with_fast(40_000, 240_000, 4_000) - .with_long(40_000, 180_000, 4_000) - .with_long_flex(20_000, 90_000, 2_000) - .with_long_fast(80_000, 360_000, 8_000), - }, - PricingRule { - model: "gpt-5.6-luna", - pricing: ModelPricing::new(2_000, 12_000, 200) - .with_cache_write(125) - .with_flex(1_000, 6_000, 100) - .with_fast(4_000, 24_000, 400) - .with_long(4_000, 18_000, 400) - .with_long_flex(2_000, 9_000, 200) - .with_long_fast(8_000, 36_000, 800), - }, - PricingRule { - model: "gpt-5.6", - pricing: ModelPricing::new(50_000, 300_000, 5_000) - .with_cache_write(125) - .with_flex(25_000, 150_000, 2_500) - .with_fast(100_000, 600_000, 10_000) - .with_long(100_000, 450_000, 10_000) - .with_long_flex(50_000, 225_000, 5_000) - .with_long_fast(200_000, 900_000, 20_000), - }, - PricingRule { - model: "gpt-5.5-pro", - pricing: ModelPricing::new(300_000, 1_800_000, 0) - .with_flex(150_000, 900_000, 0) - .with_long(600_000, 2_700_000, 0), - }, - PricingRule { - model: "gpt-5.5", - pricing: ModelPricing::new(50_000, 300_000, 5_000) - .with_flex(25_000, 150_000, 2_500) - .with_fast(125_000, 750_000, 12_500) - .with_long(100_000, 450_000, 10_000) - .with_long_flex(50_000, 225_000, 5_000), - }, - PricingRule { - model: "gpt-5.4-mini", - pricing: ModelPricing::new(7_500, 45_000, 750) - .with_flex(3_750, 22_500, 375) - .with_fast(15_000, 90_000, 1_500), - }, - PricingRule { - model: "gpt-5.4-nano", - pricing: ModelPricing::new(2_000, 12_500, 200).with_flex(1_000, 6_250, 100), - }, - PricingRule { - model: "gpt-5.4-pro", - pricing: ModelPricing::new(300_000, 1_800_000, 0) - .with_flex(150_000, 900_000, 0) - .with_long(600_000, 2_700_000, 0) - .with_long_flex(300_000, 1_350_000, 0), - }, - PricingRule { - model: "gpt-5.4", - pricing: ModelPricing::new(25_000, 150_000, 2_500) - .with_flex(12_500, 75_000, 1_300) - .with_fast(50_000, 300_000, 5_000) - .with_long(50_000, 225_000, 5_000) - .with_long_flex(25_000, 112_500, 2_500), - }, - PricingRule { - model: "gpt-5.3-codex", - pricing: ModelPricing::new(17_500, 140_000, 1_750).with_fast(35_000, 280_000, 3_500), - }, - PricingRule { - model: "gpt-5.2-pro", - pricing: ModelPricing::new(210_000, 1_680_000, 0), - }, - PricingRule { - model: "gpt-5.2", - pricing: ModelPricing::new(17_500, 140_000, 1_750) - .with_flex(8_750, 70_000, 875) - .with_fast(35_000, 280_000, 3_500), - }, - PricingRule { - model: "gpt-5.1", - pricing: ModelPricing::new(12_500, 100_000, 1_250) - .with_flex(6_250, 50_000, 625) - .with_fast(25_000, 200_000, 2_500), - }, - PricingRule { - model: "gpt-5-mini", - pricing: ModelPricing::new(2_500, 20_000, 250) - .with_flex(1_250, 10_000, 125) - .with_fast(4_500, 36_000, 450), - }, - PricingRule { - model: "gpt-5-nano", - pricing: ModelPricing::new(500, 4_000, 50).with_flex(250, 2_000, 25), - }, - PricingRule { - model: "gpt-5-pro", - pricing: ModelPricing::new(150_000, 1_200_000, 0), - }, - PricingRule { - model: "gpt-5", - pricing: ModelPricing::new(12_500, 100_000, 1_250) - .with_flex(6_250, 50_000, 625) - .with_fast(25_000, 200_000, 2_500), - }, - PricingRule { - model: "gpt-4.1-mini", - pricing: ModelPricing::new(4_000, 16_000, 1_000).with_fast(7_000, 28_000, 1_750), - }, - PricingRule { - model: "gpt-4.1-nano", - pricing: ModelPricing::new(1_000, 4_000, 250).with_fast(2_000, 8_000, 500), - }, - PricingRule { - model: "gpt-4.1", - pricing: ModelPricing::new(20_000, 80_000, 5_000).with_fast(35_000, 140_000, 8_750), - }, - PricingRule { - model: "gpt-4o-2024-05-13", - pricing: ModelPricing::new(50_000, 150_000, 0).with_fast(87_500, 262_500, 0), - }, - PricingRule { - model: "gpt-4o-mini", - pricing: ModelPricing::new(1_500, 6_000, 750).with_fast(2_500, 10_000, 1_250), - }, - PricingRule { - model: "gpt-4o", - pricing: ModelPricing::new(25_000, 100_000, 12_500).with_fast(42_500, 170_000, 21_250), - }, - PricingRule { - model: "o1-pro", - pricing: ModelPricing::new(1_500_000, 6_000_000, 0), - }, - PricingRule { - model: "o1", - pricing: ModelPricing::new(150_000, 600_000, 75_000), - }, - PricingRule { - model: "o3-pro", - pricing: ModelPricing::new(200_000, 800_000, 0), - }, - PricingRule { - model: "o3-mini", - pricing: ModelPricing::new(11_000, 44_000, 5_500), - }, - PricingRule { - model: "o3", - pricing: ModelPricing::new(20_000, 80_000, 5_000) - .with_flex(10_000, 40_000, 2_500) - .with_fast(35_000, 140_000, 8_750), - }, - PricingRule { - model: "o4-mini", - pricing: ModelPricing::new(11_000, 44_000, 2_750) - .with_flex(5_500, 22_000, 1_380) - .with_fast(20_000, 80_000, 5_000), - }, - PricingRule { - model: "gpt-4-turbo", - pricing: ModelPricing::new(100_000, 300_000, 0), - }, - PricingRule { - model: "gpt-4", - pricing: ModelPricing::new(300_000, 600_000, 0), - }, - PricingRule { - model: "gpt-3.5-turbo-instruct", - pricing: ModelPricing::new(15_000, 20_000, 0), - }, - PricingRule { - model: "gpt-3.5-turbo-1106", - pricing: ModelPricing::new(10_000, 20_000, 0), - }, - PricingRule { - model: "gpt-3.5-turbo", - pricing: ModelPricing::new(5_000, 15_000, 0), - }, - // 各变体独立采用已公开的价格与档位,不能继承父型号的所有档位 - // Cyber 长上下文的官方来源存在差异,该区间暂不估价 - PricingRule { - model: "gpt-5.6-cyber", - pricing: ModelPricing::new(125_000, 750_000, 12_500) - .with_cache_write(125) - .with_unpriced_long_context(), - }, - PricingRule { - model: "gpt-5.5-cyber", - pricing: ModelPricing::new(125_000, 750_000, 12_500).with_unpriced_long_context(), - }, - PricingRule { - model: "chat-latest", - pricing: ModelPricing::new(50_000, 300_000, 5_000), - }, -]; - -#[derive(Clone, Copy)] -struct TokenAmounts { - input_ticks: u128, - output_ticks: u128, - cache_read_ticks: u128, - cache_write_ticks: u128, - total_ticks: u128, -} - -/// 按 OpenAI Provider 当前受控价格规则计算费用明细 -#[must_use] -pub fn openai_billing_breakdown( - model: &str, - usage: OpenAiBillingUsage, - service_tier: Option<&str>, -) -> Option { - token_billing_breakdown_with_context( - model_pricing(model), - usage, - service_tier, - usage.input_tokens > LONG_CONTEXT_THRESHOLD, - None, - ) -} - -/// 使用请求开始时冻结的价格覆盖,不读取管理存储 -#[must_use] -pub fn openai_billing_breakdown_with_override( - model: &str, - usage: OpenAiBillingUsage, - service_tier: Option<&str>, - pricing: Option<&gateway_core::metering::ModelPriceOverride>, -) -> Option { - token_billing_breakdown_with_context( - model_pricing(model), - usage, - service_tier, - usage.input_tokens > LONG_CONTEXT_THRESHOLD, - pricing, - ) -} - -/// 其他 API 协议仅使用明确配置的标准 Token 单价,不继承 OpenAI 型号与档位规则 -pub(crate) fn configured_token_billing_breakdown( - usage: OpenAiBillingUsage, - pricing: &gateway_core::metering::ModelPriceOverride, -) -> Option { - token_billing_breakdown_with_context(None, usage, None, false, Some(pricing)) -} - -fn token_billing_breakdown_with_context( - pricing: Option, - usage: OpenAiBillingUsage, - service_tier: Option<&str>, - long_context: bool, - custom: Option<&gateway_core::metering::ModelPriceOverride>, -) -> Option { - if usage - .cached_input_tokens - .checked_add(usage.cache_write_input_tokens)? - > usage.input_tokens - || usage.image_input_tokens > 0 - || usage.image_output_tokens > 0 - { - return None; - } - let tool_ticks = web_search_amount_ticks(usage)? - .checked_add(u128::from(usage.file_search_calls).checked_mul(FILE_SEARCH_CALL_TICKS)?)?; - let normalized_tier = normalize_service_tier(service_tier); - let tier = pricing_tier(normalized_tier.as_deref())?; - let (standard_rates, _) = - effective_rates(pricing, custom, PricingTier::Standard, long_context)?; - let (selected_rates, long_context_billing_applied) = - effective_rates(pricing, custom, tier, long_context)?; - let cache_write_percent = pricing.map_or(0, |pricing| pricing.cache_write_percent); - let mut standard = token_amounts( - standard_rates, - cache_write_percent, - usage.input_tokens, - usage.output_tokens, - usage.cached_input_tokens, - usage.cache_write_input_tokens, - )?; - let mut selected = token_amounts( - selected_rates, - cache_write_percent, - usage.input_tokens, - usage.output_tokens, - usage.cached_input_tokens, - usage.cache_write_input_tokens, - )?; - standard.total_ticks = standard.total_ticks.checked_add(tool_ticks)?; - selected.total_ticks = selected.total_ticks.checked_add(tool_ticks)?; - let multiplier_percent = - effective_multiplier_percent(selected.total_ticks, standard.total_ticks)?; - let cache_write_rate = cache_write_rate(selected_rates, cache_write_percent)?; - - CalculatedCostBreakdown::new( - CalculatedCostAmounts::new( - usd_money(selected.input_ticks)?, - usd_money(selected.output_ticks)?, - usd_money(selected.cache_read_ticks)?, - usd_money(selected.cache_write_ticks)?, - usd_money(standard.total_ticks)?, - usd_money(selected.total_ticks)?, - ), - CalculatedCostRates::new( - usd_price_per_million(selected_rates.input_ticks)?, - usd_price_per_million(selected_rates.output_ticks)?, - usd_price_per_million(selected_rates.cache_read_ticks)?, - usd_price_per_million(cache_write_rate)?, - ), - Some(normalized_tier.unwrap_or_else(|| "default".to_owned())), - multiplier_percent, - ) - .with_long_context_billing(long_context_billing_applied) - .with_custom_multiplier(custom.map_or(10_000, |pricing| pricing.multiplier_bps)) -} - -fn effective_rates( - default: Option, - custom: Option<&gateway_core::metering::ModelPriceOverride>, - tier: PricingTier, - long_context: bool, -) -> Option<(TokenRates, bool)> { - let long_band = match tier { - PricingTier::Standard => "long_standard", - PricingTier::Fast => "long_fast", - PricingTier::Flex => "long_flex", - PricingTier::Ultrafast => "long_ultrafast", - }; - let uses_long = long_context - && (default.is_some_and(|p| p.long_standard.is_configured() || p.unpriced_long_context) - || custom.is_some_and(|p| p.bands.contains_key(long_band))); - let band = match (tier, uses_long) { - (PricingTier::Standard, false) => "standard", - (PricingTier::Fast, false) => "fast", - (PricingTier::Flex, false) => "flex", - (PricingTier::Ultrafast, false) => "ultrafast", - (PricingTier::Standard, true) => "long_standard", - (PricingTier::Fast, true) => "long_fast", - (PricingTier::Flex, true) => "long_flex", - (PricingTier::Ultrafast, true) => "long_ultrafast", - }; - if let Some(rates) = custom.and_then(|p| p.bands.get(band)) { - return Some(( - TokenRates { - input_ticks: rates.input.ticks_per_token(), - output_ticks: rates.output.ticks_per_token(), - cache_read_ticks: rates.cache_read.ticks_per_token(), - cache_write_ticks: Some(rates.cache_write.ticks_per_token()), - explicit_cache: true, - }, - uses_long, - )); - } - let default = default?; - Some(( - default.rates(tier, long_context)?, - long_context && default.long_standard.is_configured(), - )) -} - -pub(crate) fn pricing_catalog() --> std::collections::BTreeMap { - use gateway_core::metering::{ModelPriceOverride, TokenPrice, TokenPriceOverride}; - let price = |ticks: u128| -> Option { - Decimal::from_scaled(ticks.checked_mul(1_000_000)?) - .ok()? - .canonical() - .try_into() - .ok() - }; - let mut catalog: std::collections::BTreeMap<_, _> = PRICING_RULES - .iter() - .map(|rule| { - let pricing = rule.pricing; - let bands = [ - ("standard", pricing.standard), - ("fast", pricing.fast), - ("ultrafast", pricing.ultrafast), - ("flex", pricing.flex), - ("long_standard", pricing.long_standard), - ("long_fast", pricing.long_fast), - ("long_ultrafast", pricing.long_ultrafast), - ("long_flex", pricing.long_flex), - ] - .into_iter() - .filter(|(_, rates)| rates.is_configured()) - .filter_map(|(name, rates)| { - Some(( - name.to_owned(), - TokenPriceOverride { - input: price(rates.input_ticks)?, - output: price(rates.output_ticks)?, - cache_read: price(if rates.cache_read_ticks == 0 { - rates.input_ticks - } else { - rates.cache_read_ticks - })?, - // 内置表没有独立缓存写入费时,这部分 Token 原本按输入计费 - // 管理页复制来源档位不能把它改成显式免费 - cache_write: price(if pricing.cache_write_percent == 0 { - rates.input_ticks - } else { - cache_write_rate(rates, pricing.cache_write_percent)? - })?, - }, - )) - }) - .collect(); - ( - rule.model.to_owned(), - ModelPriceOverride { - multiplier_bps: 10_000, - bands, - }, - ) - }) - .collect(); - for model in IMAGE_MODELS { - let bands = [("standard", IMAGE_TEXT_RATES), ("image", IMAGE_TOKEN_RATES)] - .into_iter() - .map(|(band, rates)| { - ( - band.to_owned(), - TokenPriceOverride { - input: price(rates.input_ticks).expect("内置图像价格合法"), - output: price(rates.output_ticks).expect("内置图像价格合法"), - cache_read: price(rates.cache_read_ticks).expect("内置图像价格合法"), - cache_write: price(0).expect("零价格合法"), - }, - ) - }) - .collect(); - catalog.insert( - (*model).to_owned(), - ModelPriceOverride { - multiplier_bps: 10_000, - bands, - }, - ); - } - catalog -} - -const IMAGE_MODELS: &[&str] = &[ - "gpt-image-2", - "gpt-image-2-2026-04-21", - "gpt-image-2.5-sunburst", - "gpt-image-2.5-sunburst-2026-09-08", - "gpt-image-2.5-flare", - "gpt-image-2.5-flare-2026-09-08", -]; -const IMAGE_TEXT_RATES: TokenRates = TokenRates::new(50_000, 0, 12_500); -const IMAGE_TOKEN_RATES: TokenRates = TokenRates::new(80_000, 300_000, 20_000); - -/// 独立 Images 端点按公开标准 API 单价估算;不是 ChatGPT 账号实际扣费 -pub(crate) fn image_calculated_cost( - request_body: &[u8], - usage: &Value, - prices: &gateway_core::metering::PricingOverrides, -) -> Option { - #[derive(serde::Deserialize)] - struct ImageModel { - model: String, - } - // 只读取模型,跳过编辑请求中可能很大的 base64 图片 - let request = serde_json::from_slice::(request_body).ok()?; - let custom = prices - .get("openai") - .and_then(|models| models.get(&request.model)); - let known = IMAGE_MODELS.contains(&request.model.as_str()); - let rates = |band, builtin| { - custom - .and_then(|p| p.bands.get(band)) - .map(|p| TokenRates { - input_ticks: p.input.ticks_per_token(), - output_ticks: p.output.ticks_per_token(), - cache_read_ticks: p.cache_read.ticks_per_token(), - cache_write_ticks: Some(p.cache_write.ticks_per_token()), - explicit_cache: true, - }) - .or_else(|| known.then_some(builtin)) - }; - let text_rates = rates("standard", IMAGE_TEXT_RATES)?; - let image_rates = rates("image", IMAGE_TOKEN_RATES)?; - let input = usage.get("input_tokens")?.as_u64()?; - let output = usage.get("output_tokens")?.as_u64()?; - let details = usage.get("input_tokens_details")?; - let text_input = details.get("text_tokens")?.as_u64()?; - let image_input = details.get("image_tokens")?.as_u64()?; - if text_input.checked_add(image_input)? != input { - return None; - } - if let Some(total) = usage.get("total_tokens") - && total.as_u64()? != input.checked_add(output)? - { - return None; - } - // 此模型仅输出图片;上游如报告其他输出模态,不能套用图片单价 - if let Some(details) = usage.get("output_tokens_details") - && (details.get("image_tokens")?.as_u64()? != output - || details.get("text_tokens")?.as_u64()? != 0) - { - return None; - } - let cached = match details.get("cached_tokens") { - None => 0, - Some(value) => value.as_u64()?, - }; - if cached > input { - return None; - } - // 缓存只给总量时,混合输入无法判定应套用哪种缓存单价 - let (cached_text, cached_image) = match (text_input, image_input, cached) { - (_, _, 0) => (0, 0), - (_, 0, cached) => (cached, 0), - (0, _, cached) => (0, cached), - (_, _, cached) if cached == input => (text_input, image_input), - _ => return None, - }; - // 价格来源:https://developers.openai.com/api/docs/pricing,核验日期 2026-09-09 - // GPT Image 2 和两个 2.5 型号按相同的 token 单价计费,不使用按张估价 - // 每百万 token 的美元单价:文本 5 / 缓存 1.25;图片 8 / 缓存 2 / 输出 30 - let text = token_amounts(text_rates, 0, text_input, 0, cached_text, 0)?; - let image = token_amounts(image_rates, 0, image_input, output, cached_image, 0)?; - let total = usd_money(text.total_ticks.checked_add(image.total_ticks)?)?; - let breakdown = CalculatedCostBreakdown::new( - CalculatedCostAmounts::new( - usd_money(text.input_ticks)?, - usd_money(image.output_ticks)?, - usd_money(text.cache_read_ticks)?, - usd_money(0)?, - total, - total, - ), - CalculatedCostRates::new( - usd_price_per_million(text_rates.input_ticks)?, - usd_price_per_million(image_rates.output_ticks)?, - usd_price_per_million(text_rates.cache_read_ticks)?, - usd_money(0)?, - ), - Some("default".to_owned()), - 100, - ) - .with_image(gateway_core::metering::ImageCostBreakdown { - input_tokens: image_input, - cached_input_tokens: cached_image, - input_amount: usd_money(image.input_ticks)?, - cache_read_amount: usd_money(image.cache_read_ticks)?, - input_price_per_million: usd_price_per_million(image_rates.input_ticks)?, - cache_read_price_per_million: usd_price_per_million(image_rates.cache_read_ticks)?, - }) - .with_custom_multiplier(custom.map_or(10_000, |p| p.multiplier_bps))?; - Some(breakdown.calculated_cost()) -} - -fn model_pricing(model: &str) -> Option { - let normalized = normalize_model_name(model); - let model = pricing_model_name(&normalized); - PRICING_RULES - .iter() - .find(|rule| model == rule.model) - .map(|rule| rule.pricing) -} - -pub(crate) fn web_search_pricing(model: &str, tools: Option<&[Value]>) -> Option { - let mut standard = false; - let mut preview = false; - for tool_type in tools - .into_iter() - .flatten() - .filter_map(|tool| tool.get("type").and_then(Value::as_str)) - { - if tool_type == "web_search_preview" || tool_type.starts_with("web_search_preview_") { - preview = true; - } else if tool_type == "web_search" || tool_type.starts_with("web_search_") { - standard = true; - } - } - match (standard, preview) { - // 这两个模型将非预览搜索内容按固定 8K 输入块计费 - // 响应缺少足够明细,无法排除与普通输入重复计费,因此保留为未定价 - (true, false) if fixed_block_web_search_model(model) => None, - (true, false) => Some(WebSearchPricing::Standard), - (false, true) if reasoning_model(model) => Some(WebSearchPricing::Standard), - (false, true) => Some(WebSearchPricing::PreviewNonReasoning), - (false, false) | (true, true) => None, - } -} - -fn fixed_block_web_search_model(model: &str) -> bool { - let normalized = normalize_model_name(model); - ["gpt-4o-mini", "gpt-4.1-mini"] - .iter() - .any(|rule| model_matches_rule(&normalized, rule)) -} - -fn reasoning_model(model: &str) -> bool { - let normalized = normalize_model_name(model); - let model = pricing_model_name(&normalized); - model.starts_with("gpt-5") - || matches!( - model, - "gpt-6.2-astra" - | "gpt-6.2-sol" - | "gpt-6-astra" - | "gpt-6.1-sol" - | "gpt-6.1-terra" - | "gpt-6-sol" - | "gpt-6-luna" - ) - || model.starts_with("o1") - || model.starts_with("o3") - || model.starts_with("o4") -} - -fn pricing_tier(service_tier: Option<&str>) -> Option { - match service_tier { - None | Some("default" | "standard") => Some(PricingTier::Standard), - Some("flex") => Some(PricingTier::Flex), - Some("fast" | "priority") => Some(PricingTier::Fast), - Some("ultrafast") => Some(PricingTier::Ultrafast), - Some(_) => None, - } -} - -fn web_search_amount_ticks(usage: OpenAiBillingUsage) -> Option { - if usage.web_search_calls == 0 { - return Some(0); - } - u128::from(usage.web_search_calls).checked_mul(usage.web_search_pricing?.price_per_call_ticks()) -} - -fn token_amounts( - rates: TokenRates, - cache_write_percent: u32, - input_tokens: u64, - output_tokens: u64, - cached_input_tokens: u64, - cache_write_input_tokens: u64, -) -> Option { - if cached_input_tokens.checked_add(cache_write_input_tokens)? > input_tokens { - return None; - } - let billed_cache_read = if rates.explicit_cache || rates.cache_read_ticks > 0 { - cached_input_tokens - } else { - 0 - }; - let cache_write_rate = cache_write_rate(rates, cache_write_percent)?; - let billed_cache_write = if rates.explicit_cache || cache_write_rate > 0 { - cache_write_input_tokens - } else { - 0 - }; - let uncached_input = input_tokens - .checked_sub(billed_cache_read)? - .checked_sub(billed_cache_write)?; - let input_ticks = u128::from(uncached_input).checked_mul(rates.input_ticks)?; - let output_ticks = u128::from(output_tokens).checked_mul(rates.output_ticks)?; - let cache_read_ticks = u128::from(billed_cache_read).checked_mul(rates.cache_read_ticks)?; - let cache_write_ticks = u128::from(billed_cache_write).checked_mul(cache_write_rate)?; - let total_ticks = input_ticks - .checked_add(output_ticks)? - .checked_add(cache_read_ticks)? - .checked_add(cache_write_ticks)?; - Some(TokenAmounts { - input_ticks, - output_ticks, - cache_read_ticks, - cache_write_ticks, - total_ticks, - }) -} - -fn cache_write_rate(rates: TokenRates, percent: u32) -> Option { - if let Some(ticks) = rates.cache_write_ticks { - return Some(ticks); - } - if percent == 0 { - return Some(0); - } - apply_percent(rates.input_ticks, percent) -} - -fn effective_multiplier_percent(total: u128, standard: u128) -> Option { - if standard == 0 { - return Some(100); - } - let rounded = total - .checked_mul(100)? - .checked_add(standard / 2)? - .checked_div(standard)?; - u32::try_from(rounded).ok() -} - -fn normalize_model_name(model: &str) -> String { - model - .trim() - .trim_start_matches('/') - .rsplit('/') - .next() - .unwrap_or_default() - .to_ascii_lowercase() -} - -// 仅已核验的别名和快照可以共用价格;未知后缀、未来日期和微调模型 -// 不得直接继承父型号的价格 -fn pricing_model_name(model: &str) -> &str { - match model { - "gpt-3.5-turbo-0125" => "gpt-3.5-turbo", - "gpt-4-0613" => "gpt-4", - "gpt-4-turbo-2024-04-09" => "gpt-4-turbo", - "gpt-4.1-2025-04-14" => "gpt-4.1", - "gpt-4.1-mini-2025-04-14" => "gpt-4.1-mini", - "gpt-4.1-nano-2025-04-14" => "gpt-4.1-nano", - "gpt-4o-2024-08-06" => "gpt-4o", - "gpt-4o-2024-11-20" => "gpt-4o", - "gpt-4o-mini-2024-07-18" => "gpt-4o-mini", - "gpt-5-2025-08-07" => "gpt-5", - "gpt-5-mini-2025-08-07" => "gpt-5-mini", - "gpt-5-nano-2025-08-07" => "gpt-5-nano", - "gpt-5-pro-2025-10-06" => "gpt-5-pro", - "gpt-5.1-2025-11-13" => "gpt-5.1", - "gpt-5.2-2025-12-11" => "gpt-5.2", - "gpt-5.2-pro-2025-12-11" => "gpt-5.2-pro", - "gpt-5.4-2026-03-05" => "gpt-5.4", - "gpt-5.4-mini-2026-03-17" => "gpt-5.4-mini", - "gpt-5.4-nano-2026-03-17" => "gpt-5.4-nano", - "gpt-5.4-pro-2026-03-05" => "gpt-5.4-pro", - "gpt-5.5-2026-04-23" => "gpt-5.5", - "gpt-5.5-pro-2026-04-23" => "gpt-5.5-pro", - "gpt-daybreak-blue-latest" => "gpt-5.6-sol", - "gpt-daybreak-red-latest" => "gpt-5.6-cyber", - "o1-2024-12-17" => "o1", - "o1-pro-2025-03-19" => "o1-pro", - "o3-2025-04-16" => "o3", - "o3-mini-2025-01-31" => "o3-mini", - "o3-pro-2025-06-10" => "o3-pro", - "o4-mini-2025-04-16" => "o4-mini", - _ => model, - } -} - -fn model_matches_rule(model: &str, rule: &str) -> bool { - pricing_model_name(model) == rule -} - -/// 规范化请求或响应携带的服务档位,供观测与计费共用 -pub(crate) fn normalize_service_tier(service_tier: Option<&str>) -> Option { - service_tier - .map(str::trim) - .filter(|value| { - !value.is_empty() && value.len() <= 64 && !value.chars().any(char::is_control) - }) - .map(str::to_ascii_lowercase) -} - -fn apply_percent(value: u128, percent: u32) -> Option { - value - .checked_mul(u128::from(percent))? - .checked_add(50) - .map(|scaled| scaled / 100) -} - -fn usd_money(ticks: u128) -> Option { - Some(Money::new( - Decimal::from_scaled(ticks).ok()?, - CurrencyCode::new("USD").ok()?, - )) -} - -fn usd_price_per_million(per_token_ticks: u128) -> Option { - usd_money(per_token_ticks.checked_mul(1_000_000)?) -} - /// 单次 Codex usage 响应允许保留和解析的最大字节数 pub const MAX_CODEX_USAGE_BODY_BYTES: usize = 1024 * 1024; diff --git a/backend/crates/providers/openai/tests/admin/mod.rs b/backend/crates/providers/openai/tests/admin/mod.rs index fb2439d01..97db9d369 100644 --- a/backend/crates/providers/openai/tests/admin/mod.rs +++ b/backend/crates/providers/openai/tests/admin/mod.rs @@ -1,6 +1,7 @@ //! 验证 OpenAI 管理能力、请求画像、Bundle 组装与额度投影 mod peer_info; +mod provider; use std::collections::{BTreeMap, BTreeSet}; use std::num::NonZeroU32; @@ -50,7 +51,7 @@ use gateway_core::routing::{ use gateway_core::task::{WorkerContribution, WorkerKind, WorkerRunnable}; use provider_openai::config::OpenAiConfig; use provider_openai::credential::{CodexCredentialCodec, ImportCodexOAuthCredential}; -use provider_openai::transport::profile::APPCAST_POLL_INTERVAL; +use provider_openai::profile::APPCAST_POLL_INTERVAL; use secrecy::SecretString; use serde_json::{Map, Value, json}; use tempfile::TempDir; @@ -68,1980 +69,10 @@ const COMPLETED_SESSION_SSE: &str = concat!( "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_initialized_session\",\"model\":\"gpt-5.4\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":1,\"total_tokens\":2}}}\n\n" ); -#[tokio::test] -async fn plan_display_uses_pro_short_names_and_codex_status_labels_for_other_known_plans() { - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports(), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .unwrap(); - let admin = bundle.admin_provider(); - for (raw, display) in [ - ("prolite", "ProLite"), - ("pro", "Pro"), - ("promax", "ProMax"), - ("free", "Free"), - ("go", "Go"), - ("plus", "Plus"), - ("team", "Business"), - ("self_serve_business_prolite", "Business Premium"), - ("self_serve_business_usage_based", "Business"), - ("business", "Enterprise"), - ("ent26", "Enterprise"), - ("enterprise", "Enterprise"), - ("hc", "Enterprise"), - ("enterprise_cbp_automation", "Enterprise (Automation)"), - ("enterprise_cbp_usage_based", "Enterprise"), - ("edu", "Edu"), - ("education", "Edu"), - ("edu_plus", "Edu Plus"), - ("edu_pro", "Edu Pro"), - ("sci", "Academic Researchers"), - ("sci_plus", "Academic Researchers Plus"), - ("SCI_PLUS", "Academic Researchers Plus"), - ("Future_Plan", "Future_Plan"), - ] { - assert_eq!(admin.plan_type_display(raw), display, "{raw}"); - } -} - -#[tokio::test] -async fn account_capabilities_distinguish_oauth_from_api_key_and_unknown_credentials() { - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports(), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .unwrap(); - let provider = bundle.admin_provider(); - let id = ProviderAccountId::new("acct_capabilities").unwrap(); - let oauth = provider.account_capabilities(&id, "oauth"); - assert!( - oauth.quota - && oauth.quota_refresh - && oauth.profile - && oauth.subscription - && oauth.avatar - && oauth.reset_credits - && oauth.consume_reset_credit - ); - for kind in ["api_key", "unknown"] { - assert_eq!(provider.account_capabilities(&id, kind), Default::default()); - } -} - -#[tokio::test] -async fn custom_identity_preview_and_dashboard_share_the_exact_request_profile() { - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports(), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .unwrap(); - let provider = bundle.admin_provider(); - let user_agent = - "codex_exec/0.156.1 (Ubuntu 24.4.0; x86_64) xterm-256color (codex_exec; 0.156.1)"; - let configuration = OpaqueProviderData::new( - json!({"mode":"custom", "userAgent":user_agent}) - .as_object() - .unwrap() - .clone(), - ); - let preview = provider.preview_client_profile(&configuration).unwrap(); - let dashboard = provider.configured_wire_profile(&configuration).unwrap(); - assert_eq!(preview.expose_to_provider()["userAgent"], user_agent); - assert_eq!(dashboard.user_agent, user_agent); - assert_eq!(dashboard.product, "codex_exec"); - assert_eq!(dashboard.version, "0.156.1"); - assert!(dashboard.verified_at.is_none()); - assert!(dashboard.release.is_none()); - assert_ne!( - provider.dashboard_wire_profile().unwrap().user_agent, - user_agent - ); -} - -#[tokio::test] -async fn installation_seed_is_optional_and_validated_only_for_key_profiles() { - let bundle = provider_openai::initialize( - valid_config().config, - provider_ports(), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .unwrap(); - let provider = bundle.admin_provider(); - let id = "3B11BC82-C666-417D-B9FF-2A34FD040385"; - for (value, valid) in [ - (json!(id), true), - (json!(null), true), - (json!(""), true), - (json!(id.replace('-', "")), false), - (json!("bad"), false), - (json!(42), false), - ] { - let configuration = OpaqueProviderData::new( - json!({ - "mode": "custom", "userAgent": "codex-tui/1.0.0", "installationSeed": value - }) - .as_object() - .unwrap() - .clone(), - ); - let preview = provider.preview_key_client_profile(&configuration, None); - assert_eq!(preview.is_ok(), valid); - if value == id { - assert_eq!( - preview.unwrap().expose_to_provider()["configuration"]["installationSeed"], - id.to_lowercase() - ); - assert!(provider.preview_client_profile(&configuration).is_err()); - } - } - let doc = - |value: serde_json::Value| OpaqueProviderData::new(value.as_object().unwrap().clone()); - let global = doc(json!({"mode": "custom", "userAgent": "codex-tui/2.0.0"})); - let key = doc(json!({"inherit":{"installationSeed":id}})); - let preview = provider - .preview_key_client_profile(&key, Some(&global)) - .unwrap() - .into_inner(); - assert_eq!(preview["userAgent"], "codex-tui/2.0.0"); - assert_eq!( - preview["configuration"]["installationSeed"], - id.to_lowercase() - ); - assert!(provider.preview_client_profile(&key).is_err()); - assert!( - provider - .preview_key_client_profile( - &doc(json!({"inherit":{"userAgent":"other"}})), - Some(&global) - ) - .is_err() - ); -} - -#[tokio::test] -async fn openai_bundle_exposes_one_core_provider_and_drains_worker_contributions_once() { - let config = valid_config(); - let mut bundle = provider_openai::initialize( - config.config.clone(), - provider_ports(), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - - assert_eq!(bundle.core_provider().name(), "openai"); - assert_eq!(bundle.admin_provider().provider_kind().as_str(), "openai"); - let contributions = bundle.take_worker_contributions(); - assert_eq!(contributions.len(), 8); - assert!( - contributions - .iter() - .any(|item| item.kind() == WorkerKind::OAuthRefresh) - ); - assert!( - contributions - .iter() - .any(|item| item.kind() == WorkerKind::QuotaCatalogHealth) - ); - let release_worker = contributions - .iter() - .find_map(|contribution| match contribution { - WorkerContribution::Registration(registration) - if registration.id.owner() == "openai-desktop-release" => - { - Some(registration) - } - WorkerContribution::Registration(_) | WorkerContribution::Disabled { .. } => None, - }) - .expect("Desktop release worker"); - assert_eq!(release_worker.id.kind(), WorkerKind::QuotaCatalogHealth); - let WorkerRunnable::Scheduled { schedule, .. } = &release_worker.runnable else { - panic!("Desktop release worker must be scheduled"); - }; - assert_eq!(schedule.interval(), APPCAST_POLL_INTERVAL); - for (owner, interval) in [ - ("openai-cli-release", APPCAST_POLL_INTERVAL), - ("openai-platform-desktop-release", APPCAST_POLL_INTERVAL), - ("openai", Duration::from_secs(30)), - ("openai-account-warmup", Duration::from_secs(30)), - ( - "openai-model-catalog", - config.config.quota_refresh_policy().interval(), - ), - ] { - let schedule = contributions - .iter() - .find_map(|contribution| match contribution { - WorkerContribution::Registration(registration) - if registration.id.kind() == WorkerKind::QuotaCatalogHealth - && registration.id.owner() == owner => - { - match ®istration.runnable { - WorkerRunnable::Scheduled { schedule, .. } => Some(schedule), - WorkerRunnable::Daemon { .. } => None, - } - } - _ => None, - }) - .expect("quota/catalog scheduled worker"); - assert_eq!(schedule.interval(), interval, "{owner}"); - } - assert!(contributions.iter().any(|contribution| { - matches!( - contribution, - WorkerContribution::Registration(registration) - if registration.id.owner() == "openai-model-etag" - && matches!(®istration.runnable, WorkerRunnable::Daemon { .. }) - ) - })); - assert!(bundle.take_worker_contributions().is_empty()); -} - -#[tokio::test] -async fn quota_forecast_observation_reuses_protocol_parser_and_keeps_window_identity() { - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports(), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .unwrap(); - let provider = bundle.admin_provider(); - let mut window = gateway_admin::model::provider_credentials::ProviderQuotaWindow { - upstream: None, - key: "codex:604800s".to_owned(), - group: "shortTerm".to_owned(), - label: "周额度".to_owned(), - limit_id: Some("codex".to_owned()), - limit_name: None, - role: Some(ProviderQuotaWindowRole::Primary), - local_usage_attribution: QuotaLocalUsageAttribution::AccountWide, - window_seconds: Some(604_800), - used_percent: Some(50.0), - reset_at: None, - limit_reached: false, - local_usage: None, - provider_data: None, - }; - let document = ProviderDocument::new(OpaqueProviderData::new( - json!({ - "requestSummary": {"ignored": true}, - "rateLimitHeaders": [ - ["x-codex-primary-used-percent", "32.5"], - ["x-codex-primary-window-minutes", "10080"], - ["x-codex-primary-reset-at", "1789805447"], - ["x-codex-secondary-used-percent", "4"], - ["x-codex-secondary-window-minutes", "300"], - ["x-codex-secondary-reset-at", "1789218647"], - ["x-codex-plan-type", "pro"] - ] - }) - .as_object() - .unwrap() - .clone(), - )); - let history = provider.quota_history_parser().unwrap(); - let short = history(&document, "codex:18000s").unwrap(); - assert_eq!(short.used_percent, 4.0); - assert_eq!(short.reset_at.unwrap().timestamp(), 1_789_218_647); - assert!(history(&document, "other:18000s").is_none()); - let named = ProviderDocument::new(OpaqueProviderData::new( - json!({ - "rateLimitHeaders": [ - ["x-codex-primary-used-percent","23"],["x-codex-primary-window-minutes","1"], - ["x-feature-primary-used-percent","23"],["x-feature-primary-window-minutes","1"], - ["x-feature-secondary-used-percent","56"],["x-feature-secondary-window-minutes","1"] - ] - }) - .as_object() - .unwrap() - .clone(), - )); - assert!(history(&named, "codex:60s").is_none()); - assert!(history(&named, "feature:60s").is_none()); - let primary = history(&named, "feature:60s:primary_window").unwrap(); - assert_eq!((primary.used_percent, primary.reset_at), (23.0, None)); - assert_eq!( - history(&named, "feature:60s:secondary_window") - .unwrap() - .used_percent, - 56.0 - ); - let observed = provider - .quota_forecast_observation(&document, &window) - .unwrap(); - assert_eq!(observed.used_percent, 32.5); - assert_eq!(observed.plan_type.as_deref(), Some("pro")); - assert_eq!(observed.reset_at.timestamp(), 1_789_805_447); - window.role = Some(ProviderQuotaWindowRole::Secondary); - assert!( - provider - .quota_forecast_observation(&document, &window) - .is_none() - ); - window.role = Some(ProviderQuotaWindowRole::Primary); - window.limit_id = Some("other_bucket".to_owned()); - assert!( - provider - .quota_forecast_observation(&document, &window) - .is_none() - ); - let malformed = ProviderDocument::new(OpaqueProviderData::new( - json!({ - "rateLimitHeaders": "not-a-header-list" - }) - .as_object() - .unwrap() - .clone(), - )); - assert!( - provider - .quota_forecast_observation(&malformed, &window) - .is_none() - ); -} - -#[tokio::test] -async fn initialized_provider_keeps_thread_spawn_transport_conversations_distinct() { - let account_id = "acct_initialized_thread_spawn"; - let store = Arc::new(MemoryAccountStore::default()); - store - .seed_oauth_credential(ImportCodexOAuthCredential { - account_id: account_id.to_owned(), - name: account_id.to_owned(), - secret: secret("at-initialized-thread-spawn"), - verified_account: profile("chatgpt-initialized-thread-spawn"), - next_refresh_at: Some(Utc::now() + chrono::Duration::minutes(30)), - enabled: true, - }) - .await; - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/codex/responses")) - .respond_with( - ResponseTemplate::new(200) - .insert_header("content-type", "text/event-stream") - .set_body_string(COMPLETED_SESSION_SSE), - ) - .expect(2) - .mount(&server) - .await; - let mut config = valid_config(); - config.config.api.base_url = server.uri(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports_with(store, Arc::new(TestOAuthPending::default())), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("initialized OpenAI provider"); - let provider = bundle.core_provider(); - let root = Operation::Generate(GenerateRequest::from_protocol_payload( - ProtocolPayload::json_object("openai", json!({"model":"gpt-5.4","input":"root","session_id":"parent-session","thread_id":"parent-session"}).as_object().unwrap().clone()).unwrap() - .with_context(Map::from_iter([("use_websocket".to_owned(), json!(false))])), - )); - drop( - provider - .clone() - .execute( - initialized_provider_request(root, account_id), - initialized_attempt_context("req_initialized_root", account_id), - ) - .await - .unwrap(), - ); - let thread_spawn = r#"{"subagent_kind":"thread_spawn"}"#; - let mut conversation_ids = Vec::new(); - - for (request_id, thread_id) in [ - ("req_initialized_thread_spawn_first", "child-one"), - ("req_initialized_thread_spawn_second", "child-two"), - ] { - let payload = ProtocolPayload::json_object( - "openai", - Map::from_iter([ - ("model".to_owned(), json!("gpt-5.4")), - ("input".to_owned(), json!("child task")), - ("session_id".to_owned(), json!("parent-session")), - ("thread_id".to_owned(), json!(thread_id)), - ("turnMetadata".to_owned(), json!(thread_spawn)), - ]), - ) - .expect("OpenAI payload") - .with_context(Map::from_iter([("use_websocket".to_owned(), json!(false))])); - let operation = Operation::Generate(GenerateRequest::from_protocol_payload(payload)); - let mut stream = Arc::clone(&provider) - .execute( - initialized_provider_request(operation, account_id), - initialized_attempt_context(request_id, account_id), - ) - .await - .expect("prepare child provider stream"); - let mut conversation_id = None; - while let Some(event) = stream.next().await { - let event = event.expect("child provider response"); - if let Some(update) = event.session_update() { - conversation_id = update - .payload() - .get("conversation_id") - .and_then(Value::as_str) - .map(ToOwned::to_owned); - } - } - conversation_ids.push(conversation_id.expect("child transport conversation id")); - } - - assert_ne!(conversation_ids[0], conversation_ids[1]); -} - -#[tokio::test] -async fn copying_builtin_prices_keeps_cache_read_and_write_fallback_costs() { - use provider_openai::transport::{ - OpenAiBillingUsage, openai_billing_breakdown, openai_billing_breakdown_with_override, - }; - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports(), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .unwrap(); - let prices = bundle.admin_provider().pricing_catalog(); - for model in [ - "gpt-4", - "gpt-4o", - "gpt-6.2-astra", - "gpt-6.2-sol", - "gpt-6-astra", - "gpt-6.1-sol", - "gpt-6.1-terra", - "gpt-6-sol", - "gpt-6-luna", - ] { - let ultrafast_supported = matches!( - model, - "gpt-6.2-astra" | "gpt-6.2-sol" | "gpt-6-astra" | "gpt-6.1-sol" - ); - for band in ["ultrafast", "long_ultrafast"] { - assert_eq!(prices[model].bands.contains_key(band), ultrafast_supported); - } - for tier in [None, Some("ultrafast")] { - if tier.is_some() && !ultrafast_supported { - continue; - } - for input in [100, 272_001] { - let usage = OpenAiBillingUsage::new(input, 10, 20, 15); - let inherited = openai_billing_breakdown(model, usage, tier).unwrap(); - let copied = openai_billing_breakdown_with_override( - model, - usage, - tier, - Some(&prices[model]), - ) - .unwrap(); - assert_eq!( - inherited.total_amount(), - copied.total_amount(), - "{model} {tier:?} {input}" - ); - } - } - } -} - -#[tokio::test] -async fn openai_admin_provider_exposes_live_wire_profile_and_validated_billing() { - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports(), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - let admin = bundle.admin_provider(); - let baseline = admin.dashboard_wire_profile().expect("official baseline"); - assert_eq!( - baseline.release.as_ref().map(|release| release.status), - Some(DesktopReleaseStatus::Unchecked) - ); - let selection = OpaqueProviderData::new(json!({ - "client": "desktop", "platform": "macos", "versionMode": "fixed", - "codexVersion": "0.102.0", "desktopVersion": "1.2026.190", "desktopBuild": "19012345678", - "osVersion": "15.5.0", "arch": "arm64", "terminal": "xterm-256color" - }).as_object().unwrap().clone()); - let profile = admin - .configured_wire_profile(&selection) - .expect("managed fixed profile"); - assert_eq!(profile.version, "0.102.0"); - assert_eq!(profile.build, None); - assert_eq!(profile.target.os_type, "Mac OS"); - assert_eq!(profile.target.os_version, "15.5.0"); - assert_eq!( - profile.user_agent, - "Codex Desktop/0.102.0 (Mac OS 15.5.0; arm64) xterm-256color (Codex Desktop; 1.2026.190)" - ); - assert_eq!( - profile - .attributes - .iter() - .find(|attribute| attribute.key == "client_identifier") - .map(|attribute| attribute.value.as_str()), - Some("Codex Desktop; 1.2026.190") - ); - assert_eq!( - profile - .attributes - .iter() - .find(|attribute| attribute.key == "version_policy") - .map(|attribute| attribute.value.as_str()), - Some("fixed") - ); - assert!(profile.release.is_none()); - let billing = admin - .calculated_billing(&ProviderBillingInput { - upstream_model_id: "gpt-4o".to_owned(), - service_tier: None, - input_tokens: Some(1_000_000), - output_tokens: Some(0), - cached_input_tokens: Some(0), - cache_write_input_tokens: Some(0), - total: CurrencyCost { - currency: "USD".to_owned(), - amount: "2.5".parse().expect("amount"), - }, - }) - .expect("billing") - .expect("known pricing"); - assert_eq!(billing.total_amount.amount.as_str(), "2.5"); - assert_eq!(billing.input_price_per_million.amount.as_str(), "2.5"); - - let fast_billing = admin - .calculated_billing(&ProviderBillingInput { - upstream_model_id: "gpt-4o".to_owned(), - service_tier: Some("priority".to_owned()), - input_tokens: Some(1_000_000), - output_tokens: Some(0), - cached_input_tokens: Some(0), - cache_write_input_tokens: Some(0), - total: CurrencyCost { - currency: "USD".to_owned(), - amount: "4.25".parse().expect("fast amount"), - }, - }) - .expect("fast billing") - .expect("known fast pricing"); - assert_eq!(fast_billing.service_tier.as_deref(), Some("priority")); - assert_eq!(fast_billing.multiplier_percent, 170); - assert_eq!(fast_billing.standard_amount.amount.as_str(), "2.5"); - assert_eq!(fast_billing.total_amount.amount.as_str(), "4.25"); -} - -#[tokio::test] -async fn openai_legacy_billing_should_not_infer_long_context_flag() { - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports(), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - let billing = bundle - .admin_provider() - .calculated_billing(&ProviderBillingInput { - upstream_model_id: "gpt-5.4".to_owned(), - service_tier: None, - input_tokens: Some(300_000), - output_tokens: Some(0), - cached_input_tokens: Some(0), - cache_write_input_tokens: Some(0), - total: CurrencyCost { - currency: "USD".to_owned(), - amount: "1.5".parse().expect("stored total"), - }, - }) - .expect("legacy billing") - .expect("matching billing breakdown"); - - assert_eq!(billing.total_amount.amount.as_str(), "1.5"); - assert_eq!(billing.input_price_per_million.amount.as_str(), "5"); - assert!(!billing.long_context_billing_applied); -} - -#[tokio::test] -async fn reset_credit_success_with_invalid_body_should_remain_an_unknown_consume_result() { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/codex/rate-limit-reset-credits/consume")) - .respond_with(ResponseTemplate::new(200).set_body_raw("{}", "application/json")) - .expect(1) - .mount(&server) - .await; - let (bundle, account_id, _config) = reset_credit_admin(&server).await; - - let error = bundle - .admin_provider() - .consume_reset_credit(reset_credit_command(account_id)) - .await - .expect_err("invalid success body must be ambiguous"); - - assert_eq!(error.kind(), ProviderAdminErrorKind::Ambiguous); - assert_eq!( - error.message(), - Some( - "OpenAI reset-credit consume result is unknown; refresh the credit list before retrying" - ) - ); -} - -#[tokio::test] -async fn reset_credit_explicit_http_rejection_should_preserve_the_raw_body() { - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/api/codex/rate-limit-reset-credits/consume")) - .respond_with(ResponseTemplate::new(409).set_body_raw( - r#"{"code":"nothing_to_reset","detail":"window is fresh"}"#, - "application/json", - )) - .expect(1) - .mount(&server) - .await; - let (bundle, account_id, _config) = reset_credit_admin(&server).await; - - let error = bundle - .admin_provider() - .consume_reset_credit(reset_credit_command(account_id)) - .await - .expect_err("explicit upstream rejection"); - - assert_eq!(error.kind(), ProviderAdminErrorKind::BadGateway); - assert_eq!( - error.message(), - Some( - r#"OpenAI reset-credit upstream returned HTTP 409: {"code":"nothing_to_reset","detail":"window is fresh"}"# - ) - ); - let debug = format!("{error:?}"); - assert!(debug.contains("")); - assert!(!debug.contains("window is fresh")); -} - -#[tokio::test] -async fn openai_core_provider_projects_private_request_observation_without_execution() { - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports(), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - let payload = ProtocolPayload::json_object( - "openai", - Map::from_iter([ - ("model".to_owned(), json!("gpt-5.4")), - ("input".to_owned(), json!("summarize")), - ("session_id".to_owned(), json!("observation-session")), - ("previous_response_id".to_owned(), json!("resp_previous")), - ]), - ) - .expect("OpenAI payload"); - let operation = Operation::Generate(GenerateRequest::from_protocol_payload(payload)); - - let client_key_id = ClientApiKeyId::new("key_openai_admin_observation").expect("client key"); - let observation = bundle - .core_provider() - .request_observation(&operation, &client_key_id); - - assert!(observation.continuation.requested); - assert!(observation.continuation.previous_response_id_hash.is_some()); - assert!(observation.continuation.affinity_hash.is_some()); -} - -#[tokio::test] -async fn openai_admin_provider_persists_the_full_pending_envelope_and_binds_owner() { - let pending = Arc::new(TestOAuthPending::default()); - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports_with( - Arc::new(MemoryAccountStore::default()), - Arc::clone(&pending), - ), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - let start_context = MutationContext { - actor: MutationActor::AdminSession { - admin_user_id: "admin-owner".to_owned(), - }, - request_id: "request-start".to_owned(), - }; - let started = bundle - .admin_provider() - .start_authorization(PendingAuthorizationMutation::new( - ProviderKind::new("openai").expect("provider"), - AuthorizationMutationTarget::Create { - name: "OAuth account".to_owned(), - }, - AuthorizationOwnerBinding::from_context(&start_context), - )) - .await - .expect("start authorization"); - { - let values = pending.values.lock().expect("OAuth pending"); - let (_, payload, _, _) = values.values().next().expect("stored pending"); - let mutation = payload - .expose_to_provider() - .get("mutation") - .and_then(Value::as_object) - .expect("pending mutation"); - assert!( - payload - .expose_to_provider() - .get("installation_id") - .and_then(Value::as_str) - .and_then(|value| uuid::Uuid::parse_str(value).ok()) - .is_some_and(|value| value.get_version_num() == 4) - ); - assert_eq!( - mutation.get("schema_version").and_then(Value::as_u64), - Some(3) - ); - assert_eq!(mutation["target"]["kind"], "create"); - assert_eq!(mutation["target"]["name"], "OAuth account"); - assert_eq!( - mutation.get("started_request_id").and_then(Value::as_str), - Some("request-start") - ); - } - let error = bundle - .admin_provider() - .complete_authorization(CompleteAuthorization { - settings: None, - context: MutationContext { - actor: MutationActor::AdminSession { - admin_user_id: "different-owner".to_owned(), - }, - request_id: "request-complete".to_owned(), - }, - flow_id: started.flow_id, - callback_url: "http://127.0.0.1:1455/auth/callback?code=unused&state=unused".to_owned(), - }) - .await - .expect_err("wrong owner"); - assert_eq!(error.kind(), ProviderAdminErrorKind::NotFound); - assert_eq!(pending.values.lock().expect("OAuth pending").len(), 1); -} - -#[tokio::test] -async fn oauth_connection_failures_preserve_safe_diagnostics_and_release_the_claim() { - use std::error::Error as _; - use tokio::io::AsyncReadExt as _; - - for timed_out in [false, true] { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let proxy_task = if timed_out { - Some(tokio::spawn(async move { - let (mut socket, _) = listener.accept().await.unwrap(); - let mut request = [0; 4096]; - let count = socket.read(&mut request).await.unwrap(); - assert!(request[..count].starts_with(b"CONNECT ")); - std::future::pending::<()>().await; - })) - } else { - drop(listener); - None - }; - let pending = Arc::new(TestOAuthPending::default()); - let mut config = valid_config(); - config.config.auth.oauth_token_endpoint = - "https://oauth.example.invalid/oauth/token?PRIVATE_URL_MARKER".to_owned(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports_with(Arc::new(MemoryAccountStore::default()), pending.clone()), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .unwrap(); - let context = MutationContext { - actor: MutationActor::System, - request_id: "oauth-connection-failure".to_owned(), - }; - let started = bundle - .admin_provider() - .start_authorization( - PendingAuthorizationMutation::new( - ProviderKind::new("openai").unwrap(), - AuthorizationMutationTarget::Create { - name: String::new(), - }, - AuthorizationOwnerBinding::from_context(&context), - ) - .with_outbound_proxy(Some( - gateway_core::account::OutboundProxy::parse(&format!( - "http://proxy-user:PRIVATE_PROXY_PASSWORD@{address}" - )) - .unwrap(), - )), - ) - .await - .unwrap(); - let state = { - let values = pending.values.lock().unwrap(); - let (_, payload, _, _) = values.values().next().unwrap(); - payload.expose_to_provider()["state"] - .as_str() - .unwrap() - .to_owned() - }; - let error = bundle - .admin_provider() - .complete_authorization(CompleteAuthorization { - settings: None, - context, - flow_id: started.flow_id, - callback_url: format!( - "http://127.0.0.1:1455/auth/callback?code=PRIVATE_CODE&state={state}" - ), - }) - .await - .unwrap_err(); - if let Some(task) = proxy_task { - task.abort(); - assert!(task.await.unwrap_err().is_cancelled()); - } - assert_eq!(error.kind(), ProviderAdminErrorKind::Unavailable); - assert_eq!( - error.public_message(), - Some(if timed_out { - "连接授权服务超时,请检查出站连接" - } else { - "无法连接授权服务,请检查出站连接" - }), - ); - let mut source = error.source(); - let transport = loop { - let cause = source.expect("transport cause must reach the admin boundary"); - if let Some(transport) = cause.downcast_ref::() { - break transport; - } - source = cause.source(); - }; - assert!(transport.is_connect()); - assert_eq!(transport.is_timeout(), timed_out); - assert!(transport.url().is_none()); - assert!(!format!("{error:?} {error}").contains("PRIVATE_")); - let details = - gateway_core::error::ErrorDetails::capture(Some(&error.into()), None, true).unwrap(); - assert!(!details.as_str().contains("PRIVATE_")); - let values = pending.values.lock().unwrap(); - assert!(values.values().next().unwrap().3.is_none()); - } -} - -#[tokio::test] -async fn openai_reauthorization_pending_payload_reuses_the_account_installation_id() { - let accounts = Arc::new(MemoryAccountStore::default()); - accounts - .seed_oauth_credential(ImportCodexOAuthCredential { - account_id: "acct_pending_reauth".to_owned(), - name: "pending reauthorization".to_owned(), - secret: secret("pending-reauth-access"), - verified_account: profile("chatgpt-pending-reauth"), - next_refresh_at: Some(Utc::now() + chrono::Duration::minutes(30)), - enabled: true, - }) - .await; - let account_id = ProviderAccountId::new("acct_pending_reauth").expect("account id"); - let existing = accounts - .load_current_credential(&account_id) - .await - .expect("seeded credential"); - let expected_installation_id = CodexCredentialCodec::decode(&existing.credential) - .expect("decode seeded credential") - .installation_id; - let pending = Arc::new(TestOAuthPending::default()); - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports_with(accounts, Arc::clone(&pending)), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - let context = MutationContext { - actor: MutationActor::AdminApiKey, - request_id: "request-pending-reauth".to_owned(), - }; - - bundle - .admin_provider() - .start_authorization(PendingAuthorizationMutation::new( - ProviderKind::new("openai").expect("provider"), - AuthorizationMutationTarget::Reauthorize { account_id }, - AuthorizationOwnerBinding::from_context(&context), - )) - .await - .expect("start reauthorization"); - - let values = pending.values.lock().expect("OAuth pending"); - let (_, payload, _, _) = values.values().next().expect("stored pending"); - let document = payload.expose_to_provider(); - let mutation = document - .get("mutation") - .and_then(Value::as_object) - .expect("pending mutation"); - let target = mutation - .get("target") - .and_then(Value::as_object) - .expect("pending target"); - assert_eq!( - mutation.get("schema_version").and_then(Value::as_u64), - Some(3) - ); - assert_eq!( - document - .get("reauthorization_account_id") - .and_then(Value::as_str), - Some("acct_pending_reauth") - ); - assert_eq!( - document.get("installation_id").and_then(Value::as_str), - Some(expected_installation_id.as_str()) - ); - assert_eq!( - target.get("kind").and_then(Value::as_str), - Some("reauthorize") - ); - assert_eq!( - target.get("account_id").and_then(Value::as_str), - Some("acct_pending_reauth") - ); -} - -#[tokio::test] -async fn openai_admin_reads_a_full_quota_page_in_one_store_call() { - let store = Arc::new(MemoryAccountStore::default()); - let mut records = Vec::new(); - for index in 0..200 { - let id = format!("acct_admin_quota_page_{index}"); - store - .seed_oauth_credential(ImportCodexOAuthCredential { - account_id: id.clone(), - name: id.clone(), - secret: secret("synthetic-quota-page-access"), - verified_account: profile(&format!("chatgpt-quota-page-{index}")), - next_refresh_at: None, - enabled: false, - }) - .await; - records.push(account_record(&store.account(&id).expect("stored account"))); - } - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports_with(Arc::clone(&store), Arc::new(TestOAuthPending::default())), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - let requests = records - .iter() - .map(|account| ProviderQuotaReadRequest { - account, - rolling_usage: None, - }) - .collect::>(); - let account_reads = store.account_reads(); - let credential_loads = store.credential_loads(); - let quota_reads = store.quota_reads(); - - let results = bundle.admin_provider().read_quotas(&requests).await; - - assert_eq!(results.len(), records.len()); - assert!( - results - .into_iter() - .all(|result| result.expect("cached quota").windows.is_empty()) - ); - assert_eq!(store.quota_reads() - quota_reads, 1); - assert_eq!(store.account_reads(), account_reads); - assert_eq!(store.credential_loads(), credential_loads); -} - -#[tokio::test] -async fn openai_admin_batch_quota_isolates_stale_and_invalid_observations() { - let store = Arc::new(MemoryAccountStore::default()); - let mut records = Vec::new(); - for suffix in ["healthy", "stale", "invalid", "missing"] { - let id = format!("acct_admin_quota_batch_{suffix}"); - store - .seed_oauth_credential(ImportCodexOAuthCredential { - account_id: id.clone(), - name: id.clone(), - secret: secret("synthetic-quota-batch-access"), - verified_account: profile(&format!("chatgpt-quota-batch-{suffix}")), - next_refresh_at: None, - enabled: false, - }) - .await; - let account = store.account(&id).expect("stored account"); - if suffix != "missing" { - let used = if suffix == "invalid" { - json!("invalid") - } else { - json!(25) - }; - store - .compare_and_swap_quota(QuotaObservation { - quota_pause: None, - expected_connection: None, - account_id: account.id().clone(), - expected_revision: account.revision(), - observed_at: SystemTime::now(), - plan_type: None, - state: QuotaState::allowed(SystemTime::now()), - quota: OpaqueProviderData::new( - json!({ - "rate_limit": { "primary_window": { - "used_percent": used, - "reset_at": Utc::now().timestamp() + 3600, - "limit_window_seconds": 18000 - }} - }) - .as_object() - .expect("quota object") - .clone(), - ), - }) - .await - .expect("store quota"); - } - let mut record = account_record(&store.account(&id).expect("stored quota facts")); - if suffix == "stale" { - record.credential_revision = - Revision::new(record.credential_revision.get() + 1).unwrap(); - } - records.push(record); - } - store - .seed_api_key( - "acct_admin_quota_batch_api_key", - "http://127.0.0.1:9".to_owned(), - provider_openai::credential::ResponsesTransport::Http, - ) - .await; - records.push(account_record( - &store.account("acct_admin_quota_batch_api_key").unwrap(), - )); - let mut foreign = records[0].clone(); - foreign.provider_kind = ProviderKind::new("xai").unwrap(); - records.push(foreign); - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports_with(Arc::clone(&store), Arc::new(TestOAuthPending::default())), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - let requests = records - .iter() - .map(|account| ProviderQuotaReadRequest { - account, - rolling_usage: None, - }) - .collect::>(); - let quota_reads = store.quota_reads(); - let account_reads = store.account_reads(); - - let results = bundle.admin_provider().read_quotas(&requests).await; - - assert_eq!(results.len(), 6); - assert_eq!( - results[0].as_ref().unwrap().windows[0].used_percent, - Some(25.0) - ); - assert_eq!( - results[1].as_ref().unwrap_err().kind(), - ProviderAdminErrorKind::Conflict - ); - assert_eq!( - results[2].as_ref().unwrap_err().kind(), - ProviderAdminErrorKind::Invalid - ); - assert!(results[3].as_ref().unwrap().windows.is_empty()); - assert!(results[4].as_ref().unwrap().windows.is_empty()); - assert_eq!( - results[5].as_ref().unwrap_err().kind(), - ProviderAdminErrorKind::NotFound - ); - assert_eq!(store.quota_reads() - quota_reads, 1); - assert_eq!(store.account_reads(), account_reads); - - let api_only = bundle.admin_provider().read_quotas(&requests[4..5]).await; - assert!(api_only[0].as_ref().unwrap().windows.is_empty()); - assert!(bundle.admin_provider().read_quotas(&[]).await.is_empty()); - assert_eq!(store.quota_reads() - quota_reads, 1); -} - -#[tokio::test] -async fn openai_admin_provider_projects_cached_quota_models_and_canonical_export() { - let store = Arc::new(MemoryAccountStore::default()); - let mut oauth_secret = secret("admin-projection-access"); - oauth_secret.id_token = Some(SecretString::from("header.id-token.signature")); - store - .seed_oauth_credential(ImportCodexOAuthCredential { - account_id: "acct_admin_projection".to_owned(), - name: "admin projection".to_owned(), - secret: oauth_secret, - verified_account: profile("chatgpt-admin-projection"), - next_refresh_at: Some(chrono::Utc::now() + chrono::Duration::minutes(30)), - enabled: true, - }) - .await; - let account = store - .account("acct_admin_projection") - .expect("stored account"); - let record = account_record(&account); - let config = valid_config(); - let catalog_cache = Arc::new(TestCatalogCache::default()); - catalog_cache.seed( - provider_openai::credential::CodexCatalogScope::for_account(&account) - .cache_scope() - .unwrap() - .as_str(), - ["gpt-5.4"], - ); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports_with_catalog( - Arc::clone(&store), - Arc::new(TestOAuthPending::default()), - catalog_cache, - ), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - let admin = bundle.admin_provider(); - - let operation = admin - .connection_test_operation( - &UpstreamModelId::new("gpt-5.4").expect("upstream model"), - "Reply with exactly OK.", - ) - .await - .expect("connection test operation"); - let Operation::Generate(request) = operation else { - panic!("connection test must be a generate operation"); - }; - let encoded = provider_openai::encode_generate_request(&request, "gpt-5.4", None) - .expect("official OpenAI request"); - assert_eq!( - encoded.body().get("model").and_then(Value::as_str), - Some("gpt-5.4") - ); - assert_eq!( - encoded.body().get("stream").and_then(Value::as_bool), - Some(true) - ); - - let account_id = account.id().clone(); - let quota = admin - .quota(ProviderQuotaRequest { - account_id: account_id.clone(), - refresh: false, - rolling_usage: None, - }) - .await - .expect("cached quota"); - assert!(quota.windows.is_empty()); - let models = admin - .models(&account_id, false) - .await - .expect("cached models"); - assert_eq!(models.models[0].id.as_str(), "gpt-5.4"); - let loaded = store - .load_credential(account.id(), account.revision()) - .await - .expect("loaded credential"); - let exported = admin - .export_credentials(vec![ProviderExportCredentialInput { - account: record, - provider_material: ProviderDocument::new(OpaqueProviderData::new( - loaded.credential.into_inner(), - )), - }]) - .await - .expect("canonical export"); - assert_eq!(exported.account_ids, vec![account_id]); - let document = exported.document.expose_to_provider().expose_to_provider(); - assert_eq!( - document.get("sourceFormat").and_then(Value::as_str), - Some("cpr") - ); - let exported_account = document - .get("accounts") - .and_then(Value::as_array) - .and_then(|accounts| accounts.first()) - .expect("exported OAuth account"); - assert_eq!( - exported_account.get("accessToken").and_then(Value::as_str), - Some("admin-projection-access") - ); - assert_eq!( - exported_account.get("idToken").and_then(Value::as_str), - Some("header.id-token.signature") - ); - assert!(exported_account.get("token").is_none()); -} - -#[tokio::test] -async fn openai_admin_quota_refresh_updates_the_account_plan() { - let store = Arc::new(MemoryAccountStore::default()); - let mut verified_account = profile("chatgpt-upgraded-plan"); - verified_account.plan_type = Some("plus".to_owned()); - store - .seed_oauth_credential(ImportCodexOAuthCredential { - account_id: "acct_upgraded_plan".to_owned(), - name: "upgraded plan".to_owned(), - secret: secret("upgraded-plan-test-token"), - verified_account, - next_refresh_at: None, - enabled: true, - }) - .await; - let account = store.account("acct_upgraded_plan").unwrap(); - let server = MockServer::start().await; - Mock::given(method("GET")).and(path("/api/codex/usage")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "plan_type": "pro", "rate_limit": {"allowed": true, "primary_window": {"used_percent": 1}} - }))) - .expect(1).mount(&server).await; - let mut config = valid_config(); - config.config.api.base_url = server.uri(); - let bundle = provider_openai::initialize( - config.config, - provider_ports_with(store.clone(), Arc::new(TestOAuthPending::default())), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .unwrap(); - for refresh in [true, false] { - let quota = bundle - .admin_provider() - .quota(ProviderQuotaRequest { - account_id: account.id().clone(), - refresh, - rolling_usage: None, - }) - .await - .unwrap(); - assert_eq!(quota.plan_type.as_deref(), Some("pro")); - assert_eq!( - store.account("acct_upgraded_plan").unwrap().plan_type(), - Some("pro") - ); - } -} - -#[tokio::test] -async fn openai_admin_quota_projects_credit_balance_from_refresh_and_cached_observation() { - let store = Arc::new(MemoryAccountStore::default()); - store - .seed_oauth_credential(ImportCodexOAuthCredential { - account_id: "acct_credit_balance".to_owned(), - name: "credit balance".to_owned(), - secret: secret("credit-balance-test-token"), - verified_account: profile("chatgpt-credit-balance"), - next_refresh_at: None, - enabled: true, - }) - .await; - let account = store.account("acct_credit_balance").unwrap(); - let server = MockServer::start().await; - let mut config = valid_config(); - config.config.api.base_url = server.uri(); - let bundle = provider_openai::initialize( - config.config, - provider_ports_with(store.clone(), Arc::new(TestOAuthPending::default())), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .unwrap(); - for (wire, expected) in [ - ( - json!({"has_credits": true, "unlimited": false, "balance": "62500"}), - Some((true, false, Some("62500"))), - ), - ( - json!({"has_credits": false, "unlimited": false, "balance": 0}), - Some((false, false, Some("0"))), - ), - ( - json!({"has_credits": true, "unlimited": false, "balance": "9007199254740993.1234567890"}), - Some((true, false, Some("9007199254740993.1234567890"))), - ), - ( - json!({"has_credits": true, "unlimited": false, "balance": null}), - Some((true, false, None)), - ), - ( - json!({"has_credits": false, "unlimited": true}), - Some((false, true, None)), - ), - (Value::Null, None), - ] { - let _mock = Mock::given(method("GET")) - .and(path("/api/codex/usage")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "rate_limit": {"allowed": true, "primary_window": {"used_percent": 28}}, - "credits": wire, - }))) - .expect(1) - .mount_as_scoped(&server) - .await; - for refresh in [true, false] { - let quota = bundle - .admin_provider() - .quota(ProviderQuotaRequest { - account_id: account.id().clone(), - refresh, - rolling_usage: None, - }) - .await - .expect("quota with credits"); - assert_eq!( - quota.credits.as_ref().map(|credits| ( - credits.has_credits, - credits.unlimited, - credits.balance.as_deref(), - )), - expected - ); - assert_eq!(quota.windows[0].used_percent, Some(28.0)); - assert!(!quota.limit_reached); - } - } -} - -#[tokio::test] -async fn openai_admin_projects_free_plan_from_cached_quota_when_account_claims_omit_it() { - let store = Arc::new(MemoryAccountStore::default()); - let mut verified_account = profile("chatgpt-free-plan"); - verified_account.plan_type = None; - store - .seed_oauth_credential(ImportCodexOAuthCredential { - account_id: "acct_free_plan".to_owned(), - name: "free plan".to_owned(), - secret: secret("free-plan-test-token"), - verified_account, - next_refresh_at: None, - enabled: true, - }) - .await; - let account = store.account("acct_free_plan").expect("stored account"); - let observed_at = SystemTime::now(); - store - .compare_and_swap_quota(QuotaObservation { - quota_pause: None, - expected_connection: None, - plan_type: None, - account_id: account.id().clone(), - expected_revision: account.revision(), - quota: OpaqueProviderData::new( - json!({ - "plan_type": "free", - "rate_limit": { - "allowed": true, - "primary_window": { - "used_percent": 0, - "limit_window_seconds": 2_592_000, - "reset_at": 1_900_000_000 - } - } - }) - .as_object() - .expect("quota object") - .clone(), - ), - observed_at, - state: QuotaState::allowed(observed_at), - }) - .await - .expect("persist existing quota"); - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports_with(store, Arc::new(TestOAuthPending::default())), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - let admin = bundle.admin_provider(); - let quota = admin - .quota(ProviderQuotaRequest { - account_id: account.id().clone(), - refresh: false, - rolling_usage: None, - }) - .await - .expect("read cached free quota"); - assert_eq!(quota.plan_type.as_deref(), Some("free")); - assert_eq!( - admin.plan_type_display(quota.plan_type.as_deref().expect("plan")), - "Free" - ); -} - -#[tokio::test] -async fn openai_admin_provider_projects_official_codex_quota_and_independent_buckets_with_chinese_labels() - { - let store = Arc::new(MemoryAccountStore::default()); - store - .seed_oauth_credential(ImportCodexOAuthCredential { - account_id: "acct_admin_canonical_quota".to_owned(), - name: "admin canonical quota".to_owned(), - secret: secret("admin-canonical-quota-access"), - verified_account: profile("chatgpt-admin-canonical-quota"), - next_refresh_at: Some(chrono::Utc::now() + chrono::Duration::minutes(30)), - enabled: true, - }) - .await; - let account = store - .account("acct_admin_canonical_quota") - .expect("stored account"); - let raw = json!({ - "active_limit": "premium", - "rate_limit": { - "primary_window": { - "used_percent": 91, - "reset_at": 1_900_000_000, - "limit_window_seconds": 2_592_000 - }, - "secondary_window": { - "used_percent": 88 - } - }, - "additional_rate_limits": [{ - "limit_name": "custom_codex_label", - "metered_feature": "codex", - "rate_limit": { - "primary_window": { - "used_percent": 2, - "reset_at": 1_900_000_000, - "limit_window_seconds": 2_592_000 - }, - "secondary_window": { - "used_percent": 0 - } - } - }, { - "limit_name": "code_review", - "metered_feature": "code_review", - "rate_limit": { - "primary_window": { - "used_percent": 12, - "reset_at": 1_900_000_000, - "limit_window_seconds": 604_800 - } - } - }, { - "limit_name": "GPT-5.3-Codex-Spark", - "metered_feature": "codex_bengalfox", - "rate_limit": { - "primary_window": { - "used_percent": 0, - "reset_at": 1_900_000_000, - "limit_window_seconds": 604_800 - } - } - }] - }); - let observed_at = SystemTime::now(); - store - .compare_and_swap_quota(QuotaObservation { - quota_pause: None, - expected_connection: None, - plan_type: None, - account_id: account.id().clone(), - expected_revision: account.revision(), - quota: OpaqueProviderData::new(raw.as_object().expect("quota object").clone()), - observed_at, - state: QuotaState::observed_unknown(observed_at), - }) - .await - .expect("persist quota"); - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports_with(Arc::clone(&store), Arc::new(TestOAuthPending::default())), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - - let quota = bundle - .admin_provider() - .quota(ProviderQuotaRequest { - account_id: account.id().clone(), - refresh: false, - rolling_usage: None, - }) - .await - .expect("cached quota"); - let monthly = quota - .windows - .iter() - .filter(|window| window.group == "monthly") - .collect::>(); - - assert_eq!(monthly.len(), 1); - assert!(monthly.iter().any(|window| { - window.label == "月额度" - && window.limit_id.as_deref() == Some("codex") - && window.used_percent == Some(91.0) - })); - assert!( - !quota - .windows - .iter() - .any(|window| window.key.starts_with("additional-0-codex")), - "the additional codex alias should not become a second display bucket" - ); - let secondary = quota - .windows - .iter() - .find(|window| { - window.limit_id.as_deref() == Some("codex") - && window.role == Some(ProviderQuotaWindowRole::Secondary) - }) - .expect("core secondary quota"); - assert_eq!(secondary.label, "次级额度"); - assert_eq!(secondary.used_percent, Some(88.0)); - let review = quota - .windows - .iter() - .find(|window| window.limit_id.as_deref() == Some("code_review")) - .expect("code review quota"); - assert_eq!(review.label, "周额度"); - assert_eq!(review.limit_name.as_deref(), Some("code_review")); - assert_eq!(review.role, Some(ProviderQuotaWindowRole::Primary)); - let spark = quota - .windows - .iter() - .find(|window| window.limit_id.as_deref() == Some("codex_bengalfox")) - .expect("Spark quota"); - assert_eq!( - ( - monthly[0].local_usage_attribution, - review.local_usage_attribution, - spark.local_usage_attribution, - ), - ( - QuotaLocalUsageAttribution::AccountWide, - QuotaLocalUsageAttribution::Unavailable, - QuotaLocalUsageAttribution::Unavailable, - ), - ); -} - -#[tokio::test] -async fn openai_admin_keeps_confirmed_exhaustion_separate_from_raw_usage_display() { - let store = Arc::new(MemoryAccountStore::default()); - let account_id = "acct_admin_confirmed_exhaustion"; - store - .seed_oauth_credential(ImportCodexOAuthCredential { - account_id: account_id.to_owned(), - name: "admin confirmed exhaustion".to_owned(), - secret: secret("admin-confirmed-exhaustion-access"), - verified_account: profile("chatgpt-admin-confirmed-exhaustion"), - next_refresh_at: Some(Utc::now() + chrono::Duration::minutes(30)), - enabled: true, - }) - .await; - let account = store.account(account_id).expect("stored account"); - let reset_at = 1_900_000_000_u64; - let observed_at = SystemTime::now(); - store - .compare_and_swap_quota(QuotaObservation { - quota_pause: None, - expected_connection: None, - plan_type: None, - account_id: account.id().clone(), - expected_revision: account.revision(), - quota: OpaqueProviderData::new( - json!({ - "rate_limit": { - "allowed": true, - "limit_reached": false, - "primary_window": {"used_percent": 86, "reset_at": reset_at} - } - }) - .as_object() - .expect("quota object") - .clone(), - ), - observed_at, - state: QuotaState::allowed(observed_at), - }) - .await - .expect("persist raw quota"); - store - .apply_quota_access(QuotaAccessChange { - account_id: account.id().clone(), - expected_revision: account.revision(), - state: QuotaState::exhausted(QuotaEvidence::UsageLimitReached, SystemTime::now(), None), - }) - .await - .expect("mark account exhausted"); - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports_with(Arc::clone(&store), Arc::new(TestOAuthPending::default())), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - - let exhausted = bundle - .admin_provider() - .quota(ProviderQuotaRequest { - account_id: account.id().clone(), - refresh: false, - rolling_usage: None, - }) - .await - .expect("project exhausted quota"); - - assert_eq!(exhausted.windows.len(), 1); - assert_eq!(exhausted.windows[0].used_percent, Some(86.0)); - let raw = store - .get_quotas(std::slice::from_ref(account.id())) - .await - .expect("read raw quota") - .pop() - .expect("raw quota"); - assert_eq!( - raw.quota.expose_to_provider()["rate_limit"]["primary_window"]["used_percent"], - 86 - ); - - store - .apply_quota_access(QuotaAccessChange { - account_id: account.id().clone(), - expected_revision: account.revision(), - state: QuotaState::allowed(SystemTime::now()), - }) - .await - .expect("recover account"); - let recovered = bundle - .admin_provider() - .quota(ProviderQuotaRequest { - account_id: account.id().clone(), - refresh: false, - rolling_usage: None, - }) - .await - .expect("project recovered quota"); - - assert_eq!(recovered.windows[0].used_percent, Some(86.0)); -} - -#[tokio::test] -async fn openai_admin_preserves_expired_window_usage_and_exhaustion_attribution() { - for exhausted in [false, true] { - let store = Arc::new(MemoryAccountStore::default()); - let account_id = "acct_admin_expired_window"; - store - .seed_oauth_credential(ImportCodexOAuthCredential { - account_id: account_id.to_owned(), - name: "admin expired window".to_owned(), - secret: secret("admin-expired-window-access"), - verified_account: profile("chatgpt-admin-expired-window"), - next_refresh_at: Some(Utc::now() + chrono::Duration::minutes(30)), - enabled: true, - }) - .await; - let account = store.account(account_id).expect("stored account"); - let past_reset_at = Utc::now().timestamp() - 60; - let observed_at = SystemTime::now() - Duration::from_secs(300); - let weekly_used = if exhausted { 100.0 } else { 74.0 }; - let state = if exhausted { - QuotaState::exhausted( - QuotaEvidence::ProviderDenied, - observed_at, - Some(SystemTime::UNIX_EPOCH + Duration::from_secs(past_reset_at as u64)), - ) - } else { - QuotaState::allowed(observed_at) - }; - store - .compare_and_swap_quota(QuotaObservation { - quota_pause: None, - expected_connection: None, - plan_type: None, - account_id: account.id().clone(), - expected_revision: account.revision(), - quota: OpaqueProviderData::new( - json!({ - "rate_limit": { - "allowed": !exhausted, - "limit_reached": exhausted, - "primary_window": { - "used_percent": 15, - "reset_at": past_reset_at + 18_000, - "limit_window_seconds": 18_000, - }, - "secondary_window": { - "used_percent": weekly_used, - "reset_at": past_reset_at, - "limit_window_seconds": 604_800, - } - } - }) - .as_object() - .expect("quota object") - .clone(), - ), - observed_at, - state, - }) - .await - .expect("persist raw quota"); - - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports_with(Arc::clone(&store), Arc::new(TestOAuthPending::default())), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - let mut projected = bundle - .admin_provider() - .quota(ProviderQuotaRequest { - account_id: account.id().clone(), - refresh: false, - rolling_usage: None, - }) - .await - .expect("project quota"); - let record = account_record(&store.account(account_id).expect("stored quota facts")); - let batch = bundle - .admin_provider() - .read_quotas(&[ProviderQuotaReadRequest { - account: &record, - rolling_usage: None, - }]) - .await; - assert_eq!(batch[0].as_ref().expect("batch quota"), &projected); - assert_eq!(projected.limit_reached, exhausted); - // 账号接口还会归一化耗尽展示;过期周窗口不能把触顶错误转移到短期窗口 - projected.apply_limit_reached_display(); - let primary = projected - .windows - .iter() - .find(|w| w.window_seconds == Some(18_000)) - .expect("primary"); - let weekly = projected - .windows - .iter() - .find(|w| w.window_seconds == Some(604_800)) - .expect("weekly"); - assert_eq!( - (primary.used_percent, primary.limit_reached), - (Some(15.0), false) - ); - assert_eq!( - (weekly.used_percent, weekly.limit_reached), - (Some(weekly_used), exhausted) - ); - assert_eq!( - weekly.reset_at.map(|reset| reset.timestamp()), - Some(past_reset_at) - ); - let raw = store - .get_quotas(std::slice::from_ref(account.id())) - .await - .expect("raw quota") - .pop() - .expect("observation"); - assert_eq!(raw.observed_at, observed_at); - assert_eq!( - raw.quota.expose_to_provider()["rate_limit"]["secondary_window"]["used_percent"], - weekly_used - ); - } -} - -#[tokio::test] -async fn openai_admin_provider_rejects_unprepared_mutations_before_store_commit() { - let store = Arc::new(MemoryAccountStore::default()); - store - .seed_oauth_credential(ImportCodexOAuthCredential { - account_id: "acct_admin_invalid".to_owned(), - name: "admin invalid".to_owned(), - secret: secret("admin-invalid-access"), - verified_account: profile("chatgpt-admin-invalid"), - next_refresh_at: Some(chrono::Utc::now() + chrono::Duration::minutes(30)), - enabled: true, - }) - .await; - let account = store.account("acct_admin_invalid").expect("stored account"); - let record = account_record(&account); - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports_with(store, Arc::new(TestOAuthPending::default())), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - let admin = bundle.admin_provider(); - let import_error = admin - .prepare_import(PrepareCredentialImport { - default_outbound_proxy: None, - document: ProviderDocument::new(OpaqueProviderData::new(Map::new())), - }) - .await - .expect_err("invalid import"); - assert_eq!(import_error.kind(), ProviderAdminErrorKind::Invalid); - let mut stale_record = record.clone(); - stale_record.name = "stale name".to_owned(); - stale_record.email = None; - stale_record.plan_type = None; - stale_record.credential_revision = Revision::new(99).expect("stale revision"); - stale_record.has_refresh_token = false; - stale_record.access_token_expires_at = None; - stale_record.next_refresh_at = None; - stale_record.enabled = false; - stale_record.credential_state = CredentialState::Banned; - let rotation_error = admin - .prepare_rotation(PrepareCredentialRotation { - account: stale_record, - provider_material: ProviderDocument::new(OpaqueProviderData::new(Map::new())), - }) - .await - .expect_err("invalid rotation"); - assert_eq!(rotation_error.kind(), ProviderAdminErrorKind::Invalid); - let mut missing = record; - missing.id = "acct_admin_missing".to_owned(); - let refresh_error = admin - .prepare_refresh(PrepareCredentialRefresh { account: missing }) - .await - .expect_err("missing refresh target"); - assert_eq!(refresh_error.kind(), ProviderAdminErrorKind::NotFound); -} - -#[tokio::test] -async fn initialized_provider_reports_a_safe_pat_format_error_before_network_access() { - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports(), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - let error = bundle - .admin_provider() - .prepare_import(PrepareCredentialImport { - default_outbound_proxy: None, - document: ProviderDocument::new(OpaqueProviderData::new(Map::from_iter([( - "accessToken".to_owned(), - json!("at-sensitive-token with whitespace"), - )]))), - }) - .await - .expect_err("PAT format must be checked by the initialized provider"); - assert_eq!(error.kind(), ProviderAdminErrorKind::Invalid); - assert_eq!( - error.public_message(), - Some("请输入完整 PAT,以 at- 开头且不含空白或控制字符") - ); - assert!(error.message().is_none()); - assert!(!format!("{error:?}").contains("sensitive-token")); -} - -#[tokio::test] -async fn openai_rotation_preserves_the_new_access_token_jwt_expiration() { - let store = Arc::new(MemoryAccountStore::default()); - store - .seed_oauth_credential(ImportCodexOAuthCredential { - account_id: "acct_admin_rotation_expiration".to_owned(), - name: "admin rotation expiration".to_owned(), - secret: secret("admin-rotation-access"), - verified_account: profile("chatgpt-admin-rotation-expiration"), - next_refresh_at: None, - enabled: true, - }) - .await; - let account = store - .account("acct_admin_rotation_expiration") - .expect("stored account"); - let record = account_record(&account); - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports_with(store, Arc::new(TestOAuthPending::default())), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .expect("OpenAI bundle"); - - let expires_at = Utc - .timestamp_opt(2_000_000_000, 0) - .single() - .expect("valid test timestamp"); - let payload = URL_SAFE_NO_PAD.encode( - serde_json::to_vec(&serde_json::json!({"exp": expires_at.timestamp()})) - .expect("test JWT payload"), - ); - let mut material = Map::new(); - material.insert( - "access_token".to_owned(), - Value::String(format!("unverified-header.{payload}.unverified-signature")), - ); - material.insert( - "refresh_token".to_owned(), - Value::String("admin-rotation-refresh".to_owned()), - ); - - let prepared = bundle - .admin_provider() - .prepare_rotation(PrepareCredentialRotation { - account: record, - provider_material: ProviderDocument::new(OpaqueProviderData::new(material)), - }) - .await - .expect("JWT rotation should be prepared"); - - assert_eq!(prepared.facts().access_token_expires_at, Some(expires_at)); -} - async fn reset_credit_admin( server: &MockServer, ) -> ( - provider_openai::ProviderBundle, + gateway_admin::ports::provider::ProviderBundle, ProviderAccountId, TestOpenAiConfig, ) { @@ -2144,13 +175,14 @@ pub(crate) async fn initialized_test_provider( ) -> Arc { initialized_test_bundle(accounts, base_url) .await - .core_provider() + .core + .clone() } pub(crate) async fn initialized_test_bundle( accounts: Arc, base_url: String, -) -> provider_openai::ProviderBundle { +) -> gateway_admin::ports::provider::ProviderBundle { let mut config = valid_config(); config.config.api.base_url = base_url; provider_openai::initialize( @@ -2616,7 +648,8 @@ mod errors { let server = MockServer::start().await; let provider = initialized_test_bundle(store, server.uri()) .await - .admin_provider(); + .admin + .clone(); let quota_error = provider .quota(ProviderQuotaRequest { account_id: account_id.clone(), @@ -2699,7 +732,7 @@ mod errors { .mount(&server) .await; let error = bundle - .admin_provider() + .admin .quota(ProviderQuotaRequest { account_id: before.id().clone(), refresh: true, @@ -2742,7 +775,7 @@ mod errors { .mount(&server) .await; let quota = bundle - .admin_provider() + .admin .quota(ProviderQuotaRequest { account_id: before.id().clone(), refresh: true, @@ -2776,7 +809,7 @@ mod errors { let (bundle, store, _config) = refresh_fixture(&server, false, true).await; let before = store.account("acct_refresh_error").unwrap(); let error = bundle - .admin_provider() + .admin .prepare_refresh(PrepareCredentialRefresh { account: account_record(&before), }) @@ -2871,7 +904,7 @@ mod errors { let (bundle, store, _config) = refresh_fixture(&server, false, true).await; let before = store.account("acct_refresh_error").unwrap(); let error = bundle - .admin_provider() + .admin .prepare_refresh(PrepareCredentialRefresh { account: account_record(&before), }) @@ -2917,7 +950,7 @@ mod errors { account.upstream_user_id = Some("previous-user".to_owned()); } let error = bundle - .admin_provider() + .admin .prepare_refresh(PrepareCredentialRefresh { account }) .await .expect_err("local refresh failure"); @@ -2944,11 +977,7 @@ mod errors { let command = || PrepareCredentialRefresh { account: account_record(&before), }; - let error = bundle - .admin_provider() - .prepare_refresh(command()) - .await - .unwrap_err(); + let error = bundle.admin.prepare_refresh(command()).await.unwrap_err(); assert_eq!(error.kind(), Kind::Ambiguous); assert_eq!( error.public_message(), @@ -2964,11 +993,7 @@ mod errors { ) .await .unwrap(); - let error = bundle - .admin_provider() - .prepare_refresh(command()) - .await - .unwrap_err(); + let error = bundle.admin.prepare_refresh(command()).await.unwrap_err(); assert_eq!(error.kind(), Kind::Ambiguous); assert_eq!( error.public_message(), @@ -2991,7 +1016,7 @@ mod errors { let (bundle, store, _config) = refresh_fixture(&server, false, true).await; let before = store.account("acct_refresh_error").unwrap(); let prepared = bundle - .admin_provider() + .admin .prepare_refresh(PrepareCredentialRefresh { account: account_record(&before), }) @@ -3005,7 +1030,7 @@ mod errors { busy: bool, has_token: bool, ) -> ( - provider_openai::ProviderBundle, + gateway_admin::ports::provider::ProviderBundle, Arc, TestOpenAiConfig, ) { @@ -3086,185 +1111,6 @@ mod errors { } } -#[tokio::test] -async fn api_key_admin_exposes_only_configuration_and_preserves_key_when_rotating_address() { - let store = Arc::new(MemoryAccountStore::default()); - store - .seed_api_key( - "acct_api_admin", - "https://first.example/v1".to_owned(), - provider_openai::credential::ResponsesTransport::Http, - ) - .await; - let account = store.account("acct_api_admin").unwrap(); - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports_with(Arc::clone(&store), Arc::new(TestOAuthPending::default())), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .unwrap(); - let admin = bundle.admin_provider(); - let configuration = admin - .account_configuration(account.id()) - .await - .unwrap() - .unwrap(); - let configuration = configuration.expose_to_provider().expose_to_provider(); - assert_eq!(configuration.len(), 3); - assert_eq!(configuration.get("protocol"), Some(&json!("responses"))); - assert_eq!( - configuration.get("base_url"), - Some(&json!("https://first.example/v1")) - ); - assert!(!configuration.contains_key("api_key")); - for base_url in [ - "https://second.example/root", - "http://10.0.0.7:8080/v1", - "http://[fd00::7]:8080/v1", - "http://relay:8080/v1", - ] { - let prepared = admin - .prepare_rotation(PrepareCredentialRotation { - account: account_record(&account), - provider_material: ProviderDocument::new(OpaqueProviderData::new( - json!({"base_url":base_url, "transport":"prefer_websocket"}) - .as_object() - .unwrap() - .clone(), - )), - }) - .await - .unwrap(); - let material = prepared - .facts() - .provider_material - .expose_to_provider() - .expose_to_provider(); - assert_eq!(material.get("api_key"), Some(&json!("sk-api-test-only"))); - assert_eq!(material.get("base_url"), Some(&json!(base_url))); - assert!(!prepared.facts().has_refresh_token); - assert_eq!(prepared.facts().account_id, *account.id()); - } - assert_eq!( - admin - .prepare_refresh(PrepareCredentialRefresh { - account: account_record(&account) - }) - .await - .unwrap_err() - .kind(), - ProviderAdminErrorKind::Unsupported - ); - assert_eq!( - admin.subscription(account.id()).await.unwrap_err().kind(), - ProviderAdminErrorKind::Unsupported - ); - assert_eq!( - admin.reset_credits(account.id()).await.unwrap_err().kind(), - ProviderAdminErrorKind::Unsupported - ); -} - -#[tokio::test] -async fn oauth_transport_settings_preserve_tokens_refresh_schedule_and_health() { - let store = Arc::new(MemoryAccountStore::default()); - store - .seed_oauth_credential(ImportCodexOAuthCredential { - account_id: "acct_oauth_transport".to_owned(), - name: "OAuth transport".to_owned(), - secret: secret("test-oauth-transport"), - verified_account: profile("chatgpt-oauth-transport"), - next_refresh_at: Some(Utc::now() + chrono::Duration::minutes(30)), - enabled: true, - }) - .await; - let account = store.account("acct_oauth_transport").unwrap(); - let current = store.load_current_credential(account.id()).await.unwrap(); - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports_with(Arc::clone(&store), Arc::new(TestOAuthPending::default())), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .unwrap(); - let admin = bundle.admin_provider(); - let configuration = admin - .account_configuration(account.id()) - .await - .unwrap() - .unwrap(); - assert_eq!( - configuration.expose_to_provider().expose_to_provider(), - json!({"transport":"prefer_websocket"}).as_object().unwrap() - ); - for transport in ["http", "prefer_websocket"] { - let prepared = admin - .prepare_rotation(PrepareCredentialRotation { - account: account_record(&account), - provider_material: ProviderDocument::new(OpaqueProviderData::new( - json!({"transport":transport}).as_object().unwrap().clone(), - )), - }) - .await - .unwrap(); - let facts = prepared.facts(); - let mut expected = current.credential.expose_to_provider().clone(); - if transport == "http" { - expected.insert("transport".to_owned(), json!(transport)); - } - assert_eq!( - facts - .provider_material - .expose_to_provider() - .expose_to_provider(), - &expected - ); - assert_eq!( - facts.next_refresh_at, - account.next_refresh_at().map(DateTime::::from) - ); - assert_eq!( - facts.access_token_expires_at, - account.access_token_expires_at().map(DateTime::::from) - ); - assert_eq!(facts.has_refresh_token, account.has_refresh_token()); - assert!(facts.preserve_profile && facts.preserve_credential_state); - assert!(facts.preserve_access_token_expiry); - } - for invalid in [ - json!({"transport":"invalid"}), - json!({"transport":"http", "base_url":"https://other.example"}), - json!({"transport":"http", "api_key":"test-key"}), - ] { - let error = admin - .prepare_rotation(PrepareCredentialRotation { - account: account_record(&account), - provider_material: ProviderDocument::new(OpaqueProviderData::new( - invalid.as_object().unwrap().clone(), - )), - }) - .await - .unwrap_err(); - assert_eq!(error.kind(), ProviderAdminErrorKind::Invalid); - } - store.set_oauth_transport( - "acct_oauth_transport", - provider_openai::credential::ResponsesTransport::Http, - ); - let configuration = admin - .account_configuration(account.id()) - .await - .unwrap() - .unwrap(); - assert_eq!( - configuration.expose_to_provider().expose_to_provider(), - json!({"transport":"http"}).as_object().unwrap() - ); -} - #[derive(Default)] struct RecordingDiagnostics(std::sync::Mutex>); #[async_trait::async_trait] @@ -3277,44 +1123,3 @@ impl gateway_core::diagnostics::OperationalDiagnostics for RecordingDiagnostics Ok(()) } } - -#[tokio::test] -async fn usage_quote_reuses_native_override_and_reports_incomplete_input() { - use gateway_admin::ports::provider::ProviderUsagePricingInput; - use gateway_core::metering::{ModelPriceOverride, Usage}; - let config = valid_config(); - let bundle = provider_openai::initialize( - config.config.clone(), - provider_ports(), - Arc::new(gateway_core::account::UpstreamInfoReader::default()), - ) - .await - .unwrap(); - let admin = bundle.admin_provider(); - let mut input = ProviderUsagePricingInput { - upstream_model_id: "gpt-6-sol".into(), - service_tier: None, - usage: Usage { - input_tokens: Some(1_000_000), - output_tokens: Some(100_000), - cached_input_tokens: Some(200_000), - cache_write_input_tokens: Some(0), - image_input_tokens: Some(0), - image_output_tokens: Some(0), - ..Default::default() - }, - }; - let custom:ModelPriceOverride=serde_json::from_value(json!({"multiplierBps":10000,"bands":{"standard":{"input":"2","output":"10","cacheRead":"0.5","cacheWrite":"2"},"long_standard":{"input":"2","output":"10","cacheRead":"0.5","cacheWrite":"2"}}})).unwrap(); - let price = admin - .evaluate_usage_pricing(&input, Some(&custom)) - .unwrap() - .unwrap(); - assert_eq!(price.total_amount().amount().canonical(), "2.7"); - input.usage.cached_input_tokens = None; - assert!( - admin - .evaluate_usage_pricing(&input, Some(&custom)) - .unwrap() - .is_none() - ); -} diff --git a/backend/crates/providers/openai/tests/admin/peer_info.rs b/backend/crates/providers/openai/tests/admin/peer_info.rs index 3f0331b75..acd988a58 100644 --- a/backend/crates/providers/openai/tests/admin/peer_info.rs +++ b/backend/crates/providers/openai/tests/admin/peer_info.rs @@ -381,7 +381,7 @@ async fn quota( Some(quota) => quota, None => bundle .provider - .admin_provider() + .admin .quota(ProviderQuotaRequest { account_id: id.clone(), refresh: false, @@ -1389,7 +1389,7 @@ async fn execute_peer_request( struct PeerFixture { leases: Arc, - provider: provider_openai::ProviderBundle, + provider: gateway_admin::ports::provider::ProviderBundle, peer: gateway_admin::PeerUpstreamBundle, cooldowns: Arc, } @@ -1400,7 +1400,7 @@ impl PeerFixture { } fn core_provider(&self) -> Arc { - self.provider.core_provider() + self.provider.core.clone() } fn take_worker_contributions(&mut self) -> Vec { @@ -1435,7 +1435,7 @@ async fn peer_fixture( .await .unwrap(); let registry = - gateway_admin::ports::provider::ProviderAdminRegistry::new([provider.admin_provider()]) + gateway_admin::ports::provider::ProviderAdminRegistry::new([provider.admin.clone()]) .unwrap(); let peer = gateway_admin::initialize_peer_upstream( accounts.clone(), diff --git a/backend/crates/providers/openai/tests/admin/provider.rs b/backend/crates/providers/openai/tests/admin/provider.rs new file mode 100644 index 000000000..434816cce --- /dev/null +++ b/backend/crates/providers/openai/tests/admin/provider.rs @@ -0,0 +1,2208 @@ +//! 验证 ProviderAdmin 端口的授权、账号和管理合同 + +use super::*; + +#[tokio::test] +async fn plan_display_uses_pro_short_names_and_codex_status_labels_for_other_known_plans() { + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports(), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .unwrap(); + let admin = bundle.admin.clone(); + for (raw, display) in [ + ("prolite", "ProLite"), + ("pro", "Pro"), + ("promax", "ProMax"), + ("free", "Free"), + ("go", "Go"), + ("plus", "Plus"), + ("team", "Business"), + ("self_serve_business_prolite", "Business Premium"), + ("self_serve_business_usage_based", "Business"), + ("business", "Enterprise"), + ("ent26", "Enterprise"), + ("enterprise", "Enterprise"), + ("hc", "Enterprise"), + ("enterprise_cbp_automation", "Enterprise (Automation)"), + ("enterprise_cbp_usage_based", "Enterprise"), + ("edu", "Edu"), + ("education", "Edu"), + ("edu_plus", "Edu Plus"), + ("edu_pro", "Edu Pro"), + ("sci", "Academic Researchers"), + ("sci_plus", "Academic Researchers Plus"), + ("SCI_PLUS", "Academic Researchers Plus"), + ("Future_Plan", "Future_Plan"), + ] { + assert_eq!(admin.plan_type_display(raw), display, "{raw}"); + } +} + +#[tokio::test] +async fn account_capabilities_distinguish_oauth_from_api_key_and_unknown_credentials() { + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports(), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .unwrap(); + let provider = bundle.admin.clone(); + let id = ProviderAccountId::new("acct_capabilities").unwrap(); + let oauth = provider.account_capabilities(&id, "oauth"); + assert!( + oauth.quota + && oauth.quota_refresh + && oauth.profile + && oauth.subscription + && oauth.avatar + && oauth.reset_credits + && oauth.consume_reset_credit + ); + assert!( + oauth.credential_refresh + && oauth.reauthorize + && oauth.credential_export + && oauth.model_catalog_download + ); + assert_eq!( + provider.account_capabilities(&id, "api_key"), + gateway_admin::model::accounts::ProviderAccountCapabilities { + credential_export: true, + ..Default::default() + } + ); + assert_eq!( + provider.account_capabilities(&id, "unknown"), + Default::default() + ); +} + +#[tokio::test] +async fn custom_identity_preview_and_dashboard_share_the_exact_request_profile() { + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports(), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .unwrap(); + let provider = bundle.admin.clone(); + let user_agent = + "codex_exec/0.156.1 (Ubuntu 24.4.0; x86_64) xterm-256color (codex_exec; 0.156.1)"; + let configuration = OpaqueProviderData::new( + json!({"mode":"custom", "userAgent":user_agent}) + .as_object() + .unwrap() + .clone(), + ); + let preview = provider.preview_client_profile(&configuration).unwrap(); + let dashboard = provider.configured_wire_profile(&configuration).unwrap(); + assert_eq!(preview.expose_to_provider()["userAgent"], user_agent); + assert_eq!(dashboard.user_agent, user_agent); + assert_eq!(dashboard.product, "codex_exec"); + assert_eq!(dashboard.version, "0.156.1"); + assert!(dashboard.verified_at.is_none()); + assert!(dashboard.release.is_none()); + assert_ne!( + provider.dashboard_wire_profile().unwrap().user_agent, + user_agent + ); +} + +#[tokio::test] +async fn installation_seed_is_optional_and_validated_only_for_key_profiles() { + let bundle = provider_openai::initialize( + valid_config().config, + provider_ports(), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .unwrap(); + let provider = bundle.admin.clone(); + let id = "3B11BC82-C666-417D-B9FF-2A34FD040385"; + for (value, valid) in [ + (json!(id), true), + (json!(null), true), + (json!(""), true), + (json!(id.replace('-', "")), false), + (json!("bad"), false), + (json!(42), false), + ] { + let configuration = OpaqueProviderData::new( + json!({ + "mode": "custom", "userAgent": "codex-tui/1.0.0", "installationSeed": value + }) + .as_object() + .unwrap() + .clone(), + ); + let preview = provider.preview_key_client_profile(&configuration, None); + assert_eq!(preview.is_ok(), valid); + if value == id { + assert_eq!( + preview.unwrap().expose_to_provider()["configuration"]["installationSeed"], + id.to_lowercase() + ); + assert!(provider.preview_client_profile(&configuration).is_err()); + } + } + let doc = + |value: serde_json::Value| OpaqueProviderData::new(value.as_object().unwrap().clone()); + let global = doc(json!({"mode": "custom", "userAgent": "codex-tui/2.0.0"})); + let key = doc(json!({"inherit":{"installationSeed":id}})); + let preview = provider + .preview_key_client_profile(&key, Some(&global)) + .unwrap() + .into_inner(); + assert_eq!(preview["userAgent"], "codex-tui/2.0.0"); + assert_eq!( + preview["configuration"]["installationSeed"], + id.to_lowercase() + ); + assert!(provider.preview_client_profile(&key).is_err()); + assert!( + provider + .preview_key_client_profile( + &doc(json!({"inherit":{"userAgent":"other"}})), + Some(&global) + ) + .is_err() + ); +} + +#[tokio::test] +async fn openai_bundle_exposes_one_core_provider_and_drains_worker_contributions_once() { + let config = valid_config(); + let mut bundle = provider_openai::initialize( + config.config.clone(), + provider_ports(), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + + assert_eq!(bundle.core.clone().name(), "openai"); + assert_eq!(bundle.admin.provider_kind().as_str(), "openai"); + let contributions = std::mem::take(&mut bundle.workers); + assert_eq!(contributions.len(), 8); + assert!( + contributions + .iter() + .any(|item| item.kind() == WorkerKind::OAuthRefresh) + ); + assert!( + contributions + .iter() + .any(|item| item.kind() == WorkerKind::QuotaCatalogHealth) + ); + let release_worker = contributions + .iter() + .find_map(|contribution| match contribution { + WorkerContribution::Registration(registration) + if registration.id.owner() == "openai-desktop-release" => + { + Some(registration) + } + WorkerContribution::Registration(_) | WorkerContribution::Disabled { .. } => None, + }) + .expect("Desktop release worker"); + assert_eq!(release_worker.id.kind(), WorkerKind::QuotaCatalogHealth); + let WorkerRunnable::Scheduled { schedule, .. } = &release_worker.runnable else { + panic!("Desktop release worker must be scheduled"); + }; + assert_eq!(schedule.interval(), APPCAST_POLL_INTERVAL); + for (owner, interval) in [ + ("openai-cli-release", APPCAST_POLL_INTERVAL), + ("openai-platform-desktop-release", APPCAST_POLL_INTERVAL), + ("openai", Duration::from_secs(30)), + ("openai-account-warmup", Duration::from_secs(30)), + ( + "openai-model-catalog", + config.config.quota_refresh_policy().interval(), + ), + ] { + let schedule = contributions + .iter() + .find_map(|contribution| match contribution { + WorkerContribution::Registration(registration) + if registration.id.kind() == WorkerKind::QuotaCatalogHealth + && registration.id.owner() == owner => + { + match ®istration.runnable { + WorkerRunnable::Scheduled { schedule, .. } => Some(schedule), + WorkerRunnable::Daemon { .. } => None, + } + } + _ => None, + }) + .expect("quota/catalog scheduled worker"); + assert_eq!(schedule.interval(), interval, "{owner}"); + } + assert!(contributions.iter().any(|contribution| { + matches!( + contribution, + WorkerContribution::Registration(registration) + if registration.id.owner() == "openai-model-etag" + && matches!(®istration.runnable, WorkerRunnable::Daemon { .. }) + ) + })); + assert!(std::mem::take(&mut bundle.workers).is_empty()); +} + +#[tokio::test] +async fn quota_forecast_observation_reuses_protocol_parser_and_keeps_window_identity() { + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports(), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .unwrap(); + let provider = bundle.admin.clone(); + let mut window = gateway_admin::model::provider_credentials::ProviderQuotaWindow { + upstream: None, + key: "codex:604800s".to_owned(), + group: "shortTerm".to_owned(), + label: "周额度".to_owned(), + limit_id: Some("codex".to_owned()), + limit_name: None, + role: Some(ProviderQuotaWindowRole::Primary), + local_usage_attribution: QuotaLocalUsageAttribution::AccountWide, + window_seconds: Some(604_800), + used_percent: Some(50.0), + reset_at: None, + limit_reached: false, + local_usage: None, + provider_data: None, + }; + let document = ProviderDocument::new(OpaqueProviderData::new( + json!({ + "requestSummary": {"ignored": true}, + "rateLimitHeaders": [ + ["x-codex-primary-used-percent", "32.5"], + ["x-codex-primary-window-minutes", "10080"], + ["x-codex-primary-reset-at", "1789805447"], + ["x-codex-secondary-used-percent", "4"], + ["x-codex-secondary-window-minutes", "300"], + ["x-codex-secondary-reset-at", "1789218647"], + ["x-codex-plan-type", "pro"] + ] + }) + .as_object() + .unwrap() + .clone(), + )); + let history = provider.quota_history_parser().unwrap(); + let short = history(&document, "codex:18000s").unwrap(); + assert_eq!(short.used_percent, 4.0); + assert_eq!(short.reset_at.unwrap().timestamp(), 1_789_218_647); + assert!(history(&document, "other:18000s").is_none()); + let named = ProviderDocument::new(OpaqueProviderData::new( + json!({ + "rateLimitHeaders": [ + ["x-codex-primary-used-percent","23"],["x-codex-primary-window-minutes","1"], + ["x-feature-primary-used-percent","23"],["x-feature-primary-window-minutes","1"], + ["x-feature-secondary-used-percent","56"],["x-feature-secondary-window-minutes","1"] + ] + }) + .as_object() + .unwrap() + .clone(), + )); + assert!(history(&named, "codex:60s").is_none()); + assert!(history(&named, "feature:60s").is_none()); + let primary = history(&named, "feature:60s:primary_window").unwrap(); + assert_eq!((primary.used_percent, primary.reset_at), (23.0, None)); + assert_eq!( + history(&named, "feature:60s:secondary_window") + .unwrap() + .used_percent, + 56.0 + ); + let observed = provider + .quota_forecast_observation(&document, &window) + .unwrap(); + assert_eq!(observed.used_percent, 32.5); + assert_eq!(observed.plan_type.as_deref(), Some("pro")); + assert_eq!(observed.reset_at.timestamp(), 1_789_805_447); + window.role = Some(ProviderQuotaWindowRole::Secondary); + assert!( + provider + .quota_forecast_observation(&document, &window) + .is_none() + ); + window.role = Some(ProviderQuotaWindowRole::Primary); + window.limit_id = Some("other_bucket".to_owned()); + assert!( + provider + .quota_forecast_observation(&document, &window) + .is_none() + ); + let malformed = ProviderDocument::new(OpaqueProviderData::new( + json!({ + "rateLimitHeaders": "not-a-header-list" + }) + .as_object() + .unwrap() + .clone(), + )); + assert!( + provider + .quota_forecast_observation(&malformed, &window) + .is_none() + ); +} + +#[tokio::test] +async fn initialized_provider_keeps_thread_spawn_transport_conversations_distinct() { + let account_id = "acct_initialized_thread_spawn"; + let store = Arc::new(MemoryAccountStore::default()); + store + .seed_oauth_credential(ImportCodexOAuthCredential { + account_id: account_id.to_owned(), + name: account_id.to_owned(), + secret: secret("at-initialized-thread-spawn"), + verified_account: profile("chatgpt-initialized-thread-spawn"), + next_refresh_at: Some(Utc::now() + chrono::Duration::minutes(30)), + enabled: true, + }) + .await; + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/codex/responses")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("content-type", "text/event-stream") + .set_body_string(COMPLETED_SESSION_SSE), + ) + .expect(2) + .mount(&server) + .await; + let mut config = valid_config(); + config.config.api.base_url = server.uri(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports_with(store, Arc::new(TestOAuthPending::default())), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("initialized OpenAI provider"); + let provider = bundle.core.clone(); + let root = Operation::Generate(GenerateRequest::from_protocol_payload( + ProtocolPayload::json_object("openai", json!({"model":"gpt-5.4","input":"root","session_id":"parent-session","thread_id":"parent-session"}).as_object().unwrap().clone()).unwrap() + .with_context(Map::from_iter([("use_websocket".to_owned(), json!(false))])), + )); + drop( + provider + .clone() + .execute( + initialized_provider_request(root, account_id), + initialized_attempt_context("req_initialized_root", account_id), + ) + .await + .unwrap(), + ); + let thread_spawn = r#"{"subagent_kind":"thread_spawn"}"#; + let mut conversation_ids = Vec::new(); + + for (request_id, thread_id) in [ + ("req_initialized_thread_spawn_first", "child-one"), + ("req_initialized_thread_spawn_second", "child-two"), + ] { + let payload = ProtocolPayload::json_object( + "openai", + Map::from_iter([ + ("model".to_owned(), json!("gpt-5.4")), + ("input".to_owned(), json!("child task")), + ("session_id".to_owned(), json!("parent-session")), + ("thread_id".to_owned(), json!(thread_id)), + ("turnMetadata".to_owned(), json!(thread_spawn)), + ]), + ) + .expect("OpenAI payload") + .with_context(Map::from_iter([("use_websocket".to_owned(), json!(false))])); + let operation = Operation::Generate(GenerateRequest::from_protocol_payload(payload)); + let mut stream = Arc::clone(&provider) + .execute( + initialized_provider_request(operation, account_id), + initialized_attempt_context(request_id, account_id), + ) + .await + .expect("prepare child provider stream"); + let mut conversation_id = None; + while let Some(event) = stream.next().await { + let event = event.expect("child provider response"); + if let Some(update) = event.session_update() { + conversation_id = update + .payload() + .get("conversation_id") + .and_then(Value::as_str) + .map(ToOwned::to_owned); + } + } + conversation_ids.push(conversation_id.expect("child transport conversation id")); + } + + assert_ne!(conversation_ids[0], conversation_ids[1]); +} + +#[tokio::test] +async fn copying_builtin_prices_keeps_cache_read_and_write_fallback_costs() { + use crate::billing::{ + OpenAiBillingUsage, openai_billing_breakdown, openai_billing_breakdown_with_override, + }; + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports(), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .unwrap(); + let prices = bundle.admin.pricing_catalog(); + for model in [ + "gpt-4", + "gpt-4o", + "gpt-6.2-astra", + "gpt-6.2-sol", + "gpt-6-astra", + "gpt-6.1-sol", + "gpt-6.1-terra", + "gpt-6-sol", + "gpt-6-luna", + ] { + let ultrafast_supported = matches!( + model, + "gpt-6.2-astra" | "gpt-6.2-sol" | "gpt-6-astra" | "gpt-6.1-sol" + ); + for band in ["ultrafast", "long_ultrafast"] { + assert_eq!(prices[model].bands.contains_key(band), ultrafast_supported); + } + for tier in [None, Some("ultrafast")] { + if tier.is_some() && !ultrafast_supported { + continue; + } + for input in [100, 272_001] { + let usage = OpenAiBillingUsage::new(input, 10, 20, 15); + let inherited = openai_billing_breakdown(model, usage, tier).unwrap(); + let copied = openai_billing_breakdown_with_override( + model, + usage, + tier, + Some(&prices[model]), + ) + .unwrap(); + assert_eq!( + inherited.total_amount(), + copied.total_amount(), + "{model} {tier:?} {input}" + ); + } + } + } +} + +#[tokio::test] +async fn openai_admin_provider_exposes_live_wire_profile_and_validated_billing() { + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports(), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + let admin = bundle.admin.clone(); + let baseline = admin.dashboard_wire_profile().expect("official baseline"); + assert_eq!( + baseline.release.as_ref().map(|release| release.status), + Some(DesktopReleaseStatus::Unchecked) + ); + let selection = OpaqueProviderData::new(json!({ + "client": "desktop", "platform": "macos", "versionMode": "fixed", + "codexVersion": "0.102.0", "desktopVersion": "1.2026.190", "desktopBuild": "19012345678", + "osVersion": "15.5.0", "arch": "arm64", "terminal": "xterm-256color" + }).as_object().unwrap().clone()); + let profile = admin + .configured_wire_profile(&selection) + .expect("managed fixed profile"); + assert_eq!(profile.version, "0.102.0"); + assert_eq!(profile.build, None); + assert_eq!(profile.target.os_type, "Mac OS"); + assert_eq!(profile.target.os_version, "15.5.0"); + assert_eq!( + profile.user_agent, + "Codex Desktop/0.102.0 (Mac OS 15.5.0; arm64) xterm-256color (Codex Desktop; 1.2026.190)" + ); + assert_eq!( + profile + .attributes + .iter() + .find(|attribute| attribute.key == "client_identifier") + .map(|attribute| attribute.value.as_str()), + Some("Codex Desktop; 1.2026.190") + ); + assert_eq!( + profile + .attributes + .iter() + .find(|attribute| attribute.key == "version_policy") + .map(|attribute| attribute.value.as_str()), + Some("fixed") + ); + assert!(profile.release.is_none()); + let billing = admin + .calculated_billing(&ProviderBillingInput { + upstream_model_id: "gpt-4o".to_owned(), + service_tier: None, + input_tokens: Some(1_000_000), + output_tokens: Some(0), + cached_input_tokens: Some(0), + cache_write_input_tokens: Some(0), + total: CurrencyCost { + currency: "USD".to_owned(), + amount: "2.5".parse().expect("amount"), + }, + }) + .expect("billing") + .expect("known pricing"); + assert_eq!(billing.total_amount.amount.as_str(), "2.5"); + assert_eq!(billing.input_price_per_million.amount.as_str(), "2.5"); + + let fast_billing = admin + .calculated_billing(&ProviderBillingInput { + upstream_model_id: "gpt-4o".to_owned(), + service_tier: Some("priority".to_owned()), + input_tokens: Some(1_000_000), + output_tokens: Some(0), + cached_input_tokens: Some(0), + cache_write_input_tokens: Some(0), + total: CurrencyCost { + currency: "USD".to_owned(), + amount: "4.25".parse().expect("fast amount"), + }, + }) + .expect("fast billing") + .expect("known fast pricing"); + assert_eq!(fast_billing.service_tier.as_deref(), Some("priority")); + assert_eq!(fast_billing.multiplier_percent, 170); + assert_eq!(fast_billing.standard_amount.amount.as_str(), "2.5"); + assert_eq!(fast_billing.total_amount.amount.as_str(), "4.25"); +} + +#[tokio::test] +async fn openai_legacy_billing_should_not_infer_long_context_flag() { + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports(), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + let billing = bundle + .admin + .calculated_billing(&ProviderBillingInput { + upstream_model_id: "gpt-5.4".to_owned(), + service_tier: None, + input_tokens: Some(300_000), + output_tokens: Some(0), + cached_input_tokens: Some(0), + cache_write_input_tokens: Some(0), + total: CurrencyCost { + currency: "USD".to_owned(), + amount: "1.5".parse().expect("stored total"), + }, + }) + .expect("legacy billing") + .expect("matching billing breakdown"); + + assert_eq!(billing.total_amount.amount.as_str(), "1.5"); + assert_eq!(billing.input_price_per_million.amount.as_str(), "5"); + assert!(!billing.long_context_billing_applied); +} + +#[tokio::test] +async fn reset_credit_success_with_invalid_body_should_remain_an_unknown_consume_result() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/codex/rate-limit-reset-credits/consume")) + .respond_with(ResponseTemplate::new(200).set_body_raw("{}", "application/json")) + .expect(1) + .mount(&server) + .await; + let (bundle, account_id, _config) = reset_credit_admin(&server).await; + + let error = bundle + .admin + .consume_reset_credit(reset_credit_command(account_id)) + .await + .expect_err("invalid success body must be ambiguous"); + + assert_eq!(error.kind(), ProviderAdminErrorKind::Ambiguous); + assert_eq!( + error.message(), + Some( + "OpenAI reset-credit consume result is unknown; refresh the credit list before retrying" + ) + ); +} + +#[tokio::test] +async fn reset_credit_explicit_http_rejection_should_preserve_the_raw_body() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/codex/rate-limit-reset-credits/consume")) + .respond_with(ResponseTemplate::new(409).set_body_raw( + r#"{"code":"nothing_to_reset","detail":"window is fresh"}"#, + "application/json", + )) + .expect(1) + .mount(&server) + .await; + let (bundle, account_id, _config) = reset_credit_admin(&server).await; + + let error = bundle + .admin + .consume_reset_credit(reset_credit_command(account_id)) + .await + .expect_err("explicit upstream rejection"); + + assert_eq!(error.kind(), ProviderAdminErrorKind::BadGateway); + assert_eq!( + error.message(), + Some( + r#"OpenAI reset-credit upstream returned HTTP 409: {"code":"nothing_to_reset","detail":"window is fresh"}"# + ) + ); + let debug = format!("{error:?}"); + assert!(debug.contains("")); + assert!(!debug.contains("window is fresh")); +} + +#[tokio::test] +async fn openai_core_provider_projects_private_request_observation_without_execution() { + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports(), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + let payload = ProtocolPayload::json_object( + "openai", + Map::from_iter([ + ("model".to_owned(), json!("gpt-5.4")), + ("input".to_owned(), json!("summarize")), + ("session_id".to_owned(), json!("observation-session")), + ("previous_response_id".to_owned(), json!("resp_previous")), + ]), + ) + .expect("OpenAI payload"); + let operation = Operation::Generate(GenerateRequest::from_protocol_payload(payload)); + + let client_key_id = ClientApiKeyId::new("key_openai_admin_observation").expect("client key"); + let observation = bundle + .core + .clone() + .request_observation(&operation, &client_key_id); + + assert!(observation.continuation.requested); + assert!(observation.continuation.previous_response_id_hash.is_some()); + assert!(observation.continuation.affinity_hash.is_some()); +} + +#[tokio::test] +async fn openai_admin_provider_persists_the_full_pending_envelope_and_binds_owner() { + let pending = Arc::new(TestOAuthPending::default()); + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports_with( + Arc::new(MemoryAccountStore::default()), + Arc::clone(&pending), + ), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + let start_context = MutationContext { + actor: MutationActor::AdminSession { + admin_user_id: "admin-owner".to_owned(), + }, + request_id: "request-start".to_owned(), + }; + let started = bundle + .admin + .start_authorization(PendingAuthorizationMutation::new( + ProviderKind::new("openai").expect("provider"), + AuthorizationMutationTarget::Create { + name: "OAuth account".to_owned(), + }, + AuthorizationOwnerBinding::from_context(&start_context), + )) + .await + .expect("start authorization"); + { + let values = pending.values.lock().expect("OAuth pending"); + let (_, payload, _, _) = values.values().next().expect("stored pending"); + let mutation = payload + .expose_to_provider() + .get("mutation") + .and_then(Value::as_object) + .expect("pending mutation"); + assert!( + payload + .expose_to_provider() + .get("installation_id") + .and_then(Value::as_str) + .and_then(|value| uuid::Uuid::parse_str(value).ok()) + .is_some_and(|value| value.get_version_num() == 4) + ); + assert_eq!( + mutation.get("schema_version").and_then(Value::as_u64), + Some(3) + ); + assert_eq!(mutation["target"]["kind"], "create"); + assert_eq!(mutation["target"]["name"], "OAuth account"); + assert_eq!( + mutation.get("started_request_id").and_then(Value::as_str), + Some("request-start") + ); + } + let error = bundle + .admin + .complete_authorization(CompleteAuthorization { + settings: None, + context: MutationContext { + actor: MutationActor::AdminSession { + admin_user_id: "different-owner".to_owned(), + }, + request_id: "request-complete".to_owned(), + }, + flow_id: started.flow_id, + callback_url: "http://127.0.0.1:1455/auth/callback?code=unused&state=unused".to_owned(), + }) + .await + .expect_err("wrong owner"); + assert_eq!(error.kind(), ProviderAdminErrorKind::NotFound); + assert_eq!(pending.values.lock().expect("OAuth pending").len(), 1); +} + +#[tokio::test] +async fn oauth_connection_failures_preserve_safe_diagnostics_and_release_the_claim() { + use std::error::Error as _; + use tokio::io::AsyncReadExt as _; + + for timed_out in [false, true] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let proxy_task = if timed_out { + Some(tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = [0; 4096]; + let count = socket.read(&mut request).await.unwrap(); + assert!(request[..count].starts_with(b"CONNECT ")); + std::future::pending::<()>().await; + })) + } else { + drop(listener); + None + }; + let pending = Arc::new(TestOAuthPending::default()); + let mut config = valid_config(); + config.config.auth.oauth_token_endpoint = + "https://oauth.example.invalid/oauth/token?PRIVATE_URL_MARKER".to_owned(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports_with(Arc::new(MemoryAccountStore::default()), pending.clone()), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .unwrap(); + let context = MutationContext { + actor: MutationActor::System, + request_id: "oauth-connection-failure".to_owned(), + }; + let started = bundle + .admin + .start_authorization( + PendingAuthorizationMutation::new( + ProviderKind::new("openai").unwrap(), + AuthorizationMutationTarget::Create { + name: String::new(), + }, + AuthorizationOwnerBinding::from_context(&context), + ) + .with_outbound_proxy(Some( + gateway_core::account::OutboundProxy::parse(&format!( + "http://proxy-user:PRIVATE_PROXY_PASSWORD@{address}" + )) + .unwrap(), + )), + ) + .await + .unwrap(); + let state = { + let values = pending.values.lock().unwrap(); + let (_, payload, _, _) = values.values().next().unwrap(); + payload.expose_to_provider()["state"] + .as_str() + .unwrap() + .to_owned() + }; + let error = bundle + .admin + .complete_authorization(CompleteAuthorization { + settings: None, + context, + flow_id: started.flow_id, + callback_url: format!( + "http://127.0.0.1:1455/auth/callback?code=PRIVATE_CODE&state={state}" + ), + }) + .await + .unwrap_err(); + if let Some(task) = proxy_task { + task.abort(); + assert!(task.await.unwrap_err().is_cancelled()); + } + assert_eq!(error.kind(), ProviderAdminErrorKind::Unavailable); + assert_eq!( + error.public_message(), + Some(if timed_out { + "连接授权服务超时,请检查出站连接" + } else { + "无法连接授权服务,请检查出站连接" + }), + ); + let mut source = error.source(); + let transport = loop { + let cause = source.expect("transport cause must reach the admin boundary"); + if let Some(transport) = cause.downcast_ref::() { + break transport; + } + source = cause.source(); + }; + assert!(transport.is_connect()); + assert_eq!(transport.is_timeout(), timed_out); + assert!(transport.url().is_none()); + assert!(!format!("{error:?} {error}").contains("PRIVATE_")); + let details = + gateway_core::error::ErrorDetails::capture(Some(&error.into()), None, true).unwrap(); + assert!(!details.as_str().contains("PRIVATE_")); + let values = pending.values.lock().unwrap(); + assert!(values.values().next().unwrap().3.is_none()); + } +} + +#[tokio::test] +async fn openai_reauthorization_pending_payload_reuses_the_account_installation_id() { + let accounts = Arc::new(MemoryAccountStore::default()); + accounts + .seed_oauth_credential(ImportCodexOAuthCredential { + account_id: "acct_pending_reauth".to_owned(), + name: "pending reauthorization".to_owned(), + secret: secret("pending-reauth-access"), + verified_account: profile("chatgpt-pending-reauth"), + next_refresh_at: Some(Utc::now() + chrono::Duration::minutes(30)), + enabled: true, + }) + .await; + let account_id = ProviderAccountId::new("acct_pending_reauth").expect("account id"); + let existing = accounts + .load_current_credential(&account_id) + .await + .expect("seeded credential"); + let expected_installation_id = CodexCredentialCodec::decode(&existing.credential) + .expect("decode seeded credential") + .installation_id; + let pending = Arc::new(TestOAuthPending::default()); + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports_with(accounts, Arc::clone(&pending)), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + let context = MutationContext { + actor: MutationActor::AdminApiKey, + request_id: "request-pending-reauth".to_owned(), + }; + + bundle + .admin + .start_authorization(PendingAuthorizationMutation::new( + ProviderKind::new("openai").expect("provider"), + AuthorizationMutationTarget::Reauthorize { account_id }, + AuthorizationOwnerBinding::from_context(&context), + )) + .await + .expect("start reauthorization"); + + let values = pending.values.lock().expect("OAuth pending"); + let (_, payload, _, _) = values.values().next().expect("stored pending"); + let document = payload.expose_to_provider(); + let mutation = document + .get("mutation") + .and_then(Value::as_object) + .expect("pending mutation"); + let target = mutation + .get("target") + .and_then(Value::as_object) + .expect("pending target"); + assert_eq!( + mutation.get("schema_version").and_then(Value::as_u64), + Some(3) + ); + assert_eq!( + document + .get("reauthorization_account_id") + .and_then(Value::as_str), + Some("acct_pending_reauth") + ); + assert_eq!( + document.get("installation_id").and_then(Value::as_str), + Some(expected_installation_id.as_str()) + ); + assert_eq!( + target.get("kind").and_then(Value::as_str), + Some("reauthorize") + ); + assert_eq!( + target.get("account_id").and_then(Value::as_str), + Some("acct_pending_reauth") + ); +} + +#[tokio::test] +async fn openai_admin_reads_a_full_quota_page_in_one_store_call() { + let store = Arc::new(MemoryAccountStore::default()); + let mut records = Vec::new(); + for index in 0..200 { + let id = format!("acct_admin_quota_page_{index}"); + store + .seed_oauth_credential(ImportCodexOAuthCredential { + account_id: id.clone(), + name: id.clone(), + secret: secret("synthetic-quota-page-access"), + verified_account: profile(&format!("chatgpt-quota-page-{index}")), + next_refresh_at: None, + enabled: false, + }) + .await; + records.push(account_record(&store.account(&id).expect("stored account"))); + } + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports_with(Arc::clone(&store), Arc::new(TestOAuthPending::default())), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + let requests = records + .iter() + .map(|account| ProviderQuotaReadRequest { + account, + rolling_usage: None, + }) + .collect::>(); + let account_reads = store.account_reads(); + let credential_loads = store.credential_loads(); + let quota_reads = store.quota_reads(); + + let results = bundle.admin.read_quotas(&requests).await; + + assert_eq!(results.len(), records.len()); + assert!( + results + .into_iter() + .all(|result| result.expect("cached quota").windows.is_empty()) + ); + assert_eq!(store.quota_reads() - quota_reads, 1); + assert_eq!(store.account_reads(), account_reads); + assert_eq!(store.credential_loads(), credential_loads); +} + +#[tokio::test] +async fn openai_admin_batch_quota_isolates_stale_and_invalid_observations() { + let store = Arc::new(MemoryAccountStore::default()); + let mut records = Vec::new(); + for suffix in ["healthy", "stale", "invalid", "missing"] { + let id = format!("acct_admin_quota_batch_{suffix}"); + store + .seed_oauth_credential(ImportCodexOAuthCredential { + account_id: id.clone(), + name: id.clone(), + secret: secret("synthetic-quota-batch-access"), + verified_account: profile(&format!("chatgpt-quota-batch-{suffix}")), + next_refresh_at: None, + enabled: false, + }) + .await; + let account = store.account(&id).expect("stored account"); + if suffix != "missing" { + let used = if suffix == "invalid" { + json!("invalid") + } else { + json!(25) + }; + store + .compare_and_swap_quota(QuotaObservation { + quota_pause: None, + expected_connection: None, + account_id: account.id().clone(), + expected_revision: account.revision(), + observed_at: SystemTime::now(), + plan_type: None, + state: QuotaState::allowed(SystemTime::now()), + quota: OpaqueProviderData::new( + json!({ + "rate_limit": { "primary_window": { + "used_percent": used, + "reset_at": Utc::now().timestamp() + 3600, + "limit_window_seconds": 18000 + }} + }) + .as_object() + .expect("quota object") + .clone(), + ), + }) + .await + .expect("store quota"); + } + let mut record = account_record(&store.account(&id).expect("stored quota facts")); + if suffix == "stale" { + record.credential_revision = + Revision::new(record.credential_revision.get() + 1).unwrap(); + } + records.push(record); + } + store + .seed_api_key( + "acct_admin_quota_batch_api_key", + "http://127.0.0.1:9".to_owned(), + provider_openai::credential::ResponsesTransport::Http, + ) + .await; + records.push(account_record( + &store.account("acct_admin_quota_batch_api_key").unwrap(), + )); + let mut foreign = records[0].clone(); + foreign.provider_kind = ProviderKind::new("xai").unwrap(); + records.push(foreign); + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports_with(Arc::clone(&store), Arc::new(TestOAuthPending::default())), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + let requests = records + .iter() + .map(|account| ProviderQuotaReadRequest { + account, + rolling_usage: None, + }) + .collect::>(); + let quota_reads = store.quota_reads(); + let account_reads = store.account_reads(); + + let results = bundle.admin.read_quotas(&requests).await; + + assert_eq!(results.len(), 6); + assert_eq!( + results[0].as_ref().unwrap().windows[0].used_percent, + Some(25.0) + ); + assert_eq!( + results[1].as_ref().unwrap_err().kind(), + ProviderAdminErrorKind::Conflict + ); + assert_eq!( + results[2].as_ref().unwrap_err().kind(), + ProviderAdminErrorKind::Invalid + ); + assert!(results[3].as_ref().unwrap().windows.is_empty()); + assert!(results[4].as_ref().unwrap().windows.is_empty()); + assert_eq!( + results[5].as_ref().unwrap_err().kind(), + ProviderAdminErrorKind::NotFound + ); + assert_eq!(store.quota_reads() - quota_reads, 1); + assert_eq!(store.account_reads(), account_reads); + + let api_only = bundle.admin.read_quotas(&requests[4..5]).await; + assert!(api_only[0].as_ref().unwrap().windows.is_empty()); + assert!(bundle.admin.read_quotas(&[]).await.is_empty()); + assert_eq!(store.quota_reads() - quota_reads, 1); +} + +#[tokio::test] +async fn openai_admin_provider_projects_cached_quota_models_and_canonical_export() { + let store = Arc::new(MemoryAccountStore::default()); + let mut oauth_secret = secret("admin-projection-access"); + oauth_secret.id_token = Some(SecretString::from("header.id-token.signature")); + store + .seed_oauth_credential(ImportCodexOAuthCredential { + account_id: "acct_admin_projection".to_owned(), + name: "admin projection".to_owned(), + secret: oauth_secret, + verified_account: profile("chatgpt-admin-projection"), + next_refresh_at: Some(chrono::Utc::now() + chrono::Duration::minutes(30)), + enabled: true, + }) + .await; + let account = store + .account("acct_admin_projection") + .expect("stored account"); + let record = account_record(&account); + let config = valid_config(); + let catalog_cache = Arc::new(TestCatalogCache::default()); + catalog_cache.seed( + provider_openai::credential::CodexCatalogScope::for_account(&account) + .cache_scope() + .unwrap() + .as_str(), + ["gpt-5.4"], + ); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports_with_catalog( + Arc::clone(&store), + Arc::new(TestOAuthPending::default()), + catalog_cache, + ), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + let admin = bundle.admin.clone(); + + let operation = admin + .connection_test_operation( + &UpstreamModelId::new("gpt-5.4").expect("upstream model"), + "Reply with exactly OK.", + ) + .await + .expect("connection test operation"); + let Operation::Generate(request) = operation else { + panic!("connection test must be a generate operation"); + }; + let encoded = provider_openai::encode_generate_request(&request, "gpt-5.4", None) + .expect("official OpenAI request"); + assert_eq!( + encoded.body().get("model").and_then(Value::as_str), + Some("gpt-5.4") + ); + assert_eq!( + encoded.body().get("stream").and_then(Value::as_bool), + Some(true) + ); + + let account_id = account.id().clone(); + let quota = admin + .quota(ProviderQuotaRequest { + account_id: account_id.clone(), + refresh: false, + rolling_usage: None, + }) + .await + .expect("cached quota"); + assert!(quota.windows.is_empty()); + let models = admin + .models(&account_id, false) + .await + .expect("cached models"); + assert_eq!(models.models[0].id.as_str(), "gpt-5.4"); + let loaded = store + .load_credential(account.id(), account.revision()) + .await + .expect("loaded credential"); + let exported = admin + .export_credentials(vec![ProviderExportCredentialInput { + account: record, + provider_material: ProviderDocument::new(OpaqueProviderData::new( + loaded.credential.into_inner(), + )), + }]) + .await + .expect("canonical export"); + assert_eq!(exported.account_ids, vec![account_id]); + let document = exported.document.expose_to_provider().expose_to_provider(); + assert_eq!( + document.get("sourceFormat").and_then(Value::as_str), + Some("cpr") + ); + let exported_account = document + .get("accounts") + .and_then(Value::as_array) + .and_then(|accounts| accounts.first()) + .expect("exported OAuth account"); + assert_eq!( + exported_account.get("accessToken").and_then(Value::as_str), + Some("admin-projection-access") + ); + assert_eq!( + exported_account.get("idToken").and_then(Value::as_str), + Some("header.id-token.signature") + ); + assert!(exported_account.get("token").is_none()); +} + +#[tokio::test] +async fn openai_admin_quota_refresh_updates_the_account_plan() { + let store = Arc::new(MemoryAccountStore::default()); + let mut verified_account = profile("chatgpt-upgraded-plan"); + verified_account.plan_type = Some("plus".to_owned()); + store + .seed_oauth_credential(ImportCodexOAuthCredential { + account_id: "acct_upgraded_plan".to_owned(), + name: "upgraded plan".to_owned(), + secret: secret("upgraded-plan-test-token"), + verified_account, + next_refresh_at: None, + enabled: true, + }) + .await; + let account = store.account("acct_upgraded_plan").unwrap(); + let server = MockServer::start().await; + Mock::given(method("GET")).and(path("/api/codex/usage")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "plan_type": "pro", "rate_limit": {"allowed": true, "primary_window": {"used_percent": 1}} + }))) + .expect(1).mount(&server).await; + let mut config = valid_config(); + config.config.api.base_url = server.uri(); + let bundle = provider_openai::initialize( + config.config, + provider_ports_with(store.clone(), Arc::new(TestOAuthPending::default())), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .unwrap(); + for refresh in [true, false] { + let quota = bundle + .admin + .quota(ProviderQuotaRequest { + account_id: account.id().clone(), + refresh, + rolling_usage: None, + }) + .await + .unwrap(); + assert_eq!(quota.plan_type.as_deref(), Some("pro")); + assert_eq!( + store.account("acct_upgraded_plan").unwrap().plan_type(), + Some("pro") + ); + } +} + +#[tokio::test] +async fn openai_admin_quota_projects_credit_balance_from_refresh_and_cached_observation() { + let store = Arc::new(MemoryAccountStore::default()); + store + .seed_oauth_credential(ImportCodexOAuthCredential { + account_id: "acct_credit_balance".to_owned(), + name: "credit balance".to_owned(), + secret: secret("credit-balance-test-token"), + verified_account: profile("chatgpt-credit-balance"), + next_refresh_at: None, + enabled: true, + }) + .await; + let account = store.account("acct_credit_balance").unwrap(); + let server = MockServer::start().await; + let mut config = valid_config(); + config.config.api.base_url = server.uri(); + let bundle = provider_openai::initialize( + config.config, + provider_ports_with(store.clone(), Arc::new(TestOAuthPending::default())), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .unwrap(); + for (wire, expected) in [ + ( + json!({"has_credits": true, "unlimited": false, "balance": "62500"}), + Some((true, false, Some("62500"))), + ), + ( + json!({"has_credits": false, "unlimited": false, "balance": 0}), + Some((false, false, Some("0"))), + ), + ( + json!({"has_credits": true, "unlimited": false, "balance": "9007199254740993.1234567890"}), + Some((true, false, Some("9007199254740993.1234567890"))), + ), + ( + json!({"has_credits": true, "unlimited": false, "balance": null}), + Some((true, false, None)), + ), + ( + json!({"has_credits": false, "unlimited": true}), + Some((false, true, None)), + ), + (Value::Null, None), + ] { + let _mock = Mock::given(method("GET")) + .and(path("/api/codex/usage")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "rate_limit": {"allowed": true, "primary_window": {"used_percent": 28}}, + "credits": wire, + }))) + .expect(1) + .mount_as_scoped(&server) + .await; + for refresh in [true, false] { + let quota = bundle + .admin + .quota(ProviderQuotaRequest { + account_id: account.id().clone(), + refresh, + rolling_usage: None, + }) + .await + .expect("quota with credits"); + assert_eq!( + quota.credits.as_ref().map(|credits| ( + credits.has_credits, + credits.unlimited, + credits.balance.as_deref(), + )), + expected + ); + assert_eq!(quota.windows[0].used_percent, Some(28.0)); + assert!(!quota.limit_reached); + } + } +} + +#[tokio::test] +async fn openai_admin_projects_free_plan_from_cached_quota_when_account_claims_omit_it() { + let store = Arc::new(MemoryAccountStore::default()); + let mut verified_account = profile("chatgpt-free-plan"); + verified_account.plan_type = None; + store + .seed_oauth_credential(ImportCodexOAuthCredential { + account_id: "acct_free_plan".to_owned(), + name: "free plan".to_owned(), + secret: secret("free-plan-test-token"), + verified_account, + next_refresh_at: None, + enabled: true, + }) + .await; + let account = store.account("acct_free_plan").expect("stored account"); + let observed_at = SystemTime::now(); + store + .compare_and_swap_quota(QuotaObservation { + quota_pause: None, + expected_connection: None, + plan_type: None, + account_id: account.id().clone(), + expected_revision: account.revision(), + quota: OpaqueProviderData::new( + json!({ + "plan_type": "free", + "rate_limit": { + "allowed": true, + "primary_window": { + "used_percent": 0, + "limit_window_seconds": 2_592_000, + "reset_at": 1_900_000_000 + } + } + }) + .as_object() + .expect("quota object") + .clone(), + ), + observed_at, + state: QuotaState::allowed(observed_at), + }) + .await + .expect("persist existing quota"); + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports_with(store, Arc::new(TestOAuthPending::default())), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + let admin = bundle.admin.clone(); + let quota = admin + .quota(ProviderQuotaRequest { + account_id: account.id().clone(), + refresh: false, + rolling_usage: None, + }) + .await + .expect("read cached free quota"); + assert_eq!(quota.plan_type.as_deref(), Some("free")); + assert_eq!( + admin.plan_type_display(quota.plan_type.as_deref().expect("plan")), + "Free" + ); +} + +#[tokio::test] +async fn openai_admin_provider_projects_official_codex_quota_and_independent_buckets_with_chinese_labels() + { + let store = Arc::new(MemoryAccountStore::default()); + store + .seed_oauth_credential(ImportCodexOAuthCredential { + account_id: "acct_admin_canonical_quota".to_owned(), + name: "admin canonical quota".to_owned(), + secret: secret("admin-canonical-quota-access"), + verified_account: profile("chatgpt-admin-canonical-quota"), + next_refresh_at: Some(chrono::Utc::now() + chrono::Duration::minutes(30)), + enabled: true, + }) + .await; + let account = store + .account("acct_admin_canonical_quota") + .expect("stored account"); + let raw = json!({ + "active_limit": "premium", + "rate_limit": { + "primary_window": { + "used_percent": 91, + "reset_at": 1_900_000_000, + "limit_window_seconds": 2_592_000 + }, + "secondary_window": { + "used_percent": 88 + } + }, + "additional_rate_limits": [{ + "limit_name": "custom_codex_label", + "metered_feature": "codex", + "rate_limit": { + "primary_window": { + "used_percent": 2, + "reset_at": 1_900_000_000, + "limit_window_seconds": 2_592_000 + }, + "secondary_window": { + "used_percent": 0 + } + } + }, { + "limit_name": "code_review", + "metered_feature": "code_review", + "rate_limit": { + "primary_window": { + "used_percent": 12, + "reset_at": 1_900_000_000, + "limit_window_seconds": 604_800 + } + } + }, { + "limit_name": "GPT-5.3-Codex-Spark", + "metered_feature": "codex_bengalfox", + "rate_limit": { + "primary_window": { + "used_percent": 0, + "reset_at": 1_900_000_000, + "limit_window_seconds": 604_800 + } + } + }] + }); + let observed_at = SystemTime::now(); + store + .compare_and_swap_quota(QuotaObservation { + quota_pause: None, + expected_connection: None, + plan_type: None, + account_id: account.id().clone(), + expected_revision: account.revision(), + quota: OpaqueProviderData::new(raw.as_object().expect("quota object").clone()), + observed_at, + state: QuotaState::observed_unknown(observed_at), + }) + .await + .expect("persist quota"); + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports_with(Arc::clone(&store), Arc::new(TestOAuthPending::default())), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + + let quota = bundle + .admin + .quota(ProviderQuotaRequest { + account_id: account.id().clone(), + refresh: false, + rolling_usage: None, + }) + .await + .expect("cached quota"); + let monthly = quota + .windows + .iter() + .filter(|window| window.group == "monthly") + .collect::>(); + + assert_eq!(monthly.len(), 1); + assert!(monthly.iter().any(|window| { + window.label == "月额度" + && window.limit_id.as_deref() == Some("codex") + && window.used_percent == Some(91.0) + })); + assert!( + !quota + .windows + .iter() + .any(|window| window.key.starts_with("additional-0-codex")), + "the additional codex alias should not become a second display bucket" + ); + let secondary = quota + .windows + .iter() + .find(|window| { + window.limit_id.as_deref() == Some("codex") + && window.role == Some(ProviderQuotaWindowRole::Secondary) + }) + .expect("core secondary quota"); + assert_eq!(secondary.label, "次级额度"); + assert_eq!(secondary.used_percent, Some(88.0)); + let review = quota + .windows + .iter() + .find(|window| window.limit_id.as_deref() == Some("code_review")) + .expect("code review quota"); + assert_eq!(review.label, "周额度"); + assert_eq!(review.limit_name.as_deref(), Some("code_review")); + assert_eq!(review.role, Some(ProviderQuotaWindowRole::Primary)); + let spark = quota + .windows + .iter() + .find(|window| window.limit_id.as_deref() == Some("codex_bengalfox")) + .expect("Spark quota"); + assert_eq!( + ( + monthly[0].local_usage_attribution, + review.local_usage_attribution, + spark.local_usage_attribution, + ), + ( + QuotaLocalUsageAttribution::AccountWide, + QuotaLocalUsageAttribution::Unavailable, + QuotaLocalUsageAttribution::Unavailable, + ), + ); +} + +#[tokio::test] +async fn openai_admin_keeps_confirmed_exhaustion_separate_from_raw_usage_display() { + let store = Arc::new(MemoryAccountStore::default()); + let account_id = "acct_admin_confirmed_exhaustion"; + store + .seed_oauth_credential(ImportCodexOAuthCredential { + account_id: account_id.to_owned(), + name: "admin confirmed exhaustion".to_owned(), + secret: secret("admin-confirmed-exhaustion-access"), + verified_account: profile("chatgpt-admin-confirmed-exhaustion"), + next_refresh_at: Some(Utc::now() + chrono::Duration::minutes(30)), + enabled: true, + }) + .await; + let account = store.account(account_id).expect("stored account"); + let reset_at = 1_900_000_000_u64; + let observed_at = SystemTime::now(); + store + .compare_and_swap_quota(QuotaObservation { + quota_pause: None, + expected_connection: None, + plan_type: None, + account_id: account.id().clone(), + expected_revision: account.revision(), + quota: OpaqueProviderData::new( + json!({ + "rate_limit": { + "allowed": true, + "limit_reached": false, + "primary_window": {"used_percent": 86, "reset_at": reset_at} + } + }) + .as_object() + .expect("quota object") + .clone(), + ), + observed_at, + state: QuotaState::allowed(observed_at), + }) + .await + .expect("persist raw quota"); + store + .apply_quota_access(QuotaAccessChange { + account_id: account.id().clone(), + expected_revision: account.revision(), + state: QuotaState::exhausted(QuotaEvidence::UsageLimitReached, SystemTime::now(), None), + }) + .await + .expect("mark account exhausted"); + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports_with(Arc::clone(&store), Arc::new(TestOAuthPending::default())), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + + let exhausted = bundle + .admin + .quota(ProviderQuotaRequest { + account_id: account.id().clone(), + refresh: false, + rolling_usage: None, + }) + .await + .expect("project exhausted quota"); + + assert_eq!(exhausted.windows.len(), 1); + assert_eq!(exhausted.windows[0].used_percent, Some(86.0)); + let raw = store + .get_quotas(std::slice::from_ref(account.id())) + .await + .expect("read raw quota") + .pop() + .expect("raw quota"); + assert_eq!( + raw.quota.expose_to_provider()["rate_limit"]["primary_window"]["used_percent"], + 86 + ); + + store + .apply_quota_access(QuotaAccessChange { + account_id: account.id().clone(), + expected_revision: account.revision(), + state: QuotaState::allowed(SystemTime::now()), + }) + .await + .expect("recover account"); + let recovered = bundle + .admin + .quota(ProviderQuotaRequest { + account_id: account.id().clone(), + refresh: false, + rolling_usage: None, + }) + .await + .expect("project recovered quota"); + + assert_eq!(recovered.windows[0].used_percent, Some(86.0)); +} + +#[tokio::test] +async fn openai_admin_preserves_expired_window_usage_and_exhaustion_attribution() { + for exhausted in [false, true] { + let store = Arc::new(MemoryAccountStore::default()); + let account_id = "acct_admin_expired_window"; + store + .seed_oauth_credential(ImportCodexOAuthCredential { + account_id: account_id.to_owned(), + name: "admin expired window".to_owned(), + secret: secret("admin-expired-window-access"), + verified_account: profile("chatgpt-admin-expired-window"), + next_refresh_at: Some(Utc::now() + chrono::Duration::minutes(30)), + enabled: true, + }) + .await; + let account = store.account(account_id).expect("stored account"); + let past_reset_at = Utc::now().timestamp() - 60; + let observed_at = SystemTime::now() - Duration::from_secs(300); + let weekly_used = if exhausted { 100.0 } else { 74.0 }; + let state = if exhausted { + QuotaState::exhausted( + QuotaEvidence::ProviderDenied, + observed_at, + Some(SystemTime::UNIX_EPOCH + Duration::from_secs(past_reset_at as u64)), + ) + } else { + QuotaState::allowed(observed_at) + }; + store + .compare_and_swap_quota(QuotaObservation { + quota_pause: None, + expected_connection: None, + plan_type: None, + account_id: account.id().clone(), + expected_revision: account.revision(), + quota: OpaqueProviderData::new( + json!({ + "rate_limit": { + "allowed": !exhausted, + "limit_reached": exhausted, + "primary_window": { + "used_percent": 15, + "reset_at": past_reset_at + 18_000, + "limit_window_seconds": 18_000, + }, + "secondary_window": { + "used_percent": weekly_used, + "reset_at": past_reset_at, + "limit_window_seconds": 604_800, + } + } + }) + .as_object() + .expect("quota object") + .clone(), + ), + observed_at, + state, + }) + .await + .expect("persist raw quota"); + + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports_with(Arc::clone(&store), Arc::new(TestOAuthPending::default())), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + let mut projected = bundle + .admin + .quota(ProviderQuotaRequest { + account_id: account.id().clone(), + refresh: false, + rolling_usage: None, + }) + .await + .expect("project quota"); + let record = account_record(&store.account(account_id).expect("stored quota facts")); + let batch = bundle + .admin + .read_quotas(&[ProviderQuotaReadRequest { + account: &record, + rolling_usage: None, + }]) + .await; + assert_eq!(batch[0].as_ref().expect("batch quota"), &projected); + assert_eq!(projected.limit_reached, exhausted); + // 账号接口还会归一化耗尽展示;过期周窗口不能把触顶错误转移到短期窗口 + projected.apply_limit_reached_display(); + let primary = projected + .windows + .iter() + .find(|w| w.window_seconds == Some(18_000)) + .expect("primary"); + let weekly = projected + .windows + .iter() + .find(|w| w.window_seconds == Some(604_800)) + .expect("weekly"); + assert_eq!( + (primary.used_percent, primary.limit_reached), + (Some(15.0), false) + ); + assert_eq!( + (weekly.used_percent, weekly.limit_reached), + (Some(weekly_used), exhausted) + ); + assert_eq!( + weekly.reset_at.map(|reset| reset.timestamp()), + Some(past_reset_at) + ); + let raw = store + .get_quotas(std::slice::from_ref(account.id())) + .await + .expect("raw quota") + .pop() + .expect("observation"); + assert_eq!(raw.observed_at, observed_at); + assert_eq!( + raw.quota.expose_to_provider()["rate_limit"]["secondary_window"]["used_percent"], + weekly_used + ); + } +} + +#[tokio::test] +async fn openai_admin_provider_rejects_unprepared_mutations_before_store_commit() { + let store = Arc::new(MemoryAccountStore::default()); + store + .seed_oauth_credential(ImportCodexOAuthCredential { + account_id: "acct_admin_invalid".to_owned(), + name: "admin invalid".to_owned(), + secret: secret("admin-invalid-access"), + verified_account: profile("chatgpt-admin-invalid"), + next_refresh_at: Some(chrono::Utc::now() + chrono::Duration::minutes(30)), + enabled: true, + }) + .await; + let account = store.account("acct_admin_invalid").expect("stored account"); + let record = account_record(&account); + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports_with(store, Arc::new(TestOAuthPending::default())), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + let admin = bundle.admin.clone(); + let import_error = admin + .prepare_import(PrepareCredentialImport { + default_outbound_proxy: None, + document: ProviderDocument::new(OpaqueProviderData::new(Map::new())), + }) + .await + .expect_err("invalid import"); + assert_eq!(import_error.kind(), ProviderAdminErrorKind::Invalid); + let mut stale_record = record.clone(); + stale_record.name = "stale name".to_owned(); + stale_record.email = None; + stale_record.plan_type = None; + stale_record.credential_revision = Revision::new(99).expect("stale revision"); + stale_record.has_refresh_token = false; + stale_record.access_token_expires_at = None; + stale_record.next_refresh_at = None; + stale_record.enabled = false; + stale_record.credential_state = CredentialState::Banned; + let rotation_error = admin + .prepare_rotation(PrepareCredentialRotation { + account: stale_record, + provider_material: ProviderDocument::new(OpaqueProviderData::new(Map::new())), + }) + .await + .expect_err("invalid rotation"); + assert_eq!(rotation_error.kind(), ProviderAdminErrorKind::Invalid); + let mut missing = record; + missing.id = "acct_admin_missing".to_owned(); + let refresh_error = admin + .prepare_refresh(PrepareCredentialRefresh { account: missing }) + .await + .expect_err("missing refresh target"); + assert_eq!(refresh_error.kind(), ProviderAdminErrorKind::NotFound); +} + +#[tokio::test] +async fn initialized_provider_reports_a_safe_pat_format_error_before_network_access() { + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports(), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + let error = bundle + .admin + .prepare_import(PrepareCredentialImport { + default_outbound_proxy: None, + document: ProviderDocument::new(OpaqueProviderData::new(Map::from_iter([( + "accessToken".to_owned(), + json!("at-sensitive-token with whitespace"), + )]))), + }) + .await + .expect_err("PAT format must be checked by the initialized provider"); + assert_eq!(error.kind(), ProviderAdminErrorKind::Invalid); + assert_eq!( + error.public_message(), + Some("请输入完整 PAT,以 at- 开头且不含空白或控制字符") + ); + assert!(error.message().is_none()); + assert!(!format!("{error:?}").contains("sensitive-token")); +} + +#[tokio::test] +async fn openai_rotation_preserves_the_new_access_token_jwt_expiration() { + let store = Arc::new(MemoryAccountStore::default()); + store + .seed_oauth_credential(ImportCodexOAuthCredential { + account_id: "acct_admin_rotation_expiration".to_owned(), + name: "admin rotation expiration".to_owned(), + secret: secret("admin-rotation-access"), + verified_account: profile("chatgpt-admin-rotation-expiration"), + next_refresh_at: None, + enabled: true, + }) + .await; + let account = store + .account("acct_admin_rotation_expiration") + .expect("stored account"); + let record = account_record(&account); + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports_with(store, Arc::new(TestOAuthPending::default())), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .expect("OpenAI bundle"); + + let expires_at = Utc + .timestamp_opt(2_000_000_000, 0) + .single() + .expect("valid test timestamp"); + let payload = URL_SAFE_NO_PAD.encode( + serde_json::to_vec(&serde_json::json!({"exp": expires_at.timestamp()})) + .expect("test JWT payload"), + ); + let mut material = Map::new(); + material.insert( + "access_token".to_owned(), + Value::String(format!("unverified-header.{payload}.unverified-signature")), + ); + material.insert( + "refresh_token".to_owned(), + Value::String("admin-rotation-refresh".to_owned()), + ); + + let prepared = bundle + .admin + .prepare_rotation(PrepareCredentialRotation { + account: record, + provider_material: ProviderDocument::new(OpaqueProviderData::new(material)), + }) + .await + .expect("JWT rotation should be prepared"); + + assert_eq!(prepared.facts().access_token_expires_at, Some(expires_at)); +} + +#[tokio::test] +async fn api_key_admin_exposes_only_configuration_and_preserves_key_when_rotating_address() { + let store = Arc::new(MemoryAccountStore::default()); + store + .seed_api_key( + "acct_api_admin", + "https://first.example/v1".to_owned(), + provider_openai::credential::ResponsesTransport::Http, + ) + .await; + let account = store.account("acct_api_admin").unwrap(); + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports_with(Arc::clone(&store), Arc::new(TestOAuthPending::default())), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .unwrap(); + let admin = bundle.admin.clone(); + let configuration = admin + .account_configuration(account.id()) + .await + .unwrap() + .unwrap(); + let configuration = configuration.expose_to_provider().expose_to_provider(); + assert_eq!(configuration.len(), 3); + assert_eq!(configuration.get("protocol"), Some(&json!("responses"))); + assert_eq!( + configuration.get("base_url"), + Some(&json!("https://first.example/v1")) + ); + assert!(!configuration.contains_key("api_key")); + for base_url in [ + "https://second.example/root", + "http://10.0.0.7:8080/v1", + "http://[fd00::7]:8080/v1", + "http://relay:8080/v1", + ] { + let prepared = admin + .prepare_rotation(PrepareCredentialRotation { + account: account_record(&account), + provider_material: ProviderDocument::new(OpaqueProviderData::new( + json!({"base_url":base_url, "transport":"prefer_websocket"}) + .as_object() + .unwrap() + .clone(), + )), + }) + .await + .unwrap(); + let material = prepared + .facts() + .provider_material + .expose_to_provider() + .expose_to_provider(); + assert_eq!(material.get("api_key"), Some(&json!("sk-api-test-only"))); + assert_eq!(material.get("base_url"), Some(&json!(base_url))); + assert!(!prepared.facts().has_refresh_token); + assert_eq!(prepared.facts().account_id, *account.id()); + } + assert_eq!( + admin + .prepare_refresh(PrepareCredentialRefresh { + account: account_record(&account) + }) + .await + .unwrap_err() + .kind(), + ProviderAdminErrorKind::Unsupported + ); + assert_eq!( + admin.subscription(account.id()).await.unwrap_err().kind(), + ProviderAdminErrorKind::Unsupported + ); + assert_eq!( + admin.reset_credits(account.id()).await.unwrap_err().kind(), + ProviderAdminErrorKind::Unsupported + ); +} + +#[tokio::test] +async fn oauth_transport_settings_preserve_tokens_refresh_schedule_and_health() { + let store = Arc::new(MemoryAccountStore::default()); + store + .seed_oauth_credential(ImportCodexOAuthCredential { + account_id: "acct_oauth_transport".to_owned(), + name: "OAuth transport".to_owned(), + secret: secret("test-oauth-transport"), + verified_account: profile("chatgpt-oauth-transport"), + next_refresh_at: Some(Utc::now() + chrono::Duration::minutes(30)), + enabled: true, + }) + .await; + let account = store.account("acct_oauth_transport").unwrap(); + let current = store.load_current_credential(account.id()).await.unwrap(); + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports_with(Arc::clone(&store), Arc::new(TestOAuthPending::default())), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .unwrap(); + let admin = bundle.admin.clone(); + let configuration = admin + .account_configuration(account.id()) + .await + .unwrap() + .unwrap(); + assert_eq!( + configuration.expose_to_provider().expose_to_provider(), + json!({"transport":"prefer_websocket"}).as_object().unwrap() + ); + for transport in ["http", "prefer_websocket"] { + let prepared = admin + .prepare_rotation(PrepareCredentialRotation { + account: account_record(&account), + provider_material: ProviderDocument::new(OpaqueProviderData::new( + json!({"transport":transport}).as_object().unwrap().clone(), + )), + }) + .await + .unwrap(); + let facts = prepared.facts(); + let mut expected = current.credential.expose_to_provider().clone(); + if transport == "http" { + expected.insert("transport".to_owned(), json!(transport)); + } + assert_eq!( + facts + .provider_material + .expose_to_provider() + .expose_to_provider(), + &expected + ); + assert_eq!( + facts.next_refresh_at, + account.next_refresh_at().map(DateTime::::from) + ); + assert_eq!( + facts.access_token_expires_at, + account.access_token_expires_at().map(DateTime::::from) + ); + assert_eq!(facts.has_refresh_token, account.has_refresh_token()); + assert!(facts.preserve_profile && facts.preserve_credential_state); + assert!(facts.preserve_access_token_expiry); + } + for invalid in [ + json!({"transport":"invalid"}), + json!({"transport":"http", "base_url":"https://other.example"}), + json!({"transport":"http", "api_key":"test-key"}), + ] { + let error = admin + .prepare_rotation(PrepareCredentialRotation { + account: account_record(&account), + provider_material: ProviderDocument::new(OpaqueProviderData::new( + invalid.as_object().unwrap().clone(), + )), + }) + .await + .unwrap_err(); + assert_eq!(error.kind(), ProviderAdminErrorKind::Invalid); + } + store.set_oauth_transport( + "acct_oauth_transport", + provider_openai::credential::ResponsesTransport::Http, + ); + let configuration = admin + .account_configuration(account.id()) + .await + .unwrap() + .unwrap(); + assert_eq!( + configuration.expose_to_provider().expose_to_provider(), + json!({"transport":"http"}).as_object().unwrap() + ); +} + +#[tokio::test] +async fn usage_quote_reuses_native_override_and_reports_incomplete_input() { + use gateway_admin::ports::provider::ProviderUsagePricingInput; + use gateway_core::metering::{ModelPriceOverride, Usage}; + let config = valid_config(); + let bundle = provider_openai::initialize( + config.config.clone(), + provider_ports(), + Arc::new(gateway_core::account::UpstreamInfoReader::default()), + ) + .await + .unwrap(); + let admin = bundle.admin.clone(); + let mut input = ProviderUsagePricingInput { + upstream_model_id: "gpt-6-sol".into(), + service_tier: None, + usage: Usage { + input_tokens: Some(1_000_000), + output_tokens: Some(100_000), + cached_input_tokens: Some(200_000), + cache_write_input_tokens: Some(0), + image_input_tokens: Some(0), + image_output_tokens: Some(0), + ..Default::default() + }, + }; + let custom:ModelPriceOverride=serde_json::from_value(json!({"multiplierBps":10000,"bands":{"standard":{"input":"2","output":"10","cacheRead":"0.5","cacheWrite":"2"},"long_standard":{"input":"2","output":"10","cacheRead":"0.5","cacheWrite":"2"}}})).unwrap(); + let price = admin + .evaluate_usage_pricing(&input, Some(&custom)) + .unwrap() + .unwrap(); + assert_eq!(price.total_amount().amount().canonical(), "2.7"); + input.usage.cached_input_tokens = None; + assert!( + admin + .evaluate_usage_pricing(&input, Some(&custom)) + .unwrap() + .is_none() + ); +} diff --git a/backend/crates/providers/openai/tests/billing/calculate.rs b/backend/crates/providers/openai/tests/billing/calculate.rs new file mode 100644 index 000000000..8913ba58a --- /dev/null +++ b/backend/crates/providers/openai/tests/billing/calculate.rs @@ -0,0 +1,573 @@ +//! OpenAI 型号、档位、上下文及价格覆盖的费用合同 + +use crate::billing::{ + OpenAiBillingUsage, openai_billing_breakdown, openai_billing_breakdown_with_override, +}; +use gateway_core::metering::ModelPriceOverride; +use serde_json::json; + +fn billing_usage( + input_tokens: u64, + output_tokens: u64, + cached_input_tokens: u64, + cache_write_input_tokens: u64, +) -> OpenAiBillingUsage { + OpenAiBillingUsage::new( + input_tokens, + output_tokens, + cached_input_tokens, + cache_write_input_tokens, + ) +} + +#[test] +fn astra_billing_should_preserve_components_across_tiers_and_context_boundary() { + // 每百万 token 的美元价格,依次为输入、缓存读取、缓存写入与输出 + for (tier, input, expected, multiplier) in [ + (None, 272_000, ["10", "1", "12.5", "50"], 100), + (None, 272_001, ["20", "2", "25", "75"], 100), + (Some("flex"), 272_000, ["5", "0.5", "6.25", "25"], 50), + (Some("flex"), 272_001, ["10", "1", "12.5", "37.5"], 50), + (Some("fast"), 272_000, ["20", "2", "25", "100"], 200), + (Some("fast"), 272_001, ["40", "4", "50", "150"], 200), + (Some("priority"), 272_001, ["40", "4", "50", "150"], 200), + ] { + let breakdown = + openai_billing_breakdown("gpt-6-astra", billing_usage(input, 5, 20, 10), tier) + .expect("published Astra pricing"); + let prices = [ + breakdown.input_price_per_million(), + breakdown.cache_read_price_per_million(), + breakdown.cache_write_price_per_million(), + breakdown.output_price_per_million(), + ] + .map(|price| { + price + .amount() + .to_string() + .trim_end_matches('0') + .trim_end_matches('.') + .to_owned() + }); + assert_eq!(prices, expected, "tier={tier:?}, input={input}"); + assert_eq!(breakdown.multiplier_percent(), multiplier); + } + let breakdown = openai_billing_breakdown("gpt-6-astra", billing_usage(100, 5, 20, 10), None) + .expect("Astra component pricing"); + assert_eq!( + ( + breakdown.input_amount().amount().scaled(), + breakdown.output_amount().amount().scaled(), + breakdown.cache_read_amount().amount().scaled(), + breakdown.cache_write_amount().amount().scaled(), + breakdown.total_amount().amount().scaled(), + ), + (7_000_000, 2_500_000, 200_000, 1_250_000, 10_950_000), + ); +} + +#[test] +fn gpt_6_models_should_use_published_prices_across_tiers_and_context_boundary() { + // 每档依次核对每百万 Token 的输入、缓存读取、缓存写入和输出价格 + for (model, cases) in [ + ( + "gpt-6.2-astra", + [ + (None, 272_000, ["8", "0.4", "10", "40"]), + (None, 272_001, ["16", "0.8", "20", "60"]), + (Some("fast"), 272_000, ["16", "0.8", "20", "80"]), + (Some("priority"), 272_001, ["32", "1.6", "40", "120"]), + (Some("ultrafast"), 272_000, ["48", "2.4", "60", "240"]), + (Some("ultrafast"), 272_001, ["96", "4.8", "120", "360"]), + ], + ), + ( + "gpt-6.2-sol", + [ + (None, 272_000, ["2", "0.1", "2.5", "10"]), + (None, 272_001, ["4", "0.2", "5", "15"]), + (Some("fast"), 272_000, ["4", "0.2", "5", "20"]), + (Some("priority"), 272_001, ["8", "0.4", "10", "30"]), + (Some("ultrafast"), 272_000, ["12", "0.6", "15", "60"]), + (Some("ultrafast"), 272_001, ["24", "1.2", "30", "90"]), + ], + ), + ( + "gpt-6.1-sol", + [ + (None, 272_000, ["2", "0.1", "2.5", "10"]), + (None, 272_001, ["4", "0.2", "5", "15"]), + (Some("flex"), 272_000, ["1", "0.05", "1.25", "5"]), + (Some("flex"), 272_001, ["2", "0.1", "2.5", "7.5"]), + (Some("fast"), 272_000, ["4", "0.2", "5", "20"]), + (Some("priority"), 272_001, ["8", "0.4", "10", "30"]), + ], + ), + ( + "gpt-6.1-terra", + [ + (None, 272_000, ["1", "0.05", "1.25", "5"]), + (None, 272_001, ["2", "0.1", "2.5", "7.5"]), + (Some("flex"), 272_000, ["0.5", "0.025", "0.625", "2.5"]), + (Some("flex"), 272_001, ["1", "0.05", "1.25", "3.75"]), + (Some("fast"), 272_000, ["2", "0.1", "2.5", "10"]), + (Some("priority"), 272_001, ["4", "0.2", "5", "15"]), + ], + ), + ( + "gpt-6-sol", + [ + (None, 272_000, ["2", "0.2", "2.5", "10"]), + (None, 272_001, ["4", "0.4", "5", "15"]), + (Some("flex"), 272_000, ["1", "0.1", "1.25", "5"]), + (Some("flex"), 272_001, ["2", "0.2", "2.5", "7.5"]), + (Some("fast"), 272_000, ["4", "0.4", "5", "20"]), + (Some("priority"), 272_001, ["8", "0.8", "10", "30"]), + ], + ), + ( + "gpt-6-luna", + [ + (None, 272_000, ["0.1", "0.01", "0.125", "0.5"]), + (None, 272_001, ["0.2", "0.02", "0.25", "0.75"]), + (Some("flex"), 272_000, ["0.05", "0.005", "0.0625", "0.25"]), + (Some("flex"), 272_001, ["0.1", "0.01", "0.125", "0.375"]), + (Some("fast"), 272_000, ["0.2", "0.02", "0.25", "1"]), + (Some("priority"), 272_001, ["0.4", "0.04", "0.5", "1.5"]), + ], + ), + ] { + for (tier, input, expected) in cases { + let breakdown = openai_billing_breakdown(model, billing_usage(input, 5, 20, 10), tier) + .expect("published GPT-6 pricing"); + let actual = [ + breakdown.input_price_per_million(), + breakdown.cache_read_price_per_million(), + breakdown.cache_write_price_per_million(), + breakdown.output_price_per_million(), + ] + .map(|price| price.amount().canonical()); + assert_eq!(actual, expected, "{model} {tier:?} {input}"); + assert_eq!( + breakdown.long_context_billing_applied(), + input > 272_000, + "{model} {tier:?} {input}" + ); + } + } +} + +#[test] +fn ultrafast_billing_uses_published_prices_across_the_context_boundary() { + // 每档依次核对每百万 Token 的输入、缓存读取、缓存写入和输出价格 + for (model, input, expected, total) in [ + ("gpt-6-astra", 272_000, ["60", "6", "75", "300"], "16.32057"), + ( + "gpt-6-astra", + 272_001, + ["120", "12", "150", "450"], + "32.64051", + ), + ( + "gpt-6.1-sol", + 272_000, + ["12", "0.6", "15", "60"], + "3.264102", + ), + ( + "gpt-6.1-sol", + 272_001, + ["24", "1.2", "30", "90"], + "6.528078", + ), + ] { + let breakdown = + openai_billing_breakdown(model, billing_usage(input, 5, 20, 10), Some("ultrafast")) + .expect("published Ultrafast pricing"); + let prices = [ + breakdown.input_price_per_million(), + breakdown.cache_read_price_per_million(), + breakdown.cache_write_price_per_million(), + breakdown.output_price_per_million(), + ] + .map(|price| price.amount().canonical()); + assert_eq!(prices, expected, "{model} {input}"); + assert_eq!(breakdown.total_amount().amount().canonical(), total); + assert_eq!(breakdown.service_tier(), Some("ultrafast")); + assert_eq!(breakdown.multiplier_percent(), 600); + assert_eq!(breakdown.long_context_billing_applied(), input > 272_000); + } +} + +#[test] +fn billing_breakdown_should_preserve_input_output_and_cache_components() { + let breakdown = openai_billing_breakdown("gpt-5.6-sol", billing_usage(100, 5, 20, 10), None) + .expect("known model pricing"); + + assert_eq!(breakdown.input_amount().amount().scaled(), 3_500_000); + assert_eq!(breakdown.output_amount().amount().scaled(), 1_500_000); + assert_eq!(breakdown.cache_read_amount().amount().scaled(), 100_000); + assert_eq!(breakdown.cache_write_amount().amount().scaled(), 625_000); + assert_eq!(breakdown.total_amount().amount().scaled(), 5_725_000); + assert_eq!(breakdown.service_tier(), Some("default")); + assert_eq!(breakdown.multiplier_percent(), 100); +} + +#[test] +fn billing_breakdown_should_use_latest_gpt_5_6_and_cached_input_prices() { + let terra = openai_billing_breakdown("gpt-5.6-terra", billing_usage(1, 1, 0, 0), None) + .expect("gpt-5.6-terra standard pricing"); + assert_eq!(terra.total_amount().amount().scaled(), 140_000); + + let terra_fast = + openai_billing_breakdown("gpt-5.6-terra", billing_usage(1, 1, 0, 0), Some("fast")) + .expect("gpt-5.6-terra fast pricing"); + assert_eq!(terra_fast.total_amount().amount().scaled(), 280_000); + + let terra_long = + openai_billing_breakdown("gpt-5.6-terra", billing_usage(272_001, 0, 0, 0), None) + .expect("gpt-5.6-terra long-context pricing"); + assert_eq!(terra_long.total_amount().amount().scaled(), 10_880_040_000); + + let luna = openai_billing_breakdown("gpt-5.6-luna", billing_usage(1, 1, 0, 0), None) + .expect("gpt-5.6-luna standard pricing"); + assert_eq!(luna.total_amount().amount().scaled(), 14_000); + + let gpt_4o = openai_billing_breakdown("gpt-4o", billing_usage(1, 1, 1, 0), None) + .expect("gpt-4o cached-input pricing"); + assert_eq!(gpt_4o.total_amount().amount().scaled(), 112_500); + + let gpt_4o_mini = openai_billing_breakdown("gpt-4o-mini", billing_usage(1, 1, 1, 0), None) + .expect("gpt-4o-mini cached-input pricing"); + assert_eq!(gpt_4o_mini.total_amount().amount().scaled(), 6_750); +} + +#[test] +fn billing_breakdown_should_apply_fast_and_flex_tiers_without_guessing_unknown_models() { + let fast = openai_billing_breakdown("gpt-5.4", billing_usage(1, 1, 0, 0), Some("fast")) + .expect("fast pricing"); + let flex = openai_billing_breakdown("gpt-5.4", billing_usage(1, 1, 0, 0), Some("flex")) + .expect("flex pricing"); + + assert_eq!(fast.total_amount().amount().scaled(), 350_000); + assert_eq!(fast.service_tier(), Some("fast")); + assert_eq!(fast.multiplier_percent(), 200); + assert!(!fast.long_context_billing_applied()); + assert_eq!(flex.total_amount().amount().scaled(), 87_500); + assert_eq!(flex.multiplier_percent(), 50); + assert!(openai_billing_breakdown("unknown-model", billing_usage(1, 1, 0, 0), None).is_none()); +} + +#[test] +fn billing_breakdown_should_use_official_fast_long_context_prices() { + let breakdown = + openai_billing_breakdown("gpt-5.6-sol", billing_usage(272_001, 1, 1, 1), Some("fast")) + .expect("gpt-5.6-sol fast long-context pricing"); + + assert_eq!( + ( + breakdown.input_price_per_million().amount().scaled(), + breakdown.cache_read_price_per_million().amount().scaled(), + breakdown.cache_write_price_per_million().amount().scaled(), + breakdown.output_price_per_million().amount().scaled(), + ), + ( + 200_000_000_000, + 20_000_000_000, + 250_000_000_000, + 900_000_000_000, + ) + ); +} + +#[test] +fn billing_breakdown_should_fail_closed_for_unpublished_prices() { + assert_eq!( + ( + openai_billing_breakdown("gpt-5.5", billing_usage(272_001, 1, 0, 0), Some("fast")) + .is_none(), + openai_billing_breakdown("gpt-5.5-pro", billing_usage(1, 1, 0, 0), Some("fast")) + .is_none(), + openai_billing_breakdown("gpt-5.3-codex-spark", billing_usage(1, 1, 0, 0), None) + .is_none(), + openai_billing_breakdown("gpt-4o", billing_usage(1, 1, 0, 0), Some("flex")).is_none(), + ), + (true, true, true, true) + ); +} + +#[test] +fn billing_breakdown_should_use_official_gpt_4o_fast_prices() { + let breakdown = openai_billing_breakdown("gpt-4o", billing_usage(1, 1, 1, 0), Some("priority")) + .expect("gpt-4o fast pricing"); + + assert_eq!( + ( + breakdown.cache_read_price_per_million().amount().scaled(), + breakdown.output_price_per_million().amount().scaled(), + breakdown.standard_amount().amount().scaled(), + breakdown.total_amount().amount().scaled(), + breakdown.multiplier_percent(), + ), + (21_250_000_000, 170_000_000_000, 112_500, 191_250, 170,) + ); +} + +#[test] +fn billing_breakdown_should_use_published_flex_cache_price() { + let breakdown = openai_billing_breakdown("gpt-5.4", billing_usage(1, 0, 1, 0), Some("flex")) + .expect("gpt-5.4 flex pricing"); + + assert_eq!( + breakdown.cache_read_price_per_million().amount().scaled(), + 1_300_000_000 + ); +} + +#[test] +fn billing_breakdown_should_switch_only_after_the_long_context_threshold() { + let boundary = openai_billing_breakdown("gpt-5.4", billing_usage(272_000, 0, 0, 0), None) + .expect("short-context boundary"); + let long = openai_billing_breakdown("gpt-5.4", billing_usage(272_001, 0, 0, 0), None) + .expect("long-context pricing"); + + assert!(!boundary.long_context_billing_applied()); + assert!(long.long_context_billing_applied()); + assert!( + !openai_billing_breakdown("gpt-4o", billing_usage(272_001, 0, 0, 0), None) + .expect("model without long-context pricing") + .long_context_billing_applied() + ); + + assert_eq!( + boundary.input_price_per_million().amount().scaled(), + 25_000_000_000 + ); + assert_eq!( + long.input_price_per_million().amount().scaled(), + 50_000_000_000 + ); + assert!(openai_billing_breakdown("gpt-5.4", billing_usage(1, 0, 2, 0), None).is_none()); +} + +#[test] +fn billing_should_use_explicit_variant_prices_and_verified_snapshots() { + // 每个用例包含一个普通输入 token 和一个输出 token,金额单位为 USD ticks + for (model, expected) in [ + ("gpt-5.6-cyber", 875_000), + ("gpt-5.5-cyber", 875_000), + ("gpt-daybreak-red-latest", 875_000), + ("gpt-daybreak-blue-latest", 350_000), + ("chat-latest", 350_000), + ("gpt-5.4-2026-03-05", 175_000), + (" OpenAI/GPT-4o-2024-08-06 ", 125_000), + ("gpt-4o-2024-05-13", 200_000), + ("gpt-3.5-turbo-0125", 20_000), + ("gpt-3.5-turbo-1106", 30_000), + ] { + let billing = + openai_billing_breakdown(model, billing_usage(1, 1, 0, 0), None).expect(model); + assert_eq!( + billing.total_amount().amount().scaled(), + expected, + "{model}" + ); + } +} + +#[test] +fn billing_should_not_price_shutdown_models_or_restore_them_through_aliases() { + // 官方关闭日期已过;同族仍在服务的基础型号不能为这些旧型号兜底 + for model in [ + "gpt-4-0314", + " OpenAI/GPT-4-0314 ", + "gpt-5-codex", + "gpt-5.1-codex", + "gpt-5.1-codex-max", + "gpt-5.1-codex-mini", + "gpt-5.2-codex", + "gpt-5-chat-latest", + "gpt-5.1-chat-latest", + "gpt-5.2-chat-latest", + "gpt-5.3-chat-latest", + ] { + for tier in [None, Some("flex"), Some("fast")] { + assert!( + openai_billing_breakdown(model, billing_usage(100, 10, 20, 0), tier).is_none(), + "{model} {tier:?}" + ); + } + } +} + +#[test] +fn billing_should_keep_deprecated_models_before_their_shutdown_dates() { + // 截至 2026-09-13,这些型号尚未到官方关闭日期,仍按已公布单价计费 + for model in [ + "gpt-3.5-turbo-instruct", + "gpt-3.5-turbo-1106", + "gpt-4-0613", + "gpt-4-turbo-2024-04-09", + "gpt-4o-2024-05-13", + "gpt-4.1-nano", + "o1", + "o1-pro", + "o3-mini", + "o4-mini", + ] { + assert!( + openai_billing_breakdown(model, billing_usage(100, 10, 20, 0), None).is_some(), + "{model}" + ); + } +} + +#[test] +fn billing_should_not_inherit_prices_for_unknown_models_or_tiers() { + for model in [ + "gpt-6-astra-future", + "gpt-6-astra-2099-01-01", + "gpt-5.6-sol-wm", + "gpt-5.6-cyber-future", + "gpt-5.4-cyber", + "gpt-5.3-codex-spark", + "gpt-4.5-preview", + "gpt-4-32k", + "gpt-5.4:custom", + "gpt-5.4.1", + ] { + assert!( + openai_billing_breakdown(model, billing_usage(1, 1, 0, 0), None).is_none(), + "{model}" + ); + } + for (model, input, tier) in [ + ("gpt-5.6-cyber", 272_001, None), + ("gpt-5.5-cyber", 272_001, None), + ("gpt-5.6-cyber", 1, Some("fast")), + ("gpt-5.3-codex", 1, Some("flex")), + ("gpt-6.2-astra", 1, Some("flex")), + ("gpt-6.2-astra", 272_001, Some("flex")), + ("gpt-6.2-sol", 1, Some("flex")), + ("gpt-6.2-sol", 272_001, Some("flex")), + ("gpt-6-astra", 1, Some("auto")), + ("gpt-6-astra", 1, Some("future")), + ("gpt-6.1-terra", 1, Some("ultrafast")), + ("gpt-6.1-terra", 272_001, Some("ultrafast")), + ("gpt-6-sol", 1, Some("ultrafast")), + ("gpt-6-sol", 272_001, Some("ultrafast")), + ("gpt-6-luna", 1, Some("ultrafast")), + ("gpt-6-luna", 272_001, Some("ultrafast")), + ("gpt-5.4", 1, Some("ultrafast")), + ] { + assert!( + openai_billing_breakdown(model, billing_usage(input, 1, 0, 0), tier).is_none(), + "{model} {tier:?}" + ); + } +} + +#[test] +fn billing_should_reject_overlapping_or_overflowing_cache_counts() { + for (input, cached, written) in [(100, 20, 90), (100, 0, 101), (u64::MAX, u64::MAX, 1)] { + assert!( + openai_billing_breakdown( + "gpt-6-astra", + billing_usage(input, 0, cached, written), + None + ) + .is_none() + ); + } + let cyber = openai_billing_breakdown("gpt-5.6-cyber", billing_usage(100, 10, 20, 10), None) + .expect("已公开的 Cyber 缓存写价格"); + assert_eq!( + cyber.cache_write_price_per_million().amount().to_string(), + "15.6250000000" + ); + assert_eq!(cyber.total_amount().amount().scaled(), 18_062_500); +} + +#[test] +fn custom_price_has_exact_cache_and_multiplier_math() { + let custom: ModelPriceOverride = serde_json::from_value(json!({"multiplierBps":12500,"bands":{ + "standard":{"input":"2","output":"10","cacheRead":"0","cacheWrite":"3"} + }})) + .unwrap(); + let breakdown = openai_billing_breakdown_with_override( + "custom-model", + billing_usage(100, 10, 20, 10), + None, + Some(&custom), + ) + .unwrap(); + assert_eq!(breakdown.input_amount().amount().canonical(), "0.000175"); + assert_eq!(breakdown.output_amount().amount().canonical(), "0.000125"); + assert_eq!(breakdown.cache_read_amount().amount().canonical(), "0"); + assert_eq!( + breakdown.cache_write_amount().amount().canonical(), + "0.0000375" + ); + assert_eq!(breakdown.total_amount().amount().canonical(), "0.0003375"); + assert_eq!(breakdown.custom_multiplier_bps(), 12500); + assert!( + openai_billing_breakdown_with_override( + "custom-model", + billing_usage(100, 10, 0, 0), + Some("flex"), + Some(&custom) + ) + .is_none() + ); +} + +#[test] +fn a_custom_long_tier_does_not_require_a_long_standard_band() { + for (tier, band) in [("priority", "long_fast"), ("ultrafast", "long_ultrafast")] { + let pricing = serde_json::from_value(json!({"multiplierBps":10000,"bands":{ + "standard":{"input":"2","output":"10","cacheRead":"0","cacheWrite":"0"}, + (band):{"input":"8","output":"40","cacheRead":"0","cacheWrite":"0"} + }})) + .unwrap(); + let result = openai_billing_breakdown_with_override( + "custom-model", + billing_usage(300_000, 0, 0, 0), + Some(tier), + Some(&pricing), + ) + .unwrap(); + assert_eq!(result.total_amount().amount().canonical(), "2.4"); + assert_eq!(result.standard_amount().amount().canonical(), "0.6"); + assert!(result.long_context_billing_applied()); + } +} + +#[test] +fn multiplier_only_preserves_builtin_tiers_and_unknown_models_remain_unknown() { + let custom: ModelPriceOverride = + serde_json::from_value(json!({"multiplierBps":20000,"bands":{}})).unwrap(); + for tier in [None, Some("priority"), Some("flex"), Some("ultrafast")] { + for input in [100, 272_001] { + let usage = billing_usage(input, 10, 20, 5); + let original = openai_billing_breakdown("gpt-6-astra", usage, tier).unwrap(); + let adjusted = + openai_billing_breakdown_with_override("gpt-6-astra", usage, tier, Some(&custom)) + .unwrap(); + assert_eq!( + adjusted.total_amount().amount().scaled(), + original.total_amount().amount().scaled() * 2 + ); + assert_eq!(adjusted.multiplier_percent(), original.multiplier_percent()); + assert_eq!(adjusted.long_context_billing_applied(), input > 272_000); + } + } + assert!( + openai_billing_breakdown_with_override( + "unknown-model", + billing_usage(100, 10, 0, 0), + None, + Some(&custom) + ) + .is_none() + ); +} diff --git a/backend/crates/providers/openai/tests/billing/mod.rs b/backend/crates/providers/openai/tests/billing/mod.rs new file mode 100644 index 000000000..39b36e988 --- /dev/null +++ b/backend/crates/providers/openai/tests/billing/mod.rs @@ -0,0 +1,3 @@ +//! Provider 计价规则的行为测试 + +mod calculate; diff --git a/backend/crates/providers/openai/tests/compat/headers.rs b/backend/crates/providers/openai/tests/compat/headers.rs index 7a7ec1269..0ecb5409d 100644 --- a/backend/crates/providers/openai/tests/compat/headers.rs +++ b/backend/crates/providers/openai/tests/compat/headers.rs @@ -209,8 +209,7 @@ async fn backend_http_should_preserve_business_headers_without_downstream_transp let request = request_with_opaque_headers(false); let mut configured_profile = test_wire_profile().snapshot(); configured_profile.account_routing_override = Some("configured-route".into()); - let profile = - provider_openai::transport::profile::CodexWireProfileState::new(configured_profile); + let profile = provider_openai::profile::CodexWireProfileState::new(configured_profile); let profile_snapshot = profile.snapshot(); let expected_user_agent = profile_snapshot.user_agent(); let expected_core_version = profile_snapshot.codex_version; @@ -381,7 +380,7 @@ async fn backend_websocket_should_preserve_business_headers_without_downstream_t .build() .expect("HTTP client"), format!("http://{address}"), - provider_openai::transport::profile::CodexWireProfileState::new(profile), + provider_openai::profile::CodexWireProfileState::new(profile), ) .with_websocket_pool(Arc::new(CodexWebSocketPool::new(Duration::from_mins(1)))); diff --git a/backend/crates/providers/openai/tests/credential/admin.rs b/backend/crates/providers/openai/tests/credential/admin.rs index ae3173dac..eaaa6f027 100644 --- a/backend/crates/providers/openai/tests/credential/admin.rs +++ b/backend/crates/providers/openai/tests/credential/admin.rs @@ -388,7 +388,7 @@ fn pat_service(server: &MockServer) -> CodexCredentialAdminService { client_id: "test-public-client".to_owned(), token_endpoint: format!("{}/oauth/token", server.uri()), }, - provider_openai::transport::profile::CodexWireProfileState::new(Default::default()), + provider_openai::profile::CodexWireProfileState::new(Default::default()), ) .expect("auth client"); CodexCredentialAdminService::new( @@ -504,7 +504,7 @@ async fn pat_import_times_out_without_falling_back_to_document_identity() { client_id: "test-public-client".to_owned(), token_endpoint: format!("{}/oauth/token", server.uri()), }, - provider_openai::transport::profile::CodexWireProfileState::new(Default::default()), + provider_openai::profile::CodexWireProfileState::new(Default::default()), ); let service = CodexCredentialAdminService::new( Arc::new(UnusedRefresher), @@ -557,7 +557,7 @@ async fn pat_import_requires_a_validation_client() { #[tokio::test] async fn pat_auth_json_import_and_cpr_round_trip_preserve_a_token_without_email() { - use gateway_core::account::LoadedCredential; + use gateway_core::account::{LoadedCredential, ProviderAccount}; use provider_openai::credential::{CodexCredentialAdmin, ExportManagedCodexCredential}; let server = MockServer::start().await; @@ -586,21 +586,37 @@ async fn pat_auth_json_import_and_cpr_round_trip_preserve_a_token_without_email( .expect("policy"); let prepared = imported.into_accounts().remove(0); assert!(prepared.account.email().is_none()); + let account = ProviderAccount::new( + prepared.account.id().clone(), + prepared.account.provider().clone(), + String::new(), + prepared.account.upstream_user_id().map(str::to_owned), + prepared.account.authentication_kind().to_owned(), + prepared.account.revision(), + prepared.account.access_token_expires_at(), + ) + .with_profile( + None, + prepared.account.upstream_account_id().map(str::to_owned), + prepared.account.plan_type().map(str::to_owned), + ) + .with_model_access(policy.clone()); + let now = Utc::now(); let exported = CodexCredentialAdmin .format_cpr_export(vec![ExportManagedCodexCredential { current: LoadedCredential { - account: prepared.account.with_model_access(policy.clone()), + account, credential: prepared.credential, }, - added_at: Utc::now(), - updated_at: Utc::now(), + created_at: now, + updated_at: now, }]) .expect("export PAT using the existing credential schema"); + let document = serde_json::to_value(exported).expect("export JSON"); + assert!(document["accounts"][0].get("label").is_none()); + assert_eq!(document["accounts"][0]["createdAt"], now.to_rfc3339()); let imported = service - .prepare_import_document_with_proxy( - serde_json::to_value(exported).expect("export JSON"), - None, - ) + .prepare_import_document_with_proxy(document, None) .await .expect("re-import verifies PAT again"); assert_eq!( @@ -1080,7 +1096,7 @@ async fn api_key_import_export_preserves_target_without_oauth_exchange() { account: imported.account, credential: imported.credential, }, - added_at: now, + created_at: now, updated_at: now, }]) .expect("export") @@ -1136,7 +1152,7 @@ async fn messages_api_key_import_export_preserves_protocol_and_rejects_websocket account: imported.account, credential: imported.credential, }, - added_at: now, + created_at: now, updated_at: now, }]) .unwrap() diff --git a/backend/crates/providers/openai/tests/credential/catalog/contract.rs b/backend/crates/providers/openai/tests/credential/catalog/contract.rs new file mode 100644 index 000000000..c134bf98a --- /dev/null +++ b/backend/crates/providers/openai/tests/credential/catalog/contract.rs @@ -0,0 +1,1303 @@ +//! 跨模块行为合同测试 + +use super::*; + +#[tokio::test] +async fn discovery_refresh_and_export_use_the_current_global_profile() { + use gateway_core::account::OpaqueProviderData; + use serde_json::json; + + let document = + |value: serde_json::Value| OpaqueProviderData::new(value.as_object().unwrap().clone()); + let fixed = |version| { + document( + json!({"client":"cli","platform":"macos","versionMode":"fixed","codexVersion":version}), + ) + }; + let store = Arc::new(MemoryAccountStore::default()); + let first = seed_account(&store, "acct_profile_a").await; + let second = seed_account(&store, "acct_profile_b").await; + let server = MockServer::start().await; + for (version, originator, count) in [ + ("0.169.0", "codex_cli_rs", 2), + ("0.170.0", "codex_cli_rs", 1), + ("0.171.0", "catalog-test", 1), + ] { + Mock::given(method("GET")) + .and(path("/codex/models")) + .and(query_param("client_version", version)) + .and(header("version", version)) + .and(header("originator", originator)) + .and(move |request: &Request| request.headers.get("user-agent").and_then(|v| v.to_str().ok()).is_some_and(|ua| ua.starts_with(&format!("{originator}/{version}")))) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"models":[{"slug":format!("model-{version}"),"display_name":"Native","future_field":true}]}))) + .expect(count).mount(&server).await; + } + let policy = Arc::new(crate::support::RequestProfileRuntimePolicy( + std::sync::Mutex::new(fixed("0.169.0")), + )); + let baseline = wire_profile(); + let service = CodexCredentialCatalogService::new( + store.repository(), + baseline.clone(), + reqwest::Client::builder().no_proxy().build().unwrap(), + server.uri(), + catalog_cache(), + policy.clone(), + ); + service.refresh_catalogs().await.unwrap(); + for account in [&first, &second] { + assert_eq!( + service.cached_account_models(account).unwrap().unwrap(), + ["model-0.169.0"] + ); + } + *policy.0.lock().unwrap() = fixed("0.170.0"); + assert_eq!( + service + .refresh_account_catalog(first.id()) + .await + .unwrap() + .models(), + ["model-0.170.0"] + ); + *policy.0.lock().unwrap() = document( + json!({"mode":"custom","userAgent":"catalog-test/0.171.0","originator":"catalog-test","codexVersion":"0.171.0"}), + ); + let (models, _) = service.account_catalog_documents(&first).await.unwrap(); + assert_eq!(models[0].request_model().as_str(), "model-0.171.0"); + assert_eq!(baseline.snapshot().codex_version, "0.144.0"); + + *policy.0.lock().unwrap() = document(json!({"mode":"custom","userAgent":"invalid"})); + assert!(matches!( + service.refresh_account_catalog(first.id()).await, + Err(CodexCredentialCatalogError::Profile(_)) + )); + assert_eq!( + service.cached_account_models(&first).unwrap().unwrap(), + ["model-0.170.0"] + ); +} + +#[tokio::test] +async fn restored_catalog_is_account_scoped_and_keeps_original_objects() { + let store = Arc::new(MemoryAccountStore::default()); + let first = seed_account(&store, "acct_client_a").await; + let second = seed_account(&store, "acct_client_b").await; + let denied = second.clone().with_model_access( + gateway_core::account::AccountModelAccess::new( + gateway_core::account::AccountModelAccessMode::Denylist, + vec!["gpt-extra".into()], + ) + .unwrap(), + ); + let server = MockServer::start().await; + for (account, text) in [ + ("acct_client_a", "a-original"), + ("acct_client_b", "b-original"), + ] { + Mock::given(method("GET")).and(path("/codex/models")) + .and(header("authorization", format!("Bearer access-{account}"))) + .and(header("chatgpt-account-id", format!("chatgpt-{account}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"models":[{ + "slug":"gpt-native", "display_name":"Native", "base_instructions":text, + "future_field":{"null":null,"list":[1,true]}, "model_messages":{"new_template":text} + }, {"slug": if account == "acct_client_b" {"gpt-extra"} else {"gpt-native-a"}, "display_name":"Additional"}]}))).expect(1).mount(&server).await; + } + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + service.refresh_catalogs().await.unwrap(); + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + service.restore().await.unwrap(); + for (accounts, text, expected) in [ + ( + vec![second.clone(), first.clone()], + "a-original", + vec!["gpt-native", "gpt-native-a", "gpt-extra"], + ), + (vec![second], "b-original", vec!["gpt-native", "gpt-extra"]), + ( + vec![first.clone(), denied], + "a-original", + vec!["gpt-native", "gpt-native-a"], + ), + ( + vec![first], + "a-original", + vec!["gpt-native", "gpt-native-a"], + ), + ] { + let models = service + .client_model_catalog(&client_scope(&accounts)) + .await + .expect("catalog"); + assert_eq!( + models.iter().map(|m| m.model.as_str()).collect::>(), + expected + ); + let document: serde_json::Value = serde_json::from_slice(match &models[0].content { + gateway_core::routing::ProviderModelContent::Native(payload) => payload.body(), + _ => panic!("expected native model"), + }) + .expect("document"); + assert_eq!( + document, + serde_json::json!({ + "slug":"gpt-native", "display_name":"Native", "base_instructions":text, + "future_field":{"null":null,"list":[1,true]}, "model_messages":{"new_template":text} + }) + ); + } + assert!( + service + .client_model_catalog(&client_scope(&[])) + .await + .is_err() + ); + server.verify().await; +} + +#[tokio::test] +async fn client_catalog_cache_does_not_survive_credential_rotation() { + let store = Arc::new(MemoryAccountStore::default()); + let account = seed_account(&store, "acct_client_rotate").await; + let scope = client_scope(std::slice::from_ref(&account)); + let server = MockServer::start().await; + for (token, text) in [ + ("access-acct_client_rotate", "old"), + ("rotated-access", "new"), + ] { + Mock::given(method("GET")) + .and(path("/codex/models")) + .and(header("authorization", format!("Bearer {token}"))) + .respond_with( + ResponseTemplate::new(200).set_body_json(serde_json::json!({"models":[{ + "slug":"gpt-native", "display_name":"Native", "base_instructions":text + }]})), + ) + .expect(1) + .mount(&server) + .await; + } + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + service.refresh_catalogs().await.unwrap(); + let first = service.client_model_catalog(&scope).await.expect("old"); + store + .repository() + .rotate_refreshed_oauth_secret(&account, secret("rotated-access"), None, None) + .await + .expect("rotate"); + assert!(service.client_model_catalog(&scope).await.is_err()); + assert!(matches!( + service.account_catalog_documents(&account).await, + Err(CodexCredentialCatalogError::Credential( + CredentialRepositoryError::RevisionConflict(_) + )) + )); + service.refresh_catalogs().await.unwrap(); + let second = service.client_model_catalog(&scope).await.expect("new"); + assert_ne!(first, second); + server.verify().await; +} + +#[tokio::test] +async fn catalog_refresh_preserves_the_store_cause_for_diagnostics() { + use gateway_core::error::{ErrorDetails, ErrorSource}; + + let store = Arc::new(MemoryAccountStore::default()); + store.fail_provider_listing(); + let error = service(&store).refresh_catalogs().await.unwrap_err(); + assert!(matches!( + error, + CodexCredentialCatalogError::Credential(CredentialRepositoryError::Store(_)) + )); + assert!(!error.to_string().contains("PRIVATE_DATABASE_CAUSE")); + let details = ErrorDetails::capture(Some(&ErrorSource::new(error)), None, false).unwrap(); + assert!(details.as_str().contains("PRIVATE_DATABASE_CAUSE")); +} + +#[tokio::test] +async fn admin_model_catalog_reports_conflicts_and_store_outages_before_querying_upstream() { + use gateway_admin::ports::provider::ProviderAdminErrorKind; + use gateway_core::error::{StoreError, StoreErrorKind}; + + let store = Arc::new(MemoryAccountStore::default()); + let account = seed_account(&store, "acct_catalog_errors").await; + let server = MockServer::start().await; + let bundle = crate::admin::initialized_test_bundle(Arc::clone(&store), server.uri()).await; + for (store_kind, admin_kind) in [ + (StoreErrorKind::Conflict, ProviderAdminErrorKind::Conflict), + ( + StoreErrorKind::Unavailable, + ProviderAdminErrorKind::Unavailable, + ), + ] { + store.on_credential_load(Arc::new(move |_, _, _| { + Box::pin(async move { Err(StoreError::new(store_kind)) }) + })); + let error = bundle.admin.models(account.id(), true).await.unwrap_err(); + assert_eq!(error.kind(), admin_kind); + } + assert!(server.received_requests().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn failed_client_catalog_never_falls_back_to_an_out_of_scope_account_or_cached_profile() { + let store = Arc::new(MemoryAccountStore::default()); + let allowed = seed_account(&store, "acct_client_allowed").await; + seed_account(&store, "acct_client_outside").await; + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/codex/models")) + .and(header("authorization", "Bearer access-acct_client_allowed")) + .respond_with(ResponseTemplate::new(503)) + .expect(1) + .mount(&server) + .await; + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + let scope = client_scope(&[allowed]); + assert!(service.refresh_catalogs().await.is_err()); + for _ in 0..2 { + assert!(service.client_model_catalog(&scope).await.is_err()); + } + assert_eq!(server.received_requests().await.expect("requests").len(), 2); + server.verify().await; +} + +#[tokio::test] +async fn raw_instructions_only_change_advances_catalog_generation() { + let store = Arc::new(MemoryAccountStore::default()); + seed_account(&store, "acct_raw_generation").await; + let server = MockServer::start().await; + Mock::given(method("GET")).and(path("/codex/models")) + .respond_with(SequencedCatalogResponder { + calls: Arc::new(AtomicUsize::new(0)), + bodies: [ + br#"{"models":[{"slug":"gpt-native","display_name":"Native","model_messages":{"future":"old"}}]}"#, + br#"{"models":[{"slug":"gpt-native","display_name":"Native","model_messages":{"future":"new"}}]}"#, + ], + }).expect(2).mount(&server).await; + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + service.refresh_catalogs().await.expect("initial"); + let generation = service.catalog_generation(); + service + .observe_response_etag(&store.account("acct_raw_generation").unwrap(), "new") + .unwrap(); + service.refresh_catalogs().await.expect("refresh"); + assert!(service.catalog_generation() > generation); + server.verify().await; +} + +#[test] +fn catalog_starts_without_a_snapshot_or_generation() { + let store = Arc::new(MemoryAccountStore::default()); + let service = service(&store); + + assert!(service.cached().expect("cache read").is_none()); + assert_eq!(service.catalog_generation().get(), 0); +} + +#[tokio::test] +async fn catalog_without_openai_accounts_fails_before_network_io() { + let store = Arc::new(MemoryAccountStore::default()); + + let error = service(&store) + .refresh_catalogs() + .await + .expect_err("empty account set"); + + assert!(matches!( + error, + CodexCredentialCatalogError::NoEligibleCredential + )); +} + +#[tokio::test] +async fn missing_account_refresh_fails_before_network_io() { + let store = Arc::new(MemoryAccountStore::default()); + let account = ProviderAccountId::new("acct_missing").expect("account id"); + + let error = service(&store) + .refresh_account_catalog(&account) + .await + .expect_err("missing account"); + + assert!(matches!( + error, + CodexCredentialCatalogError::NoEligibleCredential + )); +} + +#[tokio::test] +async fn disabled_account_refresh_discovers_models_with_the_pinned_account() { + let store = Arc::new(MemoryAccountStore::default()); + let account = seed_account(&store, "acct_disabled_models").await; + store + .set_enabled(account.id(), false) + .await + .expect("disable account"); + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/codex/models")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("content-type", "application/json") + .set_body_raw( + br#"{"models":[{"slug":"gpt-5.4","display_name":"GPT-5.4"}]}"#.to_vec(), + "application/json", + ), + ) + .expect(1) + .mount(&server) + .await; + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + + let catalog = service + .refresh_account_catalog(account.id()) + .await + .expect("disabled account refresh still discovers models"); + + assert_eq!(catalog.models(), ["gpt-5.4"]); + server.verify().await; +} + +#[tokio::test] +async fn refreshing_one_account_does_not_replace_a_peers_cached_catalog() { + let store = Arc::new(MemoryAccountStore::default()); + let first = seed_account(&store, "acct_catalog_a").await; + let second = seed_account(&store, "acct_catalog_b").await; + let server = MockServer::start().await; + let calls = Arc::new(AtomicUsize::new(0)); + Mock::given(method("GET")) + .and(path("/codex/models")) + .respond_with(ReplacingCatalogResponder { + calls: Arc::clone(&calls), + }) + .expect(2) + .mount(&server) + .await; + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + + let initial = service + .cached_or_refresh_account_catalog(&first) + .await + .expect("cold cache fetch"); + let cached = service + .cached_or_refresh_account_catalog(&first) + .await + .expect("account cache hit"); + let refreshed = service + .refresh_account_catalog(second.id()) + .await + .expect("manual refresh"); + let replaced = service + .cached_or_refresh_account_catalog(&first) + .await + .expect("peer cache hit"); + + assert_eq!(initial.models(), ["gpt-5.4"]); + assert_eq!(cached.models(), ["gpt-5.4"]); + assert_eq!(refreshed.models(), ["gpt-5.5"]); + assert_eq!(replaced.models(), ["gpt-5.4"]); + assert_eq!(calls.load(Ordering::SeqCst), 2); + server.verify().await; +} + +#[tokio::test] +async fn service_tier_changes_should_replace_cached_metadata_and_advance_generation() { + let store = Arc::new(MemoryAccountStore::default()); + seed_account(&store, "acct_service_tiers").await; + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/codex/models")) + .respond_with(SequencedCatalogResponder { + calls: Arc::new(AtomicUsize::new(0)), + bodies: [ + br#"{"models":[{"slug":"gpt-5.4","display_name":"GPT-5.4","service_tiers":[{"id":"priority","name":"Fast","description":"Priority processing."}]}]}"#, + br#"{"models":[{"slug":"gpt-5.4","display_name":"GPT-5.4","service_tiers":[]}]}"#, + ], + }) + .expect(2) + .mount(&server) + .await; + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + + let initial = service.refresh_catalogs().await.expect("initial catalog"); + let generation = service.catalog_generation().get(); + let cached = service.refresh_catalogs().await.expect("cached catalog"); + assert_eq!(cached.models(), initial.models()); + assert_eq!( + cached.models()[0].metadata().service_tiers(), + [ModelServiceTier::new( + "priority", + "Fast", + "Priority processing." + )] + ); + assert_eq!(service.catalog_generation().get(), generation); + + service + .observe_response_etag(&store.account("acct_service_tiers").unwrap(), "new") + .unwrap(); + let refreshed = service.refresh_catalogs().await.expect("updated catalog"); + assert!(refreshed.models()[0].metadata().service_tiers().is_empty()); + assert_eq!(service.catalog_generation().get(), generation + 1); + assert_eq!( + service + .cached() + .expect("cache read") + .expect("cached snapshot") + .models(), + refreshed.models() + ); +} + +#[tokio::test] +async fn failed_oauth_catalog_does_not_hide_healthy_peers_or_borrow_their_models() { + let store = Arc::new(MemoryAccountStore::default()); + let failed = seed_account(&store, "acct_failed").await; + let healthy = seed_account(&store, "acct_healthy").await; + let server = MockServer::start().await; + for (account, status) in [(&failed, 503), (&healthy, 200)] { + Mock::given(method("GET")) + .and(path("/codex/models")) + .and(header( + "chatgpt-account-id", + format!("chatgpt-{}", account.id()), + )) + .respond_with( + ResponseTemplate::new(status).set_body_raw(OFFICIAL_FIXTURE, "application/json"), + ) + .expect(if status == 503 { 2 } else { 1 }) + .mount(&server) + .await; + } + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + service.refresh_catalogs().await.unwrap(); + let models = service + .client_model_catalog(&client_scope(&[failed.clone(), healthy])) + .await + .unwrap(); + assert_eq!(models.len(), 1); + assert_eq!(models[0].model.as_str(), "gpt-5.4"); + let error = service + .refresh_account_catalog(failed.id()) + .await + .expect_err("account refresh must not use a peer"); + + assert!(matches!( + error, + CodexCredentialCatalogError::Upstream { .. } + )); + server.verify().await; +} + +#[tokio::test] +async fn cross_plan_presentation_drift_unions_on_the_first_seen_model() { + let store = Arc::new(MemoryAccountStore::default()); + seed_account_with_plan(&store, "acct_union_plus", "plus").await; + seed_account_with_plan(&store, "acct_union_pro", "pro").await; + let server = MockServer::start().await; + for (account, name) in [ + ("acct_union_plus", "GPT-5.4 Plus"), + ("acct_union_pro", "GPT-5.4 Pro"), + ] { + Mock::given(method("GET")) + .and(path("/codex/models")) + .and(header("chatgpt-account-id", format!("chatgpt-{account}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "models":[{"slug":"gpt-5.4","display_name":name,"supported_in_api":true}] + }))) + .expect(1) + .mount(&server) + .await; + } + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + + let snapshot = service + .refresh_catalogs() + .await + .expect("presentation drift must not wedge the union"); + + assert_eq!(snapshot.models().len(), 1); + assert_eq!(snapshot.models()[0].display_name(), "GPT-5.4 Plus"); + server.verify().await; +} + +#[tokio::test] +async fn cross_plan_supported_in_api_drift_unions_on_the_first_seen_model() { + let store = Arc::new(MemoryAccountStore::default()); + seed_account_with_plan(&store, "acct_conflict_plus", "plus").await; + seed_account_with_plan(&store, "acct_conflict_pro", "pro").await; + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/codex/models")) + .respond_with(SequencedCatalogResponder { + calls: Arc::new(AtomicUsize::new(0)), + bodies: [ + br#"{"models":[{"slug":"gpt-5.4","display_name":"GPT-5.4","supported_in_api":true}]}"#, + br#"{"models":[{"slug":"gpt-5.4","display_name":"GPT-5.4","supported_in_api":false}]}"#, + ], + }) + .expect(2) + .mount(&server) + .await; + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + + let snapshot = service + .refresh_catalogs() + .await + .expect("supported_in_api drift must not block catalog publication"); + + assert_eq!(snapshot.models().len(), 1); + server.verify().await; +} + +#[tokio::test] +async fn account_entitlements_keep_the_discovering_account_across_plans() { + let store = Arc::new(MemoryAccountStore::default()); + let first_free = seed_account_with_plan(&store, "acct_free_a", "free").await; + let second_free = seed_account_with_plan(&store, "acct_free_b", "free").await; + let k12 = seed_account_with_plan(&store, "acct_k12", "k12").await; + let server = MockServer::start().await; + for (account, extra) in [(&first_free, false), (&second_free, true), (&k12, true)] { + let mut models = vec![serde_json::json!({"slug":"gpt-5.4","display_name":"GPT-5.4"})]; + if extra { + models.push(serde_json::json!({"slug":"gpt-5.6-sol","display_name":"Sol"})); + } + Mock::given(method("GET")) + .and(path("/codex/models")) + .and(header( + "chatgpt-account-id", + format!("chatgpt-{}", account.id()), + )) + .respond_with( + ResponseTemplate::new(200).set_body_json(serde_json::json!({"models":models})), + ) + .expect(1) + .mount(&server) + .await; + } + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + + let snapshot = service + .refresh_catalogs() + .await + .expect("mixed-plan catalog"); + + assert_eq!(snapshot.models().len(), 2); + assert_eq!( + service + .cached_account_models(&first_free) + .expect("first free entitlement"), + Some(vec!["gpt-5.4".to_owned()]) + ); + assert_eq!( + service + .cached_account_models(&second_free) + .expect("second free entitlement"), + Some(vec!["gpt-5.4".to_owned(), "gpt-5.6-sol".to_owned()]) + ); + assert_eq!( + service.cached_account_models(&k12).expect("K12 catalog"), + Some(vec!["gpt-5.4".to_owned(), "gpt-5.6-sol".to_owned()]) + ); + assert_eq!( + snapshot.model_catalog_accounts()["gpt-5.6-sol"], + std::collections::BTreeSet::from([second_free.id().clone(), k12.id().clone()]) + ); + let restarted = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + restarted.restore().await.unwrap(); + let restored = restarted.refresh_catalogs().await.unwrap(); + assert_eq!( + restored.model_catalog_accounts(), + snapshot.model_catalog_accounts() + ); + server.verify().await; +} + +#[tokio::test] +async fn api_key_catalogs_are_isolated_and_join_oauth_without_claiming_native_metadata() { + use provider_openai::credential::ResponsesTransport; + let oauth = MockServer::start().await; + let first = MockServer::start().await; + let second = MockServer::start().await; + let store = Arc::new(MemoryAccountStore::default()); + let oauth_account = seed_account(&store, "acct_oauth").await; + store + .seed_api_key("acct_first", first.uri(), ResponsesTransport::Http) + .await; + store + .seed_api_key("acct_second", second.uri(), ResponsesTransport::Http) + .await; + let a = store.account("acct_first").unwrap(); + let b = store.account("acct_second").unwrap(); + Mock::given(method("GET")) + .and(path("/codex/models")) + .respond_with(ResponseTemplate::new(200).set_body_json( + serde_json::json!({"models":[{"slug":"oauth-model","display_name":"OAuth model"}]}), + )) + .mount(&oauth) + .await; + Mock::given(method("GET")) + .and(path("/models")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(serde_json::json!({"data":[{"id":"api-first"}]})), + ) + .mount(&first) + .await; + Mock::given(method("GET")) + .and(path("/models")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(serde_json::json!({"data":[{"id":"api-second"}]})), + ) + .mount(&second) + .await; + let service = service_with_catalog_cache(&store, oauth.uri(), catalog_cache()); + service.refresh_catalogs().await.unwrap(); + assert_eq!( + service.cached_account_models(&a).unwrap().unwrap(), + ["api-first"] + ); + assert_eq!( + service.cached_account_models(&b).unwrap().unwrap(), + ["api-second"] + ); + let combined = service + .client_model_catalog(&client_scope(&[oauth_account, a.clone()])) + .await + .unwrap(); + assert_eq!( + combined + .iter() + .map(|entry| entry.model.as_str()) + .collect::>(), + ["oauth-model", "api-first"] + ); + assert!(matches!( + combined[0].content, + gateway_core::routing::ProviderModelContent::Native(_) + )); + assert!(matches!( + combined[1].content, + gateway_core::routing::ProviderModelContent::Adapted(_) + )); + first.reset().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(503)) + .mount(&first) + .await; + service + .invalidate_accounts(&[ProviderAccountId::new("acct_first").unwrap()]) + .await + .unwrap(); + service + .refresh_catalogs() + .await + .expect("failed upstream must not hide other accounts"); + assert_eq!( + service.cached_account_models(&b).unwrap().unwrap(), + ["api-second"] + ); +} + +#[tokio::test] +async fn api_key_catalog_retries_only_explicit_version_parameter_rejections() { + use provider_openai::credential::ResponsesTransport; + use serde_json::json; + + for (status, code, param, retry) in [ + (400, "unknown_parameter", "client_version", true), + (422, "unsupported_parameter", "client_version", true), + (400, "unknown_parameter", "other", false), + (400, "invalid_value", "client_version", false), + (429, "unsupported_parameter", "client_version", false), + ] { + let upstream = MockServer::start().await; + let store = Arc::new(MemoryAccountStore::default()); + store + .seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http) + .await; + Mock::given(method("GET")) + .and(path("/models")) + .and(query_param("client_version", "0.144.0")) + .respond_with( + ResponseTemplate::new(status) + .set_body_json(json!({"error":{"code":code,"param":param}})), + ) + .expect(1) + .mount(&upstream) + .await; + Mock::given(method("GET")) + .and(path("/models")) + .and(|request: &Request| request.url.query().is_none()) + .respond_with( + ResponseTemplate::new(200).set_body_json(json!({"data":[{"id":"api-model"}]})), + ) + .expect(u64::from(retry)) + .mount(&upstream) + .await; + let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); + let account = store.account("acct_api").unwrap(); + let result = service.refresh_account_catalog(account.id()).await; + if retry { + assert_eq!(result.unwrap().models(), ["api-model"]); + } else { + assert!(matches!( + result, + Err(CodexCredentialCatalogError::Upstream { .. }) + )); + } + upstream.verify().await; + } +} + +#[tokio::test] +async fn api_key_client_catalog_distinguishes_filtered_empty_from_fetch_failure() { + use gateway_core::account::AccountModelAccess; + use provider_openai::credential::ResponsesTransport; + for status in [200, 503] { + let upstream = MockServer::start().await; + let store = Arc::new(MemoryAccountStore::default()); + store + .seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http) + .await; + store.set_model_access( + "acct_api", + AccountModelAccess::new( + gateway_core::account::AccountModelAccessMode::Allowlist, + vec!["logical-model".into()], + ) + .unwrap(), + ); + Mock::given(method("GET")) + .and(path("/models")) + .respond_with( + ResponseTemplate::new(status) + .set_body_json(serde_json::json!({"data":[{"id":"wire-model"}]})), + ) + .expect(1) + .mount(&upstream) + .await; + let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); + assert_eq!(service.refresh_catalogs().await.is_ok(), status == 200); + let result = service + .client_model_catalog(&client_scope(&[store.account("acct_api").unwrap()])) + .await; + if status == 200 { + assert!( + result + .expect("success filtered by account policy") + .is_empty() + ); + } else { + assert!( + result.is_err(), + "fetch failure must not look like a successful empty catalog" + ); + } + upstream.verify().await; + } +} + +#[tokio::test] +async fn api_key_client_catalog_keeps_native_sources_stable_and_account_scoped() { + use gateway_core::routing::ProviderModelContent; + use provider_openai::credential::ResponsesTransport; + use serde_json::json; + + let upstream = MockServer::start().await; + let store = Arc::new(MemoryAccountStore::default()); + let mut accounts = Vec::new(); + for (id, delay, body) in [ + ("acct_a", 0, json!({"data":[{"id":"shared"}]})), + ( + "acct_b", + 30, + json!({"models":[{"slug":"shared", "display_name":"First native", "default_reasoning_level":"high"}]}), + ), + ( + "acct_c", + 0, + json!({"models":[{"slug":"shared", "display_name":"Second native", "default_reasoning_level":"low"}]}), + ), + ] { + store + .seed_api_key( + id, + format!("{}/{id}", upstream.uri()), + ResponsesTransport::Http, + ) + .await; + accounts.push(store.account(id).unwrap()); + Mock::given(method("GET")) + .and(path(format!("/{id}/models"))) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(body) + .set_delay(std::time::Duration::from_millis(delay)), + ) + .expect(1) + .mount(&upstream) + .await; + } + let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); + service.refresh_catalogs().await.unwrap(); + for (scope_accounts, expected) in [ + (&accounts[..], "First native"), + (&accounts[2..], "Second native"), + ] { + let models = service + .client_model_catalog(&client_scope(scope_accounts)) + .await + .unwrap(); + assert_eq!(models.len(), 1); + let ProviderModelContent::Native(payload) = &models[0].content else { + panic!("native catalog must take precedence over plain IDs") + }; + let document: serde_json::Value = serde_json::from_slice(payload.body()).unwrap(); + assert_eq!(document["display_name"], expected); + } + upstream.verify().await; +} + +#[tokio::test] +async fn api_key_client_catalog_cache_is_invalidated_by_credential_revision() { + use gateway_core::account::{CredentialCasOutcome, CredentialCasUpdate, ProviderAccountUpdate}; + use provider_openai::credential::ResponsesTransport; + + let upstream = MockServer::start().await; + let store = Arc::new(MemoryAccountStore::default()); + store + .seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http) + .await; + let account = store.account("acct_api").unwrap(); + let scope = client_scope(std::slice::from_ref(&account)); + let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); + for model in ["before-rotation", "after-rotation"] { + upstream.reset().await; + Mock::given(method("GET")) + .and(path("/models")) + .respond_with( + ResponseTemplate::new(200).set_body_json(serde_json::json!({"models":[{ + "slug":model, "display_name":model + }]})), + ) + .expect(1) + .mount(&upstream) + .await; + assert!(service.client_model_catalog(&scope).await.is_err()); + service.refresh_catalogs().await.unwrap(); + let models = service.client_model_catalog(&scope).await.unwrap(); + assert_eq!(models[0].model.as_str(), model); + upstream.verify().await; + if model == "before-rotation" { + let loaded = store.load_current_credential(account.id()).await.unwrap(); + let update = CredentialCasUpdate::new( + account.id().clone(), + account.revision(), + ProviderAccountUpdate { + account_id: account.id().clone(), + name: account.name().to_owned(), + email: None, + plan_type: None, + }, + loaded.credential, + false, + None, + None, + ) + .unwrap(); + assert!(matches!( + store.compare_and_swap_credential(update).await.unwrap(), + CredentialCasOutcome::Updated(_) + )); + } + } +} + +#[tokio::test] +async fn api_key_catalog_hides_only_known_specialized_models_in_codex_picker() { + use provider_openai::credential::ResponsesTransport; + use provider_openai::transport::CodexCatalogCapabilityEvidence; + + let upstream = MockServer::start().await; + let store = Arc::new(MemoryAccountStore::default()); + store + .seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http) + .await; + let picker_visibility = [ + ("gpt-5.4", true), + ("ft:gpt-4.1-mini:example:custom:abc", true), + ("vendor/model", true), + ("gpt-image-2-custom", true), + ("gpt-image-2", false), + ("gpt-image-2-2026-04-21", false), + ("gpt-live-1", false), + ("gpt-realtime-2", false), + ("tts-1", false), + ]; + let ids = picker_visibility.map(|(id, _)| id); + Mock::given(method("GET")) + .and(path("/models")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "data": ids.map(|id| serde_json::json!({"id": id})) + }))) + .mount(&upstream) + .await; + let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); + let snapshot = service.refresh_catalogs().await.expect("standard API IDs"); + assert_eq!( + snapshot + .models() + .iter() + .map(|model| model.request_model().as_str()) + .collect::>(), + ids + ); + for model in snapshot.models() { + assert_eq!( + model.capabilities().reasoning(), + CodexCatalogCapabilityEvidence::Unknown + ); + assert_eq!(model.limits().context_window_tokens(), None); + } + let account = store.account("acct_api").expect("API account"); + let models = service + .client_model_catalog(&client_scope(&[account])) + .await + .expect("client catalog"); + let actual_visibility = models.iter().map(|model| { + let gateway_core::routing::ProviderModelContent::Adapted(presentation) = &model.content + else { + panic!("plain API IDs must remain adapted") + }; + assert!(presentation.supported_reasoning_efforts().is_empty()); + assert_eq!(presentation.default_reasoning_effort(), None); + (model.model.as_str(), !presentation.hidden()) + }); + assert_eq!( + actual_visibility.collect::>(), + picker_visibility.into_iter().collect() + ); +} + +#[tokio::test] +async fn api_key_catalog_rejects_invalid_ids_and_duplicates() { + use provider_openai::credential::ResponsesTransport; + + let upstream = MockServer::start().await; + let store = Arc::new(MemoryAccountStore::default()); + store + .seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http) + .await; + let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); + for invalid in [ + String::new(), + "__reserved".to_owned(), + "model\nname".to_owned(), + " model".to_owned(), + "x".repeat(257), + "valid-model".to_owned(), + ] { + upstream.reset().await; + Mock::given(method("GET")) + .and(path("/models")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "data": [{"id":"valid-model"}, {"id":invalid}] + }))) + .mount(&upstream) + .await; + assert!( + service.refresh_catalogs().await.is_err(), + "invalid entry accepted: {invalid:?}" + ); + assert!(service.cached().expect("cache").is_none()); + } +} + +#[tokio::test] +async fn api_key_catalog_does_not_replace_native_metadata_for_shared_models() { + use gateway_core::routing::ProviderModelContent; + use provider_openai::credential::ResponsesTransport; + + let oauth = MockServer::start().await; + let upstream = MockServer::start().await; + let store = Arc::new(MemoryAccountStore::default()); + let oauth_account = seed_account(&store, "acct_oauth").await; + Mock::given(method("GET")).and(path("/codex/models")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"models":[{ + "slug":"gpt-5.4", "display_name":"Official Model", "context_window":272000, + "input_modalities":["text","image"], "supported_reasoning_levels":[{"effort":"high"}] + }]}))) + .mount(&oauth).await; + let service = service_with_catalog_cache(&store, oauth.uri(), catalog_cache()); + let before = service.refresh_catalogs().await.expect("OAuth directory"); + store + .seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http) + .await; + Mock::given(method("GET")) + .and(path("/models")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(serde_json::json!({"data":[{"id":"gpt-5.4"}]})), + ) + .mount(&upstream) + .await; + + let after = service.refresh_catalogs().await.expect("mixed directory"); + assert_eq!( + after.models(), + before.models(), + "preserve the complete native model" + ); + + let api_account = store.account("acct_api").expect("API account"); + assert_eq!( + service.cached_account_models(&api_account).unwrap(), + service.cached_account_models(&oauth_account).unwrap() + ); + let mixed = service + .client_model_catalog(&client_scope(&[oauth_account, api_account.clone()])) + .await + .expect("mixed client catalog"); + assert_eq!(mixed.len(), 1); + let ProviderModelContent::Native(payload) = &mixed[0].content else { + panic!("native metadata expected") + }; + assert_eq!(payload, before.models()[0].document()); + let api_only = service + .client_model_catalog(&client_scope(std::slice::from_ref(&api_account))) + .await + .expect("API client catalog"); + assert!(matches!( + api_only[0].content, + ProviderModelContent::Adapted(_) + )); + let (api_documents, _) = service + .account_catalog_documents(&api_account) + .await + .expect("target API account directory"); + assert_eq!(api_documents.len(), 1); + assert_ne!(api_documents[0].document().protocol(), "codex"); +} + +#[tokio::test] +async fn account_catalog_documents_keep_native_objects_of_the_account_plan() { + let store = Arc::new(MemoryAccountStore::default()); + let plus = seed_account_with_plan(&store, "acct_catalog_plus", "plus").await; + let pro = seed_account_with_plan(&store, "acct_catalog_pro", "pro").await; + let server = MockServer::start().await; + for (account, unique_model, name, context_window) in [ + ("acct_catalog_plus", "gpt-plus", "Plus", 128_000), + ("acct_catalog_pro", "gpt-pro", "Pro", 272_000), + ] { + Mock::given(method("GET")) + .and(path("/codex/models")) + .and(header("authorization", format!("Bearer access-{account}"))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "models": [ + {"slug": unique_model, "display_name": name, "context_window": context_window}, + {"slug": "gpt-shared", "display_name": name, "context_window": context_window} + ] + }))) + .expect(2) + .mount(&server) + .await; + } + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + let snapshot = service + .refresh_catalogs() + .await + .expect("shared union snapshot"); + assert_eq!(snapshot.models().len(), 3); + assert_eq!(snapshot.models()[1].display_name(), "Plus"); + + let (models, _) = service + .account_catalog_documents(&pro) + .await + .expect("pro catalog"); + assert_eq!(models.len(), 2); + assert_eq!(models[0].request_model().as_str(), "gpt-pro"); + assert_eq!(models[1].request_model().as_str(), "gpt-shared"); + // 导出的目录文件靠原生对象携带上下文窗口等元数据,正文必须原样保留 + assert_eq!(models[0].document().protocol(), "codex"); + let document: serde_json::Value = + serde_json::from_slice(models[1].document().body()).expect("native document"); + assert_eq!(document["context_window"], 272_000); + assert_eq!(document["display_name"], "Pro"); + + // 另一套餐的账号不能拿到别的套餐条目,否则客户端会列出自己用不了的模型 + let (plus_models, _) = service + .account_catalog_documents(&plus) + .await + .expect("plus catalog"); + assert_eq!(plus_models.len(), 2); + assert_eq!(plus_models[0].request_model().as_str(), "gpt-plus"); + let plus_document: serde_json::Value = + serde_json::from_slice(plus_models[1].document().body()).expect("plus native document"); + assert_eq!(plus_document["context_window"], 128_000); + + server.verify().await; +} + +#[tokio::test] +async fn disabled_account_can_export_native_catalog_without_a_cached_snapshot() { + let store = Arc::new(MemoryAccountStore::default()); + let account = seed_account(&store, "acct_disabled_export").await; + store + .set_enabled(account.id(), false) + .await + .expect("disable account"); + let disabled = store + .account("acct_disabled_export") + .expect("disabled account"); + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/codex/models")) + .and(header( + "authorization", + "Bearer access-acct_disabled_export", + )) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "models": [{"slug": "gpt-5.4", "display_name": "GPT-5.4", "context_window": 272000}] + }))) + .expect(1) + .mount(&server) + .await; + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + + let (models, _) = service + .account_catalog_documents(&disabled) + .await + .expect("disabled account export"); + assert_eq!(models.len(), 1); + assert_eq!(models[0].document().protocol(), "codex"); + server.verify().await; +} + +#[tokio::test] +async fn catalog_account_membership_changes_advance_generation_without_model_changes() { + use std::collections::BTreeSet; + let store = Arc::new(MemoryAccountStore::default()); + let first = seed_account(&store, "acct_source_a").await; + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/codex/models")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "models": [{"slug": "gpt-5.4", "display_name": "GPT-5.4"}] + }))) + .expect(2) + .mount(&server) + .await; + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + let initial = service.refresh_catalogs().await.unwrap(); + let generation = service.catalog_generation(); + let second = seed_account(&store, "acct_source_b").await; + let refreshed = service.refresh_catalogs().await.unwrap(); + assert_eq!(initial.models(), refreshed.models()); + assert!(service.catalog_generation() > generation); + assert_eq!( + initial.model_catalog_accounts()["gpt-5.4"], + BTreeSet::from([first.id().clone()]) + ); + assert_eq!( + refreshed.model_catalog_accounts()["gpt-5.4"], + BTreeSet::from([first.id().clone(), second.id().clone()]) + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn ten_thousand_restored_accounts_serve_concurrent_native_reads_while_upstream_stalls() { + use futures::{StreamExt as _, stream}; + use gateway_core::account::AccountCatalogObservation; + use std::time::{Duration, Instant, SystemTime}; + let store = Arc::new(MemoryAccountStore::default()); + let document = [&[0_u8][..], OFFICIAL_FIXTURE].concat(); + let mut accounts = Vec::new(); + for index in 0..10_000 { + let account = seed_account(&store, &format!("acct_load_{index:05}")).await; + assert!( + store + .save_account_catalog( + &AccountCatalogObservation { + account_id: account.id().clone(), + revision: account.revision(), + plan: account.plan_type().map(str::to_owned), + observed_at: SystemTime::now(), + etag: None + }, + &document + ) + .await + .unwrap() + ); + accounts.push(account); + } + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/codex/models")) + .respond_with(ResponseTemplate::new(503).set_delay(Duration::from_secs(30))) + .expect(1) + .mount(&server) + .await; + let catalog = Arc::new(service_with_catalog_cache( + &store, + server.uri(), + catalog_cache(), + )); + let start = Instant::now(); + catalog.restore().await.unwrap(); + let restore = start.elapsed(); + catalog.refresh_catalogs().await.unwrap(); + assert!(server.received_requests().await.unwrap().is_empty()); + let scope = Arc::new(client_scope(&accounts)); + catalog + .observe_response_etag(&accounts[0], "\"load-change\"") + .unwrap(); + let refresh = tokio::spawn({ + let catalog = catalog.clone(); + async move { catalog.refresh_catalogs().await } + }); + tokio::time::timeout(Duration::from_secs(5), async { + while server.received_requests().await.unwrap().is_empty() { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + const REQUESTS: usize = 2048; + let start = Instant::now(); + let reads = stream::iter(0..REQUESTS) + .map(|_| { + let catalog = catalog.clone(); + let scope = scope.clone(); + tokio::spawn(async move { + let started = Instant::now(); + let models = catalog.client_model_catalog(&scope).await.unwrap(); + assert!(!models.is_empty()); + started.elapsed() + }) + }) + .buffer_unordered(64) + .collect::>(); + let mut samples = tokio::time::timeout(Duration::from_secs(10), reads) + .await + .unwrap() + .into_iter() + .map(Result::unwrap) + .collect::>(); + samples.sort_unstable(); + eprintln!( + "catalog load: 10000 accounts, {REQUESTS} successful requests, concurrency 64, restore={} ms, elapsed={} ms, p50={} us, p95={} us, p99={} us", + restore.as_millis(), + start.elapsed().as_millis(), + samples[REQUESTS / 2].as_micros(), + samples[REQUESTS * 95 / 100].as_micros(), + samples[REQUESTS * 99 / 100].as_micros() + ); + assert!(!refresh.is_finished()); + refresh.abort(); + assert!(refresh.await.unwrap_err().is_cancelled()); + server.verify().await; +} diff --git a/backend/crates/providers/openai/tests/credential/catalog/mod.rs b/backend/crates/providers/openai/tests/credential/catalog/mod.rs index ef0f00426..a9157d082 100644 --- a/backend/crates/providers/openai/tests/credential/catalog/mod.rs +++ b/backend/crates/providers/openai/tests/credential/catalog/mod.rs @@ -1,5 +1,7 @@ //! 验证 OpenAI 模型目录的账号和版本隔离、缓存合并与失效 +mod contract; +mod refresh; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -15,7 +17,7 @@ use provider_openai::credential::{ CodexCredentialCatalogError, CodexCredentialCatalogService, CredentialRepositoryError, ImportCodexOAuthCredential, }; -use provider_openai::transport::profile::{CodexWireProfile, CodexWireProfileState}; +use provider_openai::profile::{CodexWireProfile, CodexWireProfileState}; use wiremock::matchers::{header, method, path, query_param}; use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate}; @@ -24,82 +26,6 @@ use crate::support::{MemoryAccountStore, catalog_cache, profile, secret}; const OFFICIAL_FIXTURE: &[u8] = include_bytes!("../../transport/fixtures/official_models_snapshot.json"); -#[tokio::test] -async fn discovery_refresh_and_export_use_the_current_global_profile() { - use gateway_core::account::OpaqueProviderData; - use serde_json::json; - - let document = - |value: serde_json::Value| OpaqueProviderData::new(value.as_object().unwrap().clone()); - let fixed = |version| { - document( - json!({"client":"cli","platform":"macos","versionMode":"fixed","codexVersion":version}), - ) - }; - let store = Arc::new(MemoryAccountStore::default()); - let first = seed_account(&store, "acct_profile_a").await; - let second = seed_account(&store, "acct_profile_b").await; - let server = MockServer::start().await; - for (version, originator, count) in [ - ("0.169.0", "codex_cli_rs", 2), - ("0.170.0", "codex_cli_rs", 1), - ("0.171.0", "catalog-test", 1), - ] { - Mock::given(method("GET")) - .and(path("/codex/models")) - .and(query_param("client_version", version)) - .and(header("version", version)) - .and(header("originator", originator)) - .and(move |request: &Request| request.headers.get("user-agent").and_then(|v| v.to_str().ok()).is_some_and(|ua| ua.starts_with(&format!("{originator}/{version}")))) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({"models":[{"slug":format!("model-{version}"),"display_name":"Native","future_field":true}]}))) - .expect(count).mount(&server).await; - } - let policy = Arc::new(crate::support::RequestProfileRuntimePolicy( - std::sync::Mutex::new(fixed("0.169.0")), - )); - let baseline = wire_profile(); - let service = CodexCredentialCatalogService::new( - store.repository(), - baseline.clone(), - reqwest::Client::builder().no_proxy().build().unwrap(), - server.uri(), - catalog_cache(), - policy.clone(), - ); - service.refresh_catalogs().await.unwrap(); - for account in [&first, &second] { - assert_eq!( - service.cached_account_models(account).unwrap().unwrap(), - ["model-0.169.0"] - ); - } - *policy.0.lock().unwrap() = fixed("0.170.0"); - assert_eq!( - service - .refresh_account_catalog(first.id()) - .await - .unwrap() - .models(), - ["model-0.170.0"] - ); - *policy.0.lock().unwrap() = document( - json!({"mode":"custom","userAgent":"catalog-test/0.171.0","originator":"catalog-test","codexVersion":"0.171.0"}), - ); - let (models, _) = service.account_catalog_documents(&first).await.unwrap(); - assert_eq!(models[0].request_model().as_str(), "model-0.171.0"); - assert_eq!(baseline.snapshot().codex_version, "0.144.0"); - - *policy.0.lock().unwrap() = document(json!({"mode":"custom","userAgent":"invalid"})); - assert!(matches!( - service.refresh_account_catalog(first.id()).await, - Err(CodexCredentialCatalogError::Profile(_)) - )); - assert_eq!( - service.cached_account_models(&first).unwrap().unwrap(), - ["model-0.170.0"] - ); -} - struct ReplacingCatalogResponder { calls: Arc, } @@ -134,7 +60,7 @@ impl Respond for SequencedCatalogResponder { fn wire_profile() -> CodexWireProfileState { CodexWireProfileState::new(CodexWireProfile { - client_kind: provider_openai::transport::profile::selection::ClientKind::Desktop, + client_kind: provider_openai::profile::selection::ClientKind::Desktop, originator: "codex_cli_rs".to_owned(), codex_version: "0.144.0".to_owned(), desktop_version: "1.0.0".to_owned(), @@ -220,1463 +146,3 @@ fn client_scope(accounts: &[ProviderAccount]) -> FrozenAccountScope { ClientRoutingScope::all_accounts(), ) } - -#[tokio::test] -async fn restored_catalog_is_account_scoped_and_keeps_original_objects() { - let store = Arc::new(MemoryAccountStore::default()); - let first = seed_account(&store, "acct_client_a").await; - let second = seed_account(&store, "acct_client_b").await; - let denied = second.clone().with_model_access( - gateway_core::account::AccountModelAccess::new( - gateway_core::account::AccountModelAccessMode::Denylist, - vec!["gpt-extra".into()], - ) - .unwrap(), - ); - let server = MockServer::start().await; - for (account, text) in [ - ("acct_client_a", "a-original"), - ("acct_client_b", "b-original"), - ] { - Mock::given(method("GET")).and(path("/codex/models")) - .and(header("authorization", format!("Bearer access-{account}"))) - .and(header("chatgpt-account-id", format!("chatgpt-{account}"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"models":[{ - "slug":"gpt-native", "display_name":"Native", "base_instructions":text, - "future_field":{"null":null,"list":[1,true]}, "model_messages":{"new_template":text} - }, {"slug": if account == "acct_client_b" {"gpt-extra"} else {"gpt-native-a"}, "display_name":"Additional"}]}))).expect(1).mount(&server).await; - } - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - service.refresh_catalogs().await.unwrap(); - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - service.restore().await.unwrap(); - for (accounts, text, expected) in [ - ( - vec![second.clone(), first.clone()], - "a-original", - vec!["gpt-native", "gpt-native-a", "gpt-extra"], - ), - (vec![second], "b-original", vec!["gpt-native", "gpt-extra"]), - ( - vec![first.clone(), denied], - "a-original", - vec!["gpt-native", "gpt-native-a"], - ), - ( - vec![first], - "a-original", - vec!["gpt-native", "gpt-native-a"], - ), - ] { - let models = service - .client_model_catalog(&client_scope(&accounts)) - .await - .expect("catalog"); - assert_eq!( - models.iter().map(|m| m.model.as_str()).collect::>(), - expected - ); - let document: serde_json::Value = serde_json::from_slice(match &models[0].content { - gateway_core::routing::ProviderModelContent::Native(payload) => payload.body(), - _ => panic!("expected native model"), - }) - .expect("document"); - assert_eq!( - document, - serde_json::json!({ - "slug":"gpt-native", "display_name":"Native", "base_instructions":text, - "future_field":{"null":null,"list":[1,true]}, "model_messages":{"new_template":text} - }) - ); - } - assert!( - service - .client_model_catalog(&client_scope(&[])) - .await - .is_err() - ); - server.verify().await; -} - -#[tokio::test] -async fn client_catalog_cache_does_not_survive_credential_rotation() { - let store = Arc::new(MemoryAccountStore::default()); - let account = seed_account(&store, "acct_client_rotate").await; - let scope = client_scope(std::slice::from_ref(&account)); - let server = MockServer::start().await; - for (token, text) in [ - ("access-acct_client_rotate", "old"), - ("rotated-access", "new"), - ] { - Mock::given(method("GET")) - .and(path("/codex/models")) - .and(header("authorization", format!("Bearer {token}"))) - .respond_with( - ResponseTemplate::new(200).set_body_json(serde_json::json!({"models":[{ - "slug":"gpt-native", "display_name":"Native", "base_instructions":text - }]})), - ) - .expect(1) - .mount(&server) - .await; - } - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - service.refresh_catalogs().await.unwrap(); - let first = service.client_model_catalog(&scope).await.expect("old"); - store - .repository() - .rotate_refreshed_oauth_secret(&account, secret("rotated-access"), None, None) - .await - .expect("rotate"); - assert!(service.client_model_catalog(&scope).await.is_err()); - assert!(matches!( - service.account_catalog_documents(&account).await, - Err(CodexCredentialCatalogError::Credential( - CredentialRepositoryError::RevisionConflict(_) - )) - )); - service.refresh_catalogs().await.unwrap(); - let second = service.client_model_catalog(&scope).await.expect("new"); - assert_ne!(first, second); - server.verify().await; -} - -#[tokio::test] -async fn catalog_refresh_preserves_the_store_cause_for_diagnostics() { - use gateway_core::error::{ErrorDetails, ErrorSource}; - - let store = Arc::new(MemoryAccountStore::default()); - store.fail_provider_listing(); - let error = service(&store).refresh_catalogs().await.unwrap_err(); - assert!(matches!( - error, - CodexCredentialCatalogError::Credential(CredentialRepositoryError::Store(_)) - )); - assert!(!error.to_string().contains("PRIVATE_DATABASE_CAUSE")); - let details = ErrorDetails::capture(Some(&ErrorSource::new(error)), None, false).unwrap(); - assert!(details.as_str().contains("PRIVATE_DATABASE_CAUSE")); -} - -#[tokio::test] -async fn admin_model_catalog_reports_conflicts_and_store_outages_before_querying_upstream() { - use gateway_admin::ports::provider::ProviderAdminErrorKind; - use gateway_core::error::{StoreError, StoreErrorKind}; - - let store = Arc::new(MemoryAccountStore::default()); - let account = seed_account(&store, "acct_catalog_errors").await; - let server = MockServer::start().await; - let bundle = crate::admin::initialized_test_bundle(Arc::clone(&store), server.uri()).await; - for (store_kind, admin_kind) in [ - (StoreErrorKind::Conflict, ProviderAdminErrorKind::Conflict), - ( - StoreErrorKind::Unavailable, - ProviderAdminErrorKind::Unavailable, - ), - ] { - store.on_credential_load(Arc::new(move |_, _, _| { - Box::pin(async move { Err(StoreError::new(store_kind)) }) - })); - let error = bundle - .admin_provider() - .models(account.id(), true) - .await - .unwrap_err(); - assert_eq!(error.kind(), admin_kind); - } - assert!(server.received_requests().await.unwrap().is_empty()); -} - -#[tokio::test] -async fn failed_client_catalog_never_falls_back_to_an_out_of_scope_account_or_cached_profile() { - let store = Arc::new(MemoryAccountStore::default()); - let allowed = seed_account(&store, "acct_client_allowed").await; - seed_account(&store, "acct_client_outside").await; - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/codex/models")) - .and(header("authorization", "Bearer access-acct_client_allowed")) - .respond_with(ResponseTemplate::new(503)) - .expect(1) - .mount(&server) - .await; - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - let scope = client_scope(&[allowed]); - assert!(service.refresh_catalogs().await.is_err()); - for _ in 0..2 { - assert!(service.client_model_catalog(&scope).await.is_err()); - } - assert_eq!(server.received_requests().await.expect("requests").len(), 2); - server.verify().await; -} - -#[tokio::test] -async fn raw_instructions_only_change_advances_catalog_generation() { - let store = Arc::new(MemoryAccountStore::default()); - seed_account(&store, "acct_raw_generation").await; - let server = MockServer::start().await; - Mock::given(method("GET")).and(path("/codex/models")) - .respond_with(SequencedCatalogResponder { - calls: Arc::new(AtomicUsize::new(0)), - bodies: [ - br#"{"models":[{"slug":"gpt-native","display_name":"Native","model_messages":{"future":"old"}}]}"#, - br#"{"models":[{"slug":"gpt-native","display_name":"Native","model_messages":{"future":"new"}}]}"#, - ], - }).expect(2).mount(&server).await; - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - service.refresh_catalogs().await.expect("initial"); - let generation = service.catalog_generation(); - service - .observe_response_etag(&store.account("acct_raw_generation").unwrap(), "new") - .unwrap(); - service.refresh_catalogs().await.expect("refresh"); - assert!(service.catalog_generation() > generation); - server.verify().await; -} - -#[test] -fn catalog_starts_without_a_snapshot_or_generation() { - let store = Arc::new(MemoryAccountStore::default()); - let service = service(&store); - - assert!(service.cached().expect("cache read").is_none()); - assert_eq!(service.catalog_generation().get(), 0); -} - -#[tokio::test] -async fn catalog_without_openai_accounts_fails_before_network_io() { - let store = Arc::new(MemoryAccountStore::default()); - - let error = service(&store) - .refresh_catalogs() - .await - .expect_err("empty account set"); - - assert!(matches!( - error, - CodexCredentialCatalogError::NoEligibleCredential - )); -} - -#[tokio::test] -async fn missing_account_refresh_fails_before_network_io() { - let store = Arc::new(MemoryAccountStore::default()); - let account = ProviderAccountId::new("acct_missing").expect("account id"); - - let error = service(&store) - .refresh_account_catalog(&account) - .await - .expect_err("missing account"); - - assert!(matches!( - error, - CodexCredentialCatalogError::NoEligibleCredential - )); -} - -#[tokio::test] -async fn disabled_account_refresh_discovers_models_with_the_pinned_account() { - let store = Arc::new(MemoryAccountStore::default()); - let account = seed_account(&store, "acct_disabled_models").await; - store - .set_enabled(account.id(), false) - .await - .expect("disable account"); - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/codex/models")) - .respond_with( - ResponseTemplate::new(200) - .insert_header("content-type", "application/json") - .set_body_raw( - br#"{"models":[{"slug":"gpt-5.4","display_name":"GPT-5.4"}]}"#.to_vec(), - "application/json", - ), - ) - .expect(1) - .mount(&server) - .await; - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - - let catalog = service - .refresh_account_catalog(account.id()) - .await - .expect("disabled account refresh still discovers models"); - - assert_eq!(catalog.models(), ["gpt-5.4"]); - server.verify().await; -} - -#[tokio::test] -async fn refreshing_one_account_does_not_replace_a_peers_cached_catalog() { - let store = Arc::new(MemoryAccountStore::default()); - let first = seed_account(&store, "acct_catalog_a").await; - let second = seed_account(&store, "acct_catalog_b").await; - let server = MockServer::start().await; - let calls = Arc::new(AtomicUsize::new(0)); - Mock::given(method("GET")) - .and(path("/codex/models")) - .respond_with(ReplacingCatalogResponder { - calls: Arc::clone(&calls), - }) - .expect(2) - .mount(&server) - .await; - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - - let initial = service - .cached_or_refresh_account_catalog(&first) - .await - .expect("cold cache fetch"); - let cached = service - .cached_or_refresh_account_catalog(&first) - .await - .expect("account cache hit"); - let refreshed = service - .refresh_account_catalog(second.id()) - .await - .expect("manual refresh"); - let replaced = service - .cached_or_refresh_account_catalog(&first) - .await - .expect("peer cache hit"); - - assert_eq!(initial.models(), ["gpt-5.4"]); - assert_eq!(cached.models(), ["gpt-5.4"]); - assert_eq!(refreshed.models(), ["gpt-5.5"]); - assert_eq!(replaced.models(), ["gpt-5.4"]); - assert_eq!(calls.load(Ordering::SeqCst), 2); - server.verify().await; -} - -#[tokio::test] -async fn service_tier_changes_should_replace_cached_metadata_and_advance_generation() { - let store = Arc::new(MemoryAccountStore::default()); - seed_account(&store, "acct_service_tiers").await; - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/codex/models")) - .respond_with(SequencedCatalogResponder { - calls: Arc::new(AtomicUsize::new(0)), - bodies: [ - br#"{"models":[{"slug":"gpt-5.4","display_name":"GPT-5.4","service_tiers":[{"id":"priority","name":"Fast","description":"Priority processing."}]}]}"#, - br#"{"models":[{"slug":"gpt-5.4","display_name":"GPT-5.4","service_tiers":[]}]}"#, - ], - }) - .expect(2) - .mount(&server) - .await; - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - - let initial = service.refresh_catalogs().await.expect("initial catalog"); - let generation = service.catalog_generation().get(); - let cached = service.refresh_catalogs().await.expect("cached catalog"); - assert_eq!(cached.models(), initial.models()); - assert_eq!( - cached.models()[0].metadata().service_tiers(), - [ModelServiceTier::new( - "priority", - "Fast", - "Priority processing." - )] - ); - assert_eq!(service.catalog_generation().get(), generation); - - service - .observe_response_etag(&store.account("acct_service_tiers").unwrap(), "new") - .unwrap(); - let refreshed = service.refresh_catalogs().await.expect("updated catalog"); - assert!(refreshed.models()[0].metadata().service_tiers().is_empty()); - assert_eq!(service.catalog_generation().get(), generation + 1); - assert_eq!( - service - .cached() - .expect("cache read") - .expect("cached snapshot") - .models(), - refreshed.models() - ); -} - -#[tokio::test] -async fn failed_oauth_catalog_does_not_hide_healthy_peers_or_borrow_their_models() { - let store = Arc::new(MemoryAccountStore::default()); - let failed = seed_account(&store, "acct_failed").await; - let healthy = seed_account(&store, "acct_healthy").await; - let server = MockServer::start().await; - for (account, status) in [(&failed, 503), (&healthy, 200)] { - Mock::given(method("GET")) - .and(path("/codex/models")) - .and(header( - "chatgpt-account-id", - format!("chatgpt-{}", account.id()), - )) - .respond_with( - ResponseTemplate::new(status).set_body_raw(OFFICIAL_FIXTURE, "application/json"), - ) - .expect(if status == 503 { 2 } else { 1 }) - .mount(&server) - .await; - } - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - service.refresh_catalogs().await.unwrap(); - let models = service - .client_model_catalog(&client_scope(&[failed.clone(), healthy])) - .await - .unwrap(); - assert_eq!(models.len(), 1); - assert_eq!(models[0].model.as_str(), "gpt-5.4"); - let error = service - .refresh_account_catalog(failed.id()) - .await - .expect_err("account refresh must not use a peer"); - - assert!(matches!( - error, - CodexCredentialCatalogError::Upstream { .. } - )); - server.verify().await; -} - -#[tokio::test] -async fn cross_plan_presentation_drift_unions_on_the_first_seen_model() { - let store = Arc::new(MemoryAccountStore::default()); - seed_account_with_plan(&store, "acct_union_plus", "plus").await; - seed_account_with_plan(&store, "acct_union_pro", "pro").await; - let server = MockServer::start().await; - for (account, name) in [ - ("acct_union_plus", "GPT-5.4 Plus"), - ("acct_union_pro", "GPT-5.4 Pro"), - ] { - Mock::given(method("GET")) - .and(path("/codex/models")) - .and(header("chatgpt-account-id", format!("chatgpt-{account}"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "models":[{"slug":"gpt-5.4","display_name":name,"supported_in_api":true}] - }))) - .expect(1) - .mount(&server) - .await; - } - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - - let snapshot = service - .refresh_catalogs() - .await - .expect("presentation drift must not wedge the union"); - - assert_eq!(snapshot.models().len(), 1); - assert_eq!(snapshot.models()[0].display_name(), "GPT-5.4 Plus"); - server.verify().await; -} - -#[tokio::test] -async fn cross_plan_supported_in_api_drift_unions_on_the_first_seen_model() { - let store = Arc::new(MemoryAccountStore::default()); - seed_account_with_plan(&store, "acct_conflict_plus", "plus").await; - seed_account_with_plan(&store, "acct_conflict_pro", "pro").await; - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/codex/models")) - .respond_with(SequencedCatalogResponder { - calls: Arc::new(AtomicUsize::new(0)), - bodies: [ - br#"{"models":[{"slug":"gpt-5.4","display_name":"GPT-5.4","supported_in_api":true}]}"#, - br#"{"models":[{"slug":"gpt-5.4","display_name":"GPT-5.4","supported_in_api":false}]}"#, - ], - }) - .expect(2) - .mount(&server) - .await; - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - - let snapshot = service - .refresh_catalogs() - .await - .expect("supported_in_api drift must not block catalog publication"); - - assert_eq!(snapshot.models().len(), 1); - server.verify().await; -} - -#[tokio::test] -async fn account_entitlements_keep_the_discovering_account_across_plans() { - let store = Arc::new(MemoryAccountStore::default()); - let first_free = seed_account_with_plan(&store, "acct_free_a", "free").await; - let second_free = seed_account_with_plan(&store, "acct_free_b", "free").await; - let k12 = seed_account_with_plan(&store, "acct_k12", "k12").await; - let server = MockServer::start().await; - for (account, extra) in [(&first_free, false), (&second_free, true), (&k12, true)] { - let mut models = vec![serde_json::json!({"slug":"gpt-5.4","display_name":"GPT-5.4"})]; - if extra { - models.push(serde_json::json!({"slug":"gpt-5.6-sol","display_name":"Sol"})); - } - Mock::given(method("GET")) - .and(path("/codex/models")) - .and(header( - "chatgpt-account-id", - format!("chatgpt-{}", account.id()), - )) - .respond_with( - ResponseTemplate::new(200).set_body_json(serde_json::json!({"models":models})), - ) - .expect(1) - .mount(&server) - .await; - } - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - - let snapshot = service - .refresh_catalogs() - .await - .expect("mixed-plan catalog"); - - assert_eq!(snapshot.models().len(), 2); - assert_eq!( - service - .cached_account_models(&first_free) - .expect("first free entitlement"), - Some(vec!["gpt-5.4".to_owned()]) - ); - assert_eq!( - service - .cached_account_models(&second_free) - .expect("second free entitlement"), - Some(vec!["gpt-5.4".to_owned(), "gpt-5.6-sol".to_owned()]) - ); - assert_eq!( - service.cached_account_models(&k12).expect("K12 catalog"), - Some(vec!["gpt-5.4".to_owned(), "gpt-5.6-sol".to_owned()]) - ); - assert_eq!( - snapshot.model_catalog_accounts()["gpt-5.6-sol"], - std::collections::BTreeSet::from([second_free.id().clone(), k12.id().clone()]) - ); - let restarted = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - restarted.restore().await.unwrap(); - let restored = restarted.refresh_catalogs().await.unwrap(); - assert_eq!( - restored.model_catalog_accounts(), - snapshot.model_catalog_accounts() - ); - server.verify().await; -} - -#[tokio::test] -async fn invalidation_queues_background_refresh_without_an_upstream_etag() { - let store = Arc::new(MemoryAccountStore::default()); - let service = service(&store); - service - .invalidate_accounts(&[ProviderAccountId::new("acct_first").unwrap()]) - .await - .unwrap(); - service - .invalidate_accounts(&[ProviderAccountId::new("acct_first").unwrap()]) - .await - .unwrap(); - tokio::time::timeout( - std::time::Duration::from_secs(1), - service.wait_for_refresh(), - ) - .await - .expect("configuration invalidation must wake the catalog worker"); - assert!( - tokio::time::timeout( - std::time::Duration::from_millis(50), - service.wait_for_refresh(), - ) - .await - .is_err(), - "duplicate invalidations should share one pending refresh" - ); -} - -#[tokio::test] -async fn matching_etag_renews_only_its_account_until_the_next_change_or_expiry() { - use gateway_core::account::AccountCatalogObservation; - use std::time::{Duration, SystemTime}; - - let store = Arc::new(MemoryAccountStore::default()); - let active = seed_account(&store, "acct_active").await; - let idle = seed_account(&store, "acct_idle").await; - let document = [&[0_u8][..], OFFICIAL_FIXTURE].concat(); - let old_tag = r#""v1""#; - let new_tag = r#""v2""#; - let observed_at = SystemTime::now() - Duration::from_mins(61); - for account in [&active, &idle] { - assert!( - store - .save_account_catalog( - &AccountCatalogObservation { - account_id: account.id().clone(), - revision: account.revision(), - plan: account.plan_type().map(str::to_owned), - observed_at, - etag: Some(old_tag.to_owned()), - }, - &document - ) - .await - .unwrap() - ); - } - let server = MockServer::start().await; - for account in [&active, &idle] { - Mock::given(method("GET")) - .and(path("/codex/models")) - .and(header( - "chatgpt-account-id", - format!("chatgpt-{}", account.id()), - )) - .respond_with( - ResponseTemplate::new(200) - .insert_header("etag", old_tag) - .set_body_raw(OFFICIAL_FIXTURE, "application/json"), - ) - .expect(1) - .mount(&server) - .await; - } - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - service.restore().await.unwrap(); - assert!(!service.observe_response_etag(&active, old_tag).unwrap()); - service.refresh_catalogs().await.unwrap(); - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 1); - assert_eq!( - requests[0].headers["chatgpt-account-id"], - "chatgpt-acct_idle" - ); - - tokio::time::pause(); - tokio::time::advance(Duration::from_mins(59)).await; - service.refresh_catalogs().await.unwrap(); - assert_eq!(server.received_requests().await.unwrap().len(), 1); - tokio::time::advance(Duration::from_mins(1)).await; - tokio::time::resume(); - service.refresh_catalogs().await.unwrap(); - server.verify().await; - - server.reset().await; - Mock::given(method("GET")) - .and(path("/codex/models")) - .and(header("chatgpt-account-id", "chatgpt-acct_active")) - .respond_with( - ResponseTemplate::new(200) - .insert_header("etag", new_tag) - .set_body_json( - serde_json::json!({"models":[{"slug":"active-only","display_name":"Active"}]}), - ), - ) - .expect(1) - .mount(&server) - .await; - assert!(!service.observe_response_etag(&active, old_tag).unwrap()); - assert!( - service - .observe_response_etag(&active, "change-hint") - .unwrap() - ); - assert!(!service.observe_response_etag(&active, old_tag).unwrap()); - service.refresh_catalogs().await.unwrap(); - assert!( - !service - .observe_response_etag(&active, "change-hint") - .unwrap() - ); - assert!(!service.observe_response_etag(&active, new_tag).unwrap()); - service.refresh_catalogs().await.unwrap(); - assert_eq!( - service.cached_account_models(&active).unwrap().unwrap(), - ["active-only"] - ); - server.verify().await; -} - -#[tokio::test] -async fn simultaneous_periodic_refreshes_share_the_completed_scan() { - let store = Arc::new(MemoryAccountStore::default()); - for index in 0..64 { - seed_account(&store, &format!("acct_refresh_{index:02}")).await; - } - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/codex/models")) - .respond_with( - ResponseTemplate::new(200) - .set_body_raw(OFFICIAL_FIXTURE.to_vec(), "application/json") - .set_delay(std::time::Duration::from_millis(20)), - ) - .expect(64) - .mount(&server) - .await; - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - let (first, second, third) = tokio::join!( - service.refresh_catalogs(), - service.refresh_catalogs(), - service.refresh_catalogs(), - ); - let first = first.expect("first refresh"); - assert_eq!(first.models(), second.expect("shared refresh").models()); - assert_eq!(first.models(), third.expect("shared refresh").models()); - server.verify().await; -} - -#[tokio::test] -async fn api_key_catalogs_are_isolated_and_join_oauth_without_claiming_native_metadata() { - use provider_openai::credential::ResponsesTransport; - let oauth = MockServer::start().await; - let first = MockServer::start().await; - let second = MockServer::start().await; - let store = Arc::new(MemoryAccountStore::default()); - let oauth_account = seed_account(&store, "acct_oauth").await; - store - .seed_api_key("acct_first", first.uri(), ResponsesTransport::Http) - .await; - store - .seed_api_key("acct_second", second.uri(), ResponsesTransport::Http) - .await; - let a = store.account("acct_first").unwrap(); - let b = store.account("acct_second").unwrap(); - Mock::given(method("GET")) - .and(path("/codex/models")) - .respond_with(ResponseTemplate::new(200).set_body_json( - serde_json::json!({"models":[{"slug":"oauth-model","display_name":"OAuth model"}]}), - )) - .mount(&oauth) - .await; - Mock::given(method("GET")) - .and(path("/models")) - .respond_with( - ResponseTemplate::new(200) - .set_body_json(serde_json::json!({"data":[{"id":"api-first"}]})), - ) - .mount(&first) - .await; - Mock::given(method("GET")) - .and(path("/models")) - .respond_with( - ResponseTemplate::new(200) - .set_body_json(serde_json::json!({"data":[{"id":"api-second"}]})), - ) - .mount(&second) - .await; - let service = service_with_catalog_cache(&store, oauth.uri(), catalog_cache()); - service.refresh_catalogs().await.unwrap(); - assert_eq!( - service.cached_account_models(&a).unwrap().unwrap(), - ["api-first"] - ); - assert_eq!( - service.cached_account_models(&b).unwrap().unwrap(), - ["api-second"] - ); - let combined = service - .client_model_catalog(&client_scope(&[oauth_account, a.clone()])) - .await - .unwrap(); - assert_eq!( - combined - .iter() - .map(|entry| entry.model.as_str()) - .collect::>(), - ["oauth-model", "api-first"] - ); - assert!(matches!( - combined[0].content, - gateway_core::routing::ProviderModelContent::Native(_) - )); - assert!(matches!( - combined[1].content, - gateway_core::routing::ProviderModelContent::Adapted(_) - )); - first.reset().await; - Mock::given(method("GET")) - .respond_with(ResponseTemplate::new(503)) - .mount(&first) - .await; - service - .invalidate_accounts(&[ProviderAccountId::new("acct_first").unwrap()]) - .await - .unwrap(); - service - .refresh_catalogs() - .await - .expect("failed upstream must not hide other accounts"); - assert_eq!( - service.cached_account_models(&b).unwrap().unwrap(), - ["api-second"] - ); -} - -#[tokio::test] -async fn api_key_background_catalog_preserves_negotiated_reasoning_levels_and_entitlements() { - use gateway_core::routing::ProviderModelContent; - use provider_openai::credential::ResponsesTransport; - use provider_openai::transport::CodexCatalogCapabilityEvidence; - use serde_json::json; - - let upstream = MockServer::start().await; - let store = Arc::new(MemoryAccountStore::default()); - store - .seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http) - .await; - let original = json!({"slug":"z-unknown-reasoning", "display_name":"Unknown reasoning"}); - let second = json!({ - "slug":"vendor/model", "display_name":"Second upstream model", - "default_reasoning_level":"high", - "supported_reasoning_levels":[{"effort":"high","description":"Upstream description"}] - }); - Mock::given(method("GET")) - .and(path("/models")) - .respond_with({ - let native = json!({"models":[original, second]}); - move |request: &Request| { - if request.url.query() == Some("client_version=0.144.0") { - ResponseTemplate::new(200).set_body_json(&native) - } else { - ResponseTemplate::new(200).set_body_json(json!({"data":[ - {"id":"z-unknown-reasoning"}, {"id":"vendor/model"} - ]})) - } - } - }) - .expect(1) - .mount(&upstream) - .await; - let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); - let snapshot = service - .refresh_catalogs() - .await - .expect("native background directory"); - assert_eq!( - snapshot.models()[0].capabilities().reasoning(), - CodexCatalogCapabilityEvidence::Unknown - ); - let account = store.account("acct_api").unwrap(); - assert_eq!( - service.cached_account_models(&account).unwrap().unwrap(), - ["z-unknown-reasoning", "vendor/model"] - ); - let models = service - .client_model_catalog(&client_scope(&[account])) - .await - .unwrap(); - assert_eq!( - models - .iter() - .map(|model| model.model.as_str()) - .collect::>(), - ["z-unknown-reasoning", "vendor/model"] - ); - for (model, expected) in models.iter().zip([original, second]) { - let ProviderModelContent::Native(payload) = &model.content else { - panic!("native model expected") - }; - assert_eq!( - serde_json::from_slice::(payload.body()).unwrap(), - expected - ); - } - upstream.verify().await; -} - -#[tokio::test] -async fn api_key_catalog_retries_only_explicit_version_parameter_rejections() { - use provider_openai::credential::ResponsesTransport; - use serde_json::json; - - for (status, code, param, retry) in [ - (400, "unknown_parameter", "client_version", true), - (422, "unsupported_parameter", "client_version", true), - (400, "unknown_parameter", "other", false), - (400, "invalid_value", "client_version", false), - (429, "unsupported_parameter", "client_version", false), - ] { - let upstream = MockServer::start().await; - let store = Arc::new(MemoryAccountStore::default()); - store - .seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http) - .await; - Mock::given(method("GET")) - .and(path("/models")) - .and(query_param("client_version", "0.144.0")) - .respond_with( - ResponseTemplate::new(status) - .set_body_json(json!({"error":{"code":code,"param":param}})), - ) - .expect(1) - .mount(&upstream) - .await; - Mock::given(method("GET")) - .and(path("/models")) - .and(|request: &Request| request.url.query().is_none()) - .respond_with( - ResponseTemplate::new(200).set_body_json(json!({"data":[{"id":"api-model"}]})), - ) - .expect(u64::from(retry)) - .mount(&upstream) - .await; - let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); - let account = store.account("acct_api").unwrap(); - let result = service.refresh_account_catalog(account.id()).await; - if retry { - assert_eq!(result.unwrap().models(), ["api-model"]); - } else { - assert!(matches!( - result, - Err(CodexCredentialCatalogError::Upstream { .. }) - )); - } - upstream.verify().await; - } -} - -#[tokio::test] -async fn api_key_client_catalog_distinguishes_filtered_empty_from_fetch_failure() { - use gateway_core::account::AccountModelAccess; - use provider_openai::credential::ResponsesTransport; - for status in [200, 503] { - let upstream = MockServer::start().await; - let store = Arc::new(MemoryAccountStore::default()); - store - .seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http) - .await; - store.set_model_access( - "acct_api", - AccountModelAccess::new( - gateway_core::account::AccountModelAccessMode::Allowlist, - vec!["logical-model".into()], - ) - .unwrap(), - ); - Mock::given(method("GET")) - .and(path("/models")) - .respond_with( - ResponseTemplate::new(status) - .set_body_json(serde_json::json!({"data":[{"id":"wire-model"}]})), - ) - .expect(1) - .mount(&upstream) - .await; - let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); - assert_eq!(service.refresh_catalogs().await.is_ok(), status == 200); - let result = service - .client_model_catalog(&client_scope(&[store.account("acct_api").unwrap()])) - .await; - if status == 200 { - assert!( - result - .expect("success filtered by account policy") - .is_empty() - ); - } else { - assert!( - result.is_err(), - "fetch failure must not look like a successful empty catalog" - ); - } - upstream.verify().await; - } -} - -#[tokio::test] -async fn api_key_client_catalog_keeps_native_sources_stable_and_account_scoped() { - use gateway_core::routing::ProviderModelContent; - use provider_openai::credential::ResponsesTransport; - use serde_json::json; - - let upstream = MockServer::start().await; - let store = Arc::new(MemoryAccountStore::default()); - let mut accounts = Vec::new(); - for (id, delay, body) in [ - ("acct_a", 0, json!({"data":[{"id":"shared"}]})), - ( - "acct_b", - 30, - json!({"models":[{"slug":"shared", "display_name":"First native", "default_reasoning_level":"high"}]}), - ), - ( - "acct_c", - 0, - json!({"models":[{"slug":"shared", "display_name":"Second native", "default_reasoning_level":"low"}]}), - ), - ] { - store - .seed_api_key( - id, - format!("{}/{id}", upstream.uri()), - ResponsesTransport::Http, - ) - .await; - accounts.push(store.account(id).unwrap()); - Mock::given(method("GET")) - .and(path(format!("/{id}/models"))) - .respond_with( - ResponseTemplate::new(200) - .set_body_json(body) - .set_delay(std::time::Duration::from_millis(delay)), - ) - .expect(1) - .mount(&upstream) - .await; - } - let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); - service.refresh_catalogs().await.unwrap(); - for (scope_accounts, expected) in [ - (&accounts[..], "First native"), - (&accounts[2..], "Second native"), - ] { - let models = service - .client_model_catalog(&client_scope(scope_accounts)) - .await - .unwrap(); - assert_eq!(models.len(), 1); - let ProviderModelContent::Native(payload) = &models[0].content else { - panic!("native catalog must take precedence over plain IDs") - }; - let document: serde_json::Value = serde_json::from_slice(payload.body()).unwrap(); - assert_eq!(document["display_name"], expected); - } - upstream.verify().await; -} - -#[tokio::test] -async fn api_key_client_catalog_cache_is_invalidated_by_credential_revision() { - use gateway_core::account::{CredentialCasOutcome, CredentialCasUpdate, ProviderAccountUpdate}; - use provider_openai::credential::ResponsesTransport; - - let upstream = MockServer::start().await; - let store = Arc::new(MemoryAccountStore::default()); - store - .seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http) - .await; - let account = store.account("acct_api").unwrap(); - let scope = client_scope(std::slice::from_ref(&account)); - let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); - for model in ["before-rotation", "after-rotation"] { - upstream.reset().await; - Mock::given(method("GET")) - .and(path("/models")) - .respond_with( - ResponseTemplate::new(200).set_body_json(serde_json::json!({"models":[{ - "slug":model, "display_name":model - }]})), - ) - .expect(1) - .mount(&upstream) - .await; - assert!(service.client_model_catalog(&scope).await.is_err()); - service.refresh_catalogs().await.unwrap(); - let models = service.client_model_catalog(&scope).await.unwrap(); - assert_eq!(models[0].model.as_str(), model); - upstream.verify().await; - if model == "before-rotation" { - let loaded = store.load_current_credential(account.id()).await.unwrap(); - let update = CredentialCasUpdate::new( - account.id().clone(), - account.revision(), - ProviderAccountUpdate { - account_id: account.id().clone(), - name: account.name().to_owned(), - email: None, - plan_type: None, - }, - loaded.credential, - false, - None, - None, - ) - .unwrap(); - assert!(matches!( - store.compare_and_swap_credential(update).await.unwrap(), - CredentialCasOutcome::Updated(_) - )); - } - } -} - -#[tokio::test] -async fn api_key_catalog_hides_only_known_specialized_models_in_codex_picker() { - use provider_openai::credential::ResponsesTransport; - use provider_openai::transport::CodexCatalogCapabilityEvidence; - - let upstream = MockServer::start().await; - let store = Arc::new(MemoryAccountStore::default()); - store - .seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http) - .await; - let picker_visibility = [ - ("gpt-5.4", true), - ("ft:gpt-4.1-mini:example:custom:abc", true), - ("vendor/model", true), - ("gpt-image-2-custom", true), - ("gpt-image-2", false), - ("gpt-image-2-2026-04-21", false), - ("gpt-live-1", false), - ("gpt-realtime-2", false), - ("tts-1", false), - ]; - let ids = picker_visibility.map(|(id, _)| id); - Mock::given(method("GET")) - .and(path("/models")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "data": ids.map(|id| serde_json::json!({"id": id})) - }))) - .mount(&upstream) - .await; - let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); - let snapshot = service.refresh_catalogs().await.expect("standard API IDs"); - assert_eq!( - snapshot - .models() - .iter() - .map(|model| model.request_model().as_str()) - .collect::>(), - ids - ); - for model in snapshot.models() { - assert_eq!( - model.capabilities().reasoning(), - CodexCatalogCapabilityEvidence::Unknown - ); - assert_eq!(model.limits().context_window_tokens(), None); - } - let account = store.account("acct_api").expect("API account"); - let models = service - .client_model_catalog(&client_scope(&[account])) - .await - .expect("client catalog"); - let actual_visibility = models.iter().map(|model| { - let gateway_core::routing::ProviderModelContent::Adapted(presentation) = &model.content - else { - panic!("plain API IDs must remain adapted") - }; - assert!(presentation.supported_reasoning_efforts().is_empty()); - assert_eq!(presentation.default_reasoning_effort(), None); - (model.model.as_str(), !presentation.hidden()) - }); - assert_eq!( - actual_visibility.collect::>(), - picker_visibility.into_iter().collect() - ); -} - -#[tokio::test] -async fn api_key_catalog_rejects_invalid_ids_and_duplicates() { - use provider_openai::credential::ResponsesTransport; - - let upstream = MockServer::start().await; - let store = Arc::new(MemoryAccountStore::default()); - store - .seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http) - .await; - let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); - for invalid in [ - String::new(), - "__reserved".to_owned(), - "model\nname".to_owned(), - " model".to_owned(), - "x".repeat(257), - "valid-model".to_owned(), - ] { - upstream.reset().await; - Mock::given(method("GET")) - .and(path("/models")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "data": [{"id":"valid-model"}, {"id":invalid}] - }))) - .mount(&upstream) - .await; - assert!( - service.refresh_catalogs().await.is_err(), - "invalid entry accepted: {invalid:?}" - ); - assert!(service.cached().expect("cache").is_none()); - } -} - -#[tokio::test] -async fn api_key_catalog_does_not_replace_native_metadata_for_shared_models() { - use gateway_core::routing::ProviderModelContent; - use provider_openai::credential::ResponsesTransport; - - let oauth = MockServer::start().await; - let upstream = MockServer::start().await; - let store = Arc::new(MemoryAccountStore::default()); - let oauth_account = seed_account(&store, "acct_oauth").await; - Mock::given(method("GET")).and(path("/codex/models")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"models":[{ - "slug":"gpt-5.4", "display_name":"Official Model", "context_window":272000, - "input_modalities":["text","image"], "supported_reasoning_levels":[{"effort":"high"}] - }]}))) - .mount(&oauth).await; - let service = service_with_catalog_cache(&store, oauth.uri(), catalog_cache()); - let before = service.refresh_catalogs().await.expect("OAuth directory"); - store - .seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http) - .await; - Mock::given(method("GET")) - .and(path("/models")) - .respond_with( - ResponseTemplate::new(200) - .set_body_json(serde_json::json!({"data":[{"id":"gpt-5.4"}]})), - ) - .mount(&upstream) - .await; - - let after = service.refresh_catalogs().await.expect("mixed directory"); - assert_eq!( - after.models(), - before.models(), - "preserve the complete native model" - ); - - let api_account = store.account("acct_api").expect("API account"); - assert_eq!( - service.cached_account_models(&api_account).unwrap(), - service.cached_account_models(&oauth_account).unwrap() - ); - let mixed = service - .client_model_catalog(&client_scope(&[oauth_account, api_account.clone()])) - .await - .expect("mixed client catalog"); - assert_eq!(mixed.len(), 1); - let ProviderModelContent::Native(payload) = &mixed[0].content else { - panic!("native metadata expected") - }; - assert_eq!(payload, before.models()[0].document()); - let api_only = service - .client_model_catalog(&client_scope(std::slice::from_ref(&api_account))) - .await - .expect("API client catalog"); - assert!(matches!( - api_only[0].content, - ProviderModelContent::Adapted(_) - )); - let (api_documents, _) = service - .account_catalog_documents(&api_account) - .await - .expect("target API account directory"); - assert_eq!(api_documents.len(), 1); - assert_ne!(api_documents[0].document().protocol(), "codex"); -} - -#[tokio::test] -async fn account_catalog_documents_keep_native_objects_of_the_account_plan() { - let store = Arc::new(MemoryAccountStore::default()); - let plus = seed_account_with_plan(&store, "acct_catalog_plus", "plus").await; - let pro = seed_account_with_plan(&store, "acct_catalog_pro", "pro").await; - let server = MockServer::start().await; - for (account, unique_model, name, context_window) in [ - ("acct_catalog_plus", "gpt-plus", "Plus", 128_000), - ("acct_catalog_pro", "gpt-pro", "Pro", 272_000), - ] { - Mock::given(method("GET")) - .and(path("/codex/models")) - .and(header("authorization", format!("Bearer access-{account}"))) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "models": [ - {"slug": unique_model, "display_name": name, "context_window": context_window}, - {"slug": "gpt-shared", "display_name": name, "context_window": context_window} - ] - }))) - .expect(2) - .mount(&server) - .await; - } - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - let snapshot = service - .refresh_catalogs() - .await - .expect("shared union snapshot"); - assert_eq!(snapshot.models().len(), 3); - assert_eq!(snapshot.models()[1].display_name(), "Plus"); - - let (models, _) = service - .account_catalog_documents(&pro) - .await - .expect("pro catalog"); - assert_eq!(models.len(), 2); - assert_eq!(models[0].request_model().as_str(), "gpt-pro"); - assert_eq!(models[1].request_model().as_str(), "gpt-shared"); - // 导出的目录文件靠原生对象携带上下文窗口等元数据,正文必须原样保留 - assert_eq!(models[0].document().protocol(), "codex"); - let document: serde_json::Value = - serde_json::from_slice(models[1].document().body()).expect("native document"); - assert_eq!(document["context_window"], 272_000); - assert_eq!(document["display_name"], "Pro"); - - // 另一套餐的账号不能拿到别的套餐条目,否则客户端会列出自己用不了的模型 - let (plus_models, _) = service - .account_catalog_documents(&plus) - .await - .expect("plus catalog"); - assert_eq!(plus_models.len(), 2); - assert_eq!(plus_models[0].request_model().as_str(), "gpt-plus"); - let plus_document: serde_json::Value = - serde_json::from_slice(plus_models[1].document().body()).expect("plus native document"); - assert_eq!(plus_document["context_window"], 128_000); - - server.verify().await; -} - -#[tokio::test] -async fn disabled_account_can_export_native_catalog_without_a_cached_snapshot() { - let store = Arc::new(MemoryAccountStore::default()); - let account = seed_account(&store, "acct_disabled_export").await; - store - .set_enabled(account.id(), false) - .await - .expect("disable account"); - let disabled = store - .account("acct_disabled_export") - .expect("disabled account"); - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/codex/models")) - .and(header( - "authorization", - "Bearer access-acct_disabled_export", - )) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "models": [{"slug": "gpt-5.4", "display_name": "GPT-5.4", "context_window": 272000}] - }))) - .expect(1) - .mount(&server) - .await; - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - - let (models, _) = service - .account_catalog_documents(&disabled) - .await - .expect("disabled account export"); - assert_eq!(models.len(), 1); - assert_eq!(models[0].document().protocol(), "codex"); - server.verify().await; -} - -#[tokio::test] -async fn catalog_account_membership_changes_advance_generation_without_model_changes() { - use std::collections::BTreeSet; - let store = Arc::new(MemoryAccountStore::default()); - let first = seed_account(&store, "acct_source_a").await; - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/codex/models")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "models": [{"slug": "gpt-5.4", "display_name": "GPT-5.4"}] - }))) - .expect(2) - .mount(&server) - .await; - let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); - let initial = service.refresh_catalogs().await.unwrap(); - let generation = service.catalog_generation(); - let second = seed_account(&store, "acct_source_b").await; - let refreshed = service.refresh_catalogs().await.unwrap(); - assert_eq!(initial.models(), refreshed.models()); - assert!(service.catalog_generation() > generation); - assert_eq!( - initial.model_catalog_accounts()["gpt-5.4"], - BTreeSet::from([first.id().clone()]) - ); - assert_eq!( - refreshed.model_catalog_accounts()["gpt-5.4"], - BTreeSet::from([first.id().clone(), second.id().clone()]) - ); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn ten_thousand_restored_accounts_serve_concurrent_native_reads_while_upstream_stalls() { - use futures::{StreamExt as _, stream}; - use gateway_core::account::AccountCatalogObservation; - use std::time::{Duration, Instant, SystemTime}; - let store = Arc::new(MemoryAccountStore::default()); - let document = [&[0_u8][..], OFFICIAL_FIXTURE].concat(); - let mut accounts = Vec::new(); - for index in 0..10_000 { - let account = seed_account(&store, &format!("acct_load_{index:05}")).await; - assert!( - store - .save_account_catalog( - &AccountCatalogObservation { - account_id: account.id().clone(), - revision: account.revision(), - plan: account.plan_type().map(str::to_owned), - observed_at: SystemTime::now(), - etag: None - }, - &document - ) - .await - .unwrap() - ); - accounts.push(account); - } - let server = MockServer::start().await; - Mock::given(method("GET")) - .and(path("/codex/models")) - .respond_with(ResponseTemplate::new(503).set_delay(Duration::from_secs(30))) - .expect(1) - .mount(&server) - .await; - let catalog = Arc::new(service_with_catalog_cache( - &store, - server.uri(), - catalog_cache(), - )); - let start = Instant::now(); - catalog.restore().await.unwrap(); - let restore = start.elapsed(); - catalog.refresh_catalogs().await.unwrap(); - assert!(server.received_requests().await.unwrap().is_empty()); - let scope = Arc::new(client_scope(&accounts)); - catalog - .observe_response_etag(&accounts[0], "\"load-change\"") - .unwrap(); - let refresh = tokio::spawn({ - let catalog = catalog.clone(); - async move { catalog.refresh_catalogs().await } - }); - tokio::time::timeout(Duration::from_secs(5), async { - while server.received_requests().await.unwrap().is_empty() { - tokio::task::yield_now().await; - } - }) - .await - .unwrap(); - const REQUESTS: usize = 2048; - let start = Instant::now(); - let reads = stream::iter(0..REQUESTS) - .map(|_| { - let catalog = catalog.clone(); - let scope = scope.clone(); - tokio::spawn(async move { - let started = Instant::now(); - let models = catalog.client_model_catalog(&scope).await.unwrap(); - assert!(!models.is_empty()); - started.elapsed() - }) - }) - .buffer_unordered(64) - .collect::>(); - let mut samples = tokio::time::timeout(Duration::from_secs(10), reads) - .await - .unwrap() - .into_iter() - .map(Result::unwrap) - .collect::>(); - samples.sort_unstable(); - eprintln!( - "catalog load: 10000 accounts, {REQUESTS} successful requests, concurrency 64, restore={} ms, elapsed={} ms, p50={} us, p95={} us, p99={} us", - restore.as_millis(), - start.elapsed().as_millis(), - samples[REQUESTS / 2].as_micros(), - samples[REQUESTS * 95 / 100].as_micros(), - samples[REQUESTS * 99 / 100].as_micros() - ); - assert!(!refresh.is_finished()); - refresh.abort(); - assert!(refresh.await.unwrap_err().is_cancelled()); - server.verify().await; -} diff --git a/backend/crates/providers/openai/tests/credential/catalog/refresh.rs b/backend/crates/providers/openai/tests/credential/catalog/refresh.rs new file mode 100644 index 000000000..8381df631 --- /dev/null +++ b/backend/crates/providers/openai/tests/credential/catalog/refresh.rs @@ -0,0 +1,235 @@ +//! 对应生产职责的行为测试 + +use super::*; + +#[tokio::test] +async fn invalidation_queues_background_refresh_without_an_upstream_etag() { + let store = Arc::new(MemoryAccountStore::default()); + let service = service(&store); + service + .invalidate_accounts(&[ProviderAccountId::new("acct_first").unwrap()]) + .await + .unwrap(); + service + .invalidate_accounts(&[ProviderAccountId::new("acct_first").unwrap()]) + .await + .unwrap(); + tokio::time::timeout( + std::time::Duration::from_secs(1), + service.wait_for_refresh(), + ) + .await + .expect("configuration invalidation must wake the catalog worker"); + assert!( + tokio::time::timeout( + std::time::Duration::from_millis(50), + service.wait_for_refresh(), + ) + .await + .is_err(), + "duplicate invalidations should share one pending refresh" + ); +} + +#[tokio::test] +async fn matching_etag_renews_only_its_account_until_the_next_change_or_expiry() { + use gateway_core::account::AccountCatalogObservation; + use std::time::{Duration, SystemTime}; + + let store = Arc::new(MemoryAccountStore::default()); + let active = seed_account(&store, "acct_active").await; + let idle = seed_account(&store, "acct_idle").await; + let document = [&[0_u8][..], OFFICIAL_FIXTURE].concat(); + let old_tag = r#""v1""#; + let new_tag = r#""v2""#; + let observed_at = SystemTime::now() - Duration::from_mins(61); + for account in [&active, &idle] { + assert!( + store + .save_account_catalog( + &AccountCatalogObservation { + account_id: account.id().clone(), + revision: account.revision(), + plan: account.plan_type().map(str::to_owned), + observed_at, + etag: Some(old_tag.to_owned()), + }, + &document + ) + .await + .unwrap() + ); + } + let server = MockServer::start().await; + for account in [&active, &idle] { + Mock::given(method("GET")) + .and(path("/codex/models")) + .and(header( + "chatgpt-account-id", + format!("chatgpt-{}", account.id()), + )) + .respond_with( + ResponseTemplate::new(200) + .insert_header("etag", old_tag) + .set_body_raw(OFFICIAL_FIXTURE, "application/json"), + ) + .expect(1) + .mount(&server) + .await; + } + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + service.restore().await.unwrap(); + assert!(!service.observe_response_etag(&active, old_tag).unwrap()); + service.refresh_catalogs().await.unwrap(); + let requests = server.received_requests().await.unwrap(); + assert_eq!(requests.len(), 1); + assert_eq!( + requests[0].headers["chatgpt-account-id"], + "chatgpt-acct_idle" + ); + + tokio::time::pause(); + tokio::time::advance(Duration::from_mins(59)).await; + service.refresh_catalogs().await.unwrap(); + assert_eq!(server.received_requests().await.unwrap().len(), 1); + tokio::time::advance(Duration::from_mins(1)).await; + tokio::time::resume(); + service.refresh_catalogs().await.unwrap(); + server.verify().await; + + server.reset().await; + Mock::given(method("GET")) + .and(path("/codex/models")) + .and(header("chatgpt-account-id", "chatgpt-acct_active")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("etag", new_tag) + .set_body_json( + serde_json::json!({"models":[{"slug":"active-only","display_name":"Active"}]}), + ), + ) + .expect(1) + .mount(&server) + .await; + assert!(!service.observe_response_etag(&active, old_tag).unwrap()); + assert!( + service + .observe_response_etag(&active, "change-hint") + .unwrap() + ); + assert!(!service.observe_response_etag(&active, old_tag).unwrap()); + service.refresh_catalogs().await.unwrap(); + assert!( + !service + .observe_response_etag(&active, "change-hint") + .unwrap() + ); + assert!(!service.observe_response_etag(&active, new_tag).unwrap()); + service.refresh_catalogs().await.unwrap(); + assert_eq!( + service.cached_account_models(&active).unwrap().unwrap(), + ["active-only"] + ); + server.verify().await; +} + +#[tokio::test] +async fn simultaneous_periodic_refreshes_share_the_completed_scan() { + let store = Arc::new(MemoryAccountStore::default()); + for index in 0..64 { + seed_account(&store, &format!("acct_refresh_{index:02}")).await; + } + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/codex/models")) + .respond_with( + ResponseTemplate::new(200) + .set_body_raw(OFFICIAL_FIXTURE.to_vec(), "application/json") + .set_delay(std::time::Duration::from_millis(20)), + ) + .expect(64) + .mount(&server) + .await; + let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); + let (first, second, third) = tokio::join!( + service.refresh_catalogs(), + service.refresh_catalogs(), + service.refresh_catalogs(), + ); + let first = first.expect("first refresh"); + assert_eq!(first.models(), second.expect("shared refresh").models()); + assert_eq!(first.models(), third.expect("shared refresh").models()); + server.verify().await; +} + +#[tokio::test] +async fn api_key_background_catalog_preserves_negotiated_reasoning_levels_and_entitlements() { + use gateway_core::routing::ProviderModelContent; + use provider_openai::credential::ResponsesTransport; + use provider_openai::transport::CodexCatalogCapabilityEvidence; + use serde_json::json; + + let upstream = MockServer::start().await; + let store = Arc::new(MemoryAccountStore::default()); + store + .seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http) + .await; + let original = json!({"slug":"z-unknown-reasoning", "display_name":"Unknown reasoning"}); + let second = json!({ + "slug":"vendor/model", "display_name":"Second upstream model", + "default_reasoning_level":"high", + "supported_reasoning_levels":[{"effort":"high","description":"Upstream description"}] + }); + Mock::given(method("GET")) + .and(path("/models")) + .respond_with({ + let native = json!({"models":[original, second]}); + move |request: &Request| { + if request.url.query() == Some("client_version=0.144.0") { + ResponseTemplate::new(200).set_body_json(&native) + } else { + ResponseTemplate::new(200).set_body_json(json!({"data":[ + {"id":"z-unknown-reasoning"}, {"id":"vendor/model"} + ]})) + } + } + }) + .expect(1) + .mount(&upstream) + .await; + let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); + let snapshot = service + .refresh_catalogs() + .await + .expect("native background directory"); + assert_eq!( + snapshot.models()[0].capabilities().reasoning(), + CodexCatalogCapabilityEvidence::Unknown + ); + let account = store.account("acct_api").unwrap(); + assert_eq!( + service.cached_account_models(&account).unwrap().unwrap(), + ["z-unknown-reasoning", "vendor/model"] + ); + let models = service + .client_model_catalog(&client_scope(&[account])) + .await + .unwrap(); + assert_eq!( + models + .iter() + .map(|model| model.model.as_str()) + .collect::>(), + ["z-unknown-reasoning", "vendor/model"] + ); + for (model, expected) in models.iter().zip([original, second]) { + let ProviderModelContent::Native(payload) = &model.content else { + panic!("native model expected") + }; + assert_eq!( + serde_json::from_slice::(payload.body()).unwrap(), + expected + ); + } + upstream.verify().await; +} diff --git a/backend/crates/providers/openai/tests/credential/contract/capacity.rs b/backend/crates/providers/openai/tests/credential/contract/capacity.rs index 6d553a3ad..cecf7d77c 100644 --- a/backend/crates/providers/openai/tests/credential/contract/capacity.rs +++ b/backend/crates/providers/openai/tests/credential/contract/capacity.rs @@ -50,7 +50,7 @@ fn capacity_attempt( .with_request_policy(request_policy), NonZeroU32::new(1).unwrap(), SystemTime::now() + Duration::from_secs(5), - policy.with_openai_account_affinity(gateway_core::account::AccountAffinity::Strict), + policy.with_account_affinity(gateway_core::account::AccountAffinity::Strict), AccountAttemptContext::new(BTreeSet::new(), None, None) .with_account_scope(contract_account_scope()), None, diff --git a/backend/crates/providers/openai/tests/credential/contract/mod.rs b/backend/crates/providers/openai/tests/credential/contract/mod.rs index 7d537f071..127d0d450 100644 --- a/backend/crates/providers/openai/tests/credential/contract/mod.rs +++ b/backend/crates/providers/openai/tests/credential/contract/mod.rs @@ -35,7 +35,7 @@ use provider_openai::credential::{ CodexCredentialSelector, CredentialSelectionError, ImportCodexOAuthCredential, SelectCodexCredential, }; -use provider_openai::transport::profile::{CodexWireProfile, CodexWireProfileState}; +use provider_openai::profile::{CodexWireProfile, CodexWireProfileState}; use secrecy::ExposeSecret; use serde_json::json; use url::Url; @@ -219,7 +219,7 @@ fn selector_with_runtime( cooldowns: Arc, ) -> CodexCredentialSelector { let profile = CodexWireProfileState::new(CodexWireProfile { - client_kind: provider_openai::transport::profile::selection::ClientKind::Desktop, + client_kind: provider_openai::profile::selection::ClientKind::Desktop, originator: "codex_cli_rs".to_owned(), codex_version: "0.144.0".to_owned(), desktop_version: "1.0.0".to_owned(), @@ -886,7 +886,7 @@ async fn select_strict_round_robin_session( RotationStrategy::RoundRobin, NonZeroU32::new(2).expect("concurrency"), ) - .with_openai_account_affinity(AccountAffinity::Strict), + .with_account_affinity(AccountAffinity::Strict), AccountAttemptContext::new(BTreeSet::new(), None, None) .with_account_scope(contract_account_scope()), None, diff --git a/backend/crates/providers/openai/tests/credential/contract/scheduling_projection.rs b/backend/crates/providers/openai/tests/credential/contract/scheduling_projection.rs index 7ad96a362..9e7c302da 100644 --- a/backend/crates/providers/openai/tests/credential/contract/scheduling_projection.rs +++ b/backend/crates/providers/openai/tests/credential/contract/scheduling_projection.rs @@ -109,7 +109,7 @@ async fn changed_owner_and_lease_contention_refresh_the_complete_pool() { let attempt = projection_attempt( "key_codex_contract", contract_account_scope(), - account_policy().with_openai_account_affinity(AccountAffinity::Preferred), + account_policy().with_account_affinity(AccountAffinity::Preferred), ); let key = ProviderSessionAffinityKey::try_new("projection-refresh").unwrap(); let selected = select(&selector, &attempt, &key, "gpt-5.4").await.unwrap(); @@ -481,7 +481,7 @@ async fn account_queue_timeout_can_reselect_for_preferred_and_sessionless_reques let leases = Arc::new(TestLeaseCoordinator::default()); let selector = selector(&store, leases.clone()); let policy = account_policy() - .with_openai_account_affinity(mode) + .with_account_affinity(mode) .with_switch_account_on_queue_failure(true) .with_queue(gateway_core::concurrency::ConcurrencyQueuePolicy { max_waiting: 1, @@ -573,7 +573,7 @@ async fn movable_waiters_use_other_accounts_even_before_queue_promotion() { let attempt = projection_attempt( "key_codex_contract", contract_account_scope(), - policy.with_openai_account_affinity(mode), + policy.with_account_affinity(mode), ); let key = ProviderSessionAffinityKey::try_new("movable-waiter").unwrap(); if bind_session { diff --git a/backend/crates/providers/openai/tests/credential/oauth.rs b/backend/crates/providers/openai/tests/credential/oauth.rs index f345ef071..aa7d31cd0 100644 --- a/backend/crates/providers/openai/tests/credential/oauth.rs +++ b/backend/crates/providers/openai/tests/credential/oauth.rs @@ -25,7 +25,7 @@ use provider_openai::credential::{ CompletedCodexOAuthCredential, ImportCodexOAuthCredential, StartCodexOAuthAuthorization, StoredCodexPendingAuthorization, }; -use provider_openai::transport::profile::CodexWireProfileState; +use provider_openai::profile::CodexWireProfileState; use secrecy::SecretString; use url::Url; use uuid::Uuid; @@ -380,7 +380,7 @@ async fn authorize_url_matches_the_official_desktop_parameter_contract() { } fn profile() -> CodexWireProfileState { - provider_openai::transport::profile::CodexWireProfileState::new(Default::default()) + provider_openai::profile::CodexWireProfileState::new(Default::default()) } #[tokio::test] diff --git a/backend/crates/providers/openai/tests/credential/profile_statistics.rs b/backend/crates/providers/openai/tests/credential/profile_statistics.rs index 5153c6f72..dc04c8b0e 100644 --- a/backend/crates/providers/openai/tests/credential/profile_statistics.rs +++ b/backend/crates/providers/openai/tests/credential/profile_statistics.rs @@ -6,7 +6,7 @@ use chrono::{TimeZone as _, Utc}; use futures::TryStreamExt as _; use gateway_core::account::ProviderAccountId; use provider_openai::credential::{CodexCredentialProfileService, ImportCodexOAuthCredential}; -use provider_openai::transport::profile::{CodexWireProfile, CodexWireProfileState}; +use provider_openai::profile::{CodexWireProfile, CodexWireProfileState}; use serde_json::json; use wiremock::matchers::{header, method, path, query_param}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -15,7 +15,7 @@ use crate::support::{MemoryAccountStore, profile, secret}; fn wire_profile() -> CodexWireProfileState { CodexWireProfileState::new(CodexWireProfile { - client_kind: provider_openai::transport::profile::selection::ClientKind::Desktop, + client_kind: provider_openai::profile::selection::ClientKind::Desktop, originator: "codex_cli_rs".to_owned(), codex_version: "0.144.0".to_owned(), desktop_version: "1.0.0".to_owned(), diff --git a/backend/crates/providers/openai/tests/credential/quota/mod.rs b/backend/crates/providers/openai/tests/credential/quota/mod.rs index 4b83ed6d4..79e34bcf0 100644 --- a/backend/crates/providers/openai/tests/credential/quota/mod.rs +++ b/backend/crates/providers/openai/tests/credential/quota/mod.rs @@ -26,7 +26,7 @@ use provider_openai::OFFICIAL_CODEX_BASE_URL; use provider_openai::credential::{ CodexCredentialQuotaError, CodexCredentialQuotaService, ImportCodexOAuthCredential, }; -use provider_openai::transport::profile::{CodexWireProfile, CodexWireProfileState}; +use provider_openai::profile::{CodexWireProfile, CodexWireProfileState}; use serde_json::json; use wiremock::matchers::{header, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -35,7 +35,7 @@ use crate::support::{MemoryAccountStore, profile, secret}; fn wire_profile() -> CodexWireProfileState { CodexWireProfileState::new(CodexWireProfile { - client_kind: provider_openai::transport::profile::selection::ClientKind::Desktop, + client_kind: provider_openai::profile::selection::ClientKind::Desktop, originator: "codex_cli_rs".to_owned(), codex_version: "0.144.0".to_owned(), desktop_version: "1.0.0".to_owned(), diff --git a/backend/crates/providers/openai/tests/credential/refresh.rs b/backend/crates/providers/openai/tests/credential/refresh.rs index 7cfe17c37..635528181 100644 --- a/backend/crates/providers/openai/tests/credential/refresh.rs +++ b/backend/crates/providers/openai/tests/credential/refresh.rs @@ -613,7 +613,7 @@ async fn scheduled_refresh_persists_retryable_message_inside_the_two_hour_window client_id: "test-public-client".to_owned(), token_endpoint: format!("{}/oauth/token", server.uri()), }, - provider_openai::transport::profile::CodexWireProfileState::new(Default::default()), + provider_openai::profile::CodexWireProfileState::new(Default::default()), )), Arc::new(RefreshLeases), Arc::new(RefreshCredentialState), diff --git a/backend/crates/providers/openai/tests/credential/token_client.rs b/backend/crates/providers/openai/tests/credential/token_client.rs index ecf6f1471..3e172af4d 100644 --- a/backend/crates/providers/openai/tests/credential/token_client.rs +++ b/backend/crates/providers/openai/tests/credential/token_client.rs @@ -59,8 +59,7 @@ async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange() .expect(4) .mount(&server) .await; - let profile = - provider_openai::transport::profile::CodexWireProfileState::new(Default::default()); + let profile = provider_openai::profile::CodexWireProfileState::new(Default::default()); let client = provider_openai::credential::token_client::openai_token_client( TokenClientConfig { client_id: "audit-client".to_owned(), @@ -73,14 +72,12 @@ async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange() ("1.2.3", "26.800.10000", "8000"), ("1.2.4", "26.901.10000", "8109"), ] { - profile.update_bundled_release( - &provider_openai::transport::profile::CodexBundledReleaseProfile { - codex_version: core.to_owned(), - desktop_version: desktop.to_owned(), - desktop_build: build.to_owned(), - verified_at: chrono::Utc::now(), - }, - ); + profile.update_bundled_release(&provider_openai::profile::CodexBundledReleaseProfile { + codex_version: core.to_owned(), + desktop_version: desktop.to_owned(), + desktop_build: build.to_owned(), + verified_at: chrono::Utc::now(), + }); client.refresh("audit-refresh").await.expect("refresh"); client .exchange_authorization_code(AuthorizationCodeGrant { @@ -126,7 +123,7 @@ fn client(server: &MockServer) -> OpenAiTokenClient { client_id: "test-public-client".to_owned(), token_endpoint: format!("{}/oauth/token", server.uri()), }, - provider_openai::transport::profile::CodexWireProfileState::new(Default::default()), + provider_openai::profile::CodexWireProfileState::new(Default::default()), ) } @@ -394,7 +391,7 @@ async fn authorization_code_response_timeouts_remain_ambiguous_without_exposing_ client_id: "test-public-client".to_owned(), token_endpoint: format!("http://{address}/oauth/token?PRIVATE_URL_MARKER"), }, - provider_openai::transport::profile::CodexWireProfileState::new(Default::default()), + provider_openai::profile::CodexWireProfileState::new(Default::default()), ); let error = client .exchange_authorization_code(AuthorizationCodeGrant { diff --git a/backend/crates/providers/openai/tests/main.rs b/backend/crates/providers/openai/tests/main.rs index 1c7282d0d..35c92e440 100644 --- a/backend/crates/providers/openai/tests/main.rs +++ b/backend/crates/providers/openai/tests/main.rs @@ -1,10 +1,16 @@ //! OpenAI Provider、凭据与上游传输的测试入口 mod admin; +#[path = "../src/billing/mod.rs"] +#[allow(dead_code, unused_imports)] +mod billing; +#[path = "billing/mod.rs"] +mod billing_tests; mod compat; mod config; mod credential; mod jitter; +mod profile; mod provider; mod support; mod transport; diff --git a/backend/crates/providers/openai/tests/transport/profile/cli_release.rs b/backend/crates/providers/openai/tests/profile/cli_release.rs similarity index 94% rename from backend/crates/providers/openai/tests/transport/profile/cli_release.rs rename to backend/crates/providers/openai/tests/profile/cli_release.rs index 543534505..4f2b6089b 100644 --- a/backend/crates/providers/openai/tests/transport/profile/cli_release.rs +++ b/backend/crates/providers/openai/tests/profile/cli_release.rs @@ -1,6 +1,6 @@ //! 验证 CLI 发行信息的平台依赖一致性与请求画像同步更新 -use provider_openai::transport::profile::cli_release::parse_cli_release; +use provider_openai::profile::cli_release::parse_cli_release; use serde_json::json; #[test] @@ -42,13 +42,13 @@ async fn official_cli_cache_updates_entry_headers_together_and_preserves_frozen_ use gateway_core::account::OpaqueProviderData; use gateway_core::provider_ports::{ProviderArtifactProfile, ProviderArtifactProfileCachePort}; use gateway_core::routing::ProviderKind; - use provider_openai::transport::headers::build_codex_model_headers; - use provider_openai::transport::profile::CodexWireProfileState; - use provider_openai::transport::profile::cli_release::CliReleaseService; - use provider_openai::transport::profile::identity::RequestProfileSelection; - use provider_openai::transport::profile::selection::{ + use provider_openai::profile::CodexWireProfileState; + use provider_openai::profile::cli_release::CliReleaseService; + use provider_openai::profile::identity::RequestProfileSelection; + use provider_openai::profile::selection::{ CliEntry, ClientKind, ClientPlatform, ClientProfileSelection, VersionMode, }; + use provider_openai::transport::headers::build_codex_model_headers; let state = CodexWireProfileState::new(super::wire_profile()); let cache = Arc::new(super::ArtifactProfiles::default()); @@ -147,12 +147,12 @@ struct CliTransport { version: std::sync::Mutex, } -impl provider_openai::transport::profile::cli_release::CliReleaseTransport for CliTransport { +impl provider_openai::profile::cli_release::CliReleaseTransport for CliTransport { fn fetch( &self, ) -> futures::future::BoxFuture< '_, - Result, + Result, > { Box::pin(async move { Ok(self.version.lock().unwrap().clone()) }) } @@ -207,7 +207,7 @@ impl gateway_core::provider_ports::ProviderArtifactProfileCachePort for CliCache #[tokio::test(start_paused = true)] async fn unchanged_cli_release_only_renews_cache_daily_and_preserves_verification_time() { - use provider_openai::transport::profile::{ + use provider_openai::profile::{ CodexWireProfileState, cli_release::CliReleaseService, selection::{ClientKind, ClientPlatform}, @@ -258,7 +258,7 @@ async fn unchanged_cli_release_only_renews_cache_daily_and_preserves_verificatio #[tokio::test(start_paused = true)] async fn cli_partial_cache_failure_retries_the_same_release_without_republishing_other_targets() { - use provider_openai::transport::profile::{ + use provider_openai::profile::{ CodexWireProfileState, cli_release::CliReleaseService, selection::{ClientKind, ClientPlatform}, diff --git a/backend/crates/providers/openai/tests/transport/profile/desktop_artifact.rs b/backend/crates/providers/openai/tests/profile/desktop_artifact.rs similarity index 98% rename from backend/crates/providers/openai/tests/transport/profile/desktop_artifact.rs rename to backend/crates/providers/openai/tests/profile/desktop_artifact.rs index bd8fd15f1..e6e5c3630 100644 --- a/backend/crates/providers/openai/tests/transport/profile/desktop_artifact.rs +++ b/backend/crates/providers/openai/tests/profile/desktop_artifact.rs @@ -1,6 +1,6 @@ //! 验证 Desktop 制品内嵌 Core 版本扫描与 ZIP 目录约束 -use provider_openai::transport::profile::desktop_artifact::{ +use provider_openai::profile::desktop_artifact::{ CodexDesktopArtifactError, CoreVersionScanner, find_core_entry, parse_content_range, }; diff --git a/backend/crates/providers/openai/tests/transport/profile/identity.rs b/backend/crates/providers/openai/tests/profile/identity.rs similarity index 96% rename from backend/crates/providers/openai/tests/transport/profile/identity.rs rename to backend/crates/providers/openai/tests/profile/identity.rs index 7f8e376c2..e1f0570e7 100644 --- a/backend/crates/providers/openai/tests/transport/profile/identity.rs +++ b/backend/crates/providers/openai/tests/profile/identity.rs @@ -1,10 +1,10 @@ //! 验证自定义客户端身份、配套头部与注入防护 use gateway_core::account::OpaqueProviderData; +use provider_openai::profile::identity::RequestProfileSelection; +use provider_openai::profile::selection::ClientProfileSelection; +use provider_openai::profile::{CodexWireProfile, CodexWireProfileState}; use provider_openai::transport::headers::build_codex_model_headers; -use provider_openai::transport::profile::identity::RequestProfileSelection; -use provider_openai::transport::profile::selection::ClientProfileSelection; -use provider_openai::transport::profile::{CodexWireProfile, CodexWireProfileState}; use serde_json::{Value, json}; fn document(value: Value) -> OpaqueProviderData { @@ -13,7 +13,7 @@ fn document(value: Value) -> OpaqueProviderData { #[test] fn batch_identity_changes_keep_each_keys_seed_and_independent_selection() { - use provider_openai::transport::profile::identity::merge_batch_key_profile; + use provider_openai::profile::identity::merge_batch_key_profile; let preset = json!({"client": "cli", "platform":"linux", "versionMode":"latest"}); let custom = json!({"mode":"custom","userAgent":"codex-tui/0.156.1"}); diff --git a/backend/crates/providers/openai/tests/profile/mod.rs b/backend/crates/providers/openai/tests/profile/mod.rs new file mode 100644 index 000000000..108c5fa75 --- /dev/null +++ b/backend/crates/providers/openai/tests/profile/mod.rs @@ -0,0 +1,198 @@ +//! 测试模块入口与共享夹具 + +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use chrono::{TimeZone, Utc}; +use futures::future::BoxFuture; +use gateway_core::provider_ports::{ + ProviderArtifactProfile, ProviderArtifactProfileCachePort, ProviderStoreError, + ProviderStoreErrorKind, +}; +use gateway_core::routing::ProviderKind; +use provider_openai::profile::{ + CodexArtifactProfileCache, CodexBundledReleaseProfile, CodexDesktopRelease, + CodexDesktopReleaseError, CodexDesktopReleaseService, CodexDesktopReleaseTransport, + CodexWireProfile, CodexWireProfileState, parse_desktop_release, +}; + +mod cli_release; +mod desktop_artifact; +mod identity; +mod platform_release; +mod selection; + +struct ReleaseTransport { + releases: Mutex>>, + core_versions: Mutex>>, + core_probes: Mutex, +} + +impl ReleaseTransport { + fn new( + releases: impl IntoIterator>, + core_versions: impl IntoIterator>, + ) -> Self { + Self { + releases: Mutex::new(releases.into_iter().collect()), + core_versions: Mutex::new(core_versions.into_iter().collect()), + core_probes: Mutex::new(0), + } + } + + fn core_probes(&self) -> usize { + *self.core_probes.lock().expect("core probe count") + } +} + +impl CodexDesktopReleaseTransport for ReleaseTransport { + fn fetch(&self) -> BoxFuture<'_, Result> { + Box::pin(async move { + self.releases + .lock() + .expect("release outcomes") + .pop_front() + .expect("release outcome") + }) + } + + fn fetch_bundled_core_version<'a>( + &'a self, + _release: &'a CodexDesktopRelease, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + *self.core_probes.lock().expect("core probe count") += 1; + self.core_versions + .lock() + .expect("Core version outcomes") + .pop_front() + .expect("Core version outcome") + }) + } +} + +#[derive(Default)] +struct ArtifactProfiles { + profile: Mutex>, + fail_writes: AtomicBool, + writes: AtomicUsize, +} + +impl ArtifactProfiles { + fn failing() -> Self { + Self { + profile: Mutex::new(None), + fail_writes: AtomicBool::new(true), + writes: AtomicUsize::new(0), + } + } +} + +impl ProviderArtifactProfileCachePort for ArtifactProfiles { + fn replace_if_newer( + &self, + profile: ProviderArtifactProfile, + _ttl: Duration, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + self.writes.fetch_add(1, Ordering::SeqCst); + if self.fail_writes.load(Ordering::SeqCst) { + return Err(ProviderStoreError::new( + ProviderStoreErrorKind::Unavailable, + "replace test artifact profile", + )); + } + let mut current = self.profile.lock().expect("artifact profile"); + if let Some(current) = current.as_ref() { + if current.artifact_sequence() > profile.artifact_sequence() { + return Ok(false); + } + if current.artifact_sequence() == profile.artifact_sequence() + && current.profile() != profile.profile() + { + return Err(ProviderStoreError::new( + ProviderStoreErrorKind::Conflict, + "replace test artifact profile", + )); + } + } + *current = Some(profile); + Ok(true) + }) + } + + fn read<'a>( + &'a self, + provider_kind: &'a ProviderKind, + artifact_key: &'a str, + ) -> BoxFuture<'a, Result, ProviderStoreError>> { + Box::pin(async move { + Ok(self + .profile + .lock() + .expect("artifact profile") + .as_ref() + .filter(|profile| { + profile.provider_kind() == provider_kind + && profile.artifact_key() == artifact_key + }) + .cloned()) + }) + } +} + +fn service( + state: CodexWireProfileState, + transport: Arc, + cache: Arc, + verified: Option, +) -> CodexDesktopReleaseService { + let provider = ProviderKind::new("openai").expect("provider kind"); + CodexDesktopReleaseService::new( + state, + transport, + CodexArtifactProfileCache::new(provider, cache), + verified, + ) +} + +fn wire_profile() -> CodexWireProfile { + CodexWireProfile { + client_kind: provider_openai::profile::selection::ClientKind::Desktop, + originator: "Codex Desktop".to_owned(), + codex_version: "0.147.0-alpha.6.6".to_owned(), + desktop_version: "26.803.81509".to_owned(), + desktop_build: "6415".to_owned(), + os_type: "Mac OS".to_owned(), + os_version: "15.7.1".to_owned(), + arch: "arm64".to_owned(), + terminal: "unknown".to_owned(), + exact_user_agent: None, + installation_seed: None, + residency: None, + account_routing_override: None, + verified_at: Utc + .with_ymd_and_hms(2026, 8, 3, 0, 0, 0) + .single() + .expect("valid fixture time"), + } +} + +fn release(version: &str, build: &str) -> CodexDesktopRelease { + CodexDesktopRelease { + version: version.to_owned(), + build: build.to_owned(), + published_at: None, + minimum_system_version: Some("14.0".to_owned()), + hardware_requirements: Some("arm64".to_owned()), + download_url: Some("https://persistent.oaistatic.com/codex.zip".to_owned()), + download_size: Some(589_926_710), + signature_present: true, + } +} + +mod state; + +mod release; diff --git a/backend/crates/providers/openai/tests/transport/profile/platform_release/artifact.rs b/backend/crates/providers/openai/tests/profile/platform_release/artifact.rs similarity index 99% rename from backend/crates/providers/openai/tests/transport/profile/platform_release/artifact.rs rename to backend/crates/providers/openai/tests/profile/platform_release/artifact.rs index 47773dc50..f7197bfa0 100644 --- a/backend/crates/providers/openai/tests/transport/profile/platform_release/artifact.rs +++ b/backend/crates/providers/openai/tests/profile/platform_release/artifact.rs @@ -1,7 +1,7 @@ //! 验证 Windows 与 Linux 制品的版本、架构和归档完整性 use super::xz::compress as xz; -use provider_openai::transport::profile::platform_release::{ +use provider_openai::profile::platform_release::{ artifact::{read_linux, read_windows}, xz::IndexedXz, }; diff --git a/backend/crates/providers/openai/tests/transport/profile/platform_release/mod.rs b/backend/crates/providers/openai/tests/profile/platform_release/mod.rs similarity index 97% rename from backend/crates/providers/openai/tests/transport/profile/platform_release/mod.rs rename to backend/crates/providers/openai/tests/profile/platform_release/mod.rs index f8b12c941..e0aadc2c0 100644 --- a/backend/crates/providers/openai/tests/transport/profile/platform_release/mod.rs +++ b/backend/crates/providers/openai/tests/profile/platform_release/mod.rs @@ -5,12 +5,12 @@ use gateway_core::provider_ports::{ ProviderArtifactProfile, ProviderArtifactProfileCachePort, ProviderStoreError, }; use gateway_core::routing::ProviderKind; -use provider_openai::transport::profile::CodexWireProfileState; -use provider_openai::transport::profile::platform_release::{ +use provider_openai::profile::CodexWireProfileState; +use provider_openai::profile::platform_release::{ DesktopArtifactTransport, DesktopTarget, PlatformDesktopReleaseService, TARGETS, VerifiedArtifact, }; -use provider_openai::transport::profile::selection::{ClientKind, ClientProfileSelection}; +use provider_openai::profile::selection::{ClientKind, ClientProfileSelection}; use serde_json::json; use std::collections::BTreeMap; use std::io; diff --git a/backend/crates/providers/openai/tests/transport/profile/platform_release/range.rs b/backend/crates/providers/openai/tests/profile/platform_release/range.rs similarity index 98% rename from backend/crates/providers/openai/tests/transport/profile/platform_release/range.rs rename to backend/crates/providers/openai/tests/profile/platform_release/range.rs index b2ca56d55..c8166191d 100644 --- a/backend/crates/providers/openai/tests/transport/profile/platform_release/range.rs +++ b/backend/crates/providers/openai/tests/profile/platform_release/range.rs @@ -1,6 +1,6 @@ //! 验证 HTTP Range 的 ETag、精确范围与取消传播 -use provider_openai::transport::profile::platform_release::range::RemoteFile; +use provider_openai::profile::platform_release::range::RemoteFile; use std::io::{self, Read}; use std::sync::Arc; use std::time::Duration; diff --git a/backend/crates/providers/openai/tests/transport/profile/platform_release/xz.rs b/backend/crates/providers/openai/tests/profile/platform_release/xz.rs similarity index 97% rename from backend/crates/providers/openai/tests/transport/profile/platform_release/xz.rs rename to backend/crates/providers/openai/tests/profile/platform_release/xz.rs index 55e48e871..79c41c33e 100644 --- a/backend/crates/providers/openai/tests/transport/profile/platform_release/xz.rs +++ b/backend/crates/providers/openai/tests/profile/platform_release/xz.rs @@ -1,6 +1,6 @@ //! 验证 XZ 索引读取的定位、跨块访问、无关块跳过与大块缓冲保留量 -use provider_openai::transport::profile::platform_release::xz::IndexedXz; +use provider_openai::profile::platform_release::xz::IndexedXz; use std::io::{Cursor, Read, Seek, SeekFrom, Write}; pub(super) fn compress(bytes: &[u8]) -> Vec { diff --git a/backend/crates/providers/openai/tests/transport/profile/mod.rs b/backend/crates/providers/openai/tests/profile/release.rs similarity index 52% rename from backend/crates/providers/openai/tests/transport/profile/mod.rs rename to backend/crates/providers/openai/tests/profile/release.rs index 6752f9b7d..d7cc63cf3 100644 --- a/backend/crates/providers/openai/tests/transport/profile/mod.rs +++ b/backend/crates/providers/openai/tests/profile/release.rs @@ -1,175 +1,6 @@ -//! 客户端画像测试入口,以及 Desktop 发行解析和原子更新测试 +//! 官方发行解析、刷新与原子更新测试 -use std::collections::VecDeque; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; -use std::time::Duration; - -use chrono::{TimeZone, Utc}; -use futures::future::BoxFuture; -use gateway_core::provider_ports::{ - ProviderArtifactProfile, ProviderArtifactProfileCachePort, ProviderStoreError, - ProviderStoreErrorKind, -}; -use gateway_core::routing::ProviderKind; -use provider_openai::transport::profile::{ - CodexArtifactProfileCache, CodexBundledReleaseProfile, CodexDesktopRelease, - CodexDesktopReleaseError, CodexDesktopReleaseService, CodexDesktopReleaseTransport, - CodexWireProfile, CodexWireProfileState, parse_desktop_release, -}; - -mod cli_release; -mod desktop_artifact; -mod identity; -mod platform_release; -mod selection; - -struct ReleaseTransport { - releases: Mutex>>, - core_versions: Mutex>>, - core_probes: Mutex, -} - -impl ReleaseTransport { - fn new( - releases: impl IntoIterator>, - core_versions: impl IntoIterator>, - ) -> Self { - Self { - releases: Mutex::new(releases.into_iter().collect()), - core_versions: Mutex::new(core_versions.into_iter().collect()), - core_probes: Mutex::new(0), - } - } - - fn core_probes(&self) -> usize { - *self.core_probes.lock().expect("core probe count") - } -} - -impl CodexDesktopReleaseTransport for ReleaseTransport { - fn fetch(&self) -> BoxFuture<'_, Result> { - Box::pin(async move { - self.releases - .lock() - .expect("release outcomes") - .pop_front() - .expect("release outcome") - }) - } - - fn fetch_bundled_core_version<'a>( - &'a self, - _release: &'a CodexDesktopRelease, - ) -> BoxFuture<'a, Result> { - Box::pin(async move { - *self.core_probes.lock().expect("core probe count") += 1; - self.core_versions - .lock() - .expect("Core version outcomes") - .pop_front() - .expect("Core version outcome") - }) - } -} - -#[derive(Default)] -struct ArtifactProfiles { - profile: Mutex>, - fail_writes: AtomicBool, - writes: AtomicUsize, -} - -impl ArtifactProfiles { - fn failing() -> Self { - Self { - profile: Mutex::new(None), - fail_writes: AtomicBool::new(true), - writes: AtomicUsize::new(0), - } - } -} - -impl ProviderArtifactProfileCachePort for ArtifactProfiles { - fn replace_if_newer( - &self, - profile: ProviderArtifactProfile, - _ttl: Duration, - ) -> BoxFuture<'_, Result> { - Box::pin(async move { - self.writes.fetch_add(1, Ordering::SeqCst); - if self.fail_writes.load(Ordering::SeqCst) { - return Err(ProviderStoreError::new( - ProviderStoreErrorKind::Unavailable, - "replace test artifact profile", - )); - } - let mut current = self.profile.lock().expect("artifact profile"); - if let Some(current) = current.as_ref() { - if current.artifact_sequence() > profile.artifact_sequence() { - return Ok(false); - } - if current.artifact_sequence() == profile.artifact_sequence() - && current.profile() != profile.profile() - { - return Err(ProviderStoreError::new( - ProviderStoreErrorKind::Conflict, - "replace test artifact profile", - )); - } - } - *current = Some(profile); - Ok(true) - }) - } - - fn read<'a>( - &'a self, - provider_kind: &'a ProviderKind, - artifact_key: &'a str, - ) -> BoxFuture<'a, Result, ProviderStoreError>> { - Box::pin(async move { - Ok(self - .profile - .lock() - .expect("artifact profile") - .as_ref() - .filter(|profile| { - profile.provider_kind() == provider_kind - && profile.artifact_key() == artifact_key - }) - .cloned()) - }) - } -} - -#[test] -fn wire_profile_should_generate_bundled_core_app_server_user_agent() { - let profile = CodexWireProfile { - client_kind: provider_openai::transport::profile::selection::ClientKind::Desktop, - originator: "Codex Desktop".to_owned(), - codex_version: "0.147.0-alpha.6.6".to_owned(), - desktop_version: "26.803.81509".to_owned(), - desktop_build: "6415".to_owned(), - os_type: "Mac OS".to_owned(), - os_version: "15.7.1".to_owned(), - arch: "arm64".to_owned(), - terminal: "unknown".to_owned(), - exact_user_agent: None, - installation_seed: None, - residency: None, - account_routing_override: None, - verified_at: Utc - .with_ymd_and_hms(2026, 8, 3, 0, 0, 0) - .single() - .expect("valid fixture time"), - }; - - assert_eq!( - profile.user_agent(), - "Codex Desktop/0.147.0-alpha.6.6 (Mac OS 15.7.1; arm64) unknown (Codex Desktop; 26.803.81509)" - ); -} +use super::*; #[test] fn desktop_appcast_should_publish_the_first_complete_release() { @@ -260,8 +91,7 @@ async fn bundled_release_update_should_change_core_and_desktop_identity_atomical assert!(status.last_error.is_none()); // 设置页反复读取预设与预览时,只展示当前生效版本及最近检查时间 - let selection = - provider_openai::transport::profile::selection::ClientProfileSelection::default(); + let selection = provider_openai::profile::selection::ClientProfileSelection::default(); let configuration = selection.document().unwrap(); let first = state.preview_selection(&configuration).unwrap(); assert_eq!( @@ -366,76 +196,10 @@ async fn cache_failure_should_not_publish_a_partially_verified_profile() { assert_eq!(state.snapshot().desktop_build, "6570"); } -/// 滞后档位按发布观察序列解析:启动种子、历次核验发布与失败观察共同构成历史。 -#[tokio::test] -async fn lagged_profiles_track_observed_release_history() { - use provider_openai::transport::profile::selection::ClientProfileSelection; - - let state = CodexWireProfileState::new(wire_profile()); - let transport = Arc::new(ReleaseTransport::new( - [ - Ok(release("26.810.41047", "6570")), - Ok(release("26.820.41131", "6700")), - Err(CodexDesktopReleaseError::InvalidDocument), - ], - [Ok("0.148.0-alpha.9".to_owned()), Ok("0.149.0".to_owned())], - )); - let service = service( - state.clone(), - transport, - Arc::new(ArtifactProfiles::default()), - None, - ); - let selection = |lag: Option| ClientProfileSelection { - version_lag: lag, - ..Default::default() - }; - - // 启动种子来自初始画像;首次检查前档位回退到该版本而不是失败。 - assert_eq!( - selection(Some(8)).resolve(&state).unwrap().codex_version, - "0.147.0-alpha.6.6" - ); - - service.refresh().await.expect("first release refresh"); - service.refresh().await.expect("second release refresh"); - - let latest = selection(None).resolve(&state).unwrap(); - assert_eq!(latest.codex_version, "0.149.0"); - assert_eq!(latest.desktop_version, "26.820.41131"); - // 滞后一档是上一次核验发布,滞后两档落到启动种子。 - let lagged = selection(Some(1)).resolve(&state).unwrap(); - assert_eq!(lagged.codex_version, "0.148.0-alpha.9"); - assert_eq!(lagged.desktop_version, "26.810.41047"); - assert_eq!( - lagged.user_agent(), - "Codex Desktop/0.148.0-alpha.9 (Mac OS 15.7.1; arm64) unknown (Codex Desktop; 26.810.41047)" - ); - assert_eq!( - selection(Some(2)).resolve(&state).unwrap().codex_version, - "0.147.0-alpha.6.6" - ); - // 观察序列不足档位深度时回退最旧已核验版本,不产生新的失败模式。 - assert_eq!( - selection(Some(8)).resolve(&state).unwrap().codex_version, - "0.147.0-alpha.6.6" - ); - - // 失败观察只更新状态,发布历史保持不变。 - service - .refresh() - .await - .expect_err("third release refresh should fail"); - assert_eq!( - selection(Some(1)).resolve(&state).unwrap().codex_version, - "0.148.0-alpha.9" - ); -} - /// 重启后首次检查发现新版时,滞后一档应选中从缓存恢复的版本 #[tokio::test] async fn restored_cache_release_should_stay_in_version_lag_history() { - use provider_openai::transport::profile::selection::ClientProfileSelection; + use provider_openai::profile::selection::ClientProfileSelection; let state = CodexWireProfileState::new(wire_profile()); let restored = CodexBundledReleaseProfile { @@ -492,59 +256,9 @@ async fn restored_cache_release_should_stay_in_version_lag_history() { ); } -fn service( - state: CodexWireProfileState, - transport: Arc, - cache: Arc, - verified: Option, -) -> CodexDesktopReleaseService { - let provider = ProviderKind::new("openai").expect("provider kind"); - CodexDesktopReleaseService::new( - state, - transport, - CodexArtifactProfileCache::new(provider, cache), - verified, - ) -} - -fn wire_profile() -> CodexWireProfile { - CodexWireProfile { - client_kind: provider_openai::transport::profile::selection::ClientKind::Desktop, - originator: "Codex Desktop".to_owned(), - codex_version: "0.147.0-alpha.6.6".to_owned(), - desktop_version: "26.803.81509".to_owned(), - desktop_build: "6415".to_owned(), - os_type: "Mac OS".to_owned(), - os_version: "15.7.1".to_owned(), - arch: "arm64".to_owned(), - terminal: "unknown".to_owned(), - exact_user_agent: None, - installation_seed: None, - residency: None, - account_routing_override: None, - verified_at: Utc - .with_ymd_and_hms(2026, 8, 3, 0, 0, 0) - .single() - .expect("valid fixture time"), - } -} - -fn release(version: &str, build: &str) -> CodexDesktopRelease { - CodexDesktopRelease { - version: version.to_owned(), - build: build.to_owned(), - published_at: None, - minimum_system_version: Some("14.0".to_owned()), - hardware_requirements: Some("arm64".to_owned()), - download_url: Some("https://persistent.oaistatic.com/codex.zip".to_owned()), - download_size: Some(589_926_710), - signature_present: true, - } -} - #[tokio::test] async fn official_appcast_uses_the_deployment_https_proxy() { - use provider_openai::transport::profile::OfficialCodexDesktopReleaseTransport; + use provider_openai::profile::OfficialCodexDesktopReleaseTransport; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; if std::env::var_os("CPR_TEST_APPCAST_PROXY").is_some() { let transport = OfficialCodexDesktopReleaseTransport::new().unwrap(); @@ -556,7 +270,7 @@ async fn official_appcast_uses_the_deployment_https_proxy() { command .args([ "--exact", - "transport::profile::official_appcast_uses_the_deployment_https_proxy", + "profile::release::official_appcast_uses_the_deployment_https_proxy", ]) .env("CPR_TEST_APPCAST_PROXY", "1") .env( diff --git a/backend/crates/providers/openai/tests/transport/profile/selection.rs b/backend/crates/providers/openai/tests/profile/selection.rs similarity index 95% rename from backend/crates/providers/openai/tests/transport/profile/selection.rs rename to backend/crates/providers/openai/tests/profile/selection.rs index 28652d9ac..14998238f 100644 --- a/backend/crates/providers/openai/tests/transport/profile/selection.rs +++ b/backend/crates/providers/openai/tests/profile/selection.rs @@ -1,10 +1,10 @@ //! 验证客户端画像预设、版本模式与请求冻结行为 use gateway_core::account::OpaqueProviderData; -use provider_openai::transport::profile::selection::{ +use provider_openai::profile::selection::{ CliEntry, ClientKind, ClientPlatform, ClientProfileSelection, VersionMode, }; -use provider_openai::transport::profile::{ +use provider_openai::profile::{ CodexBundledReleaseProfile, CodexWireProfile, CodexWireProfileState, }; use serde_json::json; @@ -157,6 +157,15 @@ fn version_lag_round_trips_and_falls_back_to_the_oldest_observed_release() { assert_eq!(preview.expose_to_provider()["versionSource"], "official"); let options = state.selection_options().unwrap(); assert_eq!(options.expose_to_provider()["maxVersionLag"], 10); + assert_eq!( + options.expose_to_provider()["recognizedUserAgentPrefixes"], + serde_json::json!([ + "Codex Desktop/", + "codex-tui/", + "codex_exec/", + "codex_cli_rs/" + ]) + ); } #[test] diff --git a/backend/crates/providers/openai/tests/profile/state.rs b/backend/crates/providers/openai/tests/profile/state.rs new file mode 100644 index 000000000..def1b82cb --- /dev/null +++ b/backend/crates/providers/openai/tests/profile/state.rs @@ -0,0 +1,97 @@ +//! 请求画像快照与身份规则测试 + +use super::*; + +#[test] +fn wire_profile_should_generate_bundled_core_app_server_user_agent() { + let profile = CodexWireProfile { + client_kind: provider_openai::profile::selection::ClientKind::Desktop, + originator: "Codex Desktop".to_owned(), + codex_version: "0.147.0-alpha.6.6".to_owned(), + desktop_version: "26.803.81509".to_owned(), + desktop_build: "6415".to_owned(), + os_type: "Mac OS".to_owned(), + os_version: "15.7.1".to_owned(), + arch: "arm64".to_owned(), + terminal: "unknown".to_owned(), + exact_user_agent: None, + installation_seed: None, + residency: None, + account_routing_override: None, + verified_at: Utc + .with_ymd_and_hms(2026, 8, 3, 0, 0, 0) + .single() + .expect("valid fixture time"), + }; + + assert_eq!( + profile.user_agent(), + "Codex Desktop/0.147.0-alpha.6.6 (Mac OS 15.7.1; arm64) unknown (Codex Desktop; 26.803.81509)" + ); +} + +/// 滞后档位按发布观察序列解析:启动种子、历次核验发布与失败观察共同构成历史。 +#[tokio::test] +async fn lagged_profiles_track_observed_release_history() { + use provider_openai::profile::selection::ClientProfileSelection; + + let state = CodexWireProfileState::new(wire_profile()); + let transport = Arc::new(ReleaseTransport::new( + [ + Ok(release("26.810.41047", "6570")), + Ok(release("26.820.41131", "6700")), + Err(CodexDesktopReleaseError::InvalidDocument), + ], + [Ok("0.148.0-alpha.9".to_owned()), Ok("0.149.0".to_owned())], + )); + let service = service( + state.clone(), + transport, + Arc::new(ArtifactProfiles::default()), + None, + ); + let selection = |lag: Option| ClientProfileSelection { + version_lag: lag, + ..Default::default() + }; + + // 启动种子来自初始画像;首次检查前档位回退到该版本而不是失败。 + assert_eq!( + selection(Some(8)).resolve(&state).unwrap().codex_version, + "0.147.0-alpha.6.6" + ); + + service.refresh().await.expect("first release refresh"); + service.refresh().await.expect("second release refresh"); + + let latest = selection(None).resolve(&state).unwrap(); + assert_eq!(latest.codex_version, "0.149.0"); + assert_eq!(latest.desktop_version, "26.820.41131"); + // 滞后一档是上一次核验发布,滞后两档落到启动种子。 + let lagged = selection(Some(1)).resolve(&state).unwrap(); + assert_eq!(lagged.codex_version, "0.148.0-alpha.9"); + assert_eq!(lagged.desktop_version, "26.810.41047"); + assert_eq!( + lagged.user_agent(), + "Codex Desktop/0.148.0-alpha.9 (Mac OS 15.7.1; arm64) unknown (Codex Desktop; 26.810.41047)" + ); + assert_eq!( + selection(Some(2)).resolve(&state).unwrap().codex_version, + "0.147.0-alpha.6.6" + ); + // 观察序列不足档位深度时回退最旧已核验版本,不产生新的失败模式。 + assert_eq!( + selection(Some(8)).resolve(&state).unwrap().codex_version, + "0.147.0-alpha.6.6" + ); + + // 失败观察只更新状态,发布历史保持不变。 + service + .refresh() + .await + .expect_err("third release refresh should fail"); + assert_eq!( + selection(Some(1)).resolve(&state).unwrap().codex_version, + "0.148.0-alpha.9" + ); +} diff --git a/backend/crates/providers/openai/tests/provider/contract/account_eligibility.rs b/backend/crates/providers/openai/tests/provider/contract/account_eligibility.rs index 923b6cf1f..b1deb5a99 100644 --- a/backend/crates/providers/openai/tests/provider/contract/account_eligibility.rs +++ b/backend/crates/providers/openai/tests/provider/contract/account_eligibility.rs @@ -63,7 +63,7 @@ fn selection_attempt( ), NonZeroU32::new(index).unwrap(), SystemTime::now() + Duration::from_secs(30), - account_policy().with_openai_account_affinity(affinity), + account_policy().with_account_affinity(affinity), accounts.with_account_scope(contract_account_scope()), None, CancellationToken::new(), diff --git a/backend/crates/providers/openai/tests/provider/contract/cache_preference.rs b/backend/crates/providers/openai/tests/provider/contract/cache_preference.rs index e94e02830..c982499f9 100644 --- a/backend/crates/providers/openai/tests/provider/contract/cache_preference.rs +++ b/backend/crates/providers/openai/tests/provider/contract/cache_preference.rs @@ -128,7 +128,7 @@ async fn cache_preference_storage_timeouts_follow_the_affinity_mode() { session_binding::context_with_affinity_policy( "req_cache_store_timeout", contract_account_scope(), - account_policy().with_openai_account_affinity(mode), + account_policy().with_account_affinity(mode), ), ) .await; @@ -163,7 +163,7 @@ async fn round_robin_retains_the_assignment_when_a_cache_preference_cannot_be_sa "req_cache_rr", contract_account_scope(), AccountSelectionPolicy::new(RotationStrategy::RoundRobin, NonZeroU32::MIN) - .with_openai_account_affinity(AccountAffinity::Preferred), + .with_account_affinity(AccountAffinity::Preferred), ); let key = attempt.client_api_key_ref().clone(); let result = provider diff --git a/backend/crates/providers/openai/tests/provider/contract/guardian_model.rs b/backend/crates/providers/openai/tests/provider/contract/guardian_model.rs index 734bbbb9b..db02a6587 100644 --- a/backend/crates/providers/openai/tests/provider/contract/guardian_model.rs +++ b/backend/crates/providers/openai/tests/provider/contract/guardian_model.rs @@ -208,8 +208,7 @@ async fn guardian_direct_model_respects_the_strict_parent_account() { .await .unwrap() ); - let preferred = - strict.with_openai_account_affinity(gateway_core::account::AccountAffinity::Preferred); + let preferred = strict.with_account_affinity(gateway_core::account::AccountAffinity::Preferred); assert!( provider .allows_direct_model_scope(&reviewer, &key, &scope, preferred) diff --git a/backend/crates/providers/openai/tests/provider/contract/image_model_access.rs b/backend/crates/providers/openai/tests/provider/contract/image_model_access.rs index 181a7f599..883bdd412 100644 --- a/backend/crates/providers/openai/tests/provider/contract/image_model_access.rs +++ b/backend/crates/providers/openai/tests/provider/contract/image_model_access.rs @@ -62,7 +62,7 @@ fn configured_attempt( ), NonZeroU32::new(index).unwrap(), SystemTime::now() + Duration::from_secs(30), - account_policy().with_openai_account_affinity(affinity), + account_policy().with_account_affinity(affinity), accounts, None, CancellationToken::new(), diff --git a/backend/crates/providers/openai/tests/provider/contract/messages/affinity.rs b/backend/crates/providers/openai/tests/provider/contract/messages/affinity.rs index b50fdcf11..ba2e87f8a 100644 --- a/backend/crates/providers/openai/tests/provider/contract/messages/affinity.rs +++ b/backend/crates/providers/openai/tests/provider/contract/messages/affinity.rs @@ -31,7 +31,7 @@ fn attempt(client: &str) -> AttemptContext { NonZeroU32::MIN, SystemTime::now() + Duration::from_secs(5), account_policy() - .with_openai_account_affinity(AccountAffinity::Strict) + .with_account_affinity(AccountAffinity::Strict) .with_queue(gateway_core::concurrency::ConcurrencyQueuePolicy { max_waiting: 1, timeout: Duration::from_secs(2), diff --git a/backend/crates/providers/openai/tests/provider/contract/mod.rs b/backend/crates/providers/openai/tests/provider/contract/mod.rs index a61f43d62..8550ebd92 100644 --- a/backend/crates/providers/openai/tests/provider/contract/mod.rs +++ b/backend/crates/providers/openai/tests/provider/contract/mod.rs @@ -81,8 +81,8 @@ use provider_openai::credential::{ CodexCookiePolicy, CodexCredentialCatalogService, CodexCredentialQuotaService, CodexCredentialSelector, ImportCodexOAuthCredential, }; +use provider_openai::profile::{CodexWireProfile, CodexWireProfileState}; use provider_openai::transport::CodexWebSocketPool; -use provider_openai::transport::profile::{CodexWireProfile, CodexWireProfileState}; use provider_openai::{CodexProvider, OFFICIAL_CODEX_BASE_URL}; use serde_json::{Map, Value, json}; use tokio::{ @@ -1150,7 +1150,7 @@ fn selected_account_log_fields<'events>( fn wire_profile() -> CodexWireProfileState { CodexWireProfileState::new(CodexWireProfile { - client_kind: provider_openai::transport::profile::selection::ClientKind::Desktop, + client_kind: provider_openai::profile::selection::ClientKind::Desktop, originator: "codex_cli_rs".to_owned(), codex_version: "0.144.0".to_owned(), desktop_version: "1.0.0".to_owned(), @@ -7492,7 +7492,7 @@ async fn relaxed_mode_skips_cache_preferences() { "req_affinity_key", contract_account_scope(), account_policy() - .with_openai_account_affinity(gateway_core::account::AccountAffinity::Relaxed), + .with_account_affinity(gateway_core::account::AccountAffinity::Relaxed), ), ) .await diff --git a/backend/crates/providers/openai/tests/provider/contract/search_model_access.rs b/backend/crates/providers/openai/tests/provider/contract/search_model_access.rs index 5e4468b16..5c99cf6a7 100644 --- a/backend/crates/providers/openai/tests/provider/contract/search_model_access.rs +++ b/backend/crates/providers/openai/tests/provider/contract/search_model_access.rs @@ -67,7 +67,7 @@ fn attempt( ), NonZeroU32::new(index).unwrap(), SystemTime::now() + Duration::from_secs(30), - account_policy().with_openai_account_affinity(affinity), + account_policy().with_account_affinity(affinity), accounts, None, CancellationToken::new(), diff --git a/backend/crates/providers/openai/tests/provider/contract/session_binding.rs b/backend/crates/providers/openai/tests/provider/contract/session_binding.rs index e064762f2..64245b942 100644 --- a/backend/crates/providers/openai/tests/provider/contract/session_binding.rs +++ b/backend/crates/providers/openai/tests/provider/contract/session_binding.rs @@ -1000,7 +1000,7 @@ async fn scheduler_distinguishes_session_bindings_from_cache_preferences_and_kee RequestAttemptContext::new(id, key).with_request_policy(Some(policy)), NonZeroU32::new(1).unwrap(), SystemTime::now() + Duration::from_secs(5), - account_policy().with_openai_account_affinity(mode), + account_policy().with_account_affinity(mode), AccountAttemptContext::new(BTreeSet::new(), None, None) .with_account_scope(contract_account_scope()), None, @@ -1288,8 +1288,8 @@ fn preferred_context_with_ttl( request_id, scope, account_policy() - .with_openai_account_affinity(gateway_core::account::AccountAffinity::Preferred) - .with_openai_session_affinity_ttl(ttl), + .with_account_affinity(gateway_core::account::AccountAffinity::Preferred) + .with_session_affinity_ttl(ttl), ) } @@ -1338,7 +1338,7 @@ async fn relaxed_and_preferred_session_requests_apply_distinct_scheduling_polici leases.clone(), ); let policy = account_policy() - .with_openai_account_affinity(mode) + .with_account_affinity(mode) .with_smart_scheduling(SmartSchedulingConfig::new([1.0; 6]).unwrap()) .with_queue(ConcurrencyQueuePolicy { max_waiting, @@ -1782,8 +1782,7 @@ async fn preferred_final_thread_rewrite_within_the_session_preserves_the_primary ), NonZeroU32::MIN, SystemTime::now() + Duration::from_secs(5), - account_policy() - .with_openai_account_affinity(gateway_core::account::AccountAffinity::Preferred), + account_policy().with_account_affinity(gateway_core::account::AccountAffinity::Preferred), AccountAttemptContext::new(BTreeSet::new(), None, None) .with_account_scope(contract_account_scope()), None, @@ -1944,7 +1943,7 @@ async fn preferred_primary_migration_distinguishes_temporary_and_persistent_unav ); let policy = AccountSelectionPolicy::new(RotationStrategy::Smart, NonZeroU32::new(2).unwrap()) - .with_openai_account_affinity(AccountAffinity::Preferred) + .with_account_affinity(AccountAffinity::Preferred) .with_queue(ConcurrencyQueuePolicy { max_waiting: 10, timeout: Duration::from_secs(30), @@ -2198,7 +2197,7 @@ async fn preferred_native_continuation_keeps_its_actual_owner_without_rebinding_ NonZeroU32::MIN, SystemTime::now() + Duration::from_secs(5), account_policy() - .with_openai_account_affinity(gateway_core::account::AccountAffinity::Preferred), + .with_account_affinity(gateway_core::account::AccountAffinity::Preferred), AccountAttemptContext::new(BTreeSet::new(), None, Some(owner)) .with_account_scope(contract_account_scope()), Some(ContinuationBinding::Pinned(pin)), diff --git a/backend/crates/providers/openai/tests/provider/contract/turn_state.rs b/backend/crates/providers/openai/tests/provider/contract/turn_state.rs index c2225889e..2eaff67d4 100644 --- a/backend/crates/providers/openai/tests/provider/contract/turn_state.rs +++ b/backend/crates/providers/openai/tests/provider/contract/turn_state.rs @@ -216,7 +216,7 @@ async fn full_http_replay_preserves_turn_state_without_local_proof() { ), NonZeroU32::new(1).unwrap(), SystemTime::now() + Duration::from_secs(30), - account_policy().with_openai_session_affinity_ttl(Duration::ZERO), + account_policy().with_session_affinity_ttl(Duration::ZERO), AccountAttemptContext::new(BTreeSet::new(), None, None) .with_account_scope(contract_account_scope()), None, diff --git a/backend/crates/providers/openai/tests/provider/live.rs b/backend/crates/providers/openai/tests/provider/live.rs index 16aa56bf0..f312fbfcb 100644 --- a/backend/crates/providers/openai/tests/provider/live.rs +++ b/backend/crates/providers/openai/tests/provider/live.rs @@ -711,7 +711,7 @@ async fn verify_live_call_identity() { }; use gateway_core::live::LiveHangupRequest; use provider_openai::credential::{CodexCredentialAdmin, ImportCodexOAuthCredential}; - use provider_openai::transport::profile::CodexWireProfile; + use provider_openai::profile::CodexWireProfile; use tokio::io::AsyncWriteExt; use tokio::net::TcpListener; let profile = CodexWireProfile { @@ -952,7 +952,7 @@ async fn verify_live_call_identity() { #[cfg(target_os = "linux")] fn assert_live_profile( headers: &reqwest::header::HeaderMap, - profile: &provider_openai::transport::profile::CodexWireProfile, + profile: &provider_openai::profile::CodexWireProfile, authorization: &str, ) { assert_eq!(headers["user-agent"], profile.user_agent()); diff --git a/backend/crates/providers/openai/tests/provider/workers.rs b/backend/crates/providers/openai/tests/provider/workers.rs index e85bd0e92..cf71ceab7 100644 --- a/backend/crates/providers/openai/tests/provider/workers.rs +++ b/backend/crates/providers/openai/tests/provider/workers.rs @@ -67,7 +67,7 @@ async fn catalog_etag_failure_returns_to_supervisor_and_recovers_pending_refresh .mount(&server) .await; let mut bundle = initialized_test_bundle(store, server.uri()).await; - let provider = bundle.core_provider(); + let provider = bundle.core.clone(); let operation = Operation::Generate(GenerateRequest::from_protocol_payload( ProtocolPayload::json_object( "openai", @@ -89,8 +89,7 @@ async fn catalog_etag_failure_returns_to_supervisor_and_recovers_pending_refresh while let Some(event) = stream.next().await { event.expect("response carrying catalog ETag"); } - let worker = bundle - .take_worker_contributions() + let worker = std::mem::take(&mut bundle.workers) .into_iter() .find_map(|contribution| match contribution { WorkerContribution::Registration(registration) diff --git a/backend/crates/providers/openai/tests/support.rs b/backend/crates/providers/openai/tests/support.rs index f3e00f102..18b61a6c4 100644 --- a/backend/crates/providers/openai/tests/support.rs +++ b/backend/crates/providers/openai/tests/support.rs @@ -1525,7 +1525,7 @@ pub(crate) fn account_policy() -> gateway_core::account::AccountSelectionPolicy gateway_core::account::RotationStrategy::Smart, NonZeroU32::new(2).expect("nonzero concurrency"), ) - .with_openai_account_affinity(gateway_core::account::AccountAffinity::Strict) + .with_account_affinity(gateway_core::account::AccountAffinity::Strict) } type CooldownReadHook = diff --git a/backend/crates/providers/openai/tests/transport/catalog.rs b/backend/crates/providers/openai/tests/transport/catalog.rs index 94dc50e48..6b76afa63 100644 --- a/backend/crates/providers/openai/tests/transport/catalog.rs +++ b/backend/crates/providers/openai/tests/transport/catalog.rs @@ -2,7 +2,7 @@ use chrono::{TimeZone, Utc}; use gateway_core::routing::ModelServiceTier; -use provider_openai::transport::profile::{CodexWireProfile, CodexWireProfileState}; +use provider_openai::profile::{CodexWireProfile, CodexWireProfileState}; use provider_openai::transport::{ CodexBackendClient, CodexCatalogCapabilityEvidence, CodexCatalogVisibility, CodexModelCatalogError, CodexRequestContext, build_reqwest_client, parse_codex_model_catalog, @@ -402,7 +402,7 @@ async fn fetch_preserves_large_model_instructions() { fn profile() -> CodexWireProfileState { CodexWireProfileState::new(CodexWireProfile { - client_kind: provider_openai::transport::profile::selection::ClientKind::Desktop, + client_kind: provider_openai::profile::selection::ClientKind::Desktop, originator: "codex_cli_rs".to_owned(), codex_version: "0.144.0".to_owned(), desktop_version: "1.0.0".to_owned(), diff --git a/backend/crates/providers/openai/tests/transport/client.rs b/backend/crates/providers/openai/tests/transport/client/backend.rs similarity index 100% rename from backend/crates/providers/openai/tests/transport/client.rs rename to backend/crates/providers/openai/tests/transport/client/backend.rs diff --git a/backend/crates/providers/openai/tests/transport/client/mod.rs b/backend/crates/providers/openai/tests/transport/client/mod.rs new file mode 100644 index 000000000..9de025da4 --- /dev/null +++ b/backend/crates/providers/openai/tests/transport/client/mod.rs @@ -0,0 +1,3 @@ +//! Codex 上游客户端测试 + +mod backend; diff --git a/backend/crates/providers/openai/tests/transport/diagnostics/contract.rs b/backend/crates/providers/openai/tests/transport/diagnostics/contract.rs new file mode 100644 index 000000000..e8cde853a --- /dev/null +++ b/backend/crates/providers/openai/tests/transport/diagnostics/contract.rs @@ -0,0 +1,468 @@ +//! 跨模块行为合同测试 + +use super::*; + +#[test] +fn model_rejection_requires_the_official_code_and_status() { + for status in [400, 403, 404] { + assert_eq!( + classify( + status, + r#"{"error":{"code":"model_not_found","message":"Access to this deployment ended."}}"# + ), + CodexFailureCategory::ModelUnsupported + ); + } + for (status, body, expected) in [ + ( + 400, + r#"{"error":{"code":"unsupported_value","type":"invalid_request_error","param":"reasoning.effort","message":"Unsupported value: 'none' is not supported with the 'gpt-6-astra' model. Supported values are: 'low', 'medium', 'high', 'xhigh', and 'max'."}}"#, + CodexFailureCategory::InvalidRequest, + ), + ( + 400, + r#"{"error":{"message":"The model is not supported."}}"#, + CodexFailureCategory::InvalidRequest, + ), + ( + 400, + r#"{"error":{"code":"unknown_error","message":"model_not_supported"}}"#, + CodexFailureCategory::InvalidRequest, + ), + ( + 400, + r#"{"error":{"code":"unknown_error"},"detail":"model_not_available"}"#, + CodexFailureCategory::InvalidRequest, + ), + ( + 500, + r#"{"error":{"code":"model_not_found","message":"The model is not available."}}"#, + CodexFailureCategory::Unavailable, + ), + ] { + let failure = CodexUpstreamFailure::from_response( + reqwest::StatusCode::from_u16(status).unwrap(), + body, + None, + &CodexUpstreamDiagnostics::default(), + None, + &[], + &[], + CodexUpstreamSendPhase::AfterPayload, + ); + assert_eq!(failure.category(), expected, "{body}"); + assert!(!failure.replay_is_safe(), "{body}"); + } +} + +#[test] +fn flex_capacity_rejection_should_be_terminal_even_before_payload_send() { + for phase in [ + CodexUpstreamSendPhase::BeforePayload, + CodexUpstreamSendPhase::AfterPayload, + ] { + let failure = CodexUpstreamFailure::from_response( + reqwest::StatusCode::TOO_MANY_REQUESTS, + r#"{"error":{"type":"resource_unavailable","code":"flex_unavailable","message":"Flex capacity unavailable."}}"#, + Some(300), + &CodexUpstreamDiagnostics::default(), + None, + &[], + &[], + phase, + ); + assert_eq!(failure.category(), CodexFailureCategory::FlexUnavailable); + assert!(!failure.replay_is_safe()); + } +} + +#[test] +fn turn_rate_limit_does_not_grant_proxy_replay_or_account_cooldown() { + for phase in [ + CodexUpstreamSendPhase::BeforePayload, + CodexUpstreamSendPhase::AfterPayload, + CodexUpstreamSendPhase::Ambiguous, + ] { + let failure = CodexUpstreamFailure::from_response( + reqwest::StatusCode::TOO_MANY_REQUESTS, + r#"{"error":{"code":"turn_rate_limit_exceeded","type":"rate_limit_error","message":"Retry this turn later."}}"#, + Some(53), + &CodexUpstreamDiagnostics::default(), + None, + &[], + &[], + phase, + ); + assert_eq!(failure.category(), CodexFailureCategory::TurnRateLimited); + assert!(!failure.replay_is_safe()); + } + assert_eq!( + classify(429, r#"{"error":{"message":"turn_rate_limit_exceeded"}}"#), + CodexFailureCategory::RateLimited + ); +} + +#[test] +fn server_error_replay_requires_explicit_503_and_unambiguous_send() { + for (status, body, retryable) in [ + ( + 503, + r#"{"error":{"code":"server_error","type":"server_error"}}"#, + true, + ), + ( + 500, + r#"{"error":{"code":"server_error","type":"server_error"}}"#, + false, + ), + ( + 504, + r#"{"error":{"code":"server_error","type":"server_error"}}"#, + false, + ), + (503, r#"{"error":{"type":"server_error"}}"#, false), + ( + 503, + r#"{"error":{"code":"Vendor.Future.v2","type":"server_error"}}"#, + false, + ), + ( + 503, + r#"{"error":{"code":"flex_unavailable","type":"server_error"}}"#, + false, + ), + (503, "server_error", false), + ] { + for phase in [ + CodexUpstreamSendPhase::BeforePayload, + CodexUpstreamSendPhase::AfterPayload, + CodexUpstreamSendPhase::Ambiguous, + ] { + let failure = CodexUpstreamFailure::from_response( + reqwest::StatusCode::from_u16(status).unwrap(), + body, + None, + &CodexUpstreamDiagnostics::default(), + None, + &[], + &[], + phase, + ); + assert_eq!( + failure.replay_is_safe(), + retryable && phase != CodexUpstreamSendPhase::Ambiguous, + "status={status}, body={body}, phase={phase:?}" + ); + } + } +} + +#[test] +fn capacity_rejections_are_request_scoped_across_http_statuses() { + for status in [400, 429, 503] { + for body in [ + r#"{"error":{"code":"server_is_overloaded","message":"busy"}}"#, + r#"{"error":{"code":"slow_down","type":"server_error"}}"#, + r#"{"error":{"type":"server_is_overloaded"}}"#, + r#"{"error":{"message":"slow_down"}}"#, + r#"{"error":{"type":"invalid_request_error","message":"Selected model is at capacity. Please try a different model."}}"#, + ] { + assert_eq!( + classify(status, body), + CodexFailureCategory::CapacityUnavailable + ); + for (phase, safe) in [ + (CodexUpstreamSendPhase::BeforePayload, true), + (CodexUpstreamSendPhase::AfterPayload, true), + (CodexUpstreamSendPhase::Ambiguous, false), + ] { + let failure = CodexUpstreamFailure::from_response( + reqwest::StatusCode::from_u16(status).expect("status"), + body, + Some(129_600), + &CodexUpstreamDiagnostics::default(), + None, + &[], + &[], + phase, + ); + assert_eq!(failure.replay_is_safe(), safe); + } + } + } +} + +#[test] +fn capacity_words_do_not_override_quota_policy_or_arbitrary_body_fields() { + for (status, body, expected) in [ + ( + 429, + r#"{"error":{"type":"usage_limit_reached","message":"Selected model is at capacity"}}"#, + CodexFailureCategory::UsageLimitExhausted, + ), + ( + 400, + r#"{"error":{"code":"cyber_policy","message":"Selected model is at capacity"}}"#, + CodexFailureCategory::InvalidRequest, + ), + ( + 400, + r#"{"error":{"message":"bad input"},"input":"Selected model is at capacity"}"#, + CodexFailureCategory::InvalidRequest, + ), + ( + 429, + r#"{"error":{"code":"rate_limit_exceeded","message":"retry later"}}"#, + CodexFailureCategory::RateLimited, + ), + ] { + assert_eq!(classify(status, body), expected); + } +} + +#[test] +fn diagnostics_should_extract_request_id_and_trace_headers() { + let mut headers = HeaderMap::new(); + headers.insert("x-request-id", HeaderValue::from_static("req_1")); + headers.insert("cf-ray", HeaderValue::from_static("ray_1")); + + let diagnostics = CodexUpstreamDiagnostics::from_headers(Some(429), &headers); + + assert_eq!( + ( + diagnostics.status_code, + diagnostics.request_id.as_deref(), + trace_header(&diagnostics, "cf-ray"), + ), + (Some(429), Some("req_1"), Some("ray_1")) + ); +} + +#[test] +fn diagnostics_should_not_treat_cf_ray_as_a_request_id() { + let mut headers = HeaderMap::new(); + headers.insert("cf-ray", HeaderValue::from_static("ray_1")); + + let diagnostics = CodexUpstreamDiagnostics::from_headers(Some(403), &headers); + + assert_eq!( + ( + diagnostics.request_id.as_deref(), + trace_header(&diagnostics, "cf-ray"), + ), + (None, Some("ray_1")) + ); +} + +#[test] +fn diagnostics_should_accept_the_oai_request_id_header() { + let mut headers = HeaderMap::new(); + headers.insert("x-oai-request-id", HeaderValue::from_static("oai_req_1")); + + let diagnostics = CodexUpstreamDiagnostics::from_headers(Some(500), &headers); + + assert_eq!(diagnostics.request_id.as_deref(), Some("oai_req_1")); +} + +#[test] +fn diagnostics_should_extract_only_the_identity_error_code() { + let encoded = STANDARD.encode(r#"{"error":{"code":"token_expired","message":"secret"}}"#); + let mut headers = HeaderMap::new(); + headers.insert( + "x-openai-authorization-error", + HeaderValue::from_static("authorization failed"), + ); + headers.insert( + "x-error-json", + HeaderValue::from_str(&encoded).expect("encoded header"), + ); + + let diagnostics = CodexUpstreamDiagnostics::from_headers(Some(403), &headers); + + assert_eq!( + ( + diagnostics.identity_authorization_error.as_deref(), + diagnostics.identity_error_code.as_deref(), + ), + (Some("authorization failed"), Some("token_expired")) + ); + assert!(!format!("{diagnostics:?}").contains("secret")); +} + +#[test] +fn diagnostics_should_ignore_malformed_identity_error_json() { + let mut headers = HeaderMap::new(); + headers.insert("x-error-json", HeaderValue::from_static("not-base64")); + + let diagnostics = CodexUpstreamDiagnostics::from_headers(Some(403), &headers); + + assert_eq!(diagnostics.identity_error_code, None); +} + +#[test] +fn unauthorized_substring_in_a_server_error_body_is_not_credential_expiry() { + assert_eq!( + classify( + 500, + r#"{"error":{"message":"upstream proxy replied: unauthorized"}}"# + ), + CodexFailureCategory::Unavailable + ); +} + +#[test] +fn http_401_classifies_as_credential_expiry_without_body_evidence() { + assert_eq!(classify(401, ""), CodexFailureCategory::CredentialExpired); +} + +#[test] +fn auth_text_with_http_403_still_classifies_as_credential_expiry() { + assert_eq!( + classify( + 403, + r#"{"error":{"message":"unauthorized: token expired"}}"# + ), + CodexFailureCategory::CredentialExpired + ); +} + +#[test] +fn structured_expiry_code_classifies_without_an_auth_status() { + assert_eq!( + classify( + 500, + r#"{"error":{"code":"token_expired","message":"internal"}}"# + ), + CodexFailureCategory::CredentialExpired + ); +} + +#[test] +fn http_429_without_usage_limit_type_remains_a_temporary_rate_limit() { + assert_eq!( + classify( + 429, + r#"{"error":{"code":"insufficient_quota","message":"rate limit reached"}}"# + ), + CodexFailureCategory::RateLimited + ); +} + +#[test] +fn structured_usage_limit_type_is_resettable_quota_exhaustion() { + assert_eq!( + classify( + 429, + r#"{"error":{"code":null,"type":"usage_limit_reached","message":"The usage limit has been reached"}}"# + ), + CodexFailureCategory::UsageLimitExhausted + ); +} + +#[test] +fn http_429_usage_limit_message_without_a_type_remains_a_temporary_rate_limit() { + assert_eq!( + classify( + 429, + r#"{"error":{"message":"The usage limit has been reached"}}"# + ), + CodexFailureCategory::RateLimited + ); +} + +#[test] +fn http_429_usage_limit_code_without_a_type_remains_a_temporary_rate_limit() { + assert_eq!( + classify( + 429, + r#"{"error":{"code":"usage_limit_reached","message":"The usage limit has been reached"}}"# + ), + CodexFailureCategory::RateLimited + ); +} + +#[test] +fn bare_http_429_remains_a_temporary_rate_limit() { + assert_eq!(classify(429, ""), CodexFailureCategory::RateLimited); +} + +#[test] +fn openai_account_failure_matrix_is_preserved() { + let cases = [ + ( + 400, + r#"{"error":{"message":"Organization has been disabled"}}"#, + CodexFailureCategory::Banned, + ), + ( + 400, + r#"{"error":{"message":"Identity verification is required"}}"#, + CodexFailureCategory::IdentityVerificationRequired, + ), + ( + 400, + r#"{"error":{"message":"invalid request payload"}}"#, + CodexFailureCategory::InvalidRequest, + ), + ( + 401, + r#"{"error":{"code":"token_revoked","message":"token has been revoked"}}"#, + CodexFailureCategory::CredentialExpired, + ), + ( + 401, + r#"{"detail":"Unauthorized"}"#, + CodexFailureCategory::CredentialExpired, + ), + ( + 402, + r#"{"detail":{"code":"deactivated_workspace","message":"workspace disabled"}}"#, + CodexFailureCategory::Banned, + ), + ( + 402, + r#"{"error":{"message":"payment required"}}"#, + CodexFailureCategory::QuotaExhausted, + ), + ( + 403, + r#"{"error":{"message":"access forbidden"}}"#, + CodexFailureCategory::PermissionDenied, + ), + (404, "", CodexFailureCategory::CloudflarePathBlocked), + (404, " \r\n\t", CodexFailureCategory::CloudflarePathBlocked), + ( + 404, + r#"{"error":{"type":"invalid_request_error","code":null,"message":"Item with id 'rs_missing' not found.","param":"input"}}"#, + CodexFailureCategory::InvalidRequest, + ), + ( + 429, + r#"{"error":{"type":"usage_limit_reached","message":"quota window reached"}}"#, + CodexFailureCategory::UsageLimitExhausted, + ), + ( + 429, + r#"{"error":{"type":"project_spend_limit_exceeded"}}"#, + CodexFailureCategory::RateLimited, + ), + ( + 401, + r#"{"error":{"code":"project_spend_limit_exceeded"}}"#, + CodexFailureCategory::CredentialExpired, + ), + ( + 529, + r#"{"error":{"type":"server_error","message":"overloaded"}}"#, + CodexFailureCategory::Unavailable, + ), + ]; + + for (status, body, expected) in cases { + assert_eq!( + classify(status, body), + expected, + "status={status} body={body}" + ); + } +} diff --git a/backend/crates/providers/openai/tests/transport/diagnostics/evidence.rs b/backend/crates/providers/openai/tests/transport/diagnostics/evidence.rs new file mode 100644 index 000000000..1dccd4c5b --- /dev/null +++ b/backend/crates/providers/openai/tests/transport/diagnostics/evidence.rs @@ -0,0 +1,85 @@ +//! 对应生产职责的行为测试 + +#[test] +fn diagnostic_wire_dump_preserves_binary_bytes_and_numbers_every_fragment() { + use base64::{Engine as _, engine::general_purpose::STANDARD}; + use gateway_core::diagnostics::TraceContext; + use std::sync::{Arc, Mutex}; + + #[derive(Clone)] + struct Writer(Arc>>); + impl std::io::Write for Writer { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().write_all(bytes)?; + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let output = Arc::new(Mutex::new(Vec::new())); + let writer = Writer(Arc::clone(&output)); + let subscriber = tracing_subscriber::fmt() + .json() + .with_writer(move || writer.clone()) + .with_ansi(false) + .finish(); + let bytes: Vec = (0..100_000).map(|index| (index % 256) as u8).collect(); + tracing::subscriber::with_default(subscriber, || { + let trace = TraceContext::new("req_binary_dump"); + trace + .attempt(3) + .exchange("websocket") + .dump("upstream.binary", &bytes); + trace.headers( + "client.connection.headers", + serde_json::json!({}), + [ + ("authorization", b"Bearer secret".as_slice()), + ("x-binary", b"\xff\x80".as_slice()), + ("x-binary", b"\x00".as_slice()), + ], + ); + let snapshot = trace.snapshot().unwrap(); + assert_eq!(snapshot["wireFrames"], 2); + assert!(!snapshot.to_string().contains("Bearer secret")); + }); + let log = output.lock().unwrap(); + let records: Vec = std::str::from_utf8(&log) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .filter(|record: &serde_json::Value| record["target"] == "request_dump") + .collect(); + assert_eq!(records.len(), 5); + let mut recovered = Vec::new(); + for (index, record) in records.iter().take(4).enumerate() { + let fields = &record["fields"]; + assert_eq!(fields["wire_sequence"], 1); + assert_eq!(fields["attempt_index"], 3); + assert_eq!(fields["exchange_id"], 1); + assert_eq!(fields["chunk_index"], index); + assert_eq!(fields["chunk_count"], 4); + recovered.extend( + STANDARD + .decode(fields["body_base64"].as_str().unwrap()) + .unwrap(), + ); + } + assert_eq!(recovered, bytes); + let header_record = &records[4]["fields"]; + assert_eq!(header_record["wire_sequence"], 2); + let header_bytes = STANDARD + .decode(header_record["body_base64"].as_str().unwrap()) + .unwrap(); + let headers: serde_json::Value = serde_json::from_slice(&header_bytes).unwrap(); + for (index, expected) in [b"Bearer secret".as_slice(), b"\xff\x80", b"\x00"] + .into_iter() + .enumerate() + { + let value = STANDARD + .decode(headers["headers"][index]["valueBase64"].as_str().unwrap()) + .unwrap(); + assert_eq!(value, expected); + } +} diff --git a/backend/crates/providers/openai/tests/transport/diagnostics/mod.rs b/backend/crates/providers/openai/tests/transport/diagnostics/mod.rs index dc2fa0140..40f904d8d 100644 --- a/backend/crates/providers/openai/tests/transport/diagnostics/mod.rs +++ b/backend/crates/providers/openai/tests/transport/diagnostics/mod.rs @@ -1,5 +1,7 @@ //! 验证上游失败分类、重放资格、请求标识与响应事实提取 +mod contract; +mod evidence; use base64::{Engine as _, engine::general_purpose::STANDARD}; use provider_openai::transport::CodexUpstreamDiagnostics; use provider_openai::transport::diagnostics::{ @@ -22,224 +24,6 @@ fn classify(status: u16, body: &str) -> CodexFailureCategory { .category() } -#[test] -fn model_rejection_requires_the_official_code_and_status() { - for status in [400, 403, 404] { - assert_eq!( - classify( - status, - r#"{"error":{"code":"model_not_found","message":"Access to this deployment ended."}}"# - ), - CodexFailureCategory::ModelUnsupported - ); - } - for (status, body, expected) in [ - ( - 400, - r#"{"error":{"code":"unsupported_value","type":"invalid_request_error","param":"reasoning.effort","message":"Unsupported value: 'none' is not supported with the 'gpt-6-astra' model. Supported values are: 'low', 'medium', 'high', 'xhigh', and 'max'."}}"#, - CodexFailureCategory::InvalidRequest, - ), - ( - 400, - r#"{"error":{"message":"The model is not supported."}}"#, - CodexFailureCategory::InvalidRequest, - ), - ( - 400, - r#"{"error":{"code":"unknown_error","message":"model_not_supported"}}"#, - CodexFailureCategory::InvalidRequest, - ), - ( - 400, - r#"{"error":{"code":"unknown_error"},"detail":"model_not_available"}"#, - CodexFailureCategory::InvalidRequest, - ), - ( - 500, - r#"{"error":{"code":"model_not_found","message":"The model is not available."}}"#, - CodexFailureCategory::Unavailable, - ), - ] { - let failure = CodexUpstreamFailure::from_response( - reqwest::StatusCode::from_u16(status).unwrap(), - body, - None, - &CodexUpstreamDiagnostics::default(), - None, - &[], - &[], - CodexUpstreamSendPhase::AfterPayload, - ); - assert_eq!(failure.category(), expected, "{body}"); - assert!(!failure.replay_is_safe(), "{body}"); - } -} - -#[test] -fn flex_capacity_rejection_should_be_terminal_even_before_payload_send() { - for phase in [ - CodexUpstreamSendPhase::BeforePayload, - CodexUpstreamSendPhase::AfterPayload, - ] { - let failure = CodexUpstreamFailure::from_response( - reqwest::StatusCode::TOO_MANY_REQUESTS, - r#"{"error":{"type":"resource_unavailable","code":"flex_unavailable","message":"Flex capacity unavailable."}}"#, - Some(300), - &CodexUpstreamDiagnostics::default(), - None, - &[], - &[], - phase, - ); - assert_eq!(failure.category(), CodexFailureCategory::FlexUnavailable); - assert!(!failure.replay_is_safe()); - } -} - -#[test] -fn turn_rate_limit_does_not_grant_proxy_replay_or_account_cooldown() { - for phase in [ - CodexUpstreamSendPhase::BeforePayload, - CodexUpstreamSendPhase::AfterPayload, - CodexUpstreamSendPhase::Ambiguous, - ] { - let failure = CodexUpstreamFailure::from_response( - reqwest::StatusCode::TOO_MANY_REQUESTS, - r#"{"error":{"code":"turn_rate_limit_exceeded","type":"rate_limit_error","message":"Retry this turn later."}}"#, - Some(53), - &CodexUpstreamDiagnostics::default(), - None, - &[], - &[], - phase, - ); - assert_eq!(failure.category(), CodexFailureCategory::TurnRateLimited); - assert!(!failure.replay_is_safe()); - } - assert_eq!( - classify(429, r#"{"error":{"message":"turn_rate_limit_exceeded"}}"#), - CodexFailureCategory::RateLimited - ); -} - -#[test] -fn server_error_replay_requires_explicit_503_and_unambiguous_send() { - for (status, body, retryable) in [ - ( - 503, - r#"{"error":{"code":"server_error","type":"server_error"}}"#, - true, - ), - ( - 500, - r#"{"error":{"code":"server_error","type":"server_error"}}"#, - false, - ), - ( - 504, - r#"{"error":{"code":"server_error","type":"server_error"}}"#, - false, - ), - (503, r#"{"error":{"type":"server_error"}}"#, false), - ( - 503, - r#"{"error":{"code":"Vendor.Future.v2","type":"server_error"}}"#, - false, - ), - ( - 503, - r#"{"error":{"code":"flex_unavailable","type":"server_error"}}"#, - false, - ), - (503, "server_error", false), - ] { - for phase in [ - CodexUpstreamSendPhase::BeforePayload, - CodexUpstreamSendPhase::AfterPayload, - CodexUpstreamSendPhase::Ambiguous, - ] { - let failure = CodexUpstreamFailure::from_response( - reqwest::StatusCode::from_u16(status).unwrap(), - body, - None, - &CodexUpstreamDiagnostics::default(), - None, - &[], - &[], - phase, - ); - assert_eq!( - failure.replay_is_safe(), - retryable && phase != CodexUpstreamSendPhase::Ambiguous, - "status={status}, body={body}, phase={phase:?}" - ); - } - } -} - -#[test] -fn capacity_rejections_are_request_scoped_across_http_statuses() { - for status in [400, 429, 503] { - for body in [ - r#"{"error":{"code":"server_is_overloaded","message":"busy"}}"#, - r#"{"error":{"code":"slow_down","type":"server_error"}}"#, - r#"{"error":{"type":"server_is_overloaded"}}"#, - r#"{"error":{"message":"slow_down"}}"#, - r#"{"error":{"type":"invalid_request_error","message":"Selected model is at capacity. Please try a different model."}}"#, - ] { - assert_eq!( - classify(status, body), - CodexFailureCategory::CapacityUnavailable - ); - for (phase, safe) in [ - (CodexUpstreamSendPhase::BeforePayload, true), - (CodexUpstreamSendPhase::AfterPayload, true), - (CodexUpstreamSendPhase::Ambiguous, false), - ] { - let failure = CodexUpstreamFailure::from_response( - reqwest::StatusCode::from_u16(status).expect("status"), - body, - Some(129_600), - &CodexUpstreamDiagnostics::default(), - None, - &[], - &[], - phase, - ); - assert_eq!(failure.replay_is_safe(), safe); - } - } - } -} - -#[test] -fn capacity_words_do_not_override_quota_policy_or_arbitrary_body_fields() { - for (status, body, expected) in [ - ( - 429, - r#"{"error":{"type":"usage_limit_reached","message":"Selected model is at capacity"}}"#, - CodexFailureCategory::UsageLimitExhausted, - ), - ( - 400, - r#"{"error":{"code":"cyber_policy","message":"Selected model is at capacity"}}"#, - CodexFailureCategory::InvalidRequest, - ), - ( - 400, - r#"{"error":{"message":"bad input"},"input":"Selected model is at capacity"}"#, - CodexFailureCategory::InvalidRequest, - ), - ( - 429, - r#"{"error":{"code":"rate_limit_exceeded","message":"retry later"}}"#, - CodexFailureCategory::RateLimited, - ), - ] { - assert_eq!(classify(status, body), expected); - } -} - fn trace_header<'a>(diagnostics: &'a CodexUpstreamDiagnostics, name: &str) -> Option<&'a str> { diagnostics .trace_headers @@ -247,334 +31,3 @@ fn trace_header<'a>(diagnostics: &'a CodexUpstreamDiagnostics, name: &str) -> Op .find(|(candidate, _)| candidate.eq_ignore_ascii_case(name)) .map(|(_, value)| value.as_str()) } - -#[test] -fn diagnostics_should_extract_request_id_and_trace_headers() { - let mut headers = HeaderMap::new(); - headers.insert("x-request-id", HeaderValue::from_static("req_1")); - headers.insert("cf-ray", HeaderValue::from_static("ray_1")); - - let diagnostics = CodexUpstreamDiagnostics::from_headers(Some(429), &headers); - - assert_eq!( - ( - diagnostics.status_code, - diagnostics.request_id.as_deref(), - trace_header(&diagnostics, "cf-ray"), - ), - (Some(429), Some("req_1"), Some("ray_1")) - ); -} - -#[test] -fn diagnostics_should_not_treat_cf_ray_as_a_request_id() { - let mut headers = HeaderMap::new(); - headers.insert("cf-ray", HeaderValue::from_static("ray_1")); - - let diagnostics = CodexUpstreamDiagnostics::from_headers(Some(403), &headers); - - assert_eq!( - ( - diagnostics.request_id.as_deref(), - trace_header(&diagnostics, "cf-ray"), - ), - (None, Some("ray_1")) - ); -} - -#[test] -fn diagnostics_should_accept_the_oai_request_id_header() { - let mut headers = HeaderMap::new(); - headers.insert("x-oai-request-id", HeaderValue::from_static("oai_req_1")); - - let diagnostics = CodexUpstreamDiagnostics::from_headers(Some(500), &headers); - - assert_eq!(diagnostics.request_id.as_deref(), Some("oai_req_1")); -} - -#[test] -fn diagnostics_should_extract_only_the_identity_error_code() { - let encoded = STANDARD.encode(r#"{"error":{"code":"token_expired","message":"secret"}}"#); - let mut headers = HeaderMap::new(); - headers.insert( - "x-openai-authorization-error", - HeaderValue::from_static("authorization failed"), - ); - headers.insert( - "x-error-json", - HeaderValue::from_str(&encoded).expect("encoded header"), - ); - - let diagnostics = CodexUpstreamDiagnostics::from_headers(Some(403), &headers); - - assert_eq!( - ( - diagnostics.identity_authorization_error.as_deref(), - diagnostics.identity_error_code.as_deref(), - ), - (Some("authorization failed"), Some("token_expired")) - ); - assert!(!format!("{diagnostics:?}").contains("secret")); -} - -#[test] -fn diagnostics_should_ignore_malformed_identity_error_json() { - let mut headers = HeaderMap::new(); - headers.insert("x-error-json", HeaderValue::from_static("not-base64")); - - let diagnostics = CodexUpstreamDiagnostics::from_headers(Some(403), &headers); - - assert_eq!(diagnostics.identity_error_code, None); -} - -#[test] -fn unauthorized_substring_in_a_server_error_body_is_not_credential_expiry() { - assert_eq!( - classify( - 500, - r#"{"error":{"message":"upstream proxy replied: unauthorized"}}"# - ), - CodexFailureCategory::Unavailable - ); -} - -#[test] -fn http_401_classifies_as_credential_expiry_without_body_evidence() { - assert_eq!(classify(401, ""), CodexFailureCategory::CredentialExpired); -} - -#[test] -fn auth_text_with_http_403_still_classifies_as_credential_expiry() { - assert_eq!( - classify( - 403, - r#"{"error":{"message":"unauthorized: token expired"}}"# - ), - CodexFailureCategory::CredentialExpired - ); -} - -#[test] -fn structured_expiry_code_classifies_without_an_auth_status() { - assert_eq!( - classify( - 500, - r#"{"error":{"code":"token_expired","message":"internal"}}"# - ), - CodexFailureCategory::CredentialExpired - ); -} - -#[test] -fn http_429_without_usage_limit_type_remains_a_temporary_rate_limit() { - assert_eq!( - classify( - 429, - r#"{"error":{"code":"insufficient_quota","message":"rate limit reached"}}"# - ), - CodexFailureCategory::RateLimited - ); -} - -#[test] -fn structured_usage_limit_type_is_resettable_quota_exhaustion() { - assert_eq!( - classify( - 429, - r#"{"error":{"code":null,"type":"usage_limit_reached","message":"The usage limit has been reached"}}"# - ), - CodexFailureCategory::UsageLimitExhausted - ); -} - -#[test] -fn http_429_usage_limit_message_without_a_type_remains_a_temporary_rate_limit() { - assert_eq!( - classify( - 429, - r#"{"error":{"message":"The usage limit has been reached"}}"# - ), - CodexFailureCategory::RateLimited - ); -} - -#[test] -fn http_429_usage_limit_code_without_a_type_remains_a_temporary_rate_limit() { - assert_eq!( - classify( - 429, - r#"{"error":{"code":"usage_limit_reached","message":"The usage limit has been reached"}}"# - ), - CodexFailureCategory::RateLimited - ); -} - -#[test] -fn bare_http_429_remains_a_temporary_rate_limit() { - assert_eq!(classify(429, ""), CodexFailureCategory::RateLimited); -} - -#[test] -fn openai_account_failure_matrix_is_preserved() { - let cases = [ - ( - 400, - r#"{"error":{"message":"Organization has been disabled"}}"#, - CodexFailureCategory::Banned, - ), - ( - 400, - r#"{"error":{"message":"Identity verification is required"}}"#, - CodexFailureCategory::IdentityVerificationRequired, - ), - ( - 400, - r#"{"error":{"message":"invalid request payload"}}"#, - CodexFailureCategory::InvalidRequest, - ), - ( - 401, - r#"{"error":{"code":"token_revoked","message":"token has been revoked"}}"#, - CodexFailureCategory::CredentialExpired, - ), - ( - 401, - r#"{"detail":"Unauthorized"}"#, - CodexFailureCategory::CredentialExpired, - ), - ( - 402, - r#"{"detail":{"code":"deactivated_workspace","message":"workspace disabled"}}"#, - CodexFailureCategory::Banned, - ), - ( - 402, - r#"{"error":{"message":"payment required"}}"#, - CodexFailureCategory::QuotaExhausted, - ), - ( - 403, - r#"{"error":{"message":"access forbidden"}}"#, - CodexFailureCategory::PermissionDenied, - ), - (404, "", CodexFailureCategory::CloudflarePathBlocked), - (404, " \r\n\t", CodexFailureCategory::CloudflarePathBlocked), - ( - 404, - r#"{"error":{"type":"invalid_request_error","code":null,"message":"Item with id 'rs_missing' not found.","param":"input"}}"#, - CodexFailureCategory::InvalidRequest, - ), - ( - 429, - r#"{"error":{"type":"usage_limit_reached","message":"quota window reached"}}"#, - CodexFailureCategory::UsageLimitExhausted, - ), - ( - 429, - r#"{"error":{"type":"project_spend_limit_exceeded"}}"#, - CodexFailureCategory::RateLimited, - ), - ( - 401, - r#"{"error":{"code":"project_spend_limit_exceeded"}}"#, - CodexFailureCategory::CredentialExpired, - ), - ( - 529, - r#"{"error":{"type":"server_error","message":"overloaded"}}"#, - CodexFailureCategory::Unavailable, - ), - ]; - - for (status, body, expected) in cases { - assert_eq!( - classify(status, body), - expected, - "status={status} body={body}" - ); - } -} - -#[test] -fn diagnostic_wire_dump_preserves_binary_bytes_and_numbers_every_fragment() { - use base64::{Engine as _, engine::general_purpose::STANDARD}; - use gateway_core::diagnostics::TraceContext; - use std::sync::{Arc, Mutex}; - - #[derive(Clone)] - struct Writer(Arc>>); - impl std::io::Write for Writer { - fn write(&mut self, bytes: &[u8]) -> std::io::Result { - self.0.lock().unwrap().write_all(bytes)?; - Ok(bytes.len()) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - let output = Arc::new(Mutex::new(Vec::new())); - let writer = Writer(Arc::clone(&output)); - let subscriber = tracing_subscriber::fmt() - .json() - .with_writer(move || writer.clone()) - .with_ansi(false) - .finish(); - let bytes: Vec = (0..100_000).map(|index| (index % 256) as u8).collect(); - tracing::subscriber::with_default(subscriber, || { - let trace = TraceContext::new("req_binary_dump"); - trace - .attempt(3) - .exchange("websocket") - .dump("upstream.binary", &bytes); - trace.headers( - "client.connection.headers", - serde_json::json!({}), - [ - ("authorization", b"Bearer secret".as_slice()), - ("x-binary", b"\xff\x80".as_slice()), - ("x-binary", b"\x00".as_slice()), - ], - ); - let snapshot = trace.snapshot().unwrap(); - assert_eq!(snapshot["wireFrames"], 2); - assert!(!snapshot.to_string().contains("Bearer secret")); - }); - let log = output.lock().unwrap(); - let records: Vec = std::str::from_utf8(&log) - .unwrap() - .lines() - .map(|line| serde_json::from_str(line).unwrap()) - .filter(|record: &serde_json::Value| record["target"] == "request_dump") - .collect(); - assert_eq!(records.len(), 5); - let mut recovered = Vec::new(); - for (index, record) in records.iter().take(4).enumerate() { - let fields = &record["fields"]; - assert_eq!(fields["wire_sequence"], 1); - assert_eq!(fields["attempt_index"], 3); - assert_eq!(fields["exchange_id"], 1); - assert_eq!(fields["chunk_index"], index); - assert_eq!(fields["chunk_count"], 4); - recovered.extend( - STANDARD - .decode(fields["body_base64"].as_str().unwrap()) - .unwrap(), - ); - } - assert_eq!(recovered, bytes); - let header_record = &records[4]["fields"]; - assert_eq!(header_record["wire_sequence"], 2); - let header_bytes = STANDARD - .decode(header_record["body_base64"].as_str().unwrap()) - .unwrap(); - let headers: serde_json::Value = serde_json::from_slice(&header_bytes).unwrap(); - for (index, expected) in [b"Bearer secret".as_slice(), b"\xff\x80", b"\x00"] - .into_iter() - .enumerate() - { - let value = STANDARD - .decode(headers["headers"][index]["valueBase64"].as_str().unwrap()) - .unwrap(); - assert_eq!(value, expected); - } -} diff --git a/backend/crates/providers/openai/tests/transport/headers.rs b/backend/crates/providers/openai/tests/transport/headers.rs index 167081101..e4c2f62fa 100644 --- a/backend/crates/providers/openai/tests/transport/headers.rs +++ b/backend/crates/providers/openai/tests/transport/headers.rs @@ -742,7 +742,7 @@ async fn websocket_should_keep_an_exact_chain_while_new_connections_adopt_the_la #[tokio::test] async fn custom_core_version_change_reconnects_new_chains_and_keeps_exact_continuations() { use gateway_core::account::OpaqueProviderData; - use provider_openai::transport::profile::identity::RequestProfileSelection; + use provider_openai::profile::identity::RequestProfileSelection; const USER_AGENT: &str = "Custom Agent/test"; let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -831,9 +831,7 @@ async fn custom_core_version_change_reconnects_new_chains_and_keeps_exact_contin #[tokio::test] async fn concurrent_request_profiles_emit_independent_http_identities() { - use provider_openai::transport::profile::selection::{ - ClientKind, ClientPlatform, ClientProfileSelection, - }; + use provider_openai::profile::selection::{ClientKind, ClientPlatform, ClientProfileSelection}; let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); let server = tokio::spawn(async move { @@ -852,7 +850,7 @@ async fn concurrent_request_profiles_emit_independent_http_identities() { } requests }); - let state = provider_openai::transport::profile::CodexWireProfileState::new(Default::default()); + let state = provider_openai::profile::CodexWireProfileState::new(Default::default()); let desktop = ClientProfileSelection::default().resolve(&state).unwrap(); let cli = ClientProfileSelection { client: ClientKind::Cli, @@ -906,7 +904,7 @@ async fn concurrent_request_profiles_emit_independent_http_identities() { #[tokio::test] async fn tui_and_exec_send_the_same_complete_identity_over_http_and_websocket() { - use provider_openai::transport::profile::selection::{ + use provider_openai::profile::selection::{ CliEntry, ClientKind, ClientPlatform, ClientProfileSelection, VersionMode, }; for (entry, name) in [(CliEntry::Tui, "codex-tui"), (CliEntry::Exec, "codex_exec")] { @@ -938,8 +936,7 @@ async fn tui_and_exec_send_the_same_complete_identity_over_http_and_websocket() .await .unwrap(); }); - let state = - provider_openai::transport::profile::CodexWireProfileState::new(Default::default()); + let state = provider_openai::profile::CodexWireProfileState::new(Default::default()); let profile = ClientProfileSelection { client: ClientKind::Cli, platform: ClientPlatform::Linux, diff --git a/backend/crates/providers/openai/tests/transport/mod.rs b/backend/crates/providers/openai/tests/transport/mod.rs index 2809f862e..1d49b2b31 100644 --- a/backend/crates/providers/openai/tests/transport/mod.rs +++ b/backend/crates/providers/openai/tests/transport/mod.rs @@ -14,7 +14,7 @@ use futures::{SinkExt, StreamExt}; use gateway_protocol::openai::events::{ TokenUsage, extract_sse_usage, rate_limits_to_header_pairs, }; -use provider_openai::transport::profile::{ +use provider_openai::profile::{ CodexBundledReleaseProfile, CodexWireProfile, CodexWireProfileState, }; use provider_openai::transport::protocol::responses::{ @@ -58,7 +58,6 @@ mod headers; mod http_client; mod latency; pub(crate) mod privacy; -mod profile; mod profile_avatar; mod profile_contract; mod protocol; @@ -128,7 +127,7 @@ where pub(crate) fn test_wire_profile() -> CodexWireProfileState { CodexWireProfileState::new(CodexWireProfile { - client_kind: provider_openai::transport::profile::selection::ClientKind::Desktop, + client_kind: provider_openai::profile::selection::ClientKind::Desktop, originator: "codex_cli_rs".to_owned(), codex_version: "1.2.3".to_owned(), desktop_version: "1.2.3".to_owned(), diff --git a/backend/crates/providers/openai/tests/transport/profile_contract.rs b/backend/crates/providers/openai/tests/transport/profile_contract.rs index 834d3e68e..baf8b358a 100644 --- a/backend/crates/providers/openai/tests/transport/profile_contract.rs +++ b/backend/crates/providers/openai/tests/transport/profile_contract.rs @@ -119,10 +119,9 @@ fn deployment_routing_survives_artifact_updates_and_profile_selection() { desktop_build: "9999".to_owned(), verified_at: Utc::now(), }); - let snapshot = - provider_openai::transport::profile::selection::ClientProfileSelection::default() - .resolve(&profile) - .expect("selected profile"); + let snapshot = provider_openai::profile::selection::ClientProfileSelection::default() + .resolve(&profile) + .expect("selected profile"); let model = provider_openai::transport::headers::build_codex_model_headers( &snapshot, "Bearer audit", diff --git a/backend/crates/providers/openai/tests/transport/request.rs b/backend/crates/providers/openai/tests/transport/request.rs index 7c232f69a..0a8549830 100644 --- a/backend/crates/providers/openai/tests/transport/request.rs +++ b/backend/crates/providers/openai/tests/transport/request.rs @@ -4,7 +4,7 @@ use gateway_core::operation::{GenerateRequest, ProtocolPayload}; use serde_json::{Map, Value, json}; use provider_openai::encode_generate_request; -use provider_openai::transport::profile::CodexRequestLocation; +use provider_openai::profile::CodexRequestLocation; #[test] fn encoder_should_override_location_while_preserving_environment_dates() { diff --git a/backend/crates/providers/openai/tests/transport/reset_credits.rs b/backend/crates/providers/openai/tests/transport/reset_credits.rs index 1d3db7b9a..0367d52f4 100644 --- a/backend/crates/providers/openai/tests/transport/reset_credits.rs +++ b/backend/crates/providers/openai/tests/transport/reset_credits.rs @@ -2,7 +2,7 @@ use chrono::{TimeZone as _, Utc}; use provider_openai::credential::CodexResetCreditsError; -use provider_openai::transport::profile::{CodexWireProfile, CodexWireProfileState}; +use provider_openai::profile::{CodexWireProfile, CodexWireProfileState}; use provider_openai::transport::{ CodexBackendClient, CodexClientError, CodexRequestContext, MAX_CODEX_RESET_CREDITS_BODY_BYTES, }; @@ -21,7 +21,7 @@ fn client(base_url: &str) -> CodexBackendClient { .expect("reset-credit client"), base_url, CodexWireProfileState::new(CodexWireProfile { - client_kind: provider_openai::transport::profile::selection::ClientKind::Desktop, + client_kind: provider_openai::profile::selection::ClientKind::Desktop, originator: "Codex Desktop".to_owned(), codex_version: "0.115.0-alpha.11".to_owned(), desktop_version: "26.818.21641".to_owned(), diff --git a/backend/crates/providers/openai/tests/transport/usage.rs b/backend/crates/providers/openai/tests/transport/usage.rs index f7612427d..9f721ba59 100644 --- a/backend/crates/providers/openai/tests/transport/usage.rs +++ b/backend/crates/providers/openai/tests/transport/usage.rs @@ -1,4 +1,4 @@ -//! 验证 OpenAI 各模型、服务档位与上下文区间的费用明细计算 +//! 验证 Codex usage 查询、响应体限制和错误元数据 use std::collections::BTreeSet; use std::io::{Read, Write}; @@ -7,10 +7,10 @@ use std::thread; use std::time::Duration; use chrono::{TimeZone, Utc}; -use provider_openai::transport::profile::{CodexWireProfile, CodexWireProfileState}; +use provider_openai::profile::{CodexWireProfile, CodexWireProfileState}; use provider_openai::transport::{ CodexBackendClient, CodexClientError, CodexRequestContext, MAX_CODEX_USAGE_BODY_BYTES, - OpenAiBillingUsage, build_reqwest_client, openai_billing_breakdown, + build_reqwest_client, }; use reqwest::StatusCode; use wiremock::matchers::{method, path}; @@ -18,350 +18,6 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; const OVERSIZED_BODY_ERROR: &str = "upstream usage response exceeded the body limit"; -fn billing_usage( - input_tokens: u64, - output_tokens: u64, - cached_input_tokens: u64, - cache_write_input_tokens: u64, -) -> OpenAiBillingUsage { - OpenAiBillingUsage::new( - input_tokens, - output_tokens, - cached_input_tokens, - cache_write_input_tokens, - ) -} - -#[test] -fn astra_billing_should_preserve_components_across_tiers_and_context_boundary() { - // 每百万 token 的美元价格,依次为输入、缓存读取、缓存写入与输出 - for (tier, input, expected, multiplier) in [ - (None, 272_000, ["10", "1", "12.5", "50"], 100), - (None, 272_001, ["20", "2", "25", "75"], 100), - (Some("flex"), 272_000, ["5", "0.5", "6.25", "25"], 50), - (Some("flex"), 272_001, ["10", "1", "12.5", "37.5"], 50), - (Some("fast"), 272_000, ["20", "2", "25", "100"], 200), - (Some("fast"), 272_001, ["40", "4", "50", "150"], 200), - (Some("priority"), 272_001, ["40", "4", "50", "150"], 200), - ] { - let breakdown = - openai_billing_breakdown("gpt-6-astra", billing_usage(input, 5, 20, 10), tier) - .expect("published Astra pricing"); - let prices = [ - breakdown.input_price_per_million(), - breakdown.cache_read_price_per_million(), - breakdown.cache_write_price_per_million(), - breakdown.output_price_per_million(), - ] - .map(|price| { - price - .amount() - .to_string() - .trim_end_matches('0') - .trim_end_matches('.') - .to_owned() - }); - assert_eq!(prices, expected, "tier={tier:?}, input={input}"); - assert_eq!(breakdown.multiplier_percent(), multiplier); - } - let breakdown = openai_billing_breakdown("gpt-6-astra", billing_usage(100, 5, 20, 10), None) - .expect("Astra component pricing"); - assert_eq!( - ( - breakdown.input_amount().amount().scaled(), - breakdown.output_amount().amount().scaled(), - breakdown.cache_read_amount().amount().scaled(), - breakdown.cache_write_amount().amount().scaled(), - breakdown.total_amount().amount().scaled(), - ), - (7_000_000, 2_500_000, 200_000, 1_250_000, 10_950_000), - ); -} - -#[test] -fn gpt_6_models_should_use_published_prices_across_tiers_and_context_boundary() { - // 每档依次核对每百万 Token 的输入、缓存读取、缓存写入和输出价格 - for (model, cases) in [ - ( - "gpt-6.2-astra", - [ - (None, 272_000, ["8", "0.4", "10", "40"]), - (None, 272_001, ["16", "0.8", "20", "60"]), - (Some("fast"), 272_000, ["16", "0.8", "20", "80"]), - (Some("priority"), 272_001, ["32", "1.6", "40", "120"]), - (Some("ultrafast"), 272_000, ["48", "2.4", "60", "240"]), - (Some("ultrafast"), 272_001, ["96", "4.8", "120", "360"]), - ], - ), - ( - "gpt-6.2-sol", - [ - (None, 272_000, ["2", "0.1", "2.5", "10"]), - (None, 272_001, ["4", "0.2", "5", "15"]), - (Some("fast"), 272_000, ["4", "0.2", "5", "20"]), - (Some("priority"), 272_001, ["8", "0.4", "10", "30"]), - (Some("ultrafast"), 272_000, ["12", "0.6", "15", "60"]), - (Some("ultrafast"), 272_001, ["24", "1.2", "30", "90"]), - ], - ), - ( - "gpt-6.1-sol", - [ - (None, 272_000, ["2", "0.1", "2.5", "10"]), - (None, 272_001, ["4", "0.2", "5", "15"]), - (Some("flex"), 272_000, ["1", "0.05", "1.25", "5"]), - (Some("flex"), 272_001, ["2", "0.1", "2.5", "7.5"]), - (Some("fast"), 272_000, ["4", "0.2", "5", "20"]), - (Some("priority"), 272_001, ["8", "0.4", "10", "30"]), - ], - ), - ( - "gpt-6.1-terra", - [ - (None, 272_000, ["1", "0.05", "1.25", "5"]), - (None, 272_001, ["2", "0.1", "2.5", "7.5"]), - (Some("flex"), 272_000, ["0.5", "0.025", "0.625", "2.5"]), - (Some("flex"), 272_001, ["1", "0.05", "1.25", "3.75"]), - (Some("fast"), 272_000, ["2", "0.1", "2.5", "10"]), - (Some("priority"), 272_001, ["4", "0.2", "5", "15"]), - ], - ), - ( - "gpt-6-sol", - [ - (None, 272_000, ["2", "0.2", "2.5", "10"]), - (None, 272_001, ["4", "0.4", "5", "15"]), - (Some("flex"), 272_000, ["1", "0.1", "1.25", "5"]), - (Some("flex"), 272_001, ["2", "0.2", "2.5", "7.5"]), - (Some("fast"), 272_000, ["4", "0.4", "5", "20"]), - (Some("priority"), 272_001, ["8", "0.8", "10", "30"]), - ], - ), - ( - "gpt-6-luna", - [ - (None, 272_000, ["0.1", "0.01", "0.125", "0.5"]), - (None, 272_001, ["0.2", "0.02", "0.25", "0.75"]), - (Some("flex"), 272_000, ["0.05", "0.005", "0.0625", "0.25"]), - (Some("flex"), 272_001, ["0.1", "0.01", "0.125", "0.375"]), - (Some("fast"), 272_000, ["0.2", "0.02", "0.25", "1"]), - (Some("priority"), 272_001, ["0.4", "0.04", "0.5", "1.5"]), - ], - ), - ] { - for (tier, input, expected) in cases { - let breakdown = openai_billing_breakdown(model, billing_usage(input, 5, 20, 10), tier) - .expect("published GPT-6 pricing"); - let actual = [ - breakdown.input_price_per_million(), - breakdown.cache_read_price_per_million(), - breakdown.cache_write_price_per_million(), - breakdown.output_price_per_million(), - ] - .map(|price| price.amount().canonical()); - assert_eq!(actual, expected, "{model} {tier:?} {input}"); - assert_eq!( - breakdown.long_context_billing_applied(), - input > 272_000, - "{model} {tier:?} {input}" - ); - } - } -} - -#[test] -fn ultrafast_billing_uses_published_prices_across_the_context_boundary() { - // 每档依次核对每百万 Token 的输入、缓存读取、缓存写入和输出价格 - for (model, input, expected, total) in [ - ("gpt-6-astra", 272_000, ["60", "6", "75", "300"], "16.32057"), - ( - "gpt-6-astra", - 272_001, - ["120", "12", "150", "450"], - "32.64051", - ), - ( - "gpt-6.1-sol", - 272_000, - ["12", "0.6", "15", "60"], - "3.264102", - ), - ( - "gpt-6.1-sol", - 272_001, - ["24", "1.2", "30", "90"], - "6.528078", - ), - ] { - let breakdown = - openai_billing_breakdown(model, billing_usage(input, 5, 20, 10), Some("ultrafast")) - .expect("published Ultrafast pricing"); - let prices = [ - breakdown.input_price_per_million(), - breakdown.cache_read_price_per_million(), - breakdown.cache_write_price_per_million(), - breakdown.output_price_per_million(), - ] - .map(|price| price.amount().canonical()); - assert_eq!(prices, expected, "{model} {input}"); - assert_eq!(breakdown.total_amount().amount().canonical(), total); - assert_eq!(breakdown.service_tier(), Some("ultrafast")); - assert_eq!(breakdown.multiplier_percent(), 600); - assert_eq!(breakdown.long_context_billing_applied(), input > 272_000); - } -} - -#[test] -fn billing_breakdown_should_preserve_input_output_and_cache_components() { - let breakdown = openai_billing_breakdown("gpt-5.6-sol", billing_usage(100, 5, 20, 10), None) - .expect("known model pricing"); - - assert_eq!(breakdown.input_amount().amount().scaled(), 3_500_000); - assert_eq!(breakdown.output_amount().amount().scaled(), 1_500_000); - assert_eq!(breakdown.cache_read_amount().amount().scaled(), 100_000); - assert_eq!(breakdown.cache_write_amount().amount().scaled(), 625_000); - assert_eq!(breakdown.total_amount().amount().scaled(), 5_725_000); - assert_eq!(breakdown.service_tier(), Some("default")); - assert_eq!(breakdown.multiplier_percent(), 100); -} - -#[test] -fn billing_breakdown_should_use_latest_gpt_5_6_and_cached_input_prices() { - let terra = openai_billing_breakdown("gpt-5.6-terra", billing_usage(1, 1, 0, 0), None) - .expect("gpt-5.6-terra standard pricing"); - assert_eq!(terra.total_amount().amount().scaled(), 140_000); - - let terra_fast = - openai_billing_breakdown("gpt-5.6-terra", billing_usage(1, 1, 0, 0), Some("fast")) - .expect("gpt-5.6-terra fast pricing"); - assert_eq!(terra_fast.total_amount().amount().scaled(), 280_000); - - let terra_long = - openai_billing_breakdown("gpt-5.6-terra", billing_usage(272_001, 0, 0, 0), None) - .expect("gpt-5.6-terra long-context pricing"); - assert_eq!(terra_long.total_amount().amount().scaled(), 10_880_040_000); - - let luna = openai_billing_breakdown("gpt-5.6-luna", billing_usage(1, 1, 0, 0), None) - .expect("gpt-5.6-luna standard pricing"); - assert_eq!(luna.total_amount().amount().scaled(), 14_000); - - let gpt_4o = openai_billing_breakdown("gpt-4o", billing_usage(1, 1, 1, 0), None) - .expect("gpt-4o cached-input pricing"); - assert_eq!(gpt_4o.total_amount().amount().scaled(), 112_500); - - let gpt_4o_mini = openai_billing_breakdown("gpt-4o-mini", billing_usage(1, 1, 1, 0), None) - .expect("gpt-4o-mini cached-input pricing"); - assert_eq!(gpt_4o_mini.total_amount().amount().scaled(), 6_750); -} - -#[test] -fn billing_breakdown_should_apply_fast_and_flex_tiers_without_guessing_unknown_models() { - let fast = openai_billing_breakdown("gpt-5.4", billing_usage(1, 1, 0, 0), Some("fast")) - .expect("fast pricing"); - let flex = openai_billing_breakdown("gpt-5.4", billing_usage(1, 1, 0, 0), Some("flex")) - .expect("flex pricing"); - - assert_eq!(fast.total_amount().amount().scaled(), 350_000); - assert_eq!(fast.service_tier(), Some("fast")); - assert_eq!(fast.multiplier_percent(), 200); - assert!(!fast.long_context_billing_applied()); - assert_eq!(flex.total_amount().amount().scaled(), 87_500); - assert_eq!(flex.multiplier_percent(), 50); - assert!(openai_billing_breakdown("unknown-model", billing_usage(1, 1, 0, 0), None).is_none()); -} - -#[test] -fn billing_breakdown_should_use_official_fast_long_context_prices() { - let breakdown = - openai_billing_breakdown("gpt-5.6-sol", billing_usage(272_001, 1, 1, 1), Some("fast")) - .expect("gpt-5.6-sol fast long-context pricing"); - - assert_eq!( - ( - breakdown.input_price_per_million().amount().scaled(), - breakdown.cache_read_price_per_million().amount().scaled(), - breakdown.cache_write_price_per_million().amount().scaled(), - breakdown.output_price_per_million().amount().scaled(), - ), - ( - 200_000_000_000, - 20_000_000_000, - 250_000_000_000, - 900_000_000_000, - ) - ); -} - -#[test] -fn billing_breakdown_should_fail_closed_for_unpublished_prices() { - assert_eq!( - ( - openai_billing_breakdown("gpt-5.5", billing_usage(272_001, 1, 0, 0), Some("fast")) - .is_none(), - openai_billing_breakdown("gpt-5.5-pro", billing_usage(1, 1, 0, 0), Some("fast")) - .is_none(), - openai_billing_breakdown("gpt-5.3-codex-spark", billing_usage(1, 1, 0, 0), None) - .is_none(), - openai_billing_breakdown("gpt-4o", billing_usage(1, 1, 0, 0), Some("flex")).is_none(), - ), - (true, true, true, true) - ); -} - -#[test] -fn billing_breakdown_should_use_official_gpt_4o_fast_prices() { - let breakdown = openai_billing_breakdown("gpt-4o", billing_usage(1, 1, 1, 0), Some("priority")) - .expect("gpt-4o fast pricing"); - - assert_eq!( - ( - breakdown.cache_read_price_per_million().amount().scaled(), - breakdown.output_price_per_million().amount().scaled(), - breakdown.standard_amount().amount().scaled(), - breakdown.total_amount().amount().scaled(), - breakdown.multiplier_percent(), - ), - (21_250_000_000, 170_000_000_000, 112_500, 191_250, 170,) - ); -} - -#[test] -fn billing_breakdown_should_use_published_flex_cache_price() { - let breakdown = openai_billing_breakdown("gpt-5.4", billing_usage(1, 0, 1, 0), Some("flex")) - .expect("gpt-5.4 flex pricing"); - - assert_eq!( - breakdown.cache_read_price_per_million().amount().scaled(), - 1_300_000_000 - ); -} - -#[test] -fn billing_breakdown_should_switch_only_after_the_long_context_threshold() { - let boundary = openai_billing_breakdown("gpt-5.4", billing_usage(272_000, 0, 0, 0), None) - .expect("short-context boundary"); - let long = openai_billing_breakdown("gpt-5.4", billing_usage(272_001, 0, 0, 0), None) - .expect("long-context pricing"); - - assert!(!boundary.long_context_billing_applied()); - assert!(long.long_context_billing_applied()); - assert!( - !openai_billing_breakdown("gpt-4o", billing_usage(272_001, 0, 0, 0), None) - .expect("model without long-context pricing") - .long_context_billing_applied() - ); - - assert_eq!( - boundary.input_price_per_million().amount().scaled(), - 25_000_000_000 - ); - assert_eq!( - long.input_price_per_million().amount().scaled(), - 50_000_000_000 - ); - assert!(openai_billing_breakdown("gpt-5.4", billing_usage(1, 0, 2, 0), None).is_none()); -} - #[tokio::test] async fn exact_limit_success_body_should_be_accepted() { let server = MockServer::start().await; @@ -383,144 +39,6 @@ async fn exact_limit_success_body_should_be_accepted() { assert!(usage["rate_limit"].is_object()); } -#[test] -fn billing_should_use_explicit_variant_prices_and_verified_snapshots() { - // 每个用例包含一个普通输入 token 和一个输出 token,金额单位为 USD ticks - for (model, expected) in [ - ("gpt-5.6-cyber", 875_000), - ("gpt-5.5-cyber", 875_000), - ("gpt-daybreak-red-latest", 875_000), - ("gpt-daybreak-blue-latest", 350_000), - ("chat-latest", 350_000), - ("gpt-5.4-2026-03-05", 175_000), - (" OpenAI/GPT-4o-2024-08-06 ", 125_000), - ("gpt-4o-2024-05-13", 200_000), - ("gpt-3.5-turbo-0125", 20_000), - ("gpt-3.5-turbo-1106", 30_000), - ] { - let billing = - openai_billing_breakdown(model, billing_usage(1, 1, 0, 0), None).expect(model); - assert_eq!( - billing.total_amount().amount().scaled(), - expected, - "{model}" - ); - } -} - -#[test] -fn billing_should_not_price_shutdown_models_or_restore_them_through_aliases() { - // 官方关闭日期已过;同族仍在服务的基础型号不能为这些旧型号兜底 - for model in [ - "gpt-4-0314", - " OpenAI/GPT-4-0314 ", - "gpt-5-codex", - "gpt-5.1-codex", - "gpt-5.1-codex-max", - "gpt-5.1-codex-mini", - "gpt-5.2-codex", - "gpt-5-chat-latest", - "gpt-5.1-chat-latest", - "gpt-5.2-chat-latest", - "gpt-5.3-chat-latest", - ] { - for tier in [None, Some("flex"), Some("fast")] { - assert!( - openai_billing_breakdown(model, billing_usage(100, 10, 20, 0), tier).is_none(), - "{model} {tier:?}" - ); - } - } -} - -#[test] -fn billing_should_keep_deprecated_models_before_their_shutdown_dates() { - // 截至 2026-09-13,这些型号尚未到官方关闭日期,仍按已公布单价计费 - for model in [ - "gpt-3.5-turbo-instruct", - "gpt-3.5-turbo-1106", - "gpt-4-0613", - "gpt-4-turbo-2024-04-09", - "gpt-4o-2024-05-13", - "gpt-4.1-nano", - "o1", - "o1-pro", - "o3-mini", - "o4-mini", - ] { - assert!( - openai_billing_breakdown(model, billing_usage(100, 10, 20, 0), None).is_some(), - "{model}" - ); - } -} - -#[test] -fn billing_should_not_inherit_prices_for_unknown_models_or_tiers() { - for model in [ - "gpt-6-astra-future", - "gpt-6-astra-2099-01-01", - "gpt-5.6-sol-wm", - "gpt-5.6-cyber-future", - "gpt-5.4-cyber", - "gpt-5.3-codex-spark", - "gpt-4.5-preview", - "gpt-4-32k", - "gpt-5.4:custom", - "gpt-5.4.1", - ] { - assert!( - openai_billing_breakdown(model, billing_usage(1, 1, 0, 0), None).is_none(), - "{model}" - ); - } - for (model, input, tier) in [ - ("gpt-5.6-cyber", 272_001, None), - ("gpt-5.5-cyber", 272_001, None), - ("gpt-5.6-cyber", 1, Some("fast")), - ("gpt-5.3-codex", 1, Some("flex")), - ("gpt-6.2-astra", 1, Some("flex")), - ("gpt-6.2-astra", 272_001, Some("flex")), - ("gpt-6.2-sol", 1, Some("flex")), - ("gpt-6.2-sol", 272_001, Some("flex")), - ("gpt-6-astra", 1, Some("auto")), - ("gpt-6-astra", 1, Some("future")), - ("gpt-6.1-terra", 1, Some("ultrafast")), - ("gpt-6.1-terra", 272_001, Some("ultrafast")), - ("gpt-6-sol", 1, Some("ultrafast")), - ("gpt-6-sol", 272_001, Some("ultrafast")), - ("gpt-6-luna", 1, Some("ultrafast")), - ("gpt-6-luna", 272_001, Some("ultrafast")), - ("gpt-5.4", 1, Some("ultrafast")), - ] { - assert!( - openai_billing_breakdown(model, billing_usage(input, 1, 0, 0), tier).is_none(), - "{model} {tier:?}" - ); - } -} - -#[test] -fn billing_should_reject_overlapping_or_overflowing_cache_counts() { - for (input, cached, written) in [(100, 20, 90), (100, 0, 101), (u64::MAX, u64::MAX, 1)] { - assert!( - openai_billing_breakdown( - "gpt-6-astra", - billing_usage(input, 0, cached, written), - None - ) - .is_none() - ); - } - let cyber = openai_billing_breakdown("gpt-5.6-cyber", billing_usage(100, 10, 20, 10), None) - .expect("已公开的 Cyber 缓存写价格"); - assert_eq!( - cyber.cache_write_price_per_million().amount().to_string(), - "15.6250000000" - ); - assert_eq!(cyber.total_amount().amount().scaled(), 18_062_500); -} - #[tokio::test] async fn fetch_should_use_wham_usage_headers_only() { let server = MockServer::start().await; @@ -911,7 +429,7 @@ fn client(base_url: &str) -> CodexBackendClient { fn profile() -> CodexWireProfileState { CodexWireProfileState::new(CodexWireProfile { - client_kind: provider_openai::transport::profile::selection::ClientKind::Desktop, + client_kind: provider_openai::profile::selection::ClientKind::Desktop, originator: "codex_cli_rs".to_owned(), codex_version: "0.144.0".to_owned(), desktop_version: "1.0.0".to_owned(), @@ -951,91 +469,3 @@ fn context() -> CodexRequestContext<'static> { account_selection: Default::default(), } } - -use gateway_core::metering::ModelPriceOverride; -use provider_openai::transport::openai_billing_breakdown_with_override; -use serde_json::json; - -#[test] -fn custom_price_has_exact_cache_and_multiplier_math() { - let custom: ModelPriceOverride = serde_json::from_value(json!({"multiplierBps":12500,"bands":{ - "standard":{"input":"2","output":"10","cacheRead":"0","cacheWrite":"3"} - }})) - .unwrap(); - let breakdown = openai_billing_breakdown_with_override( - "custom-model", - billing_usage(100, 10, 20, 10), - None, - Some(&custom), - ) - .unwrap(); - assert_eq!(breakdown.input_amount().amount().canonical(), "0.000175"); - assert_eq!(breakdown.output_amount().amount().canonical(), "0.000125"); - assert_eq!(breakdown.cache_read_amount().amount().canonical(), "0"); - assert_eq!( - breakdown.cache_write_amount().amount().canonical(), - "0.0000375" - ); - assert_eq!(breakdown.total_amount().amount().canonical(), "0.0003375"); - assert_eq!(breakdown.custom_multiplier_bps(), 12500); - assert!( - openai_billing_breakdown_with_override( - "custom-model", - billing_usage(100, 10, 0, 0), - Some("flex"), - Some(&custom) - ) - .is_none() - ); -} - -#[test] -fn a_custom_long_tier_does_not_require_a_long_standard_band() { - for (tier, band) in [("priority", "long_fast"), ("ultrafast", "long_ultrafast")] { - let pricing = serde_json::from_value(json!({"multiplierBps":10000,"bands":{ - "standard":{"input":"2","output":"10","cacheRead":"0","cacheWrite":"0"}, - (band):{"input":"8","output":"40","cacheRead":"0","cacheWrite":"0"} - }})) - .unwrap(); - let result = openai_billing_breakdown_with_override( - "custom-model", - billing_usage(300_000, 0, 0, 0), - Some(tier), - Some(&pricing), - ) - .unwrap(); - assert_eq!(result.total_amount().amount().canonical(), "2.4"); - assert_eq!(result.standard_amount().amount().canonical(), "0.6"); - assert!(result.long_context_billing_applied()); - } -} - -#[test] -fn multiplier_only_preserves_builtin_tiers_and_unknown_models_remain_unknown() { - let custom: ModelPriceOverride = - serde_json::from_value(json!({"multiplierBps":20000,"bands":{}})).unwrap(); - for tier in [None, Some("priority"), Some("flex"), Some("ultrafast")] { - for input in [100, 272_001] { - let usage = billing_usage(input, 10, 20, 5); - let original = openai_billing_breakdown("gpt-6-astra", usage, tier).unwrap(); - let adjusted = - openai_billing_breakdown_with_override("gpt-6-astra", usage, tier, Some(&custom)) - .unwrap(); - assert_eq!( - adjusted.total_amount().amount().scaled(), - original.total_amount().amount().scaled() * 2 - ); - assert_eq!(adjusted.multiplier_percent(), original.multiplier_percent()); - assert_eq!(adjusted.long_context_billing_applied(), input > 272_000); - } - } - assert!( - openai_billing_breakdown_with_override( - "unknown-model", - billing_usage(100, 10, 0, 0), - None, - Some(&custom) - ) - .is_none() - ); -} diff --git a/backend/crates/providers/openai/tests/transport/websocket/pool/contract.rs b/backend/crates/providers/openai/tests/transport/websocket/pool/contract.rs new file mode 100644 index 000000000..dafcb75c6 --- /dev/null +++ b/backend/crates/providers/openai/tests/transport/websocket/pool/contract.rs @@ -0,0 +1,118 @@ +//! 跨模块行为合同测试 + +use super::*; + +#[tokio::test] +async fn search_activation_reconnects_for_http_and_websocket_ingress() { + for downstream_ws in [false, true] { + for (warmup, mut declaration) in [ + ( + false, + json!({"tools":[{"type":"web_search", "search_content_types":["text","image"]}]}), + ), + ( + true, + json!({"tools":[{"type":"web_search", "external_web_access":false}]}), + ), + ( + false, + json!({"input":[{"type":"additional_tools", "role":"developer", "tools":[{"type":"web_search"}]}]}), + ), + ( + false, + json!({"input":[{"type":"tool_search_output", "tools":[{"type":"web_search_preview"}]}]}), + ), + ] { + let (client, pool, mut seen, server) = search_test_server().await; + let first = search_request( + downstream_ws, + json!({ + "generate": !warmup, + "tools": [{"type":"function", "name":"web_search", "parameters":{}}] + }), + ); + send(&client, &first).await.unwrap(); + assert_eq!(seen.recv().await.unwrap().0, 1); + + declaration + .as_object_mut() + .unwrap() + .entry("input") + .or_insert_with(|| json!([])); + declaration["input"].as_array_mut().unwrap().extend([ + json!({"type":"function_call", "name":"lookup", "call_id":"call_1", "arguments":"{}"}), + json!({"type":"function_call_output", "call_id":"call_1", "output":"synthetic history"}), + ]); + let second = search_request(downstream_ws, declaration); + let response = send(&client, &second).await.unwrap(); + let (connection, payload) = seen.recv().await.unwrap(); + pool.shutdown().await; + server.abort(); + + assert_eq!(connection, 2, "search activation must use a fresh socket"); + assert_eq!(response.websocket_pool_decision.unwrap().kind(), "new"); + assert_eq!(payload["input"], second.body()["input"]); + assert_eq!(payload.get("tools"), second.body().get("tools")); + assert!(payload.get("previous_response_id").is_none()); + } + } +} + +#[tokio::test] +async fn search_initialized_socket_survives_tool_removal_and_image_search_activation() { + let (client, pool, mut seen, server) = search_test_server().await; + for tools in [ + json!([{"type":"web_search", "external_web_access":false}]), + json!([]), + json!([{"type":"web_search", "search_content_types":["text","image"]}]), + ] { + let request = search_request(true, json!({"tools": tools})); + send(&client, &request).await.unwrap(); + let (connection, payload) = seen.recv().await.unwrap(); + assert_eq!(connection, 1); + assert_eq!(payload["tools"], tools); + } + pool.shutdown().await; + server.abort(); +} + +#[tokio::test] +async fn search_activation_rejects_native_delta_then_accepts_full_replay() { + let (client, pool, mut seen, server) = search_test_server().await; + let request = search_request(true, json!({})); + send(&client, &request).await.unwrap(); + seen.recv().await.unwrap(); + let mut request = search_request(true, json!({"tools":[{"type":"web_search"}]})); + request.set_previous_response_id(Some("resp_search".into())); + request.previous_response_scope = Some(PreviousResponseScope::ConnectionLocal); + let result = send(&client, &request).await; + if result.is_ok() { + pool.shutdown().await; + server.abort(); + panic!("connection-local delta must require client replay before sending"); + } + let CodexClientError::WebSocket(error) = result.unwrap_err() else { + panic!("expected a typed continuation error"); + }; + assert!(error.continuation_unavailable_reason().is_some()); + assert_eq!( + error.connection_observation().unwrap().exit_reason(), + "search_activation_required" + ); + assert!(seen.try_recv().is_err(), "delta must never reach upstream"); + + let request = search_request( + true, + json!({ + "tools":[{"type":"web_search"}], + "input":[{"role":"user", "content":"complete synthetic history"}] + }), + ); + send(&client, &request).await.unwrap(); + let (connection, payload) = seen.recv().await.unwrap(); + assert_eq!(connection, 2); + assert_eq!(payload["input"], request.body()["input"]); + assert!(payload.get("previous_response_id").is_none()); + pool.shutdown().await; + server.abort(); +} diff --git a/backend/crates/providers/openai/tests/transport/websocket/pool/mod.rs b/backend/crates/providers/openai/tests/transport/websocket/pool/mod.rs index 3665a0952..dd609e3d9 100644 --- a/backend/crates/providers/openai/tests/transport/websocket/pool/mod.rs +++ b/backend/crates/providers/openai/tests/transport/websocket/pool/mod.rs @@ -1,5 +1,6 @@ //! 搜索能力变化时的连接复用与原生续接恢复 +mod contract; use super::*; async fn search_test_server() -> ( @@ -72,118 +73,3 @@ async fn send( .await .expect("request must finish without waiting for pool expiry") } - -#[tokio::test] -async fn search_activation_reconnects_for_http_and_websocket_ingress() { - for downstream_ws in [false, true] { - for (warmup, mut declaration) in [ - ( - false, - json!({"tools":[{"type":"web_search", "search_content_types":["text","image"]}]}), - ), - ( - true, - json!({"tools":[{"type":"web_search", "external_web_access":false}]}), - ), - ( - false, - json!({"input":[{"type":"additional_tools", "role":"developer", "tools":[{"type":"web_search"}]}]}), - ), - ( - false, - json!({"input":[{"type":"tool_search_output", "tools":[{"type":"web_search_preview"}]}]}), - ), - ] { - let (client, pool, mut seen, server) = search_test_server().await; - let first = search_request( - downstream_ws, - json!({ - "generate": !warmup, - "tools": [{"type":"function", "name":"web_search", "parameters":{}}] - }), - ); - send(&client, &first).await.unwrap(); - assert_eq!(seen.recv().await.unwrap().0, 1); - - declaration - .as_object_mut() - .unwrap() - .entry("input") - .or_insert_with(|| json!([])); - declaration["input"].as_array_mut().unwrap().extend([ - json!({"type":"function_call", "name":"lookup", "call_id":"call_1", "arguments":"{}"}), - json!({"type":"function_call_output", "call_id":"call_1", "output":"synthetic history"}), - ]); - let second = search_request(downstream_ws, declaration); - let response = send(&client, &second).await.unwrap(); - let (connection, payload) = seen.recv().await.unwrap(); - pool.shutdown().await; - server.abort(); - - assert_eq!(connection, 2, "search activation must use a fresh socket"); - assert_eq!(response.websocket_pool_decision.unwrap().kind(), "new"); - assert_eq!(payload["input"], second.body()["input"]); - assert_eq!(payload.get("tools"), second.body().get("tools")); - assert!(payload.get("previous_response_id").is_none()); - } - } -} - -#[tokio::test] -async fn search_initialized_socket_survives_tool_removal_and_image_search_activation() { - let (client, pool, mut seen, server) = search_test_server().await; - for tools in [ - json!([{"type":"web_search", "external_web_access":false}]), - json!([]), - json!([{"type":"web_search", "search_content_types":["text","image"]}]), - ] { - let request = search_request(true, json!({"tools": tools})); - send(&client, &request).await.unwrap(); - let (connection, payload) = seen.recv().await.unwrap(); - assert_eq!(connection, 1); - assert_eq!(payload["tools"], tools); - } - pool.shutdown().await; - server.abort(); -} - -#[tokio::test] -async fn search_activation_rejects_native_delta_then_accepts_full_replay() { - let (client, pool, mut seen, server) = search_test_server().await; - let request = search_request(true, json!({})); - send(&client, &request).await.unwrap(); - seen.recv().await.unwrap(); - let mut request = search_request(true, json!({"tools":[{"type":"web_search"}]})); - request.set_previous_response_id(Some("resp_search".into())); - request.previous_response_scope = Some(PreviousResponseScope::ConnectionLocal); - let result = send(&client, &request).await; - if result.is_ok() { - pool.shutdown().await; - server.abort(); - panic!("connection-local delta must require client replay before sending"); - } - let CodexClientError::WebSocket(error) = result.unwrap_err() else { - panic!("expected a typed continuation error"); - }; - assert!(error.continuation_unavailable_reason().is_some()); - assert_eq!( - error.connection_observation().unwrap().exit_reason(), - "search_activation_required" - ); - assert!(seen.try_recv().is_err(), "delta must never reach upstream"); - - let request = search_request( - true, - json!({ - "tools":[{"type":"web_search"}], - "input":[{"role":"user", "content":"complete synthetic history"}] - }), - ); - send(&client, &request).await.unwrap(); - let (connection, payload) = seen.recv().await.unwrap(); - assert_eq!(connection, 2); - assert_eq!(payload["input"], request.body()["input"]); - assert!(payload.get("previous_response_id").is_none()); - pool.shutdown().await; - server.abort(); -} diff --git a/backend/crates/providers/xai/src/admin/credentials.rs b/backend/crates/providers/xai/src/admin/credentials.rs new file mode 100644 index 000000000..b7cdb1980 --- /dev/null +++ b/backend/crates/providers/xai/src/admin/credentials.rs @@ -0,0 +1,206 @@ +//! 账号资料和凭据准备结果到管理合同的转换 + +use super::error::{map_repository_error, provider_error}; +use crate::credential::{ + GrokAccountProfile, GrokCredentialAdmin, GrokOAuthSecret, PreparedGrokCredentialRotation, + PreparedGrokCredentialRotationGuard, RotateManagedGrokCredential, VerifiedTokenSet, +}; +use crate::transport::XAI_PROVIDER_NAME; +use chrono::{DateTime, Utc}; +use gateway_admin::model::Revision; +use gateway_admin::model::accounts::AccountRecord; +use gateway_admin::model::provider_credentials::{ + CredentialCommitGuard, PreparedCredentialCreate, PreparedCredentialRotation, + PreparedCredentialRotationFacts, ProviderDocument, +}; +use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind}; +use gateway_core::account::{ + CredentialCasUpdateParts, CredentialRevision, LoadedCredential, NewProviderAccount, + OpaqueProviderData, ProviderAccount, ProviderAccountId, +}; +use gateway_core::routing::ProviderKind; +use serde::Deserialize; +use std::time::SystemTime; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct RotationDocument { + pub(super) access_token: String, + pub(super) refresh_token: String, + pub(super) id_token: Option, + pub(super) scope: String, + pub(super) expires_at: DateTime, +} + +struct XaiCredentialCommitGuard { + _guard: PreparedGrokCredentialRotationGuard, +} + +impl CredentialCommitGuard for XaiCredentialCommitGuard { + fn finish(self: Box) {} +} + +pub(super) fn verified_rotation( + current: LoadedCredential, + tokens: VerifiedTokenSet, +) -> Result { + let expires_in = tokens + .expires_in() + .ok_or_else(|| provider_error(ProviderAdminErrorKind::Invalid))?; + let refresh_token = tokens + .refresh_token() + .cloned() + .ok_or_else(|| provider_error(ProviderAdminErrorKind::Invalid))?; + let access_token_expires_at = SystemTime::now() + .checked_add(expires_in) + .ok_or_else(|| provider_error(ProviderAdminErrorKind::Invalid))?; + GrokCredentialAdmin + .prepare_rotation(&RotateManagedGrokCredential { + secret: GrokOAuthSecret { + access_token: tokens.access_token().clone(), + refresh_token, + id_token: tokens.id_token().cloned(), + scope: tokens.scope().to_owned(), + }, + verified_account: GrokAccountProfile { + subject: tokens.evidence().subject().to_owned(), + email: current.account.email().map(str::to_owned), + upstream_account_id: current.account.upstream_account_id().map(str::to_owned), + plan_type: current.account.plan_type().map(str::to_owned), + access_token_expires_at: access_token_expires_at.into(), + refresh_token_expires_at: None, + }, + current, + }) + .map_err(map_repository_error) +} + +pub(super) fn prepared_create( + prepared: NewProviderAccount, + observed_at: DateTime, +) -> Result { + let NewProviderAccount { + account, + model_access, + credential, + } = prepared; + Ok(PreparedCredentialCreate { + model_access, + account_id: account.id().clone(), + provider_kind: account.provider().clone(), + name: account.name().to_owned(), + email: account.email().map(str::to_owned), + upstream_user_id: account.upstream_user_id().map(str::to_owned), + upstream_account_id: account.upstream_account_id().map(str::to_owned), + plan_type: account.plan_type().map(str::to_owned), + authentication_kind: account.authentication_kind().to_owned(), + provider_material: ProviderDocument::new(OpaqueProviderData::new(credential.into_inner())), + has_refresh_token: account.has_refresh_token(), + access_token_expires_at: account.access_token_expires_at().map(DateTime::::from), + next_refresh_at: account.next_refresh_at().map(Into::into), + enabled: account.enabled(), + outbound_proxy: account.outbound_proxy().cloned(), + credential_state: account.credential_state(), + credential_observed_at: observed_at, + }) +} + +pub(super) fn prepared_rotation( + prepared: PreparedGrokCredentialRotation, + provider_kind: ProviderKind, +) -> Result { + let (profile, credential, guard) = prepared.into_parts(); + let CredentialCasUpdateParts { + account_id, + expected_revision, + profile: credential_profile, + preserve_profile, + preserve_access_token_expiry, + credential, + has_refresh_token, + access_token_expires_at, + next_refresh_at, + account_state: _, + } = credential.into_parts(); + if profile != credential_profile || profile.account_id != account_id { + return Err(provider_error(ProviderAdminErrorKind::Internal)); + } + Ok(PreparedCredentialRotation::new( + PreparedCredentialRotationFacts { + account_id, + provider_kind, + expected_credential_revision: Revision::new(expected_revision.get()) + .map_err(|_| provider_error(ProviderAdminErrorKind::Internal))?, + replacement_identity: None, + name: profile.name, + email: profile.email, + plan_type: profile.plan_type, + preserve_profile, + preserve_credential_state: false, + preserve_access_token_expiry, + provider_material: ProviderDocument::new(OpaqueProviderData::new( + credential.into_inner(), + )), + has_refresh_token, + access_token_expires_at: access_token_expires_at.map(DateTime::::from), + next_refresh_at: next_refresh_at.map(Into::into), + }, + Box::new(XaiCredentialCommitGuard { _guard: guard }), + )) +} + +pub(super) fn validate_account_record( + account: &AccountRecord, + provider_kind: &ProviderKind, +) -> Result<(), ProviderAdminError> { + if &account.provider_kind != provider_kind || provider_kind.as_str() != XAI_PROVIDER_NAME { + return Err(provider_error(ProviderAdminErrorKind::Invalid)); + } + ProviderAccountId::new(account.id.clone()) + .map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?; + Ok(()) +} +pub(super) fn account_from_record( + account: &AccountRecord, +) -> Result { + let account_id = ProviderAccountId::new(account.id.clone()) + .map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?; + let revision = CredentialRevision::new(account.credential_revision.get()) + .map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?; + Ok(ProviderAccount::new( + account_id, + account.provider_kind.clone(), + account.name.clone(), + account.upstream_user_id.clone(), + account.authentication_kind.clone(), + revision, + account.access_token_expires_at.map(SystemTime::from), + ) + .with_outbound_proxy(account.outbound_proxy.clone()) + .with_notes(account.notes.clone()) + .with_profile( + account.email.clone(), + account.upstream_account_id.clone(), + account.plan_type.clone(), + ) + .with_account_facts( + account.enabled, + account.credential_state, + account.quota, + account.last_error_reason, + account.last_error_message.clone(), + ) + .with_model_access(account.model_access.clone()) + .with_refresh_schedule( + account.has_refresh_token, + account.next_refresh_at.map(Into::into), + )) +} + +pub(super) fn account_matches_record(account: &ProviderAccount, record: &AccountRecord) -> bool { + account.id().as_str() == record.id + && account.provider() == &record.provider_kind + && account.upstream_user_id() == record.upstream_user_id.as_deref() + && account.upstream_account_id() == record.upstream_account_id.as_deref() + && account.authentication_kind() == record.authentication_kind +} diff --git a/backend/crates/providers/xai/src/admin/error.rs b/backend/crates/providers/xai/src/admin/error.rs new file mode 100644 index 000000000..ff1ee1f72 --- /dev/null +++ b/backend/crates/providers/xai/src/admin/error.rs @@ -0,0 +1,113 @@ +//! Provider 错误到管理合同的唯一映射 + +use crate::credential::{ + FailureClass, GrokCredentialCatalogError, GrokCredentialRefreshError, + GrokCredentialRepositoryError, GrokQuotaError, OAuthError, +}; +use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind}; +use gateway_core::error::StoreErrorKind; +use gateway_core::provider_ports::{ProviderStoreError, ProviderStoreErrorKind}; + +pub(super) fn provider_error(kind: ProviderAdminErrorKind) -> ProviderAdminError { + ProviderAdminError::new(kind) +} +pub(super) fn map_failure_class(class: FailureClass) -> ProviderAdminError { + use ProviderAdminErrorKind as Kind; + let (kind, message) = match class { + FailureClass::Transient => (Kind::Unavailable, "授权服务暂不可用"), + FailureClass::Ambiguous => (Kind::Ambiguous, "授权结果未知,核对账号状态前请勿重试"), + FailureClass::CredentialPermanent => (Kind::Invalid, "凭据被拒绝,请检查账号授权"), + FailureClass::ConfigurationPermanent => (Kind::Invalid, "授权配置无效,请检查客户端配置"), + FailureClass::UserActionRequired => (Kind::Invalid, "请重新授权并确认"), + FailureClass::Security => (Kind::Invalid, "授权校验失败,请核对来源和账号"), + FailureClass::Unsupported => (Kind::Unsupported, "不支持此授权操作"), + }; + provider_error(kind).with_public_message(message) +} + +pub(super) fn map_oauth_error(error: OAuthError) -> ProviderAdminError { + map_failure_class(error.class()) +} + +pub(super) fn map_provider_store_error(error: ProviderStoreError) -> ProviderAdminError { + provider_error(match error.kind() { + ProviderStoreErrorKind::InvalidData => ProviderAdminErrorKind::Invalid, + ProviderStoreErrorKind::Conflict => ProviderAdminErrorKind::Conflict, + ProviderStoreErrorKind::Unavailable => ProviderAdminErrorKind::Unavailable, + }) +} +pub(super) fn map_store_error(error: gateway_core::error::StoreError) -> ProviderAdminError { + provider_error(match error.kind() { + StoreErrorKind::Conflict => ProviderAdminErrorKind::Conflict, + StoreErrorKind::InvalidData | StoreErrorKind::InvalidState => { + ProviderAdminErrorKind::NotFound + } + StoreErrorKind::Unavailable => ProviderAdminErrorKind::Unavailable, + _ => ProviderAdminErrorKind::Internal, + }) + .with_source(error) +} + +pub(super) fn map_repository_error(error: GrokCredentialRepositoryError) -> ProviderAdminError { + use GrokCredentialRepositoryError as Error; + provider_error(match &error { + Error::InvalidInput(_) + | Error::WrongProviderKind + | Error::IdentityRebind + | Error::InvalidCredentialData(_) => ProviderAdminErrorKind::Invalid, + Error::CredentialNotFound => ProviderAdminErrorKind::NotFound, + Error::StaleCredentialRevision(_) | Error::Conflict(_) | Error::RevisionOverflow => { + ProviderAdminErrorKind::Conflict + } + Error::Store(_) => ProviderAdminErrorKind::Unavailable, + }) + .with_source(error) +} + +pub(super) fn map_refresh_error(error: GrokCredentialRefreshError) -> ProviderAdminError { + use crate::GrokRefreshFailure as Failure; + use GrokCredentialRefreshError as Error; + use ProviderAdminErrorKind as Kind; + let (kind, message) = match error { + Error::Repository(error) => return map_repository_error(error), + Error::Lease(error) => return map_provider_store_error(error), + Error::LeaseBusy => (Kind::Conflict, "令牌刷新繁忙,请稍后重试"), + Error::InvalidRefreshResponse => (Kind::Ambiguous, "新凭据无效,核对账号状态前请勿重试"), + Error::Preparation => (Kind::Unavailable, "令牌刷新服务尚未就绪"), + Error::ManualFailure(failure) => match failure { + Failure::Transient => (Kind::Unavailable, "无法连接令牌刷新服务,请检查出站连接"), + Failure::Ambiguous => (Kind::Ambiguous, "刷新结果未知,核对账号状态前请勿重试"), + Failure::InvalidGrant => (Kind::Invalid, "刷新令牌已失效,请重新授权"), + Failure::Banned => (Kind::Invalid, "上游账号已停用"), + Failure::Rejected => (Kind::BadGateway, "令牌刷新失败"), + }, + }; + provider_error(kind).with_public_message(message) +} + +pub(super) fn map_quota_error(error: GrokQuotaError) -> ProviderAdminError { + use GrokQuotaError as Error; + use ProviderAdminErrorKind as Kind; + let (kind, message) = match error { + Error::AccountUnavailable => (Kind::NotFound, "当前账号无法查询额度"), + Error::StaleCredentialSnapshot => (Kind::Conflict, "凭据已更新,请刷新账号列表"), + Error::InvalidData => (Kind::Invalid, "凭据或额度数据无效"), + Error::Upstream => (Kind::Unavailable, "额度查询失败"), + Error::Store => (Kind::Unavailable, "额度查询暂不可用"), + }; + provider_error(kind).with_public_message(message) +} + +pub(super) fn map_catalog_error(error: GrokCredentialCatalogError) -> ProviderAdminError { + use GrokCredentialCatalogError as Error; + use ProviderAdminErrorKind as Kind; + let (kind, message) = match error { + Error::InvalidCredentialData => (Kind::Invalid, "查询模型的凭据无效,请检查账号授权"), + Error::ConflictingModelFacts => (Kind::Invalid, "模型目录不一致,请重新查询"), + Error::NoEligibleCredential => (Kind::NotFound, "没有可查询模型的账号"), + Error::StaleCredentialSnapshot => (Kind::Conflict, "凭据已更新,请刷新账号列表"), + Error::Upstream => (Kind::Unavailable, "模型查询失败"), + Error::Cache | Error::Store => (Kind::Unavailable, "模型查询暂不可用"), + }; + provider_error(kind).with_public_message(message) +} diff --git a/backend/crates/providers/xai/src/admin/mod.rs b/backend/crates/providers/xai/src/admin/mod.rs new file mode 100644 index 000000000..b99a89fae --- /dev/null +++ b/backend/crates/providers/xai/src/admin/mod.rs @@ -0,0 +1,10 @@ +//! xAI 管理边界的模块门面 + +mod credentials; +mod error; +mod pending; +mod profile; +mod provider; +mod quota; + +pub(crate) use provider::{XaiAdminProvider, XaiAdminServices}; diff --git a/backend/crates/providers/xai/src/admin/pending.rs b/backend/crates/providers/xai/src/admin/pending.rs new file mode 100644 index 000000000..0061565b0 --- /dev/null +++ b/backend/crates/providers/xai/src/admin/pending.rs @@ -0,0 +1,215 @@ +//! OAuth pending 的原子存储适配与提交守卫 + +use super::error::{map_oauth_error, map_provider_store_error, provider_error}; +use crate::SecretValue; +use crate::credential::{GrokOAuthConfig, PendingAuthorization}; +use crate::transport::XAI_PROVIDER_NAME; +use async_trait::async_trait; +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use chrono::{DateTime, TimeDelta, Utc}; +use gateway_admin::model::AdminError; +use gateway_admin::model::provider_credentials::{ + AuthorizationCommitGuard, AuthorizationOwner, PendingAuthorizationMutation, +}; +use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind}; +use gateway_core::account::OpaqueProviderData; +use gateway_core::provider_ports::{ + OAuthPendingBinding, OAuthPendingConsumeOutcome, OAuthPendingFlowPort, + OAuthPendingReleaseOutcome, ProviderStoreError, ProviderStoreErrorKind, +}; +use gateway_core::routing::ProviderKind; +use serde::Deserialize; +use serde_json::{Map, Number, Value}; +use sha2::{Digest as _, Sha256}; +use std::sync::Arc; +use std::time::Duration; + +const PENDING_SCHEMA_VERSION: u64 = 3; +pub(super) const PENDING_TTL: TimeDelta = TimeDelta::minutes(30); +pub(super) const PENDING_CLAIM_TTL: Duration = Duration::from_secs(90); +const MAX_PENDING_TEXT_BYTES: usize = 512; + +pub(super) struct ClaimedXaiAuthorization { + pub(super) authorization: StoredXaiAuthorization, + pub(super) owner_ref: String, + pub(super) claim_ref: String, +} + +pub(super) struct XaiAuthorizationCommitGuard { + pending: Arc, + provider_kind: ProviderKind, + flow: OAuthPendingBinding, + owner: OAuthPendingBinding, + claim: OAuthPendingBinding, +} + +impl XaiAuthorizationCommitGuard { + pub(super) fn new( + pending: Arc, + provider_kind: ProviderKind, + flow_id: &str, + owner_ref: &str, + claim_ref: &str, + ) -> Result { + Ok(Self { + pending, + provider_kind, + flow: binding(flow_id)?, + owner: binding(owner_ref)?, + claim: binding(claim_ref)?, + }) + } +} + +#[async_trait] +impl AuthorizationCommitGuard for XaiAuthorizationCommitGuard { + async fn commit(self: Box) -> Result<(), AdminError> { + match self + .pending + .consume_claim(&self.provider_kind, &self.flow, &self.owner, &self.claim) + .await + .map_err(map_pending_claim_settlement_error)? + { + OAuthPendingConsumeOutcome::Consumed => Ok(()), + OAuthPendingConsumeOutcome::NotFound + | OAuthPendingConsumeOutcome::OwnerMismatch + | OAuthPendingConsumeOutcome::ClaimMismatch => { + Err(AdminError::conflict("授权状态已变更,请核对账号状态")) + } + } + } + + async fn abort(self: Box) -> Result<(), AdminError> { + match self + .pending + .release_claim(&self.provider_kind, &self.flow, &self.owner, &self.claim) + .await + .map_err(map_pending_claim_settlement_error)? + { + OAuthPendingReleaseOutcome::Released => Ok(()), + OAuthPendingReleaseOutcome::NotFound + | OAuthPendingReleaseOutcome::OwnerMismatch + | OAuthPendingReleaseOutcome::ClaimMismatch => Err(AdminError::unavailable( + "授权流程未正常结束,请核对账号状态", + )), + } + } +} +pub(super) struct StoredXaiAuthorization { + pub(super) flow_id: String, + pub(super) owner_ref: String, + pub(super) expires_at: DateTime, + pub(super) server_state: String, + pub(super) mutation: PendingAuthorizationMutation, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PendingDocument { + schema_version: u64, + flow_id: String, + owner_ref: String, + expires_at: DateTime, + server_state: String, + mutation: Map, +} + +pub(super) fn encode_pending(pending: &StoredXaiAuthorization) -> Map { + let mut document = Map::new(); + document.insert( + "schema_version".to_owned(), + Value::Number(Number::from(PENDING_SCHEMA_VERSION)), + ); + document.insert("flow_id".to_owned(), Value::String(pending.flow_id.clone())); + document.insert( + "owner_ref".to_owned(), + Value::String(pending.owner_ref.clone()), + ); + document.insert( + "expires_at".to_owned(), + Value::String(pending.expires_at.to_rfc3339()), + ); + document.insert( + "server_state".to_owned(), + Value::String(pending.server_state.clone()), + ); + document.insert( + "mutation".to_owned(), + Value::Object(pending.mutation.to_storage_v1()), + ); + document +} + +pub(super) fn decode_pending( + payload: OpaqueProviderData, + oauth_config: &GrokOAuthConfig, +) -> Result { + let document: PendingDocument = serde_json::from_value(Value::Object(payload.into_inner())) + .map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?; + if document.schema_version != PENDING_SCHEMA_VERSION + || !valid_pending_text(&document.flow_id) + || !valid_pending_text(&document.owner_ref) + || document.expires_at <= Utc::now() + { + return Err(provider_error(ProviderAdminErrorKind::Invalid)); + } + let mutation = PendingAuthorizationMutation::from_storage_v1(Value::Object(document.mutation)) + .map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?; + if mutation.provider_kind().as_str() != XAI_PROVIDER_NAME + || owner_ref(mutation.owner_binding().owner()) != document.owner_ref + { + return Err(provider_error(ProviderAdminErrorKind::Invalid)); + } + PendingAuthorization::from_server_state( + oauth_config, + &SecretValue::new(document.server_state.clone()), + ) + .map_err(map_oauth_error)?; + Ok(StoredXaiAuthorization { + flow_id: document.flow_id, + owner_ref: document.owner_ref, + expires_at: document.expires_at, + server_state: document.server_state, + mutation, + }) +} + +pub(super) fn random_flow_id() -> Result { + let mut random = [0_u8; 32]; + getrandom::fill(&mut random) + .map_err(|_| provider_error(ProviderAdminErrorKind::Unavailable))?; + Ok(URL_SAFE_NO_PAD.encode(random)) +} + +pub(super) fn owner_ref(owner: &AuthorizationOwner) -> String { + let mut digest = Sha256::new(); + match owner { + AuthorizationOwner::AdminSession { admin_user_id } => { + digest.update(b"admin-session\0"); + digest.update(admin_user_id.as_bytes()); + } + AuthorizationOwner::AdminApiKey => digest.update(b"admin-api-key"), + AuthorizationOwner::System => digest.update(b"system"), + } + URL_SAFE_NO_PAD.encode(digest.finalize()) +} + +pub(super) fn binding(value: &str) -> Result { + OAuthPendingBinding::try_new(value.to_owned()).map_err(map_provider_store_error) +} + +fn valid_pending_text(value: &str) -> bool { + !value.is_empty() + && value.len() <= MAX_PENDING_TEXT_BYTES + && !value.chars().any(char::is_control) +} +fn map_pending_claim_settlement_error(error: ProviderStoreError) -> AdminError { + match error.kind() { + ProviderStoreErrorKind::InvalidData => { + AdminError::internal("xAI OAuth pending claim is invalid") + } + ProviderStoreErrorKind::Conflict => AdminError::conflict("授权状态冲突,请核对账号状态"), + ProviderStoreErrorKind::Unavailable => AdminError::unavailable("授权状态存储暂不可用"), + } +} diff --git a/backend/crates/providers/xai/src/admin/profile.rs b/backend/crates/providers/xai/src/admin/profile.rs new file mode 100644 index 000000000..534025c27 --- /dev/null +++ b/backend/crates/providers/xai/src/admin/profile.rs @@ -0,0 +1,34 @@ +//! 客户端版本与账号资料的管理展示投影 + +use crate::profile::GrokCliReleaseSnapshot; +use gateway_admin::model::observability::{DashboardDesktopRelease, DesktopReleaseStatus}; + +pub(super) fn dashboard_cli_release( + profile_version: &str, + snapshot: GrokCliReleaseSnapshot, +) -> DashboardDesktopRelease { + let status = if snapshot.checked_at.is_none() { + DesktopReleaseStatus::Unchecked + } else if snapshot.last_error.is_some() { + DesktopReleaseStatus::Failed + } else if snapshot.latest_version.as_deref() == Some(profile_version) { + DesktopReleaseStatus::Current + } else if snapshot.latest_version.is_some() { + DesktopReleaseStatus::UpdateAvailable + } else { + DesktopReleaseStatus::Failed + }; + DashboardDesktopRelease { + status, + checked_at: snapshot.checked_at, + latest_version: snapshot.latest_version, + latest_build: None, + published_at: None, + minimum_system_version: None, + hardware_requirements: None, + download_url: None, + download_size: None, + signature_present: None, + error: snapshot.last_error, + } +} diff --git a/backend/crates/providers/xai/src/admin.rs b/backend/crates/providers/xai/src/admin/provider.rs similarity index 55% rename from backend/crates/providers/xai/src/admin.rs rename to backend/crates/providers/xai/src/admin/provider.rs index ff35c5372..d4c42b802 100644 --- a/backend/crates/providers/xai/src/admin.rs +++ b/backend/crates/providers/xai/src/admin/provider.rs @@ -1,136 +1,64 @@ -//! xAI 管理边界:Provider preparation 与 Redis OAuth pending 适配 - -use std::collections::BTreeSet; -use std::sync::Arc; -use std::time::{Duration, SystemTime}; +//! 管理端口的唯一实现与 Provider 服务协调 +use super::credentials::{ + RotationDocument, account_from_record, account_matches_record, prepared_create, + prepared_rotation, validate_account_record, verified_rotation, +}; +use super::error::{ + map_catalog_error, map_failure_class, map_oauth_error, map_provider_store_error, + map_quota_error, map_refresh_error, map_repository_error, map_store_error, provider_error, +}; +use super::pending::{ + ClaimedXaiAuthorization, PENDING_CLAIM_TTL, PENDING_TTL, StoredXaiAuthorization, + XaiAuthorizationCommitGuard, binding, decode_pending, encode_pending, owner_ref, + random_flow_id, +}; +use super::profile::dashboard_cli_release; +use super::quota::project_quota; +use crate::billing::grok_billing_breakdown_with_tier; +use crate::credential::{ + GrokCredentialAdmin, GrokCredentialCatalogService, GrokCredentialQuotaService, + GrokCredentialRefreshService, GrokCredentialRepository, GrokOAuthClient, GrokOAuthConfig, + GrokOAuthImportCandidate, GrokOAuthImportDocument, GrokOAuthImportMetadata, + GrokOAuthImportTokens, PendingAuthorization, RedirectUriAllowlist, VerifiedGrokAccount, +}; +use crate::profile::GrokCliReleaseStatus; +use crate::transport::GROK_CLI_BASE_URL; +use crate::{SecretValue, XaiWireProfileState}; use async_trait::async_trait; -use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; -use chrono::{DateTime, TimeDelta, Utc}; +use chrono::Utc; +use gateway_admin::model::MutationContext; use gateway_admin::model::accounts::AccountRecord; use gateway_admin::model::observability::{ - CalculatedBillingBreakdown, CurrencyCost, DashboardDesktopRelease, DashboardWireAttribute, - DashboardWireProfile, DashboardWireTarget, DecimalAmount, DesktopReleaseStatus, - ProviderBillingInput, + CalculatedBillingBreakdown, CurrencyCost, DashboardWireAttribute, DashboardWireProfile, + DashboardWireTarget, DecimalAmount, ProviderBillingInput, }; use gateway_admin::model::provider_credentials::{ - AuthorizationCommitGuard, AuthorizationMutationTarget, AuthorizationOwner, - AuthorizationOwnerBinding, AuthorizationStarted, CompleteAuthorization, CredentialCommitGuard, - PendingAuthorizationMutation, PrepareCredentialImport, PrepareCredentialRefresh, - PrepareCredentialRotation, PreparedAuthorizationCommit, PreparedAuthorizationCredential, - PreparedCredentialCreate, PreparedCredentialImport, PreparedCredentialRotation, - PreparedCredentialRotationFacts, ProviderDocument, ProviderExport, - ProviderExportCredentialInput, ProviderModel, ProviderModels, ProviderQuota, - ProviderQuotaRequest, ProviderQuotaWindow, QuotaLocalUsageAttribution, + AuthorizationMutationTarget, AuthorizationOwnerBinding, AuthorizationStarted, + CompleteAuthorization, PendingAuthorizationMutation, PrepareCredentialImport, + PrepareCredentialRefresh, PrepareCredentialRotation, PreparedAuthorizationCommit, + PreparedAuthorizationCredential, PreparedCredentialImport, PreparedCredentialRotation, + ProviderDocument, ProviderExport, ProviderExportCredentialInput, ProviderModel, ProviderModels, + ProviderQuota, ProviderQuotaRequest, }; -use gateway_admin::model::{AdminError, MutationContext, Revision}; use gateway_admin::ports::provider::{ProviderAdmin, ProviderAdminError, ProviderAdminErrorKind}; use gateway_core::account::{ - CredentialCasUpdateParts, CredentialRevision, LoadedCredential, NewProviderAccount, - OpaqueProviderData, PlaintextCredential, ProviderAccount, ProviderAccountId, - ProviderAccountStore, + LoadedCredential, NewProviderAccount, OpaqueProviderData, PlaintextCredential, ProviderAccount, + ProviderAccountId, ProviderAccountStore, }; -use gateway_core::error::StoreErrorKind; use gateway_core::metering::Money; use gateway_core::operation::{GenerateRequest, Operation, ProtocolPayload}; use gateway_core::provider_ports::{ - NewOAuthPendingFlow, OAuthPendingBinding, OAuthPendingClaimOutcome, OAuthPendingConsumeOutcome, - OAuthPendingFlowPort, OAuthPendingPutOutcome, OAuthPendingReleaseOutcome, ProviderCooldownPort, - ProviderStoreError, ProviderStoreErrorKind, + NewOAuthPendingFlow, OAuthPendingClaimOutcome, OAuthPendingFlowPort, OAuthPendingPutOutcome, + OAuthPendingReleaseOutcome, ProviderCooldownPort, }; use gateway_core::routing::{ProviderKind, UpstreamModelId}; use gateway_protocol::openai::OPENAI_PROTOCOL; -use serde::Deserialize; -use serde_json::{Map, Number, Value}; -use sha2::{Digest as _, Sha256}; +use serde_json::{Map, Value}; +use std::collections::BTreeSet; +use std::sync::Arc; use uuid::Uuid; -use crate::credential::{ - FailureClass, GrokAccountProfile, GrokCredentialAdmin, GrokCredentialCatalogError, - GrokCredentialCatalogService, GrokCredentialQuotaService, GrokCredentialRefreshError, - GrokCredentialRefreshService, GrokCredentialRepository, GrokCredentialRepositoryError, - GrokOAuthClient, GrokOAuthConfig, GrokOAuthImportCandidate, GrokOAuthImportDocument, - GrokOAuthImportMetadata, GrokOAuthImportTokens, GrokOAuthSecret, GrokQuotaError, - GrokQuotaPeriodKind, GrokQuotaSnapshot, OAuthError, PendingAuthorization, - PreparedGrokCredentialRotation, PreparedGrokCredentialRotationGuard, RedirectUriAllowlist, - RotateManagedGrokCredential, VerifiedGrokAccount, VerifiedTokenSet, -}; -use crate::transport::profile::{GrokCliReleaseSnapshot, GrokCliReleaseStatus}; -use crate::transport::{GROK_CLI_BASE_URL, XAI_PROVIDER_NAME, grok_billing_breakdown_with_tier}; -use crate::{SecretValue, XaiWireProfileState}; - -const PENDING_SCHEMA_VERSION: u64 = 3; -const PENDING_TTL: TimeDelta = TimeDelta::minutes(30); -const PENDING_CLAIM_TTL: Duration = Duration::from_secs(90); -const MAX_PENDING_TEXT_BYTES: usize = 512; - -struct ClaimedXaiAuthorization { - authorization: StoredXaiAuthorization, - owner_ref: String, - claim_ref: String, -} - -struct XaiAuthorizationCommitGuard { - pending: Arc, - provider_kind: ProviderKind, - flow: OAuthPendingBinding, - owner: OAuthPendingBinding, - claim: OAuthPendingBinding, -} - -impl XaiAuthorizationCommitGuard { - fn new( - pending: Arc, - provider_kind: ProviderKind, - flow_id: &str, - owner_ref: &str, - claim_ref: &str, - ) -> Result { - Ok(Self { - pending, - provider_kind, - flow: binding(flow_id)?, - owner: binding(owner_ref)?, - claim: binding(claim_ref)?, - }) - } -} - -#[async_trait] -impl AuthorizationCommitGuard for XaiAuthorizationCommitGuard { - async fn commit(self: Box) -> Result<(), AdminError> { - match self - .pending - .consume_claim(&self.provider_kind, &self.flow, &self.owner, &self.claim) - .await - .map_err(map_pending_claim_settlement_error)? - { - OAuthPendingConsumeOutcome::Consumed => Ok(()), - OAuthPendingConsumeOutcome::NotFound - | OAuthPendingConsumeOutcome::OwnerMismatch - | OAuthPendingConsumeOutcome::ClaimMismatch => { - Err(AdminError::conflict("授权状态已变更,请核对账号状态")) - } - } - } - - async fn abort(self: Box) -> Result<(), AdminError> { - match self - .pending - .release_claim(&self.provider_kind, &self.flow, &self.owner, &self.claim) - .await - .map_err(map_pending_claim_settlement_error)? - { - OAuthPendingReleaseOutcome::Released => Ok(()), - OAuthPendingReleaseOutcome::NotFound - | OAuthPendingReleaseOutcome::OwnerMismatch - | OAuthPendingReleaseOutcome::ClaimMismatch => Err(AdminError::unavailable( - "授权流程未正常结束,请核对账号状态", - )), - } - } -} - pub(crate) struct XaiAdminProvider { provider_kind: ProviderKind, wire_profile: XaiWireProfileState, @@ -339,6 +267,9 @@ impl ProviderAdmin for XaiAdminProvider { ) -> gateway_admin::model::accounts::ProviderAccountCapabilities { let oauth = authentication_kind == crate::credential::XAI_AUTHENTICATION_KIND_OAUTH; gateway_admin::model::accounts::ProviderAccountCapabilities { + credential_refresh: oauth, + reauthorize: oauth, + credential_export: oauth, quota: oauth, quota_refresh: oauth, ..Default::default() @@ -348,8 +279,8 @@ impl ProviderAdmin for XaiAdminProvider { fn client_profile_options( &self, ) -> Result { - crate::transport::client_profile::object(&serde_json::json!({ - "defaults": crate::transport::client_profile::GrokClientProfileSelection::default(), + crate::profile::selection::object(&serde_json::json!({ + "defaults": crate::profile::selection::GrokClientProfileSelection::default(), })) .map_err(|_| ProviderAdminError::new(ProviderAdminErrorKind::Invalid)) } @@ -358,7 +289,7 @@ impl ProviderAdmin for XaiAdminProvider { &self, configuration: &gateway_core::account::OpaqueProviderData, ) -> Result { - crate::transport::client_profile::GrokClientProfileSelection::parse(configuration) + crate::profile::selection::GrokClientProfileSelection::parse(configuration) .and_then(|selection| { selection.preview(&self.wire_profile, &self.cli_release.snapshot()) }) @@ -369,7 +300,7 @@ impl ProviderAdmin for XaiAdminProvider { &self, configuration: &gateway_core::account::OpaqueProviderData, ) -> Option { - use crate::transport::client_profile::{GrokClientProfileSelection, VersionMode}; + use crate::profile::selection::{GrokClientProfileSelection, VersionMode}; let selection = GrokClientProfileSelection::parse(configuration).ok()?; let profile = selection.resolve(&self.wire_profile).ok()?; let mut view = self.dashboard_wire_profile()?; @@ -399,8 +330,12 @@ impl ProviderAdmin for XaiAdminProvider { Some(view) } + fn supported_pricing_bands(&self) -> &'static [&'static str] { + crate::billing::SUPPORTED_PRICING_BANDS + } + fn pricing_catalog(&self) -> gateway_admin::model::pricing::ProviderPricingCatalog { - crate::transport::canonical::pricing_catalog() + crate::billing::pricing_catalog() } fn provider_kind(&self) -> &ProviderKind { &self.provider_kind @@ -516,17 +451,15 @@ impl ProviderAdmin for XaiAdminProvider { if input.usage.image_input_tokens != Some(0) || input.usage.image_output_tokens != Some(0) { return Ok(None); } - Ok( - crate::transport::canonical::grok_billing_breakdown_with_override( - &input.upstream_model_id, - input_tokens, - output_tokens, - cached, - written, - input.service_tier.as_deref(), - pricing, - ), - ) + Ok(crate::billing::grok_billing_breakdown_with_override( + &input.upstream_model_id, + input_tokens, + output_tokens, + cached, + written, + input.service_tier.as_deref(), + pricing, + )) } async fn prepare_import( @@ -977,457 +910,6 @@ impl XaiAdminProvider { } } -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct RotationDocument { - access_token: String, - refresh_token: String, - id_token: Option, - scope: String, - expires_at: DateTime, -} - -struct XaiCredentialCommitGuard { - _guard: PreparedGrokCredentialRotationGuard, -} - -impl CredentialCommitGuard for XaiCredentialCommitGuard { - fn finish(self: Box) {} -} - -fn verified_rotation( - current: LoadedCredential, - tokens: VerifiedTokenSet, -) -> Result { - let expires_in = tokens - .expires_in() - .ok_or_else(|| provider_error(ProviderAdminErrorKind::Invalid))?; - let refresh_token = tokens - .refresh_token() - .cloned() - .ok_or_else(|| provider_error(ProviderAdminErrorKind::Invalid))?; - let access_token_expires_at = SystemTime::now() - .checked_add(expires_in) - .ok_or_else(|| provider_error(ProviderAdminErrorKind::Invalid))?; - GrokCredentialAdmin - .prepare_rotation(&RotateManagedGrokCredential { - secret: GrokOAuthSecret { - access_token: tokens.access_token().clone(), - refresh_token, - id_token: tokens.id_token().cloned(), - scope: tokens.scope().to_owned(), - }, - verified_account: GrokAccountProfile { - subject: tokens.evidence().subject().to_owned(), - email: current.account.email().map(str::to_owned), - upstream_account_id: current.account.upstream_account_id().map(str::to_owned), - plan_type: current.account.plan_type().map(str::to_owned), - access_token_expires_at: access_token_expires_at.into(), - refresh_token_expires_at: None, - }, - current, - }) - .map_err(map_repository_error) -} - -fn prepared_create( - prepared: NewProviderAccount, - observed_at: DateTime, -) -> Result { - let NewProviderAccount { - account, - model_access, - credential, - } = prepared; - Ok(PreparedCredentialCreate { - model_access, - account_id: account.id().clone(), - provider_kind: account.provider().clone(), - name: account.name().to_owned(), - email: account.email().map(str::to_owned), - upstream_user_id: account.upstream_user_id().map(str::to_owned), - upstream_account_id: account.upstream_account_id().map(str::to_owned), - plan_type: account.plan_type().map(str::to_owned), - authentication_kind: account.authentication_kind().to_owned(), - provider_material: ProviderDocument::new(OpaqueProviderData::new(credential.into_inner())), - has_refresh_token: account.has_refresh_token(), - access_token_expires_at: account.access_token_expires_at().map(DateTime::::from), - next_refresh_at: account.next_refresh_at().map(Into::into), - enabled: account.enabled(), - outbound_proxy: account.outbound_proxy().cloned(), - credential_state: account.credential_state(), - credential_observed_at: observed_at, - }) -} - -fn prepared_rotation( - prepared: PreparedGrokCredentialRotation, - provider_kind: ProviderKind, -) -> Result { - let (profile, credential, guard) = prepared.into_parts(); - let CredentialCasUpdateParts { - account_id, - expected_revision, - profile: credential_profile, - preserve_profile, - preserve_access_token_expiry, - credential, - has_refresh_token, - access_token_expires_at, - next_refresh_at, - account_state: _, - } = credential.into_parts(); - if profile != credential_profile || profile.account_id != account_id { - return Err(provider_error(ProviderAdminErrorKind::Internal)); - } - Ok(PreparedCredentialRotation::new( - PreparedCredentialRotationFacts { - account_id, - provider_kind, - expected_credential_revision: Revision::new(expected_revision.get()) - .map_err(|_| provider_error(ProviderAdminErrorKind::Internal))?, - replacement_identity: None, - name: profile.name, - email: profile.email, - plan_type: profile.plan_type, - preserve_profile, - preserve_credential_state: false, - preserve_access_token_expiry, - provider_material: ProviderDocument::new(OpaqueProviderData::new( - credential.into_inner(), - )), - has_refresh_token, - access_token_expires_at: access_token_expires_at.map(DateTime::::from), - next_refresh_at: next_refresh_at.map(Into::into), - }, - Box::new(XaiCredentialCommitGuard { _guard: guard }), - )) -} - -fn validate_account_record( - account: &AccountRecord, - provider_kind: &ProviderKind, -) -> Result<(), ProviderAdminError> { - if &account.provider_kind != provider_kind || provider_kind.as_str() != XAI_PROVIDER_NAME { - return Err(provider_error(ProviderAdminErrorKind::Invalid)); - } - ProviderAccountId::new(account.id.clone()) - .map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?; - Ok(()) -} - -fn dashboard_cli_release( - profile_version: &str, - snapshot: GrokCliReleaseSnapshot, -) -> DashboardDesktopRelease { - let status = if snapshot.checked_at.is_none() { - DesktopReleaseStatus::Unchecked - } else if snapshot.last_error.is_some() { - DesktopReleaseStatus::Failed - } else if snapshot.latest_version.as_deref() == Some(profile_version) { - DesktopReleaseStatus::Current - } else if snapshot.latest_version.is_some() { - DesktopReleaseStatus::UpdateAvailable - } else { - DesktopReleaseStatus::Failed - }; - DashboardDesktopRelease { - status, - checked_at: snapshot.checked_at, - latest_version: snapshot.latest_version, - latest_build: None, - published_at: None, - minimum_system_version: None, - hardware_requirements: None, - download_url: None, - download_size: None, - signature_present: None, - error: snapshot.last_error, - } -} - -fn account_from_record(account: &AccountRecord) -> Result { - let account_id = ProviderAccountId::new(account.id.clone()) - .map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?; - let revision = CredentialRevision::new(account.credential_revision.get()) - .map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?; - Ok(ProviderAccount::new( - account_id, - account.provider_kind.clone(), - account.name.clone(), - account.upstream_user_id.clone(), - account.authentication_kind.clone(), - revision, - account.access_token_expires_at.map(SystemTime::from), - ) - .with_outbound_proxy(account.outbound_proxy.clone()) - .with_notes(account.notes.clone()) - .with_profile( - account.email.clone(), - account.upstream_account_id.clone(), - account.plan_type.clone(), - ) - .with_account_facts( - account.enabled, - account.credential_state, - account.quota, - account.last_error_reason, - account.last_error_message.clone(), - ) - .with_model_access(account.model_access.clone()) - .with_refresh_schedule( - account.has_refresh_token, - account.next_refresh_at.map(Into::into), - )) -} - -fn account_matches_record(account: &ProviderAccount, record: &AccountRecord) -> bool { - account.id().as_str() == record.id - && account.provider() == &record.provider_kind - && account.upstream_user_id() == record.upstream_user_id.as_deref() - && account.upstream_account_id() == record.upstream_account_id.as_deref() - && account.authentication_kind() == record.authentication_kind -} - -fn project_quota( - snapshot: Option, - quota_exhausted: bool, - refresh_token_expires_at: Option>, - rolling_usage: Option, -) -> ProviderQuota { - let billing = snapshot.as_ref().map(GrokQuotaSnapshot::billing); - let window = if let Some(billing) = billing.filter(|billing| billing.has_authoritative_quota()) - { - let period_kind = billing.period_kind(); - let window_seconds = quota_window_seconds(billing.period_start(), billing.period_end()); - let mut data = Map::new(); - data.insert( - "periodStart".to_owned(), - billing - .period_start() - .map_or(Value::Null, |value| Value::String(value.to_owned())), - ); - data.insert( - "periodEnd".to_owned(), - billing - .period_end() - .map_or(Value::Null, |value| Value::String(value.to_owned())), - ); - for (key, value) in [ - ("onDemandCapCents", billing.on_demand_cap_cents()), - ("onDemandUsedCents", billing.on_demand_used_cents()), - ("prepaidBalanceCents", billing.prepaid_balance_cents()), - ] { - data.insert( - key.to_owned(), - value.map_or(Value::Null, |value| Value::Number(Number::from(value))), - ); - } - ProviderQuotaWindow { - upstream: None, - key: billing.period_type().unwrap_or("billing").to_owned(), - group: quota_group(period_kind).to_owned(), - label: xai_quota_window_label(period_kind, window_seconds), - limit_id: None, - limit_name: None, - role: None, - local_usage_attribution: QuotaLocalUsageAttribution::AccountWide, - window_seconds, - used_percent: billing.used_percent(), - reset_at: billing.period_end().and_then(parse_utc), - limit_reached: billing - .used_percent() - .is_some_and(|used| used.is_finite() && used >= 100.0), - local_usage: None, - provider_data: Some(ProviderDocument::new(OpaqueProviderData::new(data))), - } - } else { - // 本地滚动统计独立于上游额度观察,导入后尚无快照时也保留请求图与日用量 - ProviderQuotaWindow { - upstream: None, - key: "free-rolling-24h".to_owned(), - group: "shortTerm".to_owned(), - label: "日限额".to_owned(), - limit_id: None, - limit_name: None, - role: None, - local_usage_attribution: QuotaLocalUsageAttribution::AccountWide, - window_seconds: Some(crate::GROK_FREE_ROLLING_WINDOW_SECONDS), - used_percent: None, - reset_at: None, - limit_reached: false, - local_usage: rolling_usage, - provider_data: None, - } - }; - ProviderQuota { - paused_windows: Vec::new(), - upstream: None, - credits: None, - plan_type: billing - .and_then(|billing| billing.plan_type()) - .map(str::to_owned), - observed_at: snapshot.as_ref().map(GrokQuotaSnapshot::observed_at), - refresh_token_expires_at, - windows: vec![window], - limit_reached: quota_exhausted, - provider_data: None, - } -} - -const fn quota_group(kind: GrokQuotaPeriodKind) -> &'static str { - match kind { - GrokQuotaPeriodKind::Weekly => "shortTerm", - GrokQuotaPeriodKind::Monthly => "monthly", - GrokQuotaPeriodKind::Other => "other", - } -} - -fn xai_quota_window_label(kind: GrokQuotaPeriodKind, window_seconds: Option) -> String { - match kind { - GrokQuotaPeriodKind::Weekly => "周限额".to_owned(), - GrokQuotaPeriodKind::Monthly => "月限额".to_owned(), - GrokQuotaPeriodKind::Other => custom_quota_window_label(window_seconds), - } -} - -fn custom_quota_window_label(window_seconds: Option) -> String { - let Some(seconds) = window_seconds.filter(|seconds| *seconds > 0) else { - return "额度".to_owned(); - }; - if seconds % 86_400 == 0 { - format!("{}日限额", seconds / 86_400) - } else if seconds % 3_600 == 0 { - format!("{}小时限额", seconds / 3_600) - } else { - format!("{}分钟限额", seconds.div_ceil(60)) - } -} - -fn quota_window_seconds(start: Option<&str>, end: Option<&str>) -> Option { - let start = start.and_then(parse_utc)?; - let end = end.and_then(parse_utc)?; - end.signed_duration_since(start) - .num_seconds() - .try_into() - .ok() -} - -fn parse_utc(value: &str) -> Option> { - DateTime::parse_from_rfc3339(value) - .ok() - .map(|value| value.with_timezone(&Utc)) -} - -struct StoredXaiAuthorization { - flow_id: String, - owner_ref: String, - expires_at: DateTime, - server_state: String, - mutation: PendingAuthorizationMutation, -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct PendingDocument { - schema_version: u64, - flow_id: String, - owner_ref: String, - expires_at: DateTime, - server_state: String, - mutation: Map, -} - -fn encode_pending(pending: &StoredXaiAuthorization) -> Map { - let mut document = Map::new(); - document.insert( - "schema_version".to_owned(), - Value::Number(Number::from(PENDING_SCHEMA_VERSION)), - ); - document.insert("flow_id".to_owned(), Value::String(pending.flow_id.clone())); - document.insert( - "owner_ref".to_owned(), - Value::String(pending.owner_ref.clone()), - ); - document.insert( - "expires_at".to_owned(), - Value::String(pending.expires_at.to_rfc3339()), - ); - document.insert( - "server_state".to_owned(), - Value::String(pending.server_state.clone()), - ); - document.insert( - "mutation".to_owned(), - Value::Object(pending.mutation.to_storage_v1()), - ); - document -} - -fn decode_pending( - payload: OpaqueProviderData, - oauth_config: &GrokOAuthConfig, -) -> Result { - let document: PendingDocument = serde_json::from_value(Value::Object(payload.into_inner())) - .map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?; - if document.schema_version != PENDING_SCHEMA_VERSION - || !valid_pending_text(&document.flow_id) - || !valid_pending_text(&document.owner_ref) - || document.expires_at <= Utc::now() - { - return Err(provider_error(ProviderAdminErrorKind::Invalid)); - } - let mutation = PendingAuthorizationMutation::from_storage_v1(Value::Object(document.mutation)) - .map_err(|_| provider_error(ProviderAdminErrorKind::Invalid))?; - if mutation.provider_kind().as_str() != XAI_PROVIDER_NAME - || owner_ref(mutation.owner_binding().owner()) != document.owner_ref - { - return Err(provider_error(ProviderAdminErrorKind::Invalid)); - } - PendingAuthorization::from_server_state( - oauth_config, - &SecretValue::new(document.server_state.clone()), - ) - .map_err(map_oauth_error)?; - Ok(StoredXaiAuthorization { - flow_id: document.flow_id, - owner_ref: document.owner_ref, - expires_at: document.expires_at, - server_state: document.server_state, - mutation, - }) -} - -fn random_flow_id() -> Result { - let mut random = [0_u8; 32]; - getrandom::fill(&mut random) - .map_err(|_| provider_error(ProviderAdminErrorKind::Unavailable))?; - Ok(URL_SAFE_NO_PAD.encode(random)) -} - -fn owner_ref(owner: &AuthorizationOwner) -> String { - let mut digest = Sha256::new(); - match owner { - AuthorizationOwner::AdminSession { admin_user_id } => { - digest.update(b"admin-session\0"); - digest.update(admin_user_id.as_bytes()); - } - AuthorizationOwner::AdminApiKey => digest.update(b"admin-api-key"), - AuthorizationOwner::System => digest.update(b"system"), - } - URL_SAFE_NO_PAD.encode(digest.finalize()) -} - -fn binding(value: &str) -> Result { - OAuthPendingBinding::try_new(value.to_owned()).map_err(map_provider_store_error) -} - -fn valid_pending_text(value: &str) -> bool { - !value.is_empty() - && value.len() <= MAX_PENDING_TEXT_BYTES - && !value.chars().any(char::is_control) -} - fn currency_cost(money: Money) -> Result { Ok(CurrencyCost { currency: money.currency().as_str().to_owned(), @@ -1438,11 +920,6 @@ fn currency_cost(money: Money) -> Result { .map_err(|_| provider_error(ProviderAdminErrorKind::Internal))?, }) } - -fn provider_error(kind: ProviderAdminErrorKind) -> ProviderAdminError { - ProviderAdminError::new(kind) -} - fn build_connection_test_operation( upstream_model: &UpstreamModelId, input_text: &str, @@ -1468,115 +945,3 @@ fn build_connection_test_operation( payload, ))) } - -fn map_failure_class(class: FailureClass) -> ProviderAdminError { - use ProviderAdminErrorKind as Kind; - let (kind, message) = match class { - FailureClass::Transient => (Kind::Unavailable, "授权服务暂不可用"), - FailureClass::Ambiguous => (Kind::Ambiguous, "授权结果未知,核对账号状态前请勿重试"), - FailureClass::CredentialPermanent => (Kind::Invalid, "凭据被拒绝,请检查账号授权"), - FailureClass::ConfigurationPermanent => (Kind::Invalid, "授权配置无效,请检查客户端配置"), - FailureClass::UserActionRequired => (Kind::Invalid, "请重新授权并确认"), - FailureClass::Security => (Kind::Invalid, "授权校验失败,请核对来源和账号"), - FailureClass::Unsupported => (Kind::Unsupported, "不支持此授权操作"), - }; - provider_error(kind).with_public_message(message) -} - -fn map_oauth_error(error: OAuthError) -> ProviderAdminError { - map_failure_class(error.class()) -} - -fn map_provider_store_error(error: ProviderStoreError) -> ProviderAdminError { - provider_error(match error.kind() { - ProviderStoreErrorKind::InvalidData => ProviderAdminErrorKind::Invalid, - ProviderStoreErrorKind::Conflict => ProviderAdminErrorKind::Conflict, - ProviderStoreErrorKind::Unavailable => ProviderAdminErrorKind::Unavailable, - }) -} - -fn map_pending_claim_settlement_error(error: ProviderStoreError) -> AdminError { - match error.kind() { - ProviderStoreErrorKind::InvalidData => { - AdminError::internal("xAI OAuth pending claim is invalid") - } - ProviderStoreErrorKind::Conflict => AdminError::conflict("授权状态冲突,请核对账号状态"), - ProviderStoreErrorKind::Unavailable => AdminError::unavailable("授权状态存储暂不可用"), - } -} - -fn map_store_error(error: gateway_core::error::StoreError) -> ProviderAdminError { - provider_error(match error.kind() { - StoreErrorKind::Conflict => ProviderAdminErrorKind::Conflict, - StoreErrorKind::InvalidData | StoreErrorKind::InvalidState => { - ProviderAdminErrorKind::NotFound - } - StoreErrorKind::Unavailable => ProviderAdminErrorKind::Unavailable, - _ => ProviderAdminErrorKind::Internal, - }) - .with_source(error) -} - -fn map_repository_error(error: GrokCredentialRepositoryError) -> ProviderAdminError { - use GrokCredentialRepositoryError as Error; - provider_error(match &error { - Error::InvalidInput(_) - | Error::WrongProviderKind - | Error::IdentityRebind - | Error::InvalidCredentialData(_) => ProviderAdminErrorKind::Invalid, - Error::CredentialNotFound => ProviderAdminErrorKind::NotFound, - Error::StaleCredentialRevision(_) | Error::Conflict(_) | Error::RevisionOverflow => { - ProviderAdminErrorKind::Conflict - } - Error::Store(_) => ProviderAdminErrorKind::Unavailable, - }) - .with_source(error) -} - -fn map_refresh_error(error: GrokCredentialRefreshError) -> ProviderAdminError { - use crate::GrokRefreshFailure as Failure; - use GrokCredentialRefreshError as Error; - use ProviderAdminErrorKind as Kind; - let (kind, message) = match error { - Error::Repository(error) => return map_repository_error(error), - Error::Lease(error) => return map_provider_store_error(error), - Error::LeaseBusy => (Kind::Conflict, "令牌刷新繁忙,请稍后重试"), - Error::InvalidRefreshResponse => (Kind::Ambiguous, "新凭据无效,核对账号状态前请勿重试"), - Error::Preparation => (Kind::Unavailable, "令牌刷新服务尚未就绪"), - Error::ManualFailure(failure) => match failure { - Failure::Transient => (Kind::Unavailable, "无法连接令牌刷新服务,请检查出站连接"), - Failure::Ambiguous => (Kind::Ambiguous, "刷新结果未知,核对账号状态前请勿重试"), - Failure::InvalidGrant => (Kind::Invalid, "刷新令牌已失效,请重新授权"), - Failure::Banned => (Kind::Invalid, "上游账号已停用"), - Failure::Rejected => (Kind::BadGateway, "令牌刷新失败"), - }, - }; - provider_error(kind).with_public_message(message) -} - -fn map_quota_error(error: GrokQuotaError) -> ProviderAdminError { - use GrokQuotaError as Error; - use ProviderAdminErrorKind as Kind; - let (kind, message) = match error { - Error::AccountUnavailable => (Kind::NotFound, "当前账号无法查询额度"), - Error::StaleCredentialSnapshot => (Kind::Conflict, "凭据已更新,请刷新账号列表"), - Error::InvalidData => (Kind::Invalid, "凭据或额度数据无效"), - Error::Upstream => (Kind::Unavailable, "额度查询失败"), - Error::Store => (Kind::Unavailable, "额度查询暂不可用"), - }; - provider_error(kind).with_public_message(message) -} - -fn map_catalog_error(error: GrokCredentialCatalogError) -> ProviderAdminError { - use GrokCredentialCatalogError as Error; - use ProviderAdminErrorKind as Kind; - let (kind, message) = match error { - Error::InvalidCredentialData => (Kind::Invalid, "查询模型的凭据无效,请检查账号授权"), - Error::ConflictingModelFacts => (Kind::Invalid, "模型目录不一致,请重新查询"), - Error::NoEligibleCredential => (Kind::NotFound, "没有可查询模型的账号"), - Error::StaleCredentialSnapshot => (Kind::Conflict, "凭据已更新,请刷新账号列表"), - Error::Upstream => (Kind::Unavailable, "模型查询失败"), - Error::Cache | Error::Store => (Kind::Unavailable, "模型查询暂不可用"), - }; - provider_error(kind).with_public_message(message) -} diff --git a/backend/crates/providers/xai/src/admin/quota.rs b/backend/crates/providers/xai/src/admin/quota.rs new file mode 100644 index 000000000..8e22f917b --- /dev/null +++ b/backend/crates/providers/xai/src/admin/quota.rs @@ -0,0 +1,139 @@ +//! 将 xAI 额度观测与本地滚动用量投影到管理合同 + +use crate::credential::{GrokQuotaPeriodKind, GrokQuotaSnapshot}; +use chrono::{DateTime, Utc}; +use gateway_admin::model::provider_credentials::{ + ProviderDocument, ProviderQuota, ProviderQuotaWindow, QuotaLocalUsageAttribution, +}; +use gateway_core::account::OpaqueProviderData; +use serde_json::{Map, Number, Value}; + +pub(super) fn project_quota( + snapshot: Option, + quota_exhausted: bool, + refresh_token_expires_at: Option>, + rolling_usage: Option, +) -> ProviderQuota { + let billing = snapshot.as_ref().map(GrokQuotaSnapshot::billing); + let window = if let Some(billing) = billing.filter(|billing| billing.has_authoritative_quota()) + { + let period_kind = billing.period_kind(); + let window_seconds = quota_window_seconds(billing.period_start(), billing.period_end()); + let mut data = Map::new(); + data.insert( + "periodStart".to_owned(), + billing + .period_start() + .map_or(Value::Null, |value| Value::String(value.to_owned())), + ); + data.insert( + "periodEnd".to_owned(), + billing + .period_end() + .map_or(Value::Null, |value| Value::String(value.to_owned())), + ); + for (key, value) in [ + ("onDemandCapCents", billing.on_demand_cap_cents()), + ("onDemandUsedCents", billing.on_demand_used_cents()), + ("prepaidBalanceCents", billing.prepaid_balance_cents()), + ] { + data.insert( + key.to_owned(), + value.map_or(Value::Null, |value| Value::Number(Number::from(value))), + ); + } + ProviderQuotaWindow { + upstream: None, + key: billing.period_type().unwrap_or("billing").to_owned(), + group: quota_group(period_kind).to_owned(), + label: xai_quota_window_label(period_kind, window_seconds), + limit_id: None, + limit_name: None, + role: None, + local_usage_attribution: QuotaLocalUsageAttribution::AccountWide, + window_seconds, + used_percent: billing.used_percent(), + reset_at: billing.period_end().and_then(parse_utc), + limit_reached: billing + .used_percent() + .is_some_and(|used| used.is_finite() && used >= 100.0), + local_usage: None, + provider_data: Some(ProviderDocument::new(OpaqueProviderData::new(data))), + } + } else { + // 本地滚动统计独立于上游额度观察,导入后尚无快照时也保留请求图与日用量 + ProviderQuotaWindow { + upstream: None, + key: "free-rolling-24h".to_owned(), + group: "shortTerm".to_owned(), + label: "日限额".to_owned(), + limit_id: None, + limit_name: None, + role: None, + local_usage_attribution: QuotaLocalUsageAttribution::AccountWide, + window_seconds: Some(crate::GROK_FREE_ROLLING_WINDOW_SECONDS), + used_percent: None, + reset_at: None, + limit_reached: false, + local_usage: rolling_usage, + provider_data: None, + } + }; + ProviderQuota { + paused_windows: Vec::new(), + upstream: None, + credits: None, + plan_type: billing + .and_then(|billing| billing.plan_type()) + .map(str::to_owned), + observed_at: snapshot.as_ref().map(GrokQuotaSnapshot::observed_at), + refresh_token_expires_at, + windows: vec![window], + limit_reached: quota_exhausted, + provider_data: None, + } +} + +const fn quota_group(kind: GrokQuotaPeriodKind) -> &'static str { + match kind { + GrokQuotaPeriodKind::Weekly => "shortTerm", + GrokQuotaPeriodKind::Monthly => "monthly", + GrokQuotaPeriodKind::Other => "other", + } +} + +fn xai_quota_window_label(kind: GrokQuotaPeriodKind, window_seconds: Option) -> String { + match kind { + GrokQuotaPeriodKind::Weekly => "周限额".to_owned(), + GrokQuotaPeriodKind::Monthly => "月限额".to_owned(), + GrokQuotaPeriodKind::Other => custom_quota_window_label(window_seconds), + } +} + +fn custom_quota_window_label(window_seconds: Option) -> String { + let Some(seconds) = window_seconds.filter(|seconds| *seconds > 0) else { + return "额度".to_owned(); + }; + if seconds % 86_400 == 0 { + format!("{}日限额", seconds / 86_400) + } else if seconds % 3_600 == 0 { + format!("{}小时限额", seconds / 3_600) + } else { + format!("{}分钟限额", seconds.div_ceil(60)) + } +} + +fn quota_window_seconds(start: Option<&str>, end: Option<&str>) -> Option { + let start = start.and_then(parse_utc)?; + let end = end.and_then(parse_utc)?; + end.signed_duration_since(start) + .num_seconds() + .try_into() + .ok() +} + +fn parse_utc(value: &str) -> Option> { + DateTime::parse_from_rfc3339(value) + .ok() + .map(|value| value.with_timezone(&Utc)) +} diff --git a/backend/crates/providers/xai/src/billing/calculate.rs b/backend/crates/providers/xai/src/billing/calculate.rs new file mode 100644 index 000000000..0d25e8bbb --- /dev/null +++ b/backend/crates/providers/xai/src/billing/calculate.rs @@ -0,0 +1,161 @@ +//! xAI Token、缓存与 Priority 档位的费用计算 + +use super::catalog::{TokenRates, model_pricing}; +use gateway_core::metering::{ + CalculatedCostAmounts, CalculatedCostBreakdown, CalculatedCostRates, CurrencyCode, Decimal, + Money, +}; + +const LONG_CONTEXT_THRESHOLD: u64 = 200_000; + +/// 按响应确认的实际档位计算 xAI Token 费用;未知档位不估算 +#[must_use] +pub(crate) fn grok_billing_breakdown_with_tier( + model: &str, + input_tokens: u64, + output_tokens: u64, + cached_input_tokens: u64, + service_tier: Option<&str>, +) -> Option { + grok_billing_breakdown_with_override( + model, + input_tokens, + output_tokens, + cached_input_tokens, + 0, + service_tier, + None, + ) +} + +#[must_use] +pub(crate) fn grok_billing_breakdown_with_override( + model: &str, + input_tokens: u64, + output_tokens: u64, + cached_input_tokens: u64, + cache_write_input_tokens: u64, + service_tier: Option<&str>, + custom: Option<&gateway_core::metering::ModelPriceOverride>, +) -> Option { + let (tier, multiplier) = match service_tier.map(str::trim) { + None | Some("default" | "standard") => ("default", 1_u128), + Some("priority") => ("priority", 2), + Some(_) => return None, + }; + let long = input_tokens >= LONG_CONTEXT_THRESHOLD; + let standard_band = if long { "long_standard" } else { "standard" }; + let fast_band = if long { "long_fast" } else { "fast" }; + let convert = |rates: &gateway_core::metering::TokenPriceOverride| TokenRates { + input_ticks: rates.input.ticks_per_token(), + cached_input_ticks: rates.cache_read.ticks_per_token(), + output_ticks: rates.output.ticks_per_token(), + }; + let standard = custom + .and_then(|p| p.bands.get(standard_band)) + .map(convert) + .or_else(|| model_pricing(model).map(|p| if long { p.long } else { p.short }))?; + let rates = if multiplier == 2 { + custom + .and_then(|p| p.bands.get(fast_band)) + .map(convert) + .or_else(|| { + // 未覆盖档位继承内置价,不把人工标准价再次解释成 Priority 价 + let builtin = model_pricing(model).map(|p| if long { p.long } else { p.short })?; + Some(TokenRates { + input_ticks: builtin.input_ticks.checked_mul(2)?, + cached_input_ticks: builtin.cached_input_ticks.checked_mul(2)?, + output_ticks: builtin.output_ticks.checked_mul(2)?, + }) + })? + } else { + standard + }; + if cached_input_tokens.checked_add(cache_write_input_tokens)? > input_tokens { + return None; + } + let standard_write = custom + .and_then(|p| p.bands.get(standard_band)) + .map(|p| p.cache_write.ticks_per_token()); + let selected_band = if multiplier == 2 { + fast_band + } else { + standard_band + }; + let selected_write = custom + .and_then(|p| p.bands.get(selected_band)) + .map(|p| p.cache_write.ticks_per_token()); + let uncached_tokens = input_tokens.checked_sub(cached_input_tokens)?.checked_sub( + if selected_write.is_some() { + cache_write_input_tokens + } else { + 0 + }, + )?; + let standard_input_tokens = input_tokens.checked_sub(cached_input_tokens)?.checked_sub( + if standard_write.is_some() { + cache_write_input_tokens + } else { + 0 + }, + )?; + let cache_write_amount_ticks = + u128::from(cache_write_input_tokens).checked_mul(selected_write.unwrap_or_default())?; + let input_amount_ticks = u128::from(uncached_tokens).checked_mul(rates.input_ticks)?; + let cache_read_amount_ticks = + u128::from(cached_input_tokens).checked_mul(rates.cached_input_ticks)?; + let output_amount_ticks = u128::from(output_tokens).checked_mul(rates.output_ticks)?; + let selected_amount_ticks = input_amount_ticks + .checked_add(cache_read_amount_ticks)? + .checked_add(cache_write_amount_ticks)? + .checked_add(output_amount_ticks)?; + let standard_amount_ticks = u128::from(standard_input_tokens) + .checked_mul(standard.input_ticks)? + .checked_add(u128::from(cached_input_tokens).checked_mul(standard.cached_input_ticks)?)? + .checked_add( + u128::from(cache_write_input_tokens).checked_mul(standard_write.unwrap_or_default())?, + )? + .checked_add(u128::from(output_tokens).checked_mul(standard.output_ticks)?)?; + let multiplier_percent = if standard_amount_ticks == 0 { + 100 + } else { + u32::try_from( + selected_amount_ticks + .checked_mul(100)? + .checked_add(standard_amount_ticks / 2)? + .checked_div(standard_amount_ticks)?, + ) + .ok()? + }; + CalculatedCostBreakdown::new( + CalculatedCostAmounts::new( + usd_money(input_amount_ticks)?, + usd_money(output_amount_ticks)?, + usd_money(cache_read_amount_ticks)?, + usd_money(cache_write_amount_ticks)?, + usd_money(standard_amount_ticks)?, + usd_money(selected_amount_ticks)?, + ), + CalculatedCostRates::new( + usd_price_per_million(rates.input_ticks)?, + usd_price_per_million(rates.output_ticks)?, + usd_price_per_million(rates.cached_input_ticks)?, + usd_price_per_million(selected_write.unwrap_or_default())?, + ), + Some(tier.to_owned()), + multiplier_percent, + ) + .with_long_context_billing(long) + .with_custom_multiplier(custom.map_or(10_000, |p| p.multiplier_bps)) +} + +fn usd_money(ticks: u128) -> Option { + Some(Money::new( + Decimal::from_scaled(ticks).ok()?, + CurrencyCode::new("USD").ok()?, + )) +} + +fn usd_price_per_million(per_token_ticks: u128) -> Option { + usd_money(per_token_ticks.checked_mul(1_000_000)?) +} diff --git a/backend/crates/providers/xai/src/billing/catalog.rs b/backend/crates/providers/xai/src/billing/catalog.rs new file mode 100644 index 000000000..cbb417b47 --- /dev/null +++ b/backend/crates/providers/xai/src/billing/catalog.rs @@ -0,0 +1,158 @@ +//! xAI 内置模型价目、上下文档位与管理价目投影 + +pub(crate) const SUPPORTED_PRICING_BANDS: &[&str] = + &["standard", "fast", "long_standard", "long_fast"]; + +use gateway_core::metering::Decimal; + +#[derive(Clone, Copy)] +pub(super) struct TokenRates { + pub(super) input_ticks: u128, + pub(super) cached_input_ticks: u128, + pub(super) output_ticks: u128, +} + +#[derive(Clone, Copy)] +pub(super) struct ModelPricing { + pub(super) short: TokenRates, + pub(super) long: TokenRates, +} + +// 价格来源:https://docs.x.ai/developers/pricing,核验日期 2026-09-09 +const GROK_46_PRICING: ModelPricing = ModelPricing { + short: TokenRates { + input_ticks: 20_000, + cached_input_ticks: 5_000, + output_ticks: 60_000, + }, + long: TokenRates { + input_ticks: 40_000, + cached_input_ticks: 10_000, + output_ticks: 120_000, + }, +}; + +const GROK_45_PRICING: ModelPricing = ModelPricing { + short: TokenRates { + input_ticks: 20_000, + cached_input_ticks: 3_000, + output_ticks: 60_000, + }, + long: TokenRates { + input_ticks: 40_000, + cached_input_ticks: 6_000, + output_ticks: 120_000, + }, +}; + +const GROK_BUILD_PRICING: ModelPricing = ModelPricing { + short: TokenRates { + input_ticks: 10_000, + cached_input_ticks: 2_000, + output_ticks: 20_000, + }, + long: TokenRates { + input_ticks: 20_000, + cached_input_ticks: 4_000, + output_ticks: 40_000, + }, +}; + +const GROK_43_PRICING: ModelPricing = ModelPricing { + short: TokenRates { + input_ticks: 12_500, + cached_input_ticks: 2_000, + output_ticks: 25_000, + }, + long: TokenRates { + input_ticks: 25_000, + cached_input_ticks: 4_000, + output_ticks: 50_000, + }, +}; + +const PRICING_RULES: &[(&[&str], ModelPricing)] = &[ + (&["grok-4.6"], GROK_46_PRICING), + (&["grok-4.5", "grok-4.5-build-free"], GROK_45_PRICING), + ( + &[ + "grok-build-0.1", + "grok-code-fast-1", + "grok-code-fast-1-0825", + ], + GROK_BUILD_PRICING, + ), + ( + &[ + "grok-4.3", + "grok-4.20-multi-agent-0309", + "grok-4.20-multi-agent", + "grok-4.20-multi-agent-experimental-beta-0304", + "grok-4.20-multi-agent-beta-0309", + "grok-4.20-0309-reasoning", + "grok-4.20", + "grok-4.20-reasoning", + "grok-4.20-0309", + "grok-4.20-beta-0309-reasoning", + "grok-4.20-beta-0309", + "grok-4.20-experimental-beta-0304-reasoning", + "grok-4.20-experimental-beta-0304", + "grok-4.20-0309-non-reasoning", + "grok-4.20-non-reasoning", + "grok-4.20-experimental-beta-0304-non-reasoning", + "grok-4.20-beta-0309-non-reasoning", + ], + GROK_43_PRICING, + ), +]; + +pub(super) fn model_pricing(model: &str) -> Option { + PRICING_RULES + .iter() + .find(|(models, _)| models.contains(&model)) + .map(|(_, price)| *price) +} + +pub(crate) fn pricing_catalog() -> gateway_admin::model::pricing::ProviderPricingCatalog { + use gateway_core::metering::{ModelPriceOverride, TokenPrice, TokenPriceOverride}; + let price = |ticks: u128| -> TokenPrice { + Decimal::from_scaled(ticks * 1_000_000) + .expect("内置价格在范围内") + .canonical() + .try_into() + .expect("内置价格精度合法") + }; + PRICING_RULES + .iter() + .flat_map(|(models, pricing)| { + models.iter().map(|model| { + let bands = [ + ("standard", pricing.short, 1), + ("fast", pricing.short, 2), + ("long_standard", pricing.long, 1), + ("long_fast", pricing.long, 2), + ] + .into_iter() + .map(|(band, rates, multiplier)| { + ( + band.to_owned(), + TokenPriceOverride { + input: price(rates.input_ticks * multiplier), + output: price(rates.output_ticks * multiplier), + cache_read: price(rates.cached_input_ticks * multiplier), + cache_write: price(rates.input_ticks * multiplier), + }, + ) + }) + .collect(); + ( + (*model).to_owned(), + ModelPriceOverride { + multiplier_bps: 10_000, + bands, + }, + ) + }) + }) + .collect() +} diff --git a/backend/crates/providers/xai/src/billing/mod.rs b/backend/crates/providers/xai/src/billing/mod.rs new file mode 100644 index 000000000..c6b2dbaa0 --- /dev/null +++ b/backend/crates/providers/xai/src/billing/mod.rs @@ -0,0 +1,10 @@ +//! xAI 内置价目与本地费用估算入口 + +mod calculate; +mod catalog; + +pub(crate) use calculate::{ + grok_billing_breakdown_with_override, grok_billing_breakdown_with_tier, +}; +pub(crate) use catalog::SUPPORTED_PRICING_BANDS; +pub(crate) use catalog::pricing_catalog; diff --git a/backend/crates/providers/xai/src/credential/repository.rs b/backend/crates/providers/xai/src/credential/repository.rs index 977edf16a..e66d63a54 100644 --- a/backend/crates/providers/xai/src/credential/repository.rs +++ b/backend/crates/providers/xai/src/credential/repository.rs @@ -250,7 +250,7 @@ impl GrokCredentialAdmin { } credentials.insert("tokenType".to_owned(), Value::String("Bearer".to_owned())); credentials.insert( - "expiresAt".to_owned(), + "accessTokenExpiresAt".to_owned(), Value::String( loaded .account @@ -269,14 +269,13 @@ impl GrokCredentialAdmin { Value::String(OFFICIAL_CLIENT_ID.to_owned()), ); credentials.insert( - "scope".to_owned(), - Value::String(std::mem::take(&mut secret.scope)), + "scopes".to_owned(), + serde_json::json!(secret.scope.split_ascii_whitespace().collect::>()), ); if let Some(email) = loaded.account.email() { credentials.insert("email".to_owned(), Value::String(email.to_owned())); } let mut exported = serde_json::json!({ - "name": loaded.account.name(), "modelAccess": loaded.account.model_access(), "platform": "grok", "type": "oauth", @@ -288,6 +287,9 @@ impl GrokCredentialAdmin { .email() .map_or_else(|| serde_json::json!({}), |email| serde_json::json!({"email": email})), }); + if !loaded.account.name().is_empty() { + exported["label"] = Value::String(loaded.account.name().to_owned()); + } if let Some(proxy) = loaded.account.outbound_proxy() { exported["outboundProxyUrl"] = Value::String(proxy.expose_url().to_owned()); } diff --git a/backend/crates/providers/xai/src/credential/selector.rs b/backend/crates/providers/xai/src/credential/selector.rs index bae0654c0..4fd34cec5 100644 --- a/backend/crates/providers/xai/src/credential/selector.rs +++ b/backend/crates/providers/xai/src/credential/selector.rs @@ -13,9 +13,10 @@ use gateway_core::account::{ use gateway_core::concurrency::{CapacityWait, ConcurrencyQueuePolicy, ConcurrencyWaitQueue}; use gateway_core::engine::policy::{AccountPolicyError, AccountScheduleOwnership}; use gateway_core::provider_ports::{ - ProviderCooldown, ProviderCooldownPort, ProviderCooldownScope, ProviderLeaseAcquisition, - ProviderLeasePort, ProviderLeaseRequest, ProviderSchedulingLeaseRequest, - ProviderScopedCooldown, + ProviderAccountAdmission, ProviderCooldown, ProviderCooldownPort, ProviderCooldownScope, + ProviderLeaseAcquisition, ProviderLeasePort, ProviderLeaseRequest, + ProviderSchedulingLeaseRequest, ProviderScopedCooldown, ProviderSessionAffinityPort, + ProviderSessionAffinityState, }; use gateway_core::routing::{ProviderKind, UpstreamModelId}; @@ -64,10 +65,13 @@ pub struct GrokAccountSessionSelector { scheduling: Arc, cooldowns: Arc, account_feedback: Arc, + session_affinity: Arc, } impl GrokAccountSessionSelector { #[must_use] + // 各端口对应独立运行能力,避免为构造器另设一套端口集合 + #[expect(clippy::too_many_arguments)] pub fn new( provider_kind: ProviderKind, repository: GrokCredentialRepository, @@ -76,6 +80,7 @@ impl GrokAccountSessionSelector { scheduling: Arc, cooldowns: Arc, account_feedback: Arc, + session_affinity: Arc, ) -> Self { Self { provider_kind, @@ -85,6 +90,7 @@ impl GrokAccountSessionSelector { scheduling, cooldowns, account_feedback, + session_affinity, waiting: ConcurrencyWaitQueue::default(), } } @@ -286,32 +292,46 @@ impl GrokAccountSessionSelector { candidates.retain(|candidate| candidate.account.id() == required); } - let affinity_account = request.affinity().and_then(|affinity| { - candidates - .iter() - .filter(|candidate| { - !request.excluded_accounts().contains(candidate.account.id()) - }) - .max_by_key(|candidate| affinity.score(candidate.account.id())) - .map(|candidate| candidate.account.id().clone()) - }); + let affinity_key = request + .affinity() + .filter(|_| !diagnostic) + .map(crate::GrokSessionAffinityKey::store_key) + .transpose() + .map_err(affinity_unavailable)?; + let affinity = match affinity_key.as_ref() { + Some(key) => Some(ProviderSessionAffinityState::new( + key, + self.session_affinity + .load(&self.provider_kind, key) + .await + .map_err(affinity_unavailable)?, + request.account_selection_policy(), + )), + None => None, + }; let mut context = AccountSelectionContext { policy: request.account_selection_policy(), now: SystemTime::now(), excluded_accounts: request.excluded_accounts().clone(), busy_accounts: Default::default(), - preferred_account: request.required_account().cloned().or(affinity_account), + preferred_account: request.required_account().cloned(), preferred_account_overrides_weight: false, round_robin_cursor: scheduling.round_robin_cursor(), eligibility: request.eligibility(), account_scope: (!diagnostic).then(|| Arc::clone(request.account_scope())), reserved_concurrency: 0, }; + if let Some(affinity) = &affinity { + affinity.apply_preference(&mut context); + } for candidate in &candidates { if !waiting.can_try(candidate.account.id()) { context.busy_accounts.insert(candidate.account.id().clone()); } } + let binding_eligible = affinity + .as_ref() + .is_some_and(|affinity| affinity.binding_eligible(&candidates, &context)); let mut capacity_denied = false; let mut retry_after = None; loop { @@ -326,6 +346,9 @@ impl GrokAccountSessionSelector { &candidates, &mut context, AccountScheduleOwnership { + bound_account: affinity + .as_ref() + .and_then(ProviderSessionAffinityState::bound_account), pinned_account: request.required_account(), ..Default::default() }, @@ -349,6 +372,22 @@ impl GrokAccountSessionSelector { }) else { break; }; + if !selection.is_policy_choice() + && request.required_account().is_none() + && affinity + .as_ref() + .and_then(|affinity| { + affinity.wait_account( + &candidates, + &context, + queue_policy.max_waiting > 0, + ) + }) + .is_some_and(|bound| bound != selection.candidate().account.id()) + { + capacity_denied = true; + break; + } let capacity = AccountSelector.capacity_snapshot(&candidates, &context); let selected = selection.candidate(); let selected_id = selected.account.id().clone(); @@ -424,7 +463,7 @@ impl GrokAccountSessionSelector { .email() .map(|value| SecretValue::new(value.to_owned())), binding, - guard, + (), ) .map_err(|source| { GrokSessionSelectorError::InvalidSession(Some( @@ -437,6 +476,28 @@ impl GrokAccountSessionSelector { .with_capacity_snapshot( capacity.map(AccountCapacitySnapshot::with_acquired_request), ); + if let Some(affinity) = &affinity { + let claim = affinity.claim( + session.account_id(), + binding_eligible, + request.required_account().is_some(), + ); + if !self + .session_affinity + .admit_account( + &self.provider_kind, + ProviderAccountAdmission::Session(claim), + ) + .await + .map_err(affinity_unavailable)? + { + guard.release().await.map_err(affinity_unavailable)?; + // 让取消和总期限在连续认领冲突间获得轮询机会 + tokio::task::yield_now().await; + continue 'refresh; + } + } + let session = session.with_lease_guard(guard); if !waiting.elapsed().is_zero() { tracing::info!( queue_layer = "account", @@ -451,7 +512,14 @@ impl GrokAccountSessionSelector { }); } - let wait_candidates = AccountSelector.wait_candidates(&candidates, &context); + let mut wait_candidates = AccountSelector.wait_candidates(&candidates, &context); + if request.required_account().is_none() + && let Some(bound) = affinity.as_ref().and_then(|affinity| { + affinity.wait_account(&candidates, &context, queue_policy.max_waiting > 0) + }) + { + wait_candidates.retain(|account| account == bound); + } if !diagnostic && queue_policy.max_waiting > 0 && !wait_candidates.is_empty() { AccountSelector .wait_for_capacity(&mut waiting, &wait_candidates, &candidates, &context) @@ -836,3 +904,9 @@ fn insert_runtime_cooldown( cooldowns.insert(account_id.clone(), replacement); } } + +fn affinity_unavailable( + error: gateway_core::provider_ports::ProviderStoreError, +) -> GrokSessionSelectorError { + GrokSessionSelectorError::Unavailable(Some(gateway_core::error::ErrorSource::new(error))) +} diff --git a/backend/crates/providers/xai/src/lib.rs b/backend/crates/providers/xai/src/lib.rs index 45597fe45..96caabb59 100644 --- a/backend/crates/providers/xai/src/lib.rs +++ b/backend/crates/providers/xai/src/lib.rs @@ -1,8 +1,10 @@ //! 官方 Grok Build OAuth Provider 边界 mod admin; +mod billing; mod credential; mod oauth_http; +pub mod profile; mod provider; mod reasoning_replay; mod secret; @@ -11,17 +13,15 @@ pub mod transport; use std::sync::Arc; use std::time::Duration; -use gateway_admin::ports::provider::ProviderAdmin; +use gateway_admin::ports::provider::ProviderBundle; use gateway_core::account::ProviderAccountStore; -use gateway_core::engine::provider::Provider; use gateway_core::provider_ports::ProviderStorePorts; use gateway_core::routing::ProviderKind; -use gateway_core::task::WorkerContribution; use crate::admin::{XaiAdminProvider, XaiAdminServices}; -use crate::transport::profile::OfficialGrokCliReleaseTransport; +use crate::profile::OfficialGrokCliReleaseTransport; -pub use transport::{XaiWireProfile, XaiWireProfileState}; +pub use profile::{XaiWireProfile, XaiWireProfileState}; pub use credential::{ AllowedRedirectUri, AuthorizationCallback, AuthorizationCodeGrant, CallbackRejection, @@ -51,12 +51,12 @@ pub use oauth_http::{ FormField, FormValue, HttpHeader, HttpMethod, OAuthHttpRequest, OAuthHttpResponse, OAuthHttpTransport, TransportFailure, TransportFailureKind, TransportFuture, }; -pub use provider::GrokBuildProvider; -pub use secret::SecretValue; -pub use transport::profile::{ +pub use profile::{ GROK_CLI_RELEASE_URL, GrokCliReleaseError, GrokCliReleaseService, GrokCliReleaseSnapshot, GrokCliReleaseStatus, GrokCliReleaseTransport, }; +pub use provider::GrokBuildProvider; +pub use secret::SecretValue; pub use transport::{ GROK_BILLING_URL, GROK_CLI_BASE_URL, GROK_MODEL_CATALOG_URL, GROK_SUBSCRIPTION_URL, GrokBillingClient, GrokBillingError, GrokBillingRequest, GrokBillingSnapshot, @@ -81,17 +81,9 @@ pub use transport::{ GrokSessionSelectorFuture, MAX_GROK_BILLING_BYTES, MAX_GROK_MODEL_CATALOG_BYTES, OfficialGrokEndpointPolicy, ReqwestGrokInferenceTransport, ReqwestGrokModelCatalogTransport, ReqwestOAuthTransport, SelectedGrokSession, XAI_PROVIDER_NAME, build_grok_headers, - grok_billing_breakdown, grok_billing_breakdown_with_tier, parse_grok_billing, - parse_grok_model_catalog, + parse_grok_billing, parse_grok_model_catalog, }; -/// xAI 初始化后交给组装根的最小能力集 -pub struct ProviderBundle { - core_provider: Arc, - admin_provider: Arc, - worker_contributions: Vec, -} - /// 构造 xAI 数据面、管理面准备器与 Provider-owned 后台任务 pub async fn initialize(ports: ProviderStorePorts) -> Result { let profile = XaiWireProfileState::new(XaiWireProfile::default()); @@ -110,14 +102,14 @@ pub async fn initialize(ports: ProviderStorePorts) -> Result = Arc::new(OfficialGrokEndpointPolicy); @@ -151,6 +143,7 @@ pub async fn initialize(ports: ProviderStorePorts) -> Result = Arc::new( ReqwestGrokInferenceTransport::new(Arc::clone(&endpoint_policy)) @@ -181,7 +174,7 @@ pub async fn initialize(ports: ProviderStorePorts) -> Result = refresh.clone(); - let core_provider: Arc = Arc::new( + let core = Arc::new( GrokBuildProvider::new( selector, inference, @@ -192,7 +185,7 @@ pub async fn initialize(ports: ProviderStorePorts) -> Result = Arc::new(XaiAdminProvider::new( + let admin = Arc::new(XaiAdminProvider::new( provider_kind.clone(), profile, Arc::clone(&accounts), @@ -208,7 +201,7 @@ pub async fn initialize(ports: ProviderStorePorts) -> Result Result Arc { - Arc::clone(&self.core_provider) - } - - #[must_use] - pub fn admin_provider(&self) -> Arc { - Arc::clone(&self.admin_provider) - } - - /// 一次性移交 Host 任务计划,防止同一 owner 被重复注册 - pub fn take_worker_contributions(&mut self) -> Vec { - std::mem::take(&mut self.worker_contributions) - } -} - /// xAI 初始化失败的脱敏分类 #[derive(Debug, thiserror::Error)] pub enum XaiInitializeError { diff --git a/backend/crates/providers/xai/src/profile/mod.rs b/backend/crates/providers/xai/src/profile/mod.rs new file mode 100644 index 000000000..87ac35ef0 --- /dev/null +++ b/backend/crates/providers/xai/src/profile/mod.rs @@ -0,0 +1,13 @@ +//! xAI 请求画像、版本选择与官方发行资料入口 + +mod release; +pub mod selection; +mod state; + +pub use release::{ + GROK_CLI_RELEASE_URL, GrokCliReleaseError, GrokCliReleaseService, GrokCliReleaseSnapshot, + GrokCliReleaseStatus, GrokCliReleaseTransport, +}; +pub use state::{XaiWireProfile, XaiWireProfileState}; + +pub(crate) use release::{GROK_CLI_RELEASE_POLL_INTERVAL, OfficialGrokCliReleaseTransport}; diff --git a/backend/crates/providers/xai/src/transport/profile.rs b/backend/crates/providers/xai/src/profile/release.rs similarity index 68% rename from backend/crates/providers/xai/src/transport/profile.rs rename to backend/crates/providers/xai/src/profile/release.rs index d70ac2d8e..fd86b86b1 100644 --- a/backend/crates/providers/xai/src/transport/profile.rs +++ b/backend/crates/providers/xai/src/profile/release.rs @@ -1,4 +1,4 @@ -//! Grok CLI 运行时 wire profile +//! xAI CLI 官方发行查询与刷新服务 use std::{ sync::{Arc, RwLock}, @@ -8,106 +8,10 @@ use std::{ use chrono::{DateTime, Utc}; use futures::{StreamExt as _, future::BoxFuture}; use reqwest::{Client, redirect::Policy}; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; use url::Url; -/// Grok CLI 运行时身份;默认值作为官方发布检查的内置基线 -#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] -pub struct XaiWireProfile { - pub client_identifier: String, - pub client_version: String, - pub client_mode: String, - pub target_os: String, - pub target_arch: String, - pub verified_at: DateTime, -} - -impl Default for XaiWireProfile { - fn default() -> Self { - Self { - client_identifier: "grok-shell".to_owned(), - client_version: "1.0.13".to_owned(), - client_mode: "headless".to_owned(), - target_os: "linux".to_owned(), - target_arch: "x86_64".to_owned(), - verified_at: DateTime::UNIX_EPOCH + chrono::Duration::seconds(1_788_105_600), - } - } -} - -impl XaiWireProfile { - #[must_use] - pub fn user_agent(&self) -> String { - // Grok CLI 的产品名独立于 x-grok-client-identifier;自定义请求头不替换 UA 产品名 - let arch = match self.target_arch.as_str() { - "arm64" => "aarch64", - arch => arch, - }; - format!( - "grok-shell/{} ({}; {arch})", - self.client_version, self.target_os - ) - } -} - -#[derive(Debug, Clone)] -pub struct XaiWireProfileState(Arc>); - -impl XaiWireProfileState { - #[must_use] - pub fn new(profile: XaiWireProfile) -> Self { - Self(Arc::new(RwLock::new(profile))) - } - - #[must_use] - pub fn client_identifier(&self) -> String { - self.snapshot().client_identifier - } - #[must_use] - pub fn client_version(&self) -> String { - self.snapshot().client_version - } - #[must_use] - pub fn client_mode(&self) -> String { - self.snapshot().client_mode - } - #[must_use] - pub fn target_os(&self) -> String { - self.snapshot().target_os - } - #[must_use] - pub fn target_arch(&self) -> String { - self.snapshot().target_arch - } - #[must_use] - pub fn verified_at(&self) -> DateTime { - self.snapshot().verified_at - } - - #[must_use] - pub fn user_agent(&self) -> String { - self.snapshot().user_agent() - } - - #[must_use] - pub fn snapshot(&self) -> XaiWireProfile { - self.0 - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone() - } - - pub(crate) fn update_client_version(&self, version: &str) { - let mut profile = self - .0 - .write() - .unwrap_or_else(std::sync::PoisonError::into_inner); - if profile.client_version != version { - profile.client_version = version.to_owned(); - profile.verified_at = Utc::now(); - } - } -} +use super::XaiWireProfileState; pub const GROK_CLI_RELEASE_URL: &str = "https://registry.npmjs.org/@xai-official%2Fgrok/latest"; pub const GROK_CLI_RELEASE_POLL_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60); diff --git a/backend/crates/providers/xai/src/transport/client_profile.rs b/backend/crates/providers/xai/src/profile/selection.rs similarity index 98% rename from backend/crates/providers/xai/src/transport/client_profile.rs rename to backend/crates/providers/xai/src/profile/selection.rs index 71875ed0c..9c8299b49 100644 --- a/backend/crates/providers/xai/src/transport/client_profile.rs +++ b/backend/crates/providers/xai/src/profile/selection.rs @@ -99,7 +99,7 @@ impl GrokClientProfileSelection { pub fn preview( &self, state: &XaiWireProfileState, - status: &super::profile::GrokCliReleaseSnapshot, + status: &super::GrokCliReleaseSnapshot, ) -> Result { let profile = self.resolve(state)?; let latest = self.version_mode == VersionMode::Latest; diff --git a/backend/crates/providers/xai/src/profile/state.rs b/backend/crates/providers/xai/src/profile/state.rs new file mode 100644 index 000000000..83b917092 --- /dev/null +++ b/backend/crates/providers/xai/src/profile/state.rs @@ -0,0 +1,103 @@ +//! xAI 请求身份快照与运行时更新 + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use std::sync::{Arc, RwLock}; + +/// Grok CLI 运行时身份;默认值作为官方发布检查的内置基线 +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +pub struct XaiWireProfile { + pub client_identifier: String, + pub client_version: String, + pub client_mode: String, + pub target_os: String, + pub target_arch: String, + pub verified_at: DateTime, +} + +impl Default for XaiWireProfile { + fn default() -> Self { + Self { + client_identifier: "grok-shell".to_owned(), + client_version: "1.0.13".to_owned(), + client_mode: "headless".to_owned(), + target_os: "linux".to_owned(), + target_arch: "x86_64".to_owned(), + verified_at: DateTime::UNIX_EPOCH + chrono::Duration::seconds(1_788_105_600), + } + } +} + +impl XaiWireProfile { + #[must_use] + pub fn user_agent(&self) -> String { + // Grok CLI 的产品名独立于 x-grok-client-identifier;自定义请求头不替换 UA 产品名 + let arch = match self.target_arch.as_str() { + "arm64" => "aarch64", + arch => arch, + }; + format!( + "grok-shell/{} ({}; {arch})", + self.client_version, self.target_os + ) + } +} + +#[derive(Debug, Clone)] +pub struct XaiWireProfileState(Arc>); + +impl XaiWireProfileState { + #[must_use] + pub fn new(profile: XaiWireProfile) -> Self { + Self(Arc::new(RwLock::new(profile))) + } + + #[must_use] + pub fn client_identifier(&self) -> String { + self.snapshot().client_identifier + } + #[must_use] + pub fn client_version(&self) -> String { + self.snapshot().client_version + } + #[must_use] + pub fn client_mode(&self) -> String { + self.snapshot().client_mode + } + #[must_use] + pub fn target_os(&self) -> String { + self.snapshot().target_os + } + #[must_use] + pub fn target_arch(&self) -> String { + self.snapshot().target_arch + } + #[must_use] + pub fn verified_at(&self) -> DateTime { + self.snapshot().verified_at + } + + #[must_use] + pub fn user_agent(&self) -> String { + self.snapshot().user_agent() + } + + #[must_use] + pub fn snapshot(&self) -> XaiWireProfile { + self.0 + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } + + pub(crate) fn update_client_version(&self, version: &str) { + let mut profile = self + .0 + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if profile.client_version != version { + profile.client_version = version.to_owned(); + profile.verified_at = Utc::now(); + } + } +} diff --git a/backend/crates/providers/xai/src/provider/mod.rs b/backend/crates/providers/xai/src/provider/mod.rs index f67ba01ff..7ae64df5b 100644 --- a/backend/crates/providers/xai/src/provider/mod.rs +++ b/backend/crates/providers/xai/src/provider/mod.rs @@ -50,6 +50,7 @@ use crate::credential::{ GrokCredentialRecovery, GrokCredentialRecoveryOutcome, GrokCredentialRefreshOutcome, GrokCredentialRefreshService, GrokQuotaError, }; +use crate::profile::{GROK_CLI_RELEASE_POLL_INTERVAL, GrokCliReleaseService}; use crate::reasoning_replay::{ GrokReasoningReplay, GrokReasoningReplayCapture, GrokReasoningReplayKey, valid_reasoning_ciphertext, @@ -57,7 +58,6 @@ use crate::reasoning_replay::{ use crate::transport::canonical::{GrokCanonicalDecoder, GrokNativeResponseTranslator}; use crate::transport::config::XAI_PROVIDER_NAME; use crate::transport::headers::{GrokClientIdentity, build_grok_headers}; -use crate::transport::profile::{GROK_CLI_RELEASE_POLL_INTERVAL, GrokCliReleaseService}; use crate::transport::{ GROK_RESPONSES_URL, GrokCompactionDecodeError, GrokCompactionRequest, GrokCompactionSummaryDecoder, GrokCredentialFailure, GrokInferenceChunkStream, @@ -74,12 +74,11 @@ mod failure; mod outbound; mod stream; mod upstream_adapter; -mod workers; +pub(crate) mod workers; use continuation::*; use failure::*; use stream::*; -pub(crate) use workers::worker_contributions; const HTTP_SSE_TRANSPORT: &str = "http_sse"; const XAI_SESSION_STATE_MAX_BYTES: usize = 8 * 1024 * 1024; @@ -161,7 +160,7 @@ impl Provider for GrokBuildProvider { &self, configuration: &gateway_core::account::OpaqueProviderData, ) -> Result { - use crate::transport::client_profile::{GrokClientProfileSelection, object}; + use crate::profile::selection::{GrokClientProfileSelection, object}; let profile = GrokClientProfileSelection::parse(configuration) .and_then(|selection| selection.resolve(&self.wire_profile)) .and_then(|profile| object(&profile)) diff --git a/backend/crates/providers/xai/src/provider/upstream_adapter.rs b/backend/crates/providers/xai/src/provider/upstream_adapter.rs index 1af0a258f..3d3853145 100644 --- a/backend/crates/providers/xai/src/provider/upstream_adapter.rs +++ b/backend/crates/providers/xai/src/provider/upstream_adapter.rs @@ -101,7 +101,7 @@ impl UpstreamAccountConnection for SelectedConnection { } fn calculate_cost(&self, tier: Option<&str>, usage: &Usage) -> Option { - crate::transport::canonical::grok_billing_breakdown_with_override( + crate::billing::grok_billing_breakdown_with_override( self.model.as_str(), usage.input_tokens?, usage.output_tokens?, diff --git a/backend/crates/providers/xai/src/provider/workers.rs b/backend/crates/providers/xai/src/provider/workers.rs index 5207e88a4..fb390bf0f 100644 --- a/backend/crates/providers/xai/src/provider/workers.rs +++ b/backend/crates/providers/xai/src/provider/workers.rs @@ -14,7 +14,7 @@ pub(super) const EXHAUSTED_QUOTA_FALLBACK_RECHECK_INTERVAL: Duration = Duration: pub(super) const EXHAUSTED_QUOTA_REFRESH_RETRY_INTERVAL: Duration = QUOTA_CATALOG_INTERVAL; pub(super) const CLI_RELEASE_WORKER_OWNER: &str = "xai-cli-release"; -pub(crate) fn worker_contributions( +pub(crate) fn contributions( refresh: Arc, quota: Arc, catalog: Arc, diff --git a/backend/crates/providers/xai/src/transport/canonical.rs b/backend/crates/providers/xai/src/transport/canonical.rs index 13dc4df58..ebf471445 100644 --- a/backend/crates/providers/xai/src/transport/canonical.rs +++ b/backend/crates/providers/xai/src/transport/canonical.rs @@ -11,10 +11,7 @@ use gateway_core::event::{ ContentItem, ContentKind, FinishReason, GatewayEvent, ProtocolWireEvent, ProviderEvent, ReasoningDelta, ResponseMeta, TextDelta, ToolCallDelta, }; -use gateway_core::metering::{ - CalculatedCost, CalculatedCostAmounts, CalculatedCostBreakdown, CalculatedCostRates, - CurrencyCode, Decimal, Money, ProviderReportedCost, Usage, -}; +use gateway_core::metering::{CalculatedCost, ProviderReportedCost, Usage}; use gateway_core::upstream::UpstreamSendState; use gateway_protocol::openai::OPENAI_PROTOCOL; use gateway_protocol::openai::events::{TokenUsage, billable_usage_is_complete, extract_usage}; @@ -24,9 +21,9 @@ use serde_json::Value; use super::GrokInferenceTransportErrorKind; use super::request::{GrokResponseTransform, GrokResponsesRequest}; use super::upstream_error::{classify_grok_quota_failure, scrub_account_fingerprints}; +use crate::billing::grok_billing_breakdown_with_override; const CONTENTS_PER_OUTPUT: u32 = 1_024; -const LONG_CONTEXT_THRESHOLD: u64 = 200_000; const GROK_PING_SSE_COMMENT: &[u8] = b": ping\n\n"; const XAI_RESPONSE_PROTOCOL: &str = "xai"; @@ -45,241 +42,6 @@ pub(crate) struct GrokNativeResponseTranslator { response_transform: GrokResponseTransform, } -#[derive(Clone, Copy)] -struct TokenRates { - input_ticks: u128, - cached_input_ticks: u128, - output_ticks: u128, -} - -#[derive(Clone, Copy)] -struct ModelPricing { - short: TokenRates, - long: TokenRates, -} - -// 价格来源:https://docs.x.ai/developers/pricing,核验日期 2026-09-09 -const GROK_46_PRICING: ModelPricing = ModelPricing { - short: TokenRates { - input_ticks: 20_000, - cached_input_ticks: 5_000, - output_ticks: 60_000, - }, - long: TokenRates { - input_ticks: 40_000, - cached_input_ticks: 10_000, - output_ticks: 120_000, - }, -}; - -const GROK_45_PRICING: ModelPricing = ModelPricing { - short: TokenRates { - input_ticks: 20_000, - cached_input_ticks: 3_000, - output_ticks: 60_000, - }, - long: TokenRates { - input_ticks: 40_000, - cached_input_ticks: 6_000, - output_ticks: 120_000, - }, -}; - -const GROK_BUILD_PRICING: ModelPricing = ModelPricing { - short: TokenRates { - input_ticks: 10_000, - cached_input_ticks: 2_000, - output_ticks: 20_000, - }, - long: TokenRates { - input_ticks: 20_000, - cached_input_ticks: 4_000, - output_ticks: 40_000, - }, -}; - -const GROK_43_PRICING: ModelPricing = ModelPricing { - short: TokenRates { - input_ticks: 12_500, - cached_input_ticks: 2_000, - output_ticks: 25_000, - }, - long: TokenRates { - input_ticks: 25_000, - cached_input_ticks: 4_000, - output_ticks: 50_000, - }, -}; - -/// 按 xAI Provider 当前受控价格规则计算费用明细 -#[must_use] -pub fn grok_billing_breakdown( - model: &str, - input_tokens: u64, - output_tokens: u64, - cached_input_tokens: u64, -) -> Option { - grok_billing_breakdown_with_tier( - model, - input_tokens, - output_tokens, - cached_input_tokens, - None, - ) -} - -/// 按响应确认的实际档位计算 xAI Token 费用;未知档位不估算 -#[must_use] -pub fn grok_billing_breakdown_with_tier( - model: &str, - input_tokens: u64, - output_tokens: u64, - cached_input_tokens: u64, - service_tier: Option<&str>, -) -> Option { - grok_billing_breakdown_with_override( - model, - input_tokens, - output_tokens, - cached_input_tokens, - 0, - service_tier, - None, - ) -} - -#[must_use] -pub fn grok_billing_breakdown_with_override( - model: &str, - input_tokens: u64, - output_tokens: u64, - cached_input_tokens: u64, - cache_write_input_tokens: u64, - service_tier: Option<&str>, - custom: Option<&gateway_core::metering::ModelPriceOverride>, -) -> Option { - let (tier, multiplier) = match service_tier.map(str::trim) { - None | Some("default" | "standard") => ("default", 1_u128), - Some("priority") => ("priority", 2), - Some(_) => return None, - }; - let long = input_tokens >= LONG_CONTEXT_THRESHOLD; - let standard_band = if long { "long_standard" } else { "standard" }; - let fast_band = if long { "long_fast" } else { "fast" }; - let convert = |rates: &gateway_core::metering::TokenPriceOverride| TokenRates { - input_ticks: rates.input.ticks_per_token(), - cached_input_ticks: rates.cache_read.ticks_per_token(), - output_ticks: rates.output.ticks_per_token(), - }; - let standard = custom - .and_then(|p| p.bands.get(standard_band)) - .map(convert) - .or_else(|| model_pricing(model).map(|p| if long { p.long } else { p.short }))?; - let rates = if multiplier == 2 { - custom - .and_then(|p| p.bands.get(fast_band)) - .map(convert) - .or_else(|| { - // 未覆盖档位继承内置价,不把人工标准价再次解释成 Priority 价 - let builtin = model_pricing(model).map(|p| if long { p.long } else { p.short })?; - Some(TokenRates { - input_ticks: builtin.input_ticks.checked_mul(2)?, - cached_input_ticks: builtin.cached_input_ticks.checked_mul(2)?, - output_ticks: builtin.output_ticks.checked_mul(2)?, - }) - })? - } else { - standard - }; - if cached_input_tokens.checked_add(cache_write_input_tokens)? > input_tokens { - return None; - } - let standard_write = custom - .and_then(|p| p.bands.get(standard_band)) - .map(|p| p.cache_write.ticks_per_token()); - let selected_band = if multiplier == 2 { - fast_band - } else { - standard_band - }; - let selected_write = custom - .and_then(|p| p.bands.get(selected_band)) - .map(|p| p.cache_write.ticks_per_token()); - let uncached_tokens = input_tokens.checked_sub(cached_input_tokens)?.checked_sub( - if selected_write.is_some() { - cache_write_input_tokens - } else { - 0 - }, - )?; - let standard_input_tokens = input_tokens.checked_sub(cached_input_tokens)?.checked_sub( - if standard_write.is_some() { - cache_write_input_tokens - } else { - 0 - }, - )?; - let cache_write_amount_ticks = - u128::from(cache_write_input_tokens).checked_mul(selected_write.unwrap_or_default())?; - let input_amount_ticks = u128::from(uncached_tokens).checked_mul(rates.input_ticks)?; - let cache_read_amount_ticks = - u128::from(cached_input_tokens).checked_mul(rates.cached_input_ticks)?; - let output_amount_ticks = u128::from(output_tokens).checked_mul(rates.output_ticks)?; - let selected_amount_ticks = input_amount_ticks - .checked_add(cache_read_amount_ticks)? - .checked_add(cache_write_amount_ticks)? - .checked_add(output_amount_ticks)?; - let standard_amount_ticks = u128::from(standard_input_tokens) - .checked_mul(standard.input_ticks)? - .checked_add(u128::from(cached_input_tokens).checked_mul(standard.cached_input_ticks)?)? - .checked_add( - u128::from(cache_write_input_tokens).checked_mul(standard_write.unwrap_or_default())?, - )? - .checked_add(u128::from(output_tokens).checked_mul(standard.output_ticks)?)?; - let multiplier_percent = if standard_amount_ticks == 0 { - 100 - } else { - u32::try_from( - selected_amount_ticks - .checked_mul(100)? - .checked_add(standard_amount_ticks / 2)? - .checked_div(standard_amount_ticks)?, - ) - .ok()? - }; - CalculatedCostBreakdown::new( - CalculatedCostAmounts::new( - usd_money(input_amount_ticks)?, - usd_money(output_amount_ticks)?, - usd_money(cache_read_amount_ticks)?, - usd_money(cache_write_amount_ticks)?, - usd_money(standard_amount_ticks)?, - usd_money(selected_amount_ticks)?, - ), - CalculatedCostRates::new( - usd_price_per_million(rates.input_ticks)?, - usd_price_per_million(rates.output_ticks)?, - usd_price_per_million(rates.cached_input_ticks)?, - usd_price_per_million(selected_write.unwrap_or_default())?, - ), - Some(tier.to_owned()), - multiplier_percent, - ) - .with_long_context_billing(long) - .with_custom_multiplier(custom.map_or(10_000, |p| p.multiplier_bps)) -} - -fn usd_money(ticks: u128) -> Option { - Some(Money::new( - Decimal::from_scaled(ticks).ok()?, - CurrencyCode::new("USD").ok()?, - )) -} - -fn usd_price_per_million(per_token_ticks: u128) -> Option { - usd_money(per_token_ticks.checked_mul(1_000_000)?) -} - /// 单次官方 Grok Responses 尝试的增量解码器 /// /// 每个上游 event 同时保留 OpenAI wire,并在可识别时附加 canonical facts @@ -1102,92 +864,6 @@ fn calculated_cost( Some(breakdown.calculated_cost()) } -const PRICING_RULES: &[(&[&str], ModelPricing)] = &[ - (&["grok-4.6"], GROK_46_PRICING), - (&["grok-4.5", "grok-4.5-build-free"], GROK_45_PRICING), - ( - &[ - "grok-build-0.1", - "grok-code-fast-1", - "grok-code-fast-1-0825", - ], - GROK_BUILD_PRICING, - ), - ( - &[ - "grok-4.3", - "grok-4.20-multi-agent-0309", - "grok-4.20-multi-agent", - "grok-4.20-multi-agent-experimental-beta-0304", - "grok-4.20-multi-agent-beta-0309", - "grok-4.20-0309-reasoning", - "grok-4.20", - "grok-4.20-reasoning", - "grok-4.20-0309", - "grok-4.20-beta-0309-reasoning", - "grok-4.20-beta-0309", - "grok-4.20-experimental-beta-0304-reasoning", - "grok-4.20-experimental-beta-0304", - "grok-4.20-0309-non-reasoning", - "grok-4.20-non-reasoning", - "grok-4.20-experimental-beta-0304-non-reasoning", - "grok-4.20-beta-0309-non-reasoning", - ], - GROK_43_PRICING, - ), -]; - -fn model_pricing(model: &str) -> Option { - PRICING_RULES - .iter() - .find(|(models, _)| models.contains(&model)) - .map(|(_, price)| *price) -} - -pub(crate) fn pricing_catalog() -> gateway_admin::model::pricing::ProviderPricingCatalog { - use gateway_core::metering::{ModelPriceOverride, TokenPrice, TokenPriceOverride}; - let price = |ticks: u128| -> TokenPrice { - Decimal::from_scaled(ticks * 1_000_000) - .expect("内置价格在范围内") - .canonical() - .try_into() - .expect("内置价格精度合法") - }; - PRICING_RULES - .iter() - .flat_map(|(models, pricing)| { - models.iter().map(|model| { - let bands = [ - ("standard", pricing.short, 1), - ("fast", pricing.short, 2), - ("long_standard", pricing.long, 1), - ("long_fast", pricing.long, 2), - ] - .into_iter() - .map(|(band, rates, multiplier)| { - ( - band.to_owned(), - TokenPriceOverride { - input: price(rates.input_ticks * multiplier), - output: price(rates.output_ticks * multiplier), - cache_read: price(rates.cached_input_ticks * multiplier), - cache_write: price(rates.input_ticks * multiplier), - }, - ) - }) - .collect(); - ( - (*model).to_owned(), - ModelPriceOverride { - multiplier_bps: 10_000, - bands, - }, - ) - }) - }) - .collect() -} - fn incomplete_finish_reason(response: &Value) -> FinishReason { match response .pointer("/incomplete_details/reason") diff --git a/backend/crates/providers/xai/src/transport/mod.rs b/backend/crates/providers/xai/src/transport/mod.rs index bd4deb1b7..168eb0cd9 100644 --- a/backend/crates/providers/xai/src/transport/mod.rs +++ b/backend/crates/providers/xai/src/transport/mod.rs @@ -2,21 +2,17 @@ pub(crate) mod canonical; pub(crate) mod catalog; -pub mod client_profile; pub(crate) mod compaction; pub(crate) mod config; pub(crate) mod egress; pub(crate) mod headers; mod inference; pub(crate) mod network; -pub(crate) mod profile; mod request; mod session; mod upstream_error; -pub use canonical::{ - GrokCanonicalDecoder, grok_billing_breakdown, grok_billing_breakdown_with_tier, -}; +pub use canonical::GrokCanonicalDecoder; pub use catalog::{ GROK_BILLING_URL, GROK_MODEL_CATALOG_URL, GROK_SUBSCRIPTION_URL, GrokBillingClient, GrokBillingError, GrokBillingRequest, GrokBillingSnapshot, GrokBillingTransport, @@ -49,7 +45,6 @@ pub use network::{ GrokReqwestTransportBuildError, OfficialGrokEndpointPolicy, ReqwestGrokInferenceTransport, ReqwestGrokModelCatalogTransport, ReqwestOAuthTransport, }; -pub use profile::{XaiWireProfile, XaiWireProfileState}; pub(crate) use request::GrokReplayItem; pub use request::{GrokRequestEncodeError, GrokResponsesRequest}; pub use session::{ diff --git a/backend/crates/providers/xai/src/transport/session.rs b/backend/crates/providers/xai/src/transport/session.rs index 086da01e8..be21a5eb7 100644 --- a/backend/crates/providers/xai/src/transport/session.rs +++ b/backend/crates/providers/xai/src/transport/session.rs @@ -14,7 +14,6 @@ use gateway_core::account::{ use gateway_core::engine::policy::RequestPolicyContext; use gateway_core::policy::ClientApiKeyId; use gateway_core::routing::{FrozenAccountScope, UpstreamModelId}; -use sha2::{Digest as _, Sha256}; use crate::SecretValue; @@ -75,14 +74,18 @@ impl GrokSessionAffinityKey { Self(digest) } - /// 为候选账号计算稳定 rendezvous 分值,原始会话值不会离开 Provider - pub(crate) fn score(&self, account_id: &ProviderAccountId) -> [u8; 32] { - let mut hasher = Sha256::new(); - hasher.update(b"xai-account-affinity-v1\0"); - hasher.update(self.0); - hasher.update(b"\0"); - hasher.update(account_id.as_str().as_bytes()); - hasher.finalize().into() + pub(crate) fn store_key( + &self, + ) -> Result< + gateway_core::provider_ports::ProviderSessionAffinityKey, + gateway_core::provider_ports::ProviderStoreError, + > { + gateway_core::provider_ports::ProviderSessionAffinityKey::try_new( + self.0 + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(), + ) } } @@ -148,6 +151,12 @@ impl SelectedGrokSession { }) } + /// 凭据验证与会话认领完成后才转交租约,冲突时选择器仍可显式释放 + pub(crate) fn with_lease_guard(mut self, guard: impl GrokSessionLeaseGuard) -> Self { + self._guard = Box::new(guard); + self + } + /// 标记禁用账号的管理端诊断只读取真实上游结果,不回写账号状态 #[must_use] pub(crate) const fn without_account_state_mutation(mut self) -> Self { diff --git a/backend/crates/providers/xai/tests/admin.rs b/backend/crates/providers/xai/tests/admin/mod.rs similarity index 52% rename from backend/crates/providers/xai/tests/admin.rs rename to backend/crates/providers/xai/tests/admin/mod.rs index 553a80a13..285330a85 100644 --- a/backend/crates/providers/xai/tests/admin.rs +++ b/backend/crates/providers/xai/tests/admin/mod.rs @@ -1,5 +1,6 @@ //! 验证 xAI 管理能力、账号清理与后台目录任务的组装和错误处理 +mod provider; use std::collections::BTreeMap; use std::num::NonZeroU32; use std::sync::{Arc, Mutex}; @@ -53,231 +54,12 @@ use crate::support::{ TestSessionExclusions, account_id, create_input, seed_input, }; -#[tokio::test] -async fn account_capabilities_advertise_only_xai_oauth_quota_operations() { - let bundle = provider_xai::initialize(provider_ports()).await.unwrap(); - let provider = bundle.admin_provider(); - let id = ProviderAccountId::new("acct_capabilities").unwrap(); - let oauth = provider.account_capabilities(&id, "oauth"); - assert_eq!( - oauth, - gateway_admin::model::accounts::ProviderAccountCapabilities { - quota: true, - quota_refresh: true, - ..Default::default() - } - ); - for kind in ["api_key", "unknown"] { - assert_eq!(provider.account_capabilities(&id, kind), Default::default()); - } -} - -#[tokio::test] -async fn account_unavailable_clears_real_selector_cooldowns_only_for_deleted_account() { - let store = MemoryProviderAccountStore::shared(); - let cooldowns = Arc::new(MemoryCooldownPort::default()); - let ports = ProviderStorePorts::new( - store.clone(), - Arc::new(TestLeases), - Arc::new(TestSessionAffinity), - Arc::new(TestSessionExclusions), - Arc::new(TestCatalogCache::default()), - Arc::new(TestArtifactProfiles), - Arc::new(TestCredentialState), - cooldowns.clone(), - Arc::new(TestRuntimePolicy), - Arc::new(TestOAuthPending::default()), - Arc::new(RecordingDiagnostics::default()), - ); - let repository = GrokCredentialRepository::new(store.clone()); - let selector = GrokAccountSessionSelector::new( - ProviderKind::new("xai").unwrap(), - repository.clone(), - MemoryGrokCatalogCache::shared(), - Arc::new(crate::support::grok_quota_service( - repository, - Arc::new( - ReqwestGrokModelCatalogTransport::new(Arc::new(OfficialGrokEndpointPolicy)) - .unwrap(), - ), - )), - ports.leases(), - cooldowns.clone(), - ports.account_feedback(), - ); - let bundle = provider_xai::initialize(ports).await.unwrap(); - let models = ["grok-4.5", "grok-4.6"].map(|id| UpstreamModelId::new(id).unwrap()); - for suffix in ["deleted-cooldown", "retained-cooldown"] { - let input = create_input(suffix, &format!("subject-{suffix}")); - seed_input(&store, &input).await.unwrap(); - let session = SelectedGrokSession::new( - input.account_id, - CredentialRevision::new(1).unwrap(), - input.secret.access_token, - SecretValue::new(input.account.subject), - None, - GrokSessionBinding::new(suffix).unwrap(), - (), - ) - .unwrap(); - // cooldown 必须来自生产 selector 对真实反馈类型的处理,不能由 mock 手工伪造 - selector - .record_failure( - &session, - GrokCredentialFailure::RateLimited { - retry_after: Some(Duration::from_secs(60)), - }, - ) - .await; - for model in &models { - selector - .record_failure( - &session, - GrokCredentialFailure::ModelQuotaExhausted { - upstream_model: model.clone(), - retry_after: None, - }, - ) - .await; - assert!( - cooldowns - .scoped_cooldown( - session.account_id(), - &ProviderCooldownScope::upstream_model(model.clone()) - ) - .is_some() - ); - } - assert!(cooldowns.cooldown(session.account_id()).is_some()); - } - let deleted = account_id("deleted-cooldown"); - store.delete_account(&deleted).await.unwrap(); - bundle.admin_provider().account_unavailable(&deleted).await; - assert!(cooldowns.cooldown(&deleted).is_none()); - let retained = account_id("retained-cooldown"); - assert!(cooldowns.cooldown(&retained).is_some()); - for model in models { - let scope = ProviderCooldownScope::upstream_model(model); - assert!(cooldowns.scoped_cooldown(&deleted, &scope).is_none()); - assert!(cooldowns.scoped_cooldown(&retained, &scope).is_some()); - } -} - -#[tokio::test] -async fn xai_bundle_exposes_core_admin_and_drains_worker_contributions_once() { - let mut bundle = provider_xai::initialize(provider_ports()) - .await - .expect("xAI bundle"); - - assert_eq!(bundle.core_provider().name(), "xai"); - assert_eq!(bundle.admin_provider().provider_kind().as_str(), "xai"); - let contributions = bundle.take_worker_contributions(); - assert_eq!(contributions.len(), 3); - assert!( - contributions - .iter() - .any(|item| item.kind() == WorkerKind::OAuthRefresh) - ); - assert!( - contributions - .iter() - .any(|item| item.kind() == WorkerKind::QuotaCatalogHealth) - ); - assert!(bundle.take_worker_contributions().is_empty()); -} - -#[tokio::test] -async fn xai_quota_catalog_worker_treats_empty_account_pool_as_idle() { - let mut bundle = provider_xai::initialize(provider_ports()) - .await - .expect("xAI bundle"); - - run_quota_catalog_cycle(&mut bundle) - .await - .expect("idle quota cycle"); -} - -#[tokio::test] -async fn xai_quota_catalog_worker_preserves_store_failures() { - let store = Arc::new(MemoryProviderAccountStore::default()); - store.fail_provider_listing(); - let mut bundle = provider_xai::initialize(provider_ports_with( - store, - Arc::new(TestOAuthPending::default()), - )) - .await - .expect("xAI bundle"); - - let error = run_quota_catalog_cycle(&mut bundle) - .await - .expect_err("Provider account Store failure"); - assert_eq!(error.as_safe_str(), "账号列表读取失败"); -} - -#[tokio::test] -async fn xai_quota_catalog_worker_retains_both_failure_stages_and_finishes_the_batch() { - for refresh_due in [true, false] { - let store = MemoryProviderAccountStore::shared(); - for suffix in ["broken_one", "broken_two"] { - let mut input = create_input(suffix, "synthetic-subject"); - input.enabled = suffix == "broken_one"; - let mut account = crate::support::prepare_input(&input).unwrap(); - // 模拟历史持久化凭据损坏,额度与目录读取均应保留各自的失败分类 - account.credential = gateway_core::account::PlaintextCredential::new(Map::new()); - let revision = account.account.revision(); - store.create_account(account).await.unwrap(); - if refresh_due { - store - .apply_quota_access(gateway_core::account::QuotaAccessChange { - account_id: input.account_id, - expected_revision: revision, - state: gateway_core::account::QuotaState::exhausted( - gateway_core::account::QuotaEvidence::ProviderDenied, - SystemTime::UNIX_EPOCH, - None, - ), - }) - .await - .unwrap(); - } - } - let mut bundle = provider_xai::initialize(provider_ports_with( - store, - Arc::new(TestOAuthPending::default()), - )) - .await - .unwrap(); - - let error = run_quota_catalog_cycle(&mut bundle) - .await - .expect_err("invalid stored credentials"); - assert_eq!(error.as_safe_str(), "额度或模型目录同步失败"); - let details = error.error_details().expect("synchronization causes"); - let details: Value = serde_json::from_str(details.as_str()).unwrap(); - let cause = details["causes"]["messages"][0].as_str().unwrap(); - assert!( - cause.contains("catalog error: Grok provider account store is unavailable"), - "{cause}" - ); - if refresh_due { - assert!(cause.contains("quota failures=2"), "{cause}"); - assert!( - cause - .contains("first quota error: xAI quota credential or billing data is invalid"), - "{cause}" - ); - } else { - assert!(cause.contains("quota failures=0"), "{cause}"); - assert!(!cause.contains("first quota error"), "{cause}"); - } - } -} +mod quota; async fn run_quota_catalog_cycle( - bundle: &mut provider_xai::ProviderBundle, + bundle: &mut gateway_admin::ports::provider::ProviderBundle, ) -> Result<(), WorkerTaskError> { - let registration = bundle - .take_worker_contributions() + let registration = std::mem::take(&mut bundle.workers) .into_iter() .find_map(|contribution| match contribution { WorkerContribution::Registration(registration) @@ -300,381 +82,11 @@ async fn run_quota_catalog_cycle( .await } -#[tokio::test] -async fn xai_admin_provider_validates_known_billing_breakdown() { - let bundle = provider_xai::initialize(provider_ports()) - .await - .expect("xAI bundle"); - let admin = bundle.admin_provider(); - let profile = admin.dashboard_wire_profile().expect("wire profile"); - assert_eq!(profile.provider, "xai"); - assert_eq!(profile.product, "Grok Build"); - assert_eq!(profile.version, "1.0.13"); - assert_eq!(profile.user_agent, "grok-shell/1.0.13 (linux; x86_64)"); - let release = profile.release.expect("release status"); - assert_eq!(release.status, DesktopReleaseStatus::Unchecked); - assert!(release.checked_at.is_none()); - - let billing = admin - .calculated_billing(&ProviderBillingInput { - upstream_model_id: "grok-4.5".to_owned(), - service_tier: None, - input_tokens: Some(100), - output_tokens: Some(10), - cached_input_tokens: Some(25), - cache_write_input_tokens: Some(0), - total: CurrencyCost { - currency: "USD".to_owned(), - amount: "0.0002175".parse().expect("amount"), - }, - }) - .expect("billing") - .expect("known pricing"); - - assert_eq!(billing.total_amount.amount.as_str(), "0.0002175"); - assert_eq!(billing.input_price_per_million.amount.as_str(), "2"); - assert_eq!(billing.output_price_per_million.amount.as_str(), "6"); - - let priority = admin - .calculated_billing(&ProviderBillingInput { - upstream_model_id: "grok-4.6".to_owned(), - service_tier: Some("priority".to_owned()), - input_tokens: Some(100), - output_tokens: Some(10), - cached_input_tokens: Some(20), - cache_write_input_tokens: Some(0), - total: CurrencyCost { - currency: "USD".to_owned(), - amount: "0.00046".parse().expect("amount"), - }, - }) - .expect("计费明细") - .expect("已知的 Priority 价格"); - assert_eq!(priority.service_tier.as_deref(), Some("priority")); - assert_eq!(priority.standard_amount.amount.as_str(), "0.00023"); - assert_eq!(priority.input_price_per_million.amount.as_str(), "4"); - assert_eq!(priority.multiplier_percent, 200); -} - -#[tokio::test] -async fn xai_legacy_billing_should_not_infer_long_context_flag() { - let bundle = provider_xai::initialize(provider_ports()) - .await - .expect("xAI bundle"); - let billing = bundle - .admin_provider() - .calculated_billing(&ProviderBillingInput { - upstream_model_id: "grok-4.6".to_owned(), - service_tier: None, - input_tokens: Some(200_000), - output_tokens: Some(0), - cached_input_tokens: Some(0), - cache_write_input_tokens: Some(0), - total: CurrencyCost { - currency: "USD".to_owned(), - amount: "0.8".parse().expect("stored total"), - }, - }) - .expect("legacy billing") - .expect("matching billing breakdown"); - - assert_eq!(billing.total_amount.amount.as_str(), "0.8"); - assert_eq!(billing.input_price_per_million.amount.as_str(), "4"); - assert!(!billing.long_context_billing_applied); -} - -#[tokio::test] -async fn xai_admin_provider_restores_full_pending_envelope_and_binds_owner() { - let pending = Arc::new(TestOAuthPending::default()); - let bundle = provider_xai::initialize(provider_ports_with( - Arc::new(MemoryProviderAccountStore::default()), - Arc::clone(&pending), - )) - .await - .expect("xAI bundle"); - let owner = MutationContext { - actor: MutationActor::AdminSession { - admin_user_id: "admin-owner".to_owned(), - }, - request_id: "request-start".to_owned(), - }; - let flow_id = "pending-envelope"; - let owner_ref = admin_session_owner_ref("admin-owner"); - let payload = pending_payload(flow_id, &owner_ref); - pending.insert(flow_id, owner_ref, payload); - - let wrong_owner = bundle - .admin_provider() - .complete_authorization(CompleteAuthorization { - settings: None, - context: MutationContext { - actor: MutationActor::AdminSession { - admin_user_id: "different-owner".to_owned(), - }, - request_id: "request-complete".to_owned(), - }, - flow_id: flow_id.to_owned(), - callback_url: format!( - "{}?code=unused&state=wrong-owner", - provider_xai::OFFICIAL_REDIRECT_URI - ), - }) - .await - .expect_err("wrong owner"); - assert_eq!(wrong_owner.kind(), ProviderAdminErrorKind::NotFound); - assert_eq!(pending.len(), 1); - - let invalid_callback = bundle - .admin_provider() - .complete_authorization(CompleteAuthorization { - settings: None, - context: owner, - flow_id: flow_id.to_owned(), - callback_url: format!( - "{}?code=unused&state=invalid-state", - provider_xai::OFFICIAL_REDIRECT_URI - ), - }) - .await - .expect_err("restored pending must validate callback state"); - assert_eq!(invalid_callback.kind(), ProviderAdminErrorKind::Invalid); - assert_eq!(pending.len(), 1); - - let mismatched_flow = "pending-envelope-mismatch"; - let owner_ref = admin_session_owner_ref("admin-owner"); - pending.insert( - mismatched_flow, - owner_ref.clone(), - pending_payload("different-envelope", &owner_ref), - ); - let mismatched_envelope = bundle - .admin_provider() - .complete_authorization(CompleteAuthorization { - settings: None, - context: MutationContext { - actor: MutationActor::AdminSession { - admin_user_id: "admin-owner".to_owned(), - }, - request_id: "request-complete-mismatch".to_owned(), - }, - flow_id: mismatched_flow.to_owned(), - callback_url: format!( - "{}?code=unused&state=invalid-state", - provider_xai::OFFICIAL_REDIRECT_URI - ), - }) - .await - .expect_err("flow binding mismatch"); - assert_eq!(mismatched_envelope.kind(), ProviderAdminErrorKind::Invalid); - assert_eq!(pending.len(), 2); -} - -#[tokio::test] -async fn xai_admin_provider_projects_cached_quota_models_and_canonical_export() { - let store = Arc::new(MemoryProviderAccountStore::default()); - let input = create_input("admin_projection", "subject-admin-projection"); - seed_input(&store, &input).await.expect("create account"); - let account = store.account(&input.account_id).expect("stored account"); - let mut record = account_record(&account); - let proxy = - gateway_core::account::OutboundProxy::parse("socks5h://user:pass@proxy.example:1080") - .unwrap(); - record.outbound_proxy = Some(proxy.clone()); - let catalog_cache = Arc::new(TestCatalogCache::default()); - catalog_cache.seed("plan:standard", ["grok-4.5"]); - let bundle = provider_xai::initialize(provider_ports_with_catalog( - Arc::clone(&store), - Arc::new(TestOAuthPending::default()), - catalog_cache, - )) - .await - .expect("xAI bundle"); - let admin = bundle.admin_provider(); - - let operation = admin - .connection_test_operation( - &UpstreamModelId::new("grok-4.5").expect("upstream model"), - "Reply with exactly OK.", - ) - .await - .expect("connection test operation"); - let Operation::Generate(request) = operation else { - panic!("connection test must be a generate operation"); - }; - let encoded = provider_xai::GrokResponsesRequest::encode( - &request, - "grok-4.5", - &ClientApiKeyId::new("admin_connection_test").expect("client key"), - ) - .expect("official xAI request"); - assert_eq!( - encoded.body().get("model").and_then(Value::as_str), - Some("grok-4.5") - ); - assert_eq!( - encoded.body().get("stream").and_then(Value::as_bool), - Some(true) - ); - - let rolling_usage = AccountUsage { - account_id: account.id().to_string(), - request_count: 5, - success_count: 5, - input_tokens: Some(100), - output_tokens: Some(20), - cached_input_tokens: Some(80), - cache_write_input_tokens: None, - reasoning_output_tokens: None, - image_input_tokens: None, - image_output_tokens: None, - image_request_count: 0, - image_request_failed_count: 0, - total_tokens: Some(120), - cost_coverage: Default::default(), - costs: Vec::new(), - last_used_at: Some(Utc::now()), - request_buckets: Vec::new(), - models: Vec::new(), - }; - let quota = admin - .quota(ProviderQuotaRequest { - account_id: account.id().clone(), - refresh: false, - rolling_usage: Some(rolling_usage.clone()), - }) - .await - .expect("cached quota"); - assert_eq!(quota.windows.len(), 1); - assert!(quota.observed_at.is_none()); - assert!(quota.plan_type.is_none()); - assert_eq!(quota.windows[0].window_seconds, Some(86_400)); - assert_eq!(quota.windows[0].local_usage.as_ref(), Some(&rolling_usage)); - assert_eq!( - quota.usage_window().map(|(_, period)| period), - Some(AccountUsagePeriod::Daily) - ); - store - .compare_and_swap_quota(gateway_core::account::QuotaObservation { - quota_pause: None, - expected_connection: None, - plan_type: None, - account_id: account.id().clone(), - expected_revision: account.revision(), - quota: OpaqueProviderData::new( - serde_json::from_value(serde_json::json!({ - "subscriptionTier": "Free", - "config": { - "creditUsagePercent": 25, - "onDemandCap": {"val": 500}, - "onDemandUsed": {"val": 100}, - "prepaidBalance": {"val": -500} - } - })) - .expect("quota document"), - ), - observed_at: SystemTime::now(), - state: account.quota(), - }) - .await - .expect("store subscription snapshot"); - let quota = admin - .quota(ProviderQuotaRequest { - account_id: account.id().clone(), - refresh: false, - rolling_usage: None, - }) - .await - .expect("cached subscription"); - assert_eq!(quota.plan_type.as_deref(), Some("Free")); - assert_eq!(quota.windows.len(), 1); - assert_eq!(quota.windows[0].used_percent, Some(25.0)); - let window_data = quota.windows[0] - .provider_data - .as_ref() - .expect("quota details") - .expose_to_provider() - .expose_to_provider(); - assert_eq!(window_data["onDemandCapCents"], 500); - assert_eq!(window_data["onDemandUsedCents"], 100); - assert_eq!(window_data["prepaidBalanceCents"], -500); - let models = admin - .models(account.id(), false) - .await - .expect("cached models"); - assert_eq!(models.models[0].id.as_str(), "grok-4.5"); - let loaded = store - .load_credential(account.id(), account.revision()) - .await - .expect("loaded credential"); - let exported = admin - .export_credentials(vec![ProviderExportCredentialInput { - account: record, - provider_material: ProviderDocument::new(OpaqueProviderData::new( - loaded.credential.into_inner(), - )), - }]) - .await - .expect("canonical export"); - assert_eq!(exported.account_ids, vec![input.account_id]); - let document = exported.document.expose_to_provider().expose_to_provider(); - assert_eq!(document.get("version").and_then(Value::as_u64), Some(1)); - assert_eq!( - document.get("type").and_then(Value::as_str), - Some("oauth-account-bundle") - ); - let entries = - provider_xai::GrokOAuthImportDocument::parse_json(&serde_json::to_vec(document).unwrap()) - .unwrap() - .into_entries(); - assert_eq!(entries.len(), 1); - assert_eq!(entries[0].outbound_proxy(), Some(&proxy)); -} - -#[tokio::test] -async fn xai_admin_provider_rejects_unprepared_mutations_before_store_commit() { - let store = Arc::new(MemoryProviderAccountStore::default()); - let input = create_input("admin_invalid", "subject-admin-invalid"); - seed_input(&store, &input).await.expect("create account"); - let account = store.account(&input.account_id).expect("stored account"); - let record = account_record(&account); - let bundle = provider_xai::initialize(provider_ports_with( - store, - Arc::new(TestOAuthPending::default()), - )) - .await - .expect("xAI bundle"); - let admin = bundle.admin_provider(); - - let import_error = admin - .prepare_import(PrepareCredentialImport { - default_outbound_proxy: None, - document: ProviderDocument::new(OpaqueProviderData::new(Map::new())), - }) - .await - .expect_err("invalid import"); - assert_eq!(import_error.kind(), ProviderAdminErrorKind::Invalid); - let rotation_error = admin - .prepare_rotation(PrepareCredentialRotation { - account: record.clone(), - provider_material: ProviderDocument::new(OpaqueProviderData::new(Map::new())), - }) - .await - .expect_err("invalid rotation"); - assert_eq!(rotation_error.kind(), ProviderAdminErrorKind::Invalid); - let mut missing = record; - missing.id = "acct_admin_missing".to_owned(); - let refresh_error = admin - .prepare_refresh(PrepareCredentialRefresh { account: missing }) - .await - .expect_err("missing refresh target"); - assert_eq!(refresh_error.kind(), ProviderAdminErrorKind::NotFound); -} - fn pending_payload(flow_id: &str, owner_ref: &str) -> OpaqueProviderData { let config = GrokOAuthConfig::official().expect("official config"); let discovery = DiscoveryDocument::parse( &config, - include_bytes!("credential/fixtures/discovery.json"), + include_bytes!("../credential/fixtures/discovery.json"), ) .expect("discovery fixture"); let redirect = RedirectUriAllowlist::new([provider_xai::OFFICIAL_REDIRECT_URI]) @@ -739,7 +151,7 @@ fn provider_ports_with_catalog( ProviderStorePorts::new( accounts, Arc::new(TestLeases), - Arc::new(TestSessionAffinity), + Arc::new(TestSessionAffinity::default()), Arc::new(TestSessionExclusions), catalog_cache, Arc::new(TestArtifactProfiles), @@ -1226,7 +638,7 @@ mod errors { .await .unwrap(); let error = bundle - .admin_provider() + .admin .prepare_refresh(PrepareCredentialRefresh { account }) .await .unwrap_err(); @@ -1267,7 +679,7 @@ mod errors { let ports = ProviderStorePorts::new( store.clone(), Arc::new(BusyRefreshLeases), - Arc::new(TestSessionAffinity), + Arc::new(TestSessionAffinity::default()), Arc::new(TestSessionExclusions), Arc::new(TestCatalogCache::default()), Arc::new(TestArtifactProfiles), @@ -1279,7 +691,7 @@ mod errors { ); let bundle = provider_xai::initialize(ports).await.unwrap(); let error = bundle - .admin_provider() + .admin .prepare_refresh(PrepareCredentialRefresh { account }) .await .unwrap_err(); @@ -1310,7 +722,7 @@ mod errors { .await .unwrap(); let error = bundle - .admin_provider() + .admin .prepare_refresh(PrepareCredentialRefresh { account }) .await .unwrap_err(); @@ -1352,40 +764,6 @@ mod errors { } } -#[tokio::test] -async fn client_profile_preview_and_dashboard_use_saved_configuration() { - use provider_xai::transport::client_profile::{GrokClientProfileSelection, VersionMode}; - let bundle = provider_xai::initialize(provider_ports()).await.unwrap(); - let admin = bundle.admin_provider(); - let options = admin.client_profile_options().unwrap(); - assert_eq!( - options.expose_to_provider()["defaults"]["versionMode"], - "latest" - ); - let selection = GrokClientProfileSelection { - version_mode: VersionMode::Fixed, - client_version: Some("8.7.6".to_owned()), - target_os: "windows".to_owned(), - target_arch: "arm64".to_owned(), - ..Default::default() - }; - let configuration = selection.document().unwrap(); - let preview = admin.preview_client_profile(&configuration).unwrap(); - assert_eq!(preview.expose_to_provider()["clientVersion"], "8.7.6"); - assert_eq!(preview.expose_to_provider()["versionSource"], "custom"); - assert!(preview.expose_to_provider()["verifiedAt"].is_null()); - let dashboard = admin.configured_wire_profile(&configuration).unwrap(); - assert_eq!(dashboard.version, "8.7.6"); - assert_eq!(dashboard.target.os_type, "windows"); - assert_eq!(dashboard.target.arch, "arm64"); - assert_eq!( - dashboard.user_agent, - preview.expose_to_provider()["userAgent"].as_str().unwrap() - ); - assert!(dashboard.release.is_none()); - assert!(dashboard.verified_at.is_none()); -} - #[derive(Default)] struct RecordingDiagnostics(std::sync::Mutex>); #[async_trait::async_trait] @@ -1398,26 +776,3 @@ impl gateway_core::diagnostics::OperationalDiagnostics for RecordingDiagnostics Ok(()) } } - -#[tokio::test] -async fn usage_quote_reuses_native_priority_prices() { - use gateway_admin::ports::provider::ProviderUsagePricingInput; - use gateway_core::metering::Usage; - let bundle = provider_xai::initialize(provider_ports()).await.unwrap(); - let admin = bundle.admin_provider(); - let input = ProviderUsagePricingInput { - upstream_model_id: "grok-4.5".into(), - service_tier: Some("priority".into()), - usage: Usage { - input_tokens: Some(100), - output_tokens: Some(10), - cached_input_tokens: Some(25), - cache_write_input_tokens: Some(0), - image_input_tokens: Some(0), - image_output_tokens: Some(0), - ..Default::default() - }, - }; - let price = admin.evaluate_usage_pricing(&input, None).unwrap().unwrap(); - assert_eq!(price.total_amount().amount().canonical(), "0.000435"); -} diff --git a/backend/crates/providers/xai/tests/admin/provider.rs b/backend/crates/providers/xai/tests/admin/provider.rs new file mode 100644 index 000000000..6eee75d05 --- /dev/null +++ b/backend/crates/providers/xai/tests/admin/provider.rs @@ -0,0 +1,632 @@ +//! 验证 ProviderAdmin 端口的授权、账号和管理合同 + +use super::*; + +#[tokio::test] +async fn account_unavailable_clears_real_selector_cooldowns_only_for_deleted_account() { + let store = MemoryProviderAccountStore::shared(); + let cooldowns = Arc::new(MemoryCooldownPort::default()); + let ports = ProviderStorePorts::new( + store.clone(), + Arc::new(TestLeases), + Arc::new(TestSessionAffinity::default()), + Arc::new(TestSessionExclusions), + Arc::new(TestCatalogCache::default()), + Arc::new(TestArtifactProfiles), + Arc::new(TestCredentialState), + cooldowns.clone(), + Arc::new(TestRuntimePolicy), + Arc::new(TestOAuthPending::default()), + Arc::new(RecordingDiagnostics::default()), + ); + let repository = GrokCredentialRepository::new(store.clone()); + let selector = GrokAccountSessionSelector::new( + ProviderKind::new("xai").unwrap(), + repository.clone(), + MemoryGrokCatalogCache::shared(), + Arc::new(crate::support::grok_quota_service( + repository, + Arc::new( + ReqwestGrokModelCatalogTransport::new(Arc::new(OfficialGrokEndpointPolicy)) + .unwrap(), + ), + )), + ports.leases(), + cooldowns.clone(), + ports.account_feedback(), + Arc::new(crate::support::TestSessionAffinity::default()), + ); + let bundle = provider_xai::initialize(ports).await.unwrap(); + let models = ["grok-4.5", "grok-4.6"].map(|id| UpstreamModelId::new(id).unwrap()); + for suffix in ["deleted-cooldown", "retained-cooldown"] { + let input = create_input(suffix, &format!("subject-{suffix}")); + seed_input(&store, &input).await.unwrap(); + let session = SelectedGrokSession::new( + input.account_id, + CredentialRevision::new(1).unwrap(), + input.secret.access_token, + SecretValue::new(input.account.subject), + None, + GrokSessionBinding::new(suffix).unwrap(), + (), + ) + .unwrap(); + // cooldown 必须来自生产 selector 对真实反馈类型的处理,不能由 mock 手工伪造 + selector + .record_failure( + &session, + GrokCredentialFailure::RateLimited { + retry_after: Some(Duration::from_secs(60)), + }, + ) + .await; + for model in &models { + selector + .record_failure( + &session, + GrokCredentialFailure::ModelQuotaExhausted { + upstream_model: model.clone(), + retry_after: None, + }, + ) + .await; + assert!( + cooldowns + .scoped_cooldown( + session.account_id(), + &ProviderCooldownScope::upstream_model(model.clone()) + ) + .is_some() + ); + } + assert!(cooldowns.cooldown(session.account_id()).is_some()); + } + let deleted = account_id("deleted-cooldown"); + store.delete_account(&deleted).await.unwrap(); + bundle.admin.account_unavailable(&deleted).await; + assert!(cooldowns.cooldown(&deleted).is_none()); + let retained = account_id("retained-cooldown"); + assert!(cooldowns.cooldown(&retained).is_some()); + for model in models { + let scope = ProviderCooldownScope::upstream_model(model); + assert!(cooldowns.scoped_cooldown(&deleted, &scope).is_none()); + assert!(cooldowns.scoped_cooldown(&retained, &scope).is_some()); + } +} + +#[tokio::test] +async fn xai_bundle_exposes_core_admin_and_drains_worker_contributions_once() { + let mut bundle = provider_xai::initialize(provider_ports()) + .await + .expect("xAI bundle"); + + assert_eq!(bundle.core.clone().name(), "xai"); + assert_eq!(bundle.admin.provider_kind().as_str(), "xai"); + let contributions = std::mem::take(&mut bundle.workers); + assert_eq!(contributions.len(), 3); + assert!( + contributions + .iter() + .any(|item| item.kind() == WorkerKind::OAuthRefresh) + ); + assert!( + contributions + .iter() + .any(|item| item.kind() == WorkerKind::QuotaCatalogHealth) + ); + assert!(std::mem::take(&mut bundle.workers).is_empty()); +} + +#[tokio::test] +async fn xai_quota_catalog_worker_treats_empty_account_pool_as_idle() { + let mut bundle = provider_xai::initialize(provider_ports()) + .await + .expect("xAI bundle"); + + run_quota_catalog_cycle(&mut bundle) + .await + .expect("idle quota cycle"); +} + +#[tokio::test] +async fn xai_quota_catalog_worker_preserves_store_failures() { + let store = Arc::new(MemoryProviderAccountStore::default()); + store.fail_provider_listing(); + let mut bundle = provider_xai::initialize(provider_ports_with( + store, + Arc::new(TestOAuthPending::default()), + )) + .await + .expect("xAI bundle"); + + let error = run_quota_catalog_cycle(&mut bundle) + .await + .expect_err("Provider account Store failure"); + assert_eq!(error.as_safe_str(), "账号列表读取失败"); +} + +#[tokio::test] +async fn xai_quota_catalog_worker_retains_both_failure_stages_and_finishes_the_batch() { + for refresh_due in [true, false] { + let store = MemoryProviderAccountStore::shared(); + for suffix in ["broken_one", "broken_two"] { + let mut input = create_input(suffix, "synthetic-subject"); + input.enabled = suffix == "broken_one"; + let mut account = crate::support::prepare_input(&input).unwrap(); + // 模拟历史持久化凭据损坏,额度与目录读取均应保留各自的失败分类 + account.credential = gateway_core::account::PlaintextCredential::new(Map::new()); + let revision = account.account.revision(); + store.create_account(account).await.unwrap(); + if refresh_due { + store + .apply_quota_access(gateway_core::account::QuotaAccessChange { + account_id: input.account_id, + expected_revision: revision, + state: gateway_core::account::QuotaState::exhausted( + gateway_core::account::QuotaEvidence::ProviderDenied, + SystemTime::UNIX_EPOCH, + None, + ), + }) + .await + .unwrap(); + } + } + let mut bundle = provider_xai::initialize(provider_ports_with( + store, + Arc::new(TestOAuthPending::default()), + )) + .await + .unwrap(); + + let error = run_quota_catalog_cycle(&mut bundle) + .await + .expect_err("invalid stored credentials"); + assert_eq!(error.as_safe_str(), "额度或模型目录同步失败"); + let details = error.error_details().expect("synchronization causes"); + let details: Value = serde_json::from_str(details.as_str()).unwrap(); + let cause = details["causes"]["messages"][0].as_str().unwrap(); + assert!( + cause.contains("catalog error: Grok provider account store is unavailable"), + "{cause}" + ); + if refresh_due { + assert!(cause.contains("quota failures=2"), "{cause}"); + assert!( + cause + .contains("first quota error: xAI quota credential or billing data is invalid"), + "{cause}" + ); + } else { + assert!(cause.contains("quota failures=0"), "{cause}"); + assert!(!cause.contains("first quota error"), "{cause}"); + } + } +} + +#[tokio::test] +async fn xai_admin_provider_validates_known_billing_breakdown() { + let bundle = provider_xai::initialize(provider_ports()) + .await + .expect("xAI bundle"); + let admin = bundle.admin.clone(); + let profile = admin.dashboard_wire_profile().expect("wire profile"); + assert_eq!(profile.provider, "xai"); + assert_eq!(profile.product, "Grok Build"); + assert_eq!(profile.version, "1.0.13"); + assert_eq!(profile.user_agent, "grok-shell/1.0.13 (linux; x86_64)"); + let release = profile.release.expect("release status"); + assert_eq!(release.status, DesktopReleaseStatus::Unchecked); + assert!(release.checked_at.is_none()); + + let billing = admin + .calculated_billing(&ProviderBillingInput { + upstream_model_id: "grok-4.5".to_owned(), + service_tier: None, + input_tokens: Some(100), + output_tokens: Some(10), + cached_input_tokens: Some(25), + cache_write_input_tokens: Some(0), + total: CurrencyCost { + currency: "USD".to_owned(), + amount: "0.0002175".parse().expect("amount"), + }, + }) + .expect("billing") + .expect("known pricing"); + + assert_eq!(billing.total_amount.amount.as_str(), "0.0002175"); + assert_eq!(billing.input_price_per_million.amount.as_str(), "2"); + assert_eq!(billing.output_price_per_million.amount.as_str(), "6"); + + let priority = admin + .calculated_billing(&ProviderBillingInput { + upstream_model_id: "grok-4.6".to_owned(), + service_tier: Some("priority".to_owned()), + input_tokens: Some(100), + output_tokens: Some(10), + cached_input_tokens: Some(20), + cache_write_input_tokens: Some(0), + total: CurrencyCost { + currency: "USD".to_owned(), + amount: "0.00046".parse().expect("amount"), + }, + }) + .expect("计费明细") + .expect("已知的 Priority 价格"); + assert_eq!(priority.service_tier.as_deref(), Some("priority")); + assert_eq!(priority.standard_amount.amount.as_str(), "0.00023"); + assert_eq!(priority.input_price_per_million.amount.as_str(), "4"); + assert_eq!(priority.multiplier_percent, 200); +} + +#[tokio::test] +async fn xai_legacy_billing_should_not_infer_long_context_flag() { + let bundle = provider_xai::initialize(provider_ports()) + .await + .expect("xAI bundle"); + let billing = bundle + .admin + .calculated_billing(&ProviderBillingInput { + upstream_model_id: "grok-4.6".to_owned(), + service_tier: None, + input_tokens: Some(200_000), + output_tokens: Some(0), + cached_input_tokens: Some(0), + cache_write_input_tokens: Some(0), + total: CurrencyCost { + currency: "USD".to_owned(), + amount: "0.8".parse().expect("stored total"), + }, + }) + .expect("legacy billing") + .expect("matching billing breakdown"); + + assert_eq!(billing.total_amount.amount.as_str(), "0.8"); + assert_eq!(billing.input_price_per_million.amount.as_str(), "4"); + assert!(!billing.long_context_billing_applied); +} + +#[tokio::test] +async fn xai_admin_provider_restores_full_pending_envelope_and_binds_owner() { + let pending = Arc::new(TestOAuthPending::default()); + let bundle = provider_xai::initialize(provider_ports_with( + Arc::new(MemoryProviderAccountStore::default()), + Arc::clone(&pending), + )) + .await + .expect("xAI bundle"); + let owner = MutationContext { + actor: MutationActor::AdminSession { + admin_user_id: "admin-owner".to_owned(), + }, + request_id: "request-start".to_owned(), + }; + let flow_id = "pending-envelope"; + let owner_ref = admin_session_owner_ref("admin-owner"); + let payload = pending_payload(flow_id, &owner_ref); + pending.insert(flow_id, owner_ref, payload); + + let wrong_owner = bundle + .admin + .complete_authorization(CompleteAuthorization { + settings: None, + context: MutationContext { + actor: MutationActor::AdminSession { + admin_user_id: "different-owner".to_owned(), + }, + request_id: "request-complete".to_owned(), + }, + flow_id: flow_id.to_owned(), + callback_url: format!( + "{}?code=unused&state=wrong-owner", + provider_xai::OFFICIAL_REDIRECT_URI + ), + }) + .await + .expect_err("wrong owner"); + assert_eq!(wrong_owner.kind(), ProviderAdminErrorKind::NotFound); + assert_eq!(pending.len(), 1); + + let invalid_callback = bundle + .admin + .complete_authorization(CompleteAuthorization { + settings: None, + context: owner, + flow_id: flow_id.to_owned(), + callback_url: format!( + "{}?code=unused&state=invalid-state", + provider_xai::OFFICIAL_REDIRECT_URI + ), + }) + .await + .expect_err("restored pending must validate callback state"); + assert_eq!(invalid_callback.kind(), ProviderAdminErrorKind::Invalid); + assert_eq!(pending.len(), 1); + + let mismatched_flow = "pending-envelope-mismatch"; + let owner_ref = admin_session_owner_ref("admin-owner"); + pending.insert( + mismatched_flow, + owner_ref.clone(), + pending_payload("different-envelope", &owner_ref), + ); + let mismatched_envelope = bundle + .admin + .complete_authorization(CompleteAuthorization { + settings: None, + context: MutationContext { + actor: MutationActor::AdminSession { + admin_user_id: "admin-owner".to_owned(), + }, + request_id: "request-complete-mismatch".to_owned(), + }, + flow_id: mismatched_flow.to_owned(), + callback_url: format!( + "{}?code=unused&state=invalid-state", + provider_xai::OFFICIAL_REDIRECT_URI + ), + }) + .await + .expect_err("flow binding mismatch"); + assert_eq!(mismatched_envelope.kind(), ProviderAdminErrorKind::Invalid); + assert_eq!(pending.len(), 2); +} + +#[tokio::test] +async fn xai_admin_provider_projects_cached_quota_models_and_canonical_export() { + let store = Arc::new(MemoryProviderAccountStore::default()); + let input = create_input("admin_projection", "subject-admin-projection"); + seed_input(&store, &input).await.expect("create account"); + let account = store.account(&input.account_id).expect("stored account"); + let mut record = account_record(&account); + let proxy = + gateway_core::account::OutboundProxy::parse("socks5h://user:pass@proxy.example:1080") + .unwrap(); + record.outbound_proxy = Some(proxy.clone()); + let catalog_cache = Arc::new(TestCatalogCache::default()); + catalog_cache.seed("plan:standard", ["grok-4.5"]); + let bundle = provider_xai::initialize(provider_ports_with_catalog( + Arc::clone(&store), + Arc::new(TestOAuthPending::default()), + catalog_cache, + )) + .await + .expect("xAI bundle"); + let admin = bundle.admin.clone(); + + let operation = admin + .connection_test_operation( + &UpstreamModelId::new("grok-4.5").expect("upstream model"), + "Reply with exactly OK.", + ) + .await + .expect("connection test operation"); + let Operation::Generate(request) = operation else { + panic!("connection test must be a generate operation"); + }; + let encoded = provider_xai::GrokResponsesRequest::encode( + &request, + "grok-4.5", + &ClientApiKeyId::new("admin_connection_test").expect("client key"), + ) + .expect("official xAI request"); + assert_eq!( + encoded.body().get("model").and_then(Value::as_str), + Some("grok-4.5") + ); + assert_eq!( + encoded.body().get("stream").and_then(Value::as_bool), + Some(true) + ); + + let rolling_usage = AccountUsage { + account_id: account.id().to_string(), + request_count: 5, + success_count: 5, + input_tokens: Some(100), + output_tokens: Some(20), + cached_input_tokens: Some(80), + cache_write_input_tokens: None, + reasoning_output_tokens: None, + image_input_tokens: None, + image_output_tokens: None, + image_request_count: 0, + image_request_failed_count: 0, + total_tokens: Some(120), + cost_coverage: Default::default(), + costs: Vec::new(), + last_used_at: Some(Utc::now()), + request_buckets: Vec::new(), + models: Vec::new(), + }; + let quota = admin + .quota(ProviderQuotaRequest { + account_id: account.id().clone(), + refresh: false, + rolling_usage: Some(rolling_usage.clone()), + }) + .await + .expect("cached quota"); + assert_eq!(quota.windows.len(), 1); + assert!(quota.observed_at.is_none()); + assert!(quota.plan_type.is_none()); + assert_eq!(quota.windows[0].window_seconds, Some(86_400)); + assert_eq!(quota.windows[0].local_usage.as_ref(), Some(&rolling_usage)); + assert_eq!( + quota.usage_window().map(|(_, period)| period), + Some(AccountUsagePeriod::Daily) + ); + store + .compare_and_swap_quota(gateway_core::account::QuotaObservation { + quota_pause: None, + expected_connection: None, + plan_type: None, + account_id: account.id().clone(), + expected_revision: account.revision(), + quota: OpaqueProviderData::new( + serde_json::from_value(serde_json::json!({ + "subscriptionTier": "Free", + "config": { + "creditUsagePercent": 25, + "onDemandCap": {"val": 500}, + "onDemandUsed": {"val": 100}, + "prepaidBalance": {"val": -500} + } + })) + .expect("quota document"), + ), + observed_at: SystemTime::now(), + state: account.quota(), + }) + .await + .expect("store subscription snapshot"); + let quota = admin + .quota(ProviderQuotaRequest { + account_id: account.id().clone(), + refresh: false, + rolling_usage: None, + }) + .await + .expect("cached subscription"); + assert_eq!(quota.plan_type.as_deref(), Some("Free")); + assert_eq!(quota.windows.len(), 1); + assert_eq!(quota.windows[0].used_percent, Some(25.0)); + let window_data = quota.windows[0] + .provider_data + .as_ref() + .expect("quota details") + .expose_to_provider() + .expose_to_provider(); + assert_eq!(window_data["onDemandCapCents"], 500); + assert_eq!(window_data["onDemandUsedCents"], 100); + assert_eq!(window_data["prepaidBalanceCents"], -500); + let models = admin + .models(account.id(), false) + .await + .expect("cached models"); + assert_eq!(models.models[0].id.as_str(), "grok-4.5"); + let loaded = store + .load_credential(account.id(), account.revision()) + .await + .expect("loaded credential"); + let exported = admin + .export_credentials(vec![ProviderExportCredentialInput { + account: record, + provider_material: ProviderDocument::new(OpaqueProviderData::new( + loaded.credential.into_inner(), + )), + }]) + .await + .expect("canonical export"); + assert_eq!(exported.account_ids, vec![input.account_id]); + let document = exported.document.expose_to_provider().expose_to_provider(); + assert_eq!(document.get("version").and_then(Value::as_u64), Some(1)); + assert_eq!( + document.get("type").and_then(Value::as_str), + Some("oauth-account-bundle") + ); + let entries = + provider_xai::GrokOAuthImportDocument::parse_json(&serde_json::to_vec(document).unwrap()) + .unwrap() + .into_entries(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].outbound_proxy(), Some(&proxy)); +} + +#[tokio::test] +async fn xai_admin_provider_rejects_unprepared_mutations_before_store_commit() { + let store = Arc::new(MemoryProviderAccountStore::default()); + let input = create_input("admin_invalid", "subject-admin-invalid"); + seed_input(&store, &input).await.expect("create account"); + let account = store.account(&input.account_id).expect("stored account"); + let record = account_record(&account); + let bundle = provider_xai::initialize(provider_ports_with( + store, + Arc::new(TestOAuthPending::default()), + )) + .await + .expect("xAI bundle"); + let admin = bundle.admin.clone(); + + let import_error = admin + .prepare_import(PrepareCredentialImport { + default_outbound_proxy: None, + document: ProviderDocument::new(OpaqueProviderData::new(Map::new())), + }) + .await + .expect_err("invalid import"); + assert_eq!(import_error.kind(), ProviderAdminErrorKind::Invalid); + let rotation_error = admin + .prepare_rotation(PrepareCredentialRotation { + account: record.clone(), + provider_material: ProviderDocument::new(OpaqueProviderData::new(Map::new())), + }) + .await + .expect_err("invalid rotation"); + assert_eq!(rotation_error.kind(), ProviderAdminErrorKind::Invalid); + let mut missing = record; + missing.id = "acct_admin_missing".to_owned(); + let refresh_error = admin + .prepare_refresh(PrepareCredentialRefresh { account: missing }) + .await + .expect_err("missing refresh target"); + assert_eq!(refresh_error.kind(), ProviderAdminErrorKind::NotFound); +} + +#[tokio::test] +async fn client_profile_preview_and_dashboard_use_saved_configuration() { + use provider_xai::profile::selection::{GrokClientProfileSelection, VersionMode}; + let bundle = provider_xai::initialize(provider_ports()).await.unwrap(); + let admin = bundle.admin.clone(); + let options = admin.client_profile_options().unwrap(); + assert_eq!( + options.expose_to_provider()["defaults"]["versionMode"], + "latest" + ); + let selection = GrokClientProfileSelection { + version_mode: VersionMode::Fixed, + client_version: Some("8.7.6".to_owned()), + target_os: "windows".to_owned(), + target_arch: "arm64".to_owned(), + ..Default::default() + }; + let configuration = selection.document().unwrap(); + let preview = admin.preview_client_profile(&configuration).unwrap(); + assert_eq!(preview.expose_to_provider()["clientVersion"], "8.7.6"); + assert_eq!(preview.expose_to_provider()["versionSource"], "custom"); + assert!(preview.expose_to_provider()["verifiedAt"].is_null()); + let dashboard = admin.configured_wire_profile(&configuration).unwrap(); + assert_eq!(dashboard.version, "8.7.6"); + assert_eq!(dashboard.target.os_type, "windows"); + assert_eq!(dashboard.target.arch, "arm64"); + assert_eq!( + dashboard.user_agent, + preview.expose_to_provider()["userAgent"].as_str().unwrap() + ); + assert!(dashboard.release.is_none()); + assert!(dashboard.verified_at.is_none()); +} + +#[tokio::test] +async fn usage_quote_reuses_native_priority_prices() { + use gateway_admin::ports::provider::ProviderUsagePricingInput; + use gateway_core::metering::Usage; + let bundle = provider_xai::initialize(provider_ports()).await.unwrap(); + let admin = bundle.admin.clone(); + let input = ProviderUsagePricingInput { + upstream_model_id: "grok-4.5".into(), + service_tier: Some("priority".into()), + usage: Usage { + input_tokens: Some(100), + output_tokens: Some(10), + cached_input_tokens: Some(25), + cache_write_input_tokens: Some(0), + image_input_tokens: Some(0), + image_output_tokens: Some(0), + ..Default::default() + }, + }; + let price = admin.evaluate_usage_pricing(&input, None).unwrap().unwrap(); + assert_eq!(price.total_amount().amount().canonical(), "0.000435"); +} diff --git a/backend/crates/providers/xai/tests/admin/quota.rs b/backend/crates/providers/xai/tests/admin/quota.rs new file mode 100644 index 000000000..a0000e8e8 --- /dev/null +++ b/backend/crates/providers/xai/tests/admin/quota.rs @@ -0,0 +1,25 @@ +//! 验证 xAI 管理端公开的额度能力 + +use super::*; + +#[tokio::test] +async fn account_capabilities_advertise_only_xai_oauth_quota_operations() { + let bundle = provider_xai::initialize(provider_ports()).await.unwrap(); + let provider = bundle.admin.clone(); + let id = ProviderAccountId::new("acct_capabilities").unwrap(); + let oauth = provider.account_capabilities(&id, "oauth"); + assert_eq!( + oauth, + gateway_admin::model::accounts::ProviderAccountCapabilities { + credential_refresh: true, + reauthorize: true, + credential_export: true, + quota: true, + quota_refresh: true, + ..Default::default() + } + ); + for kind in ["api_key", "unknown"] { + assert_eq!(provider.account_capabilities(&id, kind), Default::default()); + } +} diff --git a/backend/crates/providers/xai/tests/billing/calculate.rs b/backend/crates/providers/xai/tests/billing/calculate.rs new file mode 100644 index 000000000..2a2d416fd --- /dev/null +++ b/backend/crates/providers/xai/tests/billing/calculate.rs @@ -0,0 +1,50 @@ +//! xAI 缓存、上下文和 Priority 档位的费用合同 + +use crate::billing::grok_billing_breakdown_with_tier; + +#[test] +fn billing_breakdown_should_preserve_token_components() { + let breakdown = grok_billing_breakdown_with_tier("grok-4.5", 100, 10, 25, None) + .expect("known Grok pricing"); + + assert_eq!(breakdown.input_amount().amount().scaled(), 1_500_000); + assert_eq!(breakdown.cache_read_amount().amount().scaled(), 75_000); + assert_eq!(breakdown.output_amount().amount().scaled(), 600_000); + assert_eq!(breakdown.total_amount().amount().scaled(), 2_175_000); + assert_eq!(breakdown.service_tier(), Some("default")); +} + +#[test] +fn billing_should_price_grok_46_cache_and_priority_at_the_context_boundary() { + // 短、长上下文分别检查普通输入、缓存、输出的单价,Priority 只采用已确认档位 + for (input, tier, expected) in [ + (199_999, None, ["2", "0.5", "6"]), + (200_000, None, ["4", "1", "12"]), + (199_999, Some("priority"), ["4", "1", "12"]), + (200_000, Some("priority"), ["8", "2", "24"]), + ] { + let billing = grok_billing_breakdown_with_tier("grok-4.6", input, 10, 20, tier) + .expect("Grok 4.6 价格"); + let rates = [ + billing.input_price_per_million(), + billing.cache_read_price_per_million(), + billing.output_price_per_million(), + ] + .map(|money| { + money + .amount() + .to_string() + .trim_end_matches('0') + .trim_end_matches('.') + .to_owned() + }); + assert_eq!(rates, expected); + assert_eq!(billing.long_context_billing_applied(), input >= 200_000); + } + assert!(grok_billing_breakdown_with_tier("grok-4.6", 10, 1, 0, Some("future")).is_none()); + let priority = grok_billing_breakdown_with_tier("grok-4.6", 100, 10, 20, Some("priority")) + .expect("Priority 价格"); + assert_eq!(priority.standard_amount().amount().scaled(), 2_300_000); + assert_eq!(priority.total_amount().amount().scaled(), 4_600_000); + assert_eq!(priority.multiplier_percent(), 200); +} diff --git a/backend/crates/providers/xai/tests/billing/mod.rs b/backend/crates/providers/xai/tests/billing/mod.rs new file mode 100644 index 000000000..39b36e988 --- /dev/null +++ b/backend/crates/providers/xai/tests/billing/mod.rs @@ -0,0 +1,3 @@ +//! Provider 计价规则的行为测试 + +mod calculate; diff --git a/backend/crates/providers/xai/tests/credential/contract.rs b/backend/crates/providers/xai/tests/credential/contract.rs index cd995a364..7fbedd98d 100644 --- a/backend/crates/providers/xai/tests/credential/contract.rs +++ b/backend/crates/providers/xai/tests/credential/contract.rs @@ -389,7 +389,7 @@ async fn oauth_bundle_export_is_provider_owned_canonical_and_debug_redacted() { assert_eq!(value["accounts"][0]["credentials"]["idToken"], "id-export"); assert_eq!(value["accounts"][0]["credentials"]["tokenType"], "Bearer"); assert!( - value["accounts"][0]["credentials"]["expiresAt"] + value["accounts"][0]["credentials"]["accessTokenExpiresAt"] .as_str() .is_some() ); @@ -398,26 +398,25 @@ async fn oauth_bundle_export_is_provider_owned_canonical_and_debug_redacted() { provider_xai::OFFICIAL_CLIENT_ID ); assert_eq!( - value["accounts"][0]["credentials"]["scope"], - "openid profile email offline_access grok-cli:access api:access" + value["accounts"][0]["credentials"]["scopes"], + serde_json::json!([ + "openid", + "profile", + "email", + "offline_access", + "grok-cli:access", + "api:access" + ]) ); - for field in [ - "access_token", - "refresh_token", - "id_token", - "token_type", - "expires_at", - "base_url", - "client_id", - ] { - assert!(value["accounts"][0]["credentials"].get(field).is_none()); - } assert_eq!(value["proxies"], serde_json::json!([])); let imported = provider_xai::GrokOAuthImportDocument::parse_json( &serde_json::to_vec(&value).expect("JSON"), ) .expect("re-import exported account"); - assert_eq!(imported.into_entries()[0].model_access(), Some(&policy)); + let entries = imported.into_entries(); + assert_eq!(entries[0].name(), input.name); + assert_eq!(entries[0].email(), input.account.email.as_deref()); + assert_eq!(entries[0].model_access(), Some(&policy)); } #[test] diff --git a/backend/crates/providers/xai/tests/credential/selector.rs b/backend/crates/providers/xai/tests/credential/selector.rs index a9cf56b53..9c65b7f6a 100644 --- a/backend/crates/providers/xai/tests/credential/selector.rs +++ b/backend/crates/providers/xai/tests/credential/selector.rs @@ -101,6 +101,7 @@ struct SelectorFixture { coordinator: Arc, cooldowns: Arc, feedback: Arc, + affinity: Arc, } impl SelectorFixture { @@ -161,6 +162,7 @@ impl SelectorFixture { Arc::new(UnavailableBillingTransport), )); let feedback = Arc::new(AccountFeedbackStats::default()); + let affinity = Arc::new(crate::support::TestSessionAffinity::default()); let selector = GrokAccountSessionSelector::new( gateway_core::routing::ProviderKind::new("xai").expect("provider"), repository.clone(), @@ -169,6 +171,7 @@ impl SelectorFixture { lease_port, cooldowns.clone(), Arc::clone(&feedback), + affinity.clone(), ); Self { store, @@ -177,6 +180,7 @@ impl SelectorFixture { coordinator, cooldowns, feedback, + affinity, } } @@ -1506,3 +1510,217 @@ async fn model_access_excludes_a_required_xai_account_before_acquiring_a_lease() .all(|lease| lease.account_id() == &allowed) ); } + +fn affinity_request( + fixture: &SelectorFixture, + mode: gateway_core::account::AccountAffinity, + queue: bool, +) -> GrokSessionSelection { + use gateway_core::operation::{GenerateRequest, ProtocolPayload}; + let request = fixture.request(BTreeSet::new()); + let body = + serde_json::json!({"model":"grok-4.5", "input":"hello", "prompt_cache_key":"same-session"}); + let generate = GenerateRequest::from_protocol_payload( + ProtocolPayload::json_object( + gateway_protocol::openai::OPENAI_PROTOCOL, + body.as_object().unwrap().clone(), + ) + .unwrap(), + ); + let encoded = provider_xai::GrokResponsesRequest::encode( + &generate, + "grok-4.5", + request.client_api_key_id(), + ) + .unwrap(); + GrokSessionSelection::new( + request.upstream_model().clone(), + BTreeSet::new(), + None, + request + .account_selection_policy() + .with_account_affinity(mode) + .with_session_affinity_ttl(Duration::from_secs(7200)) + .with_queue(gateway_core::concurrency::ConcurrencyQueuePolicy { + max_waiting: u32::from(queue), + timeout: Duration::from_millis(20), + }), + SystemTime::now() + Duration::from_secs(2), + request.account_scope().clone(), + request.client_api_key_id().clone(), + ) + .with_affinity(encoded.affinity().cloned()) +} + +#[tokio::test] +async fn preferred_affinity_keeps_primary_binding_during_temporary_capacity_spillover() { + use gateway_core::account::AccountAffinity; + let fixture = SelectorFixture::new(&["affinity-a", "affinity-b"]).await; + let primary = fixture + .selector + .select(affinity_request( + &fixture, + AccountAffinity::Preferred, + false, + )) + .await + .unwrap(); + let primary_id = primary.account_id().clone(); + fixture + .coordinator + .denied + .lock() + .unwrap() + .insert(primary_id.clone()); + let overflow = fixture + .selector + .select(affinity_request( + &fixture, + AccountAffinity::Preferred, + false, + )) + .await + .unwrap(); + assert_ne!(overflow.account_id(), &primary_id); + { + let bindings = fixture.affinity.bindings.lock().unwrap(); + let (binding, ttl) = bindings.values().next().unwrap(); + assert_eq!(binding.account_id(), &primary_id); + assert_eq!(*ttl, Duration::from_secs(7200)); + } + fixture.coordinator.denied.lock().unwrap().clear(); + let recovered = fixture + .selector + .select(affinity_request( + &fixture, + AccountAffinity::Preferred, + false, + )) + .await + .unwrap(); + assert_eq!(recovered.account_id(), &primary_id); +} + +#[tokio::test] +async fn strict_affinity_waits_for_busy_primary_instead_of_using_a_free_account() { + use gateway_core::account::AccountAffinity; + let fixture = SelectorFixture::new(&["affinity-a", "affinity-b"]).await; + let primary = fixture + .selector + .select(affinity_request(&fixture, AccountAffinity::Strict, true)) + .await + .unwrap(); + fixture + .coordinator + .denied + .lock() + .unwrap() + .insert(primary.account_id().clone()); + let error = fixture + .selector + .select(affinity_request(&fixture, AccountAffinity::Strict, true)) + .await + .err() + .unwrap(); + assert!(matches!( + error, + GrokSessionSelectorError::QueueRejected(gateway_core::concurrency::QueueRejection::Timeout) + )); + assert_eq!( + fixture + .affinity + .claims + .load(std::sync::atomic::Ordering::SeqCst), + 1 + ); +} + +#[tokio::test] +async fn relaxed_affinity_follows_scheduling_and_updates_binding() { + use gateway_core::account::AccountAffinity; + let fixture = SelectorFixture::new(&["affinity-a", "affinity-b"]).await; + let first = fixture + .selector + .select(affinity_request(&fixture, AccountAffinity::Relaxed, false)) + .await + .unwrap(); + fixture + .coordinator + .denied + .lock() + .unwrap() + .insert(first.account_id().clone()); + let next = fixture + .selector + .select(affinity_request(&fixture, AccountAffinity::Relaxed, false)) + .await + .unwrap(); + assert_ne!(first.account_id(), next.account_id()); + assert_eq!( + fixture + .affinity + .bindings + .lock() + .unwrap() + .values() + .next() + .unwrap() + .0 + .account_id(), + next.account_id() + ); +} + +#[tokio::test] +async fn unavailable_primary_migrates_binding_and_conflicted_claim_retries() { + use gateway_core::account::AccountAffinity; + let fixture = SelectorFixture::new(&["affinity-a", "affinity-b"]).await; + let first = fixture + .selector + .select(affinity_request( + &fixture, + AccountAffinity::Preferred, + false, + )) + .await + .unwrap(); + fixture + .store + .set_enabled(first.account_id(), false) + .await + .unwrap(); + fixture + .affinity + .reject_next_claim + .store(true, std::sync::atomic::Ordering::SeqCst); + let next = fixture + .selector + .select(affinity_request( + &fixture, + AccountAffinity::Preferred, + false, + )) + .await + .unwrap(); + assert_ne!(first.account_id(), next.account_id()); + assert_eq!( + fixture + .affinity + .bindings + .lock() + .unwrap() + .values() + .next() + .unwrap() + .0 + .account_id(), + next.account_id() + ); + assert_eq!( + fixture + .affinity + .claims + .load(std::sync::atomic::Ordering::SeqCst), + 3 + ); +} diff --git a/backend/crates/providers/xai/tests/main.rs b/backend/crates/providers/xai/tests/main.rs index da9d1f7f3..aa6c4c3e3 100644 --- a/backend/crates/providers/xai/tests/main.rs +++ b/backend/crates/providers/xai/tests/main.rs @@ -1,8 +1,14 @@ //! xAI Provider、凭据与上游传输的测试入口 mod admin; +#[path = "../src/billing/mod.rs"] +#[allow(dead_code, unused_imports)] +mod billing; +#[path = "billing/mod.rs"] +mod billing_tests; mod credential; mod oauth_http; +mod profile; mod provider; mod secret; mod support; diff --git a/backend/crates/providers/xai/tests/profile/mod.rs b/backend/crates/providers/xai/tests/profile/mod.rs new file mode 100644 index 000000000..892a38482 --- /dev/null +++ b/backend/crates/providers/xai/tests/profile/mod.rs @@ -0,0 +1,52 @@ +//! 测试模块入口与共享夹具 + +use std::collections::VecDeque; +use std::sync::{Arc, Mutex}; + +use chrono::Utc; +use futures::future::BoxFuture; +use provider_xai::{ + GrokCliReleaseError, GrokCliReleaseService, GrokCliReleaseTransport, XaiWireProfile, + XaiWireProfileState, +}; + +struct ReleaseTransport { + outcomes: Mutex>>, +} + +impl ReleaseTransport { + fn new(outcomes: impl IntoIterator>) -> Self { + Self { + outcomes: Mutex::new(outcomes.into_iter().collect()), + } + } +} + +impl GrokCliReleaseTransport for ReleaseTransport { + fn fetch(&self) -> BoxFuture<'_, Result> { + let outcome = self + .outcomes + .lock() + .expect("release outcomes lock") + .pop_front() + .expect("release outcome"); + Box::pin(async move { outcome }) + } +} + +fn wire_profile() -> XaiWireProfileState { + XaiWireProfileState::new(XaiWireProfile { + client_identifier: "grok-shell".to_owned(), + client_version: "0.2.106".to_owned(), + client_mode: "headless".to_owned(), + target_os: "linux".to_owned(), + target_arch: "x86_64".to_owned(), + verified_at: Utc::now(), + }) +} + +mod selection; + +mod state; + +mod release; diff --git a/backend/crates/providers/xai/tests/profile/release.rs b/backend/crates/providers/xai/tests/profile/release.rs new file mode 100644 index 000000000..cc4b87d60 --- /dev/null +++ b/backend/crates/providers/xai/tests/profile/release.rs @@ -0,0 +1,47 @@ +//! 官方发行解析、刷新与原子更新测试 + +use super::*; + +#[tokio::test] +async fn release_refresh_should_update_profile_and_observation() { + let profile = wire_profile(); + let service = GrokCliReleaseService::new( + profile.clone(), + Arc::new(ReleaseTransport::new([Ok("0.2.112".to_owned())])), + ); + let status = service.status(); + + assert_eq!(service.refresh().await.expect("release"), "0.2.112"); + assert_eq!(profile.client_version(), "0.2.112"); + let snapshot = status.snapshot(); + assert!(snapshot.checked_at.is_some()); + assert_eq!(snapshot.latest_version.as_deref(), Some("0.2.112")); + assert!(snapshot.last_error.is_none()); +} + +#[tokio::test] +async fn failed_release_refresh_should_keep_last_successful_version() { + let profile = wire_profile(); + let service = GrokCliReleaseService::new( + profile.clone(), + Arc::new(ReleaseTransport::new([ + Ok("0.2.112".to_owned()), + Err(GrokCliReleaseError::InvalidDocument), + ])), + ); + let status = service.status(); + + service.refresh().await.expect("first release"); + assert!(matches!( + service.refresh().await, + Err(GrokCliReleaseError::InvalidDocument) + )); + assert_eq!(profile.client_version(), "0.2.112"); + let snapshot = status.snapshot(); + assert!(snapshot.checked_at.is_some()); + assert_eq!(snapshot.latest_version.as_deref(), Some("0.2.112")); + assert_eq!( + snapshot.last_error.as_deref(), + Some("Grok CLI release document is invalid") + ); +} diff --git a/backend/crates/providers/xai/tests/transport/client_profile.rs b/backend/crates/providers/xai/tests/profile/selection.rs similarity index 96% rename from backend/crates/providers/xai/tests/transport/client_profile.rs rename to backend/crates/providers/xai/tests/profile/selection.rs index 508c65bac..bf9d0b067 100644 --- a/backend/crates/providers/xai/tests/transport/client_profile.rs +++ b/backend/crates/providers/xai/tests/profile/selection.rs @@ -1,7 +1,7 @@ //! 验证 Grok 客户端画像的环境、版本模式与头部注入防护 use gateway_core::account::OpaqueProviderData; -use provider_xai::transport::client_profile::{GrokClientProfileSelection, VersionMode}; +use provider_xai::profile::selection::{GrokClientProfileSelection, VersionMode}; use provider_xai::{XaiWireProfile, XaiWireProfileState}; use serde_json::json; diff --git a/backend/crates/providers/xai/tests/profile/state.rs b/backend/crates/providers/xai/tests/profile/state.rs new file mode 100644 index 000000000..bc309526b --- /dev/null +++ b/backend/crates/providers/xai/tests/profile/state.rs @@ -0,0 +1,22 @@ +//! 请求画像快照与身份规则测试 + +use super::*; + +#[test] +fn default_identity_should_match_official_grok_shell() { + let profile = XaiWireProfile::default(); + + assert_eq!(profile.client_identifier, "grok-shell"); + assert_eq!(profile.user_agent(), "grok-shell/1.0.13 (linux; x86_64)"); +} + +#[test] +fn user_agent_should_normalize_arm64_like_official_cli() { + let profile = XaiWireProfile { + target_os: "macos".to_owned(), + target_arch: "arm64".to_owned(), + ..XaiWireProfile::default() + }; + + assert_eq!(profile.user_agent(), "grok-shell/1.0.13 (macos; aarch64)"); +} diff --git a/backend/crates/providers/xai/tests/provider/contract/mod.rs b/backend/crates/providers/xai/tests/provider/contract/mod.rs index f021a443d..275e7723f 100644 --- a/backend/crates/providers/xai/tests/provider/contract/mod.rs +++ b/backend/crates/providers/xai/tests/provider/contract/mod.rs @@ -1930,6 +1930,7 @@ async fn disabled_account_diagnostic_selects_the_pinned_account_without_state_wr Arc::new(DiagnosticLeasePort), Arc::new(MemoryCooldownPort::default()), Arc::new(AccountFeedbackStats::default()), + Arc::new(crate::support::TestSessionAffinity::default()), ); let provider = Arc::new( GrokBuildProvider::new( @@ -4307,7 +4308,7 @@ async fn missing_catalog_feature_metadata_keeps_build_responses_routable() { #[tokio::test] async fn configured_request_profile_reaches_inference_headers() { - use provider_xai::transport::client_profile::{GrokClientProfileSelection, VersionMode}; + use provider_xai::profile::selection::{GrokClientProfileSelection, VersionMode}; let transport = StubInferenceTransport::success(); let provider = provider(StubSelector::success(), transport.clone()).await; let selection = GrokClientProfileSelection { diff --git a/backend/crates/providers/xai/tests/provider/contract/scheduling.rs b/backend/crates/providers/xai/tests/provider/contract/scheduling.rs index a04668fa9..d5494a6f9 100644 --- a/backend/crates/providers/xai/tests/provider/contract/scheduling.rs +++ b/backend/crates/providers/xai/tests/provider/contract/scheduling.rs @@ -232,6 +232,7 @@ async fn filtered_scheduling_covers_lease_retry_waiting_and_pinned_terminal_reje leases.clone(), Arc::new(MemoryCooldownPort::default()), Arc::new(AccountFeedbackStats::default()), + Arc::new(crate::support::TestSessionAffinity::default()), ); let transport = StubInferenceTransport::success(); let provider = Arc::new( @@ -425,6 +426,7 @@ async fn account_scoped_adapter_filters_candidates_by_adapter_and_native_request leases.clone(), Arc::new(MemoryCooldownPort::default()), Arc::new(AccountFeedbackStats::default()), + Arc::new(crate::support::TestSessionAffinity::default()), ); let provider = Arc::new( GrokBuildProvider::new( diff --git a/backend/crates/providers/xai/tests/provider/contract/selection_retry.rs b/backend/crates/providers/xai/tests/provider/contract/selection_retry.rs index f385ab1f8..6829ecffc 100644 --- a/backend/crates/providers/xai/tests/provider/contract/selection_retry.rs +++ b/backend/crates/providers/xai/tests/provider/contract/selection_retry.rs @@ -171,6 +171,7 @@ async fn cooldown_after_rotation_preserves_upstream_rejection() { Arc::new(DiagnosticLeasePort), Arc::new(MemoryCooldownPort::default()), Arc::new(AccountFeedbackStats::default()), + Arc::new(crate::support::TestSessionAffinity::default()), ); let transport = StubInferenceTransport::error( GrokInferenceTransportError::new( diff --git a/backend/crates/providers/xai/tests/support.rs b/backend/crates/providers/xai/tests/support.rs index d0a79ef0c..ce1ca809d 100644 --- a/backend/crates/providers/xai/tests/support.rs +++ b/backend/crates/providers/xai/tests/support.rs @@ -807,7 +807,20 @@ pub fn create_input(suffix: &str, subject: &str) -> CreateGrokCredential { pub struct StaticRuntimePolicy; -pub struct TestSessionAffinity; +#[derive(Default)] +pub struct TestSessionAffinity { + pub bindings: Mutex< + BTreeMap< + (ProviderKind, ProviderSessionAffinityKey), + ( + gateway_core::provider_ports::ProviderSessionBinding, + Duration, + ), + >, + >, + pub reject_next_claim: std::sync::atomic::AtomicBool, + pub claims: std::sync::atomic::AtomicUsize, +} pub struct TestSessionExclusions; @@ -837,27 +850,54 @@ impl MemoryCooldownPort { impl ProviderSessionAffinityPort for TestSessionAffinity { fn load<'a>( &'a self, - _: &'a ProviderKind, - _: &'a ProviderSessionAffinityKey, + provider: &'a ProviderKind, + key: &'a ProviderSessionAffinityKey, ) -> futures::future::BoxFuture< 'a, Result, ProviderStoreError>, > { - Box::pin(async { Ok(None) }) + Box::pin(async move { + Ok(lock(&self.bindings) + .get(&(provider.clone(), key.clone())) + .map(|(binding, _)| binding.clone())) + }) } fn round_robin_cursor<'a>( &'a self, _: &'a ProviderKind, _: &'a gateway_core::policy::ClientApiKeyId, ) -> futures::future::BoxFuture<'a, Result> { - panic!("xAI does not read session round robin cursors") + panic!("unused session round robin cursor") } fn admit_account<'a>( &'a self, - _: &'a ProviderKind, - _: gateway_core::provider_ports::ProviderAccountAdmission<'a>, + provider: &'a ProviderKind, + admission: gateway_core::provider_ports::ProviderAccountAdmission<'a>, ) -> futures::future::BoxFuture<'a, Result> { - panic!("xAI does not claim OpenAI sessions") + Box::pin(async move { + let count = self + .claims + .fetch_add(1, std::sync::atomic::Ordering::SeqCst) + + 1; + if self + .reject_next_claim + .swap(false, std::sync::atomic::Ordering::SeqCst) + { + return Ok(false); + } + let claim = admission.session().expect("session admission"); + let mut bindings = lock(&self.bindings); + let key = (provider.clone(), claim.key.clone()); + if bindings.get(&key).map(|(binding, _)| binding) != claim.expected { + return Ok(false); + } + let binding = gateway_core::provider_ports::ProviderSessionBinding::new( + claim.account.clone(), + format!("{count:032x}"), + )?; + bindings.insert(key, (binding, claim.ttl)); + Ok(true) + }) } fn load_alias<'a>( &'a self, diff --git a/backend/crates/providers/xai/tests/transport/canonical.rs b/backend/crates/providers/xai/tests/transport/canonical.rs index 5b5057f97..35fb53e66 100644 --- a/backend/crates/providers/xai/tests/transport/canonical.rs +++ b/backend/crates/providers/xai/tests/transport/canonical.rs @@ -7,10 +7,7 @@ use gateway_core::policy::ClientApiKeyId; use gateway_protocol::openai::sse::{encode_sse_event, encode_sse_event_with_metadata}; use serde_json::Value; -use provider_xai::{ - GrokCanonicalDecoder, GrokResponsesRequest, grok_billing_breakdown, - grok_billing_breakdown_with_tier, -}; +use provider_xai::{GrokCanonicalDecoder, GrokResponsesRequest}; #[test] fn decoder_should_bill_the_sent_model_independently_of_the_response_model() { @@ -267,17 +264,6 @@ fn decoder_should_calculate_grok_45_token_cost() { assert_eq!(provider_cost_ticks(&events), None); } -#[test] -fn billing_breakdown_should_match_the_calculated_terminal_cost() { - let breakdown = grok_billing_breakdown("grok-4.5", 100, 10, 25).expect("known Grok pricing"); - - assert_eq!(breakdown.input_amount().amount().scaled(), 1_500_000); - assert_eq!(breakdown.cache_read_amount().amount().scaled(), 75_000); - assert_eq!(breakdown.output_amount().amount().scaled(), 600_000); - assert_eq!(breakdown.total_amount().amount().scaled(), 2_175_000); - assert_eq!(breakdown.service_tier(), Some("default")); -} - #[test] fn decoder_should_price_official_grok_45_build_free_variant() { let events = terminal_cost_events("grok-4.5-build-free", 201, 0, 76, None); @@ -298,41 +284,6 @@ fn zero_provider_cost_should_use_available_token_pricing() { } } -#[test] -fn billing_should_price_grok_46_cache_and_priority_at_the_context_boundary() { - // 短、长上下文分别检查普通输入、缓存、输出的单价,Priority 只采用已确认档位 - for (input, tier, expected) in [ - (199_999, None, ["2", "0.5", "6"]), - (200_000, None, ["4", "1", "12"]), - (199_999, Some("priority"), ["4", "1", "12"]), - (200_000, Some("priority"), ["8", "2", "24"]), - ] { - let billing = grok_billing_breakdown_with_tier("grok-4.6", input, 10, 20, tier) - .expect("Grok 4.6 价格"); - let rates = [ - billing.input_price_per_million(), - billing.cache_read_price_per_million(), - billing.output_price_per_million(), - ] - .map(|money| { - money - .amount() - .to_string() - .trim_end_matches('0') - .trim_end_matches('.') - .to_owned() - }); - assert_eq!(rates, expected); - assert_eq!(billing.long_context_billing_applied(), input >= 200_000); - } - assert!(grok_billing_breakdown_with_tier("grok-4.6", 10, 1, 0, Some("future")).is_none()); - let priority = grok_billing_breakdown_with_tier("grok-4.6", 100, 10, 20, Some("priority")) - .expect("Priority 价格"); - assert_eq!(priority.standard_amount().amount().scaled(), 2_300_000); - assert_eq!(priority.total_amount().amount().scaled(), 4_600_000); - assert_eq!(priority.multiplier_percent(), 200); -} - fn pricing_events(response: Value, request: Option<&GrokResponsesRequest>) -> Vec { pricing_events_with_override(response, request, None) } diff --git a/backend/crates/providers/xai/tests/transport/mod.rs b/backend/crates/providers/xai/tests/transport/mod.rs index 2523f0ad6..99731ea43 100644 --- a/backend/crates/providers/xai/tests/transport/mod.rs +++ b/backend/crates/providers/xai/tests/transport/mod.rs @@ -2,11 +2,9 @@ mod canonical; mod catalog; -mod client_profile; mod compaction; mod egress; mod headers; mod network; -mod profile; mod request; mod session; diff --git a/backend/crates/providers/xai/tests/transport/profile.rs b/backend/crates/providers/xai/tests/transport/profile.rs deleted file mode 100644 index d14010762..000000000 --- a/backend/crates/providers/xai/tests/transport/profile.rs +++ /dev/null @@ -1,109 +0,0 @@ -//! 验证 Grok 客户端默认身份、架构规范化与发行版本刷新 - -use std::collections::VecDeque; -use std::sync::{Arc, Mutex}; - -use chrono::Utc; -use futures::future::BoxFuture; -use provider_xai::{ - GrokCliReleaseError, GrokCliReleaseService, GrokCliReleaseTransport, XaiWireProfile, - XaiWireProfileState, -}; - -struct ReleaseTransport { - outcomes: Mutex>>, -} - -#[test] -fn default_identity_should_match_official_grok_shell() { - let profile = XaiWireProfile::default(); - - assert_eq!(profile.client_identifier, "grok-shell"); - assert_eq!(profile.user_agent(), "grok-shell/1.0.13 (linux; x86_64)"); -} - -#[test] -fn user_agent_should_normalize_arm64_like_official_cli() { - let profile = XaiWireProfile { - target_os: "macos".to_owned(), - target_arch: "arm64".to_owned(), - ..XaiWireProfile::default() - }; - - assert_eq!(profile.user_agent(), "grok-shell/1.0.13 (macos; aarch64)"); -} - -impl ReleaseTransport { - fn new(outcomes: impl IntoIterator>) -> Self { - Self { - outcomes: Mutex::new(outcomes.into_iter().collect()), - } - } -} - -impl GrokCliReleaseTransport for ReleaseTransport { - fn fetch(&self) -> BoxFuture<'_, Result> { - let outcome = self - .outcomes - .lock() - .expect("release outcomes lock") - .pop_front() - .expect("release outcome"); - Box::pin(async move { outcome }) - } -} - -#[tokio::test] -async fn release_refresh_should_update_profile_and_observation() { - let profile = wire_profile(); - let service = GrokCliReleaseService::new( - profile.clone(), - Arc::new(ReleaseTransport::new([Ok("0.2.112".to_owned())])), - ); - let status = service.status(); - - assert_eq!(service.refresh().await.expect("release"), "0.2.112"); - assert_eq!(profile.client_version(), "0.2.112"); - let snapshot = status.snapshot(); - assert!(snapshot.checked_at.is_some()); - assert_eq!(snapshot.latest_version.as_deref(), Some("0.2.112")); - assert!(snapshot.last_error.is_none()); -} - -#[tokio::test] -async fn failed_release_refresh_should_keep_last_successful_version() { - let profile = wire_profile(); - let service = GrokCliReleaseService::new( - profile.clone(), - Arc::new(ReleaseTransport::new([ - Ok("0.2.112".to_owned()), - Err(GrokCliReleaseError::InvalidDocument), - ])), - ); - let status = service.status(); - - service.refresh().await.expect("first release"); - assert!(matches!( - service.refresh().await, - Err(GrokCliReleaseError::InvalidDocument) - )); - assert_eq!(profile.client_version(), "0.2.112"); - let snapshot = status.snapshot(); - assert!(snapshot.checked_at.is_some()); - assert_eq!(snapshot.latest_version.as_deref(), Some("0.2.112")); - assert_eq!( - snapshot.last_error.as_deref(), - Some("Grok CLI release document is invalid") - ); -} - -fn wire_profile() -> XaiWireProfileState { - XaiWireProfileState::new(XaiWireProfile { - client_identifier: "grok-shell".to_owned(), - client_version: "0.2.106".to_owned(), - client_mode: "headless".to_owned(), - target_os: "linux".to_owned(), - target_arch: "x86_64".to_owned(), - verified_at: Utc::now(), - }) -} diff --git a/backend/migrations/.frozen-sha256 b/backend/migrations/.frozen-sha256 index bc126b9a0..a3e72b294 100644 --- a/backend/migrations/.frozen-sha256 +++ b/backend/migrations/.frozen-sha256 @@ -44,3 +44,5 @@ aeff99fee7cef5a553ae49ffe27a48f49e31ccfb3fbc61a2482c9b109478202d 0041_account_m 23eeb6ef99de2315cf4a198638e9c73b364fb1cb40b7e571a3f15d3e9d15f67c 0044_account_quota_settings.sql 5cfe0227e2a4b26c268bf5b6ef7f93904e02c57d9d2d05cfe2e32db0a7d4e7a2 0045_account_group_policies_and_openai_request_settings.sql ab779ac6ec710148e7c66d82d0a0abbb13c882ad8598cf786278aab2221ef079 0046_quota_limit_window.sql +7ae7331e52dc4fa80d015cacf9bb35bcba271e5379bde57efed2e7439c268af8 0047_runtime_settings_revision.sql +b63085cffb860fa23d429ecec42b063c6ece8dfe8e96ee839b3ca94081a38a12 0048_general_session_affinity.sql diff --git a/backend/migrations/0047_runtime_settings_revision.sql b/backend/migrations/0047_runtime_settings_revision.sql new file mode 100644 index 000000000..768b73b7b --- /dev/null +++ b/backend/migrations/0047_runtime_settings_revision.sql @@ -0,0 +1,5 @@ +-- 记录最近一次运行设置写入对应的全局发布版本,供编辑草稿判断冲突。 +alter table runtime_settings add column settings_revision bigint not null default 1; +update runtime_settings set settings_revision = config_revision; +alter table runtime_settings add constraint runtime_settings_edit_revision_ck + check (settings_revision between 1 and config_revision); diff --git a/backend/migrations/0048_general_session_affinity.sql b/backend/migrations/0048_general_session_affinity.sql new file mode 100644 index 000000000..00fe58c01 --- /dev/null +++ b/backend/migrations/0048_general_session_affinity.sql @@ -0,0 +1,5 @@ +-- 亲和配置由所有 Provider 共用,重命名保留已保存的模式与时长 +alter table runtime_settings rename column openai_account_affinity to account_affinity; +alter table runtime_settings rename column openai_session_affinity_ttl_hours to session_affinity_ttl_hours; +alter table runtime_settings rename constraint runtime_settings_openai_account_affinity_check to runtime_settings_account_affinity_check; +alter table runtime_settings rename constraint runtime_settings_openai_session_affinity_ttl_hours_check to runtime_settings_session_affinity_ttl_hours_check; diff --git a/docs/api.md b/docs/api.md index 116f4ff94..d31c63043 100644 --- a/docs/api.md +++ b/docs/api.md @@ -246,6 +246,34 @@ OAuth 账号使用 Responses 上游。入站路由不决定上游协议,实际 同协议保留原生业务 wire,观测和计量不用于重建响应正文;跨协议按目标格式转换请求、完整响应及 SSE。 Messages 与 Responses 的转换边界见 [Messages 请求](#messages-请求),账号配置见[账号能力、导入与 OAuth](#账号能力导入与-oauth) +### Antigravity 客户端原生生成 + +客户端用 `Authorization: Bearer ` 访问以下 GenAI 短路径。模型名取自 URL,入口只在当前 Key 的账号范围内选择声明 GenAI 协议的原生模型。目前由 Antigravity 使用 OAuth 账号查询上游项目和可用模型。目录与凭据版本绑定,调度选定账号后,网关把原生正文、项目和模型发送到该注册对应的资源服务。个人账号的登录可用性见下文的 Antigravity OAuth。 + +| 方法 | 路径 | 交付 | +| --- | --- | --- | +| POST | `/v1beta/models/{model}:generateContent` | 原生 JSON | +| POST | `/v1beta/models/{model}:streamGenerateContent?alt=sse` | 原生 SSE,允许最后一个候选结束后继续接收用量帧 | +| POST | `/v1beta/models/{model}:countTokens` | 上游输入计数 JSON,返回 `totalTokens` | +| GET | `/v1beta/models`、`/v1beta/models/{model}` | Gemini 格式的模型列表与详情,见[模型目录](#模型目录) | +| POST | `/v1beta:{method}`(客户端后台指标) | 验证 Key 后返回 `{}`,不启动模型请求 | + +普通生成从上游 JSON 的 `response` 中取出原生正文,流式生成逐个解开 SSE 数据帧。原生正文保留工具参数、结果、思考签名和未知字段。客户端归属读取 `User-Agent`、`X-Goog-Api-Client`。网关错误使用 Google RPC 风格的 `error.code`、`error.status` 和 `error.message`。[Google 原生生成协议](https://ai.google.dev/api/generate-content) + +CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保留同名多值的原始字节。下游鉴权、Cookie、账号身份、客户端画像和 HTTP 传输头不透传;认证、项目和 UA 由所选账号与冻结画像生成。`X-Goog-User-Project` 属于调用方指定的计费项目,不能覆盖所选账号的项目,见 [Google 系统参数](https://docs.cloud.google.com/apis/docs/system-parameters) + +同账号及归属未知时保留追踪头;会话绑定或本次执行的已有账号归属明确发生切换时,CPR 清理入站或中间件带入的 `traceparent`、`tracestate`、`sentry-trace`、`baggage`。该清理作用于本次出站请求,不修改工具结果、思考签名或业务正文 + +原生生成依次使用 `X-Http-Session-Id`、`X-Session-Id`、正文 `sessionId`/`session_id` 识别会话,绑定按 Client Key、模型和入站协议隔离。会话识别只用于本地调度,保留客户端正文中的原值 + +`countTokens` 接受 `contents` 或完整的 `generateContentRequest`;后者存在时优先使用其内容。计数与生成使用相同的 AGY 系统提示词配置,调用 Cloud Code 的独立计数接口,不生成助手输出、不记为生成用量,也不在失败时回退到本地估算。该入口仅返回 JSON,不接受 `alt=sse` + +AGY 上游计数与生成响应的 `usageMetadata.promptTokenCount` 口径不完全一致:系统提示、工具定义及工具结果未完整计入计数返回值。原生与 Messages 计数均保留这一上游口径,不能作为完整上下文占用或计费用量的精确值 + +Antigravity 模型也可通过 `/v1/responses`、`/v1/chat/completions` 和 `/v1/messages` 调用,均支持 JSON 与 SSE。转换入口支持文本、内嵌图片/文档、函数工具及结果、生成参数和 JSON Schema;未知内容块返回请求错误,模型自身不支持的参数由上游校验。原生入口不经过转换器;所有 AGY 入口在出站时使用同一份系统提示词配置,替换客户端系统指令,其余原生字段保持原始表达 + +工具多轮调用须带回完整助手输出。Responses 的 `reasoning.encrypted_content` 和 Messages 的 `thinking.signature` 携带 GenAI 工具与思考签名及其所属内容,客户端应原样回传。Chat 沿用现有合同,只返回可读思考内容;转换器对缺少签名的工具调用使用 Google 官方的 `skip_thought_signature_validator` 兜底值,不增加服务端签名缓存。工具与思考的真实签名优先于兜底;普通可见文本的可选签名不附加到转换输出,以保持 CLI 最终文本完整。省略签名或使用兜底可能影响后续模型表现,见 [Google 签名规则](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking/thought-signatures)。Antigravity 转换入口不支持 `previous_response_id` 续接 + ### Chat Completions 请求 `POST /v1/chat/completions` 接受 Chat 消息历史,转换为 Responses 请求执行,再交付 Chat 格式结果。 @@ -419,6 +447,7 @@ Messages 费用按管理员显式配置的模型价格计算,未配置时保 | Messages,地址为官方 `https://api.anthropic.com`,HTTPS 端口为 443 | 请求上游 API 前缀下的 `messages/count_tokens`,返回原生计数结果 | | 自定义 Messages 上游 | 对 Messages 内容使用本地 tokenizer 估算 | | Responses 上游,包括 OAuth | 先投影为 Responses 内容,再使用本地 tokenizer 估算 | +| Antigravity | 转换为 GenAI 输入并应用 AGY 系统提示词,调用 Cloud Code `countTokens`,将 `totalTokens` 投影为 `input_tokens` | 本地估算按模型选择 tokenizer,计算可提取的文本、工具定义与工具内容,不包含图片、音频、视频、二进制文档及隐藏推理的模型专用成本。 它不保证与上游账单或完整多模态上下文一致,也不发送上游生成请求或产生上游用量。 @@ -749,6 +778,10 @@ OpenAI 聚合当前 Key 范围内合格 OAuth 和 API Key 账号的目录。每 服务启动时批量恢复账号目录;目录读取只检查本地账号资格和 Client Key 范围,不等待上游查询。 成功目录响应带 `Cache-Control: private, no-store`,不借用上游 ETag 标识经过选择/别名/聚合后的正文 +Gemini 客户端使用 `GET /v1beta/models` 和 `GET /v1beta/models/{model}`。目录只包含当前 Key 可通过原生 GenAI 入口路由的已知模型,沿用账号范围、模型限制和别名;不会将其他协议的同名模型作为原生候选。条目提供 `name: "models/{id}"`、`displayName` 与 `supportedGenerationMethods`,未知的版本、上下文和输出上限不补默认值 + +Gemini 列表按模型 ID 排序,支持 `pageSize`(默认 50,上限 1000,0 使用默认值)和 `pageToken`;后续页保持相同的 `pageSize`,末页省略 `nextPageToken`。详情查不到模型返回 Google RPC 格式的 404;分页及详情均重新检查当前 Key 的可见范围,不发起上游模型请求 + `service_tiers` 中的 `name` 用于生成 `/fast` 等命令,`id` 用作请求的 `service_tier` 值。 上游未声明档位或返回空数组时,网关不补充档位。档位更新后,客户端需重新加载模型目录 @@ -1453,7 +1486,7 @@ Images 和 Search 按原始请求正文的模型 ID 检查,不依赖模型目 模型缺失、重复或无法识别时,账号模型政策须为 `all`。对于绑定分组的 Key,还须有至少一个包含该账号的启用分组允许全部模型。 Search 的选号限制不约束插件在选号后主动改写正文。 管理员连接测试的选项包含上游目录和账号白名单中的 ID。连接测试跳过普通选号的模型政策、目录资格筛选与模型拒绝冷却,成功表示指定账号可调用测试使用的端点与模型。 -普通 `/v1/models` 和单模型查询将已发现的 OpenAI 和 xAI 模型关联到来源账号,至少一个来源账号在当前 Key 范围内且政策允许时才展示; +普通 `/v1/models` 和单模型查询将已发现的 OpenAI、xAI 和 Antigravity 模型关联到来源账号,至少一个来源账号在当前 Key 范围内且政策允许时才展示; 同 Provider 中未发现该模型的 `all` 账号不会使它进入列表。原生目录保留已有来源选择和完整模型对象 ### 独立代理管理 / Managed Proxies @@ -1616,12 +1649,14 @@ OAuth 等待回调期间允许修改代理。提交时若代理已删除、停 ### 账号能力、导入与 OAuth -敏感账号导出要求所选全部账号属于支持导出的内置平台。不支持时整个请求在读取任何凭据前拒绝,不返回部分导出结果 +敏感账号导出要求所选每个账号均具有 `credentialExport` 能力。任一账号不支持时,服务端在读取凭据前拒绝整批请求 账号列表及额度详情中的 `capabilities` 则针对当前账号,包含布尔字段 `quota`、`quotaRefresh`、`profile`、 `subscription`、`avatar`、`resetCredits` 和 `consumeResetCredit`,分别表示额度读取、额度刷新、资料、订阅、 头像、重置卡查询及消费能力。服务端结合 Provider 实现与账号认证类型生成,客户端据此显示 操作;只读与写入能力分别判断,不按 Provider 名称推测。 +`credentialRefresh`、`reauthorize`、`credentialExport` 和 `modelCatalogDownload` 分别控制刷新凭据、重新授权、导出凭据和下载模型目录 + 能力是查询时的投影,不能代替实际操作的权限校验,也不保证上游可用 导入的 `data` 必须是 JSON object,Admin API 请求上限为 64 MiB;Provider 可以收紧限制, @@ -1637,6 +1672,7 @@ OAuth 等待回调期间允许修改代理。提交时若代理已删除、停 - xAI 从单账号 object 或 `accounts` 数组中提取 OAuth token;并发、优先级等字段不参与认证 - xAI 批量导入逐条独立校验:失败条目跳过并记录日志,不中断其余条目,仅当没有任何条目成功时整个导入才报错 - xAI API Key 不是受支持的账号 credential +- Antigravity 接受本项目导出的版本 1 账号文件;使用内置 OAuth 注册验证 refresh token 与 Google 身份,文件中的身份、套餐及权限只作历史记录,不作为导入后的账号事实 - OAuth 导入由目标 Provider 完成必要的 token exchange 或身份投影。API Key 导入校验凭据格式与地址,不调用 OAuth 或 ChatGPT 身份接口;可用性由模型目录和连接测试验证 API Key 账号使用以下独立凭据形态: @@ -1687,8 +1723,8 @@ Messages API Key 账号支持生成与输入计数,通过协议转换承接 Re 互联账号按上游 Key 已提供的最长消费窗口统计本机 Token、费用和模型用量。 日、周周期的 `usage.windowKind` 分别为 `daily`、`weekly`,其他周期为 `quota`。查询边界同账号额度窗口,为 `[resetAt - windowSeconds, resetAt)`; 未开启或缺少重置边界时显示无数据,不回退到历史累计,也不采用池内其他账号的周期。 -OAuth 账号优先按实际周/月额度窗口统计。xAI 缺少可展示的上游额度时,使用过去 24 小时的本地请求统计, -`usage.windowKind` 为 `daily`,请求图和用量统计共用该滚动范围。该统计可在上游额度快照缺失时展示 +OAuth 账号优先按可归属整个账号的实际周/月额度窗口统计,缺少可归属窗口时使用过去 24 小时的本地请求统计 +此时 `usage.windowKind` 为 `daily`,Token 与模型用量共用该范围,上游额度快照缺失时仍可展示本地统计 批量导入 AT / RT 使用 `accounts` JSON 数组,最多 200 项,不接受纯文本 token 列表。例如: @@ -1719,7 +1755,11 @@ API Key 账号未指定名称时默认使用「密钥账号」 账号列表的每个 item 返回轻量 `groups: [{ id, name, enabled }]` -OpenAI 的 CPR 导出保持 OAuth 账号的既有 token 与过期时间字段。OpenAI 与 xAI 的 CPR 账号条目均包含 +内置 Provider 的账号导出统一使用 `label` 表示本地名称,名称为空时省略;本地创建与更新时间使用 +`createdAt`、`updatedAt`,AT 有效期使用 `accessTokenExpiresAt`,授权范围(如有)使用 `scopes` 字符串数组。 +xAI 的 token、有效期和范围位于条目的 `credentials` 对象,字段集合与外层结构由各 Provider 定义 + +OpenAI 与 xAI 的 CPR 账号条目均包含 `modelAccess`,重新导入时恢复;导入 `settings.modelAccess` 显式提供时覆盖条目中的政策。 导入条目未提供 `modelAccess` 且 `settings` 未指定该字段时,新账号默认 `all`,已有账号保留原值;凭据刷新、重新授权和目录刷新均保留政策。 sub2api 的 `credentials.model_mapping` 不转换为本项目的账号模型限制 @@ -1774,6 +1814,58 @@ OAuth start 使用: 账号提交成功后,`complete` 保留 24 小时的完成结果。同一管理员使用相同 `provider`、`flowId` 重试时返回原账号结果,不再执行授权或更新凭据;新提交的 `callbackUrl` 和 `settings` 不会再次应用 +Antigravity 的全局客户端设置保存在 `providerRequestProfiles.antigravity`,Key 可用 `providerRequestProfileOverrides.antigravity` 覆盖。配置使用 `client`(`desktop` 或 `cli`)、`platform`(`macos`、`linux` 或 `windows`)、`versionMode`、`clientVersion` 和 `arch`。`arch: null` 使用预设架构:macOS 为 `arm64`,Linux 与 Windows 为 `amd64`;也可显式选择 `arm64` 或 `amd64` + +`systemPrompt` 可在 AGY 设置中编辑,省略、`null` 或空白值使用内置默认,最长 16 KiB。默认取自已核对的 AGY CLI 1.5.15 身份模板,不包含客户端专属工具和工作区模板;选项接口返回 `defaultSystemPrompt` 与 `systemPromptSource`,客户端版本轮询不会改写它。提示词随请求画像一起冻结,原生和转换入口均用它替换客户端的系统指令 + +自动版本示例: + +```json +{"client":"desktop","platform":"macos","versionMode":"latest","clientVersion":null,"arch":null} +``` + +固定版本使用 `"versionMode":"fixed"`,并将 `clientVersion` 设为三段数字版本。Desktop 与 CLI 分别跟随各自的官方发布资料,各实例启动后检查,之后每 24 小时更新一次;检查失败保留上次成功结果,尚无结果时使用已核实的内置版本。请求开始时冻结客户端、平台、架构、版本及对应的 CL 构建号,重试沿用同一画像。发布资料不提供 CL,未知版本省略该字段,不套用旧版本的构建号。[Google 官方下载](https://antigravity.google/download) + +预览与实际出站请求共用 `User-Agent` 生成规则。本机 macOS arm64 的 Desktop 2.34.0 已认证请求为 `antigravity/hub/2.34.0 (aidev_client; os_type=darwin; arch=arm64; cl=1026637980)`;CLI 1.5.15 经 ACP 入口及打印模式的控制面请求核实使用 `cli` 子客户端标识、CL `1027820220` 及 `auth_method=consumer`。默认身份不添加关闭遥测才出现的 `datacollection_opt_in` 或 ACP 宿主传入的 `host_path` + +Cloud Code 请求固定使用 HTTP/1.1 和 `Accept-Encoding: gzip`,响应按流解压,大小限制作用于解压后的内容。 +传输显式使用 rustls,TLS 握手与官方 Go 客户端不同;reqwest 的默认 `Accept: */*` 和请求头顺序也不完全一致。画像预览不代表 TLS 或完整网络指纹一致 + +Antigravity 使用 Desktop 个人账号的内置 OAuth 注册,授权请求携带 PKCE S256、离线访问和个人账号权限范围。身份通过 Google OAuth2 userinfo 验证;首次授权或导入的令牌响应未返回范围时,通过 tokeninfo 查询获授权限。凭据保存后按现有 OAuth 策略自动续期,部署配置无需提供 Google OAuth 参数 + +OAuth 服务端请求使用全局 AGY 画像和 HTTP/1.1,不读取 Key 覆盖。授权码交换、导入或刷新开始时冻结当前画像,同轮 token、userinfo 和 tokeninfo 请求共用该身份;后续操作读取最新全局配置 + +Google 授权后,将浏览器中的完整 `http://localhost:8085/auth/callback?…` 地址粘贴回账号页。CPR 不监听此本机端口,浏览器提示无法连接时仍可复制地址。回调地址和 `state` 必须与当前流程匹配,不接受单独的授权码 + +账号文件的 `data` 形态如下,敏感导出返回同一格式,并由 CPR 的 `documents` 信封包装: + +```json +{ + "provider": "antigravity", + "version": 1, + "accounts": [{ + "label": "个人账号", + "email": "user@example.com", + "userId": "", + "accessToken": "", + "refreshToken": "", + "accessTokenExpiresAt": "2026-11-25T13:00:00Z", + "scopes": [""], + "planType": "Google AI Pro", + "createdAt": "2026-11-20T12:00:00Z", + "updatedAt": "2026-11-25T12:00:00Z" + }] +} +``` + +`accounts` 不能为空,每项必须提供非空 `refreshToken`;`label` 可省略或为空字符串,表示未设置本地名称,列表使用已验证的邮箱展示。重复凭据或重复 Google 账号拒绝导入 + +其余字段记录导出时已保存的凭据和账号观测,未知值省略;`createdAt`、`updatedAt` 是本地账号时间,`accessTokenExpiresAt` 是当前 AT 的有效期。导出不触发上游刷新,已过期 AT 也按原值记录。导入使用 RT 换取新 AT 并重新验证 Google 身份与权限,套餐由上游重新发现,文件中的历史观测不覆盖验证结果。出站代理通过导入请求的 `outboundProxyId` 指定 + +Antigravity 主动额度刷新同时读取套餐与上游模型组额度,优先采用明确的付费套餐。`g1-pro-tier`、`g1-ultra-tier` 分别显示为 `Google AI Pro`、`Google AI Ultra`,缺少套餐不推断为免费账号 + +`quota.windows` 只保留上游模型组各自的 5 小时与周额度、已用百分比及重置时间,同组窗口共享 `limitId`。这些窗口的 `accountWide` 为 `false`,不能相加为整号余额,也不用于整号周/月容量预测;缺失的上游百分比保持未知。本地 24 小时请求统计通过账号 `usage` 单独返回,不生成上游额度窗口 + OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上游请求总超时为 60 秒 - 授权码交换未能建立连接时返回 `50301`,提示区分连接超时与其他连接失败 @@ -1825,9 +1917,9 @@ OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上 未知或早于本次拒绝的重置时间仍按窗口证据复核,到期本身不会解除限制或将展示用量归零。 上游明确放行时,连续两次查询都有该窗口的使用率且未触顶,即可解除该窗口,即使重置时间持续向后移动 - 账号仍待恢复时,窗口展示最近观测的使用率,缺失时为 `null`。仅将已明确触顶的窗口展示为 100% -- 停用的 OpenAI 与 xAI OAuth 账号退出客户端请求调度,仍按各自策略续期 Token、查询额度。 - 成功刷新后账号保持停用。无 refresh token 或凭据已进入失效、无效、 - 封禁状态的账号不参加后台自动续期 +- 账号 `enabled` 控制是否参与请求调度,不控制 OAuth 凭据续期。Codex、xAI 与 Antigravity 的停用账号仍按各自刷新 + 策略维护 Token;刷新结果更新凭据状态,但不会启用调度。停用的 OpenAI 与 xAI OAuth 账号仍按各自策略查询额度。 + 无 refresh token 或凭据已进入失效、无效、封禁状态的账号不参加后台自动续期 - `POST /api/admin/accounts/recover` 对停用账号只将 `enabled` 改为 `true`,保留已有额度快照、凭据、错误和 Redis cooldown;启用后仍按这些事实投影状态,不会把已有错误或耗尽改成正常。对已启用账号则执行强制恢复: 清除 Redis cooldown 和已保存的额度/错误,恢复为可调度 credential。两条路径均不访问上游;强制恢复 @@ -2224,14 +2316,15 @@ HTTP 返回 `429`,`error.code` 为 `key_daily_budget_exceeded` 或 `key_weekly | `POST` | `/api/admin/settings/location/detect` | 无请求体,检测网关服务器直连出口的位置,不保存设置 | | `POST` | `/api/admin/settings/privacy/preview` | 使用管理员提供的样本预览隐私规则,不保存设置或样本 | | `GET` | `/api/admin/settings/client-downloads/codex-desktop/windows` | 提取 Codex Desktop Windows 离线安装直链;`refresh=true` 强制刷新进程内短缓存 | -| `GET` | `/api/admin/settings/client-profiles/{provider}` | 读取 `openai` 或 `xai` 的可选配置和 `globalConfiguration` | +| `GET` | `/api/admin/settings/client-profiles/{provider}` | 读取指定 Provider 的可选配置和 `globalConfiguration` | | `POST` | `/api/admin/settings/client-profiles/{provider}/preview` | `{ configuration }`,完整配置对象或 `null`(解析当前通用设置);使用已加载版本与最近检查时间,不触发上游检查或保存 | | `GET` | `/api/admin/settings/admin-api-key` | 只返回管理 API Key 是否存在 | | `POST` | `/api/admin/settings/admin-api-key/delete` | 删除管理 API Key | | `POST` | `/api/admin/settings/admin-api-key/regenerate` | 重新生成并一次性返回完整管理 API Key | 读取设置返回 `configRevision`。更新请求必须携带读取时的同一版本;版本比较、设置替换和审计在同一事务内完成。 -并发修改导致版本过期时返回 `409`,不保存当前请求;读取最新设置并确认差异后再提交,不能静默重试覆盖。 +读取后若运行设置已被修改,或提交的版本超出当前发布版本,返回 `409`。请重新读取设置并确认差异后再提交。 +调整模型价格、轮换管理密钥等独立操作只推进发布版本,原设置草稿仍可保存。 成功响应返回新版本,后续请求使用发布后的快照 位置检测返回 `status: detected` 与 `location`,双栈出口时区不一致时返回 `conflict`, @@ -2251,7 +2344,7 @@ HTTP 返回 `429`,`error.code` 为 `key_daily_budget_exceeded` 或 `key_weekly | 凭据刷新 | `refreshMarginSeconds`、`refreshConcurrency` | | [并发与排队](#并发与排队) | `maxConcurrentPerAccount`、`maxWaitingPerKey`、`maxWaitingPerAccount`、`openaiGuardianReservedConcurrency`、`keyQueueTimeoutSeconds`、`accountQueueTimeoutSeconds`、`switchAccountOnQueueFailure` | | [上游重试等待](#容量拒绝与重试) | `maxRetryAfterSeconds` | -| [亲和与换号](#账号亲和与换号) | `openaiAccountAffinity`、`openaiSessionAffinityTtlHours`、`maxAccountRotations` | +| [亲和与换号](#账号亲和与换号) | `accountAffinity`、`sessionAffinityTtlHours`、`maxAccountRotations` | | [调度策略](#智能调度) | `rotationStrategy`、`smartScheduling`、`quotaResetWindowWeights` | | [请求解压](#请求解压上限) | `responsesMaxDecompressedBodyBytes` | | [客户端门禁](#1-鉴权与公共约定) | `minCodexDesktopVersion`、`minCodexCliVersion` | @@ -2295,6 +2388,8 @@ HTTP 返回 `429`,`error.code` 为 `key_daily_budget_exceeded` 或 `key_weekly 关联代理配置了自定义位置时优先使用代理值。保存后通过现有配置发布机制对新请求生效, 已开始请求及其重试保持同一份全局值;普通文本、绝对时间戳和数据驻留要求不受影响 +Antigravity 不应用这组国家、区域、城市和时区覆盖,原生请求中的位置相关业务字段继续透传;网络出口仍使用所选账号的代理 + `openaiRequestCountry` 仅控制发往 Codex OAuth 上游的 Responses 请求顶层字段 `request_country`。API Key 上游保留客户端原值,包括显式 `null`,客户端省略时也省略。保存后对新请求生效 | 管理端选项 | 设置值 | 发往上游的字段 | @@ -2401,9 +2496,22 @@ Guardian 以 `subagent_kind` 或 `client_metadata.x-openai-subagent` 值 `guardi ### 账号亲和与换号 -`openaiAccountAffinity` 控制 OpenAI Provider 的账号亲和,包括带明确 Claude Code 会话身份的 [Messages 请求](#messages-请求),默认 `strict`(严格): +`accountAffinity` 是通用账号亲和设置,作用于 OpenAI、xAI 和 Antigravity,默认 `strict`(严格) +各 Provider 负责识别会话、投影账号资格和遵守原生续接约束,模式与 `sessionAffinityTtlHours` 随请求冻结 + +- `relaxed` 按普通调度选号,成功准入后更新绑定 +- `preferred` 优先主账号,容量不足可临时分流并保留仍可用的主绑定 +- `strict` 优先同一账号,启用账号排队时等待繁忙的绑定账号,关闭排队、绑定失效或允许换号时重新绑定 + +Antigravity 原生 GenAI 请求使用 `X-Http-Session-Id`,缺失时使用 `X-Session-Id`;这些头只作为会话标识 +Responses 和 Messages 转入 Antigravity 时分别复用 Codex 逻辑会话和 Claude Code 会话解析,在转换前按 Client Key、模型及入站协议隔离绑定 +无显式会话及计数请求不建立绑定。账号资格失效后按调度策略重选,凭据、额度、模型目录和权限仍由 Antigravity 检查 + +xAI 沿用自身显式会话及对话开头的识别规则,按 Client Key 和模型隔离绑定 +选号使用共享的版本绑定、TTL 和模式;上游 session ID、加密推理重放与原生响应续接继续由 xAI 处理 + +OpenAI 在上述模式下还保留以下协议规则,包括带明确 Claude Code 会话身份的 [Messages 请求](#messages-请求): -- `relaxed`(宽松):会话内请求直接按 `rotationStrategy` 选号,不优先主账号 - `preferred`(优先)优先使用会话主账号,短时满载、限流或模型不匹配时临时分流,后备按同一会话的稳定顺序参与既有调度 主账号被删除、停用或凭据过期、失效、封禁时,在后备账号成功准入时原子迁移绑定 额度耗尽且重置时间未知或距离当前时刻超过账号排队时限时迁移,接近重置时保留主绑定,并给刚过重置时间的额度复核同长度宽限 @@ -2417,7 +2525,7 @@ Chat Completions 和 Responses 通过原生 OpenAI Provider 选号时,缺少 后续消息及工具列表不参与匹配。优先模式允许临时分流;严格模式沿用根请求的等待与迁移规则,启用账号排队时等待繁忙的绑定账号,关闭排队或账号失效时允许重新选号并迁移绑定。 宽松模式、没有缓存键又缺少对话开头文本的请求,仍按普通调度选号。内容亲和只用于选号,不建立会话身份或续接归属 -`openaiSessionAffinityTtlHours` 是账号绑定及其会话关联的滑动保留时长,单位小时,默认 24,取值 1~720。 +`sessionAffinityTtlHours` 是账号绑定及其会话关联的滑动保留时长,单位小时,默认 24,取值 1~720。 各类请求统一在发送前成功准入时按请求冻结值续期。 响应完成不回写或续期。调整时长不扫描已有 Redis 键,已有记录保留原到期时间,下一次成功准入时使用新值; 真正过期或丢失后按缺失绑定处理,存储读取错误不会被当作过期 @@ -2492,11 +2600,13 @@ Chat Completions 和 Responses 通过原生 OpenAI Provider 选号时,缺少 | 方法 | 路由 | 请求与返回 | | --- | --- | --- | -| `GET` | `/api/admin/settings/pricing` | 返回 `{ defaults, synced, overrides, syncedAt }` | +| `GET` | `/api/admin/settings/pricing` | 返回 `{ defaults, synced, overrides, supportedBands, syncedAt, syncedAtDisplay }` | | `POST` | `/api/admin/settings/pricing/update` | `{ provider, models, change }`,成功返回 `{ saved: true }` | | `POST` | `/api/admin/settings/pricing/sync/preview` | 无 body;返回 `{ prices, skipped }`,不写入配置 | | `POST` | `/api/admin/settings/pricing/sync` | `{ preview: { prices, skipped }, models: { openai: ["gpt-5.4"] } }`;成功返回 `{ saved: true }` | +`supportedBands` 按 Provider 列出可设置的计费档位,修改价目时使用同一范围校验 + 价目使用 `Provider → 精确上游模型 ID → { multiplierBps, bands }` 的映射。优先级为人工覆盖、已同步价目、 内置价目;按档位合并,不从客户端模型别名或响应模型猜测价格。`syncedAt` 为 ISO 时间或 `null`。 每个档位包含四个非负十进制字符串:`input`、`output`、`cacheRead`、`cacheWrite`,单位 USD / 百万 @@ -2509,10 +2619,20 @@ OpenAI 长上下文为输入超过 272000 Token,xAI 为输入达到 200000 Tok xAI 不接受 `flex`、`long_flex`、`ultrafast`、`long_ultrafast`、`image`。图像端点的 `standard` 用于文本输入,`image` 用于图像 Token;不能用文本输出单价替代图像输出单价。用量无法完整拆分时不估算 +Antigravity 内置已登记 Gemini、Claude 和 GPT-OSS 模型的公开 API 参考价,思考档位共用对应基础模型单价; +参考价用于本地费用估算,不代表订阅套餐的现金账单。`models.dev` 同步通过 Provider 明确登记的对应关系读取 +Google、Anthropic 和 Google Vertex 来源,未登记的内部型号不按名称猜测价格 + +Antigravity 支持 `standard`、`long_standard`、`image`。Gemini 2.5 Pro 在输入超过 200000 Token 时使用长上下文价; +图片输出按图片 Token 单价,思考输出仍按文本单价,混合输出明细展示加权单价。 +输入已包含缓存,输出已包含思考 Token,不重复计费;含音视频或缺少必要模态计数、无法拆分异价缓存时费用未知。 +JSON 或 SSE 完整结束后按最终累计用量保存一次费用快照 + `multiplierBps` 为 0~1000000 的整数,10000 表示 1 倍、0 表示本地估算为零,最大 100 倍。 它作用于本地费用及对应明细,独立于服务档位;缺少计价依据的请求即使倍率为零仍然是费用未知 -`provider` 为内置 `openai` 或 `xai`,对应价目由 `GET` 返回的 `defaults` 提供。 +`provider` 使用 `GET` 的 `defaults` 返回的已注册 Provider ID,包括 `openai`、`xai` 和 `antigravity`; +没有内置价目的 Provider 返回空对象,仍可添加人工标准价。 `models` 为 1~500 个模型 ID,每个 ID 为 1~128 字节且不含空白、控制字符。`change` 为以下形式之一: @@ -2525,6 +2645,7 @@ xAI 不接受 `flex`、`long_flex`、`ultrafast`、`long_ultrafast`、`image`。 一批更新原子提交并写审计,不覆盖未选中的模型。未知字段、错误类型和非法价格字符串等 JSON 合同错误 返回 422;Provider、模型 ID、批量数量、倍率上限和不支持的档位等业务校验错误返回 400。 +定价页按当前选择的 Provider 预览和确认同步;来源没有该平台的价目时提示手动定价。 models.dev 同步只导入可表示为当前文本 Token 计价的 OpenAI/xAI 模型;不完整价格、其他输出模态及 不匹配的上下文梯度在 `skipped` 中返回 `provider/model`。确认会重新抓取价目;若与预览不同返回 400, 需重新预览。来源不可用返回 502,已有价目保持不变。`preview` 必须原样提交,`models` 按 Provider @@ -2538,8 +2659,9 @@ models.dev 同步只导入可表示为当前文本 Token 计价的 OpenAI/xAI 更新时省略某项保留原值,对象替换该项,`null` 删除显式选择并使用 Provider 默认值;不清除其他 Provider 的配置。 配置内容由对应 Provider 校验,不包含账号凭据。Key 可通过 `providerRequestProfileOverrides` 整体覆盖所属 Provider 的选择 -直接读取 `openai` 或 `xai` 的选项与预览。OpenAI 选项返回六个 `presets` 与 `maxVersionLag`,xAI 返回 `defaults`; -响应均包含 `globalConfiguration` +各 Provider 的选项响应均包含 `globalConfiguration`。OpenAI 返回六个 `presets`、`maxVersionLag` 和 +`recognizedUserAgentPrefixes`。匹配前缀时,OpenAI 从 UA 派生 originator 与 Core 版本,其他自定义 UA 需要提供这两个字段。 +xAI 返回 `defaults`,Antigravity 返回 `defaults` 与 `presets` ### OpenAI 上游客户端身份 @@ -2720,19 +2842,19 @@ Desktop 三段 SemVer 门禁,也不会自动回写最低版本设置。门禁 | 方法 | 路由 | 请求 | 说明 | | --- | --- | --- | --- | -| `GET` | `/api/admin/settings/backups` | 无 | 读取存储配置(含明文 Secret)、验证状态与调度配置 | +| `GET` | `/api/admin/settings/backups` | 无 | 读取存储配置、密钥配置状态、验证状态与调度配置 | | `POST` | `/api/admin/settings/backups/storage/update` | S3 配置 | 更新存储配置;`secretAccessKey` 为空字符串会校验失败 | -| `POST` | `/api/admin/settings/backups/storage/test` | 无 | 测试已保存的存储配置(Put/Head/Get/Delete 探针) | +| `POST` | `/api/admin/settings/backups/storage/test` | `{ storageRevision }` | 测试已保存的存储配置(Put/Head/Get/Delete 探针) | | `POST` | `/api/admin/settings/backups/schedule/update` | 调度配置 | 更新 Cron 与保留策略 | | `GET` | `/api/admin/settings/backups/records` | 查询参数 | 分页查询备份记录 | | `POST` | `/api/admin/settings/backups/create` | `{ expiresInDays? }` | 创建手动备份,返回 `202 Accepted`;`expiresInDays` 为过期天数(0 或缺省表示不过期) | | `POST` | `/api/admin/settings/backups/download-url` | `{ backupId }` | 创建 5 分钟有效预签名下载地址(仅 completed) | | `POST` | `/api/admin/settings/backups/delete` | `{ backupId }` | 请求删除(进入 `deleting`,由 Worker 收敛硬删除) | -读取设置响应(Secret 以明文返回): +读取与保存共用以下设置响应字段: ```text -storageRevision, endpoint, region, bucket, accessKeyId, secretAccessKey, prefix, +storageRevision, endpoint, region, bucket, accessKeyId, secretConfigured, prefix, forcePathStyle, verified, scheduleEnabled, cronExpression, retentionDays, retentionCount, nextRunAt, nextRunAtDisplay, lastVerifiedAt, lastVerifiedAtDisplay, updatedAt, updatedAtDisplay @@ -2741,21 +2863,21 @@ lastVerifiedAt, lastVerifiedAtDisplay, updatedAt, updatedAtDisplay 更新存储请求字段: ```text -endpoint, region, bucket, accessKeyId, secretAccessKey, prefix, forcePathStyle +storageRevision, endpoint, region, bucket, accessKeyId, secretAccessKey, prefix, forcePathStyle ``` -`secretAccessKey` 为空字符串会校验失败;由于 GET 会回传已保存的明文 Secret,保存时始终整体提交当前值。已有备份记录时,endpoint/region/bucket/forcePathStyle 不允许变化(存储身份锁定,`409`);只允许轮换凭据与修改 prefix +`secretConfigured` 表示是否已保存 Secret。首次配置和轮换时提交非空 `secretAccessKey`,省略该字段保留原值。保存须携带读取时的存储版本,版本过期返回 `409`。已有备份记录时,endpoint/region/bucket/forcePathStyle 不允许变化(存储身份锁定,`409`);只允许轮换凭据与修改 prefix 保存相同配置保留验证状态、定时计划及配置版本。存储配置实际变化时,会同时使验证失效、暂停定时计划并清空下次运行时间;连接测试通过后需重新启用计划 更新调度请求字段: ```text -scheduleEnabled, cronExpression, retentionDays, retentionCount +storageRevision, scheduleEnabled, cronExpression, retentionDays, retentionCount ``` `cronExpression` 为 5 段格式,按部署 `host.timezone` 解释;不存在的本地时刻跳过,重复时刻只执行较早一次。 -调度时区没有独立请求字段。`retentionDays`/`retentionCount` 为 0 表示禁用对应清理。启用计划前必须已保存完整存储配置且通过连接测试 +调度时区没有独立请求字段。`retentionDays`/`retentionCount` 为 0 表示禁用对应清理。启用计划时,存储版本必须匹配且已通过连接测试,否则返回 `409` 记录列表查询参数: @@ -2778,10 +2900,10 @@ errorCode, errorMessage, startedAt, completedAt, expiresAt, createdAt, updatedAt 连接测试响应: ```text -{ ok, stage, code, message } +{ storageRevision, ok, stage, code, message } ``` -`stage` 为 `putObject/headObject/getObject/deleteObject`。探测成功后以 `storageRevision` CAS 写入 `lastVerifiedAt`;测试期间配置变化则丢弃结果 +`stage` 为 `putObject/headObject/getObject/deleteObject`。请求版本已过期或成功探测后版本已变化时返回 `409`。成功响应中的 `ok: true` 表示服务端已为该存储版本记录验证时间 备份错误映射(`AdminErrorCode` 既有体系): @@ -2844,6 +2966,10 @@ Dashboard 的当前账号摘要包含 `upstream`,结构与账号列表一致 页面按 `key` 取值;状态判断使用原始值,不依赖界面译文 +Antigravity 的 `client_identifier` 与实际 User-Agent 共用产品标识,格式为 `antigravity/{hub|cli}/{version}`;`target` 返回系统与架构,未携带的系统版本和终端为空 + +Antigravity 的发布状态仅比较官方发布版本,页面显示“版本一致”;`verifiedAt` 只表示对应平台、架构与版本的实际画像核验时间,不随发布资料轮询刷新,尚未核验的组合为空 + ### Dashboard 容量与账号用量 Dashboard 的 `capacityInfo` 统计普通容量,不含独立审批池;`maxConcurrentPerAccount` 为默认账号并发上限,`0` 表示不限制。 @@ -3039,11 +3165,15 @@ WebSocket 握手不主动添加专项计时请求头,客户端显式提供的 以上指标按上游内部口径展示,不相加重建总耗时,不替换请求级 `firstTokenLatencyMs`。 它们仅补充性能诊断,不改变列表与聚合统计的速率分母 -列表与性能统计的速率为 `outputTokens × 1000 / upstreamResponseMs`,只在两者为正时计算。 +上游平均速率为 `outputTokens × 1000 / upstreamResponseMs`,只在两者为正时计算。 输出 Token 保留上游用量口径,OpenAI 的输出已包含推理 Token,不重复相加或扣除。 该值表示上游响应创建到完成期间的平均输出速率,按官方时间戳精度计算, 不表示模型内部的纯解码速度,也不用于替代网关观测的首个输出等待与请求总耗时 +请求列表优先展示上游平均速率。缺少有效上游耗时时,使用 `outputTokens × 1000 / latencyMs` +展示带 `≈` 的本地平均速率,并注明包含等待、重试和网络耗时;输出 Token 或耗时无效时显示缺失。 +本地估算不补写 `upstreamResponseMs`,性能聚合仍只统计上游平均速率,不混合两种计时口径 + ### 诊断与恢复关联 详情接口按 `id` 可读取成功、失败或未完成请求,普通详情与列表不传输时间线。 diff --git a/docs/architecture.md b/docs/architecture.md index 52c071228..51770c050 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -16,10 +16,10 @@ HTTP 字段见[接口文档](api.md),部署参数见[部署文档](../deploy/R Codex Proxy RS 是单进程、单副本运行的多 Provider AI 网关,同时提供: -- 面向客户端的 Responses、Chat Completions、Anthropic Messages、Images、standalone Search 和模型目录协议 +- 面向客户端的 Responses、Chat Completions、Anthropic Messages、Gemini GenerateContent、Images、standalone Search 和模型目录协议 - 面向管理员的 `/api/admin/*` 控制面和 Vue 管理端 - 面向 Key 持有者的 `/api/key-usage/*` 用量与客户端配置接口、独立 `/key-usage` 页面,以及复用数据面认证的 `/v1/usage` 额度查询 -- 固定的 OpenAI 与 xAI 两个编译期 Provider,以及插件提供的认证、中间件和管理扩展 +- 固定的 OpenAI、xAI 与 Antigravity 三个编译期 Provider,以及插件提供的认证、中间件和管理扩展 - PostgreSQL 持久化、Redis 协调状态以及 S3/R2 数据库备份 Responses、Chat Completions 和 Messages 共用生成执行链,API Key 账号可选择 Responses 或 Messages 上游协议, @@ -80,6 +80,7 @@ flowchart TB | `gateway-plugin/runtime`(包名 `gateway-plugin-runtime`) | 插件包校验、能力适配、双向 RPC 与发布集合;通过 Host 管理子进程和受管 HTTP | | `providers/openai` | OpenAI OAuth、API Key 凭据、账号选择、目录、额度和 Responses/Messages/Images/Search transport | | `providers/xai` | xAI OAuth session、账号选择、目录、额度和 Grok/Responses 转换 | +| `providers/antigravity` | 个人账号 OAuth 与凭据文件、项目与模型目录、套餐和模型分组额度、原生生成与人工计费,以及 Desktop/CLI 发布资料和请求身份 | | `frontend` | Vue 管理端与 Key 用量页,仅通过各自身份允许的控制面 API 访问状态 | | 独立仓库 `codex-proxy-ui` | 管理端与插件页面共用的 Vue 基础组件、纯主题算法和样式,不依赖宿主业务状态、路由或 API | | 独立仓库 `codex-proxy-plugins` | 官方维护综合示例,依赖公开 SDK,Rust 处理器和已构建页面合成一个可安装包,不随宿主构建发版 | @@ -177,7 +178,7 @@ flowchart LR 能力响应无法解码或消费时只结束所属调用,不连带停止共享进程;帧封装、调用关联或传输损坏才终止 RPC 会话。 故障绑定保留原有作用范围和拒绝/委托策略,入口认证故障不降级为其他认证方式;宿主配置存储与 revision 无法确认时仍停止新请求 - **宿主持有业务事实**:插件返回能力结果,Core 继续决定账号资格、发送状态、标准用量与费用;账号变更由 Admin / Store - 执行版本校验、事务和审计。Provider 由组合根静态注册为 OpenAI 与 xAI;插件停用不删除账号或历史记录,失败的观察回调不改变响应和账单 + 执行版本校验、事务和审计。Provider 由组合根静态注册为 OpenAI、xAI 与 Antigravity;插件停用不删除账号或历史记录,失败的观察回调不改变响应和账单 - **能力开放不承接插件业务**:宿主向插件提供独立、可组合的原生能力,负责类型校验、资源生命周期、事务与审计。 插件自身的触发条件、跨资源业务关联、策略和流程编排归插件所有;宿主不能因某个插件的使用场景代为实现这些流程 @@ -288,7 +289,7 @@ HTTP 字段见 [插件 API](api.md#12-插件管理),更新与数据恢复见 [ 测试模块树: 1. crate root 作为顶层门面,声明模块并暴露该 crate 的配置、Bundle、端口或稳定领域合同;目录节点使用 - `目录/mod.rs`,叶子模块使用 `名称.rs`,不混用 `名称.rs` 与 `名称/` 两套入口 + `目录/mod.rs`,叶子模块使用 `名称.rs`,不混用 `名称.rs` 与 `名称/` 两套入口;源码和测试都不保留只有 `mod.rs` 的目录 2. 生产源码不使用内联 `mod name { ... }`、`#[path]` 或 `include!` 隐藏文件归属。`lib.rs` 和各级 `mod.rs` 是模块门面,负责声明子模块、选择性 re-export 与少量同层协调 3. 子模块默认私有;只有真实的跨 crate 生产合同才能使用 `pub`。adapter/provider 的公开根模块由 @@ -300,9 +301,12 @@ HTTP 字段见 [插件 API](api.md#12-插件管理),更新与数据恢复见 [ 测试;额外场景测试必须放在最近的生产 owner 目录下。根级 `support` 及其辅助模块和冻结的 crate/workspace 架构场景 是明确例外 +同一职责的实现分片聚合到所属目录,例如 `transport/client/{backend,catalog,json,live,messages,stream}.rs`、 +`postgres/client_budgets/{store,buffer,windows}.rs` 和 `system_update/swap/{release,paths}.rs`。相同前缀本身不代表同一职责,独立授权能力和业务合同仍保留各自 owner + 较大的模块门面只负责组合和 re-export:账号 Admin HTTP 边界按 `wire`、`credentials`、`handlers`、 -`presenter` 划分;Provider 执行按 continuation、stream、failure、observation 和 worker 等职责拆分;xAI -请求转换按 response、tools 与 history 拆分。各子模块之间只使用 owner 内最小可见性 +`presenter` 划分;观测用例按 `service`、`insights`、`billing` 和 `dashboard` 分离协调与纯投影。 +Provider 执行按 continuation、stream、failure、observation 和 worker 等职责拆分;xAI 请求转换按 response、tools 与 history 拆分。各子模块之间只使用 owner 内最小可见性 ### 3.3 `gateway-core` 内部 owner @@ -357,23 +361,54 @@ Provider 可为模型提供来源账号集合;Core 在公开目录查询时结 | `api/modules/` | 页面 HTTP 合同,模块名对应 `views/` 一级目录;复杂模块在同名目录内按功能拆分,业务类型由所属模块定义 | | `api/types/` | 跨业务模块共享的接口类型,如时间展示与请求位置;不依赖请求实现或业务模块 | | `api/request/` | 请求入口与插件链;负责会话恢复、重试、错误提示、错误归一化和原始/流式响应处理,页面不重复解释响应信封 | +| `providers/` | 内置 Provider 的标识与图标,以及 `providers//` 内各 Provider 专属的账号导入格式与身份编辑器;跨 Provider 的编辑协调归共享组件 | | `stores/modules/`、`router/`、`plugins/` | 应用级登录与界面状态、路由和初始化;服务端数据的权威仍在后端 | -| `views/<页面>/index.vue`、`views/<页面>/components/` | 页面组合与局部交互;复杂组件按职责拆成目录入口和相邻模块 | -| `views/<页面>/composables/` | 页面查询、轮询、表单及操作生命周期 | -| `presenter.ts`、页面 `utils/` | 纯展示投影或该页面拥有的业务转换,不启动请求 | -| `components/usage/`、`components/account/` | 跨页面复用的用量、健康时间线、套餐和额度窗口展示,以及账号与分组共用的模型限制编辑器 | +| `views/<页面>/index.vue`、`views/<页面>/components/` | 页面入口与页面内组件;多文件组件通过自己的 `index.vue` 提供界面,私有实现放在组件目录内 | +| `views/<页面>/composables/`、`views/<页面>/utils/` | 页面查询、协调及多个组件共享的流程;页面内共享的纯函数 | +| `components/*.vue`、`components/<组件>/index.vue` | 跨页面共享的单文件或多文件组件,如用量表格、健康时间线、额度窗口和模型限制编辑器;辅助计算及局部交互随组件放置 | | `composables/` | 请求取消与过期结果隔离、分页、选择、异步动作、目录加载等共享机制 | | `i18n/` | Vue I18n 实例、三语资源和应用语言策略;从全局 Composer 派生 UI 库语言,不翻译用户数据或远端自由文本 | -| `utils/` | 按用途分开的数据解析、数字与时长格式化、位置校验、客户端配置、插件导航及颜色工具 | +| `utils/` | 跨页面使用的数据判断、数字/金额/时长格式化、位置校验、颜色和通用操作辅助;业务专用逻辑放回所属页面或组件 | + +页面采用统一骨架,目录按实际需要创建: + +```text +views/<页面>/ +├── index.vue +├── components/ +│ ├── SimpleCard.vue +│ └── complex-editor/ +│ ├── index.vue +│ ├── EditorFields.vue +│ ├── useEditor.ts +│ └── model.ts +├── composables/ +├── utils/ +└── constants.ts +``` + +- 页面根目录放入口、页面级逻辑与常量,卡片、弹窗和页面分区统一放在 `components/`,不在根目录另按功能或厂商平行分组。实际子路由可保留子页面目录,如 `views/plugins/page/` +- 普通组件使用按职责命名的 PascalCase `.vue` 文件;需要封装一组共同维护的私有实现时,使用小写连字符目录和 `index.vue` 入口。文件长度或只有一个调用方不单独构成拆分或合并理由 +- 不为整页内容再套一个目录;页面布局与独立卡片直接放在页面 `components/`。多文件组件内部优先平铺,私有子组件、composable、类型和纯函数就近放置,不机械重复 `components/composables/utils` 层级。进一步分目录应当封装独立的界面职责或生命周期 +- `composables/` 保留页面查询、操作协调和跨组件共享的流程,组件自己的请求、计时器、DOM 交互及清理随组件放置;`utils/` 只放页面内共享的纯函数,组件私有计算留在组件内 +- 复用范围扩大时再将代码上移到对应共享层。其他页面复用完整布局时引用布局组件,单文件组件直接引用 `.vue`,多文件组件引用 `index.vue`,不直接依赖其私有文件;独立复用的业务组件归应用级 `components/`,Provider 专属且跨页面共用的实现归 `providers//` + +共享 `components/` 沿用同一规则,不增加 `account/usage/charts` 等纯分类层或组件内部的 `shared/` 层。独立复用的单文件组件直接放在共享目录,组合组件按明确职责命名;供其他组件使用的单元格、展示投影和校验函数可作为组件模块的公开能力。通知实例接线归 `plugins/notification.ts`,插件页面地址归 `router/plugin.ts` + +账号页管理分组、模型限制、并发、代理与导入任务。行操作与批量导出读取服务端返回的账号能力。OpenAI 的 API Key、OAuth 传输与逐条 token 导入归 `providers/openai/accounts`,Provider 表单持有凭据草稿与校验规则。新增时向页面提交导入文档,编辑时仅提供变更的连接配置 + +运行设置由同一份草稿和配置版本原子保存。通用和平台设置分区组合 `views/settings/components/` 中的控件,备份、定价、客户端版本及隐私规则等多文件组件各自封装私有实现。平台分区按 Provider 展示专属配置,通用分区承载调度、并发与排队、重试、错误保护、凭据刷新、历史保留、全局模型映射及安全与访问设置 + +全局配置和 Key 覆盖共用 `components/request-profile/index.vue` 的身份编辑流程,各 Provider 在 `providers//request-profile/` 解释自己的配置字段。定价页按查询接口返回的档位编辑 JSON、原始字节与流式请求共用会话恢复和身份代际校验,身份变化后的迟到结果按取消处理。 流式成功正文由消费方持有读取、期限与取消;交付前失败时,请求层终止底层传输 -概览的数据请求和刷新由 `useDashboard` 持有,`views/dashboard/presenter.ts` 生成展示模型。 +概览页由 `useDashboard` 查询并刷新数据。主题预览通过 `views/dashboard/components/DashboardOverview.vue` 复用整页布局,两处分别传入接口响应与预览样本。指标、趋势和客户端身份卡片各自解释所需字段。 Key 创建与编辑共用 `useApiKeyEditor` 和 `ApiKeyFormModal`,`useApiKeyUse` 持有创建结果与使用操作的明文, 关闭对应弹窗或页面销毁时清除。 -用量表格的列、展示投影及健康时间线规则集中在 `components/usage/shared/`,管理页面与 Key 用量页共用展示, -各自的查询仍使用对应身份允许的 API +用量表格的列、单元格和展示投影放在 `components/usage-records-table/`,健康时间线及规则放在 +`components/request-health-timeline-card/`。管理页面与 Key 用量页共用展示,各自的查询仍使用对应身份允许的 API `useRequestState` 管理取消、请求序号与失效结果;分页按接口合同分别复用 `usePagedQuery` 或 `useStablePagedQuery`。 `useAsyncAction` 的 `loading` 是动作进行状态,调用方直接使用;接口错误由请求层提示,本地操作错误按动作配置处理。 @@ -524,6 +559,33 @@ WS 路由提示属于握手,连接复用时不重发;档位变化不重建 Core 只理解 `Operation`、能力要求、Provider 候选、稳定错误和 canonical event,不读取 Provider SDK 类型。Provider 独占 credential schema、OAuth、账号选择、模型目录、额度投影和上游 transport +三个内置 Provider 在各自的 `lib.rs` 返回同一个 `ProviderBundle`。组合根从这一组 Bundle 注册执行器、管理端口和后台任务。共同职责使用一致目录: + +| 目录 | 职责 | +| --- | --- | +| `admin/` | 适配管理端口,投影展示合同 | +| `billing/` | 内置价目、支持档位与费用计算,管理端口和执行路径共用 | +| `credential/` | 凭据与账号级 `catalog`、`quota` 服务 | +| `profile/` | 请求身份、版本选择与官方发行资料 | +| `provider/` | 推理执行和 worker 装配 | +| `transport/` | 出站协议与上游响应采集 | + +Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模型观测,`credential/quota` 管理额度快照。凭据续期后的目录修复由 `provider/workers` 编排。管理端连接测试固定账号并用其凭据查询项目,停用账号仍可接受探测 + +数据面协议入口位于 `gateway-api/src/data_plane`。Responses、Chat Completions、Messages 与 GenAI 共用 `generation` 的执行和交付流程。GenAI 从 URL 解码模型和生成方法,要求候选模型在原生目录中声明对应协议。Core 在 Key 的账号范围内匹配能力,Antigravity 将选中的 GenAI 请求封装为 Cloud Code 上游请求 + +GenAI 模型目录通过 Core 的原生操作路由判断过滤冻结账号范围;列表、详情和执行使用同一份能力事实。Antigravity 声明生成与输入计数能力,原生 GenAI 和 Messages 计数复用选号、画像、中间件及资源释放流程,出站调用独立的 Cloud Code `countTokens`。计数响应不产生生成用量或费用事实,失败不切换为本地估算 + +Antigravity 目录分别声明原生 GenAI 协议和接受转换的 Responses/Messages 协议;原生能力约束仍只匹配原生协议。`gateway-protocol::genai` 持有纯内容与增量事件映射,Responses 复用已有 Messages 转换能力,Chat 复用 API 层的 Responses 入口。Provider 的 `provider/translation` 负责选择和装配转换器,`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,并按冻结画像统一替换 AGY 系统指令。默认提示和可编辑配置归 Provider 的 `profile`,纯协议转换层不持有 AGY 身份规则 + +Antigravity 的业务头使用 API 保留的不透明多值字节,transport 统一执行账号身份、HTTP 传输及切号追踪头过滤。选号阶段从原会话绑定和 Core 的账号归属冻结切号事实,认领冲突后重新读取,不从重试排除集合推测归属 + +推理 HTTP 客户端按账号、凭据版本、代理和 UA 隔离,最多缓存 64 项并按最近使用淘汰;在途请求持有独立客户端引用,令牌、项目和系统指令不随连接池缓存 + +Antigravity 的 Cloud Code 传输固定使用 rustls 与 HTTP/1.1,gzip 协商和流式解压由本 Provider 持有,不启用会影响其他 Provider 的 reqwest 全局压缩特性。解压后的流继续遵循控制面和推理消费方的大小限制、取消及截止时间 + +跨协议响应在 Core 的响应中间件阶段之间转换。转换器在正常 EOF 时刷新最后内容块并发出终态,尾部用量先于完成事件交付;错误和取消不合成成功终态。转换状态随单次流释放,不增加账号级签名缓存或对话副本 + ### 连接与上游身份 Responses 下游连接的心跳和退出由 API 拥有,每条 WS 使用独立取消信号,沿 Core 的 `ResponseControl` 传到 Provider 请求上下文。 @@ -602,7 +664,7 @@ OpenAI 模型目录用于发现与原生 Responses 账号资格筛选。 首次初始化使用 Provider 内置默认值。 官方发布资料与用户选择分开:OpenAI 在 Redis 按 Provider、客户端、平台、架构隔离可重建版本缓存, 离线版本、制品身份及预设环境默认值集中在 - [`transport/profile/baseline.rs`](../backend/crates/providers/openai/src/transport/profile/baseline.rs),由发布检查与预设解析共用。 + [`profile/baseline.rs`](../backend/crates/providers/openai/src/profile/baseline.rs),由发布检查与预设解析共用。 Desktop 完整制品元组原子更新。CLI 的 TUI/Exec 入口共用官方 CLI 版本资料,Provider 在一次身份解析中 生成一致的 UA、入口后缀与配套请求头,后台更新不修改用户选择的运行环境。 完整自定义 UA 经 Provider 校验后原样传递,配套头统一解析;固定和自定义配置不受后台更新影响。 @@ -712,8 +774,21 @@ Continuation 受原请求的 Client Key、账号范围、Provider 和发送/交 - xAI 使用客户端提交的完整历史作为重放输入 - scope 外账号与跨 Key 复用均拒绝;发送结果不明时,仅接受 Provider 明确给出的有界传输恢复意图 -OpenAI Provider 解释官方逻辑 `session_id` 与 `thread_id`,按 Client Key 隔离账号绑定, -账号亲和模式随请求策略冻结: +账号亲和模式和保留时长由 Core 的 `AccountSelectionPolicy` 随请求冻结,设置页在通用区域编辑 +`ProviderSessionAffinityState` 提供通用的偏好投影、严格等待和认领目标规则;Store 以 Provider 和不透明会话键隔离版本绑定,发送前 CAS 提交,冲突先释放租约再重读 +协议身份、资格判断及原生续接约束由各 Provider 拥有,不进入共享策略 + +OpenAI 与 Antigravity 的内置 `round_robin` 在最高可调度权重层按账号 ID 轮换,使用按 Client Key 和 Provider 隔离的分配游标 +分配游标只读,取得租约后通过共享准入接口推进;有会话认领时,游标和绑定原子提交,冲突先释放租约再重选 +亲和命中、保留主绑定的临时分流、固定账号和插件显式选号不消耗轮询位置;插件委托仍参与内置轮询 + +Antigravity 在转换前识别 GenAI 会话头及正文 `sessionId`/`session_id`(头优先)、Codex 逻辑会话和 Claude Code 会话,绑定按 Client Key、模型和入站协议隔离 +xAI 继续从自身请求身份派生模型级亲和键,共用版本绑定及 TTL;上游 session ID 和推理重放身份仍由传输模块持有 +两者的优先模式在容量分流时保留合格的主绑定,绑定不再满足当前资格时迁移;严格模式等待繁忙主账号,关闭排队或资格失效时允许重选 +原生固定账号请求不改写已有主绑定,诊断请求和没有亲和键的请求不访问绑定存储 + +OpenAI Provider 解释官方逻辑 `session_id` 与 `thread_id`,按 Client Key 隔离账号绑定 +会话和轮次关系包括根线程、后代和生图借号,具体模式行为由 OpenAI Provider 解释: - 宽松:会话内请求直接按调度策略选号,不使用主账号偏好,成功准入后更新当前账号 - 优先模式在首次成功准入时认领主账号,短时容量或单模型限制触发临时分流 @@ -725,7 +800,6 @@ OpenAI Provider 解释官方逻辑 `session_id` 与 `thread_id`,按 Client Key 已有绑定的后代只跟随当前账号,账号不可用时排队,根迁移后重读共享绑定 可关联的 Search、Images、Live 创建请求共用会话绑定。严格模式下,授权池内的主账号未通过原生 Images 的模型、套餐或协议筛选时,根线程和后代均可从合格账号中借号。取得生图账号租约后,按选号时读到的主绑定原子续期;绑定已变化则重新选号。主账号具备生图资格但繁忙时,后代仍跟随主账号排队 -内置 `round_robin` 在最高可调度权重层按账号 ID 轮换。游标按 Client Key 和 Provider 隔离,在取得租约后推进;有会话绑定时,两者原子提交。并发首绑只占一个位置,亲和命中和插件显式选号不推进游标。插件委托仍走内置轮询,优先模式已有绑定时沿用会话派生的后备顺序 插件显式选号由 Core 复核账号资格并取得租约,native continuation 受独立的状态 owner 与安全重放边界约束 OpenAI 固定归属请求直接读取目标账号,其余请求按冻结的账号 ID 范围查询 Store @@ -736,7 +810,7 @@ OpenAI 固定归属请求直接读取目标账号,其余请求按冻结的账 Store 只保存带版本的绑定事实,Provider 在取得租约后、发送前原子认领、续期或按模式迁移;快照冲突释放租约并重新选择。 首次认领不依赖根线程先发请求,独立后台任务也使用自身会话绑定。 -Messages 的 Claude Code 明确会话身份由 `gateway-protocol::anthropic` 解析,OpenAI Provider 在选号前按 Client Key 派生独立命名空间的亲和键, +Messages 的 Claude Code 明确会话身份由 `gateway-protocol::anthropic` 解析;OpenAI Provider 在选号前按 Client Key 派生独立命名空间的亲和键, 沿用现有绑定与调度策略;原生执行在 attempt 改写后、协议转换前复验身份,不建立 OpenAI 轮次关联或原生续接归属。 OpenAI Provider 对无显式会话的 Responses 和 Chat Completions 入站请求,可按客户端缓存键或对话开头形成账号亲和。Messages 入站请求不按对话内容绑定账号。 亲和键按 Client Key 隔离,与会话键使用不同命名空间,不建立轮次关联或原生续接归属。 @@ -852,9 +926,14 @@ Runtime 在父调用资源表中持有读取句柄并传播取消,SDK 保留 Provider 是内置价目、服务档位、模态和工具费规则的唯一 owner;Core metering 定义中立价格覆盖与 精确金额运算。Admin 管理人工覆盖与手动同步,Host `pricing` 适配固定的 models.dev HTTPS 来源, -由组合根注入 Admin 的 `PricingSource` 端口;Store 负责来源层、人工层与审计的事务持久化。 +由组合根注入 Admin 的 `PricingSource` 端口。跨产品参考模型由 Provider 明确登记,Admin 将外部价目 +投影为已注册 Provider 的上游模型 ID;Store 负责来源层、人工层与审计的事务持久化。 同步不能覆盖人工项,更新仅修改选中的模型。HTTP 合同与价格边界见 [模型定价 API](api.md#模型定价) +各 Provider 的私有 `billing` 模块按 `catalog` 与 `calculate` 分离价目和计算,模态专属逻辑按需拆分。 +计价只消费显式传入的模型、用量、档位和冻结价格,不依赖 Provider 内的执行、传输或凭据服务。 +账号额度查询与上游用量采集仍由原有服务负责,不能因同名 usage 或 billing 接口混入本地费用计算 + 编译 RuntimeSnapshot 时合并同步与人工配置,Provider 缺省项仍由其内置表解释。不可变价格集合经 Arc 随 RoutingPlan 冻结并进入所有 attempt,不在推理请求中读取数据库、Redis 或外部价目,也不复制 整份价目。Provider 按当前 attempt 实际发送的上游模型查价,响应声明的模型只作观测,费用明细复用同一口径; @@ -879,8 +958,8 @@ HTTP validation 会改变路由快照或安全配置的 mutation 在同一 PostgreSQL 事务中提交业务事实、推进内部 `config_revision` 并写入脱敏审计。账号、分组等响应中的 `configRevision` 表示已提交配置, -不构成所有写入的统一前置条件。运行设置整体替换必须携带读取版本,Store 在同一事务比较后才提交, -防止覆盖并发修改;插件、代理等资源使用各自的 `revision` / `expectedRevision`,不能与全局版本混用 +不构成所有写入的统一前置条件。Store 记录最近一次运行设置写入的发布版本,整体替换时在事务内检查草稿读取后是否发生设置写入。 +插件、代理等资源使用各自的 `revision` / `expectedRevision`,不能与全局版本混用 账号组的展示投影与配置提交结果分离;提交后的展示查询失败不阻止已提交版本发布,响应可不附带展示记录 @@ -999,6 +1078,11 @@ credential 与 quota 是两组独立事实:credential refresh 不等于 quota 团队身份不推断为 Free,订阅查询失败不影响额度观测 普通 Token 续期与刷新退避保留提交时的账号资料及额度快照,显式凭据轮换仍按原子提交合同失效旧观测。 xAI Provider 在缺少可展示上游额度时投影本地 24 小时滚动统计,Admin 按该窗口展示日用量,额度预测使用完整周/月窗口 +- Antigravity 使用 Google OAuth 离线授权,账号文件导出凭据、身份、有效期及已有观测,导入通过 refresh token 重新验证权限与主体,不采信文件中的历史观测。 + OAuth 每轮操作从运行策略读取全局 AGY 选择,由 `profile` 统一解析并冻结出站身份,换码、刷新和身份查询使用同一画像,不读取 Key 覆盖。 + `loadCodeAssist` 的付费套餐优先于基础套餐;分组额度和模型额度保存到同一带凭据版本的快照,独立模型耗尽不升级为整个账号耗尽。 + 原生额度窗口只投影上游模型分组,不归属整号 Token;Admin 独立读取过去 24 小时的本地用量及统计周期,不向额度列表补入本地窗口。选号及互联分别读取同一份模型额度事实,失效观测保持未知。 + 正常续期后续接同一身份的目录,保留原观测时间并校验新凭据版本与套餐;目录缺失立即尝试重新发现,失败由后台重试 - 账号导入和 OAuth complete(包括重新授权)在凭据提交、Provider 缓存失效与运行快照发布后, 由 Admin 共用流程后台读取一次额度;不等待观测完成才返回管理请求,失败记录告警但不回滚账号事务。 同身份重新授权在事务内保留额度观测和按桶预热进度,旧凭据版本的在途观测无法覆盖新版本。 @@ -1317,6 +1401,12 @@ OpenAI 客户端画像由 Provider 每小时检查发布元数据,发布标识 同版本的有效制品缓存每 24 小时续期,保留 30 天;续期保留原核验时间,失败不推进成功写入游标。 版本及缓存更新失败保留当前画像,下轮继续尝试;Host 只监督调度与取消。 +Antigravity 每天检查官方发布资料,后台按已使用的客户端、平台和架构核对发布包版本, +CLI 同时校验官方清单的 SHA-512;核验不执行下载程序,也不发送模型请求。 +核验事实绑定完整制品标识,使用同一缓存端口保留 30 天,每 24 小时续期并保留原核验时间。 +版本或制品变化后重新核验,失败不将旧证据套用到新制品;发布包核验不代表 TLS 或完整请求指纹一致, +未知版本的请求构建号仍省略。 + 互联同步使用账号出口的受管 HTTP 客户端,不跟随跳转;网络等待不持有数据库事务。 运行期排程、并发预算、连接失效和观测提交见 [CPR 互联观测](#cpr-互联观测),失败遵守退避及上游 `Retry-After` @@ -1392,8 +1482,7 @@ Compose 的 `stop_grace_period` 必须覆盖后台关闭预算并留出进程清 协议字段提取集中在所属 Provider 的诊断模块,调用点不重复解释字段或重试规则。 管理用例集中归纳缺口,API 对同一份脱敏文档生成 ZIP、结构化 JSON 与文本摘要,前端只负责下载。 关键事实复用请求现有 trace JSON 持久化,ZIP 不另行存储;预算和字段合同见诊断接口章节 -- 真实 secret 不进入普通日志、Debug、fixture 或 audit details;明文只能通过账号导出、Key reveal、 - 备份设置等明确的敏感 Admin 合同返回 +- 真实 secret 不进入普通日志、Debug、fixture 或 audit details;明文只能通过账号导出、Key reveal 等明确的敏感 Admin 合同返回 - OAuth pending flow 使用有期限、带 owner 的一次性 claim;事务成功后才消费,失败释放 claim ### 在线更新与回滚 @@ -1460,6 +1549,7 @@ Store 在同一可重复读快照下导出业务表和已发布小时汇总, ### 验证命令 组合根的 workspace architecture tests 检查成员清单、依赖 DAG、公开模块面、源码纪律以及生产/测试模块镜像关系; +全部 workspace 成员同时参与同级 owner 的依赖环检查;内置 Provider 的共同 owner 使用一致目录,计价模块禁止反向依赖所在 Provider 的其他内部 owner; 具体行为边界由各 crate 集成测试维护 后端验证从 `backend/Cargo.toml` 执行,仓库根目录没有 Cargo manifest: diff --git a/docs/development.md b/docs/development.md index 09013466e..41b204052 100644 --- a/docs/development.md +++ b/docs/development.md @@ -57,7 +57,7 @@ pnpm --dir frontend dev [后端 Workspace 边界](architecture.md#3-workspace-边界) · [前端模块职责](architecture.md#34-前端模块职责) · [共享 UI 组件架构](../modules/ui/playground/guide/architecture.md) Messages 与 Responses 的纯协议转换位于 `backend/crates/gateway-protocol/src/anthropic/`, -HTTP 入口位于 `backend/crates/gateway-api/src/openai/messages.rs`, +HTTP 入口位于 `backend/crates/gateway-api/src/data_plane/messages.rs`, 账号协议分派、HTTP 执行和计数位于 `backend/crates/providers/openai/src/provider/messages/`。 模块职责见 [Provider 与协议边界](architecture.md#5-provider-与协议边界) diff --git a/docs/theme.md b/docs/theme.md index abd65dcfe..b7cd81cdf 100644 --- a/docs/theme.md +++ b/docs/theme.md @@ -42,11 +42,11 @@ Vue 组件通过 CSS Variables 和 Tailwind CSS 4 使用主题,无需 Ant Desi | 场景 | 参考入口 | 关注点 | | --- | --- | --- | -| 页面头部 | `@codex-proxy/ui` 的 `ZPageHeader`、[系统概览](../frontend/src/views/dashboard/components/DashboardContent.vue) | 简短标题、必要的统计范围或状态、就近操作 | +| 页面头部 | `@codex-proxy/ui` 的 `ZPageHeader`、[系统概览](../frontend/src/views/dashboard/components/DashboardOverview.vue) | 简短标题、必要的统计范围或状态、就近操作 | | 内容与指标 | `@codex-proxy/ui` 的 `ZCard`、[用量概览卡片](../frontend/src/views/usage/components/UsageSummaryCards.vue) | 可选说明、紧凑摘要、数值与辅助信息的主次 | -| 表单帮助 | [API Key 账号字段](../frontend/src/views/accounts/components/AccountApiKeyFields.vue) | 直接命名字段,在对应位置提供短提示和示例 | +| 表单帮助 | [API Key 账号字段](../frontend/src/providers/openai/accounts/ApiKeyFields.vue) | 直接命名字段,在对应位置提供短提示和示例 | | 详细规则 | [自动审批并发帮助](../frontend/src/views/settings/components/ConcurrencyPolicyCard.vue) | 标签旁帮助图标打开 Popover,页面保留短提示,浮层补充规则和示例 | -| 账号与用量展示 | [账号额度窗口](../frontend/src/components/account/account-usage-window/index.vue)、[共用用量表格](../frontend/src/components/usage/UsageRecordsTable.vue) | 复用后端展示字段和共享 presenter,管理端与 Key 页保持同一展示口径 | +| 账号与用量展示 | [账号额度窗口](../frontend/src/components/account-usage-window/index.vue)、[共用用量表格](../frontend/src/components/usage-records-table/index.vue) | 复用后端展示字段和共享 presenter,管理端与 Key 页保持同一展示口径 | 页面查询、表单状态与纯展示逻辑的归属见 [前端模块职责](architecture.md#34-前端模块职责) @@ -65,7 +65,7 @@ Vue 组件通过 CSS Variables 和 Tailwind CSS 4 使用主题,无需 Ant Desi - 繁体中文只转换简体原文的字形,保持措辞与语序,不替换地区用词,例如 `数据 → 數據`、`设置 → 設置` - 只翻译应用拥有的文本,具体后端错误、上游诊断、日志和独立插件内容保留原文;固定错误码在请求层映射,业务分类码优先保留后端公开的具体原因,无原因时使用本地兜底文案 - 侧边栏语言图标展开就地选项,选择后切换并收起;品牌区固定显示 `Codex Proxy`、`Rust build` 和版本号 -- UI 库默认文案由 `ZConfigProvider` 提供,命令式通知通过 `utils/notification.ts` 绑定同一个语言来源,组件约定见 [UI 国际化](../modules/ui/playground/guide/i18n.md) +- UI 库默认文案由 `ZConfigProvider` 提供,命令式通知通过 `plugins/notification.ts` 绑定同一个语言来源,组件约定见 [UI 国际化](../modules/ui/playground/guide/i18n.md) 正文默认使用 Inter Variable,中文及缺失字形按系统无衬线字体栈回退。代码使用 JetBrains Mono Variable,中文由系统字体补齐,不随语言切换额外修改字重。默认值由 UI 库持有,应用负责加载字体包,图表读取同一字体 Token @@ -371,7 +371,7 @@ Store 在其他入口发生变化时更新保存基线;没有未保存修改 样式,并把预览内容 Teleport 到影子根中。预览可独立切换浅色和深色,不受外层主题影响。 画布和操作控件先显示,选中的预览内容异步加载,就绪前画布留空,资源加载完成后同步影子根样式 -- **首页画板**复用真实 `DashboardContent` 和固定 fixture,不请求接口,也不启动自动刷新 +- **首页画板**通过 `views/dashboard/components/DashboardOverview.vue` 展示固定样本,请求和刷新由真实概览页管理 - **组件概览**展示基础组件、表格、空状态、骨架、浮层和菜单等关键状态 - 画板固定为 `1600 × 1808`,使用 CSS `zoom` 重排,不使用 `transform: scale()` 长期缩放文字 - 空白区域可拖拽,滚轮以指针为锚点缩放,并提供缩小、100%、放大和适应画板操作 diff --git a/frontend/build/plugin-bridge.ts b/frontend/build/plugin-bridge.ts index 58d1c1b40..c1da02a42 100644 --- a/frontend/build/plugin-bridge.ts +++ b/frontend/build/plugin-bridge.ts @@ -6,7 +6,7 @@ import { build } from 'vite' export function pluginBridge(): Plugin { const id = 'virtual:plugin-bridge-source' const resolvedId = `\0${id}` - const entry = fileURLToPath(new URL('../src/views/plugins/management/bridge-runtime.ts', import.meta.url)) + const entry = fileURLToPath(new URL('../src/views/plugins/components/plugin-management-frame/bridge-runtime.ts', import.meta.url)) const dependencies = new Set() return { name: 'plugin-management-bridge', diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 56051cbcb..4a10cdafb 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -4,8 +4,7 @@ import { useDebounceFn, useDevicePixelRatio, useEventListener, useWindowSize } f import { watch } from 'vue' import { useI18n } from 'vue-i18n' import { RouterView } from 'vue-router' -import { applyLocale } from '@/i18n/locale' -import { uiLocale } from '@/i18n/ui' +import { applyLocale, uiLocale } from '@/i18n' const { locale } = useI18n({ useScope: 'global' }) const overlay = (navigator as Navigator & { windowControlsOverlay?: EventTarget & { getTitlebarAreaRect: () => DOMRect } }).windowControlsOverlay diff --git a/frontend/src/api/index.ts b/frontend/src/api/index.ts index d365b1b92..50d3869f1 100644 --- a/frontend/src/api/index.ts +++ b/frontend/src/api/index.ts @@ -7,6 +7,9 @@ export * from './modules/dashboard' // 账号分组 export * from './modules/groups' +// Key 自助用量查询 +export * from './modules/key-usage' + // API Keys 管理 export * from './modules/keys' @@ -27,4 +30,5 @@ export * from './modules/usage' // 跨模块共享的接口类型 export type { RequestLocation, RequestLocationDetection } from './types/location' +export type { ProviderRequestProfile, ProviderRequestProfiles, ProviderRequestProfileUpdates } from './types/request-profile' export type { RelativeTimeView } from './types/time' diff --git a/frontend/src/api/modules/accounts/index.ts b/frontend/src/api/modules/accounts/index.ts index 92bbf9f4a..c913ace34 100644 --- a/frontend/src/api/modules/accounts/index.ts +++ b/frontend/src/api/modules/accounts/index.ts @@ -36,12 +36,12 @@ export type { AccountBatchUpdateResponse, AccountConcurrencyEntry, AccountConcurrencyPage, + AccountConnectionUpdate, AccountDeletionResponse, AccountListResponse, AccountPageMeta, AccountSummary, AccountUpdateResponse, - ApiKeyConfiguration, } from './management' export { diff --git a/frontend/src/api/modules/accounts/management.ts b/frontend/src/api/modules/accounts/management.ts index 63d9600f8..9f4931b9a 100644 --- a/frontend/src/api/modules/accounts/management.ts +++ b/frontend/src/api/modules/accounts/management.ts @@ -52,8 +52,15 @@ interface AccountListParams { sortDirection?: string } +export interface AccountConnectionUpdate { + baseUrl?: string + protocol?: 'responses' | 'messages' + transport: 'http' | 'prefer_websocket' + apiKey?: string +} + interface AccountUpdateParam { - connection?: { baseUrl?: string, protocol?: ApiKeyConfiguration['protocol'], transport: ApiKeyConfiguration['transport'], apiKey?: string } + connection?: AccountConnectionUpdate outboundProxyId?: string accountId: string name?: string @@ -92,12 +99,6 @@ interface AccountConcurrencyParams extends AccountIdParam { pageSize: number } -export interface ApiKeyConfiguration { - base_url: string - protocol: 'responses' | 'messages' - transport: 'http' | 'prefer_websocket' -} - export interface AccountConcurrencyEntry { leaseId: string requestId: string | null diff --git a/frontend/src/api/modules/accounts/types.ts b/frontend/src/api/modules/accounts/types.ts index e2d4e4d36..2ca9e9dda 100644 --- a/frontend/src/api/modules/accounts/types.ts +++ b/frontend/src/api/modules/accounts/types.ts @@ -208,6 +208,10 @@ export interface AccountUpstream { } export interface AccountCapabilities { + credentialRefresh: boolean + reauthorize: boolean + credentialExport: boolean + modelCatalogDownload: boolean quotaSettingsSupported: boolean quotaCredits: boolean quota: boolean diff --git a/frontend/src/api/modules/dashboard.ts b/frontend/src/api/modules/dashboard.ts index b25887590..df5236c7b 100644 --- a/frontend/src/api/modules/dashboard.ts +++ b/frontend/src/api/modules/dashboard.ts @@ -195,7 +195,7 @@ export interface DashboardSummaryResponse { interface DashboardQuery { period: 'today' asOf: number - kind: string + kind: DashboardTrendKind } export function getDashboardSummary(data: DashboardQuery, options: RequestOptions = {}) { diff --git a/frontend/src/api/modules/keys.ts b/frontend/src/api/modules/keys.ts index 3f7300ae4..cced8ede3 100644 --- a/frontend/src/api/modules/keys.ts +++ b/frontend/src/api/modules/keys.ts @@ -1,6 +1,6 @@ import type { RequestOptions } from '../request' +import type { ProviderRequestProfile, ProviderRequestProfiles, ProviderRequestProfileUpdates } from '../types/request-profile' import type { AccountGroupRef } from './groups' -import type { ProviderRequestProfile, ProviderRequestProfiles, ProviderRequestProfileUpdates } from './settings/profiles' import request from '../request' export type ApiKeyRoutingScope = 'all' | 'groups' diff --git a/frontend/src/api/modules/settings/backups.ts b/frontend/src/api/modules/settings/backups.ts index ad3b14eb0..49f9406d1 100644 --- a/frontend/src/api/modules/settings/backups.ts +++ b/frontend/src/api/modules/settings/backups.ts @@ -7,7 +7,7 @@ export interface BackupSettingsView { region: string | null bucket: string | null accessKeyId: string | null - secretAccessKey: string | null + secretConfigured: boolean prefix: string | null forcePathStyle: boolean verified: boolean @@ -24,6 +24,7 @@ export interface BackupSettingsView { } export interface UpdateBackupStoragePayload { + storageRevision: number endpoint: string region: string bucket: string @@ -34,6 +35,7 @@ export interface UpdateBackupStoragePayload { } export interface UpdateBackupSchedulePayload { + storageRevision: number scheduleEnabled: boolean cronExpression: string retentionDays: number @@ -41,6 +43,7 @@ export interface UpdateBackupSchedulePayload { } export interface ConnectionTestResult { + storageRevision: number ok: boolean stage: string code: string | null @@ -122,9 +125,10 @@ export function updateBackupStorage(data: UpdateBackupStoragePayload) { }) } -export function testBackupStorage() { +export function testBackupStorage(storageRevision: number) { return request({ url: '/api/admin/settings/backups/storage/test', + data: { storageRevision }, method: 'POST', }) } diff --git a/frontend/src/api/modules/settings/index.ts b/frontend/src/api/modules/settings/index.ts index 0b37c5c8c..71ad28cf2 100644 --- a/frontend/src/api/modules/settings/index.ts +++ b/frontend/src/api/modules/settings/index.ts @@ -1,13 +1,14 @@ import type { RequestOptions } from '../../request' import type { RequestLocation, RequestLocationDetection } from '../../types/location' +import type { ProviderRequestProfiles, ProviderRequestProfileUpdates } from '../../types/request-profile' import type { CodexPrivacyPolicy } from './privacy' -import type { ProviderRequestProfiles, ProviderRequestProfileUpdates } from './profiles' import type { AccountErrorProtection } from './protection' import request from '../../request' export * from './backups' export * from './pricing' export * from './privacy' +export * from './profiles' export * from './protection' export * from './system' @@ -61,9 +62,9 @@ export interface RuntimeSettings { refreshConcurrency: number maxConcurrentPerAccount: number openaiGuardianReservedConcurrency: number - openaiAccountAffinity: AccountAffinity + accountAffinity: AccountAffinity maxAccountRotations: number - openaiSessionAffinityTtlHours: number + sessionAffinityTtlHours: number maxWaitingPerKey: number maxWaitingPerAccount: number keyQueueTimeoutSeconds: number diff --git a/frontend/src/api/modules/settings/pricing.ts b/frontend/src/api/modules/settings/pricing.ts index 45c46ba48..fbe72e15c 100644 --- a/frontend/src/api/modules/settings/pricing.ts +++ b/frontend/src/api/modules/settings/pricing.ts @@ -18,6 +18,7 @@ export interface ModelPricing { export type PricingMap = Record> export interface PricingCatalog { + supportedBands: Record defaults: PricingMap synced: PricingMap overrides: PricingMap diff --git a/frontend/src/api/modules/settings/profiles.ts b/frontend/src/api/modules/settings/profiles.ts index 3cd7f30f0..0fdcb3cbc 100644 --- a/frontend/src/api/modules/settings/profiles.ts +++ b/frontend/src/api/modules/settings/profiles.ts @@ -1,136 +1,33 @@ +import type { RequestOptions } from '../../request' import request from '../../request' -export type ProviderRequestProfile = Record -export type ProviderRequestProfiles = Record -export type ProviderRequestProfileUpdates = Record - -export interface PresetClientProfileSelection { - mode?: undefined - client: 'desktop' | 'cli' - platform: 'macos' | 'linux' | 'windows' - versionMode: 'latest' | 'fixed' +export interface RequestProfilePreview { + source: 'global' | 'override' + userAgent: string + versionSource: 'official' | 'custom' + verifiedAt: string | null + verifiedAtDisplay: string | null + checkedAt: string | null + checkedAtDisplay: string | null + error: string | null versionLag?: number | null - cliEntry?: 'tui' | 'exec' | null - osType?: string | null - originator: string | null - osVersion: string | null - arch: string | null - terminal: string | null - codexVersion: string | null - desktopVersion: string | null - desktopBuild: string | null } -export interface CustomClientProfileSelection { - mode: 'custom' - userAgent: string - originator?: string | null - codexVersion?: string | null -} - -export type ClientProfileSelection = PresetClientProfileSelection | CustomClientProfileSelection - -export function isValidInstallationSeed(value: unknown) { - return value == null || value === '' || (typeof value === 'string' && value.length === 36 && /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(value)) -} - -export interface ClientProfileOptions { - presets: ClientProfilePreset[] - globalConfiguration: ClientProfileSelection - maxVersionLag: number -} - -export interface ClientProfilePreview { - configuration: ClientProfileSelection - source: 'global' | 'override' - originator: string - osType: string - osVersion: string - arch: string - terminal: string - codexVersion: string - desktopVersion: string | null - desktopBuild: string | null - userAgent: string - versionSource: 'official' | 'custom' - versionLag: number | null - recognized?: boolean - verifiedAt: string | null - verifiedAtDisplay: string | null - checkedAt: string | null - checkedAtDisplay: string | null - error: string | null -} - -export interface ClientProfilePreset { - configuration: PresetClientProfileSelection - automaticAvailable: boolean - reason: string | null - defaults: Pick -} - -export function getClientProfileOptions() { - return request({ - url: '/api/admin/settings/client-profiles/openai', +export function getRequestProfileOptions(provider: string, options?: RequestOptions) { + return request({ + url: `/api/admin/settings/client-profiles/${encodeURIComponent(provider)}`, method: 'GET', - }) -} - -interface ClientProfilePreviewParam { - configuration: ClientProfileSelection | null -} - -export function previewClientProfile(data: ClientProfilePreviewParam) { - return request({ - url: '/api/admin/settings/client-profiles/openai/preview', - method: 'POST', - data, silent: true, + ...options, }) } -export interface XaiClientProfileSelection { - versionMode: 'latest' | 'fixed' - clientVersion: string | null - clientIdentifier: string - clientMode: string - targetOs: string - targetArch: string -} - -export interface XaiClientProfilePreview extends Omit { - configuration: XaiClientProfileSelection - source: 'global' | 'override' - userAgent: string - versionSource: 'official' | 'custom' - verifiedAt: string | null - verifiedAtDisplay: string | null - checkedAt: string | null - checkedAtDisplay: string | null - error: string | null -} - -interface XaiClientProfileOptions { - defaults: XaiClientProfileSelection - globalConfiguration: XaiClientProfileSelection -} - -interface XaiClientProfilePreviewParam { - configuration: XaiClientProfileSelection | null -} - -export function getXaiClientProfileOptions() { - return request({ - url: '/api/admin/settings/client-profiles/xai', - method: 'GET', - }) -} - -export function previewXaiClientProfile(data: XaiClientProfilePreviewParam) { - return request({ - url: '/api/admin/settings/client-profiles/xai/preview', +export function previewRequestProfile(provider: string, configuration: object | null, options?: RequestOptions) { + return request({ + url: `/api/admin/settings/client-profiles/${encodeURIComponent(provider)}/preview`, method: 'POST', - data, + data: { configuration }, silent: true, + ...options, }) } diff --git a/frontend/src/api/request/plugins/feedback.ts b/frontend/src/api/request/plugins/feedback.ts index 3aaa1b002..e2a465a10 100644 --- a/frontend/src/api/request/plugins/feedback.ts +++ b/frontend/src/api/request/plugins/feedback.ts @@ -1,5 +1,5 @@ import type { RequestContext, RequestNext } from '../types' -import { notification as ZNotification } from '@/utils/notification' +import { notification as ZNotification } from '@/plugins/notification' import { ApiError, isSessionRequired } from './error' // 共享刷新 Promise 的同一个失败只提示一次,弱引用不保留已结束请求 diff --git a/frontend/src/api/request/plugins/session.ts b/frontend/src/api/request/plugins/session.ts index 37d17a97d..d6f2fbde9 100644 --- a/frontend/src/api/request/plugins/session.ts +++ b/frontend/src/api/request/plugins/session.ts @@ -1,6 +1,6 @@ import type { RequestConfig, RequestContext, RequestNext } from '../types' import { t } from '@/i18n' -import { notification as ZNotification } from '@/utils/notification' +import { notification as ZNotification } from '@/plugins/notification' import { ApiError, isSessionRequired } from './error' // 会话失效是后端业务事实,登录凭据错误和 403 不清除已有会话 diff --git a/frontend/src/api/types/request-profile.ts b/frontend/src/api/types/request-profile.ts new file mode 100644 index 000000000..9bce0b2c6 --- /dev/null +++ b/frontend/src/api/types/request-profile.ts @@ -0,0 +1,3 @@ +export type ProviderRequestProfile = Record +export type ProviderRequestProfiles = Record +export type ProviderRequestProfileUpdates = Record diff --git a/frontend/src/components/account/account-usage-window/AccountRequestTimeline.vue b/frontend/src/components/AccountRequestTimeline.vue similarity index 88% rename from frontend/src/components/account/account-usage-window/AccountRequestTimeline.vue rename to frontend/src/components/AccountRequestTimeline.vue index 528e9a181..af5968955 100644 --- a/frontend/src/components/account/account-usage-window/AccountRequestTimeline.vue +++ b/frontend/src/components/AccountRequestTimeline.vue @@ -1,5 +1,5 @@