Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/backend-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ jobs:
- name: Fork v2.3.175 protocol and cache regression
working-directory: backend
run: go test -race -p 1 -parallel 1 -tags=unit ./internal/service ./internal/repository -run '^Test(FilterThinkingBlocks|SanitizeAnthropicBodyForBetaTokens_ContextManagementCompactBeta|NormalizeOpenAIResponsesLitePayload_NullBodyDoesNotPanic|SanitizeOpenAIResponsesInputItemIDsMatchesLegacy|SanitizeOpenAIResponsesInputItemIDsTruncatedBodiesMatchLegacy|SanitizeOpenAIResponsesInputItemIDsLeadingWhitespaceKeepsOffsets|StripGrokAPIKeyOpenAICompatFieldsMatchesLegacy|ReasoningContent|DeepSeekNativeReasoningReplayTreatsUndecodableCacheValueAsMiss|ChannelMonitorV2RefreshesEarlierDurableCursor|ClientErrorPrivacy.*PublicLink|SilentRefusalDetector)' -count=1
- name: Fork v2.4.5 request isolation and security regression
working-directory: backend
run: go test -race -p 1 -parallel 1 -tags=unit ./internal/config ./internal/service ./internal/repository ./internal/handler ./internal/handler/admin ./internal/pkg/ip -run '^Test(QueuedUsage|UsageRecords|DetachRequestStrings|OpenAIRequestViewStringsDoNotPinTheBody|BuildRedis|ProvideReasoningRedis|RedisPool|LoadRedisPool|ChannelMonitorV2HistogramOverflow|OpsWS|SanitizeFrontendRedirectPath)' -count=1
- name: Session revocation, atomic codes and gateway admission regression
working-directory: backend
run: go test -race -p 1 -parallel 1 -tags=unit ./internal/pkg/httputil ./internal/repository ./internal/service ./internal/handler ./internal/server/middleware ./internal/server/routes -run 'Test(AuthUserTokenCutoff|EmailCode|JWTRevocation|AuthHandlerRevokeAllSessions|OAuthBindCookieRejects|GroupModelAllowlist|GatewayRoutesGroupModelAllowlist|NormalizeLenientJSONRequestBody|DeepSeek|NativeAnthropicPassthrough|PatchGrokResponsesBody|NormalizeGrokChatReasoningEffort|ReleaseAccountSession|CleanupStaleProcessSlots)' -count=1
Expand Down
6 changes: 6 additions & 0 deletions LOCAL_FORK.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@

原生支付模块已退役,充值使用链动小铺及兑换码。服务器部署继续使用备份和校验后的受控发布流程。

## 二改 v2.4.5 选择性同步(2026-11-28)

固定正式 v2.4.5 来源,盘点 v2.3.175 后 47 个提交、1,152 个变化路径,适配 Redis 连接池回收与等待超时、异步计费请求上下文/字符串脱离、监控直方图溢出显示,以及 Ops WebSocket Origin 和登录/OAuth 站内跳转校验。原版正式版本仍为 v0.2.25,未发布 main 仅记录观察值。

保留生图分组、Images API、批量生图、Key、价格/倍率、原生厂商路由和个人主题;无限画布继续移除。新账本、配额预占、计费 schema、完整 MFA/Key seal、支付及全请求体索引等成组模块延期。用户随后授权提交 GitHub 并更新部署,个人发布版本推进至 v2.1.76;按 PR/CI、自有 Release/GHCR、备份实际恢复及受控切换流程发布,最终生产验收另存证据。具体采用与延期项见[同步记录](maintenance/notes/upstream-sync-20261128-v245.md)及[完整取舍清单](maintenance/notes/fork-selection-ledger-20261128-v245.json)。

## 二改 v2.3.155 选择性同步(2026-11-24)

