From b31b435091709920c87c2b5d4d66bf9e8d25134b Mon Sep 17 00:00:00 2001 From: feeeei Date: Thu, 24 Sep 2026 16:20:16 +0800 Subject: [PATCH 01/17] =?UTF-8?q?fix(gateway):=20Claude=20Code=20=E9=99=90?= =?UTF-8?q?=E5=88=B6=E5=88=86=E7=BB=84=E7=9A=84=20OpenAI=20=E5=85=BC?= =?UTF-8?q?=E5=AE=B9=E5=85=A5=E5=8F=A3=E6=94=B9=E8=B5=B0=E9=99=8D=E7=BA=A7?= =?UTF-8?q?=E5=88=86=E7=BB=84,=E4=B8=8D=E5=86=8D=E7=9B=B4=E6=8E=A5=20403?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 分组开启 claude_code_only 并配置降级分组时,/v1/messages 会在选号入口的 checkClaudeCodeRestriction 中把非 Claude Code 请求解析到降级分组;但 GatewayHandler.ChatCompletions / Responses 在 handler 层只要分组开了 claude_code_only 就直接返回 403,不看降级分组,请求到不了调度层:只会发 Chat Completions / Responses 的第三方客户端拿这类分组的 Key 一律 403。 - handler 层提前拒绝只在未配置降级分组时生效,拒绝的状态码与文案不变 - 配置了降级分组时请求继续,由 SelectAccountWithLoadAwareness 解析到降级分组 选号,再经已有的 Chat Completions / Responses ⇄ Anthropic Messages 转换转发; service 层无改动 - 与 /v1/messages 的降级语义一致:选号与渠道限制预检按降级分组,计费与用量 记录仍按 API Key 所属分组 新增 handler 单测覆盖两个入口在有/无降级分组时的行为。 --- .../gateway_handler_chat_completions.go | 7 +- ...teway_handler_claude_code_fallback_test.go | 181 ++++++++++++++++++ .../handler/gateway_handler_responses.go | 12 +- 3 files changed, 191 insertions(+), 9 deletions(-) create mode 100644 backend/internal/handler/gateway_handler_claude_code_fallback_test.go diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 7a9850459..6a5fd0160 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -101,8 +101,11 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { // 解析渠道级模型映射 channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel) - // Claude Code only restriction - if apiKey.Group != nil && apiKey.Group.ClaudeCodeOnly { + // Claude Code only restriction: /v1/chat/completions is never a Claude Code + // endpoint. With a fallback group the request continues and account selection + // (checkClaudeCodeRestriction) schedules it in the fallback group; without one + // it is rejected here. + if apiKey.Group != nil && apiKey.Group.ClaudeCodeOnly && apiKey.Group.FallbackGroupID == nil { h.chatCompletionsErrorResponse(c, http.StatusForbidden, "permission_error", "This group is restricted to Claude Code clients (/v1/messages only)") return diff --git a/backend/internal/handler/gateway_handler_claude_code_fallback_test.go b/backend/internal/handler/gateway_handler_claude_code_fallback_test.go new file mode 100644 index 000000000..ae15cd887 --- /dev/null +++ b/backend/internal/handler/gateway_handler_claude_code_fallback_test.go @@ -0,0 +1,181 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "net/http" + "net/http/httptest" + "sync" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// groupScopedSchedulerCache 按桶的分组只返回该分组的成员账号,并记录被查询过的分组。 +type groupScopedSchedulerCache struct { + *fakeSchedulerCache + mu sync.Mutex + groupIDs []int64 +} + +func (c *groupScopedSchedulerCache) GetSnapshot(_ context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) { + c.mu.Lock() + c.groupIDs = append(c.groupIDs, bucket.GroupID) + c.mu.Unlock() + var members []*service.Account + for _, account := range c.accounts { + for _, ag := range account.AccountGroups { + if ag.GroupID == bucket.GroupID { + members = append(members, account) + break + } + } + } + return members, true, nil +} + +func (c *groupScopedSchedulerCache) queriedGroupIDs() []int64 { + c.mu.Lock() + defer c.mu.Unlock() + return append([]int64(nil), c.groupIDs...) +} + +type groupMapRepo struct { + *fakeGroupRepo + groups map[int64]*service.Group +} + +func (r *groupMapRepo) GetByID(_ context.Context, id int64) (*service.Group, error) { + if group, ok := r.groups[id]; ok { + return group, nil + } + return nil, service.ErrGroupNotFound +} + +func (r *groupMapRepo) GetByIDLite(ctx context.Context, id int64) (*service.Group, error) { + return r.GetByID(ctx, id) +} + +func TestGatewayOpenAICompatibleHandlersClaudeCodeOnlyFallback(t *testing.T) { + gin.SetMode(gin.TestMode) + + const ( + primaryGroupID = int64(9300) + fallbackGroupID = int64(9301) + primaryAccountID = int64(9310) + fallbackAccountID = int64(9311) + ) + + // 账号不带 api_key:转发在取令牌时失败,请求不会触达上游,断言只看选号结果。 + newAccount := func(id, groupID int64) *service.Account { + return &service.Account{ + ID: id, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, + AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}}, + } + } + + endpoints := []struct { + name string + path string + body string + call func(*GatewayHandler, *gin.Context) + }{ + { + name: "responses", path: "/v1/responses", + body: `{"model":"claude-sonnet-4-5","input":"hello","stream":false}`, + call: (*GatewayHandler).Responses, + }, + { + name: "chat completions", path: "/v1/chat/completions", + body: `{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hello"}],"stream":false}`, + call: (*GatewayHandler).ChatCompletions, + }, + } + + for _, ep := range endpoints { + for _, tc := range []struct { + name string + hasFallback bool + }{ + {name: "with fallback group", hasFallback: true}, + {name: "without fallback group", hasFallback: false}, + } { + t.Run(ep.name+"/"+tc.name, func(t *testing.T) { + primary := &service.Group{ + ID: primaryGroupID, Hydrated: true, Platform: service.PlatformAnthropic, + Status: service.StatusActive, ClaudeCodeOnly: true, + } + if tc.hasFallback { + fallbackID := fallbackGroupID + primary.FallbackGroupID = &fallbackID + } + fallback := &service.Group{ + ID: fallbackGroupID, Hydrated: true, Platform: service.PlatformAnthropic, + Status: service.StatusActive, + } + + schedulerCache := &groupScopedSchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{ + newAccount(primaryAccountID, primaryGroupID), + newAccount(fallbackAccountID, fallbackGroupID), + }}} + gatewayService := service.NewGatewayService( + nil, &groupMapRepo{fakeGroupRepo: &fakeGroupRepo{}, groups: map[int64]*service.Group{ + primaryGroupID: primary, + fallbackGroupID: fallback, + }}, nil, nil, nil, nil, nil, nil, nil, + service.NewSchedulerSnapshotService(schedulerCache, nil, nil, nil, nil), + nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + cfg := &config.Config{RunMode: config.RunModeSimple} + billingCacheService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCacheService.Stop) + h := &GatewayHandler{ + gatewayService: gatewayService, + billingCacheService: billingCacheService, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + maxAccountSwitches: 1, + cfg: cfg, + } + + primaryGroupIDRef := primaryGroupID + apiKey := &service.APIKey{ + ID: 9320, UserID: 9330, GroupID: &primaryGroupIDRef, Group: primary, Status: service.StatusActive, + User: &service.User{ID: 9330, Concurrency: 10, Balance: 100}, + } + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + ctx := context.WithValue(context.Background(), ctxkey.Group, primary) + req := httptest.NewRequest(http.MethodPost, ep.path, bytes.NewBufferString(ep.body)).WithContext(ctx) + req.Header.Set("Content-Type", "application/json") + c.Request = req + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.UserID, Concurrency: 10}) + + ep.call(h, c) + + selected, reachedSelection := c.Get(opsAccountIDKey) + if !tc.hasFallback { + require.Equal(t, http.StatusForbidden, recorder.Code) + require.Contains(t, recorder.Body.String(), "This group is restricted to Claude Code clients") + require.False(t, reachedSelection, "a Claude Code only group without fallback must be rejected before account selection") + require.Empty(t, schedulerCache.queriedGroupIDs()) + return + } + require.NotContains(t, recorder.Body.String(), "restricted to Claude Code clients") + require.True(t, reachedSelection, "a Claude Code only group with fallback must reach account selection") + require.Equal(t, fallbackAccountID, selected) + queried := schedulerCache.queriedGroupIDs() + require.Contains(t, queried, fallbackGroupID) + require.NotContains(t, queried, primaryGroupID) + }) + } + } +} diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index a17087731..1cfb122cc 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -105,13 +105,11 @@ func (h *GatewayHandler) Responses(c *gin.Context) { // 解析渠道级模型映射 channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(requestCtx, apiKey.GroupID, reqModel) - // Claude Code only restriction: - // /v1/responses is never a Claude Code endpoint. - // When claude_code_only is enabled, this endpoint is rejected. - // The existing service-layer checkClaudeCodeRestriction handles degradation - // to fallback groups when the Forward path calls SelectAccountForModelWithExclusions. - // Here we just reject at handler level since /v1/responses clients can't be Claude Code. - if apiKey.Group != nil && apiKey.Group.ClaudeCodeOnly { + // Claude Code only restriction: /v1/responses is never a Claude Code + // endpoint. With a fallback group the request continues and account selection + // (checkClaudeCodeRestriction) schedules it in the fallback group; without one + // it is rejected here. + if apiKey.Group != nil && apiKey.Group.ClaudeCodeOnly && apiKey.Group.FallbackGroupID == nil { h.responsesErrorResponse(c, http.StatusForbidden, "permission_error", "This group is restricted to Claude Code clients (/v1/messages only)") return From 43f88c99aa3efea40eb76fb55b48ae88a9f5dc13 Mon Sep 17 00:00:00 2001 From: William Drake Date: Mon, 28 Sep 2026 14:20:49 -0400 Subject: [PATCH 02/17] fix(billing): reserve in-flight balance to prevent concurrent overdraft Balance-mode admission only checked cached balance > threshold, so N concurrent expensive requests could all pass and overdraw the user. Add a Redis in-flight reservation: at admission estimate a conservative per-request cost (input estimate + output price x max_tokens, times rate multiplier) and atomically require cached_balance - inflight >= estimate (first in-flight request always admitted). Reservations are released via defer on every path and expire by TTL. Fails open on estimation / Redis errors. Configurable via billing.inflight_reservation (enabled by default). Co-Authored-By: Claude Opus 5.5 (1M context) --- backend/internal/config/config.go | 31 +++ backend/internal/handler/gateway_handler.go | 13 ++ .../gateway_handler_chat_completions.go | 13 ++ .../handler/gateway_handler_responses.go | 13 ++ .../handler/gateway_inflight_reservation.go | 49 ++++ .../gateway_inflight_reservation_test.go | 46 ++++ .../internal/handler/gemini_v1beta_handler.go | 13 ++ .../handler/openai_chat_completions.go | 13 ++ .../handler/openai_gateway_handler.go | 13 ++ .../repository/billing_inflight_cache.go | 102 +++++++++ .../repository/billing_inflight_cache_test.go | 211 ++++++++++++++++++ .../service/billing_inflight_reservation.go | 198 ++++++++++++++++ .../billing_inflight_reservation_test.go | 60 +++++ deploy/config.example.yaml | 22 ++ 14 files changed, 797 insertions(+) create mode 100644 backend/internal/handler/gateway_inflight_reservation.go create mode 100644 backend/internal/handler/gateway_inflight_reservation_test.go create mode 100644 backend/internal/repository/billing_inflight_cache.go create mode 100644 backend/internal/repository/billing_inflight_cache_test.go create mode 100644 backend/internal/service/billing_inflight_reservation.go create mode 100644 backend/internal/service/billing_inflight_reservation_test.go diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 11b86e6b2..f7cfcead2 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -921,6 +921,26 @@ type BillingConfig struct { // UserPlatformQuotaSentinelTTLSeconds sentinel(无 limit 占位)entry 的 TTL, // 显著短于 quota cache 默认 86400s 以控 Redis 内存;默认 3600=1h。 UserPlatformQuotaSentinelTTLSeconds int `mapstructure:"user_platform_quota_sentinel_ttl_seconds"` + // InflightReservation 余额模式在途请求预留(Redis),防止并发请求在预检时看到同一份余额而集体透支。 + InflightReservation InflightReservationConfig `mapstructure:"inflight_reservation"` +} + +// InflightReservationConfig 余额模式在途预留配置。 +// 准入时按 输入估算 + 输出单价 × max_tokens 估算单请求费用,在 Redis 中原子地 +// 校验 缓存余额 - 在途预留合计 >= 估算 后登记预留,请求结束(任意路径)释放。 +// 估算失败或 Redis 不可用时 fail-open,退回旧的仅余额 > 阈值检查。 +type InflightReservationConfig struct { + Enabled bool `mapstructure:"enabled"` + // TTLSeconds 单条预留的最长存活时间;进程崩溃等泄漏的预留到期自动失效。 + TTLSeconds int `mapstructure:"ttl_seconds"` + // DefaultMaxTokens 请求未携带 max_tokens 时用于估算的输出 token 数。 + DefaultMaxTokens int `mapstructure:"default_max_tokens"` + // MaxOutputTokens 估算输出 token 的上限(max_tokens 超出时截断)。 + MaxOutputTokens int `mapstructure:"max_output_tokens"` + // MaxInputTokens 输入 token 估算(请求体字节数 / 4)的上限。 + MaxInputTokens int `mapstructure:"max_input_tokens"` + // MaxReservationUSD 单请求预留金额上限;0 表示不设上限。 + MaxReservationUSD float64 `mapstructure:"max_reservation_usd"` } type CircuitBreakerConfig struct { @@ -2093,6 +2113,12 @@ func setDefaults() { viper.SetDefault("billing.minimum_balance_reserve", 0.000001) viper.SetDefault("billing.user_platform_quota_cache_ttl_seconds", 86400) viper.SetDefault("billing.user_platform_quota_sentinel_ttl_seconds", 3600) + viper.SetDefault("billing.inflight_reservation.enabled", true) + viper.SetDefault("billing.inflight_reservation.ttl_seconds", 900) + viper.SetDefault("billing.inflight_reservation.default_max_tokens", 8192) + viper.SetDefault("billing.inflight_reservation.max_output_tokens", 128000) + viper.SetDefault("billing.inflight_reservation.max_input_tokens", 200000) + viper.SetDefault("billing.inflight_reservation.max_reservation_usd", 0) // Turnstile viper.SetDefault("turnstile.required", false) @@ -3062,6 +3088,11 @@ func (c *Config) Validate() error { if c.Billing.MinimumBalanceReserve < 0 { return fmt.Errorf("billing.minimum_balance_reserve must be non-negative") } + if c.Billing.InflightReservation.TTLSeconds < 0 || c.Billing.InflightReservation.DefaultMaxTokens < 0 || + c.Billing.InflightReservation.MaxOutputTokens < 0 || c.Billing.InflightReservation.MaxInputTokens < 0 || + c.Billing.InflightReservation.MaxReservationUSD < 0 { + return fmt.Errorf("billing.inflight_reservation values must be non-negative") + } if c.Database.MaxOpenConns <= 0 { return fmt.Errorf("database.max_open_conns must be positive") } diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 2f52c0bfe..acf4e21ac 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -263,6 +263,19 @@ func (h *GatewayHandler) Messages(c *gin.Context) { return } + // 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。 + inflightRelease, err := reserveInflightBalance(c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, reqModel, body) + if err != nil { + reqLog.Info("gateway.inflight_reservation_rejected", zap.Error(err)) + status, code, message, retryAfter := billingErrorDetails(err) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.handleStreamingAwareError(c, status, code, message, streamStarted) + return + } + defer inflightRelease() + // 设置请求所属分组 ID(用于渠道级功能判断,如 WebSearch 模拟) parsedReq.GroupID = apiKey.GroupID diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 9eec2bb3d..b844d27d1 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -144,6 +144,19 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { return } + // 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。 + inflightRelease, err := reserveInflightBalance(c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, reqModel, body) + if err != nil { + reqLog.Info("gateway.cc.inflight_reservation_rejected", zap.Error(err)) + status, code, message, retryAfter := billingErrorDetails(err) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.chatCompletionsErrorResponse(c, status, code, message) + return + } + defer inflightRelease() + // Parse request for session hash bodyRef := service.NewRequestBodyRef(body) parsedReq, _ := service.ParseGatewayRequest(bodyRef, "chat_completions") diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 8cf07f1e9..a10ad8d4e 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -153,6 +153,19 @@ func (h *GatewayHandler) Responses(c *gin.Context) { return } + // 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。 + inflightRelease, err := reserveInflightBalance(requestCtx, h.billingCacheService, h.gatewayService, apiKey, subscription, reqModel, body) + if err != nil { + reqLog.Info("gateway.responses.inflight_reservation_rejected", zap.Error(err)) + status, code, message, retryAfter := billingErrorDetails(err) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.responsesErrorResponse(c, status, code, message) + return + } + defer inflightRelease() + // Parse request for session hash bodyRef := service.NewRequestBodyRef(body) parsedReq, _ := service.ParseGatewayRequest(bodyRef, "responses") diff --git a/backend/internal/handler/gateway_inflight_reservation.go b/backend/internal/handler/gateway_inflight_reservation.go new file mode 100644 index 000000000..08ebaafb9 --- /dev/null +++ b/backend/internal/handler/gateway_inflight_reservation.go @@ -0,0 +1,49 @@ +package handler + +import ( + "context" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/tidwall/gjson" +) + +// inflightReservationEstimator 估算单请求在途预留金额(USD)。 +type inflightReservationEstimator interface { + EstimateInflightReservation(ctx context.Context, apiKey *service.APIKey, model string, bodyBytes, maxTokens int) float64 +} + +// requestMaxOutputTokens 从请求体中提取输出 token 上限(兼容 Anthropic / OpenAI Chat / Responses / Gemini)。 +func requestMaxOutputTokens(body []byte) int { + for _, path := range []string{"max_tokens", "max_completion_tokens", "max_output_tokens", "generationConfig.maxOutputTokens", "generation_config.max_output_tokens"} { + if v := gjson.GetBytes(body, path); v.Exists() && v.Type == gjson.Number && v.Int() > 0 { + return int(v.Int()) + } + } + return 0 +} + +// reserveInflightBalance 在 CheckBillingEligibility 之后为余额模式请求登记在途预留。 +// 返回的 release 必须 defer 调用(覆盖成功/错误/客户端断开/failover 等所有路径); +// 开关关闭、订阅模式、估算失败或 Redis 故障时返回 no-op(fail-open)。 +func reserveInflightBalance( + ctx context.Context, + billing *service.BillingCacheService, + estimator inflightReservationEstimator, + apiKey *service.APIKey, + subscription *service.UserSubscription, + model string, + body []byte, +) (func(), error) { + noop := func() {} + if billing == nil || estimator == nil || apiKey == nil || apiKey.User == nil || !billing.InflightReservationEnabled() { + return noop, nil + } + if apiKey.Group != nil && apiKey.Group.IsSubscriptionType() && subscription != nil { + return noop, nil + } + estimate := estimator.EstimateInflightReservation(ctx, apiKey, model, len(body), requestMaxOutputTokens(body)) + if estimate <= 0 { + return noop, nil + } + return billing.ReserveInflightBalance(ctx, apiKey.User, apiKey.Group, subscription, estimate) +} diff --git a/backend/internal/handler/gateway_inflight_reservation_test.go b/backend/internal/handler/gateway_inflight_reservation_test.go new file mode 100644 index 000000000..a76f5eb6c --- /dev/null +++ b/backend/internal/handler/gateway_inflight_reservation_test.go @@ -0,0 +1,46 @@ +package handler + +import ( + "context" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestRequestMaxOutputTokens(t *testing.T) { + require.Equal(t, 1024, requestMaxOutputTokens([]byte(`{"max_tokens":1024}`))) + require.Equal(t, 2048, requestMaxOutputTokens([]byte(`{"max_completion_tokens":2048}`))) + require.Equal(t, 4096, requestMaxOutputTokens([]byte(`{"max_output_tokens":4096}`))) + require.Equal(t, 512, requestMaxOutputTokens([]byte(`{"generationConfig":{"maxOutputTokens":512}}`))) + require.Equal(t, 0, requestMaxOutputTokens([]byte(`{"max_tokens":"x"}`))) + require.Equal(t, 0, requestMaxOutputTokens([]byte(`{}`))) +} + +type countingEstimator struct{ calls int } + +func (e *countingEstimator) EstimateInflightReservation(context.Context, *service.APIKey, string, int, int) float64 { + e.calls++ + return 1 +} + +func TestReserveInflightBalance_SkipsWhenDisabledOrSubscription(t *testing.T) { + cfg := &config.Config{} + billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + est := &countingEstimator{} + apiKey := &service.APIKey{User: &service.User{ID: 1}} + + release, err := reserveInflightBalance(context.Background(), billing, est, apiKey, nil, "m", []byte(`{}`)) + require.NoError(t, err) + release() + require.Equal(t, 0, est.calls, "disabled switch must not even estimate") + + cfg.Billing.InflightReservation.Enabled = true + apiKey.Group = &service.Group{SubscriptionType: service.SubscriptionTypeSubscription} + release, err = reserveInflightBalance(context.Background(), billing, est, apiKey, &service.UserSubscription{}, "m", []byte(`{}`)) + require.NoError(t, err) + release() + require.Equal(t, 0, est.calls, "subscription mode must be unaffected") +} diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index 140e29479..0fc9e5eba 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -390,6 +390,19 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { return } + // 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。 + inflightRelease, err := reserveInflightBalance(c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, modelName, body) + if err != nil { + reqLog.Info("gemini.inflight_reservation_rejected", zap.Error(err)) + status, _, message, retryAfter := billingErrorDetails(err) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + googleError(c, status, message) + return + } + defer inflightRelease() + // 3) select account (sticky session based on request body) // 优先使用 Gemini CLI 的会话标识(privileged-user-id + tmp 目录哈希) sessionHash := extractGeminiCLISessionHash(c, body) diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index 147f4460a..afecc1b06 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -146,6 +146,19 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { return } + // 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。 + inflightRelease, err := reserveInflightBalance(c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, reqModel, body) + if err != nil { + reqLog.Info("openai_chat_completions.inflight_reservation_rejected", zap.Error(err)) + status, code, message, retryAfter := billingErrorDetails(err) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.handleStreamingAwareError(c, status, code, message, streamStarted) + return + } + defer inflightRelease() + sessionHash := h.gatewayService.GenerateSessionHash(c, body) promptCacheKey := h.gatewayService.ExtractSessionID(c, body) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index bf4563f2f..5278219ea 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -606,6 +606,19 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { return } + // 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。 + inflightRelease, err := reserveInflightBalance(c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, reqModel, body) + if err != nil { + reqLog.Info("openai.inflight_reservation_rejected", zap.Error(err)) + status, code, message, retryAfter := billingErrorDetails(err) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.handleStreamingAwareError(c, status, code, message, streamStarted) + return + } + defer inflightRelease() + // Generate session hash (header first; fallback to prompt_cache_key) sessionHash := h.gatewayService.GenerateSessionHash(c, sessionHashBody) if h.rejectIfCyberSessionBlocked(c, apiKey, sessionHashBody, reqModel, cyberBlockFormatResponses) { diff --git a/backend/internal/repository/billing_inflight_cache.go b/backend/internal/repository/billing_inflight_cache.go new file mode 100644 index 000000000..47692fcf7 --- /dev/null +++ b/backend/internal/repository/billing_inflight_cache.go @@ -0,0 +1,102 @@ +package repository + +import ( + "context" + "fmt" + "strconv" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/redis/go-redis/v9" +) + +// 余额在途预留: +// - billing:inflight:{uid} ZSET member=requestID score=过期时间(ms) +// - billing:inflight_amt:{uid} HASH field=requestID value=预留金额(USD) +// +// 两个 key 使用同一 hash tag,保证 Redis Cluster 下 Lua 可同时访问。 +const ( + billingInflightKeyPrefix = "billing:inflight:" + billingInflightAmtKeyPrefix = "billing:inflight_amt:" +) + +func billingInflightKeys(userID int64) (string, string) { + return fmt.Sprintf("%s{%d}", billingInflightKeyPrefix, userID), + fmt.Sprintf("%s{%d}", billingInflightAmtKeyPrefix, userID) +} + +var ( + // KEYS: [1]=zset [2]=hash + // ARGV: [1]=now_ms [2]=expire_at_ms [3]=member [4]=amount [5]=balance [6]=key_ttl_ms + // 返回 {allowed, inflight_sum(string), inflight_count} + // 规则:先清理已过期成员;若无在途预留则直接放行(与旧行为一致,外层已校验余额 > 阈值); + // 否则要求 balance - sum(在途) >= amount。放行时登记预留。 + reserveInflightBalanceScript = redis.NewScript(` + local now = tonumber(ARGV[1]) + local expired = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', now) + if #expired > 0 then + redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now) + redis.call('HDEL', KEYS[2], unpack(expired)) + end + local vals = redis.call('HVALS', KEYS[2]) + local sum = 0 + for i = 1, #vals do + sum = sum + (tonumber(vals[i]) or 0) + end + local count = redis.call('ZCARD', KEYS[1]) + local amount = tonumber(ARGV[4]) + local balance = tonumber(ARGV[5]) + if count > 0 and (balance - sum) < amount then + return {0, tostring(sum), count} + end + redis.call('ZADD', KEYS[1], tonumber(ARGV[2]), ARGV[3]) + redis.call('HSET', KEYS[2], ARGV[3], ARGV[4]) + redis.call('PEXPIRE', KEYS[1], ARGV[6]) + redis.call('PEXPIRE', KEYS[2], ARGV[6]) + return {1, tostring(sum), count} + `) + + releaseInflightBalanceScript = redis.NewScript(` + redis.call('ZREM', KEYS[1], ARGV[1]) + redis.call('HDEL', KEYS[2], ARGV[1]) + return 1 + `) +) + +// ReserveInflightBalance 实现 service.InflightBalanceReservationCache。 +func (c *billingCache) ReserveInflightBalance(ctx context.Context, userID int64, requestID string, amount, balance float64, ttl time.Duration) (bool, float64, error) { + zkey, hkey := billingInflightKeys(userID) + now := time.Now().UnixMilli() + ttlMs := ttl.Milliseconds() + if ttlMs <= 0 { + ttlMs = 1 + } + res, err := reserveInflightBalanceScript.Run(ctx, c.rdb, []string{zkey, hkey}, + now, + now+ttlMs, + requestID, + strconv.FormatFloat(amount, 'f', -1, 64), + strconv.FormatFloat(balance, 'f', -1, 64), + ttlMs, + ).Slice() + if err != nil { + return false, 0, err + } + if len(res) < 2 { + return false, 0, fmt.Errorf("unexpected inflight reservation reply: %v", res) + } + allowed, _ := res[0].(int64) + var sum float64 + if s, ok := res[1].(string); ok { + sum, _ = strconv.ParseFloat(s, 64) + } + return allowed == 1, sum, nil +} + +// ReleaseInflightBalance 实现 service.InflightBalanceReservationCache。 +func (c *billingCache) ReleaseInflightBalance(ctx context.Context, userID int64, requestID string) error { + zkey, hkey := billingInflightKeys(userID) + return releaseInflightBalanceScript.Run(ctx, c.rdb, []string{zkey, hkey}, requestID).Err() +} + +var _ service.InflightBalanceReservationCache = (*billingCache)(nil) diff --git a/backend/internal/repository/billing_inflight_cache_test.go b/backend/internal/repository/billing_inflight_cache_test.go new file mode 100644 index 000000000..6540c83bd --- /dev/null +++ b/backend/internal/repository/billing_inflight_cache_test.go @@ -0,0 +1,211 @@ +package repository + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/alicebob/miniredis/v2" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" +) + +func newInflightTestEnv(t *testing.T, enabled bool, ttlSeconds int) (*miniredis.Miniredis, *billingCache, *service.BillingCacheService) { + t.Helper() + mr := miniredis.RunT(t) + rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) + t.Cleanup(func() { _ = rdb.Close() }) + cache := &billingCache{rdb: rdb} + cfg := &config.Config{} + cfg.Billing.InflightReservation = config.InflightReservationConfig{ + Enabled: enabled, + TTLSeconds: ttlSeconds, + DefaultMaxTokens: 8192, + } + svc := service.NewBillingCacheService(cache, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(svc.Stop) + return mr, cache, svc +} + +func inflightCount(t *testing.T, cache *billingCache, userID int64) int64 { + t.Helper() + zkey, _ := billingInflightKeys(userID) + n, err := cache.rdb.ZCard(context.Background(), zkey).Result() + require.NoError(t, err) + return n +} + +func TestInflightReservation_ConcurrentAdmitsOnlyWhatBalanceCovers(t *testing.T) { + _, cache, svc := newInflightTestEnv(t, true, 60) + ctx := context.Background() + user := &service.User{ID: 42} + require.NoError(t, cache.SetUserBalance(ctx, user.ID, 1.0)) + + const n = 20 + var admitted, rejected atomic.Int32 + releases := make(chan func(), n) + var wg sync.WaitGroup + start := make(chan struct{}) + for i := 0; i < n; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + release, err := svc.ReserveInflightBalance(ctx, user, nil, nil, 0.3) + if err != nil { + if !errors.Is(err, service.ErrInsufficientBalance) { + t.Errorf("unexpected error: %v", err) + } + rejected.Add(1) + return + } + admitted.Add(1) + releases <- release + }() + } + close(start) + wg.Wait() + close(releases) + + // balance 1.0, estimate 0.3: first always admitted, then while 1.0 - inflight >= 0.3 → 3 total. + require.Equal(t, int32(3), admitted.Load()) + require.Equal(t, int32(n-3), rejected.Load()) + require.Equal(t, int64(3), inflightCount(t, cache, user.ID)) + + for release := range releases { + release() + release() // idempotent + } + require.Equal(t, int64(0), inflightCount(t, cache, user.ID)) + + // After release, capacity is available again. + release, err := svc.ReserveInflightBalance(ctx, user, nil, nil, 0.3) + require.NoError(t, err) + release() +} + +func TestInflightReservation_FirstRequestAlwaysAdmitted(t *testing.T) { + _, cache, svc := newInflightTestEnv(t, true, 60) + ctx := context.Background() + user := &service.User{ID: 7} + require.NoError(t, cache.SetUserBalance(ctx, user.ID, 0.01)) + + release, err := svc.ReserveInflightBalance(ctx, user, nil, nil, 5) + require.NoError(t, err, "a lone request keeps legacy behavior even if estimate exceeds balance") + _, err = svc.ReserveInflightBalance(ctx, user, nil, nil, 0.001) + require.ErrorIs(t, err, service.ErrInsufficientBalance) + release() + release2, err := svc.ReserveInflightBalance(ctx, user, nil, nil, 0.001) + require.NoError(t, err) + release2() +} + +func TestInflightReservation_TTLExpiryFreesLeakedReservation(t *testing.T) { + _, cache, svc := newInflightTestEnv(t, true, 1) + ctx := context.Background() + user := &service.User{ID: 9} + require.NoError(t, cache.SetUserBalance(ctx, user.ID, 1.0)) + + _, err := svc.ReserveInflightBalance(ctx, user, nil, nil, 0.8) // leaked: never released + require.NoError(t, err) + _, err = svc.ReserveInflightBalance(ctx, user, nil, nil, 0.8) + require.ErrorIs(t, err, service.ErrInsufficientBalance) + + time.Sleep(1100 * time.Millisecond) + release, err := svc.ReserveInflightBalance(ctx, user, nil, nil, 0.8) + require.NoError(t, err) + require.Equal(t, int64(1), inflightCount(t, cache, user.ID)) + release() +} + +func TestInflightReservation_DisabledKeepsLegacyBehavior(t *testing.T) { + _, cache, svc := newInflightTestEnv(t, false, 60) + ctx := context.Background() + user := &service.User{ID: 11} + require.NoError(t, cache.SetUserBalance(ctx, user.ID, 0.01)) + require.False(t, svc.InflightReservationEnabled()) + for i := 0; i < 5; i++ { + _, err := svc.ReserveInflightBalance(ctx, user, nil, nil, 10) + require.NoError(t, err) + } + require.Equal(t, int64(0), inflightCount(t, cache, user.ID)) +} + +func TestInflightReservation_SubscriptionUnaffected(t *testing.T) { + _, cache, svc := newInflightTestEnv(t, true, 60) + ctx := context.Background() + user := &service.User{ID: 12} + require.NoError(t, cache.SetUserBalance(ctx, user.ID, 0)) + group := &service.Group{ID: 1, SubscriptionType: service.SubscriptionTypeSubscription} + sub := &service.UserSubscription{ID: 1} + for i := 0; i < 5; i++ { + _, err := svc.ReserveInflightBalance(ctx, user, group, sub, 10) + require.NoError(t, err) + } + require.Equal(t, int64(0), inflightCount(t, cache, user.ID)) +} + +func TestInflightReservation_ZeroEstimateSkips(t *testing.T) { + _, cache, svc := newInflightTestEnv(t, true, 60) + ctx := context.Background() + user := &service.User{ID: 13} + require.NoError(t, cache.SetUserBalance(ctx, user.ID, 1)) + _, err := svc.ReserveInflightBalance(ctx, user, nil, nil, 0) + require.NoError(t, err) + require.Equal(t, int64(0), inflightCount(t, cache, user.ID)) +} + +// downReserveCache 余额读取正常,但预留走一个已关闭的 Redis。 +type downReserveCache struct { + service.BillingCache + down *billingCache +} + +func (d *downReserveCache) ReserveInflightBalance(ctx context.Context, userID int64, requestID string, amount, balance float64, ttl time.Duration) (bool, float64, error) { + return d.down.ReserveInflightBalance(ctx, userID, requestID, amount, balance, ttl) +} + +func (d *downReserveCache) ReleaseInflightBalance(ctx context.Context, userID int64, requestID string) error { + return d.down.ReleaseInflightBalance(ctx, userID, requestID) +} + +func TestInflightReservation_RedisDownFailsOpen(t *testing.T) { + mr := miniredis.RunT(t) + rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) + t.Cleanup(func() { _ = rdb.Close() }) + up := &billingCache{rdb: rdb} + require.NoError(t, up.SetUserBalance(context.Background(), 5, 0.01)) + + downMR := miniredis.RunT(t) + downRDB := redis.NewClient(&redis.Options{Addr: downMR.Addr(), MaxRetries: -1, DialTimeout: 100 * time.Millisecond}) + t.Cleanup(func() { _ = downRDB.Close() }) + downMR.Close() + + cfg := &config.Config{} + cfg.Billing.InflightReservation = config.InflightReservationConfig{Enabled: true, TTLSeconds: 60} + svc := service.NewBillingCacheService(&downReserveCache{BillingCache: up, down: &billingCache{rdb: downRDB}}, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(svc.Stop) + + user := &service.User{ID: 5} + for i := 0; i < 3; i++ { + release, err := svc.ReserveInflightBalance(context.Background(), user, nil, nil, 100) + require.NoError(t, err) + release() + } +} + +func TestInflightReservation_ScriptErrorSurfaces(t *testing.T) { + mr := miniredis.RunT(t) + rdb := redis.NewClient(&redis.Options{Addr: mr.Addr(), MaxRetries: -1}) + cache := &billingCache{rdb: rdb} + mr.Close() + _, _, err := cache.ReserveInflightBalance(context.Background(), 1, "r", 1, 1, time.Second) + require.Error(t, err) + require.False(t, errors.Is(err, context.Canceled)) + _ = rdb.Close() +} diff --git a/backend/internal/service/billing_inflight_reservation.go b/backend/internal/service/billing_inflight_reservation.go new file mode 100644 index 000000000..86b7e69a8 --- /dev/null +++ b/backend/internal/service/billing_inflight_reservation.go @@ -0,0 +1,198 @@ +package service + +import ( + "context" + "math" + "sync" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/google/uuid" +) + +// InflightBalanceReservationCache 余额在途预留的缓存能力(可选)。 +// BillingCache 的 Redis 实现同时实现此接口;未实现时在途预留自动关闭(fail-open)。 +type InflightBalanceReservationCache interface { + // ReserveInflightBalance 原子地:清理过期预留;若用户已有在途预留且 + // balance - sum(在途) < amount 则拒绝;否则登记 requestID 的预留(ttl 后自动失效)。 + // 返回是否放行以及登记前的在途合计。 + ReserveInflightBalance(ctx context.Context, userID int64, requestID string, amount, balance float64, ttl time.Duration) (bool, float64, error) + // ReleaseInflightBalance 释放 requestID 的预留(幂等)。 + ReleaseInflightBalance(ctx context.Context, userID int64, requestID string) error +} + +const ( + defaultInflightReservationTTL = 15 * time.Minute + defaultInflightDefaultMaxTokens = 8192 + inflightReservationReleaseTimeout = 2 * time.Second + inflightReservationReserveTimeout = 2 * time.Second + inflightInputBytesPerTokenEstimate = 4 +) + +func noopRelease() {} + +func (s *BillingCacheService) inflightReservationConfig() (config.InflightReservationConfig, bool) { + if s == nil || s.cfg == nil { + return config.InflightReservationConfig{}, false + } + cfg := s.cfg.Billing.InflightReservation + if !cfg.Enabled || s.cfg.RunMode == config.RunModeSimple { + return cfg, false + } + return cfg, true +} + +// InflightReservationEnabled 是否启用余额在途预留。 +func (s *BillingCacheService) InflightReservationEnabled() bool { + _, ok := s.inflightReservationConfig() + return ok +} + +// ReserveInflightBalance 在余额模式下为本次请求登记在途预留。 +// +// 必须在 CheckBillingEligibility 通过后调用。返回的 release 必须在请求结束时调用 +// (所有路径,建议 defer),多次调用安全。 +// +// 以下情况直接放行且不登记预留(fail-open,保持旧行为): +// 开关关闭 / 简易模式 / 订阅模式 / estimate <= 0 / 缓存不支持 / 余额读取失败 / Redis 执行失败。 +// 仅当 Redis 明确判定 缓存余额 - 在途合计 < estimate(且已有在途请求)时返回 ErrInsufficientBalance。 +func (s *BillingCacheService) ReserveInflightBalance(ctx context.Context, user *User, group *Group, subscription *UserSubscription, estimate float64) (func(), error) { + cfg, ok := s.inflightReservationConfig() + if !ok || user == nil { + return noopRelease, nil + } + if group != nil && group.IsSubscriptionType() && subscription != nil { + return noopRelease, nil + } + if cfg.MaxReservationUSD > 0 && estimate > cfg.MaxReservationUSD { + estimate = cfg.MaxReservationUSD + } + if estimate <= 0 || math.IsNaN(estimate) || math.IsInf(estimate, 0) { + return noopRelease, nil + } + rc, ok := s.cache.(InflightBalanceReservationCache) + if !ok || rc == nil { + return noopRelease, nil + } + + balance, err := s.GetUserBalance(ctx, user.ID) + if err != nil { + logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation balance read failed for user %d (fail-open): %v", user.ID, err) + return noopRelease, nil + } + + ttl := defaultInflightReservationTTL + if cfg.TTLSeconds > 0 { + ttl = time.Duration(cfg.TTLSeconds) * time.Second + } + requestID := uuid.NewString() + reserveCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), inflightReservationReserveTimeout) + allowed, inflight, err := rc.ReserveInflightBalance(reserveCtx, user.ID, requestID, estimate, balance, ttl) + cancel() + if err != nil { + logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation failed for user %d (fail-open): %v", user.ID, err) + return noopRelease, nil + } + if !allowed { + logger.LegacyPrintf("service.billing_cache", "inflight reservation rejected: user=%d balance=%.6f inflight=%.6f estimate=%.6f", user.ID, balance, inflight, estimate) + return noopRelease, ErrInsufficientBalance + } + + var once sync.Once + userID := user.ID + return func() { + once.Do(func() { + relCtx, relCancel := context.WithTimeout(context.Background(), inflightReservationReleaseTimeout) + defer relCancel() + if err := rc.ReleaseInflightBalance(relCtx, userID, requestID); err != nil { + logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation release failed for user %d (expires by ttl): %v", userID, err) + } + }) + }, nil +} + +// EstimateInflightReservationCost 估算单请求的保守费用(USD,已乘倍率)。 +// +// input_tokens = min(bodyBytes / 4, max_input_tokens) +// output_tokens = min(max_tokens 或 default_max_tokens, max_output_tokens) +// cost = (input_tokens × 输入单价 + output_tokens × 输出单价) × rateMultiplier +// +// 无法取得定价时返回 (0, false),调用方应 fail-open。 +func EstimateInflightReservationCost(billing *BillingService, cfg config.InflightReservationConfig, model string, bodyBytes, maxTokens int, rateMultiplier float64) (float64, bool) { + if billing == nil || model == "" || rateMultiplier <= 0 { + return 0, false + } + pricing, err := billing.GetModelPricing(model) + if err != nil || pricing == nil { + return 0, false + } + inputTokens := 0 + if bodyBytes > 0 { + inputTokens = bodyBytes / inflightInputBytesPerTokenEstimate + } + if cfg.MaxInputTokens > 0 && inputTokens > cfg.MaxInputTokens { + inputTokens = cfg.MaxInputTokens + } + outputTokens := maxTokens + if outputTokens <= 0 { + outputTokens = cfg.DefaultMaxTokens + if outputTokens <= 0 { + outputTokens = defaultInflightDefaultMaxTokens + } + } + if cfg.MaxOutputTokens > 0 && outputTokens > cfg.MaxOutputTokens { + outputTokens = cfg.MaxOutputTokens + } + cost := (float64(inputTokens)*pricing.InputPricePerToken + float64(outputTokens)*pricing.OutputPricePerToken) * rateMultiplier + if cost <= 0 || math.IsNaN(cost) || math.IsInf(cost, 0) { + return 0, false + } + return cost, true +} + +func inflightReservationCfg(cfg *config.Config) config.InflightReservationConfig { + if cfg == nil { + return config.InflightReservationConfig{} + } + return cfg.Billing.InflightReservation +} + +func groupRateMultiplierOrOne(group *Group) float64 { + if group == nil { + return 1 + } + return group.RateMultiplier +} + +// EstimateInflightReservation 使用网关计费倍率估算在途预留金额;0 表示不预留。 +func (s *GatewayService) EstimateInflightReservation(ctx context.Context, apiKey *APIKey, model string, bodyBytes, maxTokens int) float64 { + if s == nil || apiKey == nil || apiKey.User == nil { + return 0 + } + rate := groupRateMultiplierOrOne(apiKey.Group) + if apiKey.GroupID != nil && apiKey.Group != nil { + rate = s.getUserGroupRateMultiplier(ctx, apiKey.User.ID, *apiKey.GroupID, rate) + } + cost, ok := EstimateInflightReservationCost(s.billingService, inflightReservationCfg(s.cfg), model, bodyBytes, maxTokens, rate) + if !ok { + return 0 + } + return cost +} + +// EstimateInflightReservation 使用 OpenAI 网关计费倍率估算在途预留金额;0 表示不预留。 +func (s *OpenAIGatewayService) EstimateInflightReservation(ctx context.Context, apiKey *APIKey, model string, bodyBytes, maxTokens int) float64 { + if s == nil || apiKey == nil || apiKey.User == nil { + return 0 + } + rate := groupRateMultiplierOrOne(apiKey.Group) + if apiKey.GroupID != nil && apiKey.Group != nil && s.userGroupRateResolver != nil { + rate = s.userGroupRateResolver.Resolve(ctx, apiKey.User.ID, *apiKey.GroupID, rate) + } + cost, ok := EstimateInflightReservationCost(s.billingService, inflightReservationCfg(s.cfg), model, bodyBytes, maxTokens, rate) + if !ok { + return 0 + } + return cost +} diff --git a/backend/internal/service/billing_inflight_reservation_test.go b/backend/internal/service/billing_inflight_reservation_test.go new file mode 100644 index 000000000..f1dff41ec --- /dev/null +++ b/backend/internal/service/billing_inflight_reservation_test.go @@ -0,0 +1,60 @@ +//go:build unit + +package service + +import ( + "context" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestEstimateInflightReservationCost(t *testing.T) { + billing := NewBillingService(&config.Config{}, nil) + pricing, err := billing.GetModelPricing("claude-sonnet-4-5") + require.NoError(t, err) + + cfg := config.InflightReservationConfig{DefaultMaxTokens: 8192, MaxOutputTokens: 64000, MaxInputTokens: 1000} + + // explicit max_tokens; body 400 bytes → 100 input tokens + cost, ok := EstimateInflightReservationCost(billing, cfg, "claude-sonnet-4-5", 400, 1000, 1) + require.True(t, ok) + require.InDelta(t, 100*pricing.InputPricePerToken+1000*pricing.OutputPricePerToken, cost, 1e-12) + + // missing max_tokens → default; rate multiplier applied + cost, ok = EstimateInflightReservationCost(billing, cfg, "claude-sonnet-4-5", 0, 0, 2) + require.True(t, ok) + require.InDelta(t, 2*8192*pricing.OutputPricePerToken, cost, 1e-12) + + // caps: input and output clamped + cost, ok = EstimateInflightReservationCost(billing, cfg, "claude-sonnet-4-5", 1_000_000, 1_000_000, 1) + require.True(t, ok) + require.InDelta(t, 1000*pricing.InputPricePerToken+64000*pricing.OutputPricePerToken, cost, 1e-12) + + // free group / missing billing → fail open + _, ok = EstimateInflightReservationCost(billing, cfg, "claude-sonnet-4-5", 10, 10, 0) + require.False(t, ok) + _, ok = EstimateInflightReservationCost(nil, cfg, "claude-sonnet-4-5", 10, 10, 1) + require.False(t, ok) + _, ok = EstimateInflightReservationCost(billing, cfg, "", 10, 10, 1) + require.False(t, ok) +} + +func TestReserveInflightBalance_NoReservationCacheFailsOpen(t *testing.T) { + cfg := &config.Config{} + cfg.Billing.InflightReservation.Enabled = true + svc := NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(svc.Stop) + release, err := svc.ReserveInflightBalance(context.Background(), &User{ID: 1}, nil, nil, 100) + require.NoError(t, err) + release() +} + +func TestReserveInflightBalance_SimpleModeDisabled(t *testing.T) { + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Billing.InflightReservation.Enabled = true + svc := NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(svc.Stop) + require.False(t, svc.InflightReservationEnabled()) +} diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index e1e1c6df7..de77ce6ad 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -1126,6 +1126,28 @@ billing: # Cache TTL (seconds) for per-user × per-platform quota records # 用户 × 平台 quota 缓存 TTL(秒),默认 86400=1天,覆盖典型 daily 窗口 user_platform_quota_cache_ttl_seconds: 86400 + # In-flight balance reservation (Redis): at admission, estimate per-request cost + # (input estimate + output price x max_tokens) and atomically require + # cached_balance - in-flight reservations >= estimate. Released when the request ends. + # The first in-flight request of a user is always admitted (same as before). + # Fails open when the estimate cannot be computed or Redis is unavailable. + # 余额模式在途预留:准入时估算单请求费用,要求 缓存余额 - 在途预留合计 >= 估算; + # 用户无在途请求时始终放行(与旧行为一致);估算失败/Redis 不可用时 fail-open。 + inflight_reservation: + enabled: true + # Max lifetime of a single reservation (self-heals leaked reservations) + # 单条预留最长存活时间(秒),泄漏的预留到期自动释放 + ttl_seconds: 900 + # Output tokens assumed when the request has no max_tokens + # 请求未携带 max_tokens 时假定的输出 token 数 + default_max_tokens: 8192 + # Cap for estimated output / input tokens + # 估算输出 / 输入 token 上限 + max_output_tokens: 128000 + max_input_tokens: 200000 + # Cap for a single reservation in USD (0 = no cap) + # 单请求预留金额上限(USD,0 为不设上限) + max_reservation_usd: 0 # ============================================================================= # Turnstile Configuration From 52c123e6f4a71effe970d7505b1dc66e03ecfce4 Mon Sep 17 00:00:00 2001 From: William Drake Date: Mon, 28 Sep 2026 16:14:43 -0400 Subject: [PATCH 03/17] fix(billing): hold inflight reservation until billing lands; price estimate like billing; wire remaining endpoints Address gaps found in adversarial verification of the in-flight balance reservation: - Early release: the reservation is now a ref-counted handle carried on the request context. Billing tasks submitted via submit*UsageRecordTask take a ref and return it only after RecordUsage has run; with reservation enabled the balance cache is deducted synchronously inside the billing task, so the reservation is released only after admission can see the deduction. Dropped tasks return their ref immediately. The reservation is renewed every ttl/3 while the handler runs; after the handler returns it is no longer renewed, so the post-handler hold is bounded by one TTL. - Estimate: use the same billing model (channel mapping + BillingModelSource, max over requested/mapped when ambiguous) and ModelPricingResolver (group ModelPricing incl. wildcards, channel per_request/image/video/token overrides), default/group/user rate + peak multiplier, plus image, video, audio and search surcharge kinds. Unpriced requests fail open with a throttled log; new billing.inflight_reservation.fail_closed_on_unpriced (default false) rejects them instead. - Wire images, embeddings, web/x search, alpha search, grok media generation, grok realtime/voice, OpenAI-platform /v1/messages and ResponsesWebSocket (session-level reservation with renewal). Co-Authored-By: Claude Opus 5.5 (1M context) --- backend/internal/config/config.go | 4 + backend/internal/handler/gateway_handler.go | 9 +- .../gateway_handler_chat_completions.go | 2 +- .../handler/gateway_handler_responses.go | 2 +- .../handler/gateway_inflight_reservation.go | 109 +++- .../gateway_inflight_reservation_test.go | 174 +++++- .../internal/handler/gateway_web_search.go | 12 + .../internal/handler/gemini_v1beta_handler.go | 2 +- backend/internal/handler/grok_audio.go | 24 + backend/internal/handler/grok_media.go | 12 + .../internal/handler/openai_alpha_search.go | 12 + .../handler/openai_chat_completions.go | 2 +- backend/internal/handler/openai_embeddings.go | 12 + .../handler/openai_gateway_handler.go | 46 +- backend/internal/handler/openai_images.go | 12 + .../repository/billing_inflight_cache.go | 36 +- .../repository/billing_inflight_cache_test.go | 58 ++ .../service/billing_inflight_reservation.go | 540 +++++++++++++++--- .../billing_inflight_reservation_test.go | 263 +++++++++ .../internal/service/gateway_usage_billing.go | 10 + deploy/config.example.yaml | 11 +- 21 files changed, 1250 insertions(+), 102 deletions(-) diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index f7cfcead2..1b07ae3a6 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -941,6 +941,9 @@ type InflightReservationConfig struct { MaxInputTokens int `mapstructure:"max_input_tokens"` // MaxReservationUSD 单请求预留金额上限;0 表示不设上限。 MaxReservationUSD float64 `mapstructure:"max_reservation_usd"` + // FailClosedOnUnpriced 无法为请求估算费用(模型/分组/渠道均无定价)时是否拒绝请求。 + // 默认 false:放行且不预留(fail-open,节流告警日志)。 + FailClosedOnUnpriced bool `mapstructure:"fail_closed_on_unpriced"` } type CircuitBreakerConfig struct { @@ -2119,6 +2122,7 @@ func setDefaults() { viper.SetDefault("billing.inflight_reservation.max_output_tokens", 128000) viper.SetDefault("billing.inflight_reservation.max_input_tokens", 200000) viper.SetDefault("billing.inflight_reservation.max_reservation_usd", 0) + viper.SetDefault("billing.inflight_reservation.fail_closed_on_unpriced", false) // Turnstile viper.SetDefault("turnstile.required", false) diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index acf4e21ac..f83494ef9 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -264,7 +264,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { } // 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。 - inflightRelease, err := reserveInflightBalance(c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, reqModel, body) + inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(reqModel, body)) if err != nil { reqLog.Info("gateway.inflight_reservation_rejected", zap.Error(err)) status, code, message, retryAfter := billingErrorDetails(err) @@ -2527,9 +2527,12 @@ func (h *GatewayHandler) submitUsageRecordTask(parent context.Context, task serv if task == nil { return } - task = wrapUsageRecordTaskContext(parent, task) + task, abandon := wrapUsageRecordTaskContext(parent, task) if h.usageRecordWorkerPool != nil { if mode := h.usageRecordWorkerPool.Submit(task); mode != service.UsageRecordSubmitModeDroppedStopped { + if mode.Dropped() { + abandon() + } return } // 池已停止(进程关停窗口):计费任务不能静默丢失,降级为内联同步执行。 @@ -2557,7 +2560,7 @@ func (h *GatewayHandler) submitMandatoryUsageRecordTask(parent context.Context, if task == nil { return } - task = wrapUsageRecordTaskContext(parent, task) + task, _ = wrapUsageRecordTaskContext(parent, task) if h.usageRecordWorkerPool != nil { if mode := h.usageRecordWorkerPool.Submit(task); !mode.Dropped() { return diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index b844d27d1..79ca02530 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -145,7 +145,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { } // 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。 - inflightRelease, err := reserveInflightBalance(c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, reqModel, body) + inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(reqModel, body)) if err != nil { reqLog.Info("gateway.cc.inflight_reservation_rejected", zap.Error(err)) status, code, message, retryAfter := billingErrorDetails(err) diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index a10ad8d4e..a13e43877 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -154,7 +154,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { } // 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。 - inflightRelease, err := reserveInflightBalance(requestCtx, h.billingCacheService, h.gatewayService, apiKey, subscription, reqModel, body) + inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(reqModel, body)) if err != nil { reqLog.Info("gateway.responses.inflight_reservation_rejected", zap.Error(err)) status, code, message, retryAfter := billingErrorDetails(err) diff --git a/backend/internal/handler/gateway_inflight_reservation.go b/backend/internal/handler/gateway_inflight_reservation.go index 08ebaafb9..5928220dc 100644 --- a/backend/internal/handler/gateway_inflight_reservation.go +++ b/backend/internal/handler/gateway_inflight_reservation.go @@ -4,12 +4,13 @@ import ( "context" "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" "github.com/tidwall/gjson" ) -// inflightReservationEstimator 估算单请求在途预留金额(USD)。 +// inflightReservationEstimator 估算单请求在途预留金额(USD);false 表示无法定价。 type inflightReservationEstimator interface { - EstimateInflightReservation(ctx context.Context, apiKey *service.APIKey, model string, bodyBytes, maxTokens int) float64 + EstimateInflightReservation(ctx context.Context, apiKey *service.APIKey, req service.InflightEstimateRequest) (float64, bool) } // requestMaxOutputTokens 从请求体中提取输出 token 上限(兼容 Anthropic / OpenAI Chat / Responses / Gemini)。 @@ -22,28 +23,110 @@ func requestMaxOutputTokens(body []byte) int { return 0 } +// tokenInflightEstimate 文本类请求的估算输入。 +func tokenInflightEstimate(model string, body []byte) service.InflightEstimateRequest { + return service.InflightEstimateRequest{ + Model: model, + BodyBytes: len(body), + MaxTokens: requestMaxOutputTokens(body), + Kind: service.InflightEstimateToken, + } +} + +func inflightNoop() {} + // reserveInflightBalance 在 CheckBillingEligibility 之后为余额模式请求登记在途预留。 -// 返回的 release 必须 defer 调用(覆盖成功/错误/客户端断开/failover 等所有路径); -// 开关关闭、订阅模式、估算失败或 Redis 故障时返回 no-op(fail-open)。 +// +// 成功时把预留句柄挂到 c.Request 的 context 上:之后通过 submit*UsageRecordTask 提交的 +// 计费任务会接管一个引用,直到余额缓存实际扣减后才释放。返回的 done 必须 defer 调用 +// (停止续期并归还 handler 引用;没有提交计费任务时即刻释放)。 +// 开关关闭、订阅模式、Redis 故障时返回 no-op(fail-open);无法定价时默认 fail-open, +// 配置 fail_closed_on_unpriced=true 时返回 ErrInsufficientBalance。 func reserveInflightBalance( - ctx context.Context, + c *gin.Context, billing *service.BillingCacheService, estimator inflightReservationEstimator, apiKey *service.APIKey, subscription *service.UserSubscription, - model string, - body []byte, + req service.InflightEstimateRequest, ) (func(), error) { - noop := func() {} + if c == nil || c.Request == nil { + return inflightNoop, nil + } + ctx, done, err := reserveInflightBalanceCtx(c.Request.Context(), billing, estimator, apiKey, subscription, req) + if err != nil { + return inflightNoop, err + } + c.Request = c.Request.WithContext(ctx) + return done, nil +} + +// reserveInflightBalanceCtx 同 reserveInflightBalance,但返回携带预留句柄的新 context +// (供 WebSocket 等自管 context 的路径)。 +func reserveInflightBalanceCtx( + ctx context.Context, + billing *service.BillingCacheService, + estimator inflightReservationEstimator, + apiKey *service.APIKey, + subscription *service.UserSubscription, + req service.InflightEstimateRequest, +) (context.Context, func(), error) { if billing == nil || estimator == nil || apiKey == nil || apiKey.User == nil || !billing.InflightReservationEnabled() { - return noop, nil + return ctx, inflightNoop, nil } if apiKey.Group != nil && apiKey.Group.IsSubscriptionType() && subscription != nil { - return noop, nil + return ctx, inflightNoop, nil + } + estimate, priced := estimator.EstimateInflightReservation(ctx, apiKey, req) + if !priced && billing.InflightReservationFailClosedOnUnpriced() { + return ctx, inflightNoop, service.ErrInsufficientBalance } - estimate := estimator.EstimateInflightReservation(ctx, apiKey, model, len(body), requestMaxOutputTokens(body)) if estimate <= 0 { - return noop, nil + return ctx, inflightNoop, nil + } + res, err := billing.ReserveInflight(ctx, apiKey.User, apiKey.Group, subscription, estimate) + if err != nil { + return ctx, inflightNoop, err + } + if res == nil { + return ctx, inflightNoop, nil + } + return service.WithInflightReservation(ctx, res), res.HandlerDone, nil +} + +// grokMediaInflightEstimate 媒体生成请求的估算输入;状态/内容查询返回空模型(不预留: +// 查询会为已生成的媒体计费,不能因余额预留而拦截用户取回已付费结果)。 +func grokMediaInflightEstimate(endpoint service.GrokMediaEndpoint, model string, info service.GrokMediaRequestInfo, body []byte) service.InflightEstimateRequest { + if !endpoint.IsGenerationRequest() { + return service.InflightEstimateRequest{} + } + switch endpoint { + case service.GrokMediaEndpointImagesGenerations, service.GrokMediaEndpointImagesEdits: + return service.InflightEstimateRequest{Model: model, BodyBytes: len(body), Kind: service.InflightEstimateImage, Units: info.N} + default: + return service.InflightEstimateRequest{ + Model: model, + BodyBytes: len(body), + Kind: service.InflightEstimateVideo, + Units: 1, + VideoResolution: info.Resolution, + VideoDurationSeconds: info.DurationSeconds, + } + } +} + +// grokVoiceSTTBytesPerSecond STT 时长粗估(~128kbps 压缩音频)。 +const grokVoiceSTTBytesPerSecond = 16000 + +// grokVoiceInflightEstimate 语音 HTTP 接口估算:TTS 按输入字符数(百万字符),STT 按音频字节粗估时长(小时)。 +// 其他接口(custom-voices)无音频计量,返回的估算为 0(不预留)。 +func grokVoiceInflightEstimate(endpoint string, body []byte) service.InflightEstimateRequest { + req := service.InflightEstimateRequest{Model: endpoint, Kind: service.InflightEstimateAudio, AudioMode: endpoint} + switch endpoint { + case "tts": + req.AudioUnits = float64(len([]rune(extractGrokTTSInputText(body)))) / 1e6 + case "stt": + req.AudioUnits = float64(len(body)) / grokVoiceSTTBytesPerSecond / 3600 } - return billing.ReserveInflightBalance(ctx, apiKey.User, apiKey.Group, subscription, estimate) + return req } diff --git a/backend/internal/handler/gateway_inflight_reservation_test.go b/backend/internal/handler/gateway_inflight_reservation_test.go index a76f5eb6c..fa99884c6 100644 --- a/backend/internal/handler/gateway_inflight_reservation_test.go +++ b/backend/internal/handler/gateway_inflight_reservation_test.go @@ -1,11 +1,18 @@ package handler import ( + "bytes" "context" + "net/http" + "net/http/httptest" + "sync" "testing" + "time" "github.com/Wei-Shaw/sub2api/internal/config" + middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" ) @@ -18,29 +25,180 @@ func TestRequestMaxOutputTokens(t *testing.T) { require.Equal(t, 0, requestMaxOutputTokens([]byte(`{}`))) } -type countingEstimator struct{ calls int } +type countingEstimator struct { + calls int + cost float64 + priced bool +} -func (e *countingEstimator) EstimateInflightReservation(context.Context, *service.APIKey, string, int, int) float64 { +func (e *countingEstimator) EstimateInflightReservation(context.Context, *service.APIKey, service.InflightEstimateRequest) (float64, bool) { e.calls++ - return 1 + return e.cost, e.priced +} + +func newInflightTestGinContext() *gin.Context { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/", nil) + return c } func TestReserveInflightBalance_SkipsWhenDisabledOrSubscription(t *testing.T) { cfg := &config.Config{} billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) t.Cleanup(billing.Stop) - est := &countingEstimator{} + est := &countingEstimator{cost: 1, priced: true} apiKey := &service.APIKey{User: &service.User{ID: 1}} - release, err := reserveInflightBalance(context.Background(), billing, est, apiKey, nil, "m", []byte(`{}`)) + done, err := reserveInflightBalance(newInflightTestGinContext(), billing, est, apiKey, nil, tokenInflightEstimate("m", []byte(`{}`))) require.NoError(t, err) - release() + done() require.Equal(t, 0, est.calls, "disabled switch must not even estimate") cfg.Billing.InflightReservation.Enabled = true apiKey.Group = &service.Group{SubscriptionType: service.SubscriptionTypeSubscription} - release, err = reserveInflightBalance(context.Background(), billing, est, apiKey, &service.UserSubscription{}, "m", []byte(`{}`)) + done, err = reserveInflightBalance(newInflightTestGinContext(), billing, est, apiKey, &service.UserSubscription{}, tokenInflightEstimate("m", []byte(`{}`))) require.NoError(t, err) - release() + done() require.Equal(t, 0, est.calls, "subscription mode must be unaffected") } + +func TestReserveInflightBalance_UnpricedFailOpenByDefaultFailClosedOptIn(t *testing.T) { + cache := newHandlerInflightCache(10) + cfg := &config.Config{} + cfg.Billing.InflightReservation = config.InflightReservationConfig{Enabled: true, TTLSeconds: 60} + billing := service.NewBillingCacheService(cache, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + apiKey := &service.APIKey{User: &service.User{ID: 1}} + est := &countingEstimator{priced: false} + + done, err := reserveInflightBalance(newInflightTestGinContext(), billing, est, apiKey, nil, tokenInflightEstimate("unknown", nil)) + require.NoError(t, err) + done() + + cfg.Billing.InflightReservation.FailClosedOnUnpriced = true + _, err = reserveInflightBalance(newInflightTestGinContext(), billing, est, apiKey, nil, tokenInflightEstimate("unknown", nil)) + require.ErrorIs(t, err, service.ErrInsufficientBalance) +} + +// handlerInflightCache 内存版余额缓存 + 在途预留(语义同 Redis Lua)。 +type handlerInflightCache struct { + service.BillingCache + mu sync.Mutex + balance float64 + res map[string]float64 +} + +func newHandlerInflightCache(balance float64) *handlerInflightCache { + return &handlerInflightCache{balance: balance, res: map[string]float64{}} +} + +func (m *handlerInflightCache) GetUserBalance(context.Context, int64) (float64, error) { + m.mu.Lock() + defer m.mu.Unlock() + return m.balance, nil +} + +func (m *handlerInflightCache) GetUserPlatformQuotaCache(context.Context, int64, string) (*service.UserPlatformQuotaCacheEntry, bool, error) { + return nil, false, nil +} + +func (m *handlerInflightCache) ReserveInflightBalance(_ context.Context, _ int64, id string, amount, balance float64, _ time.Duration) (bool, float64, error) { + m.mu.Lock() + defer m.mu.Unlock() + sum := 0.0 + for _, v := range m.res { + sum += v + } + if len(m.res) > 0 && balance-sum < amount { + return false, sum, nil + } + m.res[id] = amount + return true, sum, nil +} + +func (m *handlerInflightCache) ReleaseInflightBalance(_ context.Context, _ int64, id string) error { + m.mu.Lock() + defer m.mu.Unlock() + delete(m.res, id) + return nil +} + +func (m *handlerInflightCache) count() int { + m.mu.Lock() + defer m.mu.Unlock() + return len(m.res) +} + +func TestWrapUsageRecordTaskContext_HandsReservationToBillingTask(t *testing.T) { + cache := newHandlerInflightCache(1) + cfg := &config.Config{} + cfg.Billing.InflightReservation = config.InflightReservationConfig{Enabled: true, TTLSeconds: 60} + billing := service.NewBillingCacheService(cache, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + apiKey := &service.APIKey{User: &service.User{ID: 5}} + + c := newInflightTestGinContext() + done, err := reserveInflightBalance(c, billing, &countingEstimator{cost: 0.9, priced: true}, apiKey, nil, tokenInflightEstimate("m", nil)) + require.NoError(t, err) + require.Equal(t, 1, cache.count()) + + ran := false + task, abandon := wrapUsageRecordTaskContext(c.Request.Context(), func(context.Context) { ran = true }) + done() // handler returns; billing still pending + require.Equal(t, 1, cache.count(), "reservation held until the billing task finishes") + task(context.Background()) + require.True(t, ran) + require.Equal(t, 0, cache.count()) + abandon() // idempotent with the task's own done + + // Dropped task: the submitter abandons it and the reservation is released. + c2 := newInflightTestGinContext() + done2, err := reserveInflightBalance(c2, billing, &countingEstimator{cost: 0.9, priced: true}, apiKey, nil, tokenInflightEstimate("m", nil)) + require.NoError(t, err) + _, abandon2 := wrapUsageRecordTaskContext(c2.Request.Context(), func(context.Context) {}) + done2() + require.Equal(t, 1, cache.count()) + abandon2() + require.Equal(t, 0, cache.count()) +} + +// 新接入的端点(独立 web_search):在途预留超过余额时拒绝,且不残留预留。 +func TestWebSearch_RejectsWhenInflightExceedsBalance(t *testing.T) { + cache := newHandlerInflightCache(1.5) + cfg := &config.Config{} + cfg.Billing.InflightReservation = config.InflightReservationConfig{Enabled: true, TTLSeconds: 60} + billingCache := service.NewBillingCacheService(cache, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCache.Stop) + billing := service.NewBillingService(cfg, nil) + gw := service.NewGatewayService( + nil, nil, nil, nil, nil, nil, nil, nil, cfg, nil, nil, billing, nil, nil, + nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, service.NewModelPricingResolver(nil, billing), nil, nil, nil, + ) + h := &GatewayHandler{gatewayService: gw, billingCacheService: billingCache} + + groupID := int64(3) + perK := 1000.0 // $1 per search + apiKey := &service.APIKey{ + ID: 9, User: &service.User{ID: 42, Balance: 1.5}, GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: service.PlatformGrok, RateMultiplier: 1, SearchPricePer1k: &perK}, + } + + // Another in-flight request of this user already holds $1. + held, err := billingCache.ReserveInflight(context.Background(), apiKey.User, apiKey.Group, nil, 1.0) + require.NoError(t, err) + defer held.HandlerDone() + + gin.SetMode(gin.TestMode) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/web_search", bytes.NewBufferString(`{"query":"sub2api"}`)) + c.Request.Header.Set("Content-Type", "application/json") + c.Set(string(middleware2.ContextKeyAPIKey), apiKey) + + h.WebSearch(c) + + require.NotEqual(t, http.StatusOK, w.Code) + require.Contains(t, w.Body.String(), "balance") + require.Equal(t, 1, cache.count(), "rejected request must not leave a reservation behind") +} diff --git a/backend/internal/handler/gateway_web_search.go b/backend/internal/handler/gateway_web_search.go index 741cc322f..70fbc1b7e 100644 --- a/backend/internal/handler/gateway_web_search.go +++ b/backend/internal/handler/gateway_web_search.go @@ -88,6 +88,18 @@ func (h *GatewayHandler) WebSearch(c *gin.Context) { return } + // 余额模式在途预留(与计费同口径估算;计费任务扣减余额缓存后才释放)。 + inflightDone, inflightErr := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, service.InflightEstimateRequest{Model: "grok-" + strings.ReplaceAll(searchLabel, "_", "-"), Kind: service.InflightEstimatePerRequest, SearchCalls: 1}) + if inflightErr != nil { + status, code, message, retryAfter := billingErrorDetails(inflightErr) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + c.JSON(status, gin.H{"error": gin.H{"type": code, "message": message}}) + return + } + defer inflightDone() + subject, _ := middleware2.GetAuthSubjectFromContext(c) reqLog := requestLogger(c, "handler.gateway.web_search") // Audit user search query before upstream Grok web_search traffic. diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index 0fc9e5eba..4e56c3723 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -391,7 +391,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { } // 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。 - inflightRelease, err := reserveInflightBalance(c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, modelName, body) + inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(modelName, body)) if err != nil { reqLog.Info("gemini.inflight_reservation_rejected", zap.Error(err)) status, _, message, retryAfter := billingErrorDetails(err) diff --git a/backend/internal/handler/grok_audio.go b/backend/internal/handler/grok_audio.go index 28ae40a39..7455485d7 100644 --- a/backend/internal/handler/grok_audio.go +++ b/backend/internal/handler/grok_audio.go @@ -49,6 +49,18 @@ func (h *OpenAIGatewayHandler) GrokRealtime(c *gin.Context) { if strings.TrimSpace(model) == "" { model = "grok-voice-latest" } + // 余额模式在途预留(与计费同口径估算;计费任务扣减余额缓存后才释放)。 + inflightDone, inflightErr := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, service.InflightEstimateRequest{Model: model, Kind: service.InflightEstimateAudio, AudioMode: "realtime", AudioUnits: 1}) + if inflightErr != nil { + status, code, message, retryAfter := billingErrorDetails(inflightErr) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.errorResponse(c, status, code, message) + return + } + defer inflightDone() + // Keep the HTTP response uncommitted while selecting and probing an account. // Realtime is not an HTTP streaming response; using reqStream=true here would // let the wait queue flush an SSE ping before the WebSocket handshake succeeds. @@ -212,6 +224,18 @@ func (h *OpenAIGatewayHandler) GrokVoice(c *gin.Context, endpoint string) { return } } + // 余额模式在途预留(与计费同口径估算;计费任务扣减余额缓存后才释放)。 + inflightDone, inflightErr := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, grokVoiceInflightEstimate(endpoint, body)) + if inflightErr != nil { + status, code, message, retryAfter := billingErrorDetails(inflightErr) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.errorResponse(c, status, code, message) + return + } + defer inflightDone() + contentType := c.GetHeader("Content-Type") if strings.TrimSpace(contentType) == "" { contentType = "application/json" diff --git a/backend/internal/handler/grok_media.go b/backend/internal/handler/grok_media.go index b61cd9515..03dabf752 100644 --- a/backend/internal/handler/grok_media.go +++ b/backend/internal/handler/grok_media.go @@ -173,6 +173,18 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. return } + // 余额模式在途预留(与计费同口径估算;计费任务扣减余额缓存后才释放)。 + inflightDone, inflightErr := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, grokMediaInflightEstimate(endpoint, routingModel, requestInfo, body)) + if inflightErr != nil { + status, code, message, retryAfter := billingErrorDetails(inflightErr) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.errorResponse(c, status, code, message) + return + } + defer inflightDone() + sessionSeed := body if len(sessionSeed) == 0 && strings.TrimSpace(requestID) != "" { sessionSeed = []byte(requestID) diff --git a/backend/internal/handler/openai_alpha_search.go b/backend/internal/handler/openai_alpha_search.go index 66c50be59..3c25b66a0 100644 --- a/backend/internal/handler/openai_alpha_search.go +++ b/backend/internal/handler/openai_alpha_search.go @@ -109,6 +109,18 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) { return } + // 余额模式在途预留(与计费同口径估算;计费任务扣减余额缓存后才释放)。 + inflightDone, inflightErr := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, service.InflightEstimateRequest{Model: requestedModel, BodyBytes: len(body), MaxTokens: requestMaxOutputTokens(body), Kind: service.InflightEstimateToken, SearchCalls: 1}) + if inflightErr != nil { + status, code, message, retryAfter := billingErrorDetails(inflightErr) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.errorResponse(c, status, code, message) + return + } + defer inflightDone() + searchID := strings.TrimSpace(gjson.GetBytes(body, "id").String()) sessionHash := h.gatewayService.GenerateSessionHashWithFallback(c, nil, searchID) profitVetoCount := 0 diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index afecc1b06..0a371f12e 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -147,7 +147,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { } // 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。 - inflightRelease, err := reserveInflightBalance(c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, reqModel, body) + inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(reqModel, body)) if err != nil { reqLog.Info("openai_chat_completions.inflight_reservation_rejected", zap.Error(err)) status, code, message, retryAfter := billingErrorDetails(err) diff --git a/backend/internal/handler/openai_embeddings.go b/backend/internal/handler/openai_embeddings.go index 8dda9faf3..6c900c482 100644 --- a/backend/internal/handler/openai_embeddings.go +++ b/backend/internal/handler/openai_embeddings.go @@ -108,6 +108,18 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) { return } + // 余额模式在途预留(与计费同口径估算;计费任务扣减余额缓存后才释放)。 + inflightDone, inflightErr := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, service.InflightEstimateRequest{Model: reqModel, BodyBytes: len(body), MaxTokens: 1, Kind: service.InflightEstimateToken}) + if inflightErr != nil { + status, code, message, retryAfter := billingErrorDetails(inflightErr) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.errorResponse(c, status, code, message) + return + } + defer inflightDone() + profitVetoCount := 0 failedAccountIDs := make(map[int64]struct{}) var lastFailoverErr *service.UpstreamFailoverError diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 5278219ea..dcc8a0952 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -257,13 +257,21 @@ func usageRecordContext(parent context.Context, base context.Context) context.Co return base } -func wrapUsageRecordTaskContext(parent context.Context, task service.UsageRecordTask) service.UsageRecordTask { +// wrapUsageRecordTaskContext 包装计费任务:复制请求级 context 值,并接管请求的在途余额预留引用。 +// 返回的 abandon 在任务未被执行(被丢弃)时必须调用以归还预留引用;任务执行结束时(含 panic) +// 自动归还,此时余额缓存已在计费路径中同步扣减。 +func wrapUsageRecordTaskContext(parent context.Context, task service.UsageRecordTask) (service.UsageRecordTask, func()) { if task == nil { - return nil + return nil, func() {} + } + done := func() {} + if parent != nil { + done = service.InflightReservationFromContext(parent).Acquire() } return func(ctx context.Context) { + defer done() task(usageRecordContext(parent, ctx)) - } + }, done } func openAICompatibleRequestPlatform(ctx context.Context, apiKey *service.APIKey) string { @@ -607,7 +615,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { } // 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。 - inflightRelease, err := reserveInflightBalance(c.Request.Context(), h.billingCacheService, h.gatewayService, apiKey, subscription, reqModel, body) + inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(reqModel, body)) if err != nil { reqLog.Info("openai.inflight_reservation_rejected", zap.Error(err)) status, code, message, retryAfter := billingErrorDetails(err) @@ -1255,6 +1263,18 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { return } + // 余额模式在途预留(与计费同口径估算;计费任务扣减余额缓存后才释放)。 + inflightDone, inflightErr := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(reqModel, body)) + if inflightErr != nil { + status, code, message, retryAfter := billingErrorDetails(inflightErr) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.anthropicStreamingAwareError(c, status, code, message, streamStarted) + return + } + defer inflightDone() + sessionHash := h.gatewayService.GenerateSessionHash(c, body) promptCacheKey := h.gatewayService.ExtractSessionID(c, body) sessionHash, promptCacheKey = resolveOpenAIMessagesMetadataSession(c, sessionHash, promptCacheKey, reqModel, body) @@ -2539,6 +2559,17 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { return } + // 余额模式在途预留(会话级):按首帧估算一次,会话期间续期;每轮计费任务接管引用, + // 会话结束且所有轮次扣减落地后释放。 + inflightCtx, inflightDone, inflightErr := reserveInflightBalanceCtx(ctx, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(reqModel, firstMessage)) + if inflightErr != nil { + reqLog.Info("openai.websocket_inflight_reservation_rejected", zap.Error(inflightErr)) + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "billing check failed") + return + } + defer inflightDone() + ctx = inflightCtx + // A WebSocket may outlive a key's remaining spending window. Recheck // after acquiring turn slots, including the first account-selection wait. // Restrict this extra check to the opt-in mode so standard-mode RPM checks @@ -3279,9 +3310,12 @@ func (h *OpenAIGatewayHandler) submitUsageRecordTask(parent context.Context, tas if task == nil { return } - task = wrapUsageRecordTaskContext(parent, task) + task, abandon := wrapUsageRecordTaskContext(parent, task) if h.usageRecordWorkerPool != nil { if mode := h.usageRecordWorkerPool.Submit(task); mode != service.UsageRecordSubmitModeDroppedStopped { + if mode.Dropped() { + abandon() + } return } // 池已停止(进程关停窗口):计费任务不能静默丢失,降级为内联同步执行。 @@ -3318,7 +3352,7 @@ func (h *OpenAIGatewayHandler) submitMandatoryUsageRecordTask(parent context.Con if task == nil { return } - task = wrapUsageRecordTaskContext(parent, task) + task, _ = wrapUsageRecordTaskContext(parent, task) if h.usageRecordWorkerPool != nil { if mode := h.usageRecordWorkerPool.Submit(task); !mode.Dropped() { return diff --git a/backend/internal/handler/openai_images.go b/backend/internal/handler/openai_images.go index 990086171..beda748cf 100644 --- a/backend/internal/handler/openai_images.go +++ b/backend/internal/handler/openai_images.go @@ -143,6 +143,18 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { return } + // 余额模式在途预留(与计费同口径估算;计费任务扣减余额缓存后才释放)。 + inflightDone, inflightErr := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, service.InflightEstimateRequest{Model: routingModel, BodyBytes: len(body), Kind: service.InflightEstimateImage, Units: parsed.N}) + if inflightErr != nil { + status, code, message, retryAfter := billingErrorDetails(inflightErr) + if retryAfter > 0 { + c.Header("Retry-After", strconv.Itoa(retryAfter)) + } + h.handleStreamingAwareError(c, status, code, message, streamStarted) + return + } + defer inflightDone() + sessionHash := h.gatewayService.GenerateExplicitSessionHash(c, body) requestCtx := service.WithOpenAIImagesEndpoint(service.WithOpenAIImageGenerationIntent(c.Request.Context())) diff --git a/backend/internal/repository/billing_inflight_cache.go b/backend/internal/repository/billing_inflight_cache.go index 47692fcf7..aba021d87 100644 --- a/backend/internal/repository/billing_inflight_cache.go +++ b/backend/internal/repository/billing_inflight_cache.go @@ -56,6 +56,23 @@ var ( return {1, tostring(sum), count} `) + // KEYS: [1]=zset [2]=hash ARGV: [1]=member [2]=expire_at_ms [3]=key_ttl_ms + // 仅当成员仍存在时续期(XX),并把两个 key 的 TTL 至少延长到 key_ttl_ms。 + renewInflightBalanceScript = redis.NewScript(` + if not redis.call('ZSCORE', KEYS[1], ARGV[1]) then + return 0 + end + redis.call('ZADD', KEYS[1], 'XX', tonumber(ARGV[2]), ARGV[1]) + local ttl = tonumber(ARGV[3]) + if redis.call('PTTL', KEYS[1]) < ttl then + redis.call('PEXPIRE', KEYS[1], ttl) + end + if redis.call('PTTL', KEYS[2]) < ttl then + redis.call('PEXPIRE', KEYS[2], ttl) + end + return 1 + `) + releaseInflightBalanceScript = redis.NewScript(` redis.call('ZREM', KEYS[1], ARGV[1]) redis.call('HDEL', KEYS[2], ARGV[1]) @@ -99,4 +116,21 @@ func (c *billingCache) ReleaseInflightBalance(ctx context.Context, userID int64, return releaseInflightBalanceScript.Run(ctx, c.rdb, []string{zkey, hkey}, requestID).Err() } -var _ service.InflightBalanceReservationCache = (*billingCache)(nil) +// RenewInflightBalance 实现 service.InflightBalanceReservationRenewer。 +func (c *billingCache) RenewInflightBalance(ctx context.Context, userID int64, requestID string, ttl time.Duration) (bool, error) { + zkey, hkey := billingInflightKeys(userID) + ttlMs := ttl.Milliseconds() + if ttlMs <= 0 { + ttlMs = 1 + } + n, err := renewInflightBalanceScript.Run(ctx, c.rdb, []string{zkey, hkey}, requestID, time.Now().UnixMilli()+ttlMs, ttlMs).Int64() + if err != nil { + return false, err + } + return n == 1, nil +} + +var ( + _ service.InflightBalanceReservationCache = (*billingCache)(nil) + _ service.InflightBalanceReservationRenewer = (*billingCache)(nil) +) diff --git a/backend/internal/repository/billing_inflight_cache_test.go b/backend/internal/repository/billing_inflight_cache_test.go index 6540c83bd..d9a338a94 100644 --- a/backend/internal/repository/billing_inflight_cache_test.go +++ b/backend/internal/repository/billing_inflight_cache_test.go @@ -209,3 +209,61 @@ func TestInflightReservation_ScriptErrorSurfaces(t *testing.T) { require.False(t, errors.Is(err, context.Canceled)) _ = rdb.Close() } + +// 回归:原实现在 handler 返回时即释放预留,而计费(RecordUsage → 余额缓存扣减)是异步的, +// 窗口内的顺序请求看到「在途=0 且余额未扣」全部放行(余额 $1、5×$0.9 → -4.40)。 +// 现在预留由计费任务在余额缓存扣减之后才释放。 +func TestInflightReservation_SequentialInBillingWindowAdmitsOnlyWhatBalanceCovers(t *testing.T) { + _, cache, svc := newInflightTestEnv(t, true, 60) + ctx := context.Background() + user := &service.User{ID: 77} + require.NoError(t, cache.SetUserBalance(ctx, user.ID, 1.0)) + + const cost = 0.9 + var pendingBilling []func() + admitted := 0 + for i := 0; i < 5; i++ { + res, err := svc.ReserveInflight(ctx, user, nil, nil, cost) + if err != nil { + require.ErrorIs(t, err, service.ErrInsufficientBalance) + continue + } + admitted++ + taskDone := res.Acquire() // handler submits the async billing task + res.HandlerDone() // handler returns before billing lands + pendingBilling = append(pendingBilling, func() { + require.NoError(t, cache.DeductUserBalance(ctx, user.ID, cost)) + taskDone() + }) + } + require.Equal(t, 1, admitted, "requests arriving before billing lands must not be admitted") + + for _, bill := range pendingBilling { + bill() + } + bal, err := cache.GetUserBalance(ctx, user.ID) + require.NoError(t, err) + require.InDelta(t, 0.1, bal, 1e-9) + require.Equal(t, int64(0), inflightCount(t, cache, user.ID)) +} + +func TestInflightReservation_RenewalKeepsStreamingReservationAlive(t *testing.T) { + _, cache, svc := newInflightTestEnv(t, true, 1) + ctx := context.Background() + user := &service.User{ID: 78} + require.NoError(t, cache.SetUserBalance(ctx, user.ID, 1.0)) + + res, err := svc.ReserveInflight(ctx, user, nil, nil, 0.8) + require.NoError(t, err) + time.Sleep(2500 * time.Millisecond) // streaming well past the 1s TTL + _, err = svc.ReserveInflight(ctx, user, nil, nil, 0.8) + require.ErrorIs(t, err, service.ErrInsufficientBalance, "renewed reservation must still count") + require.Equal(t, int64(1), inflightCount(t, cache, user.ID)) + + res.HandlerDone() + require.Equal(t, int64(0), inflightCount(t, cache, user.ID)) + + ok, err := cache.RenewInflightBalance(ctx, user.ID, "missing", time.Second) + require.NoError(t, err) + require.False(t, ok, "renew must not resurrect a released reservation") +} diff --git a/backend/internal/service/billing_inflight_reservation.go b/backend/internal/service/billing_inflight_reservation.go index 86b7e69a8..971bb472b 100644 --- a/backend/internal/service/billing_inflight_reservation.go +++ b/backend/internal/service/billing_inflight_reservation.go @@ -4,10 +4,12 @@ import ( "context" "math" "sync" + "sync/atomic" "time" "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/Wei-Shaw/sub2api/internal/pkg/timezone" "github.com/google/uuid" ) @@ -22,14 +24,167 @@ type InflightBalanceReservationCache interface { ReleaseInflightBalance(ctx context.Context, userID int64, requestID string) error } +// InflightBalanceReservationRenewer 可选:续期仍存活的预留(流式长请求期间防止 TTL 过期)。 +type InflightBalanceReservationRenewer interface { + // RenewInflightBalance 若 requestID 仍存在则把其过期时间推迟到 now+ttl;返回是否仍存在。 + RenewInflightBalance(ctx context.Context, userID int64, requestID string, ttl time.Duration) (bool, error) +} + const ( defaultInflightReservationTTL = 15 * time.Minute defaultInflightDefaultMaxTokens = 8192 inflightReservationReleaseTimeout = 2 * time.Second inflightReservationReserveTimeout = 2 * time.Second + inflightReservationRenewTimeout = 2 * time.Second inflightInputBytesPerTokenEstimate = 4 + inflightUnpricedLogInterval = time.Minute ) +// InflightReservation 一次请求的在途预留句柄。 +// +// 生命周期(引用计数,归零时释放一次): +// - 创建时持有 1 个「handler」引用,并启动续期协程(每 ttl/3 续期一次)。 +// - handler 提交计费任务时通过 Acquire 再取一个引用,由计费任务在余额缓存 +// 实际扣减之后归还(任务被丢弃时由提交方立即归还)。 +// - handler 返回时调用 HandlerDone:停止续期并归还 handler 引用。 +// +// 因此预留会一直保持到「handler 结束 且 所有计费任务已完成扣减」, +// 从而消除「handler 已返回、异步计费尚未落地」窗口内的透支。handler 结束后 +// 不再续期,所以最长持有时间受 TTL 约束(计费任务卡死时预留自动过期)。 +// 所有方法对 nil 接收者安全。 +type InflightReservation struct { + cache InflightBalanceReservationCache + userID int64 + requestID string + amount float64 + ttl time.Duration + + refs atomic.Int64 + releaseOnce sync.Once + stopOnce sync.Once + closeOnce sync.Once + stopRenew chan struct{} + renewDone chan struct{} +} + +// Amount 预留金额。 +func (r *InflightReservation) Amount() float64 { + if r == nil { + return 0 + } + return r.amount +} + +// Acquire 为一个异步计费任务增加引用;返回的 done 幂等,必须在任务结束(或被丢弃)时调用。 +// 预留已释放时返回 no-op。 +func (r *InflightReservation) Acquire() func() { + if r == nil { + return noopRelease + } + for { + cur := r.refs.Load() + if cur <= 0 { + return noopRelease + } + if r.refs.CompareAndSwap(cur, cur+1) { + break + } + } + var once sync.Once + return func() { once.Do(r.decRef) } +} + +// HandlerDone handler 结束:停止续期并归还 handler 引用(幂等)。 +func (r *InflightReservation) HandlerDone() { + if r == nil { + return + } + r.stopOnce.Do(func() { + r.stopRenewal() + r.decRef() + }) +} + +// Release 立即释放预留(幂等),不论引用计数。 +func (r *InflightReservation) Release() { + if r == nil { + return + } + r.stopRenewal() + r.releaseOnce.Do(func() { + r.refs.Store(0) + relCtx, relCancel := context.WithTimeout(context.Background(), inflightReservationReleaseTimeout) + defer relCancel() + if err := r.cache.ReleaseInflightBalance(relCtx, r.userID, r.requestID); err != nil { + logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation release failed for user %d (expires by ttl): %v", r.userID, err) + } + }) +} + +func (r *InflightReservation) decRef() { + if r.refs.Add(-1) <= 0 { + r.Release() + } +} + +func (r *InflightReservation) stopRenewal() { + if r.stopRenew == nil { + return + } + r.closeOnce.Do(func() { close(r.stopRenew) }) + <-r.renewDone +} + +func (r *InflightReservation) startRenewal(renewer InflightBalanceReservationRenewer) { + interval := r.ttl / 3 + if interval < 10*time.Millisecond { + interval = 10 * time.Millisecond + } + r.stopRenew = make(chan struct{}) + r.renewDone = make(chan struct{}) + go func() { + defer close(r.renewDone) + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-r.stopRenew: + return + case <-ticker.C: + ctx, cancel := context.WithTimeout(context.Background(), inflightReservationRenewTimeout) + alive, err := renewer.RenewInflightBalance(ctx, r.userID, r.requestID, r.ttl) + cancel() + if err != nil { + logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation renew failed for user %d: %v", r.userID, err) + continue + } + if !alive { + return + } + } + } + }() +} + +type inflightReservationCtxKey struct{} + +// WithInflightReservation 把预留句柄挂到 context 上,供计费任务提交时交接。 +func WithInflightReservation(ctx context.Context, r *InflightReservation) context.Context { + if r == nil { + return ctx + } + return context.WithValue(ctx, inflightReservationCtxKey{}, r) +} + +// InflightReservationFromContext 读取 context 中的预留句柄(可能为 nil)。 +func InflightReservationFromContext(ctx context.Context) *InflightReservation { + if ctx == nil { + return nil + } + r, _ := ctx.Value(inflightReservationCtxKey{}).(*InflightReservation) + return r +} + func noopRelease() {} func (s *BillingCacheService) inflightReservationConfig() (config.InflightReservationConfig, bool) { @@ -49,37 +204,59 @@ func (s *BillingCacheService) InflightReservationEnabled() bool { return ok } -// ReserveInflightBalance 在余额模式下为本次请求登记在途预留。 +// InflightReservationFailClosedOnUnpriced 无法估算费用时是否拒绝请求(默认 false = fail-open)。 +func (s *BillingCacheService) InflightReservationFailClosedOnUnpriced() bool { + cfg, ok := s.inflightReservationConfig() + return ok && cfg.FailClosedOnUnpriced +} + +// ReserveInflightBalance 简化封装:返回释放函数,不续期、不做计费交接(预留最长存活 TTL)。 +func (s *BillingCacheService) ReserveInflightBalance(ctx context.Context, user *User, group *Group, subscription *UserSubscription, estimate float64) (func(), error) { + r, err := s.reserveInflight(ctx, user, group, subscription, estimate, false) + if err != nil { + return noopRelease, err + } + if r == nil { + return noopRelease, nil + } + return r.Release, nil +} + +// ReserveInflight 在余额模式下为本次请求登记在途预留。 // -// 必须在 CheckBillingEligibility 通过后调用。返回的 release 必须在请求结束时调用 -// (所有路径,建议 defer),多次调用安全。 +// 必须在 CheckBillingEligibility 通过后调用。返回的句柄可能为 nil(未预留); +// 调用方须在 handler 结束时调用 HandlerDone(nil 安全)。 // // 以下情况直接放行且不登记预留(fail-open,保持旧行为): // 开关关闭 / 简易模式 / 订阅模式 / estimate <= 0 / 缓存不支持 / 余额读取失败 / Redis 执行失败。 // 仅当 Redis 明确判定 缓存余额 - 在途合计 < estimate(且已有在途请求)时返回 ErrInsufficientBalance。 -func (s *BillingCacheService) ReserveInflightBalance(ctx context.Context, user *User, group *Group, subscription *UserSubscription, estimate float64) (func(), error) { +func (s *BillingCacheService) ReserveInflight(ctx context.Context, user *User, group *Group, subscription *UserSubscription, estimate float64) (*InflightReservation, error) { + return s.reserveInflight(ctx, user, group, subscription, estimate, true) +} + +func (s *BillingCacheService) reserveInflight(ctx context.Context, user *User, group *Group, subscription *UserSubscription, estimate float64, renew bool) (*InflightReservation, error) { cfg, ok := s.inflightReservationConfig() if !ok || user == nil { - return noopRelease, nil + return nil, nil } if group != nil && group.IsSubscriptionType() && subscription != nil { - return noopRelease, nil + return nil, nil } if cfg.MaxReservationUSD > 0 && estimate > cfg.MaxReservationUSD { estimate = cfg.MaxReservationUSD } if estimate <= 0 || math.IsNaN(estimate) || math.IsInf(estimate, 0) { - return noopRelease, nil + return nil, nil } rc, ok := s.cache.(InflightBalanceReservationCache) if !ok || rc == nil { - return noopRelease, nil + return nil, nil } balance, err := s.GetUserBalance(ctx, user.ID) if err != nil { logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation balance read failed for user %d (fail-open): %v", user.ID, err) - return noopRelease, nil + return nil, nil } ttl := defaultInflightReservationTTL @@ -92,41 +269,121 @@ func (s *BillingCacheService) ReserveInflightBalance(ctx context.Context, user * cancel() if err != nil { logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation failed for user %d (fail-open): %v", user.ID, err) - return noopRelease, nil + return nil, nil } if !allowed { logger.LegacyPrintf("service.billing_cache", "inflight reservation rejected: user=%d balance=%.6f inflight=%.6f estimate=%.6f", user.ID, balance, inflight, estimate) - return noopRelease, ErrInsufficientBalance + return nil, ErrInsufficientBalance } - var once sync.Once - userID := user.ID - return func() { - once.Do(func() { - relCtx, relCancel := context.WithTimeout(context.Background(), inflightReservationReleaseTimeout) - defer relCancel() - if err := rc.ReleaseInflightBalance(relCtx, userID, requestID); err != nil { - logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation release failed for user %d (expires by ttl): %v", userID, err) - } - }) - }, nil + r := &InflightReservation{cache: rc, userID: user.ID, requestID: requestID, amount: estimate, ttl: ttl} + r.refs.Store(1) + if renewer, ok := s.cache.(InflightBalanceReservationRenewer); renew && ok && renewer != nil { + r.startRenewal(renewer) + } + return r, nil } -// EstimateInflightReservationCost 估算单请求的保守费用(USD,已乘倍率)。 -// -// input_tokens = min(bodyBytes / 4, max_input_tokens) -// output_tokens = min(max_tokens 或 default_max_tokens, max_output_tokens) -// cost = (input_tokens × 输入单价 + output_tokens × 输出单价) × rateMultiplier -// -// 无法取得定价时返回 (0, false),调用方应 fail-open。 -func EstimateInflightReservationCost(billing *BillingService, cfg config.InflightReservationConfig, model string, bodyBytes, maxTokens int, rateMultiplier float64) (float64, bool) { - if billing == nil || model == "" || rateMultiplier <= 0 { - return 0, false +// ============================================ +// 费用估算 +// ============================================ + +// InflightEstimateKind 估算口径。 +type InflightEstimateKind int + +const ( + // InflightEstimateToken 文本/对话类:输入估算 + 输出上限(按次渠道定价时按次计)。 + InflightEstimateToken InflightEstimateKind = iota + // InflightEstimateImage 图片生成:按张计(取所有尺寸档最高单价)。 + InflightEstimateImage + // InflightEstimatePerRequest 按次类(独立搜索等):仅按渠道/分组按次价与搜索附加费,不做 token 估算。 + InflightEstimatePerRequest + // InflightEstimateVideo 视频生成:按秒 × 条数(分组/模型视频价)。 + InflightEstimateVideo + // InflightEstimateAudio 语音(tts/stt/realtime):按 AudioMode/AudioUnits 计。 + InflightEstimateAudio +) + +// InflightEstimateRequest 单请求估算输入。 +type InflightEstimateRequest struct { + Model string + BodyBytes int + MaxTokens int + Kind InflightEstimateKind + // Units 按次/按张数量(<=0 视为 1)。 + Units int + // SearchCalls 叠加的搜索次数(按分组 search_price_per_1k 计)。 + SearchCalls int + // 视频:分辨率与时长(秒)。 + VideoResolution string + VideoDurationSeconds int + // 音频:模式(tts/stt/realtime)与计量单位(百万字符/小时/分钟)。 + AudioMode string + AudioUnits float64 +} + +// inflightEstimateDeps 两种网关 service 共用的估算依赖。 +type inflightEstimateDeps struct { + cfg *config.Config + billing *BillingService + resolver *ModelPricingResolver + resolveMapping func(ctx context.Context, groupID int64, model string) ChannelMappingResult + userGroupRate func(ctx context.Context, userID, groupID int64, groupDefault float64) float64 +} + +var inflightUnpricedLastLog atomic.Int64 + +func logInflightUnpriced(model string, groupID *int64) { + now := time.Now().UnixNano() + last := inflightUnpricedLastLog.Load() + if now-last < int64(inflightUnpricedLogInterval) || !inflightUnpricedLastLog.CompareAndSwap(last, now) { + return } - pricing, err := billing.GetModelPricing(model) - if err != nil || pricing == nil { - return 0, false + var gid int64 + if groupID != nil { + gid = *groupID + } + logger.LegacyPrintf("service.billing_cache", "Warning: inflight reservation cannot price model=%q group=%d; request admitted without reservation (fail-open, throttled log)", model, gid) +} + +// inflightBillingModelCandidates 与计费路径一致地挑选计费模型: +// channel_mapped(默认)→ 映射后模型;requested → 请求模型; +// upstream / response_model 在准入时未知 → 取请求模型与映射模型两者较高估算。 +func inflightBillingModelCandidates(ctx context.Context, deps inflightEstimateDeps, apiKey *APIKey, model string) []string { + if apiKey == nil || apiKey.GroupID == nil || deps.resolveMapping == nil { + return []string{model} + } + m := deps.resolveMapping(ctx, *apiKey.GroupID, model) + mapped := m.MappedModel + if mapped == "" || mapped == model { + return []string{model} } + switch m.BillingModelSource { + case BillingModelSourceRequested: + return []string{model} + case BillingModelSourceChannelMapped, "": + // 计费侧对无价映射模型会回落到具体转发模型;此处同时估算请求模型,取较高者。 + return []string{mapped, model} + default: + return []string{mapped, model} + } +} + +func (d inflightEstimateDeps) rates(ctx context.Context, apiKey *APIKey) (text, image float64) { + rate := 1.0 + if d.cfg != nil && d.cfg.Default.RateMultiplier > 0 { + rate = d.cfg.Default.RateMultiplier + } + if apiKey != nil && apiKey.GroupID != nil && apiKey.Group != nil { + rate = apiKey.Group.RateMultiplier + if d.userGroupRate != nil && apiKey.User != nil { + rate = d.userGroupRate(ctx, apiKey.User.ID, *apiKey.GroupID, rate) + } + } + return computePeakAwareMultipliers(apiKey, rate, timezone.Now()) +} + +func tokenCounts(cfg config.InflightReservationConfig, bodyBytes, maxTokens int) (int, int) { inputTokens := 0 if bodyBytes > 0 { inputTokens = bodyBytes / inflightInputBytesPerTokenEstimate @@ -144,8 +401,165 @@ func EstimateInflightReservationCost(billing *BillingService, cfg config.Infligh if cfg.MaxOutputTokens > 0 && outputTokens > cfg.MaxOutputTokens { outputTokens = cfg.MaxOutputTokens } + return inputTokens, outputTokens +} + +func maxPerRequestPrice(resolved *ResolvedPricing) float64 { + if resolved == nil { + return 0 + } + p := resolved.DefaultPerRequestPrice + for _, tier := range resolved.RequestTiers { + if tier.PerRequestPrice != nil && *tier.PerRequestPrice > p { + p = *tier.PerRequestPrice + } + } + return p +} + +func validCost(v float64) bool { return v > 0 && !math.IsNaN(v) && !math.IsInf(v, 0) } + +// estimateOne 估算单个候选计费模型(未乘倍率的 token 部分与按次部分分开返回,便于套用不同倍率)。 +func (d inflightEstimateDeps) estimateOne(ctx context.Context, apiKey *APIKey, model string, req InflightEstimateRequest, textRate, imageRate float64) float64 { + cfg := inflightReservationCfg(d.cfg) + units := req.Units + if units <= 0 { + units = 1 + } + var resolved *ResolvedPricing + if d.resolver != nil { + in := PricingInput{Model: model} + if apiKey != nil { + in.GroupID = apiKey.GroupID + in.Group = apiKey.Group + } + resolved = d.resolver.Resolve(ctx, in) + } + + inputTokens, outputTokens := tokenCounts(cfg, req.BodyBytes, req.MaxTokens) + tokenCost := func() float64 { + var pricing *ModelPricing + if resolved != nil && (resolved.Mode == BillingModeToken || resolved.Mode == "") && d.resolver != nil { + pricing = d.resolver.GetIntervalPricing(resolved, inputTokens) + } + if pricing == nil && d.billing != nil { + pricing, _ = d.billing.GetModelPricing(model) + } + if pricing == nil { + return 0 + } + return (float64(inputTokens)*pricing.InputPricePerToken + float64(outputTokens)*pricing.OutputPricePerToken) * textRate + } + + var cost float64 + perRequestMode := resolved != nil && (resolved.Mode == BillingModePerRequest || resolved.Mode == BillingModeImage || resolved.Mode == BillingModeVideo) + switch req.Kind { + case InflightEstimateImage: + if perRequestMode { + cost = maxPerRequestPrice(resolved) * float64(units) * imageRate + } + if d.billing != nil { + cfgImg := imagePriceConfigFromAPIKey(apiKey) + for _, tier := range []string{ImageBillingSize1K, ImageBillingSize2K, ImageBillingSize4K} { + if b := d.billing.CalculateImageCost(model, tier, units, cfgImg, imageRate); b != nil && b.ActualCost > cost { + cost = b.ActualCost + } + } + } + if cost <= 0 { + cost = tokenCost() + } + case InflightEstimateVideo: + if perRequestMode { + cost = maxPerRequestPrice(resolved) * float64(units) * math.Max(textRate, imageRate) + } + if d.billing != nil { + if b := d.billing.CalculateVideoCost(model, req.VideoResolution, units, req.VideoDurationSeconds, videoPriceConfigFromAPIKey(apiKey), math.Max(textRate, imageRate)); b != nil && b.ActualCost > cost { + cost = b.ActualCost + } + } + case InflightEstimateAudio: + if perRequestMode && resolved.Mode == BillingModePerRequest { + u := req.AudioUnits + if u <= 0 { + u = 1 + } + cost = maxPerRequestPrice(resolved) * u * textRate + } + if d.billing != nil && req.AudioUnits > 0 { + if b := d.billing.CalculateAudioCost(req.AudioMode, req.AudioUnits, groupAudioPriceConfigFromAPIKey(apiKey), textRate); b != nil && b.ActualCost > cost { + cost = b.ActualCost + } + } + default: + if perRequestMode { + rate := textRate + if resolved.Mode == BillingModeImage { + rate = imageRate + } + cost = maxPerRequestPrice(resolved) * float64(units) * rate + } else if req.Kind != InflightEstimatePerRequest { + cost = tokenCost() + } + } + if req.SearchCalls > 0 { + if d.billing != nil { + if b := d.billing.CalculateSearchCost(req.SearchCalls, groupSearchPricePer1kFromAPIKey(apiKey), textRate); b != nil && b.ActualCost > 0 { + cost += b.ActualCost + } + } + } + if !validCost(cost) { + return 0 + } + return cost +} + +// estimate 返回保守的单请求费用(USD,已乘倍率);无法定价返回 (0,false)。 +func (d inflightEstimateDeps) estimate(ctx context.Context, apiKey *APIKey, req InflightEstimateRequest) (float64, bool) { + if apiKey == nil || apiKey.User == nil { + return 0, false + } + if req.Model == "" || (req.Kind == InflightEstimateAudio && req.AudioUnits <= 0) { + // 非计量请求(媒体状态查询、custom-voices 等):无需预留,也不算「无法定价」。 + return 0, true + } + textRate, imageRate := d.rates(ctx, apiKey) + if textRate <= 0 && imageRate <= 0 { + // 免费分组:不计费,也无需预留。 + return 0, true + } + best := 0.0 + for _, m := range inflightBillingModelCandidates(ctx, d, apiKey, req.Model) { + if c := d.estimateOne(ctx, apiKey, m, req, textRate, imageRate); c > best { + best = c + } + } + if best <= 0 { + logInflightUnpriced(req.Model, apiKey.GroupID) + return 0, false + } + return best, true +} + +// EstimateInflightReservationCost 仅用基础定价的简化估算(保留给无 resolver 的调用方/测试)。 +// +// input_tokens = min(bodyBytes / 4, max_input_tokens) +// output_tokens = min(max_tokens 或 default_max_tokens, max_output_tokens) +// cost = (input_tokens × 输入单价 + output_tokens × 输出单价) × rateMultiplier +// +// 无法取得定价时返回 (0, false),调用方应 fail-open。 +func EstimateInflightReservationCost(billing *BillingService, cfg config.InflightReservationConfig, model string, bodyBytes, maxTokens int, rateMultiplier float64) (float64, bool) { + if billing == nil || model == "" || rateMultiplier <= 0 { + return 0, false + } + pricing, err := billing.GetModelPricing(model) + if err != nil || pricing == nil { + return 0, false + } + inputTokens, outputTokens := tokenCounts(cfg, bodyBytes, maxTokens) cost := (float64(inputTokens)*pricing.InputPricePerToken + float64(outputTokens)*pricing.OutputPricePerToken) * rateMultiplier - if cost <= 0 || math.IsNaN(cost) || math.IsInf(cost, 0) { + if !validCost(cost) { return 0, false } return cost, true @@ -158,41 +572,37 @@ func inflightReservationCfg(cfg *config.Config) config.InflightReservationConfig return cfg.Billing.InflightReservation } -func groupRateMultiplierOrOne(group *Group) float64 { - if group == nil { - return 1 +func (s *GatewayService) inflightEstimateDeps() inflightEstimateDeps { + d := inflightEstimateDeps{cfg: s.cfg, billing: s.billingService, resolver: s.resolver} + if s.channelService != nil { + d.resolveMapping = s.channelService.ResolveChannelMapping } - return group.RateMultiplier + d.userGroupRate = s.getUserGroupRateMultiplier + return d } -// EstimateInflightReservation 使用网关计费倍率估算在途预留金额;0 表示不预留。 -func (s *GatewayService) EstimateInflightReservation(ctx context.Context, apiKey *APIKey, model string, bodyBytes, maxTokens int) float64 { - if s == nil || apiKey == nil || apiKey.User == nil { - return 0 - } - rate := groupRateMultiplierOrOne(apiKey.Group) - if apiKey.GroupID != nil && apiKey.Group != nil { - rate = s.getUserGroupRateMultiplier(ctx, apiKey.User.ID, *apiKey.GroupID, rate) - } - cost, ok := EstimateInflightReservationCost(s.billingService, inflightReservationCfg(s.cfg), model, bodyBytes, maxTokens, rate) - if !ok { - return 0 +// EstimateInflightReservation 与计费路径同口径(计费模型 / ModelPricingResolver / 倍率)估算在途预留金额。 +// 第二个返回值为 false 表示无法定价(调用方 fail-open 或按配置 fail-closed)。 +func (s *GatewayService) EstimateInflightReservation(ctx context.Context, apiKey *APIKey, req InflightEstimateRequest) (float64, bool) { + if s == nil { + return 0, false } - return cost + return s.inflightEstimateDeps().estimate(ctx, apiKey, req) } -// EstimateInflightReservation 使用 OpenAI 网关计费倍率估算在途预留金额;0 表示不预留。 -func (s *OpenAIGatewayService) EstimateInflightReservation(ctx context.Context, apiKey *APIKey, model string, bodyBytes, maxTokens int) float64 { - if s == nil || apiKey == nil || apiKey.User == nil { - return 0 - } - rate := groupRateMultiplierOrOne(apiKey.Group) - if apiKey.GroupID != nil && apiKey.Group != nil && s.userGroupRateResolver != nil { - rate = s.userGroupRateResolver.Resolve(ctx, apiKey.User.ID, *apiKey.GroupID, rate) +func (s *OpenAIGatewayService) inflightEstimateDeps() inflightEstimateDeps { + d := inflightEstimateDeps{cfg: s.cfg, billing: s.billingService, resolver: s.resolver} + if s.channelService != nil { + d.resolveMapping = s.channelService.ResolveChannelMapping } - cost, ok := EstimateInflightReservationCost(s.billingService, inflightReservationCfg(s.cfg), model, bodyBytes, maxTokens, rate) - if !ok { - return 0 + d.userGroupRate = s.ResolveUserGroupRateMultiplier + return d +} + +// EstimateInflightReservation 同 GatewayService.EstimateInflightReservation(OpenAI 网关倍率口径)。 +func (s *OpenAIGatewayService) EstimateInflightReservation(ctx context.Context, apiKey *APIKey, req InflightEstimateRequest) (float64, bool) { + if s == nil { + return 0, false } - return cost + return s.inflightEstimateDeps().estimate(ctx, apiKey, req) } diff --git a/backend/internal/service/billing_inflight_reservation_test.go b/backend/internal/service/billing_inflight_reservation_test.go index f1dff41ec..bef02bc18 100644 --- a/backend/internal/service/billing_inflight_reservation_test.go +++ b/backend/internal/service/billing_inflight_reservation_test.go @@ -4,7 +4,10 @@ package service import ( "context" + "sync" + "sync/atomic" "testing" + "time" "github.com/Wei-Shaw/sub2api/internal/config" "github.com/stretchr/testify/require" @@ -58,3 +61,263 @@ func TestReserveInflightBalance_SimpleModeDisabled(t *testing.T) { t.Cleanup(svc.Stop) require.False(t, svc.InflightReservationEnabled()) } + +// --------------------------------------------------------------------------- +// estimate: same model / resolver as billing +// --------------------------------------------------------------------------- + +func newInflightEstimateGateway(t *testing.T, channelService *ChannelService) *GatewayService { + t.Helper() + cfg := &config.Config{} + cfg.Billing.InflightReservation = config.InflightReservationConfig{Enabled: true, DefaultMaxTokens: 1000, MaxInputTokens: 200000, MaxOutputTokens: 128000} + billing := NewBillingService(cfg, nil) + return &GatewayService{ + cfg: cfg, + billingService: billing, + resolver: NewModelPricingResolver(channelService, billing), + channelService: channelService, + } +} + +func TestInflightEstimate_ChannelAliasUsesMappedModel(t *testing.T) { + groupID := int64(10) + ch := Channel{ + ID: 1, + Status: StatusActive, + GroupIDs: []int64{groupID}, + ModelMapping: map[string]map[string]string{ + "anthropic": {"my-alias": "claude-sonnet-4-5"}, + }, + } + cs := newTestChannelService(makeStandardRepo(ch, map[int64]string{groupID: "anthropic"})) + svc := newInflightEstimateGateway(t, cs) + apiKey := &APIKey{User: &User{ID: 1}, GroupID: &groupID, Group: &Group{ID: groupID, Platform: PlatformAnthropic, RateMultiplier: 1}} + + // Old estimate (client model, base pricing only) → 0 → reservation bypassed. + _, ok := EstimateInflightReservationCost(svc.billingService, svc.cfg.Billing.InflightReservation, "my-alias", 4000, 1000, 1) + require.False(t, ok, "precondition: alias has no base pricing") + + est, priced := svc.EstimateInflightReservation(context.Background(), apiKey, InflightEstimateRequest{Model: "my-alias", BodyBytes: 4000, MaxTokens: 1000}) + require.True(t, priced) + require.Greater(t, est, 0.0) + + direct, _ := svc.EstimateInflightReservation(context.Background(), apiKey, InflightEstimateRequest{Model: "claude-sonnet-4-5", BodyBytes: 4000, MaxTokens: 1000}) + require.InDelta(t, direct, est, 1e-12, "alias must be estimated as the channel-mapped billing model") +} + +func TestInflightEstimate_GroupPerRequestPricing(t *testing.T) { + groupID := int64(20) + price := 0.5 + group := &Group{ID: groupID, Platform: PlatformAnthropic, RateMultiplier: 2, ModelPricing: []ChannelModelPricing{ + {Models: []string{"custom-per-request"}, BillingMode: BillingModePerRequest, PerRequestPrice: &price}, + }} + svc := newInflightEstimateGateway(t, nil) + apiKey := &APIKey{User: &User{ID: 1}, GroupID: &groupID, Group: group} + + est, priced := svc.EstimateInflightReservation(context.Background(), apiKey, InflightEstimateRequest{Model: "custom-per-request", BodyBytes: 100}) + require.True(t, priced) + require.InDelta(t, 1.0, est, 1e-12, "per_request 0.5 × group rate 2") + + // Wildcard group token pricing is honored as well. + in, out := 1e-6, 2e-6 + group.ModelPricing = []ChannelModelPricing{{Models: []string{"wild-*"}, BillingMode: BillingModeToken, InputPrice: &in, OutputPrice: &out}} + est, priced = svc.EstimateInflightReservation(context.Background(), apiKey, InflightEstimateRequest{Model: "wild-x", BodyBytes: 4000, MaxTokens: 500}) + require.True(t, priced) + require.InDelta(t, (1000*in+500*out)*2, est, 1e-12) +} + +func TestInflightEstimate_UnpricedIsReportedAndNonMeteredIsNot(t *testing.T) { + svc := newInflightEstimateGateway(t, nil) + apiKey := &APIKey{User: &User{ID: 1}} + est, priced := svc.EstimateInflightReservation(context.Background(), apiKey, InflightEstimateRequest{Model: "totally-unknown-model-xyz"}) + require.False(t, priced) + require.Zero(t, est) + + est, priced = svc.EstimateInflightReservation(context.Background(), apiKey, InflightEstimateRequest{}) + require.True(t, priced, "non-metered requests (e.g. media status lookups) are not 'unpriced'") + require.Zero(t, est) +} + +func TestInflightEstimate_MediaKinds(t *testing.T) { + groupID := int64(30) + p4k := 0.3 + search := 1000.0 + group := &Group{ID: groupID, Platform: PlatformOpenAI, RateMultiplier: 1, ImagePrice4K: &p4k, SearchPricePer1k: &search} + svc := newInflightEstimateGateway(t, nil) + apiKey := &APIKey{User: &User{ID: 1}, GroupID: &groupID, Group: group} + + est, priced := svc.EstimateInflightReservation(context.Background(), apiKey, InflightEstimateRequest{Model: "gpt-image-1", Kind: InflightEstimateImage, Units: 2}) + require.True(t, priced) + require.GreaterOrEqual(t, est, 0.6, "image estimate uses the highest size tier × n") + + est, priced = svc.EstimateInflightReservation(context.Background(), apiKey, InflightEstimateRequest{Model: "grok-web-search", Kind: InflightEstimatePerRequest, SearchCalls: 1}) + require.True(t, priced) + require.InDelta(t, 1.0, est, 1e-12) + + est, priced = svc.EstimateInflightReservation(context.Background(), apiKey, InflightEstimateRequest{Model: "realtime", Kind: InflightEstimateAudio, AudioMode: "realtime", AudioUnits: 1}) + require.True(t, priced) + require.Greater(t, est, 0.0) +} + +// --------------------------------------------------------------------------- +// reservation handle: hand-off to billing task, renewal +// --------------------------------------------------------------------------- + +type memInflightCache struct { + BillingCache + mu sync.Mutex + balance float64 + res map[string]float64 + exp map[string]time.Time + renews atomic.Int32 + deducts atomic.Int32 + releaseCt atomic.Int32 +} + +func newMemInflightCache(balance float64) *memInflightCache { + return &memInflightCache{balance: balance, res: map[string]float64{}, exp: map[string]time.Time{}} +} + +func (m *memInflightCache) GetUserBalance(context.Context, int64) (float64, error) { + m.mu.Lock() + defer m.mu.Unlock() + return m.balance, nil +} + +func (m *memInflightCache) DeductUserBalance(_ context.Context, _ int64, amount float64) error { + m.mu.Lock() + defer m.mu.Unlock() + m.balance -= amount + m.deducts.Add(1) + return nil +} + +func (m *memInflightCache) gc() { + now := time.Now() + for id, e := range m.exp { + if !e.After(now) { + delete(m.exp, id) + delete(m.res, id) + } + } +} + +func (m *memInflightCache) ReserveInflightBalance(_ context.Context, _ int64, id string, amount, balance float64, ttl time.Duration) (bool, float64, error) { + m.mu.Lock() + defer m.mu.Unlock() + m.gc() + sum := 0.0 + for _, v := range m.res { + sum += v + } + if len(m.res) > 0 && balance-sum < amount { + return false, sum, nil + } + m.res[id] = amount + m.exp[id] = time.Now().Add(ttl) + return true, sum, nil +} + +func (m *memInflightCache) ReleaseInflightBalance(_ context.Context, _ int64, id string) error { + m.mu.Lock() + defer m.mu.Unlock() + delete(m.res, id) + delete(m.exp, id) + m.releaseCt.Add(1) + return nil +} + +func (m *memInflightCache) RenewInflightBalance(_ context.Context, _ int64, id string, ttl time.Duration) (bool, error) { + m.mu.Lock() + defer m.mu.Unlock() + m.renews.Add(1) + if _, ok := m.res[id]; !ok { + return false, nil + } + m.exp[id] = time.Now().Add(ttl) + return true, nil +} + +func (m *memInflightCache) count() int { + m.mu.Lock() + defer m.mu.Unlock() + m.gc() + return len(m.res) +} + +func newInflightSvc(t *testing.T, cache BillingCache, ttlSeconds int) *BillingCacheService { + t.Helper() + cfg := &config.Config{} + cfg.Billing.InflightReservation = config.InflightReservationConfig{Enabled: true, TTLSeconds: ttlSeconds} + svc := NewBillingCacheService(cache, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(svc.Stop) + return svc +} + +func TestInflightReservation_HeldUntilBillingTaskDone(t *testing.T) { + cache := newMemInflightCache(1) + svc := newInflightSvc(t, cache, 60) + user := &User{ID: 1} + + res, err := svc.ReserveInflight(context.Background(), user, nil, nil, 0.9) + require.NoError(t, err) + require.NotNil(t, res) + taskDone := res.Acquire() // billing task submitted + res.HandlerDone() // handler returned + require.Equal(t, 1, cache.count(), "reservation must survive handler return while billing is pending") + + _, err = svc.ReserveInflight(context.Background(), user, nil, nil, 0.9) + require.ErrorIs(t, err, ErrInsufficientBalance) + + taskDone() + taskDone() // idempotent + require.Equal(t, 0, cache.count()) + require.Equal(t, int32(1), cache.releaseCt.Load(), "released exactly once") + + // No billing task → HandlerDone releases immediately; Acquire after release is a no-op. + res2, err := svc.ReserveInflight(context.Background(), user, nil, nil, 0.1) + require.NoError(t, err) + res2.HandlerDone() + res2.HandlerDone() + require.Equal(t, 0, cache.count()) + res2.Acquire()() + require.Equal(t, int32(2), cache.releaseCt.Load()) + + // Nil handle is safe. + var nilRes *InflightReservation + nilRes.Acquire()() + nilRes.HandlerDone() + nilRes.Release() +} + +func TestInflightReservation_RenewedWhileHandlerActive(t *testing.T) { + cache := newMemInflightCache(1) + svc := newInflightSvc(t, cache, 1) + user := &User{ID: 2} + + res, err := svc.ReserveInflight(context.Background(), user, nil, nil, 0.9) + require.NoError(t, err) + time.Sleep(2500 * time.Millisecond) // > 2 × TTL + require.Equal(t, 1, cache.count(), "renewal keeps the reservation alive past its TTL") + require.Greater(t, cache.renews.Load(), int32(3)) + _, err = svc.ReserveInflight(context.Background(), user, nil, nil, 0.9) + require.ErrorIs(t, err, ErrInsufficientBalance) + + done := res.Acquire() + res.HandlerDone() + renewsAtStop := cache.renews.Load() + time.Sleep(1200 * time.Millisecond) + require.Equal(t, renewsAtStop, cache.renews.Load(), "no renewal after handler end") + require.Equal(t, 0, cache.count(), "post-handler hold is bounded by TTL") + done() +} + +func TestSyncBalanceCacheAfterDeduction_SynchronousWhenInflightEnabled(t *testing.T) { + cache := newMemInflightCache(1) + svc := newInflightSvc(t, cache, 60) + p := &postUsageBillingParams{Cost: &CostBreakdown{ActualCost: 0.25}, User: &User{ID: 3}} + syncBalanceCacheAfterDeduction(context.Background(), p, &billingDeps{billingCacheService: svc}, nil) + require.Equal(t, int32(1), cache.deducts.Load(), "cache deduction must land before the billing task returns") + bal, _ := cache.GetUserBalance(context.Background(), 3) + require.InDelta(t, 0.75, bal, 1e-12) +} diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 64b4e05fb..3a612d17d 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -477,6 +477,16 @@ func syncBalanceCacheAfterDeduction(ctx context.Context, p *postUsageBillingPara } return } + if deps.billingCacheService.InflightReservationEnabled() { + // 在途预留开启时同步扣减余额缓存:计费任务结束后才会释放预留, + // 必须保证此时准入读取的缓存余额已反映本次扣费,否则释放与扣减之间 + // 仍存在「在途=0 且余额未扣」的窗口。本函数运行在计费 worker 中,不在请求热路径。 + err := deps.billingCacheService.DeductBalanceCache(ctx, p.User.ID, p.Cost.ActualCost) + if err == nil { + return + } + logger.LegacyPrintf("service.gateway", "Warning: sync deduct balance cache failed for user %d, falling back to queue: %v", p.User.ID, err) + } deps.billingCacheService.QueueDeductBalance(p.User.ID, p.Cost.ActualCost) } diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index de77ce6ad..a49c400f7 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -1135,8 +1135,11 @@ billing: # 用户无在途请求时始终放行(与旧行为一致);估算失败/Redis 不可用时 fail-open。 inflight_reservation: enabled: true - # Max lifetime of a single reservation (self-heals leaked reservations) - # 单条预留最长存活时间(秒),泄漏的预留到期自动释放 + # Reservation TTL. Renewed every ttl/3 while the request is running; after the + # handler returns it is held (not renewed) until the async billing task has + # deducted the cached balance, so a stuck billing task frees it after at most one TTL. + # 预留 TTL(秒)。请求进行中每 ttl/3 续期;请求结束后不再续期,保持到异步计费 + # 扣减余额缓存后释放,计费任务卡死时最多一个 TTL 后自动失效 ttl_seconds: 900 # Output tokens assumed when the request has no max_tokens # 请求未携带 max_tokens 时假定的输出 token 数 @@ -1148,6 +1151,10 @@ billing: # Cap for a single reservation in USD (0 = no cap) # 单请求预留金额上限(USD,0 为不设上限) max_reservation_usd: 0 + # When a request cannot be priced (no base / group / channel pricing for the + # billing model), reject it instead of admitting it without reservation. + # 无法为请求定价(计费模型无基础/分组/渠道定价)时拒绝请求;默认 false 为放行不预留(节流告警日志) + fail_closed_on_unpriced: false # ============================================================================= # Turnstile Configuration From 652a7d74f924e19d0d3f5671b5a5ca72a812c13d Mon Sep 17 00:00:00 2001 From: William Drake Date: Mon, 28 Sep 2026 16:49:29 -0400 Subject: [PATCH 04/17] fix(billing): estimate unpriced aliases via billing fallback models; don't renew expired reservations - Inflight estimate now mirrors billableModelWithFallback: when the primary billing model has no price, fall back to the channel-mapped model (also for billing_model_source=requested) and to account-level mapped models (max over schedulable accounts in the group, cached 30s). - Composite groups also consider concrete account-mapped models (max) so the alias' family fuzzy price cannot underestimate. - Renew Lua refuses (and purges) members whose score <= now. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../repository/billing_inflight_cache.go | 16 ++- .../repository/billing_inflight_cache_test.go | 18 +++ .../service/billing_inflight_reservation.go | 114 ++++++++++++++---- .../billing_inflight_reservation_test.go | 59 +++++++++ 4 files changed, 181 insertions(+), 26 deletions(-) diff --git a/backend/internal/repository/billing_inflight_cache.go b/backend/internal/repository/billing_inflight_cache.go index aba021d87..898cf3b52 100644 --- a/backend/internal/repository/billing_inflight_cache.go +++ b/backend/internal/repository/billing_inflight_cache.go @@ -56,10 +56,17 @@ var ( return {1, tostring(sum), count} `) - // KEYS: [1]=zset [2]=hash ARGV: [1]=member [2]=expire_at_ms [3]=key_ttl_ms - // 仅当成员仍存在时续期(XX),并把两个 key 的 TTL 至少延长到 key_ttl_ms。 + // KEYS: [1]=zset [2]=hash ARGV: [1]=member [2]=expire_at_ms [3]=key_ttl_ms [4]=now_ms + // 仅当成员仍存在且尚未过期(score > now)时续期(XX),并把两个 key 的 TTL 至少延长到 key_ttl_ms。 + // 已过期但尚未被惰性清理的成员不得被复活:顺手清掉并返回 0。 renewInflightBalanceScript = redis.NewScript(` - if not redis.call('ZSCORE', KEYS[1], ARGV[1]) then + local score = redis.call('ZSCORE', KEYS[1], ARGV[1]) + if not score then + return 0 + end + if tonumber(score) <= tonumber(ARGV[4]) then + redis.call('ZREM', KEYS[1], ARGV[1]) + redis.call('HDEL', KEYS[2], ARGV[1]) return 0 end redis.call('ZADD', KEYS[1], 'XX', tonumber(ARGV[2]), ARGV[1]) @@ -123,7 +130,8 @@ func (c *billingCache) RenewInflightBalance(ctx context.Context, userID int64, r if ttlMs <= 0 { ttlMs = 1 } - n, err := renewInflightBalanceScript.Run(ctx, c.rdb, []string{zkey, hkey}, requestID, time.Now().UnixMilli()+ttlMs, ttlMs).Int64() + now := time.Now().UnixMilli() + n, err := renewInflightBalanceScript.Run(ctx, c.rdb, []string{zkey, hkey}, requestID, now+ttlMs, ttlMs, now).Int64() if err != nil { return false, err } diff --git a/backend/internal/repository/billing_inflight_cache_test.go b/backend/internal/repository/billing_inflight_cache_test.go index d9a338a94..ddab7c4de 100644 --- a/backend/internal/repository/billing_inflight_cache_test.go +++ b/backend/internal/repository/billing_inflight_cache_test.go @@ -267,3 +267,21 @@ func TestInflightReservation_RenewalKeepsStreamingReservationAlive(t *testing.T) require.NoError(t, err) require.False(t, ok, "renew must not resurrect a released reservation") } + +func TestInflightReservation_RenewDoesNotResurrectExpiredMember(t *testing.T) { + _, cache, _ := newInflightTestEnv(t, true, 60) + ctx := context.Background() + userID := int64(79) + zkey, hkey := billingInflightKeys(userID) + // 已过期但尚未被惰性清理的成员(score 在过去)。 + require.NoError(t, cache.rdb.ZAdd(ctx, zkey, redis.Z{Score: float64(time.Now().UnixMilli() - 1000), Member: "stale"}).Err()) + require.NoError(t, cache.rdb.HSet(ctx, hkey, "stale", "0.5").Err()) + + ok, err := cache.RenewInflightBalance(ctx, userID, "stale", time.Minute) + require.NoError(t, err) + require.False(t, ok, "renew must not resurrect an expired member") + require.Equal(t, int64(0), inflightCount(t, cache, userID)) + exists, err := cache.rdb.HExists(ctx, hkey, "stale").Result() + require.NoError(t, err) + require.False(t, exists) +} diff --git a/backend/internal/service/billing_inflight_reservation.go b/backend/internal/service/billing_inflight_reservation.go index 971bb472b..a9c43d0f9 100644 --- a/backend/internal/service/billing_inflight_reservation.go +++ b/backend/internal/service/billing_inflight_reservation.go @@ -2,7 +2,9 @@ package service import ( "context" + "fmt" "math" + "strings" "sync" "sync/atomic" "time" @@ -11,6 +13,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/pkg/timezone" "github.com/google/uuid" + gocache "github.com/patrickmn/go-cache" ) // InflightBalanceReservationCache 余额在途预留的缓存能力(可选)。 @@ -329,6 +332,51 @@ type inflightEstimateDeps struct { resolver *ModelPricingResolver resolveMapping func(ctx context.Context, groupID int64, model string) ChannelMappingResult userGroupRate func(ctx context.Context, userID, groupID int64, groupDefault float64) float64 + // accountMappedModels 返回分组内可调度账号对 model 的账号级映射结果(去重,不含 model 本身)。 + // 准入时账号尚未选定,计费侧 billableModelWithFallback 会回退到实际转发模型(UpstreamModel, + // 即账号映射后的模型),因此这里取所有候选映射模型的最高估算。 + accountMappedModels func(ctx context.Context, groupID int64, model string) []string +} + +// inflightAccountMappingCache 缓存「分组 + 模型 → 账号级映射模型集合」,避免未定价别名每次请求都查库。 +var inflightAccountMappingCache = gocache.New(30*time.Second, time.Minute) + +func inflightAccountMappedModelsFromRepo(repo AccountRepository) func(ctx context.Context, groupID int64, model string) []string { + if repo == nil { + return nil + } + return func(ctx context.Context, groupID int64, model string) []string { + model = strings.TrimSpace(model) + if groupID <= 0 || model == "" { + return nil + } + key := fmt.Sprintf("%d|%s", groupID, model) + if v, ok := inflightAccountMappingCache.Get(key); ok { + if out, ok := v.([]string); ok { + return out + } + } + accounts, err := repo.ListSchedulableByGroupID(ctx, groupID) + if err != nil { + return nil + } + seen := map[string]struct{}{} + var out []string + for i := range accounts { + mapped, matched := accounts[i].ResolveMappedModel(model) + mapped = strings.TrimSpace(mapped) + if !matched || mapped == "" || mapped == model { + continue + } + if _, dup := seen[mapped]; dup { + continue + } + seen[mapped] = struct{}{} + out = append(out, mapped) + } + inflightAccountMappingCache.Set(key, out, gocache.DefaultExpiration) + return out + } } var inflightUnpricedLastLog atomic.Int64 @@ -347,26 +395,32 @@ func logInflightUnpriced(model string, groupID *int64) { } // inflightBillingModelCandidates 与计费路径一致地挑选计费模型: -// channel_mapped(默认)→ 映射后模型;requested → 请求模型; -// upstream / response_model 在准入时未知 → 取请求模型与映射模型两者较高估算。 -func inflightBillingModelCandidates(ctx context.Context, deps inflightEstimateDeps, apiKey *APIKey, model string) []string { - if apiKey == nil || apiKey.GroupID == nil || deps.resolveMapping == nil { - return []string{model} - } - m := deps.resolveMapping(ctx, *apiKey.GroupID, model) - mapped := m.MappedModel - if mapped == "" || mapped == model { - return []string{model} - } - switch m.BillingModelSource { - case BillingModelSourceRequested: - return []string{model} - case BillingModelSourceChannelMapped, "": - // 计费侧对无价映射模型会回落到具体转发模型;此处同时估算请求模型,取较高者。 - return []string{mapped, model} - default: - return []string{mapped, model} +// 返回 primary(计费侧首选的计费模型)与 fallbacks(计费侧 billableModelWithFallback +// 在首选模型查无价时回退到的实际转发模型:渠道映射模型 → 账号级映射模型)。 +// - channel_mapped(默认)→ 映射后模型(同时估算请求模型,取较高者); +// - requested → 请求模型; +// - upstream / response_model 在准入时未知 → 取请求模型与映射模型两者较高估算。 +func inflightBillingModelCandidates(ctx context.Context, deps inflightEstimateDeps, apiKey *APIKey, model string) (primary, fallbacks []string) { + if apiKey == nil || apiKey.GroupID == nil { + return []string{model}, nil + } + upstreamInput := model + primary = []string{model} + if deps.resolveMapping != nil { + m := deps.resolveMapping(ctx, *apiKey.GroupID, model) + if mapped := m.MappedModel; mapped != "" && mapped != model { + upstreamInput = mapped + if m.BillingModelSource == BillingModelSourceRequested { + fallbacks = append(fallbacks, mapped) + } else { + primary = []string{mapped, model} + } + } + } + if deps.accountMappedModels != nil { + fallbacks = append(fallbacks, deps.accountMappedModels(ctx, *apiKey.GroupID, upstreamInput)...) } + return primary, fallbacks } func (d inflightEstimateDeps) rates(ctx context.Context, apiKey *APIKey) (text, image float64) { @@ -529,9 +583,23 @@ func (d inflightEstimateDeps) estimate(ctx context.Context, apiKey *APIKey, req // 免费分组:不计费,也无需预留。 return 0, true } - best := 0.0 - for _, m := range inflightBillingModelCandidates(ctx, d, apiKey, req.Model) { - if c := d.estimateOne(ctx, apiKey, m, req, textRate, imageRate); c > best { + primary, fallbacks := inflightBillingModelCandidates(ctx, d, apiKey, req.Model) + bestOf := func(models []string) float64 { + best := 0.0 + for _, m := range models { + if c := d.estimateOne(ctx, apiKey, m, req, textRate, imageRate); c > best { + best = c + } + } + return best + } + best := bestOf(primary) + // composite 分组:计费侧除非别名有显式渠道价,否则按实际转发的具体模型计费; + // 别名本身可能命中家族模糊价(低估),因此与候选具体模型一起取最高。 + composite := apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite + if best <= 0 || composite { + // 与 billableModelWithFallback 同口径:首选模型无价时回退到实际转发模型。 + if c := bestOf(fallbacks); c > best { best = c } } @@ -578,6 +646,7 @@ func (s *GatewayService) inflightEstimateDeps() inflightEstimateDeps { d.resolveMapping = s.channelService.ResolveChannelMapping } d.userGroupRate = s.getUserGroupRateMultiplier + d.accountMappedModels = inflightAccountMappedModelsFromRepo(s.accountRepo) return d } @@ -596,6 +665,7 @@ func (s *OpenAIGatewayService) inflightEstimateDeps() inflightEstimateDeps { d.resolveMapping = s.channelService.ResolveChannelMapping } d.userGroupRate = s.ResolveUserGroupRateMultiplier + d.accountMappedModels = inflightAccountMappedModelsFromRepo(s.accountRepo) return d } diff --git a/backend/internal/service/billing_inflight_reservation_test.go b/backend/internal/service/billing_inflight_reservation_test.go index bef02bc18..6d194af4f 100644 --- a/backend/internal/service/billing_inflight_reservation_test.go +++ b/backend/internal/service/billing_inflight_reservation_test.go @@ -4,6 +4,7 @@ package service import ( "context" + "math" "sync" "sync/atomic" "testing" @@ -321,3 +322,61 @@ func TestSyncBalanceCacheAfterDeduction_SynchronousWhenInflightEnabled(t *testin bal, _ := cache.GetUserBalance(context.Background(), 3) require.InDelta(t, 0.75, bal, 1e-12) } + +// 计费侧:requested 来源下别名本身无价 → billableModelWithFallback 回退到映射模型。 +// 准入估算必须同口径地 > 0,且等于按回退模型的估算。 +func TestInflightEstimate_RequestedSourceUnpricedAliasFallsBackLikeBilling(t *testing.T) { + groupID := int64(30) + ch := Channel{ + ID: 3, + Status: StatusActive, + GroupIDs: []int64{groupID}, + BillingModelSource: BillingModelSourceRequested, + ModelMapping: map[string]map[string]string{ + "anthropic": {"req-alias": "claude-sonnet-4-5"}, + }, + } + cs := newTestChannelService(makeStandardRepo(ch, map[int64]string{groupID: "anthropic"})) + svc := newInflightEstimateGateway(t, cs) + apiKey := &APIKey{User: &User{ID: 1}, GroupID: &groupID, Group: &Group{ID: groupID, Platform: PlatformAnthropic, RateMultiplier: 1}} + ctx := context.Background() + + billed := svc.billableModelWithFallback(ctx, apiKey, "req-alias", "claude-sonnet-4-5", "req-alias") + require.Equal(t, "claude-sonnet-4-5", billed, "precondition: billing falls back to the mapped model") + + est, priced := svc.EstimateInflightReservation(ctx, apiKey, InflightEstimateRequest{Model: "req-alias", BodyBytes: 4000, MaxTokens: 1000}) + require.True(t, priced) + require.Greater(t, est, 0.0) + direct, _ := svc.EstimateInflightReservation(ctx, apiKey, InflightEstimateRequest{Model: billed, BodyBytes: 4000, MaxTokens: 1000}) + require.InDelta(t, direct, est, 1e-12) +} + +// 计费侧:别名仅在账号级映射(无渠道映射)→ UpstreamModel 为账号映射模型,计费回退到它。 +// 准入时账号未选定:按分组内候选账号映射模型的最高估算。 +func TestInflightEstimate_AccountLevelMappingFallsBackLikeBilling(t *testing.T) { + groupID := int64(31) + svc := newInflightEstimateGateway(t, nil) + svc.accountRepo = &modelsListAccountRepoStub{byGroup: map[int64][]Account{groupID: { + {ID: 1, Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-31": "claude-sonnet-4-5"}}}, + {ID: 2, Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-31": "claude-opus-4-1"}}}, + }}} + apiKey := &APIKey{User: &User{ID: 1}, GroupID: &groupID, Group: &Group{ID: groupID, Platform: PlatformAnthropic, RateMultiplier: 1}} + ctx := context.Background() + + _, ok := EstimateInflightReservationCost(svc.billingService, svc.cfg.Billing.InflightReservation, "acct-alias-31", 4000, 1000, 1) + require.False(t, ok, "precondition: alias has no pricing") + + est, priced := svc.EstimateInflightReservation(ctx, apiKey, InflightEstimateRequest{Model: "acct-alias-31", BodyBytes: 4000, MaxTokens: 1000}) + require.True(t, priced) + req := InflightEstimateRequest{BodyBytes: 4000, MaxTokens: 1000} + best := 0.0 + for _, upstream := range []string{"claude-sonnet-4-5", "claude-opus-4-1"} { + billed := svc.billableModelWithFallback(ctx, apiKey, "acct-alias-31", upstream, "acct-alias-31") + require.Equal(t, upstream, billed, "precondition: billing charges the account-mapped model") + req.Model = billed + c, _ := svc.EstimateInflightReservation(ctx, apiKey, req) + require.Greater(t, c, 0.0) + best = math.Max(best, c) + } + require.InDelta(t, best, est, 1e-12, "estimate = max over candidate account-mapped billing models") +} From b886fb8edb9a9b889570616d3238cc9f280b4667 Mon Sep 17 00:00:00 2001 From: William Drake Date: Mon, 28 Sep 2026 17:08:13 -0400 Subject: [PATCH 05/17] fix(billing): read account-level mappings from scheduler snapshot only when unpriced - only consult account mappings after primary/channel candidates fail to price (or composite) - source mappings from the scheduler snapshot (same pool as account selection), no direct DB query and no per-model cache - ungrouped API keys use the scheduler's ungrouped pool - no negative caching: new mappings take effect on the next request Co-Authored-By: Claude Opus 5.5 (1M context) --- .../service/billing_inflight_reservation.go | 120 ++++++++++++------ .../billing_inflight_reservation_test.go | 120 +++++++++++++++++- 2 files changed, 197 insertions(+), 43 deletions(-) diff --git a/backend/internal/service/billing_inflight_reservation.go b/backend/internal/service/billing_inflight_reservation.go index a9c43d0f9..7c6c7b45f 100644 --- a/backend/internal/service/billing_inflight_reservation.go +++ b/backend/internal/service/billing_inflight_reservation.go @@ -2,7 +2,6 @@ package service import ( "context" - "fmt" "math" "strings" "sync" @@ -13,7 +12,6 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/pkg/timezone" "github.com/google/uuid" - gocache "github.com/patrickmn/go-cache" ) // InflightBalanceReservationCache 余额在途预留的缓存能力(可选)。 @@ -332,51 +330,59 @@ type inflightEstimateDeps struct { resolver *ModelPricingResolver resolveMapping func(ctx context.Context, groupID int64, model string) ChannelMappingResult userGroupRate func(ctx context.Context, userID, groupID int64, groupDefault float64) float64 - // accountMappedModels 返回分组内可调度账号对 model 的账号级映射结果(去重,不含 model 本身)。 + // accountMappedModels 返回调度器可选账号对 model 的账号级映射结果(去重,不含 model 本身)。 // 准入时账号尚未选定,计费侧 billableModelWithFallback 会回退到实际转发模型(UpstreamModel, // 即账号映射后的模型),因此这里取所有候选映射模型的最高估算。 - accountMappedModels func(ctx context.Context, groupID int64, model string) []string + // 仅在首选/渠道候选均无法定价(或 composite 分组)时才调用;实现只读调度器快照, + // 不在请求路径上直接查库,也不按模型名缓存(内存不随请求模型名增长)。 + accountMappedModels func(ctx context.Context, apiKey *APIKey, model string) []string } -// inflightAccountMappingCache 缓存「分组 + 模型 → 账号级映射模型集合」,避免未定价别名每次请求都查库。 -var inflightAccountMappingCache = gocache.New(30*time.Second, time.Minute) +// inflightSnapshotLister 调度器快照读取(与账号选择同源:Redis 快照,未命中时由快照服务自身回源并回填)。 +type inflightSnapshotLister func(ctx context.Context, groupID *int64, platform string, hasForcePlatform bool) ([]Account, error) -func inflightAccountMappedModelsFromRepo(repo AccountRepository) func(ctx context.Context, groupID int64, model string) []string { - if repo == nil { +// inflightAccountMappedModelsFromSnapshot 基于调度器快照在内存中匹配账号级映射(支持通配规则)。 +// resolvePlatform 返回与调度器一致的平台;无分组 API Key 使用调度器的未分组账号池(groupID=nil)。 +func inflightAccountMappedModelsFromSnapshot(list inflightSnapshotLister, resolvePlatform func(ctx context.Context, apiKey *APIKey, model string) (string, bool, bool)) func(ctx context.Context, apiKey *APIKey, model string) []string { + if list == nil || resolvePlatform == nil { return nil } - return func(ctx context.Context, groupID int64, model string) []string { + return func(ctx context.Context, apiKey *APIKey, model string) []string { model = strings.TrimSpace(model) - if groupID <= 0 || model == "" { + if apiKey == nil || model == "" { return nil } - key := fmt.Sprintf("%d|%s", groupID, model) - if v, ok := inflightAccountMappingCache.Get(key); ok { - if out, ok := v.([]string); ok { - return out - } + platform, forced, ok := resolvePlatform(ctx, apiKey, model) + if !ok || platform == "" { + return nil } - accounts, err := repo.ListSchedulableByGroupID(ctx, groupID) + accounts, err := list(ctx, apiKey.GroupID, platform, forced) if err != nil { return nil } - seen := map[string]struct{}{} - var out []string - for i := range accounts { - mapped, matched := accounts[i].ResolveMappedModel(model) - mapped = strings.TrimSpace(mapped) - if !matched || mapped == "" || mapped == model { - continue - } - if _, dup := seen[mapped]; dup { - continue - } - seen[mapped] = struct{}{} - out = append(out, mapped) + return accountMappedModelsFrom(accounts, model) + } +} + +func accountMappedModelsFrom(accounts []Account, model string) []string { + var seen map[string]struct{} + var out []string + for i := range accounts { + mapped, matched := accounts[i].ResolveMappedModel(model) + mapped = strings.TrimSpace(mapped) + if !matched || mapped == "" || mapped == model { + continue + } + if seen == nil { + seen = map[string]struct{}{} + } + if _, dup := seen[mapped]; dup { + continue } - inflightAccountMappingCache.Set(key, out, gocache.DefaultExpiration) - return out + seen[mapped] = struct{}{} + out = append(out, mapped) } + return out } var inflightUnpricedLastLog atomic.Int64 @@ -400,12 +406,12 @@ func logInflightUnpriced(model string, groupID *int64) { // - channel_mapped(默认)→ 映射后模型(同时估算请求模型,取较高者); // - requested → 请求模型; // - upstream / response_model 在准入时未知 → 取请求模型与映射模型两者较高估算。 -func inflightBillingModelCandidates(ctx context.Context, deps inflightEstimateDeps, apiKey *APIKey, model string) (primary, fallbacks []string) { +func inflightBillingModelCandidates(ctx context.Context, deps inflightEstimateDeps, apiKey *APIKey, model string) (primary, fallbacks []string, upstreamInput string) { + upstreamInput = model + primary = []string{model} if apiKey == nil || apiKey.GroupID == nil { - return []string{model}, nil + return primary, nil, upstreamInput } - upstreamInput := model - primary = []string{model} if deps.resolveMapping != nil { m := deps.resolveMapping(ctx, *apiKey.GroupID, model) if mapped := m.MappedModel; mapped != "" && mapped != model { @@ -417,10 +423,7 @@ func inflightBillingModelCandidates(ctx context.Context, deps inflightEstimateDe } } } - if deps.accountMappedModels != nil { - fallbacks = append(fallbacks, deps.accountMappedModels(ctx, *apiKey.GroupID, upstreamInput)...) - } - return primary, fallbacks + return primary, fallbacks, upstreamInput } func (d inflightEstimateDeps) rates(ctx context.Context, apiKey *APIKey) (text, image float64) { @@ -583,7 +586,7 @@ func (d inflightEstimateDeps) estimate(ctx context.Context, apiKey *APIKey, req // 免费分组:不计费,也无需预留。 return 0, true } - primary, fallbacks := inflightBillingModelCandidates(ctx, d, apiKey, req.Model) + primary, fallbacks, upstreamInput := inflightBillingModelCandidates(ctx, d, apiKey, req.Model) bestOf := func(models []string) float64 { best := 0.0 for _, m := range models { @@ -602,6 +605,12 @@ func (d inflightEstimateDeps) estimate(ctx context.Context, apiKey *APIKey, req if c := bestOf(fallbacks); c > best { best = c } + // 账号级映射候选(读调度器快照)仅在仍无法定价或 composite 时才查,已定价模型不触发。 + if (best <= 0 || composite) && d.accountMappedModels != nil { + if c := bestOf(d.accountMappedModels(ctx, apiKey, upstreamInput)); c > best { + best = c + } + } } if best <= 0 { logInflightUnpriced(req.Model, apiKey.GroupID) @@ -646,7 +655,19 @@ func (s *GatewayService) inflightEstimateDeps() inflightEstimateDeps { d.resolveMapping = s.channelService.ResolveChannelMapping } d.userGroupRate = s.getUserGroupRateMultiplier - d.accountMappedModels = inflightAccountMappedModelsFromRepo(s.accountRepo) + if s.schedulerSnapshot != nil { + snap := s.schedulerSnapshot + d.accountMappedModels = inflightAccountMappedModelsFromSnapshot( + func(ctx context.Context, groupID *int64, platform string, forced bool) ([]Account, error) { + accounts, _, err := snap.ListSchedulableAccounts(ctx, groupID, platform, forced) + return accounts, err + }, + func(ctx context.Context, apiKey *APIKey, model string) (string, bool, bool) { + platform, forced, err := s.resolvePlatform(ctx, apiKey.GroupID, apiKey.Group, model) + return platform, forced, err == nil + }, + ) + } return d } @@ -665,7 +686,22 @@ func (s *OpenAIGatewayService) inflightEstimateDeps() inflightEstimateDeps { d.resolveMapping = s.channelService.ResolveChannelMapping } d.userGroupRate = s.ResolveUserGroupRateMultiplier - d.accountMappedModels = inflightAccountMappedModelsFromRepo(s.accountRepo) + if s.schedulerSnapshot != nil { + snap := s.schedulerSnapshot + d.accountMappedModels = inflightAccountMappedModelsFromSnapshot( + func(ctx context.Context, groupID *int64, platform string, forced bool) ([]Account, error) { + accounts, _, err := snap.ListSchedulableAccounts(ctx, groupID, platform, forced) + return accounts, err + }, + func(ctx context.Context, apiKey *APIKey, model string) (string, bool, bool) { + platform := PlatformOpenAI + if apiKey.Group != nil && apiKey.Group.Platform != "" && apiKey.Group.Platform != PlatformComposite { + platform = apiKey.Group.Platform + } + return NormalizeOpenAICompatiblePlatform(platform), false, true + }, + ) + } return d } diff --git a/backend/internal/service/billing_inflight_reservation_test.go b/backend/internal/service/billing_inflight_reservation_test.go index 6d194af4f..dc02072eb 100644 --- a/backend/internal/service/billing_inflight_reservation_test.go +++ b/backend/internal/service/billing_inflight_reservation_test.go @@ -4,6 +4,8 @@ package service import ( "context" + "fmt" + "runtime" "math" "sync" "sync/atomic" @@ -356,10 +358,11 @@ func TestInflightEstimate_RequestedSourceUnpricedAliasFallsBackLikeBilling(t *te func TestInflightEstimate_AccountLevelMappingFallsBackLikeBilling(t *testing.T) { groupID := int64(31) svc := newInflightEstimateGateway(t, nil) - svc.accountRepo = &modelsListAccountRepoStub{byGroup: map[int64][]Account{groupID: { + snap := &inflightSnapshotCacheStub{byBucket: map[string][]Account{inflightBucketKey(groupID, PlatformAnthropic): { {ID: 1, Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-31": "claude-sonnet-4-5"}}}, {ID: 2, Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-31": "claude-opus-4-1"}}}, }}} + attachInflightSnapshot(svc, snap) apiKey := &APIKey{User: &User{ID: 1}, GroupID: &groupID, Group: &Group{ID: groupID, Platform: PlatformAnthropic, RateMultiplier: 1}} ctx := context.Background() @@ -380,3 +383,118 @@ func TestInflightEstimate_AccountLevelMappingFallsBackLikeBilling(t *testing.T) } require.InDelta(t, best, est, 1e-12, "estimate = max over candidate account-mapped billing models") } + +type inflightSnapshotCacheStub struct { + SchedulerCache + mu sync.Mutex + byBucket map[string][]Account + reads atomic.Int64 +} + +func inflightBucketKey(groupID int64, platform string) string { + return fmt.Sprintf("%d|%s", groupID, platform) +} + +func (c *inflightSnapshotCacheStub) set(groupID int64, platform string, accounts []Account) { + c.mu.Lock() + defer c.mu.Unlock() + c.byBucket[inflightBucketKey(groupID, platform)] = accounts +} + +func (c *inflightSnapshotCacheStub) GetSnapshot(ctx context.Context, bucket SchedulerBucket) ([]*Account, bool, error) { + c.reads.Add(1) + c.mu.Lock() + defer c.mu.Unlock() + src := c.byBucket[inflightBucketKey(bucket.GroupID, bucket.Platform)] + out := make([]*Account, 0, len(src)) + for i := range src { + a := src[i] + out = append(out, &a) + } + return out, true, nil +} + +// inflightCountingAccountRepo 统计请求路径上的任何直接查库。 +type inflightCountingAccountRepo struct { + AccountRepository + dbCalls atomic.Int64 +} + +func (r *inflightCountingAccountRepo) ListSchedulableByGroupID(ctx context.Context, groupID int64) ([]Account, error) { + r.dbCalls.Add(1) + return nil, nil +} + +func attachInflightSnapshot(svc *GatewayService, snap *inflightSnapshotCacheStub) *inflightCountingAccountRepo { + repo := &inflightCountingAccountRepo{} + svc.accountRepo = repo + svc.schedulerSnapshot = NewSchedulerSnapshotService(snap, nil, repo, nil, svc.cfg) + return repo +} + +// 已定价模型永不查账号映射;随机未定价模型名不直接查库、不产生按模型名的缓存(内存有界)。 +func TestInflightEstimate_AccountMappingNoDBAndBoundedMemory(t *testing.T) { + groupID := int64(40) + svc := newInflightEstimateGateway(t, nil) + snap := &inflightSnapshotCacheStub{byBucket: map[string][]Account{inflightBucketKey(groupID, PlatformAnthropic): { + {ID: 1, Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-40": "claude-sonnet-4-5"}}}, + }}} + repo := attachInflightSnapshot(svc, snap) + apiKey := &APIKey{User: &User{ID: 1}, GroupID: &groupID, Group: &Group{ID: groupID, Platform: PlatformAnthropic, RateMultiplier: 1}} + ctx := context.Background() + + for i := 0; i < 100; i++ { + _, priced := svc.EstimateInflightReservation(ctx, apiKey, InflightEstimateRequest{Model: "claude-sonnet-4-5", BodyBytes: 4000, MaxTokens: 1000}) + require.True(t, priced) + } + require.Zero(t, snap.reads.Load(), "priced models must never trigger account-mapping lookup") + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + const n = 20000 + for i := 0; i < n; i++ { + _, priced := svc.EstimateInflightReservation(ctx, apiKey, InflightEstimateRequest{Model: fmt.Sprintf("rand-%d-%d", i, time.Now().UnixNano()), BodyBytes: 4000, MaxTokens: 1000}) + require.False(t, priced) + } + runtime.GC() + runtime.ReadMemStats(&after) + require.Zero(t, repo.dbCalls.Load(), "no direct DB query on the request path") + require.Equal(t, int64(n), snap.reads.Load(), "unpriced lookups read the scheduler snapshot only") + require.Less(t, int64(after.HeapAlloc)-int64(before.HeapAlloc), int64(8<<20), "no per-model cache growth") +} + +// 无分组 API Key:使用调度器的未分组账号池,估算与计费回退的账号映射模型同口径。 +func TestInflightEstimate_NoGroupKeyUsesUngroupedAccountMapping(t *testing.T) { + svc := newInflightEstimateGateway(t, nil) + snap := &inflightSnapshotCacheStub{byBucket: map[string][]Account{inflightBucketKey(0, PlatformAnthropic): { + {ID: 1, Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-nog": "claude-opus-4-1"}}}, + }}} + attachInflightSnapshot(svc, snap) + apiKey := &APIKey{User: &User{ID: 1}} + ctx := context.Background() + + est, priced := svc.EstimateInflightReservation(ctx, apiKey, InflightEstimateRequest{Model: "acct-alias-nog", BodyBytes: 4000, MaxTokens: 1000}) + require.True(t, priced) + direct, ok := svc.EstimateInflightReservation(ctx, apiKey, InflightEstimateRequest{Model: "claude-opus-4-1", BodyBytes: 4000, MaxTokens: 1000}) + require.True(t, ok) + require.InDelta(t, direct, est, 1e-12) +} + +// 管理员新增账号映射后立即生效(不缓存负结果)。 +func TestInflightEstimate_AccountMappingNoNegativeCaching(t *testing.T) { + groupID := int64(41) + svc := newInflightEstimateGateway(t, nil) + snap := &inflightSnapshotCacheStub{byBucket: map[string][]Account{}} + attachInflightSnapshot(svc, snap) + apiKey := &APIKey{User: &User{ID: 1}, GroupID: &groupID, Group: &Group{ID: groupID, Platform: PlatformAnthropic, RateMultiplier: 1}} + ctx := context.Background() + req := InflightEstimateRequest{Model: "acct-alias-41", BodyBytes: 4000, MaxTokens: 1000} + + _, priced := svc.EstimateInflightReservation(ctx, apiKey, req) + require.False(t, priced) + snap.set(groupID, PlatformAnthropic, []Account{{ID: 9, Platform: PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"acct-*": "claude-sonnet-4-5"}}}}) + est, priced := svc.EstimateInflightReservation(ctx, apiKey, req) + require.True(t, priced, "new mapping (incl. wildcard) visible on next request") + require.Greater(t, est, 0.0) +} From 475c0839c6fd1c23cc7b0f45452608e7bc518353 Mon Sep 17 00:00:00 2001 From: William Drake Date: Mon, 28 Sep 2026 17:08:27 -0400 Subject: [PATCH 06/17] style: gofmt Co-Authored-By: Claude Opus 5.5 (1M context) --- backend/internal/service/billing_inflight_reservation_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/internal/service/billing_inflight_reservation_test.go b/backend/internal/service/billing_inflight_reservation_test.go index dc02072eb..fa9281823 100644 --- a/backend/internal/service/billing_inflight_reservation_test.go +++ b/backend/internal/service/billing_inflight_reservation_test.go @@ -5,8 +5,8 @@ package service import ( "context" "fmt" - "runtime" "math" + "runtime" "sync" "sync/atomic" "testing" From a60a29549f488a854966aaec9541abbe006cac22 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 29 Sep 2026 08:28:45 +0000 Subject: [PATCH 07/17] chore: sync VERSION to 0.2.10 [skip ci] --- backend/cmd/server/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index 1866a362b..13dead7eb 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.2.9 +0.2.10 From 196b47757a3132aaf1c17240b0317798952a9cae Mon Sep 17 00:00:00 2001 From: William Drake Date: Tue, 29 Sep 2026 11:41:33 -0400 Subject: [PATCH 08/17] feat(claude): redeem native limit resets with server-selected grant POST /admin/accounts/:id/claude/reset-credits/redeem (Idempotency-Key required, same middleware chain as the Codex reset-quota route). The server re-queries eligibility and claims only the upstream next_grant_id when it is redeemable; grant/org IDs never reach the client. Claims are serialized by account and organization Redis leases, and a durable per-organization fence in the idempotency table blocks further redemption after an unconfirmed outcome (settles after 24h). Ported from upstream PR #7591. Co-authored-by: korkin25 Co-Authored-By: Claude Opus 5.5 (1M context) --- backend/cmd/server/wire_gen.go | 4 +- .../handler/admin/claude_reset_handler.go | 22 ++ .../admin/claude_reset_handler_test.go | 56 +++ backend/internal/server/routes/admin.go | 2 + .../routes/claude_reset_redeem_routes_test.go | 57 +++ .../internal/service/claude_reset_credits.go | 38 +- .../internal/service/claude_reset_redeem.go | 321 +++++++++++++++++ .../service/claude_reset_redeem_test.go | 329 ++++++++++++++++++ backend/internal/service/wire.go | 10 +- 9 files changed, 833 insertions(+), 6 deletions(-) create mode 100644 backend/internal/handler/admin/claude_reset_handler_test.go create mode 100644 backend/internal/server/routes/claude_reset_redeem_routes_test.go create mode 100644 backend/internal/service/claude_reset_redeem.go create mode 100644 backend/internal/service/claude_reset_redeem_test.go diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 4394db413..1eda60da7 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -288,7 +288,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { auditLogHandler := admin.NewAuditLogHandler(auditLogService, totpService) upstreamBillingProbeService := service.ProvideUpstreamBillingProbeService(accountRepository, accountTestService, settingService, leaderLockCache, db) openCodeGoUsageService := service.ProvideOpenCodeGoUsageService(accountRepository, httpUpstream, settingService, leaderLockCache, db) - claudeResetCreditService := service.NewClaudeResetCreditService(accountRepository, claudeTokenProvider, proxyRepository, settingService) + idempotencyCoordinator := service.ProvideIdempotencyCoordinator(idempotencyRepository, configConfig) + claudeResetCreditService := service.ProvideClaudeResetCreditService(accountRepository, claudeTokenProvider, proxyRepository, settingService, idempotencyCoordinator, leaderLockCache) adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, adminAnnouncementHandler, dataManagementHandler, backupHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, grokOAuthHandler, cnProviderHandler, proxyHandler, adminRedeemHandler, promoHandler, settingHandler, opsHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler, errorPassthroughHandler, tlsFingerprintProfileHandler, pluginHandler, adminAPIKeyHandler, scheduledTestHandler, channelHandler, channelMonitorHandler, channelMonitorRequestTemplateHandler, contentModerationHandler, promptAdminHandler, paymentHandler, affiliateHandler, complianceHandler, auditLogHandler, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, claudeResetCreditService) usageRecordWorkerPool := service.NewUsageRecordWorkerPool(configConfig) userMsgQueueCache := repository.NewUserMsgQueueCache(redisClient) @@ -322,7 +323,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { batchImageDownloadService := service.NewBatchImageDownloadService(batchImageRepository, accountRepository, batchImageDownloadLimiter, configConfig) batchImageCleanupService := service.ProvideBatchImageCleanupService(batchImageRepository, accountRepository, configConfig) batchImageHandler := handler.ProvideBatchImageHandler(batchImagePublicService, batchImageDownloadService, batchImageCleanupService, openAIGatewayHandler) - idempotencyCoordinator := service.ProvideIdempotencyCoordinator(idempotencyRepository, configConfig) idempotencyCleanupService := service.ProvideIdempotencyCleanupService(idempotencyRepository, configConfig) openAIQuotaAutoResetService := service.ProvideOpenAIQuotaAutoResetService(accountRepository, openAIQuotaService, rateLimitService, idempotencyCoordinator, auditLogService, settingService, leaderLockCache) handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, channelMonitorV2Handler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, passkeyHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, modelPlazaHandler, asyncImageHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService, openAIQuotaAutoResetService) diff --git a/backend/internal/handler/admin/claude_reset_handler.go b/backend/internal/handler/admin/claude_reset_handler.go index 8ec456444..35cd8e559 100644 --- a/backend/internal/handler/admin/claude_reset_handler.go +++ b/backend/internal/handler/admin/claude_reset_handler.go @@ -10,6 +10,7 @@ import ( type claudeResetReader interface { Query(context.Context, int64) (*service.ClaudeResetCredits, error) + Redeem(context.Context, int64, string) (*service.ClaudeResetOutcome, error) } func (h *AccountHandler) SetClaudeResetCreditService(s *service.ClaudeResetCreditService) { @@ -32,3 +33,24 @@ func (h *AccountHandler) ClaudeResetCredits(c *gin.Context) { } response.Success(c, status) } + +// RedeemClaudeResetCredit consumes the upstream next reset credit. The request has +// no body: the server picks the grant; the Idempotency-Key header identifies one +// operator confirmation and replays its outcome. +func (h *AccountHandler) RedeemClaudeResetCredit(c *gin.Context) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil || id <= 0 { + response.BadRequest(c, "Invalid account ID") + return + } + if h.claudeResetCredits == nil { + response.Error(c, 503, "Claude reset service unavailable") + return + } + result, err := h.claudeResetCredits.Redeem(c.Request.Context(), id, c.GetHeader("Idempotency-Key")) + if err != nil { + response.ErrorFrom(c, err) + return + } + response.Success(c, result) +} diff --git a/backend/internal/handler/admin/claude_reset_handler_test.go b/backend/internal/handler/admin/claude_reset_handler_test.go new file mode 100644 index 000000000..9b28650fe --- /dev/null +++ b/backend/internal/handler/admin/claude_reset_handler_test.go @@ -0,0 +1,56 @@ +package admin + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type claudeResetHandlerStub struct { + key string + calls int +} + +func (s *claudeResetHandlerStub) Query(context.Context, int64) (*service.ClaudeResetCredits, error) { + return &service.ClaudeResetCredits{Credits: []service.ClaudeResetCredit{}}, nil +} + +func (s *claudeResetHandlerStub) Redeem(_ context.Context, _ int64, key string) (*service.ClaudeResetOutcome, error) { + s.calls++ + s.key = key + if key == "" { + return nil, service.ErrIdempotencyKeyRequired + } + return &service.ClaudeResetOutcome{Outcome: "reset", Cleared: []string{"five_hour"}}, nil +} + +func TestClaudeResetHandlerRedeemContract(t *testing.T) { + gin.SetMode(gin.TestMode) + stub := &claudeResetHandlerStub{} + h := &AccountHandler{claudeResetCredits: stub} + r := gin.New() + r.POST("/accounts/:id/claude/reset-credits/redeem", h.RedeemClaudeResetCredit) + + req := httptest.NewRequest(http.MethodPost, "/accounts/1/claude/reset-credits/redeem", nil) + req.Header.Set("Idempotency-Key", "same-operation") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, http.StatusOK, w.Code) + require.Equal(t, "same-operation", stub.key) + require.Contains(t, w.Body.String(), `"outcome":"reset"`) + + w = httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/accounts/1/claude/reset-credits/redeem", nil)) + require.Equal(t, http.StatusBadRequest, w.Code) + require.Contains(t, w.Body.String(), "IDEMPOTENCY_KEY_REQUIRED") + + w = httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/accounts/abc/claude/reset-credits/redeem", nil)) + require.Equal(t, http.StatusBadRequest, w.Code) + require.Equal(t, 2, stub.calls) +} diff --git a/backend/internal/server/routes/admin.go b/backend/internal/server/routes/admin.go index ab28619b6..315fc20e4 100644 --- a/backend/internal/server/routes/admin.go +++ b/backend/internal/server/routes/admin.go @@ -368,6 +368,8 @@ func registerAccountRoutes(admin *gin.RouterGroup, h *handler.Handlers, stepUpAu accounts.PUT("/opencode-go-usage/settings", h.Admin.Account.UpdateOpenCodeGoUsageSettings) accounts.GET("/:id", h.Admin.Account.GetByID) accounts.GET("/:id/claude/reset-credits", h.Admin.Account.ClaudeResetCredits) + // Same protection as the Codex reset-quota route (admin auth, audit, compliance guard). + accounts.POST("/:id/claude/reset-credits/redeem", h.Admin.Account.RedeemClaudeResetCredit) accounts.POST("", h.Admin.Account.Create) accounts.POST("/:id/duplicate", h.Admin.Account.Duplicate) accounts.POST("/check-mixed-channel", h.Admin.Account.CheckMixedChannel) diff --git a/backend/internal/server/routes/claude_reset_redeem_routes_test.go b/backend/internal/server/routes/claude_reset_redeem_routes_test.go new file mode 100644 index 000000000..b4a9e7ada --- /dev/null +++ b/backend/internal/server/routes/claude_reset_redeem_routes_test.go @@ -0,0 +1,57 @@ +package routes + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/handler" + adminhandler "github.com/Wei-Shaw/sub2api/internal/handler/admin" + servermiddleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// The Claude redeem route consumes an irreversible credit just like the Codex +// reset-quota route, so it must sit behind exactly the same middleware chain. +func TestClaudeResetRedeemRouteMatchesCodexResetProtection(t *testing.T) { + gin.SetMode(gin.TestMode) + router := gin.New() + handlers := &handler.Handlers{Admin: &handler.AdminHandlers{Account: &adminhandler.AccountHandler{}, OpenAIOAuth: &adminhandler.OpenAIOAuthHandler{}}} + chains := map[string][]string{} + adminAuth := servermiddleware.AdminAuthMiddleware(func(c *gin.Context) { + names := c.HandlerNames() + chains[c.FullPath()] = names[:len(names)-1] + if c.GetHeader("Authorization") == "" { + servermiddleware.AbortWithError(c, http.StatusUnauthorized, "UNAUTHORIZED", "Authorization required") + return + } + servermiddleware.AbortWithError(c, http.StatusForbidden, "FORBIDDEN", "Admin access required") + }) + auditLog := servermiddleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }) + stepUp := servermiddleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() }) + RegisterAdminRoutes(router.Group("/api/v1"), handlers, adminAuth, auditLog, stepUp, nil, nil) + + codex := "/api/v1/admin/openai/accounts/1/reset-quota" + claude := "/api/v1/admin/accounts/1/claude/reset-credits/redeem" + for _, path := range []string{codex, claude} { + for _, auth := range []string{"", "Bearer user-token"} { + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, path, nil) + if auth != "" { + request.Header.Set("Authorization", auth) + } + router.ServeHTTP(recorder, request) + if auth == "" { + require.Equal(t, http.StatusUnauthorized, recorder.Code, path) + } else { + require.Equal(t, http.StatusForbidden, recorder.Code, path) + } + } + } + codexChain := chains["/api/v1/admin/openai/accounts/:id/reset-quota"] + claudeChain := chains["/api/v1/admin/accounts/:id/claude/reset-credits/redeem"] + require.NotEmpty(t, codexChain) + require.Equal(t, strings.Join(codexChain, "\n"), strings.Join(claudeChain, "\n")) +} diff --git a/backend/internal/service/claude_reset_credits.go b/backend/internal/service/claude_reset_credits.go index 059aaa4b5..62b024279 100644 --- a/backend/internal/service/claude_reset_credits.go +++ b/backend/internal/service/claude_reset_credits.go @@ -76,6 +76,10 @@ type ClaudeResetCreditService struct { settings *SettingService do func(*http.Request, string) (*http.Response, error) now func() time.Time + + // Redemption only; both are mandatory and never fail open. + idempotency *IdempotencyCoordinator + locks LeaderLockCache } func NewClaudeResetCreditService(accounts AccountRepository, tokens *ClaudeTokenProvider, proxies ProxyRepository, settings *SettingService) *ClaudeResetCreditService { @@ -139,6 +143,16 @@ func (s *ClaudeResetCreditService) query(ctx context.Context, id int64) (*Claude if err != nil { return nil, err } + block, err := s.fetchBlock(ctx, token, proxy) + if err != nil { + return nil, err + } + return projectClaudeResetCredits(block, s.now()), nil +} + +// fetchBlock returns the raw cedar_ember block (nil when absent). It carries grant +// IDs, so it must never leave the service. +func (s *ClaudeResetCreditService) fetchBlock(ctx context.Context, token, proxy string) (*claudeResetBlock, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, claudeResetUsageURL, nil) if err != nil { return nil, err @@ -166,7 +180,7 @@ func (s *ClaudeResetCreditService) query(ctx context.Context, id int64) (*Claude return nil, infraerrors.New(http.StatusBadGateway, "CLAUDE_RESET_STATUS_INVALID", "invalid reset grants") } } - return projectClaudeResetCredits(block, s.now()), nil + return block, nil } func (s *ClaudeResetCreditService) Query(ctx context.Context, id int64) (*ClaudeResetCredits, error) { @@ -184,11 +198,11 @@ func projectClaudeResetCredits(b *claudeResetBlock, now time.Time) *ClaudeResetC } r.WeeklyResetsAt = b.WeeklyResetsAt for _, g := range b.Grants { - if !claudeResetGrantIDPattern.MatchString(g.ID) || len(g.Clears) == 0 || g.ResetsLeft <= 0 || g.Paused || (g.StartsAt != nil && now.Before(*g.StartsAt)) || (g.EndsAt != nil && !now.Before(*g.EndsAt)) { + if !claudeResetGrantHeld(g, now) { continue } requires := g.UseRequiresLimit == nil || *g.UseRequiresLimit - usable := b.Eligible && g.UsableNow && g.ID == b.NextGrantID && (!requires || b.AtLimit) && len(g.Blocking) == 0 && (b.CooldownUntil == nil || !now.Before(*b.CooldownUntil)) + usable := claudeResetGrantRedeemable(b, g, now) used := map[string]float64{} for k, v := range g.PercentUsed { if v >= 0 && v <= 100 { @@ -202,3 +216,21 @@ func projectClaudeResetCredits(b *claudeResetBlock, now time.Time) *ClaudeResetC } return r } + +// claudeResetGrantHeld reports whether a grant is a live, well-formed credit. +func claudeResetGrantHeld(g claudeResetGrant, now time.Time) bool { + return claudeResetGrantIDPattern.MatchString(g.ID) && len(g.Clears) > 0 && g.ResetsLeft > 0 && !g.Paused && + (g.StartsAt == nil || !now.Before(*g.StartsAt)) && (g.EndsAt == nil || now.Before(*g.EndsAt)) +} + +// claudeResetGrantRedeemable is the single gate shared by the query projection and +// redemption: only the upstream next grant, usable now, unblocked, outside cooldown, +// and with its at-limit requirement satisfied. +func claudeResetGrantRedeemable(b *claudeResetBlock, g claudeResetGrant, now time.Time) bool { + if b == nil || !claudeResetGrantHeld(g, now) { + return false + } + requires := g.UseRequiresLimit == nil || *g.UseRequiresLimit + return b.Eligible && g.UsableNow && g.ID == b.NextGrantID && (!requires || b.AtLimit) && len(g.Blocking) == 0 && + (b.CooldownUntil == nil || !now.Before(*b.CooldownUntil)) +} diff --git a/backend/internal/service/claude_reset_redeem.go b/backend/internal/service/claude_reset_redeem.go new file mode 100644 index 000000000..5ac5e34a4 --- /dev/null +++ b/backend/internal/service/claude_reset_redeem.go @@ -0,0 +1,321 @@ +package service + +// Manual redemption of Claude native limit resets. The claim protocol (idempotent +// operation, account + organization leases, durable organization fence) is ported +// from upstream PR #7591 by korkin25, adapted so the server alone selects the grant. + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "regexp" + "strings" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/google/uuid" +) + +const ( + claudeResetOperationScope = "claude_reset_redeem" + claudeResetFenceScope = "claude_reset_org_fence" + claudeResetProfileURL = "https://api.anthropic.com/api/oauth/profile" + claudeResetRedeemURLFmt = "https://api.anthropic.com/api/organizations/%s/reset_rate_limits" + claudeResetLeaseTTL = 90 * time.Second + claudeResetRecordTTL = 365 * 24 * time.Hour + // An unconfirmed claim blocks every further redemption of the organization until + // the upstream outcome has certainly settled; after that a fresh query is + // authoritative again (a consumed credit shows up as a lower count or cooldown). + claudeResetUnknownFenceTTL = 24 * time.Hour + + ClaudeResetOutcomeReset = "reset" + ClaudeResetOutcomeAlreadyUsed = "already_used" + ClaudeResetOutcomeNotLimited = "not_limited" + ClaudeResetOutcomeCooldown = "cooldown" + ClaudeResetOutcomeIneligible = "ineligible" + ClaudeResetOutcomeUnknown = "unknown" +) + +var claudeResetReasonPattern = regexp.MustCompile(`^[a-z0-9_]{1,64}$`) + +// ClaudeResetOutcome is the sanitized redemption result. It never carries grant, +// organization, or upstream request IDs. +type ClaudeResetOutcome struct { + Outcome string `json:"outcome"` + Reason string `json:"reason,omitempty"` + Cleared []string `json:"cleared,omitempty"` + CooldownUntil *time.Time `json:"cooldown_until,omitempty"` + Credits *ClaudeResetCredits `json:"credits,omitempty"` + Replayed bool `json:"replayed"` +} + +// claudeResetFence is stored in the idempotency table, one row per provider +// organization, so duplicate local accounts share it and account edits cannot erase it. +type claudeResetFence struct { + Operation string `json:"operation"` + Outcome string `json:"outcome"` + Reason string `json:"reason,omitempty"` + At time.Time `json:"at"` +} + +// ConfigureRedemption enables Redeem. Without both stores Redeem refuses to run. +func (s *ClaudeResetCreditService) ConfigureRedemption(idem *IdempotencyCoordinator, locks LeaderLockCache) { + s.idempotency = idem + s.locks = locks +} + +// Redeem consumes the upstream next reset grant of the account, if and only if a +// fresh query shows it redeemable. key identifies one operator confirmation: the +// same key replays the stored outcome and never sends a second claim. +func (s *ClaudeResetCreditService) Redeem(ctx context.Context, id int64, key string) (*ClaudeResetOutcome, error) { + if strings.TrimSpace(key) == "" { + return nil, ErrIdempotencyKeyRequired + } + normalized, err := NormalizeIdempotencyKey(key) + if err != nil { + return nil, err + } + if s.idempotency == nil || s.idempotency.repo == nil || s.locks == nil { + return nil, ErrIdempotencyStoreUnavail + } + // Validate before entering the idempotency scope so a deleted or converted + // account never replays. No token is stored anywhere. + if _, _, _, err = s.account(ctx, id); err != nil { + return nil, err + } + operation := HashIdempotencyKey(fmt.Sprintf("claude-reset:%d:%s", id, normalized)) + result, err := s.idempotency.Execute(ctx, IdempotencyExecuteOptions{ + Scope: claudeResetOperationScope, ActorScope: fmt.Sprintf("account:%d", id), Method: http.MethodPost, + Route: "/admin/accounts/:id/claude/reset-credits/redeem", IdempotencyKey: operation, + Payload: map[string]any{"account_id": id}, TTL: claudeResetRecordTTL, RequireKey: true, ExecutionTimeout: 60 * time.Second, + }, func(exec context.Context) (any, error) { return s.redeemOnce(exec, id, operation) }) + if err != nil { + return nil, err + } + raw, err := json.Marshal(result.Data) + if err != nil { + return nil, err + } + var outcome ClaudeResetOutcome + if err = json.Unmarshal(raw, &outcome); err != nil { + return nil, err + } + outcome.Replayed = outcome.Replayed || result.Replayed + return &outcome, nil +} + +func (s *ClaudeResetCreditService) lease(ctx context.Context, key, owner string) (func(), error) { + acquired, err := s.locks.TryAcquireLeaderLock(ctx, key, owner, claudeResetLeaseTTL) + if err != nil { + return nil, infraerrors.ServiceUnavailable("CLAUDE_RESET_LOCK_UNAVAILABLE", "reset coordination unavailable") + } + if !acquired { + return nil, infraerrors.Conflict("CLAUDE_RESET_BUSY", "another reset is in progress") + } + return func() { + release, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + _ = s.locks.ReleaseLeaderLock(release, key, owner) + }, nil +} + +func (s *ClaudeResetCreditService) redeemOnce(ctx context.Context, id int64, operation string) (*ClaudeResetOutcome, error) { + owner := uuid.NewString() + release, err := s.lease(ctx, fmt.Sprintf("claude:reset-credit:account:%d", id), owner) + if err != nil { + return nil, err + } + defer release() + _, token, proxy, err := s.account(ctx, id) + if err != nil { + return nil, err + } + org, err := s.organization(ctx, token, proxy) + if err != nil { + return nil, err + } + orgHash := HashIdempotencyKey("claude-org:" + org) + releaseOrg, err := s.lease(ctx, "claude:reset-credit:organization:"+orgHash, owner) + if err != nil { + return nil, err + } + defer releaseOrg() + + fence, err := s.loadFence(ctx, orgHash) + if err != nil { + return nil, err + } + var prior claudeResetFence + if fence.ResponseBody != nil { + if json.Unmarshal([]byte(*fence.ResponseBody), &prior) != nil || prior.Operation == "" { + return nil, infraerrors.Conflict("CLAUDE_RESET_UNRESOLVED", "previous reset requires reconciliation") + } + if prior.Operation == operation { + // A crashed or interrupted attempt of this same confirmation: never resend. + return &ClaudeResetOutcome{Outcome: prior.Outcome, Reason: prior.Reason, Replayed: true}, nil + } + if prior.Outcome == ClaudeResetOutcomeUnknown && s.now().Before(prior.At.Add(claudeResetUnknownFenceTTL)) { + return nil, infraerrors.Conflict("CLAUDE_RESET_UNRESOLVED", "previous reset outcome is unconfirmed; redemption is blocked for now") + } + } + + // Fresh eligibility check right before the irreversible call; the server alone + // picks the grant, and only the upstream next grant can qualify. + block, err := s.fetchBlock(ctx, token, proxy) + if err != nil { + return nil, err + } + var grant *claudeResetGrant + if block != nil { + for i := range block.Grants { + if block.Grants[i].ID == block.NextGrantID && claudeResetGrantRedeemable(block, block.Grants[i], s.now()) { + grant = &block.Grants[i] + break + } + } + } + if grant == nil { + return nil, infraerrors.Conflict("CLAUDE_RESET_NOT_AVAILABLE", "no reset is redeemable right now") + } + + // Persist the unknown marker before sending: a crash after this point blocks + // both a resend and another credit until the fence settles. + marker := claudeResetFence{Operation: operation, Outcome: ClaudeResetOutcomeUnknown, Reason: "claim_unconfirmed", At: s.now().UTC()} + if err = s.persistFence(ctx, fence.ID, marker); err != nil { + return nil, err + } + outcome := s.claim(ctx, token, proxy, org, grant.ID, operation) + marker.Outcome, marker.Reason = outcome.Outcome, outcome.Reason + persistCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) + persistErr := s.persistFence(persistCtx, fence.ID, marker) + cancel() + if persistErr != nil { + return &ClaudeResetOutcome{Outcome: ClaudeResetOutcomeUnknown, Reason: "result_persistence_failed"}, nil + } + if outcome.Outcome != ClaudeResetOutcomeUnknown { + if fresh, e := s.fetchBlock(ctx, token, proxy); e == nil { + outcome.Credits = projectClaudeResetCredits(fresh, s.now()) + } + } + return outcome, nil +} + +func (s *ClaudeResetCreditService) loadFence(ctx context.Context, orgHash string) (*IdempotencyRecord, error) { + repo := s.idempotency.repo + fence, err := repo.GetByScopeAndKeyHash(ctx, claudeResetFenceScope, orgHash) + if err != nil { + return nil, ErrIdempotencyStoreUnavail + } + if fence != nil { + return fence, nil + } + row := &IdempotencyRecord{Scope: claudeResetFenceScope, IdempotencyKeyHash: orgHash, RequestFingerprint: orgHash, Status: IdempotencyStatusProcessing, ExpiresAt: s.now().Add(claudeResetRecordTTL)} + if _, err = repo.CreateProcessing(ctx, row); err != nil { + return nil, ErrIdempotencyStoreUnavail + } + fence, err = repo.GetByScopeAndKeyHash(ctx, claudeResetFenceScope, orgHash) + if err != nil || fence == nil { + return nil, ErrIdempotencyStoreUnavail + } + return fence, nil +} + +func (s *ClaudeResetCreditService) persistFence(ctx context.Context, id int64, marker claudeResetFence) error { + body, err := json.Marshal(marker) + if err != nil { + return err + } + if err = s.idempotency.repo.MarkSucceeded(ctx, id, http.StatusOK, string(body), s.now().Add(claudeResetRecordTTL)); err != nil { + return ErrIdempotencyStoreUnavail + } + return nil +} + +func (s *ClaudeResetCreditService) organization(ctx context.Context, token, proxy string) (string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, claudeResetProfileURL, nil) + if err != nil { + return "", err + } + s.headers(ctx, req, token) + resp, err := s.do(req, proxy) + if err != nil { + return "", infraerrors.ServiceUnavailable("CLAUDE_RESET_PROFILE_FAILED", "OAuth profile unavailable") + } + defer func() { _ = resp.Body.Close() }() + var body struct { + Organization struct { + UUID string `json:"uuid"` + } `json:"organization"` + } + if resp.StatusCode != http.StatusOK || json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&body) != nil { + return "", infraerrors.New(http.StatusBadGateway, "CLAUDE_RESET_PROFILE_FAILED", "OAuth profile unavailable") + } + parsed, err := uuid.Parse(body.Organization.UUID) + if err != nil || parsed == uuid.Nil { + return "", infraerrors.New(http.StatusBadGateway, "CLAUDE_RESET_ORGANIZATION_INVALID", "OAuth organization unavailable") + } + return parsed.String(), nil +} + +// claim sends the single irreversible request. Anything but a well-formed, known +// result is reported as unknown so the fence blocks a blind retry. +func (s *ClaudeResetCreditService) claim(ctx context.Context, token, proxy, org, grantID, operation string) *ClaudeResetOutcome { + unknown := &ClaudeResetOutcome{Outcome: ClaudeResetOutcomeUnknown, Reason: "claim_unconfirmed"} + // Deterministic per confirmation (64 hex chars, matches ^[A-Za-z0-9_-]{1,64}$). + body, err := json.Marshal(map[string]string{"program": "cedar_ember", "grant_id": grantID, "request_id": operation}) + if err != nil { + return unknown + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf(claudeResetRedeemURLFmt, org), bytes.NewReader(body)) + if err != nil { + return unknown + } + s.headers(ctx, req, token) + resp, err := s.do(req, proxy) + if err != nil { + return unknown + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { + return &ClaudeResetOutcome{Outcome: ClaudeResetOutcomeIneligible, Reason: "authorization_rejected"} + } + if resp.StatusCode != http.StatusOK { + return unknown + } + var result struct { + Result string `json:"result"` + Reason string `json:"reason"` + Cleared []string `json:"cleared"` + CooldownUntil *time.Time `json:"cooldown_until"` + } + if json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&result) != nil { + return unknown + } + reason := "" + if claudeResetReasonPattern.MatchString(result.Reason) { + reason = result.Reason + } + if reason == "stamp_indeterminate" || reason == "reset_unconfirmed" { + return unknown + } + switch result.Result { + case ClaudeResetOutcomeReset, ClaudeResetOutcomeAlreadyUsed, ClaudeResetOutcomeNotLimited, ClaudeResetOutcomeCooldown, ClaudeResetOutcomeIneligible: + out := &ClaudeResetOutcome{Outcome: result.Result, Reason: reason, CooldownUntil: result.CooldownUntil} + for _, w := range result.Cleared { + if claudeResetReasonPattern.MatchString(w) { + out.Cleared = append(out.Cleared, w) + } + } + return out + case "unavailable": + if reason == "" { + reason = "upstream_unavailable" + } + return &ClaudeResetOutcome{Outcome: ClaudeResetOutcomeUnknown, Reason: reason} + default: + return unknown + } +} diff --git a/backend/internal/service/claude_reset_redeem_test.go b/backend/internal/service/claude_reset_redeem_test.go new file mode 100644 index 000000000..8a7da9424 --- /dev/null +++ b/backend/internal/service/claude_reset_redeem_test.go @@ -0,0 +1,329 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "strings" + "sync" + "testing" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +const redeemTestOrg = "11111111-1111-4111-8111-111111111111" + +type redeemAccountsStub struct{} + +func (redeemAccountsStub) GetByID(_ context.Context, id int64) (*Account, error) { + return &Account{ID: id, Platform: PlatformAnthropic, Type: AccountTypeOAuth, Credentials: map[string]any{"scope": "user:profile"}}, nil +} + +type redeemLeaseStub struct { + mu sync.Mutex + keys map[string]bool + fail bool +} + +func (s *redeemLeaseStub) TryAcquireLeaderLock(_ context.Context, key, _ string, _ time.Duration) (bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.fail { + return false, errors.New("unavailable") + } + if s.keys == nil { + s.keys = map[string]bool{} + } + if s.keys[key] { + return false, nil + } + s.keys[key] = true + return true, nil +} + +func (s *redeemLeaseStub) ReleaseLeaderLock(_ context.Context, key, _ string) error { + s.mu.Lock() + defer s.mu.Unlock() + delete(s.keys, key) + return nil +} + +type redeemFake struct { + mu sync.Mutex + status string // usage body + claim string // POST body, or "network-error" + claimHTTP int + posts []map[string]string + gate chan struct{} // when set, POST blocks until closed + entered chan struct{} +} + +func (f *redeemFake) postCount() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.posts) +} + +const redeemableStatus = `{"cedar_ember":{"eligible":true,"at_limit":true,"next_grant_id":"grant_next","grants":[` + + `{"id":"grant_other","resets_left":1,"usable_now":true,"use_requires_limit":false,"clears":["five_hour"]},` + + `{"id":"grant_next","resets_left":2,"usable_now":true,"use_requires_limit":true,"clears":["five_hour","seven_day"]}]}}` + +func newRedeemService(t *testing.T, f *redeemFake) (*ClaudeResetCreditService, *inMemoryIdempotencyRepo, *redeemLeaseStub) { + t.Helper() + repo := newInMemoryIdempotencyRepo() + cfg := DefaultIdempotencyConfig() + cfg.FailedRetryBackoff = 0 + locks := &redeemLeaseStub{} + s := &ClaudeResetCreditService{accounts: redeemAccountsStub{}, tokens: resetTokenStub{}, now: time.Now} + s.ConfigureRedemption(NewIdempotencyCoordinator(repo, cfg), locks) + if f.status == "" { + f.status = redeemableStatus + } + s.do = func(r *http.Request, _ string) (*http.Response, error) { + require.Equal(t, "Bearer synthetic-token", r.Header.Get("Authorization")) + code := http.StatusOK + var body string + switch { + case r.Method == http.MethodGet && r.URL.String() == claudeResetProfileURL: + body = `{"organization":{"uuid":"` + redeemTestOrg + `"}}` + case r.Method == http.MethodGet && r.URL.String() == claudeResetUsageURL: + f.mu.Lock() + body = f.status + f.mu.Unlock() + case r.Method == http.MethodPost: + require.Equal(t, "https://api.anthropic.com/api/organizations/"+redeemTestOrg+"/reset_rate_limits", r.URL.String()) + var payload map[string]string + require.NoError(t, json.NewDecoder(r.Body).Decode(&payload)) + require.Regexp(t, `^[A-Za-z0-9_-]{1,64}$`, payload["request_id"]) + f.mu.Lock() + f.posts = append(f.posts, payload) + f.mu.Unlock() + if f.entered != nil { + f.entered <- struct{}{} + } + if f.gate != nil { + <-f.gate + } + if f.claim == "network-error" { + return nil, errors.New("timeout private upstream details") + } + body = f.claim + if f.claimHTTP != 0 { + code = f.claimHTTP + } + default: + t.Fatalf("unexpected upstream request %s %s", r.Method, r.URL) + } + return &http.Response{StatusCode: code, Body: io.NopCloser(strings.NewReader(body))}, nil + } + return s, repo, locks +} + +func TestClaudeResetRedeemHappyPathServerPicksNextGrant(t *testing.T) { + f := &redeemFake{claim: `{"result":"reset","resets_left":1,"cleared":["five_hour","seven_day"]}`} + s, _, _ := newRedeemService(t, f) + out, err := s.Redeem(context.Background(), 1, "op-1") + require.NoError(t, err) + require.Equal(t, ClaudeResetOutcomeReset, out.Outcome) + require.False(t, out.Replayed) + require.Equal(t, []string{"five_hour", "seven_day"}, out.Cleared) + require.NotNil(t, out.Credits) + require.Equal(t, 1, f.postCount()) + require.Equal(t, "grant_next", f.posts[0]["grant_id"]) + require.Equal(t, "cedar_ember", f.posts[0]["program"]) + + raw, err := json.Marshal(out) + require.NoError(t, err) + for _, secret := range []string{"grant_next", "grant_other", redeemTestOrg, "synthetic-token", f.posts[0]["request_id"], `"id"`} { + require.NotContains(t, string(raw), secret) + } +} + +func TestClaudeResetRedeemNonRedeemableSendsNoPost(t *testing.T) { + future := time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + cases := map[string]string{ + "not at limit": strings.Replace(redeemableStatus, `"at_limit":true`, `"at_limit":false`, 1), + "ineligible": strings.Replace(redeemableStatus, `"eligible":true`, `"eligible":false`, 1), + "cooldown": strings.Replace(redeemableStatus, `"eligible":true,`, `"eligible":true,"cooldown_until":"`+future+`",`, 1), + "no next grant": strings.Replace(redeemableStatus, `"next_grant_id":"grant_next"`, `"next_grant_id":"missing"`, 1), + "blocked": strings.Replace(redeemableStatus, `"clears":["five_hour","seven_day"]`, `"clears":["five_hour","seven_day"],"blocking":["x"]`, 1), + "paused": strings.Replace(redeemableStatus, `"id":"grant_next",`, `"id":"grant_next","paused":true,`, 1), + "not usable now": strings.Replace(redeemableStatus, `"id":"grant_next","resets_left":2,"usable_now":true`, `"id":"grant_next","resets_left":2,"usable_now":false`, 1), + "expired": strings.Replace(redeemableStatus, `"id":"grant_next",`, `"id":"grant_next","ends_at":"2000-01-01T00:00:00Z",`, 1), + "not started": strings.Replace(redeemableStatus, `"id":"grant_next",`, `"id":"grant_next","starts_at":"`+future+`",`, 1), + "no resets left": strings.Replace(redeemableStatus, `"id":"grant_next","resets_left":2`, `"id":"grant_next","resets_left":0`, 1), + "no program": `{"cedar_ember":null}`, + } + for name, status := range cases { + t.Run(name, func(t *testing.T) { + require.NotEqual(t, redeemableStatus, status) + f := &redeemFake{status: status, claim: `{"result":"reset"}`} + s, _, _ := newRedeemService(t, f) + _, err := s.Redeem(context.Background(), 1, "op-1") + require.Error(t, err) + require.Equal(t, "CLAUDE_RESET_NOT_AVAILABLE", infraerrors.Reason(err)) + require.Zero(t, f.postCount()) + }) + } +} + +func TestClaudeResetRedeemRequiresKeyAndStores(t *testing.T) { + f := &redeemFake{claim: `{"result":"reset"}`} + s, _, locks := newRedeemService(t, f) + _, err := s.Redeem(context.Background(), 1, " ") + require.ErrorIs(t, err, ErrIdempotencyKeyRequired) + locks.fail = true + _, err = s.Redeem(context.Background(), 1, "op-1") + require.Error(t, err) + unconfigured := &ClaudeResetCreditService{accounts: redeemAccountsStub{}, tokens: resetTokenStub{}, now: time.Now} + _, err = unconfigured.Redeem(context.Background(), 1, "op-2") + require.ErrorIs(t, err, ErrIdempotencyStoreUnavail) + require.Zero(t, f.postCount()) +} + +func TestClaudeResetRedeemSameKeyReplaysWithoutSecondPost(t *testing.T) { + f := &redeemFake{claim: `{"result":"reset"}`} + s, _, _ := newRedeemService(t, f) + first, err := s.Redeem(context.Background(), 1, "op-1") + require.NoError(t, err) + again, err := s.Redeem(context.Background(), 1, "op-1") + require.NoError(t, err) + require.True(t, again.Replayed) + require.Equal(t, first.Outcome, again.Outcome) + require.Equal(t, 1, f.postCount()) + + // A new confirmation is a new operation with a new upstream request_id. + _, err = s.Redeem(context.Background(), 1, "op-2") + require.NoError(t, err) + require.Equal(t, 2, f.postCount()) + require.NotEqual(t, f.posts[0]["request_id"], f.posts[1]["request_id"]) +} + +func TestClaudeResetRedeemDuplicateOrgAccountsConcurrentOnlyOnePost(t *testing.T) { + f := &redeemFake{claim: `{"result":"reset"}`, gate: make(chan struct{}), entered: make(chan struct{}, 2)} + s, _, _ := newRedeemService(t, f) + type res struct { + out *ClaudeResetOutcome + err error + } + first := make(chan res, 1) + go func() { + out, err := s.Redeem(context.Background(), 1, "account-one") + first <- res{out, err} + }() + <-f.entered // account 1 holds the organization lease and is mid-claim + _, err := s.Redeem(context.Background(), 2, "account-two") + require.Error(t, err) + require.Equal(t, "CLAUDE_RESET_BUSY", infraerrors.Reason(err)) + close(f.gate) + r := <-first + require.NoError(t, r.err) + require.Equal(t, ClaudeResetOutcomeReset, r.out.Outcome) + require.Equal(t, 1, f.postCount()) +} + +func TestClaudeResetRedeemUnknownOutcomeFencesOrganization(t *testing.T) { + for _, claim := range []string{"network-error", `{broken`, `{"result":"weird"}`, `{"result":"unavailable"}`, `{"result":"reset","reason":"reset_unconfirmed"}`, "http-500"} { + t.Run(claim, func(t *testing.T) { + f := &redeemFake{claim: claim} + if claim == "http-500" { + f.claim, f.claimHTTP = `{"result":"reset"}`, http.StatusInternalServerError + } + s, _, _ := newRedeemService(t, f) + out, err := s.Redeem(context.Background(), 1, "op-1") + require.NoError(t, err) + require.Equal(t, ClaudeResetOutcomeUnknown, out.Outcome) + require.Nil(t, out.Credits) + require.NotContains(t, out.Reason, "private") + + // Same confirmation replays, no resend. + again, err := s.Redeem(context.Background(), 1, "op-1") + require.NoError(t, err) + require.True(t, again.Replayed) + require.Equal(t, ClaudeResetOutcomeUnknown, again.Outcome) + + // Simulated restart (fresh leases); a new confirmation on this or a + // duplicate account of the same organization is blocked by the fence. + s.locks = &redeemLeaseStub{} + for _, id := range []int64{1, 2} { + _, err = s.Redeem(context.Background(), id, "op-new") + require.Error(t, err) + require.Equal(t, "CLAUDE_RESET_UNRESOLVED", infraerrors.Reason(err)) + } + require.Equal(t, 1, f.postCount()) + + // Once the fence has settled, a fresh query is authoritative again. + s.now = func() time.Time { return time.Now().Add(claudeResetUnknownFenceTTL + time.Minute) } + f.claim, f.claimHTTP = `{"result":"reset"}`, 0 + out, err = s.Redeem(context.Background(), 1, "op-later") + require.NoError(t, err) + require.Equal(t, ClaudeResetOutcomeReset, out.Outcome) + require.Equal(t, 2, f.postCount()) + }) + } +} + +func TestClaudeResetRedeemCrashAfterMarkerNeverResends(t *testing.T) { + f := &redeemFake{claim: `{"result":"reset"}`} + s, _, _ := newRedeemService(t, f) + // Simulate a process that persisted the marker for op-1 and died mid-claim. + orgHash := HashIdempotencyKey("claude-org:" + redeemTestOrg) + fence, err := s.loadFence(context.Background(), orgHash) + require.NoError(t, err) + op := HashIdempotencyKey("claude-reset:1:op-1") + require.NoError(t, s.persistFence(context.Background(), fence.ID, claudeResetFence{Operation: op, Outcome: ClaudeResetOutcomeUnknown, Reason: "claim_unconfirmed", At: time.Now()})) + out, err := s.Redeem(context.Background(), 1, "op-1") + require.NoError(t, err) + require.Equal(t, ClaudeResetOutcomeUnknown, out.Outcome) + require.True(t, out.Replayed) + require.Zero(t, f.postCount()) +} + +func TestClaudeResetRedeemMapsUpstreamResults(t *testing.T) { + cases := []struct { + claim, outcome string + http int + }{ + {`{"result":"reset"}`, ClaudeResetOutcomeReset, 0}, + {`{"result":"already_used"}`, ClaudeResetOutcomeAlreadyUsed, 0}, + {`{"result":"not_limited"}`, ClaudeResetOutcomeNotLimited, 0}, + {`{"result":"cooldown","cooldown_until":"2099-01-01T00:00:00Z"}`, ClaudeResetOutcomeCooldown, 0}, + {`{"result":"ineligible","reason":"plan_changed"}`, ClaudeResetOutcomeIneligible, 0}, + {`{"result":"unavailable","reason":"stamp_indeterminate"}`, ClaudeResetOutcomeUnknown, 0}, + {`{}`, ClaudeResetOutcomeIneligible, http.StatusForbidden}, + } + for _, tc := range cases { + t.Run(tc.claim, func(t *testing.T) { + f := &redeemFake{claim: tc.claim, claimHTTP: tc.http} + s, _, _ := newRedeemService(t, f) + out, err := s.Redeem(context.Background(), 1, "op-1") + require.NoError(t, err) + require.Equal(t, tc.outcome, out.Outcome) + if tc.outcome == ClaudeResetOutcomeCooldown { + require.NotNil(t, out.CooldownUntil) + } + if tc.outcome == ClaudeResetOutcomeIneligible && tc.http == 0 { + require.Equal(t, "plan_changed", out.Reason) + } + // Definite outcomes never block a later confirmation. + if tc.outcome != ClaudeResetOutcomeUnknown { + _, err = s.Redeem(context.Background(), 1, "op-2") + require.NoError(t, err) + require.Equal(t, 2, f.postCount()) + } + }) + } +} + +func TestClaudeResetRedeemSanitizesUpstreamReason(t *testing.T) { + f := &redeemFake{claim: `{"result":"ineligible","reason":"Bearer synthetic-token leaked