From ff59be9aca35a2fa32aea5e9aff5973efe674d49 Mon Sep 17 00:00:00 2001 From: info-talent <135145953+info-talent@users.noreply.github.com> Date: Sat, 17 Oct 2026 03:40:26 +0800 Subject: [PATCH 1/5] chore(release): sync upstream 0.2.17 and publish Sub4API 1.1.11 Preserve BPS customizations, point images and updates to info-talent/sub4api, and support GHCR-only releases without Docker Hub credentials. Validate portable release archives, legacy updater compatibility, and Unix executable permissions. --- .github/release-tools/release-images.sh | 5 +- .github/release-tools/release_matrix.py | 4 +- .github/release-tools/test_release_matrix.py | 13 +- .github/upstream-sync.json | 8 + .github/workflows/backend-ci.yml | 12 +- .github/workflows/main-release.yml | 13 +- .github/workflows/security-scan.yml | 2 +- .gitignore | 1 + .goreleaser.simple.yaml | 12 +- .goreleaser.yaml | 64 +- Dockerfile | 6 +- Dockerfile.goreleaser | 6 +- Makefile | 1 + README.md | 18 +- README_CN.md | 43 +- README_JA.md | 43 +- assets/partners/logos/aimzoon.jpg | Bin 25231 -> 0 bytes assets/partners/logos/modelflare.png | Bin 0 -> 5507 bytes assets/partners/logos/proxy4free.png | Bin 7529 -> 0 bytes backend/cmd/server/VERSION | 2 +- backend/cmd/server/wire.go | 7 + backend/cmd/server/wire_gen.go | 13 +- backend/cmd/server/wire_gen_test.go | 1 + backend/ent/group.go | 15 +- backend/ent/group/group.go | 5 + backend/ent/group_create.go | 57 + backend/ent/group_update.go | 18 + backend/ent/migrate/schema.go | 13 +- backend/ent/mutation.go | 56 +- backend/ent/runtime/runtime.go | 96 +- backend/ent/schema/group.go | 5 + backend/internal/config/config.go | 11 + backend/internal/config/config_test.go | 38 + backend/internal/domain/constants.go | 13 + backend/internal/domain/constants_test.go | 22 + backend/internal/domain/group_i18n.go | 113 ++ backend/internal/domain/group_i18n_test.go | 107 ++ .../handler/admin/account_codex_import.go | 12 +- .../admin/account_codex_import_test.go | 80 +- .../internal/handler/admin/account_handler.go | 4 +- .../account_handler_available_models_test.go | 9 +- .../internal/handler/admin/group_handler.go | 11 +- backend/internal/handler/api_key_handler.go | 10 +- .../handler/available_channel_handler.go | 13 + .../internal/handler/dto/group_localize.go | 49 + .../handler/dto/group_localize_test.go | 71 + backend/internal/handler/dto/mappers.go | 1 + backend/internal/handler/dto/types.go | 4 + backend/internal/handler/endpoint.go | 9 +- backend/internal/handler/endpoint_test.go | 3 + backend/internal/handler/gateway_handler.go | 21 +- .../internal/handler/gateway_models_test.go | 66 +- .../gemini_cached_contents_billing_test.go | 955 +++++++++++++ .../handler/gemini_cached_contents_handler.go | 848 ++++++++++++ .../gemini_cached_contents_handler_test.go | 264 ++++ .../internal/handler/gemini_v1beta_handler.go | 164 ++- .../handler/gemini_v1beta_handler_test.go | 76 +- .../handler/gemini_vertex_models_test.go | 83 ++ .../internal/handler/group_localize_test.go | 92 ++ .../internal/handler/model_plaza_handler.go | 19 +- .../handler/model_plaza_handler_test.go | 43 + backend/internal/handler/no_account_error.go | 6 +- .../internal/handler/no_account_error_test.go | 19 + .../handler/openai_gateway_handler.go | 5 + backend/internal/handler/ops_error_logger.go | 13 + .../handler/ops_error_logger_google_test.go | 135 ++ backend/internal/handler/payment_handler.go | 4 +- .../handler/payment_webhook_handler.go | 21 +- .../handler/payment_webhook_handler_test.go | 4 +- backend/internal/handler/redeem_handler.go | 6 +- .../internal/handler/security_audit_errors.go | 7 +- .../handler/security_audit_order_test.go | 1 + .../internal/handler/subscription_handler.go | 11 +- backend/internal/handler/usage_handler.go | 4 +- backend/internal/handler/wire.go | 2 + backend/internal/payment/provider/alipay.go | 73 +- .../internal/payment/provider/alipay_test.go | 127 ++ backend/internal/payment/provider/easypay.go | 186 ++- .../payment/provider/easypay_confirm_test.go | 253 ++++ .../payment/provider/easypay_query_test.go | 78 +- backend/internal/payment/types.go | 17 +- .../internal/pkg/antigravity/claude_types.go | 12 + .../pkg/antigravity/claude_types_test.go | 29 + backend/internal/pkg/antigravity/client.go | 51 +- .../internal/pkg/antigravity/client_test.go | 155 +++ backend/internal/pkg/antigravity/oauth.go | 6 +- .../internal/pkg/antigravity/oauth_test.go | 108 +- .../pkg/antigravity/request_transformer.go | 26 + .../antigravity/request_transformer_test.go | 61 + .../pkg/apicompat/anthropic_responses_test.go | 66 + .../pkg/apicompat/anthropic_to_responses.go | 10 +- .../anthropic_to_responses_response.go | 6 +- .../chatcompletions_anthropic_bridge.go | 10 +- .../chatcompletions_anthropic_bridge_test.go | 37 + .../chatcompletions_responses_test.go | 56 + .../apicompat/chatcompletions_to_responses.go | 10 +- .../responses_to_anthropic_request.go | 34 +- backend/internal/pkg/apicompat/types.go | 9 +- backend/internal/pkg/claude/constants.go | 6 + .../pkg/claude/constants_model_test.go | 13 + backend/internal/pkg/claude/effort_catalog.go | 9 + .../pkg/claude/effort_catalog_test.go | 19 + backend/internal/pkg/gemini/models.go | 1 + backend/internal/pkg/geminicli/models.go | 1 + backend/internal/repository/api_key_repo.go | 5 +- .../api_key_repo_integration_test.go | 4 + .../repository/billing_inflight_cache.go | 64 + .../repository/billing_inflight_cache_test.go | 69 + .../repository/gemini_cached_content_repo.go | 205 +++ ...ni_cached_content_repo_integration_test.go | 120 ++ backend/internal/repository/group_repo.go | 33 + .../repository/group_repo_integration_test.go | 169 +++ .../internal/repository/scheduler_cache.go | 4 +- .../repository/scheduler_cache_test.go | 17 + backend/internal/repository/setting_repo.go | 29 + backend/internal/repository/wire.go | 1 + .../server/routes/composite_platform_test.go | 47 + backend/internal/server/routes/gateway.go | 14 + .../routes/gateway_models_pinned_test.go | 8 + .../prompt_audit_route_coverage_test.go | 1 + backend/internal/service/account.go | 125 +- .../service/account_kimi_coding_test.go | 83 ++ .../service/account_stats_pricing_test.go | 2 +- .../internal/service/account_test_service.go | 28 +- .../account_test_service_antigravity_test.go | 66 + .../service/account_websearch_test.go | 20 +- backend/internal/service/admin_group.go | 16 +- .../internal/service/admin_group_duplicate.go | 1 + backend/internal/service/admin_service.go | 2 + .../service/admin_service_group_i18n_test.go | 150 ++ .../service/antigravity_gateway_compat.go | 2 +- .../service/antigravity_gateway_gemini.go | 2 + .../service/antigravity_gateway_retry.go | 7 +- .../service/antigravity_gateway_service.go | 88 +- .../antigravity_gateway_service_test.go | 172 +++ .../service/antigravity_gateway_streaming.go | 114 +- .../antigravity_gemini_thinking_variant.go | 44 +- ...ntigravity_gemini_thinking_variant_test.go | 20 +- .../service/antigravity_rate_limit_test.go | 31 + backend/internal/service/api_key_service.go | 2 + backend/internal/service/apicompat_config.go | 28 + .../internal/service/billing_cache_service.go | 127 +- .../service/billing_inflight_reservation.go | 74 +- backend/internal/service/billing_service.go | 80 +- .../internal/service/billing_service_test.go | 27 + backend/internal/service/channel_available.go | 2 + .../service/channel_monitor_checker.go | 4 +- .../channel_monitor_checker_body_test.go | 11 + .../service/cn_provider_probe_url_test.go | 79 +- .../service/cn_provider_quota_service.go | 25 +- backend/internal/service/cn_providers_test.go | 54 + .../internal/service/composite_model_route.go | 5 + .../service/composite_platform_test.go | 51 +- .../service/composite_route_resolver.go | 33 +- .../service/composite_route_resolver_test.go | 27 + .../internal/service/content_moderation.go | 13 +- .../gateway_anthropic_base_url_test.go | 106 ++ .../service/gateway_anthropic_passthrough.go | 12 +- backend/internal/service/gateway_bedrock.go | 16 +- .../service/gateway_claude_oauth_body.go | 6 +- .../gateway_context_management_test.go | 19 + .../internal/service/gateway_count_tokens.go | 37 +- backend/internal/service/gateway_forward.go | 4 +- .../gateway_forward_as_chat_completions.go | 2 +- .../service/gateway_forward_as_responses.go | 2 +- .../gateway_hotpath_optimization_test.go | 4 + .../gateway_image_reasoning_pricing_test.go | 2 +- .../service/gateway_model_availability.go | 3 + backend/internal/service/gateway_request.go | 53 +- .../service/gateway_request_haiku55_test.go | 55 + backend/internal/service/gateway_service.go | 32 +- .../service/gateway_upstream_request.go | 54 +- .../service/gateway_upstream_request_test.go | 73 + .../service/gateway_upstream_response.go | 14 +- .../internal/service/gateway_usage_billing.go | 175 ++- .../gateway_usage_billing_request_id_test.go | 18 + .../service/gateway_websearch_emulation.go | 38 +- .../gateway_websearch_emulation_test.go | 85 ++ .../service/gemini_cache_storage_pricing.go | 72 + .../gemini_cache_storage_pricing_test.go | 80 ++ .../internal/service/gemini_cached_content.go | 1226 +++++++++++++++++ .../gemini_cached_content_hardening_test.go | 480 +++++++ .../gemini_cached_content_not_found_test.go | 186 +++ .../service/gemini_cached_content_test.go | 522 +++++++ .../gemini_chat_completions_compat_service.go | 77 +- .../service/gemini_compat_thinking.go | 320 +++++ .../service/gemini_compat_thinking_test.go | 367 +++++ .../gemini_error_policy_single_check_test.go | 201 +++ .../service/gemini_error_policy_test.go | 215 ++- .../service/gemini_messages_compat_service.go | 524 ++++--- .../gemini_messages_compat_service_test.go | 99 ++ .../service/gemini_models_endpoints.go | 302 ++++ .../service/gemini_models_endpoints_test.go | 208 +++ .../gemini_native_reasoning_pricing_test.go | 9 +- backend/internal/service/gemini_quota.go | 4 + backend/internal/service/gemini_quota_test.go | 80 ++ .../gemini_vertex_api_key_forward_test.go | 165 +++ .../service/gemini_vertex_token_error.go | 60 + .../service/gemini_vertex_token_error_test.go | 207 +++ backend/internal/service/group.go | 1 + backend/internal/service/group_i18n.go | 64 + backend/internal/service/group_i18n_test.go | 83 ++ .../internal/service/model_plaza_service.go | 2 + backend/internal/service/model_rate_limit.go | 9 +- .../internal/service/model_rate_limit_test.go | 25 + .../openai_account_runtime_block_fastpath.go | 6 +- .../service/openai_account_scheduler.go | 2 +- .../service/openai_account_scheduler_test.go | 4 + .../openai_alpha_search_billing_test.go | 6 +- .../service/openai_codex_model_metadata.go | 12 +- .../openai_codex_model_metadata_test.go | 65 + .../service/openai_codex_models_service.go | 52 +- .../openai_codex_models_service_test.go | 34 +- .../service/openai_compact_fallback.go | 9 +- .../service/openai_gateway_cc_pipeline.go | 17 +- .../openai_gateway_chat_completions.go | 174 ++- ...teway_chat_completions_anthropic_native.go | 2 +- .../openai_gateway_chat_completions_raw.go | 12 +- .../openai_gateway_chat_completions_test.go | 545 +++++++- .../service/openai_gateway_cn_fixes_test.go | 2 +- .../service/openai_gateway_count_tokens.go | 4 +- .../service/openai_gateway_forward.go | 4 +- .../openai_gateway_grok_chat_bridge.go | 2 +- .../service/openai_gateway_messages.go | 12 +- .../openai_gateway_messages_chat_fallback.go | 5 +- .../openai_gateway_model_availability.go | 3 + .../service/openai_gateway_passthrough.go | 7 +- .../service/openai_gateway_request_body.go | 8 +- .../openai_gateway_response_flush_test.go | 6 +- .../openai_gateway_response_handling.go | 40 +- .../openai_gateway_responses_chat_fallback.go | 3 +- ...ai_gateway_responses_chat_fallback_test.go | 29 + .../service/openai_gateway_scheduling.go | 2 +- .../openai_gateway_search_surcharge_test.go | 3 + .../service/openai_gateway_service.go | 7 + .../internal/service/openai_gateway_usage.go | 30 +- .../openai_image_generation_controls_test.go | 106 ++ .../service/openai_model_retirement.go | 91 ++ .../service/openai_model_retirement_test.go | 236 ++++ .../internal/service/openai_models_list.go | 18 +- .../openai_response_model_rewrite_test.go | 2 +- .../service/openai_responses_created_at.go | 94 ++ .../openai_responses_created_at_test.go | 355 +++++ .../openai_responses_ingress_compat.go | 11 +- .../openai_subscription_long_context_test.go | 238 ++++ .../service/openai_ws_forwarder_ingress.go | 2 +- .../service/openai_ws_forwarder_support.go | 4 +- .../internal/service/openai_ws_http_bridge.go | 24 +- .../openai_ws_v2_passthrough_adapter.go | 4 +- .../internal/service/ops_upstream_context.go | 44 + .../internal/service/payment_config_plans.go | 4 + .../internal/service/payment_fulfillment.go | 66 +- .../payment_notification_confirm_test.go | 101 ++ backend/internal/service/payment_order.go | 13 +- .../service/payment_order_type_test.go | 80 ++ backend/internal/service/payment_refund.go | 277 +++- .../payment_refund_pending_hold_test.go | 312 +++++ .../internal/service/payment_refund_test.go | 42 +- .../service/payment_resume_service.go | 28 + .../service/payment_resume_service_test.go | 36 + backend/internal/service/payment_service.go | 2 + backend/internal/service/pricing_service.go | 60 +- .../internal/service/pricing_service_test.go | 140 +- backend/internal/service/ratelimit_service.go | 102 +- backend/internal/service/temp_unsched.go | 2 + .../service/temp_unsched_scope_test.go | 493 +++++++ backend/internal/service/update_service.go | 2 +- backend/internal/service/upstream_models.go | 271 +++- .../upstream_models_antigravity_test.go | 245 ++++ .../service/upstream_models_vertex_test.go | 276 ++++ .../service/vertex_service_account.go | 113 +- .../service/vertex_service_account_test.go | 56 + backend/internal/service/wire.go | 8 + backend/internal/util/logredact/redact.go | 3 + .../internal/util/logredact/redact_test.go | 22 + backend/internal/web/embed_test.go | 8 +- backend/migrations/242_group_i18n.sql | 5 + .../migrations/243_gemini_cached_contents.sql | 30 + ...4_gemini_cached_contents_channel_usage.sql | 4 + ..._gemini_cached_contents_mutation_lease.sql | 10 + .../model_prices_and_context_window.json | 80 +- changelog/1.1.11/CHANGELOG.md | 24 + deploy/.env.example | 5 +- deploy/APPLE_CONTAINER.md | 6 +- deploy/DOCKER.md | 8 +- deploy/Dockerfile | 6 +- deploy/README.md | 10 +- deploy/apple-container.sh | 2 +- deploy/build_image.sh | 2 +- deploy/config.example.yaml | 18 +- deploy/docker-compose.local.yml | 2 +- deploy/docker-compose.standalone.yml | 2 +- deploy/docker-compose.yml | 2 +- deploy/docker-deploy.sh | 2 +- deploy/install.sh | 6 +- deploy/sub2api.service | 2 +- deploy/tests/install-github-token-test.sh | 16 +- docs/OPENAI_GPT55_RETIREMENT.md | 43 + frontend/package.json | 5 +- .../components/account/AccountGroupsCell.vue | 9 +- .../components/account/AccountTestModal.vue | 2 +- .../components/account/AccountUsageCell.vue | 35 +- .../components/account/CreateAccountModal.vue | 406 ++++-- .../components/account/EditAccountModal.vue | 276 +++- .../account/ModelWhitelistSelector.vue | 3 +- .../components/account/UsageProgressBar.vue | 7 +- .../__tests__/AccountUsageCell.spec.ts | 95 ++ .../__tests__/CreateAccountModal.spec.ts | 146 ++ .../__tests__/EditAccountModal.spec.ts | 204 +++ .../__tests__/ModelWhitelistSelector.spec.ts | 22 +- .../__tests__/UsageProgressBar.spec.ts | 20 + .../admin/account/AccountTableFilters.vue | 52 +- .../admin/account/AccountTestModal.vue | 2 +- .../__tests__/AccountTableFilters.spec.ts | 149 -- .../components/admin/group/GroupI18nField.vue | 179 +++ .../admin/group/GroupRPMOverridesModal.vue | 17 +- .../admin/group/GroupRateMultipliersModal.vue | 2 +- .../group/__tests__/GroupI18nField.spec.ts | 197 +++ .../GroupRPMOverridesModal.requests.spec.ts | 100 ++ .../GroupRateMultipliersModal.edit.spec.ts | 52 + frontend/src/components/common/GroupBadge.vue | 5 +- .../src/components/common/LocaleSwitcher.vue | 2 + .../components/common/PlatformTypeBadge.vue | 2 +- frontend/src/components/common/Select.vue | 1 + .../src/components/common/VersionBadge.vue | 2 +- .../common/__tests__/LocaleSwitcher.spec.ts | 60 + .../common/__tests__/Select.ime.spec.ts | 32 + .../components/payment/PaymentQRDialog.vue | 3 +- .../components/payment/PaymentStatusPanel.vue | 3 +- .../__tests__/paymentCountdown.spec.ts | 68 + .../__tests__/useGeminiOAuth.errors.spec.ts | 39 + .../__tests__/useModelWhitelist.spec.ts | 25 + frontend/src/composables/useGeminiOAuth.ts | 5 +- frontend/src/composables/useModelWhitelist.ts | 53 +- .../MonitorSettingsPanel.vue | 32 + .../__tests__/MonitorSettingsPanel.spec.ts | 153 ++ .../src/i18n/locales/en/admin/accounts.ts | 42 +- frontend/src/i18n/locales/en/admin/ops.ts | 1 + .../src/i18n/locales/en/admin/overview.ts | 6 + frontend/src/i18n/locales/en/batchImage.ts | 6 +- .../src/i18n/locales/en/channelMonitorV2.ts | 2 + .../src/i18n/locales/zh/admin/accounts.ts | 42 +- frontend/src/i18n/locales/zh/admin/ops.ts | 1 + .../src/i18n/locales/zh/admin/overview.ts | 6 + frontend/src/i18n/locales/zh/batchImage.ts | 6 +- .../src/i18n/locales/zh/channelMonitorV2.ts | 2 + frontend/src/types/index.ts | 21 + .../__tests__/geminiExplicitCache.spec.ts | 50 + frontend/src/utils/geminiExplicitCache.ts | 47 + frontend/src/views/admin/AccountsView.vue | 1 - frontend/src/views/admin/GroupsView.vue | 53 +- .../ops/components/OpsDashboardHeader.vue | 6 +- .../ops/components/OpsRequestDetailsModal.vue | 33 + .../OpsDashboardHeader.timezone.spec.ts | 54 + .../__tests__/OpsRequestDetailsModal.spec.ts | 31 +- .../views/admin/ops/utils/accountNameMap.ts | 33 + .../src/views/user/ChannelStatusV1View.vue | 8 +- frontend/src/views/user/PaymentQRCodeView.vue | 3 +- frontend/src/views/user/PaymentView.vue | 2 - frontend/src/views/user/StripePaymentView.vue | 17 +- .../ChannelStatusV1View.details.spec.ts | 77 ++ .../user/__tests__/StripePaymentView.spec.ts | 71 +- scripts/release/archive.py | 44 + scripts/release/build-archives.sh | 14 +- scripts/release/notes.py | 12 +- scripts/release/prepare.sh | 22 +- scripts/release/test_release.py | 62 +- 367 files changed, 21227 insertions(+), 1656 deletions(-) create mode 100644 .github/upstream-sync.json delete mode 100644 assets/partners/logos/aimzoon.jpg create mode 100644 assets/partners/logos/modelflare.png delete mode 100644 assets/partners/logos/proxy4free.png create mode 100644 backend/internal/domain/group_i18n.go create mode 100644 backend/internal/domain/group_i18n_test.go create mode 100644 backend/internal/handler/dto/group_localize.go create mode 100644 backend/internal/handler/dto/group_localize_test.go create mode 100644 backend/internal/handler/gemini_cached_contents_billing_test.go create mode 100644 backend/internal/handler/gemini_cached_contents_handler.go create mode 100644 backend/internal/handler/gemini_cached_contents_handler_test.go create mode 100644 backend/internal/handler/gemini_vertex_models_test.go create mode 100644 backend/internal/handler/group_localize_test.go create mode 100644 backend/internal/handler/ops_error_logger_google_test.go create mode 100644 backend/internal/payment/provider/easypay_confirm_test.go create mode 100644 backend/internal/repository/gemini_cached_content_repo.go create mode 100644 backend/internal/repository/gemini_cached_content_repo_integration_test.go create mode 100644 backend/internal/service/account_kimi_coding_test.go create mode 100644 backend/internal/service/admin_service_group_i18n_test.go create mode 100644 backend/internal/service/apicompat_config.go create mode 100644 backend/internal/service/gateway_anthropic_base_url_test.go create mode 100644 backend/internal/service/gateway_request_haiku55_test.go create mode 100644 backend/internal/service/gateway_upstream_request_test.go create mode 100644 backend/internal/service/gemini_cache_storage_pricing.go create mode 100644 backend/internal/service/gemini_cache_storage_pricing_test.go create mode 100644 backend/internal/service/gemini_cached_content.go create mode 100644 backend/internal/service/gemini_cached_content_hardening_test.go create mode 100644 backend/internal/service/gemini_cached_content_not_found_test.go create mode 100644 backend/internal/service/gemini_cached_content_test.go create mode 100644 backend/internal/service/gemini_compat_thinking.go create mode 100644 backend/internal/service/gemini_compat_thinking_test.go create mode 100644 backend/internal/service/gemini_error_policy_single_check_test.go create mode 100644 backend/internal/service/gemini_models_endpoints.go create mode 100644 backend/internal/service/gemini_models_endpoints_test.go create mode 100644 backend/internal/service/gemini_quota_test.go create mode 100644 backend/internal/service/gemini_vertex_api_key_forward_test.go create mode 100644 backend/internal/service/gemini_vertex_token_error.go create mode 100644 backend/internal/service/gemini_vertex_token_error_test.go create mode 100644 backend/internal/service/group_i18n.go create mode 100644 backend/internal/service/group_i18n_test.go create mode 100644 backend/internal/service/openai_model_retirement.go create mode 100644 backend/internal/service/openai_model_retirement_test.go create mode 100644 backend/internal/service/openai_responses_created_at.go create mode 100644 backend/internal/service/openai_responses_created_at_test.go create mode 100644 backend/internal/service/openai_subscription_long_context_test.go create mode 100644 backend/internal/service/payment_notification_confirm_test.go create mode 100644 backend/internal/service/payment_order_type_test.go create mode 100644 backend/internal/service/payment_refund_pending_hold_test.go create mode 100644 backend/internal/service/temp_unsched_scope_test.go create mode 100644 backend/internal/service/upstream_models_antigravity_test.go create mode 100644 backend/internal/service/upstream_models_vertex_test.go create mode 100644 backend/migrations/242_group_i18n.sql create mode 100644 backend/migrations/243_gemini_cached_contents.sql create mode 100644 backend/migrations/244_gemini_cached_contents_channel_usage.sql create mode 100644 backend/migrations/245_gemini_cached_contents_mutation_lease.sql create mode 100644 changelog/1.1.11/CHANGELOG.md create mode 100644 docs/OPENAI_GPT55_RETIREMENT.md delete mode 100644 frontend/src/components/admin/account/__tests__/AccountTableFilters.spec.ts create mode 100644 frontend/src/components/admin/group/GroupI18nField.vue create mode 100644 frontend/src/components/admin/group/__tests__/GroupI18nField.spec.ts create mode 100644 frontend/src/components/admin/group/__tests__/GroupRPMOverridesModal.requests.spec.ts create mode 100644 frontend/src/components/admin/group/__tests__/GroupRateMultipliersModal.edit.spec.ts create mode 100644 frontend/src/components/common/__tests__/LocaleSwitcher.spec.ts create mode 100644 frontend/src/components/common/__tests__/Select.ime.spec.ts create mode 100644 frontend/src/components/payment/__tests__/paymentCountdown.spec.ts create mode 100644 frontend/src/composables/__tests__/useGeminiOAuth.errors.spec.ts create mode 100644 frontend/src/features/channel-monitor-v2/__tests__/MonitorSettingsPanel.spec.ts create mode 100644 frontend/src/utils/__tests__/geminiExplicitCache.spec.ts create mode 100644 frontend/src/utils/geminiExplicitCache.ts create mode 100644 frontend/src/views/admin/ops/components/__tests__/OpsDashboardHeader.timezone.spec.ts create mode 100644 frontend/src/views/admin/ops/utils/accountNameMap.ts create mode 100644 frontend/src/views/user/__tests__/ChannelStatusV1View.details.spec.ts create mode 100644 scripts/release/archive.py diff --git a/.github/release-tools/release-images.sh b/.github/release-tools/release-images.sh index 532d176c8..977fda9a6 100644 --- a/.github/release-tools/release-images.sh +++ b/.github/release-tools/release-images.sh @@ -1,10 +1,9 @@ #!/usr/bin/env bash set -euo pipefail : "${RELEASE_VERSION:?}" "${RELEASE_SHA:?}" "${GITHUB_REPOSITORY:?}" "${RUNNER_TEMP:?}" -owner=${GITHUB_REPOSITORY%%/*} -registries=("ghcr.io/${owner,,}/sub2api") +registries=("ghcr.io/${GITHUB_REPOSITORY,,}") if [[ ${SIMPLE_RELEASE:-false} != true && ${DOCKERHUB_USERNAME:-skip} != skip ]]; then - registries+=("${DOCKERHUB_USERNAME}/sub2api") + registries+=("${DOCKERHUB_USERNAME,,}/sub4api") fi arches=(amd64 arm64) if [[ ${SIMPLE_RELEASE:-false} == true ]]; then arches=(amd64); fi diff --git a/.github/release-tools/release_matrix.py b/.github/release-tools/release_matrix.py index 4ea183879..f2f946a90 100644 --- a/.github/release-tools/release_matrix.py +++ b/.github/release-tools/release_matrix.py @@ -42,7 +42,7 @@ def archive_name(version, target): if not VERSION_RE.fullmatch(version) or target not in targets(): raise ValueError('invalid release version or target') suffix = 'zip' if target['goos'] == 'windows' else 'tar.gz' - return f"sub2api_{version}_{target['goos']}_{target['goarch']}.{suffix}" + return f"sub4api_{version}_{target['goos']}_{target['goarch']}.{suffix}" def sha256(path): @@ -95,7 +95,7 @@ def generate_config(args): data['before'] = {'hooks': []} data['builds'] = [{'id': 'sub2api', 'skip': True}] data['archives'] = [] - extra = [{'glob': 'release-input/sub2api_*.tar.gz'}, {'glob': 'release-input/sub2api_*.zip'}] + extra = [{'glob': 'release-input/sub4api_*.tar.gz'}, {'glob': 'release-input/sub4api_*.zip'}] if args.simple: data['checksum'] = {'disable': True} else: diff --git a/.github/release-tools/test_release_matrix.py b/.github/release-tools/test_release_matrix.py index bbfc0fc67..6738d7a36 100644 --- a/.github/release-tools/test_release_matrix.py +++ b/.github/release-tools/test_release_matrix.py @@ -108,6 +108,7 @@ def test_missing_extra_and_wrong_commit_artifacts_are_rejected(self): with self.assertRaises(FileNotFoundError): release.verify(args) + @unittest.skipIf(os.name == 'nt', 'POSIX executable mode requires a POSIX filesystem') def test_linux_context_preserves_binary_executable_mode(self): args = self.fixture_artifacts() Path('Dockerfile.goreleaser').write_text('FROM scratch\nCOPY sub2api /sub2api\n') @@ -147,7 +148,7 @@ def test_docker_commands_do_not_publish_during_dry_run(self): docker.chmod(0o755) env = {**os.environ, 'PATH': str(fake_bin.resolve()) + os.pathsep + os.environ['PATH'], 'DOCKER_LOG': str(Path('docker.log').resolve()), 'RUNNER_TEMP': self.temp.name, - 'RELEASE_VERSION': '9.8.7', 'RELEASE_SHA': 'a' * 40, 'GITHUB_REPOSITORY': 'ExampleOwner/sub2api', + 'RELEASE_VERSION': '9.8.7', 'RELEASE_SHA': 'a' * 40, 'GITHUB_REPOSITORY': 'ExampleOwner/sub4api', 'DRY_RUN': 'true', 'SIMPLE_RELEASE': 'false', 'DOCKERHUB_USERNAME': 'skip'} subprocess.run(['bash', str(ROOT / '.github/release-tools/release-images.sh')], env=env, check=True) log = Path('docker.log').read_text() @@ -156,7 +157,7 @@ def test_docker_commands_do_not_publish_during_dry_run(self): self.assertNotIn('--push', log) self.assertNotIn('imagetools', log) self.assertNotIn('skip/sub2api', log) - self.assertIn('ghcr.io/exampleowner/sub2api', log) + self.assertIn('ghcr.io/exampleowner/sub4api', log) def test_published_full_and_simple_image_tags(self): @@ -170,7 +171,7 @@ def test_published_full_and_simple_image_tags(self): log_path = Path(f'docker-{simple}.log').resolve() env = {**os.environ, 'PATH': str(fake_bin.resolve()) + os.pathsep + os.environ['PATH'], 'DOCKER_LOG': str(log_path), 'RUNNER_TEMP': self.temp.name, - 'RELEASE_VERSION': '9.8.7', 'RELEASE_SHA': 'a' * 40, 'GITHUB_REPOSITORY': 'ExampleOwner/sub2api', + 'RELEASE_VERSION': '9.8.7', 'RELEASE_SHA': 'a' * 40, 'GITHUB_REPOSITORY': 'ExampleOwner/sub4api', 'DRY_RUN': 'false', 'SIMPLE_RELEASE': str(simple).lower(), 'DOCKERHUB_USERNAME': 'fixturehub'} subprocess.run(['bash', str(ROOT / '.github/release-tools/release-images.sh')], env=env, check=True) log = log_path.read_text() @@ -179,11 +180,11 @@ def test_published_full_and_simple_image_tags(self): if simple: self.assertNotIn('fixturehub', log) self.assertNotIn('imagetools', log) - self.assertIn('ghcr.io/exampleowner/sub2api:latest', log) + self.assertIn('ghcr.io/exampleowner/sub4api:latest', log) else: self.assertEqual(log.count('imagetools create'), 2) - self.assertIn('fixturehub/sub2api:9.8', log) - self.assertIn('ghcr.io/exampleowner/sub2api:9', log) + self.assertIn('fixturehub/sub4api:9.8', log) + self.assertIn('ghcr.io/exampleowner/sub4api:9', log) diff --git a/.github/upstream-sync.json b/.github/upstream-sync.json new file mode 100644 index 000000000..49f524e82 --- /dev/null +++ b/.github/upstream-sync.json @@ -0,0 +1,8 @@ +{ + "repository": "Wei-Shaw/sub2api", + "version": "0.2.17", + "commit": "b0a02a3304a0a78cdd003ddda1dd23ba02c03084", + "previous_commit": "f2669c8cf62555cd92389b3f55920e9e6e7c6ff2", + "sub4api_version": "1.1.11", + "method": "Three-way source merge with Sub4API module paths and customizations preserved" +} diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml index 276bd8b23..89c939c50 100644 --- a/.github/workflows/backend-ci.yml +++ b/.github/workflows/backend-ci.yml @@ -8,6 +8,16 @@ permissions: contents: read jobs: + release-validation: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-python@v6 + with: + python-version: '3.13' + - name: Validate fork packaging and update compatibility + run: python3 scripts/release/test_release.py + shell: runs-on: macos-15 steps: @@ -48,7 +58,7 @@ jobs: - name: Setup pnpm uses: pnpm/action-setup@v6 with: - version: 9 + version: 9.15.9 - name: Setup Node.js uses: actions/setup-node@v6 with: diff --git a/.github/workflows/main-release.yml b/.github/workflows/main-release.yml index acc719155..3ebdc706f 100644 --- a/.github/workflows/main-release.yml +++ b/.github/workflows/main-release.yml @@ -22,7 +22,6 @@ concurrency: jobs: release: runs-on: ubuntu-latest - environment: sub4api steps: - uses: actions/checkout@v6 with: @@ -71,7 +70,7 @@ jobs: - uses: pnpm/action-setup@v6 if: steps.current.outputs.publish == 'true' with: - version: 9 + version: 9.15.9 - uses: actions/setup-node@v6 if: steps.current.outputs.publish == 'true' with: @@ -108,11 +107,11 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - uses: docker/login-action@v3 - if: steps.current.outputs.publish == 'true' + if: steps.current.outputs.publish == 'true' && steps.meta.outputs.dockerhub_enabled == 'true' with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} - - name: Build and push both registries + - name: Build and push images if: steps.current.outputs.publish == 'true' id: image uses: docker/build-push-action@v6 @@ -121,11 +120,7 @@ jobs: file: Dockerfile platforms: linux/amd64,linux/arm64 push: true - tags: | - ${{ steps.meta.outputs.ghcr }}:${{ steps.meta.outputs.version }} - ${{ steps.meta.outputs.ghcr }}:latest - ${{ steps.meta.outputs.dockerhub }}:${{ steps.meta.outputs.version }} - ${{ steps.meta.outputs.dockerhub }}:latest + tags: ${{ steps.meta.outputs.tags }} build-args: | VERSION=${{ steps.meta.outputs.version }} COMMIT=${{ steps.meta.outputs.commit }} diff --git a/.github/workflows/security-scan.yml b/.github/workflows/security-scan.yml index 8caec3ff4..d2b59934b 100644 --- a/.github/workflows/security-scan.yml +++ b/.github/workflows/security-scan.yml @@ -37,7 +37,7 @@ jobs: - name: Set up pnpm uses: pnpm/action-setup@v6 with: - version: 9 + version: 9.15.9 - name: Set up Node.js uses: actions/setup-node@v6 with: diff --git a/.gitignore b/.gitignore index ea3076a05..c8ea0d1ab 100644 --- a/.gitignore +++ b/.gitignore @@ -139,6 +139,7 @@ docs/* !docs/ASYNC_IMAGE_TASKS.md !docs/BATCH_IMAGE_MVP.md !docs/COMPOSITE_GROUPS.md +!docs/OPENAI_GPT55_RETIREMENT.md !docs/openai-bps.md !docs/openai-bps-sources.md !docs/PLUGIN_DEVELOPMENT.md diff --git a/.goreleaser.simple.yaml b/.goreleaser.simple.yaml index b25df6e3b..bc3a58e1d 100644 --- a/.goreleaser.simple.yaml +++ b/.goreleaser.simple.yaml @@ -1,7 +1,7 @@ # 简化版 GoReleaser 配置 - 仅发布 x86_64 GHCR 镜像 version: 2 -project_name: sub2api +project_name: sub4api before: hooks: @@ -42,9 +42,9 @@ dockers: goos: linux goarch: amd64 image_templates: - - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }}-amd64" - - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }}" - - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:latest" + - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Version }}-amd64" + - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Version }}" + - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:latest" dockerfile: Dockerfile.goreleaser use: buildx extra_files: @@ -65,7 +65,7 @@ release: name: "{{ .Env.GITHUB_REPO_NAME }}" draft: false prerelease: auto - name_template: "Sub2API {{.Version}} (Simple)" + name_template: "Sub4API {{.Version}} (Simple)" # 跳过上传二进制包 skip_upload: true header: | @@ -81,7 +81,7 @@ release: **Docker (x86_64 only):** ```bash - docker pull ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }} + docker pull ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Version }} ``` ## 📚 Documentation diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 19adfdf6d..48ec76879 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -1,6 +1,6 @@ version: 2 -project_name: sub2api +project_name: sub4api before: hooks: @@ -60,7 +60,7 @@ dockers: goarch: amd64 skip_push: '{{ if eq .Env.DOCKERHUB_USERNAME "skip" }}true{{ else }}false{{ end }}' image_templates: - - "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Version }}-amd64" + - "{{ .Env.DOCKERHUB_USERNAME }}/sub4api:{{ .Version }}-amd64" dockerfile: Dockerfile.goreleaser use: buildx extra_files: @@ -76,7 +76,7 @@ dockers: goarch: arm64 skip_push: '{{ if eq .Env.DOCKERHUB_USERNAME "skip" }}true{{ else }}false{{ end }}' image_templates: - - "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Version }}-arm64" + - "{{ .Env.DOCKERHUB_USERNAME }}/sub4api:{{ .Version }}-arm64" dockerfile: Dockerfile.goreleaser use: buildx extra_files: @@ -92,7 +92,7 @@ dockers: goos: linux goarch: amd64 image_templates: - - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }}-amd64" + - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Version }}-amd64" dockerfile: Dockerfile.goreleaser use: buildx extra_files: @@ -108,7 +108,7 @@ dockers: goos: linux goarch: arm64 image_templates: - - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }}-arm64" + - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Version }}-arm64" dockerfile: Dockerfile.goreleaser use: buildx extra_files: @@ -123,50 +123,50 @@ dockers: # Docker manifests for multi-arch support docker_manifests: # DockerHub manifests (skipped if DOCKERHUB_USERNAME is 'skip') - - name_template: "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Version }}" + - name_template: "{{ .Env.DOCKERHUB_USERNAME }}/sub4api:{{ .Version }}" skip_push: '{{ if eq .Env.DOCKERHUB_USERNAME "skip" }}true{{ else }}false{{ end }}' image_templates: - - "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Version }}-amd64" - - "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Version }}-arm64" + - "{{ .Env.DOCKERHUB_USERNAME }}/sub4api:{{ .Version }}-amd64" + - "{{ .Env.DOCKERHUB_USERNAME }}/sub4api:{{ .Version }}-arm64" - - name_template: "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:latest" + - name_template: "{{ .Env.DOCKERHUB_USERNAME }}/sub4api:latest" skip_push: '{{ if eq .Env.DOCKERHUB_USERNAME "skip" }}true{{ else }}false{{ end }}' image_templates: - - "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Version }}-amd64" - - "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Version }}-arm64" + - "{{ .Env.DOCKERHUB_USERNAME }}/sub4api:{{ .Version }}-amd64" + - "{{ .Env.DOCKERHUB_USERNAME }}/sub4api:{{ .Version }}-arm64" - - name_template: "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Major }}.{{ .Minor }}" + - name_template: "{{ .Env.DOCKERHUB_USERNAME }}/sub4api:{{ .Major }}.{{ .Minor }}" skip_push: '{{ if eq .Env.DOCKERHUB_USERNAME "skip" }}true{{ else }}false{{ end }}' image_templates: - - "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Version }}-amd64" - - "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Version }}-arm64" + - "{{ .Env.DOCKERHUB_USERNAME }}/sub4api:{{ .Version }}-amd64" + - "{{ .Env.DOCKERHUB_USERNAME }}/sub4api:{{ .Version }}-arm64" - - name_template: "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Major }}" + - name_template: "{{ .Env.DOCKERHUB_USERNAME }}/sub4api:{{ .Major }}" skip_push: '{{ if eq .Env.DOCKERHUB_USERNAME "skip" }}true{{ else }}false{{ end }}' image_templates: - - "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Version }}-amd64" - - "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Version }}-arm64" + - "{{ .Env.DOCKERHUB_USERNAME }}/sub4api:{{ .Version }}-amd64" + - "{{ .Env.DOCKERHUB_USERNAME }}/sub4api:{{ .Version }}-arm64" # GHCR manifests (owner must be lowercase) - - name_template: "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }}" + - name_template: "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Version }}" image_templates: - - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }}-amd64" - - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }}-arm64" + - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Version }}-amd64" + - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Version }}-arm64" - - name_template: "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:latest" + - name_template: "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:latest" image_templates: - - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }}-amd64" - - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }}-arm64" + - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Version }}-amd64" + - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Version }}-arm64" - - name_template: "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Major }}.{{ .Minor }}" + - name_template: "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Major }}.{{ .Minor }}" image_templates: - - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }}-amd64" - - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }}-arm64" + - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Version }}-amd64" + - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Version }}-arm64" - - name_template: "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Major }}" + - name_template: "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Major }}" image_templates: - - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }}-amd64" - - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }}-arm64" + - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Version }}-amd64" + - "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Version }}-arm64" release: github: @@ -174,7 +174,7 @@ release: name: "{{ .Env.GITHUB_REPO_NAME }}" draft: false prerelease: auto - name_template: "Sub2API {{.Version}}" + name_template: "Sub4API {{.Version}}" # 完全使用 tag 消息作为 release 内容(通过环境变量传入) header: | > AI API Gateway Platform - 将 AI 订阅配额分发和管理 @@ -191,11 +191,11 @@ release: ```bash {{ if ne .Env.DOCKERHUB_USERNAME "skip" -}} # Docker Hub - docker pull {{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Version }} + docker pull {{ .Env.DOCKERHUB_USERNAME }}/sub4api:{{ .Version }} {{ end -}} # GitHub Container Registry - docker pull ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }} + docker pull ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub4api:{{ .Version }} ``` **One-line install (Linux):** diff --git a/Dockerfile b/Dockerfile index 64e93d84e..2fbb1fc53 100644 --- a/Dockerfile +++ b/Dockerfile @@ -108,9 +108,9 @@ FROM ${POSTGRES_IMAGE} AS pg-client FROM ${ALPINE_IMAGE} # Labels -LABEL maintainer="Wei-Shaw " -LABEL description="Sub2API - AI API Gateway Platform" -LABEL org.opencontainers.image.source="https://github.com/MACOS-DO/sub4api" +LABEL maintainer="info-talent " +LABEL description="Sub4API - AI API Gateway Platform" +LABEL org.opencontainers.image.source="https://github.com/info-talent/sub4api" # Install runtime dependencies RUN apk add --no-cache \ diff --git a/Dockerfile.goreleaser b/Dockerfile.goreleaser index 5c196fd70..c030bc441 100644 --- a/Dockerfile.goreleaser +++ b/Dockerfile.goreleaser @@ -12,9 +12,9 @@ FROM ${POSTGRES_IMAGE} AS pg-client FROM ${ALPINE_IMAGE} -LABEL maintainer="Wei-Shaw " -LABEL description="Sub2API - AI API Gateway Platform" -LABEL org.opencontainers.image.source="https://github.com/MACOS-DO/sub4api" +LABEL maintainer="info-talent " +LABEL description="Sub4API - AI API Gateway Platform" +LABEL org.opencontainers.image.source="https://github.com/info-talent/sub4api" # Install runtime dependencies RUN apk add --no-cache \ diff --git a/Makefile b/Makefile index 55d9b7353..4a853cefd 100644 --- a/Makefile +++ b/Makefile @@ -5,6 +5,7 @@ FRONTEND_CRITICAL_VITEST := \ src/api/__tests__/client.spec.ts \ src/api/__tests__/tokenRefresh.spec.ts \ src/api/__tests__/keys.bulkUpdate.spec.ts \ + src/composables/__tests__/useModelWhitelist.spec.ts \ src/components/account/__tests__/OpenAIReferralCell.spec.ts \ src/components/account/__tests__/OpenAIReferralCell.transport.spec.ts \ src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts \ diff --git a/README.md b/README.md index b7e7885f8..32d681568 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Sub4API 基于 sub2api 二次开发,完全兼容 sub2api,并会持续同步 在原有 API 网关与账号管理能力的基础上,Sub4API 重点增强 **Codex 打票与票据管理、请求时区替换以及请求头语言统一**,并提供票据流水和降智检测,方便管理与排查账号状态。 -已部署 sub2api 的用户,只需将应用镜像替换为 `macosdo/sub4api:latest` 并重新创建应用容器,即可沿用原有配置与数据切换到 Sub4API。 +已部署 sub2api 的用户,只需将应用镜像替换为 `ghcr.io/info-talent/sub4api:latest` 并重新创建应用容器,即可沿用原有配置与数据切换到 Sub4API。 ## 相比 sub2api 的主要改进 @@ -86,7 +86,7 @@ Accept-Language: en-US,en;q=0.9 ## 部署与切换 -Docker 镜像统一使用 `macosdo/sub4api:latest`。为沿用现有部署配置,Compose 服务名和 Linux 安装脚本的 systemd 服务名仍为 `sub2api`。 +Docker 镜像统一使用 `ghcr.io/info-talent/sub4api:latest`。为沿用现有部署配置,Compose 服务名和 Linux 安装脚本的 systemd 服务名仍为 `sub2api`。 ### 从 sub2api 一键切换到 Sub4API @@ -99,7 +99,7 @@ Docker 镜像统一使用 `macosdo/sub4api:latest`。为沿用现有部署配置 ```yaml services: sub2api: - image: macosdo/sub4api:latest + image: ghcr.io/info-talent/sub4api:latest ``` 上面仅展示需要修改的片段,其余配置继续沿用。保留原服务名、端口、数据目录与数据卷,以及原 `.env` 中的数据库、Redis 连接、`JWT_SECRET` 和 `TOTP_ENCRYPTION_KEY`,无需重新初始化或导入账号。 @@ -140,7 +140,7 @@ mkdir -p sub4api-deploy cd sub4api-deploy # 下载 Compose 配置并生成首次部署所需的密钥和数据目录 -curl -fsSL https://raw.githubusercontent.com/MACOS-DO/sub4api/main/deploy/docker-deploy.sh | bash +curl -fsSL https://raw.githubusercontent.com/info-talent/sub4api/main/deploy/docker-deploy.sh | bash chmod 600 .env ``` @@ -149,7 +149,7 @@ chmod 600 .env 打开生成的 `docker-compose.yml`,将 `sub2api` 服务的镜像改为: ```yaml -image: macosdo/sub4api:latest +image: ghcr.io/info-talent/sub4api:latest ``` 随后检查 `.env`,按需设置 `ADMIN_EMAIL`、`ADMIN_PASSWORD` 和 `SERVER_PORT`。这里仅修改应用镜像,其余服务及数据挂载保持生成的配置。 @@ -184,7 +184,7 @@ docker compose logs -f sub2api 适用于 amd64 或 arm64 Linux 服务器。需要 Bash 4 或更新版本、root 或 sudo 权限,以及可连接的 PostgreSQL 和 Redis。 ```bash -curl -fsSL https://raw.githubusercontent.com/MACOS-DO/sub4api/main/deploy/install.sh | sudo bash +curl -fsSL https://raw.githubusercontent.com/info-talent/sub4api/main/deploy/install.sh | sudo bash # 启动服务并设置开机启动 sudo systemctl enable --now sub2api @@ -210,7 +210,7 @@ sudo systemctl restart sub2api 需要 Go 1.27.0、Node.js 24、pnpm 9,以及可连接的 PostgreSQL 和 Redis。Go 版本与当前 `backend/go.mod` 一致,Node.js 与 pnpm 版本与仓库 Docker 构建保持一致。 ```bash -git clone https://github.com/MACOS-DO/sub4api.git +git clone https://github.com/info-talent/sub4api.git cd sub4api # 安装 pnpm 并构建前端 @@ -237,7 +237,7 @@ go build -tags embed -ldflags="-X main.Version=${VERSION}" -o sub4api ./cmd/serv 适用于搭载 Apple 芯片、运行 macOS 26 或更新版本的 Mac,需要 Apple `container` 1.1.0 或更新版本及 `openssl`。 ```bash -git clone https://github.com/MACOS-DO/sub4api.git +git clone https://github.com/info-talent/sub4api.git cd sub4api/deploy # 生成首次部署配置 @@ -247,7 +247,7 @@ cd sub4api/deploy 编辑生成的 `.env`,设置应用镜像: ```dotenv -APPLE_CONTAINER_SUB2API_IMAGE=macosdo/sub4api:latest +APPLE_CONTAINER_SUB2API_IMAGE=ghcr.io/info-talent/sub4api:latest ``` 随后启动并检查服务: diff --git a/README_CN.md b/README_CN.md index 0c68b3620..5cce71c33 100644 --- a/README_CN.md +++ b/README_CN.md @@ -55,8 +55,8 @@ -AIGoCode -感谢 AIGoCode 赞助了本项目!AIGoCode 是一站式集成 Claude Code、Codex 以及最新 Gemini 模型的综合平台,为您提供稳定、高效、高性价比的 AI 编程服务。平台提供灵活的订阅方案,零封号风险,免 VPN 直连,响应极速。AIGoCode 为 sub2api 用户准备了专属福利:通过此链接注册,首次充值可额外获得 10% 赠送额度! +AIGoCode +感谢 AIGoCode 赞助了本项目!AIGoCode 是一站式集成 Claude Code、Codex 以及最新 Gemini 模型的综合平台,为您提供稳定、高效、高性价比的 AI 编程服务。平台提供灵活的订阅方案,零封号风险,免 VPN 直连,响应极速。AIGoCode 为 sub2api 用户准备了专属福利:通过此链接注册,首次充值可额外获得 10% 赠送额度! @@ -64,11 +64,6 @@ Real GPT-5.6 series at 3% of OpenAI pricing — CodexEverywhere is democratizing access to frontier models for developers worldwide. We believe in transparency and honesty, with model quality verified by active community oversight for months. USD and crypto friendly. Start with a free $20 trial at codex-everywhere.com. - -bmoplus -感谢 BmoPlus 赞助了本项目!BmoPlus 是一家专为AI订阅重度用户打造的可靠 AI 账号代充服务商,提供稳定的 ChatGPT Plus / ChatGPT Pro(全程质保) / Claude Pro / Super Grok / Gemini Pro 的官方代充&成品账号。 通过BmoPlus AI成品号专卖/代充注册下单的用户,可享GPT 官网订阅一折 的震撼价格! - - bestproxy 感谢 Bestproxy 赞助了本项目!Bestproxy 是一家提供高纯度住宅IP,支持一号一IP独享,结合真实家庭网络与指纹隔离,可实现链路环境隔离,降低关联风控概率。 @@ -99,18 +94,6 @@ - -proxy4free -感谢 Proxy4Free 赞助本项目!Proxy4Free 是面向开发者和 AI 应用的数据代理服务商,提供住宅代理、静态住宅代理、ISP 代理及数据中心代理等多种代理解决方案,适用于 Web Scraping、Browser Automation、AI Agent 等场景。支持全球 IP 资源、稳定连接与灵活切换,帮助开发者提升数据采集成功率,降低 IP 封禁风险。通过此链接注册即可开始体验,轻松构建更稳定、高效的自动化工作流。 - - - - -aimzoon -感谢 Aimzoon 对本项目的赞助! Aimzoon 提供稳定、高性价比的 AI API 接入服务,支持开发者将常用 AI 服务快速接入 Codex、Claude Code、Gemini CLI 等编程工具。无需复杂配置,更快接入,更稳调用,更省成本。codex倍率优惠,特价倍率等促销不断,注册即送免费体验额度,让 AI 编程真正进入日常工作流。点击这里注册体验! - - - Nagora Nagora 是专为开发者和团队打造的多模型 AI API 网关。通过一个账户和一枚 API Key,即可统一调用 26+ 款主流文本与图像模型,兼容 OpenAI、Anthropic 与 Gemini 协议,并可无缝接入 Claude Code、Codex、Gemini CLI 等开发工具。平台提供智能路由、自动故障转移、透明计费与统一账单,同时支持预算、限速、并发控制,让个人开发、团队协作和生产环境中的 AI 调用更稳定、更可控。无需改造现有应用,只需替换 Base URL 与 API Key,最快 1 分钟即可完成接入。 @@ -146,11 +129,6 @@ Swiftproxy 是面向开发者的高性能代理解决方案,提供稳定可靠的住宅代理和静态住宅代理服务。拥有 9000 万+ 纯净住宅 IP,覆盖全球,支持灵活轮换和精准地理定位,帮助网页抓取、AI 自动化、浏览器自动化、SEO 监控和多账号管理等项目突破访问限制,提升工作流效率。支持 HTTP(S) 和 SOCKS5 协议,兼容 Playwright、Selenium、Puppeteer 等主流自动化工具,动态代理流量用完为止永不过期,支持免费测试 — 立即开始免费测试! - -DuckIP -DuckIP - 9000 万+ 全球住宅网络资源,覆盖 195+ 国家和地区,支持轮换和粘性会话,适用于公共数据采集、RAG 更新、模型评估和多区域数据工作负载。🟢住宅代理 - 8 折优惠;🟢静态住宅代理 - ¥50.00/IP 起;🟢无限住宅代理 - ¥19.8/小时 起。✅免费领取 500M 试用流量。 - - APIMart 感谢 APIMart 赞助了本项目!APIMart 是专注于 AI 图片/视频生成的低价 API 平台,GPT-Image-2 低至 $0.006/张,1 美元可生成 160+ 张图片。图片、视频一套异步 API 通吃:提交任务获取 ID,通过轮询或回调获取结果;批量生成上万张图片也不会超时,切换模型无需修改代码。按量付费、无月费,通过此注册链接注册即可开始使用。 @@ -171,6 +149,11 @@ ColaProxy 提供专为网页抓取、自动化和多账号管理打造的高质量住宅代理。免费试用,流量永不过期,价格低至 $0.3/GB,支持无限并发连接和智能 IP 轮换,带来更流畅、更稳定的代理体验。使用优惠码 COLA10 立享 9 折优惠,立即开始使用可靠的住宅代理扩展您的项目。立即开始使用 ColaProxy + +Modelflare +Modelflare:满血稳定不掺水,低成本享受全球 SOTA 模型。站点由美国 LLC 主体 Havenbyte LLC 运营,支持 GPT、Claude、Gemini、Grok 等主流模型和常用兼容协议,还支持 40 多种图片和视频模型。缓存补偿是一大亮点:部分 OpenAI 价格优先、稳定和高级分组提供每日 65%、75%、85% 的缓存命中率保障,符合条件的请求没达到目标的,平台补偿差额,结算后可在用量看板查看。特惠活动:单笔充值 US$20 即可解锁 0.015 倍价格倍率的 GPT 特惠分组,单笔充值 US$50 即可解锁 0.03 倍价格倍率的 Claude 特惠分组。通过专属链接注册即可参与 + + ## 项目概述 @@ -261,7 +244,7 @@ fast_mode = true #### 安装步骤 ```bash -curl -sSL https://raw.githubusercontent.com/MACOS-DO/sub4api/main/deploy/install.sh | sudo bash +curl -sSL https://raw.githubusercontent.com/info-talent/sub4api/main/deploy/install.sh | sudo bash ``` 脚本会自动: @@ -311,7 +294,7 @@ sudo journalctl -u sub2api -f sudo systemctl restart sub2api # 卸载 -curl -sSL https://raw.githubusercontent.com/MACOS-DO/sub4api/main/deploy/install.sh | sudo bash -s -- uninstall -y +curl -sSL https://raw.githubusercontent.com/info-talent/sub4api/main/deploy/install.sh | sudo bash -s -- uninstall -y ``` --- @@ -334,7 +317,7 @@ curl -sSL https://raw.githubusercontent.com/MACOS-DO/sub4api/main/deploy/install mkdir -p sub2api-deploy && cd sub2api-deploy # 下载并运行部署准备脚本 -curl -sSL https://raw.githubusercontent.com/MACOS-DO/sub4api/main/deploy/docker-deploy.sh | bash +curl -sSL https://raw.githubusercontent.com/info-talent/sub4api/main/deploy/docker-deploy.sh | bash # 启动服务 docker compose up -d @@ -356,7 +339,7 @@ docker compose logs -f sub2api ```bash # 1. 克隆仓库 -git clone https://github.com/MACOS-DO/sub4api.git +git clone https://github.com/info-talent/sub4api.git cd sub2api/deploy # 2. 复制环境配置文件 @@ -500,7 +483,7 @@ rm -rf data/ postgres_data/ redis_data/ Apple 芯片 Mac 在 macOS 26 上可使用 Apple `container` 1.1.0 或更高版本运行完整的 Sub2API、PostgreSQL 和 Redis: ```bash -git clone https://github.com/MACOS-DO/sub4api.git +git clone https://github.com/info-talent/sub4api.git cd sub2api/deploy ./apple-container.sh init ./apple-container.sh up @@ -526,7 +509,7 @@ cd sub2api/deploy ```bash # 1. 克隆仓库 -git clone https://github.com/MACOS-DO/sub4api.git +git clone https://github.com/info-talent/sub4api.git cd sub2api # 2. 安装 pnpm(如果还没有安装) diff --git a/README_JA.md b/README_JA.md index 26b9d0944..c24a4bf38 100644 --- a/README_JA.md +++ b/README_JA.md @@ -54,8 +54,8 @@ -AIGoCode -AIGoCode のご支援に感謝します!AIGoCode は Claude Code、Codex、最新の Gemini モデルを統合したオールインワンプラットフォームで、安定的かつ効率的でコストパフォーマンスに優れた AI コーディングサービスを提供します。柔軟なサブスクリプションプラン、アカウント停止リスクゼロ、VPN 不要の直接アクセス、超高速レスポンスが特長です。AIGoCode は sub2api ユーザー向けに特別特典を用意しています:こちらのリンクから登録すると、初回チャージ時に 10% のボーナスクレジットを追加プレゼント! +AIGoCode +AIGoCode のご支援に感謝します!AIGoCode は Claude Code、Codex、最新の Gemini モデルを統合したオールインワンプラットフォームで、安定的かつ効率的でコストパフォーマンスに優れた AI コーディングサービスを提供します。柔軟なサブスクリプションプラン、アカウント停止リスクゼロ、VPN 不要の直接アクセス、超高速レスポンスが特長です。AIGoCode は sub2api ユーザー向けに特別特典を用意しています:こちらのリンクから登録すると、初回チャージ時に 10% のボーナスクレジットを追加プレゼント! @@ -63,11 +63,6 @@ OpenAI 公式価格のわずか 3% で本物の GPT-5.6 シリーズを提供 — CodexEverywhere は世界中の開発者にフロンティアモデルへのアクセスを民主化しています。私たちは透明性と誠実さを信条とし、モデル品質は数か月にわたるアクティブなコミュニティの監視によって検証されています。USD および暗号通貨に対応。codex-everywhere.com で $20 の無料トライアルから始めましょう。 - -bmoplus -本プロジェクトにご支援いただいた BmoPlus に感謝いたします!BmoPlusは、AIサブスクリプションのヘビーユーザー向けに特化した信頼性の高いAIアカウントサービスプロバイダーであり、安定した ChatGPT Plus / ChatGPT Pro (完全保証) / Claude Pro / Super Grok / Gemini Pro の公式代行チャージおよび即納アカウントを提供しています。こちらのBmoPlus AIアカウント専門店/代行チャージ経由でご登録・ご注文いただいたユーザー様は、GPTを 公式サイト価格の約1割(90% OFF) という驚異的な価格でご利用いただけます! - - bestproxy Bestproxy のご支援に感謝します!Bestproxy は高純度の住宅IPを提供し、1アカウント1IP専有をサポートしています。実際の家庭ネットワークとフィンガープリント分離を組み合わせることで、リンク環境の分離を実現し、関連付けによるリスク管理の確率を低減します。 @@ -98,18 +93,6 @@ - -proxy4free -Proxy4Free のご支援に感謝します!Proxy4Free は開発者と AI アプリケーション向けのデータプロキシサービスプロバイダーで、住宅プロキシ、静的住宅プロキシ、ISP プロキシ、データセンタープロキシなど多様なプロキシソリューションを提供しており、Web Scraping、Browser Automation、AI Agent などのシナリオに適しています。グローバル IP リソース、安定した接続、柔軟な切り替えをサポートし、開発者のデータ収集成功率の向上と IP ブロックリスクの低減を支援します。こちらのリンクから登録して、より安定した効率的な自動化ワークフローを簡単に構築しましょう。 - - - - -aimzoon -Aimzoon のご支援に感謝します!Aimzoon は安定してコストパフォーマンスに優れた AI API 接続サービスを提供し、開発者が主要な AI サービスを Codex、Claude Code、Gemini CLI などのコーディングツールへ素早く接続できるようにします。複雑な設定は不要で、より速い接続、より安定した呼び出し、より低いコストを実現。Codex レート割引や特価レートなどのキャンペーンも随時開催中、登録するだけで無料お試しクレジットをプレゼント。AI コーディングを日常のワークフローへ。こちらから登録してお試しください! - - - Nagora Nagoraは、開発者やチーム向けに設計されたマルチモデルAI APIゲートウェイです。1つのアカウントと1つのAPIキーだけで、26種類以上の主要なテキストモデルおよび画像モデルを一元的に利用できます。OpenAI、Anthropic、Geminiの各プロトコルに対応し、Claude Code、Codex、Gemini CLIなどの開発ツールにもシームレスに接続できます。 プラットフォームには、インテリジェントルーティング、自動フェイルオーバー、透明性の高い料金体系、請求の一元管理に加え、予算管理、レート制限、同時実行数の制御機能が備わっています。これにより、個人開発、チームでの共同作業、本番環境におけるAI APIの利用を、より安定的かつ柔軟に管理できます。 既存のアプリケーションを改修する必要はありません。Base URLとAPIキーを置き換えるだけで、最短1分で導入を完了できます。 @@ -145,11 +128,6 @@ Swiftproxy は開発者向けの高性能プロキシソリューションで、安定して信頼できるレジデンシャルおよび静的レジデンシャルプロキシサービスを提供します。9,000 万以上のクリーンな住宅 IP を保有し、グローバルカバレッジ、柔軟なローテーション、精密なジオターゲティングにより、Web スクレイピング、AI オートメーション、ブラウザ自動化、SEO モニタリング、マルチアカウント管理などのプロジェクトがアクセス制限を克服し、ワークフロー効率を向上させます。HTTP(S) および SOCKS5 プロトコルに対応し、Playwright、Selenium、Puppeteer などの主要な自動化ツールと統合可能。動的プロキシトラフィックは使い切るまで期限切れなし、無料テストも利用可能 — 今すぐ無料テストを開始! - -DuckIP -DuckIP - 195 以上の国と地域にわたる 9,000 万以上のグローバルレジデンシャルネットワークリソース。ローテーションとスティッキーセッションに対応し、パブリックデータ収集、RAG 更新、モデル評価、マルチリージョンデータワークロードに最適。🟢レジデンシャルプロキシ - 20% オフ;🟢スタティックレジデンシャルプロキシ - ¥50.00/IP から;🟢無制限レジデンシャルプロキシ - ¥19.8/時間 から。✅500M 無料トライアルを取得。 - - APIMart APIMart のご支援に感謝します!APIMart は AI 画像・動画生成に特化した低価格 API プラットフォームです。GPT-Image-2 は 1 枚 $0.006 から、1 ドルで 160 枚以上の画像を生成できます。画像と動画の両方に対応する非同期 API を 1 つで利用でき、タスクを送信して ID を取得し、ポーリングまたはコールバックで結果を取得できます。数万枚規模のバッチ処理でもタイムアウトせず、モデルを変更してもコードの変更は不要です。月額料金なしの従量課金制で、こちらの登録リンクからすぐに利用を開始できます。 @@ -170,6 +148,11 @@ ColaProxy は、Web スクレイピング、自動化、マルチアカウント管理向けに構築された高品質な住宅プロキシを提供します。有効期限なしのトラフィックで無料トライアルが利用でき、料金は $0.3/GB から、無制限の同時接続とインテリジェントな IP ローテーションにより、よりスムーズで安定したプロキシ体験を実現します。割引コード COLA10 で 10% オフ、信頼性の高い住宅プロキシでプロジェクトを今すぐスケールしましょう。ColaProxy を始める + +Modelflare +Modelflare:フルスペック、安定、水増しなし。世界の SOTA モデルを、より低いコストで。米国拠点の Havenbyte LLC が運営する Modelflare は、一般的な互換プロトコルを通じて GPT、Claude、Gemini、Grok などの主要モデルに対応し、さらに 40 以上の画像・動画モデルも利用できます。注目はキャッシュ補償です。対象の OpenAI グループ(価格優先・安定・プレミアム)は、1 日のキャッシュヒット率をそれぞれ 65%、75%、85% で保証します。対象リクエストがこの水準に達しない場合、Modelflare が差額を返金し、精算後に利用状況ダッシュボードで確認できます。特別オファー:US$20 を 1 回チャージすると、価格倍率 0.015 倍の GPT 割引グループが解放されます。US$50 を 1 回チャージすると、価格倍率 0.03 倍の Claude 割引グループが解放されます。こちらの専用リンクから登録して始めましょう。 + + ## 概要 @@ -236,7 +219,7 @@ GitHub Releases からビルド済みバイナリをダウンロードするワ #### インストール手順 ```bash -curl -sSL https://raw.githubusercontent.com/MACOS-DO/sub4api/main/deploy/install.sh | sudo bash +curl -sSL https://raw.githubusercontent.com/info-talent/sub4api/main/deploy/install.sh | sudo bash ``` スクリプトは以下を実行します: @@ -286,7 +269,7 @@ sudo journalctl -u sub2api -f sudo systemctl restart sub2api # アンインストール -curl -sSL https://raw.githubusercontent.com/MACOS-DO/sub4api/main/deploy/install.sh | sudo bash -s -- uninstall -y +curl -sSL https://raw.githubusercontent.com/info-talent/sub4api/main/deploy/install.sh | sudo bash -s -- uninstall -y ``` --- @@ -309,7 +292,7 @@ PostgreSQL と Redis のコンテナを含む Docker Compose でデプロイし mkdir -p sub2api-deploy && cd sub2api-deploy # デプロイ準備スクリプトをダウンロードして実行 -curl -sSL https://raw.githubusercontent.com/MACOS-DO/sub4api/main/deploy/docker-deploy.sh | bash +curl -sSL https://raw.githubusercontent.com/info-talent/sub4api/main/deploy/docker-deploy.sh | bash # サービスを起動 docker compose up -d @@ -331,7 +314,7 @@ docker compose logs -f sub2api ```bash # 1. リポジトリをクローン -git clone https://github.com/MACOS-DO/sub4api.git +git clone https://github.com/info-talent/sub4api.git cd sub2api/deploy # 2. 環境設定ファイルをコピー @@ -463,7 +446,7 @@ rm -rf data/ postgres_data/ redis_data/ Apple シリコン搭載 Mac と macOS 26 では、Apple `container` 1.1.0 以降を使用して Sub2API、PostgreSQL、Redis の完全なスタックを実行できます: ```bash -git clone https://github.com/MACOS-DO/sub4api.git +git clone https://github.com/info-talent/sub4api.git cd sub2api/deploy ./apple-container.sh init ./apple-container.sh up @@ -489,7 +472,7 @@ cd sub2api/deploy ```bash # 1. リポジトリをクローン -git clone https://github.com/MACOS-DO/sub4api.git +git clone https://github.com/info-talent/sub4api.git cd sub2api # 2. pnpm をインストール(未インストールの場合) diff --git a/assets/partners/logos/aimzoon.jpg b/assets/partners/logos/aimzoon.jpg deleted file mode 100644 index 3fa8c653c8f1fcaad2708d31d0062dcad34774a6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 25231 zcmdSAWmsHG)-c*Q1Z&)(aR~12PH+f8gC#(4x8UyX?he6%26uON_u!BKA-BoNnK|#g z^L;btdG3#UcUA9QwQKoWRox~1bK&O(04OUdBME?j001Ds3Gj0nAO?Vkg@uEKfro>G zLqLFkfrN>SgoucQhmL`YNrX>AOoUHJ2%=!529eQ|6B5#J(b6-su(Pw1Q1b|Iv+^^t zv9mrCfj~e&Kte>qMMlPDB_$+f{oB{iE&v)lLA zUa%05P%v=N;6^;K8c@%w{PTi%)F!h1wC!i?u z9+Hl9yljfQ?(gYLOE`!>8`xMPuPG{FrqZB}J$D@Q-m0A8Eq(Jz)n^Yf`nN2fYBU%I z6^gJ}m(p-l)L_=uVJ6Z~K&te7KMXTKe}@|?PCe5quNTLho1lJqiPjuua|33DRX~IK zLD-v_ng-n$dUj;JTSM=1j0qR^Y^N!yY*i^KLsJ+MId0?8TkH$Q`*mU4P`xsa{2l%d zTTQrR(d*4Cl?s=`*Im04I?b5Pp92^xWYv$lR#HCg@t?_(k6ce&3E=Lz&+QbcMuHjg zzN^zGeceWCcfhFoLRUNI z)#bZg%O>a94->kl^P_L(DoYC(b6!~vVrxgy&d07h5oc<-l`v7ZjYy>~%?({FCN73M ztJLy+@E0@)b5Sn;JE~uFQ`wBZ^+YW3Ob@tGM;X9pr z6jk!&&fbq3xwR?)0NPrHF4X+0#Q2r@kLjX(IpCUPo9)5`oeQ3kOc zIFhsU<%CP+2M?Vi(@tBGXjApQD`NKTaen;q^$P)Rk}!-d{tgdXYU5m^^ZaT=#QNX-&cjY~&>#Sx+r=8l@>YA~OMg=p8eY)t0 z+t;EQ`hd<%e0z6cNN4EVj6qp%2N|dz2kNpCsnsvq{UC||7gD8*9h1UoAgK6WV zOIch=(?z4*p-0Pa5m~nn-!tadvks)!lH_8Z0N{uYALX#9Cp>4z;e&a1q7rXF0J8g0 z3XOxbHW6N48h$i^c~V}=$8FlxEf(%WrfzHu%{L&Tp8!HK3i&#v3!3Zhpx5!|cs|n| z(^dvl)O#XG{T~N=+$QTFnP_&YPRIK7mhF*A`KQIj^A-__tYkW<_l5s7mMaNELRA*(pt_m za3r(2ZT(0dKPJ~6=xt(~X&=2@_Q|3R)Ub7NxOBSvb-%ns=aVyc^{m9)rGj4yw`9u*~R~3IXv~@gs9eJ z^j>({%GDLUj`)+F5sx}!7dKXGRAl^;S-(d!8x>(unO!VB6q6c{?#EsQz!BjWJ^eGh z>yI73jlv&8YoVx^7W!Z{8Tr^~cj;!kKJ-xXR%4f!=!Q5a3d{N6$6H19D3a0k8RP9Y zZ7cQjd2mTWi6cqc+VrE5Vik+3M^Rij2d7u}jxM)zk!4rfj;p?Ev}_0Byh6AFl5Ee)E{J!=5-}AozeH!#d3&8XD3I zoyU}mD9hj3wujFdiUCeCy^mr8MPR`-1O@sy_p-8-M^Sy3LIZ;_ZLFCFhMU@bqYvnK zh~y;x+YWHC)bt^TSGKE`ODwvvBVTIXbvrZ3CvELl^z|hSo*voU^Ur;oebMo*maetj zO(Ji9vXU^fh1DW}xQ63P_+s3w<#qc=&F5Y^n^hAtO~+bnu>O6ou@c^0cV&3%Z)VUX zKQmIiheJEAmA&9~0BzfbaZghm8?mTT`B4G0?|Gogo7xa;C;it=?{gV#c7A`h48Ae=9- zM<+yJ(%RKkv&*a)lCGlG#mR6`f`dKd$L&ICA&VUF{;l+-_->4VpfO+ha30p(vNK&} zebwl}g;nWnEncgIaz<9@86O{!MQPc zN0vT@Or zS^%Gk=8w*RFfXyMiwV)$G7ih^S2>VZ1NvF? zTSeY$ZM*WnZGFozTVJa?Z01U7TalrC>zlE`k;axG;WTzI!?`Ubf2925-T3QOmSuB! zLC0JpqnDvWHEuo%^Fmn{7;jM(?e|*Q0RWyAjM@vIEWnwjq002X4hqKI$!8#gQU8q& zr%Z+=`6|MwN;_6=6dxgP#eU3Fccodd=NvQT=VUkuy8~SwNT~Uf7P#*ErHV!nD-R3z z&5()DZSWl`Z8Q(B5QrJz+d3>PjwPqg|5F%%hb9lfw=bs}Hk*$bLz?SXQN?o+TgDI1 zZq!YAYL`7y*j>$*)pY6$=DxTuvzU6|{m`v_?XECbQR>8CiJYdvX{oW~!hg|rRDWe1 zVfjJzJ=n8$V9nR*$+IKf56D&P!M~-UGEv+Q$QWqh3yZQNJ=$WtIVPTbd2X&YAcy+} z9ni)L*Qy{%nFzm6hX*fX;L=b`O3#S;x*{F1DP_I{<)V z84YU2k!9d`uAgOXM3S%rlA8XRfSn`&q&f-4Gq3;Cx5OGfg)Dg^9qg_*6%FF6+Ge`@ z;|_{x)7q+z7A2Wy0tT6hx)^qTqb4%a*j_=EF{Gn84`a5d=n+Jr2)|>nW>;%W=FVS?`R*V&&WfNzb>($z)!-TMxUww_N zsIY+PP1^p_>$kjl^cnLw05dj}EM7&JPVR!QVmxU!Xa&XUzhU$z3@%%GPnC3?HoqKQ z$tq^CdKjhFvKm-xo%*UKOW9(1H7qR&(;O|8*a}Qc6@3U>`S!$Dk}KUzm46cWubxnE z>f~+dRWc;A=rk22=~%bwj~p>ev$0@=5ddhyDhZec5?Cdcb|xX04^Dhq&W6``t;`Pp z73F^d8FZh>yWLx;_BB=G@Aa6cp;cN){;y)?T@-cUjt1JoKk@!QT7m=5Jz2p&;Gm&k zVW6PFGtggCQ1G-A8UO=?MMKBH1Ywi1uyJ59>yxnxi;z>W+e9mYC#CRUKnNJfpMX^~ zAPwG<0j!6ETew@WRI&eGZsBhJe>~?ozHj!&;FZ49lUjwWO4w;8Yw1kgm@!7&MCwn|J zpw@>b!@$_fTs6GZmlreQYJ>RVQ56^#BK2u(t?UN%xjIFFuta?QWM^+c_7mXM>b&)o zOmg&nIJ2wu%;^BSkJ(>Gu92ZoZP9Z>&8&(Ut@a)16P9T7o5repJwvwjCG+zW;<8+IU#ld90Grp86~idVXO3JX1qxrzQ2)DxEY#nX-Z!$jJ=KpnEDg_!dCuREL4cG7s!4=$lgmh zH_y%#gMld7ZeEK2D&E@Tld<)(%DLtU z^WtB(B%WE8RaV48wU~e_y=a~jlBPx<9cGn1-lgkC#rk`@aJ=DU8=$xxC3Cznq)|!T zGX=(CkZ%x{+M)@ePT^rs&g*$R`ws8KR(6>JGj^_D>Z}HCU553ABf8c%Q5hmcQrzL% z_+eHRX1~?qLoG9PG?`zhW3*d3HEyhTf`mnlZvwNeLIm*lS6~v-)>CP_aqB^)#|r)euxaA ztaOq*q`sMeeV%zwek3IY_GEM)OQ>j59Ss$AokAbC&o%W29C#CMvl9ae_!vShs>9Ax zjGQPv59m58QT*{VMgb=|J^xlgN(x(A@?Z3}RHV>jx#MGc@&m6f8*Qt>XgGDqs(won zeXtV(k)U6gXmzHkK)bNmuQsQ!1zJ-S8XS2JEXQZr3{VS{`5L4M4-)!8F9Q~y?9>@u zo=Jr`Oi;n?b;JsZ z=B+a8A-V1esUzVxx-}^s?}UX00!8ew>SFZ9?+H#FB=DtrIQQ69< zy@r`wH095rpLdIE$EeC@$sVN9?SN#7u3XfPkZVi)Lpo)N7qQkvMBAyrK&778c5Zyh z$Ewm7*=E2!xf3G4K8KVqlWb@h$Y@rzJ_rOCeuG(su(ZKu%r3?Xq53=@O!+gr3hjmS zbDV%%DU(XrQWrY6iYqySN9cuw6sB_ZGoI!fJR(xGI|M&4e@sYj7-#h4{xYohvFQBm zbmb<2&vAt6kmlSs{LUdba{mB0%-S(~e2afrwmefwLX}ol_!y(f@V#VBiD|ng_CN!@ zU=rC4d9pHqUf&A9wR;O6n>tn<7ZaUiRmAxr7{v=#{$slCO`!$1Sdbn66 zWNZ~^wU!vr2ImmhG(F;^g-ZR3V=e!zXTm3VhlVPHD2^rL-5{jO(AXn-VbP)dA(I4|alL zVOUvgD5>6zM-~6^!-sjtZ2Q#9SVJl{WNp*g`Uq{)^putq4_+}G{KD7&@I%I^Q=>t*PFlb=UCHf$9#jzXnwd1@;oD(J zlC^>?f@#{ zDS~~qsRh*&&0A``wrR5LP?yW2dM)a*j`M?trob-Nto+*BG86OdQ?LD^(7Nyf)OFUe zH=-{l#7Mj4d?&!RYtv^TqGKXU9_I}urYK{ivOA$QQG0!c(-IDkr9eFj`zN=#Uu15m zJ*h&ROB;-9#_=@I5(`onO7lf%!>-!jhA+|FbgP%tiCLU8g3S^IHVay_t~eA%Fz`#^ zj+r#VDw}0{bAWl+4(>LK z-5KJ25xAAt9x&H#hzHj=lLt(B6M7;$QK||x&b%Rx|K3og$sH=Ag@!j;Am2!A{hn~8 zRnxex`&df5y^jnp+vO=g?8zP6@E6V0nyp0+PBqoaYS#S(WG4CzPK`P{F|6fB^?K4} z4nBQD9(nbMnN0G60*PW_X3?6)aGRW6f>qhkPFb82*BR`yg&%zhNm>JGJHvN^Vsf{M zu6^3g|L6gej5q2hbDG<90+%zjuQTPsa}yF`;xHXg$=^Z@!p z5D{?f&9=p1+TxfO?%RMSI`CB`qbCd4O{4HJI%-t50r6(w5p>aXWwx2D#TOG^elDW5 zKlf!QVxi4zn*Y%Q7XR!4WvrKPM}m60N)p~>aPmp9la8c>@OlcfUwrc&!?rQQ%(Z`& zYML@-Hmo%wx|z#}ZAHrO32+_0@`*G`4cEdu&c%e6{biEXg$B1+A*^qeAF01uS?Kh~ zvs9sx6fdhG$y5n)J{|8=lg~U4@1KO-x7BVF9ox7*?nT_N-Y?$ql;{5YFf1P){K!gz zBNJa2HD$A?UTQ^(l(Wkk!MIqL#xJJ|Tu!ai+={(LsFJMzAD)dIZ2K{SYTqoR3JJ}K zdB@7Bo#lAg5rJ^41pfYeLyKqp$Uz8B=(nKG_Ns!ko+4x^WbtMtV-zw2s(Iec;?3ej z*&qDZ?(-Vcfq8-1^%k;j>5U=XVqhe8=2;>>v$j}s-SZinnOBr;S#Ma8#WL|D|0M+? zv&);6(pE~G9Krc5&Wk{id7>RCZX~*H<`8fS2aZgb>W*nNI3a4*be3OrM2UJqka;p^ zq}wqEWLTwB#hS*w>yoc@>{jkprcbzcy(Jzq6aot=hTY7W6}nyH)ozy*KQIysat#H+ z@~o7@HuHYffQG>fv10E8LXMyT=eZ*6UFJ#gZ!bPs6KAgph}60Hncl!oe2BAwLs2;S z0qHYaq?g`!l6JO6w*NYC_tm312I6X%9x}qN@OC!`pgD4hQH=Y;CYo0 z#7}?=j}P%krv9o42_5%$&HkY=L3P{9+Ngv~_wuVl7C|+ z*S+u(yysaG@*kHfMQ_0oWu3l{xk%;QF$jm3!e^N*9YA1Zz-l_;~4a|ys!;*!GkQ^%~SW1)OX z<+9SxFLN_?b>4Hfx2CO^YFHu}_XX&ppPx~3pJ{o3xb!{HKR%P4LRQH&&Qq4+(`1`1 zEtJfOa%4gQeLt`9YiVXJyPc#4GuivW>Ze+X@%}P5iOxqmRna+6mD!&t-6ko>)qn#% zLZ0=bz%xvqaH)&$x*4g?Yn5ue%*f0n9q2-huip)rP&yQ@zvgE2>iz+UH0wrc#(^n+ z7R27m8)D*s%X-hv7W1D#ZQge%HsV7lBLnKU~_?XEn`Ntv8?pfuU0uz zjxJiA*L`wr)ue`IyoUyriTH=4G&O#fVt5Rhx6U6;6T>-|j@S(h@|d_g`D9CS1L$5S z6P9=G8pF{s^Jw}Eh2d&^r0xP!%UoH)J4nwsujJxwo&EaB@nhL458pOr?b=v?M*AM`-+P@DFg}f(`RrL(tx873KA9)9EHD^ z7r;BkXiz|O3=lX1p;?(l^lgNdZGVLzesMStf@wUTdi@XjB%FG^KQ0jY;=pz46+S#Vm# z`q8pZ5h`pH7S-oxR%GsHQB{+u!oTPXbNt|3$31h^y5KZ%1;N3# zEa7E!8-&BjX`04-W;u7*XEBLS_YBhXS?qH%ry@ZmhTLKwOi5HrnELIRsjaG z80$Ez#U$j`Y-`IB;RhPiLT3eL204$Tiqo};Z3+2+lCUo#V(+e~MuGI~ztD0^*61f8 zZ(uqDl6RALQ+I|6om;J~ZlmyDGLIBijRhefB525VsiRjV_!m}<9)EPMbLh=I&k+rH zf%&$f;iGitoP$@e8SS2;d%yG(@|(WZZ_H^*SVHtgvrjQ>-;ff*%dIq4s=<%@AvWqC&+Ch^s8~FIf=2T;_ z35%-e$K;Y5Vk(K*MAvj){9a~(6#|bsV-YgB&6O)vrfcf-8r6oqVc7rr_-r^Erp}=8 z{P^95b@GU1|7pSNK=3_x^E7z;buB4 zwtVfpz1?BEvKxDHrq^C_iOO1&5p_=(Yc=CUcNHk)sbs?ArTi2cOk~;bydHTTpm=St zo)CBa<65_hs^JHn+p=O?ddBoxwFdpH?_8x2V2r6P@;qy5t@;hI?|Ef=0ioDg-WTd? zM>>5?>t>SDq8hVdAN#<9dBXxPOuqVrs{lhq1Fh^h{y8I@0xy>wQ##?U6s4@ zrnachv?kSt{LoWJeXZ~_Ji_CWS6;(OJc%)q^GmJ7Ooq_I1!*}mtR{~ zwnW!(2XzDPoA!5Ke3gGF`_6J=M}@|LTel^+$=Bs2GHY<5IAS5tD(xsIVQljzJ+A7L z%lgn=#N#J7@T20_BkwK35hpZh>WK3aq1a|#T**u_iK_I2{~5v$80uDz7MSGl8Eb4N zvr({}U(~&w*gBJG`Uwb#x8)219<;{eR+e?226urq`%sJ}rWq0wK4(>KGw7Ra!Q}%cU$t={GVB#VQM1M2PxGh6Hz7 zK?H|f*^+Qy^A@s<3pa|FVOVPY*GGe+?~fRKE|1^5fQEm0Z6JzsY*)Hqi9$Nj1G>^2 z#fZQr7a87rQPl0kz@8>D7BtG)8se+#X#P5{rKir>C2ol{@m)l%gWXDb#w#i35Yw+0 zp!JJY*ZUazU}XHEd~DnzD+qf{~X?h2-20&AJ z;B2_ii~a7vGs-yhs*L%7MEa5ikyC`N!@OX zo1;ZGpZTDubfYQSpuyw#iDgxz`@GVD+e&W~VdNO6yqEJZ>gFsLh858${4A>U_qz<1au8?$G;bQ zXX}7wcwDf&FPtNCFL5A&D^6^GE5%83^?3y&s*4(@cFuy@jNwB*>;~t}lDnYV!)9oZ zB_eHKI9~bUhcB75Pt*oKEJU^sT!n~2GwsLB)pbnf^=BA@x^2w^t6Jl=;MX5CnL&Cu zn)k{dS9G?^mxuh1KQ}0AS~PX@w9q?4f0ujn))Y#+E)Siq)Pn&<25auh~i5-LK4G`iF=*BG0zps_SVF6>nQ zfr`$q`j5W0-^90W-4^%iGCJ*Z8m+M_5m$w}jWNa?X-wdva&{i=9i&n@atnCbZZr{M)T*r4*q4rd}Y}1>uA8OV(+m$j*aB zs`*qVYKD9~S4@v&+aWclb8uMA3Fw^DPKRwgeWcl|Wb^tGFGAqAre&HT`tVvDGdI#b z(YRYP>)~j3k&Ai4)y##7RQO8~?WD&cJBOMv>_Z0wkSmB(Ky~n`nd$w8(_-8s3-@C& zxbwCzDu{8s8UFGiAI$CyI90GkCR|3|we9^0AoqIU?85C4R5izcxsMNxKl$cyY?%#( z&Ms9oJMGYCi5eZEvztavbQZ~Vw5rOAQ9xQOaAGb()Odp|e4Y$EFDb$`q4MbD?A9+! zH-&^H7ng2PfY7Dx_w87yXgf>oL7w?$w2)=k9FZutWWlqP_VPsDX~HipSm!u2&w>-@ zLlr3!K}4xJCmdG8G%q!~9J`@BCb!rwW||Qa8RFe&!l)Pf;#Y+JO^mR`W6p*T@PHFp+0qsFq*Hnt%Ll)v=_piFSdUKb7!-QTIrydE1rx-E`OPRpk5EGTru$S{x*;c- zl7gW}xnPM;&4Ih=pRv@#mnT?DSx}g+)3Uxv>|?OKOn1^GRPRCaC*9|4qg$G*%^0JT z4%kNg{Xtk{$w{hB=b0mwn3H%oafaSL59vL*N#hO(I!`0a^6ioDo^sD?F{fF(N?k3P zB*Sl-9`=|Zh|*I*HqFK_mpCfQ-zGVJM-+t-=)^4@FSk6m{XWQ?TE3j^E5c<&*YLOS zO{e=umJ`L#4k5zFj+dOvt;#$>*r_sAEegkwz|MNB$0b7bEVKpo*SzG_wx6Uh;)ppH z{$WX5MAS`A9wC_Ew4i*j1qZ``E6fDSVZg5h)Uk|#Z0TtzxOv(E$*Y-hy95DoeN?NL zPRGEzENx~Np$ATzlso9}lAG@zC2d+fJaKQS9gy{VdsQTlEn9TTO130vd!ORKv3(Vi z_;Pasg-+fV`2sab<^^N6^{P=LHHp6hlS%nv55188!pNb}k`D|1G=`h|W=y&Q)VN;SAWN5Ymd{<{WK?TK1k8PX3N5%MD;QwOk}mMNPH(^w zmN9`*;%nv95f<43O`lb0u#Jsh*o{jt_H2q$U&jMDtfFa-^hqvw1~_W`gw%2LQIink z+MZg?EzR-^YX0gv(@MucwX2j-uz7z6+rOCT{TMrx*1-D-f*?JexyyUQ$`KnDP@0;e>o({_;vDU`tDm z34JJVWA7B*LOGmmm-#joXa=-lcNw!9OpejPpUA+0@RL&8lHz7ovQ7>w1zn{XZmkgV zMu#AGj`D%0vOPQ%68#vinVNm1Ls>S8@mAP+J-@q(W7T9>1kiMrKSRE5!A}JR|CBQl zB1a|11STEZMzhm|Lq|l7EO20}7BLQmT7i%h3~X)#>AS+H#Bn9Jh}Bp(%SmoyQ=DX@ zAOxTOc3iVISi=jUdhi>)_=*7a5MS*sp-HYaT3k*$M^}I#;svq&kWrYzM9FDc4^AtT zy=b{cr0X#ovS|r7^ne~G<2viyL*G?uv5AH<;b`y23Fo?(AKh$1>5Cd0PuVP}Hm`_$ zVC$41Lo`*LAJ@GWOlvj*ny`We#%9d5TIG`D7Q?YV zAgkSjqS0Uu*%uX5`9DR5dtUgp{1)52VFSnTVxPf>n|j>7B<>@`<^DF#oa;sYytt^H z?`bz=^N{c}mOCQvoiaq;)!(J>TUP%yh7B_;PlcE>6&gq_C!Q)(DIG&e^=&oWIom;v zDrGW1)Z^|esBhkm)6vAKxZ&`8$@NYPl%4W=o&QwabNgL56fKU)^0daPfb|bRWujBN z%fP{ASak*U&-qVa0!q%`xk(DU)9REz2<84lEG5LB2dUH(ku2}bCA|Yv*HS#n^`d&K z%b`G_cS)OQE|>5N^AC#P#=5N84??AXFcldd%BlEZL`Da-JXZ!wo^xY}!*ag5)4Hta z!sNg&Vjs?V`)MyyQB?v9)Qx;RZ~Z;T*R#U>n^DZnMkVv=QtQM8%-1Ep;Vg6l_gTZ% zN!}_%G6E>=D$U!qWvU}p%0Ku3A9TLt)C^}lDNrB&!JiXF{WZrUi$XmahYC&35)Nl2 z9qsy)?6JtE3QfD|o7Y444b>*!>3;$!Gj?hp6TM=`FEyWD2@RTjrwb7XHnYku(YN)u zR&7SCe3Kx;H`_NlPdC(9zMJtny*ANqOmi43v{&~X7-Gj03dVPyUJ$0`>7Ep7S~s|{ z*yFu&BO!2(rlv-E(Jco$ekGl-M68vcP!i#$$6+~W-K6pgEyHR&KC|46!LjcpVpBITbJh=MpHwRIo+2}f&ZbVaW>N3a>Nc3lSt0zSVLq}nU{34qWWB{qv7xh6W*NB}GNCDA!{>{4^> z72lwVEB)EC&j0b%Zh2XN&=oa!Hc0s7a)6EC1dPy(?RF`22cs11K9|}b|U|P;n}lZ&GlRmoEiVj zb}Ij%>N&Ii+2+Lt78p{=HO4Kv9A-^!14`d(LrqxPwQNJzWw8~qj1Q(Nev?om9h?db z6GGK#|9tqr4wa$9jFq7SdgpLg|B-|id;m?*D3;}^ytSPosggx{>th1|x!6jvlC_Y= zZjclxx@$0w3cND+Zm{e57DpTUZm>$3o1dCZ_qd@ z5uaz^m#Sb?PM{sT1OjBXu}a^2fu8_(wqa>}q#?pI1N7bVXP{ryhgp6VRWYCIX-I4E z-aPoxKtPD!!}2bi|BSc(KOhHto zVQ7dy$Q!Hv;xgdB06pNSU?ty=dM3Vf!k25e3_$n;VlbLq_%Hy1ONEa?s?@rgYbmRm z`JtFY0OJ?pU<|y!Btiz&ebicGSmjp`2nY}TEJmmWWHFcg06aczHVPM60ErVK`$8~S zGE!DjV6eDo)|uNDV@o465S~f|kiwcE4jPD#fR}s+$&w*_kTW|C^GLS`FaLI7U~XlQ^iDT?=}ot|=O6*6R|u=TkI+Imv+NwY~4^WZd>tT}=*&H{s}tmZYAn|#TKAkM_f zvcG&wEPC7qCL#h2H3;mu@kSVUF;Mw9dLAdOprBZj#cjYnv`rVD+f}6Y7150pLd6@O z6s;Huhh{9*nG#c3Lg~?M91f60h+Tqro>q{pET zZbp=ZXgp!zU5x#O61Y|s#UEIzos541s_rsheR(Dg@Izx8D6_zZG1DB zT-XDd013i25#LXq0-$TWmi8V83yS#~wWlaevl={sQHJalamMzb0rX(p@dT*GHuk3 zB3w?CCb!s=QUU7od`l1g5EiUS;%m44DMroVso{ERz*4taTgo{&r`$?fIS0#t1`*Y2 z?oGPD*>V~(%AfUMCmfOy-^Mt2pn=2zU`89$O3^xjn{r5b%Ulc%-w7lyU$cm5hac#uL8TK`0+0 zxz1_=?Q0Z3;rR8FeIXa_wR305K?qt2k|gCa#@CP4*m_m~bSHk=z6$!xUF zt_=bW%Qw@4IMad{dIN0s&6m^5Wc$h^*OI&13W(?xs zZ0Pqp7UAGtA>y>&$w_H^?MpeF+TjZos{zfDfU52>{q_?dg-7mz8A?c$yH3V-mrj4{ zg?OhJfYB{?j(o4$7~m+8co3eOj|VqKot6^5_pNh{-;;RM&*QAJNc@!08~31L3uI7F zF|$~S79FwTC2Iqsu(SPw-0!13LHP>iEk`h}vknYi(+_qexmc2`eaD>^f1n)KOL=JD z7p=i$J5w(Y*^np16t0Jg(?zNa9Ypm7VxXuDU~On}joKi=ecPAOdW}lI(N{_#$z9k#;q^x3IzDd%hw$!h~A+c2L|GmsiPmZS;b=Jw%-=d1%(%rNNDP`=SIN~iw2v0rIQ28RTtwUG?fDP|0hEEE3>A_A z>Uhu@9u(rss+#OwMlM}@{{X^ej+}->^`6;+C*x;}aY0JYA%zTq&$(6t0AQeX*1yPg z29Rnl;<{BiNnq0GHV^>Pn%>lj^MymbmaXoYFLn}&z$xLfFLL_R5SVth-a%0C$k4)) z-nX4;ogY=bLE+sq&1!j`HZTo9bxy5J{JPpq9 zvdGRfKlU5Ij-w@D;1U76+)3eSQ1y;`!=rK&@4y-c%Xq!!*+5%@!Yb8|^4R+c-~vZ% zJ_v&>hknQ}l?o=EJ%Y=R8I;>6ikRn1FKs3)IcrlF90{GAg8@J{r`l#dM|aCwm0i zx*~^SuhdmhPvvc{KEb06`Llv|(Gj3?q@Oz+1zT&gKHvp>YzfaOk=2fI=r6fLX1?dT z?PuxrYn>aN`u*-{G?z)D{O_xr!U-8-iV|Hs#5&YpIB$cLEXY~o>H`|YUa$eW*T0bu zt~?>#x;WRF6FZ&oXDDx2{;OOqq8Oy;4dQ@6{VqV4H?vPfQm#>LP=_=Y4Uii;0?Xkb z2sc=mlpTIUzJgU;GdgicRV9cp4#wj}p_GgS_-p6|&ih_l`P%#S=z5G+GVoxY%<@+| z;{C&p5CM1txk&}5sL6q{Bi97+(?>z9O}({2i`ZX#?n%B9nOj%#`-dCH8q$tPVab1k!qU*Pa%U&)~^+}%r zh)cx7>9O?^h^MWv03XJRz7lF?s8%yHA>5H0ipjX_&&19*BOXhUM8$BC!8x3|1pLPsF`p;JfOtUnXL_^J=+m8P z;(U|a8%P-})`R7m)MMWhBauwG04>Y1GQOXjuK&pcU2yUPtnVl-A2~1@yNPQNIM0{F zVhu$yDe}JpNO&KJFAa%>i$vCi?Wwxy=pxPD!QI0>?B@VP4nFen9qU;sMR1s6dU4?Zs41 z%=F}MB8)~?Hn*9Gk4K-Z4qSDIAOdOkR}5bQiFgYszG>slvSz%xf=0_|906&N1>h>_ z#zBDm6Cp4*bV;!-#hMw{#{JX#-ayFl6ea8sM&y1j$>)jDvopS6|1ntoe$T#}03=nmKS@se5(78KH=4m4K@rU%vYI z6iwgx?64lu&I+zMD>h_I%1QgljuOBWI~hJ>fI(7~s$AVMSkmpLE}pA(U%uAZzhm2A zL#rwgo(E%0pYA&-dr8*{jmUO=)LMP6KDe&_LG52Fju|B)I&gE$y4VzNJO)m(>|{gg zlo%C`XsKtPAn8#V2rD$q!YVm$Wf9=il&RfyySQFXwuzFCzE-uNN&h4&gAZdA#ty>H z)<$^uSCIz-)h#G3;1E52^E1|C=XmuKkk&}-1p(CwZOlr;UPkWQ%!8MxB`NA1Qmo0G zHXSn6i5DJ+AUY)RW~qbK9(lJ7%G_kxshpUj#NShfZ;_s>iz8gc= zVp4eTN2r!+0cCg$ox|7>$J!H;%`k_gM?G(!VAy2wH^e!?XVx|1uLhZ;w-whVg~bvC z4+3Ih#5r-iZUECX2V%tpJgIT^57)Wd0xd5gH4o8;e}K@v(*WN4_;|>(GxJXX`q7Kj z;A$8!-GO=4@u$o~1A8j&b=SmIKLH_b^m)2^+yF5o5X@hYgE7UBxuM2spuiG8 z3;h@5;TBGl)@Z7CSHou?_bwyW`2mXjm(YK~1q%YfUkwcq8HX1E;9mU|w_CHU^@D1n z%-vJ{@F`D|BH_h2|M@tf9oS35{I%o!m%j`2V85|FyN>X3{7;3)B0i{#@bLRz1q!G8 z;uHM6kRGPyt9r??m%~kUx50<EWymobMmp|FfKbllcGZ1phb<2?+rS0|f;I1CGXD z7X%uRg%rH1Jqc1eSB}Z4?gX!E+xTq$TGoC(4GDa5v9(PsBKl}qTV|kY&9!j@;ZILe zbOOs}j2EX#5i2=JUBcE?)c)$Tv-c`RtW18KnhblYfQ$nzU6$w0l$+imIn1@k?c7S- zEGsvG+shiIS^RAs_LAsn1w68*%a+rKrXxd985;4g@vn3x0&8=Bze{&7_W!Ua5Y8b@ zQH73_mK{ixEyER`WJ1!(Kk zL(0Z-Cep}~hvwfpfbQHo7^E*dRJuQOR?oRtn#LNNyCZo(VM0L4)bt)M0c1RsOnmaD zw8`G{!Q9I1ll(UsS%VS~VG2SFt4vFg$x{fq>(WfH)rlzQz{iExZ5-5D2h^S72l_^e;j+cQoZmKj(-R+E}3*EbUaGqmeB?5bc zu-Dm|i#l*!LdX_ho>_pM1z#TZVMD@8_24I9L_&i&%SnbJPEI`L|(SP_wl18kjY+A>4ty2fIDI&UOVt?mnxOCCp zId2&J^_om?PlNLD`Pd@`8u*t5#ILirzYpI6AkbKVq{;?L=O7VqoZ0&PinHeUP~n&{8AUZ zj+ir;h?6mJo%fzrmSbLeNSTF2fFv_L^CHj4=sgKq{y@S)0d=jR0&WvZryas1%l5dY zz=jd-qI`@&#Oie_3;%bPVGO}97jbK_ED<+_*dhJm9P+8*R^8;WJXkcM@{Rr#h~p`( zV3bt{%fxw8rp_ufcHo!qX=|`tNOa7Bp%L@1VDtPzRtN{HjcJw?lrUAl8u^pM{Xe_} z(bMqcVK+I8b+ij>f{E;y)#W3kfPYNq7_yTkn1#GStNI{*b*t!t+ZVXCVs_{|yWwx1 zU>I6Y!6fwV&L>LhC!jD5(|-a#ZW6tclzCFHhe^oz&ZpIKG9Mx9cp1f1Pfn2ZGN^0-)fa!3QUQ|1A}O2Hq?KiWvCBz|^*1m6 zx?2YP3HTZ+tkVO>-NjTvB+IMwC5W#T@ZH;*P^j**{ll*3^w5u@ga<{s+f1BOe(NRI z^}4I}5Br|eeLspK9z@ICgus6ep}x&jJQeEwQS`07?#jz_Jt%I?Rqr=Ch=HVqS(eM!La!c+*d*@CEYhB4P;%-JEa`1EIa_uA2H$^XyO?ckM z5g_ohT7MDmCKCR!#lax(rCRaJ>LL{z0g@)=7xi1m9|z!5-)hWkmpnd@q^j|dh^-S% zLfHX4bCtFAL`T8K{UlTz@GLKun=DR{txaTU-{gc#jiII;bOQ3fw%^gvI#WS?VRDFDO7jkDOqGZ z`tc(ITDQdFU$pe*@S9_3n7!QhNLoQ{U>%$ z4l?hjUWGXsHCNKnW8dCJ|Hgu^6Tx)zo@lf%LITUn2Zf;RQQ^x_#21|C^yKh~@oll- zK1#d;a!%E+JuZ0CC5eu}ng(^ESV|tQFE(f=9yu#~F~h`Ng{Fm#dCw%6?*Zx~YBLH` zJD+b*+xOpM$em?T6ca~7g3ZemqAzPYf{*HilGA{*hxHY$Nd;_o40zs&FnFc~qvV&Muc2z!&J!ny7-(#JgJo7V5~PrW#Ogy zofZyE)PYLniQH6bCCbu%?hGD2sGK1iB=$Xm8^Z+Mx1s{ReP;xC<00`^d34&4@HV}L_mu4rhpWwN(dlD zFbD)tR6s?FG-*n25+H!|-b<(fLhq2!L)91mckX?6=DnGn*_oa1?6==Jzw?`K&z`gS z4CG5x*`b+8%9xQsZjQ(nQlQ_h#Ie+-w6g*5F&FI=8!#Nol(4 z7$7JT+M6q8i&W#3 z&2DabBs70UIq3eT@a!M+OA)<~pdRh;Xin4`iNM33gswT_pXeZRSLClw(!}>sIF^jO z0<)9owYrKw07umw?W^mNV7uooz`(1pA(eP$z*4g(RZ+hqW&z~RlpQY(Az*?Ap(1+# zx#a(jEp<$D%d=jY_w8w1kB1G(UZk#fG|9lW&d%F~gRWIpBDyPXKI3}b{puw7F7ESR zZ{-HqL-CP?wH5u^QxT8xEH7%Z%iFke$_n8Q4sFs{i&lLDob^Mz70wvXYlE7hm{+x* zC1$gEmsLODsCgq4<;@@&3~Z}v^8P9|fO+=g>VraicFkYMn1FX;4CcdvOGSj`?M$)CO?`>&60((I@P=HTlJ#<}X zmQg5j>jT2dHSucmyEg$73Gc47cgmB%1`fKxKaWJ#yVgA)*cml9Vkhaox;f}9{Q($6 zv9zYInEr|o<)?ys(}&vMr4@)Qwvmt4Vzz;btNOEF4d02WH9*B+Dr6Lg#-2O~rw*IQ zpf`bBvW)1<-56BfnF-3vatD_Q4kHy%@81>8#IV^ceRyKz1JjET%1XWQkln-VnY8;d zJ=DD_P*NvF+IPkz)0ni@V$5Vfhpez)s3U+YJaOaxxmEr6dtz#?UE&g}hW1z#>Fbdi z{Wmk@Q7xM%fxa%Z5p46$jKl9_piM1n91%&jw3T1x-syFJ|Zh|39 zjyt{-HU~o|*Eg+r45+3|pfe`fbKeYEQsFv(0Ky%P2-Y%02|Nt4L>a=X9YC^jKZ`7G zqgC*Dz7Vm?2_C0K&~SRV{sE{aqHY=!Y)02$TV#8lG&vq3l7)w)(k@7iB_mL*G!9HRN>fGr=O?|AZrs%^8=$ZEXSY;E*9eA28gi|sK7N#2hV zy)MXUt2={V4sCPz#Pd%OfMY09AQ#jQl!!Z_K6u+*P!&*5x6nLb^Ogb7joG)=Z%fl* zQ-1H+Qo?VeYWy&yc)m?oL;ePen@lozg{jz2!W+39@<~%Gp8vf8OtBx7cLOs|G0Qqg zQku6tmf7=KRn)J(#%-?MQ66BKJRJ4Yd%;LnRpO$f#G-?bDSizZW`&S!MY3kq!P zai&VtcSq#rR-I9XXO|~mF)9XO3?*Ap)8H6tcuY=ew}!b$R$~ZFy~o;nycL&JIj*sb zqUUD-RmS3^GsScco`f+F^}>ZD*%4?m!aY?{FUuZ_eVy+dYQ!E>7Q>kng1<-eJo6fn zx+I^Odig@S!xG%7E`!+wa=en_!MPi!=PQf5D+ca)Sn}bKc0pZ`90HkSWB!fS9YkU6 z*C+ANYdL}EmcF+Nedr#!@0dUzclDjh62o@Q(0+Y`T76AeZSDGOUdFs~+1_b`Lt=AQ zPNvugUI*K-r@@@N=)#EvFZ(xak;_+1OQZC@pd^`u{F=)6KKHvRGH^!?1LmI&J8Mvb z9}(3jIpvR0R_PSS1s#?i!&i&SgWB>iyIJxzFoRh2h8&A7%56!(^I2yY)Dq<4N(XHA z;TH`GxlUAh=TyVHxj8_Y!lr#T@s)0L%ODA!aMYNAQtav>>ryp%0k@x#qPN;p#_Qg{ zH`KBJ*f>YfU&ZdDj}hsdTu9qmdQ_}=!_-ceP%nT?BfnGrNVb=F>w=z>#E>1CPA49E z*)A*`3a!`BvGH!_JzU%zxHQQX`2%>|9fR4Qb#7t_ybFKBs~}|`-pK%Sc<7N8`p(ux zu6{Ur$ConR0~Y{V5$s96h;_#MGYJ)A&}rMd2}IF4pMb66@_!hXCZ#xVdbrtxZ=ZQgi<=)^t7g4#QL zjp`P~9WW(rhz?!j%($nWQZV*Yly=sb)uE129 z0cyeVU*o_201781%%T9S*_yD{DVgWs@hFUd-o&wA1R@;Zw2O8T)?NnM z_JlZpmwWp13R=a{LW3qBIu?%RF7b`v#jf@a0tkq#dC6IJGu45eJfRZ$2jEBL*?NJ) z0s8&fJ|iimz9hNt6gJ4Wgf)tHtk1b4vFq0}Z;*IbRb;jM9f8-HS&VM;fn}qo96BNQ z4BFi14M_+rP?2W^;buQlHYm#v$E45{6ZZ!fvizEPx!cyb$Dy*FHB-`;CX~3M*r3o9 zWftKk<2*VXPSrlk@XAvN`?d3U!}r>vm;POV&(ZZG(|yx9G+IPCIJN}&mEjdThSc}B z%gDRZvHn1%1{~%1B9su<`sis?{K)P54m;FLx?M#bH7Zq6JceebxQP~@&UjwEpgtvg zOlCy0oR|CX21(RhHh2LQ6Bk#g>nKJqpgpJIdqgSQypW*U5?NCE2e8IR&=zWCN|uNu zNG>+Fg0l8HR!P7_#zEY%{nGmCcq+eA(g!|fafG7y?MXZM3#k?$DDcLS>2%%Zx9i0| zfRV|ut$d3y5tix98~JXR_-E2UG_nVe@}Mis!W_JJFqx6#u!FRbf9AC#Eu>f*Ug{8Y zuR;f)dbbQPgf#b&mXZyjNl#;02I#fgnOAwqup#h8h6A2aePSe(sEZ!;Eb)GHa&NMM z7OtH6TaMgb@5f)A(I014tF)B~fB7Us0l)K@WNTt`GBF49;<}T2ZmeWzGn&=G%GFtK zdxa4M836P~a5?Ck2x8M)wP=%5MO-0vTsbc%$(5NVobSC2Y%crd`-X3J@wYqiVs**B zSc~&ZpWFK>O`EjKh{4T+plbuQT94X&t-c{(SS@jcJF?cfr~4uyUmR1>MXtLWE~@boL60ZFLce#G3Vqk zrPAEFO`$HJTHX4W8b^@u9{@;>nt3Y37RE|IN#vT0e$+f?p~BAmDJZz<2r+eo9KNJn zncB(@Rl1qPnOiEA!De8AEib59OSimpgi~}(d#!KTJzq1pb&vODI_p>5DR%(%_e;X| zE%rW0+VYB5$^Ywoqe1vJGX`S{Eu*ALXIfpVM#m#j;LEHn2NuA}4<1FsEv zWeN?JpD9jn>s%9)YJ~jpSrKvpO#$`7NXyx%#C00_K}UY1@*!VUAH0aZVVAe~mecVl z6A4jF7wAmGjW~4HQ~!AdhV7ioCz&o(Fz|`L#^1H0vlkkZzcRfVYIm@eEzTQcJo-?Z#8gVZ-}h4XtK1UJa1N2)3+b}4s1nZRTD z)8oC2JOS9d=ceXiN`}*jfrZDNUHdD>%XeOn{`Ky|l?aT21`tk%<9Xg9zuh-Kl!jI zb0+oFS;x*vv)gkYos%&@IFMYgzbf6V?tMZYFf*(sc8@&6MeEAWv?FBw-PI7|MTQ7o z$r4MXVZ68q% z?RV#Ndi(+8YR94!@jc4fzz7}{9UljC?UV3o%zK`TWV}PKJa-FRT(qP?YY2H@4a;pZ z|HP?Y<+X_?O1?d)iq*dAu5}7sj(BoZVL06NV4#D!*sx0@cgkO}VD(rKcYpBSQ0ke^>rY`be4li$-gSoR zZnMa)FVu3-d&Jf2D}M%1{jA(d?3nOu$Fp$H2#}X|uOhk-sm7UnYC1XCS{9D#^47#H zs+U&5WBTG@I$xu!&VTQLmT#qr-NP8#fB0-Y<41{OUqy#3`X@&|e7bfnpUd1vqh|Et z-}JY5)SB(;_1S@xyOoN?jHwFSeAZBV7|@NZ*hTI?4*4NS#p<)FX(fc!Q}?o){-)d{ zX_j3upy1SdLzGgMb?_T4zAXbyqDV z%zQ+}fnUELlrxp6FJRhV{KS@Fw2n%0Wsy7wdA#vT3;n=vn2!;6a}Lx}b-qoa1f((J zToX9ax`lkSEj1e$J9Bz&4XimYhNSG`$|u3dJ?Ahlv%;JJkH`iliK676@v!vD&~%vP#~6 zX;sSWBFTnlI2Kj-#c-#;cIAm_e`8kSAySj=pdl~g%8>Is=TB)X=wJluy9 zHt!l#b+NouERxrn>1?+7O726+M*V1%>_ZiPSP9gqF@HSi04Iy6w{O`4LBb^5;ug0_ z$Iaz}v!PT=eXSE!B)4}18SSR$DdtAg-PQ9yU2mqnm+1Yk%Kv&{GfKB8OaW81t{nW+ zXj6K*w5%U0!=%4RL>;5YmYNPDWqt67pf{>opVhuZy}yw7=h6U)+*_tZc&?k}w$!up zP3u)TEbK^?H75`sty9m0S%Jw0a;n_Eh4A=aIYNj0E5%F*>yknO*!m9QurDZ-#Rz!? z%F^Le#rISsMgg@Sj;?f<0$K)5WO@_WNyz?E)L%)$1OyF9^xbCA{eUMab`Lg zJZH?!OCss%WCyHVX96|5-P#81f=qIEHv2({)UOA2{QIqeixQU48*G0b`}d8{NHixE zRoj(L2h}^D(p^3vbX&Xs8o}-+Ea~nG1bzhR_IKmCknZjuA92umg=e^E2ePE@TAE}2 z02bVfUum1r+X!~8#IQJxtJW^4`ZkBGhh7a4U1X5pmB_JBkn%dwGUneMCs%Fri;({s i3A{PG$MxT0Y2@12o4_SmPYC%g)Bghu&U5+z diff --git a/assets/partners/logos/modelflare.png b/assets/partners/logos/modelflare.png new file mode 100644 index 0000000000000000000000000000000000000000..d596cf8d53e8688ca7b68715978a0fd34d710ad2 GIT binary patch literal 5507 zcmcJT`8O2)_s2)2MD__;LbebkTZpnVmeCmd7GeyB>@k)?WX-;0&o&G*q#^rGcq7Ib z`y?U88Y8=}&mZyq;dNj4KF@ibbMLwL-19n*7$ZY%dRk6e002O*tD^w{0H~ms{%e}+ zmsWM^1OMf9^RN`oBX3_>{|WDN^}BwABEZ5$?6i;2KQTKotO}{YZCePkk9P z_-dN_8hbkX2H1N$0kq&SgnfQ(h9dv~JlEAwg}$NM%(IENF`4cs7Lj@%#56L2h2yk}XDqOu?e1xA`NJ zCasHU_#=Vu!a+3r?+XiA)O7goqav9gG_+!ua`^wdY>r_|-re=W`H@X=aJ(?iYpHMD zb0}LHHu2wo@rptFD8!5{#KctgA@K(CCbL~6KzqpF0TIGLst9^U zl0VY7_j%gvhn)QU{7IpXAYl;^^e4$lHx0{zCtml0EG80b=L!?^w2EzHC(pD%v2b0! z9(7-S7nzw4R;vb~GR+AWK1D~$?j1ZePD5<|LCk8F_`oS>Wfp_wRMk&`!M99mGvgK% zc7t`MKWn5q*ywHL!<~;^V8#1pR0k2ECY%YA<4qP`@uZ3UDK|V9uQmI%0H&8=jt9|~ zC2>y<$G&LZr%Kkh;JwCKi{jtOv1#^~&;b1OBTrVRzv-_D*k0&u;gI1(L{`@sRPIK&`25#2_~bEJkm97vqA(a+t)|{FQKvv__EH=9?4fx#Vh6W0_Jkz0$RYfAl+? zh^b3PhMXKote=m$d`-sv71v~)B?|IJU40gOSmVPxrmATtmY}7FGwdo0=GW2je|&3W zsAs3P-3j%VBS5lT$_ZL?&`8 z{5th8*Y;;ti^_C3G8)rgX!I$UPX+e)W?dtgS>5I0GLF0@Aouan-Q(|7*A4R&P10c; z0#LTh$wc$`53vJ?*r^GYS#h`|)9+{QC!ppgdY;lEBt0o%TuMT9$c|$XEDGO?Lb!;~ zqT(b!Gh0W{HMQKdj^NK&zpCzFKFAYgwrU$a6_4mkpj0lGP|0<(!0Uh#v(dD6a1eyq z4DzS9L}eM2dfB2%)vf5pX(;@M;D$r%tDPRV{$N%`L8#pAO%}ANj&gOA?Nkmdm5(mmQh2)l&D9yV?{vXK7Q-jmA96}# z!OxVdw_5`;eX@Ui3-!Im=V-Ftro%S)#>D%(+kI(vrPAx3jd>83TBnpeNCd8gbN#Z& zR?<>M_T#+owFs;+azPf;N34Rl9?=r4>eb+mTzzI}Z4$C|CU8&j_E0zDwh5#1S8%np z0!Gr>Xni^J9pC!~g!fKt1@kAy4NyG4;4wn50;CaJo^j;1{wJF)O}!%WD)?Ho*$!ZvW-8q4XDh zoXGq+=x4{fji;E}m%J|ZIL;=*95xMst1o%X1y&*hD3qE&%syQ zd;=;33WfVjUC*W)D4XXqWT70a3KB^<{~ql@i`nk++(&Qr2%QWs6H`|x(a&C=pno>U z-zj-J4S*!#JW?1*~D< z@!350C{G-NQBr3>NkNi}6|dOAo%WA+ZoKRX5;5Ar%zWss?S2KF1AN0?Mer=^3=qChv1cjwNKgYyxZ*;6=$<8cTZ{= zFya%sgt8?a7ATExT}}OT6jaCN9#^v=@JH?di&w<5FHNZjqkNRI9ZT&AlhUx^mRDj* z;YvOolTt#Go)Q0`3ROU!TN;&J@2KX$i`+34s9AYD{R6|#MCm;65Srosp&?S-)HDy` z+8841tb$)r!ns?#_8WahG+rHbqolwOx`GE^#}%YrA{& z3$qCF|9%uOYc3}|(%Q(4u}f@5zv}lPyBi0FmgKMbTKcWEni6~lXkgo%bxL&?rXjW4 zl-7!&t~`h|9@M%UhV)0A2_fmw+ZT=+r`a$lkiS4oG11|dn`7r|)mQ74SM7B#GXiWO zpG0=390e~?HtbWL-J0r(&H8O*(dik|AHQ5Jd*;A|oBO?7)G6i{Rv~`$X3#6j#nec! zC__w2D7dMJVe0rQXM68<$sUz`L`_-7;?$FWibcse6mL$SvzcSl;>s^=>)soRRR&dd z)s*gS!ZBUn-6Paw^cMbDiP7b3^TvLQ)Y)(|?tJjZf1V5FALsqtUWWvbWU=kLl)#Xk zjusW)4w=rovfE^5m6JXJ%P`mI#0Bk&K<5EOik?9zxjXrjndrGfMTN^h<6}wR`CtR^ zH_eizf3k!zARSMHn?-P~`Li1z)#GFO%b`yqsRU zCt6LUuCM)`Z;C5mp3tDpEQnkGF!>E-rkjj&1huaOl`gal972fKiE>J4v^gGjUNT_} zriih3_=K6PkA{t}SCGUh`@CO|iJGM=D^Qk?$_H6{&ExOR$AMFFuSBkk9>_E_da5^k z;(Mqb|BTH*xnlZv+($&yQ@~^`Vz&OJF`Gw>(SusL0W%(CE@m@hzm}0D7nbXJxW9Rp z=*Hyp^e``NO>9-A^XQ{NnP56s+DX|^mVc6JdvkX0#*AARz`PR zs_>`R^pAFi-@Z&%EH*Ot{%6;eZ*Erg>{frcE>q4omXU9#uSG?9y{?uXGnEG4_?B$^ zxL8*n7Y3tvY% zINosZIHlH)hI*cA3FHz*TUVOa32j(c)En8)mLbt3>MUu8n=dr!eLGhO==1ynGTrtg z0p&$U4?|r*2rE-mk|lQq&L)jr_h*TpUV;5I(4Nkq={|n~NYCa*{cMZ8J8T%0%GoJk zvppe`CAw-SCa)lI8=lh`;h1ubAW}(V6@yv8njfrV+dIK%4lKWUbuD6tE+2j=|%(YmG-Rn^uZKkr_la zJ&~IEwn6X~8+*mc{d8jPQktb_BfoYr?V!H5o(Z33N2zzJG(_K0m{^(#lzY$BV`jv3 zgDrOH8jOjXc2VPf?fRPrC~wR9*>v2Z|8d-^^TdoSYi0DI=^n3b?I%|P2eA^367?H7 zm84z^m*7^{?q=}X`n1ZS!b41uJZhNf$pbMaSD8Bsu|wgpyO1mS-qN}_9d20S1>P`? zXng_cVNk|JIW|boG|N={&qp-g6K3=~^b%`N}5F$)%Iu znIG~X#cpHfb{EHo7h_ElEaYHF$r8j&FujmDZMdtW+#+XkU(Z9i@iPlCm8V3f z)ZCYxtqxMH82*Cwt%`@0(x?zjP=XXbwS9eN#_i&4;F%#hf^>wTl~S&=%ag~Az85}s zZ_oA&sW{v?J-S0_U{6Gu2P=ozh%A5D%uP`=neo-4T8kRUvlBNp67seJ)b_VQ-I9bl z8dZ-9^7Ap_^DhoSgy)%xmp{K5kUsr=nO}>)xAP%NTl3YtZX>2B0;nhL&2qh+Te{{`t?3}{Yv@M06Q0F*eHk86A#z2=n3&UFWI{rJ}%#! zh^!1VS1bdnr$$7%ZvLdb18??(3_of(N^PFws~6>g>3htXH+l5>s=CmW8xW$sqY|H3 z86wbt^duG@V?+l{7n8{wESJe?nRJTa6JbZ-sKyk@HzN7H%MZN8M@njDc;`CVIFmHNqjJLw98I;`8z z%y@%o=kiS+!SO)NqJV@QQK>IO=`kv+o%g9n^ma>AK6F#3iFs7u`*mh{4rrg7eY-B8 zqb?mn<`C@WxR|vxdiStOD|U?QI$xQnx~Q=*?}PU;4;WO$ME}7C7^o`bQr5YA=%v%O zB6MfFhqE6ad)#}pnjM+8^|1ejOZggylb}>pd23uJd&4|6#G;EbG*D{!_ZWA;bqJZq zWsek#=jeQoWoWm|#Op+VS?_tpH>%saYSrhbyvUlMJUIb36MW_x%eb(7ag{ay);8iJ zE4jWu_N>?IrCkYvp^gz(4W9M``>m<_RSWp{0pL74yG!|Qi*Y7R)r}DByDS;Yi25lw zixCG%vC-!m;a^RxjdsO;NG&6~Sty7UTCYnIDgB9FYL3DLwmBr?WtXGKa}3Dxw24k` z{2h}pRF4OpshUyg*G#^8W4wv~eN-~r<&J*8_3|&~f$IDB!i=|UPPtY6ZYp>v0!_`r z;btWo`oC=L!r^OA?RkS`@mYHje&6nyyskU)&S}EvfqwTrx>@PFSrgXAiF7%~VyFoL zVTUWnU8|Vb^kIQqIH*Ckppd~TmG@++*uWh6-J6;~0VcK{DumP033>DlhpXM(n}^n> z78aTQ>6WXo#|+T;ctFfjejR)LdTO=Dg9frWBc`YcM9wdmTWOjc3-a&vS$?b1h-K`) z_ndKVX$@_o1-V;Lvc?g^0Rq4*NFnOT!JrvvY>p{Bc70K6@VMe<&xVfxPnpJV~Mb;G|=;97f^ZrZD$il8d)gn<7hs2_{abTRyJA5PQK+w;=O~is2 z!E~9m$qz@(+JwTcox%apszw!;xh&CH^ohmnTnWMhH1Sq#83w#YFqsTC=clFDf?KY2 z1Q$G%*XTTFF>w%D_++P7pdqz)1P(F4K_<0~O1n6l-K|t{xM$jDoI6$&B};;a(6udwQVdQ+ zAZC`T`i&i5WnNCCTV`DtB5^?WSlmAlxkV0i*UP&|Ar9g~k@PvlQN!qYP4_@%r-P%T z2R0}7)mM4lK}vMC$>-6EaS+oEYcO37#1kE1?0DF}z#a2ZaCzF65Ks!wbj zT)fhuyaa>{m(f|DH!7vyFelzAne9=1(_PR&G=)AWSB3u-90DzJ)H+DJf-@ww9fk*x zzivJ+8gr2`ALFbPnou=iAzN#er{u-mlzpYdXh`!4{#U3|I5G*S_`;R+C*Quvi0@&7 zR7>_Ls6Ao zE|!iOYAy@HJzqeJFG{Ux+*j}}Uolm9;dVM-?&-ibL>4qeOOyRI58tV%2)Ze63^EuF zrr|H;xVenwa>a72@^EH5xs_0M`(!TRQo00)9w+EuRm;N-Xu6Bmqv2-}cz8+o9zXD% z8M=IC#tMY0(THB7PG?f1RaF&=Oj0v4y2)R{^#3mRgaLlq-CU+|lk~V`qySw_Lk*1D H%kcjL(j2DA literal 0 HcmV?d00001 diff --git a/assets/partners/logos/proxy4free.png b/assets/partners/logos/proxy4free.png deleted file mode 100644 index c80741e4cd97a5b24aeb5f5a52f3c2527d8927c5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 7529 zcmeHsS5y;Dus4L>L5fNX9i$^5NDCqeD!unmL+@P(UFjV{uZo~_kfL-D5C~nmQiLE? zdLR&zFaL-8_PyViyXWlA?EdC#nVsD^b0$GoTb+uWnH&!fkLsm{sy-ebz9EkHCI#Ty z$#1|w9KrX~S69KSpJd&`byOWqUqZCB@C0!@DIR{D3m)NrBDl(ot9W<>W%zgmIEw$@ zSQ+4dP<+EOg8$+1y#Et)4?T0l!(*L$srt+?82`wMB$#oCe!WYI!(SzbT0g~~HvZ@I zhpV+vx@<054&~kME50%SIe9gQ*0;p6Xa<+W3+i%y&e2=!KQ^p=%dL54(CBF4)#>Tc zDlNSc1uxz}gVPKK`^ z{)U7UUq&r5dtHm9xE;V}x|_}5k+f%rMM%I0zbimZn+@SprKn1KrBM-o zbwG6yEeD}xd}Q1*Wu@k>m{g>iLV!wqLP&69p7YM$L}r!k!}Dg=A=9>??1)E_5@1ke zb~sMg>9V99ke#$t|N2%5&0>tbb+gmeQc~#Qn8Z$DCPHM2+}QEy>y|HG62}gc30$Ho zk+d2Q0QLDO_4^Kb+WWmfErZ$M>~JxW@%uj#Wgt&qHEn<5<>R6S#75T8X}pO8Q)aKj zOB5Zd+M0g1Ead}Dzx$b7Wp2~q@L1(pq23i9VUi7s4xdCe>&bd{d$GYv*uAL#4w4wD zmklh|XHA0y{^gSIivBG(ZdYNsqId5FDJ`Ih&O2pLtPOtsmm#Pu|IRND^}%kQq%j$l zt@X_0jw#~X-Y&3;?bYinImdcdGm7nrhlZ6!?YT`SK1(l zK_EF$QNAQ(ccFf>Pw6O=|2&|F$!C}>N@&rubzcd+b|>Cr9NeLJe7a1Ly9n)$`5UCf zX81HY8yqtpKwrc6xS#AAYaQFv5^A~>0C@)zPY7>6UMm%MbDV#nC}#CFLscty5O{kS z65JyCoM<9w$%&lUhcqLLGNBp`8LFXi48NT6B#^*@L8JdLgIwSx#9Z&m)ZG2gQincU z3s!ePgtd;czgaHEUgs`AqW*WFnxVO6DGG9SP>W`I8+V{>2Iu}P#`ZcZr*d*k|Hk4E zO2Na99CJTysg?efux=*y-&*KWkB)|+p?_xkww9~%?ia`Pf3mb`>@#p6&2+8tjK>5` z>&QPV%5$v=w4WqaK^RI66Q(-9gy@NxZTlfFlsYl|op1CLuG(*6qP*`2L-n&NryN@q z^b$b8yYq9cRr$8s+-e=D9}tOvSsCoqrGl}}J83{qUlAzIW~^UG_FmL#h#1I@*gygpVm2^US zNSa*ItlD;-+wfa+Y|5VT_`-`HvoGyz*HtslXuzX`99a`{_@>FZE|QjTkOKrl9{ey% zY#i%0?P(Tve6fQVRGcXcdGiR{1!a8SH=e7eYHkw#GvrhXqc`}A+k@|Pb~{+8Mc0x8 zJo%V6alv_kWI+iWYl1wEXh4h?TXEZ^?XRS)nlmM=%nNteu(&*n}3FR=a!RRula=aZXY9nuTRy*cBEUdn|vr%CX=M8WJwFhvW#s2@(7 zO}F8T&q|`dMBIFtUlZe|Z9SY=y)yS_V@lNv`aR`vmOe7`@HDMd>DG2iN5Ki{o-dRg zVp3_@>GQWGWi^!zjD+J2|Q@7UIKY3pKd)?qxe z>D7>afEzL7OlJx-V0+VWp4)b$RI70HFGfABMER$MnWPb!u$4@8#k_5Rz%)}#QVwt~ zz>sp>2sZx^-hAHx5_;-16Go%6gQ#QO8w%nC1h}K&rjDzkt$L$G4!hVqPQ@GQVy+)I z{B37bR^P%8Xl_GFxaEyW7)H}<51x7tfbV1G6B}KfE!z`e2>PXF>oz2d_=&0rn?m@r z`M%k1Iq5o+b7)F6Z&+7%#NFLRG$YuRL7L9+(;;jMGS=XN-Pl_V0y5?GT1q_3{wu~M zcge!d5a6sAbee2~(<4sti%0K$6o~d_N-r8K(bFN$N*CbjOhdD!AeDv#LZjM7SHYgo zS&+Jdrd`RknHaBUyN%Yq1`;I61z&#blZLkjTt(8&$+vroyXwkdDP0iX07RWL-29^7 z^T_=jnsm?3&JGvqXX4X3AsVGGAn_zaL)5*y&afxMt=z@z)X`uV`V4`CZ1)64%UFP^P z1G`tvamrY-+1*HtdbzkFaq5VakcM*LK)e#~x(Ls75b)Xv!*%#H*l+=@U3XAZn$ygi z1jAyJt6mOLTy1P}iwN;=+pvVC$+g#u`F&O8#<2o~ zpL0I1Y4=U1n%=6_8-_csq(Km?&A%M8>2DVz*kN2^YFMa&S^a6_WR)zyXs+)?$h~w$ zMUP`0(*nPXG|9S9Li;sZW)p!3(M>n#zds1yR=M!rgY-TZq1$DXRf2=SjK7)!t4>KH zRoXfF)$w0wjV67qAjf(0TLe^qPF0dzqdpI0z zisU!BSf3PoUe6=Hb~`R1w7z$k8KdkR_G4QuPlk}IIqEoPBSELMyDyYLGLv6Ub1QVF z{;E1x?@xZ*ucytT8OeT9@8{y|TZe1Wb`-{$Xl?~XEuo#*>q?D}bO#HhVe($oA~k%l zdXyY-=#zzTmiB*908(B>`6rA5u1uY8?5ji=6AKm^kT0>R0120t5uM@|MkN6O?Czta zVr<}hgX_$|U3%YxN$A&@etM?E>rV>qL0|a#(-K2vbyPDmVjl0=K!nYOwBA3?KG2GsY-Xc#G@mF5)vf9UH;5|xQ#d2&GX_Ko zn$^-;mRzyN+TwR$tJXu*7`XTZ`y`Ug?lT zBsfZMP?6<#1sfrsMqg!>I(SX z{9CT5wSzNO8|O(pSG%-#lO0vML>BU!&z>(&(>(*QW&w!IG@es7OjB^2BhE&bJTh`M znhE0=;IYTXu8yTtr0cSmF;Mm%hRJwzNb`M>Y#I^u?7z279x|!|r*Ms}nr?`#K=1a$ z>G#ryd_`t|j<|)xUQq83_iCI4JrrG=KOZ@x9!PuB)~`!VRXk#03wFQZyxtN$UER@T zIev^V`JSI=;%ij<8>^TXH}vFk2`tTIR}2Oa^*r?{pl4I&V~Xgg9vDhh^U2|A$zaKJysUiH`gbD51AqhdsbtP0boUK7u-{`hYKHmbj6o-jX@x-Yf*Q#M`kuF zSDKTF3wACo%ar)u7kKw`?UQ-}w#+9F8(~B}SWYJJ=w1_R87kZpEkuBh&ridTi zuP^_#zsG&k$fhy>>4D!$0a3Ye)vL{fJbarh3RR_0%pb>E;ow(~!KK=D`=<GD?BkuAJ#Ws6IMQ#Yj@%BW)_qe?T}d@4J`O_d?HbPfnGP+4(J@tniYd7 zhTR;3%x8L@H>ujzMQPc6&vcN+1fA=V8RW6d_;?nlMXc3=PG z@qVc-qNTJE&kk-+@6sDF`7TUllC=?|%u!~9P#+rQ1hS*Ymzd9h|SVy1{Q-Xocp zYagSIC&C$fvcb7z6^)uP>gi5xrQzu7d?@j4CC)J)M#q89mf8hBPB`$s8R@5ifuhm+ zkJlN5&l3I+eV?LVyoT5?cDA_VYioF)M8-1Nd;I$7QtUGrx@@A2k$Ag4IpKu3$T_gf z)7?qlb9@p7sASB+-qhX0Cn9ZX)rVatvYcg53=w;A!( z(L^nldPt=Gv>#-O%kPY#V;$vgIVTGO@S40YyeF_95*%z$Z=1a;@d_i@TZSk6`ZX3fqseq=B=}8iCt%XL}Nedme+wxBd7QVPZB3+lOKf(f( zIH%BS*q}K%F`oLOMk=ETb+xbfKAAfRfqi(7l!+jyWE;_6@m?ViK7gjR>h5%^x z-ncSi3_ix1)$?quwtqc|{^MW}p>u7?MWn(~j&(aEmidNHK5=3tMRcDZMZTCcha);oK zuvrjlMJvUwFIM4PeoiAY;tZ~qLJ#~yHO?O*fAh}`tqT=Np$CWY$ZF={#zM_k<7Ymf zkl8;1LA=5ANx`-&62HT4i@v@IN)vwT9(Pla*IrtIeR$UNhstz@CNIL8_4>5Y@~;2t zbmFCbppR?$<&kV67UTtAqPU&9Oazrvx91*wAw;IH zT(FiqW-Rsm759|7^&ELtLMqlipEcR&(+Eu9CR1pcnJr=-E_cBzH3@hBr~t)Om>oW# z;vaHMt3${Ci1mq07vZnrPd~aG6O4+!-k*+Wc#t-?x=houTt0s|=5=@~!c=D-2J3`c z7w&r$jxh)h5NOXO{c zcf04K47XV#!u!sP6TK9VqQ$S6~<+n(r?+nnM4Y6(e4Oe!)su=IE5SP97P z)1BEE<*PC!Byw|2-5rSG18QFm)@5BO4oO9>2#J;~5@)z|x-hsbEe#GI7gZiy6LSjR zKeZ+OyPe?5Y~d-}BsT3+Z%|gfYy@^^tmhxrJ87G6ow8sOdcz6-p1~b0Y|6Nfjr*qn>#{_hQWxU_%Rs+fQqP zgZQY=+m9t(FQc3GJ*a(OH(vRiPeMcb=RaxPxlk;eQ8OQ|^#@u!4f@j7B&ad?DDsvD z*y^&sW5i3oo7(2>bNNZc|KL zeJNUl`uz=~y74?>nXqarq48J$rZtr@coTHESXcQZY2ecn4~#i#`oREx`BZ_FNK_?v zYObr9w1khtdYjh4Mr}Fm3*x4E!0WBUZ+&78tL@eDp2OrJGv!U3NHWeFb7O6r*8>an zv161hs>T>tiW@op+vaVa4>l>ro#sTFhBW@o?kUvq?H(7;7?0>9X$Z3)uD@Yr8hF$5 zv-54NvnV0bB?#=bw^!(vC+UPkdTS6Zsd11dV z*NA^nqd*L`F)4(Z8ktK^mQS5&R+l`WhpVv)^cfPEuxcN7o78Y4_fh=F2U44h#cr`1 zk|p>qT@H#XG9?OE22u5nO{l6$Y*NB?9cspa5WuOcBYsKuJ&J;Yn6eZ`QeO;z$R4Yx z6toFGvZ;Lh0;&$Y2`8!rvDc9GL#gk4Egy77G_1vTe!!l5iZA(*xeOeMrDgw^0Pq_L ze@_$Eskx@`hgV+nKz{y(dXu~pBh?6`$8P`D^a3b%TtkTLKU7Z#)gS0$Y@MbRvw_ba zzlp!>^c1hot8C(oTV<|w4X+uNrV|yV*>9WOd`_rnb`k?i{uKIV_qLFTRBPs zNrDw6&g}=Ti~zxg6C*_p%;;0U?(ePb#G50&ZziIf(0U*z=68LCD1&!nMN8?qG!#^a zzhOab{WBc54Bi|5`)KKA<&x;KvV|wGT&oo+jSYAV$>}%{^EGgmIK=2=bMO(FQ*;li zhr=`}h^bmlmR4G+BkgWU*E+u7oj}~W=T|1383WWQ>ot;ld46lG8R(k!TAopU-8bd_ z6C@))5OxD2TPH2`W53@$=RM@HF79<5IT!wo+h07aqL{u`lkNqu$V3#(G|iVt9ljIod+s)t4cfBvAKJ@ zm28~D3Oul4xxYfTzQJohNII!j#1XiI*c2jnDb4{(fFOYfQlY*kC?U4I^HZ{5$D>fe zD8N!N2rZS35R zOA&RxP4#H0K=Kwe^|8Z5l=JXp;SDz^;et|UKP7J2lFGq%{9+s|Rp>$yauYt|*# z7GD5*<95rBYT5O&g+iH3xtP<6`Xqcei`K6Wb~Yx-@+IpTy25dx`h8c<^ks3i7o!6_$z1EVlQJO^}^TRC)YusDinqcd<1^6){vz+rD#-=n*WSw`EwXf~TeAdC$ zh#dFm+IcT0isqY06G|rD)}chGx1WxnFe`%fo)85`ZgO_*Lh>s^Soky2@;l)-5<9Z(OZ*F7rHleP0Evb zMnG!0==X*s6g5ClfZY#!B63ZIjTTOZvdOL_9YF`%3z&Bq0QF?YYP;-Qs3Yvj6&prz zz_WPd>zy-tnf(@S=t@ZFtyg-|?zRzFZ~dv3ZsmoChAg0753?U*c1=IBm}yfAni1XC zkd@-WuYua~ci7k5kWmVA8m7cVy0zUT&jDQ%YG@QaoPhH5RO;^>exLrA=6tE9ty-^Q6aD`H1njsF diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index 5ed5faa5f..9ee1f786d 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -1.1.10 +1.1.11 diff --git a/backend/cmd/server/wire.go b/backend/cmd/server/wire.go index f279b354c..47034cf2f 100644 --- a/backend/cmd/server/wire.go +++ b/backend/cmd/server/wire.go @@ -104,6 +104,7 @@ func provideCleanup( subscriptionExpiry *service.SubscriptionExpiryService, usageCleanup *service.UsageCleanupService, idempotencyCleanup *service.IdempotencyCleanupService, + geminiCachedContent *service.GeminiCachedContentService, batchImageCleanup *service.BatchImageCleanupService, batchImageWorker *service.BatchImageWorkerRuntime, pricing *service.PricingService, @@ -244,6 +245,12 @@ func provideCleanup( } return nil }}, + {"GeminiCachedContentService", func() error { + if geminiCachedContent != nil { + geminiCachedContent.Stop() + } + return nil + }}, {"BatchImageCleanupService", func() error { if batchImageCleanup != nil { batchImageCleanup.Stop() diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 71dc8aa65..e03eb7170 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -297,7 +297,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { userMessageQueueService := service.ProvideUserMessageQueueService(userMsgQueueCache, rpmCache, configConfig) legacyEngine := securityaudit.NewLegacyModerationAdapter(contentModerationService) coordinator := securityaudit.NewCoordinator(legacyEngine, promptService) - gatewayHandler := handler.ProvideGatewayHandler(gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, userMessageQueueService, configConfig, settingService, coordinator) + geminiCachedContentRepository := repository.NewGeminiCachedContentRepository(db) + geminiCachedContentService := service.ProvideGeminiCachedContentService(geminiCachedContentRepository, geminiMessagesCompatService, configConfig) + gatewayHandler := handler.ProvideGatewayHandler(gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, userMessageQueueService, configConfig, settingService, coordinator, geminiCachedContentService) openAIGatewayHandler := handler.ProvideOpenAIGatewayHandler(openAIGatewayService, pluginManager, concurrencyService, billingCacheService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, opsService, grokQuotaService, configConfig, coordinator, compositeRouteResolver) handlerSettingHandler := handler.ProvideSettingHandler(settingService, buildInfo, notificationEmailService) totpHandler := handler.NewTotpHandler(totpService) @@ -354,7 +356,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService, channelMonitorQuotaFetcher) channelMonitorV2Aggregator := service.ProvideChannelMonitorV2Aggregator(channelMonitorV2Repository, db, settingService) userPlatformQuotaUsageFlusher := service.ProvideUserPlatformQuotaUsageFlusher(configConfig, billingCache, serviceUserPlatformQuotaRepository, timingWheelService) - v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager) + v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager) application := &Application{ Server: httpServer, PromptAudit: promptService, @@ -414,6 +416,7 @@ func provideCleanup( subscriptionExpiry *service.SubscriptionExpiryService, usageCleanup *service.UsageCleanupService, idempotencyCleanup *service.IdempotencyCleanupService, + geminiCachedContent *service.GeminiCachedContentService, batchImageCleanup *service.BatchImageCleanupService, batchImageWorker *service.BatchImageWorkerRuntime, pricing *service.PricingService, @@ -553,6 +556,12 @@ func provideCleanup( } return nil }}, + {"GeminiCachedContentService", func() error { + if geminiCachedContent != nil { + geminiCachedContent.Stop() + } + return nil + }}, {"BatchImageCleanupService", func() error { if batchImageCleanup != nil { batchImageCleanup.Stop() diff --git a/backend/cmd/server/wire_gen_test.go b/backend/cmd/server/wire_gen_test.go index 384aebf68..4f083e795 100644 --- a/backend/cmd/server/wire_gen_test.go +++ b/backend/cmd/server/wire_gen_test.go @@ -74,6 +74,7 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) { subscriptionExpirySvc, &service.UsageCleanupService{}, idempotencyCleanupSvc, + service.NewGeminiCachedContentService(nil, nil, cfg), &service.BatchImageCleanupService{}, nil, // batchImageWorker pricingSvc, diff --git a/backend/ent/group.go b/backend/ent/group.go index b8aa08709..c602202bf 100644 --- a/backend/ent/group.go +++ b/backend/ent/group.go @@ -30,6 +30,8 @@ type Group struct { Name string `json:"name,omitempty"` // Description holds the value of the "description" field. Description *string `json:"description,omitempty"` + // 名称与描述的界面语言译文:语言代码 -> {name, description};缺失的语言沿用 name/description + I18n domain.GroupI18n `json:"i18n,omitempty"` // RateMultiplier holds the value of the "rate_multiplier" field. RateMultiplier float64 `json:"rate_multiplier,omitempty"` // 是否启用高峰时段倍率 @@ -258,7 +260,7 @@ func (*Group) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { - case group.FieldVideoModelPrices, group.FieldModelPricing, group.FieldModelRouting, group.FieldSupportedModelScopes, group.FieldMessagesDispatchModelConfig, group.FieldModelAllowlist, group.FieldCodexModelsManifestConfig, group.FieldReasoningEffortMappings: + case group.FieldI18n, group.FieldVideoModelPrices, group.FieldModelPricing, group.FieldModelRouting, group.FieldSupportedModelScopes, group.FieldMessagesDispatchModelConfig, group.FieldModelAllowlist, group.FieldCodexModelsManifestConfig, group.FieldReasoningEffortMappings: values[i] = new([]byte) case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldAllowBatchImageGeneration, group.FieldImageRateIndependent, group.FieldVideoRateIndependent, group.FieldLongContextPricingEnabled, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldAllowLive, group.FieldForceOpenaiFast, group.FieldFreeOpenaiFast, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet, group.FieldProfitControlEnabled: values[i] = new(sql.NullBool) @@ -323,6 +325,14 @@ func (_m *Group) assignValues(columns []string, values []any) error { _m.Description = new(string) *_m.Description = value.String } + case group.FieldI18n: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field i18n", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.I18n); err != nil { + return fmt.Errorf("unmarshal field i18n: %w", err) + } + } case group.FieldRateMultiplier: if value, ok := values[i].(*sql.NullFloat64); !ok { return fmt.Errorf("unexpected type %T for field rate_multiplier", values[i]) @@ -817,6 +827,9 @@ func (_m *Group) String() string { builder.WriteString(*v) } builder.WriteString(", ") + builder.WriteString("i18n=") + builder.WriteString(fmt.Sprintf("%v", _m.I18n)) + builder.WriteString(", ") builder.WriteString("rate_multiplier=") builder.WriteString(fmt.Sprintf("%v", _m.RateMultiplier)) builder.WriteString(", ") diff --git a/backend/ent/group/group.go b/backend/ent/group/group.go index e978df85c..182636bfa 100644 --- a/backend/ent/group/group.go +++ b/backend/ent/group/group.go @@ -26,6 +26,8 @@ const ( FieldName = "name" // FieldDescription holds the string denoting the description field in the database. FieldDescription = "description" + // FieldI18n holds the string denoting the i18n field in the database. + FieldI18n = "i18n" // FieldRateMultiplier holds the string denoting the rate_multiplier field in the database. FieldRateMultiplier = "rate_multiplier" // FieldPeakRateEnabled holds the string denoting the peak_rate_enabled field in the database. @@ -228,6 +230,7 @@ var Columns = []string{ FieldDeletedAt, FieldName, FieldDescription, + FieldI18n, FieldRateMultiplier, FieldPeakRateEnabled, FieldPeakStart, @@ -326,6 +329,8 @@ var ( UpdateDefaultUpdatedAt func() time.Time // NameValidator is a validator for the "name" field. It is called by the builders before save. NameValidator func(string) error + // DefaultI18n holds the default value on creation for the "i18n" field. + DefaultI18n domain.GroupI18n // DefaultRateMultiplier holds the default value on creation for the "rate_multiplier" field. DefaultRateMultiplier float64 // DefaultPeakRateEnabled holds the default value on creation for the "peak_rate_enabled" field. diff --git a/backend/ent/group_create.go b/backend/ent/group_create.go index 940577850..42b33cab7 100644 --- a/backend/ent/group_create.go +++ b/backend/ent/group_create.go @@ -92,6 +92,12 @@ func (_c *GroupCreate) SetNillableDescription(v *string) *GroupCreate { return _c } +// SetI18n sets the "i18n" field. +func (_c *GroupCreate) SetI18n(v domain.GroupI18n) *GroupCreate { + _c.mutation.SetI18n(v) + return _c +} + // SetRateMultiplier sets the "rate_multiplier" field. func (_c *GroupCreate) SetRateMultiplier(v float64) *GroupCreate { _c.mutation.SetRateMultiplier(v) @@ -1047,6 +1053,10 @@ func (_c *GroupCreate) defaults() error { v := group.DefaultUpdatedAt() _c.mutation.SetUpdatedAt(v) } + if _, ok := _c.mutation.I18n(); !ok { + v := group.DefaultI18n + _c.mutation.SetI18n(v) + } if _, ok := _c.mutation.RateMultiplier(); !ok { v := group.DefaultRateMultiplier _c.mutation.SetRateMultiplier(v) @@ -1230,6 +1240,9 @@ func (_c *GroupCreate) check() error { return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Group.name": %w`, err)} } } + if _, ok := _c.mutation.I18n(); !ok { + return &ValidationError{Name: "i18n", err: errors.New(`ent: missing required field "Group.i18n"`)} + } if _, ok := _c.mutation.RateMultiplier(); !ok { return &ValidationError{Name: "rate_multiplier", err: errors.New(`ent: missing required field "Group.rate_multiplier"`)} } @@ -1465,6 +1478,10 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) { _spec.SetField(group.FieldDescription, field.TypeString, value) _node.Description = &value } + if value, ok := _c.mutation.I18n(); ok { + _spec.SetField(group.FieldI18n, field.TypeJSON, value) + _node.I18n = value + } if value, ok := _c.mutation.RateMultiplier(); ok { _spec.SetField(group.FieldRateMultiplier, field.TypeFloat64, value) _node.RateMultiplier = value @@ -1925,6 +1942,18 @@ func (u *GroupUpsert) ClearDescription() *GroupUpsert { return u } +// SetI18n sets the "i18n" field. +func (u *GroupUpsert) SetI18n(v domain.GroupI18n) *GroupUpsert { + u.Set(group.FieldI18n, v) + return u +} + +// UpdateI18n sets the "i18n" field to the value that was provided on create. +func (u *GroupUpsert) UpdateI18n() *GroupUpsert { + u.SetExcluded(group.FieldI18n) + return u +} + // SetRateMultiplier sets the "rate_multiplier" field. func (u *GroupUpsert) SetRateMultiplier(v float64) *GroupUpsert { u.Set(group.FieldRateMultiplier, v) @@ -3039,6 +3068,20 @@ func (u *GroupUpsertOne) ClearDescription() *GroupUpsertOne { }) } +// SetI18n sets the "i18n" field. +func (u *GroupUpsertOne) SetI18n(v domain.GroupI18n) *GroupUpsertOne { + return u.Update(func(s *GroupUpsert) { + s.SetI18n(v) + }) +} + +// UpdateI18n sets the "i18n" field to the value that was provided on create. +func (u *GroupUpsertOne) UpdateI18n() *GroupUpsertOne { + return u.Update(func(s *GroupUpsert) { + s.UpdateI18n() + }) +} + // SetRateMultiplier sets the "rate_multiplier" field. func (u *GroupUpsertOne) SetRateMultiplier(v float64) *GroupUpsertOne { return u.Update(func(s *GroupUpsert) { @@ -4485,6 +4528,20 @@ func (u *GroupUpsertBulk) ClearDescription() *GroupUpsertBulk { }) } +// SetI18n sets the "i18n" field. +func (u *GroupUpsertBulk) SetI18n(v domain.GroupI18n) *GroupUpsertBulk { + return u.Update(func(s *GroupUpsert) { + s.SetI18n(v) + }) +} + +// UpdateI18n sets the "i18n" field to the value that was provided on create. +func (u *GroupUpsertBulk) UpdateI18n() *GroupUpsertBulk { + return u.Update(func(s *GroupUpsert) { + s.UpdateI18n() + }) +} + // SetRateMultiplier sets the "rate_multiplier" field. func (u *GroupUpsertBulk) SetRateMultiplier(v float64) *GroupUpsertBulk { return u.Update(func(s *GroupUpsert) { diff --git a/backend/ent/group_update.go b/backend/ent/group_update.go index 29c04ecb0..c3bd82c35 100644 --- a/backend/ent/group_update.go +++ b/backend/ent/group_update.go @@ -97,6 +97,12 @@ func (_u *GroupUpdate) ClearDescription() *GroupUpdate { return _u } +// SetI18n sets the "i18n" field. +func (_u *GroupUpdate) SetI18n(v domain.GroupI18n) *GroupUpdate { + _u.mutation.SetI18n(v) + return _u +} + // SetRateMultiplier sets the "rate_multiplier" field. func (_u *GroupUpdate) SetRateMultiplier(v float64) *GroupUpdate { _u.mutation.ResetRateMultiplier() @@ -1581,6 +1587,9 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) { if _u.mutation.DescriptionCleared() { _spec.ClearField(group.FieldDescription, field.TypeString) } + if value, ok := _u.mutation.I18n(); ok { + _spec.SetField(group.FieldI18n, field.TypeJSON, value) + } if value, ok := _u.mutation.RateMultiplier(); ok { _spec.SetField(group.FieldRateMultiplier, field.TypeFloat64, value) } @@ -2291,6 +2300,12 @@ func (_u *GroupUpdateOne) ClearDescription() *GroupUpdateOne { return _u } +// SetI18n sets the "i18n" field. +func (_u *GroupUpdateOne) SetI18n(v domain.GroupI18n) *GroupUpdateOne { + _u.mutation.SetI18n(v) + return _u +} + // SetRateMultiplier sets the "rate_multiplier" field. func (_u *GroupUpdateOne) SetRateMultiplier(v float64) *GroupUpdateOne { _u.mutation.ResetRateMultiplier() @@ -3805,6 +3820,9 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error) if _u.mutation.DescriptionCleared() { _spec.ClearField(group.FieldDescription, field.TypeString) } + if value, ok := _u.mutation.I18n(); ok { + _spec.SetField(group.FieldI18n, field.TypeJSON, value) + } if value, ok := _u.mutation.RateMultiplier(); ok { _spec.SetField(group.FieldRateMultiplier, field.TypeFloat64, value) } diff --git a/backend/ent/migrate/schema.go b/backend/ent/migrate/schema.go index 88292b633..adfa072b0 100644 --- a/backend/ent/migrate/schema.go +++ b/backend/ent/migrate/schema.go @@ -908,6 +908,7 @@ var ( {Name: "deleted_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}}, {Name: "name", Type: field.TypeString, Size: 100}, {Name: "description", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "text"}}, + {Name: "i18n", Type: field.TypeJSON, SchemaType: map[string]string{"postgres": "jsonb"}}, {Name: "rate_multiplier", Type: field.TypeFloat64, Default: 1, SchemaType: map[string]string{"postgres": "decimal(10,4)"}}, {Name: "peak_rate_enabled", Type: field.TypeBool, Default: false}, {Name: "peak_start", Type: field.TypeString, Size: 5, Default: ""}, @@ -979,22 +980,22 @@ var ( { Name: "group_status", Unique: false, - Columns: []*schema.Column{GroupsColumns[12]}, + Columns: []*schema.Column{GroupsColumns[13]}, }, { Name: "group_platform", Unique: false, - Columns: []*schema.Column{GroupsColumns[14]}, + Columns: []*schema.Column{GroupsColumns[15]}, }, { Name: "group_subscription_type", Unique: false, - Columns: []*schema.Column{GroupsColumns[15]}, + Columns: []*schema.Column{GroupsColumns[16]}, }, { Name: "group_is_exclusive", Unique: false, - Columns: []*schema.Column{GroupsColumns[11]}, + Columns: []*schema.Column{GroupsColumns[12]}, }, { Name: "group_deleted_at", @@ -1004,12 +1005,12 @@ var ( { Name: "group_sort_order", Unique: false, - Columns: []*schema.Column{GroupsColumns[49]}, + Columns: []*schema.Column{GroupsColumns[50]}, }, { Name: "idx_groups_duplicate_operation_id_active", Unique: true, - Columns: []*schema.Column{GroupsColumns[13]}, + Columns: []*schema.Column{GroupsColumns[14]}, Annotation: &entsql.IndexAnnotation{ Where: "duplicate_operation_id IS NOT NULL AND deleted_at IS NULL", }, diff --git a/backend/ent/mutation.go b/backend/ent/mutation.go index affee9d37..c6033a53d 100644 --- a/backend/ent/mutation.go +++ b/backend/ent/mutation.go @@ -22086,6 +22086,7 @@ type GroupMutation struct { deleted_at *time.Time name *string description *string + i18n *domain.GroupI18n rate_multiplier *float64 addrate_multiplier *float64 peak_rate_enabled *bool @@ -22505,6 +22506,42 @@ func (m *GroupMutation) ResetDescription() { delete(m.clearedFields, group.FieldDescription) } +// SetI18n sets the "i18n" field. +func (m *GroupMutation) SetI18n(di domain.GroupI18n) { + m.i18n = &di +} + +// I18n returns the value of the "i18n" field in the mutation. +func (m *GroupMutation) I18n() (r domain.GroupI18n, exists bool) { + v := m.i18n + if v == nil { + return + } + return *v, true +} + +// OldI18n returns the old "i18n" field's value of the Group entity. +// If the Group object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *GroupMutation) OldI18n(ctx context.Context) (v domain.GroupI18n, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldI18n is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldI18n requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldI18n: %w", err) + } + return oldValue.I18n, nil +} + +// ResetI18n resets all changes to the "i18n" field. +func (m *GroupMutation) ResetI18n() { + m.i18n = nil +} + // SetRateMultiplier sets the "rate_multiplier" field. func (m *GroupMutation) SetRateMultiplier(f float64) { m.rate_multiplier = &f @@ -25921,7 +25958,7 @@ func (m *GroupMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *GroupMutation) Fields() []string { - fields := make([]string, 0, 66) + fields := make([]string, 0, 67) if m.created_at != nil { fields = append(fields, group.FieldCreatedAt) } @@ -25937,6 +25974,9 @@ func (m *GroupMutation) Fields() []string { if m.description != nil { fields = append(fields, group.FieldDescription) } + if m.i18n != nil { + fields = append(fields, group.FieldI18n) + } if m.rate_multiplier != nil { fields = append(fields, group.FieldRateMultiplier) } @@ -26138,6 +26178,8 @@ func (m *GroupMutation) Field(name string) (ent.Value, bool) { return m.Name() case group.FieldDescription: return m.Description() + case group.FieldI18n: + return m.I18n() case group.FieldRateMultiplier: return m.RateMultiplier() case group.FieldPeakRateEnabled: @@ -26279,6 +26321,8 @@ func (m *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, e return m.OldName(ctx) case group.FieldDescription: return m.OldDescription(ctx) + case group.FieldI18n: + return m.OldI18n(ctx) case group.FieldRateMultiplier: return m.OldRateMultiplier(ctx) case group.FieldPeakRateEnabled: @@ -26445,6 +26489,13 @@ func (m *GroupMutation) SetField(name string, value ent.Value) error { } m.SetDescription(v) return nil + case group.FieldI18n: + v, ok := value.(domain.GroupI18n) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetI18n(v) + return nil case group.FieldRateMultiplier: v, ok := value.(float64) if !ok { @@ -27398,6 +27449,9 @@ func (m *GroupMutation) ResetField(name string) error { case group.FieldDescription: m.ResetDescription() return nil + case group.FieldI18n: + m.ResetI18n() + return nil case group.FieldRateMultiplier: m.ResetRateMultiplier() return nil diff --git a/backend/ent/runtime/runtime.go b/backend/ent/runtime/runtime.go index 60de682b3..8d7fb46b2 100644 --- a/backend/ent/runtime/runtime.go +++ b/backend/ent/runtime/runtime.go @@ -1037,204 +1037,208 @@ func init() { return nil } }() + // groupDescI18n is the schema descriptor for i18n field. + groupDescI18n := groupFields[2].Descriptor() + // group.DefaultI18n holds the default value on creation for the i18n field. + group.DefaultI18n = groupDescI18n.Default.(domain.GroupI18n) // groupDescRateMultiplier is the schema descriptor for rate_multiplier field. - groupDescRateMultiplier := groupFields[2].Descriptor() + groupDescRateMultiplier := groupFields[3].Descriptor() // group.DefaultRateMultiplier holds the default value on creation for the rate_multiplier field. group.DefaultRateMultiplier = groupDescRateMultiplier.Default.(float64) // groupDescPeakRateEnabled is the schema descriptor for peak_rate_enabled field. - groupDescPeakRateEnabled := groupFields[3].Descriptor() + groupDescPeakRateEnabled := groupFields[4].Descriptor() // group.DefaultPeakRateEnabled holds the default value on creation for the peak_rate_enabled field. group.DefaultPeakRateEnabled = groupDescPeakRateEnabled.Default.(bool) // groupDescPeakStart is the schema descriptor for peak_start field. - groupDescPeakStart := groupFields[4].Descriptor() + groupDescPeakStart := groupFields[5].Descriptor() // group.DefaultPeakStart holds the default value on creation for the peak_start field. group.DefaultPeakStart = groupDescPeakStart.Default.(string) // group.PeakStartValidator is a validator for the "peak_start" field. It is called by the builders before save. group.PeakStartValidator = groupDescPeakStart.Validators[0].(func(string) error) // groupDescPeakEnd is the schema descriptor for peak_end field. - groupDescPeakEnd := groupFields[5].Descriptor() + groupDescPeakEnd := groupFields[6].Descriptor() // group.DefaultPeakEnd holds the default value on creation for the peak_end field. group.DefaultPeakEnd = groupDescPeakEnd.Default.(string) // group.PeakEndValidator is a validator for the "peak_end" field. It is called by the builders before save. group.PeakEndValidator = groupDescPeakEnd.Validators[0].(func(string) error) // groupDescPeakRateMultiplier is the schema descriptor for peak_rate_multiplier field. - groupDescPeakRateMultiplier := groupFields[6].Descriptor() + groupDescPeakRateMultiplier := groupFields[7].Descriptor() // group.DefaultPeakRateMultiplier holds the default value on creation for the peak_rate_multiplier field. group.DefaultPeakRateMultiplier = groupDescPeakRateMultiplier.Default.(float64) // groupDescIsExclusive is the schema descriptor for is_exclusive field. - groupDescIsExclusive := groupFields[7].Descriptor() + groupDescIsExclusive := groupFields[8].Descriptor() // group.DefaultIsExclusive holds the default value on creation for the is_exclusive field. group.DefaultIsExclusive = groupDescIsExclusive.Default.(bool) // groupDescStatus is the schema descriptor for status field. - groupDescStatus := groupFields[8].Descriptor() + groupDescStatus := groupFields[9].Descriptor() // group.DefaultStatus holds the default value on creation for the status field. group.DefaultStatus = groupDescStatus.Default.(string) // group.StatusValidator is a validator for the "status" field. It is called by the builders before save. group.StatusValidator = groupDescStatus.Validators[0].(func(string) error) // groupDescDuplicateOperationID is the schema descriptor for duplicate_operation_id field. - groupDescDuplicateOperationID := groupFields[9].Descriptor() + groupDescDuplicateOperationID := groupFields[10].Descriptor() // group.DuplicateOperationIDValidator is a validator for the "duplicate_operation_id" field. It is called by the builders before save. group.DuplicateOperationIDValidator = groupDescDuplicateOperationID.Validators[0].(func(string) error) // groupDescPlatform is the schema descriptor for platform field. - groupDescPlatform := groupFields[10].Descriptor() + groupDescPlatform := groupFields[11].Descriptor() // group.DefaultPlatform holds the default value on creation for the platform field. group.DefaultPlatform = groupDescPlatform.Default.(string) // group.PlatformValidator is a validator for the "platform" field. It is called by the builders before save. group.PlatformValidator = groupDescPlatform.Validators[0].(func(string) error) // groupDescSubscriptionType is the schema descriptor for subscription_type field. - groupDescSubscriptionType := groupFields[11].Descriptor() + groupDescSubscriptionType := groupFields[12].Descriptor() // group.DefaultSubscriptionType holds the default value on creation for the subscription_type field. group.DefaultSubscriptionType = groupDescSubscriptionType.Default.(string) // group.SubscriptionTypeValidator is a validator for the "subscription_type" field. It is called by the builders before save. group.SubscriptionTypeValidator = groupDescSubscriptionType.Validators[0].(func(string) error) // groupDescDefaultValidityDays is the schema descriptor for default_validity_days field. - groupDescDefaultValidityDays := groupFields[15].Descriptor() + groupDescDefaultValidityDays := groupFields[16].Descriptor() // group.DefaultDefaultValidityDays holds the default value on creation for the default_validity_days field. group.DefaultDefaultValidityDays = groupDescDefaultValidityDays.Default.(int) // groupDescAllowImageGeneration is the schema descriptor for allow_image_generation field. - groupDescAllowImageGeneration := groupFields[16].Descriptor() + groupDescAllowImageGeneration := groupFields[17].Descriptor() // group.DefaultAllowImageGeneration holds the default value on creation for the allow_image_generation field. group.DefaultAllowImageGeneration = groupDescAllowImageGeneration.Default.(bool) // groupDescAllowBatchImageGeneration is the schema descriptor for allow_batch_image_generation field. - groupDescAllowBatchImageGeneration := groupFields[17].Descriptor() + groupDescAllowBatchImageGeneration := groupFields[18].Descriptor() // group.DefaultAllowBatchImageGeneration holds the default value on creation for the allow_batch_image_generation field. group.DefaultAllowBatchImageGeneration = groupDescAllowBatchImageGeneration.Default.(bool) // groupDescImageRateIndependent is the schema descriptor for image_rate_independent field. - groupDescImageRateIndependent := groupFields[18].Descriptor() + groupDescImageRateIndependent := groupFields[19].Descriptor() // group.DefaultImageRateIndependent holds the default value on creation for the image_rate_independent field. group.DefaultImageRateIndependent = groupDescImageRateIndependent.Default.(bool) // groupDescImageRateMultiplier is the schema descriptor for image_rate_multiplier field. - groupDescImageRateMultiplier := groupFields[19].Descriptor() + groupDescImageRateMultiplier := groupFields[20].Descriptor() // group.DefaultImageRateMultiplier holds the default value on creation for the image_rate_multiplier field. group.DefaultImageRateMultiplier = groupDescImageRateMultiplier.Default.(float64) // groupDescBatchImageDiscountMultiplier is the schema descriptor for batch_image_discount_multiplier field. - groupDescBatchImageDiscountMultiplier := groupFields[23].Descriptor() + groupDescBatchImageDiscountMultiplier := groupFields[24].Descriptor() // group.DefaultBatchImageDiscountMultiplier holds the default value on creation for the batch_image_discount_multiplier field. group.DefaultBatchImageDiscountMultiplier = groupDescBatchImageDiscountMultiplier.Default.(float64) // groupDescBatchImageHoldMultiplier is the schema descriptor for batch_image_hold_multiplier field. - groupDescBatchImageHoldMultiplier := groupFields[24].Descriptor() + groupDescBatchImageHoldMultiplier := groupFields[25].Descriptor() // group.DefaultBatchImageHoldMultiplier holds the default value on creation for the batch_image_hold_multiplier field. group.DefaultBatchImageHoldMultiplier = groupDescBatchImageHoldMultiplier.Default.(float64) // groupDescVideoRateIndependent is the schema descriptor for video_rate_independent field. - groupDescVideoRateIndependent := groupFields[25].Descriptor() + groupDescVideoRateIndependent := groupFields[26].Descriptor() // group.DefaultVideoRateIndependent holds the default value on creation for the video_rate_independent field. group.DefaultVideoRateIndependent = groupDescVideoRateIndependent.Default.(bool) // groupDescVideoRateMultiplier is the schema descriptor for video_rate_multiplier field. - groupDescVideoRateMultiplier := groupFields[26].Descriptor() + groupDescVideoRateMultiplier := groupFields[27].Descriptor() // group.DefaultVideoRateMultiplier holds the default value on creation for the video_rate_multiplier field. group.DefaultVideoRateMultiplier = groupDescVideoRateMultiplier.Default.(float64) // groupDescSearchPricePer1k is the schema descriptor for search_price_per_1k field. - groupDescSearchPricePer1k := groupFields[32].Descriptor() + groupDescSearchPricePer1k := groupFields[33].Descriptor() // group.SearchPricePer1kValidator is a validator for the "search_price_per_1k" field. It is called by the builders before save. group.SearchPricePer1kValidator = groupDescSearchPricePer1k.Validators[0].(func(float64) error) // groupDescAudioRealtimePricePerMin is the schema descriptor for audio_realtime_price_per_min field. - groupDescAudioRealtimePricePerMin := groupFields[33].Descriptor() + groupDescAudioRealtimePricePerMin := groupFields[34].Descriptor() // group.AudioRealtimePricePerMinValidator is a validator for the "audio_realtime_price_per_min" field. It is called by the builders before save. group.AudioRealtimePricePerMinValidator = groupDescAudioRealtimePricePerMin.Validators[0].(func(float64) error) // groupDescAudioTtsPricePerMillionChars is the schema descriptor for audio_tts_price_per_million_chars field. - groupDescAudioTtsPricePerMillionChars := groupFields[34].Descriptor() + groupDescAudioTtsPricePerMillionChars := groupFields[35].Descriptor() // group.AudioTtsPricePerMillionCharsValidator is a validator for the "audio_tts_price_per_million_chars" field. It is called by the builders before save. group.AudioTtsPricePerMillionCharsValidator = groupDescAudioTtsPricePerMillionChars.Validators[0].(func(float64) error) // groupDescAudioSttPricePerHour is the schema descriptor for audio_stt_price_per_hour field. - groupDescAudioSttPricePerHour := groupFields[35].Descriptor() + groupDescAudioSttPricePerHour := groupFields[36].Descriptor() // group.AudioSttPricePerHourValidator is a validator for the "audio_stt_price_per_hour" field. It is called by the builders before save. group.AudioSttPricePerHourValidator = groupDescAudioSttPricePerHour.Validators[0].(func(float64) error) // groupDescLongContextPricingEnabled is the schema descriptor for long_context_pricing_enabled field. - groupDescLongContextPricingEnabled := groupFields[36].Descriptor() + groupDescLongContextPricingEnabled := groupFields[37].Descriptor() // group.DefaultLongContextPricingEnabled holds the default value on creation for the long_context_pricing_enabled field. group.DefaultLongContextPricingEnabled = groupDescLongContextPricingEnabled.Default.(bool) // groupDescClaudeCodeOnly is the schema descriptor for claude_code_only field. - groupDescClaudeCodeOnly := groupFields[38].Descriptor() + groupDescClaudeCodeOnly := groupFields[39].Descriptor() // group.DefaultClaudeCodeOnly holds the default value on creation for the claude_code_only field. group.DefaultClaudeCodeOnly = groupDescClaudeCodeOnly.Default.(bool) // groupDescModelRoutingEnabled is the schema descriptor for model_routing_enabled field. - groupDescModelRoutingEnabled := groupFields[42].Descriptor() + groupDescModelRoutingEnabled := groupFields[43].Descriptor() // group.DefaultModelRoutingEnabled holds the default value on creation for the model_routing_enabled field. group.DefaultModelRoutingEnabled = groupDescModelRoutingEnabled.Default.(bool) // groupDescMcpXMLInject is the schema descriptor for mcp_xml_inject field. - groupDescMcpXMLInject := groupFields[43].Descriptor() + groupDescMcpXMLInject := groupFields[44].Descriptor() // group.DefaultMcpXMLInject holds the default value on creation for the mcp_xml_inject field. group.DefaultMcpXMLInject = groupDescMcpXMLInject.Default.(bool) // groupDescSupportedModelScopes is the schema descriptor for supported_model_scopes field. - groupDescSupportedModelScopes := groupFields[44].Descriptor() + groupDescSupportedModelScopes := groupFields[45].Descriptor() // group.DefaultSupportedModelScopes holds the default value on creation for the supported_model_scopes field. group.DefaultSupportedModelScopes = groupDescSupportedModelScopes.Default.([]string) // groupDescSortOrder is the schema descriptor for sort_order field. - groupDescSortOrder := groupFields[45].Descriptor() + groupDescSortOrder := groupFields[46].Descriptor() // group.DefaultSortOrder holds the default value on creation for the sort_order field. group.DefaultSortOrder = groupDescSortOrder.Default.(int) // groupDescAllowMessagesDispatch is the schema descriptor for allow_messages_dispatch field. - groupDescAllowMessagesDispatch := groupFields[46].Descriptor() + groupDescAllowMessagesDispatch := groupFields[47].Descriptor() // group.DefaultAllowMessagesDispatch holds the default value on creation for the allow_messages_dispatch field. group.DefaultAllowMessagesDispatch = groupDescAllowMessagesDispatch.Default.(bool) // groupDescAllowLive is the schema descriptor for allow_live field. - groupDescAllowLive := groupFields[47].Descriptor() + groupDescAllowLive := groupFields[48].Descriptor() // group.DefaultAllowLive holds the default value on creation for the allow_live field. group.DefaultAllowLive = groupDescAllowLive.Default.(bool) // groupDescForceOpenaiFast is the schema descriptor for force_openai_fast field. - groupDescForceOpenaiFast := groupFields[48].Descriptor() + groupDescForceOpenaiFast := groupFields[49].Descriptor() // group.DefaultForceOpenaiFast holds the default value on creation for the force_openai_fast field. group.DefaultForceOpenaiFast = groupDescForceOpenaiFast.Default.(bool) // groupDescFreeOpenaiFast is the schema descriptor for free_openai_fast field. - groupDescFreeOpenaiFast := groupFields[49].Descriptor() + groupDescFreeOpenaiFast := groupFields[50].Descriptor() // group.DefaultFreeOpenaiFast holds the default value on creation for the free_openai_fast field. group.DefaultFreeOpenaiFast = groupDescFreeOpenaiFast.Default.(bool) // groupDescRequireOauthOnly is the schema descriptor for require_oauth_only field. - groupDescRequireOauthOnly := groupFields[50].Descriptor() + groupDescRequireOauthOnly := groupFields[51].Descriptor() // group.DefaultRequireOauthOnly holds the default value on creation for the require_oauth_only field. group.DefaultRequireOauthOnly = groupDescRequireOauthOnly.Default.(bool) // groupDescRequirePrivacySet is the schema descriptor for require_privacy_set field. - groupDescRequirePrivacySet := groupFields[51].Descriptor() + groupDescRequirePrivacySet := groupFields[52].Descriptor() // group.DefaultRequirePrivacySet holds the default value on creation for the require_privacy_set field. group.DefaultRequirePrivacySet = groupDescRequirePrivacySet.Default.(bool) // groupDescDefaultMappedModel is the schema descriptor for default_mapped_model field. - groupDescDefaultMappedModel := groupFields[52].Descriptor() + groupDescDefaultMappedModel := groupFields[53].Descriptor() // group.DefaultDefaultMappedModel holds the default value on creation for the default_mapped_model field. group.DefaultDefaultMappedModel = groupDescDefaultMappedModel.Default.(string) // group.DefaultMappedModelValidator is a validator for the "default_mapped_model" field. It is called by the builders before save. group.DefaultMappedModelValidator = groupDescDefaultMappedModel.Validators[0].(func(string) error) // groupDescMessagesDispatchModelConfig is the schema descriptor for messages_dispatch_model_config field. - groupDescMessagesDispatchModelConfig := groupFields[53].Descriptor() + groupDescMessagesDispatchModelConfig := groupFields[54].Descriptor() // group.DefaultMessagesDispatchModelConfig holds the default value on creation for the messages_dispatch_model_config field. group.DefaultMessagesDispatchModelConfig = groupDescMessagesDispatchModelConfig.Default.(domain.OpenAIMessagesDispatchModelConfig) // groupDescModelAllowlist is the schema descriptor for model_allowlist field. - groupDescModelAllowlist := groupFields[54].Descriptor() + groupDescModelAllowlist := groupFields[55].Descriptor() // group.DefaultModelAllowlist holds the default value on creation for the model_allowlist field. group.DefaultModelAllowlist = groupDescModelAllowlist.Default.(domain.GroupModelAllowlist) // groupDescCodexModelsManifestConfig is the schema descriptor for codex_models_manifest_config field. - groupDescCodexModelsManifestConfig := groupFields[55].Descriptor() + groupDescCodexModelsManifestConfig := groupFields[56].Descriptor() // group.DefaultCodexModelsManifestConfig holds the default value on creation for the codex_models_manifest_config field. group.DefaultCodexModelsManifestConfig = groupDescCodexModelsManifestConfig.Default.(domain.GroupCodexModelsManifestConfig) // groupDescRpmLimit is the schema descriptor for rpm_limit field. - groupDescRpmLimit := groupFields[56].Descriptor() + groupDescRpmLimit := groupFields[57].Descriptor() // group.DefaultRpmLimit holds the default value on creation for the rpm_limit field. group.DefaultRpmLimit = groupDescRpmLimit.Default.(int) // groupDescMaxReasoningEffort is the schema descriptor for max_reasoning_effort field. - groupDescMaxReasoningEffort := groupFields[57].Descriptor() + groupDescMaxReasoningEffort := groupFields[58].Descriptor() // group.DefaultMaxReasoningEffort holds the default value on creation for the max_reasoning_effort field. group.DefaultMaxReasoningEffort = groupDescMaxReasoningEffort.Default.(string) // group.MaxReasoningEffortValidator is a validator for the "max_reasoning_effort" field. It is called by the builders before save. group.MaxReasoningEffortValidator = groupDescMaxReasoningEffort.Validators[0].(func(string) error) // groupDescMaxReasoningEffortOverLimit is the schema descriptor for max_reasoning_effort_over_limit field. - groupDescMaxReasoningEffortOverLimit := groupFields[58].Descriptor() + groupDescMaxReasoningEffortOverLimit := groupFields[59].Descriptor() // group.DefaultMaxReasoningEffortOverLimit holds the default value on creation for the max_reasoning_effort_over_limit field. group.DefaultMaxReasoningEffortOverLimit = groupDescMaxReasoningEffortOverLimit.Default.(string) // group.MaxReasoningEffortOverLimitValidator is a validator for the "max_reasoning_effort_over_limit" field. It is called by the builders before save. group.MaxReasoningEffortOverLimitValidator = groupDescMaxReasoningEffortOverLimit.Validators[0].(func(string) error) // groupDescReasoningEffortMappings is the schema descriptor for reasoning_effort_mappings field. - groupDescReasoningEffortMappings := groupFields[59].Descriptor() + groupDescReasoningEffortMappings := groupFields[60].Descriptor() // group.DefaultReasoningEffortMappings holds the default value on creation for the reasoning_effort_mappings field. group.DefaultReasoningEffortMappings = groupDescReasoningEffortMappings.Default.([]domain.ReasoningEffortMapping) // groupDescProfitControlEnabled is the schema descriptor for profit_control_enabled field. - groupDescProfitControlEnabled := groupFields[60].Descriptor() + groupDescProfitControlEnabled := groupFields[61].Descriptor() // group.DefaultProfitControlEnabled holds the default value on creation for the profit_control_enabled field. group.DefaultProfitControlEnabled = groupDescProfitControlEnabled.Default.(bool) // groupDescProfitMinMargin is the schema descriptor for profit_min_margin field. - groupDescProfitMinMargin := groupFields[61].Descriptor() + groupDescProfitMinMargin := groupFields[62].Descriptor() // group.DefaultProfitMinMargin holds the default value on creation for the profit_min_margin field. group.DefaultProfitMinMargin = groupDescProfitMinMargin.Default.(float64) // groupDescProfitSafetyBuffer is the schema descriptor for profit_safety_buffer field. - groupDescProfitSafetyBuffer := groupFields[62].Descriptor() + groupDescProfitSafetyBuffer := groupFields[63].Descriptor() // group.DefaultProfitSafetyBuffer holds the default value on creation for the profit_safety_buffer field. group.DefaultProfitSafetyBuffer = groupDescProfitSafetyBuffer.Default.(float64) idempotencyrecordMixin := schema.IdempotencyRecord{}.Mixin() diff --git a/backend/ent/schema/group.go b/backend/ent/schema/group.go index 1a77daa66..277f46852 100644 --- a/backend/ent/schema/group.go +++ b/backend/ent/schema/group.go @@ -44,6 +44,11 @@ func (Group) Fields() []ent.Field { Optional(). Nillable(). SchemaType(map[string]string{dialect.Postgres: "text"}), + // 名称与描述的界面语言译文 (added by migration 242) + field.JSON("i18n", domain.GroupI18n{}). + Default(domain.GroupI18n{}). + SchemaType(map[string]string{dialect.Postgres: "jsonb"}). + Comment("名称与描述的界面语言译文:语言代码 -> {name, description};缺失的语言沿用 name/description"), field.Float("rate_multiplier"). SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}). Default(1.0), diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index a9f0b6353..20756413e 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -979,6 +979,9 @@ const ( // GatewayConfig API网关相关配置 type GatewayConfig struct { + // MinOutputTokens is the minimum max_output_tokens used when + // converting Chat Completions or Anthropic requests to Responses. + MinOutputTokens int `mapstructure:"min_output_tokens"` // 等待上游响应头的超时时间(秒),0表示无超时 // 注意:这不影响流式数据传输,只控制等待响应头的时间 ResponseHeaderTimeout int `mapstructure:"response_header_timeout"` @@ -1005,6 +1008,8 @@ type GatewayConfig struct { ProxyProbeResponseReadMaxBytes int64 `mapstructure:"proxy_probe_response_read_max_bytes"` // Gemini 上游响应头调试日志开关(默认关闭,避免高频日志开销) GeminiDebugResponseHeaders bool `mapstructure:"gemini_debug_response_headers"` + // GeminiCachedContentMaxTTLSeconds: Gemini 显式缓存单次可设置的最长有效期(秒),<=0 时按 86400 处理 + GeminiCachedContentMaxTTLSeconds int `mapstructure:"gemini_cached_content_max_ttl_seconds"` // ConnectionPoolIsolation: 上游连接池隔离策略(proxy/account/account_proxy) ConnectionPoolIsolation string `mapstructure:"connection_pool_isolation"` // ForceCodexCLI: 强制将 OpenAI `/v1/responses` 请求按 Codex CLI 处理。 @@ -2054,6 +2059,7 @@ func configureConfigSource(setConfigFile, addConfigPath func(string)) { func setDefaults() { viper.SetDefault("run_mode", RunModeStandard) + viper.SetDefault("gateway.min_output_tokens", 128) viper.SetDefault("simple_mode.auto_create_default_groups", true) viper.SetDefault("simple_mode_key_rate_limit_enabled", false) @@ -2111,6 +2117,7 @@ func setDefaults() { "api.openai.com", "api.anthropic.com", "api.kimi.com", + "api.kimi.ai", "api.moonshot.ai", "api.moonshot.cn", "open.bigmodel.cn", @@ -2561,6 +2568,7 @@ func setDefaults() { viper.SetDefault("gateway.models_list_read_max_bytes", DefaultModelsListReadMaxBytes) viper.SetDefault("gateway.proxy_probe_response_read_max_bytes", int64(1024*1024)) viper.SetDefault("gateway.gemini_debug_response_headers", false) + viper.SetDefault("gateway.gemini_cached_content_max_ttl_seconds", 86400) viper.SetDefault("gateway.connection_pool_isolation", ConnectionPoolIsolationAccountProxy) // HTTP 上游连接池配置(针对 5000+ 并发用户优化) viper.SetDefault("gateway.max_idle_conns", 2560) // 最大空闲连接总数(高并发场景可调大) @@ -2737,6 +2745,9 @@ func setEnvReachableDefaults() { } func (c *Config) Validate() error { + if c.Gateway.MinOutputTokens < 16 { + return fmt.Errorf("gateway.min_output_tokens must be at least 16") + } forwardedClientIPHeaders, err := NormalizeForwardedClientIPHeaders(c.Security.ForwardedClientIPHeaders) if err != nil { return fmt.Errorf("security.forwarded_client_ip_headers: %w", err) diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go index b68a26d49..b41d710f9 100644 --- a/backend/internal/config/config_test.go +++ b/backend/internal/config/config_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "github.com/MACOS-DO/sub4api/internal/util/urlvalidator" "github.com/spf13/viper" "github.com/stretchr/testify/require" ) @@ -30,6 +31,29 @@ func TestLoadDefaultModelsListReadMaxBytes(t *testing.T) { require.Equal(t, DefaultModelsListReadMaxBytes, cfg.Gateway.ModelsListReadMaxBytes) } +func TestLoadDefaultMinOutputTokens(t *testing.T) { + resetViperWithJWTSecret(t) + cfg, err := Load() + require.NoError(t, err) + require.Equal(t, 128, cfg.Gateway.MinOutputTokens) +} + +func TestLoadMinOutputTokensFromEnv(t *testing.T) { + resetViperWithJWTSecret(t) + t.Setenv("GATEWAY_MIN_OUTPUT_TOKENS", "16") + cfg, err := Load() + require.NoError(t, err) + require.Equal(t, 16, cfg.Gateway.MinOutputTokens) +} + +func TestValidateMinOutputTokensMinimum(t *testing.T) { + resetViperWithJWTSecret(t) + cfg, err := Load() + require.NoError(t, err) + cfg.Gateway.MinOutputTokens = 15 + require.EqualError(t, cfg.Validate(), "gateway.min_output_tokens must be at least 16") +} + func TestLoadTimezonePrecedence(t *testing.T) { tests := []struct { name string @@ -831,6 +855,7 @@ func TestLoadDefaultSecurityToggles(t *testing.T) { wantHosts := []string{ "api.kimi.com", + "api.kimi.ai", "api.moonshot.ai", "api.moonshot.cn", } @@ -843,6 +868,19 @@ func TestLoadDefaultSecurityToggles(t *testing.T) { t.Fatalf("URLAllowlist.UpstreamHosts missing %q; got %v", want, cfg.Security.URLAllowlist.UpstreamHosts) } } + opts := urlvalidator.ValidationOptions{ + AllowedHosts: cfg.Security.URLAllowlist.UpstreamHosts, + RequireAllowlist: true, + AllowPrivate: cfg.Security.URLAllowlist.AllowPrivateHosts, + } + for _, host := range []string{"api.kimi.com", "api.kimi.ai"} { + target := "https://" + host + "/coding/v1/usages" + normalized, err := urlvalidator.ValidateHTTPSURL(target, opts) + require.NoError(t, err) + require.Equal(t, target, normalized) + _, err = urlvalidator.ValidateHTTPSURL("https://"+host+".attacker.example/coding/v1/usages", opts) + require.Error(t, err) + } } func TestLoadDefaultServerMode(t *testing.T) { diff --git a/backend/internal/domain/constants.go b/backend/internal/domain/constants.go index 94f51a6d9..fcd116a5a 100644 --- a/backend/internal/domain/constants.go +++ b/backend/internal/domain/constants.go @@ -114,6 +114,14 @@ var DefaultAntigravityModelMapping = map[string]string{ // Claude 白名单 "claude-fable-5-1": "claude-fable-5-1", // 官方模型 "claude-fable-5": "claude-fable-5", // 官方模型 + "claude-opus-5-5": "claude-opus-5-5-high", // 简称映射 + "claude-opus-5-5-high": "claude-opus-5-5-high", // 官方模型 + "claude-opus-5-5-medium": "claude-opus-5-5-medium", // 官方模型 + "claude-opus-5-5-low": "claude-opus-5-5-low", // 官方模型 + "claude-sonnet-5-5": "claude-sonnet-5-5-high", // 简称映射 + "claude-sonnet-5-5-high": "claude-sonnet-5-5-high", // 官方模型 + "claude-sonnet-5-5-medium": "claude-sonnet-5-5-medium", // 官方模型 + "claude-sonnet-5-5-low": "claude-sonnet-5-5-low", // 官方模型 "claude-opus-4-8": "claude-opus-4-8", // 官方模型 "claude-opus-4-7": "claude-opus-4-7", // 官方模型 "claude-opus-4-6-thinking": "claude-opus-4-6-thinking", // 官方模型 @@ -171,6 +179,11 @@ var DefaultAntigravityModelMapping = map[string]string{ "gemini-3.8-flash-low": "gemini-3.8-flash-low", "gemini-3.8-flash-medium": "gemini-3.8-flash-medium", "gemini-3.8-flash-tiered": "gemini-3.8-flash-tiered", + // Gemini 4 Argon tiered models + "gemini-4-argon": "gemini-4-argon-high", + "gemini-4-argon-high": "gemini-4-argon-high", + "gemini-4-argon-low": "gemini-4-argon-low", + "gemini-4-argon-medium": "gemini-4-argon-medium", // Gemini 3 image 兼容映射(向 3.1 image 迁移) "gemini-3-pro-image": "gemini-3.1-flash-image", "gemini-3-pro-image-preview": "gemini-3.1-flash-image", diff --git a/backend/internal/domain/constants_test.go b/backend/internal/domain/constants_test.go index 076688d6c..430d4802e 100644 --- a/backend/internal/domain/constants_test.go +++ b/backend/internal/domain/constants_test.go @@ -105,6 +105,28 @@ func TestDefaultAntigravityModelMapping_Gemini38FlashModels(t *testing.T) { } } +func TestDefaultAntigravityModelMapping_Gemini4ArgonAndClaude55Models(t *testing.T) { + cases := map[string]string{ + "gemini-4-argon": "gemini-4-argon-high", + "gemini-4-argon-high": "gemini-4-argon-high", + "gemini-4-argon-low": "gemini-4-argon-low", + "gemini-4-argon-medium": "gemini-4-argon-medium", + "claude-opus-5-5": "claude-opus-5-5-high", + "claude-opus-5-5-high": "claude-opus-5-5-high", + "claude-opus-5-5-low": "claude-opus-5-5-low", + "claude-opus-5-5-medium": "claude-opus-5-5-medium", + "claude-sonnet-5-5": "claude-sonnet-5-5-high", + "claude-sonnet-5-5-high": "claude-sonnet-5-5-high", + "claude-sonnet-5-5-low": "claude-sonnet-5-5-low", + "claude-sonnet-5-5-medium": "claude-sonnet-5-5-medium", + } + for from, want := range cases { + if got := DefaultAntigravityModelMapping[from]; got != want { + t.Fatalf("expected %s to map to %q, got %q", from, want, got) + } + } +} + func TestDefaultBedrockModelMapping_ContainsNewClaudeModels(t *testing.T) { t.Parallel() diff --git a/backend/internal/domain/group_i18n.go b/backend/internal/domain/group_i18n.go new file mode 100644 index 000000000..c02b1c5a4 --- /dev/null +++ b/backend/internal/domain/group_i18n.go @@ -0,0 +1,113 @@ +package domain + +import ( + "strconv" + "strings" +) + +// GroupLocaleText 是分组名称与描述在某个界面语言下的译文。 +// 字段为空表示该语言沿用分组自身的 name/description。 +type GroupLocaleText struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` +} + +// GroupI18n 以界面语言代码(如 "en"、"zh")为键保存分组展示文案的译文。 +// 仅用于页面展示;分组的唯一性、搜索与各类日志仍以 name 为准。 +type GroupI18n map[string]GroupLocaleText + +// Localize 返回 name、description 在请求首选语言下的版本;该语言没有译文的字段保持原值。 +// acceptLanguage 是 Accept-Language 请求头。只采用其中优先级最高的语言:原字段的语言 +// 未知,退到次选语言的译文不一定比原字段更合适。 +func (m GroupI18n) Localize(acceptLanguage, name, description string) (string, string) { + text, ok := m.lookup(preferredLanguage(acceptLanguage)) + if !ok { + return name, description + } + if text.Name != "" { + name = text.Name + } + if text.Description != "" { + description = text.Description + } + return name, description +} + +// LocalizeName 是只需要名称时的 Localize。 +func (m GroupI18n) LocalizeName(acceptLanguage, name string) string { + name, _ = m.Localize(acceptLanguage, name, "") + return name +} + +// CanonicalLocale 按 BCP 47 的惯用大小写书写语言代码:主语言小写,4 位文字代码首字母大写, +// 2 位地区代码大写,其余小写(zh-hant-tw -> zh-Hant-TW);单字母扩展标记之后的部分全部小写。 +// 只调整大小写,不校验代码是否合法。 +func CanonicalLocale(locale string) string { + subtags := strings.Split(locale, "-") + extension := false + for i, subtag := range subtags { + subtag = strings.ToLower(subtag) + switch { + case i == 0 || extension: + case len(subtag) == 1: + extension = true + case len(subtag) == 2: + subtag = strings.ToUpper(subtag) + case len(subtag) == 4: + subtag = strings.ToUpper(subtag[:1]) + subtag[1:] + } + subtags[i] = subtag + } + return strings.Join(subtags, "-") +} + +// lookup 先按完整语言代码匹配(zh-TW),再按主语言匹配(zh-CN -> zh),不区分大小写。 +// 写入时语言代码已统一为 CanonicalLocale,同一语言只有一个键;若存有仅大小写不同的多个键, +// 规范写法的键优先,其余按字节序取最小者,保证同一请求语言的结果固定。 +func (m GroupI18n) lookup(tag string) (GroupLocaleText, bool) { + if tag == "" || len(m) == 0 { + return GroupLocaleText{}, false + } + primary, _, _ := strings.Cut(tag, "-") + for _, candidate := range []string{tag, primary} { + candidate = CanonicalLocale(candidate) + if text, ok := m[candidate]; ok { + return text, true + } + matched := "" + for locale := range m { + if strings.EqualFold(locale, candidate) && (matched == "" || locale < matched) { + matched = locale + } + } + if matched != "" { + return m[matched], true + } + } + return GroupLocaleText{}, false +} + +// preferredLanguage 取 Accept-Language 中权重最高的语言代码,权重相同取靠前者; +// 通配符 * 与 q=0 的条目不参与。 +func preferredLanguage(acceptLanguage string) string { + best, bestQ := "", 0.0 + for _, part := range strings.Split(acceptLanguage, ",") { + tag, params, _ := strings.Cut(part, ";") + tag = strings.ReplaceAll(strings.TrimSpace(tag), "_", "-") + if tag == "" || tag == "*" { + continue + } + q := 1.0 + if value, ok := strings.CutPrefix(strings.TrimSpace(params), "q="); ok { + parsed, err := strconv.ParseFloat(strings.TrimSpace(value), 64) + if err != nil { + continue + } + q = parsed + } + if q > bestQ { + best, bestQ = tag, q + } + } + return best +} diff --git a/backend/internal/domain/group_i18n_test.go b/backend/internal/domain/group_i18n_test.go new file mode 100644 index 000000000..2860a0a6e --- /dev/null +++ b/backend/internal/domain/group_i18n_test.go @@ -0,0 +1,107 @@ +package domain + +import "testing" + +func TestGroupI18nLocalize(t *testing.T) { + i18n := GroupI18n{ + "en": {Name: "Standard", Description: "Pro + Max pool"}, + "zh-TW": {Name: "標準"}, + "ja": {Description: "説明のみ"}, + } + const name, description = "标准", "号池" + + tests := []struct { + title string + acceptLanguage string + wantName string + wantDescription string + }{ + {"exact locale", "en", "Standard", "Pro + Max pool"}, + {"region falls back to the primary language", "en-US", "Standard", "Pro + Max pool"}, + {"locale match ignores case and underscore", "ZH_tw", "標準", description}, + {"a missing field keeps the original text", "ja", name, "説明のみ"}, + {"no translation for the language keeps both", "zh", name, description}, + {"primary language does not match a regional translation", "zh-CN", name, description}, + {"empty header keeps both", "", name, description}, + {"wildcard only keeps both", "*", name, description}, + // 原字段的语言未知,不退到次选语言:浏览器的 zh 用户不应拿到英文译文。 + {"only the preferred language is considered", "zh-CN,zh;q=0.9,en;q=0.8", name, description}, + {"highest weight wins over position", "zh;q=0.5, en;q=0.9", "Standard", "Pro + Max pool"}, + {"equal weight keeps the first", "en, zh", "Standard", "Pro + Max pool"}, + {"entries with q=0 are ignored", "en;q=0, ja", name, "説明のみ"}, + {"malformed weight is skipped", "en;q=abc, ja", name, "説明のみ"}, + } + for _, tt := range tests { + t.Run(tt.title, func(t *testing.T) { + gotName, gotDescription := i18n.Localize(tt.acceptLanguage, name, description) + if gotName != tt.wantName || gotDescription != tt.wantDescription { + t.Fatalf("Localize(%q) = (%q, %q), want (%q, %q)", + tt.acceptLanguage, gotName, gotDescription, tt.wantName, tt.wantDescription) + } + }) + } +} + +func TestGroupI18nLocalize_NilMap(t *testing.T) { + var i18n GroupI18n + + name, description := i18n.Localize("en", "标准", "号池") + + if name != "标准" || description != "号池" { + t.Fatalf("nil translations must keep the original text, got (%q, %q)", name, description) + } + if got := i18n.LocalizeName("en", "标准"); got != "标准" { + t.Fatalf("LocalizeName on nil translations = %q", got) + } +} + +func TestGroupI18nLocalizeName(t *testing.T) { + i18n := GroupI18n{"en": {Name: "Standard"}} + + if got := i18n.LocalizeName("en", "标准"); got != "Standard" { + t.Fatalf("LocalizeName(en) = %q", got) + } + if got := i18n.LocalizeName("zh", "标准"); got != "标准" { + t.Fatalf("LocalizeName(zh) = %q", got) + } +} + +func TestCanonicalLocale(t *testing.T) { + tests := map[string]string{ + "en": "en", + "EN": "en", + "zh-tw": "zh-TW", + "ZH-Hant-tw": "zh-Hant-TW", + "es-419": "es-419", + "de-CH-1901": "de-CH-1901", + "en-US-x-Twain": "en-US-x-twain", + } + for in, want := range tests { + if got := CanonicalLocale(in); got != want { + t.Errorf("CanonicalLocale(%q) = %q, want %q", in, got, want) + } + } +} + +// 写入路径已拒绝仅大小写不同的语言代码;已存在的此类数据读取时也必须得到固定结果。 +func TestGroupI18nLocalize_CaseCollidingKeysAreDeterministic(t *testing.T) { + tests := []struct { + title string + i18n GroupI18n + acceptLanguage string + want string + }{ + {"canonical key wins", GroupI18n{"EN": {Name: "B"}, "en": {Name: "A"}, "En": {Name: "C"}}, "en", "A"}, + {"otherwise the smallest key wins", GroupI18n{"eN": {Name: "B"}, "EN": {Name: "A"}}, "en", "A"}, + {"primary language fallback is deterministic too", GroupI18n{"ZH": {Name: "B"}, "zh": {Name: "A"}}, "zh-CN", "A"}, + } + for _, tt := range tests { + t.Run(tt.title, func(t *testing.T) { + for range 200 { + if got := tt.i18n.LocalizeName(tt.acceptLanguage, "原名"); got != tt.want { + t.Fatalf("LocalizeName(%q) = %q, want %q", tt.acceptLanguage, got, tt.want) + } + } + }) + } +} diff --git a/backend/internal/handler/admin/account_codex_import.go b/backend/internal/handler/admin/account_codex_import.go index b604d2be1..9d7cb7e5b 100644 --- a/backend/internal/handler/admin/account_codex_import.go +++ b/backend/internal/handler/admin/account_codex_import.go @@ -908,14 +908,16 @@ func buildCodexAgentIdentityKeys(accountID string) []string { return []string{"account:" + accountID} } -// buildCodexStoredIdentityKeys 生成存量账号索引键,保留 user/account 维度, -// 让 accessToken-only 账号后续升级为完整 OAuth 时仍能命中并更新原账号。 +// buildCodexStoredIdentityKeys 生成存量账号索引键,按 workspace/account +// 和 user 组合隔离身份,避免同一用户在不同 workspace 的账号误合并。 func buildCodexStoredIdentityKeys(accountID, userID, email, accessToken string) []string { keys := make([]string, 0, 3) accountID = strings.TrimSpace(accountID) userID = strings.TrimSpace(userID) accessToken = strings.TrimSpace(accessToken) - if userID != "" { + if accountID != "" && userID != "" { + keys = append(keys, "account_user:"+codexCompositeIdentityKey(accountID, userID)) + } else if userID != "" { keys = append(keys, "user:"+userID) } if accountID == "" && userID == "" { @@ -932,6 +934,10 @@ func buildCodexStoredIdentityKeys(accountID, userID, email, accessToken string) return keys } +func codexCompositeIdentityKey(accountID, userID string) string { + return fmt.Sprintf("%d:%s%d:%s", len(accountID), accountID, len(userID), userID) +} + func buildCodexAccountIndex(accounts []service.Account) *codexAccountIndex { index := &codexAccountIndex{ accountsByKey: map[string][]service.Account{}, diff --git a/backend/internal/handler/admin/account_codex_import_test.go b/backend/internal/handler/admin/account_codex_import_test.go index 3d440723d..6011178bb 100644 --- a/backend/internal/handler/admin/account_codex_import_test.go +++ b/backend/internal/handler/admin/account_codex_import_test.go @@ -303,8 +303,8 @@ func TestResolveCodexImportExpiryForNoRefreshTokenUsesEarlierRequestExpiry(t *te func TestCodexIdentityKeysPreferStrongIdentifiers(t *testing.T) { keys := buildCodexImportIdentityKeys("acct-1", "user-1", "same@example.com", "token", "refresh") - if len(keys) == 0 || keys[0] != "user:user-1" { - t.Fatalf("user key should have highest priority when refresh token exists: %v", keys) + if len(keys) == 0 || keys[0] != "account_user:6:acct-16:user-1" { + t.Fatalf("workspace-scoped user key should have highest priority when refresh token exists: %v", keys) } if keys[len(keys)-1] != "account:acct-1" { t.Fatalf("shared account key should be the last fallback: %v", keys) @@ -465,12 +465,84 @@ func TestCodexAccountIndexKeepsAllCandidatesForSharedAccountKey(t *testing.T) { if got == nil || got.ID != member.ID { t.Fatalf("Find by user key = %v, want member account ID %d", got, member.ID) } - if matchedKey != "user:user-2" { - t.Fatalf("matched key = %q, want user:user-2", matchedKey) + if matchedKey != "account_user:6:team-16:user-2" { + t.Fatalf("matched key = %q, want account_user:6:team-16:user-2", matchedKey) } } } +func TestImportCodexSessionsSameUserDifferentWorkspacesCreatesSeparateAccounts(t *testing.T) { + svc := newCodexImportMemoryAdminService(nil) + handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + req := CodexSessionImportRequest{SkipDefaultGroupBind: boolPtr(true)} + entries := []codexImportEntry{ + {Index: 1, Value: buildCodexRefreshImportValue(t, "workspace-1", "shared-user", "refresh-1")}, + {Index: 2, Value: buildCodexRefreshImportValue(t, "workspace-2", "shared-user", "refresh-2")}, + } + + result, err := handler.importCodexSessions(context.Background(), req, entries) + if err != nil { + t.Fatalf("importCodexSessions error = %v", err) + } + if result.Created != 2 || result.Updated != 0 || result.Skipped != 0 || result.Failed != 0 { + t.Fatalf("result = %+v, want two created accounts", result) + } + if len(svc.createdAccounts) != 2 { + t.Fatalf("created accounts = %d, want 2", len(svc.createdAccounts)) + } + if got := svc.createdAccounts[0].Credentials["chatgpt_account_id"]; got != "workspace-1" { + t.Fatalf("first workspace = %v, want workspace-1", got) + } + if got := svc.createdAccounts[1].Credentials["chatgpt_account_id"]; got != "workspace-2" { + t.Fatalf("second workspace = %v, want workspace-2", got) + } +} + +func TestCodexImportIdentityKeySeparatesDelimiterValues(t *testing.T) { + left := buildCodexImportIdentityKeys("ab:c", "shared-user", "", "", "refresh") + right := buildCodexImportIdentityKeys("ab", "c:shared-user", "", "", "refresh") + if left[0] == right[0] { + t.Fatalf("composite identity keys collided: %q", left[0]) + } +} + +func TestImportCodexSessionsSameWorkspaceAccountUpdatesAndDifferentUserIsolated(t *testing.T) { + svc := newCodexImportMemoryAdminService(nil) + handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + req := CodexSessionImportRequest{SkipDefaultGroupBind: boolPtr(true)} + initialEntries := []codexImportEntry{ + {Index: 1, Value: buildCodexRefreshImportValue(t, "workspace-1", "user-1", "refresh-1")}, + {Index: 2, Value: buildCodexRefreshImportValue(t, "workspace-1", "user-2", "refresh-2")}, + } + + initialResult, err := handler.importCodexSessions(context.Background(), req, initialEntries) + if err != nil { + t.Fatalf("importCodexSessions error = %v", err) + } + if initialResult.Created != 2 || initialResult.Updated != 0 || initialResult.Skipped != 0 || initialResult.Failed != 0 { + t.Fatalf("initial result = %+v, want two created accounts", initialResult) + } + + updateResult, err := handler.importCodexSessions(context.Background(), req, []codexImportEntry{ + {Index: 3, Value: buildCodexRefreshImportValue(t, "workspace-1", "user-1", "refresh-3")}, + }) + if err != nil { + t.Fatalf("importCodexSessions update error = %v", err) + } + if updateResult.Created != 0 || updateResult.Updated != 1 || updateResult.Skipped != 0 || updateResult.Failed != 0 { + t.Fatalf("update result = %+v, want one updated account", updateResult) + } + if len(svc.createdAccounts) != 2 || len(svc.updatedAccounts) != 1 { + t.Fatalf("created = %d, updated = %d, want 2 and 1", len(svc.createdAccounts), len(svc.updatedAccounts)) + } + if svc.updatedAccounts[0].id != 100 { + t.Fatalf("updated account ID = %d, want user-1 account ID 100", svc.updatedAccounts[0].id) + } + if got := svc.updatedAccounts[0].input.Credentials["chatgpt_user_id"]; got != "user-1" { + t.Fatalf("updated user = %v, want user-1", got) + } +} + func TestCodexAccountIndexUpsertReplacesSameAccount(t *testing.T) { legacy := service.Account{ ID: 40, diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index ddf63b133..0a2e6a170 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -3078,13 +3078,13 @@ func antigravityAccountTestModels(rawMapping any) []antigravity.ClaudeModel { switch mapping := rawMapping.(type) { case map[string]any: for id := range mapping { - if strings.TrimSpace(id) != "" { + if strings.TrimSpace(id) != "" && !strings.Contains(id, "*") { mappedIDs = append(mappedIDs, id) } } case map[string]string: for id := range mapping { - if strings.TrimSpace(id) != "" { + if strings.TrimSpace(id) != "" && !strings.Contains(id, "*") { mappedIDs = append(mappedIDs, id) } } diff --git a/backend/internal/handler/admin/account_handler_available_models_test.go b/backend/internal/handler/admin/account_handler_available_models_test.go index e08a73374..24c8bca63 100644 --- a/backend/internal/handler/admin/account_handler_available_models_test.go +++ b/backend/internal/handler/admin/account_handler_available_models_test.go @@ -345,11 +345,12 @@ func TestAccountHandlerGetAvailableModels_Antigravity(t *testing.T) { {name: "empty JSON mapping", credentials: map[string]any{"model_mapping": map[string]any{}}, want: defaults}, {name: "empty string mapping", credentials: map[string]any{"model_mapping": map[string]string{}}, want: defaults}, {name: "blank key", credentials: map[string]any{"model_mapping": map[string]any{" ": "upstream-model"}}, want: defaults}, - {name: "JSON mapping keys and metadata", credentials: map[string]any{"model_mapping": map[string]any{ - known.ID: known.ID, custom.ID: "upstream-model", + {name: "wildcard only falls back to defaults", credentials: map[string]any{"model_mapping": map[string]any{"claude-*": "claude-sonnet-4-6", "gemini-3*": "gemini-3-flash"}}, want: defaults}, + {name: "JSON mapping keys and metadata skips wildcards", credentials: map[string]any{"model_mapping": map[string]any{ + known.ID: known.ID, custom.ID: "upstream-model", "claude-*": "claude-sonnet-4-6", }}, want: []antigravity.ClaudeModel{custom, known}}, - {name: "string mapping keys and metadata", credentials: map[string]any{"model_mapping": map[string]string{ - known.ID: known.ID, custom.ID: "upstream-model", + {name: "string mapping keys and metadata skips wildcards", credentials: map[string]any{"model_mapping": map[string]string{ + known.ID: known.ID, custom.ID: "upstream-model", "gemini-*": "gemini-3-flash", }}, want: []antigravity.ClaudeModel{custom, known}}, } for _, tc := range cases { diff --git a/backend/internal/handler/admin/group_handler.go b/backend/internal/handler/admin/group_handler.go index a5ccc87e3..e8bc1403d 100644 --- a/backend/internal/handler/admin/group_handler.go +++ b/backend/internal/handler/admin/group_handler.go @@ -142,6 +142,8 @@ type simpleModeGroupResponse struct { Platform string `json:"platform"` Status string `json:"status"` + I18n service.GroupI18n `json:"i18n,omitempty"` + AccountCount int64 `json:"account_count,omitempty"` ActiveAccountCount int64 `json:"active_account_count,omitempty"` RateLimitedAccountCount int64 `json:"rate_limited_account_count,omitempty"` @@ -157,6 +159,7 @@ func groupForSimpleMode(group *service.Group) *simpleModeGroupResponse { return &simpleModeGroupResponse{ ID: group.ID, Name: group.Name, Description: group.Description, Platform: group.Platform, Status: group.Status, + I18n: group.I18n, AccountCount: group.AccountCount, ActiveAccountCount: group.ActiveAccountCount, RateLimitedAccountCount: group.RateLimitedAccountCount, SortOrder: group.SortOrder, CreatedAt: group.CreatedAt, UpdatedAt: group.UpdatedAt, @@ -167,7 +170,7 @@ func sanitizeCreateGroupRequestForSimpleMode(req *CreateGroupRequest) { if req == nil { return } - allowed := CreateGroupRequest{Name: req.Name, Description: req.Description, Platform: req.Platform} + allowed := CreateGroupRequest{Name: req.Name, Description: req.Description, I18n: req.I18n, Platform: req.Platform} allowed.RateMultiplier = 1 allowed.SubscriptionType = service.SubscriptionTypeStandard *req = allowed @@ -177,13 +180,14 @@ func sanitizeUpdateGroupRequestForSimpleMode(req *UpdateGroupRequest) { if req == nil { return } - *req = UpdateGroupRequest{Name: req.Name, Description: req.Description} + *req = UpdateGroupRequest{Name: req.Name, Description: req.Description, I18n: req.I18n} } // CreateGroupRequest represents create group request type CreateGroupRequest struct { Name string `json:"name" binding:"required"` Description string `json:"description"` + I18n service.GroupI18n `json:"i18n"` // 名称与描述的界面语言译文 Platform string `json:"platform" binding:"omitempty,group_platform"` RateMultiplier float64 `json:"rate_multiplier"` IsExclusive bool `json:"is_exclusive"` @@ -258,6 +262,7 @@ type CreateGroupRequest struct { type UpdateGroupRequest struct { Name string `json:"name"` Description *string `json:"description"` + I18n *service.GroupI18n `json:"i18n"` // 缺省不修改,传入则整体替换 Platform string `json:"platform" binding:"omitempty,group_platform"` RateMultiplier *float64 `json:"rate_multiplier"` IsExclusive *bool `json:"is_exclusive"` @@ -664,6 +669,7 @@ func (h *GroupHandler) Create(c *gin.Context) { group, err := h.adminService.CreateGroup(c.Request.Context(), &service.CreateGroupInput{ Name: req.Name, Description: req.Description, + I18n: req.I18n, Platform: req.Platform, RateMultiplier: req.RateMultiplier, IsExclusive: req.IsExclusive, @@ -809,6 +815,7 @@ func (h *GroupHandler) Update(c *gin.Context) { group, err := h.adminService.UpdateGroup(c.Request.Context(), groupID, &service.UpdateGroupInput{ Name: req.Name, Description: req.Description, + I18n: req.I18n, Platform: req.Platform, RateMultiplier: req.RateMultiplier, IsExclusive: req.IsExclusive, diff --git a/backend/internal/handler/api_key_handler.go b/backend/internal/handler/api_key_handler.go index d42de8aa1..1c2603e76 100644 --- a/backend/internal/handler/api_key_handler.go +++ b/backend/internal/handler/api_key_handler.go @@ -142,7 +142,7 @@ func (h *APIKeyHandler) List(c *gin.Context) { out := make([]dto.APIKey, 0, len(keys)) for i := range keys { - out = append(out, *dto.APIKeyFromService(&keys[i])) + out = append(out, *dto.APIKeyFromService(&keys[i]).Localized(c.GetHeader("Accept-Language"))) } response.Paginated(c, out, result.Total, page, pageSize) } @@ -174,7 +174,7 @@ func (h *APIKeyHandler) GetByID(c *gin.Context) { return } - response.Success(c, dto.APIKeyFromService(key)) + response.Success(c, dto.APIKeyFromService(key).Localized(c.GetHeader("Accept-Language"))) } // Create handles creating a new API key @@ -222,7 +222,7 @@ func (h *APIKeyHandler) Create(c *gin.Context) { if err != nil { return nil, err } - return dto.APIKeyFromService(key), nil + return dto.APIKeyFromService(key).Localized(c.GetHeader("Accept-Language")), nil }) } @@ -290,7 +290,7 @@ func (h *APIKeyHandler) Update(c *gin.Context) { return } - response.Success(c, dto.APIKeyFromService(key)) + response.Success(c, dto.APIKeyFromService(key).Localized(c.GetHeader("Accept-Language"))) } // Delete handles deleting an API key @@ -334,7 +334,7 @@ func (h *APIKeyHandler) GetAvailableGroups(c *gin.Context) { out := make([]dto.Group, 0, len(groups)) for i := range groups { - out = append(out, *dto.GroupFromService(&groups[i])) + out = append(out, *dto.GroupFromService(&groups[i]).Localized(c.GetHeader("Accept-Language"))) } response.Success(c, out) } diff --git a/backend/internal/handler/available_channel_handler.go b/backend/internal/handler/available_channel_handler.go index 2815a5640..f71840737 100644 --- a/backend/internal/handler/available_channel_handler.go +++ b/backend/internal/handler/available_channel_handler.go @@ -62,6 +62,9 @@ type userAvailableGroup struct { PeakEnd string `json:"peak_end"` PeakRateMultiplier float64 `json:"peak_rate_multiplier"` IsExclusive bool `json:"is_exclusive"` + + // 不对外输出;List 按请求语言把 Name 换成译文后丢弃。 + i18n service.GroupI18n } // userSupportedModelPricing 用户可见的定价字段白名单。 @@ -154,6 +157,7 @@ func (h *AvailableChannelHandler) List(c *gin.Context) { return } + acceptLanguage := c.GetHeader("Accept-Language") out := make([]userAvailableChannel, 0, len(channels)) for _, ch := range channels { if ch.Status != service.StatusActive { @@ -163,6 +167,7 @@ func (h *AvailableChannelHandler) List(c *gin.Context) { if len(visibleGroups) == 0 { continue } + localizeUserAvailableGroups(visibleGroups, acceptLanguage) sections := buildPlatformSections(ch, visibleGroups) if len(sections) == 0 { continue @@ -177,6 +182,13 @@ func (h *AvailableChannelHandler) List(c *gin.Context) { response.Success(c, out) } +// localizeUserAvailableGroups 把分组名称就地换成请求首选语言的版本。 +func localizeUserAvailableGroups(groups []userAvailableGroup, acceptLanguage string) { + for i := range groups { + groups[i].Name = groups[i].i18n.LocalizeName(acceptLanguage, groups[i].Name) + } +} + // buildPlatformSections 把一个渠道按 visibleGroups 的平台集合拆成有序的 section 列表: // 每个 section 对应一个具体平台,只包含该平台的 groups 和 supported_models。 // @@ -254,6 +266,7 @@ func filterUserVisibleGroups( visible = append(visible, userAvailableGroup{ ID: g.ID, Name: g.Name, + i18n: g.I18n, Platform: g.Platform, SubscriptionType: g.SubscriptionType, RateMultiplier: g.RateMultiplier, diff --git a/backend/internal/handler/dto/group_localize.go b/backend/internal/handler/dto/group_localize.go new file mode 100644 index 000000000..6a9ce7d8f --- /dev/null +++ b/backend/internal/handler/dto/group_localize.go @@ -0,0 +1,49 @@ +package dto + +// 用户侧接口在输出前调用 Localized:把分组的名称与描述换成请求首选语言 +// (Accept-Language)的版本,并去掉译文表。管理端接口不调用,保留原字段与译文表, +// 分组编辑表单依赖原字段回写。 + +// Localized 就地本地化分组并返回自身。 +func (g *Group) Localized(acceptLanguage string) *Group { + if g == nil { + return nil + } + g.Name, g.Description = g.I18n.Localize(acceptLanguage, g.Name, g.Description) + g.I18n = nil + return g +} + +// Localized 本地化 API Key 所属分组并返回自身。 +func (k *APIKey) Localized(acceptLanguage string) *APIKey { + if k != nil { + k.Group.Localized(acceptLanguage) + } + return k +} + +// Localized 本地化兑换码关联分组并返回自身。 +func (r *RedeemCode) Localized(acceptLanguage string) *RedeemCode { + if r != nil { + r.Group.Localized(acceptLanguage) + } + return r +} + +// Localized 本地化使用记录关联的分组(含其 API Key 与订阅各自携带的分组)并返回自身。 +func (l *UsageLog) Localized(acceptLanguage string) *UsageLog { + if l != nil { + l.Group.Localized(acceptLanguage) + l.APIKey.Localized(acceptLanguage) + l.Subscription.Localized(acceptLanguage) + } + return l +} + +// Localized 本地化订阅关联分组并返回自身。 +func (s *UserSubscription) Localized(acceptLanguage string) *UserSubscription { + if s != nil { + s.Group.Localized(acceptLanguage) + } + return s +} diff --git a/backend/internal/handler/dto/group_localize_test.go b/backend/internal/handler/dto/group_localize_test.go new file mode 100644 index 000000000..978e0a1f1 --- /dev/null +++ b/backend/internal/handler/dto/group_localize_test.go @@ -0,0 +1,71 @@ +package dto + +import ( + "encoding/json" + "testing" + + "github.com/MACOS-DO/sub4api/internal/domain" + "github.com/stretchr/testify/require" +) + +func localizableGroup() *Group { + return &Group{ + ID: 1, Name: "标准", Description: "号池", + I18n: domain.GroupI18n{"en": {Name: "Standard", Description: "Pro + Max pool"}}, + } +} + +func TestGroupLocalized_ReplacesTextAndDropsTranslations(t *testing.T) { + g := localizableGroup().Localized("en") + + require.Equal(t, "Standard", g.Name) + require.Equal(t, "Pro + Max pool", g.Description) + + raw, err := json.Marshal(g) + require.NoError(t, err) + var decoded map[string]any + require.NoError(t, json.Unmarshal(raw, &decoded)) + require.NotContains(t, decoded, "i18n", "user-facing output must not carry the translation table") +} + +func TestGroupLocalized_KeepsOriginalWhenLanguageHasNoTranslation(t *testing.T) { + g := localizableGroup().Localized("zh") + + require.Equal(t, "标准", g.Name) + require.Equal(t, "号池", g.Description) + require.Nil(t, g.I18n) +} + +func TestLocalized_NilSafe(t *testing.T) { + require.Nil(t, (*Group)(nil).Localized("en")) + require.Nil(t, (*APIKey)(nil).Localized("en")) + require.Nil(t, (*RedeemCode)(nil).Localized("en")) + require.Nil(t, (*UsageLog)(nil).Localized("en")) + require.Nil(t, (*UserSubscription)(nil).Localized("en")) + + // 未携带分组的记录原样返回 + require.Nil(t, (&APIKey{}).Localized("en").Group) +} + +func TestLocalized_NestedGroups(t *testing.T) { + key := (&APIKey{Group: localizableGroup()}).Localized("en") + require.Equal(t, "Standard", key.Group.Name) + + code := (&RedeemCode{Group: localizableGroup()}).Localized("en") + require.Equal(t, "Standard", code.Group.Name) + + sub := (&UserSubscription{Group: localizableGroup()}).Localized("en") + require.Equal(t, "Standard", sub.Group.Name) + + // 使用记录除自身分组外,还带着 API Key 与订阅各自的分组 + log := (&UsageLog{ + Group: localizableGroup(), + APIKey: &APIKey{Group: localizableGroup()}, + Subscription: &UserSubscription{Group: localizableGroup()}, + }).Localized("en") + require.Equal(t, "Standard", log.Group.Name) + require.Equal(t, "Standard", log.APIKey.Group.Name) + require.Equal(t, "Standard", log.Subscription.Group.Name) + require.Nil(t, log.APIKey.Group.I18n) + require.Nil(t, log.Subscription.Group.I18n) +} diff --git a/backend/internal/handler/dto/mappers.go b/backend/internal/handler/dto/mappers.go index 8ff75e756..6a2b07631 100644 --- a/backend/internal/handler/dto/mappers.go +++ b/backend/internal/handler/dto/mappers.go @@ -182,6 +182,7 @@ func groupFromServiceBase(g *service.Group) Group { ID: g.ID, Name: g.Name, Description: g.Description, + I18n: g.I18n, Platform: g.Platform, RateMultiplier: g.RateMultiplier, IsExclusive: g.IsExclusive, diff --git a/backend/internal/handler/dto/types.go b/backend/internal/handler/dto/types.go index 21e7077e2..a05857f1e 100644 --- a/backend/internal/handler/dto/types.go +++ b/backend/internal/handler/dto/types.go @@ -99,6 +99,10 @@ type Group struct { IsExclusive bool `json:"is_exclusive"` Status string `json:"status"` + // I18n 名称与描述的各语言译文。只有管理端输出;用户侧接口经 Localized 把 + // name/description 换成请求语言的版本后清空本字段。 + I18n domain.GroupI18n `json:"i18n,omitempty"` + SubscriptionType string `json:"subscription_type"` DailyLimitUSD *float64 `json:"daily_limit_usd"` WeeklyLimitUSD *float64 `json:"weekly_limit_usd"` diff --git a/backend/internal/handler/endpoint.go b/backend/internal/handler/endpoint.go index 38ce98a51..105f8dac6 100644 --- a/backend/internal/handler/endpoint.go +++ b/backend/internal/handler/endpoint.go @@ -32,6 +32,7 @@ const ( EndpointVideos = "/v1/videos" EndpointSeedanceTasks = "/api/v3/contents/generations/tasks" EndpointGeminiModels = "/v1beta/models" + EndpointGeminiCachedContents = "/v1beta/cachedContents" ) const EndpointAntigravityGenerateContent = "/v1internal:streamGenerateContent" @@ -53,6 +54,7 @@ const ( // "/v1/chat/completions" → "/v1/chat/completions" // "/openai/v1/responses/foo" → "/v1/responses" // "/v1beta/models/gemini:gen" → "/v1beta/models" +// "/v1beta/cachedContents/abc" → "/v1beta/cachedContents" // // The OpenAI Responses API is also exposed via a few bare/alias // routes that do not carry a "/v1/" prefix (top-level bare route and @@ -117,6 +119,8 @@ func NormalizeInboundEndpoint(path string) string { return EndpointResponses case strings.Contains(path, EndpointGeminiModels): return EndpointGeminiModels + case strings.Contains(path, EndpointGeminiCachedContents): + return EndpointGeminiCachedContents default: return path } @@ -194,7 +198,7 @@ func isBareOrSubpathOf(path, root string) bool { // retain their paths. Grok raw Chat requests override this through the // forwarding result consumed by resolveOpenAIUpstreamEndpoint. // - Anthropic → /v1/messages -// - Gemini → /v1beta/models +// - Gemini → /v1beta/models(显式缓存管理接口保留 /v1beta/cachedContents) // - Antigravity → /v1/messages (Claude) or gemini (Gemini) // - Antigravity routes may target either Claude or Gemini, so the // inbound endpoint is used to distinguish. @@ -230,6 +234,9 @@ func DeriveUpstreamEndpoint(inbound, rawRequestPath, platform string) string { return EndpointSystemOne case service.PlatformGemini: + if inbound == EndpointGeminiCachedContents { + return EndpointGeminiCachedContents + } return EndpointGeminiModels case service.PlatformAntigravity: diff --git a/backend/internal/handler/endpoint_test.go b/backend/internal/handler/endpoint_test.go index 6bef9dcce..ac50a36a0 100644 --- a/backend/internal/handler/endpoint_test.go +++ b/backend/internal/handler/endpoint_test.go @@ -37,6 +37,8 @@ func TestNormalizeInboundEndpoint(t *testing.T) { {"/v1/videos/generations", EndpointVideosGenerations}, {"/v1/videos/req_123", EndpointVideos}, {"/v1beta/models", EndpointGeminiModels}, + {"/v1beta/cachedContents", EndpointGeminiCachedContents}, + {"/v1beta/cachedContents/gfo2i2haszm3wbwiyivyok5cyddubfwsr77efg7h", EndpointGeminiCachedContents}, // Prefixed paths (antigravity, openai) — root Responses. {"/antigravity/v1/messages", EndpointMessages}, @@ -102,6 +104,7 @@ func TestDeriveUpstreamEndpoint(t *testing.T) { // Gemini. {"gemini models", EndpointGeminiModels, "/v1beta/models/gemini:gen", service.PlatformGemini, EndpointGeminiModels}, + {"gemini cached contents", EndpointGeminiCachedContents, "/v1beta/cachedContents/abc", service.PlatformGemini, EndpointGeminiCachedContents}, // OpenAI — root Responses. {"openai responses root", EndpointResponses, "/v1/responses", service.PlatformOpenAI, EndpointResponses}, diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 2f597e4e5..d50115451 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -52,12 +52,14 @@ type GatewayHandler struct { errorPassthroughService *service.ErrorPassthroughService contentModerationService *service.ContentModerationService securityAuditCoordinator *securityaudit.Coordinator - concurrencyHelper *ConcurrencyHelper - userMsgQueueHelper *UserMsgQueueHelper - maxAccountSwitches int - maxAccountSwitchesGemini int - cfg *config.Config - settingService *service.SettingService + // geminiCachedContentService 管理 Gemini 显式缓存;为 nil 时相关接口不可用。 + geminiCachedContentService *service.GeminiCachedContentService + concurrencyHelper *ConcurrencyHelper + userMsgQueueHelper *UserMsgQueueHelper + maxAccountSwitches int + maxAccountSwitchesGemini int + cfg *config.Config + settingService *service.SettingService } // NewGatewayHandler creates a new GatewayHandler @@ -1195,7 +1197,7 @@ func (h *GatewayHandler) Models(c *gin.Context) { return } - if len(availableModels) > 0 { + if len(availableModels) > 0 || (platform == service.PlatformOpenAI && availableModels != nil) { writeModelsList(c, platform, availableModels) return } @@ -1326,7 +1328,7 @@ func (h *GatewayHandler) compositeAvailableModels(ctx context.Context, groupID * continue } platformModels := h.gatewayService.GetAvailableModels(ctx, groupID, platform) - if len(platformModels) == 0 { + if len(platformModels) == 0 && (platform != service.PlatformOpenAI || platformModels == nil) { // CN 供应商没有静态默认模型列表(defaultModelIDsForPlatform 的 // default 分支是 Claude 列表),composite 下只暴露账号映射键。 if _, ok := schedulablePlatforms[platform]; ok && !service.IsMultiProtocolAPIKeyProvider(platform) { @@ -1475,6 +1477,9 @@ func writeOpenAIModelsList(c *gin.Context, modelIDs []string) { // 与平台默认列表(fallbackModels)。账号映射为空时回落默认列表;Anthropic // 平台两者取并集,其余平台以账号映射键为准。 func modelListingSource(platform string, availableModels, fallbackModels []string) []string { + if platform == service.PlatformOpenAI && availableModels != nil { + return availableModels + } if len(availableModels) == 0 { return fallbackModels } diff --git a/backend/internal/handler/gateway_models_test.go b/backend/internal/handler/gateway_models_test.go index 6d975e000..83c0998c1 100644 --- a/backend/internal/handler/gateway_models_test.go +++ b/backend/internal/handler/gateway_models_test.go @@ -324,6 +324,12 @@ func TestGatewayModels_UnmappedOpenAIAccountsSupplementMappedModels(t *testing.T Credentials: map[string]any{"model_mapping": map[string]any{alias: "gpt-5.6-sol"}}, }, } + subscriptionDefaults := make([]string, 0) + for _, model := range openai.DefaultModelIDs() { + if model != "gpt-5.5" { + subscriptionDefaults = append(subscriptionDefaults, model) + } + } tests := []struct { name string accounts []service.Account @@ -333,7 +339,7 @@ func TestGatewayModels_UnmappedOpenAIAccountsSupplementMappedModels(t *testing.T { name: "unmapped parent and Spark shadow retain defaults and aliases", accounts: accounts, - want: append(openai.DefaultModelIDs(), alias), + want: append(append([]string{}, subscriptionDefaults...), alias), }, { name: "unmapped API key account also contributes defaults", @@ -343,7 +349,7 @@ func TestGatewayModels_UnmappedOpenAIAccountsSupplementMappedModels(t *testing.T { name: "unmapped accounts alone retain default response shape", accounts: accounts[:1], - want: openai.DefaultModelIDs(), + want: subscriptionDefaults, }, { name: "custom list can select defaults and aliases", @@ -372,7 +378,7 @@ func TestGatewayModels_UnmappedOpenAIAccountsSupplementMappedModels(t *testing.T Credentials: map[string]any{"model_mapping": map[string]any{"stale-model": "stale-model"}}, Extra: map[string]any{"openai_passthrough": true}, }}, accounts[1:]...), - want: append(openai.DefaultModelIDs(), alias), + want: append(append([]string{}, subscriptionDefaults...), alias), }, { name: "unmapped accounts from another platform do not add defaults", @@ -1408,6 +1414,60 @@ func modelIDsForTest(models []gatewayModelItemForTest) []string { return ids } +func TestGatewayModels_AntigravityExplicitMappingAppearsInBothCatalogs(t *testing.T) { + gin.SetMode(gin.TestMode) + const groupID int64 = 93 + mapping := map[string]any{ + "gemini-3.8-flash": "gemini-3.8-flash-high", + "gemini-3.8-flash-high": "gemini-3.8-flash-high", + "claude-opus-4-6-thinking": "claude-opus-4-6-thinking", + "gemini-pro-agent": "gemini-pro-agent", + } + for _, platform := range []string{service.PlatformAntigravity, service.PlatformComposite, service.PlatformGemini} { + t.Run(platform, func(t *testing.T) { + h := newGatewayModelsHandlerForTest(&gatewayModelsAccountRepoStub{ + byGroup: map[int64][]service.Account{groupID: {{ + ID: 25, Platform: service.PlatformAntigravity, + Extra: map[string]any{"mixed_scheduling": true}, + Credentials: map[string]any{"model_mapping": mapping}, + }}}, + }) + want := []string{"gemini-3.8-flash", "gemini-3.8-flash-high", "gemini-pro-agent", "claude-opus-4-6-thinking"} + if platform == service.PlatformGemini { + want = want[:3] + } + for _, codex := range []bool{false, true} { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil) + c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{ID: groupID, Platform: platform}, + }) + var ids []string + if codex { + h.CodexModels(c) + var got codexModelsResponseForTest + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got)) + for _, model := range got.Models { + ids = append(ids, model.Slug) + } + } else { + h.Models(c) + var got gatewayModelsResponseForTest + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got)) + ids = modelIDsForTest(got.Data) + } + require.Equal(t, http.StatusOK, rec.Code) + // 显式条目必须同时出现在两种目录;默认透传补齐的条目不锁定。 + require.Subset(t, ids, want, "codex=%t", codex) + if platform == service.PlatformGemini { + require.NotContains(t, ids, "claude-opus-4-6-thinking", "codex=%t", codex) + } + } + }) + } +} + // gemini 分组混合调度:组内 antigravity 账号的 gemini-* 映射也应出现在 /v1/models, // 与路由层(listSchedulableAccountsOnce 的 useMixedScheduling)同源;claude-* 不带入, // 非混合调度的异平台账号(anthropic)仍被过滤。 diff --git a/backend/internal/handler/gemini_cached_contents_billing_test.go b/backend/internal/handler/gemini_cached_contents_billing_test.go new file mode 100644 index 000000000..8f430809f --- /dev/null +++ b/backend/internal/handler/gemini_cached_contents_billing_test.go @@ -0,0 +1,955 @@ +//go:build unit + +package handler + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/MACOS-DO/sub4api/internal/pkg/ctxkey" + middleware "github.com/MACOS-DO/sub4api/internal/server/middleware" + "github.com/MACOS-DO/sub4api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +const ( + cachedBillingInputPrice = 0.00000125 + cachedBillingStoragePrice = 0.0000045 + cachedBillingAliasStoragePrice = 0.000009 + cachedBillingTokens = 1_000_000 +) + +type cachedBillingRepo struct { + mu sync.Mutex + records map[string]*service.GeminiCachedContent + // mutations 按记录 id 保存修改意图。 + mutations map[int64]cachedBillingMutation + failCommit bool + nextID int64 + deleted []int64 +} + +type cachedBillingMutation struct { + token string + leaseUntil time.Time +} + +func (r *cachedBillingRepo) Create(_ context.Context, record *service.GeminiCachedContent) error { + r.mu.Lock() + defer r.mu.Unlock() + r.nextID++ + record.ID = r.nextID + cp := *record + r.records[record.PublicID] = &cp + return nil +} + +func (r *cachedBillingRepo) GetForOwner(_ context.Context, apiKeyID int64, publicID string) (*service.GeminiCachedContent, error) { + r.mu.Lock() + defer r.mu.Unlock() + record, ok := r.records[publicID] + if !ok || record.APIKeyID != apiKeyID || r.liveLocked(record.ID) == nil { + return nil, service.ErrGeminiCachedContentNotFound + } + cp := *record + return &cp, nil +} + +func (r *cachedBillingRepo) ListForOwner(context.Context, int64, int64, time.Time, int64, int) ([]*service.GeminiCachedContent, error) { + return nil, nil +} + +// liveLocked 返回未删除的记录;调用方须持有 mu。 +func (r *cachedBillingRepo) liveLocked(id int64) *service.GeminiCachedContent { + for _, deleted := range r.deleted { + if deleted == id { + return nil + } + } + for _, record := range r.records { + if record.ID == id { + return record + } + } + return nil +} + +func (r *cachedBillingRepo) BeginMutation(_ context.Context, id int64, baseline time.Time, token string, lease time.Duration) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + record := r.liveLocked(id) + if record == nil { + return false, service.ErrGeminiCachedContentNotFound + } + if _, pending := r.mutations[id]; pending || !record.ExpireTime.Equal(baseline) { + return false, nil + } + r.mutations[id] = cachedBillingMutation{token: token, leaseUntil: time.Now().Add(lease)} + return true, nil +} + +func (r *cachedBillingRepo) TakeOverStaleMutation(_ context.Context, id int64, token string, lease time.Duration) (*service.GeminiCachedContent, error) { + r.mu.Lock() + defer r.mu.Unlock() + record := r.liveLocked(id) + mutation, pending := r.mutations[id] + if record == nil || !pending || mutation.leaseUntil.After(time.Now()) { + return nil, nil + } + r.mutations[id] = cachedBillingMutation{token: token, leaseUntil: time.Now().Add(lease)} + cp := *record + return &cp, nil +} + +func (r *cachedBillingRepo) CommitMutation(_ context.Context, id int64, token string, expireTime time.Time) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.failCommit { + return errors.New("db unavailable") + } + record := r.liveLocked(id) + mutation, pending := r.mutations[id] + if record == nil || !pending || mutation.token != token { + return service.ErrGeminiCachedContentMutationConflict + } + record.ExpireTime = expireTime + delete(r.mutations, id) + return nil +} + +func (r *cachedBillingRepo) ReleaseMutation(_ context.Context, id int64, token string) error { + r.mu.Lock() + defer r.mu.Unlock() + if mutation, pending := r.mutations[id]; pending && mutation.token == token { + delete(r.mutations, id) + } + return nil +} + +func (r *cachedBillingRepo) ListStaleMutations(_ context.Context, limit int) ([]int64, error) { + r.mu.Lock() + defer r.mu.Unlock() + var ids []int64 + for id, mutation := range r.mutations { + if len(ids) < limit && mutation.leaseUntil.Before(time.Now()) && r.liveLocked(id) != nil { + ids = append(ids, id) + } + } + return ids, nil +} + +func (r *cachedBillingRepo) SoftDelete(_ context.Context, id int64) error { + r.mu.Lock() + defer r.mu.Unlock() + r.deleted = append(r.deleted, id) + return nil +} + +// pendingMutation 返回记录是否有未清除的修改意图。 +func (r *cachedBillingRepo) pendingMutation(id int64) bool { + r.mu.Lock() + defer r.mu.Unlock() + _, pending := r.mutations[id] + return pending +} + +// expireLease 让记录上的修改意图租约立即过期。 +func (r *cachedBillingRepo) expireLease(id int64) { + r.mu.Lock() + defer r.mu.Unlock() + mutation := r.mutations[id] + mutation.leaseUntil = time.Now().Add(-time.Second) + r.mutations[id] = mutation +} + +type cachedBillingAccountRepo struct { + service.AccountRepository + accounts map[int64]*service.Account +} + +func (r *cachedBillingAccountRepo) GetByID(_ context.Context, id int64) (*service.Account, error) { + account, ok := r.accounts[id] + if !ok { + return nil, service.ErrAccountNotFound + } + cp := *account + return &cp, nil +} + +type cachedBillingUpstream struct { + service.HTTPUpstream + mu sync.Mutex + createBody string + calls []string + // patchTTLs 按顺序记录 PATCH 请求体中的 ttl。 + patchTTLs []string + beforePost func(n int) + // failures 按请求方法返回上游错误响应;transportErrors 按请求方法返回传输层错误(上游结果未知)。 + failures map[string]cachedBillingUpstreamFailure + transportErrors map[string]error +} + +type cachedBillingUpstreamFailure struct { + status int + body string +} + +func (u *cachedBillingUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + var patch struct { + TTL string `json:"ttl"` + } + if req.Method == http.MethodPatch { + _ = json.NewDecoder(req.Body).Decode(&patch) + } + u.mu.Lock() + u.calls = append(u.calls, req.Method+" "+req.URL.Path) + n := len(u.calls) + if req.Method == http.MethodPatch { + u.patchTTLs = append(u.patchTTLs, patch.TTL) + } + failure, failed := u.failures[req.Method] + transportErr := u.transportErrors[req.Method] + u.mu.Unlock() + if transportErr != nil { + return nil, transportErr + } + if failed { + return &http.Response{StatusCode: failure.status, Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(failure.body))}, nil + } + body := "{}" + switch req.Method { + case http.MethodPost: + body = u.createBody + case http.MethodPatch: + if u.beforePost != nil { + u.beforePost(n) + } + seconds, _ := strconv.ParseInt(strings.TrimSuffix(patch.TTL, "s"), 10, 64) + body = fmt.Sprintf(`{"name":"cachedContents/up1","expireTime":%q}`, time.Now().Add(time.Duration(seconds)*time.Second).UTC().Format(time.RFC3339Nano)) + } + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(body))}, nil +} + +func (u *cachedBillingUpstream) methodCalls(method string) int { + u.mu.Lock() + defer u.mu.Unlock() + n := 0 + for _, call := range u.calls { + if strings.HasPrefix(call, method+" ") { + n++ + } + } + return n +} + +type cachedBillingUserRepo struct { + service.UserRepository + balance float64 +} + +func (r *cachedBillingUserRepo) GetByID(_ context.Context, id int64) (*service.User, error) { + return &service.User{ID: id, Balance: r.balance}, nil +} + +func (r *cachedBillingUserRepo) DeductBalance(context.Context, int64, float64) error { return nil } + +type cachedBillingUsageRepo struct { + service.UsageLogRepository + mu sync.Mutex + logs []*service.UsageLog +} + +func (r *cachedBillingUsageRepo) Create(_ context.Context, log *service.UsageLog) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.logs = append(r.logs, log) + return true, nil +} + +func (r *cachedBillingUsageRepo) first() *service.UsageLog { + r.mu.Lock() + defer r.mu.Unlock() + return r.logs[0] +} + +func (r *cachedBillingUsageRepo) totals() []float64 { + r.mu.Lock() + defer r.mu.Unlock() + out := make([]float64, 0, len(r.logs)) + for _, log := range r.logs { + out = append(out, log.TotalCost) + } + return out +} + +type cachedBillingEnv struct { + h *GatewayHandler + repo *cachedBillingRepo + upstream *cachedBillingUpstream + usage *cachedBillingUsageRepo + apiKey *service.APIKey + group *service.Group + // accounts 是调度快照桩直接返回的账号对象,测试可改其凭据。 + accounts map[int64]*service.Account +} + +func newCachedBillingEnv(t *testing.T, balance float64, accountIDs ...int64) *cachedBillingEnv { + t.Helper() + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "model_pricing.json"), []byte(fmt.Sprintf(`{"gemini-2.5-pro":{ + "litellm_provider":"gemini","mode":"chat","input_cost_per_token":%g,"output_cost_per_token":0.00001, + "cache_storage_cost_per_token_per_hour":%g},"gemini-alias":{ + "litellm_provider":"gemini","mode":"chat","input_cost_per_token":%g,"output_cost_per_token":0.00001, + "cache_storage_cost_per_token_per_hour":%g}}`, + cachedBillingInputPrice, cachedBillingStoragePrice, cachedBillingInputPrice, cachedBillingAliasStoragePrice)), 0o644)) + cfg := &config.Config{} + cfg.Pricing.DataDir = dir + cfg.Pricing.UpdateIntervalHours = 100000 + cfg.Default.RateMultiplier = 1 + pricing := service.NewPricingService(cfg, nil) + require.NoError(t, pricing.Initialize()) + billing := service.NewBillingService(cfg, pricing) + + groupID := int64(42) + group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformGemini, Status: service.StatusActive, RateMultiplier: 1} + accounts := map[int64]*service.Account{} + var scheduled []*service.Account + for _, id := range accountIDs { + account := &service.Account{ID: id, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "k"}, Status: service.StatusActive, Schedulable: true, + Concurrency: 5, Priority: 1, AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}}} + accounts[id] = account + scheduled = append(scheduled, account) + } + userRepo := &cachedBillingUserRepo{balance: balance} + usage := &cachedBillingUsageRepo{} + bcs := service.NewBillingCacheService(nil, userRepo, nil, nil, nil, nil, cfg, nil) + t.Cleanup(bcs.Stop) + snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: scheduled}, nil, nil, nil, nil) + gw := service.NewGatewayService(nil, &fakeGroupRepo{group: group}, usage, nil, userRepo, nil, nil, nil, cfg, snapshot, nil, + billing, nil, &service.BillingCacheService{}, nil, nil, &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + upstream := &cachedBillingUpstream{} + compat := service.NewGeminiMessagesCompatService(&cachedBillingAccountRepo{accounts: accounts}, nil, nil, nil, nil, nil, upstream, nil, cfg) + repo := &cachedBillingRepo{records: map[string]*service.GeminiCachedContent{}, mutations: map[int64]cachedBillingMutation{}} + h := &GatewayHandler{ + gatewayService: gw, + billingCacheService: bcs, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatNone, 0), + geminiCachedContentService: service.NewGeminiCachedContentService(repo, compat, cfg), + } + apiKey := &service.APIKey{ID: 7, UserID: 3, GroupID: &groupID, Group: group, Status: service.StatusActive, + User: &service.User{ID: 3, Concurrency: 10, Balance: balance}} + return &cachedBillingEnv{h: h, repo: repo, upstream: upstream, usage: usage, apiKey: apiKey, group: group, accounts: accounts} +} + +// TestGeminiExplicitCacheExclusions_FiltersUnsupportedAccountsFromSnapshot 候选过滤直接按快照里的凭据判定: +// 第三方地址且未声明上游显式缓存的 Key 账号在选号前就被排除,官方地址与声明了上游显式缓存的账号保留。 +func TestGeminiExplicitCacheExclusions_FiltersUnsupportedAccountsFromSnapshot(t *testing.T) { + env := newCachedBillingEnv(t, 500, 900, 901, 902) + env.accounts[901].Credentials["base_url"] = "https://third.example.com" + env.accounts[902].Credentials["base_url"] = "https://gw.example.com" + env.accounts[902].Credentials[service.GeminiExplicitCacheUpstreamCredentialKey] = true + + groupID := env.group.ID + excluded, err := env.h.gatewayService.GeminiExplicitCacheExclusions(context.Background(), &groupID, 0) + require.NoError(t, err) + require.Equal(t, map[int64]struct{}{901: {}}, excluded) + + excluded, err = env.h.gatewayService.GeminiExplicitCacheExclusions(context.Background(), &groupID, 902) + require.NoError(t, err) + require.Equal(t, map[int64]struct{}{900: {}, 901: {}}, excluded, "绑定缓存的请求只保留持有账号") +} + +func (e *cachedBillingEnv) serve(method, target, body string, params gin.Params, call func(*gin.Context)) *httptest.ResponseRecorder { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + req := httptest.NewRequest(method, target, strings.NewReader(body)) + c.Request = req.WithContext(context.WithValue(req.Context(), ctxkey.Group, e.group)) + c.Params = params + c.Set(string(middleware.ContextKeyAPIKey), e.apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: e.apiKey.UserID, Concurrency: 10}) + call(c) + return rec +} + +// waitForUsage 等待异步计费任务落库(无 worker 池时同步执行,直接返回)。 +func (e *cachedBillingEnv) waitForUsage(t *testing.T, n int) []float64 { + t.Helper() + require.Eventually(t, func() bool { return len(e.usage.totals()) >= n }, time.Second, 10*time.Millisecond) + return e.usage.totals() +} + +func (e *cachedBillingEnv) create() *httptest.ResponseRecorder { + return e.serve(http.MethodPost, "/v1beta/cachedContents", + `{"model":"models/gemini-2.5-pro","ttl":"86400s","contents":[{"role":"user","parts":[{"text":"doc"}]}]}`, + nil, e.h.GeminiCachedContentsCreate) +} + +func (e *cachedBillingEnv) seed(expire time.Time) { + e.repo.records["abc"] = &service.GeminiCachedContent{ + ID: 100, PublicID: "abc", UserID: 3, APIKeyID: 7, GroupID: 42, AccountID: 900, + UpstreamName: "cachedContents/up1", Model: "gemini-2.5-pro", UpstreamModel: "models/gemini-2.5-pro", + TotalTokenCount: cachedBillingTokens, ExpireTime: expire, + } +} + +func (e *cachedBillingEnv) patch() *httptest.ResponseRecorder { + return e.serve(http.MethodPatch, "/v1beta/cachedContents/abc?updateMask=ttl", `{"ttl":"86400s"}`, + gin.Params{{Key: "cacheID", Value: "abc"}}, e.h.GeminiCachedContentsPatch) +} + +// TestGeminiCachedContentsPatch_UsesChannelUsageRecordedAtCreate 延长有效期沿用创建时的渠道计费口径: +// 计费模型来源为请求模型时按别名定价,用量记录带渠道 ID。 +func TestGeminiCachedContentsPatch_UsesChannelUsageRecordedAtCreate(t *testing.T) { + env := newCachedBillingEnv(t, 500, 900) + env.seed(time.Now().Add(time.Hour)) + env.repo.records["abc"].ChannelUsage = service.ChannelUsageFields{ + ChannelID: 5, OriginalModel: "gemini-alias", ChannelMappedModel: "gemini-2.5-pro", + BillingModelSource: service.BillingModelSourceRequested, + } + + rec := env.patch() + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + totals := env.waitForUsage(t, 1) + require.Len(t, totals, 1) + require.InDelta(t, cachedBillingTokens*cachedBillingAliasStoragePrice*23, totals[0], 0.01, "按创建时的计费模型(请求模型别名)计存储费") + usageLog := env.usage.first() + require.NotNil(t, usageLog.ChannelID) + require.Equal(t, int64(5), *usageLog.ChannelID) + require.True(t, strings.HasPrefix(usageLog.RequestID, "gcache:patch:abc:"), usageLog.RequestID) +} + +func cachedBillingCreateBody(expire time.Time) string { + return fmt.Sprintf(`{"name":"cachedContents/up1","usageMetadata":{"totalTokenCount":%d},"expireTime":%q}`, + cachedBillingTokens, expire.UTC().Format(time.RFC3339Nano)) +} + +func TestGeminiCachedContentsCreate_ChargesInputAndStorage(t *testing.T) { + env := newCachedBillingEnv(t, 500, 900) + env.upstream.createBody = cachedBillingCreateBody(time.Now().Add(100 * time.Hour)) + + rec := env.create() + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + totals := env.waitForUsage(t, 1) + require.Len(t, totals, 1) + require.InDelta(t, cachedBillingTokens*cachedBillingInputPrice+cachedBillingTokens*cachedBillingStoragePrice*24, totals[0], 1e-9) + require.Len(t, env.repo.records, 1) + for _, record := range env.repo.records { + require.False(t, record.ExpireTime.After(time.Now().Add(24*time.Hour)), "本地到期时间不超过请求的有效期") + require.Equal(t, "gcache:create:"+record.PublicID, env.usage.first().RequestID, "费用行按缓存 ID 可检索") + } +} + +func TestGeminiCachedContentsCreate_UnaffordableStorageDeletesUpstreamAndBillsInputOnly(t *testing.T) { + env := newCachedBillingEnv(t, 1, 900) + env.upstream.createBody = cachedBillingCreateBody(time.Now().Add(24 * time.Hour)) + + rec := env.create() + require.NotEqual(t, http.StatusOK, rec.Code) + require.Contains(t, rec.Body.String(), "error") + require.Equal(t, 1, env.upstream.methodCalls(http.MethodDelete), "删除已创建的上游缓存,避免产生存储费") + require.Empty(t, env.repo.records, "不登记缓存") + totals := env.waitForUsage(t, 1) + require.Len(t, totals, 1) + require.InDelta(t, cachedBillingTokens*cachedBillingInputPrice, totals[0], 1e-9, "只收已发生的缓存 token 输入费") +} + +func TestGeminiCachedContentsCreate_UnusableUpstreamResponseCleansUpWithoutRetry(t *testing.T) { + env := newCachedBillingEnv(t, 500, 900, 901) + env.upstream.createBody = `{"name":"cachedContents/up1","expireTime":"2099-01-01T00:00:00Z"}` + + rec := env.create() + require.Equal(t, http.StatusBadGateway, rec.Code) + require.Equal(t, 1, env.upstream.methodCalls(http.MethodPost), "不换号重建") + require.Equal(t, 1, env.upstream.methodCalls(http.MethodDelete), "删除已创建的上游缓存") + require.Empty(t, env.repo.records) + require.Empty(t, env.usage.totals()) +} + +func (e *cachedBillingEnv) patchTTL(id, ttl string) *httptest.ResponseRecorder { + return e.serve(http.MethodPatch, "/v1beta/cachedContents/"+id+"?updateMask=ttl", fmt.Sprintf(`{"ttl":%q}`, ttl), + gin.Params{{Key: "cacheID", Value: id}}, e.h.GeminiCachedContentsPatch) +} + +// requireTTLNear 断言发往上游的 ttl("Ns")与 want 相差不超过 5 秒。 +func requireTTLNear(t *testing.T, ttl string, want time.Duration) { + t.Helper() + seconds, err := strconv.ParseInt(strings.TrimSuffix(ttl, "s"), 10, 64) + require.NoError(t, err, ttl) + require.InDelta(t, want.Seconds(), float64(seconds), 5, ttl) +} + +// 同一缓存的修改串行执行:第一个 PATCH 的上游调用返回前,第二个 PATCH 直接得到 409 且不调用上游, +// 本地到期时间与上游最后生效的修改一致,只按第一个 PATCH 实际推进的时长收费。 +func TestGeminiCachedContentsPatch_ConcurrentUpdateConflictsAndKeepsUpstreamInSync(t *testing.T) { + env := newCachedBillingEnv(t, 1000, 900) + env.seed(time.Now().Add(time.Hour)) + env.upstream.beforePost = func(n int) { + if n == 1 { + rec := env.patchTTL("abc", "86400s") + require.Equal(t, http.StatusConflict, rec.Code, rec.Body.String()) + require.Contains(t, rec.Body.String(), `"ABORTED"`) + } + } + + rec := env.patchTTL("abc", "7200s") + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch), "冲突的修改不调用上游") + require.WithinDuration(t, time.Now().Add(2*time.Hour), env.repo.records["abc"].ExpireTime, 5*time.Second, "本地到期时间与上游一致") + require.False(t, env.repo.pendingMutation(100)) + totals := env.waitForUsage(t, 1) + require.Len(t, totals, 1) + require.InDelta(t, cachedBillingTokens*cachedBillingStoragePrice, totals[0], cachedBillingTokens*cachedBillingStoragePrice*time.Minute.Hours(), "只收推进的 1 小时") +} + +// 上游已修改但本地写回失败:不计费并保留修改意图;租约内的修改返回 409, +// 租约过期后后台恢复把上游有效期回滚到修改前的到期时间并清除意图。 +func TestGeminiCachedContentsPatch_CommitFailureRollsBackUpstreamWithoutCharge(t *testing.T) { + env := newCachedBillingEnv(t, 1000, 900) + baseline := time.Now().Add(time.Hour) + env.seed(baseline) + env.repo.failCommit = true + + require.Equal(t, http.StatusInternalServerError, env.patch().Code) + require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch)) + require.True(t, env.repo.pendingMutation(100), "上游可能已修改:保留修改意图") + require.Empty(t, env.usage.totals(), "未提交的修改不收费") + + env.repo.failCommit = false + require.Equal(t, http.StatusConflict, env.patch().Code, "租约内的修改被拒绝") + require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch)) + + env.repo.expireLease(100) + recovered, err := env.h.geminiCachedContentService.RecoverStaleMutations(context.Background()) + require.NoError(t, err) + require.Equal(t, 1, recovered) + require.Equal(t, 2, env.upstream.methodCalls(http.MethodPatch)) + requireTTLNear(t, env.upstream.patchTTLs[1], time.Until(baseline)) + require.False(t, env.repo.pendingMutation(100)) + require.True(t, env.repo.records["abc"].ExpireTime.Equal(baseline), "本地到期时间保持修改前的值") + require.Empty(t, env.usage.totals()) +} + +// 租约过期的遗留修改意图在下一次修改前先回滚,随后的修改按修改前的到期时间计费。 +func TestGeminiCachedContentsPatch_StaleMutationRolledBackBeforeNextUpdate(t *testing.T) { + env := newCachedBillingEnv(t, 1000, 900) + baseline := time.Now().Add(time.Hour) + env.seed(baseline) + env.repo.failCommit = true + require.Equal(t, http.StatusInternalServerError, env.patch().Code) + env.repo.failCommit = false + env.repo.expireLease(100) + + rec := env.patch() + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.Equal(t, 3, env.upstream.methodCalls(http.MethodPatch), "失败的修改、回滚、本次修改") + requireTTLNear(t, env.upstream.patchTTLs[1], time.Until(baseline)) + require.Equal(t, "86400s", env.upstream.patchTTLs[2]) + totals := env.waitForUsage(t, 1) + require.Len(t, totals, 1) + require.InDelta(t, cachedBillingTokens*cachedBillingStoragePrice*23, totals[0], 0.01) +} + +// 上游结果未知(传输层错误)时保留修改意图等待回滚;上游明确拒绝时清除修改意图。两种情况都不收费。 +func TestGeminiCachedContentsPatch_MutationKeptOnlyWhenUpstreamOutcomeUnknown(t *testing.T) { + t.Run("transport error", func(t *testing.T) { + env := newCachedBillingEnv(t, 1000, 900) + env.seed(time.Now().Add(time.Hour)) + env.upstream.transportErrors = map[string]error{http.MethodPatch: errors.New("connection reset")} + + require.Equal(t, http.StatusBadGateway, env.patch().Code) + require.True(t, env.repo.pendingMutation(100)) + require.Empty(t, env.usage.totals()) + }) + t.Run("upstream rejected", func(t *testing.T) { + env := newCachedBillingEnv(t, 1000, 900) + env.seed(time.Now().Add(time.Hour)) + env.upstream.failures = map[string]cachedBillingUpstreamFailure{http.MethodPatch: {status: http.StatusBadRequest, + body: `{"error":{"code":400,"message":"invalid ttl","status":"INVALID_ARGUMENT"}}`}} + + require.Equal(t, http.StatusBadRequest, env.patch().Code) + require.False(t, env.repo.pendingMutation(100)) + require.Empty(t, env.usage.totals()) + }) +} + +// 修改前的到期时间已过:恢复时删除上游缓存与本地记录。 +func TestGeminiCachedContentMutationRecovery_DeletesUpstreamWhenBaselineExpired(t *testing.T) { + env := newCachedBillingEnv(t, 1000, 900) + env.seed(time.Now().Add(-time.Minute)) + env.repo.mutations[100] = cachedBillingMutation{token: "stale", leaseUntil: time.Now().Add(-time.Second)} + + recovered, err := env.h.geminiCachedContentService.RecoverStaleMutations(context.Background()) + require.NoError(t, err) + require.Equal(t, 1, recovered) + require.Equal(t, 1, env.upstream.methodCalls(http.MethodDelete)) + require.Zero(t, env.upstream.methodCalls(http.MethodPatch)) + require.Equal(t, []int64{100}, env.repo.deleted) +} + +// cachedBillingReservationCache 是启用在途预留时的计费缓存桩:余额与订阅用量取固定值,各维度预留按 key 记账。 +type cachedBillingReservationCache struct { + service.BillingCache + mu sync.Mutex + balance float64 + sub *service.SubscriptionCacheData + reserved map[string]map[string]float64 +} + +func (c *cachedBillingReservationCache) GetUserBalance(context.Context, int64) (float64, error) { + return c.balance, nil +} + +func (c *cachedBillingReservationCache) GetSubscriptionCache(context.Context, int64, int64) (*service.SubscriptionCacheData, error) { + return c.sub, nil +} + +func (c *cachedBillingReservationCache) reserveLocked(key, requestID string, amount float64) float64 { + if c.reserved == nil { + c.reserved = map[string]map[string]float64{} + } + if c.reserved[key] == nil { + c.reserved[key] = map[string]float64{} + } + others := 0.0 + for _, v := range c.reserved[key] { + others += v + } + c.reserved[key][requestID] = amount + return others +} + +func (c *cachedBillingReservationCache) ReserveInflightBalance(_ context.Context, userID int64, requestID string, amount, balance float64, _ time.Duration) (bool, float64, error) { + c.mu.Lock() + defer c.mu.Unlock() + key := fmt.Sprintf("user:%d", userID) + others := c.reserveLocked(key, requestID, amount) + if len(c.reserved[key]) > 1 && balance-others < amount { + delete(c.reserved[key], requestID) + return false, others, nil + } + return true, others, nil +} + +func (c *cachedBillingReservationCache) ReleaseInflightBalance(_ context.Context, userID int64, requestID string) error { + c.mu.Lock() + defer c.mu.Unlock() + delete(c.reserved[fmt.Sprintf("user:%d", userID)], requestID) + return nil +} + +func (c *cachedBillingReservationCache) ReserveInflightScope(_ context.Context, scope, requestID string, amount float64, _ time.Duration) (float64, error) { + c.mu.Lock() + defer c.mu.Unlock() + return c.reserveLocked(scope, requestID, amount), nil +} + +func (c *cachedBillingReservationCache) ReleaseInflightScope(_ context.Context, scope, requestID string) error { + c.mu.Lock() + defer c.mu.Unlock() + delete(c.reserved[scope], requestID) + return nil +} + +func enableCachedBillingReservations(t *testing.T, env *cachedBillingEnv, cache *cachedBillingReservationCache) { + t.Helper() + cfg := &config.Config{} + cfg.Billing.InflightReservation.Enabled = true + bcs := service.NewBillingCacheService(cache, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(bcs.Stop) + env.h.billingCacheService = bcs +} + +// 确定金额的续期费按 API Key 与余额维度预留:第一笔续期(约 $103.5)尚未入账时, +// 第二个缓存的续期超出 Key 剩余额度或余额,在调用上游前被拒绝。 +func TestGeminiCachedContentsPatch_UnsettledChargeHoldsKeyQuotaAndBalance(t *testing.T) { + for _, tc := range []struct { + name string + balance, quota float64 + }{ + {name: "api key quota", balance: 1000, quota: 110}, + {name: "balance", balance: 110}, + } { + t.Run(tc.name, func(t *testing.T) { + env := newCachedBillingEnv(t, tc.balance, 900) + env.seed(time.Now().Add(time.Hour)) + second := *env.repo.records["abc"] + second.ID, second.PublicID, second.UpstreamName = 101, "def", "cachedContents/up2" + env.repo.records["def"] = &second + env.apiKey.Quota = tc.quota + enableCachedBillingReservations(t, env, &cachedBillingReservationCache{balance: tc.balance}) + env.upstream.beforePost = func(n int) { + if n == 1 { + rec := env.patchTTL("def", "86400s") + require.NotEqual(t, http.StatusOK, rec.Code, rec.Body.String()) + } + } + + require.Equal(t, http.StatusOK, env.patch().Code) + require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch), "第二笔续期没有到达上游") + }) + } +} + +// 订阅模式的确定金额费用按订阅维度预留:第一笔未入账时第二笔超出日剩余额度被拒绝,释放后放行。 +func TestReserveGeminiCachedContentCharge_UnsettledChargeHoldsSubscriptionHeadroom(t *testing.T) { + env := newCachedBillingEnv(t, 1000, 900) + limit := 110.0 + env.group.SubscriptionType = service.SubscriptionTypeSubscription + env.group.DailyLimitUSD = &limit + enableCachedBillingReservations(t, env, &cachedBillingReservationCache{balance: 1000, + sub: &service.SubscriptionCacheData{Status: service.SubscriptionStatusActive, ExpiresAt: time.Now().Add(time.Hour)}}) + sub := &service.UserSubscription{ID: 1, UserID: env.apiKey.UserID, GroupID: env.group.ID, Status: service.SubscriptionStatusActive, + ExpiresAt: time.Now().Add(time.Hour)} + reserve := func() (func(), error) { + var done func() + var err error + env.serve(http.MethodPatch, "/", `{}`, nil, func(c *gin.Context) { + done, err = env.h.reserveGeminiCachedContentCharge(c, env.apiKey, sub, 103.5) + }) + return done, err + } + + firstDone, err := reserve() + require.NoError(t, err) + _, err = reserve() + require.ErrorIs(t, err, service.ErrDailyLimitExceeded) + firstDone() + secondDone, err := reserve() + require.NoError(t, err) + secondDone() +} + +func TestGeminiCachedContentsPatch_UnaffordableExtensionRejectedBeforeUpstream(t *testing.T) { + env := newCachedBillingEnv(t, 1, 900) + env.seed(time.Now().Add(time.Hour)) + + rec := env.patch() + require.NotEqual(t, http.StatusOK, rec.Code) + require.Zero(t, env.upstream.methodCalls(http.MethodPatch), "余额不足以支付延长部分时不调用上游") + require.Empty(t, env.usage.totals()) +} + +// 上游对缓存不存在的响应:AI Studio 403;Vertex 缓存资源接口 404,文案含上游缓存数字 ID。 +var cachedBillingUpstreamNotFoundCases = []struct { + name string + failure cachedBillingUpstreamFailure +}{ + {name: "ai studio 403", failure: cachedBillingUpstreamFailure{status: http.StatusForbidden, + body: `{"error":{"code":403,"message":"CachedContent not found (or permission denied)","status":"PERMISSION_DENIED"}}`}}, + {name: "vertex 404", failure: cachedBillingUpstreamFailure{status: http.StatusNotFound, + body: `{"error":{"code":404,"message":"Cached content 8079767076522164224 is not found.","status":"NOT_FOUND"}}`}}, +} + +func TestGeminiCachedContentsPatch_UpstreamNotFoundForgetsAndReturnsStandardForbidden(t *testing.T) { + for _, tc := range cachedBillingUpstreamNotFoundCases { + t.Run(tc.name, func(t *testing.T) { + env := newCachedBillingEnv(t, 1000, 900) + env.seed(time.Now().Add(time.Hour)) + env.upstream.failures = map[string]cachedBillingUpstreamFailure{http.MethodPatch: tc.failure} + + rec := env.patch() + require.Equal(t, http.StatusForbidden, rec.Code) + require.Equal(t, service.GeminiCachedContentNotFoundResponse, rec.Body.String()) + require.NotContains(t, rec.Body.String(), "8079767076522164224", "不应暴露上游缓存 ID") + require.Equal(t, []int64{100}, env.repo.deleted, "上游已不存在的缓存应从本地移除") + require.Empty(t, env.usage.totals(), "上游未延长不收费") + }) + } +} + +func TestGeminiCachedContentsDelete_UpstreamNotFoundStillForgets(t *testing.T) { + for _, tc := range cachedBillingUpstreamNotFoundCases { + t.Run(tc.name, func(t *testing.T) { + env := newCachedBillingEnv(t, 1000, 900) + env.seed(time.Now().Add(time.Hour)) + env.upstream.failures = map[string]cachedBillingUpstreamFailure{http.MethodDelete: tc.failure} + + rec := env.serve(http.MethodDelete, "/v1beta/cachedContents/abc", "", + gin.Params{{Key: "cacheID", Value: "abc"}}, env.h.GeminiCachedContentsDelete) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.JSONEq(t, `{}`, rec.Body.String()) + require.Equal(t, []int64{100}, env.repo.deleted) + }) + } +} + +// 持有账号暂时不支持显式缓存(能力被关闭)时,恢复流程不能把修改意图当作已回滚而清除; +// 能力恢复后再回滚上游并清除意图。 +func TestGeminiCachedContentMutationRecovery_KeepsIntentWhileAccountCannotCache(t *testing.T) { + env := newCachedBillingEnv(t, 1000, 900) + env.accounts[900].Credentials["base_url"] = "https://gw.example.com" + env.accounts[900].Credentials[service.GeminiExplicitCacheUpstreamCredentialKey] = true + baseline := time.Now().Add(time.Hour) + env.seed(baseline) + env.repo.failCommit = true + require.Equal(t, http.StatusInternalServerError, env.patch().Code) + require.True(t, env.repo.pendingMutation(100)) + require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch)) + env.repo.failCommit = false + env.repo.expireLease(100) + + env.accounts[900].Credentials[service.GeminiExplicitCacheUpstreamCredentialKey] = false + recovered, err := env.h.geminiCachedContentService.RecoverStaleMutations(context.Background()) + require.Error(t, err, "账号暂不支持缓存时恢复失败") + require.Zero(t, recovered) + require.True(t, env.repo.pendingMutation(100), "未回滚上游前保留修改意图") + require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch), "不改动上游") + require.Empty(t, env.repo.deleted) + + env.accounts[900].Credentials[service.GeminiExplicitCacheUpstreamCredentialKey] = true + env.repo.expireLease(100) + recovered, err = env.h.geminiCachedContentService.RecoverStaleMutations(context.Background()) + require.NoError(t, err) + require.Equal(t, 1, recovered) + require.Equal(t, 2, env.upstream.methodCalls(http.MethodPatch)) + requireTTLNear(t, env.upstream.patchTTLs[1], time.Until(baseline)) + require.False(t, env.repo.pendingMutation(100)) + require.True(t, env.repo.records["abc"].ExpireTime.Equal(baseline)) + require.Empty(t, env.usage.totals()) +} + +// 持有账号长期不支持显式缓存,且修改前到期时间加上单次最长有效期都已过去:上游缓存必已自行过期, +// 恢复流程不再保留意图,直接移除本地记录。 +func TestGeminiCachedContentMutationRecovery_AbandonsIntentOnceUpstreamMustHaveExpired(t *testing.T) { + env := newCachedBillingEnv(t, 1000, 900) + env.accounts[900].Credentials["base_url"] = "https://gw.example.com" + env.accounts[900].Credentials[service.GeminiExplicitCacheUpstreamCredentialKey] = true + env.seed(time.Now().Add(time.Hour)) + env.repo.failCommit = true + require.Equal(t, http.StatusInternalServerError, env.patch().Code) + env.repo.failCommit = false + env.repo.expireLease(100) + env.accounts[900].Credentials[service.GeminiExplicitCacheUpstreamCredentialKey] = false + + // 修改前到期时间 + 24h 上限 + 1h 容忍仍未过去:保留意图。 + env.repo.records["abc"].ExpireTime = time.Now().Add(-20 * time.Hour) + recovered, err := env.h.geminiCachedContentService.RecoverStaleMutations(context.Background()) + require.Error(t, err) + require.Zero(t, recovered) + require.True(t, env.repo.pendingMutation(100)) + require.Empty(t, env.repo.deleted) + + env.repo.expireLease(100) + env.repo.records["abc"].ExpireTime = time.Now().Add(-26 * time.Hour) + recovered, err = env.h.geminiCachedContentService.RecoverStaleMutations(context.Background()) + require.NoError(t, err) + require.Equal(t, 1, recovered) + require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch), "不改动上游") + require.Zero(t, env.upstream.methodCalls(http.MethodDelete)) + require.Equal(t, []int64{100}, env.repo.deleted) + require.Empty(t, env.usage.totals()) + + recovered, err = env.h.geminiCachedContentService.RecoverStaleMutations(context.Background()) + require.NoError(t, err) + require.Zero(t, recovered, "作废的记录不再被选中") +} + +// 作废判定的边界:默认上限 24h 加 1h 容忍;配置上限低于 24h 时仍按 24h 兜底。 +func TestGeminiCachedContentMutationRecovery_AbandonBoundary(t *testing.T) { + disableCache := func(env *cachedBillingEnv) { + env.accounts[900].Credentials["base_url"] = "https://gw.example.com" + env.accounts[900].Credentials[service.GeminiExplicitCacheUpstreamCredentialKey] = false + } + t.Run("within grace keeps intent", func(t *testing.T) { + env := newCachedBillingEnv(t, 1000, 900) + env.seed(time.Now().Add(-25*time.Hour + time.Minute)) + env.repo.mutations[100] = cachedBillingMutation{token: "stale", leaseUntil: time.Now().Add(-time.Second)} + disableCache(env) + + recovered, err := env.h.geminiCachedContentService.RecoverStaleMutations(context.Background()) + require.Error(t, err) + require.Zero(t, recovered) + require.True(t, env.repo.pendingMutation(100)) + require.Empty(t, env.repo.deleted) + }) + t.Run("configured max ttl below default still waits a day", func(t *testing.T) { + env := newCachedBillingEnv(t, 1000, 900) + env.seed(time.Now().Add(-12 * time.Hour)) + env.repo.mutations[100] = cachedBillingMutation{token: "stale", leaseUntil: time.Now().Add(-time.Second)} + disableCache(env) + cfg := &config.Config{} + cfg.Gateway.GeminiCachedContentMaxTTLSeconds = 3600 + compat := service.NewGeminiMessagesCompatService(&cachedBillingAccountRepo{accounts: env.accounts}, nil, nil, nil, nil, nil, env.upstream, nil, cfg) + svc := service.NewGeminiCachedContentService(env.repo, compat, cfg) + + recovered, err := svc.RecoverStaleMutations(context.Background()) + require.Error(t, err) + require.Zero(t, recovered) + require.True(t, env.repo.pendingMutation(100)) + + env.repo.expireLease(100) + env.repo.records["abc"].ExpireTime = time.Now().Add(-26 * time.Hour) + recovered, err = svc.RecoverStaleMutations(context.Background()) + require.NoError(t, err) + require.Equal(t, 1, recovered) + require.Equal(t, []int64{100}, env.repo.deleted) + }) +} + +// 持有账号可用但上游回滚持续失败(如 Key 已失效):上游缓存必已自行过期后不再重试,移除本地记录。 +func TestGeminiCachedContentMutationRecovery_AbandonsIntentWhenRollbackKeepsFailing(t *testing.T) { + env := newCachedBillingEnv(t, 1000, 900) + env.seed(time.Now().Add(-time.Minute)) + env.repo.mutations[100] = cachedBillingMutation{token: "stale", leaseUntil: time.Now().Add(-time.Second)} + env.upstream.failures = map[string]cachedBillingUpstreamFailure{http.MethodDelete: {status: http.StatusUnauthorized, + body: `{"error":{"code":401,"message":"API key not valid","status":"UNAUTHENTICATED"}}`}} + + recovered, err := env.h.geminiCachedContentService.RecoverStaleMutations(context.Background()) + require.Error(t, err, "上游缓存可能仍存活:保留意图等待重试") + require.Zero(t, recovered) + require.Equal(t, 1, env.upstream.methodCalls(http.MethodDelete)) + require.True(t, env.repo.pendingMutation(100)) + require.Empty(t, env.repo.deleted) + + env.repo.expireLease(100) + env.repo.records["abc"].ExpireTime = time.Now().Add(-26 * time.Hour) + recovered, err = env.h.geminiCachedContentService.RecoverStaleMutations(context.Background()) + require.NoError(t, err) + require.Equal(t, 1, recovered) + require.Equal(t, 2, env.upstream.methodCalls(http.MethodDelete), "账号可用时仍先尝试回滚") + require.Equal(t, []int64{100}, env.repo.deleted) + require.Empty(t, env.usage.totals()) +} + +// 持有账号已删除时没有凭据可回滚上游:恢复流程移除本地记录并清除意图,不再重试。 +func TestGeminiCachedContentMutationRecovery_ForgetsRecordWhenAccountDeleted(t *testing.T) { + env := newCachedBillingEnv(t, 1000, 900) + env.seed(time.Now().Add(time.Hour)) + env.repo.failCommit = true + require.Equal(t, http.StatusInternalServerError, env.patch().Code) + require.True(t, env.repo.pendingMutation(100)) + env.repo.failCommit = false + env.repo.expireLease(100) + + delete(env.accounts, 900) + recovered, err := env.h.geminiCachedContentService.RecoverStaleMutations(context.Background()) + require.NoError(t, err) + require.Equal(t, 1, recovered) + require.Equal(t, 1, env.upstream.methodCalls(http.MethodPatch), "无凭据,不改动上游") + require.Zero(t, env.upstream.methodCalls(http.MethodDelete)) + require.Equal(t, []int64{100}, env.repo.deleted, "本地记录作废") + require.Empty(t, env.usage.totals()) + require.Equal(t, http.StatusForbidden, env.serve(http.MethodGet, "/v1beta/cachedContents/abc", "", gin.Params{{Key: "cacheID", Value: "abc"}}, env.h.GeminiCachedContentsGet).Code, "作废的记录对客户端不可见") + + recovered, err = env.h.geminiCachedContentService.RecoverStaleMutations(context.Background()) + require.NoError(t, err) + require.Zero(t, recovered, "不再重复处理") +} diff --git a/backend/internal/handler/gemini_cached_contents_handler.go b/backend/internal/handler/gemini_cached_contents_handler.go new file mode 100644 index 000000000..bd5136481 --- /dev/null +++ b/backend/internal/handler/gemini_cached_contents_handler.go @@ -0,0 +1,848 @@ +package handler + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/http" + "strconv" + "strings" + "time" + + pkghttputil "github.com/MACOS-DO/sub4api/internal/pkg/httputil" + "github.com/MACOS-DO/sub4api/internal/pkg/ip" + "github.com/MACOS-DO/sub4api/internal/pkg/logger" + "github.com/MACOS-DO/sub4api/internal/server/middleware" + "github.com/MACOS-DO/sub4api/internal/service" + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +// geminiCachedContentCreateMaxAttempts 限制创建缓存时实际发往上游的账号数。 +const geminiCachedContentCreateMaxAttempts = 3 + +// geminiCachedContentPersistTimeout 是上游操作完成后落库的超时;落库与客户端连接脱钩。 +const geminiCachedContentPersistTimeout = 15 * time.Second + +const geminiCachedContentUnavailableMessage = "The account holding this cached content is temporarily unavailable" + +// geminiCachedContentsPreamble 校验显式缓存管理接口的公共前置条件:gemini 分组、非 composite 分组、功能已装配。 +func (h *GatewayHandler) geminiCachedContentsPreamble(c *gin.Context, component string) (*service.APIKey, middleware.AuthSubject, *zap.Logger, bool) { + apiKey, ok := middleware.GetAPIKeyFromContext(c) + if !ok || apiKey == nil { + googleError(c, http.StatusUnauthorized, "Invalid API key") + return nil, middleware.AuthSubject{}, nil, false + } + authSubject, ok := middleware.GetAuthSubjectFromContext(c) + if !ok { + googleError(c, http.StatusInternalServerError, "User context not found") + return nil, middleware.AuthSubject{}, nil, false + } + if h.geminiCachedContentService == nil { + googlePlatformError(c, http.StatusNotFound, "Explicit context caching is not enabled") + return nil, middleware.AuthSubject{}, nil, false + } + if apiKey.Group == nil || apiKey.GroupID == nil || apiKey.Group.Platform == service.PlatformComposite { + googleError(c, http.StatusBadRequest, "Explicit context caching is not supported for this API key group") + return nil, middleware.AuthSubject{}, nil, false + } + if effectiveAPIKeyPlatform(c, apiKey) != service.PlatformGemini { + googleError(c, http.StatusBadRequest, "API key group platform is not gemini") + return nil, middleware.AuthSubject{}, nil, false + } + reqLog := requestLogger( + c, + component, + zap.Int64("user_id", authSubject.UserID), + zap.Int64("api_key_id", apiKey.ID), + zap.Any("group_id", apiKey.GroupID), + ) + return apiKey, authSubject, reqLog, true +} + +func readGeminiCachedContentBody(c *gin.Context) ([]byte, bool) { + body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) + if err != nil { + if maxErr, ok := extractMaxBytesError(err); ok { + googleError(c, http.StatusRequestEntityTooLarge, buildBodyTooLargeMessage(maxErr.Limit)) + return nil, false + } + googleError(c, http.StatusBadRequest, "Failed to read request body") + return nil, false + } + if len(body) == 0 { + googleError(c, http.StatusBadRequest, "Request body is empty") + return nil, false + } + return body, true +} + +func (h *GatewayHandler) checkGeminiCachedContentBilling(c *gin.Context, reqLog *zap.Logger, apiKey *service.APIKey, subscription *service.UserSubscription) bool { + if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(c.Request.Context(), apiKey)); err != nil { + reqLog.Info("gemini.cached_content.billing_eligibility_check_failed", zap.Error(err)) + status, code, message, retryAfter := billingErrorDetails(err) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + googleErrorWithType(c, status, code, "", message) + return false + } + return true +} + +// GeminiCachedContentsCreate POST /v1beta/cachedContents +// 创建请求内一次性收取缓存 token 的输入费与整个有效期的存储费。 +func (h *GatewayHandler) GeminiCachedContentsCreate(c *gin.Context) { + apiKey, authSubject, reqLog, ok := h.geminiCachedContentsPreamble(c, "handler.gemini_v1beta.cached_contents.create") + if !ok { + return + } + svc := h.geminiCachedContentService + + body, ok := readGeminiCachedContentBody(c) + if !ok { + return + } + req, err := service.ParseGeminiCachedContentCreateRequest(body, svc.Now(), svc.MaxTTL()) + if err != nil { + googleError(c, http.StatusBadRequest, err.Error()) + return + } + modelName := req.Model + reqLog = reqLog.With(zap.String("model", modelName)) + + setOpsRequestContext(c, modelName, false) + setOpsEndpointContext(c, "", int16(service.RequestTypeFromLegacy(false, false))) + pricingCtx, pricingAt := service.WithGatewayTokenRequestPricing(c.Request.Context()) + c.Request = c.Request.WithContext(pricingCtx) + + if decision := h.checkSecurityAudit(c, reqLog, apiKey, authSubject, service.ContentModerationProtocolGemini, modelName, body); decision != nil && !decision.AllowNextStage { + googleSecurityAuditError(c, decision) + return + } + + channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, modelName) + reqModel := modelName + if channelMapping.Mapped { + modelName = channelMapping.MappedModel + } + + subscription, _ := middleware.GetSubscriptionFromContext(c) + geminiConcurrency := NewConcurrencyHelper(h.concurrencyHelper.concurrencyService, SSEPingFormatNone, 0) + streamStarted := false + userReleaseFunc, err := geminiConcurrency.AcquireUserSlotWithWait(c, authSubject.UserID, authSubject.Concurrency, false, &streamStarted) + if err != nil { + reqLog.Warn("gemini.cached_content.user_slot_acquire_failed", zap.Error(err)) + googleConcurrencyError(c, err, "user") + return + } + userReleaseFunc = wrapReleaseOnDone(c.Request.Context(), userReleaseFunc) + if userReleaseFunc != nil { + defer userReleaseFunc() + } + + if !h.checkGeminiCachedContentBilling(c, reqLog, apiKey, subscription) { + return + } + inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(modelName, body)) + if err != nil { + reqLog.Info("gemini.cached_content.inflight_reservation_rejected", zap.Error(err)) + status, code, message, retryAfter := billingErrorDetails(err) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + googleErrorWithType(c, status, code, "", message) + return + } + defer inflightRelease() + + excluded, err := h.gatewayService.GeminiExplicitCacheExclusions(c.Request.Context(), apiKey.GroupID, 0) + if err != nil { + reqLog.Warn("gemini.cached_content.list_accounts_failed", zap.Error(err)) + googleError(c, http.StatusServiceUnavailable, "No available Gemini accounts support explicit context caching") + return + } + + var lastUpstreamErr *service.GeminiCachedContentUpstreamError + var ttlRejectedLimit time.Duration + for attempts := 0; attempts < geminiCachedContentCreateMaxAttempts; { + selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, "", modelName, excluded, "", int64(0)) + if err != nil { + if failoverClientGone(c) { + return + } + reqLog.Info("gemini.cached_content.account_select_exhausted", zap.Error(err)) + break + } + account := selection.Account + if !service.IsGeminiExplicitCacheAccount(account) { + if selection.Acquired && selection.ReleaseFunc != nil { + selection.ReleaseFunc() + } + excluded[account.ID] = struct{}{} + continue + } + ttl, ttlAllowed := req.TTLForAccount(account) + if !ttlAllowed { + if selection.Acquired && selection.ReleaseFunc != nil { + selection.ReleaseFunc() + } + excluded[account.ID] = struct{}{} + ttlRejectedLimit = max(ttlRejectedLimit, account.GeminiExplicitCacheUpstreamMaxTTL()) + continue + } + accountReleaseFunc, ok := h.acquireGeminiCachedContentAccountSlot(c, reqLog, geminiConcurrency, selection) + if !ok { + return + } + admissionCtx := service.ContextWithSelectionProfitGate(c.Request.Context(), selection) + latest, vetoed, reason := h.gatewayService.GatewayProfitControlVetoLatest(admissionCtx, account) + if vetoed { + accountReleaseFunc() + reqLog.Debug("gemini.cached_content.account_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason)) + excluded[account.ID] = struct{}{} + continue + } + account = latest + attempts++ + setOpsSelectedAccount(c, account.ID, account.Platform) + + mappedModel := account.GetMappedModel(modelName) + usageFields := clientRequestedUsageFields(c, channelMapping, reqModel, mappedModel) + if !h.gatewayService.CacheStoragePriced(c.Request.Context(), &service.RecordUsageInput{ + Result: &service.ForwardResult{Model: modelName, UpstreamModel: mappedModel, CacheStorageTokenHours: 1}, + APIKey: apiKey, + ChannelUsageFields: usageFields, + }) { + accountReleaseFunc() + googlePlatformError(c, http.StatusBadRequest, fmt.Sprintf("Explicit context caching is not available for model %s: storage pricing is not configured", modelName)) + return + } + upstreamModel, err := service.GeminiCachedContentUpstreamModelResource(account, mappedModel) + if err != nil { + accountReleaseFunc() + reqLog.Warn("gemini.cached_content.upstream_model_invalid", zap.Int64("account_id", account.ID), zap.Error(err)) + excluded[account.ID] = struct{}{} + continue + } + publicID, err := service.NewGeminiCachedContentPublicID() + if err != nil { + accountReleaseFunc() + googleError(c, http.StatusInternalServerError, "Failed to allocate cached content id") + return + } + + upstream, err := svc.CreateUpstream(c.Request.Context(), account, req, mappedModel, publicID, ttl) + accountReleaseFunc() + if err != nil { + var upErr *service.GeminiCachedContentUpstreamError + if errors.As(err, &upErr) { + reqLog.Info("gemini.cached_content.upstream_create_failed", zap.Int64("account_id", account.ID), zap.Int("status", upErr.StatusCode)) + if upErr.RetryableOnOtherAccount() { + lastUpstreamErr = upErr + excluded[account.ID] = struct{}{} + continue + } + h.writeGeminiCachedContentUpstreamError(c, upErr) + return + } + // 上游已返回成功但响应不可用:不换号重建,能识别出资源名时删除上游缓存。 + var malformed *service.GeminiCachedContentMalformedResponseError + if errors.As(err, &malformed) { + reqLog.Error("gemini.cached_content.upstream_create_malformed", zap.Int64("account_id", account.ID), zap.Error(err)) + if malformed.Name != "" { + h.cleanupGeminiCachedContentUpstream(reqLog, account, malformed.Name) + } + googleError(c, http.StatusBadGateway, "Upstream returned an invalid cached content response") + return + } + if failoverClientGone(c) { + return + } + reqLog.Warn("gemini.cached_content.upstream_create_error", zap.Int64("account_id", account.ID), zap.Error(err)) + excluded[account.ID] = struct{}{} + continue + } + + // 缓存 token 数在上游创建后才确定:按确定金额校验余额 / 额度并预留,不足时删除上游缓存, + // 只收取已发生的缓存 token 输入费。 + tokens := upstream.TotalTokenCount + storageTokenHours := service.GeminiCachedContentStorageTokenHours(tokens, ttl) + amount := h.gatewayService.QuoteUsageCost(c.Request.Context(), &service.RecordUsageInput{ + Result: &service.ForwardResult{ + Model: modelName, UpstreamModel: mappedModel, + Usage: service.ClaudeUsage{InputTokens: int(tokens)}, CacheStorageTokenHours: storageTokenHours, + }, + APIKey: apiKey, User: apiKey.User, Subscription: subscription, PricingAt: pricingAt, ChannelUsageFields: usageFields, + }) + inflightRelease() + chargeDone, err := h.reserveGeminiCachedContentCharge(c, apiKey, subscription, amount) + if err != nil { + reqLog.Info("gemini.cached_content.storage_charge_rejected", zap.Float64("amount", amount), zap.Error(err)) + h.cleanupGeminiCachedContentUpstream(reqLog, account, upstream.Name) + h.submitGeminiCachedContentUsage(c, apiKey, account, subscription, pricingAt, + service.GeminiCachedContentCreateUsageRequestID(publicID), modelName, mappedModel, int(tokens), 0, usageFields, body) + writeGeminiCachedContentBillingError(c, err) + return + } + defer chargeDone() + + expireTime := service.ClampGeminiCachedContentExpire(upstream.ExpireTime, svc.Now().Add(ttl)) + record := &service.GeminiCachedContent{ + PublicID: publicID, + UserID: authSubject.UserID, + APIKeyID: apiKey.ID, + GroupID: *apiKey.GroupID, + AccountID: account.ID, + UpstreamName: upstream.Name, + Model: modelName, + UpstreamModel: upstreamModel, + DisplayName: req.DisplayName, + TotalTokenCount: tokens, + ExpireTime: expireTime, + ChannelUsage: usageFields, + } + persistCtx, cancelPersist := geminiCachedContentPersistContext(c) + err = svc.Save(persistCtx, record) + cancelPersist() + if err != nil { + reqLog.Error("gemini.cached_content.save_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + h.cleanupGeminiCachedContentUpstream(reqLog, account, record.UpstreamName) + googleError(c, http.StatusInternalServerError, "Failed to persist cached content") + return + } + + h.submitGeminiCachedContentUsage(c, apiKey, account, subscription, pricingAt, + service.GeminiCachedContentCreateUsageRequestID(publicID), modelName, mappedModel, int(tokens), storageTokenHours, usageFields, body) + c.JSON(http.StatusOK, service.GeminiCachedContentView(record)) + return + } + + if lastUpstreamErr != nil { + h.writeGeminiCachedContentUpstreamError(c, lastUpstreamErr) + return + } + if ttlRejectedLimit > 0 { + googleError(c, http.StatusBadRequest, fmt.Sprintf("ttl exceeds the maximum allowed %ds by the upstream accounts", int64(ttlRejectedLimit.Seconds()))) + return + } + markOpsRoutingCapacityLimited(c) + googleError(c, http.StatusServiceUnavailable, "No available Gemini accounts support explicit context caching") +} + +// GeminiCachedContentsList GET /v1beta/cachedContents +// 只返回当前 API Key 在当前分组下仍有效的缓存,不透传上游 list(同一账号上其他租户的缓存不可见)。 +func (h *GatewayHandler) GeminiCachedContentsList(c *gin.Context) { + apiKey, _, reqLog, ok := h.geminiCachedContentsPreamble(c, "handler.gemini_v1beta.cached_contents.list") + if !ok { + return + } + pageSize := service.GeminiCachedContentListDefaultPageSize + if raw := strings.TrimSpace(c.Query("pageSize")); raw != "" { + n, err := strconv.Atoi(raw) + if err != nil || n < 0 { + googleError(c, http.StatusBadRequest, "pageSize must be a non-negative integer") + return + } + if n > 0 { + pageSize = min(n, service.GeminiCachedContentListMaxPageSize) + } + } + beforeID := int64(0) + if raw := strings.TrimSpace(c.Query("pageToken")); raw != "" { + id, ok := decodeGeminiCachedContentPageToken(raw) + if !ok { + googleError(c, http.StatusBadRequest, "Invalid pageToken") + return + } + beforeID = id + } + records, err := h.geminiCachedContentService.List(c.Request.Context(), apiKey.ID, *apiKey.GroupID, beforeID, pageSize+1) + if err != nil { + reqLog.Error("gemini.cached_content.list_failed", zap.Error(err)) + googleError(c, http.StatusInternalServerError, "Failed to list cached contents") + return + } + resp := gin.H{} + if len(records) > pageSize { + records = records[:pageSize] + resp["nextPageToken"] = encodeGeminiCachedContentPageToken(records[len(records)-1].ID) + } + if len(records) > 0 { + views := make([]map[string]any, 0, len(records)) + for _, record := range records { + views = append(views, service.GeminiCachedContentView(record)) + } + resp["cachedContents"] = views + } + c.JSON(http.StatusOK, resp) +} + +// GeminiCachedContentsGet GET /v1beta/cachedContents/:cacheID +func (h *GatewayHandler) GeminiCachedContentsGet(c *gin.Context) { + apiKey, _, reqLog, ok := h.geminiCachedContentsPreamble(c, "handler.gemini_v1beta.cached_contents.get") + if !ok { + return + } + record, ok := h.resolveGeminiCachedContentOrWrite(c, reqLog, apiKey, c.Param("cacheID")) + if !ok { + return + } + c.JSON(http.StatusOK, service.GeminiCachedContentView(record)) +} + +// GeminiCachedContentsPatch PATCH /v1beta/cachedContents/:cacheID +// 只允许修改有效期;延长部分在本次请求内按增量时长收取存储费,缩短不退费。 +// 同一缓存的修改串行执行:上游修改、本地写回与计费都在修改意图的租约内完成,并发的修改返回 409。 +// 上游结果未知或本地写回失败的修改不计费,租约过期后由恢复流程把上游有效期回滚到修改前的到期时间。 +func (h *GatewayHandler) GeminiCachedContentsPatch(c *gin.Context) { + apiKey, _, reqLog, ok := h.geminiCachedContentsPreamble(c, "handler.gemini_v1beta.cached_contents.patch") + if !ok { + return + } + svc := h.geminiCachedContentService + body, ok := readGeminiCachedContentBody(c) + if !ok { + return + } + record, ok := h.resolveGeminiCachedContentOrWrite(c, reqLog, apiKey, c.Param("cacheID")) + if !ok { + return + } + account, err := svc.BoundAccount(c.Request.Context(), record) + if err != nil { + reqLog.Error("gemini.cached_content.load_account_failed", zap.Int64("account_id", record.AccountID), zap.Error(err)) + googleError(c, http.StatusInternalServerError, "Failed to load cached content account") + return + } + if account == nil { + googleError(c, http.StatusServiceUnavailable, geminiCachedContentUnavailableMessage) + return + } + ttl, err := service.ParseGeminiCachedContentPatchRequest(body, c.Query("updateMask"), svc.Now(), svc.MaxTTLForAccount(account)) + if err != nil { + googleError(c, http.StatusBadRequest, err.Error()) + return + } + setOpsRequestContext(c, record.Model, false) + pricingCtx, pricingAt := service.WithGatewayTokenRequestPricing(c.Request.Context()) + c.Request = c.Request.WithContext(pricingCtx) + + subscription, _ := middleware.GetSubscriptionFromContext(c) + if extension := svc.Now().Add(ttl).Sub(record.ExpireTime); extension > 0 { + usage := &service.RecordUsageInput{ + Result: &service.ForwardResult{ + Model: record.Model, UpstreamModel: record.UpstreamModelID(), + CacheStorageTokenHours: service.GeminiCachedContentStorageTokenHours(record.TotalTokenCount, extension), + }, + APIKey: apiKey, User: apiKey.User, Subscription: subscription, PricingAt: pricingAt, + ChannelUsageFields: record.ChannelUsage, + } + if !h.gatewayService.CacheStoragePriced(c.Request.Context(), usage) { + googlePlatformError(c, http.StatusBadRequest, fmt.Sprintf("Explicit context caching is not available for model %s: storage pricing is not configured", record.Model)) + return + } + if !h.checkGeminiCachedContentBilling(c, reqLog, apiKey, subscription) { + return + } + chargeDone, err := h.reserveGeminiCachedContentCharge(c, apiKey, subscription, h.gatewayService.QuoteUsageCost(c.Request.Context(), usage)) + if err != nil { + reqLog.Info("gemini.cached_content.storage_charge_rejected", zap.Error(err)) + writeGeminiCachedContentBillingError(c, err) + return + } + defer chargeDone() + } + + setOpsSelectedAccount(c, account.ID, account.Platform) + mutation, err := svc.BeginMutation(c.Request.Context(), record) + if err != nil { + switch { + case errors.Is(err, service.ErrGeminiCachedContentNotFound): + googleError(c, http.StatusForbidden, service.GeminiCachedContentNotFoundMessage) + case errors.Is(err, service.ErrGeminiCachedContentMutationConflict): + reqLog.Info("gemini.cached_content.mutation_conflict", zap.Int64("account_id", account.ID), zap.Error(err)) + writeGeminiCachedContentMutationConflict(c) + default: + reqLog.Error("gemini.cached_content.begin_mutation_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + googleError(c, http.StatusInternalServerError, "Failed to update cached content") + } + return + } + upstream, err := svc.PatchUpstream(c.Request.Context(), account, record, ttl) + if err != nil { + var upErr *service.GeminiCachedContentUpstreamError + upstreamRejected := errors.As(err, &upErr) + if upstreamRejected || errors.Is(err, service.ErrGeminiCachedContentRequestNotSent) { + // 上游有效期未变:清除修改意图。 + persistCtx, cancelPersist := geminiCachedContentPersistContext(c) + if releaseErr := svc.ReleaseMutation(persistCtx, mutation); releaseErr != nil { + reqLog.Warn("gemini.cached_content.release_mutation_failed", zap.Error(releaseErr)) + } + cancelPersist() + } + if upstreamRejected { + if upErr.NotFound() { + if forgetErr := svc.Forget(c.Request.Context(), record); forgetErr != nil { + reqLog.Warn("gemini.cached_content.forget_failed", zap.Error(forgetErr)) + } + } + h.writeGeminiCachedContentUpstreamError(c, upErr) + return + } + reqLog.Warn("gemini.cached_content.upstream_patch_error", zap.Int64("account_id", account.ID), zap.Error(err)) + googleError(c, http.StatusBadGateway, "Upstream request failed") + return + } + expireTime := service.ClampGeminiCachedContentExpire(upstream.ExpireTime, svc.Now().Add(ttl)) + persistCtx, cancelPersist := geminiCachedContentPersistContext(c) + err = svc.CommitMutation(persistCtx, mutation, expireTime) + cancelPersist() + if err != nil { + reqLog.Error("gemini.cached_content.commit_mutation_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + if errors.Is(err, service.ErrGeminiCachedContentMutationConflict) { + writeGeminiCachedContentMutationConflict(c) + return + } + googleError(c, http.StatusInternalServerError, "Failed to persist cached content expiration") + return + } + // 提交前库中的到期时间一直是修改前的值:按本次实际推进的时长收费。 + if extended := expireTime.Sub(mutation.Baseline()); extended > 0 { + h.submitGeminiCachedContentUsage(c, apiKey, account, subscription, pricingAt, + service.GeminiCachedContentPatchUsageRequestID(record.PublicID), record.Model, record.UpstreamModelID(), 0, + service.GeminiCachedContentStorageTokenHours(record.TotalTokenCount, extended), record.ChannelUsage, body) + } + c.JSON(http.StatusOK, service.GeminiCachedContentView(record)) +} + +// GeminiCachedContentsDelete DELETE /v1beta/cachedContents/:cacheID +// 删除不退还已收取的存储费。 +func (h *GatewayHandler) GeminiCachedContentsDelete(c *gin.Context) { + apiKey, _, reqLog, ok := h.geminiCachedContentsPreamble(c, "handler.gemini_v1beta.cached_contents.delete") + if !ok { + return + } + svc := h.geminiCachedContentService + record, ok := h.resolveGeminiCachedContentOrWrite(c, reqLog, apiKey, c.Param("cacheID")) + if !ok { + return + } + account, err := svc.BoundAccount(c.Request.Context(), record) + if err != nil { + reqLog.Error("gemini.cached_content.load_account_failed", zap.Int64("account_id", record.AccountID), zap.Error(err)) + googleError(c, http.StatusInternalServerError, "Failed to load cached content account") + return + } + if account != nil { + setOpsSelectedAccount(c, account.ID, account.Platform) + if err := svc.DeleteUpstream(c.Request.Context(), account, record); err != nil { + var upErr *service.GeminiCachedContentUpstreamError + if !errors.As(err, &upErr) { + reqLog.Warn("gemini.cached_content.upstream_delete_error", zap.Int64("account_id", account.ID), zap.Error(err)) + googleError(c, http.StatusBadGateway, "Upstream request failed") + return + } + if !upErr.NotFound() { + h.writeGeminiCachedContentUpstreamError(c, upErr) + return + } + } + } + persistCtx, cancelPersist := geminiCachedContentPersistContext(c) + err = svc.Forget(persistCtx, record) + cancelPersist() + if err != nil { + reqLog.Error("gemini.cached_content.forget_failed", zap.Error(err)) + googleError(c, http.StatusInternalServerError, "Failed to delete cached content") + return + } + c.JSON(http.StatusOK, gin.H{}) +} + +func (h *GatewayHandler) resolveGeminiCachedContentOrWrite(c *gin.Context, reqLog *zap.Logger, apiKey *service.APIKey, cacheID string) (*service.GeminiCachedContent, bool) { + record, err := h.geminiCachedContentService.Resolve(c.Request.Context(), apiKey.ID, apiKey.GroupID, cacheID) + if err != nil { + if errors.Is(err, service.ErrGeminiCachedContentNotFound) { + googleError(c, http.StatusForbidden, service.GeminiCachedContentNotFoundMessage) + return nil, false + } + reqLog.Error("gemini.cached_content.lookup_failed", zap.Error(err)) + googleError(c, http.StatusInternalServerError, "Failed to load cached content") + return nil, false + } + return record, true +} + +// resolveGeminiCachedContentBinding 处理 generateContent / countTokens 请求对显式缓存的引用: +// 校验归属与模型后把引用改写为上游资源名,返回绑定记录;请求未引用缓存时返回 nil。 +// 返回 false 表示已写出错误响应。 +func (h *GatewayHandler) resolveGeminiCachedContentBinding(c *gin.Context, reqLog *zap.Logger, apiKey *service.APIKey, modelName string, body []byte) (*service.GeminiCachedContent, []byte, bool) { + ref, err := service.FindGeminiCachedContentReference(body) + if err != nil { + googleError(c, http.StatusBadRequest, err.Error()) + return nil, nil, false + } + if ref == nil { + return nil, body, true + } + if middleware.HasForcePlatform(c) || h.geminiCachedContentService == nil || + apiKey.Group == nil || apiKey.Group.Platform == service.PlatformComposite { + googleError(c, http.StatusBadRequest, "cachedContent is not supported on this route") + return nil, nil, false + } + record, err := h.geminiCachedContentService.Resolve(c.Request.Context(), apiKey.ID, apiKey.GroupID, ref.Name) + if err != nil { + if errors.Is(err, service.ErrGeminiCachedContentNotFound) { + googleError(c, http.StatusForbidden, service.GeminiCachedContentNotFoundMessage) + return nil, nil, false + } + reqLog.Error("gemini.cached_content.lookup_failed", zap.Error(err)) + googleError(c, http.StatusInternalServerError, "Failed to load cached content") + return nil, nil, false + } + if record.Model != modelName { + googleError(c, http.StatusBadRequest, fmt.Sprintf( + "Model used by GenerateContent request (models/%s) and CachedContent (models/%s) has to be the same.", modelName, record.Model)) + return nil, nil, false + } + rewritten, err := service.RewriteGeminiCachedContentReference(body, ref, record.UpstreamName) + if err != nil { + googleError(c, http.StatusBadRequest, "Invalid cachedContent reference") + return nil, nil, false + } + return record, rewritten, true +} + +// acquireGeminiCachedContentAccountSlot 获取选中账号的并发槽(含等待计划);返回 false 表示已写出错误响应。 +func (h *GatewayHandler) acquireGeminiCachedContentAccountSlot(c *gin.Context, reqLog *zap.Logger, helper *ConcurrencyHelper, selection *service.AccountSelectionResult) (func(), bool) { + if selection.Acquired { + release := selection.ReleaseFunc + if release == nil { + release = func() {} + } + return wrapReleaseOnDone(c.Request.Context(), release), true + } + account := selection.Account + if selection.WaitPlan == nil { + markOpsRoutingCapacityLimited(c) + googleError(c, http.StatusServiceUnavailable, "No available Gemini accounts") + return nil, false + } + canWait, err := helper.IncrementAccountWaitCount(c.Request.Context(), account.ID, selection.WaitPlan.MaxWaiting) + if err != nil { + reqLog.Warn("gemini.cached_content.account_wait_counter_increment_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + } else if !canWait { + googleError(c, http.StatusTooManyRequests, "Too many pending requests, please retry later") + return nil, false + } + streamStarted := false + release, acquireErr := helper.AcquireAccountSlotWithWaitTimeout(c, account.ID, selection.WaitPlan.MaxConcurrency, selection.WaitPlan.Timeout, false, &streamStarted) + if err == nil { + helper.DecrementAccountWaitCount(c.Request.Context(), account.ID) + } + if acquireErr != nil { + reqLog.Warn("gemini.cached_content.account_slot_acquire_failed", zap.Int64("account_id", account.ID), zap.Error(acquireErr)) + googleConcurrencyError(c, acquireErr, "account") + return nil, false + } + if release == nil { + release = func() {} + } + return wrapReleaseOnDone(c.Request.Context(), release), true +} + +// submitGeminiCachedContentUsage 记录缓存创建 / 延长的计费:inputTokens 按输入价计,storageTokenHours 按计费模型的存储单价计; +// requestID 是带固定前缀的费用行标识(见 GeminiCachedContentUsageRequestIDPrefix),落库时不被请求 id 覆盖。 +func (h *GatewayHandler) submitGeminiCachedContentUsage( + c *gin.Context, + apiKey *service.APIKey, + account *service.Account, + subscription *service.UserSubscription, + pricingAt time.Time, + requestID string, + model string, + upstreamModel string, + inputTokens int, + storageTokenHours float64, + usageFields service.ChannelUsageFields, + payload []byte, +) { + if inputTokens <= 0 && storageTokenHours <= 0 { + return + } + if upstreamModel == model { + upstreamModel = "" + } + result := &service.ForwardResult{ + RequestID: requestID, + Model: model, + UpstreamModel: upstreamModel, + Usage: service.ClaudeUsage{InputTokens: inputTokens}, + CacheStorageTokenHours: storageTokenHours, + } + inboundEndpoint := GetInboundEndpoint(c) + upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) + userAgent := c.GetHeader("User-Agent") + clientIP := ip.GetClientIP(c) + requestPayloadHash := service.HashUsageRequestPayload(payload) + quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) { + if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ + Result: result, + APIKey: apiKey, + User: apiKey.User, + Account: account, + Subscription: subscription, + PricingAt: pricingAt, + InboundEndpoint: inboundEndpoint, + UpstreamEndpoint: upstreamEndpoint, + UserAgent: userAgent, + IPAddress: clientIP, + RequestPayloadHash: requestPayloadHash, + APIKeyService: h.apiKeyService, + QuotaPlatform: quotaPlatform, + ChannelUsageFields: usageFields, + }); err != nil { + logger.L().With( + zap.String("component", "handler.gemini_v1beta.cached_contents"), + zap.Int64("api_key_id", apiKey.ID), + zap.Int64("account_id", account.ID), + zap.String("request_id", result.RequestID), + ).Error("gemini.cached_content.record_usage_failed", zap.Error(err)) + } + }) +} + +// geminiCachedContentPersistContext 返回与客户端连接脱钩的落库 context:上游操作已生效时,客户端断开不应让本地记录缺失。 +func geminiCachedContentPersistContext(c *gin.Context) (context.Context, context.CancelFunc) { + return context.WithTimeout(context.WithoutCancel(c.Request.Context()), geminiCachedContentPersistTimeout) +} + +// cleanupGeminiCachedContentUpstream 尽力删除已在上游创建、但网关不会登记的缓存,避免其持续产生存储费。 +func (h *GatewayHandler) cleanupGeminiCachedContentUpstream(reqLog *zap.Logger, account *service.Account, upstreamName string) { + ctx, cancel := context.WithTimeout(context.Background(), geminiCachedContentPersistTimeout) + defer cancel() + if err := h.geminiCachedContentService.DeleteUpstream(ctx, account, &service.GeminiCachedContent{UpstreamName: upstreamName}); err != nil { + reqLog.Error("gemini.cached_content.orphan_cleanup_failed", zap.Int64("account_id", account.ID), zap.String("upstream_name", upstreamName), zap.Error(err)) + } +} + +// reserveGeminiCachedContentCharge 校验余额 / 订阅额度 / API Key 额度足以支付确定金额 amount(倍率后), +// 并按该金额在用户、订阅、API Key 维度登记在途预留(不受预留上限封顶,见 ReserveFixedCharge)。 +// 返回的 done 须在 handler 结束时调用;预留随计费任务交接,落库后释放。 +func (h *GatewayHandler) reserveGeminiCachedContentCharge(c *gin.Context, apiKey *service.APIKey, subscription *service.UserSubscription, amount float64) (func(), error) { + ctx := c.Request.Context() + res, err := h.billingCacheService.ReserveFixedCharge(ctx, apiKey.User, apiKey, apiKey.Group, subscription, amount) + if err != nil { + return inflightNoop, err + } + if res == nil { + return inflightNoop, nil + } + c.Request = c.Request.WithContext(service.WithInflightReservation(ctx, res)) + return res.HandlerDone, nil +} + +// writeGeminiCachedContentMutationConflict 回写同一缓存的修改冲突(Google 并发冲突语义 ABORTED),客户端可稍后重试。 +func writeGeminiCachedContentMutationConflict(c *gin.Context) { + c.JSON(http.StatusConflict, gin.H{ + "error": gin.H{ + "code": http.StatusConflict, + "message": "Another update to this cached content is in progress, please retry later", + "status": "ABORTED", + }, + }) +} + +func writeGeminiCachedContentBillingError(c *gin.Context, err error) { + status, code, message, retryAfter := billingErrorDetails(err) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + googleErrorWithType(c, status, code, "", message) +} + +// writeGeminiCachedContentUpstreamError 回写上游错误:缓存不存在统一返回标准 403(各上游形态不同且可能含上游资源 ID); +// 账号凭据或权限类错误不是客户端问题,统一改为 502;限流 / 不可用按普通 Gemini 路径处理(透传规则、通用映射), +// 只有上游网关账号的这类响应反映持有缓存的上游账号状态,原样回写。 +func (h *GatewayHandler) writeGeminiCachedContentUpstreamError(c *gin.Context, upErr *service.GeminiCachedContentUpstreamError) { + status := upErr.StatusCode + message := strings.TrimSpace(extractGoogleErrorMessage(upErr.Body)) + service.SetOpsUpstreamError(c, status, message, "") + if upErr.NotFound() { + service.MarkOpsRequestScopedError(c, "permission_error") + c.Data(http.StatusForbidden, "application/json", []byte(service.GeminiCachedContentNotFoundResponse)) + return + } + if (status == http.StatusTooManyRequests || status >= http.StatusInternalServerError) && !upErr.UpstreamGateway { + h.handleGeminiFailoverExhausted(c, &service.UpstreamFailoverError{StatusCode: status, ResponseBody: upErr.Body}) + return + } + if status == http.StatusUnauthorized || status == http.StatusForbidden { + googleError(c, http.StatusBadGateway, "Upstream account rejected the cached content request") + return + } + if len(upErr.Body) == 0 || !json.Valid(upErr.Body) { + if message == "" { + message = http.StatusText(status) + } + googleError(c, status, message) + return + } + c.Data(status, "application/json", upErr.Body) +} + +func extractGoogleErrorMessage(body []byte) string { + var envelope struct { + Error struct { + Message string `json:"message"` + } `json:"error"` + } + if err := json.Unmarshal(body, &envelope); err != nil { + return "" + } + return envelope.Error.Message +} + +func encodeGeminiCachedContentPageToken(id int64) string { + return base64.RawURLEncoding.EncodeToString([]byte(strconv.FormatInt(id, 10))) +} + +func decodeGeminiCachedContentPageToken(raw string) (int64, bool) { + decoded, err := base64.RawURLEncoding.DecodeString(raw) + if err != nil { + return 0, false + } + id, err := strconv.ParseInt(string(decoded), 10, 64) + if err != nil || id <= 0 { + return 0, false + } + return id, true +} + +// mergeAccountIDSets 返回两个账号 ID 集合的并集(不修改入参)。 +func mergeAccountIDSets(a, b map[int64]struct{}) map[int64]struct{} { + out := make(map[int64]struct{}, len(a)+len(b)) + for id := range a { + out[id] = struct{}{} + } + for id := range b { + out[id] = struct{}{} + } + return out +} + +// handleGeminiCachedContentFailoverExhausted 处理绑定缓存的请求在持有账号上重试耗尽:没有其他账号可换。 +// 上游网关账号的限流 / 不可用响应反映持有缓存的上游账号状态,原样返回供客户端判断; +// 其余(含官方账号)仍按普通 Gemini 路径处理:透传规则、通用映射。 +func (h *GatewayHandler) handleGeminiCachedContentFailoverExhausted(c *gin.Context, failoverErr *service.UpstreamFailoverError) { + if failoverErr == nil || !failoverErr.BoundUpstreamPassthrough || len(failoverErr.ResponseBody) == 0 || !json.Valid(failoverErr.ResponseBody) { + h.handleGeminiFailoverExhausted(c, failoverErr) + return + } + service.SetOpsUpstreamError(c, failoverErr.StatusCode, service.ExtractUpstreamErrorMessage(failoverErr.ResponseBody), "") + c.Data(failoverErr.StatusCode, "application/json", failoverErr.ResponseBody) +} diff --git a/backend/internal/handler/gemini_cached_contents_handler_test.go b/backend/internal/handler/gemini_cached_contents_handler_test.go new file mode 100644 index 000000000..7b9c99e27 --- /dev/null +++ b/backend/internal/handler/gemini_cached_contents_handler_test.go @@ -0,0 +1,264 @@ +//go:build unit + +package handler + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/MACOS-DO/sub4api/internal/config" + middleware "github.com/MACOS-DO/sub4api/internal/server/middleware" + "github.com/MACOS-DO/sub4api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +type geminiCachedContentHandlerRepoStub struct { + records []*service.GeminiCachedContent +} + +func (r *geminiCachedContentHandlerRepoStub) Create(_ context.Context, record *service.GeminiCachedContent) error { + record.ID = int64(len(r.records) + 1) + r.records = append(r.records, record) + return nil +} + +func (r *geminiCachedContentHandlerRepoStub) GetForOwner(_ context.Context, apiKeyID int64, publicID string) (*service.GeminiCachedContent, error) { + for _, record := range r.records { + if record.PublicID == publicID && record.APIKeyID == apiKeyID { + return record, nil + } + } + return nil, service.ErrGeminiCachedContentNotFound +} + +func (r *geminiCachedContentHandlerRepoStub) ListForOwner(_ context.Context, apiKeyID, groupID int64, activeAt time.Time, beforeID int64, limit int) ([]*service.GeminiCachedContent, error) { + var out []*service.GeminiCachedContent + for i := len(r.records) - 1; i >= 0; i-- { + record := r.records[i] + if record.APIKeyID == apiKeyID && record.GroupID == groupID && record.ExpireTime.After(activeAt) && (beforeID <= 0 || record.ID < beforeID) { + out = append(out, record) + } + if len(out) == limit { + break + } + } + return out, nil +} + +func (r *geminiCachedContentHandlerRepoStub) BeginMutation(context.Context, int64, time.Time, string, time.Duration) (bool, error) { + return true, nil +} + +func (r *geminiCachedContentHandlerRepoStub) TakeOverStaleMutation(context.Context, int64, string, time.Duration) (*service.GeminiCachedContent, error) { + return nil, nil +} + +func (r *geminiCachedContentHandlerRepoStub) CommitMutation(context.Context, int64, string, time.Time) error { + return nil +} + +func (r *geminiCachedContentHandlerRepoStub) ReleaseMutation(context.Context, int64, string) error { + return nil +} + +func (r *geminiCachedContentHandlerRepoStub) ListStaleMutations(context.Context, int) ([]int64, error) { + return nil, nil +} + +func (r *geminiCachedContentHandlerRepoStub) SoftDelete(context.Context, int64) error { + return nil +} + +func newGeminiCachedContentHandlerForTest(repo *geminiCachedContentHandlerRepoStub) *GatewayHandler { + return &GatewayHandler{geminiCachedContentService: service.NewGeminiCachedContentService(repo, nil, &config.Config{})} +} + +func geminiCachedContentTestAPIKey(platform string) *service.APIKey { + groupID := int64(42) + return &service.APIKey{ID: 7, UserID: 3, GroupID: &groupID, Group: &service.Group{ID: groupID, Platform: platform}} +} + +func newGeminiCachedContentTestContext(method, target string, apiKey *service.APIKey) (*gin.Context, *httptest.ResponseRecorder) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(method, target, nil) + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.UserID, Concurrency: 10}) + return c, rec +} + +func seedGeminiCachedContent(repo *geminiCachedContentHandlerRepoStub, publicID string, apiKeyID int64, expire time.Time) *service.GeminiCachedContent { + record := &service.GeminiCachedContent{ + PublicID: publicID, + UserID: 3, + APIKeyID: apiKeyID, + GroupID: 42, + AccountID: 900, + UpstreamName: "cachedContents/upstream" + publicID, + Model: "gemini-3.8-flash", + UpstreamModel: "models/gemini-3.8-flash", + TotalTokenCount: 6273, + ExpireTime: expire, + CreatedAt: time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC), + UpdatedAt: time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC), + } + _ = repo.Create(context.Background(), record) + return record +} + +func TestResolveGeminiCachedContentBinding(t *testing.T) { + repo := &geminiCachedContentHandlerRepoStub{} + seedGeminiCachedContent(repo, "abc", 7, time.Now().Add(time.Hour)) + seedGeminiCachedContent(repo, "foreign", 8, time.Now().Add(time.Hour)) + h := newGeminiCachedContentHandlerForTest(repo) + apiKey := geminiCachedContentTestAPIKey(service.PlatformGemini) + + t.Run("request without cache passes through", func(t *testing.T) { + c, _ := newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", apiKey) + body := []byte(`{"contents":[]}`) + record, out, ok := h.resolveGeminiCachedContentBinding(c, zap.NewNop(), apiKey, "gemini-3.8-flash", body) + require.True(t, ok) + require.Nil(t, record) + require.Equal(t, body, out) + }) + + t.Run("owned cache rewrites reference and binds account", func(t *testing.T) { + c, _ := newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", apiKey) + record, out, ok := h.resolveGeminiCachedContentBinding(c, zap.NewNop(), apiKey, "gemini-3.8-flash", + []byte(`{"cachedContent":"cachedContents/abc","contents":[]}`)) + require.True(t, ok) + require.Equal(t, int64(900), record.AccountID) + require.JSONEq(t, `{"cachedContent":"cachedContents/upstreamabc","contents":[]}`, string(out)) + }) + + t.Run("cache owned by another key looks missing", func(t *testing.T) { + c, rec := newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", apiKey) + _, _, ok := h.resolveGeminiCachedContentBinding(c, zap.NewNop(), apiKey, "gemini-3.8-flash", + []byte(`{"cachedContent":"cachedContents/foreign","contents":[]}`)) + require.False(t, ok) + require.Equal(t, http.StatusForbidden, rec.Code) + require.Contains(t, rec.Body.String(), service.GeminiCachedContentNotFoundMessage) + }) + + t.Run("model must match the cache literally", func(t *testing.T) { + c, rec := newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-flash-latest:generateContent", apiKey) + _, _, ok := h.resolveGeminiCachedContentBinding(c, zap.NewNop(), apiKey, "gemini-flash-latest", + []byte(`{"cachedContent":"cachedContents/abc","contents":[]}`)) + require.False(t, ok) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Contains(t, rec.Body.String(), "has to be the same") + }) + + t.Run("composite groups are rejected", func(t *testing.T) { + composite := geminiCachedContentTestAPIKey(service.PlatformComposite) + c, rec := newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", composite) + _, _, ok := h.resolveGeminiCachedContentBinding(c, zap.NewNop(), composite, "gemini-3.8-flash", + []byte(`{"cachedContent":"cachedContents/abc","contents":[]}`)) + require.False(t, ok) + require.Equal(t, http.StatusBadRequest, rec.Code) + }) +} + +func TestGeminiCachedContentsListAndGet(t *testing.T) { + repo := &geminiCachedContentHandlerRepoStub{} + seedGeminiCachedContent(repo, "first", 7, time.Now().Add(time.Hour)) + seedGeminiCachedContent(repo, "second", 7, time.Now().Add(time.Hour)) + seedGeminiCachedContent(repo, "expired", 7, time.Now().Add(-time.Minute)) + seedGeminiCachedContent(repo, "foreign", 8, time.Now().Add(time.Hour)) + h := newGeminiCachedContentHandlerForTest(repo) + apiKey := geminiCachedContentTestAPIKey(service.PlatformGemini) + + c, rec := newGeminiCachedContentTestContext(http.MethodGet, "/v1beta/cachedContents?pageSize=1", apiKey) + h.GeminiCachedContentsList(c) + require.Equal(t, http.StatusOK, rec.Code) + var page struct { + CachedContents []map[string]any `json:"cachedContents"` + NextPageToken string `json:"nextPageToken"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &page)) + require.Len(t, page.CachedContents, 1) + require.Equal(t, "cachedContents/second", page.CachedContents[0]["name"]) + require.NotEmpty(t, page.NextPageToken) + + c, rec = newGeminiCachedContentTestContext(http.MethodGet, "/v1beta/cachedContents?pageSize=1&pageToken="+page.NextPageToken, apiKey) + h.GeminiCachedContentsList(c) + require.Equal(t, http.StatusOK, rec.Code) + page.NextPageToken = "" + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &page)) + require.Len(t, page.CachedContents, 1) + require.Equal(t, "cachedContents/first", page.CachedContents[0]["name"]) + require.Empty(t, page.NextPageToken, "过期与其他 Key 的缓存不出现在列表里") + + c, rec = newGeminiCachedContentTestContext(http.MethodGet, "/v1beta/cachedContents/first", apiKey) + c.Params = gin.Params{{Key: "cacheID", Value: "first"}} + h.GeminiCachedContentsGet(c) + require.Equal(t, http.StatusOK, rec.Code) + var view map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &view)) + require.Equal(t, "cachedContents/first", view["name"]) + require.Equal(t, "models/gemini-3.8-flash", view["model"]) + require.NotContains(t, rec.Body.String(), "upstreamfirst", "上游资源名不暴露给客户端") + + c, rec = newGeminiCachedContentTestContext(http.MethodGet, "/v1beta/cachedContents/foreign", apiKey) + c.Params = gin.Params{{Key: "cacheID", Value: "foreign"}} + h.GeminiCachedContentsGet(c) + require.Equal(t, http.StatusForbidden, rec.Code) + require.True(t, strings.Contains(rec.Body.String(), service.GeminiCachedContentNotFoundMessage)) +} + +func TestHandleGeminiCachedContentFailoverExhausted(t *testing.T) { + h := &GatewayHandler{} + apiKey := geminiCachedContentTestAPIKey(service.PlatformGemini) + unavailable := `{"error":{"code":503,"message":"The account holding this cached content is temporarily unavailable","status":"UNAVAILABLE"}}` + + c, rec := newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", apiKey) + h.handleGeminiCachedContentFailoverExhausted(c, &service.UpstreamFailoverError{StatusCode: http.StatusServiceUnavailable, ResponseBody: []byte(unavailable), BoundUpstreamPassthrough: true}) + require.Equal(t, http.StatusServiceUnavailable, rec.Code, "绑定缓存的请求无账号可换,上游网关的 503 原样返回") + require.JSONEq(t, unavailable, rec.Body.String()) + + c, rec = newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", apiKey) + h.handleGeminiCachedContentFailoverExhausted(c, &service.UpstreamFailoverError{StatusCode: http.StatusTooManyRequests, ResponseBody: []byte(`{"error":{"code":429,"message":"Too many pending requests, please retry later","status":"RESOURCE_EXHAUSTED"}}`), BoundUpstreamPassthrough: true}) + require.Equal(t, http.StatusTooManyRequests, rec.Code) + require.Contains(t, rec.Body.String(), "Too many pending requests") + + officialQuota := `{"error":{"code":429,"message":"You exceeded your current quota","status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.QuotaFailure","violations":[{"quotaId":"GenerateRequestsPerDayPerProjectPerModel-FreeTier"}]}]}}` + c, rec = newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", apiKey) + h.handleGeminiCachedContentFailoverExhausted(c, &service.UpstreamFailoverError{StatusCode: http.StatusTooManyRequests, ResponseBody: []byte(officialQuota)}) + require.Equal(t, http.StatusTooManyRequests, rec.Code, "官方账号的限流按普通 Gemini 路径映射") + require.NotContains(t, rec.Body.String(), "FreeTier", "不向客户端暴露上游账号的配额明细") + require.Contains(t, rec.Body.String(), "Upstream rate limit exceeded") + + c, rec = newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/models/gemini-3.8-flash:generateContent", apiKey) + h.handleGeminiCachedContentFailoverExhausted(c, &service.UpstreamFailoverError{StatusCode: http.StatusUnauthorized, ResponseBody: []byte(`{"error":{"code":401,"message":"bad key"}}`)}) + require.Equal(t, http.StatusBadGateway, rec.Code, "账号凭据类错误仍按网关映射,不透传给客户端") + require.NotContains(t, rec.Body.String(), "bad key") +} + +func TestWriteGeminiCachedContentUpstreamError_RateLimitMappedUnlessUpstreamGateway(t *testing.T) { + h := &GatewayHandler{} + apiKey := geminiCachedContentTestAPIKey(service.PlatformGemini) + quota := `{"error":{"code":429,"message":"You exceeded your current quota","status":"RESOURCE_EXHAUSTED","details":[{"quotaId":"GenerateRequestsPerDayPerProjectPerModel-FreeTier"}]}}` + + c, rec := newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/cachedContents", apiKey) + h.writeGeminiCachedContentUpstreamError(c, &service.GeminiCachedContentUpstreamError{StatusCode: http.StatusTooManyRequests, Body: []byte(quota)}) + require.Equal(t, http.StatusTooManyRequests, rec.Code) + require.NotContains(t, rec.Body.String(), "FreeTier", "官方账号的限流不透传配额明细") + + c, rec = newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/cachedContents", apiKey) + h.writeGeminiCachedContentUpstreamError(c, &service.GeminiCachedContentUpstreamError{StatusCode: http.StatusTooManyRequests, Body: []byte(quota), UpstreamGateway: true}) + require.Equal(t, http.StatusTooManyRequests, rec.Code) + require.JSONEq(t, quota, rec.Body.String(), "上游网关账号的限流反映持有缓存的上游账号状态,原样回写") + + c, rec = newGeminiCachedContentTestContext(http.MethodPost, "/v1beta/cachedContents", apiKey) + h.writeGeminiCachedContentUpstreamError(c, &service.GeminiCachedContentUpstreamError{StatusCode: http.StatusBadRequest, Body: []byte(`{"error":{"code":400,"message":"Cached content is too small","status":"INVALID_ARGUMENT"}}`)}) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Contains(t, rec.Body.String(), "too small", "请求校验类错误仍原样回写") +} diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index d55aa1643..21792e469 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -39,9 +39,11 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) { googleError(c, http.StatusUnauthorized, "Invalid API key") return } - // 检查平台:优先使用强制平台(/antigravity 路由),否则要求 gemini 分组 + // 检查平台:优先使用强制平台(/antigravity 路由),否则要求 gemini 分组(composite 分组允许路由到 antigravity) forcePlatform, hasForcePlatform := middleware.GetForcePlatformFromContext(c) - if !hasForcePlatform && effectiveAPIKeyPlatform(c, apiKey) != service.PlatformGemini { + effectivePlatform := effectiveAPIKeyPlatform(c, apiKey) + if !hasForcePlatform && effectivePlatform != service.PlatformGemini && + !servesCompositeAntigravityGemini(apiKey, effectivePlatform) { googleError(c, http.StatusBadRequest, "API key group platform is not gemini") return } @@ -74,7 +76,7 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) { return } - account, err := h.geminiCompatService.SelectAccountForAIStudioEndpoints(c.Request.Context(), apiKey.GroupID) + account, err := h.geminiCompatService.SelectAccountForModelsEndpoints(c.Request.Context(), apiKey.GroupID) if err != nil { if len(agModels) > 0 { c.JSON(http.StatusOK, gemini.ModelsListResponse{Models: filterGeminiModels(agModels)}) @@ -85,7 +87,7 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) { return } - res, err := h.geminiCompatService.ForwardAIStudioGET(c.Request.Context(), account, "/v1beta/models") + res, err := h.geminiCompatService.ForwardListModels(c.Request.Context(), account) if err != nil { googleError(c, http.StatusBadGateway, err.Error()) return @@ -223,9 +225,11 @@ func (h *GatewayHandler) GeminiV1BetaGetModel(c *gin.Context) { googleError(c, http.StatusUnauthorized, "Invalid API key") return } - // 检查平台:优先使用强制平台(/antigravity 路由),否则要求 gemini 分组 + // 检查平台:优先使用强制平台(/antigravity 路由),否则要求 gemini 分组(composite 分组允许路由到 antigravity) forcePlatform, hasForcePlatform := middleware.GetForcePlatformFromContext(c) - if !hasForcePlatform && effectiveAPIKeyPlatform(c, apiKey) != service.PlatformGemini { + effectivePlatform := effectiveAPIKeyPlatform(c, apiKey) + if !hasForcePlatform && effectivePlatform != service.PlatformGemini && + !servesCompositeAntigravityGemini(apiKey, effectivePlatform) { googleError(c, http.StatusBadRequest, "API key group platform is not gemini") return } @@ -244,14 +248,18 @@ func (h *GatewayHandler) GeminiV1BetaGetModel(c *gin.Context) { if resolvedModel, ok := service.ResolvedUpstreamModelFromContext(c.Request.Context()); ok && strings.TrimSpace(resolvedModel) != "" { modelName = strings.TrimSpace(resolvedModel) } + if !hasForcePlatform && servesCompositeAntigravityGemini(apiKey, effectivePlatform) && !isAntigravityGeminiModel(modelName) { + googleError(c, http.StatusBadRequest, "API key group platform is not gemini") + return + } - // 强制 antigravity 模式:返回 antigravity 模型信息 - if forcePlatform == service.PlatformAntigravity { + // 强制 antigravity 模式或 composite 路由到 antigravity:返回 antigravity 模型信息 + if forcePlatform == service.PlatformAntigravity || effectivePlatform == service.PlatformAntigravity { c.JSON(http.StatusOK, antigravity.FallbackGeminiModel(modelName)) return } - account, err := h.geminiCompatService.SelectAccountForAIStudioEndpoints(c.Request.Context(), apiKey.GroupID) + account, err := h.geminiCompatService.SelectAccountForModelsEndpoints(c.Request.Context(), apiKey.GroupID) if err != nil { // 没有 gemini 账户,检查是否有 antigravity 账户可用 hasAntigravity, _ := h.geminiCompatService.HasAntigravityAccounts(c.Request.Context(), apiKey.GroupID) @@ -265,7 +273,7 @@ func (h *GatewayHandler) GeminiV1BetaGetModel(c *gin.Context) { return } - res, err := h.geminiCompatService.ForwardAIStudioGET(c.Request.Context(), account, "/v1beta/models/"+modelName) + res, err := h.geminiCompatService.ForwardGetModel(c.Request.Context(), account, modelName) if err != nil { googleError(c, http.StatusBadGateway, err.Error()) return @@ -299,9 +307,11 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { zap.Any("group_id", apiKey.GroupID), ) - // 检查平台:优先使用强制平台(/antigravity 路由,中间件已设置 request.Context),否则要求 gemini 分组 + // 检查平台:优先使用强制平台(/antigravity 路由,中间件已设置 request.Context),否则要求 gemini 分组(composite 分组允许路由到 antigravity) + effectivePlatform := effectiveAPIKeyPlatform(c, apiKey) if !middleware.HasForcePlatform(c) { - if effectiveAPIKeyPlatform(c, apiKey) != service.PlatformGemini { + if effectivePlatform != service.PlatformGemini && + !servesCompositeAntigravityGemini(apiKey, effectivePlatform) { googleError(c, http.StatusBadRequest, "API key group platform is not gemini") return } @@ -321,6 +331,10 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { if resolvedModel, ok := service.ResolvedUpstreamModelFromContext(c.Request.Context()); ok && strings.TrimSpace(resolvedModel) != "" { modelName = strings.TrimSpace(resolvedModel) } + if !middleware.HasForcePlatform(c) && servesCompositeAntigravityGemini(apiKey, effectivePlatform) && !isAntigravityGeminiModel(modelName) { + googleError(c, http.StatusBadRequest, "API key group platform is not gemini") + return + } stream := action == "streamGenerateContent" reqLog = reqLog.With(zap.String("model", modelName), zap.String("action", action), zap.Bool("stream", stream)) @@ -356,6 +370,12 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { modelName = channelMapping.MappedModel } + // 引用显式缓存的请求只能发往持有该缓存的账号,且不参与会话粘性与换号。 + cachedContentBinding, body, ok := h.resolveGeminiCachedContentBinding(c, reqLog, apiKey, modelName, body) + if !ok { + return + } + // Get subscription (may be nil) subscription, _ := middleware.GetSubscriptionFromContext(c) @@ -382,11 +402,11 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { // 2) billing eligibility check (after wait) if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(c.Request.Context(), apiKey)); err != nil { reqLog.Info("gemini.billing_eligibility_check_failed", zap.Error(err)) - status, _, message, retryAfter := billingErrorDetails(err) + status, code, message, retryAfter := billingErrorDetails(err) if retryAfter > 0 { c.Header("Retry-After", strconv.Itoa(retryAfter)) } - googleError(c, status, message) + googleErrorWithType(c, status, code, "", message) return } @@ -394,19 +414,22 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(modelName, body)) if err != nil { reqLog.Info("gemini.inflight_reservation_rejected", zap.Error(err)) - status, _, message, retryAfter := billingErrorDetails(err) + status, code, message, retryAfter := billingErrorDetails(err) if retryAfter > 0 { c.Header("Retry-After", strconv.Itoa(retryAfter)) } - googleError(c, status, message) + googleErrorWithType(c, status, code, "", message) return } defer inflightRelease() // 3) select account (sticky session based on request body) // 优先使用 Gemini CLI 的会话标识(privileged-user-id + tmp 目录哈希) - sessionHash := extractGeminiCLISessionHash(c, body) - if sessionHash == "" { + sessionHash := "" + if cachedContentBinding == nil { + sessionHash = extractGeminiCLISessionHash(c, body) + } + if sessionHash == "" && cachedContentBinding == nil { // Fallback: 使用通用的会话哈希生成逻辑(适用于其他客户端) parsedReq, _ := service.ParseGatewayRequest(service.NewRequestBodyRef(body), domain.PlatformGemini) if parsedReq != nil { @@ -443,7 +466,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { var geminiPrefixHash string var geminiSessionUUID string var matchedDigestChain string - useDigestFallback := sessionBoundAccountID == 0 + useDigestFallback := sessionBoundAccountID == 0 && cachedContentBinding == nil if useDigestFallback { // 解析 Gemini 请求体 @@ -507,7 +530,21 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { hasBoundSession := sessionKey != "" && sessionBoundAccountID > 0 cleanedForUnknownBinding := false - fs := NewFailoverState(h.maxAccountSwitchesGemini, hasBoundSession) + maxAccountSwitches := h.maxAccountSwitchesGemini + var cachedContentExclusions map[int64]struct{} + if cachedContentBinding != nil { + // 缓存只存在于绑定账号:排除分组内其余账号,失败不换号。 + maxAccountSwitches = 0 + sessionBoundAccountID = cachedContentBinding.AccountID + c.Request = c.Request.WithContext(service.WithGeminiCachedContentBound(c.Request.Context())) + cachedContentExclusions, err = h.gatewayService.GeminiExplicitCacheExclusions(c.Request.Context(), apiKey.GroupID, cachedContentBinding.AccountID) + if err != nil { + reqLog.Warn("gemini.cached_content.list_accounts_failed", zap.Error(err)) + googleError(c, http.StatusServiceUnavailable, geminiCachedContentUnavailableMessage) + return + } + } + fs := NewFailoverState(maxAccountSwitches, hasBoundSession) // 单账号分组提前设置 SingleAccountRetry 标记,让 Service 层首次 503 就不设模型限流标记。 // 避免单账号分组收到 503 (MODEL_CAPACITY_EXHAUSTED) 时设 29s 限流,导致后续请求连续快速失败。 @@ -517,14 +554,38 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { } for { - selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, sessionKey, modelName, fs.FailedAccountIDs, "", int64(0)) // Gemini 不使用会话限制 + excludedAccountIDs := fs.FailedAccountIDs + if cachedContentExclusions != nil { + excludedAccountIDs = mergeAccountIDSets(cachedContentExclusions, fs.FailedAccountIDs) + } + selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, sessionKey, modelName, excludedAccountIDs, "", int64(0)) // Gemini 不使用会话限制 + if err == nil && cachedContentBinding != nil && selection.Account.ID != cachedContentBinding.AccountID { + if selection.Acquired && selection.ReleaseFunc != nil { + selection.ReleaseFunc() + } + err = service.ErrNoAvailableAccounts + } if err != nil { if failoverClientGone(c) { reqLog.Info("gemini.account_select_aborted_client_disconnected", zap.Error(err)) return } + if cachedContentBinding != nil { + if fs.LastFailoverErr != nil { + h.handleGeminiCachedContentFailoverExhausted(c, fs.LastFailoverErr) + return + } + reqLog.Info("gemini.cached_content.bound_account_unavailable", zap.Int64("account_id", cachedContentBinding.AccountID), zap.Error(err)) + markOpsRoutingCapacityLimited(c) + googleError(c, http.StatusServiceUnavailable, geminiCachedContentUnavailableMessage) + return + } if len(fs.FailedAccountIDs) == 0 { - cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, modelName, modelName, service.PlatformGemini) + diagPlatform := service.PlatformGemini + if p := effectiveAPIKeyPlatform(c, apiKey); p == service.PlatformAntigravity { + diagPlatform = service.PlatformAntigravity + } + cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, modelName, modelName, diagPlatform) if !cls.ModelNotFound { markOpsRoutingCapacityLimitedIfNoAvailable(c, err) } @@ -631,6 +692,11 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { accountReleaseFunc() } reqLog.Debug("gemini.account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason)) + if cachedContentBinding != nil { + markOpsRoutingCapacityLimited(c) + googleError(c, http.StatusServiceUnavailable, geminiCachedContentUnavailableMessage) + return + } if fs.RecordProfitVeto(account.ID) == FailoverExhausted { reqLog.Warn("gemini.profit_veto_attempts_exhausted", zap.Int("profit_veto_count", fs.ProfitVetoCount())) markOpsRoutingCapacityLimited(c) @@ -684,6 +750,10 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { case FailoverContinue: continue case FailoverExhausted: + if cachedContentBinding != nil { + h.handleGeminiCachedContentFailoverExhausted(c, fs.LastFailoverErr) + return + } h.handleGeminiFailoverExhausted(c, fs.LastFailoverErr) return case FailoverCanceled: @@ -809,7 +879,8 @@ func (h *GatewayHandler) handleGeminiFailoverExhausted(c *gin.Context, failoverE c.Set(service.OpsSkipPassthroughKey, true) } - googleError(c, respCode, msg) + // 按透传规则改写的是上游错误,不登记本地错误类型。 + googleErrorWithType(c, respCode, "", "", msg) return } } @@ -844,7 +915,21 @@ type pathParseError struct{ msg string } func (e *pathParseError) Error() string { return e.msg } +// googleError 以 Google 错误格式回写网关产生的错误,并按状态码向 ops 登记错误类型: +// 4xx 为客户端请求问题,其余状态码不登记(按平台错误统计)。 func googleError(c *gin.Context, status int, message string) { + googleErrorWithType(c, status, googleClientErrorType(status), "", message) +} + +// googlePlatformError 以 Google 错误格式回写由平台侧原因(如管理员未完成配置)导致的错误,ops 按平台错误统计。 +func googlePlatformError(c *gin.Context, status int, message string) { + googleErrorWithType(c, status, "", "", message) +} + +// googleErrorWithType 以 Google 错误格式回写错误,并向 ops 登记错误类型与错误码(Google 错误体没有 type 字段), +// 与 Claude / OpenAI 格式错误同口径分类;errType 为空时不登记。 +func googleErrorWithType(c *gin.Context, status int, errType, code, message string) { + service.SetOpsLocalErrorType(c, errType, code) c.JSON(status, gin.H{ "error": gin.H{ "code": status, @@ -854,11 +939,27 @@ func googleError(c *gin.Context, status int, message string) { }) } +// googleClientErrorType 返回客户端请求类 4xx 状态码对应的 ops 错误类型;其余状态码返回空串。 +func googleClientErrorType(status int) string { + switch status { + case http.StatusBadRequest, http.StatusRequestEntityTooLarge: + return "invalid_request_error" + case http.StatusUnauthorized: + return "authentication_error" + case http.StatusForbidden: + return "permission_error" + case http.StatusNotFound: + return "not_found_error" + default: + return "" + } +} + // googleConcurrencyError 以 Google 错误格式回写并发槽获取失败,状态码与文案 // 沿用 concurrencyErrorResponse 的统一映射(客户端断开为 499)。 func googleConcurrencyError(c *gin.Context, err error, slotType string) { - status, _, _, message := concurrencyErrorResponse(err, slotType) - googleError(c, status, message) + status, errType, code, message := concurrencyErrorResponse(err, slotType) + googleErrorWithType(c, status, errType, code, message) } func writeUpstreamResponse(c *gin.Context, res *service.UpstreamHTTPResult) { @@ -970,3 +1071,16 @@ func derefGroupID(groupID *int64) int64 { } return *groupID } + +func servesCompositeAntigravityGemini(apiKey *service.APIKey, effectivePlatform string) bool { + return apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite && effectivePlatform == service.PlatformAntigravity +} + +func isAntigravityGeminiModel(model string) bool { + trimmed := strings.ToLower(strings.TrimSpace(strings.TrimPrefix(model, "models/"))) + if trimmed == "" || strings.HasPrefix(trimmed, "claude-") { + return false + } + detected, ok := service.DetectModelPlatform(trimmed) + return ok && detected == service.PlatformGemini +} diff --git a/backend/internal/handler/gemini_v1beta_handler_test.go b/backend/internal/handler/gemini_v1beta_handler_test.go index 4f56085bd..fd11d4681 100644 --- a/backend/internal/handler/gemini_v1beta_handler_test.go +++ b/backend/internal/handler/gemini_v1beta_handler_test.go @@ -109,7 +109,7 @@ func TestGeminiV1BetaHandler_ListModelsAntigravityFallback(t *testing.T) { expectedBehavior string }{ { - name: "有Gemini账户-调用ForwardAIStudioGET", + name: "有Gemini账户-调用ForwardListModels", hasGeminiAccount: true, hasAntigravity: false, expectedBehavior: "forward_to_upstream", @@ -155,7 +155,7 @@ func TestGeminiV1BetaHandler_GetModelAntigravityFallback(t *testing.T) { expectedBehavior string }{ { - name: "有Gemini账户-调用ForwardAIStudioGET", + name: "有Gemini账户-调用ForwardGetModel", hasGeminiAccount: true, hasAntigravity: false, expectedBehavior: "forward_to_upstream", @@ -216,3 +216,75 @@ func TestShouldFallbackGeminiModel_DelegatesScopeFallback(t *testing.T) { } require.True(t, shouldFallbackGeminiModel("gemini-future-model", res)) } + +func TestGeminiV1BetaGetModel_CompositeAntigravityRoute(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("composite route to antigravity gemini model succeeds", func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + req := httptest.NewRequest(http.MethodGet, "/v1beta/models/gemini-4-argon", nil) + req = req.WithContext(service.WithCompositeRouteDecision(req.Context(), service.CompositeRouteDecision{ + Matched: true, + TargetPlatform: service.PlatformAntigravity, + UpstreamModel: "gemini-4-argon-high", + })) + c.Request = req + c.Params = gin.Params{{Key: "model", Value: "gemini-4-argon"}} + groupID := int64(4) + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ + ID: 1, + GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: service.PlatformComposite}, + }) + + (&GatewayHandler{}).GeminiV1BetaGetModel(c) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.Contains(t, rec.Body.String(), "models/gemini-4-argon-high") + }) + + t.Run("composite route to antigravity claude model is rejected on v1beta", func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + req := httptest.NewRequest(http.MethodGet, "/v1beta/models/claude-sonnet-5-5-high", nil) + req = req.WithContext(service.WithCompositeRouteDecision(req.Context(), service.CompositeRouteDecision{ + Matched: true, + TargetPlatform: service.PlatformAntigravity, + UpstreamModel: "claude-sonnet-5-5-high", + })) + c.Request = req + c.Params = gin.Params{{Key: "model", Value: "claude-sonnet-5-5-high"}} + groupID := int64(4) + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ + ID: 1, + GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: service.PlatformComposite}, + }) + + (&GatewayHandler{}).GeminiV1BetaGetModel(c) + require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String()) + }) + + t.Run("composite route to antigravity claude model is rejected on generateContent", func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + req := httptest.NewRequest(http.MethodPost, "/v1beta/models/claude-sonnet-5-5-high:generateContent", nil) + req = req.WithContext(service.WithCompositeRouteDecision(req.Context(), service.CompositeRouteDecision{ + Matched: true, + TargetPlatform: service.PlatformAntigravity, + UpstreamModel: "claude-sonnet-5-5-high", + })) + c.Request = req + c.Params = gin.Params{{Key: "modelAction", Value: "/claude-sonnet-5-5-high:generateContent"}} + groupID := int64(4) + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ + ID: 1, + GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: service.PlatformComposite}, + }) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1, Concurrency: 1}) + + (&GatewayHandler{}).GeminiV1BetaModels(c) + require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String()) + }) +} diff --git a/backend/internal/handler/gemini_vertex_models_test.go b/backend/internal/handler/gemini_vertex_models_test.go new file mode 100644 index 000000000..db1c4e09d --- /dev/null +++ b/backend/internal/handler/gemini_vertex_models_test.go @@ -0,0 +1,83 @@ +package handler + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/MACOS-DO/sub4api/internal/server/middleware" + "github.com/MACOS-DO/sub4api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type geminiVertexModelsTokenCache struct{} + +func (geminiVertexModelsTokenCache) GetAccessToken(context.Context, string) (string, error) { + return "ya29.vertex-token", nil +} + +func (geminiVertexModelsTokenCache) SetAccessToken(context.Context, string, string, time.Duration) error { + return nil +} + +func (geminiVertexModelsTokenCache) DeleteAccessToken(context.Context, string) error { + return nil +} + +func (geminiVertexModelsTokenCache) AcquireRefreshLock(context.Context, string, time.Duration) (bool, error) { + return false, nil +} + +func (geminiVertexModelsTokenCache) ReleaseRefreshLock(context.Context, string) error { + return nil +} + +// 分组里只有 Agent Platform (Vertex) 服务账号时,模型列表与模型详情接口返回 Vertex 上的 Gemini 模型。 +func TestGeminiV1BetaModelsEndpoints_VertexServiceAccountOnlyGroup(t *testing.T) { + groupID := int64(8) + repo := &geminiAllowlistAccountRepoStub{gatewayModelsAccountRepoStub: gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{groupID: {{ + ID: 18, + Platform: service.PlatformGemini, + Type: service.AccountTypeServiceAccount, + Credentials: map[string]any{ + "location": "global", + "service_account_json": map[string]any{ + "type": "service_account", + "project_id": "proj", + "private_key": "-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----\n", + "client_email": "svc@proj.iam.gserviceaccount.com", + }, + }, + }}}}} + upstream := &geminiMixedModelsUpstream{status: http.StatusOK, body: `{"publisherModels":[{"name":"publishers/google/models/gemini-3.8-flash"}]}`} + tokenProvider := service.NewGeminiTokenProvider(nil, geminiVertexModelsTokenCache{}, nil) + h := &GatewayHandler{geminiCompatService: service.NewGeminiMessagesCompatService(repo, nil, nil, nil, tokenProvider, nil, upstream, nil, &config.Config{})} + apiKey := &service.APIKey{GroupID: &groupID, Group: &service.Group{ID: groupID, Platform: service.PlatformGemini}} + + t.Run("list", func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models", nil) + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + + h.GeminiV1BetaListModels(c) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.JSONEq(t, `{"models":[{"name":"models/gemini-3.8-flash","supportedGenerationMethods":["generateContent","streamGenerateContent"]}]}`, rec.Body.String()) + }) + + t.Run("get", func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models/gemini-3.8-flash", nil) + c.Params = gin.Params{{Key: "model", Value: "gemini-3.8-flash"}} + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + + h.GeminiV1BetaGetModel(c) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.JSONEq(t, `{"name":"models/gemini-3.8-flash","supportedGenerationMethods":["generateContent","streamGenerateContent"]}`, rec.Body.String()) + }) +} diff --git a/backend/internal/handler/group_localize_test.go b/backend/internal/handler/group_localize_test.go new file mode 100644 index 000000000..1bb984c67 --- /dev/null +++ b/backend/internal/handler/group_localize_test.go @@ -0,0 +1,92 @@ +package handler + +import ( + "encoding/json" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + + "github.com/MACOS-DO/sub4api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestToLocalizedModelPlazaGroups(t *testing.T) { + visible := []service.PlazaGroup{ + { + ID: 1, Name: "标准", Description: "号池", Platform: "anthropic", + I18n: service.GroupI18n{"en": {Name: "Standard", Description: "Pro + Max pool"}}, + }, + {ID: 2, Name: "无译文", Description: "原描述", Platform: "openai"}, + } + + english := toLocalizedModelPlazaGroups(visible, nil, "en") + require.Equal(t, "Standard", english[0].Name) + require.Equal(t, "Pro + Max pool", english[0].Description) + require.Equal(t, "无译文", english[1].Name) + require.Equal(t, "原描述", english[1].Description) + + chinese := toLocalizedModelPlazaGroups(visible, nil, "zh") + require.Equal(t, "标准", chinese[0].Name) + require.Equal(t, "号池", chinese[0].Description) + + // service 层对象不被改写,同一批分组可继续按别的语言输出 + require.Equal(t, "标准", visible[0].Name) + + raw, err := json.Marshal(english[0]) + require.NoError(t, err) + var decoded map[string]any + require.NoError(t, json.Unmarshal(raw, &decoded)) + require.NotContains(t, decoded, "i18n") +} + +func TestLocalizeUserAvailableGroups(t *testing.T) { + refs := []service.AvailableGroupRef{ + {ID: 1, Name: "标准", Platform: "anthropic", I18n: service.GroupI18n{"en": {Name: "Standard"}}}, + {ID: 2, Name: "无译文", Platform: "anthropic"}, + } + allowed := map[int64]struct{}{1: {}, 2: {}} + + english := filterUserVisibleGroups(refs, allowed) + localizeUserAvailableGroups(english, "en") + require.Equal(t, "Standard", english[0].Name) + require.Equal(t, "无译文", english[1].Name) + + chinese := filterUserVisibleGroups(refs, allowed) + localizeUserAvailableGroups(chinese, "zh") + require.Equal(t, "标准", chinese[0].Name) + + raw, err := json.Marshal(english[0]) + require.NoError(t, err) + var decoded map[string]any + require.NoError(t, json.Unmarshal(raw, &decoded)) + require.NotContains(t, decoded, "i18n") +} + +// 用户侧 handler 输出带分组的 DTO 时必须经过 Localized,否则分组名称与描述会 +// 停留在原字段,并把译文表原样带给用户。管理端(handler/admin)不在此列。 +func TestUserFacingGroupDTOsAreLocalized(t *testing.T) { + mapperCall := regexp.MustCompile(`dto\.(APIKey|UserSubscription|RedeemCode|UsageLog|Group)FromService[A-Za-z]*\(`) + + files, err := filepath.Glob("*.go") + require.NoError(t, err) + + checked := 0 + for _, file := range files { + if strings.HasSuffix(file, "_test.go") { + continue + } + source, err := os.ReadFile(file) + require.NoError(t, err) + for i, line := range strings.Split(string(source), "\n") { + if !mapperCall.MatchString(line) { + continue + } + checked++ + require.Containsf(t, line, ".Localized(", + "%s:%d outputs a group DTO without Localized(Accept-Language)", file, i+1) + } + } + require.NotZero(t, checked, "expected to find user-facing group DTO call sites") +} diff --git a/backend/internal/handler/model_plaza_handler.go b/backend/internal/handler/model_plaza_handler.go index f4d42cde1..c7d2747d8 100644 --- a/backend/internal/handler/model_plaza_handler.go +++ b/backend/internal/handler/model_plaza_handler.go @@ -151,10 +151,10 @@ func (h *ModelPlazaHandler) Get(c *gin.Context) { visible := filterPlazaVisibleGroups(groups, allowedGroups, restrictPublicGroups) - out := make([]modelPlazaGroup, 0, len(visible)) - for i := range visible { - out = append(out, toModelPlazaGroupDTO(&visible[i], userRates)) - } + // 广场可匿名访问,分组文案随请求语言变化,提示中间缓存按语言区分。 + // 追加而非覆盖:CORS 中间件已为具体来源写入 Vary: Origin。 + c.Writer.Header().Add("Vary", "Accept-Language") + out := toLocalizedModelPlazaGroups(visible, userRates, c.GetHeader("Accept-Language")) response.Success(c, modelPlazaResponse{ Description: rt.Description, Groups: out, @@ -185,6 +185,17 @@ func filterPlazaVisibleGroups( return visible } +// toLocalizedModelPlazaGroups 转换可见分组,并把名称与描述换成请求首选语言的版本。 +func toLocalizedModelPlazaGroups(visible []service.PlazaGroup, userRates map[int64]float64, acceptLanguage string) []modelPlazaGroup { + out := make([]modelPlazaGroup, 0, len(visible)) + for i := range visible { + group := toModelPlazaGroupDTO(&visible[i], userRates) + group.Name, group.Description = visible[i].I18n.Localize(acceptLanguage, group.Name, group.Description) + out = append(out, group) + } + return out +} + // toModelPlazaGroupDTO 将 service 层广场分组映射为白名单 DTO,并合并用户专属倍率。 func toModelPlazaGroupDTO(g *service.PlazaGroup, userRates map[int64]float64) modelPlazaGroup { models := make([]modelPlazaModel, 0, len(g.Models)) diff --git a/backend/internal/handler/model_plaza_handler_test.go b/backend/internal/handler/model_plaza_handler_test.go index 0a164fd11..1df199faa 100644 --- a/backend/internal/handler/model_plaza_handler_test.go +++ b/backend/internal/handler/model_plaza_handler_test.go @@ -3,11 +3,14 @@ package handler import ( + "context" "encoding/json" "net/http" "net/http/httptest" "testing" + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/MACOS-DO/sub4api/internal/server/middleware" "github.com/MACOS-DO/sub4api/internal/service" "github.com/gin-gonic/gin" @@ -262,3 +265,43 @@ func TestFilterPlazaVisibleGroups_SubscribedExclusiveGroup(t *testing.T) { require.Equal(t, int64(42), visible[0].ID) } } + +type plazaVarySettingRepo struct{ service.SettingRepository } + +func (plazaVarySettingRepo) GetMultiple(context.Context, []string) (map[string]string, error) { + return map[string]string{service.SettingKeyModelPlazaEnabled: "true"}, nil +} + +type plazaVaryChannelRepo struct{ service.ChannelRepository } + +func (plazaVaryChannelRepo) ListAll(context.Context) ([]service.Channel, error) { return nil, nil } + +type plazaVaryGroupRepo struct{ service.GroupRepository } + +func (plazaVaryGroupRepo) ListActive(context.Context) ([]service.Group, error) { return nil, nil } + +func TestModelPlazaHandler_VaryKeepsCORSOrigin(t *testing.T) { + gin.SetMode(gin.TestMode) + h := NewModelPlazaHandler( + service.NewModelPlazaService(plazaVaryChannelRepo{}, plazaVaryGroupRepo{}, nil, nil, nil), + nil, + service.NewSettingService(plazaVarySettingRepo{}, &config.Config{}), + ) + r := gin.New() + r.Use(middleware.CORS(config.CORSConfig{AllowedOrigins: []string{"https://a.example", "https://b.example"}})) + r.GET("/api/v1/model-plaza", h.Get) + + for _, origin := range []string{"https://a.example", "https://b.example"} { + req := httptest.NewRequest(http.MethodGet, "/api/v1/model-plaza", nil) + req.Header.Set("Origin", origin) + req.Header.Set("Accept-Language", "en") + w := httptest.NewRecorder() + + r.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + require.Equal(t, origin, w.Header().Get("Access-Control-Allow-Origin")) + // 共享缓存需同时按来源与语言区分,否则 A 来源的响应可能被复用给 B。 + require.Equal(t, []string{"Origin", "Accept-Language"}, w.Header().Values("Vary")) + } +} diff --git a/backend/internal/handler/no_account_error.go b/backend/internal/handler/no_account_error.go index 5f2002f7b..021b54630 100644 --- a/backend/internal/handler/no_account_error.go +++ b/backend/internal/handler/no_account_error.go @@ -123,10 +123,14 @@ func classifyNoAccountError( result := diag.DiagnoseModelAvailabilityForPlatform(ctx, apiKey.GroupID, routingModel, platform) if result.HasAccountsInPool && !result.HasModelSupport { + message := fmt.Sprintf("Model %q is not supported by any configured account in this group", displayModel) + if result.HasRetiredSubscriptionModel { + message = fmt.Sprintf("Model %q targets GPT-5.5, which retired from Codex with ChatGPT sign-in on October 14, 2026. Select an available replacement such as GPT-6.1 Sol or GPT-6 Luna, or configure an API-key upstream that supports GPT-5.5.", displayModel) + } return noAccountErrorClassification{ Status: http.StatusNotFound, ErrType: "model_not_found", - Message: fmt.Sprintf("Model %q is not supported by any configured account in this group", displayModel), + Message: message, ModelNotFound: true, } } diff --git a/backend/internal/handler/no_account_error_test.go b/backend/internal/handler/no_account_error_test.go index 6ff37fda0..6f8188f75 100644 --- a/backend/internal/handler/no_account_error_test.go +++ b/backend/internal/handler/no_account_error_test.go @@ -303,3 +303,22 @@ func TestClassifySelectionFailureError_StillUpgradesNonModelNotFoundFallback(t * require.Equal(t, "rate_limit_error", got.ErrType) require.False(t, got.ModelNotFound) } + +func TestClassifyNoAccountError_GPT55Retirement(t *testing.T) { + groupID := int64(1) + apiKey := &service.APIKey{GroupID: &groupID} + fd := &fakeDiagnoser{resp: service.ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasRetiredSubscriptionModel: true}} + cls := classifyNoAccountError(context.Background(), fd, apiKey, "gpt-5.5", "legacy", service.PlatformOpenAI) + require.Equal(t, http.StatusNotFound, cls.Status) + require.Equal(t, "model_not_found", cls.ErrType) + require.Contains(t, cls.Message, "retired") + require.Contains(t, cls.Message, "API-key") + fd.resp.HasModelSupport = true + cls = classifyNoAccountError(context.Background(), fd, apiKey, "gpt-5.5", "legacy", service.PlatformOpenAI) + require.Equal(t, http.StatusServiceUnavailable, cls.Status, "a temporarily unavailable API pool is not a retirement error") +} + +func TestGPT55RetirementEmptyListingDoesNotUseDefaults(t *testing.T) { + require.Empty(t, modelListingSource(service.PlatformOpenAI, []string{}, []string{"gpt-5.5"})) + require.Equal(t, []string{"gpt-5.5"}, modelListingSource(service.PlatformOpenAI, nil, []string{"gpt-5.5"})) +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 8e5506a87..13ef4157e 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -2558,6 +2558,11 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "Failed to resolve composite model route") return } + if decision.OAuthAmbiguous() { + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration) + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, decision.AmbiguousMessage()) + return + } if decision.Matched { c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision)) wsRouteModel = decision.UpstreamModel diff --git a/backend/internal/handler/ops_error_logger.go b/backend/internal/handler/ops_error_logger.go index 719f36315..1a20c1990 100644 --- a/backend/internal/handler/ops_error_logger.go +++ b/backend/internal/handler/ops_error_logger.go @@ -1183,6 +1183,14 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { } } + // Google 格式错误体没有 type 字段:按网关回写时登记的错误类型补齐。 + if errType, code := service.OpsLocalErrorType(c); errType != "" && !parsed.StreamFailure && + (parsed.ErrorType == "" || parsed.ErrorType == "api_error") { + parsed.ErrorType = errType + if code != "" { + parsed.Code = code + } + } normalizedType := normalizeOpsErrorType(parsed.ErrorType, parsed.Code) phase, isBusinessLimited, errorOwner, errorSource := classifyOpsErrorLog(c, normalizedType, parsed.Message, parsed.Code, status) @@ -2214,6 +2222,11 @@ func classifyOpsSeverity(errType string, status int) string { func classifyOpsErrorLog(c *gin.Context, errType, message, code string, status int) (phase string, isBusinessLimited bool, errorOwner string, errorSource string) { phase = classifyOpsPhase(errType, message, code) + if service.IsOpsRequestScopedError(c) { + // 失败由请求内容决定:只按错误类型分类,上游错误上下文不参与归因。 + isBusinessLimited = classifyOpsIsBusinessLimited(errType, phase, code, status, message) + return phase, isBusinessLimited, classifyOpsErrorOwner(phase, message), classifyOpsErrorSource(phase, message) + } routingCapacityLimited := isOpsRoutingCapacityLimited(c) clientBusinessLimited := service.HasOpsClientBusinessLimited(c) localModelConfiguration := clientBusinessLimited && service.OpsClientBusinessLimitedReason(c) == service.OpsClientBusinessLimitedReasonLocalModelConfiguration diff --git a/backend/internal/handler/ops_error_logger_google_test.go b/backend/internal/handler/ops_error_logger_google_test.go new file mode 100644 index 000000000..f82758229 --- /dev/null +++ b/backend/internal/handler/ops_error_logger_google_test.go @@ -0,0 +1,135 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/MACOS-DO/sub4api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// recordGoogleFormatOpsError 让 handle 以 Google 错误格式回写错误,返回 ops 中间件记录的错误日志。 +func recordGoogleFormatOpsError(t *testing.T, handle gin.HandlerFunc) *service.OpsInsertErrorLogInput { + t.Helper() + setupOpsErrorLogTestQueue(t, 1) + gin.SetMode(gin.TestMode) + ops := service.NewOpsService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + router := gin.New() + router.Use(OpsErrorLoggerMiddleware(ops)) + router.POST("/v1beta/cachedContents", handle) + + router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, "/v1beta/cachedContents", nil)) + + require.Equal(t, int64(1), OpsErrorLogQueueLength()) + return (<-opsErrorLogQueue).entry +} + +func TestOpsErrorLoggerMiddleware_GoogleClientErrorsClassifiedAsClient(t *testing.T) { + for _, tc := range []struct { + status int + errType string + phase string + }{ + {status: http.StatusBadRequest, errType: "invalid_request_error", phase: "request"}, + {status: http.StatusRequestEntityTooLarge, errType: "invalid_request_error", phase: "request"}, + {status: http.StatusUnauthorized, errType: "authentication_error", phase: "auth"}, + {status: http.StatusForbidden, errType: "permission_error", phase: "request"}, + {status: http.StatusNotFound, errType: "not_found_error", phase: "request"}, + } { + t.Run(http.StatusText(tc.status), func(t *testing.T) { + entry := recordGoogleFormatOpsError(t, func(c *gin.Context) { + googleError(c, tc.status, "client request problem") + }) + require.Equal(t, tc.status, entry.StatusCode) + require.Equal(t, tc.errType, entry.ErrorType) + require.Equal(t, tc.phase, entry.ErrorPhase) + require.Equal(t, "client", entry.ErrorOwner) + require.Equal(t, "client_request", entry.ErrorSource) + require.Equal(t, "P3", entry.Severity) + }) + } +} + +func TestOpsErrorLoggerMiddleware_GooglePlatformErrorStaysPlatform(t *testing.T) { + entry := recordGoogleFormatOpsError(t, func(c *gin.Context) { + googlePlatformError(c, http.StatusBadRequest, "Explicit context caching is not available for model m: storage pricing is not configured") + }) + require.Equal(t, "api_error", entry.ErrorType) + require.Equal(t, "internal", entry.ErrorPhase) + require.Equal(t, "platform", entry.ErrorOwner) + require.Equal(t, "gateway", entry.ErrorSource) +} + +func TestOpsErrorLoggerMiddleware_GoogleServerErrorsNotTypedByStatus(t *testing.T) { + entry := recordGoogleFormatOpsError(t, func(c *gin.Context) { + googleError(c, http.StatusInternalServerError, "Failed to persist cached content") + }) + require.Equal(t, "api_error", entry.ErrorType) + require.Equal(t, "platform", entry.ErrorOwner) +} + +func TestOpsErrorLoggerMiddleware_GoogleBillingErrorMatchesClaudeFormat(t *testing.T) { + entry := recordGoogleFormatOpsError(t, func(c *gin.Context) { + status, code, message, _ := billingErrorDetails(service.ErrInsufficientBalance) + googleErrorWithType(c, status, code, "", message) + }) + require.Equal(t, "billing_error", entry.ErrorType) + require.Equal(t, "request", entry.ErrorPhase) + require.Equal(t, "client", entry.ErrorOwner) + require.True(t, entry.IsBusinessLimited) +} + +func TestOpsErrorLoggerMiddleware_GoogleConcurrencyErrorClassifiedAsRequest(t *testing.T) { + entry := recordGoogleFormatOpsError(t, func(c *gin.Context) { + googleConcurrencyError(c, &ConcurrencyError{SlotType: "user"}, "user") + }) + require.Equal(t, http.StatusTooManyRequests, entry.StatusCode) + require.Equal(t, "rate_limit_error", entry.ErrorType) + require.Equal(t, "request", entry.ErrorPhase) + require.Equal(t, "client", entry.ErrorOwner) +} + +func TestOpsErrorLoggerMiddleware_GoogleErrorAfterUpstreamFailureKeepsUpstreamAttribution(t *testing.T) { + entry := recordGoogleFormatOpsError(t, func(c *gin.Context) { + service.SetOpsUpstreamError(c, http.StatusBadRequest, "upstream rejected", "") + googleError(c, http.StatusBadRequest, "upstream rejected") + }) + require.Equal(t, "upstream", entry.ErrorPhase) + require.Equal(t, "provider", entry.ErrorOwner) + require.Equal(t, "upstream_http", entry.ErrorSource) +} + +func TestOpsErrorLoggerMiddleware_RequestScopedUpstreamErrorClassifiedAsClient(t *testing.T) { + entry := recordGoogleFormatOpsError(t, func(c *gin.Context) { + service.SetOpsUpstreamError(c, http.StatusBadRequest, "Invalid resource state for cache content 8079767076522164224.", "") + c.Set(service.OpsUpstreamErrorsKey, []*service.OpsUpstreamErrorEvent{{ + Platform: service.PlatformGemini, AccountID: 173, UpstreamStatusCode: http.StatusBadRequest, Kind: "http_error", + Message: "Invalid resource state for cache content 8079767076522164224.", + }}) + service.MarkOpsRequestScopedError(c, "permission_error") + c.Data(http.StatusForbidden, "application/json", []byte(service.GeminiCachedContentNotFoundResponse)) + }) + require.Equal(t, http.StatusForbidden, entry.StatusCode) + require.Equal(t, "permission_error", entry.ErrorType) + require.Equal(t, "request", entry.ErrorPhase) + require.Equal(t, "client", entry.ErrorOwner) + require.Equal(t, "client_request", entry.ErrorSource) + require.False(t, entry.IsBusinessLimited) + require.NotNil(t, entry.UpstreamStatusCode, "上游原始错误保留为明细") + require.Equal(t, http.StatusBadRequest, *entry.UpstreamStatusCode) +} + +func TestSetOpsLocalErrorTypeClearsRequestScopedMark(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + service.MarkOpsRequestScopedError(c, "permission_error") + require.True(t, service.IsOpsRequestScopedError(c)) + + service.SetOpsLocalErrorType(c, "", "") + require.False(t, service.IsOpsRequestScopedError(c)) + errType, code := service.OpsLocalErrorType(c) + require.Empty(t, errType) + require.Empty(t, code) +} diff --git a/backend/internal/handler/payment_handler.go b/backend/internal/handler/payment_handler.go index 9c361f4f8..ddfdadde2 100644 --- a/backend/internal/handler/payment_handler.go +++ b/backend/internal/handler/payment_handler.go @@ -78,7 +78,7 @@ func (h *PaymentHandler) GetPlans(c *gin.Context) { gi := groupInfo[p.GroupID] result = append(result, planWithPlatform{ ID: int64(p.ID), GroupID: p.GroupID, - GroupPlatform: gi.Platform, GroupName: gi.Name, + GroupPlatform: gi.Platform, GroupName: gi.I18n.LocalizeName(c.GetHeader("Accept-Language"), gi.Name), RateMultiplier: gi.RateMultiplier, PeakRateEnabled: gi.PeakRateEnabled, PeakStart: gi.PeakStart, PeakEnd: gi.PeakEnd, PeakRateMultiplier: gi.PeakRateMultiplier, Name: p.Name, Description: p.Description, Price: p.Price, OriginalPrice: p.OriginalPrice, @@ -126,7 +126,7 @@ func (h *PaymentHandler) GetCheckoutInfo(c *gin.Context) { gi := groupInfo[p.GroupID] planList = append(planList, checkoutPlan{ ID: int64(p.ID), GroupID: p.GroupID, - GroupPlatform: gi.Platform, GroupName: gi.Name, + GroupPlatform: gi.Platform, GroupName: gi.I18n.LocalizeName(c.GetHeader("Accept-Language"), gi.Name), RateMultiplier: gi.RateMultiplier, PeakRateEnabled: gi.PeakRateEnabled, PeakStart: gi.PeakStart, PeakEnd: gi.PeakEnd, PeakRateMultiplier: gi.PeakRateMultiplier, diff --git a/backend/internal/handler/payment_webhook_handler.go b/backend/internal/handler/payment_webhook_handler.go index 9706930c2..522cedf74 100644 --- a/backend/internal/handler/payment_webhook_handler.go +++ b/backend/internal/handler/payment_webhook_handler.go @@ -103,7 +103,7 @@ func (h *PaymentWebhookHandler) handleNotify(c *gin.Context, providerKey string) headers[strings.ToLower(k)] = c.GetHeader(k) } - resolvedProviderKey, notification, err := verifyNotificationWithProviders(c.Request.Context(), providers, rawBody, headers) + verifiedProvider, notification, err := verifyNotificationWithProviders(c.Request.Context(), providers, rawBody, headers) if err != nil { truncatedBody := rawBody if len(truncatedBody) > webhookLogTruncateLen { @@ -115,12 +115,20 @@ func (h *PaymentWebhookHandler) handleNotify(c *gin.Context, providerKey string) return } + resolvedProviderKey := verifiedProvider.ProviderKey() + // nil notification means irrelevant event (e.g. Stripe non-payment event); return success. if notification == nil { writeSuccessResponse(c, resolvedProviderKey) return } + if err := h.paymentService.ConfirmNotificationUpstream(c.Request.Context(), verifiedProvider, notification); err != nil { + slog.Error("[Payment Webhook] upstream confirmation failed", "provider", resolvedProviderKey, "outTradeNo", notification.OrderID, "tradeNo", notification.TradeNo, "error", err) + c.String(http.StatusBadGateway, "confirm failed") + return + } + if err := h.paymentService.HandlePaymentNotification(c.Request.Context(), notification, resolvedProviderKey); err != nil { // Unknown order: ack with 2xx so the provider stops retrying. This // guards against foreign environments whose webhook endpoints are @@ -170,7 +178,10 @@ func extractOutTradeNo(rawBody, providerKey string) string { return "" } -func verifyNotificationWithProviders(ctx context.Context, providers []payment.Provider, rawBody string, headers map[string]string) (string, *payment.PaymentNotification, error) { +// verifyNotificationWithProviders returns the provider instance that verified +// the notification so later steps (upstream confirmation) use the same +// merchant configuration. +func verifyNotificationWithProviders(ctx context.Context, providers []payment.Provider, rawBody string, headers map[string]string) (payment.Provider, *payment.PaymentNotification, error) { var lastErr error for _, provider := range providers { if provider == nil { @@ -181,12 +192,12 @@ func verifyNotificationWithProviders(ctx context.Context, providers []payment.Pr lastErr = err continue } - return provider.ProviderKey(), notification, nil + return provider, notification, nil } if lastErr != nil { - return "", nil, lastErr + return nil, nil, lastErr } - return "", nil, fmt.Errorf("no webhook provider could verify notification") + return nil, nil, fmt.Errorf("no webhook provider could verify notification") } // wxpaySuccessResponse is the JSON response expected by WeChat Pay webhook. diff --git a/backend/internal/handler/payment_webhook_handler_test.go b/backend/internal/handler/payment_webhook_handler_test.go index 477bc0c7c..18115d331 100644 --- a/backend/internal/handler/payment_webhook_handler_test.go +++ b/backend/internal/handler/payment_webhook_handler_test.go @@ -204,9 +204,9 @@ func TestVerifyNotificationWithProvidersReturnsMatchedProvider(t *testing.T) { }, } - providerKey, notification, err := verifyNotificationWithProviders(context.Background(), providers, "{}", map[string]string{"wechatpay-signature": "sig"}) + provider, notification, err := verifyNotificationWithProviders(context.Background(), providers, "{}", map[string]string{"wechatpay-signature": "sig"}) require.NoError(t, err) - require.Equal(t, payment.TypeWxpay, providerKey) + require.Equal(t, payment.TypeWxpay, provider.ProviderKey()) require.NotNil(t, notification) require.Equal(t, "sub2_42", notification.OrderID) } diff --git a/backend/internal/handler/redeem_handler.go b/backend/internal/handler/redeem_handler.go index 4255c912c..a28d6d6a5 100644 --- a/backend/internal/handler/redeem_handler.go +++ b/backend/internal/handler/redeem_handler.go @@ -59,7 +59,7 @@ func (h *RedeemHandler) Redeem(c *gin.Context) { return } - response.Success(c, dto.RedeemCodeFromService(result)) + response.Success(c, dto.RedeemCodeFromService(result).Localized(c.GetHeader("Accept-Language"))) } // GetHistory returns the user's redemption history @@ -98,7 +98,7 @@ func (h *RedeemHandler) GetHistory(c *gin.Context) { } out := make([]dto.RedeemCode, 0, len(codes)) for i := range codes { - out = append(out, *dto.RedeemCodeFromService(&codes[i])) + out = append(out, *dto.RedeemCodeFromService(&codes[i]).Localized(c.GetHeader("Accept-Language"))) } response.Paginated(c, out, result.Total, page, pageSize) return @@ -115,7 +115,7 @@ func (h *RedeemHandler) GetHistory(c *gin.Context) { out := make([]dto.RedeemCode, 0, len(codes)) for i := range codes { - out = append(out, *dto.RedeemCodeFromService(&codes[i])) + out = append(out, *dto.RedeemCodeFromService(&codes[i]).Localized(c.GetHeader("Accept-Language"))) } response.Success(c, out) } diff --git a/backend/internal/handler/security_audit_errors.go b/backend/internal/handler/security_audit_errors.go index bf1c53e0b..3c1ef424a 100644 --- a/backend/internal/handler/security_audit_errors.go +++ b/backend/internal/handler/security_audit_errors.go @@ -100,9 +100,14 @@ func googleSecurityAuditError(c *gin.Context, decision *securityaudit.Decision) return } if decision.Legacy != nil && decision.Legacy.Blocked { - googleError(c, securityAuditStatus(decision), securityAuditMessage(decision)) + googleErrorWithType(c, securityAuditStatus(decision), securityAuditErrorCode(decision), "", securityAuditMessage(decision)) return } + errType := "api_error" + if decision.Kind == securityaudit.DecisionBlock { + errType = "permission_error" + } + service.SetOpsLocalErrorType(c, errType, securityAuditErrorCode(decision)) status := securityAuditStatus(decision) googleStatus := googleapi.HTTPStatusToGoogleStatus(status) if status == http.StatusServiceUnavailable { diff --git a/backend/internal/handler/security_audit_order_test.go b/backend/internal/handler/security_audit_order_test.go index e9cb4e1f9..2e0182930 100644 --- a/backend/internal/handler/security_audit_order_test.go +++ b/backend/internal/handler/security_audit_order_test.go @@ -24,6 +24,7 @@ func TestPromptAuditGatePrecedesAccountBillingAndUpstreamSideEffects(t *testing. {file: "gateway_handler_chat_completions.go", function: "ChatCompletions", auditToken: "checkSecurityAudit"}, {file: "gateway_handler_responses.go", function: "Responses", auditToken: "checkSecurityAudit"}, {file: "gemini_v1beta_handler.go", function: "GeminiV1BetaModels", auditToken: "checkSecurityAudit"}, + {file: "gemini_cached_contents_handler.go", function: "GeminiCachedContentsCreate", auditToken: "checkSecurityAudit"}, {file: "openai_gateway_handler.go", function: "Responses", auditToken: "checkSecurityAudit"}, {file: "openai_gateway_handler.go", function: "Messages", auditToken: "checkSecurityAudit"}, {file: "openai_chat_completions.go", function: "ChatCompletions", auditToken: "checkSecurityAudit"}, diff --git a/backend/internal/handler/subscription_handler.go b/backend/internal/handler/subscription_handler.go index f0fe68126..8275b31a7 100644 --- a/backend/internal/handler/subscription_handler.go +++ b/backend/internal/handler/subscription_handler.go @@ -59,7 +59,7 @@ func (h *SubscriptionHandler) List(c *gin.Context) { out := make([]dto.UserSubscription, 0, len(subscriptions)) for i := range subscriptions { - out = append(out, *dto.UserSubscriptionFromService(&subscriptions[i])) + out = append(out, *dto.UserSubscriptionFromService(&subscriptions[i]).Localized(c.GetHeader("Accept-Language"))) } response.Success(c, out) } @@ -81,7 +81,7 @@ func (h *SubscriptionHandler) GetActive(c *gin.Context) { out := make([]dto.UserSubscription, 0, len(subscriptions)) for i := range subscriptions { - out = append(out, *dto.UserSubscriptionFromService(&subscriptions[i])) + out = append(out, *dto.UserSubscriptionFromService(&subscriptions[i]).Localized(c.GetHeader("Accept-Language"))) } response.Success(c, out) } @@ -110,8 +110,11 @@ func (h *SubscriptionHandler) GetProgress(c *gin.Context) { // Skip subscriptions with errors continue } + if sub.Group != nil { + progress.GroupName = sub.Group.I18n.LocalizeName(c.GetHeader("Accept-Language"), progress.GroupName) + } result = append(result, SubscriptionProgressInfo{ - Subscription: dto.UserSubscriptionFromService(sub), + Subscription: dto.UserSubscriptionFromService(sub).Localized(c.GetHeader("Accept-Language")), Progress: progress, }) } @@ -150,7 +153,7 @@ func (h *SubscriptionHandler) GetSummary(c *gin.Context) { // Add group info if preloaded if sub.Group != nil { - item.GroupName = sub.Group.Name + item.GroupName = sub.Group.I18n.LocalizeName(c.GetHeader("Accept-Language"), sub.Group.Name) if sub.Group.DailyLimitUSD != nil { item.DailyLimitUSD = *sub.Group.DailyLimitUSD } diff --git a/backend/internal/handler/usage_handler.go b/backend/internal/handler/usage_handler.go index f6c1a67c0..e3a2db812 100644 --- a/backend/internal/handler/usage_handler.go +++ b/backend/internal/handler/usage_handler.go @@ -254,7 +254,7 @@ func (h *UsageHandler) List(c *gin.Context) { out := make([]dto.UsageLog, 0, len(records)) for i := range records { - out = append(out, *dto.UsageLogFromService(&records[i])) + out = append(out, *dto.UsageLogFromService(&records[i]).Localized(c.GetHeader("Accept-Language"))) } response.Paginated(c, out, result.Total, page, pageSize) } @@ -400,7 +400,7 @@ func (h *UsageHandler) GetByID(c *gin.Context) { return } - response.Success(c, dto.UsageLogFromService(record)) + response.Success(c, dto.UsageLogFromService(record).Localized(c.GetHeader("Accept-Language"))) } // Stats handles getting usage statistics diff --git a/backend/internal/handler/wire.go b/backend/internal/handler/wire.go index e741a06f7..4c49e1f35 100644 --- a/backend/internal/handler/wire.go +++ b/backend/internal/handler/wire.go @@ -118,11 +118,13 @@ func ProvideGatewayHandler( cfg *config.Config, settingService *service.SettingService, coordinator *securityaudit.Coordinator, + geminiCachedContentService *service.GeminiCachedContentService, ) *GatewayHandler { h := NewGatewayHandler(gatewayService, openAIGatewayService, geminiCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, userMsgQueueService, cfg, settingService) h.securityAuditCoordinator = coordinator + h.geminiCachedContentService = geminiCachedContentService return h } diff --git a/backend/internal/payment/provider/alipay.go b/backend/internal/payment/provider/alipay.go index 8ea4abb7b..d0e106707 100644 --- a/backend/internal/payment/provider/alipay.go +++ b/backend/internal/payment/provider/alipay.go @@ -10,6 +10,7 @@ import ( "time" "github.com/MACOS-DO/sub4api/internal/payment" + infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors" "github.com/smartwalle/alipay/v3" ) @@ -24,7 +25,10 @@ const ( const ( alipayFundChangeYes = "Y" alipayErrTradeNotExist = "ACQ.TRADE_NOT_EXIST" - alipayRefundSuffix = "-refund" + alipayRefundStatusSucc = "REFUND_SUCCESS" + alipayRefundRequestSep = "-refund-" + // 支付宝提示退款发起后过早查询可能查不到、之后又处理成功;超过该时长仍无记录才判定失败。 + alipayRefundQueryNotFoundGrace = 10 * time.Minute ) var ( @@ -37,6 +41,12 @@ var ( alipayTradePagePay = func(client *alipay.Client, param alipay.TradePagePay) (*url.URL, error) { return client.TradePagePay(param) } + alipayTradeRefund = func(ctx context.Context, client *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) { + return client.TradeRefund(ctx, param) + } + alipayTradeFastPayRefundQuery = func(ctx context.Context, client *alipay.Client, param alipay.TradeFastPayRefundQuery) (*alipay.TradeFastPayRefundQueryRsp, error) { + return client.TradeFastPayRefundQuery(ctx, param) + } ) // Alipay implements payment.Provider and payment.CancelableProvider using the smartwalle/alipay SDK. @@ -338,32 +348,76 @@ func (a *Alipay) Refund(ctx context.Context, req payment.RefundRequest) (*paymen return nil, err } - result, err := client.TradeRefund(ctx, alipay.TradeRefund{ + outRequestNo := fmt.Sprintf("%s%s%d", req.OrderID, alipayRefundRequestSep, time.Now().UnixNano()) + result, err := alipayTradeRefund(ctx, client, alipay.TradeRefund{ OutTradeNo: req.OrderID, RefundAmount: req.Amount, RefundReason: req.Reason, - OutRequestNo: fmt.Sprintf("%s-refund-%d", req.OrderID, time.Now().UnixNano()), + OutRequestNo: outRequestNo, }) if err != nil { return nil, fmt.Errorf("alipay TradeRefund: %w", err) } + if result == nil { + return nil, fmt.Errorf("alipay TradeRefund: empty response") + } refundStatus := payment.ProviderStatusPending if result.FundChange == alipayFundChangeYes { refundStatus = payment.ProviderStatusSuccess } - refundID := result.TradeNo - if refundID == "" { - refundID = req.OrderID + alipayRefundSuffix - } - + // fund_change != Y 时需凭退款请求号查询终态,因此 RefundID 记录 out_request_no。 return &payment.RefundResponse{ - RefundID: refundID, + RefundID: outRequestNo, Status: refundStatus, }, nil } +// QueryRefund 通过 alipay.trade.fastpay.refund.query 查询退款终态。refund_status 为 REFUND_SUCCESS +// 表示成功;退款发起超过宽限期仍查不到记录表示支付宝未受理或退款失败;其余情况视为仍在处理中。 +func (a *Alipay) QueryRefund(ctx context.Context, req payment.RefundQueryRequest) (*payment.RefundResponse, error) { + orderID := strings.TrimSpace(req.OrderID) + outRequestNo := strings.TrimSpace(req.RefundID) + // 旧版本把支付宝交易号记为 RefundID,无法据此查询退款请求,只能人工核实。 + if orderID == "" || !strings.HasPrefix(outRequestNo, orderID+alipayRefundRequestSep) { + return nil, infraerrors.BadRequest("REFUND_QUERY_UNSUPPORTED", "this refund was issued without a queryable refund request number; please verify manually") + } + client, err := a.getClient() + if err != nil { + return nil, err + } + result, err := alipayTradeFastPayRefundQuery(ctx, client, alipay.TradeFastPayRefundQuery{ + OutTradeNo: orderID, + OutRequestNo: outRequestNo, + }) + if err != nil { + return nil, fmt.Errorf("alipay query refund: %w", err) + } + if result == nil { + return nil, fmt.Errorf("alipay query refund: empty response") + } + // SDK 对带签名的业务失败响应(如 ACQ.SYSTEM_ERROR)不返回 error,字段为空; + // 不检查错误码会被误判为"无退款记录"而失败收尾。 + if result.IsFailure() { + return nil, fmt.Errorf("alipay query refund: %w", result.Error) + } + + status := payment.ProviderStatusPending + switch { + case strings.TrimSpace(result.RefundStatus) == alipayRefundStatusSucc: + status = payment.ProviderStatusSuccess + case strings.TrimSpace(result.OutRequestNo) == "" && strings.TrimSpace(result.RefundAmount) == "" && + alipayRefundAbsenceIsFinal(req.RequestedAt, time.Now()): + status = payment.ProviderStatusFailed + } + return &payment.RefundResponse{RefundID: outRequestNo, Status: status}, nil +} + +func alipayRefundAbsenceIsFinal(requestedAt, now time.Time) bool { + return !requestedAt.IsZero() && now.Sub(requestedAt) >= alipayRefundQueryNotFoundGrace +} + // CancelPayment closes a pending trade on Alipay. func (a *Alipay) CancelPayment(ctx context.Context, tradeNo string) error { client, err := a.getClient() @@ -406,5 +460,6 @@ func parseAlipayAmount(values ...string) (float64, error) { var ( _ payment.Provider = (*Alipay)(nil) _ payment.CancelableProvider = (*Alipay)(nil) + _ payment.RefundQueryProvider = (*Alipay)(nil) _ payment.MerchantIdentityProvider = (*Alipay)(nil) ) diff --git a/backend/internal/payment/provider/alipay_test.go b/backend/internal/payment/provider/alipay_test.go index 2ebeef72d..865f3aa63 100644 --- a/backend/internal/payment/provider/alipay_test.go +++ b/backend/internal/payment/provider/alipay_test.go @@ -8,6 +8,7 @@ import ( "net/url" "strings" "testing" + "time" "github.com/MACOS-DO/sub4api/internal/payment" "github.com/smartwalle/alipay/v3" @@ -444,3 +445,129 @@ func TestParseAlipayAmount(t *testing.T) { t.Fatal("expected error when no valid amount field exists") } } + +func TestAlipayRefundRecordsOutRequestNoAsRefundID(t *testing.T) { + origRefund := alipayTradeRefund + t.Cleanup(func() { alipayTradeRefund = origRefund }) + + for _, tc := range []struct { + fundChange string + wantStatus string + }{ + {fundChange: alipayFundChangeYes, wantStatus: payment.ProviderStatusSuccess}, + {fundChange: "N", wantStatus: payment.ProviderStatusPending}, + } { + var gotOutRequestNo string + alipayTradeRefund = func(_ context.Context, _ *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) { + if param.OutTradeNo != "sub2_7" || param.RefundAmount != "12.50" { + t.Fatalf("unexpected refund param: %+v", param) + } + gotOutRequestNo = param.OutRequestNo + return &alipay.TradeRefundRsp{TradeNo: "2026101522001", FundChange: tc.fundChange}, nil + } + + provider := &Alipay{client: &alipay.Client{}} + resp, err := provider.Refund(context.Background(), payment.RefundRequest{OrderID: "sub2_7", Amount: "12.50", Reason: "r"}) + if err != nil { + t.Fatalf("Refund() error = %v", err) + } + if resp.Status != tc.wantStatus { + t.Fatalf("fund_change=%s status = %q, want %q", tc.fundChange, resp.Status, tc.wantStatus) + } + if !strings.HasPrefix(gotOutRequestNo, "sub2_7-refund-") || resp.RefundID != gotOutRequestNo { + t.Fatalf("RefundID = %q, out_request_no = %q", resp.RefundID, gotOutRequestNo) + } + } +} + +func TestAlipayQueryRefundMapsStatus(t *testing.T) { + origQuery := alipayTradeFastPayRefundQuery + t.Cleanup(func() { alipayTradeFastPayRefundQuery = origQuery }) + + const outRequestNo = "sub2_7-refund-1760500000000000000" + ok := alipay.Error{Code: alipay.CodeSuccess, Msg: "Success"} + settled := time.Now().Add(-alipayRefundQueryNotFoundGrace - time.Minute) + for _, tc := range []struct { + name string + rsp *alipay.TradeFastPayRefundQueryRsp + requestedAt time.Time + wantStatus string + }{ + {name: "success", rsp: &alipay.TradeFastPayRefundQueryRsp{Error: ok, OutRequestNo: outRequestNo, RefundAmount: "12.50", RefundStatus: alipayRefundStatusSucc}, requestedAt: settled, wantStatus: payment.ProviderStatusSuccess}, + {name: "record without final status", rsp: &alipay.TradeFastPayRefundQueryRsp{Error: ok, OutRequestNo: outRequestNo, RefundAmount: "12.50"}, requestedAt: settled, wantStatus: payment.ProviderStatusPending}, + {name: "no refund record after grace", rsp: &alipay.TradeFastPayRefundQueryRsp{Error: ok}, requestedAt: settled, wantStatus: payment.ProviderStatusFailed}, + {name: "no refund record within grace", rsp: &alipay.TradeFastPayRefundQueryRsp{Error: ok}, requestedAt: time.Now().Add(-time.Minute), wantStatus: payment.ProviderStatusPending}, + {name: "no refund record with unknown request time", rsp: &alipay.TradeFastPayRefundQueryRsp{Error: ok}, wantStatus: payment.ProviderStatusPending}, + } { + t.Run(tc.name, func(t *testing.T) { + alipayTradeFastPayRefundQuery = func(_ context.Context, _ *alipay.Client, param alipay.TradeFastPayRefundQuery) (*alipay.TradeFastPayRefundQueryRsp, error) { + if param.OutTradeNo != "sub2_7" || param.OutRequestNo != outRequestNo { + t.Fatalf("unexpected query param: %+v", param) + } + return tc.rsp, nil + } + provider := &Alipay{client: &alipay.Client{}} + resp, err := provider.QueryRefund(context.Background(), payment.RefundQueryRequest{OrderID: "sub2_7", RefundID: outRequestNo, RequestedAt: tc.requestedAt}) + if err != nil { + t.Fatalf("QueryRefund() error = %v", err) + } + if resp.Status != tc.wantStatus || resp.RefundID != outRequestNo { + t.Fatalf("QueryRefund() = %+v, want status %q", resp, tc.wantStatus) + } + }) + } +} + +// SDK 对带签名的业务失败响应返回 err == nil,错误码只在响应体里。 +func TestAlipayQueryRefundBusinessFailureKeepsRefundPending(t *testing.T) { + origQuery := alipayTradeFastPayRefundQuery + t.Cleanup(func() { alipayTradeFastPayRefundQuery = origQuery }) + + for _, rspErr := range []alipay.Error{ + {Code: "40004", Msg: "Business Failed", SubCode: "ACQ.SYSTEM_ERROR", SubMsg: "系统错误"}, + {Code: "20000", Msg: "Service Currently Unavailable", SubCode: "isp.unknow-error"}, + {}, + } { + alipayTradeFastPayRefundQuery = func(context.Context, *alipay.Client, alipay.TradeFastPayRefundQuery) (*alipay.TradeFastPayRefundQueryRsp, error) { + return &alipay.TradeFastPayRefundQueryRsp{Error: rspErr}, nil + } + provider := &Alipay{client: &alipay.Client{}} + resp, err := provider.QueryRefund(context.Background(), payment.RefundQueryRequest{ + OrderID: "sub2_7", + RefundID: "sub2_7-refund-1", + RequestedAt: time.Now().Add(-24 * time.Hour), + }) + if err == nil { + t.Fatalf("code %q: QueryRefund() = %+v, want error", rspErr.Code, resp) + } + if rspErr.SubCode != "" && !strings.Contains(err.Error(), string(rspErr.Code)) { + t.Fatalf("code %q: error %q should carry the gateway code", rspErr.Code, err) + } + } +} + +func TestAlipayQueryRefundErrorsKeepRefundPending(t *testing.T) { + origQuery := alipayTradeFastPayRefundQuery + t.Cleanup(func() { alipayTradeFastPayRefundQuery = origQuery }) + + calls := 0 + alipayTradeFastPayRefundQuery = func(context.Context, *alipay.Client, alipay.TradeFastPayRefundQuery) (*alipay.TradeFastPayRefundQueryRsp, error) { + calls++ + return nil, errors.New("ACQ.SYSTEM_ERROR") + } + provider := &Alipay{client: &alipay.Client{}} + + // 旧版本记录的是支付宝交易号,无法查询退款请求,需人工核实,且不能调用网关。 + for _, legacyID := range []string{"", "2026101522001", "sub2_7-refund", "sub2_70-refund-1"} { + if _, err := provider.QueryRefund(context.Background(), payment.RefundQueryRequest{OrderID: "sub2_7", RefundID: legacyID}); err == nil || !strings.Contains(err.Error(), "verify manually") { + t.Fatalf("legacy refund id %q: err = %v", legacyID, err) + } + } + if calls != 0 { + t.Fatalf("legacy refund ids must not reach the gateway, calls = %d", calls) + } + + if _, err := provider.QueryRefund(context.Background(), payment.RefundQueryRequest{OrderID: "sub2_7", RefundID: "sub2_7-refund-1"}); err == nil { + t.Fatal("gateway error must be returned so the refund stays pending") + } +} diff --git a/backend/internal/payment/provider/easypay.go b/backend/internal/payment/provider/easypay.go index f58ac0c1b..aecb6791d 100644 --- a/backend/internal/payment/provider/easypay.go +++ b/backend/internal/payment/provider/easypay.go @@ -7,8 +7,10 @@ import ( "crypto/md5" "encoding/hex" "encoding/json" + "errors" "fmt" "io" + "math" "net/http" "net/url" "sort" @@ -27,6 +29,7 @@ const ( easypayHTTPTimeout = 10 * time.Second maxEasypayResponseSize = 1 << 20 // 1MB maxEasypayErrorSummary = 512 + easypayAmountTolerance = 0.005 tradeStatusSuccess = "TRADE_SUCCESS" signTypeMD5 = "MD5" paymentModePopup = "popup" @@ -301,32 +304,86 @@ func (e *EasyPay) upstreamPaymentType(paymentType string) string { } func (e *EasyPay) QueryOrder(ctx context.Context, tradeNo string) (*payment.QueryOrderResponse, error) { + result, err := e.queryOrder(ctx, tradeNo) + if err != nil { + return nil, err + } + responseTradeNo := tradeNo + if result.tradeNo != "" { + responseTradeNo = result.tradeNo + } + amount, _ := strconv.ParseFloat(result.money, 64) + return &payment.QueryOrderResponse{ + TradeNo: responseTradeNo, + Status: result.status, + Amount: amount, + Metadata: e.MerchantIdentityMetadata(), + }, nil +} + +// easyPayQueryResult is the normalized api.php?act=order answer. tradeNo is +// the upstream trade number exactly as returned (empty when absent). +type easyPayQueryResult struct { + status string + money string + tradeNo string +} + +func (e *EasyPay) queryOrder(ctx context.Context, outTradeNo string) (*easyPayQueryResult, error) { params := map[string]string{ "act": "order", "pid": e.config["pid"], - "key": e.config["pkey"], "out_trade_no": tradeNo, + "key": e.config["pkey"], "out_trade_no": outTradeNo, } - body, err := e.post(ctx, e.apiBase()+"/api.php", params) + // 彩虹易支付 and ZPay read act=order parameters from $_GET only (a + // body-only request is answered with "No Act!"), while other forks read + // the form body; send them in both places. + query := url.Values{} + for k, v := range params { + query.Set(k, v) + } + body, err := e.post(ctx, e.apiBase()+"/api.php?"+query.Encode(), params) if err != nil { + // The request URL carries the merchant key; never let it reach logs + // or audit records through *url.Error. + var urlErr *url.Error + if errors.As(err, &urlErr) { + err = urlErr.Err + } return nil, fmt.Errorf("easypay query: %w", err) } + // Scalars are decoded leniently: PHP deployments commonly serialize + // integer columns as strings ("status":"1"). type easyPayQueryData struct { - TradeStatus *string `json:"trade_status"` - Status *int `json:"status"` - Money *string `json:"money"` - TradeNo *string `json:"trade_no"` + TradeStatus *string `json:"trade_status"` + Status json.RawMessage `json:"status"` + Money json.RawMessage `json:"money"` + TradeNo json.RawMessage `json:"trade_no"` + OutTradeNo json.RawMessage `json:"out_trade_no"` } var resp struct { - Code int `json:"code"` - Msg string `json:"msg"` - TradeStatus *string `json:"trade_status"` - Status *int `json:"status"` - Money *string `json:"money"` - TradeNo *string `json:"trade_no"` - Data easyPayQueryData `json:"data"` + easyPayQueryData + Code any `json:"code"` + Msg string `json:"msg"` + Data easyPayQueryData `json:"data"` } if err := json.Unmarshal(body, &resp); err != nil { return nil, fmt.Errorf("easypay parse query: %w", err) } + // An explicit failure code wins over any paid-looking status field that + // may accompany it. + if resp.Code != nil && !easyPayResponseCodeIsSuccess(resp.Code) { + msg := strings.TrimSpace(resp.Msg) + if msg == "" { + msg = summarizeEasyPayResponse(body) + } + return nil, fmt.Errorf("easypay query failed: %s", msg) + } + // When the upstream echoes the order identity it must be this order; some + // implementations silently ignore unknown lookup parameters. + if echoed := easyPayJSONScalar(pickEasyPayJSON(resp.OutTradeNo, resp.Data.OutTradeNo)); echoed != "" && echoed != strings.TrimSpace(outTradeNo) { + return nil, fmt.Errorf("easypay query out_trade_no mismatch: expected %s, got %s", strings.TrimSpace(outTradeNo), echoed) + } + status := payment.ProviderStatusPending if resp.TradeStatus != nil { if *resp.TradeStatus == tradeStatusSuccess { @@ -336,36 +393,72 @@ func (e *EasyPay) QueryOrder(ctx context.Context, tradeNo string) (*payment.Quer if *resp.Data.TradeStatus == tradeStatusSuccess { status = payment.ProviderStatusPaid } - } else if resp.Status != nil { - if *resp.Status == easypayStatusPaid { + } else if raw := pickEasyPayJSON(resp.Status, resp.Data.Status); raw != nil { + if easyPayJSONScalar(raw) == strconv.Itoa(easypayStatusPaid) { status = payment.ProviderStatusPaid } - } else if resp.Data.Status != nil && *resp.Data.Status == easypayStatusPaid { - status = payment.ProviderStatusPaid } - money := "" - if resp.Money != nil { - money = *resp.Money - } else if resp.Data.Money != nil { - money = *resp.Data.Money + return &easyPayQueryResult{ + status: status, + money: easyPayJSONScalar(pickEasyPayJSON(resp.Money, resp.Data.Money)), + tradeNo: easyPayJSONScalar(pickEasyPayJSON(resp.TradeNo, resp.Data.TradeNo)), + }, nil +} + +// ConfirmNotification checks a verified success notification against the +// upstream order before it is fulfilled, so crediting follows the gateway's +// own order state (paid, amount, trade_no). The query is sent to this +// instance's own apiBase with its own credentials. +func (e *EasyPay) ConfirmNotification(ctx context.Context, n *payment.PaymentNotification) error { + if n == nil || n.Status != payment.NotificationStatusSuccess { + return nil } - responseTradeNo := tradeNo - if resp.TradeNo != nil { - if *resp.TradeNo != "" { - responseTradeNo = *resp.TradeNo + result, err := e.queryOrder(ctx, n.OrderID) + if err != nil { + return fmt.Errorf("easypay confirm: %w", err) + } + if result.status != payment.ProviderStatusPaid { + return fmt.Errorf("easypay confirm: upstream reports order %s as not paid", n.OrderID) + } + queriedAmount, err := strconv.ParseFloat(result.money, 64) + if err != nil || math.Abs(queriedAmount-n.Amount) > easypayAmountTolerance { + return fmt.Errorf("easypay confirm: amount mismatch: notified %v, upstream %q", n.Amount, result.money) + } + if result.tradeNo != "" { + if n.TradeNo != "" && n.TradeNo != result.tradeNo { + return fmt.Errorf("easypay confirm: trade_no mismatch: notified %s, upstream %s", n.TradeNo, result.tradeNo) } - } else if resp.Data.TradeNo != nil && *resp.Data.TradeNo != "" { - responseTradeNo = *resp.Data.TradeNo + n.TradeNo = result.tradeNo } + return nil +} - amount, _ := strconv.ParseFloat(money, 64) - return &payment.QueryOrderResponse{ - TradeNo: responseTradeNo, - Status: status, - Amount: amount, - Metadata: e.MerchantIdentityMetadata(), - }, nil +func easyPayJSONScalar(raw json.RawMessage) string { + if len(raw) == 0 { + return "" + } + var str string + if err := json.Unmarshal(raw, &str); err == nil { + return strings.TrimSpace(str) + } + var num json.Number + if err := json.Unmarshal(raw, &num); err == nil { + return num.String() + } + return "" +} + +// pickEasyPayJSON returns the top-level field when present, otherwise the +// nested data field. JSON null counts as absent. +func pickEasyPayJSON(top, nested json.RawMessage) json.RawMessage { + if len(top) > 0 && string(top) != "null" { + return top + } + if len(nested) > 0 && string(nested) != "null" { + return nested + } + return nil } func (e *EasyPay) VerifyNotification(_ context.Context, rawBody string, _ map[string]string) (*payment.PaymentNotification, error) { @@ -379,7 +472,14 @@ func (e *EasyPay) VerifyNotification(_ context.Context, rawBody string, _ map[st if !easyPayNotifyAllowedParams[k] { return nil, fmt.Errorf("unexpected notify param: %s", k) } - params[k] = values.Get(k) + v := values.Get(k) + // Notify values are plain tokens; only the merchant-defined product + // name is free text. Delimiter characters elsewhere are rejected so + // each value maps to exactly one field of the signed string. + if k != "name" && strings.ContainsAny(v, "&=") { + return nil, fmt.Errorf("invalid notify param value: %s", k) + } + params[k] = v } sign := params["sign"] if sign == "" { @@ -388,22 +488,20 @@ func (e *EasyPay) VerifyNotification(_ context.Context, rawBody string, _ map[st if !easyPayVerifySign(params, e.config["pkey"], sign) { return nil, fmt.Errorf("invalid signature") } + // Bind the notification to this instance's merchant directly instead of + // relying on the order snapshot, which legacy orders do not carry. + if expected, actual := strings.TrimSpace(e.config["pid"]), strings.TrimSpace(params["pid"]); actual != expected { + return nil, fmt.Errorf("easypay pid mismatch: expected %s, got %s", expected, actual) + } status := payment.ProviderStatusFailed if params["trade_status"] == tradeStatusSuccess { status = payment.ProviderStatusSuccess } amount, _ := strconv.ParseFloat(params["money"], 64) - metadata := e.MerchantIdentityMetadata() - if pid := strings.TrimSpace(params["pid"]); pid != "" { - if metadata == nil { - metadata = map[string]string{} - } - metadata["pid"] = pid - } return &payment.PaymentNotification{ TradeNo: params["trade_no"], OrderID: params["out_trade_no"], - Amount: amount, Status: status, RawData: rawBody, Metadata: metadata, + Amount: amount, Status: status, RawData: rawBody, Metadata: e.MerchantIdentityMetadata(), }, nil } diff --git a/backend/internal/payment/provider/easypay_confirm_test.go b/backend/internal/payment/provider/easypay_confirm_test.go new file mode 100644 index 000000000..a16d2f452 --- /dev/null +++ b/backend/internal/payment/provider/easypay_confirm_test.go @@ -0,0 +1,253 @@ +package provider + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + + "github.com/MACOS-DO/sub4api/internal/payment" +) + +func newConfirmTestEasyPay(t *testing.T, body string, status int) (*EasyPay, *atomic.Int32) { + t.Helper() + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + if err := r.ParseForm(); err != nil { + t.Errorf("ParseForm: %v", err) + } + q := r.URL.Query() + if r.URL.Path != "/api.php" || q.Get("act") != "order" || q.Get("pid") != "1001" || q.Get("key") != "pkey-1" || q.Get("out_trade_no") != "sub2_ORDER1" { + t.Errorf("unexpected query request: path=%s query=%v", r.URL.Path, q) + } + w.WriteHeader(status) + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(server.Close) + provider, err := NewEasyPay("test-instance", map[string]string{ + "pid": "1001", + "pkey": "pkey-1", + "apiBase": server.URL, + "notifyUrl": "https://example.com/notify", + "returnUrl": "https://example.com/return", + }) + if err != nil { + t.Fatalf("NewEasyPay: %v", err) + } + return provider, &calls +} + +func confirmTestNotification() *payment.PaymentNotification { + return &payment.PaymentNotification{ + TradeNo: "2026101600001", + OrderID: "sub2_ORDER1", + Amount: 10, + Status: payment.NotificationStatusSuccess, + } +} + +func TestEasyPayConfirmNotification(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + body string + status int + notifyTrade string + wantErr string + wantTradeNo string + }{ + { + name: "paid with matching amount and trade_no", + body: `{"code":1,"pid":1001,"out_trade_no":"sub2_ORDER1","trade_no":"2026101600001","money":"10.00","status":1}`, + notifyTrade: "2026101600001", + wantTradeNo: "2026101600001", + }, + { + name: "missing notify trade_no is filled from upstream", + body: `{"code":1,"trade_no":"2026101600001","money":"10.00","trade_status":"TRADE_SUCCESS"}`, + wantTradeNo: "2026101600001", + }, + { + name: "upstream not paid", + body: `{"code":1,"trade_no":"2026101600001","money":"10.00","status":0}`, + notifyTrade: "2026101600001", + wantErr: "not paid", + }, + { + name: "upstream failure code with paid status", + body: `{"code":-1,"msg":"订单号不存在","status":1,"money":"10.00"}`, + notifyTrade: "2026101600001", + wantErr: "订单号不存在", + }, + { + name: "amount mismatch", + body: `{"code":1,"trade_no":"2026101600001","money":"0.01","status":1}`, + notifyTrade: "2026101600001", + wantErr: "amount mismatch", + }, + { + name: "missing upstream amount", + body: `{"code":1,"trade_no":"2026101600001","status":1}`, + notifyTrade: "2026101600001", + wantErr: "amount mismatch", + }, + { + name: "trade_no conflict", + body: `{"code":1,"trade_no":"2026101699999","money":"10.00","status":1}`, + notifyTrade: "2026101600001", + wantErr: "trade_no mismatch", + }, + { + name: "string status from PHP deployment", + body: `{"code":"1","pid":"1001","out_trade_no":"sub2_ORDER1","trade_no":"2026101600001","money":"10.00","status":"1"}`, + notifyTrade: "2026101600001", + wantTradeNo: "2026101600001", + }, + { + name: "foreign order echo", + body: `{"code":1,"out_trade_no":"sub2_OTHER","trade_no":"2026101600001","money":"10.00","status":1}`, + notifyTrade: "2026101600001", + wantErr: "out_trade_no mismatch", + }, + { + name: "upstream HTTP error body", + body: `502 Bad Gateway`, + status: http.StatusBadGateway, + notifyTrade: "2026101600001", + wantErr: "parse query", + }, + } + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + status := tt.status + if status == 0 { + status = http.StatusOK + } + provider, calls := newConfirmTestEasyPay(t, tt.body, status) + n := confirmTestNotification() + n.TradeNo = tt.notifyTrade + err := provider.ConfirmNotification(context.Background(), n) + if calls.Load() != 1 { + t.Fatalf("upstream query calls = %d, want 1", calls.Load()) + } + if tt.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("ConfirmNotification error = %v, want containing %q", err, tt.wantErr) + } + return + } + if err != nil { + t.Fatalf("ConfirmNotification returned error: %v", err) + } + if n.TradeNo != tt.wantTradeNo { + t.Fatalf("trade_no = %q, want %q", n.TradeNo, tt.wantTradeNo) + } + }) + } +} + +func TestEasyPayConfirmNotificationSkipsNonSuccess(t *testing.T) { + t.Parallel() + + provider, calls := newConfirmTestEasyPay(t, `{}`, http.StatusOK) + n := confirmTestNotification() + n.Status = payment.ProviderStatusFailed + if err := provider.ConfirmNotification(context.Background(), n); err != nil { + t.Fatalf("ConfirmNotification returned error: %v", err) + } + if calls.Load() != 0 { + t.Fatalf("upstream query calls = %d, want 0", calls.Load()) + } +} + +func TestEasyPayConfirmNotificationQueryTransportError(t *testing.T) { + t.Parallel() + + server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + apiBase := server.URL + server.Close() + provider := newTestEasyPay(t, apiBase) + err := provider.ConfirmNotification(context.Background(), confirmTestNotification()) + if err == nil { + t.Fatal("ConfirmNotification must fail when the upstream is unreachable") + } + // The query URL carries the merchant key; errors are logged and stored in + // the payment audit trail, so they must not echo the URL. + if strings.Contains(err.Error(), "pkey-1") || strings.Contains(err.Error(), "key=") { + t.Fatalf("error contains the merchant key: %v", err) + } +} + +func TestEasyPayNotifyRejectsForeignPid(t *testing.T) { + t.Parallel() + e := easyPayPoCProvider() + + for _, pid := range []string{"2000", ""} { + params := map[string]string{ + "trade_no": "T1", + "out_trade_no": "ORDER123", + "type": "alipay", + "name": "balance recharge", + "money": "650.00", + "trade_status": tradeStatusSuccess, + } + if pid != "" { + params["pid"] = pid + } + params["sign"] = easyPaySign(params, e.config["pkey"]) + q := url.Values{} + for k, v := range params { + q.Set(k, v) + } + if _, err := e.VerifyNotification(context.Background(), q.Encode(), nil); err == nil { + t.Fatalf("callback with pid %q must be rejected", pid) + } + } +} + +func TestEasyPayNotifyAllowsFreeTextNameOnly(t *testing.T) { + t.Parallel() + e := easyPayPoCProvider() + + base := map[string]string{ + "pid": "1000", + "trade_no": "T1", + "out_trade_no": "ORDER123", + "type": "alipay", + "name": "Plan A&B = Pro", + "money": "650.00", + "trade_status": tradeStatusSuccess, + } + encode := func(params map[string]string) string { + signed := map[string]string{} + for k, v := range params { + signed[k] = v + } + signed["sign"] = easyPaySign(params, e.config["pkey"]) + q := url.Values{} + for k, v := range signed { + q.Set(k, v) + } + return q.Encode() + } + if _, err := e.VerifyNotification(context.Background(), encode(base), nil); err != nil { + t.Fatalf("free-text name must be accepted: %v", err) + } + for _, field := range []string{"trade_no", "out_trade_no", "type", "money", "param"} { + params := map[string]string{} + for k, v := range base { + params[k] = v + } + params[field] = "v&k=x" + if _, err := e.VerifyNotification(context.Background(), encode(params), nil); err == nil { + t.Fatalf("value with &/= in %s must be rejected", field) + } + } +} diff --git a/backend/internal/payment/provider/easypay_query_test.go b/backend/internal/payment/provider/easypay_query_test.go index 8a08d4348..64460fe68 100644 --- a/backend/internal/payment/provider/easypay_query_test.go +++ b/backend/internal/payment/provider/easypay_query_test.go @@ -20,6 +20,7 @@ func TestEasyPayQueryOrderStatusMapping(t *testing.T) { wantStatus string wantTradeNo string wantAmount float64 + wantErr bool }{ { name: "top level trade success is paid", @@ -64,10 +65,64 @@ func TestEasyPayQueryOrderStatusMapping(t *testing.T) { wantAmount: 3.21, }, { - name: "query failure with missing status is pending", - body: `{"code":0,"msg":"订单不存在"}`, + name: "query failure code is an error", + body: `{"code":0,"msg":"订单不存在"}`, + wantErr: true, + }, + { + name: "explicit failure code wins over paid status fields", + body: `{"code":-1,"msg":"签名错误","status":1,"trade_status":"TRADE_SUCCESS","money":"12.34"}`, + wantErr: true, + }, + { + name: "string failure code is an error", + body: `{"code":"-1","msg":"error","status":1}`, + wantErr: true, + }, + { + name: "foreign order echo is rejected", + body: `{"code":1,"pid":"pid-1","out_trade_no":"order-999","trade_status":"TRADE_SUCCESS","money":"12.34"}`, + wantErr: true, + }, + { + name: "foreign order echo in nested data is rejected", + body: `{"code":1,"data":{"out_trade_no":"order-999","trade_status":"TRADE_SUCCESS","money":"12.34"}}`, + wantErr: true, + }, + { + name: "string numeric status from PHP deployments is paid", + body: `{"code":"1","msg":"查询订单号成功!","trade_no":"2026101600001","out_trade_no":"order-123","pid":"1001","money":"12.34","status":"1"}`, + wantStatus: payment.ProviderStatusPaid, + wantTradeNo: "2026101600001", + wantAmount: 12.34, + }, + { + name: "string numeric unpaid status is pending", + body: `{"code":1,"trade_no":"2026101600001","money":"12.34","status":"0"}`, wantStatus: payment.ProviderStatusPending, - wantTradeNo: orderID, + wantTradeNo: "2026101600001", + wantAmount: 12.34, + }, + { + name: "documented caihong response with integer pid and status is paid", + body: `{"code":1,"msg":"查询订单号成功!","trade_no":"2016080622555342651","out_trade_no":"order-123","api_trade_no":"4200001","type":"alipay","pid":1001,"addtime":"2016-08-06 22:55:52","endtime":"2016-08-06 22:55:52","name":"VIP会员","money":"1.00","status":1,"param":"","buyer":""}`, + wantStatus: payment.ProviderStatusPaid, + wantTradeNo: "2016080622555342651", + wantAmount: 1, + }, + { + name: "null top-level fields fall back to nested data", + body: `{"code":1,"status":null,"money":null,"trade_no":null,"data":{"status":1,"money":"5.00","trade_no":"data-789"}}`, + wantStatus: payment.ProviderStatusPaid, + wantTradeNo: "data-789", + wantAmount: 5, + }, + { + name: "matching identity echo with numeric fields is paid", + body: `{"code":"1","pid":"pid-1","out_trade_no":"order-123","trade_status":"TRADE_SUCCESS","money":12.34,"trade_no":2026101600001}`, + wantStatus: payment.ProviderStatusPaid, + wantTradeNo: "2026101600001", + wantAmount: 12.34, }, { name: "missing fields are pending", @@ -93,9 +148,16 @@ func TestEasyPayQueryOrderStatusMapping(t *testing.T) { if err := r.ParseForm(); err != nil { t.Errorf("ParseForm: %v", err) } - gotForm = make(url.Values, len(r.PostForm)) + // Parameters must be in the URL query (彩虹易支付 reads $_GET) + // and mirrored in the body for forks that read $_POST. + gotForm = r.URL.Query() for key, values := range r.PostForm { - gotForm[key] = append([]string(nil), values...) + if got := gotForm.Get(key); got != values[0] { + t.Errorf("body[%s] = %q, query has %q", key, values[0], got) + } + } + if len(r.PostForm) != len(gotForm) { + t.Errorf("body params %v do not mirror query params %v", r.PostForm, gotForm) } w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(tt.body)) @@ -104,6 +166,12 @@ func TestEasyPayQueryOrderStatusMapping(t *testing.T) { provider := newTestEasyPay(t, server.URL) resp, err := provider.QueryOrder(context.Background(), orderID) + if tt.wantErr { + if err == nil { + t.Fatalf("QueryOrder succeeded, want error (response=%+v)", resp) + } + return + } if err != nil { t.Fatalf("QueryOrder returned error: %v", err) } diff --git a/backend/internal/payment/types.go b/backend/internal/payment/types.go index 6421c4afe..dc3ec58ff 100644 --- a/backend/internal/payment/types.go +++ b/backend/internal/payment/types.go @@ -2,7 +2,10 @@ // registry, load balancing, and shared utilities for the payment subsystem. package payment -import "context" +import ( + "context" + "time" +) // PaymentType represents a supported payment method. type PaymentType = string @@ -192,6 +195,8 @@ type RefundQueryRequest struct { OrderID string RefundID string Amount string + // RequestedAt 为退款进入 pending 的时间;零值表示未知。 + RequestedAt time.Time } // RefundResponse is returned after a refund request. @@ -234,6 +239,16 @@ type RefundQueryProvider interface { QueryRefund(ctx context.Context, req RefundQueryRequest) (*RefundResponse, error) } +// NotificationConfirmer extends Provider for gateways whose verified +// notifications are not sufficient proof of payment on their own. The webhook +// path calls ConfirmNotification on the instance that verified the +// notification before fulfillment; implementations query the upstream order +// and may fill in missing notification fields (e.g. TradeNo) from it. +type NotificationConfirmer interface { + Provider + ConfirmNotification(ctx context.Context, n *PaymentNotification) error +} + // CancelableProvider extends Provider with the ability to cancel pending payments. type CancelableProvider interface { Provider diff --git a/backend/internal/pkg/antigravity/claude_types.go b/backend/internal/pkg/antigravity/claude_types.go index 61e32b615..3af852c8f 100644 --- a/backend/internal/pkg/antigravity/claude_types.go +++ b/backend/internal/pkg/antigravity/claude_types.go @@ -169,6 +169,12 @@ type modelDef struct { var claudeModels = []modelDef{ {ID: "claude-fable-5-1", DisplayName: "Claude Fable 5.1", CreatedAt: "2026-09-01T00:00:00Z"}, {ID: "claude-fable-5", DisplayName: "Claude Fable 5", CreatedAt: "2026-06-09T00:00:00Z"}, + {ID: "claude-opus-5-5-high", DisplayName: "Claude Opus 5.5 (High)", CreatedAt: "2026-09-22T00:00:00Z"}, + {ID: "claude-opus-5-5-medium", DisplayName: "Claude Opus 5.5 (Medium)", CreatedAt: "2026-09-22T00:00:00Z"}, + {ID: "claude-opus-5-5-low", DisplayName: "Claude Opus 5.5 (Low)", CreatedAt: "2026-09-22T00:00:00Z"}, + {ID: "claude-sonnet-5-5-high", DisplayName: "Claude Sonnet 5.5 (High)", CreatedAt: "2026-09-28T00:00:00Z"}, + {ID: "claude-sonnet-5-5-medium", DisplayName: "Claude Sonnet 5.5 (Medium)", CreatedAt: "2026-09-28T00:00:00Z"}, + {ID: "claude-sonnet-5-5-low", DisplayName: "Claude Sonnet 5.5 (Low)", CreatedAt: "2026-09-28T00:00:00Z"}, {ID: "claude-opus-4-5-thinking", DisplayName: "Claude Opus 4.5 Thinking", CreatedAt: "2025-11-01T00:00:00Z"}, {ID: "claude-sonnet-4-5", DisplayName: "Claude Sonnet 4.5", CreatedAt: "2025-09-29T00:00:00Z"}, {ID: "claude-sonnet-4-5-thinking", DisplayName: "Claude Sonnet 4.5 Thinking", CreatedAt: "2025-09-29T00:00:00Z"}, @@ -208,6 +214,9 @@ var geminiModels = []modelDef{ {ID: "gemini-3.8-flash-low", DisplayName: "Gemini 3.8 Flash Low", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true}, {ID: "gemini-3.8-flash-medium", DisplayName: "Gemini 3.8 Flash Medium", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true}, {ID: "gemini-3.8-flash-tiered", DisplayName: "Gemini 3.8 Flash", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true}, + {ID: "gemini-4-argon-high", DisplayName: "Gemini 4 Argon (High)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true}, + {ID: "gemini-4-argon-low", DisplayName: "Gemini 4 Argon (Low)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true}, + {ID: "gemini-4-argon-medium", DisplayName: "Gemini 4 Argon (Medium)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true}, {ID: "gemini-3-pro-preview", DisplayName: "Gemini 3 Pro Preview", CreatedAt: "2025-06-01T00:00:00Z", IsReasoning: true}, {ID: "gemini-3-pro-image", DisplayName: "Gemini 3 Pro Image", CreatedAt: "2025-06-01T00:00:00Z"}, } @@ -277,6 +286,9 @@ func FallbackGeminiModel(model string) GeminiModel { // IsGeminiReasoningModel 判断是否为不支持参数和强制 ToolConfig 的 Gemini 推理模型 func IsGeminiReasoningModel(modelID string) bool { lowerID := strings.ToLower(modelID) + if strings.Contains(lowerID, "gemini-pro-agent") || strings.Contains(lowerID, "gemini-4-argon") { + return true + } for _, m := range geminiModels { if strings.Contains(lowerID, m.ID) && m.IsReasoning { return true diff --git a/backend/internal/pkg/antigravity/claude_types_test.go b/backend/internal/pkg/antigravity/claude_types_test.go index 1aa5bca31..e65dcc286 100644 --- a/backend/internal/pkg/antigravity/claude_types_test.go +++ b/backend/internal/pkg/antigravity/claude_types_test.go @@ -39,6 +39,15 @@ func TestDefaultModels_ContainsNewAndLegacyImageModels(t *testing.T) { "gemini-3.8-flash-low", "gemini-3.8-flash-medium", "gemini-3.8-flash-tiered", + "gemini-4-argon-high", + "gemini-4-argon-low", + "gemini-4-argon-medium", + "claude-opus-5-5-high", + "claude-opus-5-5-low", + "claude-opus-5-5-medium", + "claude-sonnet-5-5-high", + "claude-sonnet-5-5-low", + "claude-sonnet-5-5-medium", } for _, id := range requiredIDs { @@ -67,3 +76,23 @@ func TestClaudeContentItem_ThinkingAlwaysHasSignature(t *testing.T) { t.Fatalf("text block = %s, want %s", got, want) } } + +func TestIsGeminiReasoningModel_IncludesProAgent(t *testing.T) { + t.Parallel() + + if !IsGeminiReasoningModel("gemini-pro-agent") { + t.Fatal("expected gemini-pro-agent to be recognized as a Gemini reasoning model") + } + if !IsGeminiReasoningModel("gemini-3.8-flash-high") { + t.Fatal("expected gemini-3.8-flash-high to be recognized as a Gemini reasoning model") + } + if !IsGeminiReasoningModel("gemini-4-argon") { + t.Fatal("expected gemini-4-argon to be recognized as a Gemini reasoning model") + } + if !IsGeminiReasoningModel("gemini-4-argon-high") { + t.Fatal("expected gemini-4-argon-high to be recognized as a Gemini reasoning model") + } + if IsGeminiReasoningModel("gemini-2.5-flash") { + t.Fatal("did not expect gemini-2.5-flash to be recognized as a Gemini reasoning model") + } +} diff --git a/backend/internal/pkg/antigravity/client.go b/backend/internal/pkg/antigravity/client.go index f8925b623..052d68200 100644 --- a/backend/internal/pkg/antigravity/client.go +++ b/backend/internal/pkg/antigravity/client.go @@ -239,10 +239,39 @@ func TierIDToPlanType(tierID string) string { if tierID == "" { return "Free" } + // Google 新增的细分档位(如 g1-ultra-lite-tier、g1-pro-plus-tier)仍归入 Ultra / Pro。 + if plan := paidPlanFromTierID(tierID); plan != "" { + return plan + } return tierID } } +// paidPlanFromTierID 识别 g1-ultra-*-tier / g1-pro-*-tier 形式的付费档位 ID,未知时返回空串。 +func paidPlanFromTierID(tierID string) string { + id := strings.ToLower(strings.TrimSpace(tierID)) + if !strings.HasSuffix(id, "-tier") { + return "" + } + switch { + case strings.HasPrefix(id, "g1-ultra-"): + return "Ultra" + case strings.HasPrefix(id, "g1-pro-"): + return "Pro" + default: + return "" + } +} + +// IsPaidPlanType 判断账号记录的 plan_type 是否为付费套餐,兼容旧记录里直接保存的档位 ID。 +func IsPaidPlanType(planType string) bool { + switch strings.ToLower(strings.TrimSpace(planType)) { + case "pro", "ultra": + return true + } + return paidPlanFromTierID(planType) != "" +} + // Client Antigravity API 客户端 type Client struct { httpClient *http.Client @@ -653,8 +682,22 @@ type FetchAvailableModelsResponse struct { } // FetchAvailableModels 获取可用模型和配额信息,返回解析后的结构体和原始 JSON -// 支持 URL fallback:sandbox → daily → prod +// 保留旧调用的 URL fallback:prod → daily。 func (c *Client) FetchAvailableModels(ctx context.Context, accessToken, projectID string, bodyLimit int64) (*FetchAvailableModelsResponse, map[string]any, error) { + return c.fetchAvailableModels(ctx, BaseURLs, accessToken, projectID, bodyLimit, false) +} + +// FetchAvailableModelsFromURL 获取指定端点的模型目录,不回退到其他端点。 +// 模型发现应使用与生成请求相同的端点,避免返回该端点无法访问的模型。 +func (c *Client) FetchAvailableModelsFromURL(ctx context.Context, baseURL, accessToken, projectID string, bodyLimit int64) (*FetchAvailableModelsResponse, map[string]any, error) { + baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/") + if baseURL == "" { + return nil, nil, errors.New("fetchAvailableModels base URL is required") + } + return c.fetchAvailableModels(ctx, []string{baseURL}, accessToken, projectID, bodyLimit, true) +} + +func (c *Client) fetchAvailableModels(ctx context.Context, availableURLs []string, accessToken, projectID string, bodyLimit int64, fixedEndpoint bool) (*FetchAvailableModelsResponse, map[string]any, error) { if c == nil || c.httpClient == nil { return nil, nil, errors.New("antigravity client is not configured") } @@ -668,10 +711,10 @@ func (c *Client) FetchAvailableModels(ctx context.Context, accessToken, projectI return nil, nil, fmt.Errorf("序列化请求失败: %w", err) } - // 固定顺序:prod -> daily - availableURLs := BaseURLs - fetchClient := c.fetchAvailableModelsHTTPClient() + if fixedEndpoint { + fetchClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + } var lastErr error for urlIdx, baseURL := range availableURLs { apiURL := baseURL + "/v1internal:fetchAvailableModels" diff --git a/backend/internal/pkg/antigravity/client_test.go b/backend/internal/pkg/antigravity/client_test.go index 7a525879f..b6a342788 100644 --- a/backend/internal/pkg/antigravity/client_test.go +++ b/backend/internal/pkg/antigravity/client_test.go @@ -6,6 +6,7 @@ import ( "context" "encoding/json" "fmt" + "io" "net" "net/http" "net/http/httptest" @@ -260,6 +261,8 @@ func TestTierIDToPlanType(t *testing.T) { {"free-tier", "Free"}, {"g1-pro-tier", "Pro"}, {"g1-ultra-tier", "Ultra"}, + {"g1-ultra-lite-tier", "Ultra"}, + {"G1-Pro-Plus-Tier", "Pro"}, {"FREE-TIER", "Free"}, {"", "Free"}, {"unknown-tier", "unknown-tier"}, @@ -1468,6 +1471,113 @@ func TestClient_LoadCodeAssist_ContextCanceled_RealCall(t *testing.T) { // Client.FetchAvailableModels - 真正调用方法的测试 // --------------------------------------------------------------------------- +func TestClient_FetchAvailableModelsFromURL_UsesSelectedEndpoint(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1internal:fetchAvailableModels" || r.Method != http.MethodPost { + t.Errorf("unexpected model list request: %s %s", r.Method, r.URL.Path) + } + if r.Header.Get("Authorization") != "Bearer selected-token" { + t.Errorf("unexpected authorization header") + } + var body FetchAvailableModelsRequest + if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.Project != "selected-project" { + t.Errorf("unexpected project request: %+v, %v", body, err) + } + _, _ = w.Write([]byte(`{"models":{"gemini-3.8-flash-high":{"displayName":"Gemini 3.8 Flash High","supportsImages":true,"supportsThinking":true,"thinkingBudget":24576,"maxTokens":1048576,"maxOutputTokens":65536}}}`)) + })) + defer server.Close() + + client := mustNewClient(t, "") + response, raw, err := client.FetchAvailableModelsFromURL(context.Background(), server.URL, "selected-token", "selected-project", defaultFetchAvailableModelsBodyLimit) + if err != nil { + t.Fatalf("selected endpoint should return its catalog: %v", err) + } + model, ok := response.Models["gemini-3.8-flash-high"] + if !ok || model.SupportsThinking == nil || !*model.SupportsThinking || model.MaxTokens == nil || *model.MaxTokens != 1048576 { + t.Fatalf("selected endpoint metadata must remain available: %+v", model) + } + if raw["models"] == nil { + t.Fatal("selected endpoint raw catalog must remain available") + } +} + +func TestClient_FetchAvailableModelsFromURL_DoesNotFollowAnotherEndpoint(t *testing.T) { + otherEndpointCalls := 0 + other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + otherEndpointCalls++ + _, _ = w.Write([]byte(`{"models":{"other-endpoint-model":{}}}`)) + })) + defer other.Close() + selected := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, other.URL+"/v1internal:fetchAvailableModels", http.StatusTemporaryRedirect) + })) + defer selected.Close() + withMockBaseURLs(t, []string{selected.URL, other.URL}) + + response, _, err := mustNewClient(t, "").FetchAvailableModelsFromURL(context.Background(), selected.URL, "token", "project", defaultFetchAvailableModelsBodyLimit) + if err == nil || response != nil { + t.Fatalf("selected endpoint redirect must not produce another endpoint's catalog: %v, %v", response, err) + } + if otherEndpointCalls != 0 { + t.Fatalf("model discovery must stay on selected endpoint; other endpoint received %d requests", otherEndpointCalls) + } +} + +func TestClient_FetchAvailableModelsFromURL_DoesNotFallbackOnFailure(t *testing.T) { + for _, status := range []int{http.StatusNotFound, http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusForbidden} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + otherEndpointCalls := 0 + other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + otherEndpointCalls++ + _, _ = w.Write([]byte(`{"models":{"other-endpoint-model":{}}}`)) + })) + defer other.Close() + selected := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(status) + _, _ = w.Write([]byte(`{"error":"selected endpoint unavailable"}`)) + })) + defer selected.Close() + withMockBaseURLs(t, []string{selected.URL, other.URL}) + + response, raw, err := mustNewClient(t, "").FetchAvailableModelsFromURL(context.Background(), selected.URL, "token", "project", defaultFetchAvailableModelsBodyLimit) + if err == nil || response != nil || raw != nil { + t.Fatalf("selected endpoint HTTP %d must fail without another catalog: %v, %v", status, response, err) + } + if otherEndpointCalls != 0 { + t.Fatalf("another endpoint must not receive fallback requests: %d", otherEndpointCalls) + } + if status == http.StatusForbidden { + if _, ok := err.(*ForbiddenError); !ok { + t.Fatalf("403 must preserve typed forbidden error: %T", err) + } + } + }) + } +} + +func TestClient_FetchAvailableModelsFromURL_ValidatesResponseAndLimit(t *testing.T) { + for _, tc := range []struct { + name string + body string + limit int64 + }{ + {name: "invalid JSON", body: `not JSON`, limit: defaultFetchAvailableModelsBodyLimit}, + {name: "oversized response", body: `{"models":{"model":{}}}`, limit: 8}, + {name: "nonpositive limit", body: `{"models":{"model":{}}}`, limit: 0}, + } { + t.Run(tc.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, tc.body) + })) + defer server.Close() + _, _, err := mustNewClient(t, "").FetchAvailableModelsFromURL(context.Background(), server.URL, "token", "project", tc.limit) + if err == nil { + t.Fatal("invalid model catalog response or limit must fail") + } + }) + } +} + func TestClient_FetchAvailableModels_Success_RealCall(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { @@ -1787,6 +1897,51 @@ func TestClient_FetchAvailableModels_404Fallback_RealCall(t *testing.T) { } } +func TestClient_HubUserAgentAndIDEVersionUseContextOverride(t *testing.T) { + withTestUserAgentVersionResolver(t) + ctx := context.WithValue(context.Background(), userAgentVersionTestContextKey{}, "3.4.5") + const expectedUserAgent = "antigravity/hub/3.4.5 windows/amd64" + for _, action := range []string{"generateContent", "streamGenerateContent"} { + req, err := NewAPIRequestWithURL(ctx, "https://upstream.example", action, "test-token", []byte(`{}`)) + if err != nil { + t.Fatal(err) + } + if got := req.Header.Get("User-Agent"); got != expectedUserAgent { + t.Fatalf("generation request must use the context Hub user agent: %q", got) + } + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("User-Agent"); got != expectedUserAgent { + t.Errorf("client API must use the context Hub user agent: %q", got) + } + switch r.URL.Path { + case "/v1internal:loadCodeAssist": + var body LoadCodeAssistRequest + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + if body.Metadata.IDEVersion != "3.4.5" { + t.Errorf("ideVersion must match the user agent version: %q", body.Metadata.IDEVersion) + } + _, _ = io.WriteString(w, `{"cloudaicompanionProject":"test-project"}`) + case "/v1internal:fetchAvailableModels": + _, _ = io.WriteString(w, `{"models":{"gemini-4-argon-high":{}}}`) + default: + t.Errorf("unexpected client endpoint: %s", r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + defer server.Close() + withMockBaseURLs(t, []string{server.URL}) + client := mustNewClient(t, "") + if _, _, err := client.LoadCodeAssist(ctx, "test-token"); err != nil { + t.Fatal(err) + } + if _, _, err := client.FetchAvailableModelsFromURL(ctx, server.URL, "test-token", "test-project", defaultFetchAvailableModelsBodyLimit); err != nil { + t.Fatal(err) + } +} + func TestExtractProjectIDFromOnboardResponse(t *testing.T) { t.Parallel() diff --git a/backend/internal/pkg/antigravity/oauth.go b/backend/internal/pkg/antigravity/oauth.go index 223a7b5d0..24482a763 100644 --- a/backend/internal/pkg/antigravity/oauth.go +++ b/backend/internal/pkg/antigravity/oauth.go @@ -34,7 +34,7 @@ const ( AntigravityUserAgentVersionEnv = "ANTIGRAVITY_USER_AGENT_VERSION" // DefaultUserAgentVersion 是未通过环境变量或后台设置覆盖时使用的默认版本号。 - DefaultUserAgentVersion = "2.9.1" + DefaultUserAgentVersion = "2.23.0" // 固定的 redirect_uri(用户需手动复制 code) RedirectURI = "http://localhost:8085/callback" @@ -123,9 +123,9 @@ func GetUserAgentVersionForContext(ctx context.Context) string { // BuildUserAgent 使用指定版本号构造 User-Agent;版本为空或非法时回退默认值。 func BuildUserAgent(version string) string { if normalized := NormalizeUserAgentVersion(version); normalized != "" { - return fmt.Sprintf("antigravity/%s windows/amd64", normalized) + return fmt.Sprintf("antigravity/hub/%s windows/amd64", normalized) } - return fmt.Sprintf("antigravity/%s windows/amd64", defaultUserAgentVersion) + return fmt.Sprintf("antigravity/hub/%s windows/amd64", defaultUserAgentVersion) } // GetUserAgentForContext 返回当前请求应使用的 User-Agent。 diff --git a/backend/internal/pkg/antigravity/oauth_test.go b/backend/internal/pkg/antigravity/oauth_test.go index 4ebc7e543..f75f2b4ff 100644 --- a/backend/internal/pkg/antigravity/oauth_test.go +++ b/backend/internal/pkg/antigravity/oauth_test.go @@ -3,16 +3,119 @@ package antigravity import ( + "context" "crypto/sha256" "encoding/base64" "encoding/hex" "net/url" "os" + "os/exec" "strings" "testing" "time" ) +func TestBuildUserAgentUsesHubClientFamily(t *testing.T) { + if got := BuildUserAgent(" 2.23.0 "); got != "antigravity/hub/2.23.0 windows/amd64" { + t.Fatalf("Hub client family must be sent with the configured version: %q", got) + } +} + +func TestBuildUserAgentValidatesCustomVersion(t *testing.T) { + previous := defaultUserAgentVersion + defaultUserAgentVersion = "2.23.0" + t.Cleanup(func() { defaultUserAgentVersion = previous }) + for _, tc := range []struct { + version string + want string + }{ + {version: " 3.4.5 ", want: "antigravity/hub/3.4.5 windows/amd64"}, + {version: "", want: "antigravity/hub/2.23.0 windows/amd64"}, + {version: "hub/3.4.5", want: "antigravity/hub/2.23.0 windows/amd64"}, + {version: "3.4", want: "antigravity/hub/2.23.0 windows/amd64"}, + {version: "3.4.5\r\nInjected: header", want: "antigravity/hub/2.23.0 windows/amd64"}, + } { + t.Run(tc.version, func(t *testing.T) { + if got := BuildUserAgent(tc.version); got != tc.want { + t.Fatalf("custom version must be validated before building Hub user agent: got %q, want %q", got, tc.want) + } + }) + } +} + +type userAgentVersionTestContextKey struct{} + +func withTestUserAgentVersionResolver(t *testing.T) { + t.Helper() + userAgentVersionMu.RLock() + previous := userAgentVersionResolver + userAgentVersionMu.RUnlock() + SetUserAgentVersionResolver(func(ctx context.Context) string { + version, _ := ctx.Value(userAgentVersionTestContextKey{}).(string) + return version + }) + t.Cleanup(func() { SetUserAgentVersionResolver(previous) }) +} + +func TestGetUserAgentForContextPreservesVersionOverride(t *testing.T) { + withTestUserAgentVersionResolver(t) + previous := defaultUserAgentVersion + defaultUserAgentVersion = "2.23.0" + t.Cleanup(func() { defaultUserAgentVersion = previous }) + for _, tc := range []struct { + version string + want string + }{ + {version: " 3.4.5 ", want: "antigravity/hub/3.4.5 windows/amd64"}, + {version: "invalid", want: "antigravity/hub/2.23.0 windows/amd64"}, + } { + ctx := context.WithValue(context.Background(), userAgentVersionTestContextKey{}, tc.version) + if got := GetUserAgentForContext(ctx); got != tc.want { + t.Fatalf("context version override must use Hub family: got %q, want %q", got, tc.want) + } + } + if got := GetUserAgentForContext(nil); got != "antigravity/hub/2.23.0 windows/amd64" { + t.Fatalf("nil context must keep the default Hub user agent: %q", got) + } +} + +func TestGetUserAgentEnvironmentOverride(t *testing.T) { + const expectedVersionEnv = "SUB2API_TEST_EXPECTED_ANTIGRAVITY_VERSION" + if expected := os.Getenv(expectedVersionEnv); expected != "" { + if got := GetDefaultUserAgentVersion(); got != expected { + t.Fatalf("environment version must be loaded during initialization: got %q, want %q", got, expected) + } + if got := GetUserAgent(); got != "antigravity/hub/"+expected+" windows/amd64" { + t.Fatalf("environment override must keep Hub family: %q", got) + } + return + } + for _, tc := range []struct { + version string + want string + }{ + {version: " 3.4.5 ", want: "3.4.5"}, + {version: "invalid", want: "2.23.0"}, + } { + t.Run(tc.version, func(t *testing.T) { + binary, err := os.Executable() + if err != nil { + t.Fatal(err) + } + command := exec.Command(binary, "-test.run=^TestGetUserAgentEnvironmentOverride$") + for _, variable := range os.Environ() { + if !strings.HasPrefix(variable, AntigravityUserAgentVersionEnv+"=") && !strings.HasPrefix(variable, expectedVersionEnv+"=") { + command.Env = append(command.Env, variable) + } + } + command.Env = append(command.Env, AntigravityUserAgentVersionEnv+"="+tc.version, expectedVersionEnv+"="+tc.want) + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("environment override failed: %v\n%s", err, output) + } + }) + } +} + // --------------------------------------------------------------------------- // getClientSecret // --------------------------------------------------------------------------- @@ -693,7 +796,10 @@ func TestConstants_值正确(t *testing.T) { if RedirectURI != "http://localhost:8085/callback" { t.Errorf("RedirectURI 不匹配: got %s", RedirectURI) } - if GetUserAgent() != "antigravity/2.9.1 windows/amd64" { + if DefaultUserAgentVersion != "2.23.0" { + t.Errorf("default Hub version must match the verified upstream release: got %s", DefaultUserAgentVersion) + } + if GetUserAgent() != "antigravity/hub/2.23.0 windows/amd64" { t.Errorf("UserAgent 不匹配: got %s", GetUserAgent()) } if SessionTTL != 30*time.Minute { diff --git a/backend/internal/pkg/antigravity/request_transformer.go b/backend/internal/pkg/antigravity/request_transformer.go index 9349e54ee..a13748926 100644 --- a/backend/internal/pkg/antigravity/request_transformer.go +++ b/backend/internal/pkg/antigravity/request_transformer.go @@ -588,6 +588,7 @@ func buildParts(content json.RawMessage, toolIDToName map[string]string, allowDu ID: block.ToolUseID, }, }) + parts = append(parts, extractToolResultInlineParts(block.Content)...) } } @@ -638,6 +639,31 @@ func parseToolResultContent(content json.RawMessage, isError bool) string { return string(content) } +func extractToolResultInlineParts(content json.RawMessage) []GeminiPart { + if len(content) == 0 { + return nil + } + var innerBlocks []ContentBlock + if err := json.Unmarshal(content, &innerBlocks); err != nil { + return nil + } + var inlineParts []GeminiPart + for _, item := range innerBlocks { + if (item.Type == "image" || item.Type == "document") && + item.Source != nil && + item.Source.Type == "base64" && + strings.TrimSpace(item.Source.Data) != "" { + inlineParts = append(inlineParts, GeminiPart{ + InlineData: &GeminiInlineData{ + MimeType: item.Source.MediaType, + Data: item.Source.Data, + }, + }) + } + } + return inlineParts +} + // buildGenerationConfig 构建 generationConfig const ( defaultMaxOutputTokens = 64000 diff --git a/backend/internal/pkg/antigravity/request_transformer_test.go b/backend/internal/pkg/antigravity/request_transformer_test.go index 1aff9f577..7bdb40914 100644 --- a/backend/internal/pkg/antigravity/request_transformer_test.go +++ b/backend/internal/pkg/antigravity/request_transformer_test.go @@ -694,3 +694,64 @@ func TestToolConfigAlwaysPresent(t *testing.T) { }) } } + +func TestTransformClaudeToGemini_ToolResultImagesReachUpstream(t *testing.T) { + claudeReq := &ClaudeRequest{ + Model: "claude-sonnet-4-5", + Messages: []ClaudeMessage{ + { + Role: "assistant", + Content: json.RawMessage(`[ + {"type":"tool_use","id":"toolu_img_1","name":"read_image","input":{"path":"colors.png"}} + ]`), + }, + { + Role: "user", + Content: json.RawMessage(`[ + { + "type":"tool_result", + "tool_use_id":"toolu_img_1", + "content":[ + {"type":"text","text":"loaded colors.png"}, + {"type":"image","source":{"type":"base64","media_type":"image/png","data":"aGVsbG8="}} + ] + }, + { + "type":"tool_result", + "tool_use_id":"toolu_img_1", + "content":[ + {"type":"image","source":{"type":"base64","media_type":"image/jpeg","data":"d29ybGQ="}} + ] + } + ]`), + }, + }, + } + + body, err := TransformClaudeToGeminiWithOptions(claudeReq, "project-1", "claude-sonnet-4-5", DefaultTransformOptions()) + require.NoError(t, err) + + var req V1InternalRequest + require.NoError(t, json.Unmarshal(body, &req)) + require.Len(t, req.Request.Contents, 2) + + userParts := req.Request.Contents[1].Parts + require.Len(t, userParts, 4) + + require.NotNil(t, userParts[0].FunctionResponse) + require.Equal(t, "read_image", userParts[0].FunctionResponse.Name) + require.Equal(t, "toolu_img_1", userParts[0].FunctionResponse.ID) + require.Equal(t, "loaded colors.png", userParts[0].FunctionResponse.Response["result"]) + + require.NotNil(t, userParts[1].InlineData) + require.Equal(t, "image/png", userParts[1].InlineData.MimeType) + require.Equal(t, "aGVsbG8=", userParts[1].InlineData.Data) + + require.NotNil(t, userParts[2].FunctionResponse) + require.Equal(t, "read_image", userParts[2].FunctionResponse.Name) + require.Equal(t, "Command executed successfully.", userParts[2].FunctionResponse.Response["result"]) + + require.NotNil(t, userParts[3].InlineData) + require.Equal(t, "image/jpeg", userParts[3].InlineData.MimeType) + require.Equal(t, "d29ybGQ=", userParts[3].InlineData.Data) +} diff --git a/backend/internal/pkg/apicompat/anthropic_responses_test.go b/backend/internal/pkg/apicompat/anthropic_responses_test.go index 5902128b9..700af63d4 100644 --- a/backend/internal/pkg/apicompat/anthropic_responses_test.go +++ b/backend/internal/pkg/apicompat/anthropic_responses_test.go @@ -1940,6 +1940,72 @@ func TestSonnet55SignedThinkingResponsesRoundTrip(t *testing.T) { require.Equal(t, "tool_use", blocks[2].Type) } +func TestHaiku55ResponsesThinkingAndSampling(t *testing.T) { + for _, effort := range []string{"", "low", "medium", "high", "xhigh", "max", "none"} { + req := &ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), Reasoning: &ResponsesReasoning{Effort: effort}} + out, err := ResponsesToAnthropicRequest(req) + require.NoError(t, err, effort) + require.Zero(t, out.Thinking.BudgetTokens) + if effort == "none" { + require.Equal(t, "disabled", out.Thinking.Type) + require.Equal(t, "low", out.OutputConfig.Effort) + } else { + require.Equal(t, "adaptive", out.Thinking.Type) + if effort == "" { + effort = "medium" + } + require.Equal(t, effort, out.OutputConfig.Effort) + } + } + // Haiku 5.5 accepts forced tool_choice, unlike opus/sonnet 5.5. + for _, choice := range []string{`"required"`, `{"type":"function","name":"lookup"}`} { + out, err := ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), ToolChoice: json.RawMessage(choice)}) + require.NoError(t, err, choice) + require.NotEmpty(t, out.ToolChoice) + } + temperature := 0.7 + _, err := ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), Temperature: &temperature}) + require.ErrorContains(t, err, "temperature") + for _, topP := range []float64{0.5, 0.995, 1} { + _, err = ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), TopP: &topP}) + require.ErrorContains(t, err, "top_p", "top_p=%v", topP) + } + _, err = ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), Reasoning: &ResponsesReasoning{Effort: "minimal"}}) + require.ErrorContains(t, err, "reasoning effort") + + temperature = 1 + topP := 0.99 + _, err = ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), Temperature: &temperature}) + require.NoError(t, err) + _, err = ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), TopP: &topP}) + require.NoError(t, err) + _, err = ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: json.RawMessage(`"hello"`), Temperature: &temperature, TopP: &topP}) + require.ErrorContains(t, err, "together") +} + +func TestHaiku55SignedThinkingResponsesRoundTrip(t *testing.T) { + block := AnthropicContentBlock{Type: "thinking", Thinking: "", Signature: "signed-haiku-block"} + response := AnthropicToResponsesResponse(&AnthropicResponse{Model: "claude-haiku-5-5", Content: []AnthropicContentBlock{block, {Type: "text", Text: "progress"}, {Type: "tool_use", ID: "toolu_1", Name: "lookup", Input: json.RawMessage(`{}`)}}}) + require.Len(t, response.Output, 3) + require.NotEmpty(t, response.Output[0].EncryptedContent) + require.Equal(t, "message", response.Output[1].Type) + raw, err := json.Marshal(response.Output) + require.NoError(t, err) + var items []ResponsesInputItem + require.NoError(t, json.Unmarshal(raw, &items)) + items = append(items, ResponsesInputItem{Type: "function_call_output", CallID: response.Output[2].CallID, Output: "ok"}) + raw, err = json.Marshal(items) + require.NoError(t, err) + converted, err := ResponsesToAnthropicRequest(&ResponsesRequest{Model: "claude-haiku-5-5", Input: raw}) + require.NoError(t, err) + require.Len(t, converted.Messages, 2) + var blocks []AnthropicContentBlock + require.NoError(t, json.Unmarshal(converted.Messages[0].Content, &blocks)) + require.Equal(t, block, blocks[0]) + require.Equal(t, "text", blocks[1].Type) + require.Equal(t, "tool_use", blocks[2].Type) +} + func TestGPT6ChatSamplingAndCacheFields(t *testing.T) { temperature := 0.7 for _, model := range []string{"gpt-6-sol", "gpt-6-luna"} { diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses.go b/backend/internal/pkg/apicompat/anthropic_to_responses.go index 6611d9446..c96e55d65 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses.go @@ -13,6 +13,12 @@ import ( // Chat Completions intermediary round-trip (e.g. thinking, cache_control, // structured system prompts). func AnthropicToResponses(req *AnthropicRequest) (*ResponsesRequest, error) { + return AnthropicToResponsesWithMinOutputTokens(req, DefaultMinMaxOutputTokens) +} + +// AnthropicToResponsesWithMinOutputTokens converts an Anthropic request using +// the supplied max_output_tokens floor. +func AnthropicToResponsesWithMinOutputTokens(req *AnthropicRequest, minOutputTokens int) (*ResponsesRequest, error) { if err := openai.ValidateGPT61SolReasoningEffort(req.Model, anthropicReasoningEffort(req)); err != nil { return nil, err } @@ -50,8 +56,8 @@ func AnthropicToResponses(req *AnthropicRequest) (*ResponsesRequest, error) { if req.MaxTokens > 0 { v := req.MaxTokens - if v < minMaxOutputTokens { - v = minMaxOutputTokens + if v < minOutputTokens { + v = minOutputTokens } out.MaxOutputTokens = &v } diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go index 62c2f253f..ce1b8eca4 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go @@ -53,7 +53,7 @@ func AnthropicToResponsesResponse(resp *AnthropicResponse) *ResponsesResponse { for _, block := range resp.Content { switch block.Type { case "thinking", "redacted_thinking": - if (claude.IsOpus55(resp.Model) || claude.IsSonnet55(resp.Model)) && (block.Signature != "" || block.Data != "") { + if (claude.IsOpus55(resp.Model) || claude.IsSonnet55(resp.Model) || claude.IsHaiku55(resp.Model)) && (block.Signature != "" || block.Data != "") { item := ResponsesOutput{Type: "reasoning", ID: generateItemID(), EncryptedContent: encodeAnthropicThinking(block)} if block.Thinking != "" { item.Summary = []ResponsesSummary{{Type: "summary_text", Text: block.Thinking}} @@ -72,7 +72,7 @@ func AnthropicToResponsesResponse(resp *AnthropicResponse) *ResponsesResponse { }) } case "text": - if (claude.IsOpus55(resp.Model) || claude.IsSonnet55(resp.Model)) && block.Text != "" { + if (claude.IsOpus55(resp.Model) || claude.IsSonnet55(resp.Model) || claude.IsHaiku55(resp.Model)) && block.Text != "" { outputs = append(outputs, ResponsesOutput{Type: "message", ID: generateItemID(), Role: "assistant", Status: "completed", Content: []ResponsesContentPart{{Type: "output_text", Text: block.Text}}}) continue } @@ -285,7 +285,7 @@ func ResponsesEventToSSE(evt ResponsesStreamEvent) (string, error) { func anthToResHandleMessageStart(evt *AnthropicStreamEvent, state *AnthropicEventToResponsesState) []ResponsesStreamEvent { if evt.Message != nil { state.ResponseID = evt.Message.ID - state.PreserveThinkingSignatures = state.PreserveThinkingSignatures || claude.IsOpus55(evt.Message.Model) || claude.IsSonnet55(evt.Message.Model) + state.PreserveThinkingSignatures = state.PreserveThinkingSignatures || claude.IsOpus55(evt.Message.Model) || claude.IsSonnet55(evt.Message.Model) || claude.IsHaiku55(evt.Message.Model) if state.Model == "" { state.Model = evt.Message.Model } diff --git a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go index fc73afa3a..20a590c1c 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go +++ b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go @@ -40,6 +40,12 @@ import ( // ResponsesToChatCompletionsRequest but avoids materializing the intermediate // ResponsesRequest and the extra marshal/unmarshal cycle. func AnthropicToChatCompletionsRequest(req *AnthropicRequest) (*ChatCompletionsRequest, error) { + return AnthropicToChatCompletionsRequestWithMinOutputTokens(req, DefaultMinMaxOutputTokens) +} + +// AnthropicToChatCompletionsRequestWithMinOutputTokens converts an Anthropic +// Messages request using the supplied max_completion_tokens floor. +func AnthropicToChatCompletionsRequestWithMinOutputTokens(req *AnthropicRequest, minOutputTokens int) (*ChatCompletionsRequest, error) { if req == nil { return nil, fmt.Errorf("anthropic request is nil") } @@ -63,8 +69,8 @@ func AnthropicToChatCompletionsRequest(req *AnthropicRequest) (*ChatCompletionsR if req.MaxTokens > 0 { v := req.MaxTokens - if v < minMaxOutputTokens { - v = minMaxOutputTokens + if v < minOutputTokens { + v = minOutputTokens } out.MaxCompletionTokens = &v } diff --git a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge_test.go b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge_test.go index b278c28a8..13cc945ca 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge_test.go +++ b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge_test.go @@ -267,6 +267,43 @@ func TestAnthropicToChatCompletionsRequest_MaxTokensFloor(t *testing.T) { require.Equal(t, minMaxOutputTokens, *out.MaxCompletionTokens) } +func TestAnthropicToChatCompletionsRequestWithMinOutputTokens_ConfiguredFloor(t *testing.T) { + req := &AnthropicRequest{ + Model: "claude-sonnet-4-20250514", + MaxTokens: 16, + Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}}, + } + + out, err := AnthropicToChatCompletionsRequestWithMinOutputTokens(req, 64) + require.NoError(t, err) + require.NotNil(t, out.MaxCompletionTokens) + require.Equal(t, 64, *out.MaxCompletionTokens) +} + +func TestAnthropicToResponses_ConfiguredMaxTokensFloor(t *testing.T) { + for _, input := range []int{16, 64, 127} { + req := &AnthropicRequest{ + Model: "claude-sonnet-4-20250514", + MaxTokens: input, + Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}}, + } + out, err := AnthropicToResponsesWithMinOutputTokens(req, 16) + require.NoError(t, err) + require.NotNil(t, out.MaxOutputTokens) + require.Equal(t, input, *out.MaxOutputTokens) + } + + req := &AnthropicRequest{ + Model: "claude-sonnet-4-20250514", + MaxTokens: 1, + Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}}, + } + out, err := AnthropicToResponsesWithMinOutputTokens(req, 16) + require.NoError(t, err) + require.NotNil(t, out.MaxOutputTokens) + require.Equal(t, 16, *out.MaxOutputTokens) +} + func TestAnthropicToChatCompletionsRequest_ReasoningEffortMapping(t *testing.T) { req := &AnthropicRequest{ Model: "gpt-5.4", diff --git a/backend/internal/pkg/apicompat/chatcompletions_responses_test.go b/backend/internal/pkg/apicompat/chatcompletions_responses_test.go index 1a27ef237..b94bc5c39 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_responses_test.go +++ b/backend/internal/pkg/apicompat/chatcompletions_responses_test.go @@ -2,6 +2,7 @@ package apicompat import ( "encoding/json" + "fmt" "testing" "github.com/stretchr/testify/assert" @@ -290,6 +291,46 @@ func mustMarshalJSON(t *testing.T, value any) []byte { } func TestChatCompletionsToResponses_MaxTokens(t *testing.T) { + t.Run("default floor", func(t *testing.T) { + maxTokens := 1 + req := &ChatCompletionsRequest{ + Model: "gpt-4o", + MaxTokens: &maxTokens, + Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Hi"`)}}, + } + resp, err := ChatCompletionsToResponses(req) + require.NoError(t, err) + require.NotNil(t, resp.MaxOutputTokens) + assert.Equal(t, DefaultMinMaxOutputTokens, *resp.MaxOutputTokens) + }) + + t.Run("configured floor", func(t *testing.T) { + for _, input := range []int{16, 64, 127, 128} { + input := input + t.Run(fmt.Sprintf("input_%d", input), func(t *testing.T) { + req := &ChatCompletionsRequest{ + Model: "gpt-4o", + MaxTokens: &input, + Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Hi"`)}}, + } + resp, err := ChatCompletionsToResponsesWithMinOutputTokens(req, 16) + require.NoError(t, err) + require.NotNil(t, resp.MaxOutputTokens) + assert.Equal(t, input, *resp.MaxOutputTokens) + }) + } + input := 1 + req := &ChatCompletionsRequest{ + Model: "gpt-4o", + MaxTokens: &input, + Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Hi"`)}}, + } + resp, err := ChatCompletionsToResponsesWithMinOutputTokens(req, 16) + require.NoError(t, err) + require.NotNil(t, resp.MaxOutputTokens) + assert.Equal(t, 16, *resp.MaxOutputTokens) + }) + t.Run("max_tokens", func(t *testing.T) { maxTokens := 100 req := &ChatCompletionsRequest{ @@ -318,6 +359,21 @@ func TestChatCompletionsToResponses_MaxTokens(t *testing.T) { require.NotNil(t, resp.MaxOutputTokens) assert.Equal(t, 500, *resp.MaxOutputTokens) }) + + t.Run("max_completion_tokens_preferred before configured floor", func(t *testing.T) { + maxTokens := 500 + maxCompletion := 1 + req := &ChatCompletionsRequest{ + Model: "gpt-4o", + MaxTokens: &maxTokens, + MaxCompletionTokens: &maxCompletion, + Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Hi"`)}}, + } + resp, err := ChatCompletionsToResponsesWithMinOutputTokens(req, 16) + require.NoError(t, err) + require.NotNil(t, resp.MaxOutputTokens) + assert.Equal(t, 16, *resp.MaxOutputTokens) + }) } func TestChatCompletionsToResponses_ReasoningEffort(t *testing.T) { diff --git a/backend/internal/pkg/apicompat/chatcompletions_to_responses.go b/backend/internal/pkg/apicompat/chatcompletions_to_responses.go index e7c447d0f..e12e366af 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_to_responses.go +++ b/backend/internal/pkg/apicompat/chatcompletions_to_responses.go @@ -18,6 +18,12 @@ type chatMessageContent struct { // true. store is always false and reasoning.encrypted_content is always // included so that the response translator has full context. func ChatCompletionsToResponses(req *ChatCompletionsRequest) (*ResponsesRequest, error) { + return ChatCompletionsToResponsesWithMinOutputTokens(req, DefaultMinMaxOutputTokens) +} + +// ChatCompletionsToResponsesWithMinOutputTokens converts a Chat Completions +// request using the supplied max_output_tokens floor. +func ChatCompletionsToResponsesWithMinOutputTokens(req *ChatCompletionsRequest, minOutputTokens int) (*ResponsesRequest, error) { if err := openai.ValidateGPT61SolReasoningEffort(req.Model, req.ReasoningEffort); err != nil { return nil, err } @@ -62,8 +68,8 @@ func ChatCompletionsToResponses(req *ChatCompletionsRequest) (*ResponsesRequest, } if maxTokens > 0 { v := maxTokens - if v < minMaxOutputTokens { - v = minMaxOutputTokens + if v < minOutputTokens { + v = minOutputTokens } out.MaxOutputTokens = &v } diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic_request.go b/backend/internal/pkg/apicompat/responses_to_anthropic_request.go index 3f5e2933d..e86b510a4 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic_request.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic_request.go @@ -16,7 +16,8 @@ import ( func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, error) { isOpus55 := claude.IsOpus55(req.Model) isSonnet55 := claude.IsSonnet55(req.Model) - system, messages, err := convertResponsesInputToAnthropic(req.Instructions, req.Input, isOpus55 || isSonnet55) + isHaiku55 := claude.IsHaiku55(req.Model) + system, messages, err := convertResponsesInputToAnthropic(req.Instructions, req.Input, isOpus55 || isSonnet55 || isHaiku55) if err != nil { return nil, err } @@ -56,11 +57,13 @@ func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, erro out.ToolChoice = tc } - // The 5.5 models reject manual thinking and forced tool use. Sonnet 5.5 - // additionally supports between_tools to disable up-front thinking. + // The 5.5 models reject manual thinking. Opus/Sonnet 5.5 additionally reject + // forced tool use; Haiku 5.5 accepts it (starts with the tool call, no thinking + // block). Sonnet 5.5 supports between_tools to disable up-front thinking; + // Haiku 5.5 uses disabled (at high effort or below) instead. // Resolve the upstream model before conversion: client aliases need not // identify a Claude model. - if isOpus55 || isSonnet55 { + if isOpus55 || isSonnet55 || isHaiku55 { var choice struct { Type string `json:"type"` } @@ -69,7 +72,7 @@ func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, erro return nil, fmt.Errorf("invalid tool_choice: %w", err) } } - if choice.Type == "any" || choice.Type == "tool" { + if (choice.Type == "any" || choice.Type == "tool") && !isHaiku55 { return nil, fmt.Errorf("%s does not support forced tool_choice; use auto or none", req.Model) } effort := "medium" @@ -82,6 +85,17 @@ func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, erro return nil, fmt.Errorf("claude-sonnet-5-5 does not support non-default top_p") } } + if isHaiku55 { + if req.Temperature != nil && *req.Temperature != 1 { + return nil, fmt.Errorf("claude-haiku-5-5 does not support non-default temperature") + } + if req.TopP != nil && *req.TopP != 0.99 { + return nil, fmt.Errorf("claude-haiku-5-5 does not support non-default top_p") + } + if req.Temperature != nil && req.TopP != nil { + return nil, fmt.Errorf("claude-haiku-5-5 does not allow temperature and top_p together; omit both") + } + } if req.Reasoning != nil && req.Reasoning.Effort != "" { effort = req.Reasoning.Effort } @@ -96,6 +110,16 @@ func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, erro out.OutputConfig.Effort = "low" return out, nil } + if isHaiku55 && effort == "none" { + // Haiku 5.5's lowest thinking mode is disabled (valid at high + // effort or below); low keeps token spend minimal like Sonnet above. + out.Thinking = &AnthropicThinking{Type: "disabled"} + if out.OutputConfig == nil { + out.OutputConfig = &AnthropicOutputConfig{} + } + out.OutputConfig.Effort = "low" + return out, nil + } switch effort { case "low", "medium", "high", "xhigh", "max": default: diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index b5864f2f2..956101bd7 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -860,6 +860,9 @@ func (d ChatDelta) reasoningText() *string { // Shared constants // --------------------------------------------------------------------------- -// minMaxOutputTokens is the floor for max_output_tokens in a Responses request. -// Very small values may cause upstream API errors, so we enforce a minimum. -const minMaxOutputTokens = 128 +// DefaultMinMaxOutputTokens is the default floor for max_output_tokens in a +// Responses request. Very small values may cause upstream API errors, so we +// enforce a minimum. +const DefaultMinMaxOutputTokens = 128 + +const minMaxOutputTokens = DefaultMinMaxOutputTokens diff --git a/backend/internal/pkg/claude/constants.go b/backend/internal/pkg/claude/constants.go index 5e0f9fc27..1d0d6d3a3 100644 --- a/backend/internal/pkg/claude/constants.go +++ b/backend/internal/pkg/claude/constants.go @@ -223,6 +223,12 @@ var DefaultModels = []Model{ DisplayName: "Claude Haiku 4.5", CreatedAt: "2025-10-01T00:00:00Z", }, + { + ID: "claude-haiku-5-5", + Type: "model", + DisplayName: "Claude Haiku 5.5", + CreatedAt: "2026-10-07T00:00:00Z", + }, } // DefaultModelIDs 返回默认模型的 ID 列表 diff --git a/backend/internal/pkg/claude/constants_model_test.go b/backend/internal/pkg/claude/constants_model_test.go index 4a58d540d..0a15c8d21 100644 --- a/backend/internal/pkg/claude/constants_model_test.go +++ b/backend/internal/pkg/claude/constants_model_test.go @@ -43,3 +43,16 @@ func TestDefaultModelsContainsSonnet55(t *testing.T) { } t.Fatal("claude-sonnet-5-5 missing from DefaultModels") } + +func TestDefaultModelsContainsHaiku55(t *testing.T) { + t.Parallel() + + for _, model := range DefaultModels { + if model.ID == "claude-haiku-5-5" { + require.Equal(t, "Claude Haiku 5.5", model.DisplayName) + require.Equal(t, "2026-10-07T00:00:00Z", model.CreatedAt) + return + } + } + t.Fatal("claude-haiku-5-5 missing from DefaultModels") +} diff --git a/backend/internal/pkg/claude/effort_catalog.go b/backend/internal/pkg/claude/effort_catalog.go index a3039faac..2764adc07 100644 --- a/backend/internal/pkg/claude/effort_catalog.go +++ b/backend/internal/pkg/claude/effort_catalog.go @@ -27,6 +27,7 @@ var effortFamilies = []struct { {family: "claude-opus-4-5", levels: effortLowMediumHigh}, {family: "claude-opus-5-5", levels: effortLowMediumHighXHighMax}, {family: "claude-opus-5", levels: effortLowMediumHighXHighMax}, + {family: "claude-haiku-5-5", levels: effortLowMediumHighXHighMax}, } // EffortLevelsForModel returns the output_config.effort values accepted by a @@ -51,6 +52,11 @@ func IsSonnet55(model string) bool { return normalizeEffortModelID(model) == "claude-sonnet-5-5" } +// IsHaiku55 identifies the fixed Haiku 5.5 ID after provider/local suffix normalization. +func IsHaiku55(model string) bool { + return normalizeEffortModelID(model) == "claude-haiku-5-5" +} + func normalizeEffortModelID(model string) string { id := strings.ToLower(strings.TrimSpace(model)) id = strings.TrimPrefix(id, "models/") @@ -70,6 +76,9 @@ func normalizeEffortModelID(model string) string { if id == "claude-sonnet-5.5" { id = "claude-sonnet-5-5" } + if id == "claude-haiku-5.5" { + id = "claude-haiku-5-5" + } if mapped, ok := ModelIDReverseOverrides[id]; ok { id = mapped } diff --git a/backend/internal/pkg/claude/effort_catalog_test.go b/backend/internal/pkg/claude/effort_catalog_test.go index e8f8e2f15..12f7cd451 100644 --- a/backend/internal/pkg/claude/effort_catalog_test.go +++ b/backend/internal/pkg/claude/effort_catalog_test.go @@ -18,6 +18,9 @@ func TestEffortLevelsForModel(t *testing.T) { {model: "claude-opus-5", want: []string{"low", "medium", "high", "xhigh", "max"}}, {model: "anthropic/claude-opus-5.5", want: []string{"low", "medium", "high", "xhigh", "max"}}, {model: "claude-sonnet-5-5", want: []string{"low", "medium", "high", "xhigh", "max"}}, + {model: "claude-haiku-5-5", want: []string{"low", "medium", "high", "xhigh", "max"}}, + {model: "anthropic/claude-haiku-5.5", want: []string{"low", "medium", "high", "xhigh", "max"}}, + {model: "us.anthropic.claude-haiku-5-5", want: []string{"low", "medium", "high", "xhigh", "max"}}, {model: "us.anthropic.claude-sonnet-5-5", want: []string{"low", "medium", "high", "xhigh", "max"}}, {model: "claude-opus-4-5-20251101", want: []string{"low", "medium", "high"}}, {model: "claude-haiku-4-5-20251001", want: nil}, @@ -57,3 +60,19 @@ func TestIsSonnet55(t *testing.T) { require.False(t, IsSonnet55(model), model) } } + +func TestIsHaiku55(t *testing.T) { + t.Parallel() + for _, model := range []string{ + "claude-haiku-5-5", + "anthropic/claude-haiku-5.5", + "anthropic.claude-haiku-5-5", + "us.anthropic.claude-haiku-5-5", + "global.anthropic.claude-haiku-5-5-thinking", + } { + require.True(t, IsHaiku55(model), model) + } + for _, model := range []string{"claude-haiku-5", "claude-haiku-4-5", "claude-haiku-4-5-20251001", "claude-sonnet-5-5", "claude-opus-5-5"} { + require.False(t, IsHaiku55(model), model) + } +} diff --git a/backend/internal/pkg/gemini/models.go b/backend/internal/pkg/gemini/models.go index d5d4ed64c..1d38fc990 100644 --- a/backend/internal/pkg/gemini/models.go +++ b/backend/internal/pkg/gemini/models.go @@ -28,6 +28,7 @@ func DefaultModels() []Model { {Name: "models/gemini-3.1-pro-preview", SupportedGenerationMethods: methods}, {Name: "models/gemini-3.1-pro-preview-customtools", SupportedGenerationMethods: methods}, {Name: "models/gemini-3.1-flash-image", SupportedGenerationMethods: methods}, + {Name: "models/gemini-4-argon", SupportedGenerationMethods: methods}, } } diff --git a/backend/internal/pkg/geminicli/models.go b/backend/internal/pkg/geminicli/models.go index cc9cbc80b..4e2fa55bb 100644 --- a/backend/internal/pkg/geminicli/models.go +++ b/backend/internal/pkg/geminicli/models.go @@ -20,6 +20,7 @@ var DefaultModels = []Model{ {ID: "gemini-3-pro-preview", Type: "model", DisplayName: "Gemini 3 Pro Preview", CreatedAt: ""}, {ID: "gemini-3.1-pro-preview", Type: "model", DisplayName: "Gemini 3.1 Pro Preview", CreatedAt: ""}, {ID: "gemini-3.1-flash-image", Type: "model", DisplayName: "Gemini 3.1 Flash Image", CreatedAt: ""}, + {ID: "gemini-4-argon", Type: "model", DisplayName: "Gemini 4 Argon", CreatedAt: ""}, } // GoogleOneModels is the conservative model set exposed for legacy Google One diff --git a/backend/internal/repository/api_key_repo.go b/backend/internal/repository/api_key_repo.go index f92e1e731..b84b871d2 100644 --- a/backend/internal/repository/api_key_repo.go +++ b/backend/internal/repository/api_key_repo.go @@ -857,7 +857,7 @@ func (r *apiKeyRepository) ResetRateLimitWindows(ctx context.Context, id int64) // GetRateLimitData returns the current rate limit usage and window start times for an API key. func (r *apiKeyRepository) GetRateLimitData(ctx context.Context, id int64) (result *service.APIKeyRateLimitData, err error) { rows, err := r.sql.QueryContext(ctx, ` - SELECT usage_5h, usage_1d, usage_7d, window_5h_start, window_1d_start, window_7d_start + SELECT quota_used, usage_5h, usage_1d, usage_7d, window_5h_start, window_1d_start, window_7d_start FROM api_keys WHERE id = $1 AND deleted_at IS NULL`, id) @@ -873,7 +873,7 @@ func (r *apiKeyRepository) GetRateLimitData(ctx context.Context, id int64) (resu return nil, service.ErrAPIKeyNotFound } data := &service.APIKeyRateLimitData{} - if err := rows.Scan(&data.Usage5h, &data.Usage1d, &data.Usage7d, &data.Window5hStart, &data.Window1dStart, &data.Window7dStart); err != nil { + if err := rows.Scan(&data.QuotaUsed, &data.Usage5h, &data.Usage1d, &data.Usage7d, &data.Window5hStart, &data.Window1dStart, &data.Window7dStart); err != nil { return nil, err } return data, rows.Err() @@ -979,6 +979,7 @@ func groupEntityToService(g *dbent.Group) *service.Group { ID: g.ID, Name: g.Name, Description: derefString(g.Description), + I18n: g.I18n, Platform: g.Platform, RateMultiplier: g.RateMultiplier, IsExclusive: g.IsExclusive, diff --git a/backend/internal/repository/api_key_repo_integration_test.go b/backend/internal/repository/api_key_repo_integration_test.go index 6e1f5db07..637fab9ed 100644 --- a/backend/internal/repository/api_key_repo_integration_test.go +++ b/backend/internal/repository/api_key_repo_integration_test.go @@ -464,6 +464,10 @@ func (s *APIKeyRepoSuite) TestIncrementQuotaUsed_Basic() { newQuota, err = s.repo.IncrementQuotaUsed(s.ctx, key.ID, 2.5) s.Require().NoError(err, "IncrementQuotaUsed second") s.Require().Equal(4.0, newQuota, "第二次递增后应为 4.0") + + data, err := s.repo.GetRateLimitData(s.ctx, key.ID) + s.Require().NoError(err, "GetRateLimitData") + s.Require().Equal(4.0, data.QuotaUsed, "用量读取带回总额度已用量") } func (s *APIKeyRepoSuite) TestIncrementQuotaUsed_NotFound() { diff --git a/backend/internal/repository/billing_inflight_cache.go b/backend/internal/repository/billing_inflight_cache.go index 1800529b4..0b880c7f3 100644 --- a/backend/internal/repository/billing_inflight_cache.go +++ b/backend/internal/repository/billing_inflight_cache.go @@ -25,6 +25,20 @@ func billingInflightKeys(userID int64) (string, string) { fmt.Sprintf("%s{%d}", billingInflightAmtKeyPrefix, userID) } +// 订阅 / API Key 维度在途预留(确定金额费用): +// - billing:inflight_scope:{scope} ZSET member=requestID score=过期时间(ms) +// - billing:inflight_scope_amt:{scope} HASH field=requestID value=预留金额(USD) +// +// 过期清理与释放语义与余额维度相同,不续期。 +const ( + billingInflightScopeKeyPrefix = "billing:inflight_scope:" + billingInflightScopeAmtKeyPrefix = "billing:inflight_scope_amt:" +) + +func billingInflightScopeKeys(scope string) (string, string) { + return billingInflightScopeKeyPrefix + "{" + scope + "}", billingInflightScopeAmtKeyPrefix + "{" + scope + "}" +} + var ( // KEYS: [1]=zset [2]=hash // ARGV: [1]=now_ms [2]=expire_at_ms [3]=member [4]=amount [5]=balance [6]=key_ttl_ms @@ -85,6 +99,28 @@ var ( redis.call('HDEL', KEYS[2], ARGV[1]) return 1 `) + + // KEYS: [1]=zset [2]=hash + // ARGV: [1]=now_ms [2]=expire_at_ms [3]=member [4]=amount [5]=key_ttl_ms + // 先清理已过期成员,再登记本次预留;返回登记前其他在途预留的合计(string),是否放行由调用方按权威用量判定。 + reserveInflightScopeScript = redis.NewScript(` + local now = tonumber(ARGV[1]) + local expired = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', now) + if #expired > 0 then + redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now) + redis.call('HDEL', KEYS[2], unpack(expired)) + end + local vals = redis.call('HVALS', KEYS[2]) + local sum = 0 + for i = 1, #vals do + sum = sum + (tonumber(vals[i]) or 0) + end + redis.call('ZADD', KEYS[1], tonumber(ARGV[2]), ARGV[3]) + redis.call('HSET', KEYS[2], ARGV[3], ARGV[4]) + redis.call('PEXPIRE', KEYS[1], ARGV[5]) + redis.call('PEXPIRE', KEYS[2], ARGV[5]) + return tostring(sum) + `) ) // ReserveInflightBalance 实现 service.InflightBalanceReservationCache。 @@ -138,7 +174,35 @@ func (c *billingCache) RenewInflightBalance(ctx context.Context, userID int64, r return n == 1, nil } +// ReserveInflightScope 实现 service.InflightScopeReservationCache。 +func (c *billingCache) ReserveInflightScope(ctx context.Context, scope, requestID string, amount float64, ttl time.Duration) (float64, error) { + zkey, hkey := billingInflightScopeKeys(scope) + now := time.Now().UnixMilli() + ttlMs := ttl.Milliseconds() + if ttlMs <= 0 { + ttlMs = 1 + } + res, err := reserveInflightScopeScript.Run(ctx, c.rdb, []string{zkey, hkey}, + now, + now+ttlMs, + requestID, + strconv.FormatFloat(amount, 'f', -1, 64), + ttlMs, + ).Text() + if err != nil { + return 0, err + } + return strconv.ParseFloat(res, 64) +} + +// ReleaseInflightScope 实现 service.InflightScopeReservationCache。 +func (c *billingCache) ReleaseInflightScope(ctx context.Context, scope, requestID string) error { + zkey, hkey := billingInflightScopeKeys(scope) + return releaseInflightBalanceScript.Run(ctx, c.rdb, []string{zkey, hkey}, requestID).Err() +} + var ( _ service.InflightBalanceReservationCache = (*billingCache)(nil) _ service.InflightBalanceReservationRenewer = (*billingCache)(nil) + _ service.InflightScopeReservationCache = (*billingCache)(nil) ) diff --git a/backend/internal/repository/billing_inflight_cache_test.go b/backend/internal/repository/billing_inflight_cache_test.go index b9af3e4ac..c087395e2 100644 --- a/backend/internal/repository/billing_inflight_cache_test.go +++ b/backend/internal/repository/billing_inflight_cache_test.go @@ -285,3 +285,72 @@ func TestInflightReservation_RenewDoesNotResurrectExpiredMember(t *testing.T) { require.NoError(t, err) require.False(t, exists) } + +func TestInflightScopeReservation_ReturnsOthersAndReleases(t *testing.T) { + mr, cache, _ := newInflightTestEnv(t, true, 60) + ctx := context.Background() + + others, err := cache.ReserveInflightScope(ctx, "apikey:7", "r1", 3, time.Minute) + require.NoError(t, err) + require.Zero(t, others) + others, err = cache.ReserveInflightScope(ctx, "apikey:7", "r2", 2, time.Minute) + require.NoError(t, err) + require.InDelta(t, 3, others, 1e-9, "返回登记前其他在途预留的合计") + others, err = cache.ReserveInflightScope(ctx, "sub:7", "r3", 5, time.Minute) + require.NoError(t, err) + require.Zero(t, others, "不同维度互不影响") + + require.NoError(t, cache.ReleaseInflightScope(ctx, "apikey:7", "r1")) + require.NoError(t, cache.ReleaseInflightScope(ctx, "apikey:7", "r1")) + others, err = cache.ReserveInflightScope(ctx, "apikey:7", "r4", 1, time.Minute) + require.NoError(t, err) + require.InDelta(t, 2, others, 1e-9) + + mr.FastForward(2 * time.Minute) + others, err = cache.ReserveInflightScope(ctx, "apikey:7", "r5", 1, time.Minute) + require.NoError(t, err) + require.Zero(t, others, "过期预留不再计入") +} + +func TestReserveFixedCharge_ConcurrentChargesAdmitOnlyWhatAPIKeyQuotaCovers(t *testing.T) { + _, cache, svc := newInflightTestEnv(t, true, 60) + ctx := context.Background() + user := &service.User{ID: 42} + apiKey := &service.APIKey{ID: 9, UserID: user.ID, Quota: 1.0} + require.NoError(t, cache.SetUserBalance(ctx, user.ID, 100)) + + const n = 20 + var admitted atomic.Int32 + reservations := make(chan *service.InflightReservation, n) + var wg sync.WaitGroup + start := make(chan struct{}) + for i := 0; i < n; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + res, err := svc.ReserveFixedCharge(ctx, user, apiKey, nil, nil, 0.3) + if err != nil { + if !errors.Is(err, service.ErrAPIKeyQuotaExhausted) { + t.Errorf("unexpected error: %v", err) + } + return + } + admitted.Add(1) + reservations <- res + }() + } + close(start) + wg.Wait() + close(reservations) + + require.Equal(t, int32(3), admitted.Load(), "Key 额度 1.0、每笔 0.3:同时在途的不超过 3 笔") + for res := range reservations { + res.Release() + } + zkey, _ := billingInflightScopeKeys("apikey:9") + remaining, err := cache.rdb.ZCard(ctx, zkey).Result() + require.NoError(t, err) + require.Zero(t, remaining) + require.Equal(t, int64(0), inflightCount(t, cache, user.ID)) +} diff --git a/backend/internal/repository/gemini_cached_content_repo.go b/backend/internal/repository/gemini_cached_content_repo.go new file mode 100644 index 000000000..d1621603d --- /dev/null +++ b/backend/internal/repository/gemini_cached_content_repo.go @@ -0,0 +1,205 @@ +package repository + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "time" + + "github.com/MACOS-DO/sub4api/internal/service" +) + +type geminiCachedContentSQLExecutor interface { + ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) + QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) + QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row +} + +type geminiCachedContentRepository struct { + sql geminiCachedContentSQLExecutor +} + +func NewGeminiCachedContentRepository(db *sql.DB) service.GeminiCachedContentRepository { + return &geminiCachedContentRepository{sql: db} +} + +const geminiCachedContentColumns = `id, public_id, user_id, api_key_id, group_id, account_id, upstream_name, model, + upstream_model, display_name, total_token_count, expire_time, channel_usage, created_at, updated_at` + +func (r *geminiCachedContentRepository) Create(ctx context.Context, record *service.GeminiCachedContent) error { + channelUsage, err := json.Marshal(record.ChannelUsage) + if err != nil { + return err + } + row := r.sql.QueryRowContext(ctx, ` +INSERT INTO gemini_cached_contents (public_id, user_id, api_key_id, group_id, account_id, upstream_name, model, + upstream_model, display_name, total_token_count, expire_time, channel_usage) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) +RETURNING id, created_at, updated_at`, + record.PublicID, record.UserID, record.APIKeyID, record.GroupID, record.AccountID, record.UpstreamName, + record.Model, record.UpstreamModel, record.DisplayName, record.TotalTokenCount, record.ExpireTime, channelUsage) + if err := row.Scan(&record.ID, &record.CreatedAt, &record.UpdatedAt); err != nil { + return translatePersistenceError(err, nil, service.ErrGeminiCachedContentExists) + } + return nil +} + +func (r *geminiCachedContentRepository) GetForOwner(ctx context.Context, apiKeyID int64, publicID string) (*service.GeminiCachedContent, error) { + record, err := scanGeminiCachedContent(r.sql.QueryRowContext(ctx, `SELECT `+geminiCachedContentColumns+` + FROM gemini_cached_contents + WHERE public_id = $1 AND api_key_id = $2 AND deleted_at IS NULL`, publicID, apiKeyID)) + if err != nil { + return nil, translatePersistenceError(err, service.ErrGeminiCachedContentNotFound, nil) + } + return record, nil +} + +func (r *geminiCachedContentRepository) ListForOwner(ctx context.Context, apiKeyID, groupID int64, activeAt time.Time, beforeID int64, limit int) ([]*service.GeminiCachedContent, error) { + if limit <= 0 { + limit = service.GeminiCachedContentListDefaultPageSize + } + rows, err := r.sql.QueryContext(ctx, `SELECT `+geminiCachedContentColumns+` + FROM gemini_cached_contents + WHERE api_key_id = $1 AND group_id = $2 AND deleted_at IS NULL AND expire_time > $3 AND ($4 <= 0 OR id < $4) + ORDER BY id DESC + LIMIT $5`, apiKeyID, groupID, activeAt, beforeID, limit) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + var out []*service.GeminiCachedContent + for rows.Next() { + record, err := scanGeminiCachedContent(rows) + if err != nil { + return nil, err + } + out = append(out, record) + } + return out, rows.Err() +} + +func (r *geminiCachedContentRepository) BeginMutation(ctx context.Context, id int64, baseline time.Time, token string, lease time.Duration) (bool, error) { + result, err := r.sql.ExecContext(ctx, `UPDATE gemini_cached_contents + SET mutation_token = $2, mutation_lease_until = NOW() + make_interval(secs => $3::double precision) + WHERE id = $1 AND deleted_at IS NULL AND mutation_token IS NULL AND expire_time = $4`, + id, token, lease.Seconds(), baseline) + if err != nil { + return false, err + } + affected, err := result.RowsAffected() + if err != nil { + return false, err + } + if affected > 0 { + return true, nil + } + var exists bool + if err := r.sql.QueryRowContext(ctx, `SELECT EXISTS ( + SELECT 1 FROM gemini_cached_contents WHERE id = $1 AND deleted_at IS NULL)`, id).Scan(&exists); err != nil { + return false, err + } + if !exists { + return false, service.ErrGeminiCachedContentNotFound + } + return false, nil +} + +func (r *geminiCachedContentRepository) TakeOverStaleMutation(ctx context.Context, id int64, token string, lease time.Duration) (*service.GeminiCachedContent, error) { + record, err := scanGeminiCachedContent(r.sql.QueryRowContext(ctx, `UPDATE gemini_cached_contents + SET mutation_token = $2, mutation_lease_until = NOW() + make_interval(secs => $3::double precision) + WHERE id = $1 AND deleted_at IS NULL AND mutation_token IS NOT NULL AND mutation_lease_until < NOW() + RETURNING `+geminiCachedContentColumns, id, token, lease.Seconds())) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + if err != nil { + return nil, err + } + return record, nil +} + +func (r *geminiCachedContentRepository) CommitMutation(ctx context.Context, id int64, token string, expireTime time.Time) error { + result, err := r.sql.ExecContext(ctx, `UPDATE gemini_cached_contents + SET expire_time = $3, updated_at = NOW(), mutation_token = NULL, mutation_lease_until = NULL + WHERE id = $1 AND deleted_at IS NULL AND mutation_token = $2`, id, token, expireTime) + if err != nil { + return err + } + affected, err := result.RowsAffected() + if err != nil { + return err + } + if affected == 0 { + return service.ErrGeminiCachedContentMutationConflict + } + return nil +} + +func (r *geminiCachedContentRepository) ReleaseMutation(ctx context.Context, id int64, token string) error { + _, err := r.sql.ExecContext(ctx, `UPDATE gemini_cached_contents + SET mutation_token = NULL, mutation_lease_until = NULL + WHERE id = $1 AND mutation_token = $2`, id, token) + return err +} + +func (r *geminiCachedContentRepository) ListStaleMutations(ctx context.Context, limit int) ([]int64, error) { + rows, err := r.sql.QueryContext(ctx, `SELECT id FROM gemini_cached_contents + WHERE mutation_token IS NOT NULL AND deleted_at IS NULL AND mutation_lease_until < NOW() + ORDER BY mutation_lease_until + LIMIT $1`, limit) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + var ids []int64 + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + return nil, err + } + ids = append(ids, id) + } + return ids, rows.Err() +} + +func (r *geminiCachedContentRepository) SoftDelete(ctx context.Context, id int64) error { + _, err := r.sql.ExecContext(ctx, `UPDATE gemini_cached_contents + SET deleted_at = NOW(), updated_at = NOW() + WHERE id = $1 AND deleted_at IS NULL`, id) + return err +} + +type geminiCachedContentScanner interface { + Scan(dest ...any) error +} + +func scanGeminiCachedContent(row geminiCachedContentScanner) (*service.GeminiCachedContent, error) { + var record service.GeminiCachedContent + var channelUsage []byte + if err := row.Scan( + &record.ID, + &record.PublicID, + &record.UserID, + &record.APIKeyID, + &record.GroupID, + &record.AccountID, + &record.UpstreamName, + &record.Model, + &record.UpstreamModel, + &record.DisplayName, + &record.TotalTokenCount, + &record.ExpireTime, + &channelUsage, + &record.CreatedAt, + &record.UpdatedAt, + ); err != nil { + return nil, err + } + if len(channelUsage) > 0 { + if err := json.Unmarshal(channelUsage, &record.ChannelUsage); err != nil { + return nil, err + } + } + return &record, nil +} diff --git a/backend/internal/repository/gemini_cached_content_repo_integration_test.go b/backend/internal/repository/gemini_cached_content_repo_integration_test.go new file mode 100644 index 000000000..5a003207f --- /dev/null +++ b/backend/internal/repository/gemini_cached_content_repo_integration_test.go @@ -0,0 +1,120 @@ +//go:build integration + +package repository + +import ( + "context" + "testing" + "time" + + "github.com/MACOS-DO/sub4api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestGeminiCachedContentRepository_Lifecycle(t *testing.T) { + ctx := context.Background() + tx := testTx(t) + repo := &geminiCachedContentRepository{sql: tx} + now := time.Now().UTC().Truncate(time.Microsecond) + suffix := time.Now().Format("150405.000000") + apiKeyID := int64(910001) + + newRecord := func(publicID string, keyID, groupID int64, expire time.Time) *service.GeminiCachedContent { + return &service.GeminiCachedContent{ + PublicID: publicID + suffix, UserID: 1, APIKeyID: keyID, GroupID: groupID, AccountID: 99, + UpstreamName: "cachedContents/up" + publicID, Model: "gemini-3.8-flash", UpstreamModel: "models/gemini-3.8-flash", + DisplayName: "label", TotalTokenCount: 2730, ExpireTime: expire, + ChannelUsage: service.ChannelUsageFields{ChannelID: 7, OriginalModel: "gemini-pro", ChannelMappedModel: "gemini-3.8-flash", BillingModelSource: "requested"}, + } + } + first := newRecord("a", apiKeyID, 42, now.Add(time.Hour)) + require.NoError(t, repo.Create(ctx, first)) + require.Positive(t, first.ID) + require.False(t, first.CreatedAt.IsZero()) + _, err := tx.ExecContext(ctx, `SAVEPOINT gemini_cached_content_duplicate`) + require.NoError(t, err) + require.ErrorIs(t, repo.Create(ctx, newRecord("a", apiKeyID, 42, now.Add(time.Hour))), service.ErrGeminiCachedContentExists) + _, err = tx.ExecContext(ctx, `ROLLBACK TO SAVEPOINT gemini_cached_content_duplicate`) + require.NoError(t, err) + + second := newRecord("b", apiKeyID, 42, now.Add(time.Hour)) + require.NoError(t, repo.Create(ctx, second)) + require.NoError(t, repo.Create(ctx, newRecord("expired", apiKeyID, 42, now.Add(-time.Minute)))) + require.NoError(t, repo.Create(ctx, newRecord("othergroup", apiKeyID, 43, now.Add(time.Hour)))) + require.NoError(t, repo.Create(ctx, newRecord("otherkey", apiKeyID+1, 42, now.Add(time.Hour)))) + + got, err := repo.GetForOwner(ctx, apiKeyID, first.PublicID) + require.NoError(t, err) + require.Equal(t, "cachedContents/upa", got.UpstreamName) + require.Equal(t, int64(2730), got.TotalTokenCount) + require.True(t, got.ExpireTime.Equal(first.ExpireTime)) + require.Equal(t, first.ChannelUsage, got.ChannelUsage, "创建时的渠道计费口径随记录持久化") + _, err = repo.GetForOwner(ctx, apiKeyID+1, first.PublicID) + require.ErrorIs(t, err, service.ErrGeminiCachedContentNotFound) + + list, err := repo.ListForOwner(ctx, apiKeyID, 42, now, 0, 10) + require.NoError(t, err) + require.Len(t, list, 2) + require.Equal(t, second.PublicID, list[0].PublicID) + page, err := repo.ListForOwner(ctx, apiKeyID, 42, now, list[0].ID, 10) + require.NoError(t, err) + require.Len(t, page, 1) + require.Equal(t, first.PublicID, page[0].PublicID) + + lease := 2 * time.Minute + acquired, err := repo.BeginMutation(ctx, first.ID, first.ExpireTime, "t1", lease) + require.NoError(t, err) + require.True(t, acquired) + acquired, err = repo.BeginMutation(ctx, first.ID, first.ExpireTime, "t2", lease) + require.NoError(t, err) + require.False(t, acquired, "有进行中的修改时不能再登记") + taken, err := repo.TakeOverStaleMutation(ctx, first.ID, "t2", lease) + require.NoError(t, err) + require.Nil(t, taken, "租约未过期不能接管") + require.ErrorIs(t, repo.CommitMutation(ctx, first.ID, "t2", now), service.ErrGeminiCachedContentMutationConflict) + + newExpire := now.Add(3 * time.Hour) + require.NoError(t, repo.CommitMutation(ctx, first.ID, "t1", newExpire)) + got, err = repo.GetForOwner(ctx, apiKeyID, first.PublicID) + require.NoError(t, err) + require.True(t, got.ExpireTime.Equal(newExpire)) + require.ErrorIs(t, repo.CommitMutation(ctx, first.ID, "t1", now), service.ErrGeminiCachedContentMutationConflict, "提交后修改意图已清除") + + acquired, err = repo.BeginMutation(ctx, first.ID, first.ExpireTime, "t3", lease) + require.NoError(t, err) + require.False(t, acquired, "到期时间已被其他修改改变") + acquired, err = repo.BeginMutation(ctx, first.ID, newExpire, "t3", lease) + require.NoError(t, err) + require.True(t, acquired) + stale, err := repo.ListStaleMutations(ctx, 10) + require.NoError(t, err) + require.NotContains(t, stale, first.ID) + + _, err = tx.ExecContext(ctx, `UPDATE gemini_cached_contents SET mutation_lease_until = NOW() - INTERVAL '1 second' WHERE id = $1`, first.ID) + require.NoError(t, err) + stale, err = repo.ListStaleMutations(ctx, 10) + require.NoError(t, err) + require.Contains(t, stale, first.ID) + taken, err = repo.TakeOverStaleMutation(ctx, first.ID, "t4", lease) + require.NoError(t, err) + require.NotNil(t, taken) + require.True(t, taken.ExpireTime.Equal(newExpire), "接管返回修改前的到期时间") + require.ErrorIs(t, repo.CommitMutation(ctx, first.ID, "t3", now), service.ErrGeminiCachedContentMutationConflict, "被接管后原持有者不能提交") + require.NoError(t, repo.ReleaseMutation(ctx, first.ID, "t3")) + acquired, err = repo.BeginMutation(ctx, first.ID, newExpire, "t5", lease) + require.NoError(t, err) + require.False(t, acquired, "原持有者释放不影响接管者") + require.NoError(t, repo.ReleaseMutation(ctx, first.ID, "t4")) + stale, err = repo.ListStaleMutations(ctx, 10) + require.NoError(t, err) + require.NotContains(t, stale, first.ID) + + require.NoError(t, repo.SoftDelete(ctx, first.ID)) + _, err = repo.GetForOwner(ctx, apiKeyID, first.PublicID) + require.ErrorIs(t, err, service.ErrGeminiCachedContentNotFound) + _, err = repo.BeginMutation(ctx, first.ID, newExpire, "t6", lease) + require.ErrorIs(t, err, service.ErrGeminiCachedContentNotFound) + list, err = repo.ListForOwner(ctx, apiKeyID, 42, now, 0, 10) + require.NoError(t, err) + require.Len(t, list, 1) +} diff --git a/backend/internal/repository/group_repo.go b/backend/internal/repository/group_repo.go index 2d2803365..8a0b32973 100644 --- a/backend/internal/repository/group_repo.go +++ b/backend/internal/repository/group_repo.go @@ -167,6 +167,10 @@ func createGroupRecord(ctx context.Context, client *dbent.Client, groupIn *servi // 设置支持的模型系列(始终设置,空数组表示不限制) builder = builder.SetSupportedModelScopes(groupIn.SupportedModelScopes) + if groupIn.I18n != nil { + builder = builder.SetI18n(groupIn.I18n) + } + created, err := builder.Save(ctx) if err != nil { return translatePersistenceError(err, nil, service.ErrGroupExists) @@ -431,6 +435,12 @@ func (r *groupRepository) Update(ctx context.Context, groupIn *service.Group) er // 处理 SupportedModelScopes(始终设置,空数组表示不限制) builder = builder.SetSupportedModelScopes(groupIn.SupportedModelScopes) + i18n := groupIn.I18n + if i18n == nil { + i18n = service.GroupI18n{} + } + builder = builder.SetI18n(i18n) + updated, err := builder.Save(ctx) if err != nil { return translatePersistenceError(err, service.ErrGroupNotFound, service.ErrGroupExists) @@ -957,6 +967,29 @@ func (r *groupRepository) deleteCascade(ctx context.Context, id int64, requireEm if _, err := txClient.Group.Delete().Where(group.IDEQ(id)).Exec(ctx); err != nil { return nil, err } + // Lock and validate the text value before using JSONB operators. A legacy + // malformed setting must not prevent deletion or be silently replaced. + var moderationValue string + err = scanSingleRow(ctx, exec, `SELECT value FROM settings WHERE key = $1 FOR UPDATE`, + []any{service.SettingKeyContentModerationConfig}, &moderationValue) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return nil, err + } + // Keep the moderation scope in sync in the same transaction. Updating the + // setting row in SQL also serializes concurrent group deletions across nodes. + if err == nil && json.Valid([]byte(moderationValue)) { + if _, err := exec.ExecContext(ctx, `UPDATE settings + SET value = jsonb_set(value::jsonb, '{group_ids}', + (SELECT COALESCE(jsonb_agg(group_id ORDER BY ord), '[]'::jsonb) + FROM jsonb_array_elements(value::jsonb->'group_ids') WITH ORDINALITY AS ids(group_id, ord) + WHERE group_id <> to_jsonb($2::bigint)))::text, + updated_at = NOW() + WHERE key = $1 AND jsonb_typeof(value::jsonb->'group_ids') = 'array' + AND value::jsonb->'group_ids' @> jsonb_build_array($2::bigint)`, + service.SettingKeyContentModerationConfig, id); err != nil { + return nil, err + } + } if tx != nil { if err := tx.Commit(); err != nil { diff --git a/backend/internal/repository/group_repo_integration_test.go b/backend/internal/repository/group_repo_integration_test.go index 662dcf03d..a89dfea1a 100644 --- a/backend/internal/repository/group_repo_integration_test.go +++ b/backend/internal/repository/group_repo_integration_test.go @@ -5,7 +5,9 @@ package repository import ( "context" "database/sql" + "encoding/json" "errors" + "fmt" "strings" "testing" "time" @@ -49,6 +51,55 @@ func TestGroupRepoSuite(t *testing.T) { suite.Run(t, new(GroupRepoSuite)) } +func TestModerationConfigWriteRejectsGroupDeletedAfterValidation(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + repo := newGroupRepositoryWithSQL(client, integrationDB) + settings := &settingRepository{client: client} + group := &service.Group{Name: "moderation-concurrent-delete", Platform: service.PlatformAnthropic, RateMultiplier: 1, Status: service.StatusActive, SubscriptionType: service.SubscriptionTypeStandard} + require.NoError(t, repo.Create(ctx, group)) + t.Cleanup(func() { _, _ = integrationDB.ExecContext(ctx, "DELETE FROM groups WHERE id=$1", group.ID) }) + key := service.SettingKeyContentModerationConfig + previous, previousErr := settings.GetValue(ctx, key) + t.Cleanup(func() { + if previousErr == nil { + _ = settings.Set(ctx, key, previous) + } else { + _ = settings.Delete(ctx, key) + } + }) + require.NoError(t, settings.Set(ctx, key, `{"all_groups":false,"group_ids":[]}`)) + + // Hold the deleter's group lock while the config writer starts with an ID + // that was valid before deletion. It must recheck after this transaction commits. + tx, err := integrationDB.BeginTx(ctx, nil) + require.NoError(t, err) + defer func() { _ = tx.Rollback() }() + var id int64 + require.NoError(t, tx.QueryRowContext(ctx, "SELECT id FROM groups WHERE id=$1 FOR UPDATE", group.ID).Scan(&id)) + finished := make(chan error, 1) + go func() { + finished <- settings.SetContentModerationConfig(ctx, `{"all_groups":false,"group_ids":[`+fmt.Sprint(group.ID)+`]}`, []int64{group.ID}) + }() + select { + case err := <-finished: + t.Fatalf("config write passed a locked group before deletion: %v", err) + case <-time.After(100 * time.Millisecond): + } + _, err = tx.ExecContext(ctx, "UPDATE groups SET deleted_at=NOW() WHERE id=$1", group.ID) + require.NoError(t, err) + require.NoError(t, tx.Commit()) + select { + case err := <-finished: + require.ErrorIs(t, err, service.ErrGroupNotFound) + case <-time.After(5 * time.Second): + t.Fatal("config write did not finish after deletion") + } + stored, err := settings.GetValue(ctx, key) + require.NoError(t, err) + require.JSONEq(t, `{"all_groups":false,"group_ids":[]}`, stored) +} + // --- Create / GetByID / Update / Delete --- func (s *GroupRepoSuite) TestCreate() { @@ -201,6 +252,48 @@ func (s *GroupRepoSuite) TestUpdate() { s.Require().Equal("updated", got.Name) } +func (s *GroupRepoSuite) TestI18n_RoundTrip() { + group := &service.Group{ + Name: "i18n-roundtrip", + Platform: service.PlatformAnthropic, + RateMultiplier: 1.0, + Status: service.StatusActive, + SubscriptionType: service.SubscriptionTypeStandard, + I18n: service.GroupI18n{ + "en": {Name: "Standard", Description: "Pro + Max pool"}, + }, + } + s.Require().NoError(s.repo.Create(s.ctx, group)) + + got, err := s.repo.GetByID(s.ctx, group.ID) + s.Require().NoError(err) + s.Require().Equal(group.I18n, got.I18n) + + got.I18n = service.GroupI18n{"zh": {Description: "号池"}} + s.Require().NoError(s.repo.Update(s.ctx, got)) + got, err = s.repo.GetByID(s.ctx, group.ID) + s.Require().NoError(err) + s.Require().Equal(service.GroupI18n{"zh": {Description: "号池"}}, got.I18n) + + // 未携带译文的写入落库为空对象,而不是 JSON null。 + got.I18n = nil + s.Require().NoError(s.repo.Update(s.ctx, got)) + var stored string + s.Require().NoError(scanSingleRow(s.ctx, s.tx, "SELECT i18n::text FROM groups WHERE id = $1", []any{group.ID}, &stored)) + s.Require().Equal("{}", stored) + + plain := &service.Group{ + Name: "i18n-default", + Platform: service.PlatformAnthropic, + RateMultiplier: 1.0, + Status: service.StatusActive, + SubscriptionType: service.SubscriptionTypeStandard, + } + s.Require().NoError(s.repo.Create(s.ctx, plain)) + s.Require().NoError(scanSingleRow(s.ctx, s.tx, "SELECT i18n::text FROM groups WHERE id = $1", []any{plain.ID}, &stored)) + s.Require().Equal("{}", stored) +} + func (s *GroupRepoSuite) TestGetByID_PreservesMessagesDispatchModelConfig() { group := &service.Group{ Name: "openai-dispatch", @@ -257,8 +350,14 @@ func (s *GroupRepoSuite) TestDeleteCascadeIfEmptyRejectsGroupWithNonDeletedAccou _, err := s.tx.ExecContext(s.ctx, "INSERT INTO account_groups (account_id, group_id, priority, created_at) VALUES ($1, $2, 1, NOW())", accountID, group.ID) s.Require().NoError(err) + config, marshalErr := json.Marshal(map[string]any{"group_ids": []int64{group.ID}, "all_groups": false}) + s.Require().NoError(marshalErr) + s.Require().NoError(NewSettingRepository(s.tx.Client()).Set(s.ctx, service.SettingKeyContentModerationConfig, string(config))) _, err = s.repo.DeleteCascadeIfEmpty(s.ctx, group.ID) s.Require().ErrorIs(err, service.ErrGroupNotEmpty) + stored, readErr := NewSettingRepository(s.tx.Client()).GetValue(s.ctx, service.SettingKeyContentModerationConfig) + s.Require().NoError(readErr) + s.Require().JSONEq(string(config), stored) _, err = s.repo.GetByID(s.ctx, group.ID) s.Require().NoError(err) var bindings int @@ -276,6 +375,76 @@ func (s *GroupRepoSuite) TestDeleteCascadeIfEmptyDeletesEmptyGroup() { s.Require().ErrorIs(err, service.ErrGroupNotFound) } +func (s *GroupRepoSuite) TestDeleteCascadeRemovesOnlySelectedModerationGroup() { + for _, guarded := range []bool{false, true} { + name := map[bool]string{false: "normal", true: "guarded"}[guarded] + s.Run(name, func() { + deleted := &service.Group{Name: "moderation-deleted-" + name, Platform: service.PlatformAnthropic, RateMultiplier: 1, Status: service.StatusActive, SubscriptionType: service.SubscriptionTypeStandard} + kept := &service.Group{Name: "moderation-kept-" + name, Platform: service.PlatformAnthropic, RateMultiplier: 1, Status: service.StatusActive, SubscriptionType: service.SubscriptionTypeStandard} + s.Require().NoError(s.repo.Create(s.ctx, deleted)) + s.Require().NoError(s.repo.Create(s.ctx, kept)) + config := map[string]any{"group_ids": []int64{kept.ID, deleted.ID}, "all_groups": false, "mode": "observe"} + raw, err := json.Marshal(config) + s.Require().NoError(err) + s.Require().NoError(NewSettingRepository(s.tx.Client()).Set(s.ctx, service.SettingKeyContentModerationConfig, string(raw))) + if guarded { + _, err = s.repo.DeleteCascadeIfEmpty(s.ctx, deleted.ID) + } else { + _, err = s.repo.DeleteCascade(s.ctx, deleted.ID) + } + s.Require().NoError(err) + stored, err := NewSettingRepository(s.tx.Client()).GetValue(s.ctx, service.SettingKeyContentModerationConfig) + s.Require().NoError(err) + var got struct { + GroupIDs []int64 `json:"group_ids"` + Mode string `json:"mode"` + } + s.Require().NoError(json.Unmarshal([]byte(stored), &got)) + s.Require().Equal([]int64{kept.ID}, got.GroupIDs) + s.Require().Equal("observe", got.Mode) + }) + } +} + +func (s *GroupRepoSuite) TestDeleteCascadeUnknownGroupPreservesModerationConfig() { + const original = `{"all_groups":false,"group_ids":[123,456],"mode":"observe"}` + s.Require().NoError(NewSettingRepository(s.tx.Client()).Set(s.ctx, service.SettingKeyContentModerationConfig, original)) + for _, guarded := range []bool{false, true} { + var err error + if guarded { + _, err = s.repo.DeleteCascadeIfEmpty(s.ctx, -1) + } else { + _, err = s.repo.DeleteCascade(s.ctx, -1) + } + s.Require().ErrorIs(err, service.ErrGroupNotFound) + stored, readErr := NewSettingRepository(s.tx.Client()).GetValue(s.ctx, service.SettingKeyContentModerationConfig) + s.Require().NoError(readErr) + s.Require().JSONEq(original, stored) + } +} + +func (s *GroupRepoSuite) TestDeleteCascadePreservesMalformedModerationConfig() { + for _, guarded := range []bool{false, true} { + name := map[bool]string{false: "normal", true: "guarded"}[guarded] + s.Run(name, func() { + group := &service.Group{Name: "malformed-moderation-" + name, Platform: service.PlatformAnthropic, RateMultiplier: 1, Status: service.StatusActive, SubscriptionType: service.SubscriptionTypeStandard} + s.Require().NoError(s.repo.Create(s.ctx, group)) + const malformed = `{"group_ids":[oops]}` + s.Require().NoError(NewSettingRepository(s.tx.Client()).Set(s.ctx, service.SettingKeyContentModerationConfig, malformed)) + var err error + if guarded { + _, err = s.repo.DeleteCascadeIfEmpty(s.ctx, group.ID) + } else { + _, err = s.repo.DeleteCascade(s.ctx, group.ID) + } + s.Require().NoError(err) + stored, err := NewSettingRepository(s.tx.Client()).GetValue(s.ctx, service.SettingKeyContentModerationConfig) + s.Require().NoError(err) + s.Require().Equal(malformed, stored) + }) + } +} + func (s *GroupRepoSuite) TestDeleteCascadeIfEmptyIgnoresBindingsToSoftDeletedAccounts() { group := &service.Group{Name: "guarded-soft-deleted-account", Platform: service.PlatformAnthropic, RateMultiplier: 1, Status: service.StatusActive, SubscriptionType: service.SubscriptionTypeStandard} s.Require().NoError(s.repo.Create(s.ctx, group)) diff --git a/backend/internal/repository/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index 7429f250f..2187e74bc 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -999,7 +999,9 @@ func filterSchedulerCredentials(credentials map[string]any) map[string]any { // the full account. Dropping it silently falls back to the platform threshold. // BPS admission also needs workspace identity and JWT expiry before hydration; // neither access_token nor refresh_token belongs in this metadata projection. - keys := []string{"model_mapping", "compact_model_mapping", "api_key", "project_id", "oauth_type", "plan_type", "account_scheduling_threshold", "chatgpt_account_id", "expires_at"} + keys := []string{"model_mapping", "compact_model_mapping", "api_key", "project_id", "oauth_type", "plan_type", "account_scheduling_threshold", "chatgpt_account_id", "expires_at", + // Gemini explicit cache admission needs the endpoint, auth mode and upstream capabilities. + "base_url", "auth_mode", service.GeminiExplicitCacheUpstreamCredentialKey, service.GeminiExplicitCacheUpstreamMaxTTLCredentialKey} filtered := make(map[string]any) for _, key := range keys { if value, ok := credentials[key]; ok && value != nil { diff --git a/backend/internal/repository/scheduler_cache_test.go b/backend/internal/repository/scheduler_cache_test.go index 81231b308..bd8203ed2 100644 --- a/backend/internal/repository/scheduler_cache_test.go +++ b/backend/internal/repository/scheduler_cache_test.go @@ -20,6 +20,23 @@ func TestFilterSchedulerCredentialsKeepsSubscriptionPlanType(t *testing.T) { require.NotContains(t, filtered, "refresh_token") } +func TestFilterSchedulerCredentialsKeepsGeminiExplicitCacheKeys(t *testing.T) { + filtered := filterSchedulerCredentials(map[string]any{ + "api_key": "k", + "base_url": "https://gw.example.com", + "auth_mode": "apikey", + "service_account_json": "secret", + service.GeminiExplicitCacheUpstreamCredentialKey: true, + service.GeminiExplicitCacheUpstreamMaxTTLCredentialKey: 3600, + }) + + require.Equal(t, "https://gw.example.com", filtered["base_url"]) + require.Equal(t, "apikey", filtered["auth_mode"]) + require.Equal(t, true, filtered[service.GeminiExplicitCacheUpstreamCredentialKey]) + require.Equal(t, 3600, filtered[service.GeminiExplicitCacheUpstreamMaxTTLCredentialKey]) + require.NotContains(t, filtered, "service_account_json") +} + func TestSchedulerMetadataAccountKeepsOpenAISubscriptionIdentity(t *testing.T) { account := service.Account{ ID: 24, diff --git a/backend/internal/repository/setting_repo.go b/backend/internal/repository/setting_repo.go index fb4d2f2ac..a2e352fa8 100644 --- a/backend/internal/repository/setting_repo.go +++ b/backend/internal/repository/setting_repo.go @@ -2,6 +2,7 @@ package repository import ( "context" + "errors" "time" "github.com/MACOS-DO/sub4api/ent" @@ -9,6 +10,34 @@ import ( "github.com/MACOS-DO/sub4api/internal/service" ) +// SetContentModerationConfig holds live group rows until the setting is written. +// Deletion takes FOR UPDATE on the group before cleaning this setting, so both +// operations follow the same lock order: groups, then settings. +func (r *settingRepository) SetContentModerationConfig(ctx context.Context, value string, groupIDs []int64) error { + tx, err := r.client.Tx(ctx) + if err != nil && !errors.Is(err, ent.ErrTxStarted) { + return err + } + client := r.client + if err == nil { + defer func() { _ = tx.Rollback() }() + client = tx.Client() + } + if err := lockLiveGroups(ctx, client, groupIDs); err != nil { + return err + } + now := time.Now() + if err := client.Setting.Create().SetKey(service.SettingKeyContentModerationConfig). + SetValue(value).SetUpdatedAt(now).OnConflictColumns(setting.FieldKey). + UpdateNewValues().Exec(ctx); err != nil { + return err + } + if tx != nil { + return tx.Commit() + } + return nil +} + type settingRepository struct { client *ent.Client } diff --git a/backend/internal/repository/wire.go b/backend/internal/repository/wire.go index 32cbced83..20870183f 100644 --- a/backend/internal/repository/wire.go +++ b/backend/internal/repository/wire.go @@ -82,6 +82,7 @@ var ProviderSet = wire.NewSet( NewUsageLogRepository, NewUsageBillingRepository, NewBatchImageRepository, + NewGeminiCachedContentRepository, NewIdempotencyRepository, NewUsageCleanupRepository, NewDashboardAggregationRepository, diff --git a/backend/internal/server/routes/composite_platform_test.go b/backend/internal/server/routes/composite_platform_test.go index 9c89af68f..a092204f9 100644 --- a/backend/internal/server/routes/composite_platform_test.go +++ b/backend/internal/server/routes/composite_platform_test.go @@ -185,6 +185,53 @@ func TestCompositeTargetPlatformMiddlewareRewritesNestedLiveModel(t *testing.T) require.Equal(t, http.StatusNoContent, w.Code) } +// Scenario: 回归 —— openai OAuth 与 deepseek API Key 同时映射 gpt-6-astra 时, +// 请求必须在路由层被拒绝,不能落到默认 Anthropic handler 后再按模型名猜平台。 +// 仅 API Key 的跨平台歧义保持原行为(放行且不解析平台)。 +func TestCompositeTargetPlatformMiddlewareRejectsOnlyOAuthAmbiguousOwnership(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tc := range []struct { + name string + oauthClaimed bool + wantStatus int + }{ + {name: "oauth claimant", oauthClaimed: true, wantStatus: http.StatusBadRequest}, + {name: "apikey only", oauthClaimed: false, wantStatus: http.StatusNoContent}, + } { + t.Run(tc.name, func(t *testing.T) { + resolver := service.NewCompositeRouteResolver(nil) + resolver.SetModelOwnershipResolver(func(context.Context, int64, string) (service.CompositeModelOwnership, error) { + return service.CompositeModelOwnership{Ambiguous: true, OpenAIGatewayOAuthClaimed: tc.oauthClaimed}, nil + }) + router := gin.New() + router.Use(gin.HandlerFunc(servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) { + groupID := int64(8) + c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{ + GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: service.PlatformComposite}, + }) + c.Next() + }))) + router.Use(compositeTargetPlatformMiddleware(resolver)) + router.POST("/v1/responses", func(c *gin.Context) { + _, resolved := service.ResolvedTargetPlatformFromContext(c.Request.Context()) + require.False(t, resolved) + c.Status(http.StatusNoContent) + }) + + req := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"gpt-6-astra"}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, tc.wantStatus, w.Code) + if tc.oauthClaimed { + require.Contains(t, w.Body.String(), "explicit composite route") + } + }) + } +} + func TestCompositeRequestModelFromMultipartLiveSession(t *testing.T) { var body bytes.Buffer writer := multipart.NewWriter(&body) diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index 2cb46e9a8..b4cce90ef 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -350,6 +350,12 @@ func RegisterGatewayRoutes( gemini.GET("/models/:model", h.Gateway.GeminiV1BetaGetModel) // Gin treats ":" as a param marker, but Gemini uses "{model}:{action}" in the same segment. gemini.POST("/models/*modelAction", h.Gateway.GeminiV1BetaModels) + // 显式上下文缓存:网关自管资源 ID 与账号绑定,list/get 只读本地记录。 + gemini.POST("/cachedContents", h.Gateway.GeminiCachedContentsCreate) + gemini.GET("/cachedContents", h.Gateway.GeminiCachedContentsList) + gemini.GET("/cachedContents/:cacheID", h.Gateway.GeminiCachedContentsGet) + gemini.PATCH("/cachedContents/:cacheID", h.Gateway.GeminiCachedContentsPatch) + gemini.DELETE("/cachedContents/:cacheID", h.Gateway.GeminiCachedContentsDelete) } // OpenAI Responses API(不带v1前缀的别名)— auto-route based on group platform @@ -581,6 +587,14 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) c.Abort() return } + // 含 OAuth 账号的跨平台歧义是分组配置错误:拒绝而不是放行。否则未解析的 + // 请求落到默认 Anthropic handler,handler 再按模型名前缀另猜平台, + // OAuth 凭据被送进不匹配的协议管线(如 ChatGPT token 发往 Anthropic)。 + if decision.OAuthAmbiguous() { + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration) + c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": gin.H{"type": "invalid_request_error", "message": decision.AmbiguousMessage()}}) + return + } if decision.Matched { c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision)) if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) { diff --git a/backend/internal/server/routes/gateway_models_pinned_test.go b/backend/internal/server/routes/gateway_models_pinned_test.go index 5b8257a78..67e559acb 100644 --- a/backend/internal/server/routes/gateway_models_pinned_test.go +++ b/backend/internal/server/routes/gateway_models_pinned_test.go @@ -27,6 +27,14 @@ func (r *pinnedModelsRoutesRepository) ListByGroup(context.Context, int64) ([]se return []service.Account{r.account}, nil } +func (r *pinnedModelsRoutesRepository) ListSchedulableByGroupID(context.Context, int64) ([]service.Account, error) { + return []service.Account{r.account}, nil +} + +func (r *pinnedModelsRoutesRepository) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]service.Account, error) { + return []service.Account{r.account}, nil +} + type pinnedModelsRoutesUpstream struct { service.HTTPUpstream ordinaryCalls atomic.Int32 diff --git a/backend/internal/server/routes/prompt_audit_route_coverage_test.go b/backend/internal/server/routes/prompt_audit_route_coverage_test.go index 49f8b68fa..2e1315487 100644 --- a/backend/internal/server/routes/prompt_audit_route_coverage_test.go +++ b/backend/internal/server/routes/prompt_audit_route_coverage_test.go @@ -47,6 +47,7 @@ func TestEveryGatewayPOSTRouteIsClassifiedForPromptAuditCoverage(t *testing.T) { "/videos/edits": {"grok_media.go"}, "/videos/extensions": {"grok_media.go"}, "/models/*modelAction": {"gemini_v1beta_handler.go"}, + "/cachedContents": {"gemini_cached_contents_handler.go"}, "/tts": {"grok_audio.go"}, "/web_search": {"gateway_web_search.go"}, "/x_search": {"gateway_web_search.go"}, diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index dc9b05edd..d2f7fe59e 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -8,6 +8,7 @@ import ( "log/slog" "net/url" "reflect" + "slices" "sort" "strconv" "strings" @@ -130,11 +131,20 @@ func isOpenAIPersonalAccessTokenAuthMode(value string) bool { } } +// TempUnschedulableRule.Scope 的取值:命中后隔离的粒度。 +const ( + TempUnschedScopeAccount = "account" + TempUnschedScopeModel = "model" +) + type TempUnschedulableRule struct { ErrorCode int `json:"error_code"` Keywords []string `json:"keywords"` DurationMinutes int `json:"duration_minutes"` Description string `json:"description"` + // Scope 决定命中后的隔离粒度:account 暂停整个账号,model 只冷却本次请求的模型。 + // 为空时模型已知且非 401 走模型级,否则账号级。 + Scope string `json:"scope,omitempty"` } func (a *Account) IsActive() bool { @@ -346,6 +356,13 @@ func (a *Account) IsGeminiGoogleOne() bool { return a.Platform == PlatformGemini && a.Type == AccountTypeOAuth && a.GeminiOAuthType() == "google_one" } +// IsGeminiThirdPartyAPIKey reports whether a Gemini API Key account points at a +// non-Google base URL. Such upstreams carry no AI Studio tier or daily quota. +func (a *Account) IsGeminiThirdPartyAPIKey() bool { + return a != nil && a.Platform == PlatformGemini && a.Type == AccountTypeAPIKey && + !isOfficialGeminiAPIBaseURL(a.GetCredential("base_url")) +} + func (a *Account) CanGetUsage() bool { return a.Type == AccountTypeOAuth } @@ -467,6 +484,7 @@ func (a *Account) GetTempUnschedulableRules() []TempUnschedulableRule { Keywords: parseTempUnschedStrings(entry["keywords"]), DurationMinutes: parseTempUnschedInt(entry["duration_minutes"]), Description: parseTempUnschedString(entry["description"]), + Scope: normalizeTempUnschedScope(entry["scope"]), } if rule.ErrorCode <= 0 || rule.DurationMinutes <= 0 || len(rule.Keywords) == 0 { @@ -479,6 +497,18 @@ func (a *Account) GetTempUnschedulableRules() []TempUnschedulableRule { return rules } +// normalizeTempUnschedScope 只认 account / model 两个值,其余一律视为未设置。 +func normalizeTempUnschedScope(raw any) string { + switch strings.ToLower(strings.TrimSpace(parseTempUnschedString(raw))) { + case TempUnschedScopeAccount: + return TempUnschedScopeAccount + case TempUnschedScopeModel: + return TempUnschedScopeModel + default: + return "" + } +} + func parseTempUnschedString(value any) string { s, ok := value.(string) if !ok { @@ -668,26 +698,7 @@ func (a *Account) resolveModelMapping(rawMapping map[string]any) map[string]stri } if len(result) > 0 { if a.Platform == domain.PlatformAntigravity { - ensureAntigravityDefaultPassthroughs(result, []string{ - "gemini-3-flash", - "gemini-3.1-pro-high", - "gemini-3.1-pro-low", - "gemini-3.6-flash", - "gemini-3.6-flash-high", - "gemini-3.6-flash-low", - "gemini-3.6-flash-medium", - "gemini-3.6-flash-tiered", - "gemini-3.7-flash", - "gemini-3.7-flash-high", - "gemini-3.7-flash-low", - "gemini-3.7-flash-medium", - "gemini-3.7-flash-tiered", - "gemini-3.8-flash", - "gemini-3.8-flash-high", - "gemini-3.8-flash-low", - "gemini-3.8-flash-medium", - "gemini-3.8-flash-tiered", - }) + ensureAntigravityDefaultPassthroughs(result, antigravityDefaultPassthroughModels) applyAntigravityGemini31ProAliases(result) } return result @@ -737,6 +748,51 @@ func modelMappingSignature(rawMapping map[string]any) uint64 { return h.Sum64() } +// antigravityDefaultPassthroughModels 是 Antigravity 显式 model_mapping 运行时补齐的默认透传条目: +// 让新模型发布前保存的映射也能调用这些模型。 +var antigravityDefaultPassthroughModels = []string{ + "gemini-3-flash", + "gemini-3.1-pro-high", + "gemini-3.1-pro-low", + "gemini-3.6-flash", + "gemini-3.6-flash-high", + "gemini-3.6-flash-low", + "gemini-3.6-flash-medium", + "gemini-3.6-flash-tiered", + "gemini-3.7-flash", + "gemini-3.7-flash-high", + "gemini-3.7-flash-low", + "gemini-3.7-flash-medium", + "gemini-3.7-flash-tiered", + "gemini-3.8-flash", + "gemini-3.8-flash-high", + "gemini-3.8-flash-low", + "gemini-3.8-flash-medium", + "gemini-3.8-flash-tiered", +} + +// isAntigravityInjectedDefaultPassthrough 判断 GetModelMapping 中的 key→target 是否仅由 +// resolveModelMapping 运行时补齐(管理员未写入 credentials.model_mapping)。 +func (a *Account) isAntigravityInjectedDefaultPassthrough(key, target string) bool { + if a == nil || a.Platform != domain.PlatformAntigravity || key != target || !slices.Contains(antigravityDefaultPassthroughModels, key) { + return false + } + rawMapping, _ := a.Credentials["model_mapping"].(map[string]any) + hasExplicitEntry := false + for _, v := range rawMapping { + if _, ok := v.(string); ok { + hasExplicitEntry = true + break + } + } + if !hasExplicitEntry { + // 空映射走默认目录,不做运行时补齐。 + return false + } + _, configured := rawMapping[key].(string) + return !configured +} + func ensureAntigravityDefaultPassthrough(mapping map[string]string, model string) { if mapping == nil || model == "" { return @@ -865,6 +921,10 @@ func resolveRequestedModelInMapping(mapping map[string]string, requestedModel st // (isDeepseekServableModel)——未知模型名透传上游只会得到 404/400,并误触发 // per-(账号,模型) 30 分钟冷却;带 [1m] 上下文后缀的写法先归一化再比对。 func (a *Account) IsModelSupported(requestedModel string) bool { + return supportsOpenAIRequestModel(a, requestedModel, false) +} + +func (a *Account) isModelMappingSupported(requestedModel string) bool { // 透传模式仅替换认证、模型语义完全交由上游决定,因此放行所有模型。 // 该短路必须在 model_mapping 判定之前:账号从"白名单模式"切换到透传后, // credentials 里常残留旧的非空 model_mapping,若不在此放行,透传账号会被 @@ -1582,7 +1642,7 @@ func (a *Account) GetCodingPlanProvider() string { } baseURL := strings.ToLower(a.GetOpenAIBaseURL()) switch { - case strings.Contains(baseURL, "api.kimi.com/coding"): + case isKimiCodingBaseURL(a.GetOpenAIBaseURL()): return PlatformKimi case strings.Contains(baseURL, "bigmodel.cn"), strings.Contains(baseURL, "api.z.ai"): return PlatformZhipu @@ -1595,6 +1655,24 @@ func (a *Account) GetCodingPlanProvider() string { } } +func isKimiCodingBaseURL(baseURL string) bool { + parsed, err := url.Parse(baseURL) + if err != nil || parsed.Scheme != "https" || parsed.User != nil || parsed.Opaque != "" || + parsed.RawQuery != "" || parsed.ForceQuery || strings.Contains(baseURL, "#") { + return false + } + host := strings.ToLower(parsed.Host) + if host != "api.kimi.com" && host != "api.kimi.ai" && host != "api.kimi.com:443" && host != "api.kimi.ai:443" { + return false + } + switch parsed.EscapedPath() { + case "/coding", "/coding/", "/coding/v1", "/coding/v1/": + return true + default: + return false + } +} + func (a *Account) GetOpenAIAccessToken() string { if !a.IsOpenAI() { return "" @@ -2279,7 +2357,10 @@ const ( // 三态:default(跟随渠道)/ enabled(强制开启)/ disabled(强制关闭)。 // 兼容旧 bool 值:true→enabled, false→default(并记录 debug 日志)。 func (a *Account) GetWebSearchEmulationMode() string { - if a == nil || a.Platform != PlatformAnthropic || a.Type != AccountTypeAPIKey || a.Extra == nil { + // OpenAI API Key accounts reach this via /v1/messages; their upstreams + // (DeepSeek etc. over Chat Completions) have no web_search tool. + if a == nil || a.Type != AccountTypeAPIKey || a.Extra == nil || + (a.Platform != PlatformAnthropic && a.Platform != PlatformOpenAI) { return WebSearchModeDefault } raw := a.Extra[featureKeyWebSearchEmulation] diff --git a/backend/internal/service/account_kimi_coding_test.go b/backend/internal/service/account_kimi_coding_test.go new file mode 100644 index 000000000..d2d79e1e0 --- /dev/null +++ b/backend/internal/service/account_kimi_coding_test.go @@ -0,0 +1,83 @@ +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestGetCodingPlanProvider_KimiOfficialURLs(t *testing.T) { + for _, host := range []string{"api.kimi.com", "api.kimi.ai", "API.KIMI.AI", "api.kimi.ai:443"} { + for _, path := range []string{"/coding", "/coding/", "/coding/v1", "/coding/v1/"} { + t.Run(host+path, func(t *testing.T) { + account := &Account{Platform: PlatformKimi, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "account_mode": AccountModeCoding, + "base_url": "https://" + host + path, + }} + require.Equal(t, PlatformKimi, account.GetCodingPlanProvider()) + require.Equal(t, "https://"+host+"/coding/v1/usages", kimiQuotaURL(account.GetOpenAIBaseURL())) + account.Credentials["account_mode"] = AccountModePayG + require.Empty(t, account.GetCodingPlanProvider()) + }) + } + } +} + +func TestGetCodingPlanProvider_KimiRejectsUnsafeURLs(t *testing.T) { + for _, baseURL := range []string{ + "https://api.kimi.ai.attacker.example/coding/v1", + "https://api.kimi.com.attacker.example/coding/v1", + "https://fake-api.kimi.ai/coding/v1", + "https://relay.attacker.example/api.kimi.com/coding", + "https://relay.attacker.example/?target=api.kimi.ai/coding/v1", + "https://relay.attacker.example/#api.kimi.com/coding", + "https://api.kimi.ai@relay.attacker.example/coding/v1", + "https://user@api.kimi.ai/coding/v1", + "https://api.kimi.ai/coding-other", + "https://api.kimi.com/coding/v10", + "https://api.kimi.ai/coding/v1/usages", + "https://api.kimi.ai/v1?target=/coding/v1", + "https://api.kimi.ai/coding/v1?target=attacker", + "https://api.kimi.ai/coding/v1?", + "https://api.kimi.ai/coding/v1#attacker", + "https://api.kimi.ai/coding/v1#", + "https://api.kimi.ai/%63oding/v1", + "https://api.kimi.ai/coding%2fv1", + "https://api.kimi.ai/coding/../coding/v1", + "https://api.kimi.ai/CODING/v1", + "https://api.kimi.ai:8443/coding/v1", + "https://api.kimi.ai:/coding/v1", + "http://api.kimi.ai/coding/v1", + "//api.kimi.ai/coding/v1", + "https://api.kimi.ai/%zz", + } { + t.Run(baseURL, func(t *testing.T) { + account := &Account{Platform: PlatformKimi, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "account_mode": AccountModeCoding, + "base_url": baseURL, + }} + require.Empty(t, account.GetCodingPlanProvider()) + }) + } +} + +func TestGetCodingPlanProvider_UnrelatedProvidersUnchanged(t *testing.T) { + for _, testCase := range []struct { + platform string + baseURL string + }{ + {PlatformZhipu, "https://open.bigmodel.cn/api/coding/paas/v4"}, + {PlatformZhipu, "https://api.z.ai/api/coding/paas/v4"}, + {PlatformMiniMax, "https://api.minimax.io/v1"}, + {PlatformMiniMax, "https://api.minimaxi.com/v1"}, + {PlatformMiniMax, "https://api.minimax.com/v1"}, + } { + t.Run(testCase.baseURL, func(t *testing.T) { + account := &Account{Platform: testCase.platform, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "account_mode": AccountModeCoding, + "base_url": testCase.baseURL, + }} + require.Equal(t, testCase.platform, account.GetCodingPlanProvider()) + }) + } +} diff --git a/backend/internal/service/account_stats_pricing_test.go b/backend/internal/service/account_stats_pricing_test.go index 36b840f2f..0496ddeb6 100644 --- a/backend/internal/service/account_stats_pricing_test.go +++ b/backend/internal/service/account_stats_pricing_test.go @@ -933,7 +933,7 @@ func TestResolveAccountStatsCost_Gemini36FlashTierUsesFallbackPricing(t *testing UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000, CacheReadTokens: 1_000_000}, 1, 0, "", time.Time{}, true, ) require.NotNil(t, result) - require.InDelta(t, 9.15, *result, 1e-12) + require.InDelta(t, 4.575, *result, 1e-12) } func TestResolveAccountStatsCost_AllMiss_ReturnsNil(t *testing.T) { diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index cd26e957e..e9cd59e4e 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -2471,12 +2471,12 @@ func (s *AccountTestService) routeAntigravityTest(c *gin.Context, account *Accou } return s.testClaudeAccountConnection(c, account, modelID) } - return s.testAntigravityAccountConnection(c, account, modelID) + return s.testAntigravityAccountConnection(c, account, modelID, prompt) } // testAntigravityAccountConnection tests an Antigravity account's connection // 支持 Claude 和 Gemini 两种协议,使用非流式请求 -func (s *AccountTestService) testAntigravityAccountConnection(c *gin.Context, account *Account, modelID string) error { +func (s *AccountTestService) testAntigravityAccountConnection(c *gin.Context, account *Account, modelID string, prompt string) error { ctx := c.Request.Context() testModelID := antigravityConnectionTestModel(modelID) @@ -2495,8 +2495,8 @@ func (s *AccountTestService) testAntigravityAccountConnection(c *gin.Context, ac // Send test_start event s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID}) - // 调用 AntigravityGatewayService.TestConnection(复用协议转换逻辑) - result, err := s.antigravityGatewayService.TestConnection(ctx, account, testModelID) + // 调用 AntigravityGatewayService.TestConnectionWithPrompt(复用协议转换逻辑) + result, err := s.antigravityGatewayService.TestConnectionWithPrompt(ctx, account, testModelID, prompt) if err != nil { return s.sendErrorAndEnd(c, err.Error()) } @@ -2505,6 +2505,13 @@ func (s *AccountTestService) testAntigravityAccountConnection(c *gin.Context, ac if result.Text != "" { s.sendEvent(c, TestEvent{Type: "content", Text: result.Text}) } + for _, img := range result.Images { + s.sendEvent(c, TestEvent{ + Type: "image", + ImageURL: img.ImageURL, + MimeType: img.MimeType, + }) + } s.sendEvent(c, TestEvent{Type: "test_complete", Success: true}) return nil @@ -2592,14 +2599,7 @@ func (s *AccountTestService) buildGeminiOAuthRequest(ctx context.Context, accoun } func (s *AccountTestService) buildGeminiServiceAccountRequest(ctx context.Context, account *Account, modelID string, payload []byte) (*http.Request, error) { - if s.geminiTokenProvider == nil { - return nil, fmt.Errorf("gemini token provider not configured") - } - accessToken, err := s.geminiTokenProvider.GetAccessToken(ctx, account) - if err != nil { - return nil, fmt.Errorf("failed to get service account access token: %w", err) - } - fullURL, err := buildVertexGeminiURL(account.VertexProjectID(), account.VertexLocation(modelID), modelID, "streamGenerateContent", true) + fullURL, err := buildVertexGeminiAccountURL(account, modelID, "streamGenerateContent", true) if err != nil { return nil, err } @@ -2608,7 +2608,9 @@ func (s *AccountTestService) buildGeminiServiceAccountRequest(ctx context.Contex return nil, err } req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", "Bearer "+accessToken) + if err := setVertexGeminiAuth(ctx, req, account, s.geminiTokenProvider); err != nil { + return nil, fmt.Errorf("failed to authenticate vertex request: %w", err) + } return req, nil } diff --git a/backend/internal/service/account_test_service_antigravity_test.go b/backend/internal/service/account_test_service_antigravity_test.go index b3362f3f6..6a14ea85c 100644 --- a/backend/internal/service/account_test_service_antigravity_test.go +++ b/backend/internal/service/account_test_service_antigravity_test.go @@ -3,6 +3,7 @@ package service import ( + "encoding/json" "testing" "github.com/stretchr/testify/require" @@ -14,3 +15,68 @@ func TestAntigravityConnectionTestModel(t *testing.T) { require.Equal(t, "claude-sonnet-4-6", antigravityConnectionTestModel("")) require.Equal(t, "gemini-3.1-pro-preview", antigravityConnectionTestModel("gemini-3.1-pro-preview")) } + +func TestAntigravityBuildGeminiTestRequest_IncludesValidatedToolConfig(t *testing.T) { + t.Parallel() + + svc := &AntigravityGatewayService{} + raw, err := svc.buildGeminiTestRequestWithPrompt("proj-123", "gemini-3.8-flash-high", "") + require.NoError(t, err) + + var v1Req map[string]any + require.NoError(t, json.Unmarshal(raw, &v1Req)) + require.Equal(t, "proj-123", v1Req["project"]) + require.Equal(t, "gemini-3.8-flash-high", v1Req["model"]) + + inner, ok := v1Req["request"].(map[string]any) + require.True(t, ok) + toolCfg, ok := inner["toolConfig"].(map[string]any) + require.True(t, ok, "expected toolConfig to be present in Gemini test request") + fcCfg, ok := toolCfg["functionCallingConfig"].(map[string]any) + require.True(t, ok) + require.Equal(t, "VALIDATED", fcCfg["mode"]) +} + +func TestAntigravityBuildGeminiTestRequestWithPrompt_ImageModel(t *testing.T) { + t.Parallel() + + svc := &AntigravityGatewayService{} + raw, err := svc.buildGeminiTestRequestWithPrompt("proj-123", "gemini-3.1-flash-image", "a cute cat") + require.NoError(t, err) + + var v1Req map[string]any + require.NoError(t, json.Unmarshal(raw, &v1Req)) + inner, ok := v1Req["request"].(map[string]any) + require.True(t, ok) + + genCfg, ok := inner["generationConfig"].(map[string]any) + require.True(t, ok) + require.Equal(t, []any{"TEXT", "IMAGE"}, genCfg["responseModalities"]) + + contents, ok := inner["contents"].([]any) + require.True(t, ok) + require.Len(t, contents, 1) + firstContent := contents[0].(map[string]any) + parts := firstContent["parts"].([]any) + require.Equal(t, "a cute cat", parts[0].(map[string]any)["text"]) +} + +func TestExtractContentFromSSEResponse_ExtractsTextAndInlineImages(t *testing.T) { + t.Parallel() + + sse := "data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"Here is your image\"},{\"inlineData\":{\"mimeType\":\"image/png\",\"data\":\"iVBORw0KGgo=\"}}]}}]}}\n\n" + text, images := extractContentFromSSEResponse([]byte(sse)) + require.Equal(t, "Here is your image", text) + require.Len(t, images, 1) + require.Equal(t, "image/png", images[0].MimeType) + require.Equal(t, "data:image/png;base64,iVBORw0KGgo=", images[0].ImageURL) +} + +func TestAntigravityShouldUseGeminiTestBuilder_UsesMappedModel(t *testing.T) { + t.Parallel() + + require.True(t, shouldUseAntigravityGeminiTestRequest("custom-alias", "gemini-2.5-flash")) + require.True(t, shouldUseAntigravityGeminiTestRequest("gemini-3.1-pro", "gemini-pro-agent")) + require.False(t, shouldUseAntigravityGeminiTestRequest("gemini-alias", "claude-sonnet-4-6")) + require.False(t, shouldUseAntigravityGeminiTestRequest("claude-sonnet-4-6", "claude-sonnet-4-6")) +} diff --git a/backend/internal/service/account_websearch_test.go b/backend/internal/service/account_websearch_test.go index 6ed69d4cf..66fda055c 100644 --- a/backend/internal/service/account_websearch_test.go +++ b/backend/internal/service/account_websearch_test.go @@ -86,12 +86,30 @@ func TestGetWebSearchEmulationMode_MissingField(t *testing.T) { require.Equal(t, WebSearchModeDefault, a.GetWebSearchEmulationMode()) } -func TestGetWebSearchEmulationMode_NonAnthropicPlatform(t *testing.T) { +func TestGetWebSearchEmulationMode_OpenAIAPIKey(t *testing.T) { a := &Account{ Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Extra: map[string]any{featureKeyWebSearchEmulation: "enabled"}, } + require.Equal(t, WebSearchModeEnabled, a.GetWebSearchEmulationMode()) +} + +func TestGetWebSearchEmulationMode_OpenAIOAuth(t *testing.T) { + a := &Account{ + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Extra: map[string]any{featureKeyWebSearchEmulation: "enabled"}, + } + require.Equal(t, WebSearchModeDefault, a.GetWebSearchEmulationMode()) +} + +func TestGetWebSearchEmulationMode_OtherPlatform(t *testing.T) { + a := &Account{ + Platform: PlatformGemini, + Type: AccountTypeAPIKey, + Extra: map[string]any{featureKeyWebSearchEmulation: "enabled"}, + } require.Equal(t, WebSearchModeDefault, a.GetWebSearchEmulationMode()) } diff --git a/backend/internal/service/admin_group.go b/backend/internal/service/admin_group.go index e1401f6ec..84733dc51 100644 --- a/backend/internal/service/admin_group.go +++ b/backend/internal/service/admin_group.go @@ -374,7 +374,7 @@ func normalizeCreateGroupInputForSimpleMode(input *CreateGroupInput) { return } *input = CreateGroupInput{ - Name: input.Name, Description: input.Description, Platform: input.Platform, + Name: input.Name, Description: input.Description, I18n: input.I18n, Platform: input.Platform, RateMultiplier: 1, SubscriptionType: SubscriptionTypeStandard, } } @@ -383,7 +383,7 @@ func normalizeUpdateGroupInputForSimpleMode(input *UpdateGroupInput) { if input == nil { return } - *input = UpdateGroupInput{Name: input.Name, Description: input.Description} + *input = UpdateGroupInput{Name: input.Name, Description: input.Description, I18n: input.I18n} } func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupInput) (*Group, error) { @@ -396,6 +396,10 @@ func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupIn if input.RateMultiplier <= 0 { return nil, errors.New("rate_multiplier must be > 0") } + i18n, err := normalizeGroupI18n(input.I18n) + if err != nil { + return nil, err + } platform := NormalizeGroupPlatform(input.Platform) // 固定账号 manifest 配置:账号绑定发生在创建之后,创建时无法校验成员关系, @@ -567,6 +571,7 @@ func (s *adminServiceImpl) CreateGroup(ctx context.Context, input *CreateGroupIn group := &Group{ Name: input.Name, Description: input.Description, + I18n: i18n, Platform: platform, RateMultiplier: input.RateMultiplier, IsExclusive: input.IsExclusive, @@ -778,6 +783,13 @@ func (s *adminServiceImpl) UpdateGroup(ctx context.Context, id int64, input *Upd if input.Description != nil { group.Description = *input.Description } + if input.I18n != nil { + i18n, err := normalizeGroupI18n(*input.I18n) + if err != nil { + return nil, err + } + group.I18n = i18n + } if input.Platform != "" { group.Platform = input.Platform } diff --git a/backend/internal/service/admin_group_duplicate.go b/backend/internal/service/admin_group_duplicate.go index 859d19d6f..b31a4ab33 100644 --- a/backend/internal/service/admin_group_duplicate.go +++ b/backend/internal/service/admin_group_duplicate.go @@ -97,6 +97,7 @@ func cloneGroupForDuplicate(source *Group, operationID string) *Group { return &Group{ Name: duplicateGroupName(source.Name, 1), Description: source.Description, + I18n: cloneGroupI18nForDuplicate(source.I18n), Platform: source.Platform, RateMultiplier: source.RateMultiplier, PeakRateEnabled: source.PeakRateEnabled, diff --git a/backend/internal/service/admin_service.go b/backend/internal/service/admin_service.go index d29873907..545a28479 100644 --- a/backend/internal/service/admin_service.go +++ b/backend/internal/service/admin_service.go @@ -235,6 +235,7 @@ type AdminBoundAuthIdentityChannel struct { type CreateGroupInput struct { Name string Description string + I18n GroupI18n // 名称与描述的界面语言译文 Platform string RateMultiplier float64 IsExclusive bool @@ -315,6 +316,7 @@ type CreateGroupInput struct { type UpdateGroupInput struct { Name string Description *string + I18n *GroupI18n // nil 表示不修改;非 nil 整体替换 Platform string RateMultiplier *float64 // 使用指针以支持设置为0 IsExclusive *bool diff --git a/backend/internal/service/admin_service_group_i18n_test.go b/backend/internal/service/admin_service_group_i18n_test.go new file mode 100644 index 000000000..e036a41fb --- /dev/null +++ b/backend/internal/service/admin_service_group_i18n_test.go @@ -0,0 +1,150 @@ +//go:build unit + +package service + +import ( + "context" + "net/http" + "testing" + + "github.com/MACOS-DO/sub4api/internal/config" + infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +func TestAdminService_CreateGroup_NormalizesI18n(t *testing.T) { + repo := &groupRepoStubForAdmin{} + svc := &adminServiceImpl{groupRepo: repo} + + _, err := svc.CreateGroup(context.Background(), &CreateGroupInput{ + Name: "Claude Code - 标准", + Platform: PlatformAnthropic, + RateMultiplier: 1.0, + I18n: GroupI18n{ + "en": {Name: " Claude Code - Standard ", Description: "Pro + Max pool"}, + "zh": {}, + }, + }) + + require.NoError(t, err) + require.NotNil(t, repo.created) + require.Equal(t, GroupI18n{ + "en": {Name: "Claude Code - Standard", Description: "Pro + Max pool"}, + }, repo.created.I18n) +} + +func TestAdminService_CreateGroup_RejectsInvalidI18nLocale(t *testing.T) { + repo := &groupRepoStubForAdmin{} + svc := &adminServiceImpl{groupRepo: repo} + + _, err := svc.CreateGroup(context.Background(), &CreateGroupInput{ + Name: "g", + Platform: PlatformAnthropic, + RateMultiplier: 1.0, + I18n: GroupI18n{"en_US": {Name: "x"}}, + }) + + require.Error(t, err) + appErr := infraerrors.FromError(err) + require.Equal(t, int32(http.StatusBadRequest), appErr.Code) + require.Equal(t, "INVALID_GROUP_I18N", appErr.Reason) + require.Nil(t, repo.created) +} + +func TestAdminService_CreateGroup_RejectsCaseCollidingI18nLocales(t *testing.T) { + repo := &groupRepoStubForAdmin{} + svc := &adminServiceImpl{groupRepo: repo} + + _, err := svc.CreateGroup(context.Background(), &CreateGroupInput{ + Name: "默认", + Platform: PlatformAnthropic, + RateMultiplier: 1.0, + I18n: GroupI18n{"en": {Name: "English A"}, "EN": {Name: "English B"}}, + }) + + require.Error(t, err) + appErr := infraerrors.FromError(err) + require.Equal(t, int32(http.StatusBadRequest), appErr.Code) + require.Equal(t, "INVALID_GROUP_I18N", appErr.Reason) + require.Nil(t, repo.created) +} + +func TestAdminService_UpdateGroup_I18n(t *testing.T) { + newExisting := func() *Group { + return &Group{ + ID: 1, Name: "标准", Platform: PlatformAnthropic, Status: StatusActive, RateMultiplier: 1, + I18n: GroupI18n{"en": {Name: "Standard"}}, + } + } + + t.Run("omitted i18n keeps stored translations", func(t *testing.T) { + repo := &groupRepoStubForAdmin{getByID: newExisting()} + svc := &adminServiceImpl{groupRepo: repo} + + _, err := svc.UpdateGroup(context.Background(), 1, &UpdateGroupInput{Name: "标准版"}) + + require.NoError(t, err) + require.Equal(t, "标准版", repo.updated.Name) + require.Equal(t, GroupI18n{"en": {Name: "Standard"}}, repo.updated.I18n) + }) + + t.Run("provided i18n replaces stored translations as a whole", func(t *testing.T) { + repo := &groupRepoStubForAdmin{getByID: newExisting()} + svc := &adminServiceImpl{groupRepo: repo} + next := GroupI18n{"zh": {Description: " 号池 "}} + + _, err := svc.UpdateGroup(context.Background(), 1, &UpdateGroupInput{I18n: &next}) + + require.NoError(t, err) + require.Equal(t, GroupI18n{"zh": {Description: "号池"}}, repo.updated.I18n) + }) + + t.Run("empty i18n clears stored translations", func(t *testing.T) { + repo := &groupRepoStubForAdmin{getByID: newExisting()} + svc := &adminServiceImpl{groupRepo: repo} + next := GroupI18n{} + + _, err := svc.UpdateGroup(context.Background(), 1, &UpdateGroupInput{I18n: &next}) + + require.NoError(t, err) + require.NotNil(t, repo.updated.I18n) + require.Empty(t, repo.updated.I18n) + }) + + t.Run("invalid i18n is rejected before persisting", func(t *testing.T) { + repo := &groupRepoStubForAdmin{getByID: newExisting()} + svc := &adminServiceImpl{groupRepo: repo} + next := GroupI18n{"not a locale": {Name: "x"}} + + _, err := svc.UpdateGroup(context.Background(), 1, &UpdateGroupInput{I18n: &next}) + + require.Error(t, err) + require.Equal(t, "INVALID_GROUP_I18N", infraerrors.FromError(err).Reason) + require.Nil(t, repo.updated) + }) + + // 简易模式只放行名称与描述,译文属于同一类展示文案,同样放行。 + t.Run("simple mode keeps i18n editable", func(t *testing.T) { + repo := &groupRepoStubForAdmin{getByID: newExisting()} + svc := &adminServiceImpl{cfg: &config.Config{RunMode: config.RunModeSimple}, groupRepo: repo} + next := GroupI18n{"en": {Name: "Standard v2"}} + rate := 9.0 + + _, err := svc.UpdateGroup(context.Background(), 1, &UpdateGroupInput{I18n: &next, RateMultiplier: &rate}) + + require.NoError(t, err) + require.Equal(t, GroupI18n{"en": {Name: "Standard v2"}}, repo.updated.I18n) + require.Equal(t, 1.0, repo.updated.RateMultiplier) + }) +} + +func TestCloneGroupForDuplicate_DropsNameTranslations(t *testing.T) { + source := &Group{ + ID: 7, Name: "标准", Platform: PlatformAnthropic, + I18n: GroupI18n{"en": {Name: "Standard", Description: "Pro + Max pool"}}, + } + + clone := cloneGroupForDuplicate(source, "op-1") + + require.Equal(t, GroupI18n{"en": {Description: "Pro + Max pool"}}, clone.I18n) +} diff --git a/backend/internal/service/antigravity_gateway_compat.go b/backend/internal/service/antigravity_gateway_compat.go index 9caa4809f..0fe369bf5 100644 --- a/backend/internal/service/antigravity_gateway_compat.go +++ b/backend/internal/service/antigravity_gateway_compat.go @@ -71,7 +71,7 @@ func (s *AntigravityGatewayService) ForwardAsChatCompletions( return nil, s.writeAntigravityCompatError(c, http.StatusBadRequest, "invalid_request_error", "model is required") } - responsesRequest, err := apicompat.ChatCompletionsToResponses(&request) + responsesRequest, err := chatCompletionsToResponses(settingServiceConfig(s.settingService), &request) if err != nil { return nil, s.writeAntigravityCompatError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) } diff --git a/backend/internal/service/antigravity_gateway_gemini.go b/backend/internal/service/antigravity_gateway_gemini.go index 5a12ef074..c4ba27ac9 100644 --- a/backend/internal/service/antigravity_gateway_gemini.go +++ b/backend/internal/service/antigravity_gateway_gemini.go @@ -141,6 +141,8 @@ func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Co injectedBody = reconciled } + injectedBody = ensureGeminiFunctionCallThoughtSignatures(injectedBody) + // 包装请求 wrappedBody, err := s.wrapV1InternalRequest(projectID, mappedModel, injectedBody) if err != nil { diff --git a/backend/internal/service/antigravity_gateway_retry.go b/backend/internal/service/antigravity_gateway_retry.go index f823bdf34..c21b733ad 100644 --- a/backend/internal/service/antigravity_gateway_retry.go +++ b/backend/internal/service/antigravity_gateway_retry.go @@ -78,12 +78,7 @@ func accountHasAntigravityPaidTier(account *Account) bool { if !ok { return false } - switch strings.ToLower(strings.TrimSpace(planType)) { - case "pro", "ultra": - return true - default: - return false - } + return antigravity.IsPaidPlanType(planType) } // smartRetryAction 智能重试的处理结果 diff --git a/backend/internal/service/antigravity_gateway_service.go b/backend/internal/service/antigravity_gateway_service.go index 2bd9e67aa..af99afa20 100644 --- a/backend/internal/service/antigravity_gateway_service.go +++ b/backend/internal/service/antigravity_gateway_service.go @@ -344,16 +344,32 @@ func (s *AntigravityGatewayService) IsModelSupported(requestedModel string) bool strings.HasPrefix(requestedModel, "gemini-") } +// TestConnectionImage 测试连接返回的图片结果 +type TestConnectionImage struct { + ImageURL string + MimeType string +} + // TestConnectionResult 测试连接结果 type TestConnectionResult struct { - Text string // 响应文本 - MappedModel string // 实际使用的模型 + Text string // 响应文本 + Images []TestConnectionImage // 响应图片(图片生成模型) + MappedModel string // 实际使用的模型 +} + +func shouldUseAntigravityGeminiTestRequest(_, mappedModel string) bool { + return strings.HasPrefix(strings.ToLower(strings.TrimSpace(mappedModel)), "gemini-") } // TestConnection 测试 Antigravity 账号连接。 // 复用 antigravityRetryLoop 的完整重试 / credits overages / 智能重试逻辑, // 与真实调度行为一致。差异:不做账号切换(测试指定账号)、不记录 ops 错误。 func (s *AntigravityGatewayService) TestConnection(ctx context.Context, account *Account, modelID string) (*TestConnectionResult, error) { + return s.TestConnectionWithPrompt(ctx, account, modelID, "") +} + +// TestConnectionWithPrompt 测试 Antigravity 账号连接,支持为图片生成模型指定测试提示词。 +func (s *AntigravityGatewayService) TestConnectionWithPrompt(ctx context.Context, account *Account, modelID string, prompt string) (*TestConnectionResult, error) { // 获取 token if s.tokenProvider == nil { @@ -377,8 +393,8 @@ func (s *AntigravityGatewayService) TestConnection(ctx context.Context, account // 构建请求体 var requestBody []byte - if strings.HasPrefix(modelID, "gemini-") { - requestBody, err = s.buildGeminiTestRequest(projectID, mappedModel) + if shouldUseAntigravityGeminiTestRequest(modelID, mappedModel) { + requestBody, err = s.buildGeminiTestRequestWithPrompt(projectID, mappedModel, prompt) } else { requestBody, err = s.buildClaudeTestRequest(projectID, mappedModel) } @@ -434,8 +450,8 @@ func (s *AntigravityGatewayService) TestConnection(ctx context.Context, account return nil, fmt.Errorf("API 返回 %d: %s", result.resp.StatusCode, string(respBody)) } - text := extractTextFromSSEResponse(respBody) - return &TestConnectionResult{Text: text, MappedModel: mappedModel}, nil + text, images := extractContentFromSSEResponse(respBody) + return &TestConnectionResult{Text: text, Images: images, MappedModel: mappedModel}, nil } // testConnectionHandleError 是 TestConnection 使用的轻量 handleError 回调。 @@ -451,9 +467,39 @@ func testConnectionHandleError( return nil } -// buildGeminiTestRequest 构建 Gemini 格式测试请求 -// 使用最小 token 消耗:输入 "." + maxOutputTokens: 1 -func (s *AntigravityGatewayService) buildGeminiTestRequest(projectID, model string) ([]byte, error) { +// buildGeminiTestRequestWithPrompt 构建 Gemini 格式测试请求 +// 文本模型使用最小 token 消耗:输入 "." + maxOutputTokens: 1;图片模型使用图片生成配置 +func (s *AntigravityGatewayService) buildGeminiTestRequestWithPrompt(projectID, model, prompt string) ([]byte, error) { + if isImageGenerationModel(model) { + imagePrompt := strings.TrimSpace(prompt) + if imagePrompt == "" { + imagePrompt = defaultGeminiImageTestPrompt + } + payload := map[string]any{ + "contents": []map[string]any{ + { + "role": "user", + "parts": []map[string]any{ + {"text": imagePrompt}, + }, + }, + }, + "systemInstruction": map[string]any{ + "parts": []map[string]any{ + {"text": antigravity.GetDefaultIdentityPatch()}, + }, + }, + "generationConfig": map[string]any{ + "responseModalities": []string{"TEXT", "IMAGE"}, + "imageConfig": map[string]any{ + "aspectRatio": "1:1", + }, + }, + } + payloadBytes, _ := json.Marshal(payload) + return s.wrapV1InternalRequest(projectID, model, payloadBytes) + } + payload := map[string]any{ "contents": []map[string]any{ { @@ -472,6 +518,11 @@ func (s *AntigravityGatewayService) buildGeminiTestRequest(projectID, model stri "generationConfig": map[string]any{ "maxOutputTokens": 1, }, + "toolConfig": map[string]any{ + "functionCallingConfig": map[string]any{ + "mode": "VALIDATED", + }, + }, } payloadBytes, _ := json.Marshal(payload) return s.wrapV1InternalRequest(projectID, model, payloadBytes) @@ -504,9 +555,10 @@ func (s *AntigravityGatewayService) getClaudeTransformOptions(ctx context.Contex return opts } -// extractTextFromSSEResponse 从 SSE 流式响应中提取文本 -func extractTextFromSSEResponse(respBody []byte) string { +// extractContentFromSSEResponse 从 SSE 流式响应中提取文本和内联图片 +func extractContentFromSSEResponse(respBody []byte) (string, []TestConnectionImage) { var texts []string + var images []TestConnectionImage lines := bytes.Split(respBody, []byte("\n")) for _, line := range lines { @@ -532,7 +584,7 @@ func extractTextFromSSEResponse(respBody []byte) string { continue } - // 尝试从 response.candidates[0].content.parts[].text 提取 + // 尝试从 response.candidates[0].content.parts[] 提取 response, ok := data["response"].(map[string]any) if !ok { // 尝试直接从 candidates 提取(某些响应格式) @@ -564,11 +616,21 @@ func extractTextFromSSEResponse(respBody []byte) string { if text, ok := partMap["text"].(string); ok && text != "" { texts = append(texts, text) } + if inlineData, ok := partMap["inlineData"].(map[string]any); ok { + mimeType, _ := inlineData["mimeType"].(string) + b64Data, _ := inlineData["data"].(string) + if strings.HasPrefix(strings.ToLower(mimeType), "image/") && b64Data != "" { + images = append(images, TestConnectionImage{ + ImageURL: fmt.Sprintf("data:%s;base64,%s", mimeType, b64Data), + MimeType: mimeType, + }) + } + } } } } - return strings.Join(texts, "") + return strings.Join(texts, ""), images } // injectIdentityPatchToGeminiRequest 为 Gemini 格式请求注入身份提示词 diff --git a/backend/internal/service/antigravity_gateway_service_test.go b/backend/internal/service/antigravity_gateway_service_test.go index d3c7638a2..635b478bf 100644 --- a/backend/internal/service/antigravity_gateway_service_test.go +++ b/backend/internal/service/antigravity_gateway_service_test.go @@ -2012,3 +2012,175 @@ func generateLargeUnwrapJSON(minSize int) []byte { b, _ := json.Marshal(outer) return b } + +func TestAntigravityGatewayService_ForwardGemini_NonStreamPreservesFunctionCallAndThoughtSignature(t *testing.T) { + gin.SetMode(gin.TestMode) + body := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather for Tokyo."}]}],"tools":[{"functionDeclarations":[{"name":"get_weather","description":"Get weather","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}]}]}`) + + writer := httptest.NewRecorder() + c, _ := gin.CreateTestContext(writer) + c.Request = httptest.NewRequest(http.MethodPost, "/v1beta/models/gemini-4-argon:generateContent", bytes.NewReader(body)) + + sseStream := strings.Join([]string{ + `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"sig_fc_1","functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_1"}}]}}],"usageMetadata":{"promptTokenCount":300,"candidatesTokenCount":16,"totalTokenCount":328,"thoughtsTokenCount":12},"modelVersion":"gemini-4-argon","responseId":"resp_1"}}`, + "", + `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":""}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":300,"candidatesTokenCount":22,"totalTokenCount":334,"thoughtsTokenCount":12},"modelVersion":"gemini-4-argon","responseId":"resp_1"}}`, + "", + }, "\n") + + upstream := &queuedHTTPUpstreamStub{ + responses: []*http.Response{{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(sseStream)), + }}, + } + svc := &AntigravityGatewayService{ + settingService: NewSettingService(&antigravitySettingRepoStub{}, &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}), + tokenProvider: &AntigravityTokenProvider{}, + httpUpstream: upstream, + } + account := &Account{ + ID: 109, + Name: "antigravity-fc-nonstream", + Platform: PlatformAntigravity, + Type: AccountTypeOAuth, + Status: StatusActive, + Concurrency: 1, + Credentials: map[string]any{ + "access_token": "test-access-token", + "project_id": "test-project", + "model_mapping": map[string]any{ + "gemini-4-argon": "gemini-4-argon", + }, + }, + } + + result, err := svc.ForwardGemini(context.Background(), c, account, "gemini-4-argon", "generateContent", false, body, false) + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, http.StatusOK, writer.Code) + + var respPayload map[string]any + require.NoError(t, json.Unmarshal(writer.Body.Bytes(), &respPayload)) + candidates, ok := respPayload["candidates"].([]any) + require.True(t, ok) + require.Len(t, candidates, 1) + candidate, ok := candidates[0].(map[string]any) + require.True(t, ok) + require.Equal(t, "STOP", candidate["finishReason"]) + + content, ok := candidate["content"].(map[string]any) + require.True(t, ok) + parts, ok := content["parts"].([]any) + require.True(t, ok) + require.Len(t, parts, 1, "trailing empty text part should not overwrite or pollute functionCall part") + + part0, ok := parts[0].(map[string]any) + require.True(t, ok) + require.Equal(t, "sig_fc_1", part0["thoughtSignature"]) + fc, ok := part0["functionCall"].(map[string]any) + require.True(t, ok) + require.Equal(t, "get_weather", fc["name"]) + require.Equal(t, "call_1", fc["id"]) + require.Equal(t, map[string]any{"city": "Tokyo"}, fc["args"]) +} + +func TestAntigravityGatewayService_ForwardGemini_StreamAndFunctionResponseFollowUp(t *testing.T) { + gin.SetMode(gin.TestMode) + + // 1) Stream request with functionDeclarations returns unwrapped functionCall and thoughtSignature + streamReqBody := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather for Tokyo."}]}],"tools":[{"functionDeclarations":[{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}]}]}`) + streamWriter := httptest.NewRecorder() + streamCtx, _ := gin.CreateTestContext(streamWriter) + streamCtx.Request = httptest.NewRequest(http.MethodPost, "/v1beta/models/gemini-4-argon:streamGenerateContent?alt=sse", bytes.NewReader(streamReqBody)) + + streamSSE := strings.Join([]string{ + `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"sig_stream_1","functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_s1"}}]}}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":5}}}`, + "", + `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":""}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":6}}}`, + "", + }, "\n") + + // 2) Non-stream follow-up with functionCall (missing thoughtSignature) + functionResponse (with inlineData image) + followUpReqBody := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather for Tokyo."}]},{"role":"model","parts":[{"functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_s1"}}]},{"role":"user","parts":[{"functionResponse":{"name":"get_weather","id":"call_s1","response":{"weather":"Sunny"},"parts":[{"inlineData":{"mimeType":"image/png","data":"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}}]}}]}],"tools":[{"functionDeclarations":[{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}]}]}`) + followUpWriter := httptest.NewRecorder() + followUpCtx, _ := gin.CreateTestContext(followUpWriter) + followUpCtx.Request = httptest.NewRequest(http.MethodPost, "/v1beta/models/gemini-4-argon:generateContent", bytes.NewReader(followUpReqBody)) + + followUpSSE := strings.Join([]string{ + `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"It is sunny in "}]}}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":4}}}`, + "", + `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"Tokyo."}]}}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":6}}}`, + "", + `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"sig_final","text":""}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":8}}}`, + "", + }, "\n") + + upstream := &queuedHTTPUpstreamStub{ + responses: []*http.Response{ + { + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(streamSSE)), + }, + { + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(followUpSSE)), + }, + }, + } + + svc := &AntigravityGatewayService{ + settingService: NewSettingService(&antigravitySettingRepoStub{}, &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}), + tokenProvider: &AntigravityTokenProvider{}, + httpUpstream: upstream, + } + account := &Account{ + ID: 110, + Name: "antigravity-fc-stream", + Platform: PlatformAntigravity, + Type: AccountTypeOAuth, + Status: StatusActive, + Concurrency: 1, + Credentials: map[string]any{ + "access_token": "test-access-token", + "project_id": "test-project", + "model_mapping": map[string]any{ + "gemini-4-argon": "gemini-4-argon", + }, + }, + } + + res1, err := svc.ForwardGemini(context.Background(), streamCtx, account, "gemini-4-argon", "streamGenerateContent", true, streamReqBody, false) + require.NoError(t, err) + require.NotNil(t, res1) + require.Contains(t, streamWriter.Body.String(), `"functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_s1"}`) + require.Contains(t, streamWriter.Body.String(), `"thoughtSignature":"sig_stream_1"`) + + res2, err := svc.ForwardGemini(context.Background(), followUpCtx, account, "gemini-4-argon", "generateContent", false, followUpReqBody, false) + require.NoError(t, err) + require.NotNil(t, res2) + require.Len(t, upstream.requestBodies, 2) + + // Verify follow-up request had dummy thoughtSignature injected on functionCall and preserved functionResponse image part + secondSent := string(upstream.requestBodies[1]) + require.Contains(t, secondSent, `"thoughtSignature":"skip_thought_signature_validator"`) + require.Contains(t, secondSent, `"mimeType":"image/png"`) + + var followUpResp map[string]any + require.NoError(t, json.Unmarshal(followUpWriter.Body.Bytes(), &followUpResp)) + cands, ok := followUpResp["candidates"].([]any) + require.True(t, ok) + cand0, ok := cands[0].(map[string]any) + require.True(t, ok) + content, ok := cand0["content"].(map[string]any) + require.True(t, ok) + parts, ok := content["parts"].([]any) + require.True(t, ok) + require.NotEmpty(t, parts) + firstPart, ok := parts[0].(map[string]any) + require.True(t, ok) + require.Equal(t, "It is sunny in Tokyo.", firstPart["text"]) +} diff --git a/backend/internal/service/antigravity_gateway_streaming.go b/backend/internal/service/antigravity_gateway_streaming.go index 7fa048c2e..184a02b8e 100644 --- a/backend/internal/service/antigravity_gateway_streaming.go +++ b/backend/internal/service/antigravity_gateway_streaming.go @@ -350,8 +350,7 @@ func (s *AntigravityGatewayService) handleGeminiStreamToNonStreaming(c *gin.Cont var firstTokenMs *int var last map[string]any var lastWithParts map[string]any - var collectedImageParts []map[string]any // 收集所有包含图片的 parts - var collectedTextParts []string // 收集所有文本片段 + var collectedParts []map[string]any // 收集所有 parts(text、thinking、functionCall、inlineData 等) type scanEvent struct { line string @@ -467,19 +466,10 @@ func (s *AntigravityGatewayService) handleGeminiStreamToNonStreaming(c *gin.Cont } } - // 保留最后一个有 parts 的响应 + // 保留最后一个有 parts 的响应,并收集所有 parts if parts := extractGeminiParts(parsed); len(parts) > 0 { lastWithParts = parsed - // 收集包含图片和文本的 parts - for _, part := range parts { - if inlineData, ok := part["inlineData"].(map[string]any); ok { - collectedImageParts = append(collectedImageParts, part) - _ = inlineData // 避免 unused 警告 - } - if text, ok := part["text"].(string); ok && text != "" { - collectedTextParts = append(collectedTextParts, text) - } - } + collectedParts = append(collectedParts, parts...) } case <-intervalCh: @@ -506,14 +496,9 @@ returnResponse: } } - // 如果收集到了图片 parts,需要合并到最终响应中 - if len(collectedImageParts) > 0 { - finalResponse = mergeImagePartsToResponse(finalResponse, collectedImageParts) - } - - // 如果收集到了文本,需要合并到最终响应中 - if len(collectedTextParts) > 0 { - finalResponse = mergeTextPartsToResponse(finalResponse, collectedTextParts) + // 将收集的所有 parts 合并到最终响应中 + if len(collectedParts) > 0 { + finalResponse = mergeCollectedPartsToResponse(finalResponse, collectedParts) } respBody, err := json.Marshal(finalResponse) @@ -576,21 +561,27 @@ func mergeCollectedPartsToResponse(response map[string]any, collectedParts []map return response } - result, _, setParts := getOrCreateGeminiParts(response) + result, existingParts, setParts := getOrCreateGeminiParts(response) // 合并策略: // 1. 保持原始顺序 - // 2. 连续的普通 text parts 合并为一个 + // 2. 连续的普通 text parts 合并为一个,并保留关联的 thoughtSignature // 3. thinking、functionCall、inlineData 等保持原样 var mergedParts []any var textBuffer strings.Builder + var textSignature string flushTextBuffer := func() { - if textBuffer.Len() > 0 { - mergedParts = append(mergedParts, map[string]any{ + if textBuffer.Len() > 0 || textSignature != "" { + part := map[string]any{ "text": textBuffer.String(), - }) + } + if textSignature != "" { + part["thoughtSignature"] = textSignature + } + mergedParts = append(mergedParts, part) textBuffer.Reset() + textSignature = "" } } @@ -605,6 +596,9 @@ func mergeCollectedPartsToResponse(response map[string]any, collectedParts []map } else { // 普通 text,累积到 buffer _, _ = textBuffer.WriteString(text) + if sig, ok := part["thoughtSignature"].(string); ok && sig != "" { + textSignature = sig + } } } else { // 非 text part(functionCall、inlineData 等),先刷新 text buffer,然后保留原样 @@ -616,73 +610,11 @@ func mergeCollectedPartsToResponse(response map[string]any, collectedParts []map // 刷新剩余的 text flushTextBuffer() - setParts(mergedParts) - return result -} - -// mergeImagePartsToResponse 将收集到的图片 parts 合并到 Gemini 响应中 -func mergeImagePartsToResponse(response map[string]any, imageParts []map[string]any) map[string]any { - if len(imageParts) == 0 { - return response + if len(mergedParts) == 0 { + mergedParts = existingParts } - result, existingParts, setParts := getOrCreateGeminiParts(response) - - // 检查现有 parts 中是否已经有图片 - for _, p := range existingParts { - if pm, ok := p.(map[string]any); ok { - if _, hasInline := pm["inlineData"]; hasInline { - return result // 已有图片,不重复添加 - } - } - } - - // 添加收集到的图片 parts - for _, imgPart := range imageParts { - existingParts = append(existingParts, imgPart) - } - setParts(existingParts) - return result -} - -// mergeTextPartsToResponse 将收集到的文本合并到 Gemini 响应中 -func mergeTextPartsToResponse(response map[string]any, textParts []string) map[string]any { - if len(textParts) == 0 { - return response - } - - mergedText := strings.Join(textParts, "") - result, existingParts, setParts := getOrCreateGeminiParts(response) - - // 查找并更新第一个 text part,或创建新的 - newParts := make([]any, 0, len(existingParts)+1) - textUpdated := false - - for _, p := range existingParts { - pm, ok := p.(map[string]any) - if !ok { - newParts = append(newParts, p) - continue - } - if _, hasText := pm["text"]; hasText && !textUpdated { - // 用累积的文本替换 - newPart := make(map[string]any) - for k, v := range pm { - newPart[k] = v - } - newPart["text"] = mergedText - newParts = append(newParts, newPart) - textUpdated = true - } else { - newParts = append(newParts, pm) - } - } - - if !textUpdated { - newParts = append([]any{map[string]any{"text": mergedText}}, newParts...) - } - - setParts(newParts) + setParts(mergedParts) return result } diff --git a/backend/internal/service/antigravity_gemini_thinking_variant.go b/backend/internal/service/antigravity_gemini_thinking_variant.go index cf9cfe091..23949aac6 100644 --- a/backend/internal/service/antigravity_gemini_thinking_variant.go +++ b/backend/internal/service/antigravity_gemini_thinking_variant.go @@ -108,17 +108,6 @@ func geminiThinkingLevelFromClaudeThinking(thinking *antigravity.ThinkingConfig) } } -// accountRawModelMappingHasKey 判断 key 是否由用户写在账号 credentials.model_mapping 里 -// (而不是 resolveModelMapping 运行时补进来的默认透传条目)。 -func accountRawModelMappingHasKey(account *Account, key string) bool { - if account == nil || account.Credentials == nil { - return false - } - raw, _ := account.Credentials["model_mapping"].(map[string]any) - _, ok := raw[key] - return ok -} - // resolveGeminiThinkingVariant 为裸 Gemini 模型名挑选账号映射表里存在的思考深度变体。 // 返回 (映射后的上游模型名, 是否命中)。未命中时调用方应回退到常规 getMappedModel 流程。 func resolveGeminiThinkingVariant(account *Account, requestedModel string, body []byte) (string, bool) { @@ -140,16 +129,16 @@ func resolveGeminiThinkingVariantForLevel(account *Account, requestedModel strin if len(mapping) == 0 { return "", false } - // 裸名本身已有"真正的"映射 → 尊重现有配置,不做推导。判定分两层: - // 1. 映射目标不是自己(如 gemini-3.8-flash → gemini-3.8-flash-tiered):用户明确指定了目标; - // 2. 映射目标是自己(原样透传):仅当这条是用户亲手写进 credentials.model_mapping 的才尊重。 - // resolveModelMapping 会给每个 Antigravity 账号自动补 gemini-3.x-flash 裸名自映射 - // (ensureAntigravityDefaultPassthroughs),而上游目录里并没有裸名模型,那条自映射 - // 正是导致 404 的来源,不能算作用户意图。 - if mapped, matched := resolveRequestedModelInMapping(mapping, model); matched { - if strings.TrimSpace(mapped) != model || accountRawModelMappingHasKey(account, model) { - return "", false - } + // 裸名本身若已映射到其他具体模型(如 gemini-3.8-flash → gemini-3.8-flash-tiered、 + // gemini-3.1-pro → gemini-pro-agent),尊重显式别名配置。 + // 若裸名映射目标是自己(如前端从 DefaultAntigravityModelMapping 拉取并持久化的 + // gemini-3.8-flash → gemini-3.8-flash,或 ensureAntigravityDefaultPassthroughs 注入的条目), + // 当映射表中存在该模型的精确思考变体(-high/-medium/-low/-tiered)时继续解析变体, + // 避免把上游不存在的裸名直接发出导致 404;而对已在映射表中的真实裸模型(如 gemini-2.5-flash), + // 仅查找精确变体键以避免被通配符误匹配。 + mapped, modelMatched := resolveRequestedModelInMapping(mapping, model) + if modelMatched && strings.TrimSpace(mapped) != model { + return "", false } if preferred == "" { @@ -163,8 +152,17 @@ func resolveGeminiThinkingVariantForLevel(account *Account, requestedModel strin } for _, level := range order { candidate := model + "-" + level - if mapped, matched := resolveRequestedModelInMapping(mapping, candidate); matched && strings.TrimSpace(mapped) != "" { - return mapped, true + var ( + variantMapped string + variantMatched bool + ) + if modelMatched { + variantMapped, variantMatched = mapping[candidate] + } else { + variantMapped, variantMatched = resolveRequestedModelInMapping(mapping, candidate) + } + if variantMatched && strings.TrimSpace(variantMapped) != "" { + return variantMapped, true } } return "", false diff --git a/backend/internal/service/antigravity_gemini_thinking_variant_test.go b/backend/internal/service/antigravity_gemini_thinking_variant_test.go index 4a115ac6e..8e96a1a8d 100644 --- a/backend/internal/service/antigravity_gemini_thinking_variant_test.go +++ b/backend/internal/service/antigravity_gemini_thinking_variant_test.go @@ -74,10 +74,10 @@ func TestResolveGeminiThinkingVariant(t *testing.T) { {"agy low (1000) -> -low", catalog, "gemini-3.8-flash", budget("1000"), "gemini-3.8-flash-low", true}, {"models/ prefix stripped", catalog, "models/gemini-3.8-flash", budget("1000"), "gemini-3.8-flash-low", true}, {"no thinkingConfig -> -high", catalog, "gemini-3.8-flash", []byte(`{"contents":[]}`), "gemini-3.8-flash-high", true}, - // gemini-3.6/3.7/3.8-flash 的四个变体会被 resolveModelMapping 自动补齐,所以降级用一个不在默认表里的型号 {"only -high exists: low request degrades to high", map[string]string{ "gemini-3.5-flash-high": "gemini-3.5-flash-high", }, "gemini-3.5-flash", budget("1000"), "gemini-3.5-flash-high", true}, + // gemini-3.6/3.7/3.8-flash 的四个变体会被 resolveModelMapping 自动补齐(存量显式映射账号的兼容透传)。 {"injected default variants are usable", catalog, "gemini-3.6-flash", budget("1000"), "gemini-3.6-flash-low", true}, {"already suffixed: untouched", catalog, "gemini-3.8-flash-low", budget("-1"), "", false}, {"bare name explicitly mapped: untouched", catalog, "gemini-2.5-flash", budget("-1"), "", false}, @@ -90,16 +90,22 @@ func TestResolveGeminiThinkingVariant(t *testing.T) { {"variant value is itself a mapping target", map[string]string{ "gemini-3.8-flash-high": "gemini-3.8-flash-tiered", }, "gemini-3.8-flash", budget("-1"), "gemini-3.8-flash-tiered", true}, - {"user-written bare identity passthrough: respected", map[string]string{ + // 前端持久化的默认目录含裸名自映射;-low 由默认透传补齐,按预算命中。 + {"persisted default bare identity passthrough still resolves when variants exist", map[string]string{ "gemini-3.8-flash": "gemini-3.8-flash", "gemini-3.8-flash-high": "gemini-3.8-flash-high", - }, "gemini-3.8-flash", budget("1000"), "", false}, - {"runtime-injected bare passthrough (not in credentials): still resolved", map[string]string{ - // resolveModelMapping 会补 gemini-3.7-flash → gemini-3.7-flash 的默认透传, - // 但 credentials 里没有这条,应当继续推导变体。 + }, "gemini-3.8-flash", budget("1000"), "gemini-3.8-flash-low", true}, + {"bare identity passthrough resolves a configured variant outside the default passthroughs", map[string]string{ + "gemini-3.5-flash": "gemini-3.5-flash", + "gemini-3.5-flash-high": "gemini-3.5-flash-high", + }, "gemini-3.5-flash", budget("1000"), "gemini-3.5-flash-high", true}, + {"wildcard mapping does not fabricate variants for non-tiered bare model", map[string]string{ + "gemini-2.5*": "gemini-2.5-flash", + }, "gemini-2.5-flash", budget("-1"), "", false}, + {"bare model absent from whitelist: configured variant still resolved", map[string]string{ "gemini-3.7-flash-medium": "gemini-3.7-flash-medium", }, "gemini-3.7-flash", budget("4000"), "gemini-3.7-flash-medium", true}, - // 空 credentials 映射 → 走 DefaultAntigravityModelMapping,其中同样只有带后缀的 3.8 flash + // 空 credentials 映射保留默认目录兼容行为。 {"empty mapping falls back to default catalog", map[string]string{}, "gemini-3.8-flash", budget("-1"), "gemini-3.8-flash-high", true}, } for _, tt := range tests { diff --git a/backend/internal/service/antigravity_rate_limit_test.go b/backend/internal/service/antigravity_rate_limit_test.go index c63ea9928..0e41871fa 100644 --- a/backend/internal/service/antigravity_rate_limit_test.go +++ b/backend/internal/service/antigravity_rate_limit_test.go @@ -844,6 +844,28 @@ func TestSetAntigravityModelRateLimits_GeminiWritesFamilyScope(t *testing.T) { require.Equal(t, antigravityGeminiModelRateLimitKey, repo.modelRateLimitCalls[1].modelKey) } +func TestSetAntigravityModelRateLimits_ImageDoesNotWriteFamilyScope(t *testing.T) { + repo := &stubAntigravityAccountRepo{} + svc := &AntigravityGatewayService{} + account := &Account{ID: 789, Platform: PlatformAntigravity} + resetAt := time.Now().Add(30 * time.Second) + + success := svc.setAntigravityModelRateLimits( + context.Background(), + repo, + account, + "gemini-3.1-flash-image-preview", + "[test]", + 429, + resetAt, + false, + ) + + require.True(t, success) + require.Len(t, repo.modelRateLimitCalls, 1) + require.Equal(t, "gemini-3.1-flash-image-preview", repo.modelRateLimitCalls[0].modelKey) +} + func TestSetAntigravityModelRateLimits_DoesNotDoubleMapCustomChain(t *testing.T) { repo := &stubAntigravityAccountRepo{} svc := &AntigravityGatewayService{} @@ -1071,6 +1093,15 @@ func TestResolveAntigravityForwardBaseURL(t *testing.T) { name: "ultra defaults to daily", account: &Account{Credentials: map[string]any{"plan_type": "ULTRA"}}, want: dailyURL, }, + { + name: "stored ultra tier id defaults to daily", account: &Account{Credentials: map[string]any{"plan_type": "g1-ultra-lite-tier"}}, + want: dailyURL, + }, + { + name: "stored pro tier id defaults to daily", account: &Account{Credentials: map[string]any{"plan_type": "g1-pro-tier"}}, + want: dailyURL, + }, + {name: "free tier id defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": "free-tier"}}, want: prodURL}, {name: "free defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": "free"}}, want: prodURL}, {name: "abnormal defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": "Abnormal"}}, want: prodURL}, {name: "unknown defaults to prod", account: &Account{Credentials: map[string]any{"plan_type": "enterprise"}}, want: prodURL}, diff --git a/backend/internal/service/api_key_service.go b/backend/internal/service/api_key_service.go index 61f79645f..200ec24de 100644 --- a/backend/internal/service/api_key_service.go +++ b/backend/internal/service/api_key_service.go @@ -130,6 +130,8 @@ type apiKeyAllByUserIDLister interface { // APIKeyRateLimitData holds rate limit usage and window state for an API key. type APIKeyRateLimitData struct { + // QuotaUsed 是总额度已用量(quota_used)。 + QuotaUsed float64 Usage5h float64 Usage1d float64 Usage7d float64 diff --git a/backend/internal/service/apicompat_config.go b/backend/internal/service/apicompat_config.go new file mode 100644 index 000000000..47e71ded3 --- /dev/null +++ b/backend/internal/service/apicompat_config.go @@ -0,0 +1,28 @@ +package service + +import ( + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/MACOS-DO/sub4api/internal/pkg/apicompat" +) + +func configuredMinOutputTokens(cfg *config.Config) int { + if cfg != nil && cfg.Gateway.MinOutputTokens >= 16 { + return cfg.Gateway.MinOutputTokens + } + return apicompat.DefaultMinMaxOutputTokens +} + +func chatCompletionsToResponses(cfg *config.Config, req *apicompat.ChatCompletionsRequest) (*apicompat.ResponsesRequest, error) { + return apicompat.ChatCompletionsToResponsesWithMinOutputTokens(req, configuredMinOutputTokens(cfg)) +} + +func anthropicToResponses(cfg *config.Config, req *apicompat.AnthropicRequest) (*apicompat.ResponsesRequest, error) { + return apicompat.AnthropicToResponsesWithMinOutputTokens(req, configuredMinOutputTokens(cfg)) +} + +func settingServiceConfig(settingService *SettingService) *config.Config { + if settingService == nil { + return nil + } + return settingService.cfg +} diff --git a/backend/internal/service/billing_cache_service.go b/backend/internal/service/billing_cache_service.go index bc261b481..228762b64 100644 --- a/backend/internal/service/billing_cache_service.go +++ b/backend/internal/service/billing_cache_service.go @@ -3,6 +3,7 @@ package service import ( "context" "fmt" + "math" "strconv" "sync" "sync/atomic" @@ -573,6 +574,11 @@ func (s *BillingCacheService) InvalidateAPIKeyRateLimit(ctx context.Context, key // resets expired windows in-memory and triggers async DB reset, // and returns an error if any window limit is exceeded. func (s *BillingCacheService) checkAPIKeyRateLimits(ctx context.Context, apiKey *APIKey) error { + return s.checkAPIKeyRateLimitsWithPending(ctx, apiKey, 0) +} + +// checkAPIKeyRateLimitsWithPending 在窗口用量上叠加 pending(即将扣除的金额)后检查限速窗口。 +func (s *BillingCacheService) checkAPIKeyRateLimitsWithPending(ctx context.Context, apiKey *APIKey, pending float64) error { if s.cache == nil { // No cache: fall back to reading from DB directly if s.apiKeyRateLimitLoader == nil { @@ -583,7 +589,7 @@ func (s *BillingCacheService) checkAPIKeyRateLimits(ctx context.Context, apiKey return nil // Don't block requests on DB errors } return s.evaluateRateLimits(ctx, apiKey, data.Usage5h, data.Usage1d, data.Usage7d, - data.Window5hStart, data.Window1dStart, data.Window7dStart) + data.Window5hStart, data.Window1dStart, data.Window7dStart, pending) } cacheData, err := s.cache.GetAPIKeyRateLimit(ctx, apiKey.ID) @@ -628,11 +634,11 @@ func (s *BillingCacheService) checkAPIKeyRateLimits(ctx context.Context, apiKey t := time.Unix(cacheData.Window7d, 0) w7d = &t } - return s.evaluateRateLimits(ctx, apiKey, cacheData.Usage5h, cacheData.Usage1d, cacheData.Usage7d, w5h, w1d, w7d) + return s.evaluateRateLimits(ctx, apiKey, cacheData.Usage5h, cacheData.Usage1d, cacheData.Usage7d, w5h, w1d, w7d, pending) } -// evaluateRateLimits checks usage against limits, triggering async resets for expired windows. -func (s *BillingCacheService) evaluateRateLimits(ctx context.Context, apiKey *APIKey, usage5h, usage1d, usage7d float64, w5h, w1d, w7d *time.Time) error { +// evaluateRateLimits checks usage (plus pending) against limits, triggering async resets for expired windows. +func (s *BillingCacheService) evaluateRateLimits(ctx context.Context, apiKey *APIKey, usage5h, usage1d, usage7d float64, w5h, w1d, w7d *time.Time, pending float64) error { needsReset := false // Reset expired windows in-memory for check purposes @@ -675,13 +681,16 @@ func (s *BillingCacheService) evaluateRateLimits(ctx context.Context, apiKey *AP } // Check limits - if apiKey.RateLimit5h > 0 && usage5h >= apiKey.RateLimit5h { + exceeds := func(usage, limit float64) bool { + return limit > 0 && (usage >= limit || usage+pending > limit) + } + if exceeds(usage5h, apiKey.RateLimit5h) { return ErrAPIKeyRateLimit5hExceeded } - if apiKey.RateLimit1d > 0 && usage1d >= apiKey.RateLimit1d { + if exceeds(usage1d, apiKey.RateLimit1d) { return ErrAPIKeyRateLimit1dExceeded } - if apiKey.RateLimit7d > 0 && usage7d >= apiKey.RateLimit7d { + if exceeds(usage7d, apiKey.RateLimit7d) { return ErrAPIKeyRateLimit7dExceeded } return nil @@ -781,6 +790,110 @@ func (s *BillingCacheService) CheckBillingEligibility(ctx context.Context, user return nil } +// ReserveFixedCharge 为扣费前即可确定金额的费用(倍率后 USD,如显式缓存存储费)做准入并登记在途预留。 +// +// 余额模式要求缓存余额覆盖 amount 及用户的其他在途预留;订阅模式要求日 / 周 / 月剩余额度覆盖 amount; +// API Key 总额度与限速窗口同样叠加 amount。订阅与 API Key 的用量取库中权威值,并叠加同一订阅 / Key 上其他 +// 在途预留:先登记本次预留再读用量,并发的两笔费用中后读用量的一方必然看到另一方(预留或已落库的扣费)。 +// 返回的句柄可能为 nil(未登记任何预留);调用方须在 handler 结束时调用 HandlerDone,预留在计费任务落库后释放。 +// 须在 CheckBillingEligibility 通过后调用;简易模式不校验。 +func (s *BillingCacheService) ReserveFixedCharge(ctx context.Context, user *User, apiKey *APIKey, group *Group, subscription *UserSubscription, amount float64) (*InflightReservation, error) { + if user == nil || amount <= 0 || math.IsNaN(amount) || math.IsInf(amount, 0) { + return nil, nil + } + if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple { + return nil, nil + } + subscriptionBill := group != nil && group.IsSubscriptionType() && subscription != nil + if !subscriptionBill { + balance, err := s.GetUserBalance(ctx, user.ID) + if err != nil { + return nil, ErrBillingServiceUnavailable.WithCause(err) + } + if balance < amount { + return nil, ErrInsufficientBalance + } + } + res, err := s.reserveInflight(ctx, user, group, subscription, amount, false, false) + if err != nil { + return nil, err + } + var subscriptionPending, apiKeyPending float64 + if subscriptionBill && (group.HasDailyLimit() || group.HasWeeklyLimit() || group.HasMonthlyLimit()) { + res, subscriptionPending = s.reserveInflightScope(ctx, res, user.ID, inflightSubscriptionScope(subscription.ID), amount) + } + if apiKey != nil && (apiKey.Quota > 0 || apiKey.HasRateLimits()) { + res, apiKeyPending = s.reserveInflightScope(ctx, res, user.ID, inflightAPIKeyScope(apiKey.ID), amount) + } + if subscriptionBill { + err = s.checkFixedChargeSubscription(ctx, user.ID, group, amount+subscriptionPending) + } + if err == nil && apiKey != nil { + err = s.checkFixedChargeAPIKey(ctx, apiKey, amount+apiKeyPending) + } + if err != nil { + res.Release() + return nil, err + } + return res, nil +} + +// checkFixedChargeSubscription 按库中订阅用量校验日 / 周 / 月剩余额度覆盖 pending。 +func (s *BillingCacheService) checkFixedChargeSubscription(ctx context.Context, userID int64, group *Group, pending float64) error { + read := s.GetSubscriptionStatus + if s.subRepo != nil { + read = s.getSubscriptionFromDB + } + subData, err := read(ctx, userID, group.ID) + if err != nil { + return ErrBillingServiceUnavailable.WithCause(err) + } + if group.HasDailyLimit() && subData.DailyUsage+pending > *group.DailyLimitUSD { + return ErrDailyLimitExceeded + } + if group.HasWeeklyLimit() && subData.WeeklyUsage+pending > *group.WeeklyLimitUSD { + return ErrWeeklyLimitExceeded + } + if group.HasMonthlyLimit() && subData.MonthlyUsage+pending > *group.MonthlyLimitUSD { + return ErrMonthlyLimitExceeded + } + return nil +} + +// checkFixedChargeAPIKey 按库中 Key 用量校验总额度与限速窗口覆盖 pending;未接入仓储时使用请求上下文与限速缓存中的用量。 +func (s *BillingCacheService) checkFixedChargeAPIKey(ctx context.Context, apiKey *APIKey, pending float64) error { + if apiKey.Quota <= 0 && !apiKey.HasRateLimits() { + return nil + } + if s.apiKeyRateLimitLoader == nil { + if apiKey.Quota > 0 && apiKey.QuotaUsed+pending > apiKey.Quota { + return ErrAPIKeyQuotaExhausted + } + if apiKey.HasRateLimits() { + return s.checkAPIKeyRateLimitsWithPending(ctx, apiKey, pending) + } + return nil + } + data, err := s.apiKeyRateLimitLoader.GetRateLimitData(ctx, apiKey.ID) + if err != nil { + return ErrBillingServiceUnavailable.WithCause(err) + } + exceeds := func(usage, limit float64) bool { + return limit > 0 && usage+pending > limit + } + switch { + case exceeds(data.QuotaUsed, apiKey.Quota): + return ErrAPIKeyQuotaExhausted + case exceeds(data.EffectiveUsage5h(), apiKey.RateLimit5h): + return ErrAPIKeyRateLimit5hExceeded + case exceeds(data.EffectiveUsage1d(), apiKey.RateLimit1d): + return ErrAPIKeyRateLimit1dExceeded + case exceeds(data.EffectiveUsage7d(), apiKey.RateLimit7d): + return ErrAPIKeyRateLimit7dExceeded + } + return nil +} + // checkSimpleModeAPIKeyRateLimits is deliberately DB-authoritative. Redis // updates are asynchronous and can be dropped or missed after a committed // transaction, so using the cache here could let a limited simple-mode key diff --git a/backend/internal/service/billing_inflight_reservation.go b/backend/internal/service/billing_inflight_reservation.go index a1924fe5e..d1129e878 100644 --- a/backend/internal/service/billing_inflight_reservation.go +++ b/backend/internal/service/billing_inflight_reservation.go @@ -3,6 +3,7 @@ package service import ( "context" "math" + "strconv" "strings" "sync" "sync/atomic" @@ -25,6 +26,16 @@ type InflightBalanceReservationCache interface { ReleaseInflightBalance(ctx context.Context, userID int64, requestID string) error } +// InflightScopeReservationCache 订阅 / API Key 维度在途预留的缓存能力(可选),用于扣费前即可确定金额的费用; +// 未实现时这两个维度不登记预留(fail-open),准入仍按库中用量校验。 +type InflightScopeReservationCache interface { + // ReserveInflightScope 原子地清理 scope 下的过期预留并登记 requestID 的预留(ttl 后自动失效), + // 返回登记前该 scope 下其他在途预留的合计。 + ReserveInflightScope(ctx context.Context, scope, requestID string, amount float64, ttl time.Duration) (float64, error) + // ReleaseInflightScope 释放 scope 下 requestID 的预留(幂等)。 + ReleaseInflightScope(ctx context.Context, scope, requestID string) error +} + // InflightBalanceReservationRenewer 可选:续期仍存活的预留(流式长请求期间防止 TTL 过期)。 type InflightBalanceReservationRenewer interface { // RenewInflightBalance 若 requestID 仍存在则把其过期时间推迟到 now+ttl;返回是否仍存在。 @@ -54,11 +65,15 @@ const ( // 不再续期,所以最长持有时间受 TTL 约束(计费任务卡死时预留自动过期)。 // 所有方法对 nil 接收者安全。 type InflightReservation struct { + // cache 为 nil 表示未登记余额维度的预留。 cache InflightBalanceReservationCache userID int64 requestID string amount float64 ttl time.Duration + // scopes 是同一金额在订阅 / API Key 维度登记的预留(与余额维度共用 requestID),不续期。 + scopeCache InflightScopeReservationCache + scopes []string refs atomic.Int64 releaseOnce sync.Once @@ -116,8 +131,15 @@ func (r *InflightReservation) Release() { r.refs.Store(0) relCtx, relCancel := context.WithTimeout(context.Background(), inflightReservationReleaseTimeout) defer relCancel() - if err := r.cache.ReleaseInflightBalance(relCtx, r.userID, r.requestID); err != nil { - logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation release failed for user %d (expires by ttl): %v", r.userID, err) + if r.cache != nil { + if err := r.cache.ReleaseInflightBalance(relCtx, r.userID, r.requestID); err != nil { + logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation release failed for user %d (expires by ttl): %v", r.userID, err) + } + } + for _, scope := range r.scopes { + if err := r.scopeCache.ReleaseInflightScope(relCtx, scope, r.requestID); err != nil { + logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation release failed for %s (expires by ttl): %v", scope, err) + } } }) } @@ -213,7 +235,7 @@ func (s *BillingCacheService) InflightReservationFailClosedOnUnpriced() bool { // ReserveInflightBalance 简化封装:返回释放函数,不续期、不做计费交接(预留最长存活 TTL)。 func (s *BillingCacheService) ReserveInflightBalance(ctx context.Context, user *User, group *Group, subscription *UserSubscription, estimate float64) (func(), error) { - r, err := s.reserveInflight(ctx, user, group, subscription, estimate, false) + r, err := s.reserveInflight(ctx, user, group, subscription, estimate, false, true) if err != nil { return noopRelease, err } @@ -232,10 +254,50 @@ func (s *BillingCacheService) ReserveInflightBalance(ctx context.Context, user * // 开关关闭 / 简易模式 / 订阅模式 / estimate <= 0 / 缓存不支持 / 余额读取失败 / Redis 执行失败。 // 仅当 Redis 明确判定 缓存余额 - 在途合计 < estimate(且已有在途请求)时返回 ErrInsufficientBalance。 func (s *BillingCacheService) ReserveInflight(ctx context.Context, user *User, group *Group, subscription *UserSubscription, estimate float64) (*InflightReservation, error) { - return s.reserveInflight(ctx, user, group, subscription, estimate, true) + return s.reserveInflight(ctx, user, group, subscription, estimate, true, true) +} + +// inflightSubscriptionScope / inflightAPIKeyScope 是订阅 / API Key 维度在途预留的 scope 名。 +func inflightSubscriptionScope(subscriptionID int64) string { + return "sub:" + strconv.FormatInt(subscriptionID, 10) +} + +func inflightAPIKeyScope(apiKeyID int64) string { + return "apikey:" + strconv.FormatInt(apiKeyID, 10) +} + +// reserveInflightScope 在 scope 维度为 amount 登记在途预留并挂到 res 上(res 为 nil 时新建句柄), +// 返回句柄与登记前该 scope 下其他在途预留的合计。开关关闭 / 缓存不支持 / Redis 执行失败时不登记(fail-open),合计按 0。 +func (s *BillingCacheService) reserveInflightScope(ctx context.Context, res *InflightReservation, userID int64, scope string, amount float64) (*InflightReservation, float64) { + cfg, ok := s.inflightReservationConfig() + if !ok { + return res, 0 + } + sc, ok := s.cache.(InflightScopeReservationCache) + if !ok || sc == nil { + return res, 0 + } + if res == nil { + ttl := defaultInflightReservationTTL + if cfg.TTLSeconds > 0 { + ttl = time.Duration(cfg.TTLSeconds) * time.Second + } + res = &InflightReservation{userID: userID, requestID: uuid.NewString(), amount: amount, ttl: ttl} + res.refs.Store(1) + } + reserveCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), inflightReservationReserveTimeout) + pending, err := sc.ReserveInflightScope(reserveCtx, scope, res.requestID, amount, res.ttl) + cancel() + if err != nil { + logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation failed for %s (fail-open): %v", scope, err) + return res, 0 + } + res.scopeCache = sc + res.scopes = append(res.scopes, scope) + return res, pending } -func (s *BillingCacheService) reserveInflight(ctx context.Context, user *User, group *Group, subscription *UserSubscription, estimate float64, renew bool) (*InflightReservation, error) { +func (s *BillingCacheService) reserveInflight(ctx context.Context, user *User, group *Group, subscription *UserSubscription, estimate float64, renew, capped bool) (*InflightReservation, error) { cfg, ok := s.inflightReservationConfig() if !ok || user == nil { return nil, nil @@ -243,7 +305,7 @@ func (s *BillingCacheService) reserveInflight(ctx context.Context, user *User, g if group != nil && group.IsSubscriptionType() && subscription != nil { return nil, nil } - if cfg.MaxReservationUSD > 0 && estimate > cfg.MaxReservationUSD { + if capped && cfg.MaxReservationUSD > 0 && estimate > cfg.MaxReservationUSD { estimate = cfg.MaxReservationUSD } if estimate <= 0 || math.IsNaN(estimate) || math.IsInf(estimate, 0) { diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go index 13b0b33f6..2aabe21d1 100644 --- a/backend/internal/service/billing_service.go +++ b/backend/internal/service/billing_service.go @@ -444,6 +444,20 @@ func (s *BillingService) initFallbackPricing() { CacheCreation1hPrice: 4e-6, SupportsCacheBreakdown: true, } + // Claude Haiku 5.5(2026-10-07,$0.10/$0.50,prompt 超 100k tokens 整单 5x)。 + // 长文本阶梯与目录 *_above_100k_tokens 绝对价同口径,缺目录时回退也不丢阶梯。 + s.fallbackPrices["claude-haiku-5-5"] = &ModelPricing{ + InputPricePerToken: 0.1e-6, + OutputPricePerToken: 0.5e-6, + CacheCreationPricePerToken: 0.125e-6, + CacheReadPricePerToken: 0.01e-6, + CacheCreation5mPrice: 0.125e-6, + CacheCreation1hPrice: 0.2e-6, + SupportsCacheBreakdown: true, + LongContextInputThreshold: 100000, + LongContextInputMultiplier: 5, + LongContextOutputMultiplier: 5, + } // Claude Fable 5.x uses the same input/output and cache-write prices, while // Fable 5.1 reduces cache reads from $1 to $0.25 per MTok. s.fallbackPrices["claude-fable-5"] = &ModelPricing{ @@ -474,14 +488,15 @@ func (s *BillingService) initFallbackPricing() { SupportsCacheBreakdown: false, } - // Gemini 3.6 Flash (Google AI pricing: $1.50 input / $7.50 output / - // $0.15 cached input per MTok). Antigravity's -high/-low/-medium/-tiered - // aliases are matched below so unavailable remote pricing never records - // token-bearing requests at $0. + // Gemini 3.6 Flash (Google AI pricing: $0.75 input / $3.75 output / + // $0.075 cached input per MTok, promotional through 2026-12-31; official + // rates double to $1.50/$7.50/$0.15 from 2027-01-01). Antigravity's + // -high/-low/-medium/-tiered aliases are matched below so unavailable + // remote pricing never records token-bearing requests at $0. s.fallbackPrices["gemini-3.6-flash"] = &ModelPricing{ - InputPricePerToken: 1.5e-6, - OutputPricePerToken: 7.5e-6, - CacheReadPricePerToken: 0.15e-6, + InputPricePerToken: 0.75e-6, + OutputPricePerToken: 3.75e-6, + CacheReadPricePerToken: 0.075e-6, SupportsCacheBreakdown: false, } @@ -509,6 +524,27 @@ func (s *BillingService) initFallbackPricing() { SupportsCacheBreakdown: false, } + // Gemini 4 Argon (Google AI pricing: $2 input / $10 output / $0.10 cached + // input per MTok, promotional through 2026-11-30; official rates double to + // $4/$20/$0.20 from 2026-12-01). One rate covers every prompt length. + // Antigravity's -high/-low/-medium aliases are matched below so unavailable + // remote pricing never records token-bearing requests at $0. + s.fallbackPrices["gemini-4-argon"] = &ModelPricing{ + InputPricePerToken: 2e-6, + OutputPricePerToken: 10e-6, + CacheReadPricePerToken: 0.1e-6, + SupportsCacheBreakdown: false, + } + + // Gemini 4 Argon Cyber Permissive (Vertex AI pricing: $4 input / $20 output / + // $0.20 cached input per MTok). The Gemini 4 Argon promotion does not apply. + s.fallbackPrices["gemini-4-argon-cyber-permissive"] = &ModelPricing{ + InputPricePerToken: 4e-6, + OutputPricePerToken: 20e-6, + CacheReadPricePerToken: 0.2e-6, + SupportsCacheBreakdown: false, + } + // OpenAI GPT-5.4(业务指定价格) s.fallbackPrices["gpt-5.4"] = &ModelPricing{ InputPricePerToken: 2.5e-6, // $2.5 per MTok @@ -999,7 +1035,7 @@ func (s *BillingService) initFallbackPricing() { // getFallbackPricing 根据模型系列获取回退价格 func (s *BillingService) getFallbackPricing(model string) *ModelPricing { - modelLower := strings.ToLower(model) + modelLower := normalizeAntigravityClaudeTierAlias(strings.ToLower(model)) if modelLower == "jev-latest" { return s.fallbackPrices["jev-latest"] } @@ -1017,6 +1053,9 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing { if claude.IsSonnet55(modelLower) { return s.fallbackPrices["claude-sonnet-5-5"] } + if claude.IsHaiku55(modelLower) { + return s.fallbackPrices["claude-haiku-5-5"] + } if strings.Contains(modelLower, "opus") { // "opus-5" 必须先判:不能用裸 "5" 匹配,否则 claude-opus-4-5 会被误判。 if strings.Contains(modelLower, "opus-5") || strings.Contains(modelLower, "opus5") { @@ -1064,6 +1103,13 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing { if strings.Contains(modelLower, "gemini-3.8-flash") || strings.Contains(modelLower, "gemini-3-8-flash") { return s.fallbackPrices["gemini-3.8-flash"] } + // Cyber 变体不享受 Gemini 4 Argon 的优惠价,必须先于 "gemini-4-argon" 判。 + if strings.Contains(modelLower, "gemini-4-argon-cyber") { + return s.fallbackPrices["gemini-4-argon-cyber-permissive"] + } + if strings.Contains(modelLower, "gemini-4-argon") { + return s.fallbackPrices["gemini-4-argon"] + } // DeepSeek 系列:官方模型 V4 Pro/Flash(含 vision-exp)按各自价卡; // 其余 deepseek-*(含已停服的 deepseek-chat / deepseek-reasoner 与未知型号) @@ -1325,6 +1371,18 @@ func (s *BillingService) GetModelPricing(model string) (*ModelPricing, error) { return s.getModelPricingAt(model, timezone.Now()) } +// CacheStoragePricePerTokenHour 返回模型的显式上下文缓存存储单价(每 token 每小时,USD)。 +// 优先级:价格表(override_file 等)按确定性识别配置的值 > 内置型号价 > 内置 Pro/Flash 系列兜底价; +// 均未命中返回 0。 +func (s *BillingService) CacheStoragePricePerTokenHour(model string) float64 { + if s != nil && s.pricingService != nil { + if pricing := s.pricingService.GetIdentifiedModelPricing(model); pricing != nil && pricing.CacheStorageCostPerTokenPerHour > 0 { + return pricing.CacheStorageCostPerTokenPerHour + } + } + return builtinGeminiCacheStoragePrice(model) +} + // getModelPricingAt 是 GetModelPricing 的带计费时点内部变体:pricingAt 显式 // 驱动 DeepSeek pro→Flash 切换判定(切换点前 Pro 价、之后 Flash 价),使 // 展示/估算路径可与历史补账同刻复算,测试也能用固定时点钉住断言。 @@ -1476,6 +1534,8 @@ type CostInput struct { Resolver *ModelPricingResolver // 定价解析器 Resolved *ResolvedPricing // 可选:预解析的定价结果(避免重复 Resolve 调用) LongContextBillingEnabled *bool + // DisableModelLongContextPricing 豁免模型价卡的长上下文附加费,不改变自定义区间价格。 + DisableModelLongContextPricing bool } // CalculateCostUnified 统一计费入口,支持三种计费模式。 @@ -1491,7 +1551,7 @@ func (s *BillingService) CalculateCostUnified(input CostInput) (*CostBreakdown, if err != nil { return nil, err } - breakdown := s.computeTokenBreakdown(pricing, input.Tokens, input.RateMultiplier, input.ServiceTier, applyLongContextBilling) + breakdown := s.computeTokenBreakdown(pricing, input.Tokens, input.RateMultiplier, input.ServiceTier, applyLongContextBilling && !input.DisableModelLongContextPricing) applyCostBreakdownMultiplier(breakdown, reasoningEffortBillingMultiplier(input.ReasoningEffort, pricing.ReasoningEffortMultipliers)) return breakdown, nil } @@ -1578,7 +1638,7 @@ func (s *BillingService) calculateTokenCost(resolved *ResolvedPricing, input Cos } // 官方长上下文阶梯仅在无区间定价时应用(区间定价已包含上下文分层)。 - applyLongCtx := len(resolved.Intervals) == 0 && contextTierPricingEnabled + applyLongCtx := len(resolved.Intervals) == 0 && contextTierPricingEnabled && !input.DisableModelLongContextPricing breakdown := s.computeTokenBreakdown(pricing, input.Tokens, input.RateMultiplier, input.ServiceTier, applyLongCtx) applyCostBreakdownMultiplier(breakdown, resolvedChannelTimeMultiplier(resolved, input.PricingAt)) diff --git a/backend/internal/service/billing_service_test.go b/backend/internal/service/billing_service_test.go index 4d180337c..6cf50e711 100644 --- a/backend/internal/service/billing_service_test.go +++ b/backend/internal/service/billing_service_test.go @@ -2055,6 +2055,33 @@ func TestNewModelPricingCatalogFallbackAndContext(t *testing.T) { require.False(t, cost.LongContextBillingApplied) }) } + // claude-haiku-5-5:prompt 超 100k tokens 整单 5x(官方定价), + // billing/catalog/fallback 三源口径一致(issue #7919)。 + for _, model := range []string{ + "claude-haiku-5-5", + "anthropic/claude-haiku-5.5", + } { + t.Run(source+"/"+model, func(t *testing.T) { + for _, n := range []int{99999, 100000, 100001} { + tokens := UsageTokens{ + InputTokens: n - 3000, OutputTokens: 500, + CacheReadTokens: 2000, CacheCreationTokens: 1000, + } + cost, err := svc.CalculateCost(model, tokens, 1) + require.NoError(t, err) + im, om := 1.0, 1.0 + if n > 100000 { + im, om = 5.0, 5.0 + } + require.InDelta(t, float64(tokens.InputTokens)*1e-7*im, cost.InputCost, 1e-10) + require.InDelta(t, 1000*1.25e-7*im, cost.CacheCreationCost, 1e-10) + require.InDelta(t, 2000*1e-8*im, cost.CacheReadCost, 1e-10) + require.InDelta(t, 500*5e-7*om, cost.OutputCost, 1e-10) + require.InDelta(t, cost.InputCost+cost.OutputCost+cost.CacheCreationCost+cost.CacheReadCost, cost.TotalCost, 1e-10) + require.Equal(t, n > 100000, cost.LongContextBillingApplied) + } + }) + } } } diff --git a/backend/internal/service/channel_available.go b/backend/internal/service/channel_available.go index 262a38482..3a6c5aba2 100644 --- a/backend/internal/service/channel_available.go +++ b/backend/internal/service/channel_available.go @@ -16,6 +16,7 @@ import ( type AvailableGroupRef struct { ID int64 Name string + I18n GroupI18n Platform string SubscriptionType string RateMultiplier float64 @@ -66,6 +67,7 @@ func (s *ChannelService) ListAvailable(ctx context.Context) ([]AvailableChannel, groupByID[g.ID] = AvailableGroupRef{ ID: g.ID, Name: g.Name, + I18n: g.I18n, Platform: g.Platform, SubscriptionType: g.SubscriptionType, RateMultiplier: g.RateMultiplier, diff --git a/backend/internal/service/channel_monitor_checker.go b/backend/internal/service/channel_monitor_checker.go index d8d29e895..a91ac50a4 100644 --- a/backend/internal/service/channel_monitor_checker.go +++ b/backend/internal/service/channel_monitor_checker.go @@ -642,6 +642,8 @@ var monitorAPIKeyPatterns = []struct { {regexp.MustCompile(`xai-[A-Za-z0-9_-]{6,}`), "xai-***REDACTED***"}, // Gemini / Google API Key:固定前缀 + 35 位 {regexp.MustCompile(`AIza[A-Za-z0-9_-]{35}`), "AIza***REDACTED***"}, + // Gemini auth key:AQ.Ab 前缀 + 48 位,长度放宽以覆盖格式变体 + {regexp.MustCompile(`AQ\.Ab[A-Za-z0-9_-]{40,}`), "AQ.***REDACTED***"}, // JWT 三段式(Bearer 后常出现):eyJxxx.eyJxxx.signature {regexp.MustCompile(`eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}`), "eyJ***REDACTED.JWT***"}, } @@ -649,7 +651,7 @@ var monitorAPIKeyPatterns = []struct { // sanitizeErrorMessage 擦除错误/响应文本中可能泄露的 API key。 // 处理两类来源: // 1. URL query 中的 ?key= / ?api_key= 等(Go *url.Error 会回填完整 URL) -// 2. 上游 HTTP body 文本里直接出现的 sk-* / xai-* / AIza* / JWT 等密钥碎片 +// 2. 上游 HTTP body 文本里直接出现的 sk-* / xai-* / AIza* / AQ.* / JWT 等密钥碎片 // // 注意:与 gemini_messages_compat_service.go 的 sanitizeUpstreamErrorMessage 关注点类似但参数集更广, // 监控模块独立维护,避免互相耦合。 diff --git a/backend/internal/service/channel_monitor_checker_body_test.go b/backend/internal/service/channel_monitor_checker_body_test.go index 922eb8673..5c347cae8 100644 --- a/backend/internal/service/channel_monitor_checker_body_test.go +++ b/backend/internal/service/channel_monitor_checker_body_test.go @@ -279,6 +279,17 @@ func TestRunCheckForModel_Grok_RedactsXAIKeyFromUpstreamBody(t *testing.T) { } } +func TestSanitizeErrorMessage_RedactsGeminiAuthKey(t *testing.T) { + authKey := "AQ." + "Ab" + strings.Repeat("Xy9_-z", 8) + got := sanitizeErrorMessage(`{"error":{"message":"API key not valid: ` + authKey + `"}}`) + if strings.Contains(got, authKey) { + t.Fatalf("Gemini auth key leaked: %q", got) + } + if !strings.Contains(got, "AQ.***REDACTED***") { + t.Fatalf("expected redaction marker, got %q", got) + } +} + func TestRunCheckForModel_OpenAIResponses_DefaultRequest(t *testing.T) { h := &openAICaptureHandler{} endpoint := setupFakeOpenAI(t, h) diff --git a/backend/internal/service/cn_provider_probe_url_test.go b/backend/internal/service/cn_provider_probe_url_test.go index 19f2e747a..255499e88 100644 --- a/backend/internal/service/cn_provider_probe_url_test.go +++ b/backend/internal/service/cn_provider_probe_url_test.go @@ -6,7 +6,9 @@ package service import ( "context" + "io" "net/http" + "strings" "testing" "github.com/MACOS-DO/sub4api/internal/config" @@ -72,15 +74,13 @@ func (r *fakeCNProbeAccountRepo) GetByID(ctx context.Context, id int64) (*Accoun return r.account, nil } -// kimi coding 账号的 base_url 指向中转(含 api.kimi.com/coding 路径段即可被识别 -// 为 kimi coding plan)→ 衍生额度端点落在中转主机上,白名单未列名必须拒绝。 func TestCNProviderQuotaService_RejectsURLBlockedByPolicy(t *testing.T) { repo := &fakeCNProbeAccountRepo{account: &Account{ ID: 1, Platform: PlatformKimi, Type: AccountTypeAPIKey, Status: StatusActive, Credentials: map[string]any{ "account_mode": "coding", "api_key": "sk-test", - "base_url": "https://relay.attacker.example/api.kimi.com/coding", + "base_url": "https://api.kimi.ai/coding/v1", }, }} upstream := &recordingHTTPUpstream{} @@ -92,6 +92,79 @@ func TestCNProviderQuotaService_RejectsURLBlockedByPolicy(t *testing.T) { require.Zero(t, upstream.calls, "probe must not issue any upstream request when URL policy rejects the target") } +func TestCNProviderQuotaService_RejectsSpoofedKimiURL(t *testing.T) { + repo := &fakeCNProbeAccountRepo{account: &Account{ + ID: 1, Platform: PlatformKimi, Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "account_mode": AccountModeCoding, + "api_key": "test-only-placeholder", + "base_url": "https://relay.attacker.example/api.kimi.com/coding", + }, + }} + upstream := &recordingHTTPUpstream{} + svc := NewCNProviderQuotaService(repo, nil, upstream, nil) + _, err := svc.QueryUsage(context.Background(), 1) + require.ErrorContains(t, err, "CN_QUOTA_NOT_CODING_PLAN") + require.Zero(t, upstream.calls) +} + +type kimiQuotaTestRepo struct { + fakeCNProbeAccountRepo + updates map[string]any +} + +func (r *kimiQuotaTestRepo) UpdateExtra(ctx context.Context, id int64, updates map[string]any) error { + r.updates = updates + return nil +} + +type kimiQuotaTestUpstream struct { + recordingHTTPUpstream + request *http.Request +} + +func (u *kimiQuotaTestUpstream) Do(req *http.Request, proxyURL string, accountID int64, accountConcurrency int) (*http.Response, error) { + u.calls++ + u.request = req + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(`{"limits":[{"detail":{"limit":100,"remaining":75}}],"usage":{"limit":1000,"remaining":800}}`)), + }, nil +} + +func TestCNProviderQuotaService_KimiOfficialHosts(t *testing.T) { + for _, host := range []string{"api.kimi.com", "api.kimi.ai"} { + for _, path := range []string{"/coding", "/coding/", "/coding/v1", "/coding/v1/"} { + t.Run(host+path, func(t *testing.T) { + repo := &kimiQuotaTestRepo{fakeCNProbeAccountRepo: fakeCNProbeAccountRepo{account: &Account{ + ID: 1, Platform: PlatformKimi, Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "account_mode": AccountModeCoding, + "api_key": "test-only-placeholder", + "base_url": "https://" + host + path, + }, + }}} + upstream := &kimiQuotaTestUpstream{} + svc := NewCNProviderQuotaService(repo, nil, upstream, cnProbeAllowlistConfig(host)) + result, err := svc.QueryUsage(context.Background(), 1) + require.NoError(t, err) + require.True(t, result.Success) + require.True(t, result.CredentialValid) + require.True(t, result.Persisted) + require.Equal(t, PlatformKimi, result.Provider) + require.Len(t, result.Tiers, 2) + require.Equal(t, float64(25), result.Tiers[0].UsedPercent) + require.Equal(t, float64(20), result.Tiers[1].UsedPercent) + require.Equal(t, float64(25), repo.updates["kimi_5h_used_percent"]) + require.Equal(t, 1, upstream.calls) + require.Equal(t, http.MethodGet, upstream.request.Method) + require.Equal(t, "https://"+host+"/coding/v1/usages", upstream.request.URL.String()) + require.Equal(t, "Bearer test-only-placeholder", upstream.request.Header.Get("Authorization")) + }) + } + } +} + // deepseek payg 账号自定义 base_url → 余额端点落在中转主机上,必须先过策略。 func TestCNProviderBalanceService_RejectsURLBlockedByPolicy(t *testing.T) { repo := &fakeCNProbeAccountRepo{account: &Account{ diff --git a/backend/internal/service/cn_provider_quota_service.go b/backend/internal/service/cn_provider_quota_service.go index 39acdadde..3410e0931 100644 --- a/backend/internal/service/cn_provider_quota_service.go +++ b/backend/internal/service/cn_provider_quota_service.go @@ -497,7 +497,7 @@ func minimaxResetTime(v gjson.Result) string { return time.UnixMilli(ms).UTC().Format(time.RFC3339) } -// cnZhipuWindow 标识智谱 TOKENS_LIMIT 条目所属窗口。 +// cnZhipuWindow 标识智谱额度条目(TOKENS_LIMIT / CREDIT_LIMIT)所属窗口。 type cnZhipuWindow int const ( @@ -529,7 +529,8 @@ func classifyZhipuWindowUnit(unit int64) cnZhipuWindow { // // CREDIT_LIMIT(信用额度)与 TOKENS_LIMIT(token 窗口)度量不同:两者同时返回时 // 只让 TOKENS_LIMIT 参与 5h/weekly 槽位竞争,避免信用额度百分比污染阈值停调 -// 快照;仅当无任何 TOKENS_LIMIT 条目时才降级用 CREDIT_LIMIT 展示。 +// 快照;仅当无任何 TOKENS_LIMIT 条目时才降级用 CREDIT_LIMIT 展示 —— 此时 +// CREDIT_LIMIT 同样按 unit 分类(它也携带 unit),不依赖 reset 时间排序。 // 老套餐只回 1 条 TOKENS_LIMIT,自然降级为仅 5h;新套餐回 2 条。 func parseZhipuTokenTiers(data gjson.Result) []CNQuotaTier { type entry struct { @@ -537,6 +538,7 @@ func parseZhipuTokenTiers(data gjson.Result) []CNQuotaTier { hasReset bool percentage float64 resetISO string + unit int64 } var ( fiveHour entry @@ -546,8 +548,8 @@ func parseZhipuTokenTiers(data gjson.Result) []CNQuotaTier { unclassified []entry ) - classify := func(item gjson.Result, e entry) { - switch classifyZhipuWindowUnit(item.Get("unit").Int()) { + classify := func(unit int64, e entry) { + switch classifyZhipuWindowUnit(unit) { case cnZhipuWindow5h: if !fiveHourSet { fiveHour, fiveHourSet = e, true @@ -592,10 +594,10 @@ func parseZhipuTokenTiers(data gjson.Result) []CNQuotaTier { hasReset = resetISO != "" } } - e := entry{resetMs: resetMs, hasReset: hasReset, percentage: percentage, resetISO: resetISO} + e := entry{resetMs: resetMs, hasReset: hasReset, percentage: percentage, resetISO: resetISO, unit: item.Get("unit").Int()} if limitType == "TOKENS_LIMIT" { hasTokensLimit = true - classify(item, e) + classify(e.unit, e) } else { creditFallback = append(creditFallback, e) } @@ -603,8 +605,17 @@ func parseZhipuTokenTiers(data gjson.Result) []CNQuotaTier { }) // 无任何 TOKENS_LIMIT 条目(部分套餐只报信用额度):降级用 CREDIT_LIMIT 展示。 + // CREDIT_LIMIT 条目同样带 unit(3=5h / 6=weekly;实测 GLM Coding Plan 两条窗口 + // 都是 CREDIT_LIMIT),必须和 TOKENS_LIMIT 一样先按 unit 显式分类 —— 否则会退化 + // 成 reset 时间启发式,而周期末尾周窗口比 5h 更早重置,时间排序必然把两档标反。 if !hasTokensLimit { - unclassified = append(unclassified, creditFallback...) + for _, e := range creditFallback { + if classifyZhipuWindowUnit(e.unit) != cnZhipuWindowUnknown { + classify(e.unit, e) + continue + } + unclassified = append(unclassified, e) + } } // 无 reset 的条目排前,再按 reset 升序,依次填入仍空缺的槽位。 diff --git a/backend/internal/service/cn_providers_test.go b/backend/internal/service/cn_providers_test.go index b623c1eeb..74bb93c3a 100644 --- a/backend/internal/service/cn_providers_test.go +++ b/backend/internal/service/cn_providers_test.go @@ -126,6 +126,60 @@ func TestParseZhipuTokenTiers_UnitClassification(t *testing.T) { require.InDelta(t, 70.0, tiers[1].UsedPercent, 1e-9) } +// TestParseZhipuTokenTiers_CreditLimitUnitClassification GLM Coding Plan 当前把 5h / weekly +// 两条窗口都标成 CREDIT_LIMIT(实测 level=lite)。CREDIT_LIMIT 同样携带 unit, +// 必须和 TOKENS_LIMIT 一样按 unit 显式分类,否则会退化成 reset 时间排序 —— +// 此处刻意让 weekly 的 nextResetTime 早于 5h(周期末尾),两档会被标反。 +func TestParseZhipuTokenTiers_CreditLimitUnitClassification(t *testing.T) { + t.Parallel() + data := gjson.Parse(`{ + "limits": [ + {"type":"CREDIT_LIMIT","unit":3,"number":5,"percentage":14,"nextResetTime":1700000099999}, + {"type":"CREDIT_LIMIT","unit":6,"number":1,"percentage":90,"nextResetTime":1700000000000} + ] + }`) + tiers := parseZhipuTokenTiers(data) + require.Len(t, tiers, 2) + require.Equal(t, "5h", tiers[0].Window) + require.InDelta(t, 14.0, tiers[0].UsedPercent, 1e-9) + require.Equal(t, "weekly", tiers[1].Window) + require.InDelta(t, 90.0, tiers[1].UsedPercent, 1e-9) +} + +// TestParseZhipuTokenTiers_CreditLimitWithoutUnitFallback CREDIT_LIMIT 缺 unit 时, +// 保留原有 fallback:无 nextResetTime 的优先归 5h,其余按 reset 升序填入剩余槽位。 +func TestParseZhipuTokenTiers_CreditLimitWithoutUnitFallback(t *testing.T) { + t.Parallel() + data := gjson.Parse(`{ + "limits": [ + {"type":"CREDIT_LIMIT","percentage":30,"nextResetTime":1700000000000}, + {"type":"CREDIT_LIMIT","percentage":80} + ] + }`) + tiers := parseZhipuTokenTiers(data) + require.Len(t, tiers, 2) + require.Equal(t, "5h", tiers[0].Window) + require.InDelta(t, 80.0, tiers[0].UsedPercent, 1e-9) + require.Equal(t, "weekly", tiers[1].Window) + require.InDelta(t, 30.0, tiers[1].UsedPercent, 1e-9) +} + +// TestParseZhipuTokenTiers_TokensLimitWinsOverCreditLimit 两种 type 同时返回时, +// TOKENS_LIMIT 仍然优先占槽、CREDIT_LIMIT 不参与(原有语义保持不变)。 +func TestParseZhipuTokenTiers_TokensLimitWinsOverCreditLimit(t *testing.T) { + t.Parallel() + data := gjson.Parse(`{ + "limits": [ + {"type":"TOKENS_LIMIT","unit":3,"percentage":20,"nextResetTime":1700000000000}, + {"type":"CREDIT_LIMIT","unit":6,"percentage":99,"nextResetTime":1700000099999} + ] + }`) + tiers := parseZhipuTokenTiers(data) + require.Len(t, tiers, 1) + require.Equal(t, "5h", tiers[0].Window) + require.InDelta(t, 20.0, tiers[0].UsedPercent, 1e-9) +} + // TestParseZhipuTokenTiers_SingleTierOldPlan 老套餐仅回 1 条 → 降级为仅 5h。 func TestParseZhipuTokenTiers_SingleTierOldPlan(t *testing.T) { t.Parallel() diff --git a/backend/internal/service/composite_model_route.go b/backend/internal/service/composite_model_route.go index df23d1d0a..7784891d1 100644 --- a/backend/internal/service/composite_model_route.go +++ b/backend/internal/service/composite_model_route.go @@ -32,6 +32,11 @@ type CompositeModelOwnership struct { TargetPlatform string Matched bool Ambiguous bool + // OpenAIGatewayOAuthClaimed 表示声明方中含 OpenAI 网关族平台的 OAuth / + // setup-token 凭据。歧义请求无法解析平台,会落到默认的 Anthropic 网关 + // handler:Anthropic / Gemini / Antigravity 的 OAuth 在那里有原生或兼容 + // 转发,API Key 上游可能兼容多种格式,唯独这类凭据只能走 OpenAI 网关。 + OpenAIGatewayOAuthClaimed bool } type CompositeModelOwnershipResolver func(context.Context, int64, string) (CompositeModelOwnership, error) diff --git a/backend/internal/service/composite_platform_test.go b/backend/internal/service/composite_platform_test.go index 8ac9e95f0..943d63847 100644 --- a/backend/internal/service/composite_platform_test.go +++ b/backend/internal/service/composite_platform_test.go @@ -13,7 +13,7 @@ type compositeOwnershipAccountRepo struct { accounts []Account } -func (r *compositeOwnershipAccountRepo) ListSchedulableByGroupID(context.Context, int64) ([]Account, error) { +func (r *compositeOwnershipAccountRepo) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]Account, error) { return r.accounts, nil } @@ -103,6 +103,55 @@ func TestResolveCompositeModelOwnershipAllowsSamePlatformAndRejectsCrossPlatform require.Equal(t, CompositeModelOwnership{Ambiguous: true}, ambiguous) } +// Scenario: 只有 OpenAI 网关族的 OAuth 声明方会被标记(API Key 上游可能兼容多协议, +// Anthropic / Antigravity 的 OAuth 在默认 Anthropic handler 中可正常转发) +func TestResolveCompositeModelOwnershipFlagsOpenAIGatewayOAuthClaimants(t *testing.T) { + groupID := int64(7) + repo := &compositeOwnershipAccountRepo{ + accounts: []Account{ + {ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"model_mapping": map[string]any{"gpt-6-astra": "gpt-6-astra"}}}, + {ID: 2, Platform: PlatformDeepseek, Type: AccountTypeAPIKey, Credentials: map[string]any{"model_mapping": map[string]any{"gpt-6-astra": "deepseek-v4-pro", "apikey-only": "deepseek-v4-pro"}}}, + {ID: 3, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{"model_mapping": map[string]any{"apikey-only": "gpt-5"}}}, + // Antigravity 账号创建时会把默认映射(含 claude-*)写入 model_mapping。 + {ID: 4, Platform: PlatformAntigravity, Type: AccountTypeOAuth, Credentials: map[string]any{"model_mapping": map[string]any{"claude-opus-4-8": "claude-opus-4-8"}}}, + {ID: 5, Platform: PlatformAnthropic, Type: AccountTypeSetupToken, Credentials: map[string]any{"model_mapping": map[string]any{"claude-opus-4-8": "claude-opus-4-8"}}}, + }, + } + svc := &GatewayService{accountRepo: repo} + + withOAuth, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "gpt-6-astra") + require.NoError(t, err) + require.Equal(t, CompositeModelOwnership{Ambiguous: true, OpenAIGatewayOAuthClaimed: true}, withOAuth) + + apiKeyOnly, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "apikey-only") + require.NoError(t, err) + require.Equal(t, CompositeModelOwnership{Ambiguous: true}, apiKeyOnly) + + anthropicFamily, err := svc.resolveCompositeModelOwnership(context.Background(), groupID, "claude-opus-4-8") + require.NoError(t, err) + require.Equal(t, CompositeModelOwnership{Ambiguous: true}, anthropicFamily) +} + +func TestResolveCompositeModelOwnershipExcludesBPSWithoutDroppingOAuthProtection(t *testing.T) { + svc := &GatewayService{accountRepo: &compositeOwnershipAccountRepo{accounts: []Account{ + {ID: 1, Platform: PlatformOpenAIBPS, Type: AccountTypeOAuth, Credentials: map[string]any{ + "model_mapping": map[string]any{"shared": "gpt-6-astra", "bps-only": "gpt-6-astra"}, + }}, + {ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{ + "model_mapping": map[string]any{"shared": "gpt-6-astra"}, + }}, + }}} + ownership, err := svc.resolveCompositeModelOwnership(context.Background(), 7, "shared") + require.NoError(t, err) + require.Equal(t, CompositeModelOwnership{ + TargetPlatform: PlatformOpenAI, Matched: true, OpenAIGatewayOAuthClaimed: true, + }, ownership) + + ownership, err = svc.resolveCompositeModelOwnership(context.Background(), 7, "bps-only") + require.NoError(t, err) + require.Equal(t, CompositeModelOwnership{}, ownership) +} + func TestNewGatewayServiceWiresCompositeModelOwnershipResolver(t *testing.T) { groupID := int64(7) repo := &compositeOwnershipAccountRepo{ diff --git a/backend/internal/service/composite_route_resolver.go b/backend/internal/service/composite_route_resolver.go index 2eccbf853..7f58ffbc4 100644 --- a/backend/internal/service/composite_route_resolver.go +++ b/backend/internal/service/composite_route_resolver.go @@ -5,8 +5,34 @@ import ( "fmt" "sort" "strings" + + "github.com/MACOS-DO/sub4api/internal/domain" +) + +const ( + // CompositeRouteReasonAmbiguous marks a model whose explicit account + // mappings span several provider platforms. + CompositeRouteReasonAmbiguous = "model is exposed by multiple provider platforms" + // CompositeRouteReasonOAuthAmbiguous is the ambiguous case where a claimant + // holds an OAuth / setup-token credential that only the OpenAI gateway can + // carry, and the model-name fallback would also pick an OpenAI-gateway + // platform. The unresolved request would land in the Anthropic gateway + // handler and select those credentials, so this group misconfiguration must + // be rejected instead of guessing a platform from the model name. + CompositeRouteReasonOAuthAmbiguous = "model is exposed by multiple provider platforms including OAuth accounts" ) +// OAuthAmbiguous reports whether the request must be rejected because the +// cross-platform ownership involves OpenAI-gateway OAuth credentials. +func (d CompositeRouteDecision) OAuthAmbiguous() bool { + return !d.Matched && d.Reason == CompositeRouteReasonOAuthAmbiguous +} + +// AmbiguousMessage is the client-facing rejection for an OAuthAmbiguous decision. +func (d CompositeRouteDecision) AmbiguousMessage() string { + return fmt.Sprintf("Model %q is mapped on multiple provider platforms in this group; configure an explicit composite route", d.PublicModel) +} + type CompositeRouteResolver struct { repo CompositeModelRouteRepository modelOwnershipResolver CompositeModelOwnershipResolver @@ -117,7 +143,12 @@ func (r *CompositeRouteResolver) Resolve(ctx context.Context, groupID int64, mod return decision, fmt.Errorf("resolve account model ownership: %w", err) } } else if ownership.Ambiguous { - decision.Reason = "model is exposed by multiple provider platforms" + decision.Reason = CompositeRouteReasonAmbiguous + // 未解析的请求由下游 handler 按模型名前缀兜底选平台;只有兜底落在 + // OpenAI 网关族时,OpenAI 网关 OAuth 声明方才会被误送进 Anthropic 管线。 + if guessed, ok := DetectModelPlatform(model); ok && ownership.OpenAIGatewayOAuthClaimed && domain.UsesOpenAIGateway(guessed) { + decision.Reason = CompositeRouteReasonOAuthAmbiguous + } return decision, nil } else if ownership.Matched { platform := strings.TrimSpace(ownership.TargetPlatform) diff --git a/backend/internal/service/composite_route_resolver_test.go b/backend/internal/service/composite_route_resolver_test.go index 92827ab65..76e40e407 100644 --- a/backend/internal/service/composite_route_resolver_test.go +++ b/backend/internal/service/composite_route_resolver_test.go @@ -221,6 +221,33 @@ func TestCompositeRouteResolverDoesNotGuessAmbiguousAccountOwnership(t *testing. require.False(t, decision.Matched) require.Empty(t, decision.TargetPlatform) require.Equal(t, "model is exposed by multiple provider platforms", decision.Reason) + require.False(t, decision.OAuthAmbiguous()) +} + +// Scenario: 含 OAuth 账号的跨平台歧义必须被识别为需拒绝的配置错误 +func TestCompositeRouteResolverFlagsOAuthAmbiguousOwnership(t *testing.T) { + resolver := NewCompositeRouteResolver(nil) + resolver.SetModelOwnershipResolver(func(context.Context, int64, string) (CompositeModelOwnership, error) { + return CompositeModelOwnership{Ambiguous: true, OpenAIGatewayOAuthClaimed: true}, nil + }) + + // gpt-* 可被内置探测器识别,验证歧义不会退化为按模型名猜平台。 + decision, err := resolver.Resolve(context.Background(), 7, "gpt-6-astra", CompositeRouteEndpointResponses) + + require.NoError(t, err) + require.False(t, decision.Matched) + require.Empty(t, decision.TargetPlatform) + require.True(t, decision.OAuthAmbiguous()) + require.Contains(t, decision.AmbiguousMessage(), `"gpt-6-astra"`) + + // 兜底按模型名落到 Anthropic(如 OpenAI OAuth 映射 claude-* 给 Claude Code 用) + // 或无法兜底的自定义别名:OpenAI 网关 OAuth 不会被选中,保持原有行为。 + for _, model := range []string{"claude-sonnet-4-6", "team-alias"} { + decision, err := resolver.Resolve(context.Background(), 7, model, CompositeRouteEndpointMessages) + require.NoError(t, err) + require.False(t, decision.OAuthAmbiguous(), "model=%s", model) + require.Equal(t, CompositeRouteReasonAmbiguous, decision.Reason, "model=%s", model) + } } func TestCompositeRouteResolverOwnershipLookupErrorFallsBackOnlyForDetectableModels(t *testing.T) { diff --git a/backend/internal/service/content_moderation.go b/backend/internal/service/content_moderation.go index 5c5d51598..78ddbb656 100644 --- a/backend/internal/service/content_moderation.go +++ b/backend/internal/service/content_moderation.go @@ -720,7 +720,18 @@ func (s *ContentModerationService) UpdateConfig(ctx context.Context, input Updat if err != nil { return nil, fmt.Errorf("marshal content moderation config: %w", err) } - if err := s.settingRepo.Set(ctx, SettingKeyContentModerationConfig, string(raw)); err != nil { + var saveErr error + if writer, ok := s.settingRepo.(interface { + SetContentModerationConfig(context.Context, string, []int64) error + }); ok { + saveErr = writer.SetContentModerationConfig(ctx, string(raw), cfg.GroupIDs) + if errors.Is(saveErr, ErrGroupNotFound) { + return nil, infraerrors.BadRequest("INVALID_CONTENT_MODERATION_GROUP", "审计分组不存在") + } + } else { + saveErr = s.settingRepo.Set(ctx, SettingKeyContentModerationConfig, string(raw)) + } + if err := saveErr; err != nil { return nil, fmt.Errorf("save content moderation config: %w", err) } s.replaceRuntimeConfig(cfg, raw) diff --git a/backend/internal/service/gateway_anthropic_base_url_test.go b/backend/internal/service/gateway_anthropic_base_url_test.go new file mode 100644 index 000000000..9ca8f4b23 --- /dev/null +++ b/backend/internal/service/gateway_anthropic_base_url_test.go @@ -0,0 +1,106 @@ +//go:build unit + +package service + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func gatewayAnthropicBaseURLAccount(apiBaseURLs map[string]any) *Account { + return &Account{ + ID: 8074, + Platform: PlatformDeepseek, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "test-key", + "base_url": "https://api.deepseek.com", + "api_protocol": APIProtocolAdaptive, + "api_base_urls": apiBaseURLs, + }, + } +} + +func gatewayAnthropicBaseURLContext(t *testing.T) *gin.Context { + t.Helper() + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + return c +} + +func TestGatewayService_AdaptiveAnthropicBaseURLRouting(t *testing.T) { + svc := &GatewayService{cfg: &config.Config{}} + body := []byte(`{"model":"deepseek-chat","max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`) + + t.Run("base present is used by messages and count_tokens", func(t *testing.T) { + account := gatewayAnthropicBaseURLAccount(map[string]any{ + APIProtocolAnthropic: "https://anthropic.example.com", + APIProtocolChatCompletions: "https://chat.example.com", + }) + c := gatewayAnthropicBaseURLContext(t) + + req, _, err := svc.buildUpstreamRequest(context.Background(), c, account, body, "test-key", "apikey", "deepseek-chat", false, false) + require.NoError(t, err) + require.Equal(t, "https://anthropic.example.com/v1/messages?beta=true", req.URL.String()) + + countReq, _, err := svc.buildCountTokensRequest(context.Background(), c, account, body, "test-key", "apikey", "deepseek-chat", false) + require.NoError(t, err) + require.Equal(t, "https://anthropic.example.com/v1/messages/count_tokens?beta=true", countReq.URL.String()) + }) + + t.Run("missing anthropic base uses provider fallback", func(t *testing.T) { + account := gatewayAnthropicBaseURLAccount(map[string]any{ + APIProtocolChatCompletions: "https://chat.example.com", + }) + req, _, err := svc.buildUpstreamRequest(context.Background(), gatewayAnthropicBaseURLContext(t), account, body, "test-key", "apikey", "deepseek-chat", false, false) + require.NoError(t, err) + require.Equal(t, "https://api.deepseek.com/anthropic/v1/messages?beta=true", req.URL.String()) + }) + + t.Run("ordinary anthropic api key keeps base_url fallback", func(t *testing.T) { + account := &Account{ + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "test-key", + "base_url": "https://custom-anthropic.example.com", + }, + } + req, _, err := svc.buildUpstreamRequest(context.Background(), gatewayAnthropicBaseURLContext(t), account, body, "test-key", "apikey", "deepseek-chat", false, false) + require.NoError(t, err) + require.Equal(t, "https://custom-anthropic.example.com/v1/messages?beta=true", req.URL.String()) + }) +} + +func TestGatewayService_AnthropicPassthroughAndCountTokensUseSelectedBase(t *testing.T) { + svc := &GatewayService{cfg: &config.Config{}} + account := gatewayAnthropicBaseURLAccount(map[string]any{ + APIProtocolAnthropic: "https://ollama.com", + }) + body := []byte(`{"model":"deepseek-v4-flash","max_tokens":256000,"messages":[{"role":"user","content":"hi"}]}`) + c := gatewayAnthropicBaseURLContext(t) + + passthroughReq, wireBody, err := svc.buildUpstreamRequestAnthropicAPIKeyPassthrough(context.Background(), c, account, body, "test-key") + require.NoError(t, err) + require.Equal(t, "https://ollama.com/v1/messages?beta=true", passthroughReq.URL.String()) + require.Equal(t, "Bearer test-key", passthroughReq.Header.Get("Authorization")) + require.Equal(t, int64(65535), gjson.GetBytes(wireBody, "max_tokens").Int()) + + countPassthroughReq, err := svc.buildCountTokensRequestAnthropicAPIKeyPassthrough(context.Background(), c, account, body, "test-key") + require.NoError(t, err) + require.Equal(t, "https://ollama.com/v1/messages/count_tokens?beta=true", countPassthroughReq.URL.String()) + require.Equal(t, "Bearer test-key", countPassthroughReq.Header.Get("Authorization")) + + countReq, _, err := svc.buildCountTokensRequest(context.Background(), c, account, body, "test-key", "apikey", "deepseek-v4-flash", false) + require.NoError(t, err) + require.Equal(t, "https://ollama.com/v1/messages/count_tokens?beta=true", countReq.URL.String()) + require.Equal(t, "Bearer test-key", countReq.Header.Get("Authorization")) +} diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go index 39d4324b0..27072dcd6 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -184,7 +184,7 @@ func (s *GatewayService) forwardAnthropicAPIKeyPassthroughWithInput( logger.LegacyPrintf("service.gateway", "[Anthropic Passthrough] Upstream error (retry exhausted, failover): Account=%d(%s) Status=%d RequestID=%s Body=%s", account.ID, account.Name, resp.StatusCode, resp.Header.Get("x-request-id"), truncateString(string(respBody), 1000)) - s.handleRetryExhaustedSideEffects(ctx, resp, account) + s.handleRetryExhaustedSideEffects(ctx, resp, account, input.RequestModel) appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ ProxyID: opsUpstreamProxyID(account), ProxyName: opsUpstreamProxyName(account), @@ -209,7 +209,7 @@ func (s *GatewayService) forwardAnthropicAPIKeyPassthroughWithInput( RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } - return s.handleRetryExhaustedError(ctx, resp, c, account) + return s.handleRetryExhaustedError(ctx, resp, c, account, input.RequestModel) } if resp.StatusCode >= 400 && s.shouldFailoverUpstreamError(resp.StatusCode) { @@ -301,7 +301,7 @@ func (s *GatewayService) buildUpstreamRequestAnthropicAPIKeyPassthrough( ) (*http.Request, []byte, error) { body = stripDeferredToolCacheControl(body) targetURL := claudeAPIURL - baseURL := account.GetBaseURL() + baseURL := getAnthropicGatewayBaseURL(account) if baseURL != "" { validatedURL, err := s.validateUpstreamBaseURL(baseURL) if err != nil { @@ -326,8 +326,8 @@ func (s *GatewayService) buildUpstreamRequestAnthropicAPIKeyPassthrough( } // Ollama Cloud DeepSeek 出站 max_tokens clamp:判定与上方 targetURL 的 - // base 取值同源(GetBaseURL),详见 helper 注释。 - body = clampOllamaCloudAnthropicMessagesMaxTokens(account, account.GetBaseURL(), body) + // base 取值同源,详见 helper 注释。 + body = clampOllamaCloudAnthropicMessagesMaxTokens(account, baseURL, body) req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, bytes.NewReader(body)) if err != nil { @@ -354,7 +354,7 @@ func (s *GatewayService) buildUpstreamRequestAnthropicAPIKeyPassthrough( req.Header.Del("cookie") // Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方 // targetURL 的 base 取值),其余保持 extra/default 行为。 - setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL()) + setAnthropicAPIKeyAuthHeader(req.Header, account, token, baseURL) if getHeaderRaw(req.Header, "content-type") == "" { setHeaderRaw(req.Header, "content-type", "application/json") diff --git a/backend/internal/service/gateway_bedrock.go b/backend/internal/service/gateway_bedrock.go index 6ba666a8a..5cb66856e 100644 --- a/backend/internal/service/gateway_bedrock.go +++ b/backend/internal/service/gateway_bedrock.go @@ -130,7 +130,9 @@ func (s *GatewayService) forwardBedrock( // 错误/failover 处理 if resp.StatusCode >= 400 { - return s.handleBedrockUpstreamErrors(ctx, resp, c, account) + // 账号状态按模型隔离时用调度器的模型键(账号映射后的模型名),不是发往上游的 Bedrock 模型 ID; + // 两者不一致会让模型级冷却写到调度器不会读取的键上。 + return s.handleBedrockUpstreamErrors(ctx, resp, c, account, account.GetMappedModel(reqModel)) } // Bedrock 分支绕过通用 Forward 成功路径,这里保持上游接受回调语义一致。 @@ -263,12 +265,14 @@ func (s *GatewayService) executeBedrockUpstream( return resp, nil } -// handleBedrockUpstreamErrors 处理 Bedrock 上游 4xx/5xx 错误(failover + 错误响应) +// handleBedrockUpstreamErrors 处理 Bedrock 上游 4xx/5xx 错误(failover + 错误响应); +// modelKey 是调度器按模型隔离账号状态时使用的模型键(account.GetMappedModel 的结果)。 func (s *GatewayService) handleBedrockUpstreamErrors( ctx context.Context, resp *http.Response, c *gin.Context, account *Account, + modelKey string, ) (*ForwardResult, error) { // retry exhausted + failover if s.shouldRetryUpstreamError(account, resp.StatusCode) { @@ -280,7 +284,7 @@ func (s *GatewayService) handleBedrockUpstreamErrors( logger.LegacyPrintf("service.gateway", "[Bedrock] Upstream error (retry exhausted, failover): Account=%d(%s) Status=%d Body=%s", account.ID, account.Name, resp.StatusCode, truncateString(string(respBody), 1000)) - s.handleRetryExhaustedSideEffects(ctx, resp, account) + s.handleRetryExhaustedSideEffects(ctx, resp, account, modelKey) appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ ProxyID: opsUpstreamProxyID(account), ProxyName: opsUpstreamProxyName(account), @@ -297,7 +301,7 @@ func (s *GatewayService) handleBedrockUpstreamErrors( RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } - return s.handleRetryExhaustedError(ctx, resp, c, account) + return s.handleRetryExhaustedError(ctx, resp, c, account, modelKey) } // non-retryable failover @@ -306,7 +310,7 @@ func (s *GatewayService) handleBedrockUpstreamErrors( _ = resp.Body.Close() resp.Body = io.NopCloser(bytes.NewReader(respBody)) - s.handleFailoverSideEffects(ctx, resp, account) + s.handleFailoverSideEffects(ctx, resp, account, modelKey) appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ ProxyID: opsUpstreamProxyID(account), ProxyName: opsUpstreamProxyName(account), @@ -325,7 +329,7 @@ func (s *GatewayService) handleBedrockUpstreamErrors( } // other errors - return s.handleErrorResponse(ctx, resp, c, account) + return s.handleErrorResponse(ctx, resp, c, account, modelKey) } // buildUpstreamRequestBedrock 构建 Bedrock 上游请求 diff --git a/backend/internal/service/gateway_claude_oauth_body.go b/backend/internal/service/gateway_claude_oauth_body.go index b4f33b470..e2c847e56 100644 --- a/backend/internal/service/gateway_claude_oauth_body.go +++ b/backend/internal/service/gateway_claude_oauth_body.go @@ -263,7 +263,11 @@ func normalizeClaudeOAuthRequestBody(body []byte, modelID string, opts claudeOAu // temperature:真实 Claude Code CLI 总是发送 temperature(默认 1,客户端可覆盖)。 // 之前的实现直接 delete 会导致 payload 缺字段,与真实 CLI 字节级不一致。 // 策略:客户端传了什么就透传;没传则补默认 1。 - if !gjson.GetBytes(out, "temperature").Exists() && !claude.IsOpus55(modelID) { + // 例外:采样锁定的模型(sonnet-5-5/haiku-5-5)上 temperature+top_p 共存即 400, + // 客户端只传 top_p 时不得再补 temperature,否则网关自己制造 400(issue #7919)。 + samplingLocked := claude.IsSonnet55(modelID) || claude.IsHaiku55(modelID) + if !gjson.GetBytes(out, "temperature").Exists() && !claude.IsOpus55(modelID) && + (!samplingLocked || !gjson.GetBytes(out, "top_p").Exists()) { if next, ok := setJSONValueBytes(out, "temperature", 1); ok { out = next modified = true diff --git a/backend/internal/service/gateway_context_management_test.go b/backend/internal/service/gateway_context_management_test.go index 7cd9e0b57..32644f7fb 100644 --- a/backend/internal/service/gateway_context_management_test.go +++ b/backend/internal/service/gateway_context_management_test.go @@ -371,6 +371,25 @@ func TestNormalizeClaudeOAuthRequestBody_HaikuShortModelStillNormalizesToDatedID require.Equal(t, "claude-haiku-4-5-20251001", gjson.GetBytes(out, "model").String()) } +// issue #7919:采样锁定的模型上 temperature+top_p 共存即 400, +// 只传 top_p 时不得再补 temperature,否则网关自己制造 400。 +func TestNormalizeClaudeOAuthRequestBody_SkipsTemperatureTopUpWithTopPOnLockedModels(t *testing.T) { + for _, model := range []string{"claude-haiku-5-5", "claude-sonnet-5-5"} { + body := []byte(`{"model":"` + model + `","top_p":0.99,"messages":[]}`) + out, _ := normalizeClaudeOAuthRequestBody(body, model, claudeOAuthNormalizeOptions{}) + require.False(t, gjson.GetBytes(out, "temperature").Exists(), + "model %s with top_p must not gain temperature", model) + require.Equal(t, 0.99, gjson.GetBytes(out, "top_p").Float()) + } +} + +func TestNormalizeClaudeOAuthRequestBody_StillTopsUpTemperatureWithoutTopP(t *testing.T) { + body := []byte(`{"model":"claude-haiku-5-5","messages":[]}`) + out, _ := normalizeClaudeOAuthRequestBody(body, "claude-haiku-5-5", claudeOAuthNormalizeOptions{}) + require.Equal(t, int64(1), gjson.GetBytes(out, "temperature").Int(), + "无 top_p 时 temperature:1 补齐保持不变") +} + func TestApplyClaudeCodeOAuthMimicryToBody_HaikuRewritesSystem(t *testing.T) { account := &Account{ID: 405, Platform: PlatformAnthropic, Type: AccountTypeOAuth} body := []byte(`{"model":"claude-haiku-4-5","system":"Pi project instructions","messages":[{"role":"user","content":"hello"}]}`) diff --git a/backend/internal/service/gateway_count_tokens.go b/backend/internal/service/gateway_count_tokens.go index c99648d34..66dfb4c6f 100644 --- a/backend/internal/service/gateway_count_tokens.go +++ b/backend/internal/service/gateway_count_tokens.go @@ -22,6 +22,13 @@ func (s *GatewayService) ForwardCountTokens(ctx context.Context, c *gin.Context, s.countTokensError(c, http.StatusBadRequest, "invalid_request_error", "Request body is empty") return fmt.Errorf("parse request: empty request") } + // Antigravity 账户不支持 count_tokens,返回 404 让客户端 fallback 到本地估算。 + // 返回 nil 避免 handler 层记录为错误,也不设置 ops 上游错误上下文。 + // 凭据只能走其他协议的 OAuth 账号同理,且必须在取 token、建请求之前拦下。 + if account != nil && (account.Platform == PlatformAntigravity || !anthropicMessagesCredentialAllowed(account)) { + s.countTokensError(c, http.StatusNotFound, "not_found_error", "count_tokens endpoint is not supported for this platform") + return nil + } validationModel := parsed.Model if account != nil { @@ -42,13 +49,15 @@ func (s *GatewayService) ForwardCountTokens(ctx context.Context, c *gin.Context, if account != nil && account.IsAnthropicAPIKeyPassthroughEnabled() { passthroughBody := parsed.Body.Bytes() + passthroughModel := parsed.Model if reqModel := parsed.Model; reqModel != "" { if mappedModel := account.GetMappedModel(reqModel); mappedModel != reqModel { passthroughBody = s.replaceModelInBody(passthroughBody, mappedModel) + passthroughModel = mappedModel logger.LegacyPrintf("service.gateway", "CountTokens passthrough model mapping: %s -> %s (account: %s)", reqModel, mappedModel, account.Name) } } - return s.forwardCountTokensAnthropicAPIKeyPassthrough(ctx, c, account, passthroughBody) + return s.forwardCountTokensAnthropicAPIKeyPassthrough(ctx, c, account, passthroughBody, passthroughModel) } // Bedrock 不支持 count_tokens 端点 @@ -103,13 +112,6 @@ func (s *GatewayService) ForwardCountTokens(ctx context.Context, c *gin.Context, } } - // Antigravity 账户不支持 count_tokens,返回 404 让客户端 fallback 到本地估算。 - // 返回 nil 避免 handler 层记录为错误,也不设置 ops 上游错误上下文。 - if account.Platform == PlatformAntigravity { - s.countTokensError(c, http.StatusNotFound, "not_found_error", "count_tokens endpoint is not supported for this platform") - return nil - } - // 应用模型映射: // - APIKey 账号:使用账号级别的显式映射(如果配置),否则透传原始模型名 // - OAuth/SetupToken 账号:使用 Anthropic 标准映射(短ID → 长ID) @@ -220,8 +222,8 @@ func (s *GatewayService) ForwardCountTokens(ctx context.Context, c *gin.Context, // 处理错误响应 if resp.StatusCode >= 400 { - // 标记账号状态(429/529等) - s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody) + // 标记账号状态(429/529等);传入实际发往上游的模型,临时不可调度规则才能按模型隔离 + s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, reqModel) upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) @@ -267,7 +269,9 @@ func (s *GatewayService) ForwardCountTokens(ctx context.Context, c *gin.Context, return nil } -func (s *GatewayService) forwardCountTokensAnthropicAPIKeyPassthrough(ctx context.Context, c *gin.Context, account *Account, body []byte) error { +// forwardCountTokensAnthropicAPIKeyPassthrough 透传 count_tokens 请求;upstreamModel 是 body 中实际发往上游的模型, +// 仅用于上游错误处理按模型隔离。 +func (s *GatewayService) forwardCountTokensAnthropicAPIKeyPassthrough(ctx context.Context, c *gin.Context, account *Account, body []byte, upstreamModel string) error { token, tokenType, err := s.GetAccessToken(ctx, account) if err != nil { s.countTokensError(c, http.StatusBadGateway, "upstream_error", "Failed to get access token") @@ -322,7 +326,7 @@ func (s *GatewayService) forwardCountTokensAnthropicAPIKeyPassthrough(ctx contex if resp.StatusCode >= 400 { if s.rateLimitService != nil { - s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody) + s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, upstreamModel) } upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody)) @@ -395,7 +399,7 @@ func (s *GatewayService) buildCountTokensRequestAnthropicAPIKeyPassthrough( ) (*http.Request, error) { body = stripDeferredToolCacheControl(body) targetURL := claudeAPICountTokensURL - baseURL := account.GetBaseURL() + baseURL := getAnthropicGatewayBaseURL(account) if baseURL != "" { validatedURL, err := s.validateUpstreamBaseURL(baseURL) if err != nil { @@ -442,7 +446,7 @@ func (s *GatewayService) buildCountTokensRequestAnthropicAPIKeyPassthrough( req.Header.Del("cookie") // Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方 // targetURL 的 base 取值),其余保持 extra/default 行为。 - setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL()) + setAnthropicAPIKeyAuthHeader(req.Header, account, token, baseURL) if req.Header.Get("content-type") == "" { req.Header.Set("content-type", "application/json") @@ -463,8 +467,9 @@ func (s *GatewayService) buildCountTokensRequest(ctx context.Context, c *gin.Con body = stripDeferredToolCacheControl(body) // 确定目标 URL targetURL := claudeAPICountTokensURL + baseURL := "" if account.Type == AccountTypeAPIKey { - baseURL := account.GetBaseURL() + baseURL = getAnthropicGatewayBaseURL(account) if baseURL != "" { validatedURL, err := s.validateUpstreamBaseURL(baseURL) if err != nil { @@ -554,7 +559,7 @@ func (s *GatewayService) buildCountTokensRequest(ctx context.Context, c *gin.Con } else { // Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方 // targetURL 的 base 取值),其余保持 extra/default 行为。 - setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL()) + setAnthropicAPIKeyAuthHeader(req.Header, account, token, baseURL) } // 白名单透传 headers(恢复真实 wire casing) diff --git a/backend/internal/service/gateway_forward.go b/backend/internal/service/gateway_forward.go index e66e35cad..922d0fda9 100644 --- a/backend/internal/service/gateway_forward.go +++ b/backend/internal/service/gateway_forward.go @@ -689,7 +689,7 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A logger.LegacyPrintf("service.gateway", "[Forward] Upstream error (retry exhausted, failover): Account=%d(%s) Status=%d RequestID=%s Body=%s", account.ID, account.Name, resp.StatusCode, resp.Header.Get("x-request-id"), truncateString(string(respBody), 1000)) - s.handleRetryExhaustedSideEffects(ctx, resp, account) + s.handleRetryExhaustedSideEffects(ctx, resp, account, reqModel) appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ ProxyID: opsUpstreamProxyID(account), ProxyName: opsUpstreamProxyName(account), @@ -713,7 +713,7 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } - return s.handleRetryExhaustedError(ctx, resp, c, account) + return s.handleRetryExhaustedError(ctx, resp, c, account, reqModel) } // 处理可切换账号的错误 diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index ed0716ae3..bdb237a8a 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -44,7 +44,7 @@ func (s *GatewayService) ForwardAsChatCompletions( clientStream := ccReq.Stream // 2. Convert CC → Responses → Anthropic (chained conversion) - responsesReq, err := apicompat.ChatCompletionsToResponses(&ccReq) + responsesReq, err := chatCompletionsToResponses(s.cfg, &ccReq) if err != nil { return nil, fmt.Errorf("convert chat completions to responses: %w", err) } diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index 78a4af4f6..12a332439 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -37,7 +37,7 @@ func (s *GatewayService) ForwardAsResponses( ) (*ForwardResult, error) { startTime := time.Now() - normalizedBody, normalized, err := normalizeOpenAIResponsesLegacyIngress(body) + normalizedBody, normalized, err := normalizeOpenAIResponsesLegacyIngressWithConfig(s.cfg, body) if err != nil { return nil, err } diff --git a/backend/internal/service/gateway_hotpath_optimization_test.go b/backend/internal/service/gateway_hotpath_optimization_test.go index 9c4404659..d5b5ce803 100644 --- a/backend/internal/service/gateway_hotpath_optimization_test.go +++ b/backend/internal/service/gateway_hotpath_optimization_test.go @@ -180,6 +180,10 @@ func (s *modelsListAccountRepoStub) ListSchedulableByGroupID(ctx context.Context return out, nil } +func (s *modelsListAccountRepoStub) ListModelAvailabilityCandidates(ctx context.Context, groupID *int64, _ []string, _ bool) ([]Account, error) { + return s.ListSchedulableByGroupID(ctx, *groupID) +} + func (s *modelsListAccountRepoStub) ListSchedulable(ctx context.Context) ([]Account, error) { s.listAllCalls.Add(1) if s.err != nil { diff --git a/backend/internal/service/gateway_image_reasoning_pricing_test.go b/backend/internal/service/gateway_image_reasoning_pricing_test.go index 39309153b..322f3cb84 100644 --- a/backend/internal/service/gateway_image_reasoning_pricing_test.go +++ b/backend/internal/service/gateway_image_reasoning_pricing_test.go @@ -131,7 +131,7 @@ func TestCalculateRecordUsageCost_MediaReasoningPricing(t *testing.T) { } var err error cost, err = svc.calculateOpenAIRecordUsageCost(context.Background(), result, apiKey, - []string{model}, 0.5, 0.5, 0.5, 0.5, UsageTokens{}, "", nil, time.Time{}) + []string{model}, 0.5, 0.5, 0.5, 0.5, UsageTokens{}, "", nil, false, time.Time{}) require.NoError(t, err) } require.NotNil(t, cost) diff --git a/backend/internal/service/gateway_model_availability.go b/backend/internal/service/gateway_model_availability.go index 6ff256cda..816c2f133 100644 --- a/backend/internal/service/gateway_model_availability.go +++ b/backend/internal/service/gateway_model_availability.go @@ -21,6 +21,9 @@ type ModelAvailabilityDiagnosis struct { // HasModelSupport is true if at least one account's model mapping admits // the requested model. HasModelSupport bool + // HasRetiredSubscriptionModel records a ChatGPT upstream blocked by model + // retirement, so an unsupported request can include migration guidance. + HasRetiredSubscriptionModel bool } // ModelAvailabilityDiagnoser is implemented by gateway services that can diff --git a/backend/internal/service/gateway_request.go b/backend/internal/service/gateway_request.go index e1f99fc7f..460fd1f0e 100644 --- a/backend/internal/service/gateway_request.go +++ b/backend/internal/service/gateway_request.go @@ -570,7 +570,7 @@ func StripEmptyTextBlocks(body []byte) []byte { // isClaude55SignedThinkingModel identifies models whose default thinking mode // requires signed history to survive protocol conversion and request filtering. func isClaude55SignedThinkingModel(model string) bool { - return claude.IsOpus55(model) || claude.IsSonnet55(model) + return claude.IsOpus55(model) || claude.IsSonnet55(model) || claude.IsHaiku55(model) } // validateClaude55Request rejects settings that the upstream cannot honor. @@ -580,14 +580,31 @@ func validateClaude55Request(body []byte, model string) error { return nil } isSonnet55 := claude.IsSonnet55(model) - switch gjson.GetBytes(body, "thinking.type").String() { + isHaiku55 := claude.IsHaiku55(model) + thinkingType := gjson.GetBytes(body, "thinking.type").String() + switch thinkingType { case "disabled", "enabled": + if isHaiku55 { + // haiku-5-5:enabled 一律 400(用 adaptive);disabled 仅 high 及以下 + // 可用,xhigh/max 上 400。见官方 migration guide。 + if thinkingType == "enabled" { + return fmt.Errorf("claude-haiku-5-5 requires adaptive thinking; omit thinking or use thinking.type=adaptive and output_config.effort") + } + switch gjson.GetBytes(body, "output_config.effort").String() { + case "xhigh", "max": + return fmt.Errorf("claude-haiku-5-5 thinking.type=disabled supports only low, medium or high effort") + } + break + } if isSonnet55 { return fmt.Errorf("claude-sonnet-5-5 requires adaptive thinking or thinking.type=between_tools; omit thinking or use one of those modes") } return fmt.Errorf("claude-opus-5-5 requires adaptive thinking; omit thinking or use thinking.type=adaptive and output_config.effort") case "between_tools": if !isSonnet55 { + if isHaiku55 { + return fmt.Errorf("claude-haiku-5-5 requires adaptive thinking; thinking.type=between_tools is unsupported (use thinking.type=disabled at high effort or below)") + } return fmt.Errorf("claude-opus-5-5 requires adaptive thinking; thinking.type=between_tools is unsupported") } effort := gjson.GetBytes(body, "output_config.effort").String() @@ -604,22 +621,34 @@ func validateClaude55Request(body []byte, model string) error { if isSonnet55 { modelName = "claude-sonnet-5-5" } - if gjson.GetBytes(body, "tool_choice").String() == "required" { - return fmt.Errorf("%s does not support forced tool_choice; use auto or none", modelName) + if isHaiku55 { + modelName = "claude-haiku-5-5" } - switch gjson.GetBytes(body, "tool_choice.type").String() { - case "any", "tool", "function", "custom", "namespace": - return fmt.Errorf("%s does not support forced tool_choice; use auto or none", modelName) + // haiku-5-5 接受强制 tool_choice(响应以 tool call 开头、无 thinking 块), + // 与 opus/sonnet-5-5 不同,不拦截。见官方 migration guide。 + if !isHaiku55 { + if gjson.GetBytes(body, "tool_choice").String() == "required" { + return fmt.Errorf("%s does not support forced tool_choice; use auto or none", modelName) + } + switch gjson.GetBytes(body, "tool_choice.type").String() { + case "any", "tool", "function", "custom", "namespace": + return fmt.Errorf("%s does not support forced tool_choice; use auto or none", modelName) + } } - if isSonnet55 { + if isSonnet55 || isHaiku55 { if temperature := gjson.GetBytes(body, "temperature"); temperature.Exists() && (temperature.Type != gjson.Number || temperature.Float() != 1) { - return fmt.Errorf("claude-sonnet-5-5 does not support non-default temperature") + return fmt.Errorf("%s does not support non-default temperature", modelName) } - if topP := gjson.GetBytes(body, "top_p"); topP.Exists() && (topP.Type != gjson.Number || topP.Float() < 0.99 || topP.Float() > 1) { - return fmt.Errorf("claude-sonnet-5-5 does not support non-default top_p") + // Haiku 5.5 只接受显式 top_p=0.99;保留 Sonnet 5.5 既有的区间策略。 + if topP := gjson.GetBytes(body, "top_p"); topP.Exists() && (topP.Type != gjson.Number || + (isHaiku55 && topP.Float() != 0.99) || (isSonnet55 && (topP.Float() < 0.99 || topP.Float() > 1))) { + return fmt.Errorf("%s does not support non-default top_p", modelName) } if gjson.GetBytes(body, "top_k").Exists() { - return fmt.Errorf("claude-sonnet-5-5 does not support top_k") + return fmt.Errorf("%s does not support top_k", modelName) + } + if isHaiku55 && gjson.GetBytes(body, "temperature").Exists() && gjson.GetBytes(body, "top_p").Exists() { + return fmt.Errorf("%s does not allow temperature and top_p together; omit both", modelName) } } return nil diff --git a/backend/internal/service/gateway_request_haiku55_test.go b/backend/internal/service/gateway_request_haiku55_test.go new file mode 100644 index 000000000..c81309792 --- /dev/null +++ b/backend/internal/service/gateway_request_haiku55_test.go @@ -0,0 +1,55 @@ +//go:build unit + +package service + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +// issue #7919:claude-haiku-5-5 请求校验(官方 migration guide 口径)。 +func TestValidateClaude55Request_Haiku55(t *testing.T) { + const model = "claude-haiku-5-5" + const prefix = `{"model":"claude-haiku-5-5","max_tokens":16000,"messages":[{"role":"user","content":"hi"}]` + cases := []struct { + name string + // extra 为追加进最小合法请求的 JSON 片段(含前导逗号) + extra string + wantErr string // 为空表示期望通过 + }{ + {name: "adaptive thinking passes", extra: `,"thinking":{"type":"adaptive"},"output_config":{"effort":"medium"}`}, + {name: "omitted thinking passes", extra: ``}, + {name: "enabled thinking rejected", extra: `,"thinking":{"type":"enabled","budget_tokens":8000}`, wantErr: "requires adaptive thinking"}, + {name: "拒绝 between_tools 并返回 Haiku 错误说明", extra: `,"thinking":{"type":"between_tools"}`, wantErr: "claude-haiku-5-5 requires adaptive thinking; thinking.type=between_tools is unsupported"}, + {name: "disabled thinking allowed at medium effort", extra: `,"thinking":{"type":"disabled"},"output_config":{"effort":"medium"}`}, + {name: "disabled thinking allowed when effort omitted", extra: `,"thinking":{"type":"disabled"}`}, + {name: "disabled thinking rejected at xhigh", extra: `,"thinking":{"type":"disabled"},"output_config":{"effort":"xhigh"}`, wantErr: "supports only low, medium or high effort"}, + {name: "disabled thinking rejected at max", extra: `,"thinking":{"type":"disabled"},"output_config":{"effort":"max"}`, wantErr: "supports only low, medium or high effort"}, + {name: "temperature 1 passes", extra: `,"temperature":1`}, + {name: "non-default temperature rejected", extra: `,"temperature":0.5`, wantErr: "non-default temperature"}, + {name: "top_p 0.99 passes", extra: `,"top_p":0.99`}, + {name: "拒绝 top_p=0.995", extra: `,"top_p":0.995`, wantErr: "non-default top_p"}, + {name: "拒绝 top_p=1", extra: `,"top_p":1`, wantErr: "non-default top_p"}, + {name: "拒绝字符串 top_p", extra: `,"top_p":"0.99"`, wantErr: "non-default top_p"}, + {name: "top_p 0.5 rejected", extra: `,"top_p":0.5`, wantErr: "non-default top_p"}, + {name: "top_k rejected", extra: `,"top_k":5`, wantErr: "does not support top_k"}, + {name: "temperature and top_p together rejected", extra: `,"temperature":1,"top_p":0.99`, wantErr: "does not allow temperature and top_p together"}, + {name: "forced tool_choice any allowed", extra: `,"tool_choice":{"type":"any"}`}, + {name: "forced tool_choice required allowed", extra: `,"tool_choice":"required"`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body := []byte(prefix + tc.extra + "}") + err := validateClaude55Request(body, model) + if tc.wantErr == "" { + require.NoError(t, err) + return + } + require.Error(t, err) + require.True(t, strings.Contains(err.Error(), tc.wantErr), + "error %q should contain %q", err.Error(), tc.wantErr) + }) + } +} diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index 316c6c13b..e39107f97 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -20,7 +20,9 @@ import ( "unsafe" "github.com/MACOS-DO/sub4api/internal/config" + "github.com/MACOS-DO/sub4api/internal/domain" "github.com/MACOS-DO/sub4api/internal/pkg/logger" + "github.com/MACOS-DO/sub4api/internal/pkg/openai" "github.com/MACOS-DO/sub4api/internal/pkg/xai" "github.com/MACOS-DO/sub4api/internal/util/responseheaders" "github.com/cespare/xxhash/v2" @@ -649,6 +651,9 @@ type ForwardResult struct { ImageSizeBreakdown map[string]int SearchCount int AudioUsage *AudioUsage + // CacheStorageTokenHours 显式上下文缓存的存储量(缓存 token 数 × 存储小时数),按计费模型的 + // 存储单价折算为费用后叠加在 token 费用之上。 + CacheStorageTokenHours float64 } // GatewayFailureStage identifies which request stage failed. The zero value is @@ -696,6 +701,7 @@ type UpstreamFailoverError struct { SameAccountRetryMax int // 可选的错误级同账号重试上限,低于 handler 默认预算时优先采用 RequestScopedTransient bool // 故障因素与账号无关(如上游按客户端身份/模型容量降载):可同账号重试,但不得据此对账号做临时封禁 SafeToFailoverAfterWrite bool // 仅写出 SSE 注释等非语义字节时,仍可在同一客户端流中切换账号 + BoundUpstreamPassthrough bool // 绑定显式缓存的请求在上游网关账号上收到的 429 / 5xx:反映持有缓存的上游账号状态,原样回写不走错误映射 Stage GatewayFailureStage Scope GatewayFailureScope Reason GatewayFailureReason @@ -1456,6 +1462,12 @@ func (s *GatewayService) GetAvailableModels(ctx context.Context, groupID *int64, } // If no account has model_mapping, return nil (use default) + if !hasAnyMapping && platform == PlatformOpenAI { + models := filterRetiredOpenAIModelIDs(accounts, openai.DefaultModelIDs()) + if len(models) != len(openai.DefaultModels) { + return models + } + } if !hasAnyMapping { if s.modelsListCache != nil { s.modelsListCache.Set(cacheKey, []string(nil), s.modelsListCacheTTL) @@ -1473,6 +1485,12 @@ func (s *GatewayService) GetAvailableModels(ctx context.Context, groupID *int64, if platform == PlatformOpenAI { models = supplementUnmappedOpenAIModels(accounts, models) + models = filterRetiredOpenAIModelIDs(accounts, models) + // nil means "use defaults" to listing callers; an empty filtered catalog + // must remain authoritative instead of resurrecting retired defaults. + if len(models) == 0 { + return models + } } if s.modelsListCache != nil { @@ -1497,21 +1515,27 @@ func (s *GatewayService) resolveCompositeModelOwnership(ctx context.Context, gro } } - accounts, err := s.accountRepo.ListSchedulableByGroupID(ctx, groupID) + // 归属取决于配置而非运行时健康:限流/临时不可调度不应让同一模型在 + // 「唯一归属」与「歧义」之间来回翻转,否则配置错误只会间歇暴露。 + accounts, err := s.accountRepo.ListModelAvailabilityCandidates(ctx, &groupID, domain.ConcretePlatformIDs(), false) if err != nil { return CompositeModelOwnership{}, err } platforms := make(map[string]struct{}) + ownership := CompositeModelOwnership{} for _, account := range accounts { platform := strings.TrimSpace(account.Platform) - if platform == PlatformOpenAIBPS || !isConcreteRequestPlatform(platform) || !explicitModelMappingClaims(account, model) { + if platform == PlatformOpenAIBPS || !isConcreteRequestPlatform(platform) { continue } - platforms[platform] = struct{}{} + if explicitModelMappingClaims(account, model) { + platforms[platform] = struct{}{} + ownership.OpenAIGatewayOAuthClaimed = ownership.OpenAIGatewayOAuthClaimed || + (account.IsOAuth() && domain.UsesOpenAIGateway(platform)) + } } - ownership := CompositeModelOwnership{} if len(platforms) == 1 { for platform := range platforms { ownership.TargetPlatform = platform diff --git a/backend/internal/service/gateway_upstream_request.go b/backend/internal/service/gateway_upstream_request.go index 1430506a3..ef01376ec 100644 --- a/backend/internal/service/gateway_upstream_request.go +++ b/backend/internal/service/gateway_upstream_request.go @@ -9,6 +9,7 @@ import ( "strconv" "strings" + "github.com/MACOS-DO/sub4api/internal/domain" "github.com/MACOS-DO/sub4api/internal/pkg/claude" "github.com/MACOS-DO/sub4api/internal/pkg/logger" "github.com/MACOS-DO/sub4api/internal/util/urlvalidator" @@ -18,7 +19,37 @@ import ( "github.com/gin-gonic/gin" ) +// anthropicMessagesForeignOAuthReason 标记账号凭据与 Anthropic Messages 协议不匹配。 +const anthropicMessagesForeignOAuthReason = GatewayFailureReason("anthropic_messages_foreign_oauth") + +// anthropicMessagesCredentialAllowed 判断账号凭据能否经 Anthropic Messages 协议 +// 出站。OAuth / setup-token 只对签发它的供应商有效(ChatGPT token 只认 +// chatgpt.com),送错协议既泄露凭据,上游 401 还会被误记到账号头上; +// API Key 不受限:其上游可能同时兼容多种协议格式。 +func anthropicMessagesCredentialAllowed(account *Account) bool { + if !account.IsOAuth() { + return true + } + spec, ok := domain.LookupPlatform(account.Platform) + return ok && spec.Gateway == domain.PlatformGatewayAnthropic +} + +// checkAnthropicMessagesCredential 在发出任何上游请求前拦截不匹配的凭据。返回的 +// failover 错误只让 handler 换下一个账号:没有上游响应,也就不触发任何账号处罚。 +func checkAnthropicMessagesCredential(account *Account) error { + if anthropicMessagesCredentialAllowed(account) { + return nil + } + return &UpstreamFailoverError{ + StatusCode: http.StatusBadGateway, + Reason: anthropicMessagesForeignOAuthReason, + } +} + func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Context, account *Account, body []byte, token, tokenType, modelID string, reqStream bool, mimicClaudeCode bool) (*http.Request, []byte, error) { + if err := checkAnthropicMessagesCredential(account); err != nil { + return nil, nil, err + } body = stripDeferredToolCacheControl(body) if account.Platform == PlatformAnthropic && account.Type == AccountTypeServiceAccount { req, err := s.buildUpstreamRequestAnthropicVertex(ctx, c, account, body, token, modelID, reqStream) @@ -27,8 +58,9 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex // 确定目标URL targetURL := claudeAPIURL + baseURL := "" if account.Type == AccountTypeAPIKey { - baseURL := account.GetBaseURL() + baseURL = getAnthropicGatewayBaseURL(account) if baseURL != "" { validatedURL, err := s.validateUpstreamBaseURL(baseURL) if err != nil { @@ -124,9 +156,9 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex } // Ollama Cloud DeepSeek 出站 max_tokens clamp:判定与上方 targetURL 的 - // base 取值同源(GetBaseURL),仅实际上游为 ollama.com 且映射后出站模型 + // base 取值同源,仅实际上游为 ollama.com 且映射后出站模型 // 为 DeepSeek 系时压到 cap,详见 helper 注释。 - body = clampOllamaCloudAnthropicMessagesMaxTokens(account, account.GetBaseURL(), body) + body = clampOllamaCloudAnthropicMessagesMaxTokens(account, baseURL, body) req, err := http.NewRequestWithContext(ctx, "POST", targetURL, bytes.NewReader(body)) if err != nil { @@ -139,7 +171,7 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex } else { // Ollama Cloud Anthropic 兼容端点按实际 base_url 强制 Bearer(同上方 // targetURL 的 base 取值),其余保持 extra/default 行为。 - setAnthropicAPIKeyAuthHeader(req.Header, account, token, account.GetBaseURL()) + setAnthropicAPIKeyAuthHeader(req.Header, account, token, baseURL) } // 白名单透传 headers @@ -225,6 +257,16 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex return req, body, nil } +func getAnthropicGatewayBaseURL(account *Account) string { + if account == nil { + return "" + } + if baseURL := account.GetAnthropicProtocolBaseURL(); baseURL != "" { + return baseURL + } + return account.GetBaseURL() +} + // vertexSupportedBetaTokens 是 Vertex AI 的 Anthropic 端点接受的 anthropic-beta // 白名单。Vertex 对任何未知 token 直接 HTTP 400,故采用白名单(与 Bedrock 的 // bedrockSupportedBetaTokens 同思路)而非黑名单:未来 Claude Code 新增的、Vertex 尚未 @@ -419,11 +461,13 @@ func defaultAPIKeyBetaHeader(body []byte) string { // The legacy streaming beta is incompatible with the stable computer and // browser toolsets. The per-tool eager_input_streaming field remains available. +// Applies to Sonnet 5.5 and Haiku 5.5, which share the computer_toolset_20260801 +// / browser_toolset_20260801 toolsets (Haiku 5.5 migration guide). func filterSonnet55ToolsetBeta(header string, body []byte, modelID string) string { if at := strings.IndexByte(modelID, '@'); at >= 0 { modelID = modelID[:at] // Vertex's dated model ID } - if !claude.IsSonnet55(modelID) { + if !claude.IsSonnet55(modelID) && !claude.IsHaiku55(modelID) { return header } for _, tool := range gjson.GetBytes(body, "tools").Array() { diff --git a/backend/internal/service/gateway_upstream_request_test.go b/backend/internal/service/gateway_upstream_request_test.go new file mode 100644 index 000000000..b6093e7fa --- /dev/null +++ b/backend/internal/service/gateway_upstream_request_test.go @@ -0,0 +1,73 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// Scenario: OAuth / setup-token 凭据只能走签发方协议,API Key 与其他凭据类型不受限 +func TestAnthropicMessagesCredentialAllowed(t *testing.T) { + cases := []struct { + platform string + typ string + allowed bool + }{ + {PlatformAnthropic, AccountTypeOAuth, true}, + {PlatformAnthropic, AccountTypeSetupToken, true}, + {PlatformAnthropic, AccountTypeServiceAccount, true}, + {PlatformAnthropic, AccountTypeBedrock, true}, + {PlatformTypeSafe, AccountTypeOAuth, true}, + {PlatformOpenAI, AccountTypeAPIKey, true}, + {PlatformDeepseek, AccountTypeAPIKey, true}, + {PlatformOpenAI, AccountTypeOAuth, false}, + {PlatformOpenAI, AccountTypeSetupToken, false}, + {PlatformGrok, AccountTypeOAuth, false}, + {PlatformGemini, AccountTypeOAuth, false}, + {PlatformAntigravity, AccountTypeOAuth, false}, + } + for _, tc := range cases { + allowed := anthropicMessagesCredentialAllowed(&Account{ID: 1, Platform: tc.platform, Type: tc.typ}) + require.Equal(t, tc.allowed, allowed, "%s/%s", tc.platform, tc.typ) + } +} + +// Scenario: 回归 —— OpenAI OAuth 账号误入 Anthropic 管线时,在构建请求前即被拒绝 +// (ChatGPT token 不会发往 api.anthropic.com),且只让 handler 换号、不处罚账号 +func TestGatewayBuildUpstreamRequestRejectsForeignOAuthWithoutPenalty(t *testing.T) { + account := &Account{ID: 25, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + body := []byte(`{"model":"gpt-6-astra","messages":[]}`) + + req, _, err := (&GatewayService{}).buildUpstreamRequest(context.Background(), nil, account, body, "chatgpt-token", "oauth", "gpt-6-astra", true, false) + require.Nil(t, req) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr)) + require.True(t, failoverErr.ShouldRetryNextAccount()) + require.False(t, failoverErr.RetryableOnSameAccount, "same-account retry would end in temp-unschedulable") + require.False(t, failoverErr.IsCredentialFailure()) + require.Equal(t, anthropicMessagesForeignOAuthReason, failoverErr.Reason) +} + +// Scenario: count_tokens 对不匹配凭据按「平台不支持」返回 404,不取 token、不出站 +func TestForwardCountTokensRejectsForeignOAuthAsUnsupported(t *testing.T) { + gin.SetMode(gin.TestMode) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", nil) + + account := &Account{ID: 25, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + parsed := &ParsedRequest{Model: "gpt-6-astra", Body: NewRequestBodyRef([]byte(`{"model":"gpt-6-astra","messages":[]}`))} + + err := (&GatewayService{}).ForwardCountTokens(context.Background(), c, account, parsed) + + require.NoError(t, err) + require.Equal(t, http.StatusNotFound, w.Code) +} diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index 71d8bc7a5..65347b004 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -527,13 +527,19 @@ func (s *GatewayService) handleErrorResponse(ctx context.Context, resp *http.Res return nil, fmt.Errorf("upstream error: %d message=%s", resp.StatusCode, upstreamMsg) } -func (s *GatewayService) handleRetryExhaustedSideEffects(ctx context.Context, resp *http.Response, account *Account) { +// handleRetryExhaustedSideEffects 在重试耗尽后标记账号状态;requestedModel 是实际发往上游的模型, +// 临时不可调度规则据此按模型隔离。 +func (s *GatewayService) handleRetryExhaustedSideEffects(ctx context.Context, resp *http.Response, account *Account, requestedModel ...string) { body, _ := s.readUpstreamErrorBody(resp) statusCode := resp.StatusCode // OAuth/Setup Token 账号的 403:标记账号异常 if account.IsOAuth() && statusCode == 403 { - s.rateLimitService.HandleUpstreamError(ctx, account, statusCode, resp.Header, body) + if len(requestedModel) > 0 { + s.rateLimitService.HandleUpstreamError(ctx, account, statusCode, resp.Header, body, requestedModel[0]) + } else { + s.rateLimitService.HandleUpstreamError(ctx, account, statusCode, resp.Header, body) + } logger.LegacyPrintf("service.gateway", "Account %d: marked as error after %d retries for status %d", account.ID, maxRetryAttempts, statusCode) } else { // API Key 未配置错误码:不标记账号状态 @@ -553,14 +559,14 @@ func (s *GatewayService) handleFailoverSideEffects(ctx context.Context, resp *ht // handleRetryExhaustedError 处理重试耗尽后的错误 // OAuth 403:标记账号异常 // API Key 未配置错误码:仅返回错误,不标记账号 -func (s *GatewayService) handleRetryExhaustedError(ctx context.Context, resp *http.Response, c *gin.Context, account *Account) (*ForwardResult, error) { +func (s *GatewayService) handleRetryExhaustedError(ctx context.Context, resp *http.Response, c *gin.Context, account *Account, requestedModel ...string) (*ForwardResult, error) { MarkResponseCommitted(c) // Capture upstream error body before side-effects consume the stream. respBody, _ := s.readUpstreamErrorBody(resp) _ = resp.Body.Close() resp.Body = io.NopCloser(bytes.NewReader(respBody)) - s.handleRetryExhaustedSideEffects(ctx, resp, account) + s.handleRetryExhaustedSideEffects(ctx, resp, account, requestedModel...) upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index e0b7e6efe..bd5c374a8 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -241,7 +241,8 @@ func isForcedUsageBillingRequestID(requestID string) bool { return strings.HasPrefix(id, "web_search:") || strings.HasPrefix(id, "grok-video:") || strings.HasPrefix(id, "grok_audio:") || - strings.HasPrefix(id, "grok_realtime:") + strings.HasPrefix(id, "grok_realtime:") || + strings.HasPrefix(id, GeminiCachedContentUsageRequestIDPrefix) } // StableGrokAudioBillingRequestID is the durable usage_logs / dedup key for one @@ -787,42 +788,9 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage cacheTTLOverridden = (result.Usage.CacheCreation5mTokens + result.Usage.CacheCreation1hTokens) > 0 } - // 获取费率倍数(优先级:用户专属 > 分组默认 > 系统默认) - multiplier := 1.0 - if s.cfg != nil { - multiplier = s.cfg.Default.RateMultiplier - } - if apiKey.GroupID != nil && apiKey.Group != nil { - groupDefault := apiKey.Group.RateMultiplier - multiplier = s.ResolveUserGroupRateMultiplier(ctx, user.ID, *apiKey.GroupID, groupDefault) - } - // token 倍率叠加高峰因子(token 计费含图片 token,图片按次倍率不受影响)。高峰因子按请求时刻现算, - // 不并入上面的 getUserGroupRateMultiplier,以免污染 user:group 倍率缓存。 - pricingAt := input.PricingAt - if pricingAt.IsZero() { - pricingAt = timezone.Now() - } - multiplier, imageMultiplier := computePeakAwareMultipliers(apiKey, multiplier, pricingAt) - - // 确定计费模型 - concreteBillingModel := forwardResultBillingModel(result.Model, result.UpstreamModel) - billingModel := concreteBillingModel - if input.BillingModelSource == BillingModelSourceChannelMapped && input.ChannelMappedModel != "" { - billingModel = input.ChannelMappedModel - } - if input.BillingModelSource == BillingModelSourceRequested && input.OriginalModel != "" { - billingModel = input.OriginalModel - } - // composite 分组的公开别名(如 all/claude)会经 OriginalModel/ChannelMappedModel - // 进入上面的来源覆盖:任意别名查无价会静默落 $0,含家族词的别名则被价格表的 - // 家族模糊匹配错计(如 Opus 流量按 Sonnet 兜底价)。除非管理员为别名显式配置了 - // 渠道定价(OpenRouter 式自定价),composite 请求一律按实际转发的具体模型计费。 - if apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite { - billingModel = s.compositeBillableModel(ctx, apiKey, billingModel, concreteBillingModel) - } - // 通用兜底(与 OpenAI 路径的 usageBillingModelCandidates 语义对齐): - // 选定模型查不到任何价格时回退到实际转发的具体模型。已定价流量不受影响。 - billingModel = s.billableModelWithFallback(ctx, apiKey, billingModel, result.UpstreamModel, result.Model) + multiplier, imageMultiplier, pricingAt := s.recordUsageMultipliers(ctx, apiKey, user, input.PricingAt) + billingModel := s.recordUsageBillingModel(ctx, apiKey, result, input.ChannelUsageFields) + cacheStorageCost := s.cacheStorageCost(result, billingModel) // 确定 RequestedModel(渠道映射前的原始模型) requestedModel := result.Model @@ -840,7 +808,7 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage input.BillingModelSource, result.UpstreamResponseModel, result.UpstreamResponseModelConflict, - result.ImageCount > 0 || result.AudioUsage != nil || result.SearchCount > 0, + result.ImageCount > 0 || result.AudioUsage != nil || result.SearchCount > 0 || result.CacheStorageTokenHours > 0, ); responseModel != "" && !strings.EqualFold(responseModel, strings.TrimSpace(billingModel)) { if identified, responseChannelPriced := s.hasIdentifiedResponseModelPricing(ctx, responseModel, apiKey); identified { responseCost := s.calculateRecordUsageCost(ctx, result, apiKey, responseModel, multiplier, imageMultiplier, pricingAt) @@ -866,8 +834,9 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage usageLog := s.buildRecordUsageLog(ctx, input, result, apiKey, user, account, subscription, requestedModel, multiplier, imageMultiplier, accountRateMultiplier, billingType, cacheTTLOverridden, cost) - // 计算账号统计定价费用(使用最终上游模型匹配自定义规则) - if apiKey.GroupID != nil { + // 计算账号统计定价费用(使用最终上游模型匹配自定义规则)。纯存储费不是一次模型请求, + // 账号统计成本回落 total_cost(官方存储价)。 + if apiKey.GroupID != nil && !isCacheStorageOnlyResult(result) { applyAccountStatsCost(ctx, usageLog, s.channelService, s.billingService, account.ID, *apiKey.GroupID, result.UpstreamModel, result.Model, // Anthropic's input_tokens excludes cache_read and cache_creation (billed separately); @@ -879,9 +848,10 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage CacheReadTokens: result.Usage.CacheReadInputTokens, ImageOutputTokens: result.Usage.ImageOutputTokens, }, - cost.TotalCost, pricingAt, + cost.TotalCost-cacheStorageCost, pricingAt, accountStatsLongContextPricingEnabled(nil), ) + addCacheStorageToAccountStatsCost(usageLog, cacheStorageCost) } simpleModeKeyRateLimitOnly := simpleModeKeyRateLimitBillingEnabled(s.cfg, apiKey) @@ -927,6 +897,112 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage return nil } +// recordUsageMultipliers 返回 token / 图片售价倍率(用户专属 > 分组默认 > 系统默认,token 倍率叠加高峰因子) +// 与计价时刻;pricingAt 为零值时取当前时刻。 +func (s *GatewayService) recordUsageMultipliers(ctx context.Context, apiKey *APIKey, user *User, pricingAt time.Time) (float64, float64, time.Time) { + multiplier := 1.0 + if s.cfg != nil { + multiplier = s.cfg.Default.RateMultiplier + } + if apiKey.GroupID != nil && apiKey.Group != nil { + multiplier = apiKey.Group.RateMultiplier + if user != nil { + multiplier = s.ResolveUserGroupRateMultiplier(ctx, user.ID, *apiKey.GroupID, multiplier) + } + } + // 高峰因子按请求时刻现算,不并入 getUserGroupRateMultiplier,以免污染 user:group 倍率缓存。 + if pricingAt.IsZero() { + pricingAt = timezone.Now() + } + multiplier, imageMultiplier := computePeakAwareMultipliers(apiKey, multiplier, pricingAt) + return multiplier, imageMultiplier, pricingAt +} + +// recordUsageBillingModel 按计费模型来源、composite 规则与无价兜底确定计费模型。 +func (s *GatewayService) recordUsageBillingModel(ctx context.Context, apiKey *APIKey, result *ForwardResult, fields ChannelUsageFields) string { + concreteBillingModel := forwardResultBillingModel(result.Model, result.UpstreamModel) + billingModel := concreteBillingModel + if fields.BillingModelSource == BillingModelSourceChannelMapped && fields.ChannelMappedModel != "" { + billingModel = fields.ChannelMappedModel + } + if fields.BillingModelSource == BillingModelSourceRequested && fields.OriginalModel != "" { + billingModel = fields.OriginalModel + } + // composite 分组的公开别名(如 all/claude)会经 OriginalModel/ChannelMappedModel + // 进入上面的来源覆盖:任意别名查无价会静默落 $0,含家族词的别名则被价格表的 + // 家族模糊匹配错计(如 Opus 流量按 Sonnet 兜底价)。除非管理员为别名显式配置了 + // 渠道定价(OpenRouter 式自定价),composite 请求一律按实际转发的具体模型计费。 + if apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite { + billingModel = s.compositeBillableModel(ctx, apiKey, billingModel, concreteBillingModel) + } + // 通用兜底(与 OpenAI 路径的 usageBillingModelCandidates 语义对齐): + // 选定模型查不到任何价格时回退到实际转发的具体模型。已定价流量不受影响。 + return s.billableModelWithFallback(ctx, apiKey, billingModel, result.UpstreamModel, result.Model) +} + +// cacheStoragePrice 返回计费模型的显式缓存存储单价;计费模型未配置时依次回退到实际转发模型与请求模型。 +func (s *GatewayService) cacheStoragePrice(result *ForwardResult, billingModel string) float64 { + if s.billingService == nil { + return 0 + } + for _, model := range []string{billingModel, result.UpstreamModel, result.Model} { + if strings.TrimSpace(model) == "" { + continue + } + if price := s.billingService.CacheStoragePricePerTokenHour(model); price > 0 { + return price + } + } + return 0 +} + +// cacheStorageCost 返回 result 的显式缓存存储费(USD,倍率前)。 +func (s *GatewayService) cacheStorageCost(result *ForwardResult, billingModel string) float64 { + if result.CacheStorageTokenHours <= 0 { + return 0 + } + return result.CacheStorageTokenHours * s.cacheStoragePrice(result, billingModel) +} + +// isCacheStorageOnlyResult 判断 result 是否只有显式缓存存储费(延长有效期):不含 token 用量,不算一次模型请求。 +func isCacheStorageOnlyResult(result *ForwardResult) bool { + u := result.Usage + return result.CacheStorageTokenHours > 0 && u.InputTokens == 0 && u.OutputTokens == 0 && + u.CacheCreationInputTokens == 0 && u.CacheReadInputTokens == 0 && u.ImageOutputTokens == 0 && + result.ImageCount == 0 && result.AudioUsage == nil && result.SearchCount == 0 +} + +// CacheStoragePriced 判断 RecordUsage 对 input.Result 采用的计费模型(含回退候选)是否配置了显式缓存存储单价。 +func (s *GatewayService) CacheStoragePriced(ctx context.Context, input *RecordUsageInput) bool { + billingModel := s.recordUsageBillingModel(ctx, input.APIKey, input.Result, input.ChannelUsageFields) + return s.cacheStoragePrice(input.Result, billingModel) > 0 +} + +// QuoteUsageCost 按与 RecordUsage 相同的倍率、计费模型与定价计算 input.Result 的应付金额(倍率后 USD),不记录也不扣费。 +func (s *GatewayService) QuoteUsageCost(ctx context.Context, input *RecordUsageInput) float64 { + user := input.User + if user == nil { + user = input.APIKey.User + } + multiplier, imageMultiplier, pricingAt := s.recordUsageMultipliers(ctx, input.APIKey, user, input.PricingAt) + billingModel := s.recordUsageBillingModel(ctx, input.APIKey, input.Result, input.ChannelUsageFields) + cost := s.calculateRecordUsageCost(ctx, input.Result, input.APIKey, billingModel, multiplier, imageMultiplier, pricingAt) + if cost == nil { + return 0 + } + return cost.ActualCost +} + +// addCacheStorageToAccountStatsCost 把显式缓存存储费按官方价叠加到账号统计成本。 +// 账号统计定价只覆盖 token 部分;统计成本为空时成本统计回落 total_cost,其中已含存储费。 +func addCacheStorageToAccountStatsCost(usageLog *UsageLog, storageCost float64) { + if usageLog == nil || usageLog.AccountStatsCost == nil || storageCost <= 0 { + return + } + cost := *usageLog.AccountStatsCost + storageCost + usageLog.AccountStatsCost = &cost +} + // calculateRecordUsageCost 根据请求类型计算费用。 func (s *GatewayService) calculateRecordUsageCost( ctx context.Context, @@ -964,8 +1040,13 @@ func (s *GatewayService) calculateRecordUsageCost( return s.billingService.CalculateAudioCost(result.AudioUsage.Mode, result.AudioUsage.DurationOrUnits, cfg, multiplier) } - // Token 计费;SearchCount 为叠加 surcharge(不替代 token)。 - tokenCost := s.calculateTokenCost(ctx, result, apiKey, billingModel, multiplier, pricingAt) + // Token 计费;SearchCount 为叠加 surcharge(不替代 token)。纯存储费不是一次模型请求,不计 token / 按次费用。 + var tokenCost *CostBreakdown + if isCacheStorageOnlyResult(result) { + tokenCost = &CostBreakdown{} + } else { + tokenCost = s.calculateTokenCost(ctx, result, apiKey, billingModel, multiplier, pricingAt) + } if result.SearchCount > 0 { price := groupSearchPricePer1kFromAPIKey(apiKey) if price != nil && *price == 0 { @@ -980,6 +1061,14 @@ func (s *GatewayService) calculateRecordUsageCost( tokenCost.ActualCost += searchCost.ActualCost } } + // 显式缓存存储费同为叠加 surcharge,与 token 费用使用同一计费模型与倍率。 + if storageCost := s.cacheStorageCost(result, billingModel); storageCost > 0 { + if tokenCost == nil { + tokenCost = &CostBreakdown{} + } + tokenCost.TotalCost += storageCost + tokenCost.ActualCost += storageCost * multiplier + } return tokenCost } diff --git a/backend/internal/service/gateway_usage_billing_request_id_test.go b/backend/internal/service/gateway_usage_billing_request_id_test.go index 710f64d23..11e7dfcfe 100644 --- a/backend/internal/service/gateway_usage_billing_request_id_test.go +++ b/backend/internal/service/gateway_usage_billing_request_id_test.go @@ -31,9 +31,27 @@ func TestIsForcedUsageBillingRequestID(t *testing.T) { require.True(t, isForcedUsageBillingRequestID("grok-video:task-1")) require.True(t, isForcedUsageBillingRequestID("grok_audio:up-1")) require.True(t, isForcedUsageBillingRequestID("grok_realtime:sess-1")) + require.True(t, isForcedUsageBillingRequestID(GeminiCachedContentCreateUsageRequestID("abc"))) require.False(t, isForcedUsageBillingRequestID("resp_abc")) } +func TestGeminiCachedContentUsageRequestIDs(t *testing.T) { + t.Parallel() + publicID, err := NewGeminiCachedContentPublicID() + require.NoError(t, err) + create := GeminiCachedContentCreateUsageRequestID(publicID) + patch := GeminiCachedContentPatchUsageRequestID(publicID) + require.Equal(t, "gcache:create:"+publicID, create) + require.True(t, strings.HasPrefix(patch, "gcache:patch:"+publicID+":")) + require.NotEqual(t, patch, GeminiCachedContentPatchUsageRequestID(publicID), "每次延长各自唯一") + require.LessOrEqual(t, len(create), 64, "usage_logs.request_id 列长 64") + require.LessOrEqual(t, len(patch), 64, "usage_logs.request_id 列长 64") + + ctx := context.WithValue(context.Background(), ctxkey.ClientRequestID, "client-shared-id") + require.Equal(t, create, resolveUsageBillingRequestID(ctx, create), "缓存费用行不被客户端请求 id 覆盖") + require.Equal(t, patch, resolveUsageBillingRequestID(ctx, patch)) +} + func TestStableGrokAudioBillingRequestID(t *testing.T) { t.Parallel() require.Equal(t, "grok_audio:up-1", StableGrokAudioBillingRequestID("up-1")) diff --git a/backend/internal/service/gateway_websearch_emulation.go b/backend/internal/service/gateway_websearch_emulation.go index bb2f35909..d3716d713 100644 --- a/backend/internal/service/gateway_websearch_emulation.go +++ b/backend/internal/service/gateway_websearch_emulation.go @@ -52,13 +52,27 @@ func getWebSearchManager() *websearch.Manager { // Judgment chain: manager exists → only web_search tool → global enabled → account/channel enabled. // Account-level mode: "enabled" (force on), "disabled" (force off), "default" (follow channel). func (s *GatewayService) shouldEmulateWebSearch(ctx context.Context, account *Account, groupID *int64, body []byte) bool { - if getWebSearchManager() == nil { + return shouldEmulateWebSearchFor(ctx, s.settingService, s.channelService, account, groupID, body) +} + +// shouldEmulateWebSearchFor is shared by the Anthropic gateway and the OpenAI +// gateway's /v1/messages path. +func shouldEmulateWebSearchFor( + ctx context.Context, settingService *SettingService, channelService *ChannelService, + account *Account, groupID *int64, body []byte, +) bool { + if getWebSearchManager() == nil || account == nil || settingService == nil { + return false + } + // OpenAI OAuth/setup-token accounts retain native search regardless of + // channel configuration. Only API key accounts opt into emulation. + if account.Platform == PlatformOpenAI && account.Type != AccountTypeAPIKey { return false } if !isOnlyWebSearchToolInBody(body) { return false } - if !s.settingService.IsWebSearchEmulationEnabled(ctx) { + if !settingService.IsWebSearchEmulationEnabled(ctx) { return false } @@ -69,10 +83,10 @@ func (s *GatewayService) shouldEmulateWebSearch(ctx context.Context, account *Ac case WebSearchModeDisabled: return false default: // "default" → follow channel config - if groupID == nil || s.channelService == nil { + if groupID == nil || channelService == nil { return false } - ch, err := s.channelService.GetChannelForGroup(ctx, *groupID) + ch, err := channelService.GetChannelForGroup(ctx, *groupID) if err != nil || ch == nil { return false } @@ -143,14 +157,21 @@ func extractWebSearchTextFromContent(content gjson.Result) string { func (s *GatewayService) handleWebSearchEmulation( ctx context.Context, c *gin.Context, account *Account, parsed *ParsedRequest, ) (*ForwardResult, error) { - startTime := time.Now() - // Release the serial queue lock immediately — we don't need upstream. if parsed.OnUpstreamAccepted != nil { parsed.OnUpstreamAccepted() } + return writeEmulatedWebSearch(ctx, c, account, parsed.Body.Bytes(), parsed.Model, parsed.Stream) +} + +// writeEmulatedWebSearch runs the search for the last user message and writes +// an Anthropic Messages response (SSE when stream is true). +func writeEmulatedWebSearch( + ctx context.Context, c *gin.Context, account *Account, body []byte, model string, stream bool, +) (*ForwardResult, error) { + startTime := time.Now() - query := extractSearchQueryFromBody(parsed.Body.Bytes()) + query := extractSearchQueryFromBody(body) if query == "" { return nil, fmt.Errorf("web search emulation: no query found in messages") } @@ -173,12 +194,11 @@ func (s *GatewayService) handleWebSearchEmulation( slog.Info("web search emulation: search completed", "provider", providerName, "results_count", len(resp.Results)) - model := parsed.Model if model == "" { model = defaultWebSearchModel } - if parsed.Stream { + if stream { return writeWebSearchStreamResponse(c, query, resp, model, startTime) } return writeWebSearchNonStreamResponse(c, query, resp, model, startTime) diff --git a/backend/internal/service/gateway_websearch_emulation_test.go b/backend/internal/service/gateway_websearch_emulation_test.go index e7eb7c2b5..06be3fe50 100644 --- a/backend/internal/service/gateway_websearch_emulation_test.go +++ b/backend/internal/service/gateway_websearch_emulation_test.go @@ -378,3 +378,88 @@ func TestShouldEmulateWebSearch_DefaultMode_NilChannelService(t *testing.T) { // nil channelService + default mode → returns false require.False(t, svc.shouldEmulateWebSearch(context.Background(), account, &groupID, webSearchToolBody)) } + +func TestShouldEmulateWebSearchFor_OpenAIAPIKeyAccountEnabled(t *testing.T) { + mgr := websearch.NewManager([]websearch.ProviderConfig{{Type: "brave", APIKey: "k"}}, nil) + SetWebSearchManager(mgr) + defer SetWebSearchManager(nil) + + setGlobalWebSearchConfig(&WebSearchEmulationConfig{ + Enabled: true, + Providers: []WebSearchProviderConfig{{Type: "brave", APIKey: "k"}}, + }) + defer clearGlobalWebSearchConfig() + + settingSvc := newSettingServiceForWebSearchTest(true) + account := &Account{ + ID: 1, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Extra: map[string]any{featureKeyWebSearchEmulation: WebSearchModeEnabled}, + } + groupID := int64(0) + require.True(t, shouldEmulateWebSearchFor(context.Background(), settingSvc, nil, account, &groupID, webSearchToolBody)) + require.False(t, shouldEmulateWebSearchFor(context.Background(), settingSvc, nil, account, &groupID, nonWebSearchToolBody)) +} + +// Exercise the shared interception gate, including channel inheritance. +func TestShouldEmulateWebSearchFor_AccountChannelModes(t *testing.T) { + previousManager := getWebSearchManager() + previousConfig := webSearchEmulationCache.Load() + SetWebSearchManager(websearch.NewManager([]websearch.ProviderConfig{{Type: "brave", APIKey: "k"}}, nil)) + t.Cleanup(func() { + SetWebSearchManager(previousManager) + if previousConfig == nil { + clearGlobalWebSearchConfig() + } else { + webSearchEmulationCache.Store(previousConfig) + } + }) + + settingSvc := newSettingServiceForWebSearchTest(true) + groupID := int64(42) + for _, platform := range []string{PlatformOpenAI, PlatformAnthropic} { + for _, accountType := range []string{AccountTypeAPIKey, AccountTypeOAuth, AccountTypeSetupToken} { + for _, mode := range []string{WebSearchModeDefault, WebSearchModeEnabled, WebSearchModeDisabled} { + for _, channelEnabled := range []bool{false, true} { + channelMode := "channel_off" + if channelEnabled { + channelMode = "channel_on" + } + t.Run(platform+"/"+accountType+"/"+mode+"/"+channelMode, func(t *testing.T) { + account := &Account{ + Platform: platform, Type: accountType, + Extra: map[string]any{featureKeyWebSearchEmulation: mode}, + } + channelSvc := newChannelServiceWithCache(groupID, &Channel{ + ID: 10, Status: StatusActive, + FeaturesConfig: map[string]any{ + featureKeyWebSearchEmulation: map[string]any{platform: channelEnabled}, + }, + }) + want := channelEnabled + if accountType == AccountTypeAPIKey { + switch mode { + case WebSearchModeEnabled: + want = true + case WebSearchModeDisabled: + want = false + } + } else if platform == PlatformOpenAI { + want = false + } + for _, globalEnabled := range []bool{false, true} { + setGlobalWebSearchConfig(&WebSearchEmulationConfig{ + Enabled: globalEnabled, + Providers: []WebSearchProviderConfig{{Type: "brave", APIKey: "k"}}, + }) + require.Equal(t, globalEnabled && want, shouldEmulateWebSearchFor( + context.Background(), settingSvc, channelSvc, account, &groupID, webSearchToolBody), + "globalEnabled=%v", globalEnabled) + } + }) + } + } + } + } +} diff --git a/backend/internal/service/gemini_cache_storage_pricing.go b/backend/internal/service/gemini_cache_storage_pricing.go new file mode 100644 index 000000000..c08ed2f68 --- /dev/null +++ b/backend/internal/service/gemini_cache_storage_pricing.go @@ -0,0 +1,72 @@ +package service + +import ( + "slices" + "strings" +) + +// Gemini 显式上下文缓存存储的内置官方单价(USD / token / 小时,Standard 档)。 +// 存储价与上下文长度无关(≤200K 与 >200K 同价);Priority 档的更高存储价不在此列。 +// 来源:https://ai.google.dev/gemini-api/docs/pricing +// 与 https://cloud.google.com/gemini-enterprise-agent-platform/generative-ai/pricing +const ( + geminiProCacheStoragePrice = 4.5e-6 // $4.50 / 1M tokens / 小时 + geminiFlashCacheStoragePrice = 1e-6 // $1.00 / 1M tokens / 小时,Flash-Lite 同价 + + // 3.6/3.7/3.8 Flash 的优惠价 $0.50 / 1M tokens / 小时,有效期至 2026-12-31, + // 2027-01-01 起恢复为 geminiFlashCacheStoragePrice。AI Studio 价目页直接标注该优惠价; + // Vertex 价目页存储价标 $1.00,优惠以「按该模型净消费返还 50% 抵扣金」发放, + // 官方未明确存储费是否在返还范围内,两类账号统一按优惠价计。 + geminiFlashPromoCacheStoragePrice = 0.5e-6 +) + +// geminiCacheStorageModelPrices 是已发布型号的存储单价。模型名等于前缀,或以「前缀-」开头 +// (-preview、-customtools、-001 等变体)即命中;更具体的前缀排在前面。 +var geminiCacheStorageModelPrices = []struct { + prefix string + price float64 +}{ + {"gemini-3.8-flash-cyber", geminiFlashCacheStoragePrice}, + {"gemini-3.8-flash", geminiFlashPromoCacheStoragePrice}, + {"gemini-3.7-flash", geminiFlashPromoCacheStoragePrice}, + {"gemini-3.6-flash", geminiFlashPromoCacheStoragePrice}, + {"gemini-3.5-flash-lite", geminiFlashCacheStoragePrice}, + {"gemini-3.5-flash", geminiFlashCacheStoragePrice}, + {"gemini-3.1-flash-lite", geminiFlashCacheStoragePrice}, + {"gemini-3.1-pro", geminiProCacheStoragePrice}, + {"gemini-3-flash", geminiFlashCacheStoragePrice}, + {"gemini-3-pro", geminiProCacheStoragePrice}, + {"gemini-2.5-flash-lite", geminiFlashCacheStoragePrice}, + {"gemini-2.5-flash", geminiFlashCacheStoragePrice}, + {"gemini-2.5-pro", geminiProCacheStoragePrice}, + {"gemini-2.0-flash-lite", geminiFlashCacheStoragePrice}, + {"gemini-2.0-flash", geminiFlashCacheStoragePrice}, +} + +// builtinGeminiCacheStoragePrice 返回内置的显式缓存存储单价:先按已发布型号匹配,未命中时按系列兜底, +// Pro 系列取 geminiProCacheStoragePrice,Flash 与 Flash-Lite 系列取 geminiFlashCacheStoragePrice(标准价, +// 不套用优惠价)。其他 Gemini 模型与非 Gemini 模型返回 0。 +func builtinGeminiCacheStoragePrice(model string) float64 { + name := lastSegment(strings.ToLower(strings.TrimSpace(model))) + if !strings.HasPrefix(name, "gemini-") { + return 0 + } + parts := strings.Split(name, "-") + lite := slices.Contains(parts, "lite") + for _, entry := range geminiCacheStorageModelPrices { + // Flash-Lite 变体只匹配 Flash-Lite 条目:gemini-3.8-flash-lite 不能落到 3.8 Flash 的优惠价。 + if lite != strings.HasSuffix(entry.prefix, "-lite") { + continue + } + if name == entry.prefix || strings.HasPrefix(name, entry.prefix+"-") { + return entry.price + } + } + switch { + case slices.Contains(parts, "pro"): + return geminiProCacheStoragePrice + case slices.Contains(parts, "flash"): + return geminiFlashCacheStoragePrice + } + return 0 +} diff --git a/backend/internal/service/gemini_cache_storage_pricing_test.go b/backend/internal/service/gemini_cache_storage_pricing_test.go new file mode 100644 index 000000000..1090f063d --- /dev/null +++ b/backend/internal/service/gemini_cache_storage_pricing_test.go @@ -0,0 +1,80 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestBuiltinGeminiCacheStoragePrice(t *testing.T) { + for _, tc := range []struct { + model string + want float64 + }{ + // 已发布型号 + {"gemini-3.8-flash", 0.5e-6}, + {"gemini-3.7-flash", 0.5e-6}, + {"gemini-3.6-flash", 0.5e-6}, + {"gemini-3.8-flash-cyber", 1e-6}, + {"gemini-3.5-flash", 1e-6}, + {"gemini-3.5-flash-lite", 1e-6}, + {"gemini-3.1-flash-lite", 1e-6}, + {"gemini-3.1-pro-preview", 4.5e-6}, + {"gemini-3.1-pro-preview-customtools", 4.5e-6}, + {"gemini-3-flash-preview", 1e-6}, + {"gemini-3-pro-preview", 4.5e-6}, + {"gemini-2.5-pro", 4.5e-6}, + {"gemini-2.5-flash", 1e-6}, + {"gemini-2.5-flash-lite", 1e-6}, + {"gemini-2.0-flash-001", 1e-6}, + {"gemini-2.0-flash-lite-001", 1e-6}, + // 资源名与大小写 + {"models/gemini-3.8-flash", 0.5e-6}, + {"projects/p/locations/global/publishers/google/models/gemini-2.5-pro", 4.5e-6}, + {" Gemini-3.8-Flash ", 0.5e-6}, + // 系列兜底:未发布型号与别名按标准价 + {"gemini-3.9-flash", 1e-6}, + {"gemini-3.9-flash-lite", 1e-6}, + {"gemini-3.8-flash-lite", 1e-6}, + {"gemini-3.9-pro-preview", 4.5e-6}, + {"gemini-flash-latest", 1e-6}, + {"gemini-flash-lite-latest", 1e-6}, + {"gemini-pro-latest", 4.5e-6}, + // 无存储价(Gemini 4 Argon 仅支持隐式缓存) + {"gemini-4-argon", 0}, + {"gemini-4-argon-high", 0}, + {"gemini-4-argon-cyber-permissive", 0}, + {"gemini-embedding-001", 0}, + {"gemini-unknown-model", 0}, + {"claude-sonnet-5-5", 0}, + {"", 0}, + } { + require.InDelta(t, tc.want, builtinGeminiCacheStoragePrice(tc.model), 1e-15, tc.model) + } +} + +func TestCacheStoragePricePerTokenHourPriority(t *testing.T) { + pricing := &PricingService{} + data, err := pricing.parsePricingData([]byte(`{ + "gemini-3.8-flash":{"litellm_provider":"gemini","input_cost_per_token":0.00000075,"output_cost_per_token":0.00000375, + "cache_storage_cost_per_token_per_hour":0.000002}, + "gemini-3.9-flash":{"litellm_provider":"gemini","input_cost_per_token":0.0000015,"output_cost_per_token":0.0000075, + "cache_storage_cost_per_token_per_hour":0.0000007}, + "gemini-2.5-pro":{"litellm_provider":"gemini","input_cost_per_token":0.00000125,"output_cost_per_token":0.00001}}`)) + require.NoError(t, err) + pricing.pricingData = data + billing := NewBillingService(&config.Config{}, pricing) + + require.InDelta(t, 2e-6, billing.CacheStoragePricePerTokenHour("gemini-3.8-flash"), 1e-15, "价格表配置值优先于内置型号价") + require.InDelta(t, 0.7e-6, billing.CacheStoragePricePerTokenHour("gemini-3.9-flash"), 1e-15, "价格表配置值优先于内置系列兜底价") + require.InDelta(t, 4.5e-6, billing.CacheStoragePricePerTokenHour("gemini-2.5-pro"), 1e-15, "价格表条目缺存储价时取内置型号价") + require.InDelta(t, 0.5e-6, billing.CacheStoragePricePerTokenHour("gemini-3.7-flash"), 1e-15, "价格表无条目时取内置型号价") + require.InDelta(t, 4.5e-6, billing.CacheStoragePricePerTokenHour("gemini-3.9-pro"), 1e-15, "内置型号未命中时取系列兜底价") + require.Zero(t, billing.CacheStoragePricePerTokenHour("customer-alias")) + + noCatalog := NewBillingService(&config.Config{}, nil) + require.InDelta(t, 0.5e-6, noCatalog.CacheStoragePricePerTokenHour("gemini-3.8-flash"), 1e-15, "无价格服务时取内置价") +} diff --git a/backend/internal/service/gemini_cached_content.go b/backend/internal/service/gemini_cached_content.go new file mode 100644 index 000000000..92d7daf6f --- /dev/null +++ b/backend/internal/service/gemini_cached_content.go @@ -0,0 +1,1226 @@ +package service + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/base32" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "net/http" + "net/url" + "regexp" + "slices" + "strconv" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/MACOS-DO/sub4api/internal/config" + infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors" + "github.com/MACOS-DO/sub4api/internal/pkg/geminicli" + "github.com/MACOS-DO/sub4api/internal/pkg/logger" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +const ( + // GeminiCachedContentNamePrefix 是缓存资源名前缀,网关与上游 AI Studio 一致。 + GeminiCachedContentNamePrefix = "cachedContents/" + // GeminiCachedContentNotFoundMessage 与上游对不存在、已过期或无权访问的缓存返回的文案一致。 + GeminiCachedContentNotFoundMessage = "CachedContent not found (or permission denied)" + // GeminiCachedContentNotFoundResponse 是网关对引用不存在缓存统一返回的 403 响应体(与 AI Studio 上游一致)。 + GeminiCachedContentNotFoundResponse = `{"error":{"code":403,"message":"CachedContent not found (or permission denied)","status":"PERMISSION_DENIED"}}` + + geminiCachedContentDefaultTTL = time.Hour + geminiCachedContentDefaultMaxTTL = 24 * time.Hour + geminiCachedContentDisplayNameMaxRunes = 128 + geminiCachedContentUpstreamTagPrefix = "s2a-" + geminiCachedContentResponseMaxBytes = 4 << 20 + geminiCachedContentUpstreamTimeout = 5 * time.Minute + geminiCachedContentOfficialHost = "generativelanguage.googleapis.com" + + // geminiCachedContentMutationUpstreamTimeout 是修改 / 删除上游缓存的单次调用超时。 + geminiCachedContentMutationUpstreamTimeout = 30 * time.Second + // geminiCachedContentMutationLease 是修改意图的租约时长,须覆盖持有者在租约内的全部操作 + // (一次上游修改与一次落库,或恢复流程的一次上游回滚与一次落库),租约过期后持有者不会再改动上游。 + geminiCachedContentMutationLease = 2 * time.Minute + // geminiCachedContentMutationRecoveryInterval / geminiCachedContentMutationRecoveryBatch 约束后台回滚恢复的节奏; + // geminiCachedContentMutationRecoveryTimeout 是恢复单条记录的落库超时,与一次上游回滚合计不超过租约。 + geminiCachedContentMutationRecoveryInterval = time.Minute + geminiCachedContentMutationRecoveryBatch = 50 + geminiCachedContentMutationRecoveryTimeout = time.Minute + // geminiCachedContentMutationAbandonGrace 是判定"上游缓存必已自行过期"时额外容忍的网关与上游时钟偏差。 + geminiCachedContentMutationAbandonGrace = time.Hour + + // GeminiCachedContentListDefaultPageSize / GeminiCachedContentListMaxPageSize 约束 list 分页。 + GeminiCachedContentListDefaultPageSize = 50 + GeminiCachedContentListMaxPageSize = 1000 +) + +var ( + ErrGeminiCachedContentNotFound = infraerrors.New(http.StatusNotFound, "GEMINI_CACHED_CONTENT_NOT_FOUND", "gemini cached content not found") + ErrGeminiCachedContentExists = infraerrors.New(http.StatusConflict, "GEMINI_CACHED_CONTENT_EXISTS", "gemini cached content already exists") + // ErrGeminiCachedContentMutationConflict 表示同一缓存有进行中的修改、到期时间已被其他修改改变,或修改意图已不属于调用方。 + ErrGeminiCachedContentMutationConflict = infraerrors.New(http.StatusConflict, "GEMINI_CACHED_CONTENT_MUTATION_CONFLICT", "another update to this cached content is in progress") + // ErrGeminiCachedContentRequestNotSent 表示上游缓存请求在发出前失败(地址、凭据等),上游状态未被改变。 + ErrGeminiCachedContentRequestNotSent = errors.New("gemini cached content request was not sent") + // errGeminiCachedContentAccountUnsupported 表示持有缓存的账号存在,但当前不支持显式缓存(能力被关闭或认证方式不支持)。 + errGeminiCachedContentAccountUnsupported = errors.New("gemini cached content account does not support explicit caching") + + geminiCachedContentPublicIDPattern = regexp.MustCompile(`^[a-z0-9]{1,64}$`) + geminiCachedContentAIStudioName = regexp.MustCompile(`^cachedContents/[A-Za-z0-9_-]+$`) + geminiCachedContentVertexName = regexp.MustCompile(`^projects/[A-Za-z0-9_.:-]+/locations/([a-z0-9-]+)/cachedContents/[A-Za-z0-9_-]+$`) + geminiCachedContentPublicIDEncoding = base32.StdEncoding.WithPadding(base32.NoPadding) +) + +// GeminiCachedContent 是网关对外暴露的显式缓存与上游资源、账号、归属的绑定。 +type GeminiCachedContent struct { + ID int64 + PublicID string + UserID int64 + APIKeyID int64 + GroupID int64 + // AccountID 是持有上游缓存的账号;引用缓存的请求只能发往该账号。 + AccountID int64 + UpstreamName string + // Model 是客户端视角的模型名(渠道映射后,不含 models/ 前缀),引用缓存的请求模型必须与之字面一致。 + Model string + // UpstreamModel 是创建时发给上游的模型资源名。 + UpstreamModel string + DisplayName string + TotalTokenCount int64 + ExpireTime time.Time + // ChannelUsage 是创建时的渠道计费口径(渠道 ID、请求模型、计费模型来源),延长有效期按同一口径计费。 + ChannelUsage ChannelUsageFields + CreatedAt time.Time + UpdatedAt time.Time +} + +// PublicName 返回客户端可见的缓存资源名。 +func (c *GeminiCachedContent) PublicName() string { + return GeminiCachedContentNamePrefix + c.PublicID +} + +// UpstreamModelID 返回上游模型资源名的末段(裸模型名),用于计费定价查找。 +func (c *GeminiCachedContent) UpstreamModelID() string { + model := c.UpstreamModel + if i := strings.LastIndex(model, "/"); i >= 0 { + model = model[i+1:] + } + return model +} + +// GeminiCachedContentRepository 持久化显式缓存绑定。所有读取都过滤已软删除的记录。 +type GeminiCachedContentRepository interface { + Create(ctx context.Context, record *GeminiCachedContent) error + GetForOwner(ctx context.Context, apiKeyID int64, publicID string) (*GeminiCachedContent, error) + // ListForOwner 按 id 倒序返回分组内 expire_time 晚于 activeAt 的记录;beforeID>0 时只返回 id 更小的记录。 + ListForOwner(ctx context.Context, apiKeyID, groupID int64, activeAt time.Time, beforeID int64, limit int) ([]*GeminiCachedContent, error) + // BeginMutation 在记录没有修改意图且 expire_time 仍为 baseline 时登记修改意图(token 与自数据库当前时间起的租约), + // 返回是否登记成功;记录不存在或已删除时返回 ErrGeminiCachedContentNotFound。 + BeginMutation(ctx context.Context, id int64, baseline time.Time, token string, lease time.Duration) (bool, error) + // TakeOverStaleMutation 把记录上租约已过期的修改意图换成 token 与新租约并返回记录;没有可接管的意图时返回 nil。 + TakeOverStaleMutation(ctx context.Context, id int64, token string, lease time.Duration) (*GeminiCachedContent, error) + // CommitMutation 由 token 的持有者写入新的到期时间并清除修改意图;token 已失效或记录已删除时返回 + // ErrGeminiCachedContentMutationConflict。 + CommitMutation(ctx context.Context, id int64, token string, expireTime time.Time) error + // ReleaseMutation 由 token 的持有者清除修改意图,不改变到期时间。 + ReleaseMutation(ctx context.Context, id int64, token string) error + // ListStaleMutations 返回修改意图租约已过期的未删除记录 id。 + ListStaleMutations(ctx context.Context, limit int) ([]int64, error) + SoftDelete(ctx context.Context, id int64) error +} + +// IsGeminiExplicitCacheAccountType 只按平台与账号类型判断是否可能支持显式缓存,适用于调度快照账号。 +func IsGeminiExplicitCacheAccountType(account *Account) bool { + if account == nil || account.Platform != PlatformGemini { + return false + } + return account.Type == AccountTypeAPIKey || account.Type == AccountTypeServiceAccount +} + +// IsGeminiExplicitCacheAccount 判断完整账号是否支持显式缓存:官方地址的 AI Studio API Key 账号、 +// 声明上游支持显式缓存的自定义地址 API Key 账号,或 Service Account JSON 认证的 Vertex 账号。 +// API Key 认证的 Vertex 账号不参与显式缓存:Vertex 缓存接口只接受 OAuth access token,不接受 API Key。 +func IsGeminiExplicitCacheAccount(account *Account) bool { + if !IsGeminiExplicitCacheAccountType(account) { + return false + } + if account.Type == AccountTypeServiceAccount { + return !account.IsVertexAPIKey() + } + if strings.TrimSpace(account.GetCredential("api_key")) == "" { + return false + } + return isOfficialGeminiAPIBaseURL(account.GetCredential("base_url")) || account.GeminiExplicitCacheUpstreamEnabled() +} + +// GeminiExplicitCacheUpstreamCredentialKey / GeminiExplicitCacheUpstreamMaxTTLCredentialKey 是 API Key 账号凭据里 +// 声明上游实现显式缓存接口及其有效期上限的键;调度快照投影须保留它们,候选过滤才能直接判定账号是否支持显式缓存。 +const ( + GeminiExplicitCacheUpstreamCredentialKey = "explicit_cache_upstream" + GeminiExplicitCacheUpstreamMaxTTLCredentialKey = "explicit_cache_upstream_max_ttl_seconds" +) + +// GeminiExplicitCacheUpstreamEnabled 判断 API Key 账号是否声明其上游实现了显式缓存接口, +// 并保证缓存只在创建它的上游账号上使用(本系统同版本网关)。 +func (a *Account) GeminiExplicitCacheUpstreamEnabled() bool { + if a == nil || a.Type != AccountTypeAPIKey || a.Credentials == nil { + return false + } + enabled, _ := a.Credentials[GeminiExplicitCacheUpstreamCredentialKey].(bool) + return enabled +} + +// GeminiExplicitCacheUpstreamMaxTTL 返回上游网关允许的缓存最长有效期;0 表示未配置。 +func (a *Account) GeminiExplicitCacheUpstreamMaxTTL() time.Duration { + if !a.GeminiExplicitCacheUpstreamEnabled() { + return 0 + } + var seconds float64 + switch v := a.Credentials[GeminiExplicitCacheUpstreamMaxTTLCredentialKey].(type) { + case float64: + seconds = v + case int: + seconds = float64(v) + case int64: + seconds = float64(v) + case json.Number: + seconds, _ = v.Float64() + case string: + seconds, _ = strconv.ParseFloat(strings.TrimSpace(v), 64) + } + if seconds <= 0 || math.IsNaN(seconds) || math.IsInf(seconds, 0) { + return 0 + } + return time.Duration(seconds) * time.Second +} + +// geminiCachedContentAPIBase 返回 API Key 账号缓存接口的上游根地址。 +func geminiCachedContentAPIBase(account *Account) string { + if isOfficialGeminiAPIBaseURL(account.GetCredential("base_url")) { + return geminicli.AIStudioBaseURL + } + return account.GetGeminiBaseURL(geminicli.AIStudioBaseURL) +} + +func isOfficialGeminiAPIBaseURL(raw string) bool { + raw = strings.TrimSpace(raw) + if raw == "" { + return true + } + u, err := url.Parse(raw) + if err != nil { + return false + } + path := strings.TrimRight(u.Path, "/") + return strings.EqualFold(u.Scheme, "https") && + strings.EqualFold(u.Hostname(), geminiCachedContentOfficialHost) && + u.Port() == "" && path == "" && u.RawQuery == "" +} + +// NewGeminiCachedContentPublicID 生成 40 位小写字母数字的缓存 ID。 +func NewGeminiCachedContentPublicID() (string, error) { + var b [25]byte + if _, err := rand.Read(b[:]); err != nil { + return "", err + } + return strings.ToLower(geminiCachedContentPublicIDEncoding.EncodeToString(b[:])), nil +} + +// GeminiCachedContentUsageRequestIDPrefix 是显式缓存创建 / 延长费用在 usage_logs.request_id 中的固定前缀: +// 这类费用行是独立的扣费事件,不随客户端或网关请求 id 变化,按缓存 ID 即可检索一个缓存的全部费用行。 +// 两种格式都不超过 request_id 列的 64 字符。 +const GeminiCachedContentUsageRequestIDPrefix = "gcache:" + +// GeminiCachedContentCreateUsageRequestID 返回创建费用的 request_id("gcache:create:{id}");一个缓存只创建一次。 +func GeminiCachedContentCreateUsageRequestID(publicID string) string { + return GeminiCachedContentUsageRequestIDPrefix + "create:" + publicID +} + +// GeminiCachedContentPatchUsageRequestID 返回一次延长费用的 request_id("gcache:patch:{id}:{8 位随机}");每次延长各自唯一。 +func GeminiCachedContentPatchUsageRequestID(publicID string) string { + var b [5]byte + if _, err := rand.Read(b[:]); err != nil { + return GeminiCachedContentUsageRequestIDPrefix + "patch:" + publicID + ":" + strconv.FormatInt(time.Now().UnixNano()%(1<<40), 32) + } + return GeminiCachedContentUsageRequestIDPrefix + "patch:" + publicID + ":" + strings.ToLower(geminiCachedContentPublicIDEncoding.EncodeToString(b[:])) +} + +// ParseGeminiCachedContentPublicID 从 "cachedContents/{id}" 或裸 id 中解析缓存 ID。 +func ParseGeminiCachedContentPublicID(name string) (string, bool) { + id := strings.TrimPrefix(strings.TrimSpace(name), GeminiCachedContentNamePrefix) + if !geminiCachedContentPublicIDPattern.MatchString(id) { + return "", false + } + return id, true +} + +type geminiCachedContentBoundCtxKey struct{} + +// WithGeminiCachedContentBound 标记请求引用了显式缓存并已硬绑定到持有账号。 +func WithGeminiCachedContentBound(ctx context.Context) context.Context { + return context.WithValue(ctx, geminiCachedContentBoundCtxKey{}, true) +} + +func geminiCachedContentBoundFromContext(ctx context.Context) bool { + if ctx == nil { + return false + } + bound, _ := ctx.Value(geminiCachedContentBoundCtxKey{}).(bool) + return bound +} + +// isGeminiBoundCacheUpstreamPassthrough 判断绑定缓存的请求在上游网关账号上收到的错误是否只反映 +// 上游持有缓存的那个账号的状态(429 / 5xx),不应据此限流或重试本账号。 +func isGeminiBoundCacheUpstreamPassthrough(ctx context.Context, account *Account, statusCode int) bool { + if statusCode != http.StatusTooManyRequests && statusCode < http.StatusInternalServerError { + return false + } + return account.GeminiExplicitCacheUpstreamEnabled() && geminiCachedContentBoundFromContext(ctx) +} + +// GeminiCachedContentReference 是请求体中引用显式缓存的位置。 +type GeminiCachedContentReference struct { + Name string + Paths []string +} + +var geminiCachedContentReferencePaths = []string{"cachedContent", "generateContentRequest.cachedContent"} + +// FindGeminiCachedContentReference 返回 generateContent / countTokens 请求体中引用的缓存名;未引用时返回 nil。 +// 引用键重复、使用 snake_case 写法或多个位置引用不同缓存时返回错误,保证校验与改写的引用就是发往上游的引用。 +func FindGeminiCachedContentReference(body []byte) (*GeminiCachedContentReference, error) { + root := gjson.ParseBytes(body) + if !root.IsObject() { + return nil, nil + } + if err := checkGeminiCachedContentReferenceKeys(root, "cachedContent", "generateContentRequest"); err != nil { + return nil, err + } + if nested := root.Get("generateContentRequest"); nested.IsObject() { + if err := checkGeminiCachedContentReferenceKeys(nested, "cachedContent"); err != nil { + return nil, err + } + } + var ref *GeminiCachedContentReference + for _, path := range geminiCachedContentReferencePaths { + value := gjson.GetBytes(body, path) + if !value.Exists() || value.Type == gjson.Null { + continue + } + if value.Type != gjson.String { + return nil, errors.New("cachedContent must be a string") + } + name := strings.TrimSpace(value.String()) + if name == "" { + continue + } + if ref == nil { + ref = &GeminiCachedContentReference{Name: name} + } else if ref.Name != name { + return nil, errors.New("conflicting cachedContent references") + } + ref.Paths = append(ref.Paths, path) + } + return ref, nil +} + +// checkGeminiCachedContentReferenceKeys 拒绝对象中重复出现的 uniqueKeys 与 snake_case 写法的缓存引用键。 +func checkGeminiCachedContentReferenceKeys(obj gjson.Result, uniqueKeys ...string) error { + seen := make(map[string]bool, len(uniqueKeys)) + var err error + obj.ForEach(func(key, value gjson.Result) bool { + name := key.String() + switch { + case name == "cached_content": + err = errors.New("cached_content is not supported, use cachedContent") + case name == "generate_content_request" && (value.Get("cachedContent").Exists() || value.Get("cached_content").Exists()): + err = errors.New("generate_content_request is not supported with cachedContent, use generateContentRequest") + case slices.Contains(uniqueKeys, name): + if seen[name] { + err = fmt.Errorf("duplicate %s field", name) + } + seen[name] = true + } + return err == nil + }) + return err +} + +// RewriteGeminiCachedContentReference 把请求体中的缓存引用改写为上游资源名。 +func RewriteGeminiCachedContentReference(body []byte, ref *GeminiCachedContentReference, upstreamName string) ([]byte, error) { + if ref == nil { + return body, nil + } + out := body + for _, path := range ref.Paths { + next, err := sjson.SetBytes(out, path, upstreamName) + if err != nil { + return nil, err + } + out = next + } + return out, nil +} + +// GeminiCachedContentCreateRequest 是校验后的创建请求。 +type GeminiCachedContentCreateRequest struct { + // Model 为客户端请求的模型名(不含 models/ 前缀)。 + Model string + TTL time.Duration + DisplayName string + // ttlExplicit 表示客户端显式指定了 ttl 或 expireTime。 + ttlExplicit bool + payload map[string]any +} + +// TTLSeconds 返回发往上游的整秒 TTL。 +func (r *GeminiCachedContentCreateRequest) TTLSeconds() int64 { + return int64(math.Ceil(r.TTL.Seconds())) +} + +// TTLForAccount 返回在账号上创建缓存使用的整秒有效期。账号上限小于请求有效期时: +// 未显式指定有效期的请求按账号上限创建,显式指定的返回 false(该账号不可用)。 +func (r *GeminiCachedContentCreateRequest) TTLForAccount(account *Account) (time.Duration, bool) { + ttl := time.Duration(r.TTLSeconds()) * time.Second + limit := account.GeminiExplicitCacheUpstreamMaxTTL() + if limit <= 0 || ttl <= limit { + return ttl, true + } + if r.ttlExplicit { + return 0, false + } + return limit, true +} + +// ParseGeminiCachedContentCreateRequest 校验创建请求。未指定有效期时使用上游默认的 1 小时(不超过 maxTTL)。 +// 数字按原文保留,重新编码后发往上游的内容与请求一致。 +func ParseGeminiCachedContentCreateRequest(body []byte, now time.Time, maxTTL time.Duration) (*GeminiCachedContentCreateRequest, error) { + payload, err := decodeGeminiCachedContentPayload(body) + if err != nil { + return nil, err + } + rawModel, _ := payload["model"].(string) + model := strings.TrimPrefix(strings.TrimSpace(rawModel), "models/") + if model == "" { + return nil, errors.New("model is required") + } + if !IsSafeGeminiModelPathSegment(model) { + return nil, errors.New("model name must be in the format 'models/{model_name}'") + } + + ttl, err := parseGeminiCachedContentExpiration(payload, now) + if err != nil { + return nil, err + } + ttlExplicit := ttl > 0 + if ttl == 0 { + ttl = geminiCachedContentDefaultTTL + if maxTTL > 0 && ttl > maxTTL { + ttl = maxTTL + } + } + if maxTTL > 0 && ttl > maxTTL { + return nil, fmt.Errorf("ttl exceeds the maximum allowed %ds", int64(maxTTL.Seconds())) + } + + displayName := "" + if raw, ok := payload["displayName"]; ok && raw != nil { + s, ok := raw.(string) + if !ok { + return nil, errors.New("displayName must be a string") + } + if utf8.RuneCountInString(s) > geminiCachedContentDisplayNameMaxRunes { + return nil, fmt.Errorf("displayName must be at most %d characters", geminiCachedContentDisplayNameMaxRunes) + } + displayName = s + } + + for _, key := range []string{"name", "model", "displayName", "ttl", "expireTime", "createTime", "updateTime", "usageMetadata"} { + delete(payload, key) + } + return &GeminiCachedContentCreateRequest{Model: model, TTL: ttl, DisplayName: displayName, ttlExplicit: ttlExplicit, payload: payload}, nil +} + +// ParseGeminiCachedContentPatchRequest 校验更新请求,只允许修改有效期,返回新的 TTL(自 now 起算)。 +func ParseGeminiCachedContentPatchRequest(body []byte, updateMask string, now time.Time, maxTTL time.Duration) (time.Duration, error) { + payload, err := decodeGeminiCachedContentPayload(body) + if err != nil { + return 0, err + } + for key := range payload { + switch key { + case "ttl", "expireTime", "name": + default: + return 0, errors.New("can not update immutable fields (model or display_name)") + } + } + for _, field := range strings.Split(updateMask, ",") { + switch strings.TrimSpace(field) { + case "", "ttl", "expireTime", "expire_time": + default: + return 0, errors.New("can not update immutable fields (model or display_name)") + } + } + ttl, err := parseGeminiCachedContentExpiration(payload, now) + if err != nil { + return 0, err + } + if ttl == 0 { + return 0, errors.New("ttl or expireTime is required") + } + if maxTTL > 0 && ttl > maxTTL { + return 0, fmt.Errorf("ttl exceeds the maximum allowed %ds", int64(maxTTL.Seconds())) + } + return ttl, nil +} + +// geminiCachedContentFieldAliases 是缓存元数据字段的 snake_case 写法到 camelCase 的映射。 +var geminiCachedContentFieldAliases = map[string]string{ + "display_name": "displayName", + "expire_time": "expireTime", + "create_time": "createTime", + "update_time": "updateTime", + "usage_metadata": "usageMetadata", +} + +// decodeGeminiCachedContentPayload 解码缓存请求体(数字保留原文),并把 snake_case 写法的元数据字段改为 camelCase; +// 同一字段两种写法同时出现时报错。 +func decodeGeminiCachedContentPayload(body []byte) (map[string]any, error) { + dec := json.NewDecoder(bytes.NewReader(body)) + dec.UseNumber() + var payload map[string]any + if err := dec.Decode(&payload); err != nil || payload == nil { + return nil, errors.New("request body must be a JSON object") + } + if _, err := dec.Token(); !errors.Is(err, io.EOF) { + return nil, errors.New("request body must be a JSON object") + } + for alias, canonical := range geminiCachedContentFieldAliases { + value, ok := payload[alias] + if !ok { + continue + } + if _, dup := payload[canonical]; dup { + return nil, fmt.Errorf("only one of %s or %s may be set", canonical, alias) + } + delete(payload, alias) + payload[canonical] = value + } + return payload, nil +} + +// parseGeminiCachedContentExpiration 解析 ttl / expireTime(二选一),未设置时返回 0;结果向上取整到秒,与发往上游的 ttl 一致。 +func parseGeminiCachedContentExpiration(payload map[string]any, now time.Time) (time.Duration, error) { + rawTTL, hasTTL := payload["ttl"] + rawExpire, hasExpire := payload["expireTime"] + hasTTL = hasTTL && rawTTL != nil + hasExpire = hasExpire && rawExpire != nil + if hasTTL && hasExpire { + return 0, errors.New("only one of ttl or expireTime may be set") + } + if hasTTL { + s, ok := rawTTL.(string) + if !ok { + return 0, errors.New("ttl must be a duration string such as \"3600s\"") + } + return parseGoogleDurationSeconds(s) + } + if hasExpire { + s, ok := rawExpire.(string) + if !ok { + return 0, errors.New("expireTime must be an RFC 3339 timestamp") + } + expire, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(s)) + if err != nil { + return 0, errors.New("expireTime must be an RFC 3339 timestamp") + } + ttl := expire.Sub(now) + if ttl <= 0 { + return 0, errors.New("expireTime must be in the future") + } + return time.Duration(math.Ceil(ttl.Seconds())) * time.Second, nil + } + return 0, nil +} + +func parseGoogleDurationSeconds(raw string) (time.Duration, error) { + raw = strings.TrimSpace(raw) + if !strings.HasSuffix(raw, "s") { + return 0, errors.New("ttl must be a duration string such as \"3600s\"") + } + seconds, err := strconv.ParseFloat(strings.TrimSuffix(raw, "s"), 64) + if err != nil || math.IsNaN(seconds) || math.IsInf(seconds, 0) { + return 0, errors.New("ttl must be a duration string such as \"3600s\"") + } + if seconds <= 0 { + return 0, errors.New("ttl must be positive") + } + if seconds > float64(math.MaxInt64/int64(time.Second)) { + return 0, errors.New("ttl is too large") + } + return time.Duration(math.Ceil(seconds)) * time.Second, nil +} + +// GeminiCachedContentUpstream 是上游缓存资源的元数据。 +type GeminiCachedContentUpstream struct { + Name string + TotalTokenCount int64 + ExpireTime time.Time +} + +// GeminiCachedContentUpstreamError 是上游返回的非 2xx 响应。 +type GeminiCachedContentUpstreamError struct { + StatusCode int + Body []byte + // UpstreamGateway 表示响应来自声明实现显式缓存的上游网关账号:限流 / 不可用反映的是持有缓存的上游账号状态。 + UpstreamGateway bool +} + +func (e *GeminiCachedContentUpstreamError) Error() string { + return fmt.Sprintf("gemini cached content upstream error: %d", e.StatusCode) +} + +// NotFound 判断上游是否报告缓存不存在(含已过期、已删除)。 +func (e *GeminiCachedContentUpstreamError) NotFound() bool { + return e != nil && isGeminiCachedContentNotFound(e.StatusCode, e.Body) +} + +// GeminiCachedContentMalformedResponseError 表示上游返回 2xx 但响应体不可用;Name 非空时上游资源已经创建。 +type GeminiCachedContentMalformedResponseError struct { + Name string + Err error +} + +func (e *GeminiCachedContentMalformedResponseError) Error() string { + return "gemini cached content upstream returned an unusable response: " + e.Err.Error() +} + +func (e *GeminiCachedContentMalformedResponseError) Unwrap() error { + return e.Err +} + +// RetryableOnOtherAccount 判断创建失败是否值得换一个账号重试(账号凭据、配额或上游可用性问题)。 +func (e *GeminiCachedContentUpstreamError) RetryableOnOtherAccount() bool { + if e == nil { + return false + } + switch e.StatusCode { + case http.StatusUnauthorized, http.StatusForbidden, http.StatusTooManyRequests: + return true + default: + return e.StatusCode >= 500 + } +} + +// GeminiCachedContentService 管理显式缓存的上游资源与网关绑定。 +type GeminiCachedContentService struct { + repo GeminiCachedContentRepository + compat *GeminiMessagesCompatService + cfg *config.Config + now func() time.Time + + startOnce sync.Once + stopOnce sync.Once + stopCh chan struct{} +} + +func NewGeminiCachedContentService(repo GeminiCachedContentRepository, compat *GeminiMessagesCompatService, cfg *config.Config) *GeminiCachedContentService { + return &GeminiCachedContentService{repo: repo, compat: compat, cfg: cfg, now: time.Now, stopCh: make(chan struct{})} +} + +// Start 启动后台回滚恢复:定期处理租约已过期仍未清除的修改意图。 +func (s *GeminiCachedContentService) Start() { + if s == nil || s.repo == nil { + return + } + s.startOnce.Do(func() { go s.runMutationRecovery() }) +} + +// Stop 停止后台回滚恢复。 +func (s *GeminiCachedContentService) Stop() { + if s == nil { + return + } + s.stopOnce.Do(func() { close(s.stopCh) }) +} + +func (s *GeminiCachedContentService) runMutationRecovery() { + ticker := time.NewTicker(geminiCachedContentMutationRecoveryInterval) + defer ticker.Stop() + for { + select { + case <-s.stopCh: + return + case <-ticker.C: + recovered, err := s.RecoverStaleMutations(context.Background()) + if err != nil { + logger.LegacyPrintf("service.gemini_cached_content", "Warning: gemini cached content mutation recovery failed (recovered=%d): %v", recovered, err) + } else if recovered > 0 { + logger.LegacyPrintf("service.gemini_cached_content", "gemini cached content mutation recovery rolled back %d stale mutations", recovered) + } + } + } +} + +// Now 返回服务时钟。 +func (s *GeminiCachedContentService) Now() time.Time { + return s.now() +} + +// MaxTTL 返回单次创建或延长允许的最长有效期。 +func (s *GeminiCachedContentService) MaxTTL() time.Duration { + if s.cfg != nil && s.cfg.Gateway.GeminiCachedContentMaxTTLSeconds > 0 { + return time.Duration(s.cfg.Gateway.GeminiCachedContentMaxTTLSeconds) * time.Second + } + return geminiCachedContentDefaultMaxTTL +} + +// MaxTTLForAccount 返回在账号上可设置的最长有效期:全局上限与上游网关上限取较小值。 +func (s *GeminiCachedContentService) MaxTTLForAccount(account *Account) time.Duration { + limit := s.MaxTTL() + if upstream := account.GeminiExplicitCacheUpstreamMaxTTL(); upstream > 0 && upstream < limit { + return upstream + } + return limit +} + +// GeminiCachedContentStorageTokenHours 返回 tokens 个缓存 token 存储 duration 的存储量(token·小时)。 +func GeminiCachedContentStorageTokenHours(tokens int64, duration time.Duration) float64 { + if tokens <= 0 || duration <= 0 { + return 0 + } + return float64(tokens) * duration.Hours() +} + +// ClampGeminiCachedContentExpire 返回本地记录与计费采用的到期时间:上游回报的到期时间不晚于 limit,缺失时取 limit。 +func ClampGeminiCachedContentExpire(upstream, limit time.Time) time.Time { + if upstream.IsZero() || upstream.After(limit) { + return limit + } + return upstream +} + +// Resolve 返回 API Key 名下仍有效的缓存;不存在、不在当前分组或已过期时返回 ErrGeminiCachedContentNotFound。 +func (s *GeminiCachedContentService) Resolve(ctx context.Context, apiKeyID int64, groupID *int64, name string) (*GeminiCachedContent, error) { + publicID, ok := ParseGeminiCachedContentPublicID(name) + if !ok { + return nil, ErrGeminiCachedContentNotFound + } + record, err := s.repo.GetForOwner(ctx, apiKeyID, publicID) + if err != nil { + return nil, err + } + if groupID == nil || record.GroupID != *groupID || !record.ExpireTime.After(s.now()) { + return nil, ErrGeminiCachedContentNotFound + } + return record, nil +} + +func (s *GeminiCachedContentService) Save(ctx context.Context, record *GeminiCachedContent) error { + return s.repo.Create(ctx, record) +} + +func (s *GeminiCachedContentService) List(ctx context.Context, apiKeyID, groupID int64, beforeID int64, limit int) ([]*GeminiCachedContent, error) { + return s.repo.ListForOwner(ctx, apiKeyID, groupID, s.now(), beforeID, limit) +} + +// GeminiCachedContentMutation 是一次已登记修改意图、尚未提交的有效期修改。持有期间同一缓存的其他修改被拒绝; +// 未提交的修改(上游结果未知、落库失败、进程退出)在租约过期后由恢复流程把上游有效期回滚到 Baseline,不计费。 +type GeminiCachedContentMutation struct { + record *GeminiCachedContent + baseline time.Time + token string +} + +// Baseline 返回修改前的到期时间:提交前它始终是库中的到期时间。 +func (m *GeminiCachedContentMutation) Baseline() time.Time { + return m.baseline +} + +// BeginMutation 登记修改 record 有效期的意图并取得租约。同一缓存有进行中的修改,或库中到期时间已不是 +// record.ExpireTime 时返回 ErrGeminiCachedContentMutationConflict;租约已过期的遗留意图先回滚恢复再登记。 +func (s *GeminiCachedContentService) BeginMutation(ctx context.Context, record *GeminiCachedContent) (*GeminiCachedContentMutation, error) { + for attempt := 0; ; attempt++ { + token, err := NewGeminiCachedContentPublicID() + if err != nil { + return nil, err + } + acquired, err := s.repo.BeginMutation(ctx, record.ID, record.ExpireTime, token, geminiCachedContentMutationLease) + if err != nil { + return nil, err + } + if acquired { + return &GeminiCachedContentMutation{record: record, baseline: record.ExpireTime, token: token}, nil + } + if attempt > 0 { + return nil, ErrGeminiCachedContentMutationConflict + } + recovered, err := s.recoverStaleMutation(ctx, record.ID) + if err != nil { + return nil, errors.Join(ErrGeminiCachedContentMutationConflict, err) + } + if !recovered { + return nil, ErrGeminiCachedContentMutationConflict + } + } +} + +// CommitMutation 写入新的到期时间并清除修改意图。修改意图已不属于 m(缓存已删除或租约已被接管)时返回 +// ErrGeminiCachedContentMutationConflict;其他失败时意图保留,由恢复流程回滚上游。 +func (s *GeminiCachedContentService) CommitMutation(ctx context.Context, m *GeminiCachedContentMutation, expireTime time.Time) error { + if err := s.repo.CommitMutation(ctx, m.record.ID, m.token, expireTime); err != nil { + return err + } + m.record.ExpireTime = expireTime + m.record.UpdatedAt = s.now() + return nil +} + +// ReleaseMutation 放弃修改并清除修改意图,用于上游明确未改变有效期的情形。 +func (s *GeminiCachedContentService) ReleaseMutation(ctx context.Context, m *GeminiCachedContentMutation) error { + return s.repo.ReleaseMutation(ctx, m.record.ID, m.token) +} + +// RecoverStaleMutations 回滚恢复一批租约已过期的修改意图,返回完成恢复的数量。 +func (s *GeminiCachedContentService) RecoverStaleMutations(ctx context.Context) (int, error) { + listCtx, cancel := context.WithTimeout(ctx, geminiCachedContentMutationRecoveryTimeout) + ids, err := s.repo.ListStaleMutations(listCtx, geminiCachedContentMutationRecoveryBatch) + cancel() + if err != nil { + return 0, err + } + recovered := 0 + var errs []error + for _, id := range ids { + select { + case <-s.stopCh: + return recovered, errors.Join(errs...) + default: + } + itemCtx, cancel := context.WithTimeout(ctx, geminiCachedContentMutationRecoveryTimeout) + ok, err := s.recoverStaleMutation(itemCtx, id) + cancel() + if err != nil { + errs = append(errs, fmt.Errorf("cached content %d: %w", id, err)) + continue + } + if ok { + recovered++ + } + } + return recovered, errors.Join(errs...) +} + +// recoverStaleMutation 接管 id 上租约已过期的修改意图,把上游有效期回滚到库中的到期时间后清除意图; +// 库中到期时间已到时删除上游缓存与本地记录。没有可接管的意图时返回 false;回滚失败时意图保留, +// 本次接管取得的新租约(geminiCachedContentMutationLease)过期后重试,期间同一缓存的修改返回 409。 +func (s *GeminiCachedContentService) recoverStaleMutation(ctx context.Context, id int64) (bool, error) { + token, err := NewGeminiCachedContentPublicID() + if err != nil { + return false, err + } + record, err := s.repo.TakeOverStaleMutation(ctx, id, token, geminiCachedContentMutationLease) + if err != nil || record == nil { + return false, err + } + forget, err := s.rollbackUpstream(ctx, record) + if err != nil { + return false, err + } + if forget { + return true, s.repo.SoftDelete(ctx, record.ID) + } + return true, s.repo.ReleaseMutation(ctx, record.ID, token) +} + +// rollbackUpstream 把上游有效期改回 record.ExpireTime,剩余不足 1 秒时删除上游缓存; +// 返回 true 表示上游缓存已不存在、或已没有凭据可触达(持有账号已删除),本地记录应移除。 +// 持有账号存在但当前不支持显式缓存时不改动上游,修改意图保留到账号恢复后重试;账号可用时总是先向上游回滚。 +// 两种情况下只要 mutationUpstreamMustHaveExpired 成立(上游缓存必已自行过期),本地记录直接作废,不再重试。 +func (s *GeminiCachedContentService) rollbackUpstream(ctx context.Context, record *GeminiCachedContent) (bool, error) { + account, err := s.boundAccount(ctx, record) + if errors.Is(err, errGeminiCachedContentAccountUnsupported) { + if s.mutationUpstreamMustHaveExpired(record) { + logger.LegacyPrintf("service.gemini_cached_content", "Warning: gemini cached content %d (upstream %s) has a pending mutation but account %d stopped supporting explicit caching and the upstream cache has expired since; dropping the local record", record.ID, record.UpstreamName, record.AccountID) + return true, nil + } + return false, fmt.Errorf("%w (account %d)", err, record.AccountID) + } + if err != nil { + return false, err + } + if account == nil { + logger.LegacyPrintf("service.gemini_cached_content", "Warning: gemini cached content %d (upstream %s) has a pending mutation but account %d no longer exists; dropping the local record without touching upstream", record.ID, record.UpstreamName, record.AccountID) + return true, nil + } + remaining := record.ExpireTime.Sub(s.now()) + if remaining < time.Second { + err = s.DeleteUpstream(ctx, account, record) + } else { + _, err = s.PatchUpstream(ctx, account, record, remaining) + } + var upErr *GeminiCachedContentUpstreamError + if errors.As(err, &upErr) && upErr.NotFound() { + return true, nil + } + if err != nil { + if s.mutationUpstreamMustHaveExpired(record) { + logger.LegacyPrintf("service.gemini_cached_content", "Warning: gemini cached content %d (upstream %s) rollback keeps failing on account %d but the upstream cache has expired since; dropping the local record: %v", record.ID, record.UpstreamName, record.AccountID, err) + return true, nil + } + return false, err + } + return remaining < time.Second, nil +} + +// mutationUpstreamMustHaveExpired 判断 record 上未完成修改所涉及的上游缓存是否必已自行过期: +// 修改发生时记录尚未到期(Resolve 拒绝已过期记录),且单次延长不超过 MaxTTL, +// 所以上游有效期最晚为 record.ExpireTime + MaxTTL;再过 geminiCachedContentMutationAbandonGrace 后判定为已过期。 +// MaxTTL 取判定时刻的配置并以默认上限兜底:配置被调低后判定可能早于上游真实过期,此时只影响运营方的上游存储费, +// 不涉及用户计费。 +func (s *GeminiCachedContentService) mutationUpstreamMustHaveExpired(record *GeminiCachedContent) bool { + maxTTL := s.MaxTTL() + if maxTTL < geminiCachedContentDefaultMaxTTL { + maxTTL = geminiCachedContentDefaultMaxTTL + } + return s.now().After(record.ExpireTime.Add(maxTTL + geminiCachedContentMutationAbandonGrace)) +} + +func (s *GeminiCachedContentService) Forget(ctx context.Context, record *GeminiCachedContent) error { + return s.repo.SoftDelete(ctx, record.ID) +} + +// BoundAccount 返回持有缓存的账号;账号已删除或不再支持显式缓存时返回 nil。 +func (s *GeminiCachedContentService) BoundAccount(ctx context.Context, record *GeminiCachedContent) (*Account, error) { + account, err := s.boundAccount(ctx, record) + if errors.Is(err, errGeminiCachedContentAccountUnsupported) { + return nil, nil + } + return account, err +} + +// boundAccount 返回持有缓存的账号:账号已删除返回 nil;账号存在但当前不支持显式缓存返回 +// errGeminiCachedContentAccountUnsupported,调用方据此区分"永久不可用"与"暂时不可用"。 +func (s *GeminiCachedContentService) boundAccount(ctx context.Context, record *GeminiCachedContent) (*Account, error) { + if s.compat == nil || s.compat.accountRepo == nil { + return nil, errors.New("account repository not configured") + } + account, err := s.compat.accountRepo.GetByID(ctx, record.AccountID) + if err != nil { + if errors.Is(err, ErrAccountNotFound) { + return nil, nil + } + return nil, err + } + if account == nil { + return nil, nil + } + if !IsGeminiExplicitCacheAccount(account) { + return nil, errGeminiCachedContentAccountUnsupported + } + return account, nil +} + +// GeminiCachedContentUpstreamModelResource 返回创建缓存时发往上游的模型资源名。 +func GeminiCachedContentUpstreamModelResource(account *Account, mappedModel string) (string, error) { + switch account.Type { + case AccountTypeAPIKey: + return "models/" + mappedModel, nil + case AccountTypeServiceAccount: + projectID := strings.TrimSpace(account.VertexProjectID()) + if projectID == "" { + return "", errors.New("vertex project_id is required") + } + location := strings.TrimSpace(account.VertexLocation(mappedModel)) + if location == "" { + location = vertexDefaultLocation + } + if !vertexLocationPattern.MatchString(location) { + return "", fmt.Errorf("invalid vertex location: %s", location) + } + return fmt.Sprintf("projects/%s/locations/%s/publishers/google/models/%s", projectID, location, mappedModel), nil + default: + return "", fmt.Errorf("account type %s does not support explicit context caching", account.Type) + } +} + +// CreateUpstream 在账号上创建上游缓存。 +func (s *GeminiCachedContentService) CreateUpstream(ctx context.Context, account *Account, req *GeminiCachedContentCreateRequest, mappedModel, publicID string, ttl time.Duration) (*GeminiCachedContentUpstream, error) { + upstreamModel, err := GeminiCachedContentUpstreamModelResource(account, mappedModel) + if err != nil { + return nil, err + } + payload := make(map[string]any, len(req.payload)+3) + for k, v := range req.payload { + payload[k] = v + } + payload["model"] = upstreamModel + payload["ttl"] = fmt.Sprintf("%ds", int64(math.Ceil(ttl.Seconds()))) + payload["displayName"] = geminiCachedContentUpstreamTagPrefix + publicID + body, err := json.Marshal(payload) + if err != nil { + return nil, err + } + base, err := s.apiBase(account) + if err != nil { + return nil, err + } + collectionURL, err := geminiCachedContentCollectionURL(account, base, mappedModel) + if err != nil { + return nil, err + } + respBody, err := s.doUpstream(ctx, account, http.MethodPost, collectionURL, body, geminiCachedContentUpstreamTimeout) + if err != nil { + return nil, err + } + upstream, err := parseGeminiCachedContentUpstream(respBody) + if err != nil { + return nil, err + } + if upstream.TotalTokenCount <= 0 { + return nil, &GeminiCachedContentMalformedResponseError{Name: upstream.Name, Err: errors.New("missing usageMetadata.totalTokenCount")} + } + return upstream, nil +} + +// PatchUpstream 把上游缓存的有效期改为自现在起 ttl。 +func (s *GeminiCachedContentService) PatchUpstream(ctx context.Context, account *Account, record *GeminiCachedContent, ttl time.Duration) (*GeminiCachedContentUpstream, error) { + resourceURL, err := s.upstreamResourceURL(account, record) + if err != nil { + return nil, err + } + seconds := int64(math.Ceil(ttl.Seconds())) + body, _ := json.Marshal(map[string]any{"ttl": fmt.Sprintf("%ds", seconds)}) + respBody, err := s.doUpstream(ctx, account, http.MethodPatch, resourceURL+"?updateMask=ttl", body, geminiCachedContentMutationUpstreamTimeout) + if err != nil { + return nil, err + } + out := &GeminiCachedContentUpstream{Name: record.UpstreamName} + if raw := gjson.GetBytes(respBody, "expireTime").String(); raw != "" { + if t, err := time.Parse(time.RFC3339Nano, raw); err == nil { + out.ExpireTime = t + } + } + return out, nil +} + +// DeleteUpstream 删除上游缓存。 +func (s *GeminiCachedContentService) DeleteUpstream(ctx context.Context, account *Account, record *GeminiCachedContent) error { + resourceURL, err := s.upstreamResourceURL(account, record) + if err != nil { + return err + } + _, err = s.doUpstream(ctx, account, http.MethodDelete, resourceURL, nil, geminiCachedContentMutationUpstreamTimeout) + return err +} + +// upstreamResourceURL 返回 record 对应上游缓存资源的地址;失败时请求不会发出。 +func (s *GeminiCachedContentService) upstreamResourceURL(account *Account, record *GeminiCachedContent) (string, error) { + base, err := s.apiBase(account) + if err != nil { + return "", geminiCachedContentNotSent(err) + } + resourceURL, err := geminiCachedContentResourceURL(account, base, record.UpstreamName) + if err != nil { + return "", geminiCachedContentNotSent(err) + } + return resourceURL, nil +} + +func geminiCachedContentNotSent(err error) error { + return fmt.Errorf("%w: %w", ErrGeminiCachedContentRequestNotSent, err) +} + +// doUpstream 调用上游缓存接口并返回 2xx 响应体,单次调用不超过 timeout。上游调用与客户端连接脱钩:客户端断开不会中途取消 +// 已发出的创建 / 修改,调用方据结果完成落库、计费或清理。请求发出前的失败包装为 ErrGeminiCachedContentRequestNotSent。 +func (s *GeminiCachedContentService) doUpstream(ctx context.Context, account *Account, method, target string, body []byte, timeout time.Duration) ([]byte, error) { + if s.compat == nil || s.compat.httpUpstream == nil { + return nil, geminiCachedContentNotSent(errors.New("gemini upstream client not configured")) + } + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeout) + defer cancel() + var reader io.Reader + if body != nil { + reader = bytes.NewReader(body) + } + req, err := http.NewRequestWithContext(ctx, method, target, reader) + if err != nil { + return nil, geminiCachedContentNotSent(err) + } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + switch account.Type { + case AccountTypeAPIKey: + apiKey := strings.TrimSpace(account.GetCredential("api_key")) + if apiKey == "" { + return nil, geminiCachedContentNotSent(errors.New("gemini api_key not configured")) + } + req.Header.Set("x-goog-api-key", apiKey) + case AccountTypeServiceAccount: + if s.compat.tokenProvider == nil { + return nil, geminiCachedContentNotSent(errors.New("gemini token provider not configured")) + } + accessToken, err := s.compat.tokenProvider.GetAccessToken(ctx, account) + if err != nil { + return nil, geminiCachedContentNotSent(err) + } + req.Header.Set("Authorization", "Bearer "+accessToken) + default: + return nil, geminiCachedContentNotSent(fmt.Errorf("account type %s does not support explicit context caching", account.Type)) + } + proxyURL := "" + if account.ProxyID != nil && account.Proxy != nil { + proxyURL = account.Proxy.URL() + } + resp, err := s.compat.httpUpstream.Do(req, proxyURL, account.ID, account.Concurrency) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + respBody, err := io.ReadAll(io.LimitReader(resp.Body, geminiCachedContentResponseMaxBytes)) + success := resp.StatusCode >= 200 && resp.StatusCode < 300 + if err != nil { + if success { + return nil, &GeminiCachedContentMalformedResponseError{Err: err} + } + return nil, err + } + if !success { + return nil, &GeminiCachedContentUpstreamError{StatusCode: resp.StatusCode, Body: respBody, UpstreamGateway: account.GeminiExplicitCacheUpstreamEnabled()} + } + return respBody, nil +} + +// apiBase 返回 API Key 账号经地址校验后的上游根地址;Vertex 账号返回空串(地址由区域决定)。 +func (s *GeminiCachedContentService) apiBase(account *Account) (string, error) { + if account.Type != AccountTypeAPIKey { + return "", nil + } + if s.compat == nil { + return "", errors.New("gemini upstream client not configured") + } + return s.compat.validateUpstreamBaseURL(geminiCachedContentAPIBase(account)) +} + +func parseGeminiCachedContentUpstream(body []byte) (*GeminiCachedContentUpstream, error) { + name := strings.TrimSpace(gjson.GetBytes(body, "name").String()) + if name == "" { + return nil, &GeminiCachedContentMalformedResponseError{Err: errors.New("missing name")} + } + if !geminiCachedContentAIStudioName.MatchString(name) && !geminiCachedContentVertexName.MatchString(name) { + return nil, &GeminiCachedContentMalformedResponseError{Err: fmt.Errorf("unexpected name %q", name)} + } + out := &GeminiCachedContentUpstream{ + Name: name, + TotalTokenCount: gjson.GetBytes(body, "usageMetadata.totalTokenCount").Int(), + } + if raw := gjson.GetBytes(body, "expireTime").String(); raw != "" { + if t, err := time.Parse(time.RFC3339Nano, raw); err == nil { + out.ExpireTime = t + } + } + return out, nil +} + +func geminiCachedContentCollectionURL(account *Account, base, mappedModel string) (string, error) { + switch account.Type { + case AccountTypeAPIKey: + base = strings.TrimRight(strings.TrimSpace(base), "/") + if base == "" { + return "", errors.New("gemini base url is required") + } + return base + "/v1beta/cachedContents", nil + case AccountTypeServiceAccount: + projectID := strings.TrimSpace(account.VertexProjectID()) + if projectID == "" { + return "", errors.New("vertex project_id is required") + } + location := strings.TrimSpace(account.VertexLocation(mappedModel)) + if location == "" { + location = vertexDefaultLocation + } + if !vertexLocationPattern.MatchString(location) { + return "", fmt.Errorf("invalid vertex location: %s", location) + } + return fmt.Sprintf("https://%s/v1/projects/%s/locations/%s/cachedContents", + geminiCachedContentVertexHost(location), url.PathEscape(projectID), url.PathEscape(location)), nil + default: + return "", fmt.Errorf("account type %s does not support explicit context caching", account.Type) + } +} + +func geminiCachedContentResourceURL(account *Account, base, upstreamName string) (string, error) { + switch account.Type { + case AccountTypeAPIKey: + if !geminiCachedContentAIStudioName.MatchString(upstreamName) { + return "", fmt.Errorf("invalid upstream cached content name: %s", upstreamName) + } + base = strings.TrimRight(strings.TrimSpace(base), "/") + if base == "" { + return "", errors.New("gemini base url is required") + } + return base + "/v1beta/" + upstreamName, nil + case AccountTypeServiceAccount: + m := geminiCachedContentVertexName.FindStringSubmatch(upstreamName) + if m == nil { + return "", fmt.Errorf("invalid upstream cached content name: %s", upstreamName) + } + return fmt.Sprintf("https://%s/v1/%s", geminiCachedContentVertexHost(m[1]), upstreamName), nil + default: + return "", fmt.Errorf("account type %s does not support explicit context caching", account.Type) + } +} + +func geminiCachedContentVertexHost(location string) string { + if location == "global" { + return "aiplatform.googleapis.com" + } + return location + "-aiplatform.googleapis.com" +} + +// GeminiCachedContentView 返回客户端可见的缓存元数据。 +func GeminiCachedContentView(record *GeminiCachedContent) map[string]any { + view := map[string]any{ + "name": record.PublicName(), + "model": "models/" + record.Model, + "usageMetadata": map[string]any{"totalTokenCount": record.TotalTokenCount}, + "createTime": record.CreatedAt.UTC().Format(time.RFC3339Nano), + "updateTime": record.UpdatedAt.UTC().Format(time.RFC3339Nano), + "expireTime": record.ExpireTime.UTC().Format(time.RFC3339Nano), + } + if record.DisplayName != "" { + view["displayName"] = record.DisplayName + } + return view +} + +// GeminiExplicitCacheExclusions 返回显式缓存请求在 gemini 分组内需要排除的可调度账号。 +// boundAccountID > 0 时只保留该账号;否则排除不支持显式缓存的账号。判定所需的凭据键 +// (api_key、base_url、auth_mode、上游显式缓存声明)都在调度快照投影内,候选过滤一次算全; +// 选中后仍对完整账号复核。 +func (s *GatewayService) GeminiExplicitCacheExclusions(ctx context.Context, groupID *int64, boundAccountID int64) (map[int64]struct{}, error) { + accounts, _, err := s.listSchedulableAccounts(ctx, groupID, PlatformGemini, false) + if err != nil { + return nil, err + } + excluded := make(map[int64]struct{}, len(accounts)) + for i := range accounts { + account := &accounts[i] + keep := IsGeminiExplicitCacheAccount(account) + if boundAccountID > 0 { + keep = account.ID == boundAccountID + } + if !keep { + excluded[account.ID] = struct{}{} + } + } + return excluded, nil +} diff --git a/backend/internal/service/gemini_cached_content_hardening_test.go b/backend/internal/service/gemini_cached_content_hardening_test.go new file mode 100644 index 000000000..4d00d60f9 --- /dev/null +++ b/backend/internal/service/gemini_cached_content_hardening_test.go @@ -0,0 +1,480 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "strings" + "testing" + "time" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +const geminiCacheHardeningPricing = `{ + "gemini-3.8-flash":{"litellm_provider":"gemini","input_cost_per_token":0.00000075,"output_cost_per_token":0.00000375, + "cache_storage_cost_per_token_per_hour":0.0000005}, + "gemini-2.5-pro":{"litellm_provider":"gemini","input_cost_per_token":0.00000125,"output_cost_per_token":0.00001, + "cache_storage_cost_per_token_per_hour":0.0000045}}` + +func newGeminiCacheBillingGatewayForTest(t *testing.T) (*GatewayService, *openAIRecordUsageLogRepoStub) { + t.Helper() + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}) + pricing := &PricingService{} + data, err := pricing.parsePricingData([]byte(geminiCacheHardeningPricing)) + require.NoError(t, err) + pricing.pricingData = data + svc.billingService = NewBillingService(svc.cfg, pricing) + return svc, usageRepo +} + +func TestGeminiCachedContentStoragePriceFollowsBillingModel(t *testing.T) { + ctx := context.Background() + svc, usageRepo := newGeminiCacheBillingGatewayForTest(t) + groupID := int64(33) + apiKey := &APIKey{ID: 821, GroupID: &groupID, User: &User{ID: 621}, + Group: &Group{ID: groupID, Platform: PlatformGemini, RateMultiplier: 2, Hydrated: true}} + tokenHours := GeminiCachedContentStorageTokenHours(1000, 24*time.Hour) + + mapped := &RecordUsageInput{ + Result: &ForwardResult{RequestID: "cc-mapped", Model: "gemini-2.5-pro", UpstreamModel: "gemini-3.8-flash", + Usage: ClaudeUsage{InputTokens: 1000}, CacheStorageTokenHours: tokenHours}, + APIKey: apiKey, User: apiKey.User, Account: &Account{ID: 713, Platform: PlatformGemini}, + } + require.True(t, svc.CacheStoragePriced(ctx, mapped)) + want := (1000*0.00000125 + tokenHours*0.0000045) * 2 + require.InDelta(t, want, svc.QuoteUsageCost(ctx, mapped), 1e-12, "存储与 token 同按计费模型(请求模型)定价") + require.NoError(t, svc.RecordUsage(ctx, mapped)) + require.InDelta(t, want, usageRepo.lastLog.ActualCost, 1e-12, "报价与实际计费同口径") + + alias := &RecordUsageInput{ + Result: &ForwardResult{Model: "customer-alias", UpstreamModel: "gemini-3.8-flash", CacheStorageTokenHours: tokenHours}, + APIKey: apiKey, + } + require.True(t, svc.CacheStoragePriced(ctx, alias)) + require.InDelta(t, tokenHours*0.0000005*2, svc.QuoteUsageCost(ctx, alias), 1e-12, "计费模型无存储价时回退到实际转发模型") + + unpriced := &RecordUsageInput{ + Result: &ForwardResult{Model: "customer-alias", UpstreamModel: "unknown-upstream", CacheStorageTokenHours: tokenHours}, + APIKey: apiKey, + } + require.False(t, svc.CacheStoragePriced(ctx, unpriced)) +} + +func TestGeminiCachedContentStorageOnlyIsNotARequest(t *testing.T) { + ctx := context.Background() + svc, usageRepo := newGeminiCacheBillingGatewayForTest(t) + groupID := int64(34) + perRequest := 0.05 + pricing := []ChannelModelPricing{{Models: []string{"gemini-3.8-flash"}, BillingMode: BillingModePerRequest, PerRequestPrice: &perRequest}} + svc.channelService = newTestChannelServiceForStats(t, &Channel{ID: 1, Status: StatusActive, + AccountStatsPricingRules: []AccountStatsPricingRule{{GroupIDs: []int64{groupID}, Pricing: pricing}}}, groupID, PlatformGemini) + svc.resolver = NewModelPricingResolver(svc.channelService, svc.billingService) + apiKey := &APIKey{ID: 822, GroupID: &groupID, User: &User{ID: 622}, + Group: &Group{ID: groupID, Platform: PlatformGemini, RateMultiplier: 1, Hydrated: true, ModelPricing: pricing}} + tokenHours := 20000.0 + storage := tokenHours * 0.0000005 + + record := func(tokens int) *UsageLog { + require.NoError(t, svc.RecordUsage(ctx, &RecordUsageInput{ + Result: &ForwardResult{RequestID: fmt.Sprintf("cc-%d", tokens), Model: "gemini-3.8-flash", + Usage: ClaudeUsage{InputTokens: tokens}, CacheStorageTokenHours: tokenHours}, + APIKey: apiKey, User: apiKey.User, Account: &Account{ID: 712, Platform: PlatformGemini}, + })) + return usageRepo.lastLog + } + + created := record(10000) + require.InDelta(t, perRequest+storage, created.TotalCost, 1e-12, "创建是一次请求:按次价 + 存储费") + require.NotNil(t, created.AccountStatsCost) + require.InDelta(t, perRequest+storage, *created.AccountStatsCost, 1e-12) + + extended := record(0) + require.InDelta(t, storage, extended.TotalCost, 1e-12, "延长有效期不算一次请求,只收存储费") + require.Nil(t, extended.AccountStatsCost, "账号统计成本回落 total_cost,不套按次规则") +} + +func TestFindGeminiCachedContentReferenceRejectsAmbiguousKeys(t *testing.T) { + for name, body := range map[string]string{ + "duplicate top-level": `{"cachedContent":"cachedContents/a","contents":[],"cachedContent":"cachedContents/b"}`, + "snake top-level": `{"cached_content":"cachedContents/a"}`, + "snake beside camel": `{"cachedContent":"cachedContents/a","cached_content":"cachedContents/b"}`, + "duplicate nested": `{"generateContentRequest":{"cachedContent":"cachedContents/a","cachedContent":"cachedContents/b"}}`, + "snake nested": `{"generateContentRequest":{"cached_content":"cachedContents/a"}}`, + "snake parent with cache": `{"generate_content_request":{"cachedContent":"cachedContents/a"}}`, + "duplicate nested parent": `{"generateContentRequest":{},"generateContentRequest":{"cachedContent":"cachedContents/a"}}`, + "conflicting two locations": `{"cachedContent":"cachedContents/a","generateContentRequest":{"cachedContent":"cachedContents/b"}}`, + } { + t.Run(name, func(t *testing.T) { + _, err := FindGeminiCachedContentReference([]byte(body)) + require.Error(t, err) + }) + } + + for name, body := range map[string]string{ + "snake parent without cache": `{"generate_content_request":{"contents":[]}}`, + "key name inside content": `{"contents":[{"role":"user","cached_content":"x","parts":[{"text":"cached_content"}]}]}`, + "not an object": `[{"cachedContent":"cachedContents/a"}]`, + } { + t.Run("allows "+name, func(t *testing.T) { + ref, err := FindGeminiCachedContentReference([]byte(body)) + require.NoError(t, err) + require.Nil(t, ref) + }) + } + + ref, err := FindGeminiCachedContentReference([]byte(`{"cachedContent":"cachedContents/a","generateContentRequest":{"cachedContent":"cachedContents/a"}}`)) + require.NoError(t, err) + require.Equal(t, []string{"cachedContent", "generateContentRequest.cachedContent"}, ref.Paths) +} + +func TestGeminiCachedContentPayloadNormalization(t *testing.T) { + now := time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC) + maxTTL := 24 * time.Hour + + req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash","display_name":"docs","expire_time":"2026-10-09T10:00:00Z"}`), now, maxTTL) + require.NoError(t, err) + require.Equal(t, "docs", req.DisplayName) + require.Equal(t, 2*time.Hour, req.TTL) + for _, key := range []string{"display_name", "expire_time", "displayName", "expireTime"} { + require.NotContains(t, req.payload, key, "元数据字段不随内容发往上游") + } + + for name, body := range map[string]string{ + "both spellings": `{"model":"gemini-3.8-flash","displayName":"a","display_name":"b"}`, + "trailing data": `{"model":"gemini-3.8-flash"} {"model":"x"}`, + } { + t.Run("rejects "+name, func(t *testing.T) { + _, err := ParseGeminiCachedContentCreateRequest([]byte(body), now, maxTTL) + require.Error(t, err) + }) + } + + ttl, err := ParseGeminiCachedContentPatchRequest([]byte(`{"expire_time":"2026-10-09T09:00:00Z"}`), "", now, maxTTL) + require.NoError(t, err) + require.Equal(t, time.Hour, ttl) + _, err = ParseGeminiCachedContentPatchRequest([]byte(`{"display_name":"x"}`), "", now, maxTTL) + require.ErrorContains(t, err, "immutable") +} + +func TestGeminiCachedContentTTLRoundsUpToWholeSeconds(t *testing.T) { + now := time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC) + req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash","ttl":"1e-10s"}`), now, 24*time.Hour) + require.NoError(t, err) + require.Equal(t, time.Second, req.TTL, "极小的显式有效期按 1 秒处理,不回落到默认 1 小时") + require.True(t, req.ttlExplicit) + + ttl, err := ParseGeminiCachedContentPatchRequest([]byte(`{"ttl":"1e-10s"}`), "", now, 24*time.Hour) + require.NoError(t, err) + require.Equal(t, time.Second, ttl) + + req, err = ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash","expireTime":"2026-10-09T08:00:10.2Z"}`), now, 24*time.Hour) + require.NoError(t, err) + require.Equal(t, 11*time.Second, req.TTL, "expireTime 折算的有效期与发往上游的整秒 ttl 一致") +} + +func TestGeminiCachedContentCreateKeepsNumbersVerbatim(t *testing.T) { + svc, httpStub := newGeminiCachedContentServiceForTest(t, http.StatusOK, + `{"name":"cachedContents/up1","usageMetadata":{"totalTokenCount":2000}}`) + req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"models/gemini-3.8-flash","contents":[{"role":"user","parts":[ + {"functionResponse":{"name":"lookup","response":{"order_id":1790000000000000001,"ratio":0.10}}}]}]}`), time.Now(), 24*time.Hour) + require.NoError(t, err) + account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "secret"}} + _, err = svc.CreateUpstream(context.Background(), account, req, "gemini-3.8-flash", "pub1", time.Hour) + require.NoError(t, err) + raw, err := io.ReadAll(httpStub.lastReq.Body) + require.NoError(t, err) + require.Contains(t, string(raw), `"order_id":1790000000000000001`) + require.Contains(t, string(raw), `"ratio":0.10`) +} + +func TestGeminiCachedContentCreateUpstreamUnusableResponse(t *testing.T) { + account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "secret"}} + for name, tc := range map[string]struct { + body string + wantName string + }{ + "missing token count": {`{"name":"cachedContents/up9","expireTime":"2099-01-01T00:00:00Z"}`, "cachedContents/up9"}, + "zero token count": {`{"name":"cachedContents/up9","usageMetadata":{"totalTokenCount":0}}`, "cachedContents/up9"}, + "unexpected name": {`{"name":"cachedContents/a/../b","usageMetadata":{"totalTokenCount":5}}`, ""}, + "not json": {``, ""}, + } { + t.Run(name, func(t *testing.T) { + svc, _ := newGeminiCachedContentServiceForTest(t, http.StatusOK, tc.body) + req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash"}`), time.Now(), 24*time.Hour) + require.NoError(t, err) + _, err = svc.CreateUpstream(context.Background(), account, req, "gemini-3.8-flash", "pub1", time.Hour) + var malformed *GeminiCachedContentMalformedResponseError + require.ErrorAs(t, err, &malformed) + require.Equal(t, tc.wantName, malformed.Name) + }) + } +} + +type geminiCachedContentCtxProbeUpstream struct { + geminiCompatHTTPUpstreamStub + ctxErrAtSend error +} + +func (s *geminiCachedContentCtxProbeUpstream) Do(req *http.Request, proxyURL string, accountID int64, accountConcurrency int) (*http.Response, error) { + s.ctxErrAtSend = req.Context().Err() + return s.geminiCompatHTTPUpstreamStub.Do(req, proxyURL, accountID, accountConcurrency) +} + +func TestGeminiCachedContentUpstreamCallIgnoresClientCancel(t *testing.T) { + up := &geminiCachedContentCtxProbeUpstream{geminiCompatHTTPUpstreamStub: geminiCompatHTTPUpstreamStub{response: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"name":"cachedContents/up1","usageMetadata":{"totalTokenCount":2000}}`)), + }}} + svc := NewGeminiCachedContentService(newGeminiCachedContentRepoStub(), + &GeminiMessagesCompatService{httpUpstream: up, cfg: &config.Config{}}, &config.Config{}) + req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash"}`), time.Now(), 24*time.Hour) + require.NoError(t, err) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "secret"}} + _, err = svc.CreateUpstream(ctx, account, req, "gemini-3.8-flash", "pub1", time.Hour) + require.NoError(t, err) + require.NoError(t, up.ctxErrAtSend, "客户端断开不取消发往上游的创建") +} + +func TestClampGeminiCachedContentExpire(t *testing.T) { + limit := time.Date(2026, 10, 10, 8, 0, 0, 0, time.UTC) + require.Equal(t, limit, ClampGeminiCachedContentExpire(time.Time{}, limit)) + require.Equal(t, limit, ClampGeminiCachedContentExpire(limit.Add(100*time.Hour), limit), "上游回报的到期时间不超过请求的有效期") + earlier := limit.Add(-time.Second) + require.Equal(t, earlier, ClampGeminiCachedContentExpire(earlier, limit)) +} + +type geminiBoundCacheRateLimitRepo struct { + errorPolicyRepoStub + rateLimitedCalls int +} + +func (r *geminiBoundCacheRateLimitRepo) SetRateLimited(context.Context, int64, time.Time) error { + r.rateLimitedCalls++ + return nil +} + +func TestGeminiForwardNative_BoundCacheUpstreamGatewayErrorsSkipAccountPenalty(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, status := range []int{http.StatusTooManyRequests, http.StatusServiceUnavailable} { + t.Run(http.StatusText(status), func(t *testing.T) { + body := fmt.Sprintf(`{"error":{"code":%d,"message":"The account holding this cached content is temporarily unavailable","status":"UNAVAILABLE"}}`, status) + svc, httpStub, _ := newGeminiCachedContentTestService(status, body) + repo := &geminiBoundCacheRateLimitRepo{} + svc.accountRepo = repo + svc.rateLimitService = NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + account := &Account{ID: 711, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "k", "base_url": "https://gw.example.com", "explicit_cache_upstream": true, + }} + c, _ := newGeminiNativeTestContext(t) + + _, err := svc.ForwardNative(WithGeminiCachedContentBound(context.Background()), c, account, + "gemini-3.8-flash", "generateContent", false, []byte(geminiCachedContentRequestBody)) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "交由绑定请求的耗尽处理透传") + require.Equal(t, status, failoverErr.StatusCode) + require.JSONEq(t, body, string(failoverErr.ResponseBody)) + require.True(t, failoverErr.BoundUpstreamPassthrough, "标记为上游网关账号的响应,handler 原样回写") + require.False(t, failoverErr.RetryableOnSameAccount) + require.Equal(t, 1, httpStub.calls, "不在同一账号上退避重试") + require.Zero(t, repo.rateLimitedCalls, "不限流整个网关账号") + require.Zero(t, repo.tempCalls) + require.Zero(t, repo.setErrCalls) + }) + } +} + +type fixedChargeCacheStub struct { + billingCacheWorkerStub + balance float64 + sub *SubscriptionCacheData + rate *APIKeyRateLimitCacheData + // reserved 按维度(user:{id} / scope 名)记录在途预留。 + reserved map[string]map[string]float64 +} + +func (s *fixedChargeCacheStub) GetUserBalance(context.Context, int64) (float64, error) { + return s.balance, nil +} + +func (s *fixedChargeCacheStub) GetSubscriptionCache(context.Context, int64, int64) (*SubscriptionCacheData, error) { + if s.sub == nil { + return nil, errors.New("cache miss") + } + return s.sub, nil +} + +func (s *fixedChargeCacheStub) GetAPIKeyRateLimit(context.Context, int64) (*APIKeyRateLimitCacheData, error) { + if s.rate == nil { + return nil, errors.New("cache miss") + } + return s.rate, nil +} + +func (s *fixedChargeCacheStub) reserve(key, requestID string, amount float64) float64 { + if s.reserved == nil { + s.reserved = map[string]map[string]float64{} + } + if s.reserved[key] == nil { + s.reserved[key] = map[string]float64{} + } + sum := 0.0 + for _, v := range s.reserved[key] { + sum += v + } + s.reserved[key][requestID] = amount + return sum +} + +func (s *fixedChargeCacheStub) ReserveInflightBalance(_ context.Context, userID int64, requestID string, amount, balance float64, _ time.Duration) (bool, float64, error) { + key := fmt.Sprintf("user:%d", userID) + others := s.reserve(key, requestID, amount) + if len(s.reserved[key]) > 1 && balance-others < amount { + delete(s.reserved[key], requestID) + return false, others, nil + } + return true, others, nil +} + +func (s *fixedChargeCacheStub) ReleaseInflightBalance(_ context.Context, userID int64, requestID string) error { + delete(s.reserved[fmt.Sprintf("user:%d", userID)], requestID) + return nil +} + +func (s *fixedChargeCacheStub) ReserveInflightScope(_ context.Context, scope, requestID string, amount float64, _ time.Duration) (float64, error) { + return s.reserve(scope, requestID, amount), nil +} + +func (s *fixedChargeCacheStub) ReleaseInflightScope(_ context.Context, scope, requestID string) error { + delete(s.reserved[scope], requestID) + return nil +} + +type fixedChargeAPIKeyRepoStub struct { + APIKeyRepository + data *APIKeyRateLimitData +} + +func (r *fixedChargeAPIKeyRepoStub) GetRateLimitData(context.Context, int64) (*APIKeyRateLimitData, error) { + return r.data, nil +} + +type fixedChargeSubscriptionRepoStub struct { + UserSubscriptionRepository + sub *UserSubscription +} + +func (r *fixedChargeSubscriptionRepoStub) GetActiveByUserIDAndGroupID(context.Context, int64, int64) (*UserSubscription, error) { + return r.sub, nil +} + +func TestReserveFixedCharge(t *testing.T) { + ctx := context.Background() + user := &User{ID: 1} + newSvc := func(cache *fixedChargeCacheStub) *BillingCacheService { + svc := NewBillingCacheService(cache, nil, nil, nil, nil, nil, &config.Config{}, nil) + t.Cleanup(svc.Stop) + return svc + } + reservingSvc := func(cache *fixedChargeCacheStub, subRepo UserSubscriptionRepository, apiKeyRepo APIKeyRepository) *BillingCacheService { + cfg := &config.Config{} + cfg.Billing.InflightReservation.Enabled = true + svc := NewBillingCacheService(cache, nil, subRepo, apiKeyRepo, nil, nil, cfg, nil) + t.Cleanup(svc.Stop) + return svc + } + reserve := func(svc *BillingCacheService, apiKey *APIKey, group *Group, sub *UserSubscription, amount float64) error { + res, err := svc.ReserveFixedCharge(ctx, user, apiKey, group, sub, amount) + res.Release() + return err + } + + t.Run("balance must cover the amount", func(t *testing.T) { + svc := newSvc(&fixedChargeCacheStub{balance: 10}) + require.NoError(t, reserve(svc, nil, nil, nil, 10)) + require.ErrorIs(t, reserve(svc, nil, nil, nil, 10.01), ErrInsufficientBalance) + require.NoError(t, reserve(svc, nil, nil, nil, 0)) + }) + + t.Run("subscription windows must cover the amount", func(t *testing.T) { + daily := 5.0 + group := &Group{ID: 2, SubscriptionType: SubscriptionTypeSubscription, DailyLimitUSD: &daily} + svc := newSvc(&fixedChargeCacheStub{sub: &SubscriptionCacheData{ + Status: SubscriptionStatusActive, ExpiresAt: time.Now().Add(time.Hour), DailyUsage: 3, + }}) + sub := &UserSubscription{ID: 1} + require.NoError(t, reserve(svc, nil, group, sub, 2)) + require.ErrorIs(t, reserve(svc, nil, group, sub, 2.5), ErrDailyLimitExceeded) + }) + + t.Run("api key quota and rate windows include the amount", func(t *testing.T) { + svc := newSvc(&fixedChargeCacheStub{balance: 100, rate: &APIKeyRateLimitCacheData{ + Usage1d: 8, Window1d: time.Now().Unix(), + }}) + quotaKey := &APIKey{ID: 5, Quota: 10, QuotaUsed: 9} + require.NoError(t, reserve(svc, quotaKey, nil, nil, 1)) + require.ErrorIs(t, reserve(svc, quotaKey, nil, nil, 1.5), ErrAPIKeyQuotaExhausted) + + windowKey := &APIKey{ID: 6, RateLimit1d: 10} + require.NoError(t, reserve(svc, windowKey, nil, nil, 2)) + require.ErrorIs(t, reserve(svc, windowKey, nil, nil, 2.5), ErrAPIKeyRateLimit1dExceeded) + }) + + t.Run("usage is read from the database instead of request snapshots", func(t *testing.T) { + now := time.Now() + apiKeyRepo := &fixedChargeAPIKeyRepoStub{data: &APIKeyRateLimitData{QuotaUsed: 9.5, Usage1d: 8, Window1dStart: &now}} + svc := reservingSvc(&fixedChargeCacheStub{balance: 100}, nil, apiKeyRepo) + require.ErrorIs(t, reserve(svc, &APIKey{ID: 5, Quota: 10}, nil, nil, 1), ErrAPIKeyQuotaExhausted, "请求上下文中的 QuotaUsed 可能滞后") + require.ErrorIs(t, reserve(svc, &APIKey{ID: 6, RateLimit1d: 10}, nil, nil, 2.5), ErrAPIKeyRateLimit1dExceeded) + + daily := 5.0 + group := &Group{ID: 2, SubscriptionType: SubscriptionTypeSubscription, DailyLimitUSD: &daily} + subRepo := &fixedChargeSubscriptionRepoStub{sub: &UserSubscription{Status: SubscriptionStatusActive, DailyUsageUSD: 4}} + svc = reservingSvc(&fixedChargeCacheStub{sub: &SubscriptionCacheData{Status: SubscriptionStatusActive}}, subRepo, nil) + require.ErrorIs(t, reserve(svc, nil, group, &UserSubscription{ID: 1}, 2), ErrDailyLimitExceeded, "订阅缓存用量可能滞后") + }) + + t.Run("unsettled charges hold subscription and api key headroom", func(t *testing.T) { + daily := 110.0 + group := &Group{ID: 2, SubscriptionType: SubscriptionTypeSubscription, DailyLimitUSD: &daily} + sub := &UserSubscription{ID: 1} + cache := &fixedChargeCacheStub{balance: 1000, sub: &SubscriptionCacheData{Status: SubscriptionStatusActive}} + svc := reservingSvc(cache, nil, nil) + first, err := svc.ReserveFixedCharge(ctx, user, nil, group, sub, 103.5) + require.NoError(t, err) + _, err = svc.ReserveFixedCharge(ctx, user, nil, group, sub, 103.5) + require.ErrorIs(t, err, ErrDailyLimitExceeded) + first.Release() + second, err := svc.ReserveFixedCharge(ctx, user, nil, group, sub, 103.5) + require.NoError(t, err) + second.Release() + + apiKey := &APIKey{ID: 5, Quota: 110} + first, err = svc.ReserveFixedCharge(ctx, user, apiKey, nil, nil, 103.5) + require.NoError(t, err) + _, err = svc.ReserveFixedCharge(ctx, user, apiKey, nil, nil, 103.5) + require.ErrorIs(t, err, ErrAPIKeyQuotaExhausted) + first.Release() + for key, reservations := range cache.reserved { + require.Empty(t, reservations, "拒绝与释放都不留下预留:%s", key) + } + }) + + t.Run("simple mode skips the check", func(t *testing.T) { + cfg := &config.Config{RunMode: config.RunModeSimple} + svc := NewBillingCacheService(&fixedChargeCacheStub{}, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(svc.Stop) + require.NoError(t, reserve(svc, nil, nil, nil, 1000)) + }) +} diff --git a/backend/internal/service/gemini_cached_content_not_found_test.go b/backend/internal/service/gemini_cached_content_not_found_test.go new file mode 100644 index 000000000..e2637189c --- /dev/null +++ b/backend/internal/service/gemini_cached_content_not_found_test.go @@ -0,0 +1,186 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "io" + "net/http" + "strings" + "testing" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// 上游对不存在、已过期、已删除或不属于当前项目的显式缓存一律返回这个 403。 +const geminiCachedContentNotFoundBody = `{"error":{"code":403,"message":"CachedContent not found (or permission denied)","status":"PERMISSION_DENIED"}}` + +func newGeminiCachedContentTestService(status int, body string) (*GeminiMessagesCompatService, *geminiCompatHTTPUpstreamStub, *errorPolicyRepoStub) { + repo := &errorPolicyRepoStub{} + httpStub := &geminiCompatHTTPUpstreamStub{ + response: &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + }, + } + svc := &GeminiMessagesCompatService{ + httpUpstream: httpStub, + cfg: &config.Config{}, + rateLimitService: NewRateLimitService(repo, nil, &config.Config{}, nil, nil), + } + return svc, httpStub, repo +} + +func geminiDefaultPolicyAPIKeyAccount() *Account { + return &Account{ + ID: 710, + Platform: PlatformGemini, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "test-key", + }, + } +} + +const geminiCachedContentRequestBody = `{"cachedContent":"cachedContents/doesnotexist","contents":[{"role":"user","parts":[{"text":"hi"}]}]}` + +func TestGeminiForwardNative_CachedContentNotFoundPassthroughWithoutAccountPenalty(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tc := range []struct { + name string + action string + stream bool + }{ + {name: "generateContent", action: "generateContent"}, + {name: "streamGenerateContent", action: "streamGenerateContent", stream: true}, + {name: "countTokens", action: "countTokens"}, + } { + t.Run(tc.name, func(t *testing.T) { + svc, httpStub, repo := newGeminiCachedContentTestService(http.StatusForbidden, geminiCachedContentNotFoundBody) + c, rec := newGeminiNativeTestContext(t) + + result, err := svc.ForwardNative(context.Background(), c, geminiDefaultPolicyAPIKeyAccount(), + "gemini-3.8-flash", tc.action, tc.stream, []byte(geminiCachedContentRequestBody)) + + require.Nil(t, result) + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "缓存不存在是请求问题,不应换号") + require.Equal(t, 0, repo.setErrCalls, "不应把账号标记为错误") + require.Equal(t, 0, repo.tempCalls, "不应临时停调度") + require.Equal(t, 1, httpStub.calls, "不应重试") + require.Equal(t, http.StatusForbidden, rec.Code) + require.Equal(t, GeminiCachedContentNotFoundResponse, rec.Body.String(), "应返回标准缓存不存在响应") + require.True(t, IsOpsRequestScopedError(c), "缓存不存在按客户端请求错误统计") + }) + } +} + +func TestGeminiForwardNative_CachedContentNotFoundBypassesTempUnschedulableRules(t *testing.T) { + gin.SetMode(gin.TestMode) + svc, _, repo := newGeminiCachedContentTestService(http.StatusForbidden, geminiCachedContentNotFoundBody) + c, rec := newGeminiNativeTestContext(t) + account := geminiDefaultPolicyAPIKeyAccount() + account.Credentials["temp_unschedulable_enabled"] = true + account.Credentials["temp_unschedulable_rules"] = []any{ + map[string]any{ + "error_code": float64(403), + "keywords": []any{"permission denied"}, + "duration_minutes": float64(10), + "description": "403 permission denied", + }, + } + + _, err := svc.ForwardNative(context.Background(), c, account, + "gemini-3.8-flash", "generateContent", false, []byte(geminiCachedContentRequestBody)) + + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr)) + require.Equal(t, 0, repo.tempCalls, "临时不可调度规则不应命中") + require.Equal(t, 0, repo.setErrCalls) + require.Equal(t, http.StatusForbidden, rec.Code) +} + +func TestGeminiForwardNative_OtherForbiddenStillPenalizesAccount(t *testing.T) { + gin.SetMode(gin.TestMode) + body := `{"error":{"code":403,"message":"Your project has been denied access. Please contact support.","status":"PERMISSION_DENIED"}}` + svc, _, repo := newGeminiCachedContentTestService(http.StatusForbidden, body) + c, _ := newGeminiNativeTestContext(t) + + _, err := svc.ForwardNative(context.Background(), c, geminiDefaultPolicyAPIKeyAccount(), + "gemini-3.8-flash", "generateContent", false, []byte(geminiCachedContentRequestBody)) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "其他 403 仍按账号问题换号") + require.Equal(t, 1, repo.setErrCalls, "其他 403 仍标记账号错误") +} + +// Vertex 对已删除 / 已过期缓存的响应(2026-10 实测):生成请求 400,缓存资源接口 404,文案含上游缓存数字 ID。 +const ( + geminiVertexCachedContentInvalidStateBody = `{"error":{"code":400,"message":"Invalid resource state for cache content 8079767076522164224.","status":"FAILED_PRECONDITION"}}` + geminiVertexCachedContentNotFoundBody = `{"error":{"code":404,"message":"Cached content 8079767076522164224 is not found.","status":"NOT_FOUND"}}` +) + +func TestIsGeminiCachedContentNotFound(t *testing.T) { + require.True(t, isGeminiCachedContentNotFound(http.StatusForbidden, []byte(geminiCachedContentNotFoundBody))) + require.True(t, isGeminiCachedContentNotFound(http.StatusForbidden, + []byte(`[{"error":{"code":403,"message":"CachedContent not found (or permission denied)","status":"PERMISSION_DENIED"}}]`))) + require.True(t, isGeminiCachedContentNotFound(http.StatusBadRequest, []byte(geminiVertexCachedContentInvalidStateBody))) + require.True(t, isGeminiCachedContentNotFound(http.StatusNotFound, []byte(geminiVertexCachedContentNotFoundBody))) + + require.False(t, isGeminiCachedContentNotFound(http.StatusBadRequest, []byte(geminiCachedContentNotFoundBody))) + require.False(t, isGeminiCachedContentNotFound(http.StatusForbidden, + []byte(`{"error":{"code":403,"message":"Permission denied: Consumer has been suspended.","status":"PERMISSION_DENIED"}}`))) + require.False(t, isGeminiCachedContentNotFound(http.StatusNotFound, + []byte(`{"error":{"code":404,"message":"Publisher Model `+"`projects/p/locations/global/publishers/google/models/gemini-9`"+` was not found.","status":"NOT_FOUND"}}`))) + require.False(t, isGeminiCachedContentNotFound(http.StatusBadRequest, + []byte(`{"error":{"code":400,"message":"Tool config, tools and system instruction should not be set in the request when using cached content.","status":"INVALID_ARGUMENT"}}`))) + require.False(t, isGeminiCachedContentNotFound(http.StatusInternalServerError, []byte(geminiVertexCachedContentNotFoundBody))) +} + +func TestGeminiForwardNative_VertexCachedContentNotFoundReturnsStandardForbidden(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tc := range []struct { + name string + status int + body string + action string + stream bool + }{ + {name: "generate invalid resource state", status: http.StatusBadRequest, body: geminiVertexCachedContentInvalidStateBody, action: "generateContent"}, + {name: "stream invalid resource state", status: http.StatusBadRequest, body: geminiVertexCachedContentInvalidStateBody, action: "streamGenerateContent", stream: true}, + {name: "generate not found", status: http.StatusNotFound, body: geminiVertexCachedContentNotFoundBody, action: "generateContent"}, + } { + t.Run(tc.name, func(t *testing.T) { + svc, httpStub, repo := newGeminiCachedContentTestService(tc.status, tc.body) + svc.tokenProvider = NewGeminiTokenProvider(nil, &fakeGeminiTokenCache{token: "ya29.test-token"}, nil) + c, rec := newGeminiNativeTestContext(t) + account := vertexServiceAccount() + account.ID = 811 + + result, err := svc.ForwardNative(context.Background(), c, account, + "gemini-3.8-flash", tc.action, tc.stream, + []byte(`{"cachedContent":"projects/proj-1/locations/global/cachedContents/8079767076522164224","contents":[{"role":"user","parts":[{"text":"hi"}]}]}`)) + + require.Nil(t, result) + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "缓存不存在是请求问题,不应换号") + require.Equal(t, 0, repo.setErrCalls) + require.Equal(t, 0, repo.tempCalls) + require.Empty(t, repo.modelRateLimitCalls, "404 不应按模型不存在记模型限流") + require.Equal(t, 1, httpStub.calls, "不应重试") + require.Equal(t, http.StatusForbidden, rec.Code) + require.Equal(t, GeminiCachedContentNotFoundResponse, rec.Body.String()) + require.NotContains(t, rec.Body.String(), "8079767076522164224", "不应暴露上游缓存 ID") + require.True(t, IsOpsRequestScopedError(c), "缓存不存在按客户端请求错误统计") + errType, _ := OpsLocalErrorType(c) + require.Equal(t, "permission_error", errType) + }) + } +} diff --git a/backend/internal/service/gemini_cached_content_test.go b/backend/internal/service/gemini_cached_content_test.go new file mode 100644 index 000000000..1b7cca4dd --- /dev/null +++ b/backend/internal/service/gemini_cached_content_test.go @@ -0,0 +1,522 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + "testing" + "time" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/stretchr/testify/require" +) + +type geminiCachedContentRepoStub struct { + records map[string]*GeminiCachedContent + nextID int64 + deleted []int64 +} + +func newGeminiCachedContentRepoStub() *geminiCachedContentRepoStub { + return &geminiCachedContentRepoStub{records: map[string]*GeminiCachedContent{}} +} + +func (r *geminiCachedContentRepoStub) Create(_ context.Context, record *GeminiCachedContent) error { + r.nextID++ + record.ID = r.nextID + r.records[record.PublicID] = record + return nil +} + +func (r *geminiCachedContentRepoStub) GetForOwner(_ context.Context, apiKeyID int64, publicID string) (*GeminiCachedContent, error) { + record, ok := r.records[publicID] + if !ok || record.APIKeyID != apiKeyID { + return nil, ErrGeminiCachedContentNotFound + } + return record, nil +} + +func (r *geminiCachedContentRepoStub) ListForOwner(_ context.Context, apiKeyID, groupID int64, activeAt time.Time, beforeID int64, limit int) ([]*GeminiCachedContent, error) { + var out []*GeminiCachedContent + for _, record := range r.records { + if record.APIKeyID == apiKeyID && record.GroupID == groupID && record.ExpireTime.After(activeAt) && (beforeID <= 0 || record.ID < beforeID) { + out = append(out, record) + } + } + if len(out) > limit { + out = out[:limit] + } + return out, nil +} + +func (r *geminiCachedContentRepoStub) BeginMutation(context.Context, int64, time.Time, string, time.Duration) (bool, error) { + return true, nil +} + +func (r *geminiCachedContentRepoStub) TakeOverStaleMutation(context.Context, int64, string, time.Duration) (*GeminiCachedContent, error) { + return nil, nil +} + +func (r *geminiCachedContentRepoStub) CommitMutation(_ context.Context, id int64, _ string, expireTime time.Time) error { + for _, record := range r.records { + if record.ID == id { + record.ExpireTime = expireTime + return nil + } + } + return ErrGeminiCachedContentMutationConflict +} + +func (r *geminiCachedContentRepoStub) ReleaseMutation(context.Context, int64, string) error { + return nil +} + +func (r *geminiCachedContentRepoStub) ListStaleMutations(context.Context, int) ([]int64, error) { + return nil, nil +} + +func (r *geminiCachedContentRepoStub) SoftDelete(_ context.Context, id int64) error { + r.deleted = append(r.deleted, id) + for key, record := range r.records { + if record.ID == id { + delete(r.records, key) + } + } + return nil +} + +func TestParseGeminiCachedContentCreateRequest(t *testing.T) { + now := time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC) + maxTTL := 24 * time.Hour + + t.Run("defaults to one hour and strips output-only fields", func(t *testing.T) { + req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"models/gemini-3.8-flash","displayName":"docs", + "contents":[{"role":"user","parts":[{"text":"x"}]}],"name":"cachedContents/forged","usageMetadata":{"totalTokenCount":1}}`), now, maxTTL) + require.NoError(t, err) + require.Equal(t, "gemini-3.8-flash", req.Model) + require.Equal(t, time.Hour, req.TTL) + require.Equal(t, int64(3600), req.TTLSeconds()) + require.Equal(t, "docs", req.DisplayName) + require.NotContains(t, req.payload, "name") + require.NotContains(t, req.payload, "usageMetadata") + require.Contains(t, req.payload, "contents") + }) + + t.Run("default is capped by a shorter max ttl", func(t *testing.T) { + req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash"}`), now, 30*time.Minute) + require.NoError(t, err) + require.Equal(t, 30*time.Minute, req.TTL) + }) + + t.Run("fractional ttl rounds up to whole seconds", func(t *testing.T) { + req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash","ttl":"3.5s"}`), now, maxTTL) + require.NoError(t, err) + require.Equal(t, int64(4), req.TTLSeconds()) + }) + + t.Run("expireTime converts to ttl", func(t *testing.T) { + req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash","expireTime":"2026-10-09T10:00:00Z"}`), now, maxTTL) + require.NoError(t, err) + require.Equal(t, 2*time.Hour, req.TTL) + }) + + for name, body := range map[string]string{ + "missing model": `{"ttl":"60s"}`, + "vertex style model": `{"model":"projects/p/locations/l/publishers/google/models/x"}`, + "ttl and expireTime": `{"model":"m","ttl":"60s","expireTime":"2026-10-09T10:00:00Z"}`, + "ttl over max": `{"model":"m","ttl":"86401s"}`, + "non positive ttl": `{"model":"m","ttl":"0s"}`, + "ttl without unit": `{"model":"m","ttl":"60"}`, + "expireTime in past": `{"model":"m","expireTime":"2026-10-09T07:00:00Z"}`, + "displayName too long": `{"model":"m","displayName":"` + strings.Repeat("字", 129) + `"}`, + "not an object": `[]`, + } { + t.Run("rejects "+name, func(t *testing.T) { + _, err := ParseGeminiCachedContentCreateRequest([]byte(body), now, maxTTL) + require.Error(t, err) + }) + } +} + +func TestParseGeminiCachedContentPatchRequest(t *testing.T) { + now := time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC) + ttl, err := ParseGeminiCachedContentPatchRequest([]byte(`{"ttl":"7200s"}`), "ttl", now, 24*time.Hour) + require.NoError(t, err) + require.Equal(t, 2*time.Hour, ttl) + + ttl, err = ParseGeminiCachedContentPatchRequest([]byte(`{"expireTime":"2026-10-09T09:00:00Z"}`), "", now, 24*time.Hour) + require.NoError(t, err) + require.Equal(t, time.Hour, ttl) + + _, err = ParseGeminiCachedContentPatchRequest([]byte(`{"displayName":"x"}`), "displayName", now, 24*time.Hour) + require.ErrorContains(t, err, "immutable") + _, err = ParseGeminiCachedContentPatchRequest([]byte(`{"ttl":"60s"}`), "ttl,displayName", now, 24*time.Hour) + require.ErrorContains(t, err, "immutable") + _, err = ParseGeminiCachedContentPatchRequest([]byte(`{}`), "", now, 24*time.Hour) + require.Error(t, err) + _, err = ParseGeminiCachedContentPatchRequest([]byte(`{"ttl":"90000s"}`), "", now, 24*time.Hour) + require.ErrorContains(t, err, "maximum") +} + +func TestGeminiCachedContentReferenceRewrite(t *testing.T) { + ref, err := FindGeminiCachedContentReference([]byte(`{"contents":[]}`)) + require.NoError(t, err) + require.Nil(t, ref) + + body := []byte(`{"cachedContent":"cachedContents/abc","contents":[]}`) + ref, err = FindGeminiCachedContentReference(body) + require.NoError(t, err) + require.Equal(t, "cachedContents/abc", ref.Name) + out, err := RewriteGeminiCachedContentReference(body, ref, "cachedContents/upstream1") + require.NoError(t, err) + require.JSONEq(t, `{"cachedContent":"cachedContents/upstream1","contents":[]}`, string(out)) + + countBody := []byte(`{"generateContentRequest":{"model":"models/m","cachedContent":"cachedContents/abc","contents":[]}}`) + ref, err = FindGeminiCachedContentReference(countBody) + require.NoError(t, err) + out, err = RewriteGeminiCachedContentReference(countBody, ref, "projects/1/locations/us-central1/cachedContents/9") + require.NoError(t, err) + require.JSONEq(t, `{"generateContentRequest":{"model":"models/m","cachedContent":"projects/1/locations/us-central1/cachedContents/9","contents":[]}}`, string(out)) + + _, err = FindGeminiCachedContentReference([]byte(`{"cachedContent":"cachedContents/a","generateContentRequest":{"cachedContent":"cachedContents/b"}}`)) + require.Error(t, err) + _, err = FindGeminiCachedContentReference([]byte(`{"cachedContent":1}`)) + require.Error(t, err) +} + +func TestIsGeminiExplicitCacheAccount(t *testing.T) { + cases := []struct { + name string + account *Account + want bool + }{ + {"official api key", &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k"}}, true}, + {"explicit official base url", &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k", "base_url": "https://generativelanguage.googleapis.com/"}}, true}, + {"reseller base url", &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k", "base_url": "https://relay.example.com"}}, false}, + {"upstream gateway with explicit cache switch", &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k", "base_url": "https://relay.example.com", "explicit_cache_upstream": true}}, true}, + {"official host with path prefix", &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k", "base_url": "https://generativelanguage.googleapis.com/antigravity"}}, false}, + {"missing api key", &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey}, false}, + {"vertex service account", &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount}, true}, + {"vertex api key", &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{"auth_mode": "apikey", "api_key": "k", "project_id": "my-project"}}, false}, + {"oauth", &Account{Platform: PlatformGemini, Type: AccountTypeOAuth}, false}, + {"antigravity api key", &Account{Platform: PlatformAntigravity, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k"}}, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, IsGeminiExplicitCacheAccount(tc.account)) + }) + } +} + +func TestGeminiCachedContentVertexURLs(t *testing.T) { + account := &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{ + "project_id": "proj-1", + "location": "us-central1", + "vertex_model_locations": map[string]any{"gemini-3.8-flash": "global"}, + }} + model, err := GeminiCachedContentUpstreamModelResource(account, "gemini-3.8-flash") + require.NoError(t, err) + require.Equal(t, "projects/proj-1/locations/global/publishers/google/models/gemini-3.8-flash", model) + + collection, err := geminiCachedContentCollectionURL(account, "", "gemini-3.8-flash") + require.NoError(t, err) + require.Equal(t, "https://aiplatform.googleapis.com/v1/projects/proj-1/locations/global/cachedContents", collection) + + collection, err = geminiCachedContentCollectionURL(account, "", "gemini-3.1-pro-preview") + require.NoError(t, err) + require.Equal(t, "https://us-central1-aiplatform.googleapis.com/v1/projects/proj-1/locations/us-central1/cachedContents", collection) + + resource, err := geminiCachedContentResourceURL(account, "", "projects/123/locations/europe-west4/cachedContents/456") + require.NoError(t, err) + require.Equal(t, "https://europe-west4-aiplatform.googleapis.com/v1/projects/123/locations/europe-west4/cachedContents/456", resource) + + _, err = geminiCachedContentResourceURL(account, "", "projects/123/locations/europe-west4/cachedContents/../x") + require.Error(t, err) + _, err = geminiCachedContentResourceURL(&Account{Type: AccountTypeAPIKey}, "https://generativelanguage.googleapis.com", "cachedContents/a/../b") + require.Error(t, err) +} + +func newGeminiCachedContentServiceForTest(t *testing.T, status int, respBody string) (*GeminiCachedContentService, *geminiCompatHTTPUpstreamStub) { + t.Helper() + httpStub := &geminiCompatHTTPUpstreamStub{response: &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(respBody)), + }} + compat := &GeminiMessagesCompatService{httpUpstream: httpStub, cfg: &config.Config{}} + return NewGeminiCachedContentService(newGeminiCachedContentRepoStub(), compat, &config.Config{}), httpStub +} + +func TestGeminiCachedContentCreateUpstreamAIStudio(t *testing.T) { + svc, httpStub := newGeminiCachedContentServiceForTest(t, http.StatusOK, + `{"name":"cachedContents/up123","model":"models/gemini-3.8-flash","usageMetadata":{"totalTokenCount":6273},"expireTime":"2026-10-09T09:50:26.591575799Z"}`) + account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "secret"}} + req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"models/gemini-3.8-flash","displayName":"user label", + "systemInstruction":{"parts":[{"text":"sys"}]},"contents":[{"role":"user","parts":[{"text":"doc"}]}]}`), time.Now(), 24*time.Hour) + require.NoError(t, err) + + upstream, err := svc.CreateUpstream(context.Background(), account, req, "gemini-3.8-flash", "pub1", req.TTL) + require.NoError(t, err) + require.Equal(t, "cachedContents/up123", upstream.Name) + require.Equal(t, int64(6273), upstream.TotalTokenCount) + require.Equal(t, 2026, upstream.ExpireTime.Year()) + + sent := httpStub.lastReq + require.Equal(t, http.MethodPost, sent.Method) + require.Equal(t, "https://generativelanguage.googleapis.com/v1beta/cachedContents", sent.URL.String()) + require.Equal(t, "secret", sent.Header.Get("x-goog-api-key")) + raw, err := io.ReadAll(sent.Body) + require.NoError(t, err) + var payload map[string]any + require.NoError(t, json.Unmarshal(raw, &payload)) + require.Equal(t, "models/gemini-3.8-flash", payload["model"]) + require.Equal(t, "3600s", payload["ttl"]) + require.Equal(t, "s2a-pub1", payload["displayName"], "上游 displayName 写网关标记,用户标签只存本地") + require.Contains(t, payload, "systemInstruction") + require.Contains(t, payload, "contents") +} + +func TestGeminiCachedContentUpstreamErrorClassification(t *testing.T) { + notFoundBody := `{"error":{"code":403,"message":"CachedContent not found (or permission denied)","status":"PERMISSION_DENIED"}}` + svc, _ := newGeminiCachedContentServiceForTest(t, http.StatusForbidden, notFoundBody) + account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "secret"}} + record := &GeminiCachedContent{UpstreamName: "cachedContents/up123"} + + err := svc.DeleteUpstream(context.Background(), account, record) + var upErr *GeminiCachedContentUpstreamError + require.ErrorAs(t, err, &upErr) + require.True(t, upErr.NotFound()) + require.True(t, upErr.RetryableOnOtherAccount()) + + quota := &GeminiCachedContentUpstreamError{StatusCode: http.StatusTooManyRequests} + require.True(t, quota.RetryableOnOtherAccount()) + badRequest := &GeminiCachedContentUpstreamError{StatusCode: http.StatusBadRequest} + require.False(t, badRequest.RetryableOnOtherAccount()) + require.False(t, badRequest.NotFound()) +} + +func TestGeminiCachedContentResolve(t *testing.T) { + repo := newGeminiCachedContentRepoStub() + now := time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC) + svc := NewGeminiCachedContentService(repo, nil, &config.Config{}) + svc.now = func() time.Time { return now } + groupID := int64(5) + require.NoError(t, repo.Create(context.Background(), &GeminiCachedContent{ + PublicID: "abc123", APIKeyID: 1, GroupID: groupID, ExpireTime: now.Add(time.Hour), + })) + require.NoError(t, repo.Create(context.Background(), &GeminiCachedContent{ + PublicID: "expired1", APIKeyID: 1, GroupID: groupID, ExpireTime: now.Add(-time.Second), + })) + + record, err := svc.Resolve(context.Background(), 1, &groupID, "cachedContents/abc123") + require.NoError(t, err) + require.Equal(t, "abc123", record.PublicID) + + otherGroup := int64(6) + for name, call := range map[string]func() error{ + "other api key": func() error { + _, err := svc.Resolve(context.Background(), 2, &groupID, "cachedContents/abc123") + return err + }, + "other group": func() error { + _, err := svc.Resolve(context.Background(), 1, &otherGroup, "cachedContents/abc123") + return err + }, + "expired": func() error { + _, err := svc.Resolve(context.Background(), 1, &groupID, "cachedContents/expired1") + return err + }, + "malformed": func() error { + _, err := svc.Resolve(context.Background(), 1, &groupID, "cachedContents/../x") + return err + }, + } { + t.Run(name, func(t *testing.T) { + require.ErrorIs(t, call(), ErrGeminiCachedContentNotFound) + }) + } +} + +func TestGeminiCachedContentPublicID(t *testing.T) { + id, err := NewGeminiCachedContentPublicID() + require.NoError(t, err) + require.Len(t, id, 40) + parsed, ok := ParseGeminiCachedContentPublicID(GeminiCachedContentNamePrefix + id) + require.True(t, ok) + require.Equal(t, id, parsed) +} + +func TestGeminiCachedContentStoragePricingAndSurcharge(t *testing.T) { + pricing := &PricingService{} + data, err := pricing.parsePricingData([]byte(`{"gemini-3.8-flash":{"litellm_provider":"gemini","input_cost_per_token":0.00000075, + "output_cost_per_token":0.00000375,"cache_read_input_token_cost":0.000000075,"cache_storage_cost_per_token_per_hour":0.0000005}}`)) + require.NoError(t, err) + pricing.pricingData = data + billing := NewBillingService(&config.Config{}, pricing) + + price := billing.CacheStoragePricePerTokenHour("models/gemini-3.8-flash") + require.InDelta(t, 0.0000005, price, 1e-15) + require.Zero(t, billing.CacheStoragePricePerTokenHour("gemini-unknown-model")) + + tokenHours := GeminiCachedContentStorageTokenHours(10000, 2*time.Hour) + require.InDelta(t, 20000, tokenHours, 1e-9) + storage := tokenHours * price + require.InDelta(t, 0.01, storage, 1e-12) + + gateway := &GatewayService{billingService: billing} + groupID := int64(3) + apiKey := &APIKey{GroupID: &groupID, Group: &Group{ID: groupID, Hydrated: true}} + cost := gateway.calculateRecordUsageCost(context.Background(), &ForwardResult{ + Model: "gemini-3.8-flash", + Usage: ClaudeUsage{InputTokens: 10000}, + CacheStorageTokenHours: tokenHours, + }, apiKey, "gemini-3.8-flash", 2, 2, time.Now()) + inputCost := 10000 * 0.00000075 + require.InDelta(t, inputCost+storage, cost.TotalCost, 1e-12) + require.InDelta(t, (inputCost+storage)*2, cost.ActualCost, 1e-12) + + storageOnly := gateway.calculateRecordUsageCost(context.Background(), &ForwardResult{ + Model: "gemini-3.8-flash", + CacheStorageTokenHours: tokenHours, + }, apiKey, "gemini-3.8-flash", 1.5, 1.5, time.Now()) + require.InDelta(t, storage, storageOnly.TotalCost, 1e-12) + require.InDelta(t, storage*1.5, storageOnly.ActualCost, 1e-12) +} + +func TestGeminiCachedContentStorageCostInAccountStats(t *testing.T) { + const ( + model = "gemini-3.8-flash" + groupID = int64(31) + inputTokens = 10000 + storage = 0.01 + inputPrice = 0.00000075 + rulePrice = 0.0000002 + ) + newPricing := func() *PricingService { + pricing := &PricingService{} + data, err := pricing.parsePricingData([]byte(`{"gemini-3.8-flash":{"litellm_provider":"gemini","input_cost_per_token":0.00000075, + "output_cost_per_token":0.00000375,"cache_storage_cost_per_token_per_hour":0.0000005}}`)) + require.NoError(t, err) + pricing.pricingData = data + return pricing + } + officialInput := inputTokens * inputPrice + + for _, tc := range []struct { + name string + channel *Channel + tokens int + wantStats float64 + }{ + {name: "no_channel", tokens: inputTokens, wantStats: officialInput + storage}, + {name: "model_file_pricing", channel: &Channel{ID: 1, Status: StatusActive}, tokens: inputTokens, wantStats: officialInput + storage}, + {name: "apply_pricing_to_account_stats", channel: &Channel{ID: 1, Status: StatusActive, ApplyPricingToAccountStats: true}, + tokens: inputTokens, wantStats: officialInput + storage}, + {name: "custom_rule", channel: &Channel{ID: 1, Status: StatusActive, AccountStatsPricingRules: []AccountStatsPricingRule{{ + GroupIDs: []int64{groupID}, + Pricing: []ChannelModelPricing{{Models: []string{model}, InputPrice: testPtrFloat64(rulePrice)}}, + }}}, tokens: inputTokens, wantStats: inputTokens*rulePrice + storage}, + {name: "storage_only_with_custom_rule", channel: &Channel{ID: 1, Status: StatusActive, AccountStatsPricingRules: []AccountStatsPricingRule{{ + GroupIDs: []int64{groupID}, + Pricing: []ChannelModelPricing{{Models: []string{model}, InputPrice: testPtrFloat64(rulePrice)}}, + }}}, wantStats: storage}, + } { + t.Run(tc.name, func(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}) + svc.billingService = NewBillingService(svc.cfg, newPricing()) + if tc.channel != nil { + svc.channelService = newTestChannelServiceForStats(t, tc.channel, groupID, PlatformGemini) + } + groupRate, accountRate := 1.5, 0.6 + gid := groupID + err := svc.RecordUsage(context.Background(), &RecordUsageInput{ + Result: &ForwardResult{ + RequestID: GeminiCachedContentCreateUsageRequestID(tc.name), + Model: model, + Usage: ClaudeUsage{InputTokens: tc.tokens}, + CacheStorageTokenHours: storage / 0.0000005, + }, + APIKey: &APIKey{ID: 811, GroupID: &gid, Group: &Group{ID: groupID, Platform: PlatformGemini, RateMultiplier: groupRate, Hydrated: true}}, + User: &User{ID: 611}, + Account: &Account{ID: 711, Platform: PlatformGemini, RateMultiplier: &accountRate}, + }) + require.NoError(t, err) + log := usageRepo.lastLog + require.NotNil(t, log) + + wantTotal := float64(tc.tokens)*inputPrice + storage + require.InDelta(t, wantTotal, log.TotalCost, 1e-12) + require.InDelta(t, wantTotal*groupRate, log.ActualCost, 1e-12, "售价 = 官方价 × 分组倍率") + + statsCost := log.TotalCost + if log.AccountStatsCost != nil { + statsCost = *log.AccountStatsCost + } + require.InDelta(t, tc.wantStats, statsCost, 1e-12, "账号统计成本须含存储费且只计一次") + require.NotNil(t, log.AccountRateMultiplier) + require.InDelta(t, tc.wantStats*accountRate, statsCost**log.AccountRateMultiplier, 1e-12, "成本 = 统计成本 × 账号倍率") + }) + } +} + +func TestGeminiExplicitCacheUpstreamTTL(t *testing.T) { + now := time.Date(2026, 10, 9, 8, 0, 0, 0, time.UTC) + upstream := &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "k", "base_url": "https://relay.example.com", "explicit_cache_upstream": true, + "explicit_cache_upstream_max_ttl_seconds": float64(1800), + }} + official := &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "k", "explicit_cache_upstream_max_ttl_seconds": float64(1800), + }} + require.Equal(t, 30*time.Minute, upstream.GeminiExplicitCacheUpstreamMaxTTL()) + require.Zero(t, official.GeminiExplicitCacheUpstreamMaxTTL(), "未开启开关时上限字段不生效") + + svc := NewGeminiCachedContentService(newGeminiCachedContentRepoStub(), nil, &config.Config{}) + require.Equal(t, 30*time.Minute, svc.MaxTTLForAccount(upstream)) + require.Equal(t, 24*time.Hour, svc.MaxTTLForAccount(official)) + + implicit, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash"}`), now, 24*time.Hour) + require.NoError(t, err) + ttl, ok := implicit.TTLForAccount(upstream) + require.True(t, ok) + require.Equal(t, 30*time.Minute, ttl, "未显式指定有效期时按上游上限创建") + ttl, ok = implicit.TTLForAccount(official) + require.True(t, ok) + require.Equal(t, time.Hour, ttl) + + explicit, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash","ttl":"3600s"}`), now, 24*time.Hour) + require.NoError(t, err) + _, ok = explicit.TTLForAccount(upstream) + require.False(t, ok, "显式有效期超过上游上限时该账号不可用") + ttl, ok = explicit.TTLForAccount(official) + require.True(t, ok) + require.Equal(t, time.Hour, ttl) +} + +func TestGeminiCachedContentCreateUpstreamGateway(t *testing.T) { + svc, httpStub := newGeminiCachedContentServiceForTest(t, http.StatusOK, + `{"name":"cachedContents/gatewayid0001","model":"models/gemini-3.8-flash","usageMetadata":{"totalTokenCount":2730},"expireTime":"2026-10-09T09:00:00Z"}`) + account := &Account{ID: 11, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "downstream-key", "base_url": "https://upstream.example.com/gw/", "explicit_cache_upstream": true, + }} + req, err := ParseGeminiCachedContentCreateRequest([]byte(`{"model":"gemini-3.8-flash","contents":[{"role":"user","parts":[{"text":"doc"}]}]}`), time.Now(), 24*time.Hour) + require.NoError(t, err) + + upstream, err := svc.CreateUpstream(context.Background(), account, req, "gemini-3.8-flash", "pub2", 30*time.Minute) + require.NoError(t, err) + require.Equal(t, "cachedContents/gatewayid0001", upstream.Name) + require.Equal(t, "https://upstream.example.com/gw/v1beta/cachedContents", httpStub.lastReq.URL.String()) + require.Equal(t, "downstream-key", httpStub.lastReq.Header.Get("x-goog-api-key")) + raw, err := io.ReadAll(httpStub.lastReq.Body) + require.NoError(t, err) + require.Contains(t, string(raw), `"ttl":"1800s"`) + + resource, err := geminiCachedContentResourceURL(account, geminiCachedContentAPIBase(account), upstream.Name) + require.NoError(t, err) + require.Equal(t, "https://upstream.example.com/gw/v1beta/cachedContents/gatewayid0001", resource) +} diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index bb2503623..46e016ec7 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -42,7 +42,16 @@ func (s *GeminiMessagesCompatService) ForwardAsChatCompletions( clientStream := ccReq.Stream includeUsage := ccReq.StreamOptions != nil && ccReq.StreamOptions.IncludeUsage - responsesReq, err := apicompat.ChatCompletionsToResponses(&ccReq) + // 历史推理内容不回传给 Gemini:Gemini 的思考连续性由 thoughtSignature 承载。 + for i := range ccReq.Messages { + ccReq.Messages[i].ReasoningContent = "" + ccReq.Messages[i].Reasoning = "" + if ccReq.Messages[i].Role == "assistant" { + ccReq.Messages[i].Content = dropChatReasoningContentParts(ccReq.Messages[i].Content) + } + } + + responsesReq, err := chatCompletionsToResponses(s.cfg, &ccReq) if err != nil { return nil, s.writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) } @@ -92,6 +101,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( return nil, s.writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) } geminiReq = ensureGeminiFunctionCallThoughtSignatures(geminiReq) + geminiReq = applyGeminiCompatThinkingConfig(geminiReq, claudeBody, mappedModel, clientStream) proxyURL := "" if account.ProxyID != nil && account.Proxy != nil { @@ -112,12 +122,17 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( ) var resp *http.Response + // checkedPolicy 是循环内对当前 resp 的错误策略检查结果,未检查时为 nil。 + var checkedPolicy *ErrorPolicyResult for attempt := 1; attempt <= geminiMaxRetries; attempt++ { upstreamReq, idHeader, err := buildReq(ctx) if err != nil { if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { return nil, err } + if failoverErr := s.handleVertexServiceAccountNotFound(ctx, c, account, err); failoverErr != nil { + return nil, failoverErr + } return nil, s.writeChatCompletionsError(c, http.StatusBadGateway, "upstream_error", err.Error()) } requestIDHeader = idHeader @@ -127,11 +142,11 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( return nil, s.handleUpstreamTransportError(ctx, c, account, err) } - if matched, rebuilt := s.checkErrorPolicyInLoop(ctx, account, resp, mappedModel); matched { - resp = rebuilt + checked, rebuilt := s.checkErrorPolicyInLoop(ctx, account, resp, mappedModel) + resp = rebuilt + checkedPolicy = checked + if checked != nil && *checked != ErrorPolicyNone { break - } else { - resp = rebuilt } if resp.StatusCode >= 400 && s.shouldRetryGeminiUpstreamError(account, resp.StatusCode) { @@ -196,7 +211,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( respBody := s.readUpstreamErrorBody(resp) policy := ErrorPolicyNone if s.rateLimitService != nil { - policy = s.rateLimitService.CheckErrorPolicy(ctx, account, resp.StatusCode, respBody, mappedModel) + policy = s.finalErrorPolicy(ctx, account, resp.StatusCode, respBody, mappedModel, checkedPolicy) } // 与 messages 兼容层一致:只有 None / Matched 才走账号状态处理。 // Skipped(池模式、或自定义错误码未命中)与 TempUnscheduled 已由策略层裁决完毕。 @@ -399,19 +414,11 @@ func (s *GeminiMessagesCompatService) buildGeminiChatCompletionsUpstreamRequestF case AccountTypeServiceAccount: return func(ctx context.Context) (*http.Request, string, error) { - if s.tokenProvider == nil { - return nil, "", errors.New("gemini token provider not configured") - } - accessToken, err := s.tokenProvider.GetAccessToken(ctx, account) - if err != nil { - return nil, "", err - } - action := "generateContent" if clientStream { action = "streamGenerateContent" } - fullURL, err := buildVertexGeminiURL(account.VertexProjectID(), account.VertexLocation(mappedModel), mappedModel, action, clientStream) + fullURL, err := buildVertexGeminiAccountURL(account, mappedModel, action, clientStream) if err != nil { return nil, "", err } @@ -422,7 +429,9 @@ func (s *GeminiMessagesCompatService) buildGeminiChatCompletionsUpstreamRequestF return nil, "", err } upstreamReq.Header.Set("Content-Type", "application/json") - upstreamReq.Header.Set("Authorization", "Bearer "+accessToken) + if err := setVertexGeminiAuth(ctx, upstreamReq, account, s.tokenProvider); err != nil { + return nil, "", err + } return upstreamReq, "x-request-id", nil }, "x-request-id" @@ -571,6 +580,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom openBlockIndex := -1 openBlockType := "" seenText := "" + seenThought := "" openToolIndex := -1 openToolName := "" seenToolJSON := "" @@ -625,6 +635,41 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom } for _, part := range extractGeminiParts(geminiResp) { + if text, ok := part["text"].(string); ok && isGeminiThoughtPart(part) { + delta, newSeen := computeGeminiTextDelta(seenThought, text) + seenThought = newSeen + if delta == "" { + continue + } + if openToolIndex >= 0 { + if closeOpenTool() { + return &geminiStreamResult{usage: &usage, firstTokenMs: firstTokenMs}, nil + } + } + if openBlockType != "thinking" { + if closeOpenBlock() { + return &geminiStreamResult{usage: &usage, firstTokenMs: firstTokenMs}, nil + } + idx := nextBlockIndex + nextBlockIndex++ + openBlockIndex = idx + openBlockType = "thinking" + if emitAnthropicEvent(&apicompat.AnthropicStreamEvent{ + Type: "content_block_start", + Index: &idx, + ContentBlock: &apicompat.AnthropicContentBlock{Type: "thinking"}, + }) { + return &geminiStreamResult{usage: &usage, firstTokenMs: firstTokenMs}, nil + } + } + if emitAnthropicEvent(&apicompat.AnthropicStreamEvent{ + Type: "content_block_delta", + Delta: &apicompat.AnthropicDelta{Type: "thinking_delta", Thinking: delta}, + }) { + return &geminiStreamResult{usage: &usage, firstTokenMs: firstTokenMs}, nil + } + continue + } if text, ok := part["text"].(string); ok && text != "" { if openToolIndex >= 0 { if closeOpenTool() { diff --git a/backend/internal/service/gemini_compat_thinking.go b/backend/internal/service/gemini_compat_thinking.go new file mode 100644 index 000000000..6c75dd919 --- /dev/null +++ b/backend/internal/service/gemini_compat_thinking.go @@ -0,0 +1,320 @@ +package service + +import ( + "bytes" + "encoding/json" + "strconv" + "strings" + + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// geminiThinkingParam 是上游模型接受的思考参数形态。 +type geminiThinkingParam int + +const ( + geminiThinkingParamNone geminiThinkingParam = iota + geminiThinkingParamBudget + geminiThinkingParamLevel +) + +const ( + gemini25ProMaxThinkingBudget = 32768 + gemini25ProMinThinkingBudget = 128 + gemini25FlashMaxThinkingBudget = 24576 + gemini25FlashLiteMinThinkingBudget = 512 +) + +// geminiThinkingParamForModel 按上游模型名判断思考参数形态:2.5 系列用 thinkingBudget, +// 3 及以上用 thinkingLevel。2.5 之前的版本、无法解析版本号的名字、图像/语音/向量类模型 +// 不写思考参数。 +func geminiThinkingParamForModel(model string) geminiThinkingParam { + name := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(model)), "models/") + rest, ok := strings.CutPrefix(name, "gemini-") + if !ok { + return geminiThinkingParamNone + } + for _, kind := range []string{"image", "tts", "embedding", "live", "audio"} { + if strings.Contains(rest, kind) { + return geminiThinkingParamNone + } + } + version, _, _ := strings.Cut(rest, "-") + majorText, minorText, _ := strings.Cut(version, ".") + major, err := strconv.Atoi(majorText) + if err != nil { + return geminiThinkingParamNone + } + minor := 0 + if minorText != "" { + if minor, err = strconv.Atoi(minorText); err != nil { + return geminiThinkingParamNone + } + } + switch { + case major >= 3: + return geminiThinkingParamLevel + case major == 2 && minor >= 5: + return geminiThinkingParamBudget + default: + return geminiThinkingParamNone + } +} + +// geminiModelNameCarriesThinkingTier 判断模型名是否以档位后缀结尾(如 -low/-high), +// 这类名字由上游按名字选档,不再叠加思考档位参数。 +func geminiModelNameCarriesThinkingTier(model string) bool { + name := strings.ToLower(strings.TrimSpace(model)) + for _, suffix := range []string{"-minimal", "-low", "-medium", "-high", "-xhigh", "-max", "-tiered"} { + if strings.HasSuffix(name, suffix) { + return true + } + } + return false +} + +// claudeThinkingIntent 是 Anthropic 请求体里与思考相关的意图。 +type claudeThinkingIntent struct { + thinkingType string // enabled / adaptive / disabled / 空 + tier string // minimal / low / medium / high / 空 + budgetTokens int // thinking.type=enabled 时的 budget_tokens +} + +// parseClaudeThinkingIntent 读取 Anthropic 请求的思考参数。thinking.type=disabled 优先于 +// output_config.effort;effort 归一到 minimal/low/medium/high,未识别的取值视为未指定。 +func parseClaudeThinkingIntent(claudeBody []byte) claudeThinkingIntent { + intent := claudeThinkingIntent{ + thinkingType: strings.ToLower(strings.TrimSpace(gjson.GetBytes(claudeBody, "thinking.type").String())), + } + if intent.thinkingType == "disabled" { + intent.tier = "minimal" + return intent + } + switch strings.ToLower(strings.TrimSpace(gjson.GetBytes(claudeBody, "output_config.effort").String())) { + case "none", "minimal": + intent.tier = "minimal" + case "low": + intent.tier = "low" + case "medium": + intent.tier = "medium" + case "high", "xhigh", "max": + intent.tier = "high" + } + if intent.thinkingType == "enabled" { + intent.budgetTokens = int(gjson.GetBytes(claudeBody, "thinking.budget_tokens").Int()) + } + return intent +} + +// claudeRequestEnablesThinking 判断 Anthropic 请求是否开启了思考输出。 +func claudeRequestEnablesThinking(claudeBody []byte) bool { + switch parseClaudeThinkingIntent(claudeBody).thinkingType { + case "enabled", "adaptive": + return true + default: + return false + } +} + +// geminiThinkingLevelFor 把思考意图映射为 thinkingLevel;返回空串表示交给模型默认档位。 +// minimal 只发给 flash 系列,其余模型用 low;medium 只发给 flash 系列与 Gemini 3.1 Pro, +// 其余模型用 high(Gemini 3 及以上未指定档位时的默认档位)。 +func geminiThinkingLevelFor(model string, intent claudeThinkingIntent) string { + tier := intent.tier + if tier == "" && intent.budgetTokens > 0 { + switch { + case intent.budgetTokens <= 1024: + tier = "low" + case intent.budgetTokens <= 8192: + tier = "medium" + default: + tier = "high" + } + } + name := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(model)), "models/") + isFlash := strings.Contains(name, "flash") + if tier == "minimal" && !isFlash { + tier = "low" + } + if tier == "medium" && !isFlash && !strings.HasPrefix(name, "gemini-3.1-pro") { + tier = "high" + } + return tier +} + +// geminiThinkingBudgetFor 把思考意图映射为 Gemini 2.5 的 thinkingBudget;ok=false 表示交给 +// 模型动态预算。Pro 不能关闭思考(最小 128,最大 32768),Flash 为 0–24576, +// Flash-Lite 的正预算最小 512。 +func geminiThinkingBudgetFor(model string, intent claudeThinkingIntent) (budget int, ok bool) { + name := strings.ToLower(model) + isPro := strings.Contains(name, "pro") + maxBudget, minPositive := gemini25FlashMaxThinkingBudget, 1 + switch { + case isPro: + maxBudget, minPositive = gemini25ProMaxThinkingBudget, gemini25ProMinThinkingBudget + case strings.Contains(name, "flash-lite"): + minPositive = gemini25FlashLiteMinThinkingBudget + } + switch intent.tier { + case "minimal": + if isPro { + return gemini25ProMinThinkingBudget, true + } + return 0, true + case "low": + budget = 1024 + case "medium": + budget = 8192 + case "high": + budget = maxBudget + default: + if intent.budgetTokens <= 0 { + return 0, false + } + budget = intent.budgetTokens + } + budget = min(max(budget, minPositive), maxBudget) + return budget, true +} + +// applyGeminiCompatThinkingConfig 把兼容入口(Anthropic 形态请求体)的思考意图写进转换后的 +// Gemini 请求 generationConfig.thinkingConfig。includeThoughts 为 true 时要求上游返回 +// 思考摘要(thought=true 的 part);思考被关闭(预算为 0)时不要求。 +func applyGeminiCompatThinkingConfig(geminiReq, claudeBody []byte, upstreamModel string, includeThoughts bool) []byte { + param := geminiThinkingParamForModel(upstreamModel) + if param == geminiThinkingParamNone { + return geminiReq + } + intent := parseClaudeThinkingIntent(claudeBody) + out := geminiReq + thinkingOff := false + if !geminiModelNameCarriesThinkingTier(upstreamModel) { + switch param { + case geminiThinkingParamLevel: + if level := geminiThinkingLevelFor(upstreamModel, intent); level != "" { + out = setGeminiThinkingField(out, "thinkingLevel", level) + } + case geminiThinkingParamBudget: + if budget, ok := geminiThinkingBudgetFor(upstreamModel, intent); ok { + out = setGeminiThinkingField(out, "thinkingBudget", budget) + thinkingOff = budget == 0 + } + } + } + if includeThoughts && !thinkingOff { + out = setGeminiThinkingField(out, "includeThoughts", true) + } + return out +} + +func setGeminiThinkingField(body []byte, field string, value any) []byte { + updated, err := sjson.SetBytes(body, "generationConfig.thinkingConfig."+field, value) + if err != nil { + return body + } + return updated +} + +// isGeminiThoughtPart 判断响应 part 是否为思考摘要。 +func isGeminiThoughtPart(part map[string]any) bool { + thought, _ := part["thought"].(bool) + return thought +} + +// dropClaudeHistoryThinkingBlocks 删除 Anthropic 请求历史消息里的 thinking/redacted_thinking 块, +// 只含思考块的消息整条删除;与 convertClaudeMessagesToGeminiContents 的取舍一致,供签名降级 +// 重试在把思考块改写成正文之前使用。 +func dropClaudeHistoryThinkingBlocks(claudeBody []byte) []byte { + var req map[string]any + if err := json.Unmarshal(claudeBody, &req); err != nil { + return claudeBody + } + messages, ok := req["messages"].([]any) + if !ok { + return claudeBody + } + changed := false + kept := make([]any, 0, len(messages)) + for _, m := range messages { + mm, ok := m.(map[string]any) + if !ok { + kept = append(kept, m) + continue + } + blocks, ok := mm["content"].([]any) + if !ok { + kept = append(kept, m) + continue + } + filtered := make([]any, 0, len(blocks)) + for _, block := range blocks { + if bm, ok := block.(map[string]any); ok { + if bt, _ := bm["type"].(string); bt == "thinking" || bt == "redacted_thinking" { + continue + } + } + filtered = append(filtered, block) + } + if len(filtered) == len(blocks) { + kept = append(kept, m) + continue + } + // 原消息是多块,转换器会过滤空白正文块;删掉思考块后同样过滤,避免剩下的单块空白正文被原样发出。 + nonBlank := filtered[:0] + for _, block := range filtered { + if bm, ok := block.(map[string]any); ok { + if bt, _ := bm["type"].(string); bt == "text" { + if text, _ := bm["text"].(string); strings.TrimSpace(text) == "" { + continue + } + } + } + nonBlank = append(nonBlank, block) + } + filtered = nonBlank + changed = true + if len(filtered) == 0 { + continue + } + mm["content"] = filtered + kept = append(kept, mm) + } + if !changed { + return claudeBody + } + req["messages"] = kept + out, err := json.Marshal(req) + if err != nil { + return claudeBody + } + return out +} + +// dropChatReasoningContentParts 删除 Chat Completions assistant 消息 content 数组里 +// type 为 thinking/reasoning 的部分;字符串形态的 content 原样返回。 +func dropChatReasoningContentParts(content json.RawMessage) json.RawMessage { + if !bytes.HasPrefix(bytes.TrimSpace(content), []byte("[")) { + return content + } + var parts []json.RawMessage + if err := json.Unmarshal(content, &parts); err != nil { + return content + } + kept := make([]json.RawMessage, 0, len(parts)) + for _, part := range parts { + switch gjson.GetBytes(part, "type").String() { + case "thinking", "reasoning": + continue + } + kept = append(kept, part) + } + if len(kept) == len(parts) { + return content + } + out, err := json.Marshal(kept) + if err != nil { + return content + } + return out +} diff --git a/backend/internal/service/gemini_compat_thinking_test.go b/backend/internal/service/gemini_compat_thinking_test.go new file mode 100644 index 000000000..feea6f890 --- /dev/null +++ b/backend/internal/service/gemini_compat_thinking_test.go @@ -0,0 +1,367 @@ +package service + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestApplyGeminiCompatThinkingConfig(t *testing.T) { + budget := func(v int64) *int64 { return &v } + const baseReq = `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"generationConfig":{"maxOutputTokens":8192}}` + tests := []struct { + name string + model string + claudeBody string + includeThoughts bool + wantLevel string + wantBudget *int64 + wantThoughts bool + wantNoConfig bool + }{ + {name: "effort medium on flash", model: "gemini-3.8-flash", claudeBody: `{"output_config":{"effort":"medium"},"thinking":{"type":"enabled","budget_tokens":4096}}`, wantLevel: "medium"}, + {name: "effort low", model: "gemini-3.7-flash", claudeBody: `{"output_config":{"effort":"low"}}`, wantLevel: "low"}, + {name: "effort none on flash", model: "gemini-3.8-flash", claudeBody: `{"output_config":{"effort":"none"},"thinking":{"type":"enabled","budget_tokens":10240}}`, wantLevel: "minimal"}, + {name: "effort minimal on pro", model: "gemini-3.1-pro-preview", claudeBody: `{"output_config":{"effort":"minimal"}}`, wantLevel: "low"}, + {name: "effort medium on gemini 3 pro", model: "gemini-3-pro-preview", claudeBody: `{"output_config":{"effort":"medium"}}`, wantLevel: "high"}, + {name: "effort medium on gemini 3.1 pro", model: "gemini-3.1-pro-preview", claudeBody: `{"output_config":{"effort":"medium"}}`, wantLevel: "medium"}, + {name: "effort max", model: "gemini-3.7-flash", claudeBody: `{"output_config":{"effort":"max"}}`, wantLevel: "high"}, + {name: "effort xhigh", model: "gemini-3.7-flash", claudeBody: `{"output_config":{"effort":"xhigh"}}`, wantLevel: "high"}, + {name: "thinking disabled wins over effort", model: "gemini-3.8-flash", claudeBody: `{"thinking":{"type":"disabled"},"output_config":{"effort":"high"}}`, wantLevel: "minimal"}, + {name: "budget only maps to high", model: "gemini-3.8-flash", claudeBody: `{"thinking":{"type":"enabled","budget_tokens":31999}}`, wantLevel: "high"}, + {name: "budget only maps to medium", model: "gemini-3.8-flash", claudeBody: `{"thinking":{"type":"enabled","budget_tokens":4096}}`, wantLevel: "medium"}, + {name: "budget only maps to low", model: "gemini-3.8-flash", claudeBody: `{"thinking":{"type":"enabled","budget_tokens":1024}}`, wantLevel: "low"}, + {name: "adaptive keeps default level", model: "gemini-3.7-flash", claudeBody: `{"thinking":{"type":"adaptive"}}`, includeThoughts: true, wantThoughts: true}, + {name: "no thinking params streams thoughts only", model: "gemini-3.7-flash", claudeBody: `{}`, includeThoughts: true, wantThoughts: true}, + {name: "unknown effort ignored", model: "gemini-3.7-flash", claudeBody: `{"output_config":{"effort":"turbo"}}`, wantNoConfig: true}, + {name: "level with thoughts", model: "gemini-3.8-flash", claudeBody: `{"output_config":{"effort":"high"}}`, includeThoughts: true, wantLevel: "high", wantThoughts: true}, + {name: "gemini 4 uses level", model: "gemini-4-argon", claudeBody: `{"output_config":{"effort":"low"}}`, wantLevel: "low"}, + {name: "medium outside verified models becomes high", model: "gemini-4-argon", claudeBody: `{"output_config":{"effort":"medium"}}`, wantLevel: "high"}, + {name: "medium budget outside verified models becomes high", model: "gemini-4-argon", claudeBody: `{"thinking":{"type":"enabled","budget_tokens":4096}}`, wantLevel: "high"}, + {name: "medium on unverified pro becomes high", model: "gemini-3.5-pro", claudeBody: `{"output_config":{"effort":"medium"}}`, wantLevel: "high"}, + {name: "medium on flash lite", model: "gemini-3.1-flash-lite", claudeBody: `{"output_config":{"effort":"medium"}}`, wantLevel: "medium"}, + {name: "tier suffix model keeps name tier", model: "gemini-4-argon-high", claudeBody: `{"output_config":{"effort":"low"}}`, includeThoughts: true, wantThoughts: true}, + {name: "tiered suffix model keeps name tier", model: "gemini-3.8-flash-tiered", claudeBody: `{"output_config":{"effort":"low"}}`, includeThoughts: true, wantThoughts: true}, + {name: "2.5 flash low", model: "gemini-2.5-flash", claudeBody: `{"output_config":{"effort":"low"}}`, wantBudget: budget(1024)}, + {name: "2.5 flash high", model: "gemini-2.5-flash", claudeBody: `{"output_config":{"effort":"high"}}`, includeThoughts: true, wantBudget: budget(24576), wantThoughts: true}, + {name: "2.5 flash none disables thinking and thoughts", model: "gemini-2.5-flash", claudeBody: `{"output_config":{"effort":"none"}}`, includeThoughts: true, wantBudget: budget(0)}, + {name: "2.5 pro cannot disable thinking", model: "gemini-2.5-pro", claudeBody: `{"thinking":{"type":"disabled"}}`, includeThoughts: true, wantBudget: budget(128), wantThoughts: true}, + {name: "2.5 pro high", model: "gemini-2.5-pro", claudeBody: `{"output_config":{"effort":"max"}}`, wantBudget: budget(32768)}, + {name: "2.5 pro budget clamps up", model: "gemini-2.5-pro", claudeBody: `{"thinking":{"type":"enabled","budget_tokens":50}}`, wantBudget: budget(128)}, + {name: "2.5 flash budget clamps down", model: "gemini-2.5-flash", claudeBody: `{"thinking":{"type":"enabled","budget_tokens":31999}}`, wantBudget: budget(24576)}, + {name: "2.5 flash lite budget clamps up", model: "gemini-2.5-flash-lite", claudeBody: `{"thinking":{"type":"enabled","budget_tokens":100}}`, wantBudget: budget(512)}, + {name: "2.5 adaptive keeps dynamic budget", model: "gemini-2.5-flash", claudeBody: `{"thinking":{"type":"adaptive"}}`, wantNoConfig: true}, + {name: "2.0 untouched", model: "gemini-2.0-flash", claudeBody: `{"output_config":{"effort":"high"}}`, includeThoughts: true, wantNoConfig: true}, + {name: "image model untouched", model: "gemini-3-pro-image-preview", claudeBody: `{"output_config":{"effort":"high"}}`, includeThoughts: true, wantNoConfig: true}, + {name: "unparsable model untouched", model: "gemini-flash-latest", claudeBody: `{"output_config":{"effort":"high"}}`, includeThoughts: true, wantNoConfig: true}, + {name: "non gemini model untouched", model: "custom-model", claudeBody: `{"output_config":{"effort":"high"}}`, includeThoughts: true, wantNoConfig: true}, + {name: "models prefix", model: "models/gemini-3.8-flash", claudeBody: `{"output_config":{"effort":"low"}}`, wantLevel: "low"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + out := applyGeminiCompatThinkingConfig([]byte(baseReq), []byte(tt.claudeBody), tt.model, tt.includeThoughts) + require.Equal(t, int64(8192), gjson.GetBytes(out, "generationConfig.maxOutputTokens").Int()) + require.Equal(t, "hi", gjson.GetBytes(out, "contents.0.parts.0.text").String()) + cfg := gjson.GetBytes(out, "generationConfig.thinkingConfig") + if tt.wantNoConfig { + require.False(t, cfg.Exists(), cfg.Raw) + return + } + require.Equal(t, tt.wantLevel, cfg.Get("thinkingLevel").String()) + if tt.wantBudget != nil { + require.True(t, cfg.Get("thinkingBudget").Exists(), cfg.Raw) + require.Equal(t, *tt.wantBudget, cfg.Get("thinkingBudget").Int()) + } else { + require.False(t, cfg.Get("thinkingBudget").Exists(), cfg.Raw) + } + require.Equal(t, tt.wantThoughts, cfg.Get("includeThoughts").Bool(), cfg.Raw) + require.False(t, cfg.Get("thinkingLevel").Exists() && cfg.Get("thinkingBudget").Exists(), "thinkingLevel and thinkingBudget are mutually exclusive") + }) + } +} + +func geminiCompatThinkingTestAccount() *Account { + return &Account{ + ID: 611, + Platform: PlatformGemini, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "gemini-api-key"}, + Concurrency: 1, + } +} + +func TestGeminiForwardAsChatCompletions_StreamsThoughtsAsReasoningContent(t *testing.T) { + gin.SetMode(gin.TestMode) + upstreamBody := `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"Weighing options","thought":true}]}}]}` + "\n\n" + + `data: {"candidates":[{"content":{"role":"model","parts":[{"text":" carefully.","thought":true}]}}]}` + "\n\n" + + `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"Final answer","thoughtSignature":"sig"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":4,"candidatesTokenCount":2,"thoughtsTokenCount":7}}` + "\n\n" + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }}} + svc := &GeminiMessagesCompatService{httpUpstream: upstream, cfg: &config.Config{}} + body := []byte(`{"model":"gemini-3.8-flash","stream":true,"reasoning_effort":"medium","messages":[{"role":"user","content":"hi"}]}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body) + + result, err := svc.ForwardAsChatCompletions(context.Background(), c, geminiCompatThinkingTestAccount(), body) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + require.Equal(t, "medium", gjson.GetBytes(upstream.requestBodies[0], "generationConfig.thinkingConfig.thinkingLevel").String()) + require.True(t, gjson.GetBytes(upstream.requestBodies[0], "generationConfig.thinkingConfig.includeThoughts").Bool()) + require.Equal(t, "medium", optionalStringValue(result.ReasoningEffort)) + require.Equal(t, 9, result.Usage.OutputTokens) + + var reasoning, content strings.Builder + firstContentChunk, lastReasoningChunk := -1, -1 + for i, line := range strings.Split(recorder.Body.String(), "\n") { + payload, ok := strings.CutPrefix(line, "data: ") + if !ok || payload == "[DONE]" { + continue + } + delta := gjson.Get(payload, "choices.0.delta") + if r := delta.Get("reasoning_content"); r.Exists() { + _, _ = reasoning.WriteString(r.String()) + lastReasoningChunk = i + } + if text := delta.Get("content"); text.Exists() && text.String() != "" { + _, _ = content.WriteString(text.String()) + if firstContentChunk < 0 { + firstContentChunk = i + } + } + } + require.Equal(t, "Weighing options carefully.", reasoning.String()) + require.Equal(t, "Final answer", content.String()) + require.Less(t, lastReasoningChunk, firstContentChunk) +} + +func TestGeminiForwardAsChatCompletions_NonStreamForwardsEffortWithoutThoughts(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":1}}`)), + }}} + svc := &GeminiMessagesCompatService{httpUpstream: upstream, cfg: &config.Config{}} + body := []byte(`{"model":"gemini-3.8-flash","reasoning_effort":"none","messages":[{"role":"user","content":"hi"}]}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body) + + result, err := svc.ForwardAsChatCompletions(context.Background(), c, geminiCompatThinkingTestAccount(), body) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + cfg := gjson.GetBytes(upstream.requestBodies[0], "generationConfig.thinkingConfig") + require.Equal(t, "minimal", cfg.Get("thinkingLevel").String()) + require.False(t, cfg.Get("includeThoughts").Exists(), cfg.Raw) + require.Equal(t, "minimal", optionalStringValue(result.ReasoningEffort)) + require.Equal(t, "ok", gjson.Get(recorder.Body.String(), "choices.0.message.content").String()) +} + +func TestGeminiMessagesForward_IncludeThoughtsFollowsClientThinking(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + body string + wantThoughts bool + wantLevel string + }{ + {name: "stream with adaptive thinking", body: `{"model":"gemini-3.7-flash","stream":true,"max_tokens":1024,"thinking":{"type":"adaptive"},"output_config":{"effort":"medium"},"messages":[{"role":"user","content":"hi"}]}`, wantThoughts: true, wantLevel: "medium"}, + {name: "stream without thinking", body: `{"model":"gemini-3.7-flash","stream":true,"max_tokens":1024,"messages":[{"role":"user","content":"hi"}]}`}, + {name: "non stream with thinking", body: `{"model":"gemini-3.7-flash","max_tokens":1024,"thinking":{"type":"enabled","budget_tokens":31999},"messages":[{"role":"user","content":"hi"}]}`, wantLevel: "high"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + stream := gjson.Get(tt.body, "stream").Bool() + respBody := `{"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":1}}` + contentType := "application/json" + if stream { + respBody = "data: " + respBody + "\n\n" + contentType = "text/event-stream" + } + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{contentType}}, + Body: io.NopCloser(strings.NewReader(respBody)), + }}} + svc := &GeminiMessagesCompatService{httpUpstream: upstream, cfg: &config.Config{}} + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/messages", []byte(tt.body)) + + result, err := svc.Forward(context.Background(), c, geminiCompatThinkingTestAccount(), []byte(tt.body)) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + cfg := gjson.GetBytes(upstream.requestBodies[0], "generationConfig.thinkingConfig") + require.Equal(t, tt.wantThoughts, cfg.Get("includeThoughts").Bool(), cfg.Raw) + require.Equal(t, tt.wantLevel, cfg.Get("thinkingLevel").String(), cfg.Raw) + require.Equal(t, tt.wantLevel, optionalStringValue(result.ReasoningEffort)) + }) + } +} + +func TestGeminiMessagesHandleStreamingResponse_EmitsThinkingBlockBeforeText(t *testing.T) { + gin.SetMode(gin.TestMode) + upstreamBody := `data: {"candidates":[{"content":{"parts":[{"text":"Plan the reply","thought":true}]}}]}` + "\n\n" + + `data: {"candidates":[{"content":{"parts":[{"text":"Hello"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":1,"thoughtsTokenCount":4}}` + "\n\n" + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + svc := &GeminiMessagesCompatService{} + + result, err := svc.handleStreamingResponse(c, resp, time.Now(), "claude-sonnet-4-5") + require.NoError(t, err) + require.NotNil(t, result.firstTokenMs) + + events := parseAnthropicContentBlockEvents(t, rec.Body.String()) + open := -1 + var started []string + for _, ev := range events { + switch ev.event { + case "content_block_start": + require.Equalf(t, -1, open, "block %d opened while block %d was still open", ev.index, open) + open = ev.index + started = append(started, ev.blockType) + case "content_block_stop": + require.Equal(t, open, ev.index) + open = -1 + } + } + require.Equal(t, -1, open) + require.Equal(t, []string{"thinking", "text"}, started) + + out := rec.Body.String() + require.Contains(t, out, `"content_block":{"signature":"","thinking":"","type":"thinking"}`) + require.Contains(t, out, `"type":"thinking_delta"`) + require.Contains(t, out, `"thinking":"Plan the reply"`) + require.NotContains(t, out, `"text":"Plan the reply"`) +} + +func TestConvertClaudeMessagesToGemini_DropsHistoryThinkingBlocks(t *testing.T) { + body := []byte(`{"model":"gemini-3.7-flash","max_tokens":1024,"messages":[ + {"role":"user","content":"hi"}, + {"role":"assistant","content":[{"type":"thinking","thinking":"PRIOR_THOUGHT","signature":""},{"type":"text","text":"Hello"}]}, + {"role":"user","content":"again"}, + {"role":"assistant","content":[{"type":"thinking","thinking":"ONLY_THOUGHT","signature":""},{"type":"redacted_thinking","data":"opaque"}]}, + {"role":"user","content":"last"} + ]}`) + out, err := convertClaudeMessagesToGeminiGenerateContent(body) + require.NoError(t, err) + require.NotContains(t, string(out), "PRIOR_THOUGHT") + require.NotContains(t, string(out), "ONLY_THOUGHT") + require.NotContains(t, string(out), "opaque") + + contents := gjson.GetBytes(out, "contents").Array() + require.Len(t, contents, 4) + require.Equal(t, "model", contents[1].Get("role").String()) + require.Len(t, contents[1].Get("parts").Array(), 1) + require.Equal(t, "Hello", contents[1].Get("parts.0.text").String()) + for i, content := range contents { + require.NotEmpty(t, content.Get("parts").Array(), "contents[%d] has empty parts", i) + } +} + +func TestGeminiForwardAsChatCompletions_DropsHistoryReasoningContent(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":1}}`)), + }}} + svc := &GeminiMessagesCompatService{httpUpstream: upstream, cfg: &config.Config{}} + body := []byte(`{"model":"gemini-3.8-flash","messages":[ + {"role":"user","content":"hi"}, + {"role":"assistant","content":"Hello","reasoning_content":"PRIOR_REASONING"}, + {"role":"assistant","content":"Again","reasoning":"ALIAS_REASONING"}, + {"role":"assistant","content":[{"type":"thinking","thinking":"PART_THINKING"},{"type":"reasoning","text":"PART_REASONING"},{"type":"text","text":"Third"}]}, + {"role":"user","content":"next"} + ]}`) + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body) + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, geminiCompatThinkingTestAccount(), body) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 1) + sent := string(upstream.requestBodies[0]) + require.NotContains(t, sent, "PRIOR_REASONING") + require.NotContains(t, sent, "ALIAS_REASONING") + require.NotContains(t, sent, "PART_THINKING") + require.NotContains(t, sent, "PART_REASONING") + require.NotContains(t, sent, "") + require.Contains(t, sent, "Third") + require.Contains(t, sent, "Hello") + require.Contains(t, sent, "Again") +} + +func TestGeminiMessagesForward_SignatureRetryKeepsClientThinkingParams(t *testing.T) { + gin.SetMode(gin.TestMode) + okBody := "data: " + `{"candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":1}}` + "\n\n" + upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{ + { + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"code":400,"message":"Function call is missing a thought_signature","status":"INVALID_ARGUMENT"}}`)), + }, + { + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"code":400,"message":"Function call is missing a thought_signature","status":"INVALID_ARGUMENT"}}`)), + }, + { + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(okBody)), + }, + }} + svc := &GeminiMessagesCompatService{httpUpstream: upstream, cfg: &config.Config{}} + body := []byte(`{"model":"claude-sonnet-4-5","stream":true,"max_tokens":1024,"thinking":{"type":"adaptive"},"output_config":{"effort":"low"},"messages":[ + {"role":"user","content":"hi"}, + {"role":"assistant","content":[{"type":"thinking","thinking":"RETRY_THOUGHT","signature":""},{"type":"tool_use","id":"toolu_1","name":"lookup","input":{"q":"x"}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"found"}]}, + {"role":"assistant","content":[{"type":"thinking","thinking":"RETRY_ONLY_THOUGHT","signature":""}]}, + {"role":"user","content":"next"}, + {"role":"assistant","content":[{"type":"thinking","thinking":"RETRY_BLANK_THOUGHT","signature":""},{"type":"text","text":""}]}, + {"role":"user","content":"again"}, + {"role":"assistant","content":[{"type":"thinking","thinking":"RETRY_SPACE_THOUGHT","signature":""},{"type":"text","text":" "}]}, + {"role":"user","content":"last"} + ]}`) + account := geminiCompatThinkingTestAccount() + account.Credentials["model_mapping"] = map[string]any{"claude-sonnet-4-5": "gemini-3.8-flash"} + c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/messages", body) + + result, err := svc.Forward(context.Background(), c, account, body) + require.NoError(t, err) + require.Equal(t, http.StatusOK, recorder.Code) + require.Len(t, upstream.requestBodies, 3) + for i, sent := range upstream.requestBodies { + require.NotContains(t, string(sent), "RETRY_THOUGHT", "request %d", i) + require.NotContains(t, string(sent), "RETRY_ONLY_THOUGHT", "request %d", i) + require.NotContains(t, string(sent), "RETRY_BLANK_THOUGHT", "request %d", i) + require.NotContains(t, string(sent), "RETRY_SPACE_THOUGHT", "request %d", i) + for j, content := range gjson.GetBytes(sent, "contents").Array() { + require.NotEmpty(t, content.Get("parts").Array(), "request %d contents[%d] has empty parts", i, j) + for k, part := range content.Get("parts").Array() { + if text := part.Get("text"); text.Exists() { + require.NotEmpty(t, strings.TrimSpace(text.String()), "request %d contents[%d].parts[%d] is blank text", i, j, k) + } + } + } + cfg := gjson.GetBytes(sent, "generationConfig.thinkingConfig") + require.Equal(t, "low", cfg.Get("thinkingLevel").String(), "request %d: %s", i, cfg.Raw) + require.True(t, cfg.Get("includeThoughts").Bool(), "request %d: %s", i, cfg.Raw) + } + require.Equal(t, "low", optionalStringValue(result.ReasoningEffort)) +} diff --git a/backend/internal/service/gemini_error_policy_single_check_test.go b/backend/internal/service/gemini_error_policy_single_check_test.go new file mode 100644 index 000000000..bcb12e299 --- /dev/null +++ b/backend/internal/service/gemini_error_policy_single_check_test.go @@ -0,0 +1,201 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/MACOS-DO/sub4api/internal/pkg/tlsfingerprint" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// --------------------------------------------------------------------------- +// Gemini 三条转发路径对每个上游错误响应只检查一次错误策略: +// - 重试循环内已检查的最终响应,循环外的错误处理复用该结果; +// - 账号级 401 规则首次命中只临时不可调度,账号上已有 401 暂停记录时才升级为 error; +// - 循环内未检查的最终响应(如 Claude 兼容层的非签名 400)在循环外检查。 +// --------------------------------------------------------------------------- + +type geminiSingleCheckRepoStub struct { + errorPolicyRepoStub + tempReason string +} + +func (r *geminiSingleCheckRepoStub) SetTempUnschedulable(_ context.Context, _ int64, _ time.Time, reason string) error { + r.tempCalls++ + r.tempReason = reason + return nil +} + +func (r *geminiSingleCheckRepoStub) GetByID(_ context.Context, id int64) (*Account, error) { + return &Account{ID: id, TempUnschedulableReason: r.tempReason}, nil +} + +type geminiSequenceUpstreamResponse struct { + status int + body string +} + +type geminiSequenceUpstreamStub struct { + responses []geminiSequenceUpstreamResponse + calls int +} + +func (s *geminiSequenceUpstreamStub) Do(*http.Request, string, int64, int) (*http.Response, error) { + r := s.responses[min(s.calls, len(s.responses)-1)] + s.calls++ + return &http.Response{ + StatusCode: r.status, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(r.body)), + }, nil +} + +func (s *geminiSequenceUpstreamStub) DoWithTLS(req *http.Request, proxyURL string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return s.Do(req, proxyURL, accountID, concurrency) +} + +func newGeminiSingleCheckService(responses ...geminiSequenceUpstreamResponse) (*GeminiMessagesCompatService, *geminiSequenceUpstreamStub, *geminiSingleCheckRepoStub) { + repo := &geminiSingleCheckRepoStub{} + rateLimit := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + upstream := &geminiSequenceUpstreamStub{responses: responses} + svc := &GeminiMessagesCompatService{ + accountRepo: repo, + httpUpstream: upstream, + rateLimitService: rateLimit, + cfg: &config.Config{}, + } + return svc, upstream, repo +} + +func geminiAPIKeyAccountWithTempRule(rule map[string]any) *Account { + return &Account{ + ID: 830, + Platform: PlatformGemini, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "test-key", + "temp_unschedulable_enabled": true, + "temp_unschedulable_rules": []any{rule}, + }, + } +} + +const geminiSingleCheck401Body = `{"error":{"code":401,"message":"API key expired. Please renew the API key.","status":"UNAUTHENTICATED"}}` + +func geminiAccountScoped401Rule() map[string]any { + return map[string]any{ + "error_code": float64(401), + "keywords": []any{"expired"}, + "duration_minutes": float64(30), + "scope": TempUnschedScopeAccount, + } +} + +// geminiSingleCheckForwarders 以三条转发路径各发一次请求,返回转发错误与 gin.Context。 +var geminiSingleCheckForwarders = []struct { + name string + forward func(t *testing.T, svc *GeminiMessagesCompatService, account *Account) (error, *gin.Context) +}{ + { + name: "native", + forward: func(t *testing.T, svc *GeminiMessagesCompatService, account *Account) (error, *gin.Context) { + c, _ := newGeminiNativeTestContext(t) + _, err := svc.ForwardNative(context.Background(), c, account, "gemini-2.5-flash", "generateContent", false, + []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`)) + return err, c + }, + }, + { + name: "claude_compat", + forward: func(t *testing.T, svc *GeminiMessagesCompatService, account *Account) (error, *gin.Context) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + body := []byte(`{"model":"gemini-2.5-flash","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + _, err := svc.Forward(context.Background(), c, account, body) + return err, c + }, + }, + { + name: "chat_completions_compat", + forward: func(t *testing.T, svc *GeminiMessagesCompatService, account *Account) (error, *gin.Context) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + body := []byte(`{"model":"gemini-2.5-flash","messages":[{"role":"user","content":"hi"}]}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body) + return err, c + }, + }, +} + +func TestGeminiForward_First401RuleHitOnlyTempUnschedules(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, fw := range geminiSingleCheckForwarders { + t.Run(fw.name, func(t *testing.T) { + svc, upstream, repo := newGeminiSingleCheckService(geminiSequenceUpstreamResponse{status: http.StatusUnauthorized, body: geminiSingleCheck401Body}) + + err, _ := fw.forward(t, svc, geminiAPIKeyAccountWithTempRule(geminiAccountScoped401Rule())) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "规则命中应换号,got %T: %v", err, err) + require.Equal(t, http.StatusUnauthorized, failoverErr.StatusCode) + require.Equal(t, 1, upstream.calls) + require.Equal(t, 1, repo.tempCalls, "首次 401 命中规则应临时不可调度") + require.Zero(t, repo.setErrCalls, "首次 401 命中规则不应升级为 error") + }) + } +} + +func TestGeminiForward_Repeated401RuleHitEscalatesToError(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, fw := range geminiSingleCheckForwarders { + t.Run(fw.name, func(t *testing.T) { + svc, _, repo := newGeminiSingleCheckService(geminiSequenceUpstreamResponse{status: http.StatusUnauthorized, body: geminiSingleCheck401Body}) + repo.tempReason = `{"until_unix":1,"triggered_at_unix":1,"status_code":401,"matched_keyword":"expired","rule_index":0,"scope":"account"}` + + _, _ = fw.forward(t, svc, geminiAPIKeyAccountWithTempRule(geminiAccountScoped401Rule())) + + require.Zero(t, repo.tempCalls, "已有 401 暂停记录时直接升级,不临时不可调度") + require.Equal(t, 1, repo.setErrCalls, "已有 401 暂停记录时应升级为 error") + require.Contains(t, repo.lastErrorMsg, "Authentication failed (401)") + }) + } +} + +func TestGeminiForward_UncheckedFinalResponseIsCheckedAfterLoop(t *testing.T) { + gin.SetMode(gin.TestMode) + if testing.Short() { + t.Skip("包含一次 1s 的重试退避") + } + // 第一次 503 在循环内检查后重试;第二次非签名 400 走 Claude 兼容层的签名分支,循环内不检查。 + svc, upstream, repo := newGeminiSingleCheckService( + geminiSequenceUpstreamResponse{status: http.StatusServiceUnavailable, body: `{"error":{"code":503,"message":"backend busy","status":"UNAVAILABLE"}}`}, + geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: `{"error":{"code":400,"message":"quota project misconfigured","status":"FAILED_PRECONDITION"}}`}, + ) + account := geminiAPIKeyAccountWithTempRule(map[string]any{ + "error_code": float64(400), + "keywords": []any{"misconfigured"}, + "duration_minutes": float64(30), + "scope": TempUnschedScopeAccount, + }) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + body := []byte(`{"model":"gemini-2.5-flash","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + + _, err := svc.Forward(context.Background(), c, account, body) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "400 规则命中应换号,got %T: %v", err, err) + require.Equal(t, 2, upstream.calls) + require.Equal(t, 1, repo.tempCalls, "循环内未检查的最终响应应在循环外检查") +} diff --git a/backend/internal/service/gemini_error_policy_test.go b/backend/internal/service/gemini_error_policy_test.go index 73ae096b8..12f4f7d73 100644 --- a/backend/internal/service/gemini_error_policy_test.go +++ b/backend/internal/service/gemini_error_policy_test.go @@ -631,30 +631,159 @@ func TestHandleGeminiUpstreamError_VertexRetryInfoUsesParsedDelay(t *testing.T) require.WithinDuration(t, before.Add(39*time.Second), repo.lastRateLimitReset, 2*time.Second) } -// Vertex(service_account)429 响应不带任何可解析的重置时间时,走短冷却兜底, -// 不再冷却到 PST 午夜(按量付费没有每日配额,长冷却会导致整组不可用)。 -func TestHandleGeminiUpstreamError_VertexFallbackUsesShortCooldown(t *testing.T) { +// Vertex(service_account)共享容量不足的 429 不写账号级限流:账号保持可调度, +// 由请求内的同号退避重试与换号消化。 +func TestHandleGeminiUpstreamError_VertexSharedCapacityKeepsAccountSchedulable(t *testing.T) { + tests := []struct { + name string + body string + }{ + { + name: "object", + body: `{"error":{"code":429,"message":"Resource exhausted. Please try again later. Please refer to https://cloud.google.com/vertex-ai/generative-ai/docs/error-code-429 for more details.","status":"RESOURCE_EXHAUSTED"}}`, + }, + { + name: "array_wrapped", + body: `[{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED"}}]`, + }, + { + name: "empty_details", + body: `{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED","details":[]}}`, + }, + { + name: "documented_comma_wording", + body: `{"error":{"code":429,"message":"Resource exhausted, please try again later.","status":"RESOURCE_EXHAUSTED"}}`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + repo := &rateLimit429AccountRepoStub{} + svc := &GeminiMessagesCompatService{accountRepo: repo} + account := &Account{ + ID: 602, + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Credentials: map[string]any{ + "project_id": "my-vertex-project", + }, + } + + svc.handleGeminiUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{}, []byte(tt.body)) + + require.Zero(t, repo.rateLimitCalls) + }) + } +} + +// Vertex(service_account)项目配额、预留吞吐等账号自身的 429 不带可解析的重置时间时, +// 走短冷却兜底,不冷却到 PST 午夜(按量付费没有每日配额,长冷却会导致整组不可用)。 +func TestHandleGeminiUpstreamError_VertexAccountScoped429UsesShortCooldown(t *testing.T) { + tests := []struct { + name string + body string + }{ + { + name: "project_quota", + body: `{"error":{"code":429,"message":"Quota exceeded for aiplatform.googleapis.com/generate_content_requests_per_minute_per_project_per_base_model with base model: gemini-2.5-pro. Please submit a quota increase request.","status":"RESOURCE_EXHAUSTED"}}`, + }, + { + name: "provisioned_throughput", + body: `{"error":{"code":429,"message":"Too many requests. Exceeded the Provisioned Throughput.","status":"RESOURCE_EXHAUSTED"}}`, + }, + { + name: "quota_failure_details", + body: `{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.QuotaFailure","violations":[{"subject":"project"}]}]}}`, + }, + { + name: "other_status", + body: `{"error":{"code":429,"message":"Too many requests.","status":"UNAVAILABLE"}}`, + }, + { + name: "unknown_wording", + body: `{"error":{"code":429,"message":"Rate limit exceeded for requests per minute per project.","status":"RESOURCE_EXHAUSTED"}}`, + }, + { + name: "missing_message", + body: `{"error":{"code":429,"status":"RESOURCE_EXHAUSTED"}}`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + repo := &rateLimit429AccountRepoStub{} + svc := &GeminiMessagesCompatService{accountRepo: repo} + account := &Account{ + ID: 604, + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Credentials: map[string]any{ + "project_id": "my-vertex-project", + }, + } + + before := time.Now() + svc.handleGeminiUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{}, []byte(tt.body)) + + require.Equal(t, 1, repo.rateLimitCalls) + require.Equal(t, int64(604), repo.lastRateLimitID) + require.WithinDuration(t, before.Add(geminiVertexFallbackCooldown), repo.lastRateLimitReset, 2*time.Second) + // 显式守护:不应被冷却超过 15 分钟(更不应到次日 PST 午夜) + require.True(t, repo.lastRateLimitReset.Before(before.Add(15*time.Minute))) + }) + } +} + +// Vertex 共享容量形态的 429 只对 Vertex 账号豁免冷却:AI Studio 官方 API Key 与 Code Assist OAuth +// 收到同样的响应体仍按各自语义冷却。 +func TestHandleGeminiUpstreamError_SharedCapacityBodyStillCoolsNonVertexAccounts(t *testing.T) { + body := []byte(`{"error":{"code":429,"message":"Resource exhausted. Please try again later. Please refer to https://cloud.google.com/vertex-ai/generative-ai/docs/error-code-429 for more details.","status":"RESOURCE_EXHAUSTED"}}`) + tests := []struct { + name string + account *Account + }{ + { + name: "ai_studio_api_key", + account: &Account{ID: 605, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k"}}, + }, + { + name: "code_assist_oauth", + account: &Account{ID: 606, Platform: PlatformGemini, Type: AccountTypeOAuth, Credentials: map[string]any{ + "oauth_type": "code_assist", "project_id": "my-code-assist-project", + }}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + repo := &rateLimit429AccountRepoStub{} + svc := &GeminiMessagesCompatService{accountRepo: repo} + + svc.handleGeminiUpstreamError(context.Background(), tt.account, http.StatusTooManyRequests, http.Header{}, body) + + require.Equal(t, 1, repo.rateLimitCalls) + require.Equal(t, tt.account.ID, repo.lastRateLimitID) + }) + } +} + +// Vertex 429 文案里给出了重试时长时按该时长冷却,不归为共享容量不足。 +func TestHandleGeminiUpstreamError_VertexMessageRetryHintUsesParsedDelay(t *testing.T) { repo := &rateLimit429AccountRepoStub{} svc := &GeminiMessagesCompatService{accountRepo: repo} - account := &Account{ - ID: 602, + ID: 607, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{ "project_id": "my-vertex-project", }, } - body := []byte(`{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED"}}`) + body := []byte(`{"error":{"code":429,"message":"Resource exhausted. Please retry in 5s","status":"RESOURCE_EXHAUSTED"}}`) before := time.Now() svc.handleGeminiUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{}, body) require.Equal(t, 1, repo.rateLimitCalls) - require.Equal(t, int64(602), repo.lastRateLimitID) - require.WithinDuration(t, before.Add(geminiVertexFallbackCooldown), repo.lastRateLimitReset, 2*time.Second) - // 显式守护:不应被冷却超过 15 分钟(更不应到次日 PST 午夜) - require.True(t, repo.lastRateLimitReset.Before(before.Add(15*time.Minute))) + require.Equal(t, int64(607), repo.lastRateLimitID) + require.WithinDuration(t, before.Add(5*time.Second), repo.lastRateLimitReset, 2*time.Second) } // API Key(AI Studio)无法解析重置时间时仍冷却到 PST 午夜,行为保持不变。 @@ -677,6 +806,72 @@ func TestHandleGeminiUpstreamError_APIKeyFallbackStillPSTMidnight(t *testing.T) require.WithinDuration(t, expected, repo.lastRateLimitReset, 5*time.Second) } +// 第三方上游 API Key 的 429 不套用 AI Studio 每日配额语义:只认显式重试时长, +// 否则走全局 429 兜底冷却(未配置时默认 5 秒)。 +func TestHandleGeminiUpstreamError_ThirdPartyAPIKey429(t *testing.T) { + const relayBaseURL = "https://relay.example.com" + tests := []struct { + name string + baseURL string + body string + expectWait time.Duration + pstNight bool + }{ + { + name: "no_reset_time_uses_global_fallback", + baseURL: relayBaseURL, + body: `{"error":{"code":429,"message":"You have exhausted your capacity on this model. Your quota will reset after 6h53m10s."}}`, + expectWait: defaultRateLimit429CooldownSeconds * time.Second, + }, + { + name: "daily_quota_message_not_treated_as_pst_midnight", + baseURL: relayBaseURL, + body: `{"error":{"code":429,"message":"Quota exceeded for metric: generate_content_free_tier_requests, limit: 50 per day"}}`, + expectWait: defaultRateLimit429CooldownSeconds * time.Second, + }, + { + name: "explicit_quota_reset_delay_respected", + baseURL: relayBaseURL, + body: `{"error":{"code":429,"message":"rate limit","details":[{"metadata":{"quotaResetDelay":"42s"}}]}}`, + expectWait: 42 * time.Second, + }, + { + name: "official_base_url_keeps_pst_midnight", + baseURL: "https://generativelanguage.googleapis.com/", + body: `{"error":{"code":429,"message":"rate limit"}}`, + pstNight: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + repo := &rateLimit429AccountRepoStub{} + svc := &GeminiMessagesCompatService{ + accountRepo: repo, + rateLimitService: NewRateLimitService(repo, nil, &config.Config{}, nil, nil), + } + account := &Account{ + ID: 700, + Platform: PlatformGemini, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"base_url": tt.baseURL}, + } + + before := time.Now() + svc.handleGeminiUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{}, []byte(tt.body)) + + require.Equal(t, 1, repo.rateLimitCalls) + require.Equal(t, int64(700), repo.lastRateLimitID) + if tt.pstNight { + expected := time.Unix(*nextGeminiDailyResetUnix(), 0) + require.WithinDuration(t, expected, repo.lastRateLimitReset, 5*time.Second) + return + } + require.WithinDuration(t, before.Add(tt.expectWait), repo.lastRateLimitReset, 2*time.Second) + }) + } +} + type geminiErrorPolicyRepo struct { mockAccountRepoForGemini setErrorCalls int diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 9677a2466..7456df528 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -45,8 +45,8 @@ const ( geminiRetryInfoTypeURL = "type.googleapis.com/google.rpc.RetryInfo" // RetryInfo.retryDelay 的上限,防止异常值导致账号长时间不可用 geminiRetryInfoMaxDelay = 15 * time.Minute - // Vertex(service_account,按量付费)429 无法解析重置时间时的兜底冷却: - // 按量付费限速是短窗口 RPM/TPM,没有每日配额,不适用 PST 午夜重置 + // Vertex(service_account)账号自身的 429(按量付费的项目配额、预留吞吐超额等)无法解析重置时间时的兜底冷却: + // 这类限速是短窗口 RPM/TPM,没有每日配额,不适用 PST 午夜重置;共享容量不足的 429 不冷却 geminiVertexFallbackCooldown = time.Minute ) @@ -529,94 +529,6 @@ func (s *GeminiMessagesCompatService) HasAntigravityAccounts(ctx context.Context return len(accounts) > 0, nil } -// SelectAccountForAIStudioEndpoints selects an account that is likely to succeed against -// generativelanguage.googleapis.com (e.g. GET /v1beta/models). -// -// Preference order: -// 1) API key accounts (AI Studio) -// 2) OAuth accounts without project_id (AI Studio OAuth) -// 3) OAuth accounts explicitly marked as ai_studio -// 4) Any remaining Gemini accounts (fallback) -func (s *GeminiMessagesCompatService) SelectAccountForAIStudioEndpoints(ctx context.Context, groupID *int64) (*Account, error) { - accounts, err := s.listSchedulableAccountsOnce(ctx, groupID, PlatformGemini, true) - if err != nil { - return nil, fmt.Errorf("query accounts failed: %w", err) - } - if len(accounts) == 0 { - return nil, errors.New("no available Gemini accounts") - } - - rank := func(a *Account) int { - if a == nil { - return 999 - } - switch a.Type { - case AccountTypeAPIKey: - if strings.TrimSpace(a.GetCredential("api_key")) != "" { - return 0 - } - return 9 - case AccountTypeOAuth: - if strings.TrimSpace(a.GetCredential("project_id")) == "" { - return 1 - } - if strings.TrimSpace(a.GetCredential("oauth_type")) == "ai_studio" { - return 2 - } - // Code Assist OAuth tokens often lack AI Studio scopes for models listing. - return 3 - case AccountTypeServiceAccount: - // Vertex service accounts use aiplatform.googleapis.com, not the AI Studio - // endpoint (generativelanguage.googleapis.com), so they cannot serve these requests. - return 999 - default: - return 10 - } - } - - var selected *Account - for i := range accounts { - acc := &accounts[i] - if selected == nil { - selected = acc - continue - } - - r1, r2 := rank(acc), rank(selected) - if r1 < r2 { - selected = acc - continue - } - if r1 > r2 { - continue - } - - if acc.Priority < selected.Priority { - selected = acc - } else if acc.Priority == selected.Priority { - switch { - case acc.LastUsedAt == nil && selected.LastUsedAt != nil: - selected = acc - case acc.LastUsedAt != nil && selected.LastUsedAt == nil: - // keep selected - case acc.LastUsedAt == nil && selected.LastUsedAt == nil: - if acc.Type == AccountTypeOAuth && selected.Type != AccountTypeOAuth { - selected = acc - } - default: - if acc.LastUsedAt.Before(*selected.LastUsedAt) { - selected = acc - } - } - } - } - - if selected == nil { - return nil, errors.New("no available Gemini accounts") - } - return s.hydrateSelectedAccount(ctx, selected) -} - func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte) (*ForwardResult, error) { beginUpstreamResponseModelObservation(c) beginGeminiImageOutputObservation(c) @@ -644,6 +556,8 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex return nil, s.writeClaudeError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) } geminiReq = ensureGeminiFunctionCallThoughtSignatures(geminiReq) + includeThoughts := req.Stream && claudeRequestEnablesThinking(body) + geminiReq = applyGeminiCompatThinkingConfig(geminiReq, body, mappedModel, includeThoughts) originalClaudeBody := body proxyURL := "" @@ -770,19 +684,11 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex case AccountTypeServiceAccount: buildReq = func(ctx context.Context) (*http.Request, string, error) { - if s.tokenProvider == nil { - return nil, "", errors.New("gemini token provider not configured") - } - accessToken, err := s.tokenProvider.GetAccessToken(ctx, account) - if err != nil { - return nil, "", err - } - action := "generateContent" if req.Stream { action = "streamGenerateContent" } - fullURL, err := buildVertexGeminiURL(account.VertexProjectID(), account.VertexLocation(mappedModel), mappedModel, action, req.Stream) + fullURL, err := buildVertexGeminiAccountURL(account, mappedModel, action, req.Stream) if err != nil { return nil, "", err } @@ -793,7 +699,9 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex return nil, "", err } upstreamReq.Header.Set("Content-Type", "application/json") - upstreamReq.Header.Set("Authorization", "Bearer "+accessToken) + if err := setVertexGeminiAuth(ctx, upstreamReq, account, s.tokenProvider); err != nil { + return nil, "", err + } return upstreamReq, "x-request-id", nil } requestIDHeader = "x-request-id" @@ -803,13 +711,19 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex } var resp *http.Response + // checkedPolicy 是循环内对当前 resp 的错误策略检查结果,未检查时为 nil。 + var checkedPolicy *ErrorPolicyResult signatureRetryStage := 0 for attempt := 1; attempt <= geminiMaxRetries; attempt++ { + checkedPolicy = nil upstreamReq, idHeader, err := buildReq(ctx) if err != nil { if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { return nil, err } + if failoverErr := s.handleVertexServiceAccountNotFound(ctx, c, account, err); failoverErr != nil { + return nil, failoverErr + } // Local build error: don't retry. if strings.Contains(err.Error(), "missing project_id") { return nil, s.writeClaudeError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) @@ -859,25 +773,28 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex var strippedClaudeBody []byte stageName := "" + // 降级函数会把思考块改写成正文,Gemini 侧先删掉历史思考块再降级。 + retrySourceBody := dropClaudeHistoryThinkingBlocks(originalClaudeBody) // 路径说明:本处上游是 Gemini,但被剥离的 body 是 Anthropic 格式。传 originalModel // (客户端原 Anthropic model)而非 mappedModel(上游 Gemini model),让剥离逻辑按 // 客户端请求的 Anthropic 子协议族判定(详见 ResolveThinkingProtocol 文档)。 switch signatureRetryStage { case 0: // Stage 1: disable thinking + thinking->text - strippedClaudeBody = FilterThinkingBlocksForRetry(originalClaudeBody, originalModel) + strippedClaudeBody = FilterThinkingBlocksForRetry(retrySourceBody, originalModel) stageName = "thinking-only" signatureRetryStage = 1 default: // Stage 2: additionally downgrade tool_use/tool_result blocks to text - strippedClaudeBody = FilterSignatureSensitiveBlocksForRetry(originalClaudeBody, originalModel) + strippedClaudeBody = FilterSignatureSensitiveBlocksForRetry(retrySourceBody, originalModel) stageName = "thinking+tools" signatureRetryStage = 2 } retryGeminiReq, txErr := convertClaudeMessagesToGeminiGenerateContent(strippedClaudeBody) if txErr == nil { logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: detected signature-related 400, retrying with downgraded Claude blocks (%s)", account.ID, stageName) - geminiReq = retryGeminiReq + // 降级只改写历史块,思考参数沿用客户端原始请求。 + geminiReq = applyGeminiCompatThinkingConfig(retryGeminiReq, originalClaudeBody, mappedModel, includeThoughts) // Consume one retry budget attempt and continue with the updated request payload. sleepGeminiBackoff(1) continue @@ -894,11 +811,11 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex } // 错误策略优先:匹配则跳过重试直接处理。 - if matched, rebuilt := s.checkErrorPolicyInLoop(ctx, account, resp, mappedModel); matched { - resp = rebuilt + checked, rebuilt := s.checkErrorPolicyInLoop(ctx, account, resp, mappedModel) + resp = rebuilt + checkedPolicy = checked + if checked != nil && *checked != ErrorPolicyNone { break - } else { - resp = rebuilt } if resp.StatusCode >= 400 && s.shouldRetryGeminiUpstreamError(account, resp.StatusCode) { @@ -914,7 +831,7 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex break } if resp.StatusCode == 429 { - // Mark as rate-limited early so concurrent requests avoid this account. + // Apply account-scoped 429 handling early so concurrent requests avoid a rate-limited account. s.handleGeminiUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody) } if attempt < geminiMaxRetries { @@ -966,7 +883,7 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex respBody := s.readUpstreamErrorBody(resp) // 统一错误策略:自定义错误码 + 临时不可调度 if s.rateLimitService != nil { - policy := s.rateLimitService.CheckErrorPolicy(ctx, account, resp.StatusCode, respBody, mappedModel) + policy := s.finalErrorPolicy(ctx, account, resp.StatusCode, respBody, mappedModel, checkedPolicy) switch policy { case ErrorPolicySkipped: upstreamReqID := resp.Header.Get(requestIDHeader) @@ -1144,6 +1061,7 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex Stream: req.Stream, Duration: time.Since(startTime), FirstTokenMs: firstTokenMs, + ReasoningEffort: extractGeminiReasoningEffortFromBody(geminiReq), ImageCount: imageCount, ImageSize: imageSize, ImageInputSize: imageInputSize, @@ -1311,15 +1229,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. case AccountTypeServiceAccount: buildReq = func(ctx context.Context) (*http.Request, string, error) { - if s.tokenProvider == nil { - return nil, "", errors.New("gemini token provider not configured") - } - accessToken, err := s.tokenProvider.GetAccessToken(ctx, account) - if err != nil { - return nil, "", err - } - - fullURL, err := buildVertexGeminiURL(account.VertexProjectID(), account.VertexLocation(mappedModel), mappedModel, upstreamAction, useUpstreamStream) + fullURL, err := buildVertexGeminiAccountURL(account, mappedModel, upstreamAction, useUpstreamStream) if err != nil { return nil, "", err } @@ -1329,7 +1239,9 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. return nil, "", err } upstreamReq.Header.Set("Content-Type", "application/json") - upstreamReq.Header.Set("Authorization", "Bearer "+accessToken) + if err := setVertexGeminiAuth(ctx, upstreamReq, account, s.tokenProvider); err != nil { + return nil, "", err + } return upstreamReq, "x-request-id", nil } requestIDHeader = "x-request-id" @@ -1339,12 +1251,18 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. } var resp *http.Response + // checkedPolicy 是循环内对当前 resp 的错误策略检查结果,未检查时为 nil。 + var checkedPolicy *ErrorPolicyResult for attempt := 1; attempt <= geminiMaxRetries; attempt++ { + checkedPolicy = nil upstreamReq, idHeader, err := buildReq(ctx) if err != nil { if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { return nil, err } + if failoverErr := s.handleVertexServiceAccountNotFound(ctx, c, account, err); failoverErr != nil { + return nil, failoverErr + } // Local build error: don't retry. if strings.Contains(err.Error(), "missing project_id") { return nil, s.writeGoogleError(c, http.StatusBadRequest, err.Error()) @@ -1374,14 +1292,23 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. return nil, transportErr } - // 错误策略优先:匹配则跳过重试直接处理。 - if matched, rebuilt := s.checkErrorPolicyInLoop(ctx, account, resp, mappedModel); matched { + // 引用缓存不存在、上游网关持有缓存的账号不可用先于错误策略识别:错误策略会写临时不可调度, + // 重试与换号也无法恢复。 + if passthrough, rebuilt := s.cachedContentPassthroughInLoop(ctx, account, resp); passthrough { resp = rebuilt break } else { resp = rebuilt } + // 错误策略优先:匹配则跳过重试直接处理。 + checked, rebuilt := s.checkErrorPolicyInLoop(ctx, account, resp, mappedModel) + resp = rebuilt + checkedPolicy = checked + if checked != nil && *checked != ErrorPolicyNone { + break + } + if resp.StatusCode >= 400 && s.shouldRetryGeminiUpstreamError(account, resp.StatusCode) { respBody := s.readUpstreamErrorBody(resp) _ = resp.Body.Close() @@ -1467,6 +1394,14 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. if resp.StatusCode >= 400 { respBody := s.readUpstreamErrorBody(resp) + // 引用缓存不存在是请求问题:统一返回 403,不改账号状态、不换号。 + if isGeminiCachedContentNotFound(resp.StatusCode, respBody) { + return nil, s.writeGeminiCachedContentNotFound(c, account, resp, respBody, requestID, isOAuth) + } + // 上游网关的限流 / 不可用只针对其持有缓存的账号:不改本账号状态,交由绑定请求的耗尽处理透传。 + if isGeminiBoundCacheUpstreamPassthrough(ctx, account, resp.StatusCode) { + return nil, &UpstreamFailoverError{StatusCode: resp.StatusCode, ResponseBody: respBody, BoundUpstreamPassthrough: true} + } // Best-effort fallback for OAuth tokens missing AI Studio scopes when calling countTokens. // This avoids Gemini SDKs failing hard during preflight token counting. // Checked before error policy so it always works regardless of custom error codes. @@ -1487,7 +1422,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. // 统一错误策略:自定义错误码 + 临时不可调度 if s.rateLimitService != nil { - policy := s.rateLimitService.CheckErrorPolicy(ctx, account, resp.StatusCode, respBody, mappedModel) + policy := s.finalErrorPolicy(ctx, account, resp.StatusCode, respBody, mappedModel, checkedPolicy) switch policy { case ErrorPolicySkipped: if failoverErr := s.skippedErrorPolicyFailoverError(c, account, resp.StatusCode, respBody, requestID); failoverErr != nil { @@ -1656,14 +1591,14 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. }, nil } -// checkErrorPolicyInLoop 在重试循环内预检查错误策略。 -// 返回 true 表示策略已匹配(调用者应 break),resp 已重建可直接使用。 -// 返回 false 表示 ErrorPolicyNone,resp 已重建,调用者继续走重试逻辑。 +// checkErrorPolicyInLoop 在重试循环内对上游错误响应检查错误策略,resp 已重建可直接使用。 +// checked 为 nil 表示未检查(非错误响应或未配置限流服务);否则指向检查结果, +// 非 ErrorPolicyNone 时调用者应 break 并由循环外的错误处理复用该结果。 func (s *GeminiMessagesCompatService) checkErrorPolicyInLoop( ctx context.Context, account *Account, resp *http.Response, mappedModel string, -) (matched bool, rebuilt *http.Response) { +) (checked *ErrorPolicyResult, rebuilt *http.Response) { if resp.StatusCode < 400 || s.rateLimitService == nil { - return false, resp + return nil, resp } body := s.readUpstreamErrorBody(resp) _ = resp.Body.Close() @@ -1673,7 +1608,41 @@ func (s *GeminiMessagesCompatService) checkErrorPolicyInLoop( Body: io.NopCloser(bytes.NewReader(body)), } policy := s.rateLimitService.CheckErrorPolicy(ctx, account, resp.StatusCode, body, mappedModel) - return policy != ErrorPolicyNone, rebuilt + return &policy, rebuilt +} + +// finalErrorPolicy 返回循环外处理最终上游错误响应时使用的错误策略。每个上游响应只检查一次: +// 错误策略检查会触发临时不可调度规则,并据账号上已记录的 401 暂停把 401 升级为 error。 +// checked 非 nil 时它就是重试循环内对同一响应的检查结果,直接复用;否则在此检查。 +// 调用方保证 s.rateLimitService 非 nil。 +func (s *GeminiMessagesCompatService) finalErrorPolicy( + ctx context.Context, account *Account, statusCode int, body []byte, mappedModel string, checked *ErrorPolicyResult, +) ErrorPolicyResult { + if checked != nil { + return *checked + } + return s.rateLimitService.CheckErrorPolicy(ctx, account, statusCode, body, mappedModel) +} + +// cachedContentPassthroughInLoop 判断上游响应是否跳过同号重试与错误策略直接处理:引用缓存不存在, +// 或绑定缓存的请求在上游网关账号上收到的 429 / 5xx。读取过的响应体以内存副本重建。 +func (s *GeminiMessagesCompatService) cachedContentPassthroughInLoop(ctx context.Context, account *Account, resp *http.Response) (passthrough bool, rebuilt *http.Response) { + if isGeminiBoundCacheUpstreamPassthrough(ctx, account, resp.StatusCode) { + return true, resp + } + switch resp.StatusCode { + case http.StatusBadRequest, http.StatusForbidden, http.StatusNotFound: + default: + return false, resp + } + body := s.readUpstreamErrorBody(resp) + _ = resp.Body.Close() + rebuilt = &http.Response{ + StatusCode: resp.StatusCode, + Header: resp.Header.Clone(), + Body: io.NopCloser(bytes.NewReader(body)), + } + return isGeminiCachedContentNotFound(resp.StatusCode, body), rebuilt } func (s *GeminiMessagesCompatService) shouldRetryGeminiUpstreamError(account *Account, statusCode int) bool { @@ -1781,36 +1750,53 @@ func (s *GeminiMessagesCompatService) writeGeminiCustomCodeSkippedError(c *gin.C // 并记录 ops 错误事件。状态码保真:下游据此区分请求级错误与可重试的链路故障。 func (s *GeminiMessagesCompatService) writeGeminiNativeUpstreamError(c *gin.Context, account *Account, resp *http.Response, respBody []byte, requestID string, isOAuth bool) error { respBody = unwrapIfNeeded(isOAuth, respBody) + upstreamMsg := s.recordGeminiNativeUpstreamError(c, account, resp.StatusCode, respBody, requestID) + + contentType := resp.Header.Get("Content-Type") + if contentType == "" { + contentType = "application/json" + } + MarkResponseCommitted(c) + c.Data(resp.StatusCode, contentType, respBody) + if upstreamMsg == "" { + return fmt.Errorf("gemini upstream error: %d", resp.StatusCode) + } + return fmt.Errorf("gemini upstream error: %d message=%s", resp.StatusCode, upstreamMsg) +} + +// writeGeminiCachedContentNotFound 记录上游原始错误,并向客户端统一返回缓存不存在的 403: +// 各上游的响应形态不同,且 Vertex 的文案含上游缓存资源 ID。失败由请求引用的缓存决定,ops 按客户端请求错误统计。 +func (s *GeminiMessagesCompatService) writeGeminiCachedContentNotFound(c *gin.Context, account *Account, resp *http.Response, respBody []byte, requestID string, isOAuth bool) error { + respBody = unwrapIfNeeded(isOAuth, respBody) + upstreamMsg := s.recordGeminiNativeUpstreamError(c, account, resp.StatusCode, respBody, requestID) + MarkOpsRequestScopedError(c, "permission_error") + MarkResponseCommitted(c) + c.Data(http.StatusForbidden, "application/json", []byte(GeminiCachedContentNotFoundResponse)) + return fmt.Errorf("gemini upstream error: %d message=%s", resp.StatusCode, upstreamMsg) +} + +// recordGeminiNativeUpstreamError 把上游错误响应登记到 ops 上下文,返回脱敏后的上游错误文案。 +func (s *GeminiMessagesCompatService) recordGeminiNativeUpstreamError(c *gin.Context, account *Account, statusCode int, respBody []byte, requestID string) string { upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) upstreamDetail := s.upstreamErrorDetail(respBody) if s.cfg != nil && s.cfg.Gateway.LogUpstreamErrorBody { - logger.LegacyPrintf("service.gemini_messages_compat", "[Gemini] native upstream error %d: %s", resp.StatusCode, truncateForLog(respBody, s.cfg.Gateway.LogUpstreamErrorBodyMaxBytes)) + logger.LegacyPrintf("service.gemini_messages_compat", "[Gemini] native upstream error %d: %s", statusCode, truncateForLog(respBody, s.cfg.Gateway.LogUpstreamErrorBodyMaxBytes)) } - setOpsUpstreamError(c, resp.StatusCode, upstreamMsg, upstreamDetail) + setOpsUpstreamError(c, statusCode, upstreamMsg, upstreamDetail) appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ ProxyID: opsUpstreamProxyID(account), ProxyName: opsUpstreamProxyName(account), Platform: account.Platform, AccountID: account.ID, AccountName: account.Name, - UpstreamStatusCode: resp.StatusCode, + UpstreamStatusCode: statusCode, UpstreamRequestID: requestID, Kind: "http_error", Message: upstreamMsg, Detail: upstreamDetail, }) - - contentType := resp.Header.Get("Content-Type") - if contentType == "" { - contentType = "application/json" - } - MarkResponseCommitted(c) - c.Data(resp.StatusCode, contentType, respBody) - if upstreamMsg == "" { - return fmt.Errorf("gemini upstream error: %d", resp.StatusCode) - } - return fmt.Errorf("gemini upstream error: %d message=%s", resp.StatusCode, upstreamMsg) + return upstreamMsg } func sleepGeminiBackoff(attempt int) { @@ -2155,6 +2141,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re openBlockIndex := -1 openBlockType := "" seenText := "" + seenThought := "" openToolIndex := -1 openToolID := "" openToolName := "" @@ -2203,6 +2190,56 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re parts := extractGeminiParts(geminiResp) for _, part := range parts { + if text, ok := part["text"].(string); ok && isGeminiThoughtPart(part) { + delta, newSeen := computeGeminiTextDelta(seenThought, text) + seenThought = newSeen + if delta == "" { + continue + } + if openToolIndex >= 0 { + writeSSE(c.Writer, "content_block_stop", map[string]any{ + "type": "content_block_stop", + "index": openToolIndex, + }) + openToolIndex = -1 + openToolName = "" + seenToolJSON = "" + } + if openBlockType != "thinking" { + if openBlockIndex >= 0 { + writeSSE(c.Writer, "content_block_stop", map[string]any{ + "type": "content_block_stop", + "index": openBlockIndex, + }) + } + openBlockType = "thinking" + openBlockIndex = nextBlockIndex + nextBlockIndex++ + writeSSE(c.Writer, "content_block_start", map[string]any{ + "type": "content_block_start", + "index": openBlockIndex, + "content_block": map[string]any{ + "type": "thinking", + "thinking": "", + "signature": "", + }, + }) + } + if firstTokenMs == nil { + ms := int(time.Since(startTime).Milliseconds()) + firstTokenMs = &ms + } + writeSSE(c.Writer, "content_block_delta", map[string]any{ + "type": "content_block_delta", + "index": openBlockIndex, + "delta": map[string]any{ + "type": "thinking_delta", + "thinking": delta, + }, + }) + flusher.Flush() + continue + } if text, ok := part["text"].(string); ok && text != "" { // Close an open tool_use block before starting text, mirroring // the functionCall branch (which closes open text blocks) and @@ -2635,6 +2672,25 @@ func isGeminiInsufficientScope(headers http.Header, body []byte) bool { return strings.Contains(lower, "insufficient authentication scopes") || strings.Contains(lower, "access_token_scope_insufficient") } +// isGeminiCachedContentNotFound 识别请求引用的显式缓存不存在(含已过期、已删除、不属于当前项目)时上游的响应, +// 这类响应由请求的 cachedContent 决定,与账号凭据状态无关: +// - AI Studio 及本系统网关:一律 403 "CachedContent not found (or permission denied)"; +// - Vertex 生成请求:400 "Invalid resource state for cache content {id}."; +// - Vertex 缓存资源 GET / PATCH / DELETE:404 "Cached content {id} is not found."。 +func isGeminiCachedContentNotFound(statusCode int, body []byte) bool { + lower := strings.ToLower(string(body)) + switch statusCode { + case http.StatusForbidden: + return strings.Contains(lower, "cachedcontent not found") + case http.StatusBadRequest: + return strings.Contains(lower, "invalid resource state for cache content") + case http.StatusNotFound: + return strings.Contains(lower, "cached content") && strings.Contains(lower, "not found") + default: + return false + } +} + func estimateGeminiCountTokens(reqBody []byte) int { total := 0 @@ -2854,78 +2910,6 @@ func (s *GeminiMessagesCompatService) handleNativeStreamingResponse(c *gin.Conte return &geminiNativeStreamResult{usage: usage, firstTokenMs: firstTokenMs}, nil } -// ForwardAIStudioGET forwards a GET request to AI Studio (generativelanguage.googleapis.com) for -// endpoints like /v1beta/models and /v1beta/models/{model}. -// -// This is used to support Gemini SDKs that call models listing endpoints before generation. -func (s *GeminiMessagesCompatService) ForwardAIStudioGET(ctx context.Context, account *Account, path string) (*UpstreamHTTPResult, error) { - if account == nil { - return nil, errors.New("account is nil") - } - // path 会被直接拼到上游 base URL 后面,因此按路径护栏逐片段校验, - // 见 upstream_path_guard.go。 - sanitizedPath, ok := sanitizedUpstreamPathSuffix(path) - if !ok || sanitizedPath == "" { - return nil, errors.New("invalid path") - } - path = sanitizedPath - - baseURL := account.GetGeminiBaseURL(geminicli.AIStudioBaseURL) - normalizedBaseURL, err := s.validateUpstreamBaseURL(baseURL) - if err != nil { - return nil, err - } - fullURL := strings.TrimRight(normalizedBaseURL, "/") + path - - var proxyURL string - if account.ProxyID != nil && account.Proxy != nil { - proxyURL = account.Proxy.URL() - } - - req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil) - if err != nil { - return nil, err - } - - switch account.Type { - case AccountTypeAPIKey: - apiKey := strings.TrimSpace(account.GetCredential("api_key")) - if apiKey == "" { - return nil, errors.New("gemini api_key not configured") - } - req.Header.Set("x-goog-api-key", apiKey) - case AccountTypeOAuth: - if s.tokenProvider == nil { - return nil, errors.New("gemini token provider not configured") - } - accessToken, err := s.tokenProvider.GetAccessToken(ctx, account) - if err != nil { - return nil, err - } - req.Header.Set("Authorization", "Bearer "+accessToken) - default: - return nil, fmt.Errorf("unsupported account type: %s", account.Type) - } - - resp, err := s.httpUpstream.Do(req, proxyURL, account.ID, account.Concurrency) - if err != nil { - return nil, err - } - defer func() { _ = resp.Body.Close() }() - - body, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) - wwwAuthenticate := resp.Header.Get("Www-Authenticate") - filteredHeaders := responseheaders.FilterHeaders(resp.Header, s.responseHeaderFilter) - if wwwAuthenticate != "" { - filteredHeaders.Set("Www-Authenticate", wwwAuthenticate) - } - return &UpstreamHTTPResult{ - StatusCode: resp.StatusCode, - Headers: filteredHeaders, - Body: body, - }, nil -} - // unwrapGeminiResponse 解包 Gemini OAuth 响应中的 response 字段 // 使用 gjson 零拷贝提取,避免完整 Unmarshal+Marshal func unwrapGeminiResponse(raw []byte) ([]byte, error) { @@ -3097,6 +3081,10 @@ func (s *GeminiMessagesCompatService) handleGeminiUpstreamError(ctx context.Cont if account.IsPoolMode() && !account.IsCustomErrorCodesEnabled() { return } + if account.IsGeminiThirdPartyAPIKey() { + s.handleGeminiThirdParty429(ctx, account, body) + return + } oauthType := account.GeminiOAuthType() tierID := account.GeminiTierID() @@ -3120,7 +3108,13 @@ func (s *GeminiMessagesCompatService) handleGeminiUpstreamError(ctx context.Cont logger.LegacyPrintf("service.gemini_messages_compat", "[Gemini 429] Account %d (Google One OAuth, tier=%s, project=%s) rate limited, cooldown=%v", account.ID, tierID, projectID, time.Until(ra).Truncate(time.Second)) } } else if account.IsVertexServiceAccount() { - // Vertex 按量付费:短窗限速,无每日配额,短冷却后即可恢复 + // 共享容量不足描述的是请求当时的上游容量,不是账号额度:账号保持可调度, + // 由请求内的同号退避重试与换号消化。 + if isVertexSharedCapacity429(body) { + logger.LegacyPrintf("service.gemini_messages_compat", "[Gemini 429] Account %d (Vertex service account, project=%s) shared capacity exhausted, account stays schedulable", account.ID, projectID) + return + } + // 项目配额、预留吞吐等账号自身的限速是短窗口 RPM/TPM,无每日配额,短冷却后即可恢复 ra = time.Now().Add(geminiVertexFallbackCooldown) logger.LegacyPrintf("service.gemini_messages_compat", "[Gemini 429] Account %d (Vertex service account, project=%s) rate limited, cooldown=%v", account.ID, projectID, time.Until(ra).Truncate(time.Second)) } else { @@ -3145,16 +3139,60 @@ func (s *GeminiMessagesCompatService) handleGeminiUpstreamError(ctx context.Cont account.ID, resetTime, oauthType, tierID) } +// isVertexSharedCapacity429 判断 Vertex 429 是否为按量付费共享容量不足:RESOURCE_EXHAUSTED、 +// 不带任何错误明细(RetryInfo / QuotaFailure / ErrorInfo),文案为 "Resource exhausted ... try again later" +// 且不涉及项目配额或预留吞吐。其他形态的 429 按账号自身限速处理。 +func isVertexSharedCapacity429(body []byte) bool { + errObj := gjson.GetBytes(body, "error") + if !errObj.Exists() { + errObj = gjson.GetBytes(body, "0.error") + } + if !errObj.IsObject() { + return false + } + if !strings.EqualFold(strings.TrimSpace(errObj.Get("status").String()), "RESOURCE_EXHAUSTED") { + return false + } + if len(errObj.Get("details").Array()) > 0 { + return false + } + msg := strings.ToLower(errObj.Get("message").String()) + if !strings.Contains(msg, "resource exhausted") || !strings.Contains(msg, "try again later") { + return false + } + return !strings.Contains(msg, "quota") && !strings.Contains(msg, "provisioned throughput") +} + +// handleGeminiThirdParty429 处理第三方上游的 429:不套用 AI Studio 每日配额语义, +// 只认响应里显式给出的重试时间,否则走全局 429 兜底冷却。 +func (s *GeminiMessagesCompatService) handleGeminiThirdParty429(ctx context.Context, account *Account, body []byte) { + if resetAt := parseGeminiRetryDelayResetTime(body); resetAt != nil { + resetTime := time.Unix(*resetAt, 0) + _ = s.accountRepo.SetRateLimited(ctx, account.ID, resetTime) + logger.LegacyPrintf("service.gemini_messages_compat", "[Gemini 429] Account %d (third-party API Key) rate limited until %v", account.ID, resetTime) + return + } + if s.rateLimitService != nil { + s.rateLimitService.apply429FallbackRateLimit(ctx, account, "gemini_third_party_no_reset_time") + return + } + _ = s.accountRepo.SetRateLimited(ctx, account.ID, time.Now().Add(defaultRateLimit429CooldownSeconds*time.Second)) +} + // ParseGeminiRateLimitResetTime 解析 Gemini 格式的 429 响应,返回重置时间的 Unix 时间戳 func ParseGeminiRateLimitResetTime(body []byte) *int64 { - // 第一阶段:gjson 结构化提取 errMsg := gjson.GetBytes(body, "error.message").String() if looksLikeGeminiDailyQuota(errMsg) { if ts := nextGeminiDailyResetUnix(); ts != nil { return ts } } + return parseGeminiRetryDelayResetTime(body) +} +// parseGeminiRetryDelayResetTime 只解析响应里显式给出的重试时长,返回重置时间的 Unix 时间戳。 +func parseGeminiRetryDelayResetTime(body []byte) *int64 { + // 第一阶段:gjson 结构化提取 // 遍历 error.details 查找 quotaResetDelay(AI Studio)或 RetryInfo.retryDelay(Vertex) var found *int64 gjson.GetBytes(body, "error.details").ForEach(func(_, detail gjson.Result) bool { @@ -3433,6 +3471,7 @@ func convertClaudeMessagesToGeminiContents(messages any, toolUseIDToName map[str } parts := make([]any, 0) + droppedThinking := false switch content := mm["content"].(type) { case string: // 字符串形式的 content,保留所有内容(包括空白) @@ -3440,12 +3479,18 @@ func convertClaudeMessagesToGeminiContents(messages any, toolUseIDToName map[str case []any: // 如果只有一个 block,不过滤空白(让上游 API 报错) singleBlock := len(content) == 1 + var toolImageParts []any for _, block := range content { bm, ok := block.(map[string]any) if !ok { continue } + // 历史思考块不回传给 Gemini:Gemini 的思考连续性由 thoughtSignature 承载。 + if bt, _ := bm["type"].(string); bt == "thinking" || bt == "redacted_thinking" { + droppedThinking = true + continue + } bt, _ := bm["type"].(string) switch bt { case "text": @@ -3480,14 +3525,20 @@ func convertClaudeMessagesToGeminiContents(messages any, toolUseIDToName map[str if name == "" { name = "tool" } + text := extractClaudeContentText(bm["content"]) + images := extractClaudeToolResultImageParts(bm["content"]) + if text == "" && len(images) > 0 { + text = "[image attached below]" + } parts = append(parts, map[string]any{ "functionResponse": map[string]any{ "name": name, "response": map[string]any{ - "content": extractClaudeContentText(bm["content"]), + "content": text, }, }, }) + toolImageParts = append(toolImageParts, images...) case "image": if src, ok := bm["source"].(map[string]any); ok { if srcType, _ := src["type"].(string); srcType == "base64" { @@ -3510,9 +3561,14 @@ func convertClaudeMessagesToGeminiContents(messages any, toolUseIDToName map[str } } } + parts = append(parts, toolImageParts...) default: // ignore } + // 只含思考块的消息去掉思考后为空,整条跳过(Gemini 拒收空 parts)。 + if droppedThinking && len(parts) == 0 { + continue + } out = append(out, map[string]any{ "role": gRole, @@ -3546,6 +3602,40 @@ func extractClaudeContentText(v any) string { } } +func extractClaudeToolResultImageParts(v any) []any { + arr, ok := v.([]any) + if !ok { + return nil + } + + parts := make([]any, 0) + for _, part := range arr { + pm, ok := part.(map[string]any) + if !ok || pm["type"] != "image" { + continue + } + source, ok := pm["source"].(map[string]any) + if !ok { + continue + } + if sourceType, _ := source["type"].(string); sourceType != "base64" { + continue + } + mediaType, _ := source["media_type"].(string) + data, _ := source["data"].(string) + if mediaType == "" || data == "" { + continue + } + parts = append(parts, map[string]any{ + "inlineData": map[string]any{ + "mimeType": mediaType, + "data": data, + }, + }) + } + return parts +} + func convertClaudeToolsToGeminiTools(tools any) []any { arr, ok := tools.([]any) if !ok || len(arr) == 0 { diff --git a/backend/internal/service/gemini_messages_compat_service_test.go b/backend/internal/service/gemini_messages_compat_service_test.go index 2bd70c11c..6cdba32ba 100644 --- a/backend/internal/service/gemini_messages_compat_service_test.go +++ b/backend/internal/service/gemini_messages_compat_service_test.go @@ -704,6 +704,105 @@ func TestConvertClaudeMessagesToGeminiGenerateContent_AddsThoughtSignatureForToo } } +func TestConvertClaudeMessagesToGeminiGenerateContent_ExtractsToolResultImages(t *testing.T) { + claudeReq := map[string]any{ + "messages": []any{ + map[string]any{ + "role": "assistant", + "content": []any{ + map[string]any{ + "type": "tool_use", + "id": "toolu_123", + "name": "inspect", + "input": map[string]any{ + "path": "image.png", + }, + }, + }, + }, + map[string]any{ + "role": "user", + "content": []any{ + map[string]any{ + "type": "tool_result", + "tool_use_id": "toolu_123", + "content": []any{ + map[string]any{"type": "text", "text": "found it"}, + map[string]any{ + "type": "image", + "source": map[string]any{ + "type": "base64", + "media_type": "image/png", + "data": "aGVsbG8=", + }, + }, + }, + }, + map[string]any{ + "type": "tool_result", + "tool_use_id": "toolu_123", + "content": []any{ + map[string]any{ + "type": "image", + "source": map[string]any{ + "type": "base64", + "media_type": "image/jpeg", + "data": "d29ybGQ=", + }, + }, + }, + }, + }, + }, + }, + } + body, err := json.Marshal(claudeReq) + require.NoError(t, err) + + converted, err := convertClaudeMessagesToGeminiGenerateContent(body) + require.NoError(t, err) + + var geminiReq map[string]any + require.NoError(t, json.Unmarshal(converted, &geminiReq)) + contents, ok := geminiReq["contents"].([]any) + require.True(t, ok) + content, ok := contents[1].(map[string]any) + require.True(t, ok) + parts, ok := content["parts"].([]any) + require.True(t, ok) + require.Len(t, parts, 4) + + firstPart, ok := parts[0].(map[string]any) + require.True(t, ok) + firstResponse, ok := firstPart["functionResponse"].(map[string]any) + require.True(t, ok) + require.Equal(t, "inspect", firstResponse["name"]) + firstResponseBody, ok := firstResponse["response"].(map[string]any) + require.True(t, ok) + require.Equal(t, "found it", firstResponseBody["content"]) + + secondPart, ok := parts[1].(map[string]any) + require.True(t, ok) + secondResponse, ok := secondPart["functionResponse"].(map[string]any) + require.True(t, ok) + secondResponseBody, ok := secondResponse["response"].(map[string]any) + require.True(t, ok) + require.Equal(t, "[image attached below]", secondResponseBody["content"]) + + firstImagePart, ok := parts[2].(map[string]any) + require.True(t, ok) + firstImage, ok := firstImagePart["inlineData"].(map[string]any) + require.True(t, ok) + require.Equal(t, "image/png", firstImage["mimeType"]) + require.Equal(t, "aGVsbG8=", firstImage["data"]) + secondImagePart, ok := parts[3].(map[string]any) + require.True(t, ok) + secondImage, ok := secondImagePart["inlineData"].(map[string]any) + require.True(t, ok) + require.Equal(t, "image/jpeg", secondImage["mimeType"]) + require.Equal(t, "d29ybGQ=", secondImage["data"]) +} + func TestEnsureGeminiFunctionCallThoughtSignatures_InsertsWhenMissing(t *testing.T) { geminiReq := map[string]any{ "contents": []any{ diff --git a/backend/internal/service/gemini_models_endpoints.go b/backend/internal/service/gemini_models_endpoints.go new file mode 100644 index 000000000..f9c80c869 --- /dev/null +++ b/backend/internal/service/gemini_models_endpoints.go @@ -0,0 +1,302 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "slices" + "strings" + + "github.com/MACOS-DO/sub4api/internal/pkg/gemini" + "github.com/MACOS-DO/sub4api/internal/pkg/geminicli" + "github.com/MACOS-DO/sub4api/internal/pkg/googleapi" + "github.com/MACOS-DO/sub4api/internal/util/responseheaders" +) + +// Gemini 分组对外提供 AI Studio 兼容协议(GET /v1beta/models、/v1beta/models/{model}), +// 分组内的账号可以是 AI Studio 兼容上游(API Key / OAuth),也可以是 Agent Platform (Vertex)。 +// 本文件把不同账号类型的模型接口统一成 AI Studio 格式的响应。 + +// errGeminiModelsUpstreamStatus 在 Vertex 分页读取遇到非 2xx 时中止分页,原始响应由调用方另行保存。 +var errGeminiModelsUpstreamStatus = errors.New("upstream model list returned non-2xx status") + +// SelectAccountForModelsEndpoints 为模型列表与模型详情接口选择账号。 +// +// 优先级: +// 1. 配置了 api_key 的 API Key 账号 +// 2. 不带 project_id 的 OAuth 账号(AI Studio OAuth) +// 3. 显式标记为 ai_studio 的 OAuth 账号 +// 4. Code Assist OAuth 账号(令牌常缺 AI Studio 权限范围,多半退回内置列表) +// 5. 其余类型的账号 +// 6. Vertex 服务账号(服务账号 JSON 认证,读取 Google 发布方模型列表) +// 7. Vertex API Key 账号(列表接口不接受 API Key,只能返回内置列表) +// +// Vertex 账号排在所有 AI Studio 兼容账号之后,混合分组始终由 AI Studio 兼容账号应答。 +// 同级账号按 priority、最近使用时间挑选。 +func (s *GeminiMessagesCompatService) SelectAccountForModelsEndpoints(ctx context.Context, groupID *int64) (*Account, error) { + accounts, err := s.listSchedulableAccountsOnce(ctx, groupID, PlatformGemini, true) + if err != nil { + return nil, fmt.Errorf("query accounts failed: %w", err) + } + if len(accounts) == 0 { + return nil, errors.New("no available Gemini accounts") + } + + var selected *Account + for i := range accounts { + acc := &accounts[i] + if selected == nil { + selected = acc + continue + } + + r1, r2 := modelsEndpointAccountRank(acc), modelsEndpointAccountRank(selected) + if r1 < r2 { + selected = acc + continue + } + if r1 > r2 { + continue + } + + if acc.Priority < selected.Priority { + selected = acc + } else if acc.Priority == selected.Priority { + switch { + case acc.LastUsedAt == nil && selected.LastUsedAt != nil: + selected = acc + case acc.LastUsedAt != nil && selected.LastUsedAt == nil: + // keep selected + case acc.LastUsedAt == nil && selected.LastUsedAt == nil: + if acc.Type == AccountTypeOAuth && selected.Type != AccountTypeOAuth { + selected = acc + } + default: + if acc.LastUsedAt.Before(*selected.LastUsedAt) { + selected = acc + } + } + } + } + + if selected == nil { + return nil, errors.New("no available Gemini accounts") + } + return s.hydrateSelectedAccount(ctx, selected) +} + +// modelsEndpointAccountRank 返回账号在模型接口选号中的优先级,数值越小越优先,顺序见 SelectAccountForModelsEndpoints。 +func modelsEndpointAccountRank(a *Account) int { + if a == nil { + return 999 + } + switch a.Type { + case AccountTypeAPIKey: + if strings.TrimSpace(a.GetCredential("api_key")) != "" { + return 0 + } + return 9 + case AccountTypeOAuth: + if strings.TrimSpace(a.GetCredential("project_id")) == "" { + return 1 + } + if strings.TrimSpace(a.GetCredential("oauth_type")) == "ai_studio" { + return 2 + } + return 3 + case AccountTypeServiceAccount: + if a.IsVertexAPIKey() { + return 12 + } + return 11 + default: + return 10 + } +} + +// ForwardListModels 读取账号上游的模型列表,返回 AI Studio 格式的响应(GET /v1beta/models)。 +// AI Studio 兼容账号原样返回上游响应;Vertex 服务账号读取 Google 发布方模型列表后转换格式, +// 上游非 2xx 时原样返回该响应;Vertex API Key 账号返回内置列表。 +func (s *GeminiMessagesCompatService) ForwardListModels(ctx context.Context, account *Account) (*UpstreamHTTPResult, error) { + if account == nil { + return nil, errors.New("account is nil") + } + if !account.IsVertexServiceAccount() { + return s.forwardGeminiModelsGET(ctx, account, "/v1beta/models") + } + if account.IsVertexAPIKey() { + return geminiModelsJSONResult(http.StatusOK, gemini.FallbackModelsList()) + } + + modelIDs, failure, err := s.listVertexGeminiModels(ctx, account, account.VertexLocation("")) + if err != nil { + return nil, err + } + if failure != nil { + return failure, nil + } + models := make([]gemini.Model, 0, len(modelIDs)) + for _, modelID := range modelIDs { + models = append(models, gemini.FallbackModel(modelID)) + } + return geminiModelsJSONResult(http.StatusOK, gemini.ModelsListResponse{Models: models}) +} + +// ForwardGetModel 读取账号上游的单个模型信息,返回 AI Studio 格式的响应(GET /v1beta/models/{model})。 +// Vertex 服务账号在该模型生成请求所用区域的模型列表中查找,找不到时返回 404;Vertex API Key 账号返回内置信息。 +func (s *GeminiMessagesCompatService) ForwardGetModel(ctx context.Context, account *Account, model string) (*UpstreamHTTPResult, error) { + if account == nil { + return nil, errors.New("account is nil") + } + if !account.IsVertexServiceAccount() { + return s.forwardGeminiModelsGET(ctx, account, "/v1beta/models/"+model) + } + if account.IsVertexAPIKey() { + return geminiModelsJSONResult(http.StatusOK, gemini.FallbackModel(model)) + } + + modelIDs, failure, err := s.listVertexGeminiModels(ctx, account, account.VertexLocation(model)) + if err != nil { + return nil, err + } + if failure != nil { + return failure, nil + } + if slices.Contains(modelIDs, model) { + return geminiModelsJSONResult(http.StatusOK, gemini.FallbackModel(model)) + } + return geminiModelsJSONResult(http.StatusNotFound, map[string]any{ + "error": map[string]any{ + "code": http.StatusNotFound, + "message": fmt.Sprintf("models/%s is not found", model), + "status": googleapi.HTTPStatusToGoogleStatus(http.StatusNotFound), + }, + }) +} + +// forwardGeminiModelsGET 向 AI Studio 兼容上游转发模型接口的 GET 请求。 +// path 会被直接拼到上游 base URL 后面,因此按路径护栏逐片段校验,见 upstream_path_guard.go。 +func (s *GeminiMessagesCompatService) forwardGeminiModelsGET(ctx context.Context, account *Account, path string) (*UpstreamHTTPResult, error) { + sanitizedPath, ok := sanitizedUpstreamPathSuffix(path) + if !ok || sanitizedPath == "" { + return nil, errors.New("invalid path") + } + + baseURL := account.GetGeminiBaseURL(geminicli.AIStudioBaseURL) + normalizedBaseURL, err := s.validateUpstreamBaseURL(baseURL) + if err != nil { + return nil, err + } + fullURL := strings.TrimRight(normalizedBaseURL, "/") + sanitizedPath + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil) + if err != nil { + return nil, err + } + + switch account.Type { + case AccountTypeAPIKey: + apiKey := strings.TrimSpace(account.GetCredential("api_key")) + if apiKey == "" { + return nil, errors.New("gemini api_key not configured") + } + req.Header.Set("x-goog-api-key", apiKey) + case AccountTypeOAuth: + if s.tokenProvider == nil { + return nil, errors.New("gemini token provider not configured") + } + accessToken, err := s.tokenProvider.GetAccessToken(ctx, account) + if err != nil { + return nil, err + } + req.Header.Set("Authorization", "Bearer "+accessToken) + default: + return nil, fmt.Errorf("unsupported account type: %s", account.Type) + } + + return s.doGeminiModelsGET(req, account) +} + +// listVertexGeminiModels 读取 Vertex 服务账号在指定区域可用的 Gemini 模型。 +// 上游返回非 2xx 时 failure 为该页的原始响应,modelIDs 与 err 均为空。 +func (s *GeminiMessagesCompatService) listVertexGeminiModels(ctx context.Context, account *Account, location string) (modelIDs []string, failure *UpstreamHTTPResult, err error) { + if s.tokenProvider == nil { + return nil, nil, errors.New("gemini token provider not configured") + } + accessToken, err := s.tokenProvider.GetAccessToken(ctx, account) + if err != nil { + return nil, nil, err + } + + modelIDs, err = listVertexGeminiPublisherModels(location, func(_ int, listURL string) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, listURL, nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + req.Header.Set("Authorization", "Bearer "+accessToken) + + res, err := s.doGeminiModelsGET(req, account) + if err != nil { + return nil, err + } + if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusMultipleChoices { + failure = res + return nil, errGeminiModelsUpstreamStatus + } + return res.Body, nil + }) + if failure != nil { + return nil, failure, nil + } + if err != nil { + return nil, nil, err + } + return modelIDs, nil, nil +} + +// doGeminiModelsGET 发送模型接口请求并读取响应。响应体上限取 gateway.models_list_read_max_bytes,超出时报错;响应头按配置过滤。 +func (s *GeminiMessagesCompatService) doGeminiModelsGET(req *http.Request, account *Account) (*UpstreamHTTPResult, error) { + var proxyURL string + if account.ProxyID != nil && account.Proxy != nil { + proxyURL = account.Proxy.URL() + } + + resp, err := s.httpUpstream.Do(req, proxyURL, account.ID, account.Concurrency) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + + bodyLimit := resolveModelsListReadLimit(s.cfg) + body, _ := io.ReadAll(io.LimitReader(resp.Body, bodyLimit+1)) + if int64(len(body)) > bodyLimit { + return nil, fmt.Errorf("upstream model list response exceeds %d bytes", bodyLimit) + } + wwwAuthenticate := resp.Header.Get("Www-Authenticate") + filteredHeaders := responseheaders.FilterHeaders(resp.Header, s.responseHeaderFilter) + if wwwAuthenticate != "" { + filteredHeaders.Set("Www-Authenticate", wwwAuthenticate) + } + return &UpstreamHTTPResult{ + StatusCode: resp.StatusCode, + Headers: filteredHeaders, + Body: body, + }, nil +} + +// geminiModelsJSONResult 把网关生成的模型接口响应包装成 UpstreamHTTPResult,交给 handler 统一写出。 +func geminiModelsJSONResult(status int, payload any) (*UpstreamHTTPResult, error) { + body, err := json.Marshal(payload) + if err != nil { + return nil, err + } + return &UpstreamHTTPResult{ + StatusCode: status, + Headers: http.Header{"Content-Type": []string{"application/json; charset=utf-8"}}, + Body: body, + }, nil +} diff --git a/backend/internal/service/gemini_models_endpoints_test.go b/backend/internal/service/gemini_models_endpoints_test.go new file mode 100644 index 000000000..f809811df --- /dev/null +++ b/backend/internal/service/gemini_models_endpoints_test.go @@ -0,0 +1,208 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "net/http" + "testing" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/MACOS-DO/sub4api/internal/pkg/gemini" + "github.com/stretchr/testify/require" +) + +func newGeminiModelsEndpointsTestService(accounts []Account, upstream HTTPUpstream) *GeminiMessagesCompatService { + repo := &mockAccountRepoForGemini{listByGroupFunc: func(context.Context, int64, []string) ([]Account, error) { + return accounts, nil + }} + return &GeminiMessagesCompatService{ + accountRepo: repo, + httpUpstream: upstream, + cfg: &config.Config{}, + tokenProvider: NewGeminiTokenProvider(nil, &vertexModelsTokenCacheStub{token: "ya29.vertex-token"}, nil), + } +} + +func decodeGeminiModelNames(t *testing.T, body []byte) []string { + t.Helper() + var got gemini.ModelsListResponse + require.NoError(t, json.Unmarshal(body, &got)) + names := make([]string, 0, len(got.Models)) + for _, model := range got.Models { + require.Contains(t, model.SupportedGenerationMethods, "generateContent") + names = append(names, model.Name) + } + return names +} + +func TestSelectAccountForModelsEndpoints_VertexServiceAccountOnlyGroup(t *testing.T) { + groupID := int64(8) + vertex := *vertexModelSyncTestAccount(nil) + vertex.ID = 18 + svc := newGeminiModelsEndpointsTestService([]Account{vertex}, nil) + + account, err := svc.SelectAccountForModelsEndpoints(context.Background(), &groupID) + require.NoError(t, err) + require.Equal(t, int64(18), account.ID) +} + +func TestModelsEndpointAccountRank_Order(t *testing.T) { + ordered := []*Account{ + {Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k"}}, + {Platform: PlatformGemini, Type: AccountTypeOAuth, Credentials: map[string]any{}}, + {Platform: PlatformGemini, Type: AccountTypeOAuth, Credentials: map[string]any{"project_id": "p", "oauth_type": "ai_studio"}}, + {Platform: PlatformGemini, Type: AccountTypeOAuth, Credentials: map[string]any{"project_id": "p", "oauth_type": "code_assist"}}, + {Platform: PlatformGemini, Type: AccountTypeUpstream, Credentials: map[string]any{"api_key": "k"}}, + vertexModelSyncTestAccount(nil), + {Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{"auth_mode": "apikey", "api_key": "AQ.k"}}, + } + for i := 1; i < len(ordered); i++ { + require.Less(t, modelsEndpointAccountRank(ordered[i-1]), modelsEndpointAccountRank(ordered[i]), "position %d", i) + } +} + +func TestSelectAccountForModelsEndpoints_PrefersAPIKeyOverVertex(t *testing.T) { + groupID := int64(8) + vertex := *vertexModelSyncTestAccount(nil) + vertex.ID = 18 + apiKey := Account{ID: 19, Platform: PlatformGemini, Type: AccountTypeAPIKey, Priority: 9, Credentials: map[string]any{"api_key": "k"}} + svc := newGeminiModelsEndpointsTestService([]Account{vertex, apiKey}, nil) + + account, err := svc.SelectAccountForModelsEndpoints(context.Background(), &groupID) + require.NoError(t, err) + require.Equal(t, int64(19), account.ID) +} + +func TestForwardListModels_VertexServiceAccountReturnsAIStudioFormat(t *testing.T) { + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[ + {"name":"publishers/google/models/gemini-3.8-flash"}, + {"name":"publishers/google/models/gemma4"} + ],"nextPageToken":"page-2"}`), + vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[{"name":"publishers/google/models/gemini-2.5-flash"}]}`), + }} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + + res, err := svc.ForwardListModels(context.Background(), vertexModelSyncTestAccount(map[string]any{"location": "europe-west4"})) + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode) + require.Equal(t, []string{"models/gemini-2.5-flash", "models/gemini-3.8-flash"}, decodeGeminiModelNames(t, res.Body)) + + require.Len(t, upstream.requests, 2) + require.Equal(t, "https://europe-west4-aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300", upstream.requests[0].URL.String()) + require.Equal(t, "https://europe-west4-aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300&pageToken=page-2", upstream.requests[1].URL.String()) + for _, req := range upstream.requests { + require.Equal(t, "Bearer ya29.vertex-token", req.Header.Get("Authorization")) + } +} + +func TestForwardListModels_VertexUpstreamErrorPassesThrough(t *testing.T) { + body := `{"error":{"code":403,"status":"PERMISSION_DENIED"}}` + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusForbidden, body)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + + res, err := svc.ForwardListModels(context.Background(), vertexModelSyncTestAccount(map[string]any{"location": "global"})) + require.NoError(t, err) + require.Equal(t, http.StatusForbidden, res.StatusCode) + require.JSONEq(t, body, string(res.Body)) +} + +func TestForwardListModels_VertexAPIKeyReturnsBuiltinList(t *testing.T) { + upstream := &httpUpstreamRecorder{} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + account := &Account{ID: 174, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{ + "auth_mode": "apikey", + "api_key": "AQ.test-key", + }} + + res, err := svc.ForwardListModels(context.Background(), account) + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode) + expected, err := json.Marshal(gemini.FallbackModelsList()) + require.NoError(t, err) + require.JSONEq(t, string(expected), string(res.Body)) + require.Empty(t, upstream.requests) +} + +func TestForwardListModels_APIKeyForwardsToBaseURL(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"models":[{"name":"models/gemini-native"}]}`)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + account := &Account{ID: 261, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "sk-pool", + "base_url": "https://relay.example.com", + }} + + res, err := svc.ForwardListModels(context.Background(), account) + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode) + require.JSONEq(t, `{"models":[{"name":"models/gemini-native"}]}`, string(res.Body)) + require.Equal(t, "https://relay.example.com/v1beta/models", upstream.lastReq.URL.String()) + require.Equal(t, "sk-pool", upstream.lastReq.Header.Get("x-goog-api-key")) +} + +func TestForwardGetModel_VertexServiceAccountLooksUpModelList(t *testing.T) { + listBody := `{"publisherModels":[{"name":"publishers/google/models/gemini-3.8-flash"}]}` + + t.Run("listed model", func(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, listBody)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + + res, err := svc.ForwardGetModel(context.Background(), vertexModelSyncTestAccount(nil), "gemini-3.8-flash") + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode) + var model gemini.Model + require.NoError(t, json.Unmarshal(res.Body, &model)) + require.Equal(t, "models/gemini-3.8-flash", model.Name) + }) + + t.Run("unlisted model", func(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, listBody)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + + res, err := svc.ForwardGetModel(context.Background(), vertexModelSyncTestAccount(nil), "gemini-unknown") + require.NoError(t, err) + require.Equal(t, http.StatusNotFound, res.StatusCode) + require.JSONEq(t, `{"error":{"code":404,"message":"models/gemini-unknown is not found","status":"NOT_FOUND"}}`, string(res.Body)) + }) +} + +func TestForwardGetModel_VertexUsesModelLocation(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[{"name":"publishers/google/models/gemini-3.8-flash"}]}`)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + account := vertexModelSyncTestAccount(map[string]any{ + "location": "europe-west4", + "vertex_model_locations": map[string]any{"gemini-3.8-flash": "global"}, + }) + + res, err := svc.ForwardGetModel(context.Background(), account, "gemini-3.8-flash") + require.NoError(t, err) + require.Equal(t, http.StatusOK, res.StatusCode) + require.Equal(t, "https://aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300", upstream.lastReq.URL.String()) +} + +func TestForwardListModels_VertexMidPaginationErrorPassesThrough(t *testing.T) { + body := `{"error":{"code":503,"status":"UNAVAILABLE"}}` + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[{"name":"publishers/google/models/gemini-3.8-flash"}],"nextPageToken":"page-2"}`), + vertexModelsJSONResponse(http.StatusServiceUnavailable, body), + }} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + + res, err := svc.ForwardListModels(context.Background(), vertexModelSyncTestAccount(nil)) + require.NoError(t, err) + require.Equal(t, http.StatusServiceUnavailable, res.StatusCode) + require.JSONEq(t, body, string(res.Body)) + require.Len(t, upstream.requests, 2) +} + +func TestForwardListModels_ResponseOverReadLimitFails(t *testing.T) { + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"models":[{"name":"models/gemini-native"}]}`)} + svc := newGeminiModelsEndpointsTestService(nil, upstream) + svc.cfg.Gateway.ModelsListReadMaxBytes = 16 + account := &Account{ID: 261, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk-pool"}} + + _, err := svc.ForwardListModels(context.Background(), account) + require.ErrorContains(t, err, "exceeds 16 bytes") +} diff --git a/backend/internal/service/gemini_native_reasoning_pricing_test.go b/backend/internal/service/gemini_native_reasoning_pricing_test.go index f6565cfa7..c978331a4 100644 --- a/backend/internal/service/gemini_native_reasoning_pricing_test.go +++ b/backend/internal/service/gemini_native_reasoning_pricing_test.go @@ -137,7 +137,7 @@ func TestGeminiNativeReasoningPricingUsesExplicitForwardedLevel(t *testing.T) { } } -func TestGeminiChatCompatReasoningPricingIgnoresUnforwardedEffort(t *testing.T) { +func TestGeminiChatCompatReasoningPricingUsesForwardedEffort(t *testing.T) { gin.SetMode(gin.TestMode) for _, stream := range []bool{false, true} { mode := "buffered" @@ -168,8 +168,9 @@ func TestGeminiChatCompatReasoningPricingIgnoresUnforwardedEffort(t *testing.T) require.NoError(t, err) require.Equal(t, http.StatusOK, recorder.Code) require.Len(t, upstream.requestBodies, 1) - require.False(t, gjson.GetBytes(upstream.requestBodies[0], "generationConfig.thinkingConfig").Exists()) - require.Nil(t, result.ReasoningEffort) + require.Equal(t, "high", gjson.GetBytes(upstream.requestBodies[0], "generationConfig.thinkingConfig.thinkingLevel").String()) + require.Equal(t, stream, gjson.GetBytes(upstream.requestBodies[0], "generationConfig.thinkingConfig.includeThoughts").Bool()) + require.Equal(t, "high", optionalStringValue(result.ReasoningEffort)) billing := NewBillingService(&config.Config{}, nil) cost, err := billing.CalculateTokenCostForRequest(TokenCostRequest{ @@ -184,7 +185,7 @@ func TestGeminiChatCompatReasoningPricingIgnoresUnforwardedEffort(t *testing.T) Resolver: NewModelPricingResolver(nil, billing), }) require.NoError(t, err) - require.InDelta(t, 1, cost.TotalCost, 1e-12) + require.InDelta(t, 2, cost.TotalCost, 1e-12) }) } } diff --git a/backend/internal/service/gemini_quota.go b/backend/internal/service/gemini_quota.go index d9f2e3734..118f02d9f 100644 --- a/backend/internal/service/gemini_quota.go +++ b/backend/internal/service/gemini_quota.go @@ -373,6 +373,10 @@ func geminiQuotaTierKeyForAccount(account *Account) string { if account == nil || account.Platform != PlatformGemini { return "" } + // 本地模拟配额只适用于按 Google 账号等级限额的通道;第三方上游与 Vertex 按量付费不套用。 + if account.IsGeminiThirdPartyAPIKey() || account.IsVertexServiceAccount() { + return "" + } // Note: GeminiOAuthType() already defaults legacy (project_id present) to code_assist. oauthType := strings.ToLower(strings.TrimSpace(account.GeminiOAuthType())) diff --git a/backend/internal/service/gemini_quota_test.go b/backend/internal/service/gemini_quota_test.go new file mode 100644 index 000000000..a9287a11d --- /dev/null +++ b/backend/internal/service/gemini_quota_test.go @@ -0,0 +1,80 @@ +//go:build unit + +package service + +import ( + "context" + "testing" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestAccountIsGeminiThirdPartyAPIKey(t *testing.T) { + tests := []struct { + name string + account *Account + expected bool + }{ + {"nil_account", nil, false}, + {"empty_base_url_is_official", geminiQuotaAPIKeyAccount(""), false}, + {"official_base_url", geminiQuotaAPIKeyAccount("https://generativelanguage.googleapis.com"), false}, + {"official_base_url_trailing_slash", geminiQuotaAPIKeyAccount("https://generativelanguage.googleapis.com/"), false}, + {"official_host_over_http", geminiQuotaAPIKeyAccount("http://generativelanguage.googleapis.com"), true}, + {"official_host_with_path_prefix", geminiQuotaAPIKeyAccount("https://generativelanguage.googleapis.com/proxy"), true}, + {"relay_base_url", geminiQuotaAPIKeyAccount("https://relay.example.com"), true}, + {"oauth_account", &Account{Platform: PlatformGemini, Type: AccountTypeOAuth, Credentials: map[string]any{"base_url": "https://relay.example.com"}}, false}, + {"vertex_service_account", &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount}, false}, + {"non_gemini_platform", &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": "https://relay.example.com"}}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.expected, tt.account.IsGeminiThirdPartyAPIKey()) + }) + } +} + +func TestGeminiQuotaService_QuotaForAccountSkipsThirdPartyAndVertex(t *testing.T) { + svc := NewGeminiQuotaService(&config.Config{}, nil) + ctx := context.Background() + + quota, ok := svc.QuotaForAccount(ctx, geminiQuotaAPIKeyAccount("")) + require.True(t, ok) + require.Equal(t, int64(50), quota.ProRPD) + + paid := geminiQuotaAPIKeyAccount("https://generativelanguage.googleapis.com") + paid.Credentials["tier_id"] = GeminiTierAIStudioPaid + quota, ok = svc.QuotaForAccount(ctx, paid) + require.True(t, ok) + require.Equal(t, int64(-1), quota.ProRPD) + + relay := geminiQuotaAPIKeyAccount("https://relay.example.com") + relay.Credentials["tier_id"] = GeminiTierAIStudioFree + _, ok = svc.QuotaForAccount(ctx, relay) + require.False(t, ok, "第三方上游不套用 AI Studio 模拟配额") + + vertex := &Account{ + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Credentials: map[string]any{"project_id": "my-project", "tier_id": "vertex"}, + } + _, ok = svc.QuotaForAccount(ctx, vertex) + require.False(t, ok, "Vertex 按量付费不套用模拟配额") + + googleOne := &Account{ + Platform: PlatformGemini, + Type: AccountTypeOAuth, + Credentials: map[string]any{"oauth_type": "google_one", "tier_id": GeminiTierGoogleOneFree}, + } + quota, ok = svc.QuotaForAccount(ctx, googleOne) + require.True(t, ok) + require.Positive(t, quota.SharedRPD) +} + +func geminiQuotaAPIKeyAccount(baseURL string) *Account { + credentials := map[string]any{} + if baseURL != "" { + credentials["base_url"] = baseURL + } + return &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: credentials} +} diff --git a/backend/internal/service/gemini_vertex_api_key_forward_test.go b/backend/internal/service/gemini_vertex_api_key_forward_test.go new file mode 100644 index 000000000..936c586b3 --- /dev/null +++ b/backend/internal/service/gemini_vertex_api_key_forward_test.go @@ -0,0 +1,165 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/MACOS-DO/sub4api/internal/pkg/tlsfingerprint" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +const geminiVertexAPIKeyTestResponse = `{"candidates":[{"content":{"parts":[{"text":"hello"}],"role":"model"},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":5,"totalTokenCount":15}}` + +func newGeminiVertexAPIKeyTestService() (*GeminiMessagesCompatService, *geminiCompatHTTPUpstreamStub) { + httpStub := &geminiCompatHTTPUpstreamStub{ + response: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}, "X-Request-Id": []string{"vertex-req-1"}}, + Body: io.NopCloser(strings.NewReader(geminiVertexAPIKeyTestResponse)), + }, + } + // tokenProvider 留空:API Key 认证不依赖 access token。 + return &GeminiMessagesCompatService{httpUpstream: httpStub, cfg: &config.Config{}}, httpStub +} + +func geminiVertexAPIKeyTestAccount(projectID string) *Account { + credentials := map[string]any{ + "auth_mode": "apikey", + "api_key": "vertex-test-key", + "location": "us-central1", + "tier_id": "vertex", + } + if projectID != "" { + credentials["project_id"] = projectID + } + return &Account{ + ID: 811, + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Credentials: credentials, + Concurrency: 1, + } +} + +func requireVertexAPIKeyAuth(t *testing.T, req *http.Request) { + t.Helper() + require.NotNil(t, req) + require.Equal(t, "vertex-test-key", req.Header.Get("x-goog-api-key")) + require.Empty(t, req.Header.Get("Authorization")) +} + +func TestGeminiForwardNative_VertexAPIKeyWithoutProjectUsesExpressEndpoint(t *testing.T) { + gin.SetMode(gin.TestMode) + svc, httpStub := newGeminiVertexAPIKeyTestService() + c, _ := newGeminiNativeTestContext(t) + + result, err := svc.ForwardNative(context.Background(), c, geminiVertexAPIKeyTestAccount(""), + "gemini-3-flash-preview", "generateContent", false, []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`)) + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 1, httpStub.calls) + require.Equal(t, "https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-3-flash-preview:generateContent", httpStub.lastReq.URL.String()) + requireVertexAPIKeyAuth(t, httpStub.lastReq) +} + +func TestGeminiMessagesCompatServiceForward_VertexAPIKeyWithProjectUsesProjectEndpoint(t *testing.T) { + gin.SetMode(gin.TestMode) + svc, httpStub := newGeminiVertexAPIKeyTestService() + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + body := []byte(`{"model":"gemini-3-flash-preview","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`) + + result, err := svc.Forward(context.Background(), c, geminiVertexAPIKeyTestAccount("my-project"), body) + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, "https://us-central1-aiplatform.googleapis.com/v1/projects/my-project/locations/us-central1/publishers/google/models/gemini-3-flash-preview:generateContent", httpStub.lastReq.URL.String()) + requireVertexAPIKeyAuth(t, httpStub.lastReq) +} + +func TestGeminiForwardAsChatCompletions_VertexAPIKeyUsesAPIKeyHeader(t *testing.T) { + gin.SetMode(gin.TestMode) + svc, httpStub := newGeminiVertexAPIKeyTestService() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gemini-3-flash-preview","messages":[{"role":"user","content":"hi"}]}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + + result, err := svc.ForwardAsChatCompletions(context.Background(), c, geminiVertexAPIKeyTestAccount(""), body) + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, "https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-3-flash-preview:generateContent", httpStub.lastReq.URL.String()) + requireVertexAPIKeyAuth(t, httpStub.lastReq) +} + +type geminiVertex429SequenceUpstream struct { + responses []*http.Response + calls int +} + +func (s *geminiVertex429SequenceUpstream) Do(req *http.Request, proxyURL string, accountID int64, accountConcurrency int) (*http.Response, error) { + resp := s.responses[min(s.calls, len(s.responses)-1)] + s.calls++ + return resp, nil +} + +func (s *geminiVertex429SequenceUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return s.Do(req, proxyURL, accountID, accountConcurrency) +} + +// Vertex 共享容量不足的 429 在同一账号上退避重试,成功后账号状态不变;绑定显式缓存的请求同样如此。 +func TestGeminiForwardNative_VertexSharedCapacity429RetriesSameAccountWithoutCooldown(t *testing.T) { + gin.SetMode(gin.TestMode) + sharedCapacity := `{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED"}}` + tests := []struct { + name string + ctx context.Context + }{ + {name: "unbound", ctx: context.Background()}, + {name: "bound_cached_content", ctx: WithGeminiCachedContentBound(context.Background())}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstream := &geminiVertex429SequenceUpstream{responses: []*http.Response{ + { + StatusCode: http.StatusTooManyRequests, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(sharedCapacity)), + }, + { + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(geminiVertexAPIKeyTestResponse)), + }, + }} + repo := &geminiBoundCacheRateLimitRepo{} + svc := &GeminiMessagesCompatService{ + httpUpstream: upstream, + cfg: &config.Config{}, + accountRepo: repo, + rateLimitService: NewRateLimitService(repo, nil, &config.Config{}, nil, nil), + } + c, rec := newGeminiNativeTestContext(t) + + result, err := svc.ForwardNative(tt.ctx, c, geminiVertexAPIKeyTestAccount("my-project"), + "gemini-3.7-flash", "generateContent", false, []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`)) + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, 2, upstream.calls, "429 后在同一账号上重试") + require.Zero(t, repo.rateLimitedCalls, "不写账号级限流") + require.Zero(t, repo.tempCalls) + require.Zero(t, repo.setErrCalls) + require.Empty(t, repo.modelRateLimitCalls) + }) + } +} diff --git a/backend/internal/service/gemini_vertex_token_error.go b/backend/internal/service/gemini_vertex_token_error.go new file mode 100644 index 000000000..7577dcca5 --- /dev/null +++ b/backend/internal/service/gemini_vertex_token_error.go @@ -0,0 +1,60 @@ +package service + +import ( + "context" + "log/slog" + "net/http" + + "github.com/gin-gonic/gin" +) + +// vertexServiceAccountNotFoundReason 标识换取 SA access token 时 SA 已不存在。 +const vertexServiceAccountNotFoundReason GatewayFailureReason = "vertex_service_account_not_found" + +// geminiVertexCredentialFailoverBody 是 SA 凭据失效时挂在 failover 错误上的 Google 格式错误体, +// 供 handler 在换号耗尽后做透传规则匹配与错误信息提取。 +var geminiVertexCredentialFailoverBody = []byte(`{"error":{"code":401,"message":"Upstream authentication failed","status":"UNAUTHENTICATED"}}`) + +// handleVertexServiceAccountNotFound 处理 Gemini 三条转发路径(原生 / Claude 兼容 / +// Chat Completions 兼容)构造上游请求时换取 SA access token 失败、且 SA 已不存在的情况: +// +// - 账号置为 error 并停止调度,错误信息带上 token 端点的 error_description; +// - 记录凭据获取阶段(stage=account_auth)的 Ops 事件,token 端点的状态码只出现在 Message 中; +// - 返回 *UpstreamFailoverError(401),由 handler 的 failover 循环换号。 +// +// 不是该类失败时返回 nil,由调用方继续处理。本函数不写响应。 +func (s *GeminiMessagesCompatService) handleVertexServiceAccountNotFound(ctx context.Context, c *gin.Context, account *Account, err error) *UpstreamFailoverError { + tokenErr, ok := vertexServiceAccountNotFoundError(err) + if !ok { + return nil + } + + msg := "Service account token rejected (400): " + tokenErr.Description + stateCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), openAIAccountStateUpdateTimeout) + defer cancel() + if s.rateLimitService != nil { + s.rateLimitService.handleAuthError(stateCtx, account, msg) + } else if s.accountRepo != nil { + if setErr := s.accountRepo.SetError(stateCtx, account.ID, msg); setErr != nil { + slog.Warn("account_set_error_failed", "account_id", account.ID, "error", setErr) + } + } + + event := OpsUpstreamErrorEvent{ + Platform: account.Platform, + AccountID: account.ID, + AccountName: account.Name, + Kind: "failover", + Stage: string(GatewayFailureStageAccountAuth), + Scope: string(GatewayFailureScopeAccount), + Reason: string(vertexServiceAccountNotFoundReason), + Message: sanitizeUpstreamErrorMessage(err.Error()), + } + event.ProxyID, event.ProxyName = opsUpstreamProxyAttribution(account) + appendOpsUpstreamError(c, event) + + return &UpstreamFailoverError{ + StatusCode: http.StatusUnauthorized, + ResponseBody: geminiVertexCredentialFailoverBody, + } +} diff --git a/backend/internal/service/gemini_vertex_token_error_test.go b/backend/internal/service/gemini_vertex_token_error_test.go new file mode 100644 index 000000000..b5eacfafd --- /dev/null +++ b/backend/internal/service/gemini_vertex_token_error_test.go @@ -0,0 +1,207 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// --------------------------------------------------------------------------- +// 换取 SA access token 时 SA 已不存在(token 端点 400 invalid_grant +// "Invalid grant: account not found")的契约,三条转发路径一致: +// - 账号置为 error 并停止调度,错误信息带 token 端点的 error_description; +// - 不发出上游请求,返回 *UpstreamFailoverError(401) 交给 handler 换号,service 不写响应; +// - Ops 事件记为凭据获取阶段(stage=account_auth); +// - 其他换 token 失败不改账号状态、不换号,直接回写 502。 +// --------------------------------------------------------------------------- + +const vertexAccountNotFoundTokenBody = `{"error":"invalid_grant","error_description":"Invalid grant: account not found"}` + +func newVertexTokenTestAccount(t *testing.T) *Account { + t.Helper() + privateKey, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + pemBytes := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}) + saJSON, err := json.Marshal(map[string]string{ + "type": "service_account", + "project_id": "proj-1", + "private_key_id": "kid-1", + "private_key": string(pemBytes), + "client_email": "svc@proj-1.iam.gserviceaccount.com", + }) + require.NoError(t, err) + return &Account{ + ID: 820, + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Credentials: map[string]any{ + "service_account_json": string(saJSON), + "project_id": "proj-1", + "location": "global", + }, + } +} + +func useVertexTokenEndpoint(t *testing.T, status int, body string) { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(server.Close) + original := vertexServiceAccountTokenURL + vertexServiceAccountTokenURL = server.URL + t.Cleanup(func() { vertexServiceAccountTokenURL = original }) +} + +func newVertexTokenErrorService() (*GeminiMessagesCompatService, *geminiCompatHTTPUpstreamStub, *errorPolicyRepoStub) { + repo := &errorPolicyRepoStub{} + httpStub := &geminiCompatHTTPUpstreamStub{} + svc := &GeminiMessagesCompatService{ + accountRepo: repo, + httpUpstream: httpStub, + tokenProvider: NewGeminiTokenProvider(repo, nil, nil), + rateLimitService: NewRateLimitService(repo, nil, &config.Config{}, nil, nil), + cfg: &config.Config{}, + } + return svc, httpStub, repo +} + +func requireVertexAccountNotFoundHandled(t *testing.T, c *gin.Context, err error, httpStub *geminiCompatHTTPUpstreamStub, repo *errorPolicyRepoStub) { + t.Helper() + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "SA 不存在应换号,got %T: %v", err, err) + require.Equal(t, http.StatusUnauthorized, failoverErr.StatusCode) + require.Equal(t, string(geminiVertexCredentialFailoverBody), string(failoverErr.ResponseBody)) + require.True(t, failoverErr.ShouldRetryNextAccount()) + require.False(t, failoverErr.RetryableOnSameAccount) + + require.Equal(t, 1, repo.setErrCalls, "SA 不存在应把账号置为 error") + require.Equal(t, "Service account token rejected (400): Invalid grant: account not found", repo.lastErrorMsg) + require.Zero(t, httpStub.calls, "换不到 token 时不应发出上游请求") + require.False(t, c.Writer.Written(), "换号场景不应写客户端响应") + + raw, ok := c.Get(OpsUpstreamErrorsKey) + require.True(t, ok, "应记录 ops 上游错误事件") + events := raw.([]*OpsUpstreamErrorEvent) + require.Len(t, events, 1) + require.Equal(t, "failover", events[0].Kind) + require.Equal(t, int64(820), events[0].AccountID) + require.Equal(t, string(GatewayFailureStageAccountAuth), events[0].Stage) + require.Equal(t, string(GatewayFailureScopeAccount), events[0].Scope) + require.Equal(t, string(vertexServiceAccountNotFoundReason), events[0].Reason) + require.Zero(t, events[0].UpstreamStatusCode, "换 token 失败不占用上游状态码") + require.Contains(t, events[0].Message, "service account token request returned 400: Invalid grant: account not found") +} + +func TestExchangeVertexServiceAccountToken_AccountNotFoundIsRecognized(t *testing.T) { + useVertexTokenEndpoint(t, http.StatusBadRequest, vertexAccountNotFoundTokenBody) + key, err := parseVertexServiceAccountKey(newVertexTokenTestAccount(t)) + require.NoError(t, err) + + _, _, err = exchangeVertexServiceAccountToken(contextWithTestTimeout(t), key, "") + + require.EqualError(t, err, "service account token request returned 400: Invalid grant: account not found") + tokenErr, ok := vertexServiceAccountNotFoundError(fmt.Errorf("build request: %w", err)) + require.True(t, ok) + require.Equal(t, "invalid_grant", tokenErr.Code) + require.Equal(t, "Invalid grant: account not found", tokenErr.Description) +} + +func TestVertexServiceAccountNotFoundError_OnlyMatchesAccountNotFound(t *testing.T) { + tests := []struct { + name string + err error + }{ + {"other_invalid_grant", &vertexTokenRequestError{StatusCode: 400, Code: "invalid_grant", Description: "Invalid JWT Signature."}}, + {"not_400", &vertexTokenRequestError{StatusCode: 401, Code: "invalid_grant", Description: "Invalid grant: account not found"}}, + {"other_code", &vertexTokenRequestError{StatusCode: 400, Code: "invalid_request", Description: "Invalid grant: account not found"}}, + {"server_error", &vertexTokenRequestError{StatusCode: 500, Message: "backend error"}}, + {"plain_error", errors.New("service account token request returned 400: Invalid grant: account not found")}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, ok := vertexServiceAccountNotFoundError(tt.err) + require.False(t, ok) + }) + } +} + +func TestGeminiForwardNative_VertexServiceAccountNotFoundDisablesAndFailsOver(t *testing.T) { + gin.SetMode(gin.TestMode) + useVertexTokenEndpoint(t, http.StatusBadRequest, vertexAccountNotFoundTokenBody) + svc, httpStub, repo := newVertexTokenErrorService() + c, _ := newGeminiNativeTestContext(t) + + result, err := svc.ForwardNative(context.Background(), c, newVertexTokenTestAccount(t), + "gemini-3.8-flash", "streamGenerateContent", true, []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`)) + + require.Nil(t, result) + requireVertexAccountNotFoundHandled(t, c, err, httpStub, repo) +} + +func TestGeminiForward_VertexServiceAccountNotFoundDisablesAndFailsOver(t *testing.T) { + gin.SetMode(gin.TestMode) + useVertexTokenEndpoint(t, http.StatusBadRequest, vertexAccountNotFoundTokenBody) + svc, httpStub, repo := newVertexTokenErrorService() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gemini-3.8-flash","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + + result, err := svc.Forward(context.Background(), c, newVertexTokenTestAccount(t), body) + + require.Nil(t, result) + requireVertexAccountNotFoundHandled(t, c, err, httpStub, repo) +} + +func TestGeminiForwardAsChatCompletions_VertexServiceAccountNotFoundDisablesAndFailsOver(t *testing.T) { + gin.SetMode(gin.TestMode) + useVertexTokenEndpoint(t, http.StatusBadRequest, vertexAccountNotFoundTokenBody) + svc, httpStub, repo := newVertexTokenErrorService() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gemini-3.8-flash","messages":[{"role":"user","content":"hi"}]}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + + result, err := svc.ForwardAsChatCompletions(context.Background(), c, newVertexTokenTestAccount(t), body) + + require.Nil(t, result) + requireVertexAccountNotFoundHandled(t, c, err, httpStub, repo) +} + +func TestGeminiForwardNative_OtherVertexTokenErrorKeepsAccountState(t *testing.T) { + gin.SetMode(gin.TestMode) + useVertexTokenEndpoint(t, http.StatusBadRequest, `{"error":"invalid_grant","error_description":"Invalid JWT Signature."}`) + svc, httpStub, repo := newVertexTokenErrorService() + c, rec := newGeminiNativeTestContext(t) + + result, err := svc.ForwardNative(context.Background(), c, newVertexTokenTestAccount(t), + "gemini-3.8-flash", "generateContent", false, []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`)) + + require.Nil(t, result) + require.Error(t, err) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr), "未识别的换 token 失败不换号") + require.Zero(t, repo.setErrCalls, "未识别的换 token 失败不改账号状态") + require.Zero(t, httpStub.calls) + require.Equal(t, http.StatusBadGateway, rec.Code) + require.True(t, strings.Contains(rec.Body.String(), "Invalid JWT Signature.")) +} diff --git a/backend/internal/service/group.go b/backend/internal/service/group.go index 822db11cd..df8395842 100644 --- a/backend/internal/service/group.go +++ b/backend/internal/service/group.go @@ -19,6 +19,7 @@ type Group struct { ID int64 Name string Description string + I18n GroupI18n // 名称与描述的界面语言译文;缺失的语言沿用 Name/Description Platform string RateMultiplier float64 // 高峰时段倍率:peak_rate_enabled 为 true 且当前时刻处于 [PeakStart, PeakEnd) 时, diff --git a/backend/internal/service/group_i18n.go b/backend/internal/service/group_i18n.go new file mode 100644 index 000000000..6483ead5c --- /dev/null +++ b/backend/internal/service/group_i18n.go @@ -0,0 +1,64 @@ +package service + +import ( + "fmt" + "maps" + "regexp" + "slices" + "strings" + "unicode/utf8" + + "github.com/MACOS-DO/sub4api/internal/domain" + infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors" +) + +type GroupI18n = domain.GroupI18n +type GroupLocaleText = domain.GroupLocaleText + +// groupI18nNameMaxRunes 与 groups.name 的长度上限一致。 +const groupI18nNameMaxRunes = 100 + +// 语言代码只校验 BCP 47 形态(en、zh、zh-TW);具体提供哪些语言由前端语言包决定。 +var groupI18nLocalePattern = regexp.MustCompile(`^[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8})*$`) + +// normalizeGroupI18n 把语言代码统一为 domain.CanonicalLocale 的写法,去除译文首尾空白, +// 并丢弃名称与描述都为空的语言。统一写法后重复的语言代码(如 en 与 EN)直接拒绝, +// 不在其中任选一份。返回值始终非 nil,落库为 JSON 对象。 +func normalizeGroupI18n(in GroupI18n) (GroupI18n, error) { + out := make(GroupI18n, len(in)) + seen := make(map[string]struct{}, len(in)) + for _, raw := range slices.Sorted(maps.Keys(in)) { + if !groupI18nLocalePattern.MatchString(raw) { + return nil, infraerrors.BadRequest("INVALID_GROUP_I18N", fmt.Sprintf("invalid locale %q in i18n", raw)) + } + locale := domain.CanonicalLocale(raw) + if _, dup := seen[locale]; dup { + return nil, infraerrors.BadRequest("INVALID_GROUP_I18N", fmt.Sprintf("duplicate locale %q in i18n", locale)) + } + seen[locale] = struct{}{} + text := in[raw] + name := strings.TrimSpace(text.Name) + description := strings.TrimSpace(text.Description) + if utf8.RuneCountInString(name) > groupI18nNameMaxRunes { + return nil, infraerrors.BadRequest("INVALID_GROUP_I18N", fmt.Sprintf("i18n name for locale %q must be at most %d characters", locale, groupI18nNameMaxRunes)) + } + if name == "" && description == "" { + continue + } + out[locale] = GroupLocaleText{Name: name, Description: description} + } + return out, nil +} + +// cloneGroupI18nForDuplicate 复制译文中的描述。名称译文不随复制带走: +// 副本的 name 已改写,沿用源分组的名称译文会让两个分组在该语言下同名。 +func cloneGroupI18nForDuplicate(in GroupI18n) GroupI18n { + out := make(GroupI18n, len(in)) + for locale, text := range in { + if text.Description == "" { + continue + } + out[locale] = GroupLocaleText{Description: text.Description} + } + return out +} diff --git a/backend/internal/service/group_i18n_test.go b/backend/internal/service/group_i18n_test.go new file mode 100644 index 000000000..c3fd84eaf --- /dev/null +++ b/backend/internal/service/group_i18n_test.go @@ -0,0 +1,83 @@ +package service + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestNormalizeGroupI18n(t *testing.T) { + t.Run("nil input yields an empty non-nil map", func(t *testing.T) { + got, err := normalizeGroupI18n(nil) + require.NoError(t, err) + require.NotNil(t, got) + require.Empty(t, got) + }) + + t.Run("trims text and drops locales with nothing left", func(t *testing.T) { + got, err := normalizeGroupI18n(GroupI18n{ + "en": {Name: " Standard ", Description: "\tPro + Max pool\n"}, + "zh": {Name: " ", Description: ""}, + "zh-TW": {Description: "僅描述"}, + }) + require.NoError(t, err) + require.Equal(t, GroupI18n{ + "en": {Name: "Standard", Description: "Pro + Max pool"}, + "zh-TW": {Description: "僅描述"}, + }, got) + }) + + t.Run("locale codes are stored in canonical case", func(t *testing.T) { + got, err := normalizeGroupI18n(GroupI18n{ + "EN": {Name: "Standard"}, + "zh-tw": {Name: "標準"}, + }) + require.NoError(t, err) + require.Equal(t, GroupI18n{ + "en": {Name: "Standard"}, + "zh-TW": {Name: "標準"}, + }, got) + }) + + t.Run("rejects locales that collide after canonicalization", func(t *testing.T) { + for _, in := range []GroupI18n{ + {"en": {Name: "English A"}, "EN": {Name: "English B"}}, + {"zh-TW": {Name: "標準"}, "zh-tw": {}}, + } { + _, err := normalizeGroupI18n(in) + require.Errorf(t, err, "input %v should be rejected", in) + } + }) + + t.Run("rejects malformed locale codes", func(t *testing.T) { + for _, locale := range []string{"", "e", "en_US", "en-", "中文", "en us"} { + _, err := normalizeGroupI18n(GroupI18n{locale: {Name: "x"}}) + require.Errorf(t, err, "locale %q should be rejected", locale) + } + }) + + t.Run("name length is capped in characters like groups.name", func(t *testing.T) { + atLimit := strings.Repeat("名", groupI18nNameMaxRunes) + got, err := normalizeGroupI18n(GroupI18n{"zh": {Name: atLimit}}) + require.NoError(t, err) + require.Equal(t, atLimit, got["zh"].Name) + + _, err = normalizeGroupI18n(GroupI18n{"zh": {Name: atLimit + "名"}}) + require.Error(t, err) + }) +} + +func TestCloneGroupI18nForDuplicate(t *testing.T) { + source := GroupI18n{ + "en": {Name: "Standard", Description: "Pro + Max pool"}, + "zh": {Name: "标准"}, + } + + got := cloneGroupI18nForDuplicate(source) + + // 副本改了 name;名称译文若照搬,副本与源分组在该语言下会同名。 + require.Equal(t, GroupI18n{"en": {Description: "Pro + Max pool"}}, got) + require.Equal(t, "Standard", source["en"].Name, "source must not be mutated") + require.NotNil(t, cloneGroupI18nForDuplicate(nil)) +} diff --git a/backend/internal/service/model_plaza_service.go b/backend/internal/service/model_plaza_service.go index 0f24a13f1..37ef1e303 100644 --- a/backend/internal/service/model_plaza_service.go +++ b/backend/internal/service/model_plaza_service.go @@ -40,6 +40,7 @@ type PlazaGroup struct { ID int64 Name string Description string + I18n GroupI18n Platform string SubscriptionType string RateMultiplier float64 @@ -125,6 +126,7 @@ func (s *ModelPlazaService) ListGroups(ctx context.Context) ([]PlazaGroup, error ID: g.ID, Name: g.Name, Description: g.Description, + I18n: g.I18n, Platform: g.Platform, SubscriptionType: g.SubscriptionType, RateMultiplier: g.RateMultiplier, diff --git a/backend/internal/service/model_rate_limit.go b/backend/internal/service/model_rate_limit.go index 970139a58..56644ab75 100644 --- a/backend/internal/service/model_rate_limit.go +++ b/backend/internal/service/model_rate_limit.go @@ -79,7 +79,7 @@ func (a *Account) modelRateLimitKeysForRequest(ctx context.Context, requestedMod keys := []string{modelKey} switch a.Platform { case PlatformAntigravity: - if isAntigravityGeminiModel(modelKey) && modelKey != antigravityGeminiModelRateLimitKey { + if isAntigravityGeminiModel(modelKey) && !isAntigravityGeminiImageModel(modelKey) && modelKey != antigravityGeminiModelRateLimitKey { keys = append(keys, antigravityGeminiModelRateLimitKey) } case PlatformOpenAI: @@ -164,12 +164,17 @@ func antigravityModelRateLimitKeys(model string) []string { return nil } keys := []string{model} - if isAntigravityGeminiModel(model) && model != antigravityGeminiModelRateLimitKey { + if isAntigravityGeminiModel(model) && !isAntigravityGeminiImageModel(model) && model != antigravityGeminiModelRateLimitKey { keys = append(keys, antigravityGeminiModelRateLimitKey) } return keys } +func isAntigravityGeminiImageModel(model string) bool { + normalized := normalizeAntigravityModelName(model) + return strings.HasPrefix(normalized, "gemini-") && strings.Contains(normalized, "-image") +} + func (a *Account) modelRateLimitResetAt(scope string) *time.Time { if a == nil || a.Extra == nil || scope == "" { return nil diff --git a/backend/internal/service/model_rate_limit_test.go b/backend/internal/service/model_rate_limit_test.go index 22e64f6db..9e81d5be7 100644 --- a/backend/internal/service/model_rate_limit_test.go +++ b/backend/internal/service/model_rate_limit_test.go @@ -255,6 +255,31 @@ func TestIsModelRateLimited_OpenAIImageGenerationIntentBlocksTextModelImageTool( require.True(t, account.isModelRateLimitedWithContext(WithOpenAIImageGenerationIntent(context.Background()), "gpt-5.4")) } +func TestIsModelRateLimited_AntigravityImageDoesNotInheritGeminiFamilyLimit(t *testing.T) { + future := time.Now().Add(10 * time.Minute).Format(time.RFC3339) + account := &Account{ + Platform: PlatformAntigravity, + Extra: map[string]any{ + modelRateLimitsKey: map[string]any{ + antigravityGeminiModelRateLimitKey: map[string]any{ + "rate_limit_reset_at": future, + }, + }, + }, + } + + for _, model := range []string{"gemini-3.1-flash-image", "gemini-3.1-flash-image-preview", "gemini-3-pro-image"} { + require.False(t, account.isModelRateLimitedWithContext(context.Background(), model), model) + } + require.True(t, account.isModelRateLimitedWithContext(context.Background(), "gemini-3-flash")) + rawLimits, ok := account.Extra[modelRateLimitsKey].(map[string]any) + require.True(t, ok) + rawLimits["gemini-3.1-flash-image"] = map[string]any{ + "rate_limit_reset_at": future, + } + require.True(t, account.isModelRateLimitedWithContext(context.Background(), "gemini-3-pro-image-preview")) +} + func TestIsModelRateLimited_Antigravity_ThinkingAffectsModelKey(t *testing.T) { now := time.Now() future := now.Add(10 * time.Minute).Format(time.RFC3339) diff --git a/backend/internal/service/openai_account_runtime_block_fastpath.go b/backend/internal/service/openai_account_runtime_block_fastpath.go index 99f017143..120f61c34 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath.go @@ -158,7 +158,8 @@ func (s *OpenAIGatewayService) handleOpenAIAccountUpstreamError(ctx context.Cont // Isolate a custom temporary-unschedulable match to the known upstream // model before entering the generic account error path. This keeps the // account available to other models and avoids the account runtime blocker. - if s.rateLimitService != nil && statusCode != http.StatusUnauthorized && len(canonicalModel) > 0 && strings.TrimSpace(canonicalModel[0]) != "" && + if s.rateLimitService != nil && len(canonicalModel) > 0 && strings.TrimSpace(canonicalModel[0]) != "" && + tempUnschedRulesApply(account, statusCode, responseBody, canonicalModel[0]) && s.rateLimitService.HandleTempUnschedulable(stateCtx, account, statusCode, responseBody, canonicalModel[0]) { return true } @@ -173,7 +174,8 @@ func (s *OpenAIGatewayService) handleOpenAIAccountUpstreamError(ctx context.Cont return false } shouldDisable := s.rateLimitService.HandleUpstreamError(stateCtx, account, statusCode, headers, responseBody) - modelTempMatched := statusCode != http.StatusUnauthorized && tempUnschedulableModel(stateCtx, nil) != "" && + tempModel := tempUnschedulableModel(stateCtx, nil) + modelTempMatched := tempModel != "" && tempUnschedRulesApply(account, statusCode, responseBody, tempModel) && len(matchTempUnschedulableRules(account, statusCode, responseBody)) > 0 if shouldDisable && !modelTempMatched { s.BlockAccountScheduling(account, time.Time{}, "upstream_disable") diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index 4f5b11666..6dfb99761 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -1815,7 +1815,7 @@ func (s *defaultOpenAIAccountScheduler) isAccountRequestCompatibleReason(ctx con }) { return false, "shadow_parent_unhealthy" } - if req.RequestedModel != "" && !account.IsModelSupported(req.RequestedModel) { + if req.RequestedModel != "" && !supportsOpenAIRequestModel(account, req.RequestedModel, req.RequireCompact) { return false, "model_not_supported" } if req.GroupID != nil && s != nil && s.service != nil && diff --git a/backend/internal/service/openai_account_scheduler_test.go b/backend/internal/service/openai_account_scheduler_test.go index eb964dfac..8d0046def 100644 --- a/backend/internal/service/openai_account_scheduler_test.go +++ b/backend/internal/service/openai_account_scheduler_test.go @@ -48,6 +48,10 @@ func (r schedulerTestOpenAIAccountRepo) ListSchedulableByGroupID(ctx context.Con return append([]Account(nil), r.accounts...), nil } +func (r schedulerTestOpenAIAccountRepo) ListModelAvailabilityCandidates(ctx context.Context, groupID *int64, _ []string, _ bool) ([]Account, error) { + return r.ListSchedulableByGroupID(ctx, *groupID) +} + func (r schedulerTestOpenAIAccountRepo) ListSchedulableByPlatform(ctx context.Context, platform string) ([]Account, error) { var result []Account for _, acc := range r.accounts { diff --git a/backend/internal/service/openai_alpha_search_billing_test.go b/backend/internal/service/openai_alpha_search_billing_test.go index 897623896..dfa1cfb5c 100644 --- a/backend/internal/service/openai_alpha_search_billing_test.go +++ b/backend/internal/service/openai_alpha_search_billing_test.go @@ -51,7 +51,7 @@ func TestCalculateOpenAIRecordUsageCostWebSearchPerCall(t *testing.T) { // 即使 token 倍率(含高峰,3.0)更高也不采用。 apiKey := &APIKey{ID: 1, GroupID: &groupID, Group: &Group{ID: groupID, Platform: PlatformOpenAI}} result := &OpenAIForwardResult{Model: "gpt-5.6-sol", UpstreamModel: "gpt-5.6-sol", WebSearchCalls: 1} - cost, err := svc.calculateOpenAIRecordUsageCost(context.Background(), result, apiKey, []string{"gpt-5.6-sol"}, 3.0, 1.0, 1.0, 2.0, UsageTokens{}, "", boolPtr(false), time.Time{}) + cost, err := svc.calculateOpenAIRecordUsageCost(context.Background(), result, apiKey, []string{"gpt-5.6-sol"}, 3.0, 1.0, 1.0, 2.0, UsageTokens{}, "", boolPtr(false), false, time.Time{}) require.NoError(t, err) require.Equal(t, string(BillingModePerRequest), cost.BillingMode) require.InDelta(t, 0.01, cost.TotalCost, 1e-12) @@ -59,7 +59,7 @@ func TestCalculateOpenAIRecordUsageCostWebSearchPerCall(t *testing.T) { // 分组配置单价 0.005 apiKey.Group.WebSearchPricePerCall = float64Ptr(0.005) - cost, err = svc.calculateOpenAIRecordUsageCost(context.Background(), result, apiKey, []string{"gpt-5.6-sol"}, 1.0, 1.0, 1.0, 1.0, UsageTokens{}, "", boolPtr(false), time.Time{}) + cost, err = svc.calculateOpenAIRecordUsageCost(context.Background(), result, apiKey, []string{"gpt-5.6-sol"}, 1.0, 1.0, 1.0, 1.0, UsageTokens{}, "", boolPtr(false), false, time.Time{}) require.NoError(t, err) require.InDelta(t, 0.005, cost.TotalCost, 1e-12) require.InDelta(t, 0.005, cost.ActualCost, 1e-12) @@ -67,7 +67,7 @@ func TestCalculateOpenAIRecordUsageCostWebSearchPerCall(t *testing.T) { // WebSearchCalls = 0 时不得走按次分支(无定价数据会返回 pricing 错误, // 证明回落到了 token 路径而不是被按次分支吞掉)。 result.WebSearchCalls = 0 - _, err = svc.calculateOpenAIRecordUsageCost(context.Background(), result, apiKey, []string{"gpt-5.6-sol"}, 1.0, 1.0, 1.0, 1.0, UsageTokens{InputTokens: 10}, "", boolPtr(false), time.Time{}) + _, err = svc.calculateOpenAIRecordUsageCost(context.Background(), result, apiKey, []string{"gpt-5.6-sol"}, 1.0, 1.0, 1.0, 1.0, UsageTokens{InputTokens: 10}, "", boolPtr(false), false, time.Time{}) require.Error(t, err) } diff --git a/backend/internal/service/openai_codex_model_metadata.go b/backend/internal/service/openai_codex_model_metadata.go index 16b56724e..32199cacb 100644 --- a/backend/internal/service/openai_codex_model_metadata.go +++ b/backend/internal/service/openai_codex_model_metadata.go @@ -123,6 +123,12 @@ func codexModelRoutingAccountIDs(group *Group, modelID string) []int64 { return group.GetRoutingAccountIDs(strings.TrimSpace(modelID)) } +func codexAccountServesPlatformModel(account *Account, platform, modelID string) bool { + return account.Platform == platform || + (account.Platform == PlatformAntigravity && mixedListingAccountAllowed(platform, account) && + mixedListingModelAllowed(platform, modelID)) +} + func groupCodexModelMetadata( platform string, modelID string, @@ -168,7 +174,7 @@ func groupCodexModelMetadata( if routed && !containsInt64(routedAccountIDs, account.ID) { continue } - if account.Platform == platform && codexExplicitModelMappingClaims(*account, modelID) { + if codexAccountServesPlatformModel(account, platform, modelID) && codexExplicitModelMappingClaims(*account, modelID) { explicitClaims = true break } @@ -183,7 +189,7 @@ func groupCodexModelMetadata( missingMetadata := false for i := range accounts { account := &accounts[i] - if account.Platform != platform { + if !codexAccountServesPlatformModel(account, platform, modelID) { continue } if routed && !containsInt64(routedAccountIDs, account.ID) { @@ -251,7 +257,7 @@ func codexExplicitModelTargetsConflictForPlatform(accounts []Account, platform, targets := make(map[string]struct{}) for i := range accounts { account := &accounts[i] - if account.Platform != platform { + if !codexAccountServesPlatformModel(account, platform, modelID) { continue } mappedModel, matched := account.ResolveMappedModel(modelID) diff --git a/backend/internal/service/openai_codex_model_metadata_test.go b/backend/internal/service/openai_codex_model_metadata_test.go index 16ed878e9..aafe8aae1 100644 --- a/backend/internal/service/openai_codex_model_metadata_test.go +++ b/backend/internal/service/openai_codex_model_metadata_test.go @@ -9,6 +9,71 @@ import ( "github.com/stretchr/testify/require" ) +func TestCodexCatalogUsesAntigravityCapabilitiesInGeminiMixedGroup(t *testing.T) { + const groupID int64 = 93 + account := Account{ + ID: 25, Platform: PlatformAntigravity, Type: AccountTypeOAuth, + Extra: map[string]any{"mixed_scheduling": true}, + Credentials: map[string]any{"model_mapping": map[string]any{ + "gemini-custom": "gemini-3.8-flash-high", + }}, + } + reasoning := true + account.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{ + Models: map[string]UpstreamModelMetadata{"gemini-3.8-flash-high": { + ID: "gemini-3.8-flash-high", Reasoning: &reasoning, + DefaultReasoningLevel: "high", SupportedReasoningLevels: []string{"high"}, + InputModalities: []string{"text", "image"}, ContextWindow: 1_048_576, + MaxOutputTokens: 65_536, + }}, + }) + svc := &GatewayService{accountRepo: codexModelsVisibilityAccountRepo{ + byGroup: map[int64][]Account{groupID: {account}}, + }} + for _, platform := range []string{PlatformAntigravity, PlatformComposite, PlatformGemini} { + t.Run(platform, func(t *testing.T) { + body, err := svc.BuildCodexModelsManifestForGroup(context.Background(), + &Group{ID: groupID, Platform: platform}, "", []string{"gemini-custom"}) + require.NoError(t, err) + model := decodeCodexManifestModels(t, body)[0] + require.Equal(t, "gemini-custom", model["slug"]) + require.Equal(t, float64(1_048_576), model["context_window"]) + require.Equal(t, []any{"text", "image"}, model["input_modalities"]) + require.Equal(t, []string{"high"}, effortsFromManifestModel(t, model)) + }) + } +} + +func TestCodexCatalogGeminiCapabilitiesExcludeNonMixedAntigravityAccounts(t *testing.T) { + const groupID int64 = 94 + reasoning := true + native := Account{ID: 1, Platform: PlatformGemini, Type: AccountTypeAPIKey, + Credentials: map[string]any{"model_mapping": map[string]any{"gemini-custom": "gemini-3.8-flash-high"}}, + } + native.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{ + Models: map[string]UpstreamModelMetadata{"gemini-3.8-flash-high": { + ID: "gemini-3.8-flash-high", Reasoning: &reasoning, + SupportedReasoningLevels: []string{"high"}, InputModalities: []string{"text", "image"}, + ContextWindow: 1_048_576, + }}, + }) + for _, extra := range []map[string]any{nil, {"mixed_scheduling": false}} { + // A peer lacking capabilities would narrow the catalog if included. + peer := Account{ID: 2, Platform: PlatformAntigravity, Type: AccountTypeOAuth, + Extra: extra, Credentials: native.Credentials} + svc := &GatewayService{accountRepo: codexModelsVisibilityAccountRepo{ + byGroup: map[int64][]Account{groupID: {native, peer}}, + }} + body, err := svc.BuildCodexModelsManifestForGroup(context.Background(), + &Group{ID: groupID, Platform: PlatformGemini}, "", []string{"gemini-custom"}) + require.NoError(t, err) + model := decodeCodexManifestModels(t, body)[0] + require.Equal(t, float64(1_048_576), model["context_window"]) + require.Equal(t, []any{"text", "image"}, model["input_modalities"]) + require.Equal(t, []string{"high"}, effortsFromManifestModel(t, model)) + } +} + func TestAstraUltraCatalogPreservesWorkflowMetadata(t *testing.T) { // Ultra is a Codex workflow. Its inference effort must survive catalog sync, // aliases and group generation instead of silently falling back to max. diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index 3bfea1d92..d02fbfb8a 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -187,13 +187,13 @@ func (s *OpenAIGatewayService) MergeGroupConfiguredCodexModels( return nil } + visible, accounts, err := loadCodexGroupCatalogAccounts(ctx, s.accountRepo, group.ID) + if err != nil { + return fmt.Errorf("load group configured Codex models: %w", err) + } var configuredModels []string if !group.CodexModelsManifestConfig.Enabled { - var err error - configuredModels, err = s.groupConfiguredCodexModelIDs(ctx, group) - if err != nil { - return fmt.Errorf("load group configured Codex models: %w", err) - } + configuredModels = openAIConfiguredCodexModelIDsForGroup(visible, group) } body, changed, err := mergeConfiguredCodexModelsManifest( manifest.Body, @@ -211,7 +211,12 @@ func (s *OpenAIGatewayService) MergeGroupConfiguredCodexModels( } changed = true } - if changed { + filtered, retired, err := filterRetiredOpenAIPublicModelsBody(body, accounts, true) + if err != nil { + return fmt.Errorf("filter retired Codex models: %w", err) + } + body = filtered + if changed || retired { manifest.Body = body manifest.ETag = codexModelsManifestBodyETag(body) } @@ -222,17 +227,6 @@ func (s *OpenAIGatewayService) MergeGroupConfiguredCodexModels( return nil } -func (s *OpenAIGatewayService) groupConfiguredCodexModelIDs(ctx context.Context, group *Group) ([]string, error) { - if group == nil { - return nil, nil - } - accounts, err := s.accountRepo.ListSchedulableByGroupID(ctx, group.ID) - if err != nil { - return nil, err - } - return openAIConfiguredCodexModelIDsForGroup(accounts, group), nil -} - // loadCodexGroupCatalogAccounts separates picker membership from capability // intersection. visible accounts are currently schedulable and decide which // public aliases appear. catalog accounts are persistently enabled group @@ -300,7 +294,7 @@ func openAIConfiguredCodexModelIDs(accounts []Account) []string { func openAIConfiguredCodexModelIDsForGroup(accounts []Account, group *Group) []string { models := supplementUnmappedOpenAIModels(accounts, openAIConfiguredCodexModelIDs(accounts)) if group == nil || !group.ModelAllowlistEnabled() { - return models + return filterRetiredOpenAIModelIDs(accounts, models) } seen := make(map[string]struct{}, len(models)+len(group.ModelAllowlist.Models)) @@ -329,7 +323,7 @@ func openAIConfiguredCodexModelIDsForGroup(accounts []Account, group *Group) []s } } sort.Strings(models) - return models + return filterRetiredOpenAIModelIDs(accounts, models) } const ( @@ -487,7 +481,7 @@ func newConfiguredCodexModelDescriptor(modelID string) configuredCodexModelDescr } if isClaudeCodexModel(modelID) { - if claude.IsOpus55(modelID) || claude.IsSonnet55(modelID) { + if claude.IsOpus55(modelID) || claude.IsSonnet55(modelID) || claude.IsHaiku55(modelID) { descriptor.ContextWindow = 1_000_000 descriptor.MaxContextWindow = 1_000_000 } @@ -546,6 +540,9 @@ func newConfiguredCodexModelDescriptor(modelID string) configuredCodexModelDescr } descriptor.Slug = modelID descriptor.officialMetadata = openai.CodexGPT61SolMetadata + // The October 12, 2026 Codex/Work default increased to 500k after + // the bundled official snapshot. Explicit upstream metadata still wins. + descriptor.ContextWindow = 500_000 } return descriptor } @@ -911,6 +908,19 @@ func buildCodexModelsManifestForAccounts( if effectivePlatform == PlatformOpenAIBPS { return buildOpenAIBPSCodexModelsManifest(modelIDs) } + if effectivePlatform == PlatformOpenAI { + modelIDs = filterRetiredOpenAIModelIDs(accounts, modelIDs) + } else if effectivePlatform == PlatformComposite { + filtered := make([]string, 0, len(modelIDs)) + for _, modelID := range modelIDs { + platform, target, resolved := resolveCodexCompositeModelTarget(modelID, accounts, compositeRoutes, compositeRoutesAvailable) + if resolved && platform == PlatformOpenAI && openAIModelRetiredForAccounts(accounts, target) { + continue + } + filtered = append(filtered, modelID) + } + modelIDs = filtered + } imageInputModels := make(map[string]bool, len(modelIDs)) searchToolModels := make(map[string]bool, len(modelIDs)) metadataModels := codexCatalogMetadataModels( @@ -1113,7 +1123,7 @@ func uniqueCodexMappedModel(accounts []Account, platform string, modelID string) targets := make(map[string]struct{}) for i := range accounts { account := &accounts[i] - if account.Platform != platform { + if !codexAccountServesPlatformModel(account, platform, modelID) { continue } mappedModel, matched := account.ResolveMappedModel(modelID) diff --git a/backend/internal/service/openai_codex_models_service_test.go b/backend/internal/service/openai_codex_models_service_test.go index 9706ec461..b968be45e 100644 --- a/backend/internal/service/openai_codex_models_service_test.go +++ b/backend/internal/service/openai_codex_models_service_test.go @@ -334,6 +334,14 @@ func TestNewConfiguredCodexModelDescriptorUsesProviderMetadataAndSafeFallback(t require.Equal(t, "none", *claudeHaiku.DefaultReasoningLevel) require.Equal(t, []string{"none"}, effortsFromConfiguredCodexLevels(claudeHaiku.SupportedReasoningLevels)) + claudeHaiku55 := newConfiguredCodexModelDescriptor("claude-haiku-5-5") + require.Equal(t, "Claude Haiku 5.5", claudeHaiku55.DisplayName) + require.Equal(t, int64(1_000_000), claudeHaiku55.ContextWindow) + require.Equal(t, int64(1_000_000), claudeHaiku55.MaxContextWindow) + require.NotNil(t, claudeHaiku55.DefaultReasoningLevel) + require.Equal(t, "medium", *claudeHaiku55.DefaultReasoningLevel) + require.Equal(t, []string{"low", "medium", "high", "xhigh", "max"}, effortsFromConfiguredCodexLevels(claudeHaiku55.SupportedReasoningLevels)) + gpt56 := newConfiguredCodexModelDescriptor("gpt-5.6-sol") require.Equal(t, "GPT-5.6 Sol", gpt56.DisplayName) require.Equal(t, "OpenAI GPT coding model routed through Sub2API.", gpt56.Description) @@ -2403,7 +2411,7 @@ func TestFetchCodexModelsManifestAPIKeyDisablesResponsesLiteForAffectedModels(t } func TestFetchCodexModelsManifestOAuthPreservesResponsesLite(t *testing.T) { - const manifestBody = ` {"models":[{"slug":"gpt-5.6-sol","use_responses_lite":true}]} ` + const manifestBody = ` {"models":[{"slug":"gpt-5.6-sol","use_responses_lite":true},{"slug":"gpt-6.1-sol","context_window":500000,"max_context_window":1000000,"use_responses_lite":true}]} ` server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(manifestBody)) })) @@ -3798,7 +3806,7 @@ func TestGPT61SolOfflineCodexCatalog(t *testing.T) { m := catalog.Models[0] require.Equal(t, "gpt-6.1-sol", m["slug"]) require.Equal(t, "low", m["default_reasoning_level"]) - require.EqualValues(t, 272000, m["context_window"]) + require.EqualValues(t, 500000, m["context_window"]) require.EqualValues(t, 872000, m["max_context_window"]) require.Equal(t, "xhigh", m["multi_agent_reasoning_effort"]) require.Equal(t, "v2", m["multi_agent_version"]) @@ -3851,3 +3859,25 @@ func TestGPT61SolAPIKeyCatalogUsesFullResponses(t *testing.T) { require.Equal(t, false, catalog.Models[0]["use_responses_lite"]) require.Equal(t, "low", catalog.Models[0]["default_reasoning_level"]) } + +func TestGPT61SolAPIKeyCatalogContextWindow(t *testing.T) { + account := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": "https://api.openai.com"}} + for _, tc := range []struct { + name string + body string + want int64 + }{ + {"missing uses updated default", `{"models":[{"slug":"gpt-6.1-sol"}]}`, 500_000}, + {"null uses updated default", `{"models":[{"slug":"gpt-6.1-sol","context_window":null}]}`, 500_000}, + {"lower upstream window is preserved", `{"models":[{"slug":"gpt-6.1-sol","context_window":272000}]}`, 272_000}, + {"higher upstream window is preserved", `{"models":[{"slug":"gpt-6.1-sol","context_window":1000000,"max_context_window":1000000}]}`, 1_000_000}, + } { + t.Run(tc.name, func(t *testing.T) { + body, err := completeAPIKeyCodexModelsManifestMetadata([]byte(tc.body), true, account) + require.NoError(t, err) + models := decodeCodexManifestModels(t, body) + require.Len(t, models, 1) + require.EqualValues(t, tc.want, models[0]["context_window"]) + }) + } +} diff --git a/backend/internal/service/openai_compact_fallback.go b/backend/internal/service/openai_compact_fallback.go index 1a61e987a..d9877912b 100644 --- a/backend/internal/service/openai_compact_fallback.go +++ b/backend/internal/service/openai_compact_fallback.go @@ -57,6 +57,9 @@ func (s *OpenAIGatewayService) resolveOpenAICompactFallbackModel(account *Accoun if account != nil { if mapped, matched := account.ResolveCompactMappedModel(requestedModel); matched { if mapped = strings.TrimSpace(mapped); mapped != "" { + if isRetiredOpenAISubscriptionModel(account, mapped) { + return "" + } return mapped } } @@ -68,7 +71,11 @@ func (s *OpenAIGatewayService) resolveOpenAICompactFallbackModel(account *Accoun if fallback == "" { return "" } - return strings.TrimSpace(resolveOpenAIAccountUpstreamModelForRequest(account, fallback, false)) + resolved := strings.TrimSpace(resolveOpenAIAccountUpstreamModelForRequest(account, fallback, false)) + if isRetiredOpenAISubscriptionModel(account, resolved) { + return "" + } + return resolved } func isOpenAICompactModelFailure(statusCode int, upstreamMsg string, upstreamBody []byte) bool { diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index 27bc97c4f..a6edbcc8d 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -67,13 +67,26 @@ func (s *OpenAIGatewayService) newStreamHeaderWriter(c *gin.Context, upstream ht // (下游 handleXxxErrorResponse 需要再次读取),返回原始错误体与脱敏后的 // 上游错误消息。 func (s *OpenAIGatewayService) readOpenAIUpstreamError(resp *http.Response) ([]byte, string) { - respBody := s.readUpstreamErrorBody(resp) + respBody, upstreamMsg, _ := s.readOpenAIUpstreamErrorWithCompleteness(resp) + return respBody, upstreamMsg +} + +func (s *OpenAIGatewayService) readOpenAIUpstreamErrorWithCompleteness(resp *http.Response) ([]byte, string, bool) { + limit := openAIUpstreamErrorBodyReadLimitForConfig(nil) + if s != nil { + limit = openAIUpstreamErrorBodyReadLimitForConfig(s.cfg) + } + respBody, readErr := io.ReadAll(io.LimitReader(resp.Body, limit+1)) + complete := readErr == nil && int64(len(respBody)) <= limit + if int64(len(respBody)) > limit { + respBody = respBody[:limit] + } _ = resp.Body.Close() resp.Body = io.NopCloser(bytes.NewReader(respBody)) upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) - return respBody, upstreamMsg + return respBody, upstreamMsg, complete } // failoverOpenAIUpstreamHTTPError 对 >=400 的上游响应做 failover 判定:命中时 diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 54b5dd67d..8d6c99266 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -7,6 +7,8 @@ import ( "errors" "fmt" "net/http" + "regexp" + "strconv" "strings" "sync/atomic" "time" @@ -229,7 +231,7 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( // Normal path: convert Chat Completions → Responses. // ChatCompletionsToResponses always sets Stream=true (upstream always streams). chatReq.Model = upstreamModel - responsesReq, err = apicompat.ChatCompletionsToResponses(&chatReq) + responsesReq, err = chatCompletionsToResponses(s.cfg, &chatReq) if err != nil { return nil, fmt.Errorf("convert chat completions to responses: %w", err) } @@ -370,7 +372,7 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( // 8. Handle error response with failover if resp.StatusCode >= 400 { - respBody, upstreamMsg := s.readOpenAIUpstreamError(resp) + respBody, upstreamMsg, completeErrorBody := s.readOpenAIUpstreamErrorWithCompleteness(resp) if !agentIdentityTaskRecoveryWasTried(ctx) && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) { expectedTaskID := account.GetCredential("task_id") if err := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); err != nil { @@ -387,7 +389,24 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( zap.Int("upstream_status", resp.StatusCode), zap.String("upstream_message", upstreamMsg), ) - return s.forwardAsRawChatCompletions(ctx, c, account, body, defaultMappedModel) + return s.forwardAsRawChatCompletionsWithStartTime(ctx, c, account, body, defaultMappedModel, startTime) + } + responsesMode, _ := account.Extra[openai_compat.ExtraKeyResponsesMode].(string) + if account.IsOpenAIApiKey() && + openai_compat.NormalizeResponsesSupportMode(responsesMode) == openai_compat.ResponsesSupportModeAuto && + openai_compat.ResolveResponsesSupport(account.Extra) == openai_compat.ResponsesSupportYes && + !isResponsesShape && + (ctx == nil || ctx.Err() == nil) && + (c.Request == nil || c.Request.Context().Err() == nil) && + !IsResponseCommitted(c) && + !c.Writer.Written() && + completeErrorBody && + isConvertedResponsesInputStringRejection(resp.StatusCode, respBody) { + logger.L().Info("openai chat_completions: structured Responses input rejected, falling back to raw chat completions", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", resp.StatusCode), + ) + return s.forwardAsRawChatCompletionsWithStartTime(ctx, c, account, body, defaultMappedModel, startTime) } if foErr := s.failoverOpenAIUpstreamHTTPError(ctx, c, account, resp, respBody, upstreamMsg, upstreamModel); foErr != nil { return nil, foErr @@ -441,6 +460,155 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( return result, handleErr } +var responsesInputStringValidationError = regexp.MustCompile(`^['"]loc['"]\s*:\s*\(\s*['"]body['"]\s*,\s*['"]input['"]\s*,\s*['"]str['"]\s*\)$`) +var responsesStringValidationMessage = regexp.MustCompile(`^['"]msg['"]\s*:\s*['"]Input should be a valid string['"]$`) +var responsesStringValidationType = regexp.MustCompile(`^['"]type['"]\s*:\s*['"]string_type['"]$`) +var responsesValidationErrors = regexp.MustCompile(`(?s)^([1-9][0-9]*) validation errors?(?: for [^\r\n:]+)?:\s*(\[.*\])$`) +var responsesInvalidInputTypeMessage = regexp.MustCompile(`(?i)^(?:Invalid type for ['"]input['"]:\s*)?Expected a string(?: for input)?, but got an (?:array|object) instead\.?$`) + +func isResponsesInputStringValidationMessage(message string) bool { + match := responsesValidationErrors.FindStringSubmatch(strings.TrimSpace(message)) + if match == nil { + return false + } + entries, ok := splitResponsesValidationFields(match[2][1 : len(match[2])-1]) + count, err := strconv.Atoi(match[1]) + if !ok || err != nil || count != len(entries) { + return false + } + matched := false + for _, entry := range entries { + if !strings.HasPrefix(entry, "{") || !strings.HasSuffix(entry, "}") { + return false + } + fields, ok := splitResponsesValidationFields(entry[1 : len(entry)-1]) + if !ok { + return false + } + location, message, stringType := false, false, false + keys := make(map[string]bool, len(fields)) + for _, field := range fields { + key, value, found := strings.Cut(field, ":") + key = strings.TrimSpace(key) + if !found || len(key) < 3 || (key[0] != '\'' && key[0] != '"') || key[len(key)-1] != key[0] || strings.TrimSpace(value) == "" || keys[key[1:len(key)-1]] { + return false + } + keys[key[1:len(key)-1]] = true + location = location || responsesInputStringValidationError.MatchString(field) + message = message || responsesStringValidationMessage.MatchString(field) + stringType = stringType || responsesStringValidationType.MatchString(field) + } + matched = matched || (location && message && stringType) + } + return matched +} + +func splitResponsesValidationFields(value string) ([]string, bool) { + var fields []string + var brackets []byte + var quote byte + escaped := false + start := 0 + for index := 0; index < len(value); index++ { + character := value[index] + if quote != 0 { + if escaped { + escaped = false + } else if character == '\\' { + escaped = true + } else if character == quote { + quote = 0 + } + continue + } + switch character { + case '\'', '"': + quote = character + case '{', '[', '(': + brackets = append(brackets, character) + case '}', ']', ')': + if len(brackets) == 0 { + return nil, false + } + opening := brackets[len(brackets)-1] + if (character == '}' && opening != '{') || (character == ']' && opening != '[') || (character == ')' && opening != '(') { + return nil, false + } + brackets = brackets[:len(brackets)-1] + case ',': + if len(brackets) == 0 { + field := strings.TrimSpace(value[start:index]) + if field == "" { + return nil, false + } + fields = append(fields, field) + start = index + 1 + } + } + } + if quote != 0 || len(brackets) != 0 { + return nil, false + } + if field := strings.TrimSpace(value[start:]); field != "" { + fields = append(fields, field) + } + return fields, len(fields) > 0 +} + +func isConvertedResponsesInputStringRejection(status int, responseBody []byte) bool { + if status != http.StatusBadRequest || !json.Valid(responseBody) { + return false + } + envelope := gjson.ParseBytes(responseBody) + for _, object := range []gjson.Result{envelope, envelope.Get("error")} { + if !object.IsObject() { + return false + } + keys := make(map[string]bool) + unambiguous := true + object.ForEach(func(key, value gjson.Result) bool { + name := key.String() + if keys[name] { + unambiguous = false + return false + } + keys[name] = true + switch name { + case "usage", "output", "output_text", "choices", "tool_calls", "response", "status", "incomplete_details": + unambiguous = false + case "code": + code := strings.ToLower(strings.TrimSpace(value.String())) + unambiguous = code == "" || code == "invalid_type" || code == "invalid_request_error" + case "param": + param := strings.ToLower(strings.TrimSpace(value.String())) + unambiguous = param == "" || param == "input" + case "type": + errorType := strings.ToLower(strings.TrimSpace(value.String())) + unambiguous = errorType == "" || errorType == "invalid_type" || errorType == "invalid_request_error" + } + return unambiguous + }) + if !unambiguous { + return false + } + } + message := gjson.GetBytes(responseBody, "error.message").String() + if isResponsesInputStringValidationMessage(message) { + return true + } + code := strings.ToLower(strings.TrimSpace(gjson.GetBytes(responseBody, "error.code").String())) + typ := strings.ToLower(strings.TrimSpace(gjson.GetBytes(responseBody, "error.type").String())) + if code != "invalid_type" && typ != "invalid_type" { + return false + } + param := strings.ToLower(strings.TrimSpace(gjson.GetBytes(responseBody, "error.param").String())) + if param != "input" { + return false + } + message = strings.ToLower(strings.TrimSpace(message)) + return responsesInvalidInputTypeMessage.MatchString(message) +} + func normalizeResponsesRequestServiceTier(req *apicompat.ResponsesRequest) { if req == nil { return diff --git a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go index df2884807..3ebac0add 100644 --- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go +++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go @@ -57,7 +57,7 @@ func (s *OpenAIGatewayService) forwardChatCompletionsViaNativeAnthropic( clientStream := ccReq.Stream // 2. Convert CC → Responses → Anthropic (chained conversion) - responsesReq, err := apicompat.ChatCompletionsToResponses(&ccReq) + responsesReq, err := chatCompletionsToResponses(s.cfg, &ccReq) if err != nil { writeChatCompletionsError(c, http.StatusBadRequest, "invalid_request_error", "Failed to convert request") return nil, fmt.Errorf("convert chat completions to responses: %w", err) diff --git a/backend/internal/service/openai_gateway_chat_completions_raw.go b/backend/internal/service/openai_gateway_chat_completions_raw.go index 4a45a3e37..a97f800bb 100644 --- a/backend/internal/service/openai_gateway_chat_completions_raw.go +++ b/backend/internal/service/openai_gateway_chat_completions_raw.go @@ -61,7 +61,17 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( body []byte, defaultMappedModel string, ) (*OpenAIForwardResult, error) { - startTime := time.Now() + return s.forwardAsRawChatCompletionsWithStartTime(ctx, c, account, body, defaultMappedModel, time.Now()) +} + +func (s *OpenAIGatewayService) forwardAsRawChatCompletionsWithStartTime( + ctx context.Context, + c *gin.Context, + account *Account, + body []byte, + defaultMappedModel string, + startTime time.Time, +) (*OpenAIForwardResult, error) { // 1. Parse minimal fields needed for routing/billing originalModel := gjson.GetBytes(body, "model").String() diff --git a/backend/internal/service/openai_gateway_chat_completions_test.go b/backend/internal/service/openai_gateway_chat_completions_test.go index f16325375..06d149d9d 100644 --- a/backend/internal/service/openai_gateway_chat_completions_test.go +++ b/backend/internal/service/openai_gateway_chat_completions_test.go @@ -3,7 +3,9 @@ package service import ( "bytes" "context" + "encoding/json" "errors" + "fmt" "io" "net/http" "net/http/httptest" @@ -13,6 +15,7 @@ import ( "github.com/MACOS-DO/sub4api/internal/config" "github.com/MACOS-DO/sub4api/internal/pkg/apicompat" + "github.com/MACOS-DO/sub4api/internal/pkg/openai_compat" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" @@ -32,6 +35,546 @@ func (w *openAIChatFailingWriter) Write(p []byte) (int, error) { return w.ResponseWriter.Write(p) } +func TestForwardAsChatCompletions_ResponsesSupportedFallsBackWhenStructuredInputRequiresString(t *testing.T) { + for name, rejection := range map[string]string{ + "OpenAI invalid type": `{"error":{"type":"invalid_request_error","code":"invalid_type","param":"input","message":"Invalid type for 'input': expected a string, but got an array instead."}}`, + "vLLM validation": `{"error":{"message":"1 validation error: [{'type':'string_type', 'loc':('body','input','str'), 'msg':'Input should be a valid string', 'input':[{'role':'user','content':'hi'}, {'role':'assistant','content':[{'type':'output_text'}]}, ResponseFunctionToolCall(type='function_call'), {'type':'function_call_output'}]}]"}}`, + } { + t.Run(name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":[{"type":"text","text":"checking"},{"type":"thinking","thinking":"think"}],"tool_calls":[{"id":"call_1","type":"function","function":{"name":"lookup","arguments":"{}"}}]},{"role":"tool","tool_call_id":"call_1","content":"done"},{"role":"user","content":"what now"}],"stream":false}`) + originalBody := append([]byte(nil), body...) + logs, releaseLogs := captureStructuredLog(t) + defer releaseLogs() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + { + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader( + rejection, + )), + }, + { + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}, "x-request-id": []string{"rid_raw_fallback"}}, + Body: io.NopCloser(strings.NewReader( + `{"id":"chatcmpl_fallback","object":"chat.completion","model":"gpt-5.4","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`, + )), + }, + }} + svc := &OpenAIGatewayService{ + cfg: structuredInputRetryTestConfig(), + httpUpstream: upstream, + } + account := structuredInputRetryTestAccount() + + result, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + require.NoError(t, err) + require.NotNil(t, result) + require.Len(t, upstream.requests, 2) + require.Equal(t, "/v1/responses", upstream.requests[0].URL.Path) + require.True(t, gjson.GetBytes(upstream.bodies[0], "input").IsArray()) + require.Equal(t, "/v1/chat/completions", upstream.requests[1].URL.Path) + require.JSONEq(t, string(body), string(upstream.bodies[1])) + require.Equal(t, originalBody, body) + require.Equal(t, "/v1/chat/completions", result.UpstreamEndpoint) + require.Equal(t, "/v1/chat/completions", GetActualOpenAIUpstreamEndpoint(c)) + require.Equal(t, "ok", gjson.Get(rec.Body.String(), "choices.0.message.content").String()) + require.True(t, logs.ContainsMessage("structured Responses input rejected")) + logs.mu.Lock() + defer logs.mu.Unlock() + for _, event := range logs.events { + require.NotContains(t, event.Fields, "upstream_message") + require.NotContains(t, event.Fields, "upstream_body") + require.NotContains(t, event.Message, rejection) + } + }) + } +} + +type openAIChatFallbackBoundaryReader struct { + io.Reader + beforeRead func() +} + +func (reader *openAIChatFallbackBoundaryReader) Read(buffer []byte) (int, error) { + if reader.beforeRead != nil { + reader.beforeRead() + reader.beforeRead = nil + } + return reader.Reader.Read(buffer) +} + +func TestForwardAsChatCompletions_StructuredInputRetrySafetyBoundaries(t *testing.T) { + rejection := `{"error":{"code":"invalid_type","param":"input","message":"Expected a string, but got an array instead."}}` + validation := `"message":"1 validation error: [{'type':'string_type','loc':('body','input','str'),'msg':'Input should be a valid string'}]"` + for _, test := range []struct { + name string + body string + }{ + {name: "duplicate error", body: strings.TrimSuffix(rejection, "}") + `,"error":{"code":"rate_limit_exceeded"}}`}, + {name: "duplicate code", body: strings.Replace(rejection, `"code":"invalid_type"`, `"code":"invalid_type","code":"rate_limit_exceeded"`, 1)}, + {name: "duplicate escaped param", body: strings.Replace(rejection, `"param":"input"`, `"param":"input","p\u0061ram":"tools"`, 1)}, + {name: "duplicate message", body: strings.Replace(rejection, `"message":"Expected a string, but got an array instead."`, `"message":"Expected a string, but got an array instead.","message":"Input is too long."`, 1)}, + {name: "contradictory error type", body: strings.Replace(rejection, `"error":{`, `"error":{"type":"authentication_error",`, 1)}, + {name: "contradictory envelope type", body: strings.TrimSuffix(rejection, "}") + `,"type":"rate_limit_error"}`}, + {name: "validation contradictory type", body: `{"error":{"type":"rate_limit_error",` + validation + `}}`}, + {name: "validation contradictory envelope type", body: `{"type":"authentication_error","error":{` + validation + `}}`}, + {name: "validation contradictory code", body: `{"error":{"code":"rate_limit_exceeded",` + validation + `}}`}, + {name: "validation contradictory param", body: `{"error":{"param":"tools",` + validation + `}}`}, + {name: "contradictory envelope code", body: strings.TrimSuffix(rejection, "}") + `,"code":"rate_limit_exceeded"}`}, + {name: "contradictory envelope param", body: strings.TrimSuffix(rejection, "}") + `,"param":"tools"}`}, + {name: "type cannot override code", body: strings.Replace(rejection, `"code":"invalid_type"`, `"code":"rate_limit_exceeded","type":"invalid_type"`, 1)}, + {name: "usage", body: strings.TrimSuffix(rejection, "}") + `,"usage":{"input_tokens":12,"output_tokens":3}}`}, + {name: "error usage", body: strings.Replace(rejection, `"error":{`, `"error":{"usage":{"input_tokens":12},`, 1)}, + {name: "output", body: strings.TrimSuffix(rejection, "}") + `,"output":[{"type":"message","content":[{"type":"output_text","text":"partial"}]}]}`}, + {name: "output text", body: strings.TrimSuffix(rejection, "}") + `,"output_text":"partial"}`}, + {name: "tool calls", body: strings.TrimSuffix(rejection, "}") + `,"tool_calls":[{"id":"call_partial","type":"function","function":{"name":"lookup","arguments":"{}"}}]}`}, + {name: "choices", body: strings.TrimSuffix(rejection, "}") + `,"choices":[{"delta":{"content":"partial"}}]}`}, + {name: "nested response", body: strings.TrimSuffix(rejection, "}") + `,"response":{"status":"incomplete","usage":{"input_tokens":12},"output":[]}}`}, + {name: "partial status", body: strings.TrimSuffix(rejection, "}") + `,"status":"in_progress"}`}, + {name: "incomplete details", body: strings.TrimSuffix(rejection, "}") + `,"incomplete_details":{"reason":"max_output_tokens"}}`}, + {name: "partial event", body: strings.TrimSuffix(rejection, "}") + `,"type":"response.output_text.delta","delta":"partial"}`}, + {name: "caller canceled"}, + {name: "request canceled"}, + {name: "response committed"}, + {name: "writer committed"}, + } { + t.Run(test.name, func(t *testing.T) { + body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"}],"stream":false}`) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + requestCtx, cancelRequest := context.WithCancel(context.Background()) + defer cancelRequest() + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)).WithContext(requestCtx) + errorBody := test.body + if errorBody == "" { + errorBody = rejection + } + reader := &openAIChatFallbackBoundaryReader{Reader: strings.NewReader(errorBody), beforeRead: func() { + switch test.name { + case "caller canceled": + cancel() + case "request canceled": + cancelRequest() + case "response committed": + MarkResponseCommitted(c) + case "writer committed": + c.Writer.WriteHeaderNow() + } + }} + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(reader), + }} + svc := &OpenAIGatewayService{cfg: structuredInputRetryTestConfig(), httpUpstream: upstream} + result, err := svc.ForwardAsChatCompletions(ctx, c, structuredInputRetryTestAccount(), body, "", "") + require.Error(t, err) + require.Nil(t, result) + require.Len(t, upstream.requests, 1) + require.Equal(t, "/v1/responses", upstream.requests[0].URL.Path) + }) + } +} + +func TestConvertedResponsesInputStringRejectionIsNarrow(t *testing.T) { + matching := []byte(`{"error":{"code":"invalid_type","param":"input","message":"Expected a string for input, but got an object instead."}}`) + require.True(t, isConvertedResponsesInputStringRejection(http.StatusBadRequest, matching)) + require.True(t, isConvertedResponsesInputStringRejection(http.StatusBadRequest, []byte(`{"error":{"type":"invalid_type","param":"input","message":"Invalid type for 'input': expected a string, but got an array instead."}}`))) + + for _, tc := range []struct { + name string + status int + body string + }{ + {name: "nested content validation", status: http.StatusBadRequest, body: `{"error":{"message":"'loc':('body','input',0,'content','str'), 'msg':'Input should be a valid string'"}}`}, + {name: "other field validation", status: http.StatusBadRequest, body: `{"error":{"message":"'loc':('body','model','str'), 'msg':'Input should be a valid string'"}}`}, + {name: "generic string validation", status: http.StatusBadRequest, body: `{"error":{"message":"Input should be a valid string"}}`}, + {name: "wrong status", status: http.StatusUnprocessableEntity, body: string(matching)}, + {name: "authentication", status: http.StatusUnauthorized, body: string(matching)}, + {name: "authorization", status: http.StatusForbidden, body: string(matching)}, + {name: "rate limit", status: http.StatusTooManyRequests, body: string(matching)}, + {name: "server error", status: http.StatusInternalServerError, body: string(matching)}, + {name: "wrong parameter", status: http.StatusBadRequest, body: `{"error":{"code":"invalid_type","param":"tools","message":"Expected a string, but got an array instead."}}`}, + {name: "wrong code", status: http.StatusBadRequest, body: `{"error":{"code":"invalid_request_error","param":"input","message":"Expected a string, but got an array instead."}}`}, + {name: "unrelated input error", status: http.StatusBadRequest, body: `{"error":{"code":"invalid_type","param":"input","message":"Input is too long."}}`}, + } { + t.Run(tc.name, func(t *testing.T) { + require.False(t, isConvertedResponsesInputStringRejection(tc.status, []byte(tc.body))) + }) + } +} + +func TestConvertedResponsesInputStringRejectionValidationBoundaries(t *testing.T) { + validation := `{'type': 'string_type', 'loc': ('body', 'input', 'str'), 'msg': 'Input should be a valid string', 'input': [{'role': 'user', 'content': 'hello'}]}` + for _, test := range []struct { + name string + message string + want bool + }{ + {name: "complete Pydantic error", message: "1 validation error: [" + validation + "]", want: true}, + {name: "multiple Pydantic errors", message: "2 validation errors for Request: [" + strings.Replace(validation, "'input', 'str'", "'model', 'str'", 1) + ", " + validation + "]", want: true}, + {name: "double quoted keys", message: "1 validation error: [" + strings.ReplaceAll(validation, "'", `"`) + "]", want: true}, + {name: "surrounding whitespace", message: " \n1 validation error: [" + validation + "]\n ", want: true}, + {name: "escaped quote in history", message: `1 validation error: [{'type':'string_type','loc':('body','input','str'),'msg':'Input should be a valid string','input':[{'content':'can\'t [close] this }'}]}]`, want: true}, + {name: "bare loc and msg", message: `'loc':('body','input','str'), 'msg':'Input should be a valid string'`}, + {name: "echoed dictionary in unrelated error", message: "Invalid history: " + validation}, + {name: "echoed fake loc and msg in input", message: `1 validation error: [{'type':'string_type','loc':('body','model','str'),'msg':'Input should be a valid string','input':{'loc':('body','input','str'),'msg':'Input should be a valid string'}}]`}, + {name: "echoed fake loc and msg in quoted history", message: `1 validation error: [{'type':'string_type','loc':('body','input',0,'content','str'),'msg':'Input should be a valid string','input':"'loc':('body','input','str'), 'msg':'Input should be a valid string'"}]`}, + {name: "echoed complete error in quoted history", message: `1 validation error: [{'type':'string_type','loc':('body','model','str'),'msg':'Input should be a valid string','input':"1 validation error: [{'type':'string_type','loc':('body','input','str'),'msg':'Input should be a valid string'}]"}]`}, + {name: "truncated error list", message: "1 validation error: [" + validation}, + {name: "truncated quoted input", message: `1 validation error: [{'type':'string_type','loc':('body','input','str'),'msg':'Input should be a valid string','input':'history}]`}, + {name: "mismatched closing bracket", message: "1 validation error: [" + strings.TrimSuffix(validation, "}") + ")]"}, + {name: "elided validation list", message: "240 validation errors: ... " + validation}, + {name: "incorrect error count", message: "2 validation errors: [" + validation + "]"}, + {name: "overflowed error count", message: "999999999999999999999999 validation errors: [" + validation + "]"}, + {name: "duplicate location", message: "1 validation error: [" + strings.Replace(validation, "'input':", "'loc': ('body', 'model', 'str'), 'input':", 1) + "]"}, + {name: "wrong validation type", message: "1 validation error: [" + strings.Replace(validation, "string_type", "value_error", 1) + "]"}, + {name: "missing validation type", message: "1 validation error: [" + strings.Replace(validation, "'type': 'string_type', ", "", 1) + "]"}, + {name: "location and message in different errors", message: "2 validation errors: [" + strings.Replace(validation, "Input should be a valid string", "Invalid history", 1) + ", " + strings.Replace(validation, "'input', 'str'", "'model', 'str'", 1) + "]"}, + {name: "trailing echoed text", message: "1 validation error: [" + validation + "] echoed history"}, + {name: "structured string array", message: "Expected a string, but got an array instead.", want: true}, + {name: "structured object", message: "Invalid type for 'input': expected a string, but got an object instead.", want: true}, + {name: "structured echoed history", message: "Invalid history containing 'expected a string' and 'got an array'"}, + {name: "structured truncated message", message: "Expected a string, but got an array"}, + } { + t.Run(test.name, func(t *testing.T) { + body, err := json.Marshal(map[string]any{"error": map[string]string{"message": test.message, "code": "invalid_type", "param": "input"}}) + require.NoError(t, err) + require.Equal(t, test.want, isConvertedResponsesInputStringRejection(http.StatusBadRequest, body)) + if test.want { + require.False(t, isConvertedResponsesInputStringRejection(http.StatusBadRequest, body[:len(body)-1])) + require.False(t, isConvertedResponsesInputStringRejection(http.StatusBadRequest, append(body, []byte(" trailing")...))) + } + }) + } +} + +func TestForwardAsChatCompletions_StructuredInputRetryRequiresCompleteErrorBody(t *testing.T) { + rejection := `{"error":{"code":"invalid_type","param":"input","message":"Expected a string, but got an array instead."}}` + limit := int(openAIUpstreamErrorBodyReadLimitForConfig(structuredInputRetryTestConfig())) + for _, test := range []struct { + name string + payload string + readErr error + unknown bool + want bool + }{ + {name: "complete JSON followed by read failure", payload: rejection, readErr: io.ErrUnexpectedEOF}, + {name: "truncated JSON", payload: rejection[:len(rejection)-1]}, + {name: "exact read limit", payload: rejection + strings.Repeat(" ", limit-len(rejection)), want: true}, + {name: "one byte beyond read limit", payload: rejection + strings.Repeat(" ", limit-len(rejection)+1)}, + {name: "valid JSON prefix before discarded suffix", payload: rejection + strings.Repeat(" ", limit-len(rejection)) + "trailing"}, + {name: "unknown capability still retries after read failure", payload: rejection, readErr: io.ErrUnexpectedEOF, unknown: true, want: true}, + {name: "unknown capability still retries beyond read limit", payload: rejection + strings.Repeat(" ", limit-len(rejection)+1), unknown: true, want: true}, + } { + t.Run(test.name, func(t *testing.T) { + body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"}]}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + errorBody := io.NopCloser(strings.NewReader(test.payload)) + if test.readErr != nil { + errorBody = &openAIChatStreamReadErrorCloser{payload: []byte(test.payload), err: test.readErr} + } + account := structuredInputRetryTestAccount() + status := http.StatusBadRequest + if test.unknown { + delete(account.Extra, openai_compat.ExtraKeyResponsesSupported) + status = http.StatusNotFound + } + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + {StatusCode: status, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: errorBody}, + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"id":"chatcmpl_retry","choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`))}, + }} + svc := &OpenAIGatewayService{cfg: structuredInputRetryTestConfig(), httpUpstream: upstream} + result, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + if test.want { + require.NoError(t, err) + require.NotNil(t, result) + require.Len(t, upstream.requests, 2) + } else { + require.Error(t, err) + require.Nil(t, result) + require.Len(t, upstream.requests, 1) + } + }) + } +} + +type openAIChatFallbackDelayReader struct { + io.Reader + elapsed time.Duration +} + +func (reader *openAIChatFallbackDelayReader) Read(buffer []byte) (int, error) { + if reader.elapsed == 0 { + started := time.Now() + time.Sleep(30 * time.Millisecond) + reader.elapsed = time.Since(started) + } + return reader.Reader.Read(buffer) +} + +func TestForwardAsChatCompletions_RawFallbackPreservesResponsesTiming(t *testing.T) { + for _, unknown := range []bool{false, true} { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("unknown=%t/stream=%t", unknown, stream), func(t *testing.T) { + body := []byte(fmt.Sprintf(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"}],"stream":%t}`, stream)) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + account := structuredInputRetryTestAccount() + status := http.StatusBadRequest + if unknown { + delete(account.Extra, openai_compat.ExtraKeyResponsesSupported) + status = http.StatusNotFound + } + initialBody := &openAIChatFallbackDelayReader{Reader: strings.NewReader(`{"error":{"code":"invalid_type","param":"input","message":"Expected a string, but got an array instead."}}`)} + responseBody := `{"id":"chatcmpl_retry","choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}` + contentType := "application/json" + if stream { + responseBody = "data: {\"id\":\"chatcmpl_retry\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\ndata: {\"choices\":[],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":1,\"total_tokens\":2}}\n\ndata: [DONE]\n\n" + contentType = "text/event-stream" + } + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + {StatusCode: status, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(initialBody)}, + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(responseBody))}, + }} + svc := &OpenAIGatewayService{cfg: structuredInputRetryTestConfig(), httpUpstream: upstream} + result, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + require.NoError(t, err) + require.NotNil(t, result) + require.Len(t, upstream.requests, 2) + require.Equal(t, "/v1/responses", upstream.requests[0].URL.Path) + require.Equal(t, "/v1/chat/completions", upstream.requests[1].URL.Path) + require.GreaterOrEqual(t, result.Duration, initialBody.elapsed) + if stream { + require.NotNil(t, result.FirstTokenMs) + require.GreaterOrEqual(t, *result.FirstTokenMs, int(initialBody.elapsed.Milliseconds())) + } + }) + } + } +} + +func TestForwardAsChatCompletions_StructuredInputRejectionDoesNotRetryIneligibleRequests(t *testing.T) { + rejection := `{"error":{"code":"invalid_type","param":"input","message":"Expected a string, but got an array instead."}}` + for _, test := range []struct { + name string + mode string + unknown bool + platform string + protocol string + endpoint string + accountType string + responsesBody bool + nativeIngress bool + status int + rejection string + }{ + {name: "forced Responses", mode: "force_responses"}, + {name: "forced Responses without probe", mode: "force_responses", unknown: true}, + {name: "unknown support", unknown: true}, + {name: "Responses shaped Chat ingress", responsesBody: true}, + {name: "native Responses ingress", responsesBody: true, nativeIngress: true}, + {name: "native CN Responses protocol", platform: PlatformDeepseek}, + {name: "adaptive Chat ingress stays raw", platform: PlatformKimi, protocol: APIProtocolAdaptive, endpoint: "/chat/completions"}, + {name: "adaptive Responses shaped ingress stays Responses", platform: PlatformKimi, protocol: APIProtocolAdaptive, responsesBody: true}, + {name: "adaptive Responses shaped ingress converts to Chat", platform: PlatformZhipu, protocol: APIProtocolAdaptive, responsesBody: true, endpoint: "/chat/completions"}, + {name: "model routed Responses is not OpenAI retry eligible", platform: PlatformCommandCode, protocol: APIProtocolResponses}, + {name: "OAuth", accountType: AccountTypeOAuth}, + {name: "authentication", status: http.StatusUnauthorized}, + {name: "authorization", status: http.StatusForbidden}, + {name: "rate limit", status: http.StatusTooManyRequests}, + {name: "unrelated validation", rejection: `{"error":{"code":"invalid_type","param":"tools","message":"Expected a string, but got an array instead."}}`}, + {name: "nested validation", rejection: `{"error":{"message":"'loc':('body','input',0,'content','str'), 'msg':'Input should be a valid string'"}}`}, + {name: "echoed validation", rejection: `{"error":{"message":"1 validation error: [{'type':'string_type','loc':('body','model','str'),'msg':'Input should be a valid string','input':{'loc':('body','input','str'),'msg':'Input should be a valid string'}}]"}}`}, + {name: "echoed structured error", rejection: `{"error":{"code":"invalid_type","param":"input","message":"Invalid history containing expected a string but got an array"}}`}, + } { + t.Run(test.name, func(t *testing.T) { + body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"}],"stream":false}`) + if test.responsesBody { + body = []byte(`{"model":"gpt-5.4","input":[{"role":"user","content":"hello"}],"stream":false}`) + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + account := structuredInputRetryTestAccount() + account.Extra = map[string]any{openai_compat.ExtraKeyResponsesSupported: true, openai_compat.ExtraKeyResponsesMode: test.mode} + if test.unknown { + delete(account.Extra, openai_compat.ExtraKeyResponsesSupported) + } + if test.platform != "" { + account.Platform = test.platform + account.Credentials["api_protocol"] = APIProtocolResponses + } + if test.protocol != "" { + account.Credentials["api_protocol"] = test.protocol + } + if test.accountType != "" { + account.Type = test.accountType + account.Credentials["access_token"] = "test-token" + } + status := test.status + if status == 0 { + status = http.StatusBadRequest + } + errorBody := rejection + if test.rejection != "" { + errorBody = test.rejection + } + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(errorBody)), + }} + svc := &OpenAIGatewayService{cfg: structuredInputRetryTestConfig(), httpUpstream: upstream} + var result *OpenAIForwardResult + var err error + if test.nativeIngress { + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + result, err = svc.Forward(context.Background(), c, account, body) + } else { + result, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + } + require.Error(t, err) + require.Nil(t, result) + require.Len(t, upstream.requests, 1) + endpoint := test.endpoint + if endpoint == "" { + endpoint = "/responses" + } + require.True(t, strings.HasSuffix(upstream.requests[0].URL.Path, endpoint)) + var failover *UpstreamFailoverError + if status == http.StatusUnauthorized || status == http.StatusForbidden || status == http.StatusTooManyRequests { + require.ErrorAs(t, err, &failover) + require.Equal(t, status, failover.StatusCode) + } else { + require.False(t, errors.As(err, &failover)) + require.True(t, c.Writer.Written()) + } + }) + } +} + +func TestForwardAsChatCompletions_StructuredInputRetryPreservesStreamingAndMapping(t *testing.T) { + for _, useAccountMapping := range []bool{false, true} { + t.Run(fmt.Sprintf("account_mapping=%t", useAccountMapping), func(t *testing.T) { + body := []byte(`{"model":"client-model","messages":[{"role":"user","content":"hello"}],"stream":true,"stream_options":{"include_usage":false},"vendor_option":"preserve"}`) + originalBody := append([]byte(nil), body...) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + account := structuredInputRetryTestAccount() + account.Extra = map[string]any{openai_compat.ExtraKeyResponsesSupported: true, openai_compat.ExtraKeyResponsesMode: "auto"} + mappedModel := "gpt-5.4" + if useAccountMapping { + account.Credentials["model_mapping"] = map[string]any{"client-model": mappedModel} + } + stream := "data: {\"id\":\"chatcmpl_retry\",\"object\":\"chat.completion.chunk\",\"model\":\"gpt-5.4\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\ndata: {\"choices\":[],\"usage\":{\"prompt_tokens\":9,\"completion_tokens\":4,\"total_tokens\":13}}\n\ndata: [DONE]\n\n" + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + {StatusCode: http.StatusBadRequest, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_type","param":"input","message":"Expected a string, but got an array instead."}}`))}, + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(stream))}, + }} + svc := &OpenAIGatewayService{cfg: structuredInputRetryTestConfig(), httpUpstream: upstream} + defaultMappedModel := mappedModel + if useAccountMapping { + defaultMappedModel = "" + } + result, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", defaultMappedModel) + require.NoError(t, err) + require.Len(t, upstream.requests, 2) + for _, outbound := range upstream.bodies { + require.Equal(t, mappedModel, gjson.GetBytes(outbound, "model").String()) + require.True(t, gjson.GetBytes(outbound, "stream").Bool()) + } + require.JSONEq(t, gjson.GetBytes(body, "messages").Raw, gjson.GetBytes(upstream.bodies[1], "messages").Raw) + require.Equal(t, "preserve", gjson.GetBytes(upstream.bodies[1], "vendor_option").String()) + require.True(t, gjson.GetBytes(upstream.bodies[1], "stream_options.include_usage").Bool()) + require.Equal(t, originalBody, body) + require.True(t, result.Stream) + require.Equal(t, mappedModel, result.BillingModel) + require.Equal(t, mappedModel, result.UpstreamModel) + require.Equal(t, 9, result.Usage.InputTokens) + require.Equal(t, 4, result.Usage.OutputTokens) + require.Equal(t, "/v1/chat/completions", result.UpstreamEndpoint) + require.Contains(t, rec.Header().Get("Content-Type"), "text/event-stream") + require.Contains(t, rec.Body.String(), "data: [DONE]") + }) + } +} + +func TestForwardAsChatCompletions_StructuredInputRetryIsBoundedAndPreservesRawErrors(t *testing.T) { + for _, status := range []int{http.StatusBadRequest, http.StatusUnauthorized, http.StatusTooManyRequests} { + t.Run(fmt.Sprintf("status=%d", status), func(t *testing.T) { + rejection := `{"error":{"code":"invalid_type","param":"input","message":"Expected a string, but got an array instead."}}` + response := func(status int) *http.Response { + return &http.Response{StatusCode: status, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(rejection))} + } + body := []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"hello"}],"stream":false}`) + account := structuredInputRetryTestAccount() + account.Extra = map[string]any{openai_compat.ExtraKeyResponsesSupported: true} + forward := func(retry bool) (*httptest.ResponseRecorder, error) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + upstream := &httpUpstreamRecorder{responses: []*http.Response{response(status)}} + if retry { + upstream.responses = append([]*http.Response{response(http.StatusBadRequest)}, upstream.responses...) + } + svc := &OpenAIGatewayService{cfg: structuredInputRetryTestConfig(), httpUpstream: upstream} + var result *OpenAIForwardResult + var err error + if retry { + result, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + require.Len(t, upstream.requests, 2) + require.Equal(t, "/v1/chat/completions", upstream.requests[1].URL.Path) + } else { + result, err = svc.forwardAsRawChatCompletions(context.Background(), c, account, body, "") + require.Len(t, upstream.requests, 1) + } + require.Nil(t, result) + require.Error(t, err) + return rec, err + } + baseline, baselineErr := forward(false) + retried, retryErr := forward(true) + require.Equal(t, baseline.Code, retried.Code) + require.Equal(t, baseline.Body.String(), retried.Body.String()) + require.Equal(t, baselineErr.Error(), retryErr.Error()) + require.IsType(t, baselineErr, retryErr) + }) + } +} + +func structuredInputRetryTestConfig() *config.Config { + return &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{ + Enabled: false, + AllowInsecureHTTP: true, + }}} +} + +func structuredInputRetryTestAccount() *Account { + return &Account{ + ID: 101, + Name: "raw-openai-apikey", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test", "base_url": "http://upstream.example"}, + Extra: map[string]any{openai_compat.ExtraKeyResponsesSupported: true}, + } +} + type openAIChatStreamReadErrorCloser struct { payload []byte err error @@ -1322,7 +1865,7 @@ func TestGPT61SolOnlyChatFallbackRejectsToolsAndDisabledReasoning(t *testing.T) svc := &OpenAIGatewayService{cfg: &config.Config{}} var err error if responses { - _, err = svc.forwardResponsesViaRawChatCompletions(context.Background(), c, account, []byte(body)) + _, err = svc.forwardResponsesViaRawChatCompletions(context.Background(), c, account, []byte(body), time.Now()) } else { _, err = svc.forwardAnthropicViaRawChatCompletions(context.Background(), c, account, []byte(body), "") } diff --git a/backend/internal/service/openai_gateway_cn_fixes_test.go b/backend/internal/service/openai_gateway_cn_fixes_test.go index 870f658b5..59d1950b3 100644 --- a/backend/internal/service/openai_gateway_cn_fixes_test.go +++ b/backend/internal/service/openai_gateway_cn_fixes_test.go @@ -74,7 +74,7 @@ func TestCalculateOpenAIRecordUsageCost_EmptyCandidatesIsPricingUnavailable(t *t _, err := svc.calculateOpenAIRecordUsageCost( context.Background(), nil, apiKey, nil, - 1.0, 1.0, 1.0, 1.0, UsageTokens{InputTokens: 100}, "", nil, time.Time{}, + 1.0, 1.0, 1.0, 1.0, UsageTokens{InputTokens: 100}, "", nil, false, time.Time{}, ) require.Error(t, err) require.True(t, isUsagePricingUnavailableError(err), diff --git a/backend/internal/service/openai_gateway_count_tokens.go b/backend/internal/service/openai_gateway_count_tokens.go index c582cd966..9827ca0f6 100644 --- a/backend/internal/service/openai_gateway_count_tokens.go +++ b/backend/internal/service/openai_gateway_count_tokens.go @@ -104,7 +104,7 @@ func (s *OpenAIGatewayService) ForwardResponsesInputTokens( return nil } if s.rateLimitService != nil { - s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody) + s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, prepared.UpstreamModel) } upstreamMsg := sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(respBody))) setOpsUpstreamError(c, resp.StatusCode, upstreamMsg, "") @@ -346,7 +346,7 @@ func (s *OpenAIGatewayService) ForwardCountTokensAsAnthropic( } if s.rateLimitService != nil { - s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody) + s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, prepared.UpstreamModel) } if isOpenAIInputTokensUnsupported(resp.StatusCode, respBody) { diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 751716a6c..0ae99e3ce 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -69,7 +69,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if normalized { body = normalizedBody } - legacyIngressBody, legacyIngressChanged, legacyIngressErr := normalizeOpenAIResponsesLegacyIngress(body) + legacyIngressBody, legacyIngressChanged, legacyIngressErr := normalizeOpenAIResponsesLegacyIngressWithConfig(s.cfg, body) if legacyIngressErr != nil { return nil, legacyIngressErr } @@ -194,7 +194,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco // 账号映射未命中时以去除首尾空白的请求模型兜底,计费名与上游模型名一致。 return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, reqModel) case APIProtocolChatCompletions: - return s.forwardResponsesViaRawChatCompletions(ctx, c, account, body) + return s.forwardResponsesViaRawChatCompletions(ctx, c, account, body, startTime) } SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint) if account.IsOpenAI() && (account.IsOpenAIApiKey() || account.IsOpenAIOAuthLike()) { diff --git a/backend/internal/service/openai_gateway_grok_chat_bridge.go b/backend/internal/service/openai_gateway_grok_chat_bridge.go index 326f06e5b..dfae6bf7a 100644 --- a/backend/internal/service/openai_gateway_grok_chat_bridge.go +++ b/backend/internal/service/openai_gateway_grok_chat_bridge.go @@ -541,7 +541,7 @@ func (s *OpenAIGatewayService) forwardGrokChatCompletionsViaResponses( return s.forwardAsRawChatCompletions(ctx, c, account, body, defaultMappedModel) } - responsesReq, err := apicompat.ChatCompletionsToResponses(&chatReq) + responsesReq, err := chatCompletionsToResponses(s.cfg, &chatReq) if err != nil { return nil, fmt.Errorf("convert grok chat completions to responses: %w", err) } diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 48dc7b328..9b383e379 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -45,6 +45,16 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( rememberOpenCodeInboundBody(c, body) beginUpstreamResponseModelObservation(c) ClearActualOpenAIUpstreamEndpoint(c) + // Web Search 模拟:Chat Completions 转换会丢掉 web_search 工具,纯 web_search + // 请求在此直接调用搜索 API 构造 Anthropic 响应,不访问上游。 + if groupID := getOpenAIGroupIDFromContext(c); shouldEmulateWebSearchFor(ctx, s.settingService, s.channelService, account, &groupID, body) { + stream := gjson.GetBytes(body, "stream").Bool() + res, err := writeEmulatedWebSearch(ctx, c, account, body, gjson.GetBytes(body, "model").String(), stream) + if err != nil { + return nil, err + } + return &OpenAIForwardResult{Model: res.Model, Stream: stream, Duration: res.Duration}, nil + } if shouldForwardOpenAIResponsesViaRawChatCompletions(account) { SetActualOpenAIUpstreamEndpoint(c, "/v1/chat/completions") } @@ -144,7 +154,7 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( // 3. Convert Anthropic → Responses after compatibility-only replay guard. anthropicReq.Model = upstreamModel - responsesReq, err := apicompat.AnthropicToResponses(&anthropicReq) + responsesReq, err := anthropicToResponses(s.cfg, &anthropicReq) if err != nil { return nil, fmt.Errorf("convert anthropic to responses: %w", err) } diff --git a/backend/internal/service/openai_gateway_messages_chat_fallback.go b/backend/internal/service/openai_gateway_messages_chat_fallback.go index 7a0e6279f..3589347d3 100644 --- a/backend/internal/service/openai_gateway_messages_chat_fallback.go +++ b/backend/internal/service/openai_gateway_messages_chat_fallback.go @@ -52,7 +52,10 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions( clientStream := anthropicReq.Stream // 2. Anthropic → Chat Completions (direct, no Responses intermediary) - chatReq, err := apicompat.AnthropicToChatCompletionsRequest(&anthropicReq) + chatReq, err := apicompat.AnthropicToChatCompletionsRequestWithMinOutputTokens( + &anthropicReq, + configuredMinOutputTokens(s.cfg), + ) if err != nil { writeAnthropicError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return nil, fmt.Errorf("convert anthropic to chat completions: %w", err) diff --git a/backend/internal/service/openai_gateway_model_availability.go b/backend/internal/service/openai_gateway_model_availability.go index 861d3e672..e1715bd15 100644 --- a/backend/internal/service/openai_gateway_model_availability.go +++ b/backend/internal/service/openai_gateway_model_availability.go @@ -56,6 +56,9 @@ func (s *OpenAIGatewayService) DiagnoseModelAvailabilityForPlatform( diag := ModelAvailabilityDiagnosis{} for i := range accounts { diag.HasAccountsInPool = true + if isRetiredOpenAISubscriptionModel(&accounts[i], resolveOpenAIAccountUpstreamModelForRequest(&accounts[i], requestedModel, false)) { + diag.HasRetiredSubscriptionModel = true + } // Mirrors the per-candidate filter used during account selection // (openai_account_scheduler.isAccountRequestCompatible): empty // model_mapping accepts everything; otherwise the explicit / wildcard diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 7217f633d..0c90914ec 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -214,6 +214,7 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( if account != nil && account.IsOpenAI() { responsesLite := isOpenAIResponsesLiteHeader(c.GetHeader(responsesLiteHeader)) || isOpenAIResponsesLiteWebSocketPayload(body) normalizedBody, normalized, normalizeErr := normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{ + Config: s.cfg, ResponsesLite: responsesLite, Compact: isOpenAIResponsesCompactPath(c), }) @@ -1905,6 +1906,9 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough( responseFailedPending := false var bareErrorPayload []byte bareErrorAccountSideEffectsPending := false + // Passthrough leaves upstream events untouched; the tracker only learns the + // upstream created_at so a synthesized response.failed matches the stream. + var createdAtTracker responsesCreatedAtStamper upstreamRequestID := strings.TrimSpace(resp.Header.Get("x-request-id")) // pendingLines 在首个可见输出前保留前导事件,确保无输出失败仍可安全 failover。 pendingLines := make([]string, 0, 8) @@ -1979,7 +1983,7 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough( if clientDisconnected || !writePendingLines() { return } - if _, err := fmt.Fprint(w, buildOpenAIResponseFailedSSE(responseID, originalModel, bareErrorPayload, failedMessage)); err != nil { + if _, err := fmt.Fprint(w, buildOpenAIResponseFailedSSE(responseID, originalModel, createdAtTracker.Value(), bareErrorPayload, failedMessage)); err != nil { clientDisconnected = true return } @@ -2054,6 +2058,7 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough( } } eventType := effectiveOpenAISSEEventType(dataBytes, rawEventType) + createdAtTracker.Observe(dataBytes, eventType) if codexFailureTerminal && sawBareError && !sawResponseFailed && eventType != "response.failed" { suppressCurrentEvent = true } diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index cb0173442..89b322461 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -11,6 +11,7 @@ import ( "strings" "unicode/utf8" + "github.com/MACOS-DO/sub4api/internal/config" "github.com/MACOS-DO/sub4api/internal/pkg/apicompat" "github.com/MACOS-DO/sub4api/internal/pkg/ctxkey" "github.com/MACOS-DO/sub4api/internal/util/urlvalidator" @@ -1433,7 +1434,12 @@ func normalizeOpenAIResponsesWebSocketCompatibilityBody(body []byte, account *Ac return normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{ResponsesLite: responsesLite}) } +func normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(cfg *config.Config, body []byte, account *Account, responsesLite bool) ([]byte, bool, error) { + return normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{Config: cfg, ResponsesLite: responsesLite}) +} + type openAIResponsesCompatibilityOptions struct { + Config *config.Config ResponsesLite bool // Compact marks the /responses/compact wire shape, which is left as-is // by request-shape compatibility rewrites such as web_search history. @@ -1449,7 +1455,7 @@ func normalizeOpenAIResponsesCompatibilityBodyWithOptions(body []byte, account * changed := false if account.IsOpenAIOAuthLike() { var err error - normalized, changed, err = normalizeOpenAIResponsesLegacyIngress(body) + normalized, changed, err = normalizeOpenAIResponsesLegacyIngressWithConfig(opts.Config, body) if err != nil { return body, false, err } diff --git a/backend/internal/service/openai_gateway_response_flush_test.go b/backend/internal/service/openai_gateway_response_flush_test.go index 1ce961fff..df221774d 100644 --- a/backend/internal/service/openai_gateway_response_flush_test.go +++ b/backend/internal/service/openai_gateway_response_flush_test.go @@ -371,7 +371,7 @@ func TestOpenAIResponseFlush_KeepaliveDoesNotSplitOpenEvent(t *testing.T) { func TestOpenAIResponseFlush_FailedAndErrorEventsFlushAtBoundaries(t *testing.T) { t.Run("failed at EOF", func(t *testing.T) { body := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"a\"}\n\n" + - "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"code\":\"safety_error\",\"message\":\"blocked\"},\"usage\":{\"input_tokens\":3,\"output_tokens\":1}}}\n" + "data: {\"type\":\"response.failed\",\"response\":{\"created_at\":1700000000,\"error\":{\"code\":\"safety_error\",\"message\":\"blocked\"},\"usage\":{\"input_tokens\":3,\"output_tokens\":1}}}\n" recorder := newOpenAIResponseFlushRecorder() result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}) @@ -381,7 +381,7 @@ func TestOpenAIResponseFlush_FailedAndErrorEventsFlushAtBoundaries(t *testing.T) require.Equal(t, 3, result.usage.InputTokens) gotBody, flushes := recorder.snapshot() expectedBody := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"a\"}\n\n" + - "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"code\":\"safety_error\",\"message\":\"blocked\"}}}\n" + "data: {\"type\":\"response.failed\",\"response\":{\"created_at\":1700000000,\"error\":{\"code\":\"safety_error\",\"message\":\"blocked\"}}}\n" require.Equal(t, expectedBody, gotBody) require.Len(t, flushes, 2) require.Contains(t, flushes[1], "response.failed") @@ -669,7 +669,7 @@ func (r *hangingOpenAISSEAfterTerminal) Close() error { } func TestOpenAIResponseFlush_TerminalEventEndsStreamWithoutEOF(t *testing.T) { - body := "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":7,\"output_tokens\":5}}}\n\n" + body := "data: {\"type\":\"response.completed\",\"response\":{\"created_at\":1700000000,\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":7,\"output_tokens\":5}}}\n\n" reader := &hangingOpenAISSEAfterTerminal{payload: []byte(body), release: make(chan struct{})} recorder := newOpenAIResponseFlushRecorder() resultCh, errCh := runOpenAIResponseFlushTestAsync(recorder, reader, config.GatewayConfig{StreamKeepaliveInterval: 1, StreamDataIntervalTimeout: 30}) diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index c14793611..648638caf 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -341,6 +341,7 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. } needModelReplace := originalModel != mappedModel + var createdAtStamper responsesCreatedAtStamper streamOutputAccumulator := apicompat.NewBufferedResponseAccumulator() streamDoneItems := newResponsesStreamOutputItems() streamImageOutputs := make([]json.RawMessage, 0, 1) @@ -382,7 +383,7 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. } if codexFailureTerminal && sawBareError && !sawResponseFailed && !clientDisconnected { applyAttemptResponseHeaders() - if _, err := writePendingString(buildOpenAIResponseFailedSSE(responseID, originalModel, bareErrorPayload, failedMessage)); err != nil { + if _, err := writePendingString(buildOpenAIResponseFailedSSE(responseID, originalModel, createdAtStamper.Value(), bareErrorPayload, failedMessage)); err != nil { handlePendingWriteError(err) } else { failureDelivered = true @@ -667,6 +668,11 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. data = string(sanitizedData) line = "data: " + data } + if stampedData, stamped := createdAtStamper.Stamp(dataBytes, eventType); stamped { + dataBytes = stampedData + data = string(stampedData) + line = "data: " + data + } // Replace model in response if needed. if needModelReplace { line = s.replaceModelInSSELine(line, mappedModel, originalModel) @@ -1667,6 +1673,7 @@ func (s *OpenAIGatewayService) handleNonStreamingResponse(ctx context.Context, r return nil, fmt.Errorf("restore OpenAI namespace response: %w", err) } body = restoreCodexToolNamesFromContext(c, body) + body = ensureOpenAIResponseObjectCreatedAt(body) responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter) // Codex 协议要求 /responses/compact JSON 响应携带 x-codex-turn-state // (codex-api/src/endpoint/compact.rs 从响应头捕获),显式回传。 @@ -1767,7 +1774,7 @@ func (s *OpenAIGatewayService) handleSSEToJSON(resp *http.Response, c *gin.Conte return nil, fmt.Errorf("restore OpenAI namespace response: %w", restoreErr) } restoredBody = restoreCodexToolNamesFromContext(c, restoredBody) - body = restoredBody + body = ensureOpenAIResponseObjectCreatedAt(restoredBody) } else { if originalModel != mappedModel { bodyText = s.replaceModelInSSEBody(bodyText, mappedModel, originalModel) @@ -1828,7 +1835,10 @@ func extractOpenAISSEErrorMessage(payload []byte) string { return sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(payload))) } -func buildOpenAIResponseFailedSSE(responseID, model string, source []byte, fallbackMessage string) string { +// buildOpenAIResponseFailedSSE synthesizes the response.failed terminal for a +// stream that ended on a bare error. created_at and sequence_number are always +// written: strict clients (grok-build, Codex) reject the frame without them. +func buildOpenAIResponseFailedSSE(responseID, model string, createdAt int64, source []byte, fallbackMessage string) string { responseID = strings.TrimSpace(responseID) if responseID == "" { responseID = "resp_" + strings.ReplaceAll(uuid.NewString(), "-", "") @@ -1855,23 +1865,31 @@ func buildOpenAIResponseFailedSSE(responseID, model string, source []byte, fallb if errorType != "" { errorBody["type"] = errorType } + if createdAt <= 0 { + createdAt = time.Now().Unix() + } + sequenceNumber := openAIResponsesFailedSequenceNumber(source) response := gin.H{ - "id": responseID, - "object": "response", - "status": "failed", - "output": []any{}, - "error": errorBody, + "id": responseID, + "object": "response", + "created_at": createdAt, + "status": "failed", + "output": []any{}, + "error": errorBody, } if model = strings.TrimSpace(model); model != "" { response["model"] = model } payload, err := marshalOpenAIUpstreamJSON(gin.H{ - "type": "response.failed", - "response": response, + "type": "response.failed", + "sequence_number": sequenceNumber, + "response": response, }) if err != nil { // All values above are JSON primitives, so this is only a defensive fallback. - payload = []byte(`{"type":"response.failed","response":{"status":"failed","output":[],"error":{"code":"upstream_error","message":"Upstream response failed"}}}`) + payload = []byte(`{"type":"response.failed","sequence_number":` + strconv.FormatInt(sequenceNumber, 10) + + `,"response":{"object":"response","created_at":` + strconv.FormatInt(createdAt, 10) + + `,"status":"failed","output":[],"error":{"code":"upstream_error","message":"Upstream response failed"}}}`) } return "event: response.failed\ndata: " + string(payload) + "\n\n" } diff --git a/backend/internal/service/openai_gateway_responses_chat_fallback.go b/backend/internal/service/openai_gateway_responses_chat_fallback.go index 60f701ee4..b1275ea4c 100644 --- a/backend/internal/service/openai_gateway_responses_chat_fallback.go +++ b/backend/internal/service/openai_gateway_responses_chat_fallback.go @@ -29,9 +29,8 @@ func (s *OpenAIGatewayService) forwardResponsesViaRawChatCompletions( c *gin.Context, account *Account, body []byte, + startTime time.Time, ) (*OpenAIForwardResult, error) { - startTime := time.Now() - var responsesReq apicompat.ResponsesRequest if err := json.Unmarshal(body, &responsesReq); err != nil { writeOpenAIResponsesFallbackError(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body") diff --git a/backend/internal/service/openai_gateway_responses_chat_fallback_test.go b/backend/internal/service/openai_gateway_responses_chat_fallback_test.go index ff0de70b0..40622574a 100644 --- a/backend/internal/service/openai_gateway_responses_chat_fallback_test.go +++ b/backend/internal/service/openai_gateway_responses_chat_fallback_test.go @@ -5,6 +5,7 @@ package service import ( "bytes" "context" + "fmt" "io" "net/http" "net/http/httptest" @@ -19,6 +20,34 @@ import ( "github.com/tidwall/gjson" ) +func TestForwardResponses_ChatFallbackPreservesProvidedStartTime(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%t", stream), func(t *testing.T) { + body := []byte(fmt.Sprintf(`{"model":"gpt-5.4","input":"hello","stream":%t}`, stream)) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + responseBody := `{"id":"chatcmpl_timing","choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}` + contentType := "application/json" + if stream { + responseBody = "data: {\"id\":\"chatcmpl_timing\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\ndata: {\"choices\":[],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":1,\"total_tokens\":2}}\n\ndata: [DONE]\n\n" + contentType = "text/event-stream" + } + upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(responseBody))}} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + startTime := time.Now().Add(-time.Minute) + result, err := svc.forwardResponsesViaRawChatCompletions(context.Background(), c, forceChatResponsesFallbackAccount(), body, startTime) + require.NoError(t, err) + require.NotNil(t, result) + require.GreaterOrEqual(t, result.Duration, time.Minute) + if stream { + require.NotNil(t, result.FirstTokenMs) + require.GreaterOrEqual(t, *result.FirstTokenMs, int(time.Minute.Milliseconds())) + } + }) + } +} + func TestForwardResponses_ForceChatCompletionsRoutesNonStreamingToChatCompletions(t *testing.T) { gin.SetMode(gin.TestMode) diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index 380186ddd..acdc6f6e3 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -446,7 +446,7 @@ func openAICompatibleAccountEligibilityFailureReasonBeforeProfit(ctx context.Con return "quota_auto_pause" } } - if requestedModel != "" && !account.IsModelSupported(requestedModel) { + if requestedModel != "" && !supportsOpenAIRequestModel(account, requestedModel, requireCompact) { return "model_not_supported" } if !account.SupportsOpenAIEndpointCapability(requiredCapability) { diff --git a/backend/internal/service/openai_gateway_search_surcharge_test.go b/backend/internal/service/openai_gateway_search_surcharge_test.go index d2d069ff5..ed9aed830 100644 --- a/backend/internal/service/openai_gateway_search_surcharge_test.go +++ b/backend/internal/service/openai_gateway_search_surcharge_test.go @@ -38,6 +38,7 @@ func TestCalculateOpenAIRecordUsageCost_SearchIsAdditiveToTokens(t *testing.T) { UsageTokens{InputTokens: 1000, OutputTokens: 500}, "", boolPtr(false), + false, time.Time{}, ) require.NoError(t, err) @@ -69,6 +70,7 @@ func TestCalculateOpenAIRecordUsageCost_SearchOnlyWhenNoTokenPricing(t *testing. UsageTokens{}, "", boolPtr(false), + false, time.Time{}, ) require.NoError(t, err) @@ -115,6 +117,7 @@ func TestCalculateOpenAIRecordUsageCost_TokenPricingErrorNotSwallowedBySearch(t UsageTokens{InputTokens: 1000, OutputTokens: 500}, "", boolPtr(false), + false, time.Time{}, ) require.Error(t, err) diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index 39da12304..ed0d8eb89 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -627,7 +627,14 @@ func (s *OpenAIGatewayService) ResolveChannelMappingAndRestrict(ctx context.Cont return s.channelService.ResolveChannelMappingAndRestrict(ctx, groupID, model) } +// isCodexImageGenerationBridgeEnabled 决定是否为 Codex 客户端自动注入 hosted +// image_generation 工具。该工具是 OpenAI Responses 专属能力,Kimi / DeepSeek / +// MiniMax 等经 OpenAI 网关转发的原生 Responses 上游不识别,注入后会被 400 拒绝, +// 因此非 OpenAI 平台账号一律不桥接,后续再按账号 → 渠道 → 全局的优先级取开关。 func (s *OpenAIGatewayService) isCodexImageGenerationBridgeEnabled(ctx context.Context, account *Account, apiKey *APIKey) bool { + if account == nil || account.Platform != PlatformOpenAI { + return false + } if override := account.CodexImageGenerationBridgeOverride(); override != nil { return *override } diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index b2a2f4c4e..bfce11ba1 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -14,6 +14,7 @@ import ( "github.com/MACOS-DO/sub4api/internal/config" "github.com/MACOS-DO/sub4api/internal/pkg/logger" + "github.com/MACOS-DO/sub4api/internal/pkg/openai" "github.com/MACOS-DO/sub4api/internal/pkg/timezone" "go.uber.org/zap" ) @@ -236,6 +237,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec serviceTier = strings.TrimSpace(*result.ServiceTier) } longContextBillingGate := openAILongContextBillingGate(billingAccount) + modelLongContextExempt := openAISubscriptionLongContextExempt(billingAccount, result) cost, err = s.calculateOpenAIRecordUsageCost( ctx, result, @@ -248,6 +250,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec tokens, serviceTier, longContextBillingGate, + modelLongContextExempt, pricingAt, ) if err != nil { @@ -281,7 +284,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec responseModels := s.filterCNProviderBillingModelCandidates(ctx, account, apiKey, usageBillingModelCandidates(responseModel)) responseCost, responseErr := s.calculateOpenAIRecordUsageCost( ctx, result, apiKey, responseModels, multiplier, imageMultiplier, - videoMultiplier, baseMultiplier, tokens, serviceTier, longContextBillingGate, pricingAt, + videoMultiplier, baseMultiplier, tokens, serviceTier, longContextBillingGate, modelLongContextExempt, pricingAt, ) // 基线定价源以 baselineBillingModel 为准:它正是 calculateOpenAIRecordUsageCost // 内部做渠道定价判断时使用的模型,且"首候选有渠道价"必然意味着首候选就是实际 @@ -312,6 +315,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec tokens, "", longContextBillingGate, + modelLongContextExempt, pricingAt, ) if standardErr != nil && !isUsagePricingUnavailableError(standardErr) { @@ -484,7 +488,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec applyAccountStatsCost(ctx, usageLog, s.channelService, s.billingService, account.ID, *apiKey.GroupID, result.UpstreamModel, result.Model, tokens, cost.TotalCost, pricingAt, - accountStatsLongContextPricingEnabled(longContextBillingGate), + accountStatsLongContextPricingEnabled(longContextBillingGate) && !modelLongContextExempt, ) } @@ -557,6 +561,20 @@ func openAILongContextBillingGate(account *Account) *bool { return &enabled } +// openAISubscriptionLongContextExempt 按实际凭据和最终发送模型判断订阅豁免。 +// GPT-6.1 Sol 的订阅请求不再收取模型长上下文附加费;API Key 仍使用 API 价卡。 +// 使用发送模型,避免客户别名、渠道计费模型或响应模型计费切换改变上游订阅规则。 +func openAISubscriptionLongContextExempt(account *Account, result *OpenAIForwardResult) bool { + if !account.IsOpenAIOAuthLike() || result == nil { + return false + } + model := strings.TrimSpace(result.UpstreamModel) + if model == "" { + model = result.Model + } + return openai.IsGPT61SolModelSpelling(model) +} + func (s *OpenAIGatewayService) calculateOpenAIRecordUsageCost( ctx context.Context, result *OpenAIForwardResult, @@ -569,6 +587,7 @@ func (s *OpenAIGatewayService) calculateOpenAIRecordUsageCost( tokens UsageTokens, serviceTier string, longContextBillingGate *bool, + modelLongContextExempt bool, pricingAt time.Time, ) (*CostBreakdown, error) { billingModel := firstUsageBillingModel(billingModels) @@ -625,6 +644,7 @@ func (s *OpenAIGatewayService) calculateOpenAIRecordUsageCost( serviceTier, optionalStringValue(result.ReasoningEffort), longContextBillingGate, + modelLongContextExempt, ) if err == nil { tokenCost = cost @@ -719,6 +739,7 @@ func (s *OpenAIGatewayService) calculateOpenAIRecordUsageTokenCost( serviceTier string, reasoningEffort string, longContextBillingGate *bool, + modelLongContextExempt bool, ) (*CostBreakdown, error) { if s.resolver != nil && apiKey.Group != nil { gid := apiKey.Group.ID @@ -726,7 +747,8 @@ func (s *OpenAIGatewayService) calculateOpenAIRecordUsageTokenCost( Ctx: ctx, Model: billingModel, GroupID: &gid, Group: apiKey.Group, Tokens: tokens, RequestCount: 1, RateMultiplier: multiplier, PricingAt: pricingAt, ServiceTier: serviceTier, ReasoningEffort: reasoningEffort, Resolver: s.resolver, - LongContextBillingEnabled: longContextBillingGate, + LongContextBillingEnabled: longContextBillingGate, + DisableModelLongContextPricing: modelLongContextExempt, }) } return s.billingService.calculateCostWithServiceTierPolicy( @@ -734,7 +756,7 @@ func (s *OpenAIGatewayService) calculateOpenAIRecordUsageTokenCost( tokens, multiplier, serviceTier, - longContextBillingGate == nil || *longContextBillingGate, + (longContextBillingGate == nil || *longContextBillingGate) && !modelLongContextExempt, ) } diff --git a/backend/internal/service/openai_image_generation_controls_test.go b/backend/internal/service/openai_image_generation_controls_test.go index 53afc1653..8270da82d 100644 --- a/backend/internal/service/openai_image_generation_controls_test.go +++ b/backend/internal/service/openai_image_generation_controls_test.go @@ -424,6 +424,76 @@ func TestOpenAIGatewayServiceForward_CodexBridgePreservesExistingToolChoice(t *t require.Equal(t, "image_generation", gjson.GetBytes(upstream.lastBody, "tool_choice.type").String()) } +// 国产原生 Responses 账号(Kimi / DeepSeek / MiniMax)在桥接由渠道级开关或全局开关 +// 单独打开时,发往上游的请求体都不能带 hosted image_generation 工具 / tool_choice / 桥接指令。 +func TestOpenAIGatewayServiceForward_CodexBridgeSkipsNativeCNResponsesAccounts(t *testing.T) { + gin.SetMode(gin.TestMode) + + groupID := int64(4242) + triggers := []struct { + name string + global bool + channel *Channel + }{ + { + name: "channel_openai_true_global_off", + global: false, + channel: &Channel{ID: 1, Status: StatusActive, FeaturesConfig: map[string]any{ + featureKeyCodexImageGenerationBridge: map[string]any{PlatformOpenAI: true}, + }}, + }, + { + name: "global_on_no_channel", + global: true, + }, + } + for _, platform := range []string{PlatformKimi, PlatformDeepseek, PlatformMiniMax} { + for _, trig := range triggers { + t.Run(platform+"/"+trig.name, func(t *testing.T) { + upstream := &httpUpstreamRecorder{ + resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"resp_cn_codex","model":"cn-model","usage":{"input_tokens":1,"output_tokens":1}}`)), + }, + } + svc := newOpenAIImageGenerationControlTestService(upstream) + svc.cfg.Gateway.CodexImageGenerationBridgeEnabled = trig.global + if trig.channel != nil { + svc.channelService = newOpenAIImageGenerationControlChannelService(groupID, trig.channel) + } + c, _ := newOpenAIImageGenerationControlTestContext(true, "codex_cli_rs/0.144.1") + account := &Account{ + ID: 6100, + Name: platform + "-native-responses", + Platform: platform, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "sk-cn-test", + "api_protocol": APIProtocolResponses, + }, + } + // 前置条件:账号确实走原生 Responses 转发,而不是 Chat Completions 转换链。 + require.True(t, account.UsesNativeCNResponses()) + require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account)) + + result, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"cn-model","input":"hello","stream":false,"tools":[{"type":"function","name":"shell","parameters":{"type":"object"}}]}`)) + + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, upstream.lastReq) + require.Falsef(t, gjson.GetBytes(upstream.lastBody, `tools.#(type=="image_generation")`).Exists(), "image_generation tool injected into %s upstream body", platform) + require.Falsef(t, gjson.GetBytes(upstream.lastBody, "tool_choice").Exists(), "tool_choice injected into %s upstream body", platform) + require.NotContains(t, gjson.GetBytes(upstream.lastBody, "instructions").String(), codexImageGenerationBridgeMarker) + require.Equal(t, "shell", gjson.GetBytes(upstream.lastBody, "tools.0.name").String()) + }) + } + } +} + func TestOpenAIGatewayServiceForward_CodexBridgeSkipsCompactRequests(t *testing.T) { gin.SetMode(gin.TestMode) @@ -524,6 +594,42 @@ func TestOpenAIGatewayService_CodexImageGenerationBridgeOverridePrecedence(t *te }, want: false, }, + { + name: "kimi account ignores channel openai true", + global: false, + channel: &Channel{ID: 1, Status: StatusActive, FeaturesConfig: map[string]any{ + featureKeyCodexImageGenerationBridge: map[string]any{PlatformOpenAI: true}, + }}, + account: &Account{Platform: PlatformKimi, Type: AccountTypeAPIKey}, + want: false, + }, + { + name: "kimi account ignores enabled global", + global: true, + account: &Account{Platform: PlatformKimi, Type: AccountTypeAPIKey}, + want: false, + }, + { + name: "deepseek account ignores enabled global", + global: true, + account: &Account{Platform: PlatformDeepseek, Type: AccountTypeAPIKey}, + want: false, + }, + { + name: "minimax account ignores channel openai true", + global: false, + channel: &Channel{ID: 1, Status: StatusActive, FeaturesConfig: map[string]any{ + featureKeyCodexImageGenerationBridge: map[string]any{PlatformOpenAI: true}, + }}, + account: &Account{Platform: PlatformMiniMax, Type: AccountTypeAPIKey}, + want: false, + }, + { + name: "nil account never bridges", + global: true, + account: nil, + want: false, + }, } for _, tt := range tests { diff --git a/backend/internal/service/openai_model_retirement.go b/backend/internal/service/openai_model_retirement.go new file mode 100644 index 000000000..d928c8ef2 --- /dev/null +++ b/backend/internal/service/openai_model_retirement.go @@ -0,0 +1,91 @@ +package service + +import ( + "encoding/json" + "strings" +) + +// GPT-5.5 retired from Codex with ChatGPT sign-in on 2026-10-14 at +// 19:00 UTC. API-key upstreams remain supported. Do not infer upstream +// eligibility from the API key a client uses to authenticate to this gateway. +// https://learn.chatgpt.com/docs/models#gpt-55-retirement +func isRetiredOpenAISubscriptionModel(account *Account, upstreamModel string) bool { + if account == nil || !account.IsOpenAI() || (!account.IsOpenAIOAuthLike() && !account.IsShadow()) { + return false + } + model := canonicalizeOpenAIModelAliasSpelling(upstreamModel) + return model == "gpt-5.5" || strings.HasPrefix(model, "gpt-5.5-") +} + +// Only remove entries blocked by retirement. Unknown models and other platforms +// retain their existing listing policy. An explicitly mapped replacement is +// allowed, but a public alias targeting retired GPT-5.5 is not. +func openAIModelRetiredForAccounts(accounts []Account, modelID string) bool { + retired := false + for i := range accounts { + account := &accounts[i] + if !account.IsOpenAI() { + continue + } + target := resolveOpenAIAccountUpstreamModelForRequest(account, modelID, false) + if isRetiredOpenAISubscriptionModel(account, target) { + retired = true + } else if account.IsModelSupported(modelID) { + return false + } + } + return retired +} + +func filterRetiredOpenAIModelIDs(accounts []Account, models []string) []string { + filtered := make([]string, 0, len(models)) + for _, model := range models { + if !openAIModelRetiredForAccounts(accounts, model) { + filtered = append(filtered, model) + } + } + return filtered +} + +// Entries must already use client-visible names, not raw upstream IDs. Resolve +// each public name exactly as routing does, after projection and before the +// final client ETag is calculated. Preserve unknown fields. +func filterRetiredOpenAIPublicModelsBody(body []byte, accounts []Account, codex bool) ([]byte, bool, error) { + field, idField := "data", "id" + if codex { + field, idField = "models", "slug" + } + envelope, entries, err := modelCatalogEntries(body, field) + if err != nil { + return nil, false, err + } + filtered := make([]json.RawMessage, 0, len(entries)) + for _, raw := range entries { + var entry map[string]json.RawMessage + var id string + if json.Unmarshal(raw, &entry) == nil { + _ = json.Unmarshal(entry[idField], &id) + } + if !openAIModelRetiredForAccounts(accounts, id) { + filtered = append(filtered, raw) + } + } + if len(filtered) == len(entries) { + return body, false, nil + } + envelope[field], err = json.Marshal(filtered) + if err != nil { + return nil, false, err + } + encoded, err := json.Marshal(envelope) + return encoded, true, err +} + +// Compact-only administrator mappings are evaluated against their actual +// target, without treating an old client-visible name as a retired target. +func supportsOpenAIRequestModel(account *Account, requestedModel string, requireCompact bool) bool { + if isRetiredOpenAISubscriptionModel(account, resolveOpenAIAccountUpstreamModelForRequest(account, requestedModel, requireCompact)) { + return false + } + return account.isModelMappingSupported(requestedModel) +} diff --git a/backend/internal/service/openai_model_retirement_test.go b/backend/internal/service/openai_model_retirement_test.go new file mode 100644 index 000000000..4b31b7e1f --- /dev/null +++ b/backend/internal/service/openai_model_retirement_test.go @@ -0,0 +1,236 @@ +package service + +import ( + "context" + "encoding/json" + "io" + "net/http" + "strings" + "testing" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestGPT55RetirementModelSupport(t *testing.T) { + for _, typ := range []string{AccountTypeOAuth, AccountTypeSetupToken, AccountTypeAPIKey} { + for _, passthrough := range []bool{false, true} { + t.Run(typ+"/passthrough="+map[bool]string{true: "true", false: "false"}[passthrough], func(t *testing.T) { + account := &Account{Platform: PlatformOpenAI, Type: typ, Extra: map[string]any{"openai_passthrough": passthrough}} + for _, model := range []string{"gpt-5.5", "openai/gpt-5.5-high", "gpt-5.5-2026-04-23", "GPT_5.5", "gpt-5.5-openai-compact"} { + require.Equal(t, typ == AccountTypeAPIKey, account.IsModelSupported(model), model) + } + require.True(t, account.IsModelSupported("gpt-6.1-sol")) + }) + } + } + for _, mapping := range []map[string]any{ + {"legacy": "gpt-5.5"}, {"legacy*": "gpt-5.5"}, + } { + account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"model_mapping": mapping}} + require.False(t, account.IsModelSupported("legacy")) + } + account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"model_mapping": map[string]any{"gpt-5.5": "gpt-6.1-sol"}}} + require.True(t, account.IsModelSupported("gpt-5.5"), "explicit administrator replacement remains authoritative") + account.Type = AccountTypeAPIKey + require.True(t, account.IsModelSupported("gpt-5.5")) + parent := int64(3) + shadow := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey, ParentAccountID: &parent} + require.False(t, shadow.IsModelSupported("gpt-5.5")) + require.False(t, isRetiredOpenAISubscriptionModel(&Account{Platform: PlatformAnthropic, Type: AccountTypeOAuth}, "gpt-5.5")) + require.False(t, isRetiredOpenAISubscriptionModel(account, "gpt-5.50")) +} + +func TestGPT55RetirementCatalogs(t *testing.T) { + oauth := Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + api := Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + group := &Group{ID: 1, Platform: PlatformOpenAI} + for _, tc := range []struct { + name string + accounts []Account + wantGPT55 bool + }{ + {"oauth", []Account{oauth}, false}, {"api", []Account{api}, true}, {"mixed", []Account{oauth, api}, true}, + } { + t.Run(tc.name, func(t *testing.T) { + repo := codexModelsVisibilityAccountRepo{byGroup: map[int64][]Account{1: tc.accounts}} + gateway := &GatewayService{accountRepo: repo} + models := gateway.GetAvailableModels(context.Background(), &group.ID, PlatformOpenAI) + if models != nil { + require.Equal(t, tc.wantGPT55, containsModelID(models, "gpt-5.5")) + } + body, err := buildCodexModelsManifestForAccounts(PlatformOpenAI, []string{"gpt-5.5", "gpt-6.1-sol"}, tc.accounts, group, nil, true) + require.NoError(t, err) + require.Equal(t, tc.wantGPT55, containsManifestModel(body, "gpt-5.5")) + // A stale/pinned upstream body must be filtered before evaluating its old ETag. + original := []byte(`{"models":[{"slug":"gpt-5.5","unknown":1},{"slug":"gpt-6.1-sol","unknown":2}],"unknown_top":3}`) + etag := CodexModelsManifestETag(original) + manifest := &OpenAIModelsResponse{Body: original, ETag: etag} + service := &OpenAIGatewayService{accountRepo: repo} + require.NoError(t, service.MergeGroupConfiguredCodexModels(context.Background(), group, manifest, etag)) + if !tc.wantGPT55 { + require.False(t, manifest.NotModified) + require.NotEqual(t, etag, manifest.ETag) + require.False(t, containsManifestModel(manifest.Body, "gpt-5.5")) + require.Equal(t, int64(3), gjson.GetBytes(manifest.Body, "unknown_top").Int()) + require.Equal(t, int64(2), gjson.GetBytes(manifest.Body, "models.0.unknown").Int()) + } + }) + } + // All configured entries retired: plain discovery must remain an authoritative empty list. + oauth.Credentials = map[string]any{"model_mapping": map[string]any{"gpt-5.5": "gpt-5.5"}} + repo := codexModelsVisibilityAccountRepo{byGroup: map[int64][]Account{1: {oauth}}} + models := (&GatewayService{accountRepo: repo}).GetAvailableModels(context.Background(), &group.ID, PlatformOpenAI) + require.NotNil(t, models) + require.Empty(t, models) +} + +func containsModelID(models []string, id string) bool { + for _, model := range models { + if model == id { + return true + } + } + return false +} +func containsManifestModel(body []byte, id string) bool { + for _, m := range gjson.GetBytes(body, "models").Array() { + if m.Get("slug").String() == id { + return true + } + } + return false +} + +func TestGPT55RetirementAccountProjection(t *testing.T) { + body := []byte(`{"object":"list","data":[{"id":"gpt-5.5"},{"id":"gpt-6.1-sol","unknown":true}],"unknown_top":true}`) + for _, typ := range []string{AccountTypeOAuth, AccountTypeAPIKey} { + account := &Account{Platform: PlatformOpenAI, Type: typ} + got, err := projectAccountModelsBody(body, account, nil, false) + require.NoError(t, err) + require.Equal(t, typ == AccountTypeAPIKey, strings.Contains(string(got), "gpt-5.5")) + require.True(t, gjson.GetBytes(got, "unknown_top").Bool()) + require.True(t, json.Valid(got)) + } +} + +func TestGPT55RetirementProjectionUsesPublicNames(t *testing.T) { + for _, codex := range []bool{false, true} { + field, idField := "data", "id" + if codex { + field, idField = "models", "slug" + } + for _, tc := range []struct { + name string + mapping map[string]any + passthrough bool + api bool + want map[string]string + }{ + {"one-hop", map[string]any{"legacy": "gpt-5.5", "gpt-5.5": "gpt-6.1-sol"}, false, false, map[string]string{"gpt-5.5": "live"}}, + {"crossed", map[string]any{"gpt-6.1-sol": "gpt-5.5", "gpt-5.5": "gpt-6.1-sol"}, false, false, map[string]string{"gpt-5.5": "live"}}, + {"wildcard", map[string]any{"legacy*": "gpt-5.5", "gpt-5.5": "gpt-6.1-sol"}, false, false, map[string]string{"gpt-5.5": "live"}}, + {"passthrough", map[string]any{"gpt-6.1-sol": "gpt-5.5", "gpt-5.5": "gpt-6.1-sol"}, true, false, map[string]string{"gpt-6.1-sol": "live"}}, + {"api", map[string]any{"legacy": "gpt-5.5", "gpt-5.5": "gpt-6.1-sol"}, false, true, map[string]string{"legacy": "retired", "gpt-5.5": "live"}}, + } { + t.Run(field+"/"+tc.name, func(t *testing.T) { + account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth, + Credentials: map[string]any{"model_mapping": tc.mapping}, Extra: map[string]any{"openai_passthrough": tc.passthrough}} + if tc.api { + account.Type = AccountTypeAPIKey + } + group := &Group{Platform: PlatformOpenAI, ModelAllowlist: GroupModelAllowlist{Enabled: true, Models: []string{"legacy", "gpt-5.5", "gpt-6.1-sol"}}} + body, err := json.Marshal(map[string]any{field: []map[string]any{ + {idField: "gpt-5.5", "source": "retired"}, {idField: "gpt-6.1-sol", "source": "live"}, + }, "unknown_top": true}) + require.NoError(t, err) + original := string(body) + got, err := projectAccountModelsBody(body, account, group, codex) + require.NoError(t, err) + require.Equal(t, original, string(body), "shared upstream cache must remain unchanged") + require.True(t, gjson.GetBytes(got, "unknown_top").Bool()) + entries := gjson.GetBytes(got, field).Array() + require.Len(t, entries, len(tc.want), string(got)) + for _, entry := range entries { + id := entry.Get(idField).String() + require.Contains(t, tc.want, id) + require.Equal(t, tc.want[id], entry.Get("source").String(), "metadata must come from the one-hop upstream target") + require.True(t, account.IsModelSupported(id), "catalog and routing must agree for %s", id) + } + if codex { + response := &OpenAIModelsResponse{Body: body, ETag: CodexModelsManifestETag(body)} + require.NoError(t, ApplyPinnedCodexModelsMapping(response, account, group)) + require.JSONEq(t, string(got), string(response.Body)) + require.Equal(t, codexModelsManifestBodyETag(response.Body), response.ETag) + group.ID = 1 + group.CodexModelsManifestConfig.Enabled = true + service := &OpenAIGatewayService{accountRepo: codexModelsVisibilityAccountRepo{byGroup: map[int64][]Account{1: {*account}}}} + require.NoError(t, service.MergeGroupConfiguredCodexModels(context.Background(), group, response, CodexModelsManifestETag(body))) + require.False(t, response.NotModified, "an upstream ETag must not hide the projected catalog") + require.Equal(t, codexModelsManifestBodyETag(response.Body), response.ETag) + require.NoError(t, service.MergeGroupConfiguredCodexModels(context.Background(), group, response, response.ETag)) + require.True(t, response.NotModified, "the final public ETag must support conditional requests") + } + }) + } + } +} + +func TestGPT55RetirementCompactFallbackKeepsSelectedModel(t *testing.T) { + for _, passthrough := range []bool{false, true} { + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "test-token"}, Extra: map[string]any{"openai_passthrough": passthrough}} + upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"id":"compact","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`))}} + svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{OpenAICompactModel: "gpt-5.5"}}, httpUpstream: upstream} + require.Empty(t, svc.resolveOpenAICompactFallbackModel(account, "gpt-6.1-sol")) + c := newOpenAICompactFallbackTestContext(t, "/v1/responses/compact") + _, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"gpt-6.1-sol","input":[],"instructions":"compact","stream":false}`)) + require.NoError(t, err) + require.Equal(t, "gpt-6.1-sol", gjson.GetBytes(upstream.lastBody, "model").String()) + account.Type = AccountTypeAPIKey + require.Equal(t, "gpt-5.5", svc.resolveOpenAICompactFallbackModel(account, "gpt-6.1-sol")) + } +} + +func TestGPT55RetirementSchedulerAndDiagnosis(t *testing.T) { + ctx := context.Background() + groupID := int64(1) + oauth := Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true} + api := Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true} + for _, typ := range []string{AccountTypeOAuth, AccountTypeSetupToken, AccountTypeAPIKey} { + account := oauth + account.Type = typ + scheduler := &defaultOpenAIAccountScheduler{} + ok, _ := scheduler.isAccountRequestCompatibleReason(ctx, &account, OpenAIAccountScheduleRequest{RequestedModel: "gpt-5.5"}) + require.Equal(t, typ == AccountTypeAPIKey, ok) + reason := openAICompatibleAccountEligibilityFailureReasonBeforeProfit(ctx, &account, PlatformOpenAI, "gpt-5.5", false, "") + require.Equal(t, typ == AccountTypeAPIKey, reason == "") + } + oauth.Credentials = map[string]any{"compact_model_mapping": map[string]any{"gpt-6.1-sol": "gpt-5.5"}} + scheduler := &defaultOpenAIAccountScheduler{} + ok, reason := scheduler.isAccountRequestCompatibleReason(ctx, &oauth, OpenAIAccountScheduleRequest{RequestedModel: "gpt-6.1-sol", RequireCompact: true}) + require.False(t, ok) + require.Equal(t, "model_not_supported", reason) + svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{OpenAICompactModel: "gpt-6.1-sol"}}} + require.Empty(t, svc.resolveOpenAICompactFallbackModel(&oauth, "gpt-6.1-sol"), "native compact retries must not use a retired explicit target") + oauth.Credentials = map[string]any{"compact_model_mapping": map[string]any{"gpt-5.5": "gpt-6.1-sol"}} + ok, _ = scheduler.isAccountRequestCompatibleReason(ctx, &oauth, OpenAIAccountScheduleRequest{RequestedModel: "gpt-5.5", RequireCompact: true}) + require.True(t, ok, "an explicit compact replacement remains usable") + for _, accounts := range [][]Account{{oauth}, {oauth, api}} { + svc := &OpenAIGatewayService{accountRepo: codexModelsVisibilityAccountRepo{byGroup: map[int64][]Account{groupID: accounts}}} + diagnosis := svc.DiagnoseModelAvailabilityForPlatform(ctx, &groupID, "gpt-5.5", PlatformOpenAI) + require.True(t, diagnosis.HasAccountsInPool) + require.True(t, diagnosis.HasRetiredSubscriptionModel) + require.Equal(t, len(accounts) == 2, diagnosis.HasModelSupport) + } +} + +func TestGPT55RetirementEmptyListingSource(t *testing.T) { + // A configured alias targeting retired GPT-5.5 must not reappear in a generated catalog. + account := Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"model_mapping": map[string]any{"legacy": "gpt-5.5"}}} + require.Empty(t, openAIConfiguredCodexModelIDsForGroup([]Account{account}, nil)) + body, err := buildCodexModelsManifestForAccounts(PlatformComposite, []string{"gpt-5.5", "gpt-6.1-sol"}, []Account{account}, nil, nil, true) + require.NoError(t, err) + require.False(t, containsManifestModel(body, "gpt-5.5")) +} diff --git a/backend/internal/service/openai_models_list.go b/backend/internal/service/openai_models_list.go index 634d65937..b6f68e18c 100644 --- a/backend/internal/service/openai_models_list.go +++ b/backend/internal/service/openai_models_list.go @@ -161,10 +161,22 @@ func standardOpenAIModelsBody(body []byte, fromManifest bool) ([]byte, error) { }{Object: "list", Data: models}) } -// projectAccountModelsBody applies the same public-name mapping to both model -// representations while retaining the source entry's metadata. It never changes -// the shared response and never synthesizes models absent from this account. +// projectAccountModelsBody projects upstream entries to public names before +// checking their routing eligibility. Applying account mappings to source IDs +// would interpret upstream names as aliases and can retain retired targets or +// discard metadata needed by a valid replacement alias. func projectAccountModelsBody(body []byte, account *Account, group *Group, codex bool) ([]byte, error) { + projected, err := projectAccountModelAliases(body, account, group, codex) + if err != nil { + return nil, err + } + filtered, _, err := filterRetiredOpenAIPublicModelsBody(projected, []Account{*account}, codex) + return filtered, err +} + +// projectAccountModelAliases retains the source entry's metadata, never changes +// the shared response, and never synthesizes models absent from this account. +func projectAccountModelAliases(body []byte, account *Account, group *Group, codex bool) ([]byte, error) { if account.IsOpenAIPassthroughEnabled() || len(account.GetModelMapping()) == 0 { return body, nil } diff --git a/backend/internal/service/openai_response_model_rewrite_test.go b/backend/internal/service/openai_response_model_rewrite_test.go index 7c7035168..53c64a030 100644 --- a/backend/internal/service/openai_response_model_rewrite_test.go +++ b/backend/internal/service/openai_response_model_rewrite_test.go @@ -56,7 +56,7 @@ func TestMappedResponseModelForwarding(t *testing.T) { contentType := "application/json" body := payload if kind == "responses" { - payload = `{"type":"response.completed","response":{"id":"resp_1","model":"` + returned + `","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}` + payload = `{"type":"response.completed","response":{"id":"resp_1","created_at":1700000000,"model":"` + returned + `","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}` want = strings.Replace(payload, `"model":"`+returned+`"`, `"model":"`+model+`"`, 1) } if kind != "json" { diff --git a/backend/internal/service/openai_responses_created_at.go b/backend/internal/service/openai_responses_created_at.go new file mode 100644 index 000000000..4387b02b5 --- /dev/null +++ b/backend/internal/service/openai_responses_created_at.go @@ -0,0 +1,94 @@ +package service + +import ( + "strings" + "time" + + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// Strict Responses clients (Rust serde: grok-build, Codex) declare +// Response.created_at as required — a response object without it fails the +// whole turn with `missing field 'created_at'` (issues #5601, #8118). +// Official upstreams always send it, but vendor gateways in front of Grok +// subscriptions and gateway-synthesized terminal frames may not, so every +// Response object leaving the gateway is stamped when the field is absent. + +// responsesCreatedAtStamper keeps one created_at per Responses stream: the +// upstream's own value once seen, otherwise a single timestamp taken on first +// use, so response.created and the terminal event always agree. +type responsesCreatedAtStamper struct { + createdAt int64 +} + +func (s *responsesCreatedAtStamper) learn(value gjson.Result) { + if s.createdAt == 0 && value.Type == gjson.Number && value.Int() > 0 { + s.createdAt = value.Int() + } +} + +// Value returns the stream's created_at, fixing it to now on first use. +func (s *responsesCreatedAtStamper) Value() int64 { + if s.createdAt <= 0 { + s.createdAt = time.Now().Unix() + } + return s.createdAt +} + +// Observe records the upstream created_at without modifying the payload. +func (s *responsesCreatedAtStamper) Observe(payload []byte, eventType string) { + if !strings.HasPrefix(strings.TrimSpace(eventType), "response.") { + return + } + s.learn(gjson.GetBytes(payload, "response.created_at")) +} + +// Stamp adds response.created_at to a Responses lifecycle event whose +// response object lacks it (absent or null). Any other value is left as-is. +func (s *responsesCreatedAtStamper) Stamp(payload []byte, eventType string) ([]byte, bool) { + if !strings.HasPrefix(strings.TrimSpace(eventType), "response.") { + return payload, false + } + response := gjson.GetBytes(payload, "response") + if !response.IsObject() { + return payload, false + } + createdAt := response.Get("created_at") + if createdAt.Exists() && createdAt.Type != gjson.Null { + s.learn(createdAt) + return payload, false + } + stamped, err := sjson.SetBytes(payload, "response.created_at", s.Value()) + if err != nil { + return payload, false + } + return stamped, true +} + +// ensureOpenAIResponseObjectCreatedAt stamps created_at onto a non-streaming +// Response object (`"object":"response"`) that lacks it. +func ensureOpenAIResponseObjectCreatedAt(body []byte) []byte { + if gjson.GetBytes(body, "object").String() != "response" { + return body + } + createdAt := gjson.GetBytes(body, "created_at") + if createdAt.Exists() && createdAt.Type != gjson.Null { + return body + } + stamped, err := sjson.SetBytes(body, "created_at", time.Now().Unix()) + if err != nil { + return body + } + return stamped +} + +// openAIResponsesFailedSequenceNumber reuses the sequence slot of the bare +// error event a synthesized response.failed replaces (that error frame is +// suppressed), keeping the client-visible sequence monotonic; 0 when unknown. +func openAIResponsesFailedSequenceNumber(source []byte) int64 { + if seq := gjson.GetBytes(source, "sequence_number"); seq.Type == gjson.Number && seq.Int() >= 0 { + return seq.Int() + } + return 0 +} diff --git a/backend/internal/service/openai_responses_created_at_test.go b/backend/internal/service/openai_responses_created_at_test.go new file mode 100644 index 000000000..39c057ea7 --- /dev/null +++ b/backend/internal/service/openai_responses_created_at_test.go @@ -0,0 +1,355 @@ +package service + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// issue #8118:grok-build(Rust serde)把 Response.created_at 当必填字段,缺失即 +// `missing field 'created_at'` 整轮读不出响应。网关送出的每个 Response 对象都必须带它。 + +// sseDataPayloads 按顺序取出 SSE 文本里的全部 data 负载(跳过 [DONE])。 +func sseDataPayloads(body string) []string { + var payloads []string + for _, line := range strings.Split(body, "\n") { + data, ok := strings.CutPrefix(line, "data: ") + if !ok || strings.TrimSpace(data) == "[DONE]" { + continue + } + payloads = append(payloads, data) + } + return payloads +} + +func TestResponsesCreatedAtStamper_StampsMissingAndKeepsStreamStable(t *testing.T) { + var stamper responsesCreatedAtStamper + + created, changed := stamper.Stamp([]byte(`{"type":"response.created","response":{"id":"resp_1","status":"in_progress"}}`), "response.created") + require.True(t, changed) + first := gjson.GetBytes(created, "response.created_at") + require.Equal(t, gjson.Number, first.Type) + require.Positive(t, first.Int()) + + completed, changed := stamper.Stamp([]byte(`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[]}}`), "response.completed") + require.True(t, changed) + require.Equal(t, first.Int(), gjson.GetBytes(completed, "response.created_at").Int(), "同一条流的 created_at 必须一致") +} + +func TestResponsesCreatedAtStamper_PreservesUpstreamValue(t *testing.T) { + var stamper responsesCreatedAtStamper + upstream := []byte(`{"type":"response.created","response":{"id":"resp_1","created_at":1700000000}}`) + + out, changed := stamper.Stamp(upstream, "response.created") + require.False(t, changed) + require.Equal(t, string(upstream), string(out), "上游已带 created_at 时字节不变") + + completed, changed := stamper.Stamp([]byte(`{"type":"response.completed","response":{"id":"resp_1"}}`), "response.completed") + require.True(t, changed) + require.EqualValues(t, 1700000000, gjson.GetBytes(completed, "response.created_at").Int(), "后续缺失时沿用上游值") + require.EqualValues(t, 1700000000, stamper.Value()) +} + +func TestResponsesCreatedAtStamper_NullIsTreatedAsMissing(t *testing.T) { + var stamper responsesCreatedAtStamper + out, changed := stamper.Stamp([]byte(`{"type":"response.created","response":{"id":"resp_1","created_at":null}}`), "response.created") + require.True(t, changed) + require.Equal(t, gjson.Number, gjson.GetBytes(out, "response.created_at").Type) +} + +func TestResponsesCreatedAtStamper_LeavesOtherEventsUntouched(t *testing.T) { + cases := []struct { + name string + eventType string + payload string + }{ + {"delta", "response.output_text.delta", `{"type":"response.output_text.delta","delta":"hi"}`}, + {"bare_error", "error", `{"type":"error","error":{"message":"boom"}}`}, + {"error_with_response_field", "error", `{"type":"error","response":{"id":"resp_1"}}`}, + {"response_not_object", "response.created", `{"type":"response.created","response":"resp_1"}`}, + {"non_numeric_created_at", "response.created", `{"type":"response.created","response":{"created_at":"2026-10-16T00:00:00Z"}}`}, + {"invalid_json", "response.created", `not json`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var stamper responsesCreatedAtStamper + out, changed := stamper.Stamp([]byte(tc.payload), tc.eventType) + require.False(t, changed) + require.Equal(t, tc.payload, string(out)) + }) + } +} + +func TestResponsesCreatedAtStamper_ObserveLearnsWithoutStamping(t *testing.T) { + var stamper responsesCreatedAtStamper + stamper.Observe([]byte(`{"type":"error","response":{"created_at":1600000000}}`), "error") + stamper.Observe([]byte(`{"type":"response.created","response":{"created_at":1700000000}}`), "response.created") + stamper.Observe([]byte(`{"type":"response.in_progress","response":{"created_at":1800000000}}`), "response.in_progress") + require.EqualValues(t, 1700000000, stamper.Value(), "记首个生命周期事件的上游值") +} + +func TestEnsureOpenAIResponseObjectCreatedAt(t *testing.T) { + stamped := ensureOpenAIResponseObjectCreatedAt([]byte(`{"id":"resp_1","object":"response","status":"completed"}`)) + require.Equal(t, gjson.Number, gjson.GetBytes(stamped, "created_at").Type) + require.Positive(t, gjson.GetBytes(stamped, "created_at").Int()) + + for _, body := range []string{ + `{"id":"resp_1","object":"response","created_at":1700000000}`, + `{"id":"cmp_1","object":"response.compaction","output":[]}`, + `{"id":"resp_1","output":[]}`, + `not json`, + } { + require.Equal(t, body, string(ensureOpenAIResponseObjectCreatedAt([]byte(body)))) + } +} + +func TestBuildOpenAIResponseFailedSSE_CarriesCreatedAtAndSequenceNumber(t *testing.T) { + frame := buildOpenAIResponseFailedSSE("resp_1", "gpt-5.5", 1700000000, + []byte(`{"type":"error","sequence_number":7,"error":{"code":"server_is_overloaded","message":"busy"}}`), "") + payloads := sseDataPayloads(frame) + require.Len(t, payloads, 1) + event := payloads[0] + require.Equal(t, "response.failed", gjson.Get(event, "type").String()) + require.EqualValues(t, 7, gjson.Get(event, "sequence_number").Int(), "沿用被替换的裸 error 帧序号") + require.EqualValues(t, 1700000000, gjson.Get(event, "response.created_at").Int()) + require.Equal(t, "resp_1", gjson.Get(event, "response.id").String()) + require.Equal(t, "failed", gjson.Get(event, "response.status").String()) + + frame = buildOpenAIResponseFailedSSE("", "", 0, []byte(`{"type":"error","error":{"message":"boom"}}`), "") + event = sseDataPayloads(frame)[0] + require.True(t, gjson.Get(event, "sequence_number").Exists(), "sequence_number 未知时也必须写出") + require.EqualValues(t, 0, gjson.Get(event, "sequence_number").Int()) + require.Positive(t, gjson.Get(event, "response.created_at").Int(), "未知 created_at 时取当前时间") +} + +func TestBuildOpenAIWSHTTPBridgeFailedEvent_CarriesCreatedAtAndSequenceNumber(t *testing.T) { + event := buildOpenAIWSHTTPBridgeFailedEvent("resp_1", "gpt-5.5", 1700000000, + []byte(`{"type":"error","sequence_number":4,"error":{"message":"boom"}}`), "") + require.Equal(t, "response.failed", gjson.GetBytes(event, "type").String()) + require.EqualValues(t, 4, gjson.GetBytes(event, "sequence_number").Int()) + require.EqualValues(t, 1700000000, gjson.GetBytes(event, "response.created_at").Int()) + + event = buildOpenAIWSHTTPBridgeFailedEvent("resp_1", "", 0, []byte(`{"type":"error","error":{"message":"boom"}}`), "") + require.EqualValues(t, 0, gjson.GetBytes(event, "sequence_number").Int()) + require.Positive(t, gjson.GetBytes(event, "response.created_at").Int()) +} + +// Grok 账号挂在不发 created_at 的上游(第三方中转)后面:每个生命周期事件都要补齐, +// 且同一条流取同一个值;增量事件字节不变。 +func TestHandleStreamingResponse_GrokStampsMissingCreatedAt(t *testing.T) { + delta := `{"type":"response.output_text.delta","sequence_number":2,"item_id":"msg_1","output_index":0,"content_index":0,"delta":"hi"}` + body := "event: response.created\n" + + `data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_grok","object":"response","model":"grok-4.5","status":"in_progress","output":[]}}` + "\n\n" + + "event: response.in_progress\n" + + `data: {"type":"response.in_progress","sequence_number":1,"response":{"id":"resp_grok","object":"response","model":"grok-4.5","status":"in_progress","output":[]}}` + "\n\n" + + "event: response.output_text.delta\n" + + "data: " + delta + "\n\n" + + "event: response.completed\n" + + `data: {"type":"response.completed","sequence_number":3,"response":{"id":"resp_grok","object":"response","model":"grok-4.5","status":"completed","output":[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"hi","annotations":[]}]}],"usage":{"input_tokens":3,"output_tokens":1,"total_tokens":4}}}` + "\n\n" + recorder := newOpenAIResponseFlushRecorder() + account := &Account{ID: 8118, Platform: PlatformGrok, Type: AccountTypeAPIKey} + + result, err := runOpenAIResponseFlushTestWithAccount(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}, account) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 3, result.usage.InputTokens) + gotBody, _ := recorder.snapshot() + payloads := sseDataPayloads(gotBody) + require.Len(t, payloads, 4) + createdAt := gjson.Get(payloads[0], "response.created_at") + require.Equal(t, gjson.Number, createdAt.Type) + require.Positive(t, createdAt.Int()) + for _, index := range []int{1, 3} { + require.Equal(t, createdAt.Int(), gjson.Get(payloads[index], "response.created_at").Int(), "payload %d", index) + } + require.Equal(t, delta, payloads[2], "非生命周期事件不得改动") + require.Equal(t, "hi", gjson.Get(payloads[3], "response.output.0.content.0.text").String()) +} + +// 官方上游自带 created_at:网关输出必须与上游逐字节一致(不引入任何改写)。 +func TestHandleStreamingResponse_GrokKeepsUpstreamCreatedAtBytes(t *testing.T) { + body := "event: response.created\n" + + `data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_grok","object":"response","created_at":1774274151,"model":"grok-4.5","status":"in_progress","output":[]}}` + "\n\n" + + "event: response.completed\n" + + `data: {"type":"response.completed","sequence_number":1,"response":{"id":"resp_grok","object":"response","created_at":1774274151,"model":"grok-4.5","status":"completed","output":[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"hi","annotations":[]}]}],"usage":{"input_tokens":3,"output_tokens":1,"total_tokens":4}}}` + "\n\n" + recorder := newOpenAIResponseFlushRecorder() + account := &Account{ID: 8118, Platform: PlatformGrok, Type: AccountTypeOAuth} + + _, err := runOpenAIResponseFlushTestWithAccount(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}, account) + + require.NoError(t, err) + gotBody, _ := recorder.snapshot() + require.Equal(t, body, gotBody) +} + +// OpenAI OAuth 流以裸 error 结束:合成的 response.failed 必须带 created_at +// (与本流 response.created 一致)和 sequence_number。 +func TestHandleStreamingResponse_BareErrorSynthesizedFailedCarriesCreatedAt(t *testing.T) { + body := `data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_bare","object":"response","created_at":1700000000,"status":"in_progress","output":[]}}` + "\n\n" + + `data: {"type":"response.output_text.delta","sequence_number":1,"item_id":"msg_1","output_index":0,"content_index":0,"delta":"partial"}` + "\n\n" + + `data: {"type":"error","sequence_number":2,"error":{"code":"server_is_overloaded","message":"busy"}}` + "\n\n" + + "data: [DONE]\n\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}) + + require.Error(t, err) + require.NotNil(t, result) + gotBody, _ := recorder.snapshot() + require.NotContains(t, gotBody, `"type":"error"`) + var failed string + for _, payload := range sseDataPayloads(gotBody) { + if gjson.Get(payload, "type").String() == "response.failed" { + failed = payload + } + } + require.NotEmpty(t, failed, "必须合成 response.failed: %s", gotBody) + require.EqualValues(t, 1700000000, gjson.Get(failed, "response.created_at").Int()) + require.EqualValues(t, 2, gjson.Get(failed, "sequence_number").Int()) + require.Equal(t, "resp_bare", gjson.Get(failed, "response.id").String()) +} + +func TestHandleStreamingResponsePassthrough_BareErrorSynthesizedFailedCarriesCreatedAt(t *testing.T) { + upstream := `data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_pt","object":"response","created_at":1700000000,"status":"in_progress","output":[]}}` + "\n\n" + + "event: error\n" + + `data: {"type":"error","sequence_number":1,"error":{"code":"content_policy","message":"request blocked by policy"}}` + "\n\n" + + "data: [DONE]\n\n" + + _, recorder, _, err := runPassthroughFlushTest(t, io.NopCloser(strings.NewReader(upstream)), -1) + + require.Error(t, err) + var failed string + for _, payload := range sseDataPayloads(recorder.Body.String()) { + if gjson.Get(payload, "type").String() == "response.failed" { + failed = payload + } + } + require.NotEmpty(t, failed, "必须合成 response.failed: %s", recorder.Body.String()) + require.EqualValues(t, 1700000000, gjson.Get(failed, "response.created_at").Int()) + require.EqualValues(t, 1, gjson.Get(failed, "sequence_number").Int()) +} + +func TestProxyOpenAIWSHTTPBridgeTurn_GrokStampsMissingCreatedAt(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(strings.Join([]string{ + `data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_ws","object":"response","model":"grok-4.5","status":"in_progress"}}`, + "", + `data: {"type":"response.completed","sequence_number":1,"response":{"id":"resp_ws","object":"response","model":"grok-4.5","status":"completed","usage":{"input_tokens":1,"output_tokens":1}}}`, + "", + }, "\n"))), + }} + svc := &OpenAIGatewayService{ + cfg: &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}, + httpUpstream: upstream, + } + account := &Account{ID: 8118, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1} + payload := []byte(`{"type":"response.create","model":"grok-4.5","stream":true,"input":"hi"}`) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil) + var events [][]byte + + result, err := svc.proxyOpenAIWSHTTPBridgeTurn( + context.Background(), c, account, "access-token", payload, len(payload), + "grok-4.5", "", "", "", "", 1, + func(message []byte) error { + events = append(events, append([]byte(nil), message...)) + return nil + }, + ) + + require.NoError(t, err) + require.NotNil(t, result) + require.Len(t, events, 2) + createdAt := gjson.GetBytes(events[0], "response.created_at") + require.Equal(t, gjson.Number, createdAt.Type) + require.Positive(t, createdAt.Int()) + require.Equal(t, createdAt.Int(), gjson.GetBytes(events[1], "response.created_at").Int()) +} + +func TestProxyOpenAIWSHTTPBridgeTurn_BareErrorSynthesizedFailedCarriesCreatedAt(t *testing.T) { + gin.SetMode(gin.TestMode) + body := `data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_eof","created_at":1700000000,"status":"in_progress"}}` + "\n\n" + + `data: {"type":"error","sequence_number":1,"error":{"code":"invalid_request","message":"bad request"}}` + "\n\n" + upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := &Account{ID: 112, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Concurrency: 1} + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil) + payload := []byte(`{"type":"response.create","model":"gpt-5","input":"hi"}`) + var writes [][]byte + + _, err := svc.proxyOpenAIWSHTTPBridgeTurn(context.Background(), c, account, "sk-test", payload, len(payload), "gpt-5", "", "", "", "", 2, func(message []byte) error { + writes = append(writes, append([]byte(nil), message...)) + return nil + }) + + require.EqualError(t, err, "bad request") + require.Len(t, writes, 2) + require.Equal(t, "response.failed", gjson.GetBytes(writes[1], "type").String()) + require.EqualValues(t, 1700000000, gjson.GetBytes(writes[1], "response.created_at").Int()) + require.EqualValues(t, 1, gjson.GetBytes(writes[1], "sequence_number").Int()) +} + +func TestHandleNonStreamingResponse_StampsMissingCreatedAt(t *testing.T) { + run := func(t *testing.T, upstreamBody string) string { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + svc := &OpenAIGatewayService{cfg: &config.Config{}, toolCorrector: NewCodexToolCorrector()} + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + } + result, err := svc.handleNonStreamingResponse(context.Background(), resp, c, &Account{ID: 8118, Platform: PlatformGrok, Type: AccountTypeAPIKey}, "grok-4.5", "grok-4.5") + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 3, result.usage.InputTokens) + return rec.Body.String() + } + + missing := run(t, `{"id":"resp_1","object":"response","model":"grok-4.5","status":"completed","output":[],"usage":{"input_tokens":3,"output_tokens":1,"total_tokens":4}}`) + require.Equal(t, gjson.Number, gjson.Get(missing, "created_at").Type) + require.Positive(t, gjson.Get(missing, "created_at").Int()) + + present := `{"id":"resp_1","object":"response","created_at":1700000000,"model":"grok-4.5","status":"completed","output":[],"usage":{"input_tokens":3,"output_tokens":1,"total_tokens":4}}` + require.Equal(t, present, run(t, present)) +} + +func TestHandleSSEToJSON_StampsMissingCreatedAt(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + svc := &OpenAIGatewayService{cfg: &config.Config{}, toolCorrector: NewCodexToolCorrector()} + body := `data: {"type":"response.completed","response":{"id":"resp_1","object":"response","status":"completed","output":[{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"hi","annotations":[]}]}],"usage":{"input_tokens":3,"output_tokens":1,"total_tokens":4}}}` + "\n\n" + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(body)), + } + + result, err := svc.handleNonStreamingResponse(context.Background(), resp, c, &Account{ID: 8118, Platform: PlatformGrok, Type: AccountTypeOAuth}, "grok-4.5", "grok-4.5") + + require.NoError(t, err) + require.NotNil(t, result) + out := rec.Body.String() + require.Equal(t, "resp_1", gjson.Get(out, "id").String()) + require.Positive(t, gjson.Get(out, "created_at").Int()) +} diff --git a/backend/internal/service/openai_responses_ingress_compat.go b/backend/internal/service/openai_responses_ingress_compat.go index 69de3f289..4b984a60e 100644 --- a/backend/internal/service/openai_responses_ingress_compat.go +++ b/backend/internal/service/openai_responses_ingress_compat.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "github.com/MACOS-DO/sub4api/internal/config" "github.com/MACOS-DO/sub4api/internal/pkg/apicompat" "github.com/tidwall/gjson" ) @@ -13,6 +14,10 @@ import ( // payloads that a few Responses clients still emit. Native Responses input is // always authoritative because this path has no separate full-replay attempt. func normalizeOpenAIResponsesLegacyIngress(body []byte) ([]byte, bool, error) { + return normalizeOpenAIResponsesLegacyIngressWithConfig(nil, body) +} + +func normalizeOpenAIResponsesLegacyIngressWithConfig(cfg *config.Config, body []byte) ([]byte, bool, error) { if len(body) == 0 { return body, false, nil } @@ -43,7 +48,7 @@ func normalizeOpenAIResponsesLegacyIngress(body []byte) ([]byte, bool, error) { if hasMessages { messages, messagesAreArray := messagesValue.([]any) if messagesAreArray && len(messages) > 0 { - legacy, err := convertLegacyResponsesMessages(body) + legacy, err := convertLegacyResponsesMessages(cfg, body) if err != nil { return body, false, err } @@ -105,13 +110,13 @@ type convertedLegacyResponsesMessages struct { hasReasoningEffort bool } -func convertLegacyResponsesMessages(body []byte) (convertedLegacyResponsesMessages, error) { +func convertLegacyResponsesMessages(cfg *config.Config, body []byte) (convertedLegacyResponsesMessages, error) { var converted convertedLegacyResponsesMessages var chatRequest apicompat.ChatCompletionsRequest if err := json.Unmarshal(body, &chatRequest); err != nil { return converted, fmt.Errorf("normalize legacy Responses messages: %w", err) } - responsesRequest, err := apicompat.ChatCompletionsToResponses(&chatRequest) + responsesRequest, err := chatCompletionsToResponses(cfg, &chatRequest) if err != nil { return converted, fmt.Errorf("normalize legacy Responses messages: %w", err) } diff --git a/backend/internal/service/openai_subscription_long_context_test.go b/backend/internal/service/openai_subscription_long_context_test.go new file mode 100644 index 000000000..bdf5b9549 --- /dev/null +++ b/backend/internal/service/openai_subscription_long_context_test.go @@ -0,0 +1,238 @@ +//go:build unit + +package service + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestOpenAISubscriptionLongContextExempt(t *testing.T) { + oauth := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth} + for _, tt := range []struct { + name string + account *Account + result *OpenAIForwardResult + want bool + }{ + {name: "空账号", result: &OpenAIForwardResult{Model: "gpt-6.1-sol"}}, + {name: "空结果", account: oauth}, + {name: "订阅", account: oauth, result: &OpenAIForwardResult{Model: "gpt-6.1-sol"}, want: true}, + {name: "别名", account: oauth, result: &OpenAIForwardResult{Model: "openai/GPT_6.1_SOL-max"}, want: true}, + {name: "压缩", account: oauth, result: &OpenAIForwardResult{Model: "gpt-6.1-sol-openai-compact"}, want: true}, + {name: "映射到目标", account: oauth, result: &OpenAIForwardResult{Model: "custom", UpstreamModel: "gpt-6.1-sol"}, want: true}, + {name: "映射离开目标", account: oauth, result: &OpenAIForwardResult{Model: "gpt-6.1-sol", UpstreamModel: "gpt-6-sol"}}, + {name: "仅计费标签相同", account: oauth, result: &OpenAIForwardResult{Model: "gpt-6-sol", BillingModel: "gpt-6.1-sol"}}, + {name: "仅响应标签相同", account: oauth, result: &OpenAIForwardResult{Model: "gpt-6-sol", UpstreamResponseModel: "gpt-6.1-sol"}}, + {name: "其他模型", account: oauth, result: &OpenAIForwardResult{Model: "gpt-6-astra"}}, + {name: "相似名称", account: oauth, result: &OpenAIForwardResult{Model: "gpt-6.1-sol-preview"}}, + {name: "API账号", account: &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, result: &OpenAIForwardResult{Model: "gpt-6.1-sol"}}, + {name: "其他平台", account: &Account{Platform: PlatformGrok, Type: AccountTypeOAuth}, result: &OpenAIForwardResult{Model: "gpt-6.1-sol"}}, + {name: "订阅访问令牌", account: &Account{Platform: PlatformOpenAI, Type: AccountTypeSetupToken}, result: &OpenAIForwardResult{Model: "gpt-6.1-sol"}, want: true}, + } { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.want, openAISubscriptionLongContextExempt(tt.account, tt.result)) + }) + } +} + +// 同时覆盖远程目录更新、静态兜底、旧计费入口和分组入口,校验真实扣款与账号成本。 +func TestOpenAIGatewayServiceRecordUsage_GPT61SolSubscriptionLongContext(t *testing.T) { + for _, catalog := range []bool{false, true} { + for _, groupMode := range []string{"无分组", "分组关闭", "分组开启"} { + for _, accountEnabled := range []bool{false, true} { + for _, accountType := range []string{AccountTypeOAuth, AccountTypeSetupToken, AccountTypeAPIKey} { + for _, tier := range []string{"", "priority"} { + name := fmt.Sprintf("目录=%t/%s/账号开关=%t/%s/%s", catalog, groupMode, accountEnabled, accountType, tier) + t.Run(name, func(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + userRepo := &openAIRecordUsageUserRepoStub{} + svc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil) + if catalog { + svc.billingService = NewBillingService(svc.cfg, newStubPricingServiceFromJSON(t, `{ + "gpt-6.1-sol": {"litellm_provider": "openai", "mode": "chat", + "input_cost_per_token": 2e-6, "output_cost_per_token": 10e-6, + "cache_read_input_token_cost": 0.1e-6, "cache_creation_input_token_cost": 2.5e-6, + "input_cost_per_token_above_272k_tokens": 4e-6, + "output_cost_per_token_above_272k_tokens": 15e-6} + }`)) + } + apiKey := &APIKey{ID: 1} + if groupMode != "无分组" { + apiKey = openAIRecordUsageAPIKeyWithGroup(svc, 1, groupMode == "分组开启") + apiKey.GroupID = i64p(1) + apiKey.Group.RateMultiplier = 1.1 + svc.channelService = newTestChannelServiceForStats(t, &Channel{ID: 1, Status: StatusActive}, 1, PlatformOpenAI) + } + account := &Account{ID: 3, Platform: PlatformOpenAI, Type: accountType, + Extra: map[string]any{openAILongContextBillingEnabledKey: accountEnabled}} + err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{ + RequestID: name, Model: "gpt-6.1-sol", ServiceTier: &tier, Duration: time.Second, + // 普通输入只有 200k,由缓存使总上下文越过 272k。 + Usage: OpenAIUsage{InputTokens: 300000, OutputTokens: 2000, CacheReadInputTokens: 80000, CacheCreationInputTokens: 20000}, + }, + APIKey: apiKey, User: &User{ID: 2}, Account: account, + }) + require.NoError(t, err) + wantLong := accountType == AccountTypeAPIKey && (accountEnabled || groupMode == "分组开启") + inputFactor, outputFactor, tierFactor := 1.0, 1.0, 1.0 + if wantLong { + inputFactor, outputFactor = 2, 1.5 + } + if tier == "priority" { + tierFactor = 2 + } + log := usageRepo.lastLog + require.NotNil(t, log) + require.Equal(t, wantLong, log.LongContextBillingApplied) + require.InDelta(t, 200000*2e-6*inputFactor*tierFactor, log.InputCost, 1e-12) + require.InDelta(t, 80000*0.1e-6*inputFactor*tierFactor, log.CacheReadCost, 1e-12) + require.InDelta(t, 20000*2.5e-6*inputFactor*tierFactor, log.CacheCreationCost, 1e-12) + require.InDelta(t, 2000*10e-6*outputFactor*tierFactor, log.OutputCost, 1e-12) + wantTotal := (0.458*inputFactor + 0.02*outputFactor) * tierFactor + require.InDelta(t, wantTotal, log.TotalCost, 1e-12) + require.InDelta(t, wantTotal*1.1, log.ActualCost, 1e-12) + require.Equal(t, 1, userRepo.deductCalls) + require.InDelta(t, wantTotal*1.1, userRepo.lastAmount, 1e-12) + if groupMode != "无分组" { + wantStats := 0.478 * tierFactor + if accountType == AccountTypeAPIKey && accountEnabled { + wantStats = (0.458*2 + 0.02*1.5) * tierFactor + } + require.NotNil(t, log.AccountStatsCost) + require.InDelta(t, wantStats, *log.AccountStatsCost, 1e-12) + } + }) + } + } + } + } + } +} + +func TestOpenAIGatewayServiceRecordUsage_GPT61SolUsesCredentialAndUpstreamModel(t *testing.T) { + for _, tt := range []struct { + name string + model string + upstream string + parentType string + wantTotal float64 + wantLong bool + }{ + {name: "客户别名映射到目标", model: "custom", upstream: "gpt-6.1-sol", parentType: AccountTypeOAuth, wantTotal: 0.62}, + {name: "请求目标映射到旧模型", model: "gpt-6.1-sol", upstream: "gpt-6-sol", parentType: AccountTypeOAuth, wantTotal: 1.23, wantLong: true}, + {name: "其他订阅模型", model: "gpt-6-sol", parentType: AccountTypeOAuth, wantTotal: 1.23, wantLong: true}, + {name: "订阅母账号", model: "gpt-6.1-sol", parentType: AccountTypeOAuth, wantTotal: 0.62}, + } { + t.Run(tt.name, func(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + svc := newOpenAIRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + parentID := int64(4) + svc.accountRepo = &openAIRecordUsageAccountRepoStub{account: &Account{ + ID: parentID, Platform: PlatformOpenAI, Type: tt.parentType, + Extra: map[string]any{openAILongContextBillingEnabledKey: true}, + }} + err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{RequestID: tt.name, Model: tt.model, UpstreamModel: tt.upstream, + Usage: OpenAIUsage{InputTokens: 300000, OutputTokens: 2000}, Duration: time.Second}, + APIKey: openAIRecordUsageAPIKeyWithGroup(svc, 1, true), User: &User{ID: 2}, + Account: &Account{ID: 3, Platform: PlatformOpenAI, Type: AccountTypeOAuth, ParentAccountID: &parentID, QuotaDimension: QuotaDimensionSpark}, + }) + require.NoError(t, err) + require.Equal(t, tt.wantLong, usageRepo.lastLog.LongContextBillingApplied) + require.InDelta(t, tt.wantTotal, usageRepo.lastLog.TotalCost, 1e-12) + }) + } +} + +func TestCalculateCostUnified_ModelLongContextExemptionPreservesCustomIntervals(t *testing.T) { + service := NewBillingService(nil, nil) + for _, withResolver := range []bool{false, true} { + input := CostInput{Model: "gpt-6.1-sol", Tokens: UsageTokens{InputTokens: 300000}, RateMultiplier: 1, + LongContextBillingEnabled: boolPtr(true), DisableModelLongContextPricing: true} + if withResolver { + input.Ctx = context.Background() + input.Resolver = NewModelPricingResolver(nil, service) + } + cost, err := service.CalculateCostUnified(input) + require.NoError(t, err) + require.InDelta(t, 0.6, cost.TotalCost, 1e-12) + require.False(t, cost.LongContextBillingApplied) + if withResolver { + input.Resolved = &ResolvedPricing{ + BasePricing: &ModelPricing{InputPricePerToken: 2e-6}, + Intervals: []PricingInterval{{MinTokens: 272000, InputMultiplier: pricingMultiplier(3)}}, + longContextPricingEnabled: true, + } + cost, err = service.CalculateCostUnified(input) + require.NoError(t, err) + require.InDelta(t, 1.8, cost.TotalCost, 1e-12, "管理员显式区间价格应保留") + } + } +} + +func TestOpenAIGatewayServiceRecordUsage_GPT61SolLongContextBoundary(t *testing.T) { + for _, totalInput := range []int{271999, 272000, 272001} { + for _, accountType := range []string{AccountTypeOAuth, AccountTypeAPIKey} { + t.Run(fmt.Sprintf("%s/%d", accountType, totalInput), func(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + svc := newOpenAIRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{RequestID: "boundary", Model: "gpt-6.1-sol", Duration: time.Second, + Usage: OpenAIUsage{InputTokens: totalInput, OutputTokens: 1000}}, + APIKey: openAIRecordUsageAPIKeyWithGroup(svc, 1, true), User: &User{ID: 2}, + Account: &Account{ID: 3, Platform: PlatformOpenAI, Type: accountType, + Extra: map[string]any{openAILongContextBillingEnabledKey: true}}, + }) + require.NoError(t, err) + wantLong := accountType == AccountTypeAPIKey && totalInput > 272000 + wantInput, wantOutput := float64(totalInput)*2e-6, 0.01 + if wantLong { + wantInput *= 2 + wantOutput *= 1.5 + } + require.Equal(t, wantLong, usageRepo.lastLog.LongContextBillingApplied) + require.InDelta(t, wantInput, usageRepo.lastLog.InputCost, 1e-12) + require.InDelta(t, wantOutput, usageRepo.lastLog.OutputCost, 1e-12) + }) + } + } +} + +func TestOpenAIGatewayServiceRecordUsage_GPT61SolExemptionSurvivesRepricing(t *testing.T) { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + userRepo := &openAIRecordUsageUserRepoStub{} + svc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil) + apiKey := openAIRecordUsageAPIKeyWithGroup(svc, 1, true) + apiKey.GroupID = i64p(1) + apiKey.Group.Platform = PlatformOpenAI + apiKey.Group.RateMultiplier = 1.1 + apiKey.Group.FreeOpenAIFast = true + svc.channelService = newTestChannelServiceForStats(t, &Channel{ID: 1, Status: StatusActive}, 1, PlatformOpenAI) + tier := "priority" + err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{ + RequestID: "repricing", Model: "gpt-6-sol", UpstreamModel: "gpt-6.1-sol", BillingModel: "gpt-6-sol", + UpstreamResponseModel: "gpt-6.1-sol", ServiceTier: &tier, Duration: time.Second, + Usage: OpenAIUsage{InputTokens: 300000, OutputTokens: 2000, CacheReadInputTokens: 80000}, + }, + APIKey: apiKey, User: &User{ID: 2}, + Account: &Account{ID: 3, Platform: PlatformOpenAI, Type: AccountTypeOAuth, + Extra: map[string]any{openAILongContextBillingEnabledKey: true}}, + ChannelUsageFields: ChannelUsageFields{BillingModelSource: BillingModelSourceResponse}, + }) + require.NoError(t, err) + // 响应模型改用较低的缓存价;免费 Fast 再按标准档扣款,两次重算均须保留豁免。 + const standardCost = 220000*2e-6 + 80000*0.1e-6 + 2000*10e-6 + require.InDelta(t, standardCost*2, usageRepo.lastLog.TotalCost, 1e-12) + require.InDelta(t, standardCost*1.1, usageRepo.lastLog.ActualCost, 1e-12) + require.InDelta(t, standardCost*1.1, userRepo.lastAmount, 1e-12) + require.False(t, usageRepo.lastLog.LongContextBillingApplied) + require.NotNil(t, usageRepo.lastLog.AccountStatsCost) + require.InDelta(t, standardCost*2, *usageRepo.lastLog.AccountStatsCost, 1e-12) +} diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index aaa8a9f36..4532566c5 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -270,7 +270,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( normalized = next } responsesLite := isOpenAIResponsesLiteWebSocketPayload(normalized) - if compatibilityBody, compatibilityChanged, compatibilityErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(normalized, account, responsesLite); compatibilityErr != nil { + if compatibilityBody, compatibilityChanged, compatibilityErr := normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(s.cfg, normalized, account, responsesLite); compatibilityErr != nil { return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", compatibilityErr) } else if compatibilityChanged { normalized = compatibilityBody diff --git a/backend/internal/service/openai_ws_forwarder_support.go b/backend/internal/service/openai_ws_forwarder_support.go index 65baa0fd1..490be4346 100644 --- a/backend/internal/service/openai_ws_forwarder_support.go +++ b/backend/internal/service/openai_ws_forwarder_support.go @@ -571,7 +571,7 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability( _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) return 0, nil, "", nil } - if requestedModel != "" && !account.IsModelSupported(requestedModel) { + if requestedModel != "" && !supportsOpenAIRequestModel(account, requestedModel, requireCompact) { return 0, nil, "", nil } if !account.SupportsOpenAIEndpointCapability(requiredCapability) { @@ -610,7 +610,7 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability( _ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID) return 0, nil, "", nil } - if requestedModel != "" && !latest.IsModelSupported(requestedModel) { + if requestedModel != "" && !supportsOpenAIRequestModel(latest, requestedModel, requireCompact) { return 0, nil, "", nil } if !latest.SupportsOpenAIEndpointCapability(requiredCapability) { diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index 3096c092a..9f0e1954e 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -9,6 +9,7 @@ import ( "io" "net/http" "slices" + "strconv" "strings" "time" @@ -369,7 +370,10 @@ func buildOpenAIWSHTTPBridgeErrorEvent(statusCode int, message string) []byte { return body } -func buildOpenAIWSHTTPBridgeFailedEvent(responseID, model string, source []byte, fallbackMessage string) []byte { +// buildOpenAIWSHTTPBridgeFailedEvent synthesizes response.failed for a turn that +// ended on a bare error. created_at and sequence_number are always written: +// strict clients (grok-build, Codex) reject the frame without them. +func buildOpenAIWSHTTPBridgeFailedEvent(responseID, model string, createdAt int64, source []byte, fallbackMessage string) []byte { errorType := strings.TrimSpace(gjson.GetBytes(source, "error.type").String()) if errorType == "" { errorType = strings.TrimSpace(gjson.GetBytes(source, "response.error.type").String()) @@ -392,16 +396,22 @@ func buildOpenAIWSHTTPBridgeFailedEvent(responseID, model string, source []byte, if errorType != "" { errorBody["type"] = errorType } + if createdAt <= 0 { + createdAt = time.Now().Unix() + } + sequenceNumber := openAIResponsesFailedSequenceNumber(source) response := map[string]any{ - "id": responseID, "object": "response", "status": "failed", + "id": responseID, "object": "response", "created_at": createdAt, "status": "failed", "output": []any{}, "error": errorBody, } if model = strings.TrimSpace(model); model != "" { response["model"] = model } - body, err := json.Marshal(map[string]any{"type": "response.failed", "sequence_number": 0, "response": response}) + body, err := json.Marshal(map[string]any{"type": "response.failed", "sequence_number": sequenceNumber, "response": response}) if err != nil { - return []byte(`{"type":"response.failed","sequence_number":0,"response":{"status":"failed","output":[],"error":{"code":"upstream_error","message":"Upstream response failed"}}}`) + return []byte(`{"type":"response.failed","sequence_number":` + strconv.FormatInt(sequenceNumber, 10) + + `,"response":{"object":"response","created_at":` + strconv.FormatInt(createdAt, 10) + + `,"status":"failed","output":[],"error":{"code":"upstream_error","message":"Upstream response failed"}}}`) } return body } @@ -641,6 +651,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( officialOpenAIResponses := account != nil && account.Platform == PlatformOpenAI bareErrorPending := false var bareErrorPayload []byte + var createdAtStamper responsesCreatedAtStamper bareErrorMessage := "" failureAccountSideEffectsApplied := false mappedModel := actualModel @@ -712,7 +723,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( if clientDisconnected { return nil } - clientMessage := buildOpenAIWSHTTPBridgeFailedEvent(responseID, originalModel, bareErrorPayload, bareErrorMessage) + clientMessage := buildOpenAIWSHTTPBridgeFailedEvent(responseID, originalModel, createdAtStamper.Value(), bareErrorPayload, bareErrorMessage) if rewritten, changed := sanitizeOpenAICapacityShedErrorCodeForClient(clientMessage); changed { clientMessage = rewritten } @@ -794,6 +805,9 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( upstreamMessage = corrected } } + if stamped, changed := createdAtStamper.Stamp(upstreamMessage, eventType); changed { + upstreamMessage = stamped + } replayCollector.AddEvent(eventType, upstreamMessage) var upstreamEventErr error diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index da24f4970..1dbcbec11 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -747,7 +747,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( firstClientMessage = s.ReplaceModelInBody(firstClientMessage, capturedSessionModel) } firstMessageResponsesLite := isOpenAIResponsesLiteWebSocketPayload(firstClientMessage) - if normalized, compatibilityChanged, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(firstClientMessage, account, firstMessageResponsesLite); normalizeErr != nil { + if normalized, compatibilityChanged, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(s.cfg, firstClientMessage, account, firstMessageResponsesLite); normalizeErr != nil { return fmt.Errorf("normalize first websocket response.create: %w", normalizeErr) } else if compatibilityChanged { firstClientMessage = normalized @@ -1005,7 +1005,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( responsesLite := isResponseCreate && isOpenAIResponsesLiteWebSocketPayload(payload) if isResponseCreate { payload = normalizeOpenAIRequestLocale(ctx, account, payload, "ws") - if normalized, compatibilityChanged, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(payload, account, responsesLite); normalizeErr != nil { + if normalized, compatibilityChanged, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(s.cfg, payload, account, responsesLite); normalizeErr != nil { return payload, nil, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", normalizeErr) } else if compatibilityChanged { payload = normalized diff --git a/backend/internal/service/ops_upstream_context.go b/backend/internal/service/ops_upstream_context.go index 34b01b0e4..95b726d96 100644 --- a/backend/internal/service/ops_upstream_context.go +++ b/backend/internal/service/ops_upstream_context.go @@ -52,6 +52,14 @@ const ( // ensureForwardErrorResponse 检查此 key,为 true 时跳过兜底写入,避免在已完成的 JSON 后追加 SSE。 ResponseCommittedKey = "response_committed" + // OpsLocalErrorTypeKey / OpsLocalErrorCodeKey 记录网关以 Google 错误格式回写的错误类型与错误码: + // Google 错误体没有 type 字段,ops_error_logger 据此按与 Claude / OpenAI 格式错误相同的口径分类。 + OpsLocalErrorTypeKey = "ops_local_error_type" + OpsLocalErrorCodeKey = "ops_local_error_code" + // OpsRequestScopedErrorKey 标记失败由请求内容决定(如引用的显式缓存不存在):只按错误类型分类, + // 上游错误上下文保留为明细但不参与归因。 + OpsRequestScopedErrorKey = "ops_request_scoped_error" + OpsClientBusinessLimitedKey = "ops_client_business_limited" OpsClientBusinessLimitedReasonKey = "ops_client_business_limited_reason" OpsClientBusinessLimitedReasonIPRestriction = "api_key_ip_restriction" @@ -134,6 +142,42 @@ func OpsClientBusinessLimitedReason(c *gin.Context) string { return strings.TrimSpace(reason) } +// SetOpsLocalErrorType 登记响应错误体缺少的错误类型与错误码,并清除请求级失败标记;errType 为空表示不登记。 +func SetOpsLocalErrorType(c *gin.Context, errType, code string) { + if c == nil { + return + } + c.Set(OpsLocalErrorTypeKey, strings.TrimSpace(errType)) + c.Set(OpsLocalErrorCodeKey, strings.TrimSpace(code)) + c.Set(OpsRequestScopedErrorKey, false) +} + +// OpsLocalErrorType 返回 SetOpsLocalErrorType 登记的错误类型与错误码;未登记时返回空串。 +func OpsLocalErrorType(c *gin.Context) (errType, code string) { + if c == nil { + return "", "" + } + errType = c.GetString(OpsLocalErrorTypeKey) + if errType == "" { + return "", "" + } + return errType, c.GetString(OpsLocalErrorCodeKey) +} + +// MarkOpsRequestScopedError 登记错误类型,并标记失败由请求内容决定:上游错误上下文不参与 ops 归因。 +func MarkOpsRequestScopedError(c *gin.Context, errType string) { + if c == nil { + return + } + SetOpsLocalErrorType(c, errType, "") + c.Set(OpsRequestScopedErrorKey, true) +} + +// IsOpsRequestScopedError 判断 MarkOpsRequestScopedError 是否标记了本次请求的失败。 +func IsOpsRequestScopedError(c *gin.Context) bool { + return c != nil && c.GetBool(OpsRequestScopedErrorKey) +} + // OpsStreamError 描述承载在 2xx 响应上的带内错误:网关在响应状态已固化为 200 之后 // 就地以 SSE error 帧返回的错误(并发限流回退、Wait 后二次计费校验失败、流开始后才无 // 可用账号等),以及上游 2xx 正文或事件里携带的错误结果(NonStream 标记非流式正文)。 diff --git a/backend/internal/service/payment_config_plans.go b/backend/internal/service/payment_config_plans.go index 2356a78d3..b5b8acba9 100644 --- a/backend/internal/service/payment_config_plans.go +++ b/backend/internal/service/payment_config_plans.go @@ -86,6 +86,9 @@ type PlanGroupInfo struct { WeeklyLimitUSD *float64 `json:"weekly_limit_usd"` MonthlyLimitUSD *float64 `json:"monthly_limit_usd"` ModelScopes []string `json:"supported_model_scopes"` + + // 不对外输出;handler 按请求语言用它换出 Name 的译文。 + I18n GroupI18n `json:"-"` } // GetGroupInfoMap returns a map of group_id → PlanGroupInfo for the given plans. @@ -119,6 +122,7 @@ func (s *PaymentConfigService) GetGroupInfoMap(ctx context.Context, plans []*dbe WeeklyLimitUSD: g.WeeklyLimitUsd, MonthlyLimitUSD: g.MonthlyLimitUsd, ModelScopes: g.SupportedModelScopes, + I18n: g.I18n, } } return m diff --git a/backend/internal/service/payment_fulfillment.go b/backend/internal/service/payment_fulfillment.go index 14ff8963f..0960b8413 100644 --- a/backend/internal/service/payment_fulfillment.go +++ b/backend/internal/service/payment_fulfillment.go @@ -18,6 +18,7 @@ import ( "github.com/MACOS-DO/sub4api/ent/paymentorder" "github.com/MACOS-DO/sub4api/internal/payment" infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors" + "github.com/MACOS-DO/sub4api/internal/pkg/servertiming" ) // ErrOrderNotFound is returned by HandlePaymentNotification when the webhook @@ -56,6 +57,33 @@ func (s *PaymentService) HandlePaymentNotification(ctx context.Context, n *payme return s.confirmPayment(ctx, order.ID, n.TradeNo, n.Amount, pk, n.Metadata) } +// ConfirmNotificationUpstream asks providers that implement +// payment.NotificationConfirmer to confirm a verified success notification +// against the upstream order, using the same instance that verified it. +// Failures are recorded on the order's audit trail and returned so the webhook +// answers non-success and the gateway retries. +func (s *PaymentService) ConfirmNotificationUpstream(ctx context.Context, prov payment.Provider, n *payment.PaymentNotification) error { + confirmer, ok := prov.(payment.NotificationConfirmer) + if !ok || n == nil || n.Status != payment.NotificationStatusSuccess { + return nil + } + notifiedTradeNo := n.TradeNo + finishProviderCall := servertiming.ObserveDependency(ctx, "payment") + err := confirmer.ConfirmNotification(ctx, n) + finishProviderCall() + if err == nil { + return nil + } + if order, lookupErr := s.entClient.PaymentOrder.Query().Where(paymentorder.OutTradeNo(n.OrderID)).Only(ctx); lookupErr == nil { + s.writeAuditLog(ctx, order.ID, "PAYMENT_UPSTREAM_UNCONFIRMED", prov.ProviderKey(), map[string]any{ + "detail": err.Error(), + "tradeNo": notifiedTradeNo, + "amount": n.Amount, + }) + } + return err +} + func parseLegacyPaymentOrderID(orderID string, lookupErr error) (int64, bool) { if !dbent.IsNotFound(lookupErr) { return 0, false @@ -218,10 +246,38 @@ func (s *PaymentService) executeFulfillment(ctx context.Context, oid int64) erro if err != nil { return fmt.Errorf("get order: %w", err) } - if o.OrderType == payment.OrderTypeSubscription { + switch o.OrderType { + case payment.OrderTypeSubscription: return s.ExecuteSubscriptionFulfillment(ctx, oid) + case payment.OrderTypeBalance: + return s.ExecuteBalanceFulfillment(ctx, oid) + default: + // 不支持的订单类型不履约:标记 FAILED 后正常返回,避免支付回调持续 500 重试。 + s.rejectUnsupportedOrderType(ctx, o) + return nil + } +} + +func isSupportedPaymentOrderType(orderType string) bool { + return orderType == payment.OrderTypeBalance || orderType == payment.OrderTypeSubscription +} + +func (s *PaymentService) rejectUnsupportedOrderType(ctx context.Context, o *dbent.PaymentOrder) { + reason := "unsupported order type: " + o.OrderType + c, err := s.entClient.PaymentOrder.Update(). + Where( + paymentorder.IDEQ(o.ID), + paymentorder.StatusIn(OrderStatusPaid, OrderStatusRecharging), + ). + SetStatus(OrderStatusFailed).SetFailedAt(time.Now()).SetFailedReason(reason).Save(ctx) + if err != nil { + slog.Error("mark unsupported order type FAILED", "orderID", o.ID, "error", err) + return + } + if c > 0 { + slog.Warn("payment order with unsupported order type not fulfilled", "orderID", o.ID, "orderType", o.OrderType) + s.writeAuditLog(ctx, o.ID, "FULFILLMENT_FAILED", "system", map[string]any{"reason": reason}) } - return s.ExecuteBalanceFulfillment(ctx, oid) } func (s *PaymentService) ExecuteBalanceFulfillment(ctx context.Context, oid int64) error { @@ -229,6 +285,9 @@ func (s *PaymentService) ExecuteBalanceFulfillment(ctx context.Context, oid int6 if err != nil { return infraerrors.NotFound("NOT_FOUND", "order not found") } + if o.OrderType != payment.OrderTypeBalance { + return infraerrors.BadRequest("INVALID_ORDER_TYPE", "order is not a balance order") + } if o.Status == OrderStatusCompleted { return nil } @@ -885,6 +944,9 @@ func (s *PaymentService) RetryFulfillment(ctx context.Context, oid int64) error if o.Status != OrderStatusFailed && o.Status != OrderStatusPaid && o.Status != OrderStatusRecharging { return infraerrors.BadRequest("INVALID_STATUS", "only paid, failed, and recoverable recharging orders can retry") } + if !isSupportedPaymentOrderType(o.OrderType) { + return infraerrors.BadRequest("INVALID_ORDER_TYPE", "unsupported order type") + } s.writeAuditLog(ctx, oid, "RECHARGE_RETRY", "admin", map[string]any{"detail": "admin manual retry"}) return s.executeFulfillment(ctx, oid) } diff --git a/backend/internal/service/payment_notification_confirm_test.go b/backend/internal/service/payment_notification_confirm_test.go new file mode 100644 index 000000000..f1f205daa --- /dev/null +++ b/backend/internal/service/payment_notification_confirm_test.go @@ -0,0 +1,101 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "strconv" + "testing" + "time" + + "github.com/MACOS-DO/sub4api/ent/paymentauditlog" + "github.com/MACOS-DO/sub4api/internal/payment" + "github.com/stretchr/testify/require" +) + +type paymentConfirmTestProvider struct { + paymentFulfillmentTestProvider + err error + calls *int +} + +func (p paymentConfirmTestProvider) ConfirmNotification(_ context.Context, n *payment.PaymentNotification) error { + *p.calls++ + if p.err == nil && n.TradeNo == "" { + n.TradeNo = "upstream-trade" + } + return p.err +} + +func TestConfirmNotificationUpstreamRecordsAuditOnFailure(t *testing.T) { + ctx := context.Background() + client := newPaymentConfigServiceTestClient(t) + user, err := client.User.Create(). + SetEmail("confirm-upstream@example.com"). + SetPasswordHash("hash"). + SetUsername("confirm-upstream-user"). + Save(ctx) + require.NoError(t, err) + order, err := client.PaymentOrder.Create(). + SetUserID(user.ID). + SetUserEmail(user.Email). + SetUserName(user.Username). + SetAmount(10). + SetPayAmount(10). + SetFeeRate(0). + SetRechargeCode("PAY-CONFIRM-UPSTREAM"). + SetOutTradeNo("sub2_confirm_upstream"). + SetPaymentType(payment.TypeAlipay). + SetPaymentTradeNo(""). + SetOrderType(payment.OrderTypeBalance). + SetStatus(OrderStatusPending). + SetExpiresAt(time.Now().Add(time.Hour)). + SetClientIP("127.0.0.1"). + SetSrcHost("api.example.com"). + Save(ctx) + require.NoError(t, err) + + svc := &PaymentService{entClient: client} + calls := 0 + prov := paymentConfirmTestProvider{ + paymentFulfillmentTestProvider: paymentFulfillmentTestProvider{key: payment.TypeEasyPay}, + err: errors.New("easypay confirm: upstream reports order sub2_confirm_upstream as not paid"), + calls: &calls, + } + n := &payment.PaymentNotification{OrderID: order.OutTradeNo, TradeNo: "T-unconfirmed", Amount: 10, Status: payment.NotificationStatusSuccess} + + err = svc.ConfirmNotificationUpstream(ctx, prov, n) + require.Error(t, err) + require.Equal(t, 1, calls) + + count, err := client.PaymentAuditLog.Query(). + Where(paymentauditlog.OrderIDEQ(strconv.FormatInt(order.ID, 10)), paymentauditlog.ActionEQ("PAYMENT_UPSTREAM_UNCONFIRMED")). + Count(ctx) + require.NoError(t, err) + require.Equal(t, 1, count) + + reloaded, err := client.PaymentOrder.Get(ctx, order.ID) + require.NoError(t, err) + require.Equal(t, OrderStatusPending, reloaded.Status) +} + +func TestConfirmNotificationUpstreamPassThrough(t *testing.T) { + svc := &PaymentService{} + n := &payment.PaymentNotification{OrderID: "sub2_x", Amount: 10, Status: payment.NotificationStatusSuccess} + + // Providers without the confirmer capability keep their existing flow. + require.NoError(t, svc.ConfirmNotificationUpstream(context.Background(), paymentFulfillmentTestProvider{key: payment.TypeStripe}, n)) + + calls := 0 + prov := paymentConfirmTestProvider{paymentFulfillmentTestProvider: paymentFulfillmentTestProvider{key: payment.TypeEasyPay}, calls: &calls} + + // Non-success notifications are never fulfilled, so they are not queried. + failed := &payment.PaymentNotification{OrderID: "sub2_x", Status: payment.ProviderStatusFailed} + require.NoError(t, svc.ConfirmNotificationUpstream(context.Background(), prov, failed)) + require.Equal(t, 0, calls) + + require.NoError(t, svc.ConfirmNotificationUpstream(context.Background(), prov, n)) + require.Equal(t, 1, calls) + require.Equal(t, "upstream-trade", n.TradeNo) +} diff --git a/backend/internal/service/payment_order.go b/backend/internal/service/payment_order.go index a4948f060..642a3f697 100644 --- a/backend/internal/service/payment_order.go +++ b/backend/internal/service/payment_order.go @@ -120,11 +120,16 @@ func (s *PaymentService) CreateOrder(ctx context.Context, req CreateOrderRequest } func (s *PaymentService) validateOrderInput(ctx context.Context, req CreateOrderRequest, cfg *PaymentConfig) (*dbent.SubscriptionPlan, error) { - if req.OrderType == payment.OrderTypeBalance && cfg.BalanceDisabled { - return nil, infraerrors.Forbidden("BALANCE_PAYMENT_DISABLED", "balance recharge has been disabled") - } - if req.OrderType == payment.OrderTypeSubscription { + // 订单类型必须走白名单:未知类型会跳过充值开关与倍率计算,履约时却仍按余额到账。 + switch req.OrderType { + case payment.OrderTypeBalance: + if cfg.BalanceDisabled { + return nil, infraerrors.Forbidden("BALANCE_PAYMENT_DISABLED", "balance recharge has been disabled") + } + case payment.OrderTypeSubscription: return s.validateSubOrder(ctx, req) + default: + return nil, infraerrors.BadRequest("INVALID_ORDER_TYPE", "unsupported order type") } if math.IsNaN(req.Amount) || math.IsInf(req.Amount, 0) || req.Amount <= 0 { return nil, infraerrors.BadRequest("INVALID_AMOUNT", "amount must be a positive number") diff --git a/backend/internal/service/payment_order_type_test.go b/backend/internal/service/payment_order_type_test.go new file mode 100644 index 000000000..a6a3775de --- /dev/null +++ b/backend/internal/service/payment_order_type_test.go @@ -0,0 +1,80 @@ +//go:build unit + +package service + +import ( + "context" + "strconv" + "testing" + "time" + + "github.com/MACOS-DO/sub4api/ent/paymentauditlog" + "github.com/MACOS-DO/sub4api/internal/payment" + infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +func TestValidateOrderInputRejectsUnknownOrderType(t *testing.T) { + svc := &PaymentService{} + for _, orderType := range []string{"x", "Balance", " balance", "subscription "} { + for _, disabled := range []bool{false, true} { + cfg := &PaymentConfig{BalanceDisabled: disabled} + plan, err := svc.validateOrderInput(context.Background(), CreateOrderRequest{OrderType: orderType, Amount: 10}, cfg) + require.Nil(t, plan) + require.Error(t, err, "order type %q must be rejected", orderType) + require.Equal(t, "INVALID_ORDER_TYPE", infraerrors.Reason(err), "order type %q", orderType) + } + } +} + +func TestValidateOrderInputKeepsBalanceDisabledSwitch(t *testing.T) { + svc := &PaymentService{} + _, err := svc.validateOrderInput(context.Background(), CreateOrderRequest{OrderType: payment.OrderTypeBalance, Amount: 10}, &PaymentConfig{BalanceDisabled: true}) + require.Equal(t, "BALANCE_PAYMENT_DISABLED", infraerrors.Reason(err)) + + plan, err := svc.validateOrderInput(context.Background(), CreateOrderRequest{OrderType: payment.OrderTypeBalance, Amount: 10}, &PaymentConfig{}) + require.NoError(t, err) + require.Nil(t, plan) +} + +func TestFulfillmentRejectsUnknownOrderType(t *testing.T) { + ctx := context.Background() + client := newPaymentConfigServiceTestClient(t) + order := createPaymentFulfillmentSubscriptionOrder(t, ctx, client, OrderStatusPaid, time.Now()) + order, err := client.PaymentOrder.UpdateOneID(order.ID). + SetOrderType("x"). + ClearPlanID(). + ClearSubscriptionGroupID(). + ClearSubscriptionDays(). + Save(ctx) + require.NoError(t, err) + + userRepo := &mockUserRepo{getByIDUser: &User{ID: order.UserID}} + userRepo.updateBalanceFn = func(context.Context, int64, float64) error { + t.Fatal("unknown order type must not credit balance") + return nil + } + svc := &PaymentService{entClient: client, userRepo: userRepo} + + err = svc.ExecuteBalanceFulfillment(ctx, order.ID) + require.Equal(t, "INVALID_ORDER_TYPE", infraerrors.Reason(err)) + + // 不履约,但标记 FAILED 并正常返回,使支付回调得到确认而不是无限重试。 + require.NoError(t, svc.executeFulfillment(ctx, order.ID)) + reloaded, err := client.PaymentOrder.Get(ctx, order.ID) + require.NoError(t, err) + require.Equal(t, OrderStatusFailed, reloaded.Status) + require.NotNil(t, reloaded.FailedReason) + require.Contains(t, *reloaded.FailedReason, "unsupported order type") + + // 回调重试经 alreadyProcessed 再次进入履约:幂等,不重复写审计。 + require.NoError(t, svc.executeFulfillment(ctx, order.ID)) + audits, err := client.PaymentAuditLog.Query(). + Where(paymentauditlog.OrderIDEQ(strconv.FormatInt(order.ID, 10)), paymentauditlog.ActionEQ("FULFILLMENT_FAILED")). + Count(ctx) + require.NoError(t, err) + require.Equal(t, 1, audits) + + err = svc.RetryFulfillment(ctx, order.ID) + require.Equal(t, "INVALID_ORDER_TYPE", infraerrors.Reason(err)) +} diff --git a/backend/internal/service/payment_refund.go b/backend/internal/service/payment_refund.go index a1330b753..502e702a9 100644 --- a/backend/internal/service/payment_refund.go +++ b/backend/internal/service/payment_refund.go @@ -210,7 +210,8 @@ func (s *PaymentService) PrepareRefund(ctx context.Context, oid int64, amt float if err != nil { return nil, nil, infraerrors.NotFound("NOT_FOUND", "order not found") } - ok := []string{OrderStatusCompleted, OrderStatusRefundRequested, OrderStatusRefundPending, OrderStatusRefundFailed} + // REFUND_PENDING 只能通过 QueryAndFinalizeRefund 收敛:重新发起会重复扣减并向网关重复退款。 + ok := []string{OrderStatusCompleted, OrderStatusRefundRequested, OrderStatusRefundFailed} if !psSliceContains(ok, o.Status) { return nil, nil, infraerrors.BadRequest("INVALID_STATUS", "order status does not allow refund") } @@ -295,8 +296,16 @@ func (s *PaymentService) deductAvailableBalance(ctx context.Context, userID int6 return repo.DeductAvailableBalance(ctx, userID, amount) } +// invalidateRefundBalanceCache 退款扣减或归还余额后失效计费缓存,否则网关在缓存 TTL 内仍按旧余额放行。 +func (s *PaymentService) invalidateRefundBalanceCache(ctx context.Context, userID int64) { + if s.redeemService == nil { + return + } + s.redeemService.invalidateRedeemCaches(ctx, userID, &RedeemCode{Type: RedeemTypeBalance}) +} + func (s *PaymentService) ExecuteRefund(ctx context.Context, p *RefundPlan) (*RefundResult, error) { - c, err := s.entClient.PaymentOrder.Update().Where(paymentorder.IDEQ(p.OrderID), paymentorder.StatusIn(OrderStatusCompleted, OrderStatusRefundRequested, OrderStatusRefundPending, OrderStatusRefundFailed)).SetStatus(OrderStatusRefunding).Save(ctx) + c, err := s.entClient.PaymentOrder.Update().Where(paymentorder.IDEQ(p.OrderID), paymentorder.StatusIn(OrderStatusCompleted, OrderStatusRefundRequested, OrderStatusRefundFailed)).SetStatus(OrderStatusRefunding).Save(ctx) if err != nil { return nil, fmt.Errorf("lock: %w", err) } @@ -313,6 +322,7 @@ func (s *PaymentService) ExecuteRefund(ctx context.Context, p *RefundPlan) (*Ref return nil, fmt.Errorf("deduction: %w", err) } p.BalanceToDeduct = deducted + s.invalidateRefundBalanceCache(ctx, p.Order.UserID) } else { slog.Warn("skipping balance deduction on retry (previous rollback failed)", "orderID", p.OrderID) p.BalanceToDeduct = 0 @@ -436,31 +446,37 @@ func (s *PaymentService) QueryAndFinalizeRefund(ctx context.Context, oid int64) return nil, infraerrors.BadRequest("REFUND_QUERY_UNSUPPORTED", "this payment provider does not support refund status query; please verify manually") } - pendingDetail := s.latestRefundPendingDetail(ctx, oid) + pendingDetail, err := s.latestRefundPendingDetail(ctx, oid) + if err != nil { + return nil, err + } finishProviderCall := servertiming.ObserveDependency(ctx, "payment") resp, err := queryProvider.QueryRefund(ctx, payment.RefundQueryRequest{ - TradeNo: o.PaymentTradeNo, - OrderID: o.OutTradeNo, - RefundID: pendingDetail.RefundID, - Amount: formatGatewayRefundAmount(o.RefundAmount, o), + TradeNo: o.PaymentTradeNo, + OrderID: o.OutTradeNo, + RefundID: pendingDetail.RefundID, + Amount: formatGatewayRefundAmount(o.RefundAmount, o), + RequestedAt: pendingDetail.requestedAt, }) finishProviderCall() if err != nil { return nil, fmt.Errorf("query refund: %w", err) } - if err := validateRefundProviderResponse(resp); err != nil { - return s.finalizeRefundFailed(ctx, o, err) - } - plan := s.refundFinalizePlan(o) - if !pendingDetail.DeductionRollbackOK { + switch { + case pendingDetail.DeductionHeld: + pendingDetail.applyTo(plan) + case !pendingDetail.DeductionRollbackOK: plan.BalanceToDeduct = 0 plan.SubDaysToDeduct = 0 - } else if o.OrderType == payment.OrderTypeSubscription { + case o.OrderType == payment.OrderTypeSubscription: if early := s.prepDeduct(ctx, o, plan, true); early != nil { return early, nil } } + if err := validateRefundProviderResponse(resp); err != nil { + return s.finalizeRefundFailed(ctx, plan, err) + } switch strings.TrimSpace(resp.Status) { case payment.ProviderStatusSuccess, payment.ProviderStatusRefunded: return s.finalizePendingRefundSuccess(ctx, plan) @@ -468,7 +484,7 @@ func (s *PaymentService) QueryAndFinalizeRefund(ctx context.Context, oid int64) s.writeAuditLog(ctx, oid, "REFUND_QUERY_PENDING", "admin", map[string]any{"refundID": resp.RefundID}) return &RefundResult{Success: false, Warning: "gateway refund is still pending confirmation"}, nil default: - return s.finalizeRefundFailed(ctx, o, fmt.Errorf("payment refund returned unknown status: %s", strings.TrimSpace(resp.Status))) + return s.finalizeRefundFailed(ctx, plan, fmt.Errorf("payment refund returned unknown status: %s", strings.TrimSpace(resp.Status))) } } @@ -505,6 +521,9 @@ func (s *PaymentService) finalizePendingRefundSuccess(ctx context.Context, p *Re if err = tx.Commit(); err != nil { return nil, fmt.Errorf("commit refund finalization: %w", err) } + if !p.deductionHeld && p.DeductionType == payment.DeductionTypeBalance && p.BalanceToDeduct > 0 { + s.invalidateRefundBalanceCache(ctx, p.Order.UserID) + } return result, nil } @@ -533,6 +552,10 @@ func (s *PaymentService) refundFinalizePlan(o *dbent.PaymentOrder) *RefundPlan { } func (s *PaymentService) applyRefundFinalDeduction(ctx context.Context, p *RefundPlan) error { + if p.deductionHeld { + // 进入 pending 时扣减已保留,终态成功无需再扣。 + return nil + } if p.DeductionType == payment.DeductionTypeBalance && p.BalanceToDeduct > 0 { deducted, err := s.deductAvailableBalance(ctx, p.Order.UserID, p.BalanceToDeduct) if err != nil { @@ -554,30 +577,164 @@ func (s *PaymentService) applyRefundFinalDeduction(ctx context.Context, p *Refun return nil } -func (s *PaymentService) finalizeRefundFailed(ctx context.Context, o *dbent.PaymentOrder, gErr error) (*RefundResult, error) { - now := time.Now() - _, _ = s.entClient.PaymentOrder.UpdateOneID(o.ID).SetStatus(OrderStatusRefundFailed).SetFailedAt(now).SetFailedReason(psErrMsg(gErr)).Save(ctx) - s.writeAuditLog(ctx, o.ID, "REFUND_FAILED", "admin", map[string]any{"detail": psErrMsg(gErr)}) - return &RefundResult{Success: false, Warning: "gateway refund failed: " + psErrMsg(gErr)}, nil +// finalizeRefundFailed 将 REFUND_PENDING 收敛为 REFUND_FAILED,并归还进入 pending 时保留的扣减。 +// 认领状态、归还扣减与审计在同一事务内完成:两者分开提交时,进程在中间退出会留下 +// 已失败但扣减未归还、且没有 REFUND_ROLLBACK_FAILED 标记的订单,重试退款会再扣一次。 +func (s *PaymentService) finalizeRefundFailed(ctx context.Context, p *RefundPlan, gErr error) (*RefundResult, error) { + warning := "gateway refund failed: " + psErrMsg(gErr) + returnErr, err := s.finalizeRefundFailedTx(ctx, p, gErr, nil) + if err != nil { + return nil, err + } + if returnErr == nil { + if p.deductionHeld && p.DeductionType == payment.DeductionTypeBalance && p.BalanceToDeduct > 0 { + s.invalidateRefundBalanceCache(ctx, p.Order.UserID) + } + return &RefundResult{Success: false, Warning: warning}, nil + } + + // 归还失败(整个事务已回滚,订单仍为 REFUND_PENDING):仍收敛为 REFUND_FAILED, + // 并同事务写入 REFUND_ROLLBACK_FAILED,使重试退款跳过扣减,避免二次扣减。 + slog.Error("[CRITICAL] refund failed but held deduction could not be returned", "orderID", p.OrderID, "error", returnErr) + if _, err := s.finalizeRefundFailedTx(ctx, p, gErr, returnErr); err != nil { + return nil, err + } + return &RefundResult{Success: false, Warning: warning + "; refund deduction rollback failed"}, nil +} + +// finalizeRefundFailedTx 在单个事务内认领 REFUND_PENDING → REFUND_FAILED。rollbackErr 为 nil 时同事务 +// 归还保留的扣减,归还失败则回滚整个事务并通过 returnErr 返回;rollbackErr 非 nil 时不再归还, +// 改为同事务记录 REFUND_ROLLBACK_FAILED。 +func (s *PaymentService) finalizeRefundFailedTx(ctx context.Context, p *RefundPlan, gErr, rollbackErr error) (returnErr error, err error) { + tx, err := s.entClient.Tx(ctx) + if err != nil { + return nil, fmt.Errorf("begin refund failure finalization: %w", err) + } + committed := false + defer func() { + if !committed { + _ = tx.Rollback() + } + }() + txCtx := dbent.NewTxContext(ctx, tx) + + claimed, err := tx.PaymentOrder.Update(). + Where(paymentorder.IDEQ(p.OrderID), paymentorder.StatusEQ(OrderStatusRefundPending)). + SetStatus(OrderStatusRefundFailed). + SetFailedAt(time.Now()). + SetFailedReason(psErrMsg(gErr)). + Save(txCtx) + if err != nil { + return nil, fmt.Errorf("mark refund failed: %w", err) + } + if claimed == 0 { + return nil, infraerrors.Conflict("CONFLICT", "order status changed") + } + + if p.deductionHeld && rollbackErr == nil { + if err := s.returnHeldRefundDeduction(txCtx, p); err != nil { + return err, nil + } + } + if rollbackErr != nil { + if err := createPaymentAuditLogTx(txCtx, tx.Client(), p.OrderID, "REFUND_ROLLBACK_FAILED", map[string]any{ + "gatewayError": psErrMsg(gErr), + "rollbackError": psErrMsg(rollbackErr), + "balanceDeducted": p.BalanceToDeduct, + "subDaysDeducted": p.SubDaysToDeduct, + }); err != nil { + return nil, err + } + } + if err := createPaymentAuditLogTx(txCtx, tx.Client(), p.OrderID, "REFUND_FAILED", map[string]any{"detail": psErrMsg(gErr)}); err != nil { + return nil, err + } + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit refund failure finalization: %w", err) + } + committed = true + return nil, nil } +// returnHeldRefundDeduction 归还进入 REFUND_PENDING 时保留的扣减;ctx 携带事务时随事务提交或回滚。 +func (s *PaymentService) returnHeldRefundDeduction(ctx context.Context, p *RefundPlan) error { + if p.DeductionType == payment.DeductionTypeBalance && p.BalanceToDeduct > 0 { + if err := s.userRepo.UpdateBalance(ctx, p.Order.UserID, p.BalanceToDeduct); err != nil { + return fmt.Errorf("return held balance deduction: %w", err) + } + } + if p.DeductionType == payment.DeductionTypeSubscription && p.SubDaysToDeduct > 0 && p.SubscriptionID > 0 { + if _, err := s.subscriptionSvc.ExtendSubscription(ctx, p.SubscriptionID, p.SubDaysToDeduct); err != nil { + return fmt.Errorf("return held subscription deduction: %w", err) + } + } + return nil +} + +func createPaymentAuditLogTx(ctx context.Context, client *dbent.Client, oid int64, action string, detail map[string]any) error { + raw, err := json.Marshal(detail) + if err != nil { + return fmt.Errorf("marshal %s audit: %w", action, err) + } + if _, err := client.PaymentAuditLog.Create(). + SetOrderID(strconv.FormatInt(oid, 10)). + SetAction(action). + SetDetail(string(raw)). + SetOperator("admin"). + Save(ctx); err != nil { + return fmt.Errorf("write %s audit: %w", action, err) + } + return nil +} + +// refundPendingAuditDetail 记录在 REFUND_PENDING 审计日志中。DeductionHeld 为 true 表示 +// 进入 pending 时扣减被保留;旧记录没有该字段,扣减已在 pending 时归还(DeductionRollbackOK)。 type refundPendingAuditDetail struct { - RefundID string `json:"refundID"` - DeductionRollbackOK bool `json:"deductionRollbackOK"` + RefundID string `json:"refundID"` + RefundAmount float64 `json:"refundAmount"` + Reason string `json:"reason"` + Force bool `json:"force"` + DeductionRollbackOK bool `json:"deductionRollbackOK,omitempty"` + DeductionHeld bool `json:"deductionHeld,omitempty"` + DeductionType string `json:"deductionType,omitempty"` + BalanceDeducted float64 `json:"balanceDeducted"` + SubDaysDeducted int `json:"subDaysDeducted"` + SubscriptionID int64 `json:"subscriptionID,omitempty"` + // requestedAt 取自审计记录的创建时间,不参与序列化。 + requestedAt time.Time } -func (s *PaymentService) latestRefundPendingDetail(ctx context.Context, oid int64) refundPendingAuditDetail { +func (d refundPendingAuditDetail) applyTo(p *RefundPlan) { + p.deductionHeld = true + p.DeductionType = d.DeductionType + if p.DeductionType == "" { + p.DeductionType = payment.DeductionTypeNone + } + p.BalanceToDeduct = d.BalanceDeducted + p.SubDaysToDeduct = d.SubDaysDeducted + p.SubscriptionID = d.SubscriptionID +} + +// latestRefundPendingDetail 读取最近一次 REFUND_PENDING 审计。没有记录视为旧订单(扣减已在 +// pending 时归还);读取或解析失败必须返回错误:误判为旧记录会让保留的扣减被重复扣减或不再归还。 +func (s *PaymentService) latestRefundPendingDetail(ctx context.Context, oid int64) (refundPendingAuditDetail, error) { + detail := refundPendingAuditDetail{DeductionRollbackOK: true} logEntry, err := s.entClient.PaymentAuditLog.Query(). Where(paymentauditlog.OrderIDEQ(strconv.FormatInt(oid, 10)), paymentauditlog.ActionEQ("REFUND_PENDING")). - Order(paymentauditlog.ByCreatedAt(sql.OrderDesc())). + Order(paymentauditlog.ByCreatedAt(sql.OrderDesc()), paymentauditlog.ByID(sql.OrderDesc())). First(ctx) - if err != nil || logEntry == nil { - return refundPendingAuditDetail{DeductionRollbackOK: true} + if err != nil { + if dbent.IsNotFound(err) { + return detail, nil + } + return refundPendingAuditDetail{}, fmt.Errorf("load refund pending audit: %w", err) + } + if err := json.Unmarshal([]byte(logEntry.Detail), &detail); err != nil { + return refundPendingAuditDetail{}, fmt.Errorf("parse refund pending audit: %w", err) } - detail := refundPendingAuditDetail{DeductionRollbackOK: true} - _ = json.Unmarshal([]byte(logEntry.Detail), &detail) detail.RefundID = strings.TrimSpace(detail.RefundID) - return detail + detail.requestedAt = logEntry.CreatedAt + return detail, nil } // getRefundProvider creates a provider using the order's original instance config. @@ -644,16 +801,36 @@ func (s *PaymentService) markRefundOkTx(ctx context.Context, client *dbent.Clien return &RefundResult{Success: true, BalanceDeducted: p.BalanceToDeduct, SubDaysDeducted: p.SubDaysToDeduct}, nil } -func (s *PaymentService) markRefundPending(ctx context.Context, p *RefundPlan, resp *payment.RefundResponse) (*RefundResult, error) { - balanceDeducted := p.BalanceToDeduct - subDaysDeducted := p.SubDaysToDeduct - rollbackOK := s.RollbackRefund(ctx, p, nil) - if rollbackOK { - p.BalanceToDeduct = 0 - p.SubDaysToDeduct = 0 +// markRefundPending 在网关未给出终态时保留已执行的扣减:若此时归还,用户可在 pending 期间 +// 消费这部分余额,终态成功时只能扣到剩余余额。网关确认失败后由 finalizeRefundFailed 归还。 +// 订单状态与审计记录同事务写入,确保终态收敛时能读到保留的扣减。 +func (s *PaymentService) markRefundPending(ctx context.Context, p *RefundPlan, resp *payment.RefundResponse) (_ *RefundResult, err error) { + detail, err := json.Marshal(refundPendingAuditDetail{ + RefundID: refundResponseID(resp), + RefundAmount: p.RefundAmount, + Reason: p.Reason, + Force: p.Force, + DeductionHeld: true, + DeductionType: p.DeductionType, + BalanceDeducted: p.BalanceToDeduct, + SubDaysDeducted: p.SubDaysToDeduct, + SubscriptionID: p.SubscriptionID, + }) + if err != nil { + return nil, fmt.Errorf("marshal refund pending audit: %w", err) } - _, err := s.entClient.PaymentOrder.UpdateOneID(p.OrderID). + tx, err := s.entClient.Tx(ctx) + if err != nil { + return nil, fmt.Errorf("begin mark refund pending: %w", err) + } + defer func() { + if err != nil { + _ = tx.Rollback() + slog.Error("[CRITICAL] gateway refund pending but order not marked", "orderID", p.OrderID, "error", err) + } + }() + _, err = tx.PaymentOrder.UpdateOneID(p.OrderID). SetStatus(OrderStatusRefundPending). SetRefundAmount(p.RefundAmount). SetRefundReason(p.Reason). @@ -665,25 +842,18 @@ func (s *PaymentService) markRefundPending(ctx context.Context, p *RefundPlan, r if err != nil { return nil, fmt.Errorf("mark refund pending: %w", err) } - - detail := map[string]any{ - "refundID": refundResponseID(resp), - "refundAmount": p.RefundAmount, - "reason": p.Reason, - "force": p.Force, - "balanceDeducted": p.BalanceToDeduct, - "subDaysDeducted": p.SubDaysToDeduct, - "balanceRolledBack": balanceDeducted, - "subDaysRolledBack": subDaysDeducted, - "deductionRollbackOK": rollbackOK, + if _, err = tx.PaymentAuditLog.Create(). + SetOrderID(strconv.FormatInt(p.OrderID, 10)). + SetAction("REFUND_PENDING"). + SetDetail(string(detail)). + SetOperator("admin"). + Save(ctx); err != nil { + return nil, fmt.Errorf("write refund pending audit: %w", err) } - s.writeAuditLog(ctx, p.OrderID, "REFUND_PENDING", "admin", detail) - - warning := "gateway refund is pending confirmation" - if !rollbackOK { - warning += "; refund deduction rollback failed" + if err = tx.Commit(); err != nil { + return nil, fmt.Errorf("commit mark refund pending: %w", err) } - return &RefundResult{Success: false, Warning: warning}, nil + return &RefundResult{Success: false, Warning: "gateway refund is pending confirmation"}, nil } func refundResponseID(resp *payment.RefundResponse) string { @@ -700,6 +870,7 @@ func (s *PaymentService) RollbackRefund(ctx context.Context, p *RefundPlan, gErr s.writeAuditLog(ctx, p.OrderID, "REFUND_ROLLBACK_FAILED", "admin", map[string]any{"gatewayError": psErrMsg(gErr), "rollbackError": psErrMsg(err), "balanceDeducted": p.BalanceToDeduct}) return false } + s.invalidateRefundBalanceCache(ctx, p.Order.UserID) } if p.DeductionType == payment.DeductionTypeSubscription && p.SubDaysToDeduct > 0 && p.SubscriptionID > 0 { if _, err := s.subscriptionSvc.ExtendSubscription(ctx, p.SubscriptionID, p.SubDaysToDeduct); err != nil { diff --git a/backend/internal/service/payment_refund_pending_hold_test.go b/backend/internal/service/payment_refund_pending_hold_test.go new file mode 100644 index 000000000..9e70404a9 --- /dev/null +++ b/backend/internal/service/payment_refund_pending_hold_test.go @@ -0,0 +1,312 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "math" + "strconv" + "testing" + "time" + + dbent "github.com/MACOS-DO/sub4api/ent" + "github.com/MACOS-DO/sub4api/ent/paymentauditlog" + "github.com/MACOS-DO/sub4api/internal/payment" + infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +type pendingRefundProviderTestDouble struct { + refundProviderTestDouble + queryStatus string + refundCalls int +} + +func (p *pendingRefundProviderTestDouble) Refund(context.Context, payment.RefundRequest) (*payment.RefundResponse, error) { + p.refundCalls++ + return &payment.RefundResponse{RefundID: "rf_hold", Status: payment.ProviderStatusPending}, nil +} + +func (p *pendingRefundProviderTestDouble) QueryRefund(context.Context, payment.RefundQueryRequest) (*payment.RefundResponse, error) { + return &payment.RefundResponse{RefundID: "rf_hold", Status: p.queryStatus}, nil +} + +// refundHoldWallet 模拟用户余额:DeductAvailableBalance 只能扣到当前余额。 +type refundHoldWallet struct { + balance float64 + deductCalls int + restoreCalls int +} + +func (w *refundHoldWallet) repo(userID int64) *mockUserRepo { + return &mockUserRepo{ + getByIDUser: &User{ID: userID, Balance: w.balance}, + deductAvailableBalanceFn: func(_ context.Context, _ int64, amount float64) (float64, error) { + w.deductCalls++ + deducted := math.Min(amount, math.Max(w.balance, 0)) + w.balance -= deducted + return deducted, nil + }, + updateBalanceFn: func(_ context.Context, _ int64, amount float64) error { + w.restoreCalls++ + w.balance += amount + return nil + }, + } +} + +func TestRefundPendingKeepsBalanceDeductedUntilGatewaySettles(t *testing.T) { + for _, tc := range []struct { + name string + queryStatus string + wantStatus string + wantBalance float64 + wantRestore int + }{ + {name: "gateway succeeds", queryStatus: payment.ProviderStatusSuccess, wantStatus: OrderStatusRefunded, wantBalance: 0}, + {name: "gateway fails", queryStatus: payment.ProviderStatusFailed, wantStatus: OrderStatusRefundFailed, wantBalance: 100, wantRestore: 1}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + client := newPaymentConfigServiceTestClient(t) + order := createCompletedRefundableOrderForTest(t, ctx, client, "hold-flow") + + wallet := &refundHoldWallet{balance: 100} + prov := &pendingRefundProviderTestDouble{queryStatus: tc.queryStatus} + restore := replacePaymentProviderFactoryForTest(t, prov) + defer restore() + svc := &PaymentService{entClient: client, loadBalancer: &captureLoadBalancer{}, userRepo: wallet.repo(order.UserID)} + + plan, early, err := svc.PrepareRefund(ctx, order.ID, 0, "user asked", false, true) + require.NoError(t, err) + require.Nil(t, early) + result, err := svc.ExecuteRefund(ctx, plan) + require.NoError(t, err) + require.False(t, result.Success) + require.Contains(t, result.Warning, "pending confirmation") + + // pending 期间余额必须保持扣减,否则用户可先消费再等网关退款成功。 + require.Zero(t, wallet.balance) + require.Zero(t, wallet.restoreCalls) + reloaded, err := client.PaymentOrder.Get(ctx, order.ID) + require.NoError(t, err) + require.Equal(t, OrderStatusRefundPending, reloaded.Status) + + // pending 订单不能再次发起退款(会重复扣减并重复调用网关)。 + _, _, err = svc.PrepareRefund(ctx, order.ID, 0, "again", true, true) + require.Equal(t, "INVALID_STATUS", infraerrors.Reason(err)) + + result, err = svc.QueryAndFinalizeRefund(ctx, order.ID) + require.NoError(t, err) + require.Equal(t, tc.queryStatus == payment.ProviderStatusSuccess, result.Success) + if result.Success { + require.Equal(t, 100.0, result.BalanceDeducted) + } + require.Equal(t, 1, wallet.deductCalls, "held deduction must not be applied twice") + require.Equal(t, tc.wantRestore, wallet.restoreCalls) + require.Equal(t, tc.wantBalance, wallet.balance) + require.Equal(t, 1, prov.refundCalls) + + reloaded, err = client.PaymentOrder.Get(ctx, order.ID) + require.NoError(t, err) + require.Equal(t, tc.wantStatus, reloaded.Status) + + _, err = svc.QueryAndFinalizeRefund(ctx, order.ID) + require.Equal(t, "INVALID_STATUS", infraerrors.Reason(err)) + require.Equal(t, tc.wantRestore, wallet.restoreCalls) + }) + } +} + +func TestFinalizeRefundFailedRestoresHeldDeductionOnce(t *testing.T) { + ctx := context.Background() + client := newPaymentConfigServiceTestClient(t) + order := createPendingRefundOrderWithDetailForTest(t, ctx, client, "hold-failed-once", + `{"refundID":"rf_test","deductionHeld":true,"deductionType":"balance","balanceDeducted":60}`) + + wallet := &refundHoldWallet{} + svc := &PaymentService{entClient: client, userRepo: wallet.repo(order.UserID)} + plan := svc.refundFinalizePlan(order) + detail, err := svc.latestRefundPendingDetail(ctx, order.ID) + require.NoError(t, err) + detail.applyTo(plan) + + first, err := svc.finalizeRefundFailed(ctx, plan, context.DeadlineExceeded) + require.NoError(t, err) + require.False(t, first.Success) + second, err := svc.finalizeRefundFailed(ctx, plan, context.DeadlineExceeded) + require.Nil(t, second) + require.Equal(t, "CONFLICT", infraerrors.Reason(err)) + + require.Equal(t, 1, wallet.restoreCalls) + require.Equal(t, 60.0, wallet.balance) +} + +func TestQueryAndFinalizeRefundHeldDeductionWithoutBalanceDeduction(t *testing.T) { + ctx := context.Background() + client := newPaymentConfigServiceTestClient(t) + // 管理员选择不扣余额时,终态收敛也不能按旧逻辑补扣。 + order := createPendingRefundOrderWithDetailForTest(t, ctx, client, "hold-no-deduct", + `{"refundID":"rf_test","deductionHeld":true,"deductionType":"none","balanceDeducted":0}`) + + wallet := &refundHoldWallet{balance: 100} + restore := replacePaymentProviderFactoryForTest(t, &pendingRefundProviderTestDouble{queryStatus: payment.ProviderStatusSuccess}) + defer restore() + svc := &PaymentService{entClient: client, loadBalancer: &captureLoadBalancer{}, userRepo: wallet.repo(order.UserID)} + + result, err := svc.QueryAndFinalizeRefund(ctx, order.ID) + require.NoError(t, err) + require.True(t, result.Success) + require.Zero(t, wallet.deductCalls) + require.Equal(t, 100.0, wallet.balance) +} + +type successRefundProviderTestDouble struct { + refundProviderTestDouble + refundCalls int +} + +func (p *successRefundProviderTestDouble) Refund(context.Context, payment.RefundRequest) (*payment.RefundResponse, error) { + p.refundCalls++ + return &payment.RefundResponse{RefundID: "rf_retry", Status: payment.ProviderStatusSuccess}, nil +} + +func countRefundAuditsForTest(t *testing.T, ctx context.Context, client *dbent.Client, orderID int64, action string) int { + t.Helper() + n, err := client.PaymentAuditLog.Query(). + Where(paymentauditlog.OrderIDEQ(strconv.FormatInt(orderID, 10)), paymentauditlog.ActionEQ(action)). + Count(ctx) + require.NoError(t, err) + return n +} + +func TestFinalizeRefundFailedRecordsRollbackFailureWhenHeldDeductionCannotBeReturned(t *testing.T) { + ctx := context.Background() + client := newPaymentConfigServiceTestClient(t) + order := createPendingRefundOrderWithDetailForTest(t, ctx, client, "hold-return-fails", + `{"refundID":"rf_test","deductionHeld":true,"deductionType":"balance","balanceDeducted":60}`) + + wallet := &refundHoldWallet{balance: 40} + repo := wallet.repo(order.UserID) + repo.updateBalanceFn = func(context.Context, int64, float64) error { + wallet.restoreCalls++ + return errors.New("db unavailable") + } + restore := replacePaymentProviderFactoryForTest(t, &pendingRefundProviderTestDouble{queryStatus: payment.ProviderStatusFailed}) + defer restore() + svc := &PaymentService{entClient: client, loadBalancer: &captureLoadBalancer{}, userRepo: repo} + + result, err := svc.QueryAndFinalizeRefund(ctx, order.ID) + require.NoError(t, err) + require.False(t, result.Success) + require.Contains(t, result.Warning, "refund deduction rollback failed") + require.Equal(t, 1, wallet.restoreCalls) + require.Equal(t, 40.0, wallet.balance) + + reloaded, err := client.PaymentOrder.Get(ctx, order.ID) + require.NoError(t, err) + require.Equal(t, OrderStatusRefundFailed, reloaded.Status) + require.Equal(t, 1, countRefundAuditsForTest(t, ctx, client, order.ID, "REFUND_ROLLBACK_FAILED")) + require.Equal(t, 1, countRefundAuditsForTest(t, ctx, client, order.ID, "REFUND_FAILED")) + + // 扣减仍被保留:重试退款必须跳过扣减,否则同一笔退款会扣两次。 + retryProvider := &successRefundProviderTestDouble{} + restoreRetry := replacePaymentProviderFactoryForTest(t, retryProvider) + defer restoreRetry() + plan, early, err := svc.PrepareRefund(ctx, order.ID, 0, "retry", true, true) + require.NoError(t, err) + require.Nil(t, early) + retried, err := svc.ExecuteRefund(ctx, plan) + require.NoError(t, err) + require.True(t, retried.Success) + require.Zero(t, wallet.deductCalls) + require.Equal(t, 40.0, wallet.balance) + require.Equal(t, 1, retryProvider.refundCalls) +} + +func TestFinalizeRefundFailedReturnsHeldDeductionAtomically(t *testing.T) { + ctx := context.Background() + client := newPaymentConfigServiceTestClient(t) + order := createPendingRefundOrderWithDetailForTest(t, ctx, client, "hold-return-atomic", + `{"refundID":"rf_test","deductionHeld":true,"deductionType":"balance","balanceDeducted":60}`) + + wallet := &refundHoldWallet{} + restore := replacePaymentProviderFactoryForTest(t, &pendingRefundProviderTestDouble{queryStatus: payment.ProviderStatusFailed}) + defer restore() + svc := &PaymentService{entClient: client, loadBalancer: &captureLoadBalancer{}, userRepo: wallet.repo(order.UserID)} + + result, err := svc.QueryAndFinalizeRefund(ctx, order.ID) + require.NoError(t, err) + require.False(t, result.Success) + require.NotContains(t, result.Warning, "rollback failed") + require.Equal(t, 1, wallet.restoreCalls) + require.Equal(t, 60.0, wallet.balance) + require.Equal(t, 1, countRefundAuditsForTest(t, ctx, client, order.ID, "REFUND_FAILED")) + require.Zero(t, countRefundAuditsForTest(t, ctx, client, order.ID, "REFUND_ROLLBACK_FAILED")) +} + +func TestQueryAndFinalizeRefundRejectsUnreadablePendingAudit(t *testing.T) { + ctx := context.Background() + client := newPaymentConfigServiceTestClient(t) + // 审计无法解析时不能退化为旧逻辑:成功会二次扣减,失败会吞掉保留的扣减。 + order := createPendingRefundOrderWithDetailForTest(t, ctx, client, "hold-bad-audit", `not-json`) + + for _, queryStatus := range []string{payment.ProviderStatusSuccess, payment.ProviderStatusFailed} { + wallet := &refundHoldWallet{balance: 100} + restore := replacePaymentProviderFactoryForTest(t, &pendingRefundProviderTestDouble{queryStatus: queryStatus}) + svc := &PaymentService{entClient: client, loadBalancer: &captureLoadBalancer{}, userRepo: wallet.repo(order.UserID)} + + result, err := svc.QueryAndFinalizeRefund(ctx, order.ID) + restore() + require.Error(t, err, queryStatus) + require.Nil(t, result) + require.Zero(t, wallet.deductCalls) + require.Zero(t, wallet.restoreCalls) + require.Equal(t, 100.0, wallet.balance) + } + + reloaded, err := client.PaymentOrder.Get(ctx, order.ID) + require.NoError(t, err) + require.Equal(t, OrderStatusRefundPending, reloaded.Status) +} + +func createCompletedRefundableOrderForTest(t *testing.T, ctx context.Context, client *dbent.Client, suffix string) *dbent.PaymentOrder { + t.Helper() + user, err := client.User.Create(). + SetEmail(suffix + "@example.com"). + SetPasswordHash("hash"). + SetUsername(suffix). + Save(ctx) + require.NoError(t, err) + inst, err := client.PaymentProviderInstance.Create(). + SetProviderKey(payment.TypeStripe). + SetName(suffix + "-provider"). + SetConfig("{}"). + SetSupportedTypes("stripe"). + SetEnabled(true). + SetRefundEnabled(true). + Save(ctx) + require.NoError(t, err) + order, err := client.PaymentOrder.Create(). + SetUserID(user.ID). + SetUserEmail(user.Email). + SetUserName(user.Username). + SetAmount(100). + SetPayAmount(100). + SetFeeRate(0). + SetRechargeCode("REFUND-" + suffix). + SetOutTradeNo("sub2_" + suffix). + SetPaymentType(payment.TypeStripe). + SetPaymentTradeNo("pi_" + suffix). + SetOrderType(payment.OrderTypeBalance). + SetStatus(OrderStatusCompleted). + SetExpiresAt(time.Now().Add(time.Hour)). + SetPaidAt(time.Now()). + SetClientIP("127.0.0.1"). + SetSrcHost("api.example.com"). + SetProviderInstanceID(strconv.FormatInt(inst.ID, 10)). + Save(ctx) + require.NoError(t, err) + return order +} diff --git a/backend/internal/service/payment_refund_test.go b/backend/internal/service/payment_refund_test.go index 07f73ca0c..e4965442e 100644 --- a/backend/internal/service/payment_refund_test.go +++ b/backend/internal/service/payment_refund_test.go @@ -299,7 +299,7 @@ func TestValidateRefundProviderResponseAcceptsPending(t *testing.T) { require.Error(t, validateRefundProviderResponse(nil)) } -func TestFinishRefundPendingMarksOrderPendingAndRollsBackDeduction(t *testing.T) { +func TestFinishRefundPendingMarksOrderPendingAndHoldsDeduction(t *testing.T) { ctx := context.Background() client := newPaymentConfigServiceTestClient(t) @@ -357,8 +357,8 @@ func TestFinishRefundPendingMarksOrderPendingAndRollsBackDeduction(t *testing.T) require.NotNil(t, result) require.False(t, result.Success) require.Contains(t, result.Warning, "pending confirmation") - require.Equal(t, 40.0, rolledBack) - require.Zero(t, plan.BalanceToDeduct) + require.Zero(t, rolledBack, "deduction must stay held while the gateway refund is pending") + require.Equal(t, 40.0, plan.BalanceToDeduct) reloaded, err := client.PaymentOrder.Get(ctx, order.ID) require.NoError(t, err) @@ -373,6 +373,11 @@ func TestFinishRefundPendingMarksOrderPendingAndRollsBackDeduction(t *testing.T) Count(ctx) require.NoError(t, err) require.Equal(t, 1, pendingAudits) + detail, err := svc.latestRefundPendingDetail(ctx, order.ID) + require.NoError(t, err) + require.True(t, detail.DeductionHeld) + require.Equal(t, payment.DeductionTypeBalance, detail.DeductionType) + require.Equal(t, 40.0, detail.BalanceDeducted) successAudits, err := client.PaymentAuditLog.Query(). Where(paymentauditlog.OrderIDEQ(strconv.FormatInt(order.ID, 10)), paymentauditlog.ActionEQ("REFUND_SUCCESS")). Count(ctx) @@ -502,6 +507,26 @@ func TestQueryAndFinalizeRefundFinalizesProviderStatuses(t *testing.T) { } } +func TestQueryAndFinalizeRefundPassesPendingAuditTimeToProvider(t *testing.T) { + ctx := context.Background() + client := newPaymentConfigServiceTestClient(t) + order := createPendingRefundOrderForTest(t, ctx, client, "query-requested-at") + pendingAudit, err := client.PaymentAuditLog.Query(). + Where(paymentauditlog.OrderIDEQ(strconv.FormatInt(order.ID, 10)), paymentauditlog.ActionEQ("REFUND_PENDING")). + Only(ctx) + require.NoError(t, err) + + svc := &PaymentService{entClient: client, loadBalancer: &captureLoadBalancer{}, userRepo: &mockUserRepo{}} + prov := &refundQueryProviderTestDouble{refundResponse: &payment.RefundResponse{RefundID: "rf_test", Status: payment.ProviderStatusPending}} + restore := replacePaymentProviderFactoryForTest(t, prov) + defer restore() + + _, err = svc.QueryAndFinalizeRefund(ctx, order.ID) + require.NoError(t, err) + require.Equal(t, "rf_test", prov.lastQuery.RefundID) + require.True(t, pendingAudit.CreatedAt.Equal(prov.lastQuery.RequestedAt), "RequestedAt = %v, want %v", prov.lastQuery.RequestedAt, pendingAudit.CreatedAt) +} + func TestFinalizePendingRefundSuccessRejectsStaleCallerBeforeSecondDeduction(t *testing.T) { ctx := context.Background() client := newPaymentConfigServiceTestClient(t) @@ -586,6 +611,11 @@ func TestQueryAndFinalizeRefundUnsupportedProviderReturnsClearError(t *testing.T func createPendingRefundOrderForTest(t *testing.T, ctx context.Context, client *dbent.Client, suffix string) *dbent.PaymentOrder { t.Helper() + return createPendingRefundOrderWithDetailForTest(t, ctx, client, suffix, `{"refundID":"rf_test","deductionRollbackOK":true}`) +} + +func createPendingRefundOrderWithDetailForTest(t *testing.T, ctx context.Context, client *dbent.Client, suffix, pendingDetail string) *dbent.PaymentOrder { + t.Helper() user, err := client.User.Create(). SetEmail(suffix + "@example.com"). @@ -631,7 +661,7 @@ func createPendingRefundOrderForTest(t *testing.T, ctx context.Context, client * SetOrderID(strconv.FormatInt(order.ID, 10)). SetAction("REFUND_PENDING"). SetOperator("admin"). - SetDetail(`{"refundID":"rf_test","deductionRollbackOK":true}`). + SetDetail(pendingDetail). Save(ctx) require.NoError(t, err) return order @@ -671,8 +701,10 @@ func (refundProviderTestDouble) Refund(context.Context, payment.RefundRequest) ( type refundQueryProviderTestDouble struct { refundProviderTestDouble refundResponse *payment.RefundResponse + lastQuery payment.RefundQueryRequest } -func (p *refundQueryProviderTestDouble) QueryRefund(context.Context, payment.RefundQueryRequest) (*payment.RefundResponse, error) { +func (p *refundQueryProviderTestDouble) QueryRefund(_ context.Context, req payment.RefundQueryRequest) (*payment.RefundResponse, error) { + p.lastQuery = req return p.refundResponse, nil } diff --git a/backend/internal/service/payment_resume_service.go b/backend/internal/service/payment_resume_service.go index 92366c631..0a30bde66 100644 --- a/backend/internal/service/payment_resume_service.go +++ b/backend/internal/service/payment_resume_service.go @@ -244,7 +244,16 @@ func CanonicalizeReturnURL(raw string, srcHost string, srcURL string) (string, e if parsed.Scheme != "http" && parsed.Scheme != "https" { return "", infraerrors.BadRequest("INVALID_RETURN_URL", "return_url must use http or https") } + // The return URL is handed to payment gateways verbatim: keep it to a + // plain hostname or IP literal and the canonical path, without userinfo. + if parsed.User != nil { + return "", infraerrors.BadRequest("INVALID_RETURN_URL", "return_url must not contain user info") + } + if !isPlainReturnURLHost(parsed.Hostname()) { + return "", infraerrors.BadRequest("INVALID_RETURN_URL", "return_url host is invalid") + } parsed.Fragment = "" + parsed.RawPath = "" // Client-supplied query parameters are dropped: buildPaymentReturnURL adds // its own signed set, and user-controlled pairs such as // "trade_status=TRADE_SUCCESS" inside the signed return_url value can be @@ -264,6 +273,25 @@ func CanonicalizeReturnURL(raw string, srcHost string, srcURL string) (string, e return parsed.String(), nil } +// isPlainReturnURLHost reports whether host is an IP literal or a hostname +// made only of letters, digits, '.', '-' and '_'. +func isPlainReturnURLHost(host string) bool { + if host == "" { + return false + } + if net.ParseIP(host) != nil { + return true + } + for _, c := range host { + switch { + case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', c == '.', c == '-', c == '_': + default: + return false + } + } + return true +} + func allowedReturnURLHost(returnURLHost string, requestHost string, refererURL string) bool { if sameOriginHost(returnURLHost, requestHost) { return true diff --git a/backend/internal/service/payment_resume_service_test.go b/backend/internal/service/payment_resume_service_test.go index 0e81ba9a8..e012ad823 100644 --- a/backend/internal/service/payment_resume_service_test.go +++ b/backend/internal/service/payment_resume_service_test.go @@ -109,6 +109,42 @@ func TestCanonicalizeReturnURLStripsSmuggledTradeStatus(t *testing.T) { } } +func TestCanonicalizeReturnURLRejectsNonPlainHostAndUserinfo(t *testing.T) { + t.Parallel() + + badHost := "a&b=c.example.com" + cases := []struct { + name string + raw string + srcHost string + srcURL string + }{ + {"host matched via referer", "https://" + badHost + "/payment/result", "app.example.com", "https://" + badHost + "/purchase"}, + {"host matched via request host", "https://" + badHost + "/payment/result", badHost, ""}, + {"userinfo", "https://a&b=c@app.example.com/payment/result", "app.example.com", ""}, + } + for _, tc := range cases { + if got, err := CanonicalizeReturnURL(tc.raw, tc.srcHost, tc.srcURL); err == nil { + t.Fatalf("%s: CanonicalizeReturnURL accepted %q", tc.name, got) + } + } +} + +func TestCanonicalizeReturnURLAllowsIPAndPortHosts(t *testing.T) { + t.Parallel() + + for _, raw := range []string{ + "http://127.0.0.1:3000/payment/result", + "http://[::1]:8080/payment/result", + "https://pay_site-1.example.com/payment/result", + } { + parsed, _ := url.Parse(raw) + if _, err := CanonicalizeReturnURL(raw, parsed.Host, ""); err != nil { + t.Fatalf("CanonicalizeReturnURL(%q) returned error: %v", raw, err) + } + } +} + func TestCanonicalizeReturnURLRejectsRelativeURL(t *testing.T) { t.Parallel() diff --git a/backend/internal/service/payment_service.go b/backend/internal/service/payment_service.go index 21379c7c5..240d67ccc 100644 --- a/backend/internal/service/payment_service.go +++ b/backend/internal/service/payment_service.go @@ -134,6 +134,8 @@ type RefundPlan struct { BalanceToDeduct float64 SubDaysToDeduct int SubscriptionID int64 + // deductionHeld 表示扣减已在进入 REFUND_PENDING 前执行并保留,终态收敛时不再重复扣减。 + deductionHeld bool } type RefundResult struct { diff --git a/backend/internal/service/pricing_service.go b/backend/internal/service/pricing_service.go index 484c075b0..5d17f2ea2 100644 --- a/backend/internal/service/pricing_service.go +++ b/backend/internal/service/pricing_service.go @@ -139,6 +139,14 @@ var ( CacheReadInputTokenCost: 0.2e-6, LiteLLMProvider: "anthropic", Mode: "chat", SupportsPromptCaching: true, } + claudeHaiku55FallbackPricing = &LiteLLMModelPricing{ + InputCostPerToken: 1e-7, OutputCostPerToken: 5e-7, + CacheCreationInputTokenCost: 1.25e-7, CacheCreationInputTokenCostAbove1hr: 2e-7, + CacheReadInputTokenCost: 1e-8, + LongContextInputTokenThreshold: 100000, + LongContextInputCostMultiplier: 5, LongContextOutputCostMultiplier: 5, + LiteLLMProvider: "anthropic", Mode: "chat", SupportsPromptCaching: true, + } openAIGPT56SolFallbackPricing = &LiteLLMModelPricing{ InputCostPerToken: 5e-06, InputCostPerTokenPriority: 1e-05, @@ -223,6 +231,9 @@ type LiteLLMModelPricing struct { OutputCostPerImageToken float64 `json:"output_cost_per_image_token"` // 图片输出 token 价格 InputCostPerImageToken float64 `json:"input_cost_per_image_token"` // 图片输入 token 价格(如 gpt-image-2 图片编辑) CacheReadInputImageTokenCost float64 `json:"cache_read_input_image_token_cost"` + // CacheStorageCostPerTokenPerHour 显式上下文缓存存储单价(每 token 每小时,USD),一般由定价覆盖文件提供, + // 配置后优先于内置价(见 BillingService.CacheStoragePricePerTokenHour)。 + CacheStorageCostPerTokenPerHour float64 `json:"cache_storage_cost_per_token_per_hour"` // TokenPricingAbsent 表示源数据中 input/output token 价格均缺失(仅有图片价)。 // 此类条目只可用于图片计费,token 计费必须回退到 fallback 或 fail-closed, @@ -258,6 +269,7 @@ type LiteLLMRawEntry struct { OutputCostPerImageToken *float64 `json:"output_cost_per_image_token"` InputCostPerImageToken *float64 `json:"input_cost_per_image_token"` CacheReadInputImageTokenCost *float64 `json:"cache_read_input_image_token_cost"` + CacheStorageCostPerTokenPerHour *float64 `json:"cache_storage_cost_per_token_per_hour"` } // PricingService 动态价格服务 @@ -730,6 +742,9 @@ func (s *PricingService) parsePricingData(body []byte) (map[string]*LiteLLMModel if entry.CacheReadInputImageTokenCost != nil { pricing.CacheReadInputImageTokenCost = *entry.CacheReadInputImageTokenCost } + if entry.CacheStorageCostPerTokenPerHour != nil { + pricing.CacheStorageCostPerTokenPerHour = *entry.CacheStorageCostPerTokenPerHour + } hasExplicitLongContext := entry.LongContextInputTokenThreshold != nil || entry.LongContextInputCostMultiplier != nil || @@ -1291,10 +1306,10 @@ func (s *PricingService) buildModelLookupCandidates(modelLower string) []string normalized := normalizeModelNameForPricing(modelLower) // A tier-specific entry should take precedence when the pricing catalog gains - // one later. Antigravity's Gemini Flash thinking tiers share the base rate, + // one later. Antigravity's Gemini thinking tiers share the base rate, // so the normalized base remains the fallback after the exact aliases. candidates := rawCandidates - if normalizeGeminiThinkingTierAlias(lastSegment(modelLower)) != lastSegment(modelLower) { + if isAntigravityThinkingTierAlias(lastSegment(modelLower)) { candidates = append(candidates, normalized) } else { // Prefer canonical model names for all other aliases (including models/xxx). @@ -1350,15 +1365,37 @@ func normalizeModelNameForPricing(model string) string { } return canonical } - return normalizeGeminiThinkingTierAlias(model) + return normalizeAntigravityClaudeTierAlias(normalizeGeminiThinkingTierAlias(model)) } -// normalizeGeminiThinkingTierAlias maps Antigravity's Gemini Flash -// thinking-tier model IDs to the public base model. The tier controls reasoning -// behavior, not the published token rate, so this keeps -high/-low/-medium and -// -tiered requests on the corresponding base model's price card. +// normalizeAntigravityClaudeTierAlias maps Antigravity's Claude 5.5 thinking-tier +// model IDs (claude-opus-5-5-high, claude-sonnet-5-5-low, ...) to the public base +// model. Like the Gemini tiers, the suffix selects reasoning depth rather than a +// separate token rate; without this the IDs fall into substring family matching +// and are billed as claude-opus-5 / claude-sonnet-4-5. +func normalizeAntigravityClaudeTierAlias(model string) string { + for _, baseModel := range []string{"claude-opus-5-5", "claude-sonnet-5-5"} { + for _, tier := range []string{"-high", "-low", "-medium"} { + if model == baseModel+tier { + return baseModel + } + } + } + return model +} + +// isAntigravityThinkingTierAlias reports whether model is an Antigravity +// Gemini or Claude thinking-tier alias of a priced base model. +func isAntigravityThinkingTierAlias(model string) bool { + return normalizeGeminiThinkingTierAlias(model) != model || normalizeAntigravityClaudeTierAlias(model) != model +} + +// normalizeGeminiThinkingTierAlias maps Antigravity's Gemini thinking-tier +// model IDs to the public base model. The tier controls reasoning behavior, not +// the published token rate, so this keeps -high/-low/-medium and -tiered +// requests on the corresponding base model's price card. func normalizeGeminiThinkingTierAlias(model string) string { - for _, baseModel := range []string{"gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.8-flash"} { + for _, baseModel := range []string{"gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.8-flash", "gemini-4-argon"} { for _, tier := range []string{"-high", "-low", "-medium", "-tiered"} { if model == baseModel+tier { return baseModel @@ -1396,6 +1433,7 @@ func (s *PricingService) extractBaseName(model string) string { // matchByModelFamily 基于模型系列匹配 func (s *PricingService) matchByModelFamily(model string) *LiteLLMModelPricing { + model = normalizeAntigravityClaudeTierAlias(model) if claude.IsOpus55(model) { if pricing, ok := s.pricingData["claude-opus-5-5"]; ok { return pricing @@ -1408,6 +1446,12 @@ func (s *PricingService) matchByModelFamily(model string) *LiteLLMModelPricing { } return claudeSonnet55FallbackPricing } + if claude.IsHaiku55(model) { + if pricing, ok := s.pricingData["claude-haiku-5-5"]; ok { + return pricing + } + return claudeHaiku55FallbackPricing + } // modelFamily 定义一个模型系列的匹配和定价查找规则。 type modelFamily struct { name string // 系列名称 diff --git a/backend/internal/service/pricing_service_test.go b/backend/internal/service/pricing_service_test.go index 241484c87..14bfe564c 100644 --- a/backend/internal/service/pricing_service_test.go +++ b/backend/internal/service/pricing_service_test.go @@ -613,10 +613,10 @@ func TestBillingService_Gemini36FlashThinkingTierFallbacksAreBillable(t *testing t.Run(model, func(t *testing.T) { cost, err := svc.CalculateCost(model, tokens, 1) require.NoError(t, err) - require.InDelta(t, 1.5, cost.InputCost, 1e-12) - require.InDelta(t, 7.5, cost.OutputCost, 1e-12) - require.InDelta(t, 0.15, cost.CacheReadCost, 1e-12) - require.InDelta(t, 9.15, cost.TotalCost, 1e-12) + require.InDelta(t, 0.75, cost.InputCost, 1e-12) + require.InDelta(t, 3.75, cost.OutputCost, 1e-12) + require.InDelta(t, 0.075, cost.CacheReadCost, 1e-12) + require.InDelta(t, 4.575, cost.TotalCost, 1e-12) }) } } @@ -725,11 +725,98 @@ func TestDefaultPricingIncludesGemini36FlashRates(t *testing.T) { t.Run(model, func(t *testing.T) { pricing, err := billingSvc.GetModelPricing(model) require.NoError(t, err) - require.InDelta(t, 1.5e-6, pricing.InputPricePerToken, 1e-12) - require.InDelta(t, 7.5e-6, pricing.OutputPricePerToken, 1e-12) - require.InDelta(t, 0.15e-6, pricing.CacheReadPricePerToken, 1e-12) + require.InDelta(t, 0.75e-6, pricing.InputPricePerToken, 1e-12) + require.InDelta(t, 3.75e-6, pricing.OutputPricePerToken, 1e-12) + require.InDelta(t, 0.075e-6, pricing.CacheReadPricePerToken, 1e-12) + }) + } +} + +func TestPricingService_Gemini4ArgonThinkingTiersUseBasePricing(t *testing.T) { + basePricing := &LiteLLMModelPricing{InputCostPerToken: 2e-6, OutputCostPerToken: 10e-6, CacheReadInputTokenCost: 0.1e-6} + cyberPricing := &LiteLLMModelPricing{InputCostPerToken: 4e-6, OutputCostPerToken: 20e-6, CacheReadInputTokenCost: 0.2e-6} + svc := &PricingService{pricingData: map[string]*LiteLLMModelPricing{ + "gemini-4-argon": basePricing, + "gemini-4-argon-cyber-permissive": cyberPricing, + }} + + for _, model := range []string{ + "gemini-4-argon", + "gemini-4-argon-high", + "gemini-4-argon-low", + "gemini-4-argon-medium", + "models/gemini-4-argon-high", + "projects/p/locations/global/publishers/google/models/gemini-4-argon", + } { + t.Run(model, func(t *testing.T) { + require.Same(t, basePricing, svc.GetModelPricing(model)) + }) + } + require.Same(t, cyberPricing, svc.GetModelPricing("gemini-4-argon-cyber-permissive")) +} + +func TestBillingService_Gemini4ArgonFallbacksAreBillable(t *testing.T) { + svc := NewBillingService(&config.Config{}, nil) + tokens := UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000, CacheReadTokens: 1_000_000} + + for _, tc := range []struct { + model string + input, output, read float64 + }{ + {"gemini-4-argon", 2, 10, 0.1}, + {"gemini-4-argon-high", 2, 10, 0.1}, + {"gemini-4-argon-low", 2, 10, 0.1}, + {"gemini-4-argon-medium", 2, 10, 0.1}, + {"models/gemini-4-argon", 2, 10, 0.1}, + {"gemini-4-argon-cyber-permissive", 4, 20, 0.2}, + {"gemini-4-argon-cyber", 4, 20, 0.2}, + {"publishers/google/models/gemini-4-argon-cyber-permissive", 4, 20, 0.2}, + } { + t.Run(tc.model, func(t *testing.T) { + cost, err := svc.CalculateCost(tc.model, tokens, 1) + require.NoError(t, err) + require.InDelta(t, tc.input, cost.InputCost, 1e-12) + require.InDelta(t, tc.output, cost.OutputCost, 1e-12) + require.InDelta(t, tc.read, cost.CacheReadCost, 1e-12) + require.InDelta(t, tc.input+tc.output+tc.read, cost.TotalCost, 1e-12) + }) + } +} + +func TestDefaultPricingIncludesGemini4ArgonRates(t *testing.T) { + data, err := os.ReadFile(filepath.Join("..", "..", "resources", "model-pricing", "model_prices_and_context_window.json")) + require.NoError(t, err) + + pricingSvc := &PricingService{} + pricingData, err := pricingSvc.parsePricingData(data) + require.NoError(t, err) + pricingSvc.pricingData = pricingData + + for _, tc := range []struct { + model string + provider string + input, output, read float64 + }{ + {"gemini-4-argon", "gemini", 2e-6, 10e-6, 0.1e-6}, + {"gemini-4-argon-high", "gemini", 2e-6, 10e-6, 0.1e-6}, + {"gemini-4-argon-cyber-permissive", "vertex_ai-language-models", 4e-6, 20e-6, 0.2e-6}, + } { + t.Run(tc.model, func(t *testing.T) { + pricing := pricingSvc.GetModelPricing(tc.model) + require.NotNil(t, pricing) + require.Equal(t, tc.provider, pricing.LiteLLMProvider) + require.InDelta(t, tc.input, pricing.InputCostPerToken, 1e-15) + require.InDelta(t, tc.output, pricing.OutputCostPerToken, 1e-15) + require.InDelta(t, tc.read, pricing.CacheReadInputTokenCost, 1e-15) + // Priority 档为标准价的 1.8 倍;单一价档不分提示词长度,显式缓存不可用故无存储价。 + require.InDelta(t, tc.input*1.8, pricing.InputCostPerTokenPriority, 1e-15) + require.InDelta(t, tc.output*1.8, pricing.OutputCostPerTokenPriority, 1e-15) + require.InDelta(t, tc.read*1.8, pricing.CacheReadInputTokenCostPriority, 1e-15) + require.Zero(t, pricing.LongContextInputTokenThreshold) + require.Zero(t, pricing.CacheStorageCostPerTokenPerHour) }) } + require.Contains(t, pricingSvc.ListModelNamesByProvider("gemini"), "gemini-4-argon") } func TestDefaultPricingUsesCurrentCodexAutoReviewBaseRates(t *testing.T) { @@ -1191,3 +1278,42 @@ func TestCalculateCost_ClaudeSonnetCatalogLadderIsDataDriven(t *testing.T) { require.NoError(t, err) require.False(t, cost.LongContextBillingApplied, "恰好 200000 不进高档(严格大于)") } + +// Antigravity 的 Claude 5.5 思考档位 ID 只决定推理深度,必须按基础型号计价, +// 不能落入子串家族匹配(opus-5-5-high → claude-opus-5、sonnet-5-5-high → sonnet-4-5)。 +func TestPricingService_AntigravityClaude55TiersUseBaseModelPricing(t *testing.T) { + opus := &LiteLLMModelPricing{InputCostPerToken: 4e-6, OutputCostPerToken: 20e-6} + sonnet := &LiteLLMModelPricing{InputCostPerToken: 2e-6, OutputCostPerToken: 10e-6} + svc := &PricingService{pricingData: map[string]*LiteLLMModelPricing{ + "claude-opus-5-5": opus, + "claude-sonnet-5-5": sonnet, + "claude-opus-5": {InputCostPerToken: 5e-6, OutputCostPerToken: 25e-6}, + "claude-sonnet-4-5": {InputCostPerToken: 3e-6, OutputCostPerToken: 15e-6}, + }} + for _, tier := range []string{"high", "medium", "low"} { + require.Same(t, opus, svc.GetModelPricing("claude-opus-5-5-"+tier)) + require.Same(t, sonnet, svc.GetModelPricing("claude-sonnet-5-5-"+tier)) + } + + // 价格目录缺基础型号时走家族兜底,同样不能落到 claude-opus-5 / sonnet-4-5。 + sparse := &PricingService{pricingData: map[string]*LiteLLMModelPricing{ + "claude-opus-5": {InputCostPerToken: 5e-6, OutputCostPerToken: 25e-6}, + "claude-sonnet-4-5": {InputCostPerToken: 3e-6, OutputCostPerToken: 15e-6}, + }} + require.Same(t, claudeOpus55FallbackPricing, sparse.GetModelPricing("claude-opus-5-5-high")) + require.Same(t, claudeSonnet55FallbackPricing, sparse.GetModelPricing("claude-sonnet-5-5-low")) +} + +func TestBillingService_AntigravityClaude55TierFallbacksUseBaseRates(t *testing.T) { + svc := NewBillingService(&config.Config{}, nil) + tokens := UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000} + for _, tier := range []string{"high", "medium", "low"} { + for base, want := range map[string]string{"claude-opus-5-5": "claude-opus-5-5", "claude-sonnet-5-5": "claude-sonnet-5-5"} { + got, err := svc.CalculateCost(base+"-"+tier, tokens, 1) + require.NoError(t, err) + ref, err := svc.CalculateCost(want, tokens, 1) + require.NoError(t, err) + require.InDelta(t, ref.TotalCost, got.TotalCost, 1e-12, base+"-"+tier) + } + } +} diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index b4861c64b..39b1849f9 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -310,8 +310,9 @@ func (s *RateLimitService) CheckErrorPolicy(ctx context.Context, account *Accoun } if account.IsPoolMode() { // 池模式只跳过默认账号状态处理;管理员显式配置的临时不可调度规则仍应生效。 - // 401 保留现有认证错误语义,避免改变重复 401 的升级行为。 - if statusCode != http.StatusUnauthorized && s.tryTempUnschedulable(ctx, account, statusCode, responseBody) { + // 401 只在非凭据级且命中显式模型级规则时由规则处理,其余保留现有认证错误语义。 + if tempUnschedRulesApply(account, statusCode, responseBody, tempUnschedulableModel(ctx, nil)) && + s.tryTempUnschedulable(ctx, account, statusCode, responseBody) { return ErrorPolicyTempUnscheduled } return ErrorPolicySkipped @@ -337,9 +338,10 @@ func (s *RateLimitService) HandleUpstreamError(ctx context.Context, account *Acc customErrorCodesEnabled := account.IsCustomErrorCodesEnabled() // 池模式默认不标记本地账号状态;但管理员显式配置的临时不可调度规则优先。 - // 401 保留现有认证错误语义,不在这里改变池模式的认证处理。 + // 401 只在非凭据级且命中显式模型级规则时由规则处理,其余保留池模式现有的认证处理。 if account.IsPoolMode() && !customErrorCodesEnabled { - if statusCode != http.StatusUnauthorized && s.tryTempUnschedulable(ctx, account, statusCode, responseBody) { + if tempUnschedRulesApply(account, statusCode, responseBody, tempUnschedulableModel(ctx, nil)) && + s.tryTempUnschedulable(ctx, account, statusCode, responseBody) { return true } slog.Info("pool_mode_error_skipped", "account_id", account.ID, "status_code", statusCode) @@ -385,9 +387,9 @@ func (s *RateLimitService) HandleUpstreamError(ctx context.Context, account *Acc } } - // 先尝试临时不可调度规则(401除外) + // 先尝试临时不可调度规则(401 仅限非凭据级且命中显式模型级规则) // 如果匹配成功,直接返回,不执行后续禁用逻辑 - if statusCode != 401 { + if tempUnschedRulesApply(account, statusCode, responseBody, tempUnschedulableModel(ctx, requestedModel)) { if s.tryTempUnschedulable(ctx, account, statusCode, responseBody, firstRequestedModel(requestedModel)) { return true } @@ -2587,6 +2589,62 @@ func firstRequestedModel(requestedModel []string) string { return strings.TrimSpace(requestedModel[0]) } +// tempUnschedRulesApply 决定本次错误是否交给临时不可调度规则处理。 +// 401 默认留给认证错误处理;只有首条命中规则按模型级生效时,才由规则只冷却该模型。 +func tempUnschedRulesApply(account *Account, statusCode int, responseBody []byte, modelKey string) bool { + if statusCode != http.StatusUnauthorized { + return true + } + matches := matchTempUnschedulableRules(account, statusCode, responseBody) + return len(matches) > 0 && tempUnschedHitUsesModelScope(account, matches[0].rule, modelKey, statusCode, responseBody) +} + +// tempUnschedHitUsesModelScope 决定一次命中是否按模型级冷却:凭据级 401 始终按账号处理, +// 其余由规则作用范围决定。 +func tempUnschedHitUsesModelScope(account *Account, rule TempUnschedulableRule, modelKey string, statusCode int, responseBody []byte) bool { + if statusCode == http.StatusUnauthorized && unauthorizedRequiresCredentialHandling(account, responseBody) { + return false + } + return tempUnschedRuleUsesModelScope(rule, modelKey, statusCode) +} + +// unauthorizedRequiresCredentialHandling 识别凭据级 401:OAuth 账号与 Spark 影子 +// (失效缓存、刷新窗口、缺 refresh_token 停用),以及 OpenAI 明确的凭据失效 +// (token_invalidated / token_revoked、{"detail":"Unauthorized"})。 +func unauthorizedRequiresCredentialHandling(account *Account, responseBody []byte) bool { + if account == nil { + return false + } + if account.Type == AccountTypeOAuth || account.IsShadow() { + return true + } + if account.Platform != PlatformOpenAI { + return false + } + switch extractUpstreamErrorCode(responseBody) { + case "token_invalidated", "token_revoked": + return true + } + return gjson.GetBytes(responseBody, "detail").String() == "Unauthorized" +} + +// tempUnschedRuleUsesModelScope 决定一次命中按模型级冷却还是账号级暂停。 +// 显式 scope 完全由规则决定;scope 为空时模型已知且非 401 走模型级。 +// 模型未知时无法隔离,一律账号级。 +func tempUnschedRuleUsesModelScope(rule TempUnschedulableRule, modelKey string, statusCode int) bool { + if strings.TrimSpace(modelKey) == "" { + return false + } + switch rule.Scope { + case TempUnschedScopeAccount: + return false + case TempUnschedScopeModel: + return true + default: + return statusCode != http.StatusUnauthorized + } +} + type tempUnschedulableModelContextKey struct{} func withTempUnschedulableModel(ctx context.Context, requestedModel []string) context.Context { @@ -2651,10 +2709,17 @@ func (s *RateLimitService) tryTempUnschedulable(ctx context.Context, account *Ac if !account.IsTempUnschedulableEnabled() { return false } + matches := matchTempUnschedulableRules(account, statusCode, responseBody) + if len(matches) == 0 { + return false + } + modelKey := tempUnschedulableModel(ctx, requestedModel) // 401 首次命中可临时不可调度(给 token 刷新窗口); // 若历史上已因 401 进入过临时不可调度,则本次应升级为 error(返回 false 交由默认错误逻辑处理)。 // Antigravity 跳过:其 401 由 applyErrorPolicy 的 temp_unschedulable_rules 自行控制,无需升级逻辑。 - if statusCode == http.StatusUnauthorized && account.Platform != PlatformAntigravity { + // 模型级命中只冷却模型、不写账号级状态,不参与升级。 + if statusCode == http.StatusUnauthorized && account.Platform != PlatformAntigravity && + !tempUnschedHitUsesModelScope(account, matches[0].rule, modelKey, statusCode, responseBody) { reason := account.TempUnschedulableReason // 缓存可能没有 reason,从 DB 回退读取 if reason == "" { @@ -2668,8 +2733,8 @@ func (s *RateLimitService) tryTempUnschedulable(ctx context.Context, account *Ac return false } } - for _, match := range matchTempUnschedulableRules(account, statusCode, responseBody) { - if s.triggerTempUnschedulable(ctx, account, match.rule, match.ruleIndex, statusCode, match.matchedKeyword, responseBody, tempUnschedulableModel(ctx, requestedModel)) { + for _, match := range matches { + if s.triggerTempUnschedulable(ctx, account, match.rule, match.ruleIndex, statusCode, match.matchedKeyword, responseBody, modelKey) { return true } } @@ -2719,6 +2784,8 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account now := time.Now() until := now.Add(time.Duration(rule.DurationMinutes) * time.Minute) + modelKey := firstRequestedModel(requestedModel) + modelScoped := tempUnschedHitUsesModelScope(account, rule, modelKey, statusCode, responseBody) state := &TempUnschedState{ UntilUnix: until.Unix(), @@ -2727,6 +2794,11 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account MatchedKeyword: matchedKeyword, RuleIndex: ruleIndex, ErrorMessage: truncateTempUnschedMessage(responseBody, tempUnschedMessageMaxBytes), + Scope: TempUnschedScopeAccount, + } + if modelScoped { + state.Scope = TempUnschedScopeModel + state.Model = modelKey } reason := "" @@ -2737,18 +2809,16 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account reason = strings.TrimSpace(state.ErrorMessage) } - // Persist known-model failures under the model key so the scheduler excludes - // only this (account, model) pair. Authentication and model-unknown failures - // retain the legacy account-wide temporary-unschedulable behavior below. - modelKey := firstRequestedModel(requestedModel) - if modelKey != "" && statusCode != http.StatusUnauthorized { + // Persist model-scoped hits under the model key so the scheduler excludes + // only this (account, model) pair; every other hit pauses the whole account below. + if modelScoped { if err := s.accountRepo.SetModelRateLimit(ctx, account.ID, modelKey, until, reason); err != nil { slog.Warn("temp_unsched_model_rate_limit_set_failed", "account_id", account.ID, "model", modelKey, "error", err) // The rule matched, so fail over the current request even if persistence // failed; never widen a model-scoped failure into an account-wide block. return true } - slog.Info("account_model_temp_unschedulable", "account_id", account.ID, "model", modelKey, "until", until, "rule_index", ruleIndex, "status_code", statusCode) + slog.Info("account_model_temp_unschedulable", "account_id", account.ID, "model", modelKey, "until", until, "rule_index", ruleIndex, "rule_scope", rule.Scope, "status_code", statusCode) return true } @@ -2764,7 +2834,7 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account } } - slog.Info("account_temp_unschedulable", "account_id", account.ID, "until", until, "rule_index", ruleIndex, "status_code", statusCode) + slog.Info("account_temp_unschedulable", "account_id", account.ID, "until", until, "rule_index", ruleIndex, "rule_scope", rule.Scope, "status_code", statusCode) return true } diff --git a/backend/internal/service/temp_unsched.go b/backend/internal/service/temp_unsched.go index 92b7da3f7..67ecb8e70 100644 --- a/backend/internal/service/temp_unsched.go +++ b/backend/internal/service/temp_unsched.go @@ -16,6 +16,8 @@ type TempUnschedState struct { TriggerCount int64 `json:"trigger_count,omitempty"` // 本次触发累计命中次数 TriggerThreshold int `json:"trigger_threshold,omitempty"` // 触发阈值 TriggerWindowMinutes int `json:"trigger_window_minutes,omitempty"` // 计数窗口(分钟) + Scope string `json:"scope,omitempty"` // 隔离粒度:account / model + Model string `json:"model,omitempty"` // 模型级时被冷却的模型键 } // TempUnschedCache 临时不可调度缓存接口 diff --git a/backend/internal/service/temp_unsched_scope_test.go b/backend/internal/service/temp_unsched_scope_test.go new file mode 100644 index 000000000..a586710eb --- /dev/null +++ b/backend/internal/service/temp_unsched_scope_test.go @@ -0,0 +1,493 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/MACOS-DO/sub4api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type tempUnschedScopeRepoStub struct { + modelNotFoundAccountRepoStub + tempReasons []string + errorCalls int +} + +func (r *tempUnschedScopeRepoStub) SetError(context.Context, int64, string) error { + r.errorCalls++ + return nil +} + +func (r *tempUnschedScopeRepoStub) SetTempUnschedulable(_ context.Context, _ int64, _ time.Time, reason string) error { + r.tempCalls++ + r.tempReasons = append(r.tempReasons, reason) + return nil +} + +func newTempUnschedScopeAccount(scope string, extra map[string]any) *Account { + rule := map[string]any{ + "error_code": float64(http.StatusServiceUnavailable), + "keywords": []any{"unavailable"}, + "duration_minutes": float64(10), + } + if scope != "" { + rule["scope"] = scope + } + for k, v := range extra { + rule[k] = v + } + return &Account{ + ID: 202, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "temp_unschedulable_enabled": true, + "temp_unschedulable_rules": []any{rule}, + }, + } +} + +var tempUnschedScopeBody = []byte(`{"error":{"message":"upstream unavailable"}}`) + +var ( + tempUnschedScope401Body = []byte(`{"error":{"message":"unauthorized"}}`) + tempUnschedScopeRevoked401Body = []byte(`{"error":{"code":"token_revoked","message":"unauthorized"}}`) + tempUnschedScopeDetail401Body = []byte(`{"detail":"Unauthorized"}`) + tempUnschedScopePrevious401Mark = `{"status_code":401,"until_unix":1735689600}` +) + +func tempUnschedScope401Rule(scope string) map[string]any { + rule := map[string]any{ + "error_code": float64(http.StatusUnauthorized), + "keywords": []any{"unauthorized"}, + "duration_minutes": float64(10), + } + if scope != "" { + rule["scope"] = scope + } + return rule +} + +func newTempUnschedScope401Account(platform string, scopes ...string) *Account { + account := newTempUnschedScopeAccount("", nil) + account.Platform = platform + rules := make([]any, 0, len(scopes)) + for _, scope := range scopes { + rules = append(rules, tempUnschedScope401Rule(scope)) + } + account.Credentials["temp_unschedulable_rules"] = rules + return account +} + +func TestGetTempUnschedulableRules_ParsesScope(t *testing.T) { + mk := func(keyword string, scope any) map[string]any { + rule := map[string]any{ + "error_code": float64(http.StatusServiceUnavailable), + "keywords": []any{keyword}, + "duration_minutes": float64(1), + } + if scope != nil { + rule["scope"] = scope + } + return rule + } + account := &Account{Credentials: map[string]any{ + "temp_unschedulable_rules": []any{ + mk("a", "account"), + mk("b", " Model "), + mk("c", "whatever"), + mk("d", nil), + }, + }} + + rules := account.GetTempUnschedulableRules() + + require.Len(t, rules, 4) + require.Equal(t, TempUnschedScopeAccount, rules[0].Scope) + require.Equal(t, TempUnschedScopeModel, rules[1].Scope, "大小写与首尾空白应被归一化") + require.Empty(t, rules[2].Scope, "未知取值视为未设置") + require.Empty(t, rules[3].Scope) +} + +func TestTempUnschedRuleUsesModelScope(t *testing.T) { + cases := []struct { + name string + scope string + model string + status int + want bool + }{ + {"缺省 模型已知 非401 走模型级", "", "gpt-5.4", http.StatusServiceUnavailable, true}, + {"缺省 401 走账号级", "", "gpt-5.4", http.StatusUnauthorized, false}, + {"缺省 模型未知 走账号级", "", "", http.StatusServiceUnavailable, false}, + {"显式账号级 模型已知 仍账号级", TempUnschedScopeAccount, "gpt-5.4", http.StatusServiceUnavailable, false}, + {"显式模型级 401 仍模型级", TempUnschedScopeModel, "gpt-5.4", http.StatusUnauthorized, true}, + {"显式模型级 模型未知 兜底账号级", TempUnschedScopeModel, " ", http.StatusServiceUnavailable, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := tempUnschedRuleUsesModelScope(TempUnschedulableRule{Scope: tc.scope}, tc.model, tc.status) + require.Equal(t, tc.want, got) + }) + } +} + +func TestHandleTempUnschedulable_ExplicitAccountScopePausesWholeAccountWithKnownModel(t *testing.T) { + repo := &tempUnschedScopeRepoStub{} + svc := &RateLimitService{accountRepo: repo} + account := newTempUnschedScopeAccount(TempUnschedScopeAccount, nil) + + handled := svc.HandleTempUnschedulable(context.Background(), account, http.StatusServiceUnavailable, tempUnschedScopeBody, "gpt-5.4") + + require.True(t, handled) + require.Equal(t, 1, repo.tempCalls) + require.Empty(t, repo.modelRateLimitCalls) + + var state TempUnschedState + require.NoError(t, json.Unmarshal([]byte(repo.tempReasons[0]), &state)) + require.Equal(t, TempUnschedScopeAccount, state.Scope) + require.Empty(t, state.Model) +} + +func TestCheckErrorPolicy_ExplicitModelScopeKeeps401ModelScoped(t *testing.T) { + repo := &tempUnschedScopeRepoStub{} + svc := &RateLimitService{accountRepo: repo} + account := newTempUnschedScopeAccount(TempUnschedScopeModel, map[string]any{ + "error_code": float64(http.StatusUnauthorized), + "keywords": []any{"unauthorized"}, + }) + + result := svc.CheckErrorPolicy(context.Background(), account, http.StatusUnauthorized, + []byte(`{"error":{"message":"unauthorized"}}`), "gpt-5.4") + + require.Equal(t, ErrorPolicyTempUnscheduled, result) + require.Zero(t, repo.tempCalls, "运营人员显式选了模型级,401 也不应连累整个账号") + require.Len(t, repo.modelRateLimitCalls, 1) + require.Equal(t, "gpt-5.4", repo.modelRateLimitCalls[0].scope) + + var state TempUnschedState + require.NoError(t, json.Unmarshal([]byte(repo.modelRateLimitCalls[0].reason), &state)) + require.Equal(t, TempUnschedScopeModel, state.Scope) + require.Equal(t, "gpt-5.4", state.Model) + require.Equal(t, http.StatusUnauthorized, state.StatusCode) +} + +func TestHandleTempUnschedulable_ExplicitModelScopeFallsBackToAccountWhenModelUnknown(t *testing.T) { + repo := &tempUnschedScopeRepoStub{} + svc := &RateLimitService{accountRepo: repo} + account := newTempUnschedScopeAccount(TempUnschedScopeModel, nil) + + handled := svc.HandleTempUnschedulable(context.Background(), account, http.StatusServiceUnavailable, tempUnschedScopeBody) + + require.True(t, handled) + require.Equal(t, 1, repo.tempCalls) + require.Empty(t, repo.modelRateLimitCalls) +} + +func TestOpenAIFailoverSideEffects_401FollowsTempUnschedScope(t *testing.T) { + cases := []struct { + name string + scopes []string + body []byte + poolMode bool + oauth bool + wantModel bool + wantTemp bool + wantSetError bool + wantBlocked bool + }{ + {name: "显式模型级 只冷却模型", scopes: []string{TempUnschedScopeModel}, wantModel: true}, + {name: "显式模型级 池模式 只冷却模型", scopes: []string{TempUnschedScopeModel}, poolMode: true, wantModel: true}, + {name: "缺省 走认证错误处理", scopes: []string{""}, wantSetError: true, wantBlocked: true}, + {name: "显式账号级 走认证错误处理", scopes: []string{TempUnschedScopeAccount}, wantSetError: true, wantBlocked: true}, + {name: "首条命中为账号级 走认证错误处理", scopes: []string{TempUnschedScopeAccount, TempUnschedScopeModel}, wantSetError: true, wantBlocked: true}, + {name: "缺省 池模式 保持跳过", scopes: []string{""}, poolMode: true}, + {name: "显式模型级 token_revoked 走认证错误处理", scopes: []string{TempUnschedScopeModel}, body: tempUnschedScopeRevoked401Body, wantSetError: true, wantBlocked: true}, + {name: "显式模型级 detail Unauthorized 走认证错误处理", scopes: []string{TempUnschedScopeModel}, body: tempUnschedScopeDetail401Body, wantSetError: true, wantBlocked: true}, + {name: "显式模型级 token_revoked 池模式 保持跳过", scopes: []string{TempUnschedScopeModel}, body: tempUnschedScopeRevoked401Body, poolMode: true}, + {name: "显式模型级 OAuth 走刷新窗口", scopes: []string{TempUnschedScopeModel}, oauth: true, wantTemp: true, wantBlocked: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + repo := &tempUnschedScopeRepoStub{} + gateway := &OpenAIGatewayService{rateLimitService: &RateLimitService{accountRepo: repo, cfg: &config.Config{}}} + account := newTempUnschedScope401Account(PlatformOpenAI, tc.scopes...) + if tc.poolMode { + account.Credentials["pool_mode"] = true + } + if tc.oauth { + account.Type = AccountTypeOAuth + account.Credentials["refresh_token"] = "rt" + } + body := tc.body + if body == nil { + body = tempUnschedScope401Body + } + + require.True(t, gateway.shouldFailoverOpenAIUpstreamResponse(account, http.StatusUnauthorized, "unauthorized", body)) + gateway.handleFailoverSideEffects(context.Background(), &http.Response{ + StatusCode: http.StatusUnauthorized, + Header: http.Header{}, + }, account, body, "gpt-5.4") + + require.Equal(t, tc.wantTemp, repo.tempCalls == 1, "SetTempUnschedulable=%d", repo.tempCalls) + require.Equal(t, tc.wantSetError, repo.errorCalls == 1, "SetError=%d", repo.errorCalls) + require.Equal(t, tc.wantBlocked, gateway.isOpenAIAccountRuntimeBlocked(account)) + if tc.wantModel { + require.Len(t, repo.modelRateLimitCalls, 1) + require.Equal(t, "gpt-5.4", repo.modelRateLimitCalls[0].scope) + } else { + require.Empty(t, repo.modelRateLimitCalls) + } + }) + } +} + +func TestHandleUpstreamError_ExplicitModelScope401(t *testing.T) { + t.Run("模型已知 只冷却模型", func(t *testing.T) { + repo := &tempUnschedScopeRepoStub{} + svc := &RateLimitService{accountRepo: repo} + account := newTempUnschedScope401Account(PlatformAnthropic, TempUnschedScopeModel) + + shouldDisable := svc.HandleUpstreamError(context.Background(), account, http.StatusUnauthorized, http.Header{}, tempUnschedScope401Body, "claude-sonnet-4-5") + + require.True(t, shouldDisable) + require.Zero(t, repo.errorCalls) + require.Zero(t, repo.tempCalls) + require.Len(t, repo.modelRateLimitCalls, 1) + require.Equal(t, "claude-sonnet-4-5", repo.modelRateLimitCalls[0].scope) + }) + + t.Run("模型未知 按账号级规则走认证错误处理", func(t *testing.T) { + repo := &tempUnschedScopeRepoStub{} + svc := &RateLimitService{accountRepo: repo} + account := newTempUnschedScope401Account(PlatformAnthropic, TempUnschedScopeModel) + + shouldDisable := svc.HandleUpstreamError(context.Background(), account, http.StatusUnauthorized, http.Header{}, tempUnschedScope401Body) + + require.True(t, shouldDisable) + require.Equal(t, 1, repo.errorCalls) + require.Empty(t, repo.modelRateLimitCalls) + }) +} + +func TestCheckErrorPolicy_401FollowsTempUnschedScope(t *testing.T) { + cases := []struct { + name string + scope string + body []byte + oauth bool + previous401 bool + want ErrorPolicyResult + wantModel bool + wantTemp bool + }{ + {name: "显式模型级 不参与重复 401 升级", scope: TempUnschedScopeModel, previous401: true, want: ErrorPolicyTempUnscheduled, wantModel: true}, + {name: "缺省 第二次 401 升级", previous401: true, want: ErrorPolicyNone}, + {name: "显式模型级 token_revoked 按账号暂停", scope: TempUnschedScopeModel, body: tempUnschedScopeRevoked401Body, want: ErrorPolicyTempUnscheduled, wantTemp: true}, + {name: "显式模型级 detail Unauthorized 按账号暂停", scope: TempUnschedScopeModel, body: tempUnschedScopeDetail401Body, want: ErrorPolicyTempUnscheduled, wantTemp: true}, + {name: "显式模型级 OAuth 按账号暂停", scope: TempUnschedScopeModel, oauth: true, want: ErrorPolicyTempUnscheduled, wantTemp: true}, + {name: "显式模型级 凭据级第二次 401 升级", scope: TempUnschedScopeModel, body: tempUnschedScopeDetail401Body, previous401: true, want: ErrorPolicyNone}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + repo := &tempUnschedScopeRepoStub{} + svc := &RateLimitService{accountRepo: repo} + account := newTempUnschedScope401Account(PlatformOpenAI, tc.scope) + if tc.oauth { + account.Type = AccountTypeOAuth + } + if tc.previous401 { + account.TempUnschedulableReason = tempUnschedScopePrevious401Mark + } + body := tc.body + if body == nil { + body = tempUnschedScope401Body + } + + result := svc.CheckErrorPolicy(context.Background(), account, http.StatusUnauthorized, body, "gpt-5.4") + + require.Equal(t, tc.want, result) + require.Equal(t, tc.wantTemp, repo.tempCalls == 1, "SetTempUnschedulable=%d", repo.tempCalls) + require.Equal(t, tc.wantModel, len(repo.modelRateLimitCalls) == 1) + }) + } +} + +// 计数入口把实际发往上游的模型交给错误处理:显式模型级 401 规则只冷却该模型,不把整号置为 error。 +func TestCountTokensEntries_ExplicitModelScope401OnlyCoolsModel(t *testing.T) { + gin.SetMode(gin.TestMode) + unauthorized := func() *http.Response { + return &http.Response{ + StatusCode: http.StatusUnauthorized, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"unauthorized"}}`)), + } + } + cfg := &config.Config{ + Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, + Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false, AllowInsecureHTTP: true}}, + } + newContext := func(path string, body []byte) (*gin.Context, *httptest.ResponseRecorder) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + return c, rec + } + + t.Run("openai count_tokens as anthropic", func(t *testing.T) { + repo := &tempUnschedScopeRepoStub{} + upstream := &httpUpstreamRecorder{resp: unauthorized()} + svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream, rateLimitService: &RateLimitService{accountRepo: repo, cfg: cfg}} + account := newTempUnschedScope401Account(PlatformOpenAI, TempUnschedScopeModel) + account.Credentials["api_key"] = "sk-test" + account.Credentials["base_url"] = "http://upstream.example" + account.Concurrency = 1 + body := []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hello"}]}`) + c, _ := newContext("/v1/messages/count_tokens", body) + + require.Error(t, svc.ForwardCountTokensAsAnthropic(context.Background(), c, account, body, "gpt-5.4")) + + require.Equal(t, "gpt-5.4", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Zero(t, repo.errorCalls) + require.Zero(t, repo.tempCalls) + require.Len(t, repo.modelRateLimitCalls, 1) + require.Equal(t, "gpt-5.4", repo.modelRateLimitCalls[0].scope) + }) + + t.Run("openai responses input_tokens", func(t *testing.T) { + repo := &tempUnschedScopeRepoStub{} + upstream := &httpUpstreamRecorder{resp: unauthorized()} + svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream, rateLimitService: &RateLimitService{accountRepo: repo, cfg: cfg}} + account := newTempUnschedScope401Account(PlatformOpenAI, TempUnschedScopeModel) + account.Credentials["api_key"] = "sk-test" + account.Credentials["model_mapping"] = map[string]any{"gpt-5.4": "gpt-5.4-upstream"} + account.Concurrency = 1 + body := []byte(`{"model":"gpt-5.4","input":"hello"}`) + c, _ := newContext("/v1/responses/input_tokens", body) + + require.Error(t, svc.ForwardResponsesInputTokens(context.Background(), c, account, body)) + + require.NotNil(t, upstream.lastReq) + require.Equal(t, "gpt-5.4-upstream", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Zero(t, repo.errorCalls) + require.Zero(t, repo.tempCalls) + require.Len(t, repo.modelRateLimitCalls, 1) + require.Equal(t, "gpt-5.4-upstream", repo.modelRateLimitCalls[0].scope) + }) + + for _, passthrough := range []bool{false, true} { + name := "anthropic count_tokens" + if passthrough { + name = "anthropic count_tokens api key passthrough" + } + t.Run(name, func(t *testing.T) { + repo := &tempUnschedScopeRepoStub{} + upstream := &anthropicHTTPUpstreamRecorder{resp: unauthorized()} + svc := &GatewayService{ + cfg: cfg, + responseHeaderFilter: compileResponseHeaderFilter(cfg), + httpUpstream: upstream, + rateLimitService: &RateLimitService{accountRepo: repo, cfg: cfg}, + } + account := newTempUnschedScope401Account(PlatformAnthropic, TempUnschedScopeModel) + account.Credentials["api_key"] = "upstream-anthropic-key" + account.Credentials["base_url"] = "https://api.anthropic.com" + account.Credentials["model_mapping"] = map[string]any{"claude-sonnet-4-5": "claude-sonnet-4-5-upstream"} + account.Concurrency = 1 + if passthrough { + account.Extra = map[string]any{"anthropic_passthrough": true} + } + body := []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hello"}]}`) + c, _ := newContext("/v1/messages/count_tokens", body) + parsed := &ParsedRequest{Body: NewRequestBodyRef(body), Model: "claude-sonnet-4-5"} + + require.Error(t, svc.ForwardCountTokens(context.Background(), c, account, parsed)) + + require.NotNil(t, upstream.lastReq) + require.Equal(t, "claude-sonnet-4-5-upstream", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Zero(t, repo.errorCalls) + require.Zero(t, repo.tempCalls) + require.Len(t, repo.modelRateLimitCalls, 1) + require.Equal(t, "claude-sonnet-4-5-upstream", repo.modelRateLimitCalls[0].scope) + }) + } +} + +// Bedrock 故障转移入口与重试耗尽入口把实际发往上游的模型交给错误处理:显式模型级规则只冷却该模型。 +func TestAnthropicFailoverEntries_ExplicitModelScopeOnlyCoolsModel(t *testing.T) { + gin.SetMode(gin.TestMode) + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}} + newResponse := func(status int, body string) *http.Response { + return &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + } + } + + t.Run("bedrock failover 401", func(t *testing.T) { + repo := &tempUnschedScopeRepoStub{} + upstream := &anthropicHTTPUpstreamRecorder{resp: newResponse(http.StatusUnauthorized, `{"message":"unauthorized"}`)} + svc := &GatewayService{cfg: cfg, httpUpstream: upstream, rateLimitService: &RateLimitService{accountRepo: repo, cfg: cfg}} + account := newTempUnschedScope401Account(PlatformAnthropic, TempUnschedScopeModel) + account.Type = AccountTypeBedrock + account.Status = StatusActive + account.Schedulable = true + account.Credentials["auth_mode"] = "apikey" + account.Credentials["api_key"] = "bedrock-key" + body := []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hello"}]}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + parsed := &ParsedRequest{Body: NewRequestBodyRef(body), Model: "claude-sonnet-4-5"} + + _, err := svc.forwardBedrock(context.Background(), c, account, parsed, time.Now()) + + var failover *UpstreamFailoverError + require.ErrorAs(t, err, &failover) + require.NotNil(t, upstream.lastReq) + require.Contains(t, upstream.lastReq.URL.Path, "anthropic.claude-sonnet-4-5-", "上游收到 Bedrock 模型 ID") + require.Zero(t, repo.errorCalls) + require.Zero(t, repo.tempCalls) + require.Len(t, repo.modelRateLimitCalls, 1) + // 冷却键必须是调度器查找的键(账号映射后的模型名),而不是 Bedrock 模型 ID。 + scope := repo.modelRateLimitCalls[0].scope + require.Equal(t, "claude-sonnet-4-5", scope) + require.True(t, account.IsSchedulableForModelWithContext(context.Background(), "claude-sonnet-4-5")) + setAccountModelRateLimitSnapshot(account, scope, time.Now().Add(10*time.Minute), "temp_unschedulable", time.Now()) + require.False(t, account.IsSchedulableForModelWithContext(context.Background(), "claude-sonnet-4-5"), "调度器按同一个键排除该模型") + }) + + t.Run("oauth retry exhausted 403", func(t *testing.T) { + repo := &tempUnschedScopeRepoStub{} + svc := &GatewayService{cfg: cfg, rateLimitService: &RateLimitService{accountRepo: repo, cfg: cfg}} + account := newTempUnschedScopeAccount(TempUnschedScopeModel, map[string]any{ + "error_code": float64(http.StatusForbidden), + "keywords": []any{"forbidden"}, + }) + account.Platform = PlatformAnthropic + account.Type = AccountTypeOAuth + + svc.handleRetryExhaustedSideEffects(context.Background(), newResponse(http.StatusForbidden, `{"error":{"message":"forbidden"}}`), account, "claude-sonnet-4-5") + + require.Zero(t, repo.errorCalls) + require.Zero(t, repo.tempCalls) + require.Len(t, repo.modelRateLimitCalls, 1) + require.Equal(t, "claude-sonnet-4-5", repo.modelRateLimitCalls[0].scope) + }) +} diff --git a/backend/internal/service/update_service.go b/backend/internal/service/update_service.go index 497fd55cc..966e584a0 100644 --- a/backend/internal/service/update_service.go +++ b/backend/internal/service/update_service.go @@ -30,7 +30,7 @@ var ( const ( updateCacheKey = "update_check_cache" updateCacheTTL = 1200 // 20 minutes - githubRepo = "MACOS-DO/sub4api" + githubRepo = "info-talent/sub4api" // Security: allowed download domains for updates allowedDownloadHost = "github.com" diff --git a/backend/internal/service/upstream_models.go b/backend/internal/service/upstream_models.go index b980c4358..d2cfed2ed 100644 --- a/backend/internal/service/upstream_models.go +++ b/backend/internal/service/upstream_models.go @@ -10,6 +10,7 @@ import ( "net/http" "net/url" "sort" + "strconv" "strings" "time" @@ -25,6 +26,10 @@ const ( UpstreamModelMetadataExtraKey = "upstream_model_metadata" UpstreamModelMetadataIncompleteCode = "upstream_model_metadata_incomplete" UpstreamModelMetadataPartialCode = "upstream_model_metadata_partial" + + vertexPublisherModelsPageSize = 300 + vertexPublisherModelsMaxPages = 20 + vertexGooglePublisherModelPrefix = "publishers/google/models/" ) type UpstreamModelMetadata struct { @@ -335,7 +340,11 @@ func configuredUpstreamModelsForCapabilitySync(account *Account) []string { return nil } models := make([]string, 0) - for _, mappedModel := range account.GetModelMapping() { + for requestedModel, mappedModel := range account.GetModelMapping() { + // Antigravity 运行时补齐的默认透传不是管理员配置的目标,上游目录未列出时不应拉低能力同步完整度。 + if account.isAntigravityInjectedDefaultPassthrough(requestedModel, mappedModel) { + continue + } mappedModel = strings.TrimSpace(mappedModel) if mappedModel == "" || strings.Contains(mappedModel, "*") { continue @@ -733,57 +742,163 @@ func (s *AccountTestService) fetchUpstreamModelList(ctx context.Context, account } if account.Platform == PlatformAntigravity && account.Type != AccountTypeAPIKey { - models, err := s.fetchAntigravityOAuthUpstreamModels(ctx, account) - return models, nil, err + return s.fetchAntigravityOAuthUpstreamModels(ctx, account) } if s.httpUpstream == nil { return nil, nil, newUpstreamModelSyncConfigError("Upstream HTTP client is not configured", nil) } + if account.IsGemini() && account.IsVertexServiceAccount() { + models, err := s.fetchVertexGeminiUpstreamModels(ctx, account) + return models, nil, err + } + req, err := s.buildUpstreamModelsRequest(ctx, account) if err != nil { return nil, nil, err } - proxyURL := upstreamModelsProxyURL(account) - resp, err := s.doUpstreamModelsRequest(req, proxyURL, account) + body, err := s.readUpstreamModelsResponse(req, account) if err != nil { - return nil, nil, newUpstreamModelSyncUpstreamError("Failed to request upstream model list", err) + return nil, nil, err + } + + extractModels := extractUpstreamModelIDs + if account.IsGrok() { + extractModels = extractGrokUpstreamModelIDs + } + models, err := extractModels(body) + if err != nil { + return nil, nil, newUpstreamModelSyncUpstreamError("Upstream model list response was not valid JSON", err) + } + if len(models) == 0 { + return nil, nil, newUpstreamModelSyncUpstreamError("Upstream returned no supported models", nil) + } + + return models, body, nil +} + +// readUpstreamModelsResponse 发送模型列表请求并读取受限大小的响应体;非 2xx 返回带状态码的同步错误。 +func (s *AccountTestService) readUpstreamModelsResponse(req *http.Request, account *Account) ([]byte, error) { + resp, err := s.doUpstreamModelsRequest(req, upstreamModelsProxyURL(account), account) + if err != nil { + return nil, newUpstreamModelSyncUpstreamError("Failed to request upstream model list", err) } defer func() { _ = resp.Body.Close() }() bodyLimit := resolveModelsListReadLimit(s.cfg) body, err := io.ReadAll(io.LimitReader(resp.Body, bodyLimit+1)) if err != nil { - return nil, nil, newUpstreamModelSyncUpstreamError("Failed to read upstream model list", err) + return nil, newUpstreamModelSyncUpstreamError("Failed to read upstream model list", err) } if int64(len(body)) > bodyLimit { - return nil, nil, newUpstreamModelSyncUpstreamError("Upstream model list response is too large", fmt.Errorf("response exceeds %d bytes", bodyLimit)) + return nil, newUpstreamModelSyncUpstreamError("Upstream model list response is too large", fmt.Errorf("response exceeds %d bytes", bodyLimit)) } if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { - return nil, nil, &UpstreamModelSyncError{ + return nil, &UpstreamModelSyncError{ Kind: UpstreamModelSyncErrorUpstream, Message: fmt.Sprintf("Upstream model list request failed with HTTP %d", resp.StatusCode), StatusCode: resp.StatusCode, Err: fmt.Errorf("upstream model list returned HTTP %d", resp.StatusCode), } } + return body, nil +} - extractModels := extractUpstreamModelIDs - if account.IsGrok() { - extractModels = extractGrokUpstreamModelIDs +// fetchVertexGeminiUpstreamModels 按账号默认区域读取 Vertex 上可用的 Gemini 模型。列表接口不接受 API Key。 +func (s *AccountTestService) fetchVertexGeminiUpstreamModels(ctx context.Context, account *Account) ([]string, error) { + if account.IsVertexAPIKey() { + return nil, newUpstreamModelSyncUnsupportedError("Vertex API key accounts do not support upstream model listing", nil) } - models, err := extractModels(body) + if _, err := parseVertexServiceAccountKey(account); err != nil { + return nil, newUpstreamModelSyncConfigError("Invalid Vertex service account credentials", err) + } + location := account.VertexLocation("") + if _, err := buildVertexPublisherModelsURL(location, ""); err != nil { + return nil, newUpstreamModelSyncConfigError("Invalid Vertex location", err) + } + if s.geminiTokenProvider == nil { + return nil, newUpstreamModelSyncConfigError("Gemini token provider is not configured", nil) + } + accessToken, err := s.geminiTokenProvider.GetAccessToken(ctx, account) if err != nil { - return nil, nil, newUpstreamModelSyncUpstreamError("Upstream model list response was not valid JSON", err) + return nil, newUpstreamModelSyncUpstreamError("Failed to get Vertex access token", err) } - if len(models) == 0 { - return nil, nil, newUpstreamModelSyncUpstreamError("Upstream returned no supported models", nil) + accessToken = strings.TrimSpace(accessToken) + if accessToken == "" { + return nil, newUpstreamModelSyncConfigError("No Vertex access token is available", nil) } - return models, body, nil + return listVertexGeminiPublisherModels(location, func(page int, listURL string) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, listURL, nil) + if err != nil { + return nil, newUpstreamModelSyncConfigError("Invalid Vertex model list URL", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("Authorization", "Bearer "+accessToken) + + body, err := s.readUpstreamModelsResponse(req, account) + if err != nil { + // 只有首页的 404/405 表示列表端点不可用;翻页途中的失败不触发配置模型回退。 + var syncErr *UpstreamModelSyncError + if page > 0 && errors.As(err, &syncErr) { + syncErr.StatusCode = 0 + } + return nil, err + } + return body, nil + }) +} + +// listVertexGeminiPublisherModels 按区域分页读取 Google 发布方模型列表,只保留 gemini- 前缀的模型(去重排序)。 +// 区域端点还会列出 Gemma、Veo、AutoML 等非 Gemini 的模型花园条目;global 端点只含 Gemini。 +// fetchPage 负责发送请求并处理非 2xx 响应,返回该页的响应体;它返回的错误原样透出。 +func listVertexGeminiPublisherModels(location string, fetchPage func(page int, listURL string) ([]byte, error)) ([]string, error) { + models := make([]string, 0) + pageToken := "" + for page := 0; page < vertexPublisherModelsMaxPages; page++ { + listURL, err := buildVertexPublisherModelsURL(location, pageToken) + if err != nil { + return nil, newUpstreamModelSyncConfigError("Invalid Vertex location", err) + } + body, err := fetchPage(page, listURL) + if err != nil { + return nil, err + } + var response struct { + PublisherModels []struct { + Name string `json:"name"` + } `json:"publisherModels"` + NextPageToken string `json:"nextPageToken"` + } + if err := json.Unmarshal(body, &response); err != nil { + return nil, newUpstreamModelSyncUpstreamError("Upstream model list response was not valid JSON", err) + } + for _, entry := range response.PublisherModels { + name := strings.TrimSpace(entry.Name) + if !strings.HasPrefix(name, vertexGooglePublisherModelPrefix) { + continue + } + modelID := strings.TrimPrefix(name, vertexGooglePublisherModelPrefix) + if strings.HasPrefix(modelID, "gemini-") && len(modelID) > len("gemini-") { + models = append(models, modelID) + } + } + + pageToken = strings.TrimSpace(response.NextPageToken) + if pageToken == "" { + if len(models) == 0 { + return nil, newUpstreamModelSyncUpstreamError("Upstream returned no supported models", nil) + } + return dedupeAndSortModelIDs(models), nil + } + } + return nil, newUpstreamModelSyncUpstreamError( + "Upstream model list pagination did not finish", + fmt.Errorf("more than %d pages", vertexPublisherModelsMaxPages), + ) } func (s *AccountTestService) buildUpstreamModelsRequest(ctx context.Context, account *Account) (*http.Request, error) { @@ -1151,42 +1266,47 @@ func (s *AccountTestService) buildGeminiUpstreamModelsRequest(ctx context.Contex return req, nil } -func (s *AccountTestService) fetchAntigravityOAuthUpstreamModels(ctx context.Context, account *Account) ([]string, error) { +func (s *AccountTestService) fetchAntigravityOAuthUpstreamModels(ctx context.Context, account *Account) ([]string, []byte, error) { if s.antigravityGatewayService == nil || s.antigravityGatewayService.GetTokenProvider() == nil { - return nil, newUpstreamModelSyncConfigError("Antigravity token provider is not configured", nil) + return nil, nil, newUpstreamModelSyncConfigError("Antigravity token provider is not configured", nil) } accessToken, err := s.antigravityGatewayService.GetTokenProvider().GetAccessToken(ctx, account) if err != nil { - return nil, newUpstreamModelSyncUpstreamError("Failed to get Antigravity access token", err) + return nil, nil, newUpstreamModelSyncUpstreamError("Failed to get Antigravity access token", err) } accessToken = strings.TrimSpace(accessToken) if accessToken == "" { - return nil, newUpstreamModelSyncConfigError("No Antigravity access token is available", nil) + return nil, nil, newUpstreamModelSyncConfigError("No Antigravity access token is available", nil) } client, err := antigravity.NewClient(upstreamModelsProxyURL(account)) if err != nil { - return nil, newUpstreamModelSyncConfigError("Failed to configure Antigravity client", err) + return nil, nil, newUpstreamModelSyncConfigError("Failed to configure Antigravity client", err) } - modelsResp, _, err := client.FetchAvailableModels( + modelsResp, raw, err := client.FetchAvailableModelsFromURL( ctx, + resolveAntigravityForwardBaseURL(account), accessToken, strings.TrimSpace(account.GetCredential("project_id")), resolveModelsListReadLimit(s.cfg), ) if err != nil { - return nil, newUpstreamModelSyncUpstreamError("Failed to fetch Antigravity available models", err) + return nil, nil, newUpstreamModelSyncUpstreamError("Failed to fetch Antigravity available models", err) } if modelsResp == nil || len(modelsResp.Models) == 0 { - return nil, newUpstreamModelSyncUpstreamError("Upstream returned no supported models", nil) + return nil, nil, newUpstreamModelSyncUpstreamError("Upstream returned no supported models", nil) } models := make([]string, 0, len(modelsResp.Models)) for modelID := range modelsResp.Models { models = append(models, strings.TrimSpace(modelID)) } - return dedupeAndSortModelIDs(models), nil + body, err := json.Marshal(raw) + if err != nil { + return nil, nil, newUpstreamModelSyncUpstreamError("Failed to read Antigravity model metadata", err) + } + return dedupeAndSortModelIDs(models), body, nil } func (s *AccountTestService) doUpstreamModelsRequest(req *http.Request, proxyURL string, account *Account) (*http.Response, error) { @@ -1218,6 +1338,26 @@ func buildOpenAIModelsURL(base string) string { return buildOpenAIEndpointURL(base, "/v1/models") } +// buildVertexPublisherModelsURL 构造 Google 发布方模型列表地址。该接口只有 v1beta1 版本,pageSize 上限 300。 +func buildVertexPublisherModelsURL(location, pageToken string) (string, error) { + location = strings.TrimSpace(location) + if location == "" { + location = vertexDefaultLocation + } + if !vertexLocationPattern.MatchString(location) { + return "", fmt.Errorf("invalid vertex location: %s", location) + } + host := location + "-aiplatform.googleapis.com" + if location == "global" { + host = vertexGlobalHost + } + query := url.Values{"pageSize": []string{strconv.Itoa(vertexPublisherModelsPageSize)}} + if pageToken != "" { + query.Set("pageToken", pageToken) + } + return fmt.Sprintf("https://%s/v1beta1/publishers/google/models?%s", host, query.Encode()), nil +} + func buildGeminiModelsURL(base string) string { normalized := strings.TrimRight(strings.TrimSpace(base), "/") if strings.HasSuffix(normalized, "/v1beta/models") { @@ -1262,6 +1402,12 @@ type upstreamModelCapabilityEntry struct { MaxContextWindow int64 `json:"max_context_window"` MaxOutputTokens int64 `json:"max_output_tokens"` Limit modelsDevLimit `json:"limit"` + DisplayNameCamel string `json:"displayName"` + SupportsImages *bool `json:"supportsImages"` + SupportsThinking *bool `json:"supportsThinking"` + ThinkingBudget *int64 `json:"thinkingBudget"` + MaxTokens int64 `json:"maxTokens"` + MaxOutputTokensCamel int64 `json:"maxOutputTokens"` } func extractUpstreamModelIDs(body []byte) ([]string, error) { @@ -1310,12 +1456,33 @@ func extractUpstreamModelCatalog(body []byte, grok bool) ([]string, map[string]U func extractUpstreamModelRawEntries(body []byte) ([]json.RawMessage, error) { var response struct { Data []json.RawMessage `json:"data"` - Models []json.RawMessage `json:"models"` + Models json.RawMessage `json:"models"` } if err := json.Unmarshal(body, &response); err == nil && (response.Data != nil || response.Models != nil) { - entries := make([]json.RawMessage, 0, len(response.Data)+len(response.Models)) - entries = append(entries, response.Data...) - entries = append(entries, response.Models...) + entries := append([]json.RawMessage{}, response.Data...) + if len(response.Models) > 0 && string(response.Models) != "null" { + var list []json.RawMessage + if err := json.Unmarshal(response.Models, &list); err == nil { + entries = append(entries, list...) + } else { + // Antigravity keys its model catalog by the exact generation model ID. + var models map[string]map[string]json.RawMessage + if err := json.Unmarshal(response.Models, &models); err != nil { + return nil, fmt.Errorf("parse upstream model catalog: %w", err) + } + for modelID, fields := range models { + if fields == nil { + fields = make(map[string]json.RawMessage) + } + fields["id"], _ = json.Marshal(modelID) + raw, err := json.Marshal(fields) + if err != nil { + return nil, fmt.Errorf("parse upstream model metadata: %w", err) + } + entries = append(entries, raw) + } + } + } return entries, nil } var entries []json.RawMessage @@ -1331,6 +1498,34 @@ func upstreamMetadataFromCapabilityEntry(modelID string, entry upstreamModelCapa levels = reasoningLevelsFromModelsDevOptions(entry.ReasoningOptions) } reasoning := entry.Reasoning + if reasoning == nil { + reasoning = entry.SupportsThinking + } + if len(levels) == 0 && entry.SupportsThinking != nil && *entry.SupportsThinking { + level := "high" + fixedLevel := normalizeReasoningLevel(modelID[strings.LastIndex(modelID, "-")+1:]) + if fixedLevel != "" && fixedLevel != "none" { + level = fixedLevel + } else if entry.ThinkingBudget != nil { + switch budget := *entry.ThinkingBudget; { + case budget < 0: + case budget <= geminiThinkingBudgetLowMax: + level = "low" + case budget <= geminiThinkingBudgetMediumMax: + level = "medium" + } + } + if fixedLevel == "" || fixedLevel == "none" { + // Bare and tiered AGY models accept configurable budgets. The fetched + // thinkingBudget is their default, not the only supported budget. + levels = []string{"low", "medium", "high"} + if entry.DefaultReasoningLevel == "" { + entry.DefaultReasoningLevel = level + } + } else { + levels = []string{level} + } + } if reasoning == nil && len(levels) > 0 { inferred := len(levels) != 1 || levels[0] != "none" reasoning = &inferred @@ -1339,6 +1534,13 @@ func upstreamMetadataFromCapabilityEntry(modelID string, entry upstreamModelCapa if len(modalities) == 0 { modalities = entry.Modalities.Input } + if len(modalities) == 0 && (entry.SupportsImages != nil || entry.SupportsThinking != nil || entry.MaxTokens > 0) { + // AGY models accept text; image input requires an explicit capability. + modalities = []string{"text"} + if entry.SupportsImages != nil && *entry.SupportsImages { + modalities = append(modalities, "image") + } + } contextWindow := entry.ContextWindow if contextWindow <= 0 { contextWindow = entry.MaxContextWindow @@ -1346,15 +1548,24 @@ func upstreamMetadataFromCapabilityEntry(modelID string, entry upstreamModelCapa if contextWindow <= 0 { contextWindow = entry.Limit.Context } + if contextWindow <= 0 { + contextWindow = entry.MaxTokens + } maxOutputTokens := entry.MaxOutputTokens if maxOutputTokens <= 0 { maxOutputTokens = entry.Limit.Output } + if maxOutputTokens <= 0 { + maxOutputTokens = entry.MaxOutputTokensCamel + } defaultReasoningLevel := normalizeReasoningLevel(entry.DefaultReasoningLevel) if defaultReasoningLevel == "" && len(levels) > 0 { defaultReasoningLevel = levels[0] } displayName := strings.TrimSpace(entry.DisplayName) + if displayName == "" { + displayName = strings.TrimSpace(entry.DisplayNameCamel) + } if displayName == "" && strings.TrimSpace(entry.Name) != "" && strings.TrimSpace(entry.Name) != modelID { displayName = strings.TrimSpace(entry.Name) } diff --git a/backend/internal/service/upstream_models_antigravity_test.go b/backend/internal/service/upstream_models_antigravity_test.go new file mode 100644 index 000000000..e1f0846fe --- /dev/null +++ b/backend/internal/service/upstream_models_antigravity_test.go @@ -0,0 +1,245 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/MACOS-DO/sub4api/internal/pkg/antigravity" + "github.com/stretchr/testify/require" +) + +func antigravityModelSyncAccount(plan string) *Account { + return &Account{ + ID: 121, Platform: PlatformAntigravity, Type: AccountTypeOAuth, + Credentials: map[string]any{ + "access_token": "model-sync-test-token", + "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + "project_id": "model-sync-test-project", + "plan_type": plan, + }, + } +} + +func antigravityModelSyncService() *AccountTestService { + return &AccountTestService{ + antigravityGatewayService: &AntigravityGatewayService{tokenProvider: &AntigravityTokenProvider{}}, + cfg: upstreamModelSyncTestConfig(), + } +} + +func withAntigravityModelSyncEndpoints(t *testing.T, production, daily string) { + t.Helper() + previous := antigravity.BaseURLs + antigravity.BaseURLs = []string{production, daily} + t.Cleanup(func() { antigravity.BaseURLs = previous }) +} + +func TestFetchUpstreamSupportedModelsAntigravityUsesGenerationEndpoint(t *testing.T) { + t.Setenv(antigravityForwardBaseURLEnv, "") + production := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, `{"models":{"gemini-3.7-flash-high":{}}}`) + })) + defer production.Close() + daily := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, `{"models":{"gemini-3.8-flash-high":{}}}`) + })) + defer daily.Close() + withAntigravityModelSyncEndpoints(t, production.URL, daily.URL) + + for _, tc := range []struct { + name string + plan string + mode string + model string + }{ + {name: "Ultra daily", plan: "Ultra", model: "gemini-3.8-flash-high"}, + {name: "Pro daily", plan: "Pro", model: "gemini-3.8-flash-high"}, + {name: "Free production", plan: "Free", model: "gemini-3.7-flash-high"}, + {name: "explicit production", plan: "Ultra", mode: "prod", model: "gemini-3.7-flash-high"}, + {name: "explicit daily", plan: "Free", mode: "daily", model: "gemini-3.8-flash-high"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv(antigravityForwardBaseURLEnv, tc.mode) + models, err := antigravityModelSyncService().FetchUpstreamSupportedModels(context.Background(), antigravityModelSyncAccount(tc.plan)) + require.NoError(t, err) + require.Equal(t, []string{tc.model}, models, "catalog must come from the endpoint used for generation") + }) + } +} + +func TestSyncUpstreamModelCatalogAntigravityPreservesDirectCapabilities(t *testing.T) { + t.Setenv(antigravityForwardBaseURLEnv, "") + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, `{"models":{"gemini-3.8-flash-high":{ + "displayName":"Gemini 3.8 Flash High", + "supportsImages":true,"supportsThinking":true,"thinkingBudget":24576, + "maxTokens":1048576,"maxOutputTokens":65536 + }}}`) + })) + defer server.Close() + withAntigravityModelSyncEndpoints(t, server.URL, server.URL) + account := antigravityModelSyncAccount("Ultra") + account.Credentials["model_mapping"] = map[string]any{"gemini-3.8-flash-high": "gemini-3.8-flash-high"} + registry := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusBadGateway, Body: io.NopCloser(strings.NewReader(`{"error":"registry unavailable"}`))}} + svc := antigravityModelSyncService() + svc.accountRepo = &upstreamModelMetadataRepoStub{} + svc.httpUpstream = registry + + catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.NoError(t, err) + require.Equal(t, []string{"gemini-3.8-flash-high"}, catalog.Models) + require.Contains(t, catalog.Metadata, "gemini-3.8-flash-high") + metadata := catalog.Metadata["gemini-3.8-flash-high"] + require.Equal(t, "Gemini 3.8 Flash High", metadata.DisplayName) + require.NotNil(t, metadata.Reasoning) + require.True(t, *metadata.Reasoning) + require.Equal(t, []string{"high"}, metadata.SupportedReasoningLevels, "fixed variant must advertise only its own reasoning level") + require.Equal(t, "high", metadata.DefaultReasoningLevel) + require.Equal(t, []string{"text", "image"}, metadata.InputModalities) + require.Equal(t, int64(1048576), metadata.ContextWindow) + require.Equal(t, int64(65536), metadata.MaxOutputTokens) + require.Empty(t, registry.requests, "complete upstream capabilities must not need guessed registry capabilities") + require.Empty(t, catalog.Warnings) + snapshot := account.GetUpstreamModelMetadataSnapshot() + require.NotNil(t, snapshot) + require.Equal(t, "upstream", snapshot.Source) + serializedMetadata, err := json.Marshal(metadata) + require.NoError(t, err) + serializedSnapshotEntry, err := json.Marshal(snapshot.Models["gemini-3.8-flash-high"]) + require.NoError(t, err) + require.JSONEq(t, string(serializedMetadata), string(serializedSnapshotEntry)) +} + +func TestSyncUpstreamModelCatalogAntigravityTieredReasoning(t *testing.T) { + t.Setenv(antigravityForwardBaseURLEnv, "") + for _, tc := range []struct { + budget string + defaultLevel string + }{ + {budget: "-1", defaultLevel: "high"}, + {budget: "0", defaultLevel: "low"}, + {budget: "1024", defaultLevel: "low"}, + {budget: "1025", defaultLevel: "medium"}, + {budget: "4000", defaultLevel: "medium"}, + {budget: "8192", defaultLevel: "medium"}, + {budget: "8193", defaultLevel: "high"}, + {defaultLevel: "high"}, + } { + t.Run("budget="+tc.budget, func(t *testing.T) { + budgetJSON := "" + if tc.budget != "" { + budgetJSON = `"thinkingBudget":` + tc.budget + "," + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, fmt.Sprintf(`{"models":{"gemini-3.8-flash-tiered":{ + "supportsImages":false,"supportsThinking":true,%s + "maxTokens":1048576,"maxOutputTokens":65536 + }}}`, budgetJSON)) + })) + defer server.Close() + withAntigravityModelSyncEndpoints(t, server.URL, server.URL) + account := antigravityModelSyncAccount("Ultra") + account.Credentials["model_mapping"] = map[string]any{"gemini-3.8-flash-tiered": "gemini-3.8-flash-tiered"} + svc := antigravityModelSyncService() + svc.accountRepo = &upstreamModelMetadataRepoStub{} + + catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.NoError(t, err) + metadata := catalog.Metadata["gemini-3.8-flash-tiered"] + require.Equal(t, []string{"low", "medium", "high"}, metadata.SupportedReasoningLevels) + require.Equal(t, tc.defaultLevel, metadata.DefaultReasoningLevel, "tiered default must follow its upstream thinking budget") + require.Equal(t, []string{"text"}, metadata.InputModalities) + }) + } +} + +func TestSyncUpstreamModelCatalogAntigravityMissingImageSupportIsTextOnly(t *testing.T) { + t.Setenv(antigravityForwardBaseURLEnv, "") + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, `{"models":{"claude-plain":{ + "supportsThinking":false,"maxTokens":200000,"maxOutputTokens":64000 + }}}`) + })) + defer server.Close() + withAntigravityModelSyncEndpoints(t, server.URL, server.URL) + account := antigravityModelSyncAccount("Ultra") + account.Credentials["model_mapping"] = map[string]any{"claude-plain": "claude-plain"} + registry := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusBadGateway, Body: io.NopCloser(strings.NewReader(`{"error":"registry unavailable"}`))}} + svc := antigravityModelSyncService() + svc.accountRepo = &upstreamModelMetadataRepoStub{} + svc.httpUpstream = registry + + catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.NoError(t, err) + metadata := catalog.Metadata["claude-plain"] + require.Equal(t, []string{"text"}, metadata.InputModalities, "missing image declaration must not advertise image input") + require.NotNil(t, metadata.Reasoning) + require.False(t, *metadata.Reasoning) + require.Empty(t, metadata.SupportedReasoningLevels) + require.Empty(t, registry.requests) +} + +func TestSyncUpstreamModelCatalogAntigravityBudgetReasoningLevels(t *testing.T) { + t.Setenv(antigravityForwardBaseURLEnv, "") + for _, tc := range []struct { + model string + budget int + defaultLevel string + levels []string + }{ + {model: "gemini-2.5-flash", budget: -1, defaultLevel: "high", levels: []string{"low", "medium", "high"}}, + {model: "gemini-2.5-flash-lite", budget: 4000, defaultLevel: "medium", levels: []string{"low", "medium", "high"}}, + {model: "gemini-3.8-flash-low", budget: -1, defaultLevel: "low", levels: []string{"low"}}, + {model: "gemini-3.8-flash-medium", budget: 1000, defaultLevel: "medium", levels: []string{"medium"}}, + {model: "gemini-3.8-flash-high", budget: 4000, defaultLevel: "high", levels: []string{"high"}}, + } { + t.Run(tc.model, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, fmt.Sprintf(`{"models":{%q:{ + "supportsImages":true,"supportsThinking":true,"thinkingBudget":%d, + "maxTokens":1048576,"maxOutputTokens":65536 + }}}`, tc.model, tc.budget)) + })) + defer server.Close() + withAntigravityModelSyncEndpoints(t, server.URL, server.URL) + account := antigravityModelSyncAccount("Ultra") + account.Credentials["model_mapping"] = map[string]any{tc.model: tc.model} + svc := antigravityModelSyncService() + svc.accountRepo = &upstreamModelMetadataRepoStub{} + + catalog, err := svc.SyncUpstreamModelCatalog(context.Background(), account) + require.NoError(t, err) + metadata := catalog.Metadata[tc.model] + require.Equal(t, tc.levels, metadata.SupportedReasoningLevels, "default budget must not restrict configurable models to one reasoning level") + require.Equal(t, tc.defaultLevel, metadata.DefaultReasoningLevel) + require.Empty(t, catalog.Warnings) + }) + } +} + +func TestConfiguredUpstreamModelsForCapabilitySyncSkipsInjectedAntigravityPassthroughs(t *testing.T) { + account := &Account{ + Platform: PlatformAntigravity, + Credentials: map[string]any{"model_mapping": map[string]any{ + "gemini-3.8-flash-high": "gemini-3.8-flash-high", + "gemini-3.8-flash": "gemini-3.8-flash-tiered", + "custom-alias": "gemini-3.6-flash-low", + }}, + } + // 运行时补齐的默认透传仍可调用(存量账号兼容)。 + require.True(t, account.IsModelSupported("gemini-3.7-flash-medium")) + + got := configuredUpstreamModelsForCapabilitySync(account) + require.ElementsMatch(t, []string{"gemini-3.8-flash-high", "gemini-3.8-flash-tiered", "gemini-3.6-flash-low"}, got) + + // 空映射走默认目录,其中的同名条目不是运行时补齐。 + empty := &Account{Platform: PlatformAntigravity, Credentials: map[string]any{}} + require.Contains(t, configuredUpstreamModelsForCapabilitySync(empty), "gemini-3.8-flash-low") +} diff --git a/backend/internal/service/upstream_models_vertex_test.go b/backend/internal/service/upstream_models_vertex_test.go new file mode 100644 index 000000000..bd4678614 --- /dev/null +++ b/backend/internal/service/upstream_models_vertex_test.go @@ -0,0 +1,276 @@ +package service + +import ( + "context" + "errors" + "io" + "net/http" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +type vertexModelsTokenCacheStub struct { + token string + calls int +} + +func (c *vertexModelsTokenCacheStub) GetAccessToken(context.Context, string) (string, error) { + c.calls++ + if c.token == "" { + return "", errors.New("missing token") + } + return c.token, nil +} + +func (c *vertexModelsTokenCacheStub) SetAccessToken(context.Context, string, string, time.Duration) error { + return nil +} + +func (c *vertexModelsTokenCacheStub) DeleteAccessToken(context.Context, string) error { + return nil +} + +func (c *vertexModelsTokenCacheStub) AcquireRefreshLock(context.Context, string, time.Duration) (bool, error) { + return false, nil +} + +func (c *vertexModelsTokenCacheStub) ReleaseRefreshLock(context.Context, string) error { + return nil +} + +func vertexModelSyncTestAccount(credentials map[string]any) *Account { + merged := map[string]any{ + "service_account_json": map[string]any{ + "type": "service_account", + "project_id": "proj", + "private_key": "-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----\n", + "client_email": "svc@proj.iam.gserviceaccount.com", + }, + } + for key, value := range credentials { + merged[key] = value + } + return &Account{ + ID: 173, + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Credentials: merged, + } +} + +func vertexModelSyncTestService(upstream *httpUpstreamRecorder) *AccountTestService { + return &AccountTestService{ + httpUpstream: upstream, + cfg: upstreamModelSyncTestConfig(), + geminiTokenProvider: NewGeminiTokenProvider(nil, &vertexModelsTokenCacheStub{token: "ya29.vertex-token"}, nil), + } +} + +func vertexModelsJSONResponse(status int, body string) *http.Response { + return &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + } +} + +func TestBuildVertexPublisherModelsURL(t *testing.T) { + t.Parallel() + + u, err := buildVertexPublisherModelsURL("global", "") + require.NoError(t, err) + require.Equal(t, "https://aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300", u) + + u, err = buildVertexPublisherModelsURL("us-central1", "next/page+token") + require.NoError(t, err) + require.Equal(t, "https://us-central1-aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300&pageToken=next%2Fpage%2Btoken", u) + + u, err = buildVertexPublisherModelsURL("", "") + require.NoError(t, err) + require.Equal(t, "https://us-central1-aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300", u) + + _, err = buildVertexPublisherModelsURL("evil.com/x", "") + require.Error(t, err) +} + +// Scenario: Vertex SA 账号按账号区域分页读取发布方模型列表,只保留 gemini- 前缀模型。 +func TestFetchUpstreamSupportedModelsVertexServiceAccountPaginatesAndKeepsGemini(t *testing.T) { + t.Parallel() + + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[ + {"name":"publishers/google/models/gemini-3.8-flash"}, + {"name":"publishers/google/models/gemma4"}, + {"name":"publishers/google/models/veo-3.1-generate-001"} + ],"nextPageToken":"page-2"}`), + vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[ + {"name":" publishers/google/models/gemini-2.5-flash "}, + {"name":"publishers/google/models/gemini-3.8-flash"}, + {"name":"gemini-without-publisher-prefix"}, + {"name":"publishers/anthropic/models/gemini-other-publisher"}, + {"name":"publishers/google/models/gemini-"} + ]}`), + }} + svc := vertexModelSyncTestService(upstream) + + models, err := svc.FetchUpstreamSupportedModels(context.Background(), vertexModelSyncTestAccount(map[string]any{ + "location": "europe-west4", + })) + require.NoError(t, err) + require.Equal(t, []string{"gemini-2.5-flash", "gemini-3.8-flash"}, models) + + require.Len(t, upstream.requests, 2) + require.Equal(t, "https://europe-west4-aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300", upstream.requests[0].URL.String()) + require.Equal(t, "https://europe-west4-aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300&pageToken=page-2", upstream.requests[1].URL.String()) + for _, req := range upstream.requests { + require.Equal(t, http.MethodGet, req.Method) + require.Equal(t, "Bearer ya29.vertex-token", req.Header.Get("Authorization")) + } +} + +func TestFetchUpstreamSupportedModelsVertexUpstreamErrorKeepsStatus(t *testing.T) { + t.Parallel() + + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusForbidden, `{"error":{"code":403,"status":"PERMISSION_DENIED"}}`)} + svc := vertexModelSyncTestService(upstream) + + _, err := svc.FetchUpstreamSupportedModels(context.Background(), vertexModelSyncTestAccount(map[string]any{"location": "global"})) + var syncErr *UpstreamModelSyncError + require.ErrorAs(t, err, &syncErr) + require.Equal(t, UpstreamModelSyncErrorUpstream, syncErr.Kind) + require.Equal(t, http.StatusForbidden, syncErr.StatusCode) + require.Equal(t, "https://aiplatform.googleapis.com/v1beta1/publishers/google/models?pageSize=300", upstream.lastReq.URL.String()) +} + +func TestFetchUpstreamSupportedModelsVertexWithoutGeminiModelsFails(t *testing.T) { + t.Parallel() + + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[{"name":"publishers/google/models/gemma4"}]}`)} + svc := vertexModelSyncTestService(upstream) + + _, err := svc.FetchUpstreamSupportedModels(context.Background(), vertexModelSyncTestAccount(nil)) + var syncErr *UpstreamModelSyncError + require.ErrorAs(t, err, &syncErr) + require.Equal(t, UpstreamModelSyncErrorUpstream, syncErr.Kind) + require.Equal(t, "Upstream returned no supported models", syncErr.SafeMessage()) +} + +func TestFetchUpstreamSupportedModelsVertexStopsEndlessPagination(t *testing.T) { + t.Parallel() + + responses := make([]*http.Response, 0, vertexPublisherModelsMaxPages) + for i := 0; i < vertexPublisherModelsMaxPages; i++ { + responses = append(responses, vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[{"name":"publishers/google/models/gemini-3.8-flash"}],"nextPageToken":"again"}`)) + } + upstream := &httpUpstreamRecorder{responses: responses} + svc := vertexModelSyncTestService(upstream) + + _, err := svc.FetchUpstreamSupportedModels(context.Background(), vertexModelSyncTestAccount(nil)) + var syncErr *UpstreamModelSyncError + require.ErrorAs(t, err, &syncErr) + require.Equal(t, "Upstream model list pagination did not finish", syncErr.SafeMessage()) + require.Len(t, upstream.requests, vertexPublisherModelsMaxPages) +} + +func TestFetchUpstreamSupportedModelsVertexAPIKeyUnsupported(t *testing.T) { + t.Parallel() + + upstream := &httpUpstreamRecorder{} + svc := vertexModelSyncTestService(upstream) + account := &Account{ + ID: 174, + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Credentials: map[string]any{ + "auth_mode": "apikey", + "api_key": "AQ.test-key", + }, + } + + _, err := svc.FetchUpstreamSupportedModels(context.Background(), account) + var syncErr *UpstreamModelSyncError + require.ErrorAs(t, err, &syncErr) + require.Equal(t, UpstreamModelSyncErrorUnsupported, syncErr.Kind) + require.Empty(t, upstream.requests) +} + +func TestFetchUpstreamSupportedModelsVertexInvalidCredentialsIsConfigError(t *testing.T) { + t.Parallel() + + cache := &vertexModelsTokenCacheStub{token: "ya29.vertex-token"} + upstream := &httpUpstreamRecorder{} + svc := &AccountTestService{ + httpUpstream: upstream, + cfg: upstreamModelSyncTestConfig(), + geminiTokenProvider: NewGeminiTokenProvider(nil, cache, nil), + } + account := &Account{ + ID: 175, + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Credentials: map[string]any{"api_key": "not-a-service-account"}, + } + + _, err := svc.FetchUpstreamSupportedModels(context.Background(), account) + var syncErr *UpstreamModelSyncError + require.ErrorAs(t, err, &syncErr) + require.Equal(t, UpstreamModelSyncErrorConfiguration, syncErr.Kind) + require.Equal(t, "Invalid Vertex service account credentials", syncErr.SafeMessage()) + require.Zero(t, cache.calls) + require.Empty(t, upstream.requests) +} + +func TestFetchUpstreamSupportedModelsVertexInvalidLocationSkipsTokenExchange(t *testing.T) { + t.Parallel() + + cache := &vertexModelsTokenCacheStub{token: "ya29.vertex-token"} + upstream := &httpUpstreamRecorder{} + svc := &AccountTestService{ + httpUpstream: upstream, + cfg: upstreamModelSyncTestConfig(), + geminiTokenProvider: NewGeminiTokenProvider(nil, cache, nil), + } + + _, err := svc.FetchUpstreamSupportedModels(context.Background(), vertexModelSyncTestAccount(map[string]any{ + "location": "us-central1.evil.com", + })) + var syncErr *UpstreamModelSyncError + require.ErrorAs(t, err, &syncErr) + require.Equal(t, UpstreamModelSyncErrorConfiguration, syncErr.Kind) + require.Equal(t, "Invalid Vertex location", syncErr.SafeMessage()) + require.Zero(t, cache.calls) + require.Empty(t, upstream.requests) +} + +// Scenario: 翻页途中的 404 不能被当成列表端点不可用而回退到配置模型。 +func TestSyncUpstreamModelCatalogVertexMidPagination404DoesNotFallback(t *testing.T) { + t.Parallel() + + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + vertexModelsJSONResponse(http.StatusOK, `{"publisherModels":[{"name":"publishers/google/models/gemini-a"}],"nextPageToken":"page-2"}`), + vertexModelsJSONResponse(http.StatusNotFound, `{"error":{"code":404}}`), + }} + svc := vertexModelSyncTestService(upstream) + + _, err := svc.SyncUpstreamModelCatalog(context.Background(), vertexModelSyncTestAccount(map[string]any{ + "model_mapping": map[string]any{"x": "gemini-mapped"}, + })) + var syncErr *UpstreamModelSyncError + require.ErrorAs(t, err, &syncErr) + require.Equal(t, UpstreamModelSyncErrorUpstream, syncErr.Kind) + require.Zero(t, syncErr.StatusCode) + require.Len(t, upstream.requests, 2) +} + +func TestFetchUpstreamSupportedModelsVertexFirstPage404KeepsStatus(t *testing.T) { + t.Parallel() + + upstream := &httpUpstreamRecorder{resp: vertexModelsJSONResponse(http.StatusNotFound, `{"error":{"code":404}}`)} + svc := vertexModelSyncTestService(upstream) + + _, err := svc.FetchUpstreamSupportedModels(context.Background(), vertexModelSyncTestAccount(nil)) + require.True(t, upstreamModelListEndpointUnsupported(err)) +} diff --git a/backend/internal/service/vertex_service_account.go b/backend/internal/service/vertex_service_account.go index 085b60904..6a48e6057 100644 --- a/backend/internal/service/vertex_service_account.go +++ b/backend/internal/service/vertex_service_account.go @@ -29,6 +29,8 @@ const ( vertexServiceAccountCacheSkew = 5 * time.Minute vertexLockWaitTime = 200 * time.Millisecond vertexAnthropicVersion = "vertex-2023-10-16" + vertexGlobalHost = "aiplatform.googleapis.com" + vertexAuthModeAPIKey = "apikey" ) var ( @@ -37,6 +39,9 @@ var ( vertexAnthropicAlreadyDatedIDPattern = regexp.MustCompile(`^.+@[0-9]{8}$`) ) +// vertexServiceAccountTokenURL 是换取 SA access token 的端点,测试中替换为本地服务。 +var vertexServiceAccountTokenURL = vertexDefaultTokenURL + type vertexServiceAccountKey struct { Type string `json:"type"` ProjectID string `json:"project_id"` @@ -58,6 +63,13 @@ func (a *Account) IsVertexServiceAccount() bool { return a != nil && a.Type == AccountTypeServiceAccount } +// IsVertexAPIKey 判断 Gemini 平台的 Vertex 账号是否使用 API Key 认证(credentials.auth_mode=apikey)。 +// Anthropic 平台的 Vertex 账号只支持 Service Account JSON。 +func (a *Account) IsVertexAPIKey() bool { + return a.IsVertexServiceAccount() && a.Platform == PlatformGemini && + strings.TrimSpace(a.GetCredential("auth_mode")) == vertexAuthModeAPIKey +} + func (a *Account) VertexProjectID() string { if a == nil { return "" @@ -129,7 +141,7 @@ func parseVertexServiceAccountJSON(raw []byte) (*vertexServiceAccountKey, error) return nil, errors.New("service account json missing project_id") } // Always use the well-known Google token endpoint to prevent SSRF via crafted token_uri. - key.TokenURI = vertexDefaultTokenURL + key.TokenURI = vertexServiceAccountTokenURL return &key, nil } @@ -268,7 +280,12 @@ func exchangeVertexServiceAccountToken(ctx context.Context, key *vertexServiceAc if msg == "" { msg = string(bytes.TrimSpace(body)) } - return "", 0, fmt.Errorf("service account token request returned %d: %s", resp.StatusCode, msg) + return "", 0, &vertexTokenRequestError{ + StatusCode: resp.StatusCode, + Code: strings.TrimSpace(parsed.Error), + Description: strings.TrimSpace(parsed.ErrorDesc), + Message: msg, + } } if strings.TrimSpace(parsed.AccessToken) == "" { return "", 0, errors.New("service account token response missing access_token") @@ -283,6 +300,90 @@ func exchangeVertexServiceAccountToken(ctx context.Context, key *vertexServiceAc return parsed.AccessToken, ttl, nil } +// vertexTokenRequestError 是 token 端点对换取 SA access token 请求返回的非 2xx 响应。 +type vertexTokenRequestError struct { + StatusCode int + Code string // 响应的 error 字段,如 invalid_grant + Description string // 响应的 error_description 字段 + Message string +} + +func (e *vertexTokenRequestError) Error() string { + return fmt.Sprintf("service account token request returned %d: %s", e.StatusCode, e.Message) +} + +// vertexServiceAccountNotFoundError 识别 SA 已不存在:token 端点返回 +// 400 {"error":"invalid_grant","error_description":"Invalid grant: account not found"}。 +// 该凭据再也换不到 token,账号需要人工更换凭据。 +func vertexServiceAccountNotFoundError(err error) (*vertexTokenRequestError, bool) { + var tokenErr *vertexTokenRequestError + if !errors.As(err, &tokenErr) { + return nil, false + } + if tokenErr.StatusCode != http.StatusBadRequest || tokenErr.Code != "invalid_grant" || + !strings.Contains(strings.ToLower(tokenErr.Description), "account not found") { + return nil, false + } + return tokenErr, true +} + +// buildVertexGeminiAccountURL 按账号构造 Vertex Gemini 请求地址:未配置 project_id 的 API Key 账号 +// 走 Express mode 全局端点,其余账号走项目级端点。 +func buildVertexGeminiAccountURL(account *Account, model, action string, stream bool) (string, error) { + if account.IsVertexAPIKey() && account.VertexProjectID() == "" { + return buildVertexGeminiExpressURL(model, action, stream) + } + return buildVertexGeminiURL(account.VertexProjectID(), account.VertexLocation(model), model, action, stream) +} + +// buildVertexGeminiExpressURL 构造不带项目与区域的全局端点地址,仅 API Key 认证可用。 +func buildVertexGeminiExpressURL(model, action string, stream bool) (string, error) { + model = strings.TrimSpace(model) + action = strings.TrimSpace(action) + if model == "" { + return "", errors.New("vertex model is required") + } + if err := validateVertexGeminiAction(action); err != nil { + return "", err + } + u := fmt.Sprintf("https://%s/v1/publishers/google/models/%s:%s", vertexGlobalHost, url.PathEscape(model), action) + if stream { + u += "?alt=sse" + } + return u, nil +} + +func validateVertexGeminiAction(action string) error { + switch action { + case "generateContent", "streamGenerateContent", "countTokens": + return nil + default: + return fmt.Errorf("unsupported vertex gemini action: %s", action) + } +} + +// setVertexGeminiAuth 给 Vertex Gemini 请求设置认证头:API Key 账号用 x-goog-api-key, +// Service Account JSON 账号用换取的 Bearer access token。 +func setVertexGeminiAuth(ctx context.Context, req *http.Request, account *Account, tokenProvider *GeminiTokenProvider) error { + if account.IsVertexAPIKey() { + apiKey := strings.TrimSpace(account.GetCredential("api_key")) + if apiKey == "" { + return errors.New("vertex api_key not configured") + } + req.Header.Set("x-goog-api-key", apiKey) + return nil + } + if tokenProvider == nil { + return errors.New("gemini token provider not configured") + } + accessToken, err := tokenProvider.GetAccessToken(ctx, account) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+accessToken) + return nil +} + func buildVertexGeminiURL(projectID, location, model, action string, stream bool) (string, error) { projectID = strings.TrimSpace(projectID) location = strings.TrimSpace(location) @@ -300,14 +401,12 @@ func buildVertexGeminiURL(projectID, location, model, action string, stream bool if model == "" { return "", errors.New("vertex model is required") } - switch action { - case "generateContent", "streamGenerateContent", "countTokens": - default: - return "", fmt.Errorf("unsupported vertex gemini action: %s", action) + if err := validateVertexGeminiAction(action); err != nil { + return "", err } host := fmt.Sprintf("%s-aiplatform.googleapis.com", location) if location == "global" { - host = "aiplatform.googleapis.com" + host = vertexGlobalHost } u := fmt.Sprintf( "https://%s/v1/projects/%s/locations/%s/publishers/google/models/%s:%s", diff --git a/backend/internal/service/vertex_service_account_test.go b/backend/internal/service/vertex_service_account_test.go index 003f07200..ebb2ce040 100644 --- a/backend/internal/service/vertex_service_account_test.go +++ b/backend/internal/service/vertex_service_account_test.go @@ -30,6 +30,62 @@ func TestBuildVertexGeminiURLUsesGlobalEndpointHost(t *testing.T) { require.Equal(t, "https://aiplatform.googleapis.com/v1/projects/my-project/locations/global/publishers/google/models/gemini-3-flash-preview:streamGenerateContent?alt=sse", got) } +func TestIsVertexAPIKey(t *testing.T) { + apiKeyCreds := map[string]any{"auth_mode": "apikey", "api_key": "k"} + require.True(t, (&Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: apiKeyCreds}).IsVertexAPIKey()) + require.False(t, (&Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{"service_account_json": "{}"}}).IsVertexAPIKey()) + require.False(t, (&Account{Platform: PlatformAnthropic, Type: AccountTypeServiceAccount, Credentials: apiKeyCreds}).IsVertexAPIKey()) + require.False(t, (&Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: apiKeyCreds}).IsVertexAPIKey()) +} + +func TestBuildVertexGeminiAccountURL(t *testing.T) { + cases := []struct { + name string + credentials map[string]any + want string + }{ + { + name: "api key without project uses express global endpoint", + credentials: map[string]any{"auth_mode": "apikey", "api_key": "k", "location": "us-central1"}, + want: "https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-3-flash-preview:streamGenerateContent?alt=sse", + }, + { + name: "api key with project uses project endpoint", + credentials: map[string]any{"auth_mode": "apikey", "api_key": "k", "project_id": "my-project", "location": "us-central1"}, + want: "https://us-central1-aiplatform.googleapis.com/v1/projects/my-project/locations/us-central1/publishers/google/models/gemini-3-flash-preview:streamGenerateContent?alt=sse", + }, + { + name: "service account uses project endpoint", + credentials: map[string]any{"project_id": "sa-project", "location": "global"}, + want: "https://aiplatform.googleapis.com/v1/projects/sa-project/locations/global/publishers/google/models/gemini-3-flash-preview:streamGenerateContent?alt=sse", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + account := &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: tc.credentials} + got, err := buildVertexGeminiAccountURL(account, "gemini-3-flash-preview", "streamGenerateContent", true) + require.NoError(t, err) + require.Equal(t, tc.want, got) + }) + } + + account := &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{"auth_mode": "apikey", "api_key": "k"}} + _, err := buildVertexGeminiAccountURL(account, "gemini-3-flash-preview", "rawPredict", false) + require.ErrorContains(t, err, "unsupported vertex gemini action") +} + +func TestSetVertexGeminiAuthUsesAPIKeyHeader(t *testing.T) { + account := &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: map[string]any{"auth_mode": "apikey", "api_key": " vertex-key "}} + req := httptest.NewRequest(http.MethodPost, "https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-3-flash-preview:generateContent", nil) + + require.NoError(t, setVertexGeminiAuth(context.Background(), req, account, nil)) + require.Equal(t, "vertex-key", req.Header.Get("x-goog-api-key")) + require.Empty(t, req.Header.Get("Authorization")) + + account.Credentials["api_key"] = "" + require.ErrorContains(t, setVertexGeminiAuth(context.Background(), req, account, nil), "vertex api_key not configured") +} + func TestBuildVertexAnthropicURL(t *testing.T) { got, err := buildVertexAnthropicURL("my-project", "us-east5", "claude-sonnet-4-5@20250929", false) require.NoError(t, err) diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index 81abd34b7..29c1b4e33 100644 --- a/backend/internal/service/wire.go +++ b/backend/internal/service/wire.go @@ -640,6 +640,13 @@ func ProvideIdempotencyCleanupService(repo IdempotencyRepository, cfg *config.Co return svc } +// ProvideGeminiCachedContentService creates GeminiCachedContentService and starts its mutation recovery loop. +func ProvideGeminiCachedContentService(repo GeminiCachedContentRepository, compat *GeminiMessagesCompatService, cfg *config.Config) *GeminiCachedContentService { + svc := NewGeminiCachedContentService(repo, compat, cfg) + svc.Start() + return svc +} + // ProvideScheduledTestService creates ScheduledTestService. func ProvideScheduledTestService( planRepo ScheduledTestPlanRepository, @@ -885,6 +892,7 @@ var ProviderSet = wire.NewSet( ProvideGrokOAuthService, wire.Bind(new(GrokOAuthTokenService), new(*GrokOAuthService)), NewGeminiOAuthService, + ProvideGeminiCachedContentService, NewGeminiQuotaService, NewCompositeTokenCacheInvalidator, wire.Bind(new(TokenCacheInvalidator), new(*CompositeTokenCacheInvalidator)), diff --git a/backend/internal/util/logredact/redact.go b/backend/internal/util/logredact/redact.go index 9249b761c..8be6448a1 100644 --- a/backend/internal/util/logredact/redact.go +++ b/backend/internal/util/logredact/redact.go @@ -42,6 +42,8 @@ type textRedactPatterns struct { var ( reGOCSPX = regexp.MustCompile(`GOCSPX-[0-9A-Za-z_-]{24,}`) reAIza = regexp.MustCompile(`AIza[0-9A-Za-z_-]{35}`) + // Gemini auth key:AQ.Ab 前缀 + 48 位,长度放宽以覆盖格式变体。 + reGeminiAuthKey = regexp.MustCompile(`AQ\.Ab[0-9A-Za-z_-]{40,}`) defaultTextRedactPatterns = compileTextRedactPatterns(nil) extraTextPatternCache sync.Map // map[string]*textRedactPatterns @@ -99,6 +101,7 @@ func RedactText(input string, extraKeys ...string) string { out := input out = reGOCSPX.ReplaceAllString(out, "GOCSPX-***") out = reAIza.ReplaceAllString(out, "AIza***") + out = reGeminiAuthKey.ReplaceAllString(out, "AQ.***") out = patterns.reJSONLike.ReplaceAllString(out, `$1***$3`) out = patterns.reQueryLike.ReplaceAllString(out, `$1=***`) out = patterns.rePlain.ReplaceAllString(out, `$1$2***`) diff --git a/backend/internal/util/logredact/redact_test.go b/backend/internal/util/logredact/redact_test.go index 266db69db..e615f33e0 100644 --- a/backend/internal/util/logredact/redact_test.go +++ b/backend/internal/util/logredact/redact_test.go @@ -38,6 +38,28 @@ func TestRedactText_GOCSPX(t *testing.T) { } } +func TestRedactText_GeminiAPIKeys(t *testing.T) { + legacyKey := "AI" + "za" + strings.Repeat("Ab1_-", 7) + authKey := "AQ." + "Ab" + strings.Repeat("Xy9_-z", 8) + in := "upstream rejected " + legacyKey + " and " + authKey + " for model gemini-3.1-pro" + out := RedactText(in) + if strings.Contains(out, legacyKey) || strings.Contains(out, authKey) { + t.Fatalf("expected Gemini keys redacted, got %q", out) + } + for _, want := range []string{"AIza***", "AQ.***", "for model gemini-3.1-pro"} { + if !strings.Contains(out, want) { + t.Fatalf("expected %q in %q", want, out) + } + } +} + +func TestRedactText_GeminiAuthKeyPrefixAloneUnchanged(t *testing.T) { + in := "key format AQ.Ab... is documented" + if out := RedactText(in); out != in { + t.Fatalf("expected short AQ. prefix unchanged, got %q", out) + } +} + func TestRedactText_ExtraKeyCacheUsesNormalizedSortedKey(t *testing.T) { clearExtraTextPatternCache() diff --git a/backend/internal/web/embed_test.go b/backend/internal/web/embed_test.go index 329eb19bf..eeba5072d 100644 --- a/backend/internal/web/embed_test.go +++ b/backend/internal/web/embed_test.go @@ -653,11 +653,11 @@ func TestFrontendServer_Middleware(t *testing.T) { // Request for existing static file w := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/logo.png", nil) + req := httptest.NewRequest(http.MethodGet, "/logo.svg", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) - assert.Contains(t, w.Header().Get("Content-Type"), "image/png") + assert.Contains(t, w.Header().Get("Content-Type"), "image/svg+xml") assert.Empty(t, w.Header().Get("Cache-Control")) entries, err := fs.ReadDir(server.distFS, "assets") @@ -772,11 +772,11 @@ func TestServeEmbeddedFrontend(t *testing.T) { router.Use(middleware) w := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/logo.png", nil) + req := httptest.NewRequest(http.MethodGet, "/logo.svg", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) - assert.Contains(t, w.Header().Get("Content-Type"), "image/png") + assert.Contains(t, w.Header().Get("Content-Type"), "image/svg+xml") }) t.Run("serves_index_html_for_root", func(t *testing.T) { diff --git a/backend/migrations/242_group_i18n.sql b/backend/migrations/242_group_i18n.sql new file mode 100644 index 000000000..2e0ab2c63 --- /dev/null +++ b/backend/migrations/242_group_i18n.sql @@ -0,0 +1,5 @@ +ALTER TABLE groups + ADD COLUMN IF NOT EXISTS i18n JSONB NOT NULL DEFAULT '{}'::jsonb; + +COMMENT ON COLUMN groups.i18n IS + 'Per-locale display text for the group: {"":{"name":string,"description":string}}; locales or fields that are absent fall back to groups.name / groups.description'; diff --git a/backend/migrations/243_gemini_cached_contents.sql b/backend/migrations/243_gemini_cached_contents.sql new file mode 100644 index 000000000..d3cbda27d --- /dev/null +++ b/backend/migrations/243_gemini_cached_contents.sql @@ -0,0 +1,30 @@ +-- Gemini 显式缓存(cachedContents)的网关资源绑定。 +-- public_id 是网关对客户端暴露的缓存 ID;upstream_name 是上游资源名, +-- 引用缓存的请求只能路由到 account_id 对应的账号。 +CREATE TABLE IF NOT EXISTS gemini_cached_contents ( + id BIGSERIAL PRIMARY KEY, + public_id VARCHAR(64) NOT NULL, + user_id BIGINT NOT NULL, + api_key_id BIGINT NOT NULL, + group_id BIGINT NOT NULL, + account_id BIGINT NOT NULL, + upstream_name VARCHAR(512) NOT NULL, + model VARCHAR(255) NOT NULL, + upstream_model VARCHAR(512) NOT NULL, + display_name VARCHAR(512) NOT NULL DEFAULT '', + total_token_count BIGINT NOT NULL DEFAULT 0, + expire_time TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + deleted_at TIMESTAMPTZ NULL +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_gemini_cached_contents_public_id + ON gemini_cached_contents (public_id); + +CREATE INDEX IF NOT EXISTS idx_gemini_cached_contents_api_key_active + ON gemini_cached_contents (api_key_id, id DESC) + WHERE deleted_at IS NULL; + +CREATE INDEX IF NOT EXISTS idx_gemini_cached_contents_account + ON gemini_cached_contents (account_id); diff --git a/backend/migrations/244_gemini_cached_contents_channel_usage.sql b/backend/migrations/244_gemini_cached_contents_channel_usage.sql new file mode 100644 index 000000000..c72f097a7 --- /dev/null +++ b/backend/migrations/244_gemini_cached_contents_channel_usage.sql @@ -0,0 +1,4 @@ +-- Gemini 显式缓存创建时的渠道计费口径(渠道 ID / 请求模型 / 计费模型来源), +-- 延长有效期按同一口径计费。 +ALTER TABLE gemini_cached_contents + ADD COLUMN IF NOT EXISTS channel_usage JSONB NOT NULL DEFAULT '{}'::jsonb; diff --git a/backend/migrations/245_gemini_cached_contents_mutation_lease.sql b/backend/migrations/245_gemini_cached_contents_mutation_lease.sql new file mode 100644 index 000000000..e0970efeb --- /dev/null +++ b/backend/migrations/245_gemini_cached_contents_mutation_lease.sql @@ -0,0 +1,10 @@ +-- Gemini 显式缓存修改有效期的进行中操作(修改意图):mutation_token 标识持有者, +-- mutation_lease_until 之前同一缓存的其他修改被拒绝;expire_time 在提交前保持修改前的值, +-- 租约过期仍未清除的意图由恢复流程把上游有效期回滚到 expire_time。 +ALTER TABLE gemini_cached_contents + ADD COLUMN IF NOT EXISTS mutation_token VARCHAR(64) NULL, + ADD COLUMN IF NOT EXISTS mutation_lease_until TIMESTAMPTZ NULL; + +CREATE INDEX IF NOT EXISTS idx_gemini_cached_contents_pending_mutation + ON gemini_cached_contents (mutation_lease_until) + WHERE mutation_token IS NOT NULL AND deleted_at IS NULL; diff --git a/backend/resources/model-pricing/model_prices_and_context_window.json b/backend/resources/model-pricing/model_prices_and_context_window.json index 99db4dbbd..5e0f608d2 100644 --- a/backend/resources/model-pricing/model_prices_and_context_window.json +++ b/backend/resources/model-pricing/model_prices_and_context_window.json @@ -381,6 +381,40 @@ "supports_tool_choice": true, "supports_vision": true }, + "claude-haiku-5-5": { + "cache_creation_input_token_cost": 1.25e-07, + "cache_creation_input_token_cost_above_1hr": 2e-07, + "cache_creation_input_token_cost_above_100k_tokens": 6.25e-07, + "cache_creation_input_token_cost_above_1hr_above_100k_tokens": 1e-06, + "cache_read_input_token_cost": 1e-08, + "cache_read_input_token_cost_above_100k_tokens": 5e-08, + "input_cost_per_token": 1e-07, + "input_cost_per_token_above_100k_tokens": 5e-07, + "litellm_provider": "anthropic", + "max_input_tokens": 1000000, + "max_output_tokens": 128000, + "max_tokens": 128000, + "mode": "chat", + "output_cost_per_token": 5e-07, + "output_cost_per_token_above_100k_tokens": 2.5e-06, + "source": "https://platform.claude.com/docs/en/models/haiku-5-5/overview", + "supports_adaptive_thinking": true, + "supports_assistant_prefill": false, + "supports_computer_use": true, + "supports_function_calling": true, + "supports_max_reasoning_effort": true, + "supports_output_config": true, + "supports_pdf_input": true, + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_response_schema": true, + "supports_sampling_params": false, + "supports_tool_choice": true, + "supports_vision": true, + "supports_xhigh_reasoning_effort": true, + "input_cost_per_token_batches": 5e-08, + "output_cost_per_token_batches": 2.5e-07 + }, "claude-opus-4-1": { "cache_creation_input_token_cost": 1.875e-05, "cache_creation_input_token_cost_above_1hr": 3e-05, @@ -2616,22 +2650,56 @@ "web_search_billing_unit": "per_query" }, "gemini-3.6-flash": { - "cache_read_input_token_cost": 1.5e-07, - "cache_read_input_token_cost_priority": 2.7e-07, - "input_cost_per_token": 1.5e-06, - "input_cost_per_token_priority": 2.7e-06, + "cache_read_input_token_cost": 7.5e-08, + "cache_read_input_token_cost_priority": 1.35e-07, + "input_cost_per_token": 7.5e-07, + "input_cost_per_token_priority": 1.35e-06, "litellm_provider": "vertex_ai-language-models", "max_input_tokens": 1048576, "max_output_tokens": 65536, "max_tokens": 65536, "mode": "chat", - "output_cost_per_token": 7.5e-06, - "output_cost_per_token_priority": 1.35e-05, + "output_cost_per_token": 3.75e-06, + "output_cost_per_token_priority": 6.75e-06, "source": "https://ai.google.dev/gemini-api/docs/latest-model", "supports_prompt_caching": true, "supports_reasoning": true, "supports_service_tier": true }, + "gemini-4-argon": { + "cache_read_input_token_cost": 1e-07, + "cache_read_input_token_cost_priority": 1.8e-07, + "input_cost_per_token": 2e-06, + "input_cost_per_token_priority": 3.6e-06, + "litellm_provider": "gemini", + "max_input_tokens": 1048576, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 1e-05, + "output_cost_per_token_priority": 1.8e-05, + "source": "https://ai.google.dev/gemini-api/docs/pricing", + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_service_tier": true + }, + "gemini-4-argon-cyber-permissive": { + "cache_read_input_token_cost": 2e-07, + "cache_read_input_token_cost_priority": 3.6e-07, + "input_cost_per_token": 4e-06, + "input_cost_per_token_priority": 7.2e-06, + "litellm_provider": "vertex_ai-language-models", + "max_input_tokens": 1048576, + "max_output_tokens": 65536, + "max_tokens": 65536, + "mode": "chat", + "output_cost_per_token": 2e-05, + "output_cost_per_token_priority": 3.6e-05, + "source": "https://cloud.google.com/gemini-enterprise-agent-platform/generative-ai/pricing", + "supports_prompt_caching": true, + "supports_reasoning": true, + "supports_service_tier": true + }, "gemini-embedding-001": { "input_cost_per_token": 1.5e-07, "litellm_provider": "vertex_ai-embedding-models", diff --git a/changelog/1.1.11/CHANGELOG.md b/changelog/1.1.11/CHANGELOG.md new file mode 100644 index 000000000..214160076 --- /dev/null +++ b/changelog/1.1.11/CHANGELOG.md @@ -0,0 +1,24 @@ +# v1.1.11 + +## 上游同步 + +- 对齐 SUB2API 0.2.17,包含 0.2.16、0.2.17 的完整代码增量;上游提交:`b0a02a3304a0a78cdd003ddda1dd23ba02c03084`。 +- 新增 Gemini 显式缓存、Vertex API Key 认证、Gemini 4 Argon、兼容入口思考档位和流式思考摘要。 +- 新增分组多语言展示、可配置最小输出 token,并修复 Responses `created_at`、Codex 工作区导入和模型调度问题。 +- 合并支付订单类型校验、退款待定扣减和失败回退、支付宝退款查询、易支付查单确认及 Stripe 支付页修复。 + +## Sub4API 兼容与打包 + +- 保留 `github.com/MACOS-DO/sub4api` 模块路径、OpenAI BPS、Codex 定制和本仓库的在线更新源。 +- 调度缓存同时保留 BPS 工作区信息与 Gemini 显式缓存能力;合并 composite OAuth 路由保护与 BPS 排除规则。 +- 部署模板默认使用 `ghcr.io/info-talent/sub4api:latest`,可通过 `SUB4API_IMAGE` 指定私有镜像或固定版本。 +- 保持本仓库的 GHCR / Docker Hub 发布流程,以及 `sub4api` 安装包和旧更新器需要的 `sub2api` 兼容包。 +- 发布地址与在线更新源改为 `info-talent/sub4api`;GHCR 可直接使用 GitHub Actions 的 `GITHUB_TOKEN` 发布,Docker Hub 仅在配置两项凭据后启用。 +- 前端包名改为 `sub4api-frontend`,版本同步为 1.1.11,并固定 pnpm 9.15.9。 +- 修复 Windows 交叉打包时 Unix 安装包丢失可执行权限的问题;归档显式保留二进制和部署脚本的 0755 权限,并新增 CI 打包回归检查。 + +## 升级说明 + +- 启动时自动应用新增的分组 i18n 和 Gemini 缓存迁移。迁移以完整文件名识别,不修改已经发布的 SQL 文件;升级前请备份 PostgreSQL。 +- 上游已停止向 ChatGPT OAuth / SetupToken 账号调度 `gpt-5.5`;使用该模型的站点需要调整模型映射或使用 API Key 账号。详见 `docs/OPENAI_GPT55_RETIREMENT.md`。 +- 保留已有服务名、数据目录和容器内 `sub2api` 可执行文件名,兼容现有部署与更新器。 diff --git a/deploy/.env.example b/deploy/.env.example index fa10e83e7..9fee859be 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -30,9 +30,12 @@ UPDATE_GITHUB_TOKEN= # Return Server-Timing for authenticated requests made by the Admin web UI ENABLE_SERVER_TIMING=false +# Docker Compose application image. Pin a version or digest for reproducible deployments. +SUB4API_IMAGE=ghcr.io/info-talent/sub4api:latest + # Apple container image overrides (ignored by Docker Compose). Pin release tags # or digests for repeatable operator-managed deployments. -APPLE_CONTAINER_SUB2API_IMAGE=weishaw/sub2api:latest +APPLE_CONTAINER_SUB2API_IMAGE=ghcr.io/info-talent/sub4api:latest APPLE_CONTAINER_POSTGRES_IMAGE=postgres:18-alpine APPLE_CONTAINER_REDIS_IMAGE=redis:8-alpine diff --git a/deploy/APPLE_CONTAINER.md b/deploy/APPLE_CONTAINER.md index 69cc4aa2c..2edfe9b23 100644 --- a/deploy/APPLE_CONTAINER.md +++ b/deploy/APPLE_CONTAINER.md @@ -25,7 +25,7 @@ container --version ## Quick Start ```bash -git clone https://github.com/MACOS-DO/sub4api.git +git clone https://github.com/info-talent/sub4api.git cd sub2api/deploy # Creates .env with random PostgreSQL, JWT, and TOTP secrets. @@ -100,7 +100,7 @@ export SUB2API_ENV_FILE=/absolute/path/to/sub2api.env Apple-specific image overrides are available: ```dotenv -APPLE_CONTAINER_SUB2API_IMAGE=weishaw/sub2api:latest +APPLE_CONTAINER_SUB2API_IMAGE=ghcr.io/info-talent/sub4api:latest APPLE_CONTAINER_POSTGRES_IMAGE=postgres:18-alpine APPLE_CONTAINER_REDIS_IMAGE=redis:8-alpine ``` @@ -199,7 +199,7 @@ To restore these backups into an existing stack, first ensure the image versions # Remove only the app container so a helper can mount its named volume. container delete sub2api-apple -SUB2API_IMAGE=weishaw/sub2api:latest # Match APPLE_CONTAINER_SUB2API_IMAGE in .env. +SUB2API_IMAGE=ghcr.io/info-talent/sub4api:latest # Match APPLE_CONTAINER_SUB2API_IMAGE in .env. container run --rm --name sub2api-apple-data-restore \ --entrypoint /bin/sh \ --volume sub2api-apple-data:/restore \ diff --git a/deploy/DOCKER.md b/deploy/DOCKER.md index 87d1f83a2..0d7874dae 100644 --- a/deploy/DOCKER.md +++ b/deploy/DOCKER.md @@ -10,7 +10,7 @@ docker run -d \ -p 8080:8080 \ -e DATABASE_URL="postgres://user:pass@host:5432/sub2api" \ -e REDIS_URL="redis://host:6379" \ - weishaw/sub2api:latest + ghcr.io/info-talent/sub4api:latest ``` ## Docker Compose @@ -20,7 +20,7 @@ version: '3.8' services: sub2api: - image: weishaw/sub2api:latest + image: ghcr.io/info-talent/sub4api:latest ports: - "8080:8080" environment: @@ -86,5 +86,5 @@ Docker restores existing containers after a host restart. ## Links -- [GitHub Repository](https://github.com/weishaw/sub2api) -- [Documentation](https://github.com/weishaw/sub2api#readme) +- [GitHub Repository](https://github.com/info-talent/sub4api) +- [Documentation](https://github.com/info-talent/sub4api#readme) diff --git a/deploy/Dockerfile b/deploy/Dockerfile index c2e0ef7ef..c09be788f 100644 --- a/deploy/Dockerfile +++ b/deploy/Dockerfile @@ -84,9 +84,9 @@ RUN VERSION_VALUE="${VERSION}" && \ FROM ${ALPINE_IMAGE} # Labels -LABEL maintainer="Wei-Shaw " -LABEL description="Sub2API - AI API Gateway Platform" -LABEL org.opencontainers.image.source="https://github.com/MACOS-DO/sub4api" +LABEL maintainer="info-talent " +LABEL description="Sub4API - AI API Gateway Platform" +LABEL org.opencontainers.image.source="https://github.com/info-talent/sub4api" # Install runtime dependencies RUN apk add --no-cache \ diff --git a/deploy/README.md b/deploy/README.md index 7d3bacac2..34caf28b8 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -56,10 +56,10 @@ Use the automated preparation script for the easiest setup: ```bash # Download and run the preparation script -curl -sSL https://raw.githubusercontent.com/MACOS-DO/sub4api/main/deploy/docker-deploy.sh | bash +curl -sSL https://raw.githubusercontent.com/info-talent/sub4api/main/deploy/docker-deploy.sh | bash # Or download first, then run -curl -sSL https://raw.githubusercontent.com/MACOS-DO/sub4api/main/deploy/docker-deploy.sh -o docker-deploy.sh +curl -sSL https://raw.githubusercontent.com/info-talent/sub4api/main/deploy/docker-deploy.sh -o docker-deploy.sh chmod +x docker-deploy.sh ./docker-deploy.sh ``` @@ -92,7 +92,7 @@ If you prefer manual control: ```bash # Clone repository -git clone https://github.com/MACOS-DO/sub4api.git +git clone https://github.com/info-talent/sub4api.git cd sub2api/deploy # Configure environment @@ -398,12 +398,12 @@ For production servers using systemd. ### One-Line Installation ```bash -curl -sSL https://raw.githubusercontent.com/MACOS-DO/sub4api/main/deploy/install.sh | sudo bash +curl -sSL https://raw.githubusercontent.com/info-talent/sub4api/main/deploy/install.sh | sudo bash ``` ### Manual Installation -1. Download the latest release from [GitHub Releases](https://github.com/MACOS-DO/sub4api/releases) +1. Download the latest release from [GitHub Releases](https://github.com/info-talent/sub4api/releases) 2. Extract and copy the binary to `/opt/sub2api/` 3. Copy `sub2api.service` to `/etc/systemd/system/` 4. Run: diff --git a/deploy/apple-container.sh b/deploy/apple-container.sh index 5a44ae5b3..a8a0844a8 100755 --- a/deploy/apple-container.sh +++ b/deploy/apple-container.sh @@ -414,7 +414,7 @@ validate_env_file_security() { prepare_environment() { validate_env_file_security - APP_IMAGE="$(read_env_value APPLE_CONTAINER_SUB2API_IMAGE weishaw/sub2api:latest)" + APP_IMAGE="$(read_env_value APPLE_CONTAINER_SUB2API_IMAGE ghcr.io/info-talent/sub4api:latest)" POSTGRES_IMAGE="$(read_env_value APPLE_CONTAINER_POSTGRES_IMAGE postgres:18-alpine)" REDIS_IMAGE="$(read_env_value APPLE_CONTAINER_REDIS_IMAGE redis:8-alpine)" BIND_HOST="$(read_env_value BIND_HOST 0.0.0.0)" diff --git a/deploy/build_image.sh b/deploy/build_image.sh index 2426f9155..838ce60a4 100755 --- a/deploy/build_image.sh +++ b/deploy/build_image.sh @@ -6,7 +6,7 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" -docker build -t sub2api:latest \ +docker build -t "${SUB4API_IMAGE:-ghcr.io/info-talent/sub4api:latest}" \ --build-arg GOPROXY=https://goproxy.cn,direct \ --build-arg GOSUMDB=sum.golang.google.cn \ -f "${REPO_ROOT}/Dockerfile" \ diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index 9754930e9..3bb978263 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -4,7 +4,7 @@ # Copy this file to /etc/sub2api/config.yaml and modify as needed # 复制此文件到 /etc/sub2api/config.yaml 并根据需要修改 # -# Documentation / 文档: https://github.com/MACOS-DO/sub4api +# Documentation / 文档: https://github.com/info-talent/sub4api # ============================================================================= # Server Configuration @@ -217,6 +217,9 @@ security: # 网关配置 # ============================================================================= gateway: + # Minimum max_output_tokens when converting Chat Completions or Anthropic requests to Responses (minimum 16, default 128) + # Chat Completions 或 Anthropic 请求转换为 Responses 时的最小 max_output_tokens(最小 16,默认 128) + min_output_tokens: 128 # Timeout for waiting upstream response headers (seconds) # 等待上游响应头超时时间(秒) response_header_timeout: 600 @@ -253,6 +256,9 @@ gateway: # Enable Gemini upstream response header debug logs (default: false) # 是否开启 Gemini 上游响应头调试日志(默认 false) gemini_debug_response_headers: false + # Maximum TTL (seconds) a Gemini explicit context cache may be created or extended to (default: 86400) + # Gemini 显式上下文缓存单次可设置的最长有效期(秒,默认 86400);存储费在创建/延长请求中一次性收取 + gemini_cached_content_max_ttl_seconds: 86400 # Connection pool isolation strategy: # 连接池隔离策略: # - proxy: Isolate by proxy, same proxy shares connection pool (suitable for few proxies, many accounts) @@ -318,6 +324,8 @@ gateway: # OpenAI /responses/compact 上游模型(默认 gpt-5.5)。 # Use this to avoid compact failures when newer models are not yet supported by the compact endpoint. # 当 compact 端点暂未支持更新模型时,可通过这里降级规避失败。 + # GPT-5.5 is API-only after its ChatGPT Codex retirement; subscription + # requests skip this retired fallback and keep their selected model. openai_compact_model: "gpt-5.5" # ChatGPT OAuth x-codex-turn-state ticket: harvest a 292-length header via a # dedicated HTTP(S)/SOCKS proxy, store it for ttl_seconds (default 3600), then inject @@ -1129,6 +1137,14 @@ pricing: # 覆盖补丁文件(可选,优先级最高):条目按字段浅合并覆盖目录/回退数据, # 字段值为 null 表示删除该字段。模型名须与目录键完全一致。 # 修改后在下一次哈希检查时按内容哈希自动重载,无需重启。 + # Gemini explicit context caching storage price (USD per token per hour) comes + # from the field cache_storage_cost_per_token_per_hour here, e.g. + # {"gemini-3.8-flash": {"cache_storage_cost_per_token_per_hour": 0.0000005}}; + # without it, built-in official prices apply (released models first, then the + # Pro / Flash series rate). Models with no price at all reject POST /v1beta/cachedContents. + # Gemini 显式缓存存储单价(每 token 每小时,USD)优先取这里的 cache_storage_cost_per_token_per_hour 字段, + # 未配置时使用内置官方价(先按已发布型号,再按 Pro / Flash 系列兜底);两者都没有的模型拒绝创建缓存。 + # 目录中不存在的模型条目还须同时提供 input_cost_per_token / output_cost_per_token。 # override_file: "./data/model_pricing_overrides.json" # Update interval in hours # 更新间隔(小时) diff --git a/deploy/docker-compose.local.yml b/deploy/docker-compose.local.yml index 32bc439f4..514396506 100644 --- a/deploy/docker-compose.local.yml +++ b/deploy/docker-compose.local.yml @@ -24,7 +24,7 @@ services: # Sub2API Application # =========================================================================== sub2api: - image: weishaw/sub2api:latest + image: ${SUB4API_IMAGE:-ghcr.io/info-talent/sub4api:latest} container_name: sub2api restart: unless-stopped security_opt: diff --git a/deploy/docker-compose.standalone.yml b/deploy/docker-compose.standalone.yml index fe9619df1..076c7dac5 100644 --- a/deploy/docker-compose.standalone.yml +++ b/deploy/docker-compose.standalone.yml @@ -12,7 +12,7 @@ services: sub2api: - image: weishaw/sub2api:latest + image: ${SUB4API_IMAGE:-ghcr.io/info-talent/sub4api:latest} container_name: sub2api restart: unless-stopped security_opt: diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 84c98643e..1f6063db5 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -16,7 +16,7 @@ services: # Sub2API Application # =========================================================================== sub2api: - image: weishaw/sub2api:latest + image: ${SUB4API_IMAGE:-ghcr.io/info-talent/sub4api:latest} container_name: sub2api restart: unless-stopped security_opt: diff --git a/deploy/docker-deploy.sh b/deploy/docker-deploy.sh index c572a7a62..5a372a3b7 100644 --- a/deploy/docker-deploy.sh +++ b/deploy/docker-deploy.sh @@ -22,7 +22,7 @@ BLUE='\033[0;34m' NC='\033[0m' # No Color # GitHub raw content base URL -GITHUB_RAW_URL="https://raw.githubusercontent.com/MACOS-DO/sub4api/main/deploy" +GITHUB_RAW_URL="https://raw.githubusercontent.com/info-talent/sub4api/main/deploy" # Print colored message print_info() { diff --git a/deploy/install.sh b/deploy/install.sh index 41ed34338..8d72cd97b 100644 --- a/deploy/install.sh +++ b/deploy/install.sh @@ -2,7 +2,7 @@ # # Sub2API Installation Script # Sub2API 安装脚本 -# Usage: curl -sSL https://raw.githubusercontent.com/MACOS-DO/sub4api/main/deploy/install.sh | bash +# Usage: curl -sSL https://raw.githubusercontent.com/info-talent/sub4api/main/deploy/install.sh | bash # set -e @@ -31,7 +31,7 @@ CYAN='\033[0;36m' NC='\033[0m' # No Color # Configuration -GITHUB_REPO="MACOS-DO/sub4api" +GITHUB_REPO="info-talent/sub4api" INSTALL_DIR="/opt/sub2api" SERVICE_NAME="sub2api" SERVICE_USER="sub2api" @@ -718,7 +718,7 @@ install_service() { cat > /etc/systemd/system/sub2api.service << EOF [Unit] Description=Sub2API - AI API Gateway Platform -Documentation=https://github.com/MACOS-DO/sub4api +Documentation=https://github.com/info-talent/sub4api After=network.target postgresql.service redis.service Wants=postgresql.service redis.service diff --git a/deploy/sub2api.service b/deploy/sub2api.service index a72f8d0ef..7f719b136 100644 --- a/deploy/sub2api.service +++ b/deploy/sub2api.service @@ -1,6 +1,6 @@ [Unit] Description=Sub2API - AI API Gateway Platform -Documentation=https://github.com/MACOS-DO/sub4api +Documentation=https://github.com/info-talent/sub4api After=network.target postgresql.service redis.service Wants=postgresql.service redis.service diff --git a/deploy/tests/install-github-token-test.sh b/deploy/tests/install-github-token-test.sh index 7deaad55a..f5604eace 100755 --- a/deploy/tests/install-github-token-test.sh +++ b/deploy/tests/install-github-token-test.sh @@ -24,7 +24,7 @@ run_api_curl() { CURL_ARGS_LOG="$1" HOME="$TEMP_DIR/home" PATH="$TEMP_DIR:$PATH" UPDATE_GITHUB_TOKEN="${2:-}" \ GITHUB_TOKEN="github-fallback" GH_TOKEN="gh-fallback" \ bash -c 'source <(head -n -1 "$1"); github_api_curl -s "$2"' bash \ - "$ROOT_DIR/deploy/install.sh" "https://api.github.com/repos/MACOS-DO/sub4api/releases/latest" + "$ROOT_DIR/deploy/install.sh" "https://api.github.com/repos/info-talent/sub4api/releases/latest" } run_api_curl "$TEMP_DIR/authenticated" "update-secret" @@ -41,7 +41,7 @@ if grep -Eq 'update-secret|github-fallback|gh-fallback' "$TEMP_DIR/authenticated echo "installer exposed a token in curl environment" >&2 exit 1 fi -test "$(grep -Fxc 'https://api.github.com/repos/MACOS-DO/sub4api/releases/latest' "$TEMP_DIR/authenticated")" -eq 1 +test "$(grep -Fxc 'https://api.github.com/repos/info-talent/sub4api/releases/latest' "$TEMP_DIR/authenticated")" -eq 1 if grep -Fq 'example.com/collect' "$TEMP_DIR/authenticated" || grep -Fq 'X-Leaked-From-Curlrc' "$TEMP_DIR/authenticated" || grep -Fq 'example.com/collect' "$TEMP_DIR/authenticated.stdin" || grep -Fq 'X-Leaked-From-Curlrc' "$TEMP_DIR/authenticated.stdin"; then echo "installer allowed hostile curl config into authenticated invocation" >&2 @@ -59,7 +59,7 @@ if grep -Fq 'Authorization:' "$TEMP_DIR/anonymous"; then exit 1 fi test ! -s "$TEMP_DIR/anonymous.stdin" -test "$(grep -Fxc 'https://api.github.com/repos/MACOS-DO/sub4api/releases/latest' "$TEMP_DIR/anonymous")" -eq 1 +test "$(grep -Fxc 'https://api.github.com/repos/info-talent/sub4api/releases/latest' "$TEMP_DIR/anonymous")" -eq 1 if grep -Fq 'example.com/collect' "$TEMP_DIR/anonymous" || grep -Fq 'X-Leaked-From-Curlrc' "$TEMP_DIR/anonymous"; then echo "installer allowed hostile curl config into anonymous invocation" >&2 exit 1 @@ -82,16 +82,16 @@ assert_unsafe_invocation_rejected() { } assert_unsafe_invocation_rejected non-api -s \ - "https://github.com/MACOS-DO/sub4api/releases/download/v1/asset" + "https://github.com/info-talent/sub4api/releases/download/v1/asset" assert_unsafe_invocation_rejected mixed-host -s \ - "https://api.github.com/repos/MACOS-DO/sub4api/releases/latest" \ + "https://api.github.com/repos/info-talent/sub4api/releases/latest" \ "https://example.com/collect" assert_unsafe_invocation_rejected multiple-api -s \ - "https://api.github.com/repos/MACOS-DO/sub4api/releases/latest" \ - "https://api.github.com/repos/MACOS-DO/sub4api/releases" + "https://api.github.com/repos/info-talent/sub4api/releases/latest" \ + "https://api.github.com/repos/info-talent/sub4api/releases" assert_unsafe_invocation_rejected url-option -s --url \ "https://example.com/collect" \ - "https://api.github.com/repos/MACOS-DO/sub4api/releases/latest" + "https://api.github.com/repos/info-talent/sub4api/releases/latest" # Every installer release API request must use the scoped helper. test "$(grep -c 'github_api_curl .*https://api.github.com/' "$ROOT_DIR/deploy/install.sh")" -eq 3 diff --git a/docs/OPENAI_GPT55_RETIREMENT.md b/docs/OPENAI_GPT55_RETIREMENT.md new file mode 100644 index 000000000..3c261373d --- /dev/null +++ b/docs/OPENAI_GPT55_RETIREMENT.md @@ -0,0 +1,43 @@ +# GPT-5.5 retirement on ChatGPT-backed Codex accounts + +OpenAI retired GPT-5.5 from Codex with ChatGPT sign-in on October 14, +2026 at 19:00 UTC (October 15 at 03:00 in Asia/Shanghai). Official API access +is unaffected. See the [official migration notice](https://learn.chatgpt.com/docs/models#gpt-55-retirement). + +Sub2API applies this distinction to the upstream account, not the key used by +clients to authenticate to Sub2API: + +- OpenAI OAuth and SetupToken accounts, including credential shadows, cannot + serve GPT-5.5. Normal, sticky, and compact scheduling exclude these targets. +- API-key accounts retain GPT-5.5 support. In mixed groups, only eligible API-key + upstreams can serve it. Their actual model availability remains authoritative. +- Public model lists and Codex catalogs omit models whose targets are retired on + the group's ChatGPT accounts and have no supporting API-key account. This also + filters stale/pinned catalog entries before calculating the client ETag. +- Explicit administrator mappings to a supported replacement remain valid. + Aliases mapped *to* GPT-5.5 are excluded from ChatGPT account routing. + Remote catalogs are projected to public aliases before retirement filtering, + using the same single mapping step as routing. Source metadata and shared + upstream caches are preserved, including when source IDs are also alias keys. +- Unsupported requests return the existing `model_not_found` error with migration + guidance when the availability diagnosis identifies a retired subscription + target. Client chat requests are not silently rewritten to a replacement. + +## Administrator migration + +Review group/account mappings, client defaults, custom agents and scheduled tasks +that select GPT-5.5. OpenAI recommends GPT-6.1 Sol for eligible paid plans or +GPT-6 Luna for Free/Go in the desktop app, subject to model availability. Check +availability on the upstream account before selecting a replacement. + +The global `gateway.openai_compact_model` setting remains compatible with API-key +upstreams. If that fallback resolves to retired GPT-5.5 on a ChatGPT account, it +is not applied; compact requests keep their selected model. A compact-only +account mapping targeting retired GPT-5.5 is ineligible for scheduling: update +that explicit mapping. No stored settings are automatically rewritten. + +Changing the public registry, deleting GPT-5.5 pricing/history, or globally +mapping GPT-5.5 to a new model is unnecessary and would affect valid API usage. + +Regression tests use local fixtures and stub upstream responses. They do not +establish real subscription access to a replacement model. diff --git a/frontend/package.json b/frontend/package.json index e714a702f..ba86cb7cc 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,8 @@ { - "name": "sub2api-frontend", + "name": "sub4api-frontend", "private": true, - "version": "1.0.0", + "version": "1.1.11", + "packageManager": "pnpm@9.15.9", "type": "module", "scripts": { "dev": "vite", diff --git a/frontend/src/components/account/AccountGroupsCell.vue b/frontend/src/components/account/AccountGroupsCell.vue index 37771275f..98b80d8f3 100644 --- a/frontend/src/components/account/AccountGroupsCell.vue +++ b/frontend/src/components/account/AccountGroupsCell.vue @@ -1,7 +1,7 @@ diff --git a/frontend/src/components/admin/group/GroupRPMOverridesModal.vue b/frontend/src/components/admin/group/GroupRPMOverridesModal.vue index f1c6d97bb..50c15aac8 100644 --- a/frontend/src/components/admin/group/GroupRPMOverridesModal.vue +++ b/frontend/src/components/admin/group/GroupRPMOverridesModal.vue @@ -246,6 +246,7 @@ const currentPage = ref(1) const pageSize = ref(10) let searchTimeout: ReturnType +let loadVersion = 0 const platformColorClass = computed(() => { switch (props.group?.platform) { @@ -273,16 +274,22 @@ const cloneEntries = (entries: GroupRPMOverrideEntry[]): LocalEntry[] => { const loadEntries = async () => { if (!props.group) return + const version = loadVersion loading.value = true + serverEntries.value = [] + localEntries.value = [] try { - serverEntries.value = await adminAPI.groups.getGroupRPMOverrides(props.group.id) + const entries = await adminAPI.groups.getGroupRPMOverrides(props.group.id) + if (version !== loadVersion) return + serverEntries.value = entries localEntries.value = cloneEntries(serverEntries.value) adjustPage() } catch (error) { + if (version !== loadVersion) return appStore.showError(t('admin.groups.failedToLoad')) console.error('Error loading RPM overrides:', error) } finally { - loading.value = false + if (version === loadVersion) loading.value = false } } @@ -291,8 +298,9 @@ const adjustPage = () => { if (currentPage.value > totalPages) currentPage.value = totalPages } -watch(() => props.show, (val) => { - if (val && props.group) { +watch([() => props.show, () => props.group?.id], ([show]) => { + loadVersion++ + if (show && props.group) { currentPage.value = 1 searchQuery.value = '' searchResults.value = [] @@ -423,6 +431,7 @@ if (typeof document !== 'undefined') { document.addEventListener('click', handleClickOutside) } onUnmounted(() => { + loadVersion++ clearTimeout(searchTimeout) document.removeEventListener('click', handleClickOutside) }) diff --git a/frontend/src/components/admin/group/GroupRateMultipliersModal.vue b/frontend/src/components/admin/group/GroupRateMultipliersModal.vue index efeb95e0e..dfcd238f3 100644 --- a/frontend/src/components/admin/group/GroupRateMultipliersModal.vue +++ b/frontend/src/components/admin/group/GroupRateMultipliersModal.vue @@ -426,7 +426,7 @@ const updateLocalRate = (userId: number, value: string) => { return } const num = parseFloat(value) - if (isNaN(num)) return + if (!Number.isFinite(num) || num <= 0) return entry.rate_multiplier = num } diff --git a/frontend/src/components/admin/group/__tests__/GroupI18nField.spec.ts b/frontend/src/components/admin/group/__tests__/GroupI18nField.spec.ts new file mode 100644 index 000000000..c91176a07 --- /dev/null +++ b/frontend/src/components/admin/group/__tests__/GroupI18nField.spec.ts @@ -0,0 +1,197 @@ +import { enableAutoUnmount, mount } from '@vue/test-utils' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { defineComponent, h, reactive } from 'vue' + +import GroupI18nField from '../GroupI18nField.vue' +import type { GroupI18n } from '@/types' + +vi.mock('vue-i18n', async () => { + const actual = await vi.importActual('vue-i18n') + return { + ...actual, + useI18n: () => ({ + t: (key: string, params?: Record) => + params ? `${key}:${params.language}` : key + }) + } +}) + +// 用例把组件挂到 document.body 上以断言焦点,逐例卸载避免互相残留 +enableAutoUnmount(afterEach) + +// 挂载一个 v-model 双向绑定的宿主,贴近分组表单里的真实用法。 +const mountField = ( + initial: { text: string; i18n: GroupI18n }, + fieldProps: Record = {} +) => { + const state = reactive({ text: initial.text, i18n: initial.i18n }) + const host = defineComponent({ + setup() { + return () => + h(GroupI18nField, { + label: 'Name', + field: 'name', + ...fieldProps, + modelValue: state.text, + 'onUpdate:modelValue': (value: string) => { + state.text = value + }, + i18n: state.i18n, + 'onUpdate:i18n': (value: GroupI18n) => { + state.i18n = value + } + }) + } + }) + return { wrapper: mount(host, { attachTo: document.body }), state } +} + +type Wrapper = ReturnType['wrapper'] + +const trigger = (wrapper: Wrapper) => wrapper.get('[data-testid="group-i18n-menu"]') +const menuItems = (wrapper: Wrapper) => wrapper.findAll('button[data-locale]') +const choose = async (wrapper: Wrapper, locale: string) => { + await trigger(wrapper).trigger('click') + await wrapper.get(`button[data-locale="${locale}"]`).trigger('click') +} + +describe('GroupI18nField', () => { + it('renders the label and the switcher on one row above a single input', () => { + const { wrapper } = mountField({ text: '标准', i18n: { en: { name: 'Standard' } } }) + + const labelRow = wrapper.get('label').element.parentElement! + expect(wrapper.get('label').text()).toBe('Name') + expect(labelRow.contains(trigger(wrapper).element)).toBe(true) + expect(labelRow.contains(wrapper.get('input').element)).toBe(false) + expect(wrapper.findAll('input')).toHaveLength(1) + }) + + it('starts on the default content', async () => { + const { wrapper, state } = mountField({ text: '标准', i18n: { en: { name: 'Standard' } } }) + const input = wrapper.get('input') + + expect(input.element.value).toBe('标准') + expect(trigger(wrapper).text()).toBe('admin.groups.i18nField.default') + + await input.setValue('标准版') + + expect(state.text).toBe('标准版') + expect(state.i18n).toEqual({ en: { name: 'Standard' } }) + }) + + it('lists the default content and an add or edit entry per interface language', async () => { + const { wrapper } = mountField({ + text: '标准', + i18n: { en: { name: 'Standard' }, zh: { description: '仅描述' } } + }) + + await trigger(wrapper).trigger('click') + + expect(menuItems(wrapper).map((item) => [item.attributes('data-locale'), item.text()])).toEqual([ + ['default', 'admin.groups.i18nField.default'], + ['en', 'admin.groups.i18nField.edit:English'], + ['zh', 'admin.groups.i18nField.add:中文'] + ]) + }) + + it('switches the same input to the chosen language version', async () => { + const { wrapper, state } = mountField({ text: '标准', i18n: { en: { name: 'Standard' } } }) + + await choose(wrapper, 'en') + + expect(menuItems(wrapper)).toHaveLength(0) + expect(wrapper.findAll('input')).toHaveLength(1) + const input = wrapper.get('input') + expect(input.element.value).toBe('Standard') + expect(document.activeElement).toBe(input.element) + expect(trigger(wrapper).text()).toBe('English') + + await input.setValue('Standard v2') + + expect(state.text).toBe('标准') + expect(state.i18n).toEqual({ en: { name: 'Standard v2' } }) + }) + + it('starts a new language version empty and keeps the other field of that language', async () => { + const { wrapper, state } = mountField({ + text: '标准', + i18n: { en: { description: 'Pro + Max pool' } } + }) + + await choose(wrapper, 'en') + const input = wrapper.get('input') + expect(input.element.value).toBe('') + expect(input.attributes('placeholder')).toBe('admin.groups.i18nField.placeholder:English') + + await input.setValue('Standard') + + expect(state.i18n).toEqual({ en: { name: 'Standard', description: 'Pro + Max pool' } }) + }) + + it('returns to the default content from a language version', async () => { + const { wrapper } = mountField({ text: '标准', i18n: { en: { name: 'Standard' } } }) + + await choose(wrapper, 'en') + await choose(wrapper, 'zh') + expect(wrapper.get('input').element.value).toBe('') + + await choose(wrapper, 'default') + + expect(wrapper.get('input').element.value).toBe('标准') + expect(trigger(wrapper).text()).toBe('admin.groups.i18nField.default') + }) + + it('marks the version being edited in the menu', async () => { + const { wrapper } = mountField({ text: '标准', i18n: {} }) + + await choose(wrapper, 'zh') + await trigger(wrapper).trigger('click') + + const checked = menuItems(wrapper) + .filter((item) => item.find('svg').exists()) + .map((item) => item.attributes('data-locale')) + expect(checked).toEqual(['zh']) + }) + + it('requires only the default content and keeps the form placeholder for it', async () => { + const { wrapper } = mountField( + { text: '', i18n: {} }, + { required: true, placeholder: 'Enter name', 'data-tour': 'group-form-name' } + ) + const input = wrapper.get('input') + expect(input.attributes('required')).toBeDefined() + expect(input.attributes('placeholder')).toBe('Enter name') + expect(input.attributes('data-tour')).toBe('group-form-name') + + await choose(wrapper, 'en') + + expect(wrapper.get('input').attributes('required')).toBeUndefined() + }) + + it('switches a single textarea for multiline fields', async () => { + const { wrapper, state } = mountField( + { text: '号池', i18n: {} }, + { field: 'description', multiline: true, rows: '3' } + ) + expect(wrapper.findAll('textarea')).toHaveLength(1) + expect(wrapper.get('textarea').attributes('rows')).toBe('3') + + await choose(wrapper, 'en') + await wrapper.get('textarea').setValue('Pro + Max pool') + + expect(wrapper.findAll('textarea')).toHaveLength(1) + expect(state.i18n).toEqual({ en: { description: 'Pro + Max pool' } }) + expect(state.text).toBe('号池') + }) + + it('closes the menu when clicking elsewhere', async () => { + const { wrapper } = mountField({ text: '标准', i18n: {} }) + await trigger(wrapper).trigger('click') + expect(menuItems(wrapper)).toHaveLength(3) + + document.body.click() + await wrapper.vm.$nextTick() + + expect(menuItems(wrapper)).toHaveLength(0) + }) +}) diff --git a/frontend/src/components/admin/group/__tests__/GroupRPMOverridesModal.requests.spec.ts b/frontend/src/components/admin/group/__tests__/GroupRPMOverridesModal.requests.spec.ts new file mode 100644 index 000000000..bd4c3ffc1 --- /dev/null +++ b/frontend/src/components/admin/group/__tests__/GroupRPMOverridesModal.requests.spec.ts @@ -0,0 +1,100 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils' +import type { AdminGroup } from '@/types' +import GroupRPMOverridesModal from '../GroupRPMOverridesModal.vue' + +const mocks = vi.hoisted(() => ({ getGroupRPMOverrides: vi.fn(), batchSetGroupRPMOverrides: vi.fn(), showError: vi.fn() })) +vi.mock('@/api/admin', () => ({ adminAPI: { groups: mocks } })) +vi.mock('@/stores/app', () => ({ useAppStore: () => ({ showError: mocks.showError, showSuccess: vi.fn() }) })) +vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) })) +enableAutoUnmount(afterEach) +beforeEach(() => vi.resetAllMocks()) +afterEach(() => vi.restoreAllMocks()) + +function deferred() { + let resolve!: (value: unknown) => void + let reject!: (reason: unknown) => void + const promise = new Promise((res, rej) => { resolve = res; reject = rej }) + return { promise, resolve, reject } +} + +const group = (id: number) => ({ id, name: `Group ${id}`, platform: 'openai', rpm_limit: 100 } as AdminGroup) +const entries = (id: number) => [{ user_id: id, user_name: '', user_email: `user${id}@example.com`, user_status: 'active', rpm_override: 100 }] + +async function openGroup() { + const wrapper = mount(GroupRPMOverridesModal, { + props: { show: false, group: group(1) }, + global: { stubs: { + BaseDialog: { props: ['show'], template: '
' }, + Icon: true, PlatformIcon: true, Pagination: true + } } + }) + await wrapper.setProps({ show: true }) + return wrapper +} + +describe('group RPM override request ownership', () => { + it('keeps the reopened group data when an older response finishes last', async () => { + const old = deferred() + mocks.getGroupRPMOverrides.mockReturnValueOnce(old.promise).mockResolvedValueOnce(entries(2)) + const wrapper = await openGroup() + await wrapper.setProps({ show: false }) + await wrapper.setProps({ show: true, group: group(2) }) + await flushPromises() + old.resolve(entries(1)) + await flushPromises() + expect(wrapper.get('tbody').text()).toContain('user2@example.com') + expect(wrapper.get('tbody').text()).not.toContain('user1@example.com') + await wrapper.get('tbody input[type="number"]').setValue('200') + await wrapper.findAll('button').find(button => button.text() === 'common.save')!.trigger('click') + expect(mocks.batchSetGroupRPMOverrides).toHaveBeenCalledWith(2, [{ user_id: 2, rpm_override: 200 }]) + }) + + it('does not end the new load or report an error when an old request fails', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const old = deferred() + const current = deferred() + mocks.getGroupRPMOverrides.mockReturnValueOnce(old.promise).mockReturnValueOnce(current.promise) + const wrapper = await openGroup() + await wrapper.setProps({ show: false }) + await wrapper.setProps({ show: true, group: group(2) }) + old.reject(new Error('old request failed')) + await flushPromises() + expect(mocks.showError).not.toHaveBeenCalled() + expect(wrapper.find('svg.animate-spin').exists()).toBe(true) + current.resolve(entries(2)) + await flushPromises() + expect(wrapper.get('tbody').text()).toContain('user2@example.com') + }) + + it('loads a different group while the dialog remains open', async () => { + mocks.getGroupRPMOverrides.mockResolvedValueOnce(entries(1)).mockResolvedValueOnce(entries(2)) + const wrapper = await openGroup() + await flushPromises() + await wrapper.setProps({ group: group(2) }) + await flushPromises() + expect(mocks.getGroupRPMOverrides).toHaveBeenLastCalledWith(2) + expect(wrapper.get('tbody').text()).toContain('user2@example.com') + }) + + it('discards the previous group draft before loading the next group', async () => { + mocks.getGroupRPMOverrides.mockResolvedValueOnce(entries(1)).mockReturnValueOnce(deferred().promise) + const wrapper = await openGroup() + await flushPromises() + await wrapper.get('tbody input[type="number"]').setValue('200') + await wrapper.setProps({ show: false }) + await wrapper.setProps({ show: true, group: group(2) }) + expect(wrapper.findAll('button').some(button => button.text() === 'common.save')).toBe(false) + }) + + it('ignores a request failure after unmounting', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const request = deferred() + mocks.getGroupRPMOverrides.mockReturnValue(request.promise) + const wrapper = await openGroup() + wrapper.unmount() + request.reject(new Error('offline')) + await flushPromises() + expect(mocks.showError).not.toHaveBeenCalled() + }) +}) diff --git a/frontend/src/components/admin/group/__tests__/GroupRateMultipliersModal.edit.spec.ts b/frontend/src/components/admin/group/__tests__/GroupRateMultipliersModal.edit.spec.ts new file mode 100644 index 000000000..e1fc6c557 --- /dev/null +++ b/frontend/src/components/admin/group/__tests__/GroupRateMultipliersModal.edit.spec.ts @@ -0,0 +1,52 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils' +import type { AdminGroup } from '@/types' +import GroupRateMultipliersModal from '../GroupRateMultipliersModal.vue' + +const mocks = vi.hoisted(() => ({ getGroupRateMultipliers: vi.fn(), batchSetGroupRateMultipliers: vi.fn() })) +vi.mock('@/api/admin', () => ({ adminAPI: { groups: mocks } })) +vi.mock('@/stores/app', () => ({ useAppStore: () => ({ showSuccess: vi.fn(), showError: vi.fn() }) })) +vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) })) +enableAutoUnmount(afterEach) +beforeEach(() => { + vi.resetAllMocks() + mocks.getGroupRateMultipliers.mockResolvedValue([ + { user_id: 7, user_email: 'user@example.com', user_name: '', user_status: 'active', rate_multiplier: 2, rpm_override: null } + ]) +}) + +async function openEditor() { + const wrapper = mount(GroupRateMultipliersModal, { + props: { show: false, group: { id: 1, name: 'Group', platform: 'openai', rate_multiplier: 1 } as AdminGroup }, + global: { stubs: { + BaseDialog: { props: ['show'], template: '
' }, + Icon: true, PlatformIcon: true, Pagination: true + } } + }) + await wrapper.setProps({ show: true }) + await flushPromises() + return wrapper +} + +describe('group rate multiplier edits', () => { + it.each(['0', '-1'])('does not stage invalid custom rate %s', async (value) => { + const wrapper = await openEditor() + await wrapper.get('tbody input[type="number"]').setValue(value) + expect(wrapper.findAll('button').some(button => button.text() === 'common.save')).toBe(false) + expect(mocks.batchSetGroupRateMultipliers).not.toHaveBeenCalled() + }) + + it.each([['0.5', 0.5], ['1e-3', 0.001]])('saves positive rate %s', async (value, expected) => { + const wrapper = await openEditor() + await wrapper.get('tbody input[type="number"]').setValue(value) + await wrapper.findAll('button').find(button => button.text() === 'common.save')!.trigger('click') + expect(mocks.batchSetGroupRateMultipliers).toHaveBeenCalledWith(1, [{ user_id: 7, rate_multiplier: expected }]) + }) + + it('still removes an override when its input is cleared', async () => { + const wrapper = await openEditor() + await wrapper.get('tbody input[type="number"]').setValue('') + await wrapper.findAll('button').find(button => button.text() === 'common.save')!.trigger('click') + expect(mocks.batchSetGroupRateMultipliers).toHaveBeenCalledWith(1, []) + }) +}) diff --git a/frontend/src/components/common/GroupBadge.vue b/frontend/src/components/common/GroupBadge.vue index b87399d03..25fc5e54f 100644 --- a/frontend/src/components/common/GroupBadge.vue +++ b/frontend/src/components/common/GroupBadge.vue @@ -8,7 +8,7 @@ - {{ name }} + {{ name }}