审阅正式 v2.3.153 至 v2.3.155 的 43 个提交、336 个变化路径,适配网关 Base URL 路径兼容及最终防护、Passkey 会话/错误反馈和 WebSocket/otel 依赖修复。智能路由富分组下拉已有覆盖;保留本地主题、原生厂商路由、计费与 TOTP 登录规则。Nuxt UI 改版、全套多因子/Key seal 验证、5xx 告警迁移及退役支付不整组导入。原版检查点仍为 v0.2.24。用户随后授权提交 GitHub 并部署,个人发布版本推进至 v2.1.72,沿用 PR/CI、自有 Release/GHCR、备份实际恢复及受控切换流程;最终发布与线上验收另存证据。来源、逐项取舍与验证边界见[同步记录](maintenance/notes/upstream-sync-20261124-v23155.md)。
Expand Down
2 changes: 1 addition & 1 deletion backend/cmd/server/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2.1.75
2.1.76
28 changes: 25 additions & 3 deletions backend/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -1700,7 +1700,12 @@ type RedisConfig struct {
// PoolSize: 连接池大小,控制最大并发连接数
PoolSize int `mapstructure:"pool_size"`
// MinIdleConns: 最小空闲连接数,保持热连接减少冷启动延迟
MinIdleConns int `mapstructure:"min_idle_conns"`
MinIdleConns int `mapstructure:"min_idle_conns"`
MaxIdleConns int `mapstructure:"max_idle_conns"`
PoolFIFO bool `mapstructure:"pool_fifo"`
PoolTimeoutMS int `mapstructure:"pool_timeout_ms"`
ConnMaxIdleTimeSeconds int `mapstructure:"conn_max_idle_time_seconds"`
ConnMaxLifetimeSeconds int `mapstructure:"conn_max_lifetime_seconds"`
// EnableTLS: 是否启用 TLS/SSL 连接
EnableTLS bool `mapstructure:"enable_tls"`
}
Expand Down Expand Up @@ -2355,8 +2360,13 @@ func setDefaults() {
viper.SetDefault("redis.dial_timeout_seconds", 5)
viper.SetDefault("redis.read_timeout_seconds", 3)
viper.SetDefault("redis.write_timeout_seconds", 3)
viper.SetDefault("redis.pool_size", 1024)
viper.SetDefault("redis.min_idle_conns", 128)
viper.SetDefault("redis.pool_size", 512)
viper.SetDefault("redis.min_idle_conns", 8)
viper.SetDefault("redis.max_idle_conns", 64)
viper.SetDefault("redis.pool_fifo", true)
viper.SetDefault("redis.pool_timeout_ms", 1000)
viper.SetDefault("redis.conn_max_idle_time_seconds", 300)
viper.SetDefault("redis.conn_max_lifetime_seconds", 1800)
viper.SetDefault("redis.enable_tls", false)

// Batch Image queue
Expand Down Expand Up @@ -3310,6 +3320,18 @@ func (c *Config) Validate() error {
if c.Redis.MinIdleConns > c.Redis.PoolSize {
return fmt.Errorf("redis.min_idle_conns cannot exceed redis.pool_size")
}
if c.Redis.MaxIdleConns < 0 {
return fmt.Errorf("redis.max_idle_conns must be non-negative")
}
if c.Redis.PoolTimeoutMS <= 0 {
return fmt.Errorf("redis.pool_timeout_ms must be positive")
}
if c.Redis.ConnMaxIdleTimeSeconds < 0 {
return fmt.Errorf("redis.conn_max_idle_time_seconds must be non-negative")
}
if c.Redis.ConnMaxLifetimeSeconds < 0 {
return fmt.Errorf("redis.conn_max_lifetime_seconds must be non-negative")
}
if c.BatchImage.QueueEnabled {
if strings.TrimSpace(c.BatchImage.QueueReadyKey) == "" {
return fmt.Errorf("batch_image.queue_ready_key must not be empty")
Expand Down
48 changes: 48 additions & 0 deletions backend/internal/config/redis_pool_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package config

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestLoadRedisPoolDefaultsAndExplicitOverrides(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, 512, cfg.Redis.PoolSize)
require.Equal(t, 8, cfg.Redis.MinIdleConns)
require.Equal(t, 64, cfg.Redis.MaxIdleConns)
require.True(t, cfg.Redis.PoolFIFO)
require.Equal(t, 1000, cfg.Redis.PoolTimeoutMS)
require.Equal(t, 300, cfg.Redis.ConnMaxIdleTimeSeconds)
require.Equal(t, 1800, cfg.Redis.ConnMaxLifetimeSeconds)

t.Setenv("REDIS_POOL_SIZE", "4096")
t.Setenv("REDIS_MIN_IDLE_CONNS", "256")
t.Setenv("REDIS_POOL_FIFO", "false")
t.Setenv("REDIS_MAX_IDLE_CONNS", "0")
t.Setenv("REDIS_POOL_TIMEOUT_MS", "250")
t.Setenv("REDIS_CONN_MAX_IDLE_TIME_SECONDS", "0")
t.Setenv("REDIS_CONN_MAX_LIFETIME_SECONDS", "0")
cfg, err = Load()
require.NoError(t, err)
require.Equal(t, 4096, cfg.Redis.PoolSize)
require.Equal(t, 256, cfg.Redis.MinIdleConns)
require.Zero(t, cfg.Redis.MaxIdleConns)
require.False(t, cfg.Redis.PoolFIFO)
require.Equal(t, 250, cfg.Redis.PoolTimeoutMS)
require.Zero(t, cfg.Redis.ConnMaxIdleTimeSeconds)
require.Zero(t, cfg.Redis.ConnMaxLifetimeSeconds)
}

func TestLoadRedisPoolRejectsInvalidSettings(t *testing.T) {
for _, key := range []string{"REDIS_MAX_IDLE_CONNS", "REDIS_POOL_TIMEOUT_MS", "REDIS_CONN_MAX_IDLE_TIME_SECONDS", "REDIS_CONN_MAX_LIFETIME_SECONDS"} {
t.Run(key, func(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv(key, "-1")
_, err := Load()
require.Error(t, err)
})
}
}
41 changes: 24 additions & 17 deletions backend/internal/handler/admin/ops_ws_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"sync/atomic"
"time"

"github.com/Wei-Shaw/sub2api/internal/pkg/ip"
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
servermiddleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
Expand Down Expand Up @@ -552,27 +553,22 @@ func isAllowedOpsWSOrigin(r *http.Request) bool {
}
}
parsed, err := url.Parse(origin)
if err != nil || parsed.Hostname() == "" {
if err != nil || !parsed.IsAbs() || parsed.Opaque != "" || parsed.User != nil ||
parsed.Path != "" || strings.ContainsAny(origin, "?#") ||
(parsed.Scheme != "http" && parsed.Scheme != "https") {
return false
}
originHost := strings.ToLower(parsed.Hostname())

trustProxyHeaders := shouldTrustOpsWSProxyHeaders(r)
reqHost := hostWithoutPort(r.Host)
if trustProxyHeaders {
xfHost := strings.TrimSpace(r.Header.Get("X-Forwarded-Host"))
if xfHost != "" {
xfHost = strings.TrimSpace(strings.Split(xfHost, ",")[0])
if xfHost != "" {
reqHost = hostWithoutPort(xfHost)
}
}
validOriginHost, ok := ip.ValidateRequestHost(parsed.Host)
if !ok {
return false
}
reqHost = strings.ToLower(reqHost)
if reqHost == "" {
// Proxies may pass client-controlled X-Forwarded-Host through unchanged.
// Compare only the validated request Host, retaining the existing port policy.
validReqHost, ok := ip.ValidateRequestHost(r.Host)
if !ok {
return false
}
return originHost == reqHost
return strings.EqualFold(hostWithoutPort(validOriginHost), hostWithoutPort(validReqHost))
}

func shouldTrustOpsWSProxyHeaders(r *http.Request) bool {
Expand Down Expand Up @@ -639,6 +635,9 @@ func isAddrInTrustedProxies(addr netip.Addr, trusted []netip.Prefix) bool {
return false
}
for _, p := range trusted {
if p.Bits() == 0 {
continue
}
if p.Contains(addr) {
return true
}
Expand Down Expand Up @@ -736,10 +735,18 @@ func parseTrustedProxyList(raw string) (prefixes []netip.Prefix, invalid []strin
}
}

if err != nil || !p.IsValid() {
if err != nil || !p.IsValid() || p.Bits() == 0 {
invalid = append(invalid, item)
continue
}
if p.Addr().Is4In6() {
bits := p.Bits() - 96
if bits <= 0 {
invalid = append(invalid, item)
continue
}
p = netip.PrefixFrom(p.Addr().Unmap(), bits)
}

prefixes = append(prefixes, p.Masked())
}
Expand Down
52 changes: 52 additions & 0 deletions backend/internal/handler/admin/ops_ws_origin_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package admin

import (
"net/http/httptest"
"net/netip"
"testing"

"github.com/stretchr/testify/require"
)

func TestOpsWSOriginUsesValidatedRequestHost(t *testing.T) {
previous := opsWSProxyConfig
opsWSProxyConfig = OpsWSProxyConfig{TrustProxy: true, TrustedProxies: defaultTrustedProxies(), OriginPolicy: OriginPolicyStrict}
t.Cleanup(func() { opsWSProxyConfig = previous })
for _, tc := range []struct {
name, host, origin, forwarded string
want bool
}{
{"same host", "example.com", "https://example.com", "", true},
{"case and port policy", "EXAMPLE.com:8080", "https://example.com", "", true},
{"IPv6", "[::1]:8080", "http://[::1]:8080", "", true},
{"spoofed forwarded host", "example.com", "https://evil.example", "evil.example", false},
{"forwarded host cannot override valid host", "example.com", "https://example.com", "evil.example", true},
{"userinfo", "example.com", "https://evil@example.com", "", false},
{"scheme", "example.com", "ftp://example.com", "", false},
{"path", "example.com", "https://example.com/", "", false},
{"query", "example.com", "https://example.com?", "", false},
{"fragment", "example.com", "https://example.com#", "", false},
{"invalid origin host", "example.com", "https://example.com:0", "", false},
{"invalid request host", "example.com,evil.example", "https://example.com", "", false},
{"invalid IPv6", "[not-an-ip]", "http://[not-an-ip]", "", false},
{"strict missing", "example.com", "", "", false},
} {
t.Run(tc.name, func(t *testing.T) {
r := httptest.NewRequest("GET", "http://example.com/ops/ws", nil)
r.Host, r.RemoteAddr = tc.host, "127.0.0.1:12345"
r.Header.Set("Origin", tc.origin)
r.Header.Set("X-Forwarded-Host", tc.forwarded)
require.Equal(t, tc.want, isAllowedOpsWSOrigin(r))
})
}
opsWSProxyConfig.OriginPolicy = OriginPolicyPermissive
require.True(t, isAllowedOpsWSOrigin(httptest.NewRequest("GET", "http://example.com", nil)))
}

func TestOpsWSTrustRejectsWildcardAndNormalizesMappedIPv4(t *testing.T) {
prefixes, invalid := parseTrustedProxyList("0.0.0.0/0,::/0,::ffff:0.0.0.0/96,::ffff:10.0.0.0/104,127.0.0.1")
require.Len(t, invalid, 3)
require.Equal(t, []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8"), netip.MustParsePrefix("127.0.0.1/32")}, prefixes)
require.True(t, isAddrInTrustedProxies(netip.MustParseAddr("10.1.2.3"), prefixes))
require.False(t, isAddrInTrustedProxies(netip.MustParseAddr("8.8.8.8"), []netip.Prefix{netip.MustParsePrefix("0.0.0.0/0")}))
}
6 changes: 4 additions & 2 deletions backend/internal/handler/auth_linuxdo_oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -1039,8 +1039,10 @@ func sanitizeFrontendRedirectPath(path string) string {
if strings.Contains(path, "://") {
return ""
}
if strings.ContainsAny(path, "\r\n") {
return ""
for i := 0; i < len(path); i++ {
if path[i] < 0x20 || path[i] == 0x7f || path[i] == '\\' {
return ""
}
}
return path
}
Expand Down
3 changes: 3 additions & 0 deletions backend/internal/handler/auth_linuxdo_oauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ func TestSanitizeFrontendRedirectPath(t *testing.T) {
require.Equal(t, "", sanitizeFrontendRedirectPath("//evil.com"))
require.Equal(t, "", sanitizeFrontendRedirectPath("https://evil.com"))
require.Equal(t, "", sanitizeFrontendRedirectPath("/\nfoo"))
for _, path := range []string{"/\\evil.example", "/\t/evil.example", "/bad\x00path", "/bad\x7fpath"} {
require.Empty(t, sanitizeFrontendRedirectPath(path), "unsafe redirect %q", path)
}

long := "/" + strings.Repeat("a", linuxDoOAuthMaxRedirectLen)
require.Equal(t, "", sanitizeFrontendRedirectPath(long))
Expand Down
2 changes: 1 addition & 1 deletion backend/internal/handler/content_moderation_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func clientRequestedModel(c *gin.Context, fallback string) string {
}

func clientRequestedUsageFields(c *gin.Context, mapping service.ChannelMappingResult, fallbackModel, upstreamModel string) service.ChannelUsageFields {
return mapping.ToUsageFields(clientRequestedModel(c, fallbackModel), upstreamModel)
return mapping.ToUsageFields(clientRequestedModel(c, fallbackModel), upstreamModel).Detached()
}

func runContentModeration(c *gin.Context, reqLog *zap.Logger, svc *service.ContentModerationService, apiKey *service.APIKey, subject middleware2.AuthSubject, protocol string, model string, body []byte) *service.ContentModerationDecision {
Expand Down
9 changes: 6 additions & 3 deletions backend/internal/handler/gateway_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
}
body = parsedReq.Body.Bytes()
service.CaptureMessagesValidationFacts(c, body)
reqModel := parsedReq.Model
reqModel := strings.Clone(parsedReq.Model)
reqStream := parsedReq.Stream
if service.IsChatUnsupportedMediaModel(reqModel) {
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "This model is not supported on the Messages endpoint")
Expand All @@ -219,7 +219,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
return
}
body = parsedReq.Body.Bytes()
reqModel = parsedReq.Model
reqModel = strings.Clone(parsedReq.Model)
reqStream = parsedReq.Stream
}
reqLog = reqLog.With(zap.String("model", reqModel), zap.Bool("stream", reqStream))
Expand Down Expand Up @@ -631,6 +631,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
sessionID := service.ExtractClientSessionID(c)
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, partial.UpstreamModel)
partial.DetachRequestStrings()
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if recordErr := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Result: partial,
Expand Down Expand Up @@ -1072,6 +1073,8 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
forceCacheBilling := fs.ForceCacheBilling
quotaPlatform := service.QuotaPlatform(c.Request.Context(), currentAPIKey)
sessionID := service.ExtractClientSessionID(c)
result.DetachRequestStrings()
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel)
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Result: result,
Expand All @@ -1089,7 +1092,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
RequestPayloadHash: requestPayloadHash,
ForceCacheBilling: forceCacheBilling,
APIKeyService: h.apiKeyService,
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
ChannelUsageFields: channelUsageFields,
}); err != nil {
logger.L().With(
zap.String("component", "handler.gateway.messages"),
Expand Down
3 changes: 2 additions & 1 deletion backend/internal/handler/gateway_handler_chat_completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required")
return
}
reqModel := modelResult.String()
reqModel := strings.Clone(modelResult.String())
bindRequestedReasoningEffort(c, body, reqModel)
ensureCompositeTargetPlatform(c, apiKey, reqModel)
if rejectSystemOneOnlyPlatform(c, apiKey, h.chatCompletionsErrorResponse) {
Expand Down Expand Up @@ -398,6 +398,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
sessionID := service.ExtractClientSessionID(c)
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, partial.UpstreamModel)
partial.DetachRequestStrings()
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Result: partial,
Expand Down
3 changes: 2 additions & 1 deletion backend/internal/handler/gateway_handler_responses.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required")
return
}
reqModel := modelResult.String()
reqModel := strings.Clone(modelResult.String())
bindRequestedReasoningEffort(c, body, reqModel)
ensureCompositeTargetPlatform(c, apiKey, reqModel)
if rejectSystemOneOnlyPlatform(c, apiKey, h.responsesErrorResponse) {
Expand Down Expand Up @@ -382,6 +382,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
sessionID := service.ExtractClientSessionID(c)
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, partial.UpstreamModel)
partial.DetachRequestStrings()
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Result: partial,
Expand Down
1 change: 1 addition & 0 deletions backend/internal/handler/gateway_systemone.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,7 @@ func (h *GatewayHandler) recordSystemOneUsage(c *gin.Context, apiKey *service.AP
sessionID := service.ExtractClientSessionID(c)
requestPayloadHash := service.HashUsageRequestPayload(body)
usageFields := clientRequestedUsageFields(c, mapping, model, result.UpstreamModel)
result.DetachRequestStrings()

task := func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Expand Down
1 change: 1 addition & 0 deletions backend/internal/handler/gemini_v1beta_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
accountReleaseFunc()
}
if result != nil {
result.DetachRequestStrings()
usageInput := &service.RecordUsageInput{
Result: result, APIKey: apiKey, User: apiKey.User, Account: account,
Subscription: subscription, PricingAt: pricingAt,
Expand Down
4 changes: 3 additions & 1 deletion backend/internal/handler/grok_audio.go
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,8 @@ func (h *OpenAIGatewayHandler) recordGrokVoiceUsage(
model = endpoint
}

result.DetachRequestStrings()
channelUsageFields := clientRequestedUsageFields(c, service.ChannelMappingResult{}, model, result.UpstreamModel)
h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{
Result: result,
Expand All @@ -386,7 +388,7 @@ func (h *OpenAIGatewayHandler) recordGrokVoiceUsage(
APIKeyService: h.apiKeyService,
QuotaPlatform: quotaPlatform,
SessionID: sessionID,
ChannelUsageFields: clientRequestedUsageFields(c, service.ChannelMappingResult{}, model, result.UpstreamModel),
ChannelUsageFields: channelUsageFields,
}); err != nil {
logger.L().With(
zap.String("component", "handler.openai_gateway.grok_voice"),
Expand Down
Loading
Loading