From 18356d4cbf13a28e2e01c053b662a6716135bf12 Mon Sep 17 00:00:00 2001 From: AdoreJC Date: Fri, 6 Nov 2026 14:20:13 -0500 Subject: [PATCH] feat(subscription): bill bound subscriptions only for their account, optional shared-pool fallback (HQ-Task T261106-02) A subscription bound to an OAuth channel account now pays only for the requests the distributor steers to that account, and those requests are billed to that subscription alone: - distributor records the binding (subscription, channel, dedicated group, original group) on every steered request; billing then pre-consumes from that subscription only (PreConsumeBoundUserSubscription), ignoring the billing preference and never overflowing to the wallet - every other request skips subscriptions with a bound channel (pre-consume candidates, HasActiveUnboundUserSubscription, UserActiveUnboundSubscriptionsAllowWalletOverflow); a user with only a bound subscription pays other models from the wallet - retries of a steered request stay in the dedicated group instead of falling back to the token group New plan switch fallback_to_shared_pool_on_limit (default off, read from the plan when the limit is hit). When the bound account answers with its own usage limit (429, rate_limit_error, unified-*-status rejected, Codex usage_limit_reached) before anything reached the client: - off: the request ends with a 429 naming the exhausted window and its reset time (response headers first, then the channel's passive usage sample) - on: the subscription reservation is refunded synchronously, the wallet reserves the request, and the retry continues in the original group (Auto without the dedicated group); the consume log carries subscription_fallback RefundSubscriptionPreConsume now applies the quota delta inside its own transaction instead of opening a nested one. Co-Authored-By: Claude Opus 5.5 --- constant/context_key.go | 8 + controller/relay.go | 13 +- controller/subscription.go | 6 + i18n/keys.go | 9 + i18n/locales/en.yaml | 8 + i18n/locales/zh-CN.yaml | 8 + i18n/locales/zh-TW.yaml | 8 + middleware/distributor.go | 21 +- middleware/distributor_test.go | 46 +- model/main.go | 2 + model/subscription.go | 115 ++++- model/subscription_channel_binding_test.go | 15 +- model/subscription_route_binding.go | 40 +- relay/channel/claude_oauth/adaptor.go | 12 +- relay/channel/codex/adaptor.go | 12 +- relay/common/relay_info.go | 30 ++ relay/helper/common.go | 15 + service/billing_session.go | 61 ++- service/funding_source.go | 22 +- service/group.go | 6 + service/group_auto_groups_test.go | 2 +- service/log_info_generate.go | 12 + service/subscription_route.go | 239 ++++++++++ service/subscription_route_test.go | 449 ++++++++++++++++++ .../subscriptions-mutate-drawer.tsx | 27 ++ .../lib/__tests__/plan-form.test.ts | 62 +++ .../features/subscriptions/lib/plan-form.ts | 4 + web/src/features/subscriptions/types.ts | 1 + web/src/i18n/locales/en.json | 2 + web/src/i18n/locales/fr.json | 2 + web/src/i18n/locales/ja.json | 2 + web/src/i18n/locales/ru.json | 2 + web/src/i18n/locales/vi.json | 2 + web/src/i18n/locales/zh-TW.json | 2 + web/src/i18n/locales/zh.json | 2 + 35 files changed, 1180 insertions(+), 87 deletions(-) create mode 100644 service/subscription_route.go create mode 100644 service/subscription_route_test.go create mode 100644 web/src/features/subscriptions/lib/__tests__/plan-form.test.ts diff --git a/constant/context_key.go b/constant/context_key.go index 743b4b5ce090..a3e81361178b 100644 --- a/constant/context_key.go +++ b/constant/context_key.go @@ -45,6 +45,14 @@ const ( // and for adaptors that build official endpoints themselves. ContextKeyUpstreamRequestOrigin ContextKey = "upstream_request_origin" + // ContextKeySubscriptionRoute holds the *relaycommon.SubscriptionRoute the + // distributor records when it steers a request to a binding's dedicated + // group. + ContextKeySubscriptionRoute ContextKey = "subscription_route" + // ContextKeyUpstreamRateLimitHeaders holds the usage-limit headers of the + // last upstream answer of a subscription OAuth channel (http.Header). + ContextKeyUpstreamRateLimitHeaders ContextKey = "upstream_rate_limit_headers" + ContextKeyAutoGroup ContextKey = "auto_group" ContextKeyAutoGroupIndex ContextKey = "auto_group_index" ContextKeyAutoGroupRetryIndex ContextKey = "auto_group_retry_index" diff --git a/controller/relay.go b/controller/relay.go index bee5ca3aadd0..dca622261dfe 100644 --- a/controller/relay.go +++ b/controller/relay.go @@ -166,7 +166,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) { retryParam := &service.RetryParam{ Ctx: c, - TokenGroup: relayInfo.TokenGroup, + TokenGroup: service.RelayRetryGroup(relayInfo), ModelName: relayInfo.OriginModelName, RequestPath: c.Request.URL.Path, Retry: common.GetPointer(0), @@ -227,6 +227,15 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) { service.RecordPolicyFailure(c, channel.Id, newAPIError, decision) processChannelError(c, *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()), newAPIError, relayInfo) + routeErr, fellBack := service.HandleSubscriptionRouteFailure(c, relayInfo, retryParam, newAPIError, helper.ResponseContentStarted(c)) + if fellBack { + continue + } + if routeErr != newAPIError { + newAPIError = routeErr + relayInfo.LastError = routeErr + break + } if decision.Action != "retry" { break } @@ -533,7 +542,7 @@ func executeTaskSubmissionWith( retryParam := &service.RetryParam{ Ctx: c, - TokenGroup: relayInfo.TokenGroup, + TokenGroup: service.RelayRetryGroup(relayInfo), ModelName: relayInfo.OriginModelName, RequestPath: c.Request.URL.Path, Retry: common.GetPointer(0), diff --git a/controller/subscription.go b/controller/subscription.go index fd0a49fa25be..c9fc34ba0791 100644 --- a/controller/subscription.go +++ b/controller/subscription.go @@ -178,6 +178,9 @@ func AdminCreateSubscriptionPlan(c *gin.Context) { if req.Plan.AllowWalletOverflow == nil { req.Plan.AllowWalletOverflow = common.GetPointer(true) } + if req.Plan.FallbackToSharedPoolOnLimit == nil { + req.Plan.FallbackToSharedPoolOnLimit = common.GetPointer(false) + } if req.Plan.DurationUnit == "" { req.Plan.DurationUnit = model.SubscriptionDurationMonth } @@ -315,6 +318,9 @@ func AdminUpdateSubscriptionPlan(c *gin.Context) { if req.Plan.AllowWalletOverflow != nil { updateMap["allow_wallet_overflow"] = *req.Plan.AllowWalletOverflow } + if req.Plan.FallbackToSharedPoolOnLimit != nil { + updateMap["fallback_to_shared_pool_on_limit"] = *req.Plan.FallbackToSharedPoolOnLimit + } if err := tx.Model(&model.SubscriptionPlan{}).Where("id = ?", id).Updates(updateMap).Error; err != nil { return err } diff --git a/i18n/keys.go b/i18n/keys.go index 4cf41e5486af..2c470cf8f441 100644 --- a/i18n/keys.go +++ b/i18n/keys.go @@ -53,6 +53,15 @@ const ( MsgRelayRetryGetChannelFailed = "relay.retry_get_channel_failed" MsgRelayRetryNoAvailableChannel = "relay.retry_no_available_channel" MsgRelayAccessTokenUnsupported = "relay.access_token_unsupported" + + MsgQuotaBoundSubscriptionInsufficient = "quota.bound_subscription_insufficient" + MsgRelaySubscriptionAccountLimited = "relay.subscription_account_limited" + MsgRelaySubscriptionAccountLimitedNoReset = "relay.subscription_account_limited_no_reset" + MsgRelaySubscriptionAccountLimitedGenericReset = "relay.subscription_account_limited_generic_reset" + MsgRelaySubscriptionAccountLimitedGeneric = "relay.subscription_account_limited_generic" + MsgRelaySubscriptionWindow5h = "relay.subscription_window_5h" + MsgRelaySubscriptionWindow7d = "relay.subscription_window_7d" + MsgRelaySubscriptionWindow7dOi = "relay.subscription_window_7d_oi" ) // Emails and the name of the token created at registration, in the diff --git a/i18n/locales/en.yaml b/i18n/locales/en.yaml index 7086f01327c2..d92354138e0e 100644 --- a/i18n/locales/en.yaml +++ b/i18n/locales/en.yaml @@ -31,6 +31,7 @@ distributor.invalid_request_parse_model: "unable to parse model" quota.user_insufficient: "Insufficient user quota, remaining quota: {{.Remaining}}" quota.pre_consume_insufficient: "Not enough quota to pre-consume for this request: {{.Remaining}} remaining, {{.Required}} required" quota.subscription_insufficient: "Subscription quota is insufficient or no subscription is configured: {{.Error}}" +quota.bound_subscription_insufficient: "The subscription bound to this account does not have enough quota: {{.Remaining}} remaining, {{.Required}} required. Models of the bound account are billed to that subscription only." relay.model_price_not_configured: "Model {{.Model}} has not been priced by the administrator yet. Please contact the site administrator to enable this model." relay.model_price_not_configured_admin: "Model {{.Model}} price not configured. Go to System Settings → Operation Settings to enable self-use mode, or configure the model price in System Settings → Group & Model Pricing." relay.task_usage_price_unsupported: "Model {{.Model}} uses a task usage expression; configure ordinary relay pricing and separate plugin billing expressions" @@ -41,6 +42,13 @@ relay.group_upstream_saturated: "The upstream of the current group is at capacit relay.retry_get_channel_failed: "Failed to get available channel for model {{.Model}} under group {{.Group}} (retry): {{.Error}}" relay.retry_no_available_channel: "No available channel for model {{.Model}} under group {{.Group}} (retry)" relay.access_token_unsupported: "Access tokens are not supported here" +relay.subscription_account_limited: "The subscription account has used up its {{.Window}} limit; it resets at {{.ResetAt}}" +relay.subscription_account_limited_no_reset: "The subscription account has used up its {{.Window}} limit; please try again later" +relay.subscription_account_limited_generic_reset: "The subscription account has used up its usage limit; it resets at {{.ResetAt}}" +relay.subscription_account_limited_generic: "The subscription account has used up its usage limit; please try again later" +relay.subscription_window_5h: "5-hour" +relay.subscription_window_7d: "7-day" +relay.subscription_window_7d_oi: "7-day Fable" # Emails and the name of the token created at registration user.default_token_name: "{{.Username}}'s initial token" diff --git a/i18n/locales/zh-CN.yaml b/i18n/locales/zh-CN.yaml index 5f0a5ff699e1..4a2d65649870 100644 --- a/i18n/locales/zh-CN.yaml +++ b/i18n/locales/zh-CN.yaml @@ -32,6 +32,7 @@ distributor.invalid_request_parse_model: "无法解析模型" quota.user_insufficient: "用户额度不足, 剩余额度: {{.Remaining}}" quota.pre_consume_insufficient: "预扣费额度失败, 用户剩余额度: {{.Remaining}}, 需要预扣费额度: {{.Required}}" quota.subscription_insufficient: "订阅额度不足或未配置订阅: {{.Error}}" +quota.bound_subscription_insufficient: "绑定账号的订阅额度不足:剩余 {{.Remaining}},需要 {{.Required}}。绑定账号的模型只从该订阅扣费" relay.model_price_not_configured: "模型 {{.Model}} 的价格尚未由管理员配置,暂时无法使用,请联系站点管理员开启该模型;Model {{.Model}} has not been priced by the administrator yet. Please contact the site administrator to enable this model." relay.model_price_not_configured_admin: "模型 {{.Model}} 的价格未配置。请前往「系统设置 → 运营设置」开启自用模式,或在「系统设置 → 分组与模型定价设置」中为该模型配置价格;Model {{.Model}} price not configured. Go to System Settings → Operation Settings to enable self-use mode, or configure the model price in System Settings → Group & Model Pricing." relay.task_usage_price_unsupported: "模型 {{.Model}} 使用了任务用量表达式;请为普通转发配置常规定价,并为插件单独配置计费表达式" @@ -42,6 +43,13 @@ relay.group_upstream_saturated: "当前分组上游负载已饱和,请稍后 relay.retry_get_channel_failed: "获取分组 {{.Group}} 下模型 {{.Model}} 的可用渠道失败(retry): {{.Error}}" relay.retry_no_available_channel: "分组 {{.Group}} 下模型 {{.Model}} 的可用渠道不存在(retry)" relay.access_token_unsupported: "暂不支持使用 access token" +relay.subscription_account_limited: "订阅账号的{{.Window}}额度已用尽,将于 {{.ResetAt}} 重置" +relay.subscription_account_limited_no_reset: "订阅账号的{{.Window}}额度已用尽,请稍后再试" +relay.subscription_account_limited_generic_reset: "订阅账号的用量额度已用尽,将于 {{.ResetAt}} 重置" +relay.subscription_account_limited_generic: "订阅账号的用量额度已用尽,请稍后再试" +relay.subscription_window_5h: " 5 小时" +relay.subscription_window_7d: " 7 天" +relay.subscription_window_7d_oi: " Fable 7 天" # Emails and the name of the token created at registration user.default_token_name: "{{.Username}}的初始令牌" diff --git a/i18n/locales/zh-TW.yaml b/i18n/locales/zh-TW.yaml index 1c3f8e989abd..433742a28a54 100644 --- a/i18n/locales/zh-TW.yaml +++ b/i18n/locales/zh-TW.yaml @@ -32,6 +32,7 @@ distributor.invalid_request_parse_model: "無法解析模型" quota.user_insufficient: "使用者額度不足,剩餘額度:{{.Remaining}}" quota.pre_consume_insufficient: "預扣費額度失敗,使用者剩餘額度:{{.Remaining}},需要預扣費額度:{{.Required}}" quota.subscription_insufficient: "訂閱額度不足或未設定訂閱:{{.Error}}" +quota.bound_subscription_insufficient: "綁定帳號的訂閱額度不足:剩餘 {{.Remaining}},需要 {{.Required}}。綁定帳號的模型只從該訂閱扣費" relay.model_price_not_configured: "模型 {{.Model}} 的價格尚未由管理員設定,暫時無法使用,請聯絡站點管理員開啟該模型" relay.model_price_not_configured_admin: "模型 {{.Model}} 的價格未設定。請前往「系統設定 → 營運設定」開啟自用模式,或在「系統設定 → 分組與模型定價設定」中為該模型設定價格" relay.task_usage_price_unsupported: "模型 {{.Model}} 使用了任務用量表達式;請為一般轉發設定常規定價,並為插件單獨設定計費表達式" @@ -42,6 +43,13 @@ relay.group_upstream_saturated: "目前分組上游負載已飽和,請稍後 relay.retry_get_channel_failed: "獲取分組 {{.Group}} 下模型 {{.Model}} 的可用管道失敗(retry):{{.Error}}" relay.retry_no_available_channel: "分組 {{.Group}} 下模型 {{.Model}} 的可用管道不存在(retry)" relay.access_token_unsupported: "暫不支援使用 access token" +relay.subscription_account_limited: "訂閱帳號的{{.Window}}額度已用盡,將於 {{.ResetAt}} 重置" +relay.subscription_account_limited_no_reset: "訂閱帳號的{{.Window}}額度已用盡,請稍後再試" +relay.subscription_account_limited_generic_reset: "訂閱帳號的用量額度已用盡,將於 {{.ResetAt}} 重置" +relay.subscription_account_limited_generic: "訂閱帳號的用量額度已用盡,請稍後再試" +relay.subscription_window_5h: " 5 小時" +relay.subscription_window_7d: " 7 天" +relay.subscription_window_7d_oi: " Fable 7 天" # Emails and the name of the token created at registration user.default_token_name: "{{.Username}}的初始令牌" diff --git a/middleware/distributor.go b/middleware/distributor.go index 89c231f9d37a..e3bd7a0740f8 100644 --- a/middleware/distributor.go +++ b/middleware/distributor.go @@ -16,6 +16,7 @@ import ( "github.com/QuantumNous/new-api/logger" "github.com/QuantumNous/new-api/model" "github.com/QuantumNous/new-api/pkg/jsplugin" + relaycommon "github.com/QuantumNous/new-api/relay/common" relayconstant "github.com/QuantumNous/new-api/relay/constant" "github.com/QuantumNous/new-api/relaykit/dto" "github.com/QuantumNous/new-api/relaykit/types" @@ -97,12 +98,20 @@ func Distribute() func(c *gin.Context) { } // A user whose subscription is bound to an OAuth channel account // has that channel's models served from the binding's dedicated - // group, whatever group the token or playground asked for; every - // other model keeps the group chosen above. - if group, ok := model.ResolveSubscriptionRouteGroup(c.GetInt("id"), modelRequest.Model, common.GetTimestamp()); ok { - if previous := common.GetContextKeyString(c, constant.ContextKeyUsingGroup); previous != group { - common.SetContextKey(c, constant.ContextKeyUsingGroup, group) - logger.LogDebug(c, "subscription binding routes model %s from group %s to the dedicated group %s", modelRequest.Model, previous, group) + // group, whatever group the token or playground asked for, and + // billed to that subscription only; every other model keeps the + // group chosen above. + if binding, ok := model.ResolveSubscriptionRoute(c.GetInt("id"), modelRequest.Model, common.GetTimestamp()); ok { + previous := common.GetContextKeyString(c, constant.ContextKeyUsingGroup) + common.SetContextKey(c, constant.ContextKeySubscriptionRoute, &relaycommon.SubscriptionRoute{ + SubscriptionId: binding.SubscriptionId, + ChannelId: binding.ChannelId, + Group: binding.Group, + OriginalGroup: previous, + }) + if previous != binding.Group { + common.SetContextKey(c, constant.ContextKeyUsingGroup, binding.Group) + logger.LogDebug(c, "subscription binding routes model %s from group %s to the dedicated group %s", modelRequest.Model, previous, binding.Group) } } } diff --git a/middleware/distributor_test.go b/middleware/distributor_test.go index be1df45fea28..25b9a84c62e9 100644 --- a/middleware/distributor_test.go +++ b/middleware/distributor_test.go @@ -14,6 +14,7 @@ import ( "github.com/QuantumNous/new-api/i18n" "github.com/QuantumNous/new-api/model" "github.com/QuantumNous/new-api/pkg/jsplugin" + relaycommon "github.com/QuantumNous/new-api/relay/common" "github.com/QuantumNous/new-api/relaykit/dto" "github.com/QuantumNous/new-api/setting" "github.com/QuantumNous/new-api/setting/model_setting" @@ -484,10 +485,13 @@ func setupSubscriptionRouteDistributeTest(t *testing.T) { model.InitChannelCache() } -func serveSubscriptionRouteRequest(t *testing.T, userId int, tokenGroup string, modelName string) (string, int) { +// serveSubscriptionRouteRequest returns the group and channel the distributor +// chose and the route it recorded for billing (nil when not steered). +func serveSubscriptionRouteRequest(t *testing.T, userId int, tokenGroup string, modelName string) (string, int, *relaycommon.SubscriptionRoute) { t.Helper() var gotGroup string var gotChannel int + var gotRoute *relaycommon.SubscriptionRoute router := gin.New() router.POST("/v1/chat/completions", RequestId(), func(c *gin.Context) { c.Set("id", userId) @@ -496,6 +500,7 @@ func serveSubscriptionRouteRequest(t *testing.T, userId int, tokenGroup string, }, Distribute(), func(c *gin.Context) { gotGroup = common.GetContextKeyString(c, constant.ContextKeyUsingGroup) gotChannel = common.GetContextKeyInt(c, constant.ContextKeyChannelId) + gotRoute, _ = common.GetContextKeyType[*relaycommon.SubscriptionRoute](c, constant.ContextKeySubscriptionRoute) c.Status(http.StatusNoContent) }) request := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(fmt.Sprintf(`{"model":%q}`, modelName))) @@ -503,7 +508,7 @@ func serveSubscriptionRouteRequest(t *testing.T, userId int, tokenGroup string, recorder := httptest.NewRecorder() router.ServeHTTP(recorder, request) require.Equal(t, http.StatusNoContent, recorder.Code, recorder.Body.String()) - return gotGroup, gotChannel + return gotGroup, gotChannel, gotRoute } func TestDistributeRoutesBoundUsersModelsToTheDedicatedGroup(t *testing.T) { @@ -516,21 +521,34 @@ func TestDistributeRoutesBoundUsersModelsToTheDedicatedGroup(t *testing.T) { modelName string wantGroup string wantChannel int + // group recorded as the fallback target; "" when the request is not + // steered and so not billed to the bound subscription + wantOriginal string }{ - {"bound user, model on the bound channel", 10, "default", "claude-x", "claude-ch1", 1}, - {"bound user, model not on the bound channel", 10, "default", "gpt-x", "default", 2}, - {"binding wins over a token pinned to another group", 10, "vip", "claude-x", "claude-ch1", 1}, - {"binding wins over Auto", 10, "auto", "claude-x", "claude-ch1", 1}, - {"Auto still serves the other models", 10, "auto", "gpt-x", "auto", 2}, - {"user without a binding", 11, "default", "claude-x", "default", 4}, - {"expired binding", 12, "default", "claude-x", "default", 4}, - {"cancelled binding", 13, "default", "claude-x", "default", 4}, + {"bound user, model on the bound channel", 10, "default", "claude-x", "claude-ch1", 1, "default"}, + {"bound user, model not on the bound channel", 10, "default", "gpt-x", "default", 2, ""}, + {"binding wins over a token pinned to another group", 10, "vip", "claude-x", "claude-ch1", 1, "vip"}, + {"binding wins over Auto", 10, "auto", "claude-x", "claude-ch1", 1, "auto"}, + {"token already in the dedicated group is still billed to the binding", 10, "claude-ch1", "claude-x", "claude-ch1", 1, "claude-ch1"}, + {"Auto still serves the other models", 10, "auto", "gpt-x", "auto", 2, ""}, + {"user without a binding", 11, "default", "claude-x", "default", 4, ""}, + {"expired binding", 12, "default", "claude-x", "default", 4, ""}, + {"cancelled binding", 13, "default", "claude-x", "default", 4, ""}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - gotGroup, gotChannel := serveSubscriptionRouteRequest(t, tc.userId, tc.tokenGroup, tc.modelName) + gotGroup, gotChannel, gotRoute := serveSubscriptionRouteRequest(t, tc.userId, tc.tokenGroup, tc.modelName) assert.Equal(t, tc.wantGroup, gotGroup) assert.Equal(t, tc.wantChannel, gotChannel) + if tc.wantOriginal == "" { + assert.Nil(t, gotRoute) + return + } + require.NotNil(t, gotRoute) + assert.Equal(t, tc.wantOriginal, gotRoute.OriginalGroup) + assert.Equal(t, "claude-ch1", gotRoute.Group) + assert.Equal(t, 1, gotRoute.ChannelId) + assert.Positive(t, gotRoute.SubscriptionId) }) } } @@ -538,17 +556,17 @@ func TestDistributeRoutesBoundUsersModelsToTheDedicatedGroup(t *testing.T) { func TestDistributeStopsRoutingOnceTheBindingCacheIsInvalidated(t *testing.T) { setupSubscriptionRouteDistributeTest(t) - group, channel := serveSubscriptionRouteRequest(t, 10, "default", "claude-x") + group, channel, _ := serveSubscriptionRouteRequest(t, 10, "default", "claude-x") assert.Equal(t, "claude-ch1", group) assert.Equal(t, 1, channel) require.NoError(t, model.DB.Model(&model.UserSubscription{}).Where("user_id = ?", 10).Update("bound_channel_id", 0).Error) - group, channel = serveSubscriptionRouteRequest(t, 10, "default", "claude-x") + group, channel, _ = serveSubscriptionRouteRequest(t, 10, "default", "claude-x") assert.Equal(t, "claude-ch1", group, "the cached binding still routes") assert.Equal(t, 1, channel) model.InvalidateSubscriptionRouteBindingCache(10) - group, channel = serveSubscriptionRouteRequest(t, 10, "default", "claude-x") + group, channel, _ = serveSubscriptionRouteRequest(t, 10, "default", "claude-x") assert.Equal(t, "default", group) assert.Equal(t, 4, channel) } diff --git a/model/main.go b/model/main.go index 3f99cd787c0b..96109aaa9d17 100644 --- a/model/main.go +++ b/model/main.go @@ -524,6 +524,7 @@ func ensureSubscriptionPlanTableSQLite() error { ` + "`sort_order`" + ` integer DEFAULT 0, ` + "`allow_balance_pay`" + ` numeric DEFAULT 1, ` + "`allow_wallet_overflow`" + ` numeric DEFAULT 1, +` + "`fallback_to_shared_pool_on_limit`" + ` numeric DEFAULT 0, ` + "`stripe_price_id`" + ` varchar(128) DEFAULT '', ` + "`creem_product_id`" + ` varchar(128) DEFAULT '', ` + "`waffo_pancake_product_id`" + ` varchar(128) DEFAULT '', @@ -561,6 +562,7 @@ PRIMARY KEY (` + "`id`" + `) {Name: "sort_order", DDL: "`sort_order` integer DEFAULT 0"}, {Name: "allow_balance_pay", DDL: "`allow_balance_pay` numeric DEFAULT 1"}, {Name: "allow_wallet_overflow", DDL: "`allow_wallet_overflow` numeric DEFAULT 1"}, + {Name: "fallback_to_shared_pool_on_limit", DDL: "`fallback_to_shared_pool_on_limit` numeric DEFAULT 0"}, {Name: "stripe_price_id", DDL: "`stripe_price_id` varchar(128) DEFAULT ''"}, {Name: "creem_product_id", DDL: "`creem_product_id` varchar(128) DEFAULT ''"}, {Name: "waffo_pancake_product_id", DDL: "`waffo_pancake_product_id` varchar(128) DEFAULT ''"}, diff --git a/model/subscription.go b/model/subscription.go index 0d17ffe2acf5..d915b4d14d8b 100644 --- a/model/subscription.go +++ b/model/subscription.go @@ -165,6 +165,12 @@ type SubscriptionPlan struct { // Allow falling back to wallet balance after subscription quota is exhausted (empty = true) AllowWalletOverflow *bool `json:"allow_wallet_overflow"` + // When the bound OAuth account of a subscription on this plan hits its own + // usage limit, move the request back to the group it came from (the shared + // pool) and bill it to the wallet instead of failing (empty = false). Read + // from the plan when the limit is hit, not snapshotted per subscription. + FallbackToSharedPoolOnLimit *bool `json:"fallback_to_shared_pool_on_limit"` + StripePriceId string `json:"stripe_price_id" gorm:"type:varchar(128);default:''"` CreemProductId string `json:"creem_product_id" gorm:"type:varchar(128);default:''"` WaffoPancakeProductId string `json:"waffo_pancake_product_id" gorm:"type:varchar(128);default:''"` @@ -208,6 +214,9 @@ func (p *SubscriptionPlan) NormalizeDefaults() { if p.AllowWalletOverflow == nil { p.AllowWalletOverflow = common.GetPointer(true) } + if p.FallbackToSharedPoolOnLimit == nil { + p.FallbackToSharedPoolOnLimit = common.GetPointer(false) + } } // Subscription order (payment -> webhook -> create UserSubscription) @@ -883,9 +892,11 @@ func GetAllActiveUserSubscriptions(userId int) ([]SubscriptionSummary, error) { return buildSubscriptionSummaries(subs), nil } -// HasActiveUserSubscription returns whether the user has any active subscription. -// This is a lightweight existence check to avoid heavy pre-consume transactions. -func HasActiveUserSubscription(userId int) (bool, error) { +// HasActiveUnboundUserSubscription returns whether the user has an active +// subscription without a bound channel, the only kind that pays for requests +// not steered to a bound account. This is a lightweight existence check to +// avoid heavy pre-consume transactions. +func HasActiveUnboundUserSubscription(userId int) (bool, error) { if userId <= 0 { return false, errors.New("invalid userId") } @@ -893,16 +904,19 @@ func HasActiveUserSubscription(userId int) (bool, error) { var count int64 if err := DB.Model(&UserSubscription{}). Where("user_id = ? AND status = ? AND end_time > ?", userId, "active", now). + Where(unboundSubscriptionCondition). Count(&count).Error; err != nil { return false, err } return count > 0, nil } -// UserActiveSubscriptionsAllowWalletOverflow returns whether wallet balance may be used -// after the user's subscription quota is exhausted. A single active subscription that -// disallows wallet overflow (allow_wallet_overflow = false) blocks the fallback. -func UserActiveSubscriptionsAllowWalletOverflow(userId int) (bool, error) { +// UserActiveUnboundSubscriptionsAllowWalletOverflow returns whether wallet +// balance may be used after the quota of the user's subscriptions without a +// bound channel is exhausted. A single such subscription that disallows wallet +// overflow (allow_wallet_overflow = false) blocks the fallback; bound +// subscriptions never take part in that decision. +func UserActiveUnboundSubscriptionsAllowWalletOverflow(userId int) (bool, error) { if userId <= 0 { return false, errors.New("invalid userId") } @@ -911,6 +925,7 @@ func UserActiveSubscriptionsAllowWalletOverflow(userId int) (bool, error) { if err := DB.Model(&UserSubscription{}). Where("user_id = ? AND status = ? AND end_time > ? AND allow_wallet_overflow = ?", userId, "active", now, false). + Where(unboundSubscriptionCondition). Count(&strictCount).Error; err != nil { return false, err } @@ -1339,8 +1354,49 @@ func maybeResetUserSubscriptionWithPlanTx(tx *gorm.DB, sub *UserSubscription, pl return tx.Save(sub).Error } -// PreConsumeUserSubscription pre-consumes from any active subscription total quota. +// unboundSubscriptionCondition selects subscriptions without a bound OAuth +// channel. A bound subscription pays only for requests the distributor steers +// to its account (PreConsumeBoundUserSubscription); every other request is +// billed as if it did not exist. +const unboundSubscriptionCondition = "COALESCE(bound_channel_id, 0) = 0" + +// SubscriptionQuotaInsufficientError reports that no candidate subscription +// had Required quota left. Remaining is set when a single subscription was +// considered (always the case for a bound subscription). +type SubscriptionQuotaInsufficientError struct { + Remaining int64 + Required int64 +} + +func (e *SubscriptionQuotaInsufficientError) Error() string { + return fmt.Sprintf("subscription quota insufficient, need=%d", e.Required) +} + +// PreConsumeUserSubscription pre-consumes from the user's active subscriptions +// that have no bound channel, earliest expiry first. func PreConsumeUserSubscription(requestId string, userId int, modelName string, quotaType int, amount int64) (*SubscriptionPreConsumeResult, error) { + return preConsumeUserSubscription(requestId, userId, amount, func(tx *gorm.DB) *gorm.DB { + return tx.Where(unboundSubscriptionCondition).Order("end_time asc, id asc") + }) +} + +// PreConsumeBoundUserSubscription pre-consumes from one subscription only: the +// one whose bound channel account serves the request. It never moves on to +// another subscription; an inactive subscription is "no active subscription" +// and a short one a *SubscriptionQuotaInsufficientError. +func PreConsumeBoundUserSubscription(requestId string, userId int, userSubscriptionId int, amount int64) (*SubscriptionPreConsumeResult, error) { + if userSubscriptionId <= 0 { + return nil, errors.New("no active subscription") + } + return preConsumeUserSubscription(requestId, userId, amount, func(tx *gorm.DB) *gorm.DB { + return tx.Where("id = ? AND bound_channel_id > 0", userSubscriptionId) + }) +} + +// preConsumeUserSubscription reserves amount from the first active +// subscription of userId selected by scope that still has room, idempotently +// per requestId. +func preConsumeUserSubscription(requestId string, userId int, amount int64, scope func(*gorm.DB) *gorm.DB) (*SubscriptionPreConsumeResult, error) { if userId <= 0 { return nil, errors.New("invalid userId") } @@ -1377,15 +1433,15 @@ func PreConsumeUserSubscription(requestId string, userId int, modelName string, } var subs []UserSubscription - if err := lockForUpdate(tx). - Where("user_id = ? AND status = ? AND end_time > ?", userId, "active", now). - Order("end_time asc, id asc"). + if err := scope(lockForUpdate(tx). + Where("user_id = ? AND status = ? AND end_time > ?", userId, "active", now)). Find(&subs).Error; err != nil { return errors.New("no active subscription") } if len(subs) == 0 { return errors.New("no active subscription") } + insufficient := &SubscriptionQuotaInsufficientError{Required: amount} for _, candidate := range subs { sub := candidate plan, err := getSubscriptionPlanByIdTx(tx, sub.PlanId) @@ -1399,6 +1455,9 @@ func PreConsumeUserSubscription(requestId string, userId int, modelName string, if sub.AmountTotal > 0 { remain := sub.AmountTotal - usedBefore if remain < amount { + if len(subs) == 1 { + insufficient.Remaining = max(remain, 0) + } continue } } @@ -1435,7 +1494,7 @@ func PreConsumeUserSubscription(requestId string, userId int, modelName string, returnValue.AmountUsedAfter = sub.AmountUsed return nil } - return fmt.Errorf("subscription quota insufficient, need=%d", amount) + return insufficient }) if err != nil { return nil, err @@ -1461,7 +1520,9 @@ func RefundSubscriptionPreConsume(requestId string) error { record.Status = "refunded" return tx.Save(&record).Error } - if err := PostConsumeUserSubscriptionDelta(record.UserSubscriptionId, -record.PreConsumed); err != nil { + // The quota and the record change in one transaction, so a refund is + // applied exactly once even when it is retried. + if err := postConsumeUserSubscriptionDeltaTx(tx, record.UserSubscriptionId, -record.PreConsumed); err != nil { return err } record.Status = "refunded" @@ -1560,17 +1621,21 @@ func PostConsumeUserSubscriptionDelta(userSubscriptionId int, delta int64) error return nil } return DB.Transaction(func(tx *gorm.DB) error { - var sub UserSubscription - if err := lockForUpdate(tx). - Where("id = ?", userSubscriptionId). - First(&sub).Error; err != nil { - return err - } - newUsed := max(sub.AmountUsed+delta, 0) - if sub.AmountTotal > 0 && newUsed > sub.AmountTotal { - return fmt.Errorf("subscription used exceeds total, used=%d total=%d", newUsed, sub.AmountTotal) - } - sub.AmountUsed = newUsed - return tx.Save(&sub).Error + return postConsumeUserSubscriptionDeltaTx(tx, userSubscriptionId, delta) }) } + +func postConsumeUserSubscriptionDeltaTx(tx *gorm.DB, userSubscriptionId int, delta int64) error { + var sub UserSubscription + if err := lockForUpdate(tx). + Where("id = ?", userSubscriptionId). + First(&sub).Error; err != nil { + return err + } + newUsed := max(sub.AmountUsed+delta, 0) + if sub.AmountTotal > 0 && newUsed > sub.AmountTotal { + return fmt.Errorf("subscription used exceeds total, used=%d total=%d", newUsed, sub.AmountTotal) + } + sub.AmountUsed = newUsed + return tx.Save(&sub).Error +} diff --git a/model/subscription_channel_binding_test.go b/model/subscription_channel_binding_test.go index 47ea18b10a32..46f806170afa 100644 --- a/model/subscription_channel_binding_test.go +++ b/model/subscription_channel_binding_test.go @@ -374,9 +374,9 @@ func TestLegacyOAuthChBindingKeepsWorkingUnderItsStoredGroup(t *testing.T) { routed, ok := GetUserSubscriptionRouteBinding(f.user.Id, time.Now().Unix()) require.True(t, ok) assert.Equal(t, legacy, routed.Group, "the stored group is used, not re-derived") - group, ok := ResolveSubscriptionRouteGroup(f.user.Id, "claude-sonnet-4-5", time.Now().Unix()) + resolved, ok := ResolveSubscriptionRoute(f.user.Id, "claude-sonnet-4-5", time.Now().Unix()) require.True(t, ok) - assert.Equal(t, legacy, group) + assert.Equal(t, legacy, resolved.Group) }) t.Run("unbind of an unmigrated row restores the plan snapshot and the channel", func(t *testing.T) { @@ -438,18 +438,19 @@ func TestSubscriptionRouteBindingCacheFollowsBindingLifecycle(t *testing.T) { _, ok := GetUserSubscriptionRouteBinding(f.user.Id, now) assert.False(t, ok, "no binding yet") - _, ok = ResolveSubscriptionRouteGroup(f.user.Id, "claude-sonnet-4-5", now) + _, ok = ResolveSubscriptionRoute(f.user.Id, "claude-sonnet-4-5", now) assert.False(t, ok) _, err := AdminBindSubscriptionChannel(sub.Id, f.channel.Id) require.NoError(t, err) dedicated := SubscriptionBoundGroupName(f.channel.Type, f.channel.Id) - group, ok := ResolveSubscriptionRouteGroup(f.user.Id, "claude-sonnet-4-5", now) + resolved, ok := ResolveSubscriptionRoute(f.user.Id, "claude-sonnet-4-5", now) require.True(t, ok, "the bind invalidated the cached miss") - assert.Equal(t, dedicated, group) - _, ok = ResolveSubscriptionRouteGroup(f.user.Id, "gpt-4o", now) + assert.Equal(t, dedicated, resolved.Group) + assert.Equal(t, sub.Id, resolved.SubscriptionId) + _, ok = ResolveSubscriptionRoute(f.user.Id, "gpt-4o", now) assert.False(t, ok, "models the bound channel does not serve keep their group") - _, ok = ResolveSubscriptionRouteGroup(f.user.Id, "", now) + _, ok = ResolveSubscriptionRoute(f.user.Id, "", now) assert.False(t, ok) // The cache answers until it is invalidated: a row edited behind its back diff --git a/model/subscription_route_binding.go b/model/subscription_route_binding.go index 0730e1d8ce1d..5117a5addd77 100644 --- a/model/subscription_route_binding.go +++ b/model/subscription_route_binding.go @@ -187,21 +187,41 @@ func clearSubscriptionRouteModelCache() { subscriptionRouteModelMemory.clear() } -// ResolveSubscriptionRouteGroup returns the dedicated group a request of -// userId for modelName is steered to: the user holds an active channel binding -// and the bound channel serves the model in that group. Every other request -// (no binding, expired or cancelled subscription, model not on the channel, -// model or channel disabled) keeps its original group. -func ResolveSubscriptionRouteGroup(userId int, modelName string, now int64) (string, bool) { +// ResolveSubscriptionRoute returns the binding a request of userId for +// modelName is steered by: the user holds an active channel binding and the +// bound channel serves the model in the binding's dedicated group. Every other +// request (no binding, expired or cancelled subscription, model not on the +// channel, model or channel disabled) keeps its original group and is not +// billed to the bound subscription. +func ResolveSubscriptionRoute(userId int, modelName string, now int64) (SubscriptionRouteBinding, bool) { if modelName == "" { - return "", false + return SubscriptionRouteBinding{}, false } binding, ok := GetUserSubscriptionRouteBinding(userId, now) if !ok { - return "", false + return SubscriptionRouteBinding{}, false } if !subscriptionBoundChannelServesModel(binding.Group, modelName, binding.ChannelId) { - return "", false + return SubscriptionRouteBinding{}, false + } + return binding, true +} + +// SubscriptionFallsBackToSharedPool reports whether the plan of a bound +// subscription lets a request whose bound account hit its usage limit move +// back to its original group, billed to the wallet. The plan is read when the +// limit is hit, so changing the plan applies to subscriptions already sold. +func SubscriptionFallsBackToSharedPool(userSubscriptionId int) (bool, error) { + if userSubscriptionId <= 0 { + return false, nil + } + var sub UserSubscription + if err := DB.Select("id", "plan_id").Where("id = ?", userSubscriptionId).First(&sub).Error; err != nil { + return false, err + } + plan, err := GetSubscriptionPlanById(sub.PlanId) + if err != nil { + return false, err } - return binding.Group, true + return plan.FallbackToSharedPoolOnLimit != nil && *plan.FallbackToSharedPoolOnLimit, nil } diff --git a/relay/channel/claude_oauth/adaptor.go b/relay/channel/claude_oauth/adaptor.go index f38cd7e125b5..f33f6fd33f66 100644 --- a/relay/channel/claude_oauth/adaptor.go +++ b/relay/channel/claude_oauth/adaptor.go @@ -63,12 +63,18 @@ func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) { // // Every upstream answer, streamed or not and whatever its status, carries the // account's rate-limit headers; they are sampled here so the usage dialog can -// show windows the usage API leaves out. +// show windows the usage API leaves out, and kept on the request so a usage +// limit of a subscription-bound account can be told apart from other errors. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) { resp, err := channel.DoApiRequest(a, c, info, requestBody) - if err == nil && resp != nil && info != nil { - service.RecordClaudePassiveUsage(info.ChannelId, resp.Header) + var headers http.Header + if err == nil && resp != nil { + headers = resp.Header + if info != nil { + service.RecordClaudePassiveUsage(info.ChannelId, resp.Header) + } } + service.RecordSubscriptionLimitHeaders(c, headers) return resp, err } diff --git a/relay/channel/codex/adaptor.go b/relay/channel/codex/adaptor.go index c2d75d5bd1ac..5db49811fe3a 100644 --- a/relay/channel/codex/adaptor.go +++ b/relay/channel/codex/adaptor.go @@ -14,6 +14,7 @@ import ( relayconstant "github.com/QuantumNous/new-api/relay/constant" "github.com/QuantumNous/new-api/relaykit/dto" "github.com/QuantumNous/new-api/relaykit/types" + "github.com/QuantumNous/new-api/service" "github.com/gin-gonic/gin" ) @@ -109,8 +110,17 @@ func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommo return request, nil } +// DoRequest keeps the usage-limit headers of the answer on the request so a +// usage limit of a subscription-bound account can be told apart from other +// errors. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) { - return channel.DoApiRequest(a, c, info, requestBody) + resp, err := channel.DoApiRequest(a, c, info, requestBody) + var headers http.Header + if err == nil && resp != nil { + headers = resp.Header + } + service.RecordSubscriptionLimitHeaders(c, headers) + return resp, err } func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) { diff --git a/relay/common/relay_info.go b/relay/common/relay_info.go index 050e90be9142..cebef8c2fca7 100644 --- a/relay/common/relay_info.go +++ b/relay/common/relay_info.go @@ -80,6 +80,29 @@ type TokenCountMeta struct { estimatePromptTokens int } +// SubscriptionRoute records that a request was steered to the dedicated group +// of the user's subscription binding. While it is not FellBack, the request is +// billed to that subscription only and every attempt stays in Group. When the +// bound account hits its usage limit and the plan allows it, the request moves +// back to OriginalGroup (the group it would have used without the binding), +// FellBack is set and the wallet pays from then on. +type SubscriptionRoute struct { + SubscriptionId int + ChannelId int + Group string + OriginalGroup string + FellBack bool + // LimitWindow is the usage window of the bound account that triggered the + // fallback ("5h", "7d", "7d_oi" or "" when unknown). + LimitWindow string +} + +// Active reports whether the request is still served and billed by the +// binding. +func (r *SubscriptionRoute) Active() bool { + return r != nil && !r.FellBack +} + type RelayInfo struct { TokenId int TokenKey string @@ -164,6 +187,10 @@ type RelayInfo struct { UseRuntimeHeadersOverride bool ParamOverrideAudit []string + // SubscriptionRoute is set when the distributor steered the request to the + // dedicated group of the user's subscription binding; nil otherwise. + SubscriptionRoute *SubscriptionRoute + PriceData hosttypes.PriceData // QuotaClamp is set (non-nil) when a quota conversion saturated at the @@ -615,6 +642,7 @@ func genBaseRelayInfo(c *gin.Context, request dto.Request) *RelayInfo { } reasoningEffort := reasoningEffortFromRequest(request) originModelName := common.GetContextKeyString(c, constant.ContextKeyOriginalModel) + subscriptionRoute, _ := common.GetContextKeyType[*SubscriptionRoute](c, constant.ContextKeySubscriptionRoute) info := &RelayInfo{ Request: request, ReasoningEffort: reasoningEffort, @@ -633,6 +661,8 @@ func genBaseRelayInfo(c *gin.Context, request dto.Request) *RelayInfo { TokenUnlimited: common.GetContextKeyBool(c, constant.ContextKeyTokenUnlimited), TokenGroup: tokenGroup, + SubscriptionRoute: subscriptionRoute, + isFirstResponse: true, RelayMode: relayconstant.Path2RelayMode(c.Request.URL.Path), RequestURLPath: c.Request.URL.String(), diff --git a/relay/helper/common.go b/relay/helper/common.go index 59ce70c2d28d..7c698b3fca79 100644 --- a/relay/helper/common.go +++ b/relay/helper/common.go @@ -84,6 +84,21 @@ func (writer *streamKeepAliveWriter) ping() error { return PingData(writer.pingContext) } +// ResponseContentStarted reports whether anything besides keep-alive pings has +// reached the client, after which a request can no longer move to another +// upstream with a different billing source. +func ResponseContentStarted(c *gin.Context) bool { + if writer, ok := c.Writer.(*streamKeepAliveWriter); ok { + select { + case <-writer.done: + default: + // The keep-alive stops on the first business write. + return false + } + } + return c.Writer.Written() +} + // StartStreamKeepAlive 按 interval 发送心跳,覆盖请求准备和重试;业务写入开始后交给流处理器。 // 内层请求复用外层的保活,内层清理不会提前结束它。 func StartStreamKeepAlive(c *gin.Context, interval time.Duration) func() { diff --git a/service/billing_session.go b/service/billing_session.go index 61c6f9c7fa12..7b5fbeb73293 100644 --- a/service/billing_session.go +++ b/service/billing_session.go @@ -100,7 +100,25 @@ func (s *BillingSession) Refund(c *gin.Context) { s.funding.Source(), )) - // 复制需要的值到闭包中 + gopool.Go(s.refundReserved()) +} + +// refundNow 同步退还所有预扣费,供请求切换资金来源前使用:新的预扣要在旧预扣 +// (含令牌额度)退回后进行。与 Refund 共用 refunded 标记,二者合计只退一次。 +func (s *BillingSession) refundNow() bool { + s.mu.Lock() + if s.settled || s.refunded || !s.needsRefundLocked() { + s.mu.Unlock() + return false + } + s.refunded = true + s.mu.Unlock() + s.refundReserved()() + return true +} + +// refundReserved 返回退还资金来源与令牌预扣的操作,所需的值在调用时复制。 +func (s *BillingSession) refundReserved() func() { tokenId := s.relayInfo.TokenId tokenKey := s.relayInfo.TokenKey isPlayground := s.relayInfo.IsPlayground @@ -109,7 +127,7 @@ func (s *BillingSession) Refund(c *gin.Context) { subscriptionId := s.relayInfo.SubscriptionId funding := s.funding - gopool.Go(func() { + return func() { // 1) 退还资金来源 if err := funding.Refund(); err != nil { common.SysLog(common.LogText("error refunding billing source: %s", err.Error())) @@ -125,7 +143,7 @@ func (s *BillingSession) Refund(c *gin.Context) { common.SysLog(common.LogText("error refunding token quota: %s", err.Error())) } } - }) + } } // NeedsRefund 返回是否存在需要退还的预扣状态。 @@ -246,6 +264,13 @@ func (s *BillingSession) preConsume(c *gin.Context, quota int) *types.NewAPIErro types.ErrorCodeInsufficientUserQuota, http.StatusForbidden, types.ErrOptionWithSkipRetry(), types.ErrOptionWithNoRecordErrorLog()) } + var shortErr *model.SubscriptionQuotaInsufficientError + if errors.As(err, &shortErr) && s.relayInfo.SubscriptionRoute.Active() { + return types.NewErrorWithStatusCode( + errors.New(i18n.T(c, i18n.MsgQuotaBoundSubscriptionInsufficient, map[string]any{"Remaining": logger.FormatQuota(int(shortErr.Remaining)), "Required": logger.FormatQuota(int(shortErr.Required))})), + types.ErrorCodeInsufficientUserQuota, http.StatusForbidden, + types.ErrOptionWithSkipRetry(), types.ErrOptionWithNoRecordErrorLog()) + } errMsg := err.Error() if strings.Contains(errMsg, "no active subscription") || strings.Contains(errMsg, "subscription quota insufficient") { return types.NewErrorWithStatusCode(errors.New(i18n.T(c, i18n.MsgQuotaSubscriptionInsufficient, map[string]any{"Error": errMsg})), types.ErrorCodeInsufficientUserQuota, http.StatusForbidden, types.ErrOptionWithSkipRetry(), types.ErrOptionWithNoRecordErrorLog()) @@ -429,15 +454,19 @@ func NewBillingSession(c *gin.Context, relayInfo *relaycommon.RelayInfo, preCons if subConsume <= 0 { subConsume = 1 } + funding := &SubscriptionFunding{ + requestId: relayInfo.RequestId, + userId: relayInfo.UserId, + modelName: relayInfo.GetBillingModelName(), + amount: subConsume, + } + if relayInfo.SubscriptionRoute.Active() { + funding.boundSubscriptionId = relayInfo.SubscriptionRoute.SubscriptionId + } session := &BillingSession{ relayInfo: relayInfo, lang: i18n.StatedLang(c), - funding: &SubscriptionFunding{ - requestId: relayInfo.RequestId, - userId: relayInfo.UserId, - modelName: relayInfo.GetBillingModelName(), - amount: subConsume, - }, + funding: funding, } // 必须传 subConsume 而非 preConsumedQuota,保证 SubscriptionFunding.amount、 // preConsume 参数和 FinalPreConsumedQuota 三者一致,避免订阅多扣费。 @@ -447,6 +476,16 @@ func NewBillingSession(c *gin.Context, relayInfo *relaycommon.RelayInfo, preCons return session, nil } + // A request served by a bound subscription account is billed to that + // subscription only, whatever the preference, without wallet overflow. + // Once it fell back to the shared pool it is billed to the wallet only. + if route := relayInfo.SubscriptionRoute; route != nil { + if route.FellBack { + return tryWallet() + } + return trySubscription() + } + switch pref { case "subscription_only": return trySubscription() @@ -464,7 +503,7 @@ func NewBillingSession(c *gin.Context, relayInfo *relaycommon.RelayInfo, preCons case "subscription_first": fallthrough default: - hasSub, subCheckErr := model.HasActiveUserSubscription(relayInfo.UserId) + hasSub, subCheckErr := model.HasActiveUnboundUserSubscription(relayInfo.UserId) if subCheckErr != nil { return nil, types.NewError(subCheckErr, types.ErrorCodeQueryDataError, types.ErrOptionWithSkipRetry()) } @@ -475,7 +514,7 @@ func NewBillingSession(c *gin.Context, relayInfo *relaycommon.RelayInfo, preCons if apiErr != nil { if apiErr.GetErrorCode() == types.ErrorCodeInsufficientUserQuota { // 仅当用户的活跃订阅允许钱包回退时才回退到钱包,否则返回订阅额度不足错误 - allowOverflow, overflowErr := model.UserActiveSubscriptionsAllowWalletOverflow(relayInfo.UserId) + allowOverflow, overflowErr := model.UserActiveUnboundSubscriptionsAllowWalletOverflow(relayInfo.UserId) if overflowErr != nil { return nil, types.NewError(overflowErr, types.ErrorCodeQueryDataError, types.ErrOptionWithSkipRetry()) } diff --git a/service/funding_source.go b/service/funding_source.go index c22210b2745e..70df238d2046 100644 --- a/service/funding_source.go +++ b/service/funding_source.go @@ -79,12 +79,14 @@ func (w *WalletFunding) Refund() error { // --------------------------------------------------------------------------- type SubscriptionFunding struct { - requestId string - userId int - modelName string - amount int64 // 预扣的订阅额度(subConsume) - subscriptionId int - preConsumed int64 + requestId string + userId int + modelName string + amount int64 // 预扣的订阅额度(subConsume) + // boundSubscriptionId 非 0 时只从这个绑定了渠道账号的订阅预扣(请求被分发到它的专属分组) + boundSubscriptionId int + subscriptionId int + preConsumed int64 // 以下字段在 PreConsume 成功后填充,供 RelayInfo 同步使用 AmountTotal int64 AmountUsedAfter int64 @@ -96,7 +98,13 @@ func (s *SubscriptionFunding) Source() string { return BillingSourceSubscription func (s *SubscriptionFunding) PreConsume(_ int) error { // amount 参数被忽略,使用内部 s.amount(已在构造时根据 preConsumedQuota 计算) - res, err := model.PreConsumeUserSubscription(s.requestId, s.userId, s.modelName, 0, s.amount) + var res *model.SubscriptionPreConsumeResult + var err error + if s.boundSubscriptionId > 0 { + res, err = model.PreConsumeBoundUserSubscription(s.requestId, s.userId, s.boundSubscriptionId, s.amount) + } else { + res, err = model.PreConsumeUserSubscription(s.requestId, s.userId, s.modelName, 0, s.amount) + } if err != nil { return err } diff --git a/service/group.go b/service/group.go index a56d4c62d9f5..d475d9a6134e 100644 --- a/service/group.go +++ b/service/group.go @@ -6,6 +6,7 @@ import ( "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/model" + relaycommon "github.com/QuantumNous/new-api/relay/common" "github.com/QuantumNous/new-api/setting" "github.com/QuantumNous/new-api/setting/ratio_setting" "github.com/gin-gonic/gin" @@ -155,6 +156,11 @@ func FilterUserTokenAutoGroups(userGroup string, groups []string) []string { // first; a malformed snapshot still fails closed. func GetRequestAutoGroups(c *gin.Context, userGroup string) []string { userId := c.GetInt("id") + // A request whose bound account hit its usage limit and fell back to the + // shared pool must not be sent to the dedicated group again. + if route, ok := common.GetContextKeyType[*relaycommon.SubscriptionRoute](c, constant.ContextKeySubscriptionRoute); ok && route != nil && route.FellBack { + userId = 0 + } value, ok := common.GetContextKey(c, constant.ContextKeyTokenAutoGroups) if !ok { return GetUserAutoGroupForUser(userId, userGroup) diff --git a/service/group_auto_groups_test.go b/service/group_auto_groups_test.go index 56687daa657d..45626b98630b 100644 --- a/service/group_auto_groups_test.go +++ b/service/group_auto_groups_test.go @@ -77,7 +77,7 @@ func TestGetRequestAutoGroupsTreatsSubscriptionBindingGroupsLikeAnyOther(t *test common.SetContextKey(ctx, constant.ContextKeyTokenAutoGroups, []string{"vip", "default"}) require.NoError(t, ratio_setting.UpdateGroupRatioByJSONString(`{"default":1,"vip":1,"svip":1,"claude-ch7":1,"oauth-ch8":1}`)) - // Binding routing is request-scoped (ResolveSubscriptionRouteGroup), so a + // Binding routing is request-scoped (ResolveSubscriptionRoute), so a // user whose group still carries a binding name is not pinned to it. assert.Equal(t, []string{"vip", "default"}, GetRequestAutoGroups(ctx, "claude-ch7")) assert.Equal(t, []string{"vip", "default", "svip"}, GetRequestAutoGroups(newRequestAutoGroupsContext(), "oauth-ch8")) diff --git a/service/log_info_generate.go b/service/log_info_generate.go index 01416c77e4ee..94773065d6e1 100644 --- a/service/log_info_generate.go +++ b/service/log_info_generate.go @@ -193,6 +193,18 @@ func appendBillingInfo(relayInfo *relaycommon.RelayInfo, other *model.LogOther) if relayInfo.UserSetting.BillingPreference != "" { other.SetPublic("billing_preference", relayInfo.UserSetting.BillingPreference) } + // The bound account hit its usage limit and the request was served by the + // shared pool, billed to the wallet. + if route := relayInfo.SubscriptionRoute; route != nil && route.FellBack { + other.SetPublic("subscription_fallback", map[string]any{ + "reason": "bound_account_limited", + "subscription_id": route.SubscriptionId, + "from_group": route.Group, + "to_group": route.OriginalGroup, + "limit_window": route.LimitWindow, + }) + other.SetAdmin("subscription_fallback_channel_id", route.ChannelId) + } if relayInfo.BillingSource == "subscription" { if relayInfo.SubscriptionId != 0 { other.SetPublic("subscription_id", relayInfo.SubscriptionId) diff --git a/service/subscription_route.go b/service/subscription_route.go new file mode 100644 index 000000000000..ee1f5eca987c --- /dev/null +++ b/service/subscription_route.go @@ -0,0 +1,239 @@ +package service + +import ( + "errors" + "net/http" + "strconv" + "strings" + "time" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/constant" + "github.com/QuantumNous/new-api/i18n" + "github.com/QuantumNous/new-api/logger" + "github.com/QuantumNous/new-api/model" + relaycommon "github.com/QuantumNous/new-api/relay/common" + "github.com/QuantumNous/new-api/relaykit/types" + + "github.com/gin-gonic/gin" +) + +// ErrorCodeSubscriptionAccountLimited is returned when the bound account of a +// steered request hit its own usage limit and the request did not fall back. +const ErrorCodeSubscriptionAccountLimited types.ErrorCode = "subscription_account_limited" + +// subscriptionLimitResetMaxAhead bounds a reset time read from upstream or a +// sample; anything further away (or in the past) is not shown. +const subscriptionLimitResetMaxAhead = 8 * 24 * time.Hour + +// Usage windows of a Claude subscription account, by rate-limit header name, +// with the key the passive samples use for the same window. +var subscriptionLimitWindows = []struct { + header string + sampleKey string + labelKey string +}{ + {header: "5h", sampleKey: "five_hour", labelKey: i18n.MsgRelaySubscriptionWindow5h}, + {header: "7d", sampleKey: "seven_day", labelKey: i18n.MsgRelaySubscriptionWindow7d}, + {header: "7d_oi", sampleKey: "seven_day_overage_included", labelKey: i18n.MsgRelaySubscriptionWindow7dOi}, +} + +// SubscriptionAccountLimit is an upstream answer saying the bound account ran +// out of one of its own usage windows. +type SubscriptionAccountLimit struct { + // Window is "5h", "7d", "7d_oi", or "" when the answer did not say which. + Window string + // ResetAt is the unix time the window resets, 0 when unknown. + ResetAt int64 +} + +// RelayRetryGroup is the group a relay retry selects channels from. A request +// served by a subscription binding stays in the binding's dedicated group: the +// subscription pays only for its own account, never for the shared pool. +func RelayRetryGroup(info *relaycommon.RelayInfo) string { + if info.SubscriptionRoute.Active() { + return info.SubscriptionRoute.Group + } + return info.TokenGroup +} + +// RecordSubscriptionLimitHeaders keeps the usage-limit headers of the latest +// upstream answer of a subscription OAuth channel for the retry loop, which +// only sees the converted error. A nil header clears what an earlier attempt +// left. +func RecordSubscriptionLimitHeaders(c *gin.Context, headers http.Header) { + if c == nil { + return + } + kept := http.Header{} + for name, values := range headers { + lower := strings.ToLower(name) + if strings.HasPrefix(lower, "anthropic-ratelimit-unified-") || strings.HasPrefix(lower, "x-codex-") || lower == "retry-after" { + kept[name] = values + } + } + common.SetContextKey(c, constant.ContextKeyUpstreamRateLimitHeaders, kept) +} + +// DetectSubscriptionAccountLimit reports whether a failed attempt on a bound +// subscription channel was the account's own usage limit: HTTP 429, an +// Anthropic rate_limit_error, a window whose unified status is "rejected", or +// a Codex usage_limit_reached / rate_limit_exceeded error. The window and reset +// time come from the response headers first, then from the channel's passive +// usage samples. +func DetectSubscriptionAccountLimit(apiErr *types.NewAPIError, headers http.Header, passive map[string]ClaudePassiveUsageWindow, now time.Time) (SubscriptionAccountLimit, bool) { + if apiErr == nil { + return SubscriptionAccountLimit{}, false + } + limited := apiErr.StatusCode == http.StatusTooManyRequests + switch apiErr.ToOpenAIError().Type { + case "rate_limit_error", "usage_limit_reached", "rate_limit_exceeded": + limited = true + } + if strings.EqualFold(strings.TrimSpace(headers.Get("anthropic-ratelimit-unified-status")), "rejected") { + limited = true + } + + // The window that keeps the account locked longest is the one to report. + var limit SubscriptionAccountLimit + found := false + for _, w := range subscriptionLimitWindows { + prefix := "anthropic-ratelimit-unified-" + w.header + "-" + rejected := strings.EqualFold(strings.TrimSpace(headers.Get(prefix+"status")), "rejected") + if !rejected { + utilization, err := strconv.ParseFloat(strings.TrimSpace(headers.Get(prefix+"utilization")), 64) + rejected = err == nil && utilization >= 1 + } + if !rejected { + continue + } + limited = true + resetAt := parseSubscriptionLimitReset(headers.Get(prefix+"reset"), now) + if !found || resetAt > limit.ResetAt { + limit = SubscriptionAccountLimit{Window: w.header, ResetAt: resetAt} + found = true + } + } + if !limited { + return SubscriptionAccountLimit{}, false + } + if limit.ResetAt == 0 { + limit.ResetAt = parseSubscriptionLimitReset(headers.Get("anthropic-ratelimit-unified-reset"), now) + } + if found || limit.ResetAt > 0 { + return limit, true + } + for _, w := range subscriptionLimitWindows { + sample, ok := passive[w.sampleKey] + if !ok || sample.Utilization < 100 || sample.ResetsAt <= now.Unix() || time.Unix(sample.ResetsAt, 0).Sub(now) > subscriptionLimitResetMaxAhead { + continue + } + if sample.ResetsAt > limit.ResetAt { + limit = SubscriptionAccountLimit{Window: w.header, ResetAt: sample.ResetsAt} + } + } + return limit, true +} + +func parseSubscriptionLimitReset(raw string, now time.Time) int64 { + reset, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64) + if err != nil || reset <= 0 { + return 0 + } + // Anthropic sends unix seconds; tolerate milliseconds. + if reset > 1e11 { + reset /= 1000 + } + if reset <= now.Unix() || time.Unix(reset, 0).Sub(now) > subscriptionLimitResetMaxAhead { + return 0 + } + return reset +} + +// HandleSubscriptionRouteFailure runs after a failed attempt of a request the +// distributor steered to a subscription binding. When the bound account +// answered with its own usage limit: +// - if the plan has fallback enabled and nothing reached the client yet, the +// bound subscription's reservation is refunded, the wallet reserves the +// request instead, and the retry continues in the request's original group +// (Auto without the dedicated group); it returns true; +// - otherwise it returns a 429 that names the exhausted window and its reset +// time, which ends the request. +// +// Any other failure is returned unchanged. +func HandleSubscriptionRouteFailure(c *gin.Context, info *relaycommon.RelayInfo, retry *RetryParam, apiErr *types.NewAPIError, responseStarted bool) (*types.NewAPIError, bool) { + route := info.SubscriptionRoute + if !route.Active() || apiErr == nil || common.GetContextKeyInt(c, constant.ContextKeyChannelId) != route.ChannelId { + return apiErr, false + } + headers, _ := common.GetContextKeyType[http.Header](c, constant.ContextKeyUpstreamRateLimitHeaders) + var passive map[string]ClaudePassiveUsageWindow + if channel, err := model.CacheGetChannel(route.ChannelId); err == nil { + passive = LoadClaudePassiveUsage(channel) + } + limit, limited := DetectSubscriptionAccountLimit(apiErr, headers, passive, time.Now()) + if !limited { + return apiErr, false + } + + fallBack := false + if !responseStarted && route.OriginalGroup != "" && route.OriginalGroup != route.Group { + enabled, err := model.SubscriptionFallsBackToSharedPool(route.SubscriptionId) + if err != nil { + logger.LogError(c, common.LogText("failed to read the shared pool fallback setting of subscription %d: %v", route.SubscriptionId, err)) + } + fallBack = enabled + } + if !fallBack { + logger.LogInfo(c, common.LogText("subscription %d bound account (channel #%d) hit its usage limit (window=%q, reset_at=%d); the request ends without falling back", route.SubscriptionId, route.ChannelId, limit.Window, limit.ResetAt)) + return subscriptionAccountLimitError(c, limit), false + } + + logger.LogWarn(c, common.LogText("subscription %d bound account (channel #%d) hit its usage limit (window=%q); falling back to the shared pool group %s, billed to the wallet", route.SubscriptionId, route.ChannelId, limit.Window, route.OriginalGroup)) + route.FellBack = true + route.LimitWindow = limit.Window + if session, ok := info.Billing.(*BillingSession); ok { + session.refundNow() + } + info.Billing = nil + if !info.PriceData.FreeModel { + if billingErr := PreConsumeBilling(c, info.PriceData.QuotaToPreConsume, info); billingErr != nil { + return billingErr, false + } + } + common.SetContextKey(c, constant.ContextKeyUsingGroup, route.OriginalGroup) + common.SetContextKey(c, constant.ContextKeyAutoGroupIndex, 0) + info.UsingGroup = route.OriginalGroup + retry.TokenGroup = route.OriginalGroup + // The shared pool gets the full attempt budget, starting at its highest + // priority. + retry.SetRetry(0) + retry.ResetRetryNextTry() + c.Set(ginKeyChannelAffinityRetryOffset, 0) + return apiErr, true +} + +func subscriptionAccountLimitError(c *gin.Context, limit SubscriptionAccountLimit) *types.NewAPIError { + resetAt := "" + if limit.ResetAt > 0 { + resetAt = time.Unix(limit.ResetAt, 0).Format("2006-01-02 15:04 MST") + } + window := "" + for _, w := range subscriptionLimitWindows { + if w.header == limit.Window { + window = i18n.T(c, w.labelKey) + } + } + var message string + switch { + case window != "" && resetAt != "": + message = i18n.T(c, i18n.MsgRelaySubscriptionAccountLimited, map[string]any{"Window": window, "ResetAt": resetAt}) + case window != "": + message = i18n.T(c, i18n.MsgRelaySubscriptionAccountLimitedNoReset, map[string]any{"Window": window}) + case resetAt != "": + message = i18n.T(c, i18n.MsgRelaySubscriptionAccountLimitedGenericReset, map[string]any{"ResetAt": resetAt}) + default: + message = i18n.T(c, i18n.MsgRelaySubscriptionAccountLimitedGeneric) + } + return types.NewErrorWithStatusCode(errors.New(message), ErrorCodeSubscriptionAccountLimited, http.StatusTooManyRequests, types.ErrOptionWithSkipRetry()) +} diff --git a/service/subscription_route_test.go b/service/subscription_route_test.go new file mode 100644 index 000000000000..7bf9e5657488 --- /dev/null +++ b/service/subscription_route_test.go @@ -0,0 +1,449 @@ +package service + +import ( + "net/http" + "net/http/httptest" + "strconv" + "testing" + "time" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/constant" + "github.com/QuantumNous/new-api/logger" + "github.com/QuantumNous/new-api/model" + relaycommon "github.com/QuantumNous/new-api/relay/common" + "github.com/QuantumNous/new-api/relaykit/dto" + "github.com/QuantumNous/new-api/relaykit/types" + "github.com/QuantumNous/new-api/setting/ratio_setting" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + routeUserId = 41 + routeTokenId = 41 + routeTokenKey = "sk-route-key" + routeBoundSubId = 41 + routeSharedSubId = 42 + routeBoundPlanId = 41 + routeSharedPlanId = 42 + routeBoundChannel = 7 + routeBoundGroup = "claude-ch7" + routeWalletQuota = 50000 + routeTokenQuota = 50000 + routeSubTotal = 1000 + routeRequestQuota = 300 + routeOriginalGroup = "default" +) + +type subscriptionRouteFixture struct { + t *testing.T +} + +// newSubscriptionRouteFixture seeds a user holding a subscription bound to +// channel 7 (dedicated group claude-ch7) and an ordinary subscription, each +// with routeSubTotal quota, plus wallet and token quota. +func newSubscriptionRouteFixture(t *testing.T) *subscriptionRouteFixture { + t.Helper() + require.NoError(t, model.DB.AutoMigrate(&model.SubscriptionPlan{}, &model.SubscriptionPreConsumeRecord{})) + truncate(t) + t.Cleanup(func() { + model.DB.Exec("DELETE FROM subscription_plans") + model.DB.Exec("DELETE FROM subscription_pre_consume_records") + model.InvalidateSubscriptionPlanCache(routeBoundPlanId) + model.InvalidateSubscriptionPlanCache(routeSharedPlanId) + model.InvalidateSubscriptionRouteBindingCache(routeUserId) + }) + seedUser(t, routeUserId, routeWalletQuota) + seedToken(t, routeTokenId, routeUserId, routeTokenKey, routeTokenQuota) + for _, plan := range []*model.SubscriptionPlan{ + {Id: routeBoundPlanId, Title: "Dedicated", PriceAmount: 1, TotalAmount: routeSubTotal}, + {Id: routeSharedPlanId, Title: "Shared", PriceAmount: 1, TotalAmount: routeSubTotal}, + } { + plan.NormalizeDefaults() + require.NoError(t, model.DB.Create(plan).Error) + model.InvalidateSubscriptionPlanCache(plan.Id) + } + now := time.Now() + for _, sub := range []*model.UserSubscription{ + {Id: routeBoundSubId, PlanId: routeBoundPlanId, BoundChannelId: routeBoundChannel, BoundGroup: routeBoundGroup, AllowWalletOverflow: true}, + {Id: routeSharedSubId, PlanId: routeSharedPlanId, AllowWalletOverflow: true}, + } { + sub.UserId = routeUserId + sub.AmountTotal = routeSubTotal + sub.Status = "active" + sub.StartTime = now.Unix() + sub.EndTime = now.Add(30 * 24 * time.Hour).Unix() + require.NoError(t, model.DB.Create(sub).Error) + } + model.InvalidateSubscriptionRouteBindingCache(routeUserId) + return &subscriptionRouteFixture{t: t} +} + +func (f *subscriptionRouteFixture) setPlanFallback(enabled bool) { + require.NoError(f.t, model.DB.Model(&model.SubscriptionPlan{}).Where("id = ?", routeBoundPlanId). + Update("fallback_to_shared_pool_on_limit", enabled).Error) + model.InvalidateSubscriptionPlanCache(routeBoundPlanId) +} + +// request builds the context and relay info of one request. A non-nil route +// marks it as steered to the bound account by the distributor. +func (f *subscriptionRouteFixture) request(requestId string, preference string, route *relaycommon.SubscriptionRoute) (*gin.Context, *relaycommon.RelayInfo) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + c.Set("id", routeUserId) + usingGroup := routeOriginalGroup + if route != nil { + usingGroup = route.Group + common.SetContextKey(c, constant.ContextKeySubscriptionRoute, route) + } + common.SetContextKey(c, constant.ContextKeyUsingGroup, usingGroup) + info := &relaycommon.RelayInfo{ + RequestId: requestId, + UserId: routeUserId, + TokenId: routeTokenId, + TokenKey: routeTokenKey, + TokenGroup: routeOriginalGroup, + UsingGroup: usingGroup, + OriginModelName: "claude-sonnet-4-5", + UserSetting: dto.UserSetting{BillingPreference: preference}, + SubscriptionRoute: route, + } + info.PriceData.QuotaToPreConsume = routeRequestQuota + return c, info +} + +func boundRoute(originalGroup string) *relaycommon.SubscriptionRoute { + return &relaycommon.SubscriptionRoute{ + SubscriptionId: routeBoundSubId, + ChannelId: routeBoundChannel, + Group: routeBoundGroup, + OriginalGroup: originalGroup, + } +} + +func preConsumeRecordStatus(t *testing.T, requestId string) string { + t.Helper() + var record model.SubscriptionPreConsumeRecord + require.NoError(t, model.DB.Where("request_id = ?", requestId).First(&record).Error) + return record.Status +} + +func TestSubscriptionRouteBillingAttribution(t *testing.T) { + tests := []struct { + name string + preference string + routed bool + dropShared bool + wantSource string + wantBoundUsed int64 + wantShareUsed int64 + wantWallet int + }{ + // A steered request pays from the bound subscription only, whatever + // the preference and even with another subscription available. + {name: "routed subscription_first", preference: "subscription_first", routed: true, wantSource: BillingSourceSubscription, wantBoundUsed: routeRequestQuota, wantWallet: routeWalletQuota}, + {name: "routed wallet_first ignores preference", preference: "wallet_first", routed: true, wantSource: BillingSourceSubscription, wantBoundUsed: routeRequestQuota, wantWallet: routeWalletQuota}, + {name: "routed wallet_only ignores preference", preference: "wallet_only", routed: true, wantSource: BillingSourceSubscription, wantBoundUsed: routeRequestQuota, wantWallet: routeWalletQuota}, + // Other requests never touch the bound subscription. + {name: "unrouted uses the ordinary subscription", preference: "subscription_first", wantSource: BillingSourceSubscription, wantShareUsed: routeRequestQuota, wantWallet: routeWalletQuota}, + {name: "unrouted subscription_only uses the ordinary subscription", preference: "subscription_only", wantSource: BillingSourceSubscription, wantShareUsed: routeRequestQuota, wantWallet: routeWalletQuota}, + {name: "unrouted with only a bound subscription uses the wallet", preference: "subscription_first", dropShared: true, wantSource: BillingSourceWallet, wantWallet: routeWalletQuota - routeRequestQuota}, + {name: "unrouted wallet_first uses the wallet", preference: "wallet_first", wantSource: BillingSourceWallet, wantWallet: routeWalletQuota - routeRequestQuota}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + newSubscriptionRouteFixture(t) + if tt.dropShared { + require.NoError(t, model.DB.Delete(&model.UserSubscription{}, routeSharedSubId).Error) + } + var route *relaycommon.SubscriptionRoute + if tt.routed { + route = boundRoute(routeOriginalGroup) + } + c, info := (&subscriptionRouteFixture{t: t}).request("req-"+tt.name, tt.preference, route) + + apiErr := PreConsumeBilling(c, routeRequestQuota, info) + + require.Nil(t, apiErr) + assert.Equal(t, tt.wantSource, info.BillingSource) + assert.Equal(t, tt.wantBoundUsed, getSubscriptionUsed(t, routeBoundSubId)) + if !tt.dropShared { + assert.Equal(t, tt.wantShareUsed, getSubscriptionUsed(t, routeSharedSubId)) + } + assert.Equal(t, tt.wantWallet, getUserQuota(t, routeUserId)) + }) + } +} + +func TestSubscriptionRouteBoundSubscriptionShortDoesNotUseWallet(t *testing.T) { + f := newSubscriptionRouteFixture(t) + require.NoError(t, model.DB.Model(&model.UserSubscription{}).Where("id = ?", routeBoundSubId).Update("amount_used", routeSubTotal-100).Error) + c, info := f.request("req-bound-short", "subscription_first", boundRoute(routeOriginalGroup)) + + apiErr := PreConsumeBilling(c, routeRequestQuota, info) + + require.NotNil(t, apiErr) + assert.Equal(t, types.ErrorCodeInsufficientUserQuota, apiErr.GetErrorCode()) + assert.Contains(t, apiErr.Error(), logger.FormatQuota(100)) + assert.Contains(t, apiErr.Error(), logger.FormatQuota(routeRequestQuota)) + assert.Nil(t, info.Billing) + assert.Equal(t, int64(routeSubTotal-100), getSubscriptionUsed(t, routeBoundSubId)) + assert.Zero(t, getSubscriptionUsed(t, routeSharedSubId), "the ordinary subscription does not pay for the bound account") + assert.Equal(t, routeWalletQuota, getUserQuota(t, routeUserId)) + assert.Equal(t, routeTokenQuota, getTokenRemainQuota(t, routeTokenId), "the token reservation is rolled back") +} + +func TestSubscriptionRouteWalletOverflowIgnoresBoundSubscriptions(t *testing.T) { + t.Run("bound subscription without overflow does not block the wallet", func(t *testing.T) { + f := newSubscriptionRouteFixture(t) + require.NoError(t, model.DB.Model(&model.UserSubscription{}).Where("id = ?", routeBoundSubId).Update("allow_wallet_overflow", false).Error) + require.NoError(t, model.DB.Model(&model.UserSubscription{}).Where("id = ?", routeSharedSubId).Update("amount_used", routeSubTotal).Error) + c, info := f.request("req-overflow-allowed", "subscription_first", nil) + + require.Nil(t, PreConsumeBilling(c, routeRequestQuota, info)) + assert.Equal(t, BillingSourceWallet, info.BillingSource) + assert.Equal(t, routeWalletQuota-routeRequestQuota, getUserQuota(t, routeUserId)) + assert.Zero(t, getSubscriptionUsed(t, routeBoundSubId)) + }) + t.Run("ordinary subscription without overflow still blocks the wallet", func(t *testing.T) { + f := newSubscriptionRouteFixture(t) + require.NoError(t, model.DB.Model(&model.UserSubscription{}).Where("id = ?", routeSharedSubId).Updates(map[string]any{"amount_used": routeSubTotal, "allow_wallet_overflow": false}).Error) + c, info := f.request("req-overflow-blocked", "subscription_first", nil) + + apiErr := PreConsumeBilling(c, routeRequestQuota, info) + require.NotNil(t, apiErr) + assert.Equal(t, types.ErrorCodeInsufficientUserQuota, apiErr.GetErrorCode()) + assert.Equal(t, routeWalletQuota, getUserQuota(t, routeUserId)) + }) +} + +func TestDetectSubscriptionAccountLimit(t *testing.T) { + now := time.Unix(1_800_000_000, 0) + reset5h := now.Add(2 * time.Hour).Unix() + reset7d := now.Add(3 * 24 * time.Hour).Unix() + headers := func(pairs ...string) http.Header { + h := http.Header{} + for i := 0; i+1 < len(pairs); i += 2 { + h.Set(pairs[i], pairs[i+1]) + } + return h + } + status := func(code int) *types.NewAPIError { + return types.NewOpenAIError(assert.AnError, types.ErrorCodeBadResponseStatusCode, code) + } + tests := []struct { + name string + err *types.NewAPIError + headers http.Header + passive map[string]ClaudePassiveUsageWindow + wantLimited bool + want SubscriptionAccountLimit + }{ + { + name: "429 with the 5h window rejected", + err: status(http.StatusTooManyRequests), + headers: headers("anthropic-ratelimit-unified-5h-status", "rejected", "anthropic-ratelimit-unified-5h-reset", "1800007200"), + wantLimited: true, + want: SubscriptionAccountLimit{Window: "5h", ResetAt: reset5h}, + }, + { + name: "both windows exhausted reports the later reset", + err: status(http.StatusTooManyRequests), + headers: headers("anthropic-ratelimit-unified-5h-status", "rejected", "anthropic-ratelimit-unified-5h-reset", "1800007200", + "anthropic-ratelimit-unified-7d-utilization", "1.0", "anthropic-ratelimit-unified-7d-reset", "1800259200"), + wantLimited: true, + want: SubscriptionAccountLimit{Window: "7d", ResetAt: reset7d}, + }, + { + name: "rate_limit_error without status 429", + err: types.WithClaudeError(types.ClaudeError{Type: "rate_limit_error", Message: "limited"}, http.StatusBadRequest), + wantLimited: true, + }, + { + name: "codex usage_limit_reached", + err: types.WithOpenAIError(types.OpenAIError{Type: "usage_limit_reached", Message: "The usage limit has been reached"}, http.StatusTooManyRequests), + wantLimited: true, + }, + { + name: "no headers falls back to the passive sample", + err: status(http.StatusTooManyRequests), + passive: map[string]ClaudePassiveUsageWindow{"five_hour": {Utilization: 100, ResetsAt: reset5h, SampledAt: now.Unix()}, "seven_day": {Utilization: 40, ResetsAt: reset7d, SampledAt: now.Unix()}}, + wantLimited: true, + want: SubscriptionAccountLimit{Window: "5h", ResetAt: reset5h}, + }, + { + name: "a reset in the past is not shown", + err: status(http.StatusTooManyRequests), + headers: headers("anthropic-ratelimit-unified-5h-status", "rejected", "anthropic-ratelimit-unified-5h-reset", "1799990000"), + wantLimited: true, + want: SubscriptionAccountLimit{Window: "5h"}, + }, + { + name: "server error is not a usage limit", + err: status(http.StatusInternalServerError), + headers: headers("anthropic-ratelimit-unified-5h-status", "allowed", "anthropic-ratelimit-unified-5h-utilization", "0.4"), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + limit, limited := DetectSubscriptionAccountLimit(tt.err, tt.headers, tt.passive, now) + assert.Equal(t, tt.wantLimited, limited) + assert.Equal(t, tt.want, limit) + }) + } +} + +// boundAccountLimited prepares a failed attempt on the bound channel whose +// answer was a 5h window rejection resetting in two hours. +func boundAccountLimited(c *gin.Context) (*types.NewAPIError, int64) { + resetAt := time.Now().Add(2 * time.Hour).Unix() + headers := http.Header{} + headers.Set("anthropic-ratelimit-unified-5h-status", "rejected") + headers.Set("anthropic-ratelimit-unified-5h-reset", strconv.FormatInt(resetAt, 10)) + common.SetContextKey(c, constant.ContextKeyChannelId, routeBoundChannel) + RecordSubscriptionLimitHeaders(c, headers) + return types.NewOpenAIError(assert.AnError, types.ErrorCodeBadResponseStatusCode, http.StatusTooManyRequests), resetAt +} + +func TestHandleSubscriptionRouteFailureWithoutFallback(t *testing.T) { + f := newSubscriptionRouteFixture(t) + c, info := f.request("req-limit-off", "subscription_first", boundRoute(routeOriginalGroup)) + require.Nil(t, PreConsumeBilling(c, routeRequestQuota, info)) + upstreamErr, resetAt := boundAccountLimited(c) + retry := &RetryParam{Ctx: c, TokenGroup: RelayRetryGroup(info), Retry: common.GetPointer(1)} + assert.Equal(t, routeBoundGroup, retry.TokenGroup, "retries of a steered request stay in the dedicated group") + + apiErr, fellBack := HandleSubscriptionRouteFailure(c, info, retry, upstreamErr, false) + + assert.False(t, fellBack) + require.NotNil(t, apiErr) + assert.Equal(t, ErrorCodeSubscriptionAccountLimited, apiErr.GetErrorCode()) + assert.Equal(t, http.StatusTooManyRequests, apiErr.StatusCode) + assert.True(t, types.IsSkipRetryError(apiErr)) + assert.Contains(t, apiErr.Error(), "5-hour") + assert.Contains(t, apiErr.Error(), time.Unix(resetAt, 0).Format("2006-01-02 15:04")) + assert.Equal(t, routeBoundGroup, retry.TokenGroup) + assert.True(t, info.SubscriptionRoute.Active()) + + // The failed request refunds the bound subscription through the normal path. + info.Billing.Refund(c) + require.Eventually(t, func() bool { return getSubscriptionUsed(t, routeBoundSubId) == 0 }, 2*time.Second, 10*time.Millisecond) + assert.Equal(t, routeWalletQuota, getUserQuota(t, routeUserId)) +} + +func TestHandleSubscriptionRouteFailureFallsBackToSharedPool(t *testing.T) { + f := newSubscriptionRouteFixture(t) + f.setPlanFallback(true) + c, info := f.request("req-limit-on", "subscription_first", boundRoute(routeOriginalGroup)) + require.Nil(t, PreConsumeBilling(c, routeRequestQuota, info)) + require.Equal(t, int64(routeRequestQuota), getSubscriptionUsed(t, routeBoundSubId)) + upstreamErr, _ := boundAccountLimited(c) + retry := &RetryParam{Ctx: c, TokenGroup: RelayRetryGroup(info), Retry: common.GetPointer(2)} + + apiErr, fellBack := HandleSubscriptionRouteFailure(c, info, retry, upstreamErr, false) + + require.True(t, fellBack) + assert.Same(t, upstreamErr, apiErr) + // The retry continues in the original group with a fresh attempt budget. + assert.Equal(t, routeOriginalGroup, retry.TokenGroup) + retry.IncreaseRetry() + assert.Zero(t, retry.GetRetry()) + assert.Equal(t, routeOriginalGroup, common.GetContextKeyString(c, constant.ContextKeyUsingGroup)) + assert.Equal(t, routeOriginalGroup, info.UsingGroup) + // The bound subscription reservation is refunded synchronously and the + // wallet reserves the request instead. + assert.Zero(t, getSubscriptionUsed(t, routeBoundSubId)) + assert.Equal(t, "refunded", preConsumeRecordStatus(t, "req-limit-on")) + assert.Zero(t, getSubscriptionUsed(t, routeSharedSubId)) + assert.Equal(t, routeWalletQuota-routeRequestQuota, getUserQuota(t, routeUserId)) + assert.Equal(t, routeTokenQuota-routeRequestQuota, getTokenRemainQuota(t, routeTokenId)) + assert.Equal(t, BillingSourceWallet, info.BillingSource) + assert.Equal(t, "5h", info.SubscriptionRoute.LimitWindow) + assert.Equal(t, routeOriginalGroup, RelayRetryGroup(info)) + + // Idempotent per request id: the route no longer applies, the bound + // subscription cannot be charged again, and the wallet is charged once. + again, fellBackAgain := HandleSubscriptionRouteFailure(c, info, retry, upstreamErr, false) + assert.False(t, fellBackAgain) + assert.Same(t, upstreamErr, again) + _, err := model.PreConsumeBoundUserSubscription("req-limit-on", routeUserId, routeBoundSubId, routeRequestQuota) + assert.ErrorContains(t, err, "already refunded") + assert.Zero(t, getSubscriptionUsed(t, routeBoundSubId)) + assert.Equal(t, routeWalletQuota-routeRequestQuota, getUserQuota(t, routeUserId)) + + // The consume log tells the fallback apart. + other := model.NewLogOther() + appendBillingInfo(info, other) + fallback, ok := other.Snapshot()["subscription_fallback"].(map[string]any) + require.True(t, ok) + assert.Equal(t, "bound_account_limited", fallback["reason"]) + assert.Equal(t, routeBoundGroup, fallback["from_group"]) + assert.Equal(t, routeOriginalGroup, fallback["to_group"]) + + // If the shared pool fails as well, only the wallet reservation is refunded. + info.Billing.Refund(c) + require.Eventually(t, func() bool { return getUserQuota(t, routeUserId) == routeWalletQuota }, 2*time.Second, 10*time.Millisecond) + assert.Zero(t, getSubscriptionUsed(t, routeBoundSubId)) +} + +func TestHandleSubscriptionRouteFailureAutoExcludesDedicatedGroup(t *testing.T) { + configureRequestAutoGroupsTest(t) + require.NoError(t, ratio_setting.UpdateGroupRatioByJSONString(`{"default":1,"vip":1,"svip":1,"claude-ch7":1}`)) + f := newSubscriptionRouteFixture(t) + f.setPlanFallback(true) + c, info := f.request("req-limit-auto", "subscription_first", boundRoute("auto")) + common.SetContextKey(c, constant.ContextKeyUserGroup, "default") + require.Equal(t, []string{routeBoundGroup, "vip", "default", "svip"}, GetRequestAutoGroups(c, "default")) + require.Nil(t, PreConsumeBilling(c, routeRequestQuota, info)) + upstreamErr, _ := boundAccountLimited(c) + retry := &RetryParam{Ctx: c, TokenGroup: RelayRetryGroup(info), Retry: common.GetPointer(0)} + + _, fellBack := HandleSubscriptionRouteFailure(c, info, retry, upstreamErr, false) + + require.True(t, fellBack) + assert.Equal(t, "auto", retry.TokenGroup) + assert.Equal(t, []string{"vip", "default", "svip"}, GetRequestAutoGroups(c, "default")) +} + +func TestHandleSubscriptionRouteFailureKeepsTheBoundAccount(t *testing.T) { + tests := []struct { + name string + originalGroup string + responseStarted bool + walletQuota int + upstreamStatus int + wantCode types.ErrorCode + }{ + {name: "response already started", originalGroup: routeOriginalGroup, responseStarted: true, walletQuota: routeWalletQuota, upstreamStatus: http.StatusTooManyRequests, wantCode: ErrorCodeSubscriptionAccountLimited}, + {name: "token already uses the dedicated group", originalGroup: routeBoundGroup, walletQuota: routeWalletQuota, upstreamStatus: http.StatusTooManyRequests, wantCode: ErrorCodeSubscriptionAccountLimited}, + {name: "wallet cannot cover the request", originalGroup: routeOriginalGroup, walletQuota: 100, upstreamStatus: http.StatusTooManyRequests, wantCode: types.ErrorCodeInsufficientUserQuota}, + {name: "not a usage limit", originalGroup: routeOriginalGroup, walletQuota: routeWalletQuota, upstreamStatus: http.StatusInternalServerError, wantCode: types.ErrorCodeBadResponseStatusCode}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := newSubscriptionRouteFixture(t) + f.setPlanFallback(true) + require.NoError(t, model.DB.Model(&model.User{}).Where("id = ?", routeUserId).Update("quota", tt.walletQuota).Error) + c, info := f.request("req-keep-"+tt.name, "subscription_first", boundRoute(tt.originalGroup)) + require.Nil(t, PreConsumeBilling(c, routeRequestQuota, info)) + limitErr, _ := boundAccountLimited(c) + upstreamErr := limitErr + if tt.upstreamStatus != http.StatusTooManyRequests { + RecordSubscriptionLimitHeaders(c, nil) + upstreamErr = types.NewOpenAIError(assert.AnError, types.ErrorCodeBadResponseStatusCode, tt.upstreamStatus) + } + retry := &RetryParam{Ctx: c, TokenGroup: RelayRetryGroup(info), Retry: common.GetPointer(0)} + + apiErr, fellBack := HandleSubscriptionRouteFailure(c, info, retry, upstreamErr, tt.responseStarted) + + assert.False(t, fellBack) + require.NotNil(t, apiErr) + assert.Equal(t, tt.wantCode, apiErr.GetErrorCode()) + assert.NotEqual(t, routeOriginalGroup, retry.TokenGroup) + assert.Equal(t, tt.walletQuota, getUserQuota(t, routeUserId), "the wallet is not charged") + }) + } +} diff --git a/web/src/features/subscriptions/components/subscriptions-mutate-drawer.tsx b/web/src/features/subscriptions/components/subscriptions-mutate-drawer.tsx index 065e2713c117..29b837cb7695 100644 --- a/web/src/features/subscriptions/components/subscriptions-mutate-drawer.tsx +++ b/web/src/features/subscriptions/components/subscriptions-mutate-drawer.tsx @@ -568,6 +568,33 @@ export function SubscriptionsMutateDrawer({ )} /> + + ( + +
+ + {t( + 'Fall back to the shared pool when the account is limited' + )} + + + {t( + 'When the bound subscription account hits its usage limit, serve the request from the shared pool and charge the wallet balance. Off: the request fails with the reset time.' + )} + +
+ + + +
+ )} + /> diff --git a/web/src/features/subscriptions/lib/__tests__/plan-form.test.ts b/web/src/features/subscriptions/lib/__tests__/plan-form.test.ts new file mode 100644 index 000000000000..274220515184 --- /dev/null +++ b/web/src/features/subscriptions/lib/__tests__/plan-form.test.ts @@ -0,0 +1,62 @@ +/* +Copyright (C) 2023-2026 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { describe, expect, test } from 'vitest' + +import { subscriptionPlanSchema } from '../../types' +import { + PLAN_FORM_DEFAULTS, + formValuesToPlanPayload, + planToFormValues, +} from '../plan-form' + +const basePlan = { + id: 1, + title: 'Dedicated Claude', + price_amount: 10, + duration_unit: 'month', + duration_value: 1, + quota_reset_period: 'never', + enabled: true, + sort_order: 0, + max_purchase_per_user: 0, + total_amount: 0, +} + +describe('shared pool fallback switch', () => { + test('new plans start with the fallback off', () => { + expect(PLAN_FORM_DEFAULTS.fallback_to_shared_pool_on_limit).toBe(false) + }) + + test('a plan saved before the switch existed loads with the fallback off', () => { + const plan = subscriptionPlanSchema.parse(basePlan) + + expect(planToFormValues(plan).fallback_to_shared_pool_on_limit).toBe(false) + }) + + test('an enabled fallback is loaded and sent back to the API', () => { + const plan = subscriptionPlanSchema.parse({ + ...basePlan, + fallback_to_shared_pool_on_limit: true, + }) + + const payload = formValuesToPlanPayload(planToFormValues(plan)) + + expect(payload.plan.fallback_to_shared_pool_on_limit).toBe(true) + }) +}) diff --git a/web/src/features/subscriptions/lib/plan-form.ts b/web/src/features/subscriptions/lib/plan-form.ts index feaaeb2a3268..d45349f48d66 100644 --- a/web/src/features/subscriptions/lib/plan-form.ts +++ b/web/src/features/subscriptions/lib/plan-form.ts @@ -43,6 +43,7 @@ export function getPlanFormSchema(t: TFunction) { sort_order: z.coerce.number(), allow_balance_pay: z.boolean(), allow_wallet_overflow: z.boolean(), + fallback_to_shared_pool_on_limit: z.boolean(), max_purchase_per_user: z.coerce.number().min(0), total_amount: z.coerce.number().min(0), upgrade_group: z.string().optional(), @@ -68,6 +69,7 @@ export const PLAN_FORM_DEFAULTS: PlanFormValues = { sort_order: 0, allow_balance_pay: true, allow_wallet_overflow: true, + fallback_to_shared_pool_on_limit: false, max_purchase_per_user: 0, total_amount: 0, upgrade_group: '', @@ -91,6 +93,8 @@ export function planToFormValues(plan: SubscriptionPlan): PlanFormValues { sort_order: Number(plan.sort_order || 0), allow_balance_pay: plan.allow_balance_pay !== false, allow_wallet_overflow: plan.allow_wallet_overflow !== false, + fallback_to_shared_pool_on_limit: + plan.fallback_to_shared_pool_on_limit === true, max_purchase_per_user: Number(plan.max_purchase_per_user || 0), total_amount: quotaUnitsToDollars(Number(plan.total_amount || 0)), upgrade_group: plan.upgrade_group || '', diff --git a/web/src/features/subscriptions/types.ts b/web/src/features/subscriptions/types.ts index c1b08a78c7f5..420e97f9fa54 100644 --- a/web/src/features/subscriptions/types.ts +++ b/web/src/features/subscriptions/types.ts @@ -37,6 +37,7 @@ export const subscriptionPlanSchema = z.object({ sort_order: z.number(), allow_balance_pay: z.boolean().optional().default(true), allow_wallet_overflow: z.boolean().optional().default(true), + fallback_to_shared_pool_on_limit: z.boolean().optional().default(false), max_purchase_per_user: z.number(), total_amount: z.number(), upgrade_group: z.string().optional(), diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index ef2729c43921..f94d52b3aec2 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -2747,6 +2747,7 @@ "Failure keywords": "Failure keywords", "Failure reason": "Failure reason", "Fair": "Fair", + "Fall back to the shared pool when the account is limited": "Fall back to the shared pool when the account is limited", "Fallback": "Fallback", "Fallback base URL": "Fallback base URL", "Fallback for remaining models": "Fallback for remaining models", @@ -7430,6 +7431,7 @@ "When no conditions are set, the operation always executes.": "When no conditions are set, the operation always executes.", "When performance monitoring is enabled and system resource usage exceeds the set threshold, new Relay requests will be rejected.": "When performance monitoring is enabled and system resource usage exceeds the set threshold, new Relay requests will be rejected.", "When running in containers or ephemeral environments, ensure the SQLite file is mapped to persistent storage to avoid data loss on restart.": "When running in containers or ephemeral environments, ensure the SQLite file is mapped to persistent storage to avoid data loss on restart.", + "When the bound subscription account hits its usage limit, serve the request from the shared pool and charge the wallet balance. Off: the request fails with the reset time.": "When the bound subscription account hits its usage limit, serve the request from the shared pool and charge the wallet balance. Off: the request fails with the reset time.", "When the primary domain changes, the previous domain is automatically kept in the compatible domains list.": "When the primary domain changes, the previous domain is automatically kept in the compatible domains list.", "Whitelist": "Whitelist", "Whitelist (Only allow listed domains)": "Whitelist (Only allow listed domains)", diff --git a/web/src/i18n/locales/fr.json b/web/src/i18n/locales/fr.json index 04f7c38b09c8..59a8ac648bff 100644 --- a/web/src/i18n/locales/fr.json +++ b/web/src/i18n/locales/fr.json @@ -2747,6 +2747,7 @@ "Failure keywords": "Mots-clés d'échec", "Failure reason": "Motif de l’échec", "Fair": "Correct", + "Fall back to the shared pool when the account is limited": "Basculer vers le pool partagé lorsque le compte est limité", "Fallback": "Repli", "Fallback base URL": "Base URL de fallback", "Fallback for remaining models": "Repli pour les modèles restants", @@ -7430,6 +7431,7 @@ "When no conditions are set, the operation always executes.": "Sans conditions, l'opération s'exécute toujours.", "When performance monitoring is enabled and system resource usage exceeds the set threshold, new Relay requests will be rejected.": "Lorsque la surveillance des performances est activée et que les ressources dépassent le seuil, les nouvelles requêtes Relay seront rejetées.", "When running in containers or ephemeral environments, ensure the SQLite file is mapped to persistent storage to avoid data loss on restart.": "Lors de l'exécution dans des conteneurs ou des environnements éphémères, assurez-vous que le fichier SQLite est mappé à un stockage persistant pour éviter la perte de données au redémarrage.", + "When the bound subscription account hits its usage limit, serve the request from the shared pool and charge the wallet balance. Off: the request fails with the reset time.": "Lorsque le compte d'abonnement lié atteint sa limite d'utilisation, la requête est servie par le pool partagé et facturée sur le solde du portefeuille. Désactivé : la requête échoue en indiquant l'heure de réinitialisation.", "When the primary domain changes, the previous domain is automatically kept in the compatible domains list.": "Lorsque le domaine principal change, l’ancien domaine est automatiquement conservé dans la liste des domaines compatibles.", "Whitelist": "Liste blanche", "Whitelist (Only allow listed domains)": "Liste blanche (Autoriser uniquement les domaines listés)", diff --git a/web/src/i18n/locales/ja.json b/web/src/i18n/locales/ja.json index 8991478d6bcc..71453b87a5a3 100644 --- a/web/src/i18n/locales/ja.json +++ b/web/src/i18n/locales/ja.json @@ -2747,6 +2747,7 @@ "Failure keywords": "失敗キーワード", "Failure reason": "失敗理由", "Fair": "公平", + "Fall back to the shared pool when the account is limited": "アカウント制限時に共有プールへフォールバック", "Fallback": "フォールバック", "Fallback base URL": "フォールバック Base URL", "Fallback for remaining models": "残りのモデル用フォールバック", @@ -7430,6 +7431,7 @@ "When no conditions are set, the operation always executes.": "条件が設定されていない場合、操作は常に実行されます。", "When performance monitoring is enabled and system resource usage exceeds the set threshold, new Relay requests will be rejected.": "パフォーマンス監視を有効にすると、システムリソース使用率が閾値を超えた場合、新しいRelayリクエストが拒否されます。", "When running in containers or ephemeral environments, ensure the SQLite file is mapped to persistent storage to avoid data loss on restart.": "コンテナまたは一時的な環境で実行する場合、再起動時のデータ損失を防ぐために、SQLiteファイルが永続ストレージにマッピングされていることを確認してください。", + "When the bound subscription account hits its usage limit, serve the request from the shared pool and charge the wallet balance. Off: the request fails with the reset time.": "紐付けたサブスクリプションアカウントが使用上限に達した場合、共有プールでリクエストを処理しウォレット残高から差し引きます。オフの場合はリセット時刻を示してリクエストが失敗します。", "When the primary domain changes, the previous domain is automatically kept in the compatible domains list.": "メインドメインを変更すると、以前のドメインは互換用ドメイン一覧に自動的に保持されます。", "Whitelist": "ホワイトリスト", "Whitelist (Only allow listed domains)": "ホワイトリスト (リストされたドメインのみを許可)", diff --git a/web/src/i18n/locales/ru.json b/web/src/i18n/locales/ru.json index aed015a4f65d..df67543df09b 100644 --- a/web/src/i18n/locales/ru.json +++ b/web/src/i18n/locales/ru.json @@ -2747,6 +2747,7 @@ "Failure keywords": "Ключевые слова сбоя", "Failure reason": "Причина сбоя", "Fair": "Удовлетворительно", + "Fall back to the shared pool when the account is limited": "Переключаться на общий пул при лимите аккаунта", "Fallback": "Резерв", "Fallback base URL": "Base URL fallback", "Fallback for remaining models": "Резерв для остальных моделей", @@ -7430,6 +7431,7 @@ "When no conditions are set, the operation always executes.": "Без условий операция выполняется всегда.", "When performance monitoring is enabled and system resource usage exceeds the set threshold, new Relay requests will be rejected.": "Когда мониторинг включён и использование ресурсов превышает порог, новые Relay-запросы будут отклонены.", "When running in containers or ephemeral environments, ensure the SQLite file is mapped to persistent storage to avoid data loss on restart.": "При работе в контейнерах или эфемерных средах убедитесь, что файл SQLite сопоставлен с постоянным хранилищем, чтобы избежать потери данных при перезапуске.", + "When the bound subscription account hits its usage limit, serve the request from the shared pool and charge the wallet balance. Off: the request fails with the reset time.": "Когда привязанный аккаунт подписки исчерпывает лимит использования, запрос обслуживается общим пулом с оплатой с баланса кошелька. Выключено: запрос завершается ошибкой с указанием времени сброса.", "When the primary domain changes, the previous domain is automatically kept in the compatible domains list.": "При изменении основного домена прежний домен автоматически сохраняется в списке совместимых доменов.", "Whitelist": "Белый список", "Whitelist (Only allow listed domains)": "Белый список (Разрешить только указанные домены)", diff --git a/web/src/i18n/locales/vi.json b/web/src/i18n/locales/vi.json index 477cd1977beb..d09b2ac4e703 100644 --- a/web/src/i18n/locales/vi.json +++ b/web/src/i18n/locales/vi.json @@ -2747,6 +2747,7 @@ "Failure keywords": "Từ khóa thất bại", "Failure reason": "Lý do thất bại", "Fair": "Công bằng", + "Fall back to the shared pool when the account is limited": "Chuyển sang nhóm dùng chung khi tài khoản bị giới hạn", "Fallback": "Dự phòng", "Fallback base URL": "Base URL fallback", "Fallback for remaining models": "Dự phòng cho mô hình còn lại", @@ -7430,6 +7431,7 @@ "When no conditions are set, the operation always executes.": "Khi không có điều kiện, thao tác luôn được thực thi.", "When performance monitoring is enabled and system resource usage exceeds the set threshold, new Relay requests will be rejected.": "Khi giám sát hiệu suất được bật và mức sử dụng tài nguyên vượt quá ngưỡng, các yêu cầu Relay mới sẽ bị từ chối.", "When running in containers or ephemeral environments, ensure the SQLite file is mapped to persistent storage to avoid data loss on restart.": "Khi chạy trong container hoặc môi trường tạm thời, hãy đảm bảo tệp SQLite được ánh xạ vào bộ nhớ lưu trữ bền vững để tránh mất dữ liệu khi khởi động lại.", + "When the bound subscription account hits its usage limit, serve the request from the shared pool and charge the wallet balance. Off: the request fails with the reset time.": "Khi tài khoản gói đăng ký được liên kết chạm giới hạn sử dụng, yêu cầu sẽ được nhóm dùng chung xử lý và trừ vào số dư ví. Tắt: yêu cầu thất bại kèm thời điểm đặt lại.", "When the primary domain changes, the previous domain is automatically kept in the compatible domains list.": "Khi đổi tên miền chính, tên miền cũ sẽ tự động được giữ trong danh sách tên miền tương thích.", "Whitelist": "Danh sách trắng", "Whitelist (Only allow listed domains)": "Danh sách trắng (Chỉ cho phép các tên miền được liệt kê)", diff --git a/web/src/i18n/locales/zh-TW.json b/web/src/i18n/locales/zh-TW.json index f3a921de2e2f..68bd85b1267a 100644 --- a/web/src/i18n/locales/zh-TW.json +++ b/web/src/i18n/locales/zh-TW.json @@ -2747,6 +2747,7 @@ "Failure keywords": "失敗關鍵詞", "Failure reason": "失敗原因", "Fair": "公平", + "Fall back to the shared pool when the account is limited": "帳號限流時回退共享池並扣餘額", "Fallback": "兜底", "Fallback base URL": "兜底 Base URL", "Fallback for remaining models": "留空匹配剩餘模型", @@ -7430,6 +7431,7 @@ "When no conditions are set, the operation always executes.": "沒有條件時,預設總是執行該操作。", "When performance monitoring is enabled and system resource usage exceeds the set threshold, new Relay requests will be rejected.": "啟用效能監控後,當系統資源使用率超過設定閾值時,將拒絕新的 Relay 請求。", "When running in containers or ephemeral environments, ensure the SQLite file is mapped to persistent storage to avoid data loss on restart.": "在容器或臨時環境中執行時,請確保 SQLite 檔案映射到持久儲存,以避免重新啟動時數據遺失。", + "When the bound subscription account hits its usage limit, serve the request from the shared pool and charge the wallet balance. Off: the request fails with the reset time.": "綁定的訂閱帳號用量額度用盡時,改由共享池處理請求並扣除錢包餘額。關閉時請求直接失敗並提示重置時間。", "When the primary domain changes, the previous domain is automatically kept in the compatible domains list.": "變更主要網域時,原網域會自動保留在相容網域清單中。", "Whitelist": "白名單", "Whitelist (Only allow listed domains)": "白名單(僅允許列出的域)", diff --git a/web/src/i18n/locales/zh.json b/web/src/i18n/locales/zh.json index a0f5564d60c2..56a558d908f2 100644 --- a/web/src/i18n/locales/zh.json +++ b/web/src/i18n/locales/zh.json @@ -2747,6 +2747,7 @@ "Failure keywords": "失败关键词", "Failure reason": "失败原因", "Fair": "公平", + "Fall back to the shared pool when the account is limited": "账号限流时回退共享池并扣余额", "Fallback": "兜底", "Fallback base URL": "兜底 Base URL", "Fallback for remaining models": "留空匹配剩余模型", @@ -7430,6 +7431,7 @@ "When no conditions are set, the operation always executes.": "没有条件时,默认总是执行该操作。", "When performance monitoring is enabled and system resource usage exceeds the set threshold, new Relay requests will be rejected.": "启用性能监控后,当系统资源使用率超过设定阈值时,将拒绝新的 Relay 请求。", "When running in containers or ephemeral environments, ensure the SQLite file is mapped to persistent storage to avoid data loss on restart.": "在容器或临时环境中运行时,请确保 SQLite 文件映射到持久存储,以避免重启时数据丢失。", + "When the bound subscription account hits its usage limit, serve the request from the shared pool and charge the wallet balance. Off: the request fails with the reset time.": "绑定的订阅账号用量额度用尽时,改由共享池处理请求并扣除钱包余额。关闭时请求直接失败并提示重置时间。", "When the primary domain changes, the previous domain is automatically kept in the compatible domains list.": "修改主域名时,原域名会自动保留在兼容域名列表中。", "Whitelist": "白名单", "Whitelist (Only allow listed domains)": "白名单(仅允许列出的域)",