mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
Merge main into perf/scheduler-snapshot-coalesce
Resolve conflicts with #8729, which caches the configured account pool and checks time-based blocks (rate limit, overload, temp-unschedulable) on every read: - readSnapshotAccounts filters by IsSchedulable on both the GetSnapshotValues path (in-place compaction of the caller-owned slice) and the GetSnapshot path. - The coalesced DB fallback still publishes the full configured pool. Each caller's private copy contains only accounts that are schedulable now. - The fallback test stubs now implement ListModelAvailabilityCandidates, which #8729 switched the DB fallback to. Values-reader fixtures are marked schedulable. Adds tests for time-blocked filtering on both paths and for publishing the full pool.
This commit is contained in:
commit
7f3fe5bfde
197 files changed
+12019
-1241
No files matched your search
@@ -35,7 +35,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.27.3'
|
||||
go version | grep -q 'go1.27.4'
|
||||
- name: Unit tests
|
||||
working-directory: backend
|
||||
run: make test-unit
|
||||
@@ -75,7 +75,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.27.3'
|
||||
go version | grep -q 'go1.27.4'
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
|
||||
@@ -137,7 +137,7 @@ jobs:
|
||||
check-latest: false
|
||||
cache: false
|
||||
- name: Verify Go version
|
||||
run: go version | grep -q 'go1.27.3'
|
||||
run: go version | grep -q 'go1.27.4'
|
||||
- name: Restore target-specific Go cache
|
||||
id: go-cache
|
||||
uses: actions/cache/restore@v6
|
||||
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.27.3'
|
||||
go version | grep -q 'go1.27.4'
|
||||
- name: Run govulncheck
|
||||
working-directory: backend
|
||||
run: |
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@ npm install -g pnpm
|
||||
|
||||
### CI 要求
|
||||
|
||||
- Go 版本必须是 **1.27.0**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.0'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。
|
||||
- Go 版本必须是 **1.27.4**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.4'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。
|
||||
- 前端使用 `pnpm install --frozen-lockfile`,必须提交 `pnpm-lock.yaml`
|
||||
|
||||
### 本地测试命令
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@
|
||||
# =============================================================================
|
||||
|
||||
ARG NODE_IMAGE=node:24-alpine
|
||||
ARG GOLANG_IMAGE=golang:1.27.3-alpine
|
||||
ARG GOLANG_IMAGE=golang:1.27.4-alpine
|
||||
ARG ALPINE_IMAGE=alpine:3.21
|
||||
ARG POSTGRES_IMAGE=postgres:18-alpine
|
||||
ARG GOPROXY=https://goproxy.cn,direct
|
||||
|
||||
@@ -11,6 +11,7 @@ FRONTEND_CRITICAL_VITEST := \
|
||||
src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts \
|
||||
src/constants/__tests__/platforms.spec.ts \
|
||||
src/components/account/__tests__/credentialsBuilder.platformCatalog.spec.ts \
|
||||
src/components/account/__tests__/CNProviderQuotaCell.spec.ts \
|
||||
src/components/account/__tests__/CreateAccountModal.spec.ts \
|
||||
src/components/account/__tests__/EditAccountModal.spec.ts \
|
||||
src/components/account/__tests__/credentialsBuilder.spec.ts \
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.27.2-alpine
|
||||
FROM golang:1.27.4-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
module github.com/Wei-Shaw/sub2api
|
||||
|
||||
go 1.27.3
|
||||
go 1.27.4
|
||||
|
||||
require (
|
||||
entgo.io/ent v0.14.5
|
||||
|
||||
@@ -1025,7 +1025,7 @@ type CircuitBreakerConfig struct {
|
||||
}
|
||||
|
||||
type ConcurrencyConfig struct {
|
||||
// PingInterval: 并发等待期间的 SSE ping 间隔(秒)
|
||||
// PingInterval: 并发等待期间的 SSE ping 间隔(秒),0 禁用 ping
|
||||
PingInterval int `mapstructure:"ping_interval"`
|
||||
}
|
||||
|
||||
@@ -3887,8 +3887,8 @@ func (c *Config) Validate() error {
|
||||
if c.Ops.Cleanup.Enabled && strings.TrimSpace(c.Ops.Cleanup.Schedule) == "" {
|
||||
return fmt.Errorf("ops.cleanup.schedule is required when ops.cleanup.enabled=true")
|
||||
}
|
||||
if c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30 {
|
||||
return fmt.Errorf("concurrency.ping_interval must be between 5-30 seconds")
|
||||
if c.Concurrency.PingInterval != 0 && (c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30) {
|
||||
return fmt.Errorf("concurrency.ping_interval must be 0 (disabled) or between 5-30 seconds")
|
||||
}
|
||||
if c.Gateway.Grok.FreeQuotaSoftGateEnabled {
|
||||
if c.Gateway.Grok.FreeQuotaTokenLimit <= 0 {
|
||||
|
||||
@@ -1577,18 +1577,20 @@ func TestValidateOpsCleanupScheduleRequired(t *testing.T) {
|
||||
|
||||
func TestValidateConcurrencyPingInterval(t *testing.T) {
|
||||
resetViperWithJWTSecret(t)
|
||||
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load() error: %v", err)
|
||||
}
|
||||
cfg.Concurrency.PingInterval = 3
|
||||
err = cfg.Validate()
|
||||
if err == nil {
|
||||
t.Fatalf("Validate() expected error for concurrency.ping_interval")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "concurrency.ping_interval") {
|
||||
t.Fatalf("Validate() expected concurrency.ping_interval error, got: %v", err)
|
||||
for _, interval := range []int{-1, 0, 1, 3, 4, 5, 10, 30, 31} {
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load() error: %v", err)
|
||||
}
|
||||
cfg.Concurrency.PingInterval = interval
|
||||
err = cfg.Validate()
|
||||
valid := interval == 0 || (interval >= 5 && interval <= 30)
|
||||
if valid && err != nil {
|
||||
t.Errorf("Validate() interval %d: %v", interval, err)
|
||||
}
|
||||
if !valid && (err == nil || !strings.Contains(err.Error(), "concurrency.ping_interval")) {
|
||||
t.Errorf("Validate() interval %d: expected concurrency.ping_interval error, got %v", interval, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
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"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
type compatEffortPolicyUpstream struct {
|
||||
service.HTTPUpstream
|
||||
bodies [][]byte
|
||||
}
|
||||
|
||||
func (u *compatEffortPolicyUpstream) DoWithTLS(req *http.Request, _ string, _ int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
body, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u.bodies = append(u.bodies, body)
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(compatStreamUsagePartialStream + compatStreamUsageCompletion)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func TestGatewayCompatibilityHandlersReasoningEffortPolicy(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
const model = "claude-sonnet-4.5"
|
||||
for _, endpoint := range []string{"chat/completions", "responses"} {
|
||||
for _, platform := range []string{service.PlatformAnthropic, service.PlatformComposite} {
|
||||
for _, stream := range []bool{false, true} {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
effort string
|
||||
ceiling string
|
||||
overLimit string
|
||||
mappings []service.ReasoningEffortMapping
|
||||
want string
|
||||
denied bool
|
||||
}{
|
||||
{name: "ceiling", effort: "high", ceiling: "medium", want: "medium"},
|
||||
{name: "mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low"}}, want: "low"},
|
||||
{name: "mapping then ceiling", effort: "low", ceiling: "medium", mappings: []service.ReasoningEffortMapping{{From: "low", To: "high"}}, want: "medium"},
|
||||
{name: "model mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low", MatchType: "exact", Model: model}}, want: "low"},
|
||||
{name: "other model mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low", MatchType: "exact", Model: "other-model"}}, want: "high"},
|
||||
{name: "deny ceiling", effort: "high", ceiling: "medium", overLimit: service.ReasoningEffortOverLimitDeny, denied: true},
|
||||
{name: "deny mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "deny"}}, denied: true},
|
||||
{name: "within ceiling", effort: "low", ceiling: "medium", want: "low"},
|
||||
{name: "no policy", effort: "high", want: "high"},
|
||||
{name: "omitted", ceiling: "medium"},
|
||||
} {
|
||||
t.Run(fmt.Sprintf("%s/%s/stream=%t/%s", endpoint, platform, stream, tc.name), func(t *testing.T) {
|
||||
cfg := &config.Config{}
|
||||
groupID := int64(9400)
|
||||
group := &service.Group{
|
||||
ID: groupID, Hydrated: true, Platform: platform, Status: service.StatusActive, RateMultiplier: 1,
|
||||
MaxReasoningEffort: tc.ceiling, MaxReasoningEffortOverLimit: tc.overLimit, ReasoningEffortMappings: tc.mappings,
|
||||
}
|
||||
account := &service.Account{
|
||||
ID: 9401, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive, Schedulable: true, Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "test-key"},
|
||||
AccountGroups: []service.AccountGroup{{AccountID: 9401, GroupID: groupID}},
|
||||
}
|
||||
cache := &countingGatewaySchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{account}}}
|
||||
snapshot := service.NewSchedulerSnapshotService(cache, nil, nil, nil, nil)
|
||||
upstream := &compatEffortPolicyUpstream{}
|
||||
usageRepo := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)}
|
||||
billingRepo := &compatStreamUsageBillingRepo{}
|
||||
billingCache := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCache.Stop)
|
||||
gateway := service.NewGatewayService(
|
||||
nil, &fakeGroupRepo{group: group}, usageRepo, billingRepo, nil, nil, nil, nil, cfg,
|
||||
snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream,
|
||||
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
h := &GatewayHandler{
|
||||
gatewayService: gateway, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1,
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
|
||||
}
|
||||
|
||||
request := map[string]any{"model": model, "stream": stream}
|
||||
if endpoint == "chat/completions" {
|
||||
request["messages"] = []map[string]string{{"role": "user", "content": "hello"}}
|
||||
if tc.effort != "" {
|
||||
request["reasoning_effort"] = tc.effort
|
||||
}
|
||||
} else {
|
||||
request["input"] = "hello"
|
||||
if tc.effort != "" {
|
||||
request["reasoning"] = map[string]string{"effort": tc.effort}
|
||||
}
|
||||
}
|
||||
body, err := json.Marshal(request)
|
||||
require.NoError(t, err)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
ctx := context.WithValue(context.Background(), ctxkey.Group, group)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, bytes.NewReader(body)).WithContext(ctx)
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
apiKey := &service.APIKey{
|
||||
ID: 9402, UserID: 9403, GroupID: &groupID, Group: group,
|
||||
User: &service.User{ID: 9403, Balance: 100},
|
||||
}
|
||||
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
|
||||
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9403})
|
||||
if endpoint == "chat/completions" {
|
||||
h.ChatCompletions(c)
|
||||
} else {
|
||||
h.Responses(c)
|
||||
}
|
||||
|
||||
if tc.denied {
|
||||
require.Equal(t, http.StatusForbidden, recorder.Code, recorder.Body.String())
|
||||
errorField := "error.type"
|
||||
if endpoint == "responses" {
|
||||
errorField = "error.code"
|
||||
}
|
||||
require.Equal(t, "permission_error", gjson.Get(recorder.Body.String(), errorField).String())
|
||||
require.Empty(t, upstream.bodies)
|
||||
require.Zero(t, cache.snapshotCalls.Load(), "local policy denial precedes account selection")
|
||||
require.Empty(t, usageRepo.created)
|
||||
require.Empty(t, billingRepo.commands)
|
||||
return
|
||||
}
|
||||
// Check the final Anthropic request, beyond handler parsing and both protocol conversions.
|
||||
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
|
||||
require.Len(t, upstream.bodies, 1)
|
||||
require.Equal(t, tc.want, gjson.GetBytes(upstream.bodies[0], "output_config.effort").String())
|
||||
require.Equal(t, model, gjson.GetBytes(upstream.bodies[0], "model").String())
|
||||
require.Contains(t, recorder.Body.String(), "partial")
|
||||
require.Len(t, usageRepo.created, 1)
|
||||
usage := <-usageRepo.created
|
||||
if tc.effort == "" {
|
||||
require.Nil(t, usage.RequestedReasoningEffort)
|
||||
} else {
|
||||
require.Equal(t, &tc.effort, usage.RequestedReasoningEffort)
|
||||
require.Equal(t, &tc.want, usage.ReasoningEffort)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,7 @@ func NewGatewayHandler(
|
||||
cfg *config.Config,
|
||||
settingService *service.SettingService,
|
||||
) *GatewayHandler {
|
||||
pingInterval := time.Duration(0)
|
||||
pingInterval := defaultPingInterval
|
||||
maxAccountSwitches := 10
|
||||
maxAccountSwitchesGemini := 3
|
||||
if cfg != nil {
|
||||
@@ -915,6 +915,10 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
if fs.ForceCacheBilling {
|
||||
requestCtx = service.WithForceCacheBilling(requestCtx)
|
||||
}
|
||||
if channelMapping.Mapped {
|
||||
// 选号按客户端模型,转发按渠道映射后的模型:模型级账号状态按选号模型记录。
|
||||
requestCtx = service.WithGatewaySchedulingModel(requestCtx, reqModel)
|
||||
}
|
||||
// 记录 Forward 前已写入字节数,Forward 后若增加则说明 SSE 内容已发,禁止 failover
|
||||
writerSizeBeforeForward := c.Writer.Size()
|
||||
if account.Platform == service.PlatformAntigravity && account.Type != service.AccountTypeAPIKey {
|
||||
@@ -1127,8 +1131,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
|
||||
// - 粘性账号因负载/RPM 被跳过、选中了其他账号:不覆盖原绑定,
|
||||
// 下次请求粘性账号恢复后仍可命中
|
||||
if sessionKey != "" && (sessionBoundAccountID == 0 || sessionBoundAccountID == account.ID) {
|
||||
if err := h.gatewayService.BindStickySession(c.Request.Context(), currentAPIKey.GroupID, sessionKey, account.ID); err != nil {
|
||||
reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(err))
|
||||
// Forward has completed; finish the bounded write even if the client disconnects.
|
||||
bindCtx, cancelBind := context.WithTimeout(context.WithoutCancel(c.Request.Context()), 5*time.Second)
|
||||
bindErr := h.gatewayService.BindStickySession(bindCtx, currentAPIKey.GroupID, sessionKey, account.ID)
|
||||
cancelBind()
|
||||
if bindErr != nil {
|
||||
reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(bindErr))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +85,12 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
if rejectSystemOneOnlyPlatform(c, apiKey, h.chatCompletionsErrorResponse) {
|
||||
return
|
||||
}
|
||||
if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil {
|
||||
respondOpenAIReasoningEffortPolicyError(c, err, h.chatCompletionsErrorResponse)
|
||||
return
|
||||
} else if changed {
|
||||
body = cappedBody
|
||||
}
|
||||
reqStream, ok := parseOpenAICompatibleStream(body)
|
||||
if !ok {
|
||||
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
|
||||
@@ -390,6 +396,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated),
|
||||
zap.Error(err),
|
||||
)
|
||||
h.gatewayService.ReleaseStickySessionAfterCommittedNoContent(context.WithoutCancel(c.Request.Context()), apiKey.GroupID, selectionSessionHash, account.ID, err)
|
||||
if result != nil {
|
||||
submitForwardUsage(result)
|
||||
}
|
||||
|
||||
@@ -85,6 +85,12 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
if rejectSystemOneOnlyPlatform(c, apiKey, h.responsesErrorResponse) {
|
||||
return
|
||||
}
|
||||
if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil {
|
||||
respondOpenAIReasoningEffortPolicyError(c, err, h.responsesErrorResponse)
|
||||
return
|
||||
} else if changed {
|
||||
body = cappedBody
|
||||
}
|
||||
reqStream, ok := parseOpenAICompatibleStream(body)
|
||||
if !ok {
|
||||
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
|
||||
@@ -373,6 +379,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated),
|
||||
zap.Error(err),
|
||||
)
|
||||
// The response is already committed, so the client retries; send that
|
||||
// retry through scheduling again instead of back to this account.
|
||||
h.gatewayService.ReleaseStickySessionAfterCommittedNoContent(context.WithoutCancel(requestCtx), apiKey.GroupID, sessionHash, account.ID, err)
|
||||
if result != nil {
|
||||
submitForwardUsage(result)
|
||||
}
|
||||
|
||||
@@ -172,7 +172,7 @@ type ConcurrencyHelper struct {
|
||||
|
||||
// NewConcurrencyHelper creates a new ConcurrencyHelper
|
||||
func NewConcurrencyHelper(concurrencyService *service.ConcurrencyService, pingFormat SSEPingFormat, pingInterval time.Duration) *ConcurrencyHelper {
|
||||
if pingInterval <= 0 {
|
||||
if pingInterval < 0 {
|
||||
pingInterval = defaultPingInterval
|
||||
}
|
||||
return &ConcurrencyHelper{
|
||||
@@ -380,7 +380,7 @@ func (h *ConcurrencyHelper) waitForSlotWithPingTimeout(c *gin.Context, slotType
|
||||
}
|
||||
|
||||
// Determine if ping is needed (streaming + ping format defined)
|
||||
needPing := isStream && h.pingFormat != ""
|
||||
needPing := isStream && h.pingFormat != "" && h.pingInterval > 0
|
||||
|
||||
var flusher http.Flusher
|
||||
if needPing {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestConcurrencyWaitPingInterval(t *testing.T) {
|
||||
for _, slotType := range []string{"user", "account"} {
|
||||
for _, format := range []SSEPingFormat{SSEPingFormatClaude, SSEPingFormatComment} {
|
||||
for _, interval := range []time.Duration{0, time.Millisecond} {
|
||||
t.Run(slotType+"/"+string(format)+"/"+interval.String(), func(t *testing.T) {
|
||||
cache := &helperConcurrencyCacheStub{}
|
||||
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), format, interval)
|
||||
require.Equal(t, interval, helper.pingInterval)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
|
||||
started := false
|
||||
_, err := helper.waitForSlotWithPingTimeout(c, slotType, 1, 1, 150*time.Millisecond, true, &started, false)
|
||||
var concurrencyErr *ConcurrencyError
|
||||
require.ErrorAs(t, err, &concurrencyErr)
|
||||
require.True(t, concurrencyErr.IsTimeout)
|
||||
if interval == 0 {
|
||||
require.False(t, started)
|
||||
require.False(t, c.Writer.Written())
|
||||
require.False(t, recorder.Flushed)
|
||||
require.Empty(t, recorder.Body.String())
|
||||
require.Empty(t, recorder.Header().Get("Content-Type"))
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{"error": "busy"})
|
||||
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
|
||||
} else {
|
||||
require.True(t, started)
|
||||
require.True(t, recorder.Flushed)
|
||||
require.Contains(t, recorder.Body.String(), string(format))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrencyWaitWithoutPingAcquiresSlot(t *testing.T) {
|
||||
for _, slotType := range []string{"user", "account"} {
|
||||
t.Run(slotType, func(t *testing.T) {
|
||||
cache := &helperConcurrencyCacheStub{userSeq: []bool{true}, accountSeq: []bool{true}}
|
||||
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatClaude, 0)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
|
||||
started := false
|
||||
release, err := helper.waitForSlotWithPingTimeout(c, slotType, 1, 1, time.Second, true, &started, false)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, release)
|
||||
release()
|
||||
require.False(t, started)
|
||||
require.False(t, c.Writer.Written())
|
||||
require.Empty(t, recorder.Body.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
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"
|
||||
)
|
||||
|
||||
type stickyWritebackContextKey struct{}
|
||||
|
||||
type stickyWritebackCall struct {
|
||||
err error
|
||||
groupID int64
|
||||
account int64
|
||||
session string
|
||||
ttl time.Duration
|
||||
value any
|
||||
deadline time.Time
|
||||
}
|
||||
|
||||
type stickyWritebackCache struct {
|
||||
service.GatewayCache
|
||||
accountID int64
|
||||
finished bool
|
||||
calls []stickyWritebackCall
|
||||
}
|
||||
|
||||
func (s *stickyWritebackCache) GetSessionAccountID(context.Context, int64, string) (int64, error) {
|
||||
return s.accountID, nil
|
||||
}
|
||||
|
||||
func (s *stickyWritebackCache) SetSessionAccountID(ctx context.Context, groupID int64, session string, account int64, ttl time.Duration) error {
|
||||
if s.finished {
|
||||
deadline, _ := ctx.Deadline()
|
||||
s.calls = append(s.calls, stickyWritebackCall{
|
||||
err: ctx.Err(), groupID: groupID, account: account, session: session, ttl: ttl,
|
||||
value: ctx.Value(stickyWritebackContextKey{}), deadline: deadline,
|
||||
})
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
s.accountID = account
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stickyWritebackCache) RefreshSessionTTL(context.Context, int64, string, time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stickyWritebackCache) DeleteSessionAccountID(context.Context, int64, string) error {
|
||||
s.accountID = 0
|
||||
return nil
|
||||
}
|
||||
|
||||
type stickyWritebackBody struct {
|
||||
io.Reader
|
||||
finish func()
|
||||
}
|
||||
|
||||
func (b *stickyWritebackBody) Close() error {
|
||||
b.finish()
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, stream := range []bool{false, true} {
|
||||
name := "buffered"
|
||||
if stream {
|
||||
name = "streaming"
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
bound int64
|
||||
cancel bool
|
||||
fail bool
|
||||
wantWrites int
|
||||
}{
|
||||
{name: "new binding", wantWrites: 1},
|
||||
{name: "new binding after disconnect", cancel: true, wantWrites: 1},
|
||||
{name: "refresh binding", bound: 9401, wantWrites: 1},
|
||||
{name: "refresh after disconnect", bound: 9401, cancel: true, wantWrites: 1},
|
||||
{name: "different binding", bound: 9499, cancel: true},
|
||||
{name: "forward failed", cancel: true, fail: true},
|
||||
} {
|
||||
t.Run(name+"/"+tt.name, func(t *testing.T) {
|
||||
groupID := int64(9400)
|
||||
group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1}
|
||||
account := &service.Account{
|
||||
ID: 9401, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive, Schedulable: true, Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "test-key"},
|
||||
Extra: map[string]any{"anthropic_passthrough": true},
|
||||
AccountGroups: []service.AccountGroup{{AccountID: 9401, GroupID: groupID}},
|
||||
}
|
||||
cache := &stickyWritebackCache{accountID: tt.bound}
|
||||
ctx := context.WithValue(context.Background(), stickyWritebackContextKey{}, "request-scoped value")
|
||||
ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
responseBody := `{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-4.5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`
|
||||
contentType := "application/json"
|
||||
if stream {
|
||||
responseBody = compatStreamUsagePartialStream + compatStreamUsageCompletion
|
||||
contentType = "text/event-stream"
|
||||
}
|
||||
status := http.StatusOK
|
||||
if tt.fail {
|
||||
status = http.StatusBadRequest
|
||||
responseBody = `{"type":"error","error":{"type":"invalid_request_error","message":"invalid input"}}`
|
||||
}
|
||||
upstream := &compatStreamUsageUpstream{response: &http.Response{
|
||||
StatusCode: status,
|
||||
Header: http.Header{"Content-Type": []string{contentType}},
|
||||
Body: &stickyWritebackBody{Reader: strings.NewReader(responseBody), finish: func() {
|
||||
// Forward closes its upstream body on return. Cancel precisely
|
||||
// after that work, before the handler's terminal sticky write.
|
||||
cache.finished = true
|
||||
if tt.cancel {
|
||||
cancel()
|
||||
}
|
||||
}},
|
||||
}}
|
||||
cfg := &config.Config{RunMode: config.RunModeSimple}
|
||||
other := *account
|
||||
other.ID = 9499
|
||||
other.Schedulable = false
|
||||
snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account, &other}}, nil, nil, nil, nil)
|
||||
gw := service.NewGatewayService(
|
||||
nil, &fakeGroupRepo{group: group}, nil, nil, nil, nil, nil, cache, cfg,
|
||||
snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream,
|
||||
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCache.Stop)
|
||||
h := &GatewayHandler{
|
||||
gatewayService: gw, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1,
|
||||
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
|
||||
}
|
||||
requestBody := `{"model":"claude-sonnet-4.5","max_tokens":16,"stream":false,"messages":[{"role":"user","content":"sticky writeback test"}]}`
|
||||
if stream {
|
||||
requestBody = strings.Replace(requestBody, `"stream":false`, `"stream":true`, 1)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(requestBody)).WithContext(ctx)
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
key := &service.APIKey{ID: 9402, UserID: 9403, GroupID: &groupID, Group: group, User: &service.User{ID: 9403, Balance: 100}}
|
||||
c.Set(string(middleware.ContextKeyAPIKey), key)
|
||||
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9403})
|
||||
|
||||
h.Messages(c)
|
||||
|
||||
require.Equal(t, 1, upstream.calls)
|
||||
require.True(t, cache.finished)
|
||||
require.Equal(t, status, rec.Code)
|
||||
if tt.cancel {
|
||||
require.ErrorIs(t, ctx.Err(), context.Canceled)
|
||||
}
|
||||
require.Len(t, cache.calls, tt.wantWrites)
|
||||
for _, call := range cache.calls {
|
||||
require.NoError(t, call.err, "a completed upstream request must retain its terminal sticky write")
|
||||
require.Equal(t, groupID, call.groupID)
|
||||
require.Equal(t, account.ID, call.account)
|
||||
require.NotEmpty(t, call.session)
|
||||
require.Positive(t, call.ttl)
|
||||
require.Equal(t, "request-scoped value", call.value)
|
||||
require.False(t, call.deadline.IsZero(), "the detached cache write must have a deadline")
|
||||
require.WithinDuration(t, time.Now(), call.deadline, 5*time.Second)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -364,7 +364,7 @@ func NewOpenAIGatewayHandler(
|
||||
opsService *service.OpsService,
|
||||
cfg *config.Config,
|
||||
) *OpenAIGatewayHandler {
|
||||
pingInterval := time.Duration(0)
|
||||
pingInterval := defaultPingInterval
|
||||
maxAccountSwitches := 3
|
||||
if cfg != nil {
|
||||
pingInterval = time.Duration(cfg.Concurrency.PingInterval) * time.Second
|
||||
@@ -489,9 +489,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
} else if changed {
|
||||
body = cappedBody
|
||||
}
|
||||
if normalizedBody, changed := normalizeCodexPageContext(body); changed {
|
||||
if normalizedBody, changed := normalizeCodexUntrustedContext(body); changed {
|
||||
body = normalizedBody
|
||||
reqLog.Info("openai.codex_page_context_normalized",
|
||||
reqLog.Info("openai.codex_untrusted_context_normalized",
|
||||
zap.String("normalization", "call_output_to_user_message"),
|
||||
)
|
||||
}
|
||||
@@ -1413,7 +1413,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
defaultMappedModel := strings.TrimSpace(effectiveMappedModel)
|
||||
// 应用渠道模型映射到请求体
|
||||
forwardBody := mappedBodyForMessages(channelMappingMsg.Mapped, channelMappingMsg.MappedModel)
|
||||
writerSizeBeforeForward := c.Writer.Size()
|
||||
writerSizeBeforeForward := service.OpenAICompactKeepaliveAdjustedWrittenSize(c)
|
||||
result, err := func() (*service.OpenAIForwardResult, error) {
|
||||
defer func() {
|
||||
if accountReleaseFunc != nil {
|
||||
@@ -1501,11 +1501,16 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
)
|
||||
return
|
||||
}
|
||||
if c.Writer.Size() != writerSizeBeforeForward {
|
||||
if !openAIForwardMayFailover(c, writerSizeBeforeForward, failoverErr) {
|
||||
h.gatewayService.ObserveOpenAIAccountHealthFailure(c.Request.Context(), account, err)
|
||||
h.handleAnthropicFailoverExhausted(c, failoverErr, true)
|
||||
return
|
||||
}
|
||||
// Only keepalive bytes were written, so failover may continue, but
|
||||
// every later error must be written as an SSE event.
|
||||
if c.Writer.Written() {
|
||||
streamStarted = true
|
||||
}
|
||||
if failoverErr.ShouldReportAccountScheduleFailure() {
|
||||
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, currentRoutingModel, false, nil), false, nil, err)
|
||||
}
|
||||
@@ -1663,16 +1668,24 @@ func (h *OpenAIGatewayHandler) handleAnthropicFailoverExhausted(c *gin.Context,
|
||||
h.anthropicStreamingAwareError(c, status, "api_error", failoverErr.ClientMessage, streamStarted)
|
||||
return
|
||||
}
|
||||
// A failed or error frame that triggered the failover no longer reaches the
|
||||
// client in-band, so its error passthrough rule is applied here instead.
|
||||
if status, errType, msg, ok := service.ApplyOpenAIStreamFailedFrameRule(c, failoverErr); ok {
|
||||
h.anthropicStreamingAwareError(c, status, errType, msg, streamStarted)
|
||||
return
|
||||
}
|
||||
status, errType, errMsg := h.mapUpstreamError(failoverErr.StatusCode)
|
||||
h.anthropicStreamingAwareError(c, status, errType, errMsg, streamStarted)
|
||||
}
|
||||
|
||||
// ensureAnthropicErrorResponse writes a fallback Anthropic error if no response was written.
|
||||
func (h *OpenAIGatewayHandler) ensureAnthropicErrorResponse(c *gin.Context, streamStarted bool) bool {
|
||||
if c == nil || c.Writer == nil || c.Writer.Written() {
|
||||
// Keepalive pings alone do not count as a written response, but they do
|
||||
// commit the response as SSE, so the fallback must then be an SSE event.
|
||||
if c == nil || c.Writer == nil || service.OpenAICompactKeepaliveAdjustedWrittenSize(c) >= 0 {
|
||||
return false
|
||||
}
|
||||
h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted)
|
||||
h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted || c.Writer.Written())
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/model"
|
||||
"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"
|
||||
"github.com/tidwall/gjson"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const (
|
||||
preContentHandlerCreated = `data: {"type":"response.created","response":{"id":"resp_pc","object":"response","model":"gpt-5.4","status":"in_progress","output":[]}}` + "\n\n"
|
||||
preContentHandlerFailed = `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"An error occurred while processing your request."}}}` + "\n\n"
|
||||
preContentHandlerSuccess = preContentHandlerCreated +
|
||||
`data: {"type":"response.output_item.added","output_index":0,"item":{"id":"msg_1","type":"message","role":"assistant","content":[]}}` + "\n\n" +
|
||||
`data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"answer from second account"}` + "\n\n" +
|
||||
`data: {"type":"response.completed","response":{"id":"resp_pc","object":"response","model":"gpt-5.4","status":"completed","output":[],"usage":{"input_tokens":3,"output_tokens":4,"total_tokens":7}}}` + "\n\n"
|
||||
)
|
||||
|
||||
// preContentFailoverUpstream hands each upstream request to respond, which
|
||||
// gets the 1-based call number.
|
||||
type preContentFailoverUpstream struct {
|
||||
service.HTTPUpstream
|
||||
mu sync.Mutex
|
||||
hits []int64
|
||||
respond func(call int) (*http.Response, error)
|
||||
}
|
||||
|
||||
func (u *preContentFailoverUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) {
|
||||
if req.Body != nil {
|
||||
_, _ = io.Copy(io.Discard, req.Body)
|
||||
}
|
||||
u.mu.Lock()
|
||||
u.hits = append(u.hits, accountID)
|
||||
call := len(u.hits)
|
||||
u.mu.Unlock()
|
||||
return u.respond(call)
|
||||
}
|
||||
|
||||
func (u *preContentFailoverUpstream) calls() int {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
return len(u.hits)
|
||||
}
|
||||
|
||||
func preContentSSEResponse(body io.ReadCloser) *http.Response {
|
||||
return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: body}
|
||||
}
|
||||
|
||||
// preContentStallThenFail stalls past one keepalive tick after the first event
|
||||
// and then fails with failed.
|
||||
func preContentStallThenFail(failed string) *http.Response {
|
||||
pr, pw := io.Pipe()
|
||||
go func() {
|
||||
_, _ = io.WriteString(pw, preContentHandlerCreated)
|
||||
time.Sleep(1300 * time.Millisecond)
|
||||
_, _ = io.WriteString(pw, failed)
|
||||
_ = pw.Close()
|
||||
}()
|
||||
return preContentSSEResponse(pr)
|
||||
}
|
||||
|
||||
type unexpectedEOFReader struct{}
|
||||
|
||||
func (unexpectedEOFReader) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
|
||||
|
||||
type preContentFailoverScenario struct {
|
||||
accounts []service.Account
|
||||
respond func(call int) (*http.Response, error)
|
||||
passthrough *service.ErrorPassthroughService
|
||||
requestBody string
|
||||
}
|
||||
|
||||
func preContentAccounts(count int) []service.Account {
|
||||
accounts := make([]service.Account, 0, count)
|
||||
for i := 0; i < count; i++ {
|
||||
accounts = append(accounts, service.Account{
|
||||
ID: int64(9201 + i), Name: "openai-apikey", Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: i + 1,
|
||||
Credentials: map[string]any{"api_key": "sk-test", "base_url": "http://upstream.example"},
|
||||
})
|
||||
}
|
||||
return accounts
|
||||
}
|
||||
|
||||
func servePreContentFailoverMessages(t *testing.T, accountCount int) (*httptest.ResponseRecorder, *preContentFailoverUpstream) {
|
||||
t.Helper()
|
||||
return serveMessagesScenario(t, preContentFailoverScenario{
|
||||
accounts: preContentAccounts(accountCount),
|
||||
respond: func(call int) (*http.Response, error) {
|
||||
if call == 1 {
|
||||
return preContentStallThenFail(preContentHandlerFailed), nil
|
||||
}
|
||||
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerSuccess))), nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func serveMessagesScenario(t *testing.T, sc preContentFailoverScenario) (*httptest.ResponseRecorder, *preContentFailoverUpstream) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
groupID := int64(9101)
|
||||
repo := &grokCredentialHandlerRepo{accounts: sc.accounts, missingOnGet: map[int64]bool{}}
|
||||
upstream := &preContentFailoverUpstream{respond: sc.respond}
|
||||
cfg := &config.Config{RunMode: config.RunModeSimple}
|
||||
cfg.Gateway.MaxAccountSwitches = 3
|
||||
cfg.Gateway.StreamKeepaliveInterval = 1
|
||||
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
|
||||
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
t.Cleanup(billingCache.Stop)
|
||||
gateway := service.NewOpenAIGatewayService(
|
||||
repo, nil, nil, nil, nil, nil, nil, cfg, nil, nil,
|
||||
service.NewBillingService(cfg, nil), nil, billingCache, upstream,
|
||||
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
cache := &concurrencyCacheMock{
|
||||
acquireUserSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil },
|
||||
acquireAccountSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil },
|
||||
}
|
||||
h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(cache), billingCache, &service.APIKeyService{}, nil, sc.passthrough, nil, nil, cfg)
|
||||
apiKey := &service.APIKey{
|
||||
ID: 9102, GroupID: &groupID,
|
||||
User: &service.User{ID: 9103, Status: service.StatusActive},
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive, AllowMessagesDispatch: true},
|
||||
}
|
||||
router := gin.New()
|
||||
router.Use(func(c *gin.Context) {
|
||||
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
|
||||
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1})
|
||||
service.BindErrorPassthroughService(c, sc.passthrough)
|
||||
c.Next()
|
||||
})
|
||||
router.POST("/v1/messages", h.Messages)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
requestBody := sc.requestBody
|
||||
if requestBody == "" {
|
||||
requestBody = `{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":true}`
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewBufferString(requestBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(rec, req)
|
||||
return rec, upstream
|
||||
}
|
||||
|
||||
// requireEndsWithSSEError checks that a response already committed as SSE ends
|
||||
// with an Anthropic error event and never carries a bare JSON line.
|
||||
func requireEndsWithSSEError(t *testing.T, body string) {
|
||||
t.Helper()
|
||||
lastEvent := body[strings.LastIndex(strings.TrimRight(body, "\n"), "\n\n")+2:]
|
||||
require.True(t, strings.HasPrefix(lastEvent, "event: error\ndata: {"), "last event: %q", lastEvent)
|
||||
require.Contains(t, lastEvent, `"type":"error"`)
|
||||
for _, line := range strings.Split(body, "\n") {
|
||||
require.False(t, strings.HasPrefix(line, "{"), "bare JSON line in SSE body: %q", line)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIMessagesFailsOverAfterKeepaliveOnlyWrite(t *testing.T) {
|
||||
rec, upstream := servePreContentFailoverMessages(t, 2)
|
||||
|
||||
body := rec.Body.String()
|
||||
require.Equal(t, 2, upstream.calls(), "body: %q", body)
|
||||
require.Equal(t, 1, strings.Count(body, "event: message_start"), "body: %q", body)
|
||||
require.Contains(t, body, "answer from second account")
|
||||
}
|
||||
|
||||
func TestOpenAIMessagesKeepaliveThenFailoverExhaustedEndsWithSSEError(t *testing.T) {
|
||||
rec, upstream := servePreContentFailoverMessages(t, 1)
|
||||
|
||||
body := rec.Body.String()
|
||||
require.Equal(t, 1, upstream.calls(), "body: %q", body)
|
||||
require.Contains(t, body, "event: ping")
|
||||
requireEndsWithSSEError(t, body)
|
||||
}
|
||||
|
||||
func TestOpenAIMessagesFailoverThenSecondAccountReadErrorEndsWithSSEError(t *testing.T) {
|
||||
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
|
||||
accounts: preContentAccounts(2),
|
||||
respond: func(call int) (*http.Response, error) {
|
||||
if call == 1 {
|
||||
return preContentStallThenFail(preContentHandlerFailed), nil
|
||||
}
|
||||
return preContentSSEResponse(io.NopCloser(unexpectedEOFReader{})), nil
|
||||
},
|
||||
})
|
||||
|
||||
body := rec.Body.String()
|
||||
require.Equal(t, 2, upstream.calls(), "body: %q", body)
|
||||
require.NotContains(t, body, "message_start")
|
||||
requireEndsWithSSEError(t, body)
|
||||
}
|
||||
|
||||
func TestOpenAIMessagesFailoverThenSecondAccountCredentialErrorEndsWithSSEError(t *testing.T) {
|
||||
accounts := preContentAccounts(2)
|
||||
accounts[1].Credentials = map[string]any{"base_url": "http://upstream.example"}
|
||||
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
|
||||
accounts: accounts,
|
||||
respond: func(call int) (*http.Response, error) {
|
||||
return preContentStallThenFail(preContentHandlerFailed), nil
|
||||
},
|
||||
})
|
||||
|
||||
body := rec.Body.String()
|
||||
require.Equal(t, 1, upstream.calls(), "body: %q", body)
|
||||
require.NotContains(t, body, "message_start")
|
||||
requireEndsWithSSEError(t, body)
|
||||
}
|
||||
|
||||
func TestOpenAIMessagesSlotAcquireFailureAfterKeepaliveIsSSE(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
|
||||
c.Header("Content-Type", "text/event-stream")
|
||||
_, err := io.WriteString(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n")
|
||||
require.NoError(t, err)
|
||||
streamStarted := true
|
||||
|
||||
h := &OpenAIGatewayHandler{}
|
||||
selection := &service.AccountSelectionResult{Account: &service.Account{ID: 9201}}
|
||||
_, result := h.acquireResponsesAccountSlot(c, nil, "", selection, true, &streamStarted, zap.NewNop())
|
||||
|
||||
require.Equal(t, openAISlotAcquireFailed, result)
|
||||
body := rec.Body.String()
|
||||
lastEvent := body[strings.LastIndex(strings.TrimRight(body, "\n"), "\n\n")+2:]
|
||||
require.True(t, strings.HasPrefix(lastEvent, "event: error\ndata: {"), "last event: %q", lastEvent)
|
||||
}
|
||||
|
||||
func newFailedFrameCodeRule(code string) *service.ErrorPassthroughService {
|
||||
status := http.StatusTeapot
|
||||
rule := &model.ErrorPassthroughRule{
|
||||
ID: 1, Name: "frame code rule", Enabled: true, Priority: 1,
|
||||
Keywords: []string{code}, MatchMode: model.MatchModeAny,
|
||||
Platforms: []string{model.PlatformOpenAI}, ResponseCode: &status, PassthroughBody: true,
|
||||
}
|
||||
return service.NewErrorPassthroughService(&errorPassthroughRepoStub{rules: []*model.ErrorPassthroughRule{rule}}, nil)
|
||||
}
|
||||
|
||||
// A failed frame that triggers a failover is no longer written in-band, so its
|
||||
// passthrough rule has to apply once the failover is exhausted. The rule is
|
||||
// keyed on the frame's own code, which the generic failover envelope lacks.
|
||||
func TestOpenAIMessagesFailoverExhaustedAppliesFailedFrameRule(t *testing.T) {
|
||||
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
|
||||
accounts: preContentAccounts(1),
|
||||
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
|
||||
respond: func(call int) (*http.Response, error) {
|
||||
failed := `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}}` + "\n\n"
|
||||
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerCreated + failed))), nil
|
||||
},
|
||||
})
|
||||
|
||||
body := rec.Body.String()
|
||||
t.Logf("status=%d body=%q", rec.Code, body)
|
||||
require.Equal(t, 1, upstream.calls(), "body: %q", body)
|
||||
require.Equal(t, http.StatusTeapot, rec.Code, "body: %q", body)
|
||||
require.Equal(t, "upstream_error", gjson.Get(body, "error.type").String(), "body: %q", body)
|
||||
require.Equal(t, "Rate limit reached for gpt-5.4", gjson.Get(body, "error.message").String(), "body: %q", body)
|
||||
}
|
||||
|
||||
const preContentRateLimitFailed = `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}}` + "\n\n"
|
||||
|
||||
func requireFailedFrameRuleJSON(t *testing.T, rec *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
body := rec.Body.String()
|
||||
t.Logf("status=%d content-type=%q body=%q", rec.Code, rec.Header().Get("Content-Type"), body)
|
||||
require.Equal(t, http.StatusTeapot, rec.Code, "body: %q", body)
|
||||
require.Contains(t, rec.Header().Get("Content-Type"), "application/json")
|
||||
require.Equal(t, "upstream_error", gjson.Get(body, "error.type").String(), "body: %q", body)
|
||||
require.Equal(t, "Rate limit reached for gpt-5.4", gjson.Get(body, "error.message").String(), "body: %q", body)
|
||||
}
|
||||
|
||||
// The failed frame is the first event of the stream, so it triggers the
|
||||
// failover before any output and used to reach the generic mapping unchecked.
|
||||
func TestOpenAIMessagesFirstEventFailedFrameExhaustedAppliesRule(t *testing.T) {
|
||||
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
|
||||
accounts: preContentAccounts(1),
|
||||
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
|
||||
respond: func(call int) (*http.Response, error) {
|
||||
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentRateLimitFailed))), nil
|
||||
},
|
||||
})
|
||||
|
||||
require.Equal(t, 1, upstream.calls())
|
||||
requireFailedFrameRuleJSON(t, rec)
|
||||
}
|
||||
|
||||
func TestOpenAIMessagesNonStreamFailedFrameExhaustedAppliesRule(t *testing.T) {
|
||||
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
|
||||
accounts: preContentAccounts(1),
|
||||
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
|
||||
requestBody: `{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":false}`,
|
||||
respond: func(call int) (*http.Response, error) {
|
||||
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerCreated + preContentRateLimitFailed))), nil
|
||||
},
|
||||
})
|
||||
|
||||
require.Equal(t, 1, upstream.calls())
|
||||
requireFailedFrameRuleJSON(t, rec)
|
||||
}
|
||||
|
||||
// A failover triggered by an HTTP status keeps the built-in exhaustion mapping:
|
||||
// no passthrough rule is looked up for it.
|
||||
func TestOpenAIMessagesHTTPStatusFailoverExhaustedIgnoresPassthroughRule(t *testing.T) {
|
||||
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
|
||||
accounts: preContentAccounts(1),
|
||||
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
|
||||
respond: func(call int) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusBadGateway,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}`)),
|
||||
}, nil
|
||||
},
|
||||
})
|
||||
|
||||
body := rec.Body.String()
|
||||
t.Logf("status=%d body=%q", rec.Code, body)
|
||||
require.Equal(t, 1, upstream.calls(), "body: %q", body)
|
||||
require.NotEqual(t, http.StatusTeapot, rec.Code, "body: %q", body)
|
||||
require.Equal(t, "Upstream service temporarily unavailable", gjson.Get(body, "error.message").String(), "body: %q", body)
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/iotest"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
type nativeEndpointUpstream struct {
|
||||
service.HTTPUpstream
|
||||
mode string
|
||||
paths []string
|
||||
}
|
||||
|
||||
func (u *nativeEndpointUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
u.paths = append(u.paths, req.URL.Path)
|
||||
if u.mode == "transport error" {
|
||||
return nil, errors.New("synthetic upstream transport failure")
|
||||
}
|
||||
body, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}}
|
||||
switch u.mode {
|
||||
case "HTTP error":
|
||||
response.StatusCode = http.StatusBadRequest
|
||||
response.Body = io.NopCloser(strings.NewReader(`{"error":{"type":"invalid_request_error","message":"synthetic rejection"}}`))
|
||||
case "body read error":
|
||||
response.Body = io.NopCloser(iotest.ErrReader(errors.New("synthetic body read failure")))
|
||||
default:
|
||||
if gjson.GetBytes(body, "stream").Bool() {
|
||||
response.Header.Set("Content-Type", "text/event-stream")
|
||||
response.Body = io.NopCloser(strings.NewReader(compatStreamUsagePartialStream + compatStreamUsageCompletion))
|
||||
} else {
|
||||
response.Body = io.NopCloser(strings.NewReader(`{"id":"msg_1","type":"message","role":"assistant","model":"k3","content":[{"type":"text","text":"partial"}],"stop_reason":"end_turn","usage":{"input_tokens":12,"output_tokens":7}}`))
|
||||
}
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (u *nativeEndpointUpstream) DoWithTLS(req *http.Request, proxy string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
return u.Do(req, proxy, accountID, concurrency)
|
||||
}
|
||||
|
||||
func TestOpenAINativeAnthropicEndpointDiagnostics(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, route := range []struct {
|
||||
name string
|
||||
path string
|
||||
protocol string
|
||||
platform string
|
||||
}{
|
||||
{"messages", "/v1/messages", service.APIProtocolAnthropic, service.PlatformKimi},
|
||||
{"chat", "/v1/chat/completions", service.APIProtocolAnthropic, service.PlatformKimi},
|
||||
{"responses", "/v1/responses", service.APIProtocolAnthropic, service.PlatformKimi},
|
||||
{"adaptive messages", "/v1/messages", service.APIProtocolAdaptive, service.PlatformZhipu},
|
||||
} {
|
||||
for _, stream := range []bool{false, true} {
|
||||
for _, mode := range []string{"transport error", "HTTP error", "body read error", "success"} {
|
||||
t.Run(fmt.Sprintf("%s/stream=%t/%s", route.name, stream, mode), func(t *testing.T) {
|
||||
upstream := &nativeEndpointUpstream{mode: mode}
|
||||
cfg := &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{AllowInsecureHTTP: true}}}
|
||||
gateway := service.NewOpenAIGatewayService(
|
||||
nil, nil, nil, nil, nil, nil, nil, cfg, nil, nil, nil, nil, nil, upstream,
|
||||
nil, nil, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
account := &service.Account{
|
||||
ID: 9501, Platform: route.platform, Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "test-key", "api_protocol": route.protocol,
|
||||
"base_url": "http://anthropic.example",
|
||||
"api_base_urls": map[string]any{
|
||||
service.APIProtocolAnthropic: "http://anthropic.example",
|
||||
service.APIProtocolChatCompletions: "http://chat.example",
|
||||
},
|
||||
},
|
||||
}
|
||||
model := "k3"
|
||||
if route.protocol == service.APIProtocolAdaptive {
|
||||
require.False(t, account.SupportsNativeCNResponses())
|
||||
model = "glm-5.3"
|
||||
}
|
||||
request := map[string]any{"model": model, "stream": stream}
|
||||
if route.path == "/v1/responses" {
|
||||
request["input"] = "hello"
|
||||
} else {
|
||||
request["messages"] = []map[string]string{{"role": "user", "content": "hello"}}
|
||||
request["max_tokens"] = 32
|
||||
}
|
||||
body, err := json.Marshal(request)
|
||||
require.NoError(t, err)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, route.path, strings.NewReader(string(body)))
|
||||
// The same Gin context can retain an earlier attempt's protocol.
|
||||
service.SetActualOpenAIUpstreamEndpoint(c, EndpointChatCompletions)
|
||||
var result *service.OpenAIForwardResult
|
||||
switch route.path {
|
||||
case "/v1/messages":
|
||||
result, err = gateway.ForwardAsAnthropic(context.Background(), c, account, body, "", "")
|
||||
case "/v1/chat/completions":
|
||||
result, err = gateway.ForwardAsChatCompletions(context.Background(), c, account, body, "", "")
|
||||
default:
|
||||
result, err = gateway.Forward(context.Background(), c, account, body)
|
||||
}
|
||||
if mode == "success" {
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Equal(t, EndpointMessages, result.UpstreamEndpoint)
|
||||
require.Contains(t, recorder.Body.String(), "partial")
|
||||
} else {
|
||||
require.Error(t, err)
|
||||
if mode != "body read error" {
|
||||
require.Nil(t, result, "error diagnostics must work without a forward result")
|
||||
}
|
||||
}
|
||||
require.Len(t, upstream.paths, 1)
|
||||
require.True(t, strings.HasSuffix(upstream.paths[0], EndpointMessages), "the request actually used native Anthropic: %v", upstream.paths)
|
||||
// This is the endpoint reader used when writing operations errors and result-less usage.
|
||||
require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, account.Platform))
|
||||
require.Equal(t, EndpointMessages, service.GetActualOpenAIUpstreamEndpoint(c))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,10 +11,10 @@ import (
|
||||
|
||||
var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_([1-9][0-9]*)_of_([1-9][0-9]*)$`)
|
||||
|
||||
// Desktop injects page snapshots as standalone outputs, without a model tool call.
|
||||
// Keep them as untrusted user text, including on history replay and mixed bootstrap turns.
|
||||
func normalizeCodexPageContext(body []byte) ([]byte, bool) {
|
||||
if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_") || !hasUniqueJSONMembers(body) {
|
||||
// Codex injects external context as standalone outputs, without a model tool call.
|
||||
// Use the legacy user-message representation for HTTP Responses interoperability.
|
||||
func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) {
|
||||
if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_", "browser_info", "goal_objective", "untrusted_context") || !hasUniqueJSONMembers(body) {
|
||||
return body, false
|
||||
}
|
||||
var request map[string]json.RawMessage
|
||||
@@ -46,15 +46,19 @@ func normalizeCodexPageContext(body []byte) ([]byte, bool) {
|
||||
}
|
||||
}
|
||||
name, output := readString("name"), readString("output")
|
||||
if !validCodexPageContext(name, output) {
|
||||
if !validCodexUntrustedContext(name, output) {
|
||||
continue
|
||||
}
|
||||
text := "<external_" + name + ">" + output + "</external_" + name + ">"
|
||||
if validCodexPageContext(name, output) {
|
||||
text = "<external_" + name + ">\n" + output + "\n</external_" + name + ">"
|
||||
}
|
||||
message := map[string]any{
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
"content": []map[string]string{{
|
||||
"type": "input_text",
|
||||
"text": "<external_" + name + ">\n" + output + "\n</external_" + name + ">",
|
||||
"text": text,
|
||||
}},
|
||||
}
|
||||
encoded, err := json.Marshal(message)
|
||||
@@ -79,6 +83,15 @@ func normalizeCodexPageContext(body []byte) ([]byte, bool) {
|
||||
return encoded, true
|
||||
}
|
||||
|
||||
func validCodexUntrustedContext(name, output string) bool {
|
||||
switch name {
|
||||
case "browser_info", "goal_objective", "untrusted_context":
|
||||
return strings.TrimSpace(output) != ""
|
||||
default:
|
||||
return validCodexPageContext(name, output)
|
||||
}
|
||||
}
|
||||
|
||||
func validCodexPageContext(name, output string) bool {
|
||||
if name == "codex_apps_open_page" {
|
||||
return validCodexPageSnapshot(output)
|
||||
|
||||
@@ -34,7 +34,7 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) {
|
||||
require.Equal(t, 400, w.Code)
|
||||
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
|
||||
|
||||
got, changed := normalizeCodexPageContext(body)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
w = httptest.NewRecorder()
|
||||
c, _ = gin.CreateTestContext(w)
|
||||
@@ -49,14 +49,130 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) {
|
||||
require.False(t, item.Get("id").Exists())
|
||||
}
|
||||
require.Equal(t, "hello", gjson.GetBytes(got, "input.2.content").String())
|
||||
again, changed := normalizeCodexPageContext(got)
|
||||
again, changed := normalizeCodexUntrustedContext(got)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, got, again)
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) {
|
||||
// AdditionalContextToolOutput derives names from caller-provided context keys.
|
||||
// Codex 0.169.0 enables this representation by default (openai/codex#60487).
|
||||
for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
output := "external context\nline two"
|
||||
body := pageContextRequest(t, pageContextItem(name, output),
|
||||
map[string]any{"role": "user", "content": "continue"})
|
||||
h := &OpenAIGatewayHandler{}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
|
||||
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
w = httptest.NewRecorder()
|
||||
c, _ = gin.CreateTestContext(w)
|
||||
require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
|
||||
require.False(t, c.Writer.Written())
|
||||
item := gjson.GetBytes(got, "input.0")
|
||||
require.Equal(t, "message", item.Get("type").String())
|
||||
require.Equal(t, "user", item.Get("role").String())
|
||||
require.Equal(t, "<external_"+name+">"+output+"</external_"+name+">", item.Get("content.0.text").String())
|
||||
require.False(t, item.Get("call_id").Exists())
|
||||
require.Equal(t, "continue", gjson.GetBytes(got, "input.1.content").String())
|
||||
again, changed := normalizeCodexUntrustedContext(got)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, got, again)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutputs(t *testing.T) {
|
||||
for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} {
|
||||
for _, override := range []map[string]any{
|
||||
{"call_id": "call_real"},
|
||||
{"call_id": nil},
|
||||
{"call_id": 42},
|
||||
{"namespace": "other"},
|
||||
{"namespace": nil},
|
||||
{"namespace": 42},
|
||||
{"output": []any{map[string]any{"type": "encrypted_content", "encrypted_content": "sealed"}}},
|
||||
{"output": " "},
|
||||
{"output": nil},
|
||||
} {
|
||||
item := pageContextItem(name, "context")
|
||||
for key, value := range override {
|
||||
item[key] = value
|
||||
}
|
||||
body := pageContextRequest(t, item)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.False(t, changed, "name=%s override=%v", name, override)
|
||||
require.Equal(t, body, got)
|
||||
}
|
||||
item := pageContextItem(name, "context")
|
||||
delete(item, "namespace")
|
||||
body := pageContextRequest(t, item)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, got)
|
||||
}
|
||||
// Recognized external context cannot make an unrelated tool result valid.
|
||||
body := pageContextRequest(t, pageContextItem("browser_info", "tab"),
|
||||
pageContextItem("read_file", "result"))
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
h := &OpenAIGatewayHandler{}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
require.False(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
|
||||
require.Equal(t, 400, w.Code)
|
||||
|
||||
// Keep historical calls, prior response and exact numeric metadata intact.
|
||||
body = []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"goal_objective","output":"finish"}]}`)
|
||||
got, changed = normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "resp_history", gjson.GetBytes(got, "previous_response_id").String())
|
||||
require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw)
|
||||
for _, index := range []string{"input.0", "input.1"} {
|
||||
require.JSONEq(t, gjson.GetBytes(body, index).Raw, gjson.GetBytes(got, index).Raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAdditionalUntrustedContextBlankCallIDsAndMixedInput(t *testing.T) {
|
||||
names := []string{"browser_info", "goal_objective", "untrusted_context"}
|
||||
for _, callID := range []string{"", " \t\n"} {
|
||||
items := make([]any, 0, len(names))
|
||||
for _, name := range names {
|
||||
item := pageContextItem(name, "context for "+name)
|
||||
item["call_id"] = callID
|
||||
delete(item, "id")
|
||||
items = append(items, item)
|
||||
}
|
||||
got, changed := normalizeCodexUntrustedContext(pageContextRequest(t, items...))
|
||||
require.True(t, changed)
|
||||
require.Len(t, gjson.GetBytes(got, "input").Array(), len(names))
|
||||
for i, item := range gjson.GetBytes(got, "input").Array() {
|
||||
require.Equal(t, "user", item.Get("role").String())
|
||||
require.Equal(t, "<external_"+names[i]+">context for "+names[i]+"</external_"+names[i]+">", item.Get("content.0.text").String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexAdditionalUntrustedContextRejectsDuplicateMembers(t *testing.T) {
|
||||
for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} {
|
||||
for _, body := range []string{
|
||||
`{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","call_id":"real","call_id":"","output":"context"}]}`,
|
||||
`{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","output":"first","output":"second"}]}`,
|
||||
} {
|
||||
got, changed := normalizeCodexUntrustedContext([]byte(body))
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, string(got))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T) {
|
||||
body := []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":\"page_1\"}"}]}`)
|
||||
got, changed := normalizeCodexPageContext(body)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, "resp_history", gjson.GetBytes(got, "previous_response_id").String())
|
||||
require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw)
|
||||
@@ -66,7 +182,7 @@ func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T
|
||||
|
||||
badTool := pageContextItem("read_file", "result")
|
||||
body = pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), badTool)
|
||||
got, changed = normalizeCodexPageContext(body)
|
||||
got, changed = normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
require.True(t, service.ValidateFunctionCallOutputContextBytes(got).HasFunctionCallOutputMissingCallID)
|
||||
}
|
||||
@@ -77,7 +193,7 @@ func TestNormalizeCodexPageContextMixedBootstrap(t *testing.T) {
|
||||
{"type": "function_call_output", "namespace": "codex_app", "name": "automation_update", "output": "<heartbeat><automation_id>test</automation_id></heartbeat>"},
|
||||
} {
|
||||
body := pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), item)
|
||||
got, changed := normalizeCodexPageContext(body)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
got, _ = normalizeCodexAutomationBootstrap(got)
|
||||
got, _ = normalizeCodexDelegationBootstrap(got)
|
||||
@@ -89,7 +205,7 @@ func TestNormalizeCodexPageContextMultipart(t *testing.T) {
|
||||
first := "Companion Page snapshot part 1 of 2:\n" + `{"page_id":"page1","document_view":"hello`
|
||||
second := "Companion Page snapshot part 2 of 2:\n" + ` world"}`
|
||||
body := pageContextRequest(t, pageContextItem("codex_apps_selected_page_part_1_of_2", first), pageContextItem("codex_apps_selected_page_part_2_of_2", second))
|
||||
got, changed := normalizeCodexPageContext(body)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.True(t, changed)
|
||||
require.Contains(t, gjson.GetBytes(got, "input.0.content.0.text").String(), first)
|
||||
require.Contains(t, gjson.GetBytes(got, "input.1.content.0.text").String(), second)
|
||||
@@ -119,7 +235,7 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T)
|
||||
item := pageContextItem("codex_apps_open_page", `{"page_id":null}`)
|
||||
item[tc.key] = tc.value
|
||||
body := pageContextRequest(t, item)
|
||||
got, changed := normalizeCodexPageContext(body)
|
||||
got, changed := normalizeCodexUntrustedContext(body)
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, got)
|
||||
})
|
||||
@@ -128,7 +244,7 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T)
|
||||
`{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","call_id":"real","call_id":"","output":"{\"page_id\":null}"}]}`,
|
||||
`{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":null}"}]} trailing`,
|
||||
} {
|
||||
got, changed := normalizeCodexPageContext([]byte(body))
|
||||
got, changed := normalizeCodexUntrustedContext([]byte(body))
|
||||
require.False(t, changed)
|
||||
require.Equal(t, body, string(got))
|
||||
}
|
||||
|
||||
@@ -417,6 +417,9 @@ func (h *UsageHandler) Stats(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
stats.TotalAccountCost = nil
|
||||
for i := range stats.Endpoints {
|
||||
stats.Endpoints[i].AccountCost = 0
|
||||
}
|
||||
stats.UpstreamEndpoints = nil
|
||||
stats.EndpointPaths = nil
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ func NewUserMsgQueueHelper(
|
||||
pingFormat SSEPingFormat,
|
||||
pingInterval time.Duration,
|
||||
) *UserMsgQueueHelper {
|
||||
if pingInterval <= 0 {
|
||||
if pingInterval < 0 {
|
||||
pingInterval = defaultPingInterval
|
||||
}
|
||||
return &UserMsgQueueHelper{
|
||||
@@ -86,7 +86,7 @@ func (h *UserMsgQueueHelper) waitForLockWithPing(
|
||||
streamStarted *bool,
|
||||
reqLog *zap.Logger,
|
||||
) (func(), error) {
|
||||
needPing := isStream && h.pingFormat != ""
|
||||
needPing := isStream && h.pingFormat != "" && h.pingInterval > 0
|
||||
|
||||
var flusher http.Flusher
|
||||
if needPing {
|
||||
@@ -196,7 +196,7 @@ func (h *UserMsgQueueHelper) ThrottleWithPing(
|
||||
)
|
||||
|
||||
// 延迟期间发送 SSE ping(复用 waitForLockWithPing 的 ping 逻辑)
|
||||
needPing := isStream && h.pingFormat != ""
|
||||
needPing := isStream && h.pingFormat != "" && h.pingInterval > 0
|
||||
var flusher http.Flusher
|
||||
if needPing {
|
||||
flusher, _ = c.Writer.(http.Flusher)
|
||||
|
||||
@@ -348,7 +348,7 @@ func (a *Alipay) Refund(ctx context.Context, req payment.RefundRequest) (*paymen
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outRequestNo := fmt.Sprintf("%s%s%d", req.OrderID, alipayRefundRequestSep, time.Now().UnixNano())
|
||||
outRequestNo := fmt.Sprintf("%s%s%s", req.OrderID, alipayRefundRequestSep, alipayRefundRequestNoSuffix(req.Amount))
|
||||
result, err := alipayTradeRefund(ctx, client, alipay.TradeRefund{
|
||||
OutTradeNo: req.OrderID,
|
||||
RefundAmount: req.Amount,
|
||||
@@ -374,6 +374,18 @@ func (a *Alipay) Refund(ctx context.Context, req payment.RefundRequest) (*paymen
|
||||
}, nil
|
||||
}
|
||||
|
||||
// alipayRefundRequestNoSuffix 生成跨重试稳定的 out_request_no 后缀。
|
||||
// 支付宝把相同的 out_request_no 视为同一次退款请求;如果重试换号,
|
||||
// "网关已受理但返回错误"后的重试会变成第二笔真实退款。
|
||||
// 与 wxpayRefundID 一致,用金额区分同一订单的不同退款金额。
|
||||
func alipayRefundRequestNoSuffix(amount string) string {
|
||||
normalized := strings.NewReplacer(".", "", "-", "").Replace(strings.TrimSpace(amount))
|
||||
if normalized == "" {
|
||||
return "0"
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
// QueryRefund 通过 alipay.trade.fastpay.refund.query 查询退款终态。refund_status 为 REFUND_SUCCESS
|
||||
// 表示成功;退款发起超过宽限期仍查不到记录表示支付宝未受理或退款失败;其余情况视为仍在处理中。
|
||||
func (a *Alipay) QueryRefund(ctx context.Context, req payment.RefundQueryRequest) (*payment.RefundResponse, error) {
|
||||
|
||||
@@ -480,6 +480,67 @@ func TestAlipayRefundRecordsOutRequestNoAsRefundID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// out_request_no 必须跨重试稳定:支付宝把相同的 out_request_no 视为同一次退款请求。
|
||||
// 如果重试生成新的请求号,一次"网关已受理但返回错误"的重试会退两次。
|
||||
func TestAlipayRefundOutRequestNoIsStableAcrossRetries(t *testing.T) {
|
||||
origRefund := alipayTradeRefund
|
||||
t.Cleanup(func() { alipayTradeRefund = origRefund })
|
||||
|
||||
var outRequestNos []string
|
||||
alipayTradeRefund = func(_ context.Context, _ *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) {
|
||||
outRequestNos = append(outRequestNos, param.OutRequestNo)
|
||||
return &alipay.TradeRefundRsp{TradeNo: "2026101522001", FundChange: alipayFundChangeYes}, nil
|
||||
}
|
||||
|
||||
provider := &Alipay{client: &alipay.Client{}}
|
||||
req := payment.RefundRequest{OrderID: "sub2_7", Amount: "12.50", Reason: "r"}
|
||||
for i := 0; i < 2; i++ {
|
||||
if _, err := provider.Refund(context.Background(), req); err != nil {
|
||||
t.Fatalf("Refund() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(outRequestNos) != 2 {
|
||||
t.Fatalf("got %d refund calls, want 2", len(outRequestNos))
|
||||
}
|
||||
if outRequestNos[0] != "sub2_7-refund-1250" {
|
||||
t.Fatalf("out_request_no = %q, want sub2_7-refund-1250", outRequestNos[0])
|
||||
}
|
||||
if outRequestNos[0] != outRequestNos[1] {
|
||||
t.Fatalf("out_request_no changed across retries: %q != %q", outRequestNos[0], outRequestNos[1])
|
||||
}
|
||||
}
|
||||
|
||||
// 模拟支付宝的幂等语义:相同的 out_request_no 只产生一笔真实退款。
|
||||
// 重试时如果请求号变了,钱会被退两次;稳定请求号下只退一次。
|
||||
func TestAlipayRefundRetryDoesNotDoubleRefund(t *testing.T) {
|
||||
origRefund := alipayTradeRefund
|
||||
t.Cleanup(func() { alipayTradeRefund = origRefund })
|
||||
|
||||
const refundCents = 1250
|
||||
refundedCents := 0
|
||||
seen := make(map[string]struct{})
|
||||
alipayTradeRefund = func(_ context.Context, _ *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) {
|
||||
if _, ok := seen[param.OutRequestNo]; !ok {
|
||||
seen[param.OutRequestNo] = struct{}{}
|
||||
refundedCents += refundCents
|
||||
}
|
||||
return &alipay.TradeRefundRsp{TradeNo: "2026101522001", FundChange: alipayFundChangeYes}, nil
|
||||
}
|
||||
|
||||
provider := &Alipay{client: &alipay.Client{}}
|
||||
req := payment.RefundRequest{OrderID: "sub2_7", Amount: "12.50", Reason: "r"}
|
||||
for i := 0; i < 2; i++ {
|
||||
if _, err := provider.Refund(context.Background(), req); err != nil {
|
||||
t.Fatalf("Refund() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if refundedCents != refundCents {
|
||||
t.Fatalf("retry refunded %d cents, want %d (one refund only)", refundedCents, refundCents)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlipayQueryRefundMapsStatus(t *testing.T) {
|
||||
origQuery := alipayTradeFastPayRefundQuery
|
||||
t.Cleanup(func() { alipayTradeFastPayRefundQuery = origQuery })
|
||||
|
||||
@@ -376,24 +376,15 @@ func cleanJSONSchemaRecursive(value any) any {
|
||||
}
|
||||
}
|
||||
|
||||
// 8. [SAFETY] 处理缺失 items 的 Array (Gemini 严苛要求 array 必须声明 items Schema)
|
||||
// 8. Gemini 只允许 array 携带 items,且 items 必须是非空 Schema 对象。
|
||||
if t, _ := schemaMap["type"].(string); t == "array" {
|
||||
itemsVal, hasItems := schemaMap["items"]
|
||||
needDefaultItems := false
|
||||
if !hasItems || itemsVal == nil {
|
||||
needDefaultItems = true
|
||||
} else if itemsMap, ok := itemsVal.(map[string]any); ok {
|
||||
if len(itemsMap) == 0 {
|
||||
needDefaultItems = true
|
||||
}
|
||||
} else if _, isBool := itemsVal.(bool); isBool {
|
||||
needDefaultItems = true
|
||||
}
|
||||
if needDefaultItems {
|
||||
if items, ok := schemaMap["items"].(map[string]any); !ok || len(items) == 0 {
|
||||
schemaMap["items"] = map[string]any{
|
||||
"type": "string",
|
||||
}
|
||||
}
|
||||
} else {
|
||||
delete(schemaMap, "items")
|
||||
}
|
||||
|
||||
// 9. [SAFETY] Required 字段对齐
|
||||
|
||||
@@ -206,6 +206,16 @@ func anthropicMsgToResponsesItems(m AnthropicMessage) ([]ResponsesInputItem, err
|
||||
return anthropicUserToResponses(m.Content)
|
||||
case "assistant":
|
||||
return anthropicAssistantToResponses(m.Content)
|
||||
case "system":
|
||||
// Mid-conversation system turns (e.g. hook output) keep system-level
|
||||
// authority: Responses uses developer for them, not user.
|
||||
items, err := anthropicUserToResponses(m.Content)
|
||||
for i := range items {
|
||||
if items[i].Role == "user" {
|
||||
items[i].Role = "developer"
|
||||
}
|
||||
}
|
||||
return items, err
|
||||
default:
|
||||
return anthropicUserToResponses(m.Content)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package apicompat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// A system message in the middle of an Anthropic conversation (e.g. hook
|
||||
// output) must reach Responses as a developer item, not as user input.
|
||||
func TestAnthropicToResponses_MidConversationSystemBecomesDeveloper(t *testing.T) {
|
||||
out, err := AnthropicToResponses(&AnthropicRequest{
|
||||
Model: "gpt-5.2",
|
||||
MaxTokens: 64,
|
||||
Messages: []AnthropicMessage{
|
||||
{Role: "user", Content: json.RawMessage(`"hi"`)},
|
||||
{Role: "system", Content: json.RawMessage(`[{"type":"text","text":"hook output"}]`)},
|
||||
{Role: "system", Content: json.RawMessage(`"extra context"`)},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
input := gjson.ParseBytes(out.Input).Array()
|
||||
require.Len(t, input, 3)
|
||||
require.Equal(t, "user", input[0].Get("role").String())
|
||||
require.Equal(t, "developer", input[1].Get("role").String())
|
||||
require.Equal(t, "hook output", input[1].Get("content.0.text").String())
|
||||
require.Equal(t, "developer", input[2].Get("role").String())
|
||||
require.Equal(t, "extra context", input[2].Get("content.0.text").String())
|
||||
}
|
||||
@@ -445,6 +445,38 @@ func TestChatCompletionsToResponses_ResponseFormatJsonSchema(t *testing.T) {
|
||||
}`, string(resp.Text.Format))
|
||||
}
|
||||
|
||||
func TestChatCompletionsToResponses_ResponseFormatJsonSchemaDefaultsStrictFalse(t *testing.T) {
|
||||
req := &ChatCompletionsRequest{
|
||||
Model: "gpt-4o",
|
||||
Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Return structured JSON"`)}},
|
||||
ResponseFormat: json.RawMessage(`{
|
||||
"type":"json_schema",
|
||||
"json_schema":{
|
||||
"name":"answer",
|
||||
"schema":{
|
||||
"type":"object",
|
||||
"properties":{"ok":{"type":"boolean"}},
|
||||
"required":["ok"]
|
||||
}
|
||||
}
|
||||
}`),
|
||||
}
|
||||
|
||||
resp, err := ChatCompletionsToResponses(req)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, resp.Text)
|
||||
assert.JSONEq(t, `{
|
||||
"type":"json_schema",
|
||||
"name":"answer",
|
||||
"schema":{
|
||||
"type":"object",
|
||||
"properties":{"ok":{"type":"boolean"}},
|
||||
"required":["ok"]
|
||||
},
|
||||
"strict":false
|
||||
}`, string(resp.Text.Format))
|
||||
}
|
||||
|
||||
func TestChatCompletionsToResponses_ImageURL(t *testing.T) {
|
||||
content := `[{"type":"text","text":"Describe this"},{"type":"image_url","image_url":{"url":"data:image/png;base64,abc123"}}]`
|
||||
req := &ChatCompletionsRequest{
|
||||
|
||||
@@ -23,6 +23,11 @@ func chatResponseFormatToResponsesTextFormat(raw json.RawMessage) json.RawMessag
|
||||
return raw
|
||||
}
|
||||
schema["type"] = rawJSONString("json_schema")
|
||||
// Chat Completions defaults strict to false while Responses defaults to strict,
|
||||
// so make the intended mode explicit to avoid the upstream rejecting the schema.
|
||||
if _, ok := schema["strict"]; !ok {
|
||||
schema["strict"] = json.RawMessage("false")
|
||||
}
|
||||
|
||||
out, err := json.Marshal(schema)
|
||||
if err != nil {
|
||||
|
||||
@@ -503,6 +503,7 @@ type bufferedFuncCall struct {
|
||||
Name string
|
||||
Namespace string
|
||||
EncryptedFunctionArgs json.RawMessage
|
||||
EncryptedContent string
|
||||
Args strings.Builder
|
||||
}
|
||||
|
||||
@@ -547,6 +548,7 @@ func (a *BufferedResponseAccumulator) ProcessEvent(event *ResponsesStreamEvent)
|
||||
Name: event.Item.Name,
|
||||
Namespace: event.Item.Namespace,
|
||||
EncryptedFunctionArgs: event.Item.EncryptedFunctionArgs,
|
||||
EncryptedContent: event.Item.EncryptedContent,
|
||||
})
|
||||
}
|
||||
case "response.function_call_arguments.delta", "response.custom_tool_call_input.delta":
|
||||
@@ -616,6 +618,7 @@ func (a *BufferedResponseAccumulator) BuildOutput() []ResponsesOutput {
|
||||
Name: a.funcCalls[i].Name,
|
||||
Namespace: a.funcCalls[i].Namespace,
|
||||
EncryptedFunctionArgs: a.funcCalls[i].EncryptedFunctionArgs,
|
||||
EncryptedContent: a.funcCalls[i].EncryptedContent,
|
||||
Arguments: a.funcCalls[i].Args.String(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ const (
|
||||
BetaContextManagement = "context-management-2025-06-27"
|
||||
BetaThinkingBindingControls = "thinking-binding-controls-2026-08-01"
|
||||
BetaMidConversationOutputConfig = "mid-conversation-output-config-2026-07-01"
|
||||
BetaPerTurnControl = "per-turn-control-2026-07-01"
|
||||
BetaExtendedCacheTTL = "extended-cache-ttl-2025-04-11"
|
||||
|
||||
// server-side refusal fallback beta 字段族(beta Messages API 专有)。
|
||||
@@ -253,7 +254,7 @@ func DefaultModelIDs() []string {
|
||||
}
|
||||
|
||||
// DefaultTestModel 测试时使用的默认模型
|
||||
const DefaultTestModel = "claude-sonnet-4-5-20250929"
|
||||
const DefaultTestModel = "claude-sonnet-4-6"
|
||||
|
||||
// ModelIDOverrides Claude OAuth 请求需要的模型 ID 映射
|
||||
var ModelIDOverrides = map[string]string{
|
||||
|
||||
@@ -111,8 +111,9 @@ type EndpointStat struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
Requests int64 `json:"requests"`
|
||||
TotalTokens int64 `json:"total_tokens"`
|
||||
Cost float64 `json:"cost"` // 标准计费
|
||||
ActualCost float64 `json:"actual_cost"` // 实际扣除
|
||||
Cost float64 `json:"cost"` // 标准计费
|
||||
ActualCost float64 `json:"actual_cost"` // 实际扣除
|
||||
AccountCost float64 `json:"account_cost,omitempty"` // 账号成本(仅管理员接口返回)
|
||||
}
|
||||
|
||||
// GroupUsageSummary represents today's, yesterday's, and cumulative cost for a single group.
|
||||
|
||||
@@ -2690,6 +2690,49 @@ func (r *accountRepository) ClearModelRateLimits(ctx context.Context, id int64)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearModelRateLimit 删除 model_rate_limits 中指定的单个 scope。
|
||||
// 与 ClearModelRateLimits 的全量清除不同,这里只解封一个模型窗口,
|
||||
// 不会把其他模型或并发新写入的限流一起抹掉。
|
||||
func (r *accountRepository) ClearModelRateLimit(ctx context.Context, id int64, scope string) error {
|
||||
if strings.TrimSpace(scope) == "" {
|
||||
return nil
|
||||
}
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.ClearModelRateLimit(ctx, id, scope)
|
||||
}
|
||||
client := clientFromContext(ctx, r.client)
|
||||
result, err := client.ExecContext(
|
||||
ctx,
|
||||
`UPDATE accounts SET
|
||||
extra = jsonb_set(
|
||||
COALESCE(extra, '{}'::jsonb),
|
||||
'{model_rate_limits}'::text[],
|
||||
COALESCE(extra->'model_rate_limits', '{}'::jsonb) - $1::text,
|
||||
true
|
||||
),
|
||||
updated_at = NOW()
|
||||
WHERE id = $2 AND deleted_at IS NULL`,
|
||||
strings.TrimSpace(scope),
|
||||
id,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return service.ErrAccountNotFound
|
||||
}
|
||||
if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &id, nil, nil); err != nil {
|
||||
logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue clear model rate limit scope failed: account=%d err=%v", id, err)
|
||||
}
|
||||
r.syncSchedulerAccountSnapshot(ctx, id)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *accountRepository) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error {
|
||||
builder := r.client.Account.Update().
|
||||
Where(dbaccount.IDEQ(id)).
|
||||
@@ -2714,8 +2757,11 @@ func (r *accountRepository) UpdateSessionWindow(ctx context.Context, id int64, s
|
||||
}
|
||||
|
||||
func (r *accountRepository) UpdateSessionWindowEnd(ctx context.Context, id int64, end time.Time) error {
|
||||
// Active five-hour quota reads must advance both bounds. Keeping the old
|
||||
// start would charge the previous window against the new window's cost limit.
|
||||
_, err := r.client.Account.Update().
|
||||
Where(dbaccount.IDEQ(id)).
|
||||
SetSessionWindowStart(end.Add(-5 * time.Hour)).
|
||||
SetSessionWindowEnd(end).
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
|
||||
@@ -2,11 +2,15 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/usagestats"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/stretchr/testify/suite"
|
||||
)
|
||||
@@ -61,6 +65,87 @@ func (s *ClaudeUsageServiceSuite) TestFetchUsage_Success() {
|
||||
require.Equal(s.T(), "oauth-2025-04-20", captured.anthropicBeta, "anthropic-beta header mismatch")
|
||||
}
|
||||
|
||||
type claudeUsageWindowAccountRepo struct {
|
||||
service.AccountRepository
|
||||
account *service.Account
|
||||
}
|
||||
|
||||
func (r *claudeUsageWindowAccountRepo) GetByID(context.Context, int64) (*service.Account, error) {
|
||||
return r.account, nil
|
||||
}
|
||||
|
||||
func (r *claudeUsageWindowAccountRepo) UpdateExtra(_ context.Context, _ int64, updates map[string]any) error {
|
||||
for key, value := range updates {
|
||||
r.account.Extra[key] = value
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type claudeUsageWindowLogRepo struct {
|
||||
service.UsageLogRepository
|
||||
}
|
||||
|
||||
func (*claudeUsageWindowLogRepo) GetAccountWindowStats(context.Context, int64, time.Time) (*usagestats.AccountStats, error) {
|
||||
return &usagestats.AccountStats{}, nil
|
||||
}
|
||||
|
||||
func TestClaudeUsageFetcher_ScopedFableRoundTrip(t *testing.T) {
|
||||
resetAt := time.Now().Add(72 * time.Hour).UTC().Truncate(time.Microsecond)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
percent string
|
||||
legacy string
|
||||
wantUsage float64
|
||||
}{
|
||||
{name: "scoped", percent: "5.25", wantUsage: 5.25},
|
||||
{name: "zero overrides passive", percent: "0", wantUsage: 0},
|
||||
{name: "missing falls back to passive", percent: "null", wantUsage: 87},
|
||||
{name: "legacy takes precedence", percent: "5.25", legacy: fmt.Sprintf(`{"utilization":56,"resets_at":%q}`, resetAt.Format(time.RFC3339Nano)), wantUsage: 56},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
legacy := tc.legacy
|
||||
if legacy == "" {
|
||||
legacy = "null"
|
||||
}
|
||||
requests := make(chan [2]string, 2)
|
||||
srv := newLocalTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests <- [2]string{r.Method, r.URL.Path}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = fmt.Fprintf(w, `{"five_hour":{"utilization":12},"seven_day_overage_included":%s,"limits":[{"kind":"weekly_scoped","group":"weekly","percent":%s,"resets_at":%q,"scope":{"model":{"display_name":"Fable"},"surface":null},"is_active":false}]}`, legacy, tc.percent, resetAt.Format(time.RFC3339Nano))
|
||||
}))
|
||||
defer srv.Close()
|
||||
fetcher := &claudeUsageService{usageURL: srv.URL + "/api/oauth/usage", allowPrivateHosts: true}
|
||||
account := &service.Account{
|
||||
ID: 1, Platform: service.PlatformAnthropic, Type: service.AccountTypeOAuth,
|
||||
Status: service.StatusActive, Credentials: map[string]any{"access_token": "test-token"},
|
||||
Extra: map[string]any{
|
||||
"passive_usage_7d_oi_utilization": 0.87,
|
||||
"passive_usage_7d_oi_reset": resetAt.Unix(),
|
||||
},
|
||||
}
|
||||
repo := &claudeUsageWindowAccountRepo{account: account}
|
||||
svc := service.NewAccountUsageService(repo, &claudeUsageWindowLogRepo{}, fetcher,
|
||||
nil, nil, nil, nil, nil, service.NewUsageCache(), nil, nil)
|
||||
for range 2 {
|
||||
usage, err := svc.GetUsageForAccount(t.Context(), account)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, usage.SevenDayFable)
|
||||
require.Equal(t, tc.wantUsage, usage.SevenDayFable.Utilization)
|
||||
require.NotNil(t, usage.SevenDayFable.ResetsAt)
|
||||
require.Equal(t, resetAt.Unix(), usage.SevenDayFable.ResetsAt.Unix())
|
||||
}
|
||||
passive, err := svc.GetPassiveUsage(t.Context(), account.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, passive.SevenDayFable)
|
||||
require.InDelta(t, tc.wantUsage, passive.SevenDayFable.Utilization, 1e-9)
|
||||
require.Equal(t, resetAt.Unix(), passive.SevenDayFable.ResetsAt.Unix())
|
||||
require.InDelta(t, tc.wantUsage/100, account.Extra["passive_usage_7d_oi_utilization"], 1e-9)
|
||||
require.Len(t, requests, 1, "the second query must reuse the decoded API response")
|
||||
require.Equal(t, [2]string{"GET", "/api/oauth/usage"}, <-requests)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ClaudeUsageServiceSuite) TestFetchUsage_NonOK() {
|
||||
s.srv = newLocalTestServer(s.T(), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
|
||||
@@ -3,6 +3,8 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
@@ -17,36 +19,43 @@ type groupUsageRollupSnapshot struct {
|
||||
valid bool
|
||||
closedBefore string // date,历史日桶的右开边界
|
||||
retainedDate string // retained_from 在服务端时区内的日期,历史日桶的左闭边界
|
||||
tailStart time.Time // 尾段(还没进日桶的那部分 usage_logs)的起点
|
||||
tailStart time.Time // 尾段(还没进日桶的那部分 usage_logs)的起点,不早于 expired_before
|
||||
}
|
||||
|
||||
// readGroupUsageRollupSnapshot 读一次汇总水位并在 Go 侧判定有效性。
|
||||
//
|
||||
// 判定条件与原先 SQL 里的 state_values CTE 完全一致:
|
||||
// 恰好一行、时区名与当前服务端配置相同、且水位不在未来。
|
||||
// expired_before 之前的 usage_logs 已超出保留期:无论水位是否有效都不进入尾段,
|
||||
// 其所在日之前的日桶也不读取。
|
||||
func (r *usageLogRepository) readGroupUsageRollupSnapshot(ctx context.Context, timezoneName, todayDate string) (groupUsageRollupSnapshot, error) {
|
||||
epoch := time.Unix(0, 0).UTC()
|
||||
invalid := groupUsageRollupSnapshot{
|
||||
closedBefore: "1970-01-01",
|
||||
retainedDate: "1970-01-01",
|
||||
tailStart: epoch,
|
||||
}
|
||||
|
||||
var rowCount int
|
||||
var closedBefore sql.NullString
|
||||
var retainedFrom sql.NullTime
|
||||
var stateTimezone sql.NullString
|
||||
var expiredBefore sql.NullTime
|
||||
if err := scanSingleRow(ctx, r.sql, `
|
||||
SELECT
|
||||
COUNT(*),
|
||||
MAX(closed_before)::text,
|
||||
MAX(retained_from),
|
||||
MAX(timezone_name)
|
||||
MAX(timezone_name),
|
||||
MAX(expired_before)
|
||||
FROM usage_group_rollup_state
|
||||
WHERE id = 1
|
||||
`, nil, &rowCount, &closedBefore, &retainedFrom, &stateTimezone); err != nil {
|
||||
`, nil, &rowCount, &closedBefore, &retainedFrom, &stateTimezone, &expiredBefore); err != nil {
|
||||
return groupUsageRollupSnapshot{}, fmt.Errorf("读取分组用量汇总水位: %w", err)
|
||||
}
|
||||
|
||||
tailFloor := time.Unix(0, 0).UTC()
|
||||
if rowCount == 1 && expiredBefore.Valid && expiredBefore.Time.After(tailFloor) {
|
||||
tailFloor = expiredBefore.Time.UTC()
|
||||
}
|
||||
invalid := groupUsageRollupSnapshot{
|
||||
closedBefore: "1970-01-01",
|
||||
retainedDate: "1970-01-01",
|
||||
tailStart: tailFloor,
|
||||
}
|
||||
if rowCount != 1 || !closedBefore.Valid || !retainedFrom.Valid ||
|
||||
!stateTimezone.Valid || stateTimezone.String != timezoneName ||
|
||||
closedBefore.String > todayDate {
|
||||
@@ -58,11 +67,19 @@ func (r *usageLogRepository) readGroupUsageRollupSnapshot(ctx context.Context, t
|
||||
// 水位值解析不出来,按无效处理:宁可多扫一次,也不要算错钱。
|
||||
return invalid, nil //nolint:nilerr // 与上面的 valid 判定同语义,均降级为全量重算
|
||||
}
|
||||
tailStart = tailStart.UTC()
|
||||
if tailFloor.After(tailStart) {
|
||||
tailStart = tailFloor
|
||||
}
|
||||
retainedDate := service.GroupUsageDate(retainedFrom.Time)
|
||||
if expiredDate := service.GroupUsageDate(tailFloor); expiredDate > retainedDate {
|
||||
retainedDate = expiredDate
|
||||
}
|
||||
return groupUsageRollupSnapshot{
|
||||
valid: true,
|
||||
closedBefore: closedBefore.String,
|
||||
retainedDate: service.GroupUsageDate(retainedFrom.Time),
|
||||
tailStart: tailStart.UTC(),
|
||||
retainedDate: retainedDate,
|
||||
tailStart: tailStart,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -162,94 +179,287 @@ func (r *usageLogRepository) getAllGroupUsageSummaryFromRollups(ctx context.Cont
|
||||
return results, nil
|
||||
}
|
||||
|
||||
const (
|
||||
groupUsageRollupBuildLockSQL = "SELECT pg_try_advisory_lock(hashtext('usage_group_daily_rollups:build'))"
|
||||
groupUsageRollupBuildUnlockSQL = "SELECT pg_advisory_unlock(hashtext('usage_group_daily_rollups:build'))"
|
||||
// groupUsageRollupBuildMaxRounds 限定一次同步内因并发变更重算脏区间的轮数;
|
||||
// 未收敛的部分保持未发布,由下一次同步继续。
|
||||
groupUsageRollupBuildMaxRounds = 3
|
||||
)
|
||||
|
||||
var errGroupUsageRollupBuildPreempted = errors.New("分组用量汇总重建登记已被替换")
|
||||
|
||||
// groupUsageRollupBuildPlan 是一轮日桶重建:用 [rowsFrom, rowsBefore) 的 usage_logs
|
||||
// 重算 [startDate, targetDate) 的日桶,并清理 retainedDate 之前的日桶。
|
||||
type groupUsageRollupBuildPlan struct {
|
||||
startDate string
|
||||
targetDate string
|
||||
retainedDate string
|
||||
rowsFrom time.Time
|
||||
rowsBefore time.Time
|
||||
timezoneName string
|
||||
}
|
||||
|
||||
// groupUsageRollupTxRunner 在一个事务里执行 fn。
|
||||
type groupUsageRollupTxRunner func(ctx context.Context, fn func(q sqlExecutor) error) error
|
||||
|
||||
// SyncGroupUsageRollups 将服务端配置时区今日以前的用量发布为分组日桶。
|
||||
//
|
||||
// 每轮分三个事务:登记(FOR UPDATE,写入 building_until)、计算(FOR KEY SHARE,重算日桶)、
|
||||
// 发布(FOR UPDATE,水位推进到 build_dirty_from 或目标日期)。usage_logs 写入与失效触发器只持
|
||||
// FOR KEY SHARE,因此只与登记、发布这两个短事务串行,计算阶段不阻塞写入。
|
||||
// 以 *sql.DB 构造时,整个过程持有会话级 advisory lock,同一时刻只有一个重建;
|
||||
// 以事务构造时,三个阶段在调用方事务内顺序执行。
|
||||
func (r *dashboardAggregationRepository) SyncGroupUsageRollups(ctx context.Context, todayStart time.Time) error {
|
||||
if r == nil || r.sql == nil {
|
||||
return nil
|
||||
}
|
||||
todayStart = service.GroupUsageTodayStart(todayStart)
|
||||
if db, ok := r.sql.(*sql.DB); ok {
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
db, ok := r.sql.(*sql.DB)
|
||||
if !ok {
|
||||
return syncGroupUsageRollupRounds(ctx, func(ctx context.Context, fn func(q sqlExecutor) error) error {
|
||||
return fn(r.sql)
|
||||
}, todayStart)
|
||||
}
|
||||
|
||||
upToDate, err := groupUsageRollupsUpToDate(ctx, db, todayStart)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if upToDate {
|
||||
return nil
|
||||
}
|
||||
|
||||
conn, err := db.Conn(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var locked bool
|
||||
if err := scanSingleRow(ctx, conn, groupUsageRollupBuildLockSQL, nil, &locked); err != nil {
|
||||
// 查询出错时服务端可能已授予锁,丢弃该物理连接以免锁随连接回到连接池。
|
||||
discardGroupUsageRollupBuildConn(conn)
|
||||
return fmt.Errorf("获取分组用量汇总重建锁: %w", err)
|
||||
}
|
||||
if !locked {
|
||||
return conn.Close()
|
||||
}
|
||||
defer releaseGroupUsageRollupBuildLock(conn)
|
||||
|
||||
return syncGroupUsageRollupRounds(ctx, func(ctx context.Context, fn func(q sqlExecutor) error) error {
|
||||
tx, err := conn.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
txRepo := newDashboardAggregationRepositoryWithSQL(tx)
|
||||
if err := txRepo.syncGroupUsageRollupsInTx(ctx, todayStart); err != nil {
|
||||
if err := fn(tx); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
return r.syncGroupUsageRollupsInTx(ctx, todayStart)
|
||||
}, todayStart)
|
||||
}
|
||||
|
||||
func (r *dashboardAggregationRepository) syncGroupUsageRollupsInTx(ctx context.Context, todayStart time.Time) error {
|
||||
// releaseGroupUsageRollupBuildLock 释放重建锁;释放失败时丢弃该物理连接,由服务端随会话结束释放锁,
|
||||
// 避免锁随连接回到连接池。
|
||||
func releaseGroupUsageRollupBuildLock(conn *sql.Conn) {
|
||||
unlockCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
var unlocked bool
|
||||
if err := scanSingleRow(unlockCtx, conn, groupUsageRollupBuildUnlockSQL, nil, &unlocked); err != nil || !unlocked {
|
||||
discardGroupUsageRollupBuildConn(conn)
|
||||
return
|
||||
}
|
||||
_ = conn.Close()
|
||||
}
|
||||
|
||||
// discardGroupUsageRollupBuildConn 关闭底层物理连接而不是归还连接池,会话级锁随会话结束释放。
|
||||
func discardGroupUsageRollupBuildConn(conn *sql.Conn) {
|
||||
_ = conn.Raw(func(any) error { return driver.ErrBadConn })
|
||||
_ = conn.Close()
|
||||
}
|
||||
|
||||
// groupUsageRollupsUpToDate 不加锁地判断今日以前的日桶是否已全部发布。
|
||||
func groupUsageRollupsUpToDate(ctx context.Context, q sqlQueryer, todayStart time.Time) (bool, error) {
|
||||
var closedBefore string
|
||||
var previousRetainedFrom time.Time
|
||||
var stateTimezoneName string
|
||||
if err := scanSingleRow(ctx, r.sql, `
|
||||
SELECT closed_before::text, retained_from, timezone_name
|
||||
var idle bool
|
||||
err := scanSingleRow(ctx, q, `
|
||||
SELECT closed_before::text, timezone_name, building_until IS NULL
|
||||
FROM usage_group_rollup_state
|
||||
WHERE id = 1
|
||||
`, nil, &closedBefore, &stateTimezoneName, &idle)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("读取分组用量汇总水位: %w", err)
|
||||
}
|
||||
return idle &&
|
||||
closedBefore == service.GroupUsageDate(todayStart) &&
|
||||
stateTimezoneName == service.GroupUsageTimezoneName(), nil
|
||||
}
|
||||
|
||||
func syncGroupUsageRollupRounds(ctx context.Context, run groupUsageRollupTxRunner, todayStart time.Time) error {
|
||||
for range groupUsageRollupBuildMaxRounds {
|
||||
var plan *groupUsageRollupBuildPlan
|
||||
if err := run(ctx, func(q sqlExecutor) error {
|
||||
var err error
|
||||
plan, err = beginGroupUsageRollupBuild(ctx, q, todayStart)
|
||||
return err
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if plan == nil {
|
||||
return nil
|
||||
}
|
||||
if err := run(ctx, func(q sqlExecutor) error {
|
||||
return buildGroupUsageRollups(ctx, q, plan)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
var dirty bool
|
||||
if err := run(ctx, func(q sqlExecutor) error {
|
||||
var err error
|
||||
dirty, err = publishGroupUsageRollups(ctx, q, plan)
|
||||
return err
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if !dirty {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// beginGroupUsageRollupBuild 在 FOR UPDATE 下确定重建区间并登记 building_until。
|
||||
// 日桶已发布到今日时返回 nil。
|
||||
func beginGroupUsageRollupBuild(ctx context.Context, q sqlExecutor, todayStart time.Time) (*groupUsageRollupBuildPlan, error) {
|
||||
var closedBefore string
|
||||
var retainedFrom time.Time
|
||||
var stateTimezoneName string
|
||||
var expiredBefore time.Time
|
||||
var buildingUntil sql.NullString
|
||||
if err := scanSingleRow(ctx, q, `
|
||||
SELECT closed_before::text, retained_from, timezone_name, expired_before, building_until::text
|
||||
FROM usage_group_rollup_state
|
||||
WHERE id = 1
|
||||
FOR UPDATE
|
||||
`, nil, &closedBefore, &previousRetainedFrom, &stateTimezoneName); err != nil {
|
||||
return fmt.Errorf("读取分组用量汇总水位: %w", err)
|
||||
`, nil, &closedBefore, &retainedFrom, &stateTimezoneName, &expiredBefore, &buildingUntil); err != nil {
|
||||
return nil, fmt.Errorf("读取分组用量汇总水位: %w", err)
|
||||
}
|
||||
|
||||
todayDate := service.GroupUsageDate(todayStart)
|
||||
timezoneName := service.GroupUsageTimezoneName()
|
||||
timezoneChanged := stateTimezoneName != timezoneName
|
||||
var closedTime time.Time
|
||||
if !timezoneChanged {
|
||||
var err error
|
||||
closedTime, err = service.ParseGroupUsageDate(closedBefore)
|
||||
closedTime, err := service.ParseGroupUsageDate(closedBefore)
|
||||
if err != nil {
|
||||
return fmt.Errorf("解析分组用量汇总水位 %q: %w", closedBefore, err)
|
||||
return nil, fmt.Errorf("解析分组用量汇总水位 %q: %w", closedBefore, err)
|
||||
}
|
||||
todayDateTime, err := service.ParseGroupUsageDate(todayDate)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if closedTime.After(todayDateTime) {
|
||||
return fmt.Errorf("分组用量汇总水位位于未来: %s", closedBefore)
|
||||
return nil, fmt.Errorf("分组用量汇总水位位于未来: %s", closedBefore)
|
||||
}
|
||||
if closedBefore == todayDate {
|
||||
return nil
|
||||
if buildingUntil.Valid {
|
||||
if _, err := q.ExecContext(ctx, `
|
||||
UPDATE usage_group_rollup_state
|
||||
SET building_until = NULL,
|
||||
build_dirty_from = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = 1
|
||||
`); err != nil {
|
||||
return nil, fmt.Errorf("清除分组用量汇总重建登记: %w", err)
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
var earliest sql.NullTime
|
||||
if err := scanSingleRow(ctx, r.sql, "SELECT MIN(created_at) FROM usage_logs", nil, &earliest); err != nil {
|
||||
return fmt.Errorf("读取最早用量记录: %w", err)
|
||||
}
|
||||
retainedFrom := todayStart
|
||||
if earliest.Valid {
|
||||
retainedFrom = earliest.Time.UTC()
|
||||
// 可读日桶从 retained_from 所在日开始,且不早于保留下界。
|
||||
if retainedFrom.Before(expiredBefore) {
|
||||
retainedFrom = expiredBefore
|
||||
}
|
||||
// closed_before 不晚于保留起点时,可读日桶为空,按保留起点全量重建;否则从水位续建。
|
||||
retainedDate := service.GroupUsageDate(retainedFrom)
|
||||
retainedDateTime, err := service.ParseGroupUsageDate(retainedDate)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rebuildStartDate := retainedDate
|
||||
if !timezoneChanged && closedTime.After(retainedDateTime) {
|
||||
rebuildStartDate = closedBefore
|
||||
}
|
||||
rebuildStart, err := service.ParseGroupUsageDate(rebuildStartDate)
|
||||
if err != nil {
|
||||
return err
|
||||
startDate := closedBefore
|
||||
if timezoneChanged || closedBefore <= retainedDate {
|
||||
var earliest sql.NullTime
|
||||
if err := scanSingleRow(ctx, q, `
|
||||
SELECT MIN(created_at)
|
||||
FROM usage_logs
|
||||
WHERE created_at >= $1
|
||||
`, []any{expiredBefore.UTC()}, &earliest); err != nil {
|
||||
return nil, fmt.Errorf("读取最早用量记录: %w", err)
|
||||
}
|
||||
retainedFrom = todayStart
|
||||
if earliest.Valid {
|
||||
retainedFrom = earliest.Time.UTC()
|
||||
}
|
||||
retainedDate = service.GroupUsageDate(retainedFrom)
|
||||
startDate = retainedDate
|
||||
}
|
||||
|
||||
if _, err := r.sql.ExecContext(ctx, `
|
||||
if _, err := q.ExecContext(ctx, `
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = $1::date,
|
||||
retained_from = $2,
|
||||
timezone_name = $3,
|
||||
building_until = $4::date,
|
||||
build_dirty_from = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = 1
|
||||
`, startDate, retainedFrom.UTC(), timezoneName, todayDate); err != nil {
|
||||
return nil, fmt.Errorf("登记分组用量汇总重建: %w", err)
|
||||
}
|
||||
|
||||
startTime, err := service.ParseGroupUsageDate(startDate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rowsFrom := startTime.UTC()
|
||||
if expiredBefore.After(rowsFrom) {
|
||||
rowsFrom = expiredBefore.UTC()
|
||||
}
|
||||
return &groupUsageRollupBuildPlan{
|
||||
startDate: startDate,
|
||||
targetDate: todayDate,
|
||||
retainedDate: retainedDate,
|
||||
rowsFrom: rowsFrom,
|
||||
rowsBefore: todayStart.UTC(),
|
||||
timezoneName: timezoneName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// buildGroupUsageRollups 重算 [startDate, targetDate) 的日桶,只写入本地日期不早于 startDate 的桶。
|
||||
// 状态行只持 FOR KEY SHARE,与 usage_logs 写入和失效触发器兼容;登记与发布的 FOR UPDATE 须等待本事务结束。
|
||||
func buildGroupUsageRollups(ctx context.Context, q sqlExecutor, plan *groupUsageRollupBuildPlan) error {
|
||||
var buildingUntil sql.NullString
|
||||
var stateTimezoneName string
|
||||
if err := scanSingleRow(ctx, q, `
|
||||
SELECT building_until::text, timezone_name
|
||||
FROM usage_group_rollup_state
|
||||
WHERE id = 1
|
||||
FOR KEY SHARE
|
||||
`, nil, &buildingUntil, &stateTimezoneName); err != nil {
|
||||
return fmt.Errorf("读取分组用量汇总重建登记: %w", err)
|
||||
}
|
||||
if !buildingUntil.Valid || buildingUntil.String != plan.targetDate || stateTimezoneName != plan.timezoneName {
|
||||
return errGroupUsageRollupBuildPreempted
|
||||
}
|
||||
|
||||
if _, err := q.ExecContext(ctx, `
|
||||
DELETE FROM usage_group_daily_rollups
|
||||
WHERE bucket_date < $1::date
|
||||
OR (bucket_date >= $2::date AND bucket_date < $3::date)
|
||||
OR bucket_date >= $3::date
|
||||
`, retainedDate, rebuildStartDate, todayDate); err != nil {
|
||||
OR bucket_date >= $2::date
|
||||
`, plan.retainedDate, plan.startDate); err != nil {
|
||||
return fmt.Errorf("清理分组用量日桶: %w", err)
|
||||
}
|
||||
|
||||
if _, err := r.sql.ExecContext(ctx, `
|
||||
if _, err := q.ExecContext(ctx, `
|
||||
INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost, computed_at)
|
||||
SELECT
|
||||
(created_at AT TIME ZONE $3::text)::date AS bucket_date,
|
||||
@@ -260,51 +470,82 @@ func (r *dashboardAggregationRepository) syncGroupUsageRollupsInTx(ctx context.C
|
||||
WHERE group_id IS NOT NULL
|
||||
AND created_at >= $1
|
||||
AND created_at < $2
|
||||
AND (created_at AT TIME ZONE $3::text)::date >= $4::date
|
||||
GROUP BY 1, 2
|
||||
ON CONFLICT (bucket_date, group_id)
|
||||
DO UPDATE SET
|
||||
actual_cost = EXCLUDED.actual_cost,
|
||||
computed_at = EXCLUDED.computed_at
|
||||
`, rebuildStart.UTC(), todayStart.UTC(), timezoneName); err != nil {
|
||||
`, plan.rowsFrom, plan.rowsBefore, plan.timezoneName, plan.startDate); err != nil {
|
||||
return fmt.Errorf("重建分组用量日桶: %w", err)
|
||||
}
|
||||
|
||||
if _, err := r.sql.ExecContext(ctx, `
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = $1::date,
|
||||
retained_from = $2,
|
||||
timezone_name = $3,
|
||||
updated_at = NOW()
|
||||
WHERE id = 1
|
||||
`, todayDate, retainedFrom, timezoneName); err != nil {
|
||||
return fmt.Errorf("更新分组用量汇总水位: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func lockGroupUsageRollupState(ctx context.Context, tx *sql.Tx) error {
|
||||
var id int16
|
||||
if err := tx.QueryRowContext(ctx, `
|
||||
SELECT id
|
||||
// publishGroupUsageRollups 在 FOR UPDATE 下发布本轮结果并清除登记,返回是否存在需要重算的脏区间。
|
||||
//
|
||||
// 登记之后 [startDate, targetDate) 内的源记录变更都记入了 build_dirty_from,[startDate, build_dirty_from)
|
||||
// 的日桶与计算快照一致;水位低于 startDate 说明有未记脏的失效,此时发布不越过当前水位。
|
||||
func publishGroupUsageRollups(ctx context.Context, q sqlExecutor, plan *groupUsageRollupBuildPlan) (bool, error) {
|
||||
var closedBefore string
|
||||
var buildingUntil sql.NullString
|
||||
var dirtyFrom sql.NullString
|
||||
if err := scanSingleRow(ctx, q, `
|
||||
SELECT closed_before::text, building_until::text, build_dirty_from::text
|
||||
FROM usage_group_rollup_state
|
||||
WHERE id = 1
|
||||
FOR UPDATE
|
||||
`).Scan(&id); err != nil {
|
||||
return fmt.Errorf("锁定分组用量汇总水位: %w", err)
|
||||
`, nil, &closedBefore, &buildingUntil, &dirtyFrom); err != nil {
|
||||
return false, fmt.Errorf("读取分组用量汇总重建登记: %w", err)
|
||||
}
|
||||
if !buildingUntil.Valid || buildingUntil.String != plan.targetDate {
|
||||
return false, errGroupUsageRollupBuildPreempted
|
||||
}
|
||||
|
||||
publishBefore := plan.targetDate
|
||||
dirty := false
|
||||
if dirtyFrom.Valid && dirtyFrom.String < publishBefore {
|
||||
publishBefore = dirtyFrom.String
|
||||
dirty = true
|
||||
}
|
||||
if closedBefore < plan.startDate && closedBefore < publishBefore {
|
||||
publishBefore = closedBefore
|
||||
dirty = true
|
||||
}
|
||||
|
||||
if _, err := q.ExecContext(ctx, `
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = $1::date,
|
||||
building_until = NULL,
|
||||
build_dirty_from = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = 1
|
||||
`, publishBefore); err != nil {
|
||||
return false, fmt.Errorf("发布分组用量汇总水位: %w", err)
|
||||
}
|
||||
return dirty, nil
|
||||
}
|
||||
|
||||
// expireGroupUsageRollupsBefore 把保留下界推进到 cutoff:早于 cutoff 的 usage_logs 不属于任何可读日桶,
|
||||
// 删除它们不触发失效。cutoff 须为服务端配置时区的自然日零点,使边界日桶不包含被删除的记录。
|
||||
func expireGroupUsageRollupsBefore(ctx context.Context, q sqlExecutor, cutoff time.Time) error {
|
||||
if _, err := q.ExecContext(ctx, `
|
||||
UPDATE usage_group_rollup_state
|
||||
SET expired_before = GREATEST(expired_before, $1),
|
||||
retained_from = GREATEST(retained_from, $1),
|
||||
updated_at = NOW()
|
||||
WHERE id = 1
|
||||
`, cutoff.UTC()); err != nil {
|
||||
return fmt.Errorf("推进分组用量汇总保留下界: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func invalidateGroupUsageRollupsAt(ctx context.Context, tx *sql.Tx, affectedAt time.Time) error {
|
||||
timezoneName := service.GroupUsageTimezoneName()
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = LEAST(
|
||||
closed_before,
|
||||
($1::timestamptz AT TIME ZONE $2::text)::date
|
||||
),
|
||||
updated_at = NOW()
|
||||
WHERE id = 1
|
||||
`, affectedAt.UTC(), timezoneName)
|
||||
// invalidateGroupUsageRollupsAt 使 affectedAt 所在自然日及之后的日桶失效;早于保留下界的时刻不生效。
|
||||
func invalidateGroupUsageRollupsAt(ctx context.Context, q sqlExecutor, affectedAt time.Time) error {
|
||||
_, err := q.ExecContext(ctx,
|
||||
"SELECT invalidate_group_usage_rollups_at($1, $2)",
|
||||
affectedAt.UTC(), service.GroupUsageTimezoneName(),
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -5,61 +5,146 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/lib/pq"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsNoopsAtCurrentDate(t *testing.T) {
|
||||
const (
|
||||
groupRollupPrecheckQuery = `SELECT closed_before::text, timezone_name, building_until IS NULL`
|
||||
groupRollupLockQuery = `SELECT pg_try_advisory_lock\(hashtext\('usage_group_daily_rollups:build'\)\)`
|
||||
groupRollupUnlockQuery = `SELECT pg_advisory_unlock\(hashtext\('usage_group_daily_rollups:build'\)\)`
|
||||
groupRollupBeginQuery = `(?s)SELECT closed_before::text, retained_from, timezone_name, expired_before, building_until::text.*FOR UPDATE`
|
||||
groupRollupBuildQuery = `(?s)SELECT building_until::text, timezone_name.*FOR KEY SHARE`
|
||||
groupRollupPublishQuery = `(?s)SELECT closed_before::text, building_until::text, build_dirty_from::text.*FOR UPDATE`
|
||||
groupRollupRegisterExec = `(?s)UPDATE usage_group_rollup_state.*building_until = \$4::date`
|
||||
groupRollupPublishExec = `(?s)UPDATE usage_group_rollup_state.*SET closed_before = \$1::date,\s+building_until = NULL`
|
||||
groupRollupExpireExec = `(?s)UPDATE usage_group_rollup_state.*expired_before = GREATEST\(expired_before, \$1\)`
|
||||
groupRollupInvalidateSQL = `SELECT invalidate_group_usage_rollups_at\(\$1, \$2\)`
|
||||
)
|
||||
|
||||
var groupRollupEpoch = time.Unix(0, 0).UTC()
|
||||
|
||||
func expectGroupRollupPrecheck(mock sqlmock.Sqlmock, closedBefore, timezoneName string, idle bool) {
|
||||
mock.ExpectQuery(groupRollupPrecheckQuery).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "timezone_name", "idle"}).
|
||||
AddRow(closedBefore, timezoneName, idle))
|
||||
}
|
||||
|
||||
func expectGroupRollupLock(mock sqlmock.Sqlmock, locked bool) {
|
||||
mock.ExpectQuery(groupRollupLockQuery).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"locked"}).AddRow(locked))
|
||||
}
|
||||
|
||||
func expectGroupRollupUnlock(mock sqlmock.Sqlmock) {
|
||||
mock.ExpectQuery(groupRollupUnlockQuery).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"unlocked"}).AddRow(true))
|
||||
}
|
||||
|
||||
func groupRollupBeginRows(closedBefore string, retainedFrom time.Time, timezoneName string, expiredBefore time.Time, buildingUntil any) *sqlmock.Rows {
|
||||
return sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name", "expired_before", "building_until"}).
|
||||
AddRow(closedBefore, retainedFrom, timezoneName, expiredBefore, buildingUntil)
|
||||
}
|
||||
|
||||
// expectGroupRollupRound 期望一轮完整的登记、计算、发布。
|
||||
func expectGroupRollupRound(
|
||||
mock sqlmock.Sqlmock,
|
||||
begin *sqlmock.Rows,
|
||||
minCreatedAt *sqlmock.Rows,
|
||||
minCreatedAfter time.Time,
|
||||
register []any,
|
||||
deleteArgs []any,
|
||||
insertArgs []any,
|
||||
publishRows *sqlmock.Rows,
|
||||
publishBefore string,
|
||||
) {
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(groupRollupBeginQuery).WillReturnRows(begin)
|
||||
if minCreatedAt != nil {
|
||||
mock.ExpectQuery(`(?s)SELECT MIN\(created_at\)\s+FROM usage_logs\s+WHERE created_at >= \$1`).
|
||||
WithArgs(minCreatedAfter).
|
||||
WillReturnRows(minCreatedAt)
|
||||
}
|
||||
mock.ExpectExec(groupRollupRegisterExec).
|
||||
WithArgs(toDriverValues(register)...).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(groupRollupBuildQuery).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"building_until", "timezone_name"}).AddRow(register[3], register[2]))
|
||||
mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`).
|
||||
WithArgs(toDriverValues(deleteArgs)...).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`).
|
||||
WithArgs(toDriverValues(append(append([]any{}, insertArgs...), register[0]))...).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(groupRollupPublishQuery).WillReturnRows(publishRows)
|
||||
mock.ExpectExec(groupRollupPublishExec).
|
||||
WithArgs(publishBefore).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
}
|
||||
|
||||
func toDriverValues(values []any) []driver.Value {
|
||||
args := make([]driver.Value, 0, len(values))
|
||||
for _, value := range values {
|
||||
args = append(args, sqlmockValue{value: value})
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
// sqlmockValue 按时刻比较 time.Time(忽略 Location),其余值按相等比较。
|
||||
type sqlmockValue struct{ value any }
|
||||
|
||||
func (v sqlmockValue) Match(actual driver.Value) bool {
|
||||
if expectedTime, ok := v.value.(time.Time); ok {
|
||||
actualTime, ok := actual.(time.Time)
|
||||
return ok && actualTime.Equal(expectedTime)
|
||||
}
|
||||
return actual == v.value
|
||||
}
|
||||
|
||||
func publishRows(closedBefore, buildingUntil string, dirtyFrom any) *sqlmock.Rows {
|
||||
return sqlmock.NewRows([]string{"closed_before", "building_until", "build_dirty_from"}).
|
||||
AddRow(closedBefore, buildingUntil, dirtyFrom)
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsNoopsWithoutLockingAtCurrentDate(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow("2026-08-14", time.Unix(0, 0).UTC(), "Asia/Shanghai"))
|
||||
mock.ExpectCommit()
|
||||
expectGroupRollupPrecheck(mock, "2026-08-14", "Asia/Shanghai", true)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsRebuildsWhenTimezoneChanges(t *testing.T) {
|
||||
useGroupUsageRepositoryTestTimezone(t, "America/New_York")
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsSkipsWhenAnotherBuildHoldsLock(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 3, 9, 4, 0, 0, 0, time.UTC)
|
||||
retainedFrom := time.Date(2026, 3, 1, 5, 0, 0, 0, time.UTC)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow("2026-03-09", time.Unix(0, 0).UTC(), "Asia/Shanghai"))
|
||||
mock.ExpectQuery(`SELECT MIN\(created_at\) FROM usage_logs`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(retainedFrom))
|
||||
mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`).
|
||||
WithArgs("2026-03-01", "2026-03-01", "2026-03-09").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`).
|
||||
WithArgs(retainedFrom, todayStart, "America/New_York").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs("2026-03-09", retainedFrom, "America/New_York").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, false)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsPublishesWatermarkLast(t *testing.T) {
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsBuildsAndPublishesInSeparateTransactions(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
@@ -67,22 +152,209 @@ func TestDashboardAggregationRepositorySyncGroupUsageRollupsPublishesWatermarkLa
|
||||
retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC)
|
||||
rebuildStart := time.Date(2026, 8, 12, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-08-13", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil),
|
||||
nil, time.Time{},
|
||||
[]any{"2026-08-13", retainedFrom, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-01", "2026-08-13"},
|
||||
[]any{rebuildStart, todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-08-13", "2026-08-14", nil),
|
||||
"2026-08-14",
|
||||
)
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsRebuildsDirtyRangeBeforeFullPublish(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-11", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
// 第一轮计算期间有 08-12 的迟到写入:只发布到 08-12。
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-08-11", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil),
|
||||
nil, time.Time{},
|
||||
[]any{"2026-08-11", retainedFrom, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-01", "2026-08-11"},
|
||||
[]any{time.Date(2026, 8, 10, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-08-11", "2026-08-14", "2026-08-12"),
|
||||
"2026-08-12",
|
||||
)
|
||||
// 第二轮只重算脏日期之后的区间。
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-08-12", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil),
|
||||
nil, time.Time{},
|
||||
[]any{"2026-08-12", retainedFrom, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-01", "2026-08-12"},
|
||||
[]any{time.Date(2026, 8, 11, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-08-12", "2026-08-14", nil),
|
||||
"2026-08-14",
|
||||
)
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsStopsAfterMaxRoundsWithoutOverPublishing(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-12", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
for range groupUsageRollupBuildMaxRounds {
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-08-12", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil),
|
||||
nil, time.Time{},
|
||||
[]any{"2026-08-12", retainedFrom, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-01", "2026-08-12"},
|
||||
[]any{time.Date(2026, 8, 11, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-08-12", "2026-08-14", "2026-08-12"),
|
||||
"2026-08-12",
|
||||
)
|
||||
}
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsPublishKeepsUnmarkedInvalidation(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
// 计算期间水位被后退到 08-10 而没有记脏:发布不越过 08-10。
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-08-13", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil),
|
||||
nil, time.Time{},
|
||||
[]any{"2026-08-13", retainedFrom, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-01", "2026-08-13"},
|
||||
[]any{time.Date(2026, 8, 12, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-08-10", "2026-08-14", nil),
|
||||
"2026-08-10",
|
||||
)
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-08-10", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil),
|
||||
nil, time.Time{},
|
||||
[]any{"2026-08-10", retainedFrom, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-01", "2026-08-10"},
|
||||
[]any{time.Date(2026, 8, 9, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-08-10", "2026-08-14", nil),
|
||||
"2026-08-14",
|
||||
)
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsRebuildsWhenTimezoneChanges(t *testing.T) {
|
||||
useGroupUsageRepositoryTestTimezone(t, "America/New_York")
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 3, 9, 4, 0, 0, 0, time.UTC)
|
||||
retainedFrom := time.Date(2026, 3, 1, 5, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-03-09", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-03-09", groupRollupEpoch, "Asia/Shanghai", groupRollupEpoch, nil),
|
||||
sqlmock.NewRows([]string{"min"}).AddRow(retainedFrom), groupRollupEpoch,
|
||||
[]any{"2026-03-01", retainedFrom, "America/New_York", "2026-03-09"},
|
||||
[]any{"2026-03-01", "2026-03-01"},
|
||||
[]any{retainedFrom, todayStart, "America/New_York"},
|
||||
publishRows("2026-03-01", "2026-03-09", nil),
|
||||
"2026-03-09",
|
||||
)
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsFullRebuildExcludesExpiredRows(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
// 保留下界不在 Asia/Shanghai 的日界上(例如在其他时区下推进):重建只计入下界之后的记录。
|
||||
expiredBefore := time.Date(2026, 5, 1, 18, 0, 0, 0, time.UTC)
|
||||
earliestRetained := time.Date(2026, 5, 1, 19, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "1970-01-01", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("1970-01-01", groupRollupEpoch, "Asia/Shanghai", expiredBefore, nil),
|
||||
sqlmock.NewRows([]string{"min"}).AddRow(earliestRetained), expiredBefore,
|
||||
[]any{"2026-05-02", earliestRetained, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-02", "2026-05-02"},
|
||||
[]any{expiredBefore, todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-05-02", "2026-08-14", nil),
|
||||
"2026-08-14",
|
||||
)
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsKeepsRetainedFromAtExpiredFloor(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
staleRetainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC)
|
||||
expiredBefore := time.Date(2026, 5, 14, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
// retained_from 早于保留下界(例如被其他版本的同步改写):登记与清理都以保留下界为起点。
|
||||
expectGroupRollupRound(mock,
|
||||
groupRollupBeginRows("2026-08-13", staleRetainedFrom, "Asia/Shanghai", expiredBefore, nil),
|
||||
nil, time.Time{},
|
||||
[]any{"2026-08-13", expiredBefore, "Asia/Shanghai", "2026-08-14"},
|
||||
[]any{"2026-05-15", "2026-08-13"},
|
||||
[]any{time.Date(2026, 8, 12, 16, 0, 0, 0, time.UTC), todayStart, "Asia/Shanghai"},
|
||||
publishRows("2026-08-13", "2026-08-14", nil),
|
||||
"2026-08-14",
|
||||
)
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsClearsStaleBuildMarkWhenPublished(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-14", "Asia/Shanghai", false)
|
||||
expectGroupRollupLock(mock, true)
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow("2026-08-13", time.Unix(0, 0).UTC(), "Asia/Shanghai"))
|
||||
mock.ExpectQuery(`SELECT MIN\(created_at\) FROM usage_logs`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(retainedFrom))
|
||||
mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`).
|
||||
WithArgs("2026-05-01", "2026-08-13", "2026-08-14").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`).
|
||||
WithArgs(rebuildStart, todayStart, "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 2))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs("2026-08-14", retainedFrom, "Asia/Shanghai").
|
||||
mock.ExpectQuery(groupRollupBeginQuery).
|
||||
WillReturnRows(groupRollupBeginRows("2026-08-14", groupRollupEpoch, "Asia/Shanghai", groupRollupEpoch, "2026-08-14"))
|
||||
mock.ExpectExec(`(?s)UPDATE usage_group_rollup_state\s+SET building_until = NULL`).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(context.Background(), todayStart))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
@@ -94,17 +366,44 @@ func TestDashboardAggregationRepositorySyncGroupUsageRollupsRejectsFutureWaterma
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-15", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow("2026-08-15", time.Unix(0, 0).UTC(), "Asia/Shanghai"))
|
||||
mock.ExpectQuery(groupRollupBeginQuery).
|
||||
WillReturnRows(groupRollupBeginRows("2026-08-15", groupRollupEpoch, "Asia/Shanghai", groupRollupEpoch, nil))
|
||||
mock.ExpectRollback()
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
err := repo.SyncGroupUsageRollups(context.Background(), todayStart)
|
||||
require.ErrorContains(t, err, "未来")
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositorySyncGroupUsageRollupsAbortsWhenBuildMarkReplaced(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
retainedFrom := time.Date(2026, 5, 1, 3, 0, 0, 0, time.UTC)
|
||||
|
||||
expectGroupRollupPrecheck(mock, "2026-08-13", "Asia/Shanghai", true)
|
||||
expectGroupRollupLock(mock, true)
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(groupRollupBeginQuery).
|
||||
WillReturnRows(groupRollupBeginRows("2026-08-13", retainedFrom, "Asia/Shanghai", groupRollupEpoch, nil))
|
||||
mock.ExpectExec(groupRollupRegisterExec).WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(groupRollupBuildQuery).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"building_until", "timezone_name"}).AddRow(nil, "Asia/Shanghai"))
|
||||
mock.ExpectRollback()
|
||||
expectGroupRollupUnlock(mock)
|
||||
|
||||
err := repo.SyncGroupUsageRollups(context.Background(), todayStart)
|
||||
require.ErrorIs(t, err, errGroupUsageRollupBuildPreempted)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryRecomputeRangeInvalidatesGroupRollupsBeforeDashboardRebuild(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
@@ -112,12 +411,10 @@ func TestDashboardAggregationRepositoryRecomputeRangeInvalidatesGroupRollupsBefo
|
||||
start := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC)
|
||||
end := start.Add(time.Hour)
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
mock.ExpectExec(groupRollupInvalidateSQL).
|
||||
WithArgs(start, "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec(`DELETE FROM usage_dashboard_hourly`).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
mock.ExpectRollback()
|
||||
@@ -127,25 +424,17 @@ func TestDashboardAggregationRepositoryRecomputeRangeInvalidatesGroupRollupsBefo
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryRecomputeRangeRebuildsGroupRollupsBeforeCommit(t *testing.T) {
|
||||
func TestDashboardAggregationRepositoryRecomputeRangeLeavesGroupRollupRebuildToSync(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
start := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC)
|
||||
end := start.Add(time.Hour)
|
||||
fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC)
|
||||
repo.clock = func() time.Time { return fixedNow }
|
||||
todayStart := service.GroupUsageTodayStart(fixedNow)
|
||||
startDate := service.GroupUsageDate(start)
|
||||
rebuildStart, err := service.ParseGroupUsageDate(startDate)
|
||||
require.NoError(t, err)
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
mock.ExpectExec(groupRollupInvalidateSQL).
|
||||
WithArgs(start, "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectBegin()
|
||||
for _, query := range []string{
|
||||
`DELETE FROM usage_dashboard_hourly WHERE`,
|
||||
`DELETE FROM usage_dashboard_hourly_users WHERE`,
|
||||
@@ -158,71 +447,67 @@ func TestDashboardAggregationRepositoryRecomputeRangeRebuildsGroupRollupsBeforeC
|
||||
} {
|
||||
mock.ExpectExec(query).WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
}
|
||||
mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow(startDate, time.Unix(0, 0).UTC(), "Asia/Shanghai"))
|
||||
mock.ExpectQuery(`SELECT MIN\(created_at\) FROM usage_logs`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(start))
|
||||
mock.ExpectExec(`DELETE FROM usage_group_daily_rollups`).
|
||||
WithArgs(startDate, startDate, service.GroupUsageDate(todayStart)).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`INSERT INTO usage_group_daily_rollups`).
|
||||
WithArgs(rebuildStart.UTC(), todayStart.UTC(), "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs(service.GroupUsageDate(todayStart), start, "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
|
||||
require.NoError(t, repo.RecomputeRange(context.Background(), start, end))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsNonPartitionedInvalidatesEachBatchAndSyncs(t *testing.T) {
|
||||
func TestDashboardAggregationRepositoryRecomputeRangeStopsWhenInvalidationFails(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
cutoff := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC)
|
||||
earliestDeletedAt := time.Date(2026, 5, 3, 2, 0, 0, 0, time.UTC)
|
||||
start := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC)
|
||||
|
||||
mock.ExpectExec(groupRollupInvalidateSQL).
|
||||
WithArgs(start, "Asia/Shanghai").
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
err := repo.RecomputeRange(context.Background(), start, start.Add(time.Hour))
|
||||
require.ErrorIs(t, err, sql.ErrConnDone)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsExpiresWholeDaysBeforeDeleting(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
// 2026-07-01 13:00 +08 对齐到 2026-07-01 00:00 +08。
|
||||
cutoff := time.Date(2026, 7, 1, 5, 0, 0, 0, time.UTC)
|
||||
alignedCutoff := time.Date(2026, 6, 30, 16, 0, 0, 0, time.UTC)
|
||||
fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC)
|
||||
repo.clock = func() time.Time { return fixedNow }
|
||||
todayStart := service.GroupUsageTodayStart(fixedNow)
|
||||
|
||||
mock.ExpectExec(groupRollupExpireExec).
|
||||
WithArgs(alignedCutoff).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectQuery(`SELECT EXISTS`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false))
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectQuery(`(?s)DELETE FROM usage_logs.*RETURNING created_at`).
|
||||
WithArgs(cutoff, usageLogsCleanupBatchSize).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"created_at"}).
|
||||
AddRow(earliestDeletedAt.Add(time.Hour)).
|
||||
AddRow(earliestDeletedAt))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs(earliestDeletedAt, "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow(service.GroupUsageDate(todayStart), time.Unix(0, 0).UTC(), "Asia/Shanghai"))
|
||||
mock.ExpectCommit()
|
||||
mock.ExpectExec(`(?s)SELECT tableoid, ctid.*ORDER BY created_at ASC, id ASC.*DELETE FROM usage_logs`).
|
||||
WithArgs(alignedCutoff, usageLogsCleanupBatchSize).
|
||||
WillReturnResult(sqlmock.NewResult(0, usageLogsCleanupBatchSize))
|
||||
mock.ExpectExec(`(?s)SELECT tableoid, ctid.*DELETE FROM usage_logs`).
|
||||
WithArgs(alignedCutoff, usageLogsCleanupBatchSize).
|
||||
WillReturnResult(sqlmock.NewResult(0, 3))
|
||||
expectGroupRollupPrecheck(mock, service.GroupUsageDate(service.GroupUsageTodayStart(fixedNow)), "Asia/Shanghai", true)
|
||||
|
||||
require.NoError(t, repo.CleanupUsageLogs(context.Background(), cutoff))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionedSortsAndInvalidatesEachDropBeforeSync(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionedInvalidatesRetainedRowsAfterDrop(t *testing.T) {
|
||||
useGroupUsageRepositoryTestTimezone(t, "UTC")
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
cutoff := time.Date(2026, 7, 18, 0, 0, 0, 0, time.UTC)
|
||||
aprilStart := time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)
|
||||
juneStart := time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC)
|
||||
fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC)
|
||||
cutoff := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC)
|
||||
fixedNow := time.Date(2026, 9, 29, 8, 0, 0, 0, time.UTC)
|
||||
repo.clock = func() time.Time { return fixedNow }
|
||||
todayStart := service.GroupUsageTodayStart(fixedNow)
|
||||
// 6 月分区建于 UTC-5 会话时区,上界是 07-01 05:00 UTC,包含保留下界之后的记录。
|
||||
retainedInJunePartition := time.Date(2026, 7, 1, 3, 0, 0, 0, time.UTC)
|
||||
|
||||
mock.ExpectExec(groupRollupExpireExec).
|
||||
WithArgs(cutoff).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectQuery(`SELECT EXISTS`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
mock.ExpectQuery(`SELECT c.relname`).
|
||||
@@ -232,78 +517,120 @@ func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionedSortsAndInvali
|
||||
AddRow("usage_logs_202604").
|
||||
AddRow("usage_logs_202607"))
|
||||
|
||||
for _, partition := range []struct {
|
||||
name string
|
||||
start time.Time
|
||||
}{
|
||||
{name: "usage_logs_202604", start: aprilStart},
|
||||
{name: "usage_logs_202606", start: juneStart},
|
||||
} {
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs(partition.start, "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`DROP TABLE IF EXISTS "` + partition.name + `"`).
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectCommit()
|
||||
}
|
||||
// The boundary partition is pruned by exact timestamp. tableoid is required
|
||||
// because ctid alone can also identify a retained row in another partition.
|
||||
// 4 月分区全部早于保留下界:直接删除。
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectQuery(`(?s)SELECT tableoid, ctid.*WHERE created_at < \$1.*WHERE \(tableoid, ctid\) IN.*RETURNING created_at`).
|
||||
mock.ExpectExec(`SET LOCAL lock_timeout = '3000ms'`).WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff))
|
||||
mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202604" WHERE created_at >= \$1`).
|
||||
WithArgs(cutoff).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(nil))
|
||||
mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202604"`).
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectCommit()
|
||||
// 6 月分区含保留下界之后的记录:删除后按其中最早时刻失效。
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec(`SET LOCAL lock_timeout = '3000ms'`).WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff))
|
||||
mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202606" WHERE created_at >= \$1`).
|
||||
WithArgs(cutoff).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(retainedInJunePartition))
|
||||
mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202606"`).
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectExec(groupRollupInvalidateSQL).
|
||||
WithArgs(retainedInJunePartition, "UTC").
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectCommit()
|
||||
// 边界分区按精确时间删除;tableoid 区分不同分区里相同的 ctid。
|
||||
mock.ExpectExec(`(?s)SELECT tableoid, ctid.*WHERE created_at < \$1.*WHERE \(tableoid, ctid\) IN`).
|
||||
WithArgs(cutoff, usageLogsCleanupBatchSize).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"created_at"}).AddRow(cutoff.Add(-time.Hour)))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs(cutoff.Add(-time.Hour), "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT closed_before::text, retained_from.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow(service.GroupUsageDate(todayStart), time.Unix(0, 0).UTC(), "Asia/Shanghai"))
|
||||
mock.ExpectCommit()
|
||||
expectGroupRollupPrecheck(mock, service.GroupUsageDate(service.GroupUsageTodayStart(fixedNow)), "UTC", true)
|
||||
|
||||
require.NoError(t, repo.CleanupUsageLogs(context.Background(), cutoff))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsNonPartitionedFailureRollsBackWithoutSync(t *testing.T) {
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsStopsWhenExpireFails(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
cutoff := time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC)
|
||||
deletedAt := time.Date(2026, 5, 3, 2, 0, 0, 0, time.UTC)
|
||||
cutoff := time.Date(2026, 6, 30, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
mock.ExpectQuery(`SELECT EXISTS`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false))
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectQuery(`(?s)SELECT tableoid, ctid.*ORDER BY created_at ASC, id ASC.*DELETE FROM usage_logs.*RETURNING created_at`).
|
||||
WithArgs(cutoff, usageLogsCleanupBatchSize).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"created_at"}).AddRow(deletedAt))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs(deletedAt, "Asia/Shanghai").
|
||||
mock.ExpectExec(groupRollupExpireExec).
|
||||
WithArgs(cutoff).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
mock.ExpectRollback()
|
||||
|
||||
err := repo.CleanupUsageLogs(context.Background(), cutoff)
|
||||
require.ErrorIs(t, err, sql.ErrConnDone)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsBatchFailureStopsWithoutSync(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
cutoff := time.Date(2026, 6, 30, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
mock.ExpectExec(groupRollupExpireExec).
|
||||
WithArgs(cutoff).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectQuery(`SELECT EXISTS`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false))
|
||||
mock.ExpectExec(`(?s)SELECT tableoid, ctid.*DELETE FROM usage_logs`).
|
||||
WithArgs(cutoff, usageLogsCleanupBatchSize).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
|
||||
err := repo.CleanupUsageLogs(context.Background(), cutoff)
|
||||
require.ErrorIs(t, err, sql.ErrConnDone)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsSkipsPartitionWhenDropLockTimesOut(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
cutoff := time.Date(2026, 7, 17, 16, 0, 0, 0, time.UTC)
|
||||
fixedNow := time.Date(2026, 8, 14, 8, 0, 0, 0, time.UTC)
|
||||
repo.clock = func() time.Time { return fixedNow }
|
||||
|
||||
mock.ExpectExec(groupRollupExpireExec).
|
||||
WithArgs(cutoff).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectQuery(`SELECT EXISTS`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
mock.ExpectQuery(`SELECT c.relname`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"relname"}).AddRow("usage_logs_202604"))
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec(`SET LOCAL lock_timeout`).WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff))
|
||||
mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202604"`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(nil))
|
||||
mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202604"`).
|
||||
WillReturnError(&pq.Error{Code: "55P03", Message: "canceling statement due to lock timeout"})
|
||||
mock.ExpectRollback()
|
||||
// 分区保留,其中的过期记录由按行删除清理。
|
||||
mock.ExpectExec(`(?s)SELECT tableoid, ctid.*DELETE FROM usage_logs`).
|
||||
WithArgs(cutoff, usageLogsCleanupBatchSize).
|
||||
WillReturnResult(sqlmock.NewResult(0, 5))
|
||||
expectGroupRollupPrecheck(mock, service.GroupUsageDate(service.GroupUsageTodayStart(fixedNow)), "Asia/Shanghai", true)
|
||||
|
||||
require.NoError(t, repo.CleanupUsageLogs(context.Background(), cutoff))
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionFailureRollsBackAndStops(t *testing.T) {
|
||||
setGroupUsageRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
cutoff := time.Date(2026, 7, 18, 0, 0, 0, 0, time.UTC)
|
||||
aprilStart := time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)
|
||||
cutoff := time.Date(2026, 7, 17, 16, 0, 0, 0, time.UTC)
|
||||
dropErr := errors.New("drop partition failed")
|
||||
|
||||
mock.ExpectExec(groupRollupExpireExec).
|
||||
WithArgs(cutoff).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectQuery(`SELECT EXISTS`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true))
|
||||
mock.ExpectQuery(`SELECT c.relname`).
|
||||
@@ -311,11 +638,11 @@ func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionFailureRollsBack
|
||||
AddRow("usage_logs_202606").
|
||||
AddRow("usage_logs_202604"))
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs(aprilStart, "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(`SET LOCAL lock_timeout`).WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectQuery(`(?s)SELECT expired_before\s+FROM usage_group_rollup_state.*FOR KEY SHARE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"expired_before"}).AddRow(cutoff))
|
||||
mock.ExpectQuery(`SELECT MIN\(created_at\) FROM "usage_logs_202604"`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(nil))
|
||||
mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202604"`).
|
||||
WillReturnError(dropErr)
|
||||
mock.ExpectRollback()
|
||||
|
||||
@@ -3,6 +3,7 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"sort"
|
||||
@@ -20,6 +21,9 @@ type dashboardAggregationRepository struct {
|
||||
}
|
||||
|
||||
const usageLogsCleanupBatchSize = 10000
|
||||
|
||||
// usageLogsPartitionDropLockTimeout 限定删除分区时等待父表锁的时长。
|
||||
const usageLogsPartitionDropLockTimeout = 3 * time.Second
|
||||
const usageBillingDedupCleanupBatchSize = 10000
|
||||
|
||||
// NewDashboardAggregationRepository 创建仪表盘预聚合仓储。
|
||||
@@ -131,29 +135,22 @@ func (r *dashboardAggregationRepository) RecomputeRange(ctx context.Context, sta
|
||||
dayEnd = dayEnd.Add(24 * time.Hour)
|
||||
}
|
||||
|
||||
// 分组日桶从 start 所在自然日起失效,由后台同步重建;失效语句独立提交,不与看板重算共享事务。
|
||||
if err := invalidateGroupUsageRollupsAt(ctx, r.sql, start); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 尽量使用事务保证范围内的一致性(允许在非 *sql.DB 的情况下退化为非事务执行)。
|
||||
if db, ok := r.sql.(*sql.DB); ok {
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := lockGroupUsageRollupState(ctx, tx); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
if err := invalidateGroupUsageRollupsAt(ctx, tx, start); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
txRepo := newDashboardAggregationRepositoryWithSQL(tx)
|
||||
if err := txRepo.recomputeRangeInTx(ctx, hourStart, hourEnd, dayStart, dayEnd); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
if err := txRepo.syncGroupUsageRollupsInTx(ctx, service.GroupUsageTodayStart(r.now())); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
return r.recomputeRangeInTx(ctx, hourStart, hourEnd, dayStart, dayEnd)
|
||||
@@ -230,7 +227,13 @@ func (r *dashboardAggregationRepository) CleanupAggregates(ctx context.Context,
|
||||
return nil
|
||||
}
|
||||
|
||||
// CleanupUsageLogs 删除服务端配置时区内 cutoff 所在自然日零点之前的 usage_logs。
|
||||
// 删除前先把分组日汇总的保留下界推进到该零点,被删除的记录不触发日桶失效。
|
||||
func (r *dashboardAggregationRepository) CleanupUsageLogs(ctx context.Context, cutoff time.Time) error {
|
||||
cutoff = service.GroupUsageTodayStart(cutoff)
|
||||
if err := expireGroupUsageRollupsBefore(ctx, r.sql, cutoff); err != nil {
|
||||
return err
|
||||
}
|
||||
isPartitioned, err := r.isUsageLogsPartitioned(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -249,19 +252,7 @@ func (r *dashboardAggregationRepository) CleanupUsageLogs(ctx context.Context, c
|
||||
}
|
||||
|
||||
func (r *dashboardAggregationRepository) cleanupUsageLogsBatches(ctx context.Context, cutoff time.Time) error {
|
||||
db, transactional := r.sql.(*sql.DB)
|
||||
for {
|
||||
if transactional {
|
||||
affected, err := cleanupUsageLogsBatchWithRollupInvalidation(ctx, db, cutoff)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected < usageLogsCleanupBatchSize {
|
||||
return nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
res, err := r.sql.ExecContext(ctx, `
|
||||
WITH victims AS (
|
||||
SELECT tableoid, ctid
|
||||
@@ -286,66 +277,6 @@ func (r *dashboardAggregationRepository) cleanupUsageLogsBatches(ctx context.Con
|
||||
}
|
||||
}
|
||||
|
||||
func cleanupUsageLogsBatchWithRollupInvalidation(ctx context.Context, db *sql.DB, cutoff time.Time) (int64, error) {
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
rollback := func(err error) (int64, error) {
|
||||
_ = tx.Rollback()
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if err := lockGroupUsageRollupState(ctx, tx); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
rows, err := tx.QueryContext(ctx, `
|
||||
WITH victims AS (
|
||||
SELECT tableoid, ctid
|
||||
FROM usage_logs
|
||||
WHERE created_at < $1
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT $2
|
||||
)
|
||||
DELETE FROM usage_logs
|
||||
WHERE (tableoid, ctid) IN (SELECT tableoid, ctid FROM victims)
|
||||
RETURNING created_at
|
||||
`, cutoff.UTC(), usageLogsCleanupBatchSize)
|
||||
if err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
|
||||
var affected int64
|
||||
var earliestDeletedAt time.Time
|
||||
for rows.Next() {
|
||||
var deletedAt time.Time
|
||||
if err := rows.Scan(&deletedAt); err != nil {
|
||||
_ = rows.Close()
|
||||
return rollback(err)
|
||||
}
|
||||
affected++
|
||||
if earliestDeletedAt.IsZero() || deletedAt.Before(earliestDeletedAt) {
|
||||
earliestDeletedAt = deletedAt
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
return rollback(err)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
if affected > 0 {
|
||||
if err := invalidateGroupUsageRollupsAt(ctx, tx, earliestDeletedAt); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return affected, nil
|
||||
}
|
||||
|
||||
func (r *dashboardAggregationRepository) CleanupUsageBillingDedup(ctx context.Context, cutoff time.Time) error {
|
||||
for {
|
||||
res, err := r.sql.ExecContext(ctx, `
|
||||
@@ -630,40 +561,69 @@ func (r *dashboardAggregationRepository) dropUsageLogsPartitions(ctx context.Con
|
||||
sort.Slice(partitions, func(i, j int) bool {
|
||||
return partitions[i].month.Before(partitions[j].month)
|
||||
})
|
||||
if db, ok := r.sql.(*sql.DB); ok {
|
||||
for _, partition := range partitions {
|
||||
if err := dropUsageLogsPartitionWithRollupInvalidation(ctx, db, partition.name, partition.month); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, partition := range partitions {
|
||||
if _, err := r.sql.ExecContext(ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", pq.QuoteIdentifier(partition.name))); err != nil {
|
||||
if err := r.dropUsageLogsPartition(ctx, partition.name); err != nil {
|
||||
// 父表锁等待超时:保留该分区,其中的过期记录由随后的按行删除清理,空分区在下次清理时删除。
|
||||
if isPostgresLockNotAvailable(err) {
|
||||
log.Printf("[DashboardAggregation] 删除分区 %s 等待锁超时,本次改为按行删除", partition.name)
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func dropUsageLogsPartitionWithRollupInvalidation(ctx context.Context, db *sql.DB, name string, monthStart time.Time) error {
|
||||
func isPostgresLockNotAvailable(err error) bool {
|
||||
var pqErr *pq.Error
|
||||
return errors.As(err, &pqErr) && pqErr.Code == "55P03"
|
||||
}
|
||||
|
||||
// dropUsageLogsPartition 删除一个 usage_logs 月分区。分区内不早于保留下界的记录参与分组日汇总,
|
||||
// 删除后按其中最早的时刻使日桶失效;状态行的 FOR KEY SHARE 使失效与重建的登记、发布串行。
|
||||
// DROP 需要父表 ACCESS EXCLUSIVE 锁,排队期间会挡住 usage_logs 写入,因此限定锁等待时长。
|
||||
func (r *dashboardAggregationRepository) dropUsageLogsPartition(ctx context.Context, name string) error {
|
||||
drop := func(q sqlExecutor) error {
|
||||
var expiredBefore time.Time
|
||||
if err := scanSingleRow(ctx, q, `
|
||||
SELECT expired_before
|
||||
FROM usage_group_rollup_state
|
||||
WHERE id = 1
|
||||
FOR KEY SHARE
|
||||
`, nil, &expiredBefore); err != nil {
|
||||
return fmt.Errorf("读取分组用量汇总保留下界: %w", err)
|
||||
}
|
||||
var earliestRetained sql.NullTime
|
||||
if err := scanSingleRow(ctx, q,
|
||||
fmt.Sprintf("SELECT MIN(created_at) FROM %s WHERE created_at >= $1", pq.QuoteIdentifier(name)),
|
||||
[]any{expiredBefore.UTC()}, &earliestRetained,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := q.ExecContext(ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", pq.QuoteIdentifier(name))); err != nil {
|
||||
return err
|
||||
}
|
||||
if earliestRetained.Valid {
|
||||
return invalidateGroupUsageRollupsAt(ctx, q, earliestRetained.Time)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
db, ok := r.sql.(*sql.DB)
|
||||
if !ok {
|
||||
return drop(r.sql)
|
||||
}
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rollback := func(err error) error {
|
||||
if _, err := tx.ExecContext(ctx, fmt.Sprintf("SET LOCAL lock_timeout = '%dms'", usageLogsPartitionDropLockTimeout.Milliseconds())); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
|
||||
if err := lockGroupUsageRollupState(ctx, tx); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
if err := invalidateGroupUsageRollupsAt(ctx, tx, monthStart); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", pq.QuoteIdentifier(name))); err != nil {
|
||||
return rollback(err)
|
||||
if err := drop(tx); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,652 @@
|
||||
//go:build integration
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lib/pq"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// 计算阶段持有状态行 FOR KEY SHARE 期间,usage_logs 的当天写入、迟到写入与窗口内删除都不等待;
|
||||
// 迟到写入与删除记入 build_dirty_from,同步重算脏区间后发布到今日,日桶与明细逐日一致。
|
||||
func TestGroupUsageRollupSyncDoesNotBlockUsageWritesDuringBuild(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai")
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai")
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
execGroupUsageRollupSQL(t, ctx, db, `
|
||||
INSERT INTO groups (id) VALUES (10), (20);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES
|
||||
(1, 1, 10, 1, TIMESTAMPTZ '2026-08-10 09:00:00+08'),
|
||||
(2, 1, 10, 2, TIMESTAMPTZ '2026-08-11 09:00:00+08'),
|
||||
(3, 1, 20, 4, TIMESTAMPTZ '2026-08-12 09:00:00+08'),
|
||||
(4, 1, 10, 8, TIMESTAMPTZ '2026-08-13 09:00:00+08');
|
||||
INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost)
|
||||
VALUES (DATE '2026-08-10', 10, 1);
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2026-08-11',
|
||||
retained_from = TIMESTAMPTZ '2026-08-10 09:00:00+08',
|
||||
timezone_name = 'Asia/Shanghai'
|
||||
WHERE id = 1;
|
||||
`)
|
||||
|
||||
// 让计算阶段停在清理日桶这一步:此时它已持有状态行的 FOR KEY SHARE。
|
||||
blocker, err := db.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = blocker.Rollback() }()
|
||||
_, err = blocker.ExecContext(ctx, "LOCK TABLE usage_group_daily_rollups IN SHARE MODE")
|
||||
require.NoError(t, err)
|
||||
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
syncDone := make(chan error, 1)
|
||||
go func() { syncDone <- repo.SyncGroupUsageRollups(ctx, todayStart) }()
|
||||
waitForBlockedGroupUsageRollupStatement(t, ctx, "DELETE FROM usage_group_daily_rollups")
|
||||
|
||||
writeCtx, writeCancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer writeCancel()
|
||||
execGroupUsageRollupSQL(t, writeCtx, db, `
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (5, 1, 20, 16, TIMESTAMPTZ '2026-08-12 18:00:00+08')
|
||||
`)
|
||||
execGroupUsageRollupSQL(t, writeCtx, db, `
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (6, 1, 10, 32, TIMESTAMPTZ '2026-08-14 09:00:00+08')
|
||||
`)
|
||||
execGroupUsageRollupSQL(t, writeCtx, db, `DELETE FROM usage_logs WHERE id = 2`)
|
||||
|
||||
state := readGroupUsageRollupTestState(t, ctx, db)
|
||||
require.Equal(t, "2026-08-11", state.closedBefore)
|
||||
require.Equal(t, "2026-08-14", state.buildingUntil.String)
|
||||
require.Equal(t, "2026-08-11", state.buildDirtyFrom.String)
|
||||
|
||||
require.NoError(t, blocker.Rollback())
|
||||
select {
|
||||
case err := <-syncDone:
|
||||
require.NoError(t, err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("等待分组日桶同步完成超时")
|
||||
}
|
||||
|
||||
state = readGroupUsageRollupTestState(t, ctx, db)
|
||||
require.Equal(t, "2026-08-14", state.closedBefore)
|
||||
require.False(t, state.buildingUntil.Valid)
|
||||
require.False(t, state.buildDirtyFrom.Valid)
|
||||
requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", state.retainedFrom, todayStart)
|
||||
|
||||
summary := groupUsageSummaryByGroup(t, ctx, db, todayStart)
|
||||
require.InDelta(t, 41, summary[10][0], 1e-9)
|
||||
require.InDelta(t, 32, summary[10][1], 1e-9)
|
||||
require.InDelta(t, 8, summary[10][2], 1e-9)
|
||||
require.InDelta(t, 20, summary[20][0], 1e-9)
|
||||
require.InDelta(t, 0, summary[20][1], 1e-9)
|
||||
require.InDelta(t, 0, summary[20][2], 1e-9)
|
||||
}
|
||||
|
||||
// 保留期清理按整日推进保留下界后删除:发布水位不动,过期记录的写入不触发失效,
|
||||
// 窗口内的删除照常使日桶失效。
|
||||
func TestGroupUsageRollupRetentionCleanupKeepsPublishedWatermark(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai")
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai")
|
||||
todayStart := time.Date(2026, 8, 9, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
execGroupUsageRollupSQL(t, ctx, db, `
|
||||
INSERT INTO groups (id) VALUES (10), (20);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES
|
||||
(1, 1, 10, 1, TIMESTAMPTZ '2026-08-01 10:00:00+08'),
|
||||
(2, 1, 10, 2, TIMESTAMPTZ '2026-08-02 05:00:00+08'),
|
||||
(3, 1, 10, 4, TIMESTAMPTZ '2026-08-02 20:00:00+08'),
|
||||
(4, 1, 20, 8, TIMESTAMPTZ '2026-08-05 12:00:00+08'),
|
||||
(5, 1, 10, 16, TIMESTAMPTZ '2026-08-10 08:00:00+08');
|
||||
`)
|
||||
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
repo.clock = func() time.Time { return todayStart.Add(10 * time.Hour) }
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart))
|
||||
require.Equal(t, "2026-08-10", readGroupUsageRollupTestState(t, ctx, db).closedBefore)
|
||||
|
||||
shanghai, err := time.LoadLocation("Asia/Shanghai")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, repo.CleanupUsageLogs(ctx, time.Date(2026, 8, 2, 12, 0, 0, 0, shanghai)))
|
||||
|
||||
alignedCutoff := time.Date(2026, 8, 2, 0, 0, 0, 0, shanghai)
|
||||
state := readGroupUsageRollupTestState(t, ctx, db)
|
||||
require.Equal(t, "2026-08-10", state.closedBefore)
|
||||
require.True(t, state.expiredBefore.Equal(alignedCutoff), "expired_before=%s", state.expiredBefore)
|
||||
require.True(t, state.retainedFrom.Equal(alignedCutoff), "retained_from=%s", state.retainedFrom)
|
||||
require.False(t, state.buildingUntil.Valid)
|
||||
|
||||
var remaining []int64
|
||||
rows, err := db.QueryContext(ctx, "SELECT id FROM usage_logs ORDER BY id")
|
||||
require.NoError(t, err)
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
require.NoError(t, rows.Scan(&id))
|
||||
remaining = append(remaining, id)
|
||||
}
|
||||
require.NoError(t, rows.Err())
|
||||
require.NoError(t, rows.Close())
|
||||
require.Equal(t, []int64{2, 3, 4, 5}, remaining)
|
||||
|
||||
requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", alignedCutoff, todayStart)
|
||||
summary := groupUsageSummaryByGroup(t, ctx, db, todayStart)
|
||||
require.InDelta(t, 22, summary[10][0], 1e-9)
|
||||
require.InDelta(t, 16, summary[10][1], 1e-9)
|
||||
require.InDelta(t, 8, summary[20][0], 1e-9)
|
||||
|
||||
execGroupUsageRollupSQL(t, ctx, db, `
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (6, 1, 10, 100, TIMESTAMPTZ '2026-08-01 12:00:00+08')
|
||||
`)
|
||||
require.Equal(t, "2026-08-10", readGroupUsageRollupTestState(t, ctx, db).closedBefore)
|
||||
summary = groupUsageSummaryByGroup(t, ctx, db, todayStart)
|
||||
require.InDelta(t, 22, summary[10][0], 1e-9)
|
||||
|
||||
execGroupUsageRollupSQL(t, ctx, db, `DELETE FROM usage_logs WHERE id = 4`)
|
||||
require.Equal(t, "2026-08-05", readGroupUsageRollupTestState(t, ctx, db).closedBefore)
|
||||
summary = groupUsageSummaryByGroup(t, ctx, db, todayStart)
|
||||
require.InDelta(t, 0, summary[20][0], 1e-9)
|
||||
require.InDelta(t, 22, summary[10][0], 1e-9)
|
||||
}
|
||||
|
||||
func TestGroupUsageRollupTriggersIgnoreRowsBeforeExpiredFloor(t *testing.T) {
|
||||
for _, partitioned := range []bool{false, true} {
|
||||
name := "ordinary"
|
||||
if partitioned {
|
||||
name = "partitioned"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, partitioned)
|
||||
tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema)
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, tx, "Asia/Shanghai"))
|
||||
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO groups (id) VALUES (10);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES
|
||||
(1, 1, 10, 1, TIMESTAMPTZ '2020-01-15 08:00:00+08'),
|
||||
(2, 1, 10, 2, TIMESTAMPTZ '2020-02-05 08:00:00+08');
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2020-03-01',
|
||||
expired_before = TIMESTAMPTZ '2020-02-01 00:00:00+08'
|
||||
WHERE id = 1;
|
||||
DELETE FROM usage_logs WHERE id = 1;
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (3, 1, 10, 4, TIMESTAMPTZ '2020-01-20 08:00:00+08');
|
||||
UPDATE usage_logs SET actual_cost = 5 WHERE id = 3;
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "2020-03-01", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore)
|
||||
|
||||
// 把过期记录改到保留窗口内,按新日期失效。
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
UPDATE usage_logs SET created_at = TIMESTAMPTZ '2020-02-20 08:00:00+08' WHERE id = 3
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "2020-02-20", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore)
|
||||
|
||||
_, err = tx.ExecContext(ctx, `DELETE FROM usage_logs WHERE id = 2`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "2020-02-05", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupUsageRollupTriggersMarkDirtyDuringBuild(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema)
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, tx, "Asia/Shanghai"))
|
||||
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO groups (id) VALUES (10);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2020-01-05',
|
||||
building_until = DATE '2020-01-10'
|
||||
WHERE id = 1;
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (1, 1, 10, 1, TIMESTAMPTZ '2020-01-12 08:00:00+08');
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
state := readGroupUsageRollupTestStateTx(t, ctx, tx)
|
||||
require.Equal(t, "2020-01-05", state.closedBefore)
|
||||
require.False(t, state.buildDirtyFrom.Valid)
|
||||
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (2, 1, 10, 1, TIMESTAMPTZ '2020-01-07 08:00:00+08')
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
state = readGroupUsageRollupTestStateTx(t, ctx, tx)
|
||||
require.Equal(t, "2020-01-05", state.closedBefore)
|
||||
require.Equal(t, "2020-01-07", state.buildDirtyFrom.String)
|
||||
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (3, 1, 10, 1, TIMESTAMPTZ '2020-01-03 08:00:00+08')
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
state = readGroupUsageRollupTestStateTx(t, ctx, tx)
|
||||
require.Equal(t, "2020-01-03", state.closedBefore)
|
||||
require.Equal(t, "2020-01-03", state.buildDirtyFrom.String)
|
||||
|
||||
_, err = tx.ExecContext(ctx, `DELETE FROM usage_logs WHERE id = 1`)
|
||||
require.NoError(t, err)
|
||||
state = readGroupUsageRollupTestStateTx(t, ctx, tx)
|
||||
require.Equal(t, "2020-01-03", state.buildDirtyFrom.String)
|
||||
}
|
||||
|
||||
// 计算阶段对状态行只持 FOR KEY SHARE:迟到写入与窗口内删除都不等待它。
|
||||
func TestGroupUsageRollupBuildKeyShareDoesNotBlockLateWrites(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
seedTx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema)
|
||||
_, err := seedTx.ExecContext(ctx, `
|
||||
INSERT INTO groups (id) VALUES (10);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (1, 1, 10, 1, TIMESTAMPTZ '2020-01-08 08:00:00+08');
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2020-01-05',
|
||||
building_until = DATE '2020-01-10'
|
||||
WHERE id = 1;
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, seedTx.Commit())
|
||||
|
||||
buildTx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema)
|
||||
defer func() { _ = buildTx.Rollback() }()
|
||||
var stateID int16
|
||||
require.NoError(t, buildTx.QueryRowContext(ctx, `
|
||||
SELECT id FROM usage_group_rollup_state WHERE id = 1 FOR KEY SHARE
|
||||
`).Scan(&stateID))
|
||||
|
||||
for _, statement := range []string{
|
||||
`INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
VALUES (2, 1, 10, 1, TIMESTAMPTZ '2020-01-07 08:00:00+08')`,
|
||||
`DELETE FROM usage_logs WHERE id = 1`,
|
||||
} {
|
||||
writeTx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema)
|
||||
require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, writeTx, "Asia/Shanghai"))
|
||||
var writePID int
|
||||
require.NoError(t, writeTx.QueryRowContext(ctx, "SELECT pg_backend_pid()").Scan(&writePID))
|
||||
result := make(chan error, 1)
|
||||
go func(statement string) {
|
||||
_, execErr := writeTx.ExecContext(ctx, statement)
|
||||
result <- execErr
|
||||
}(statement)
|
||||
blocked, err := waitForGroupUsageRollupStateLock(ctx, writePID, result)
|
||||
require.NoError(t, err)
|
||||
require.False(t, blocked, "计算阶段不得阻塞: %s", statement)
|
||||
require.NoError(t, writeTx.Commit())
|
||||
}
|
||||
|
||||
require.NoError(t, buildTx.Commit())
|
||||
var dirtyFrom string
|
||||
require.NoError(t, integrationDB.QueryRowContext(ctx, fmt.Sprintf(
|
||||
"SELECT build_dirty_from::text FROM %s.usage_group_rollup_state WHERE id = 1",
|
||||
pq.QuoteIdentifier(schema),
|
||||
)).Scan(&dirtyFrom))
|
||||
require.Equal(t, "2020-01-07", dirtyFrom)
|
||||
}
|
||||
|
||||
func TestGroupUsageRollupSyncSkipsWhileAnotherBuildHoldsLock(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai")
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai")
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
holder, err := integrationDB.Conn(ctx)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = holder.Close() }()
|
||||
var locked bool
|
||||
require.NoError(t, holder.QueryRowContext(ctx, groupUsageRollupBuildLockSQL).Scan(&locked))
|
||||
require.True(t, locked)
|
||||
defer func() { _, _ = holder.ExecContext(context.Background(), groupUsageRollupBuildUnlockSQL) }()
|
||||
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart))
|
||||
state := readGroupUsageRollupTestState(t, ctx, db)
|
||||
require.Equal(t, "1970-01-01", state.closedBefore)
|
||||
require.False(t, state.buildingUntil.Valid)
|
||||
}
|
||||
|
||||
// 上一次重建在登记之后中断:下一次同步覆盖遗留登记并发布到今日。
|
||||
func TestGroupUsageRollupSyncRecoversFromInterruptedBuild(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai")
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai")
|
||||
todayStart := time.Date(2026, 8, 13, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
execGroupUsageRollupSQL(t, ctx, db, `
|
||||
INSERT INTO groups (id) VALUES (10);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES
|
||||
(1, 1, 10, 1, TIMESTAMPTZ '2026-08-11 09:00:00+08'),
|
||||
(2, 1, 10, 2, TIMESTAMPTZ '2026-08-12 09:00:00+08'),
|
||||
(3, 1, 10, 4, TIMESTAMPTZ '2026-08-13 09:00:00+08');
|
||||
INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost) VALUES
|
||||
(DATE '2026-08-11', 10, 1),
|
||||
(DATE '2026-08-12', 10, 999);
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2026-08-12',
|
||||
retained_from = TIMESTAMPTZ '2026-08-11 09:00:00+08',
|
||||
timezone_name = 'Asia/Shanghai',
|
||||
building_until = DATE '2026-08-14',
|
||||
build_dirty_from = DATE '2026-08-13'
|
||||
WHERE id = 1;
|
||||
`)
|
||||
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart))
|
||||
|
||||
state := readGroupUsageRollupTestState(t, ctx, db)
|
||||
require.Equal(t, "2026-08-14", state.closedBefore)
|
||||
require.False(t, state.buildingUntil.Valid)
|
||||
require.False(t, state.buildDirtyFrom.Valid)
|
||||
requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", state.retainedFrom, todayStart)
|
||||
}
|
||||
|
||||
type groupUsageRollupTestState struct {
|
||||
closedBefore string
|
||||
retainedFrom time.Time
|
||||
expiredBefore time.Time
|
||||
buildingUntil sql.NullString
|
||||
buildDirtyFrom sql.NullString
|
||||
}
|
||||
|
||||
const groupUsageRollupTestStateQuery = `
|
||||
SELECT closed_before::text, retained_from, expired_before, building_until::text, build_dirty_from::text
|
||||
FROM usage_group_rollup_state
|
||||
WHERE id = 1
|
||||
`
|
||||
|
||||
func readGroupUsageRollupTestState(t *testing.T, ctx context.Context, q sqlQueryer) groupUsageRollupTestState {
|
||||
t.Helper()
|
||||
var state groupUsageRollupTestState
|
||||
require.NoError(t, scanSingleRow(ctx, q, groupUsageRollupTestStateQuery, nil,
|
||||
&state.closedBefore, &state.retainedFrom, &state.expiredBefore, &state.buildingUntil, &state.buildDirtyFrom))
|
||||
return state
|
||||
}
|
||||
|
||||
func readGroupUsageRollupTestStateTx(t *testing.T, ctx context.Context, tx *sql.Tx) groupUsageRollupTestState {
|
||||
t.Helper()
|
||||
return readGroupUsageRollupTestState(t, ctx, tx)
|
||||
}
|
||||
|
||||
// openGroupUsageRollupSchemaDB 打开一个 search_path 指向 schema 的连接池,供仓储以 *sql.DB 方式运行。
|
||||
func openGroupUsageRollupSchemaDB(t *testing.T, schema, timezoneName string) *sql.DB {
|
||||
t.Helper()
|
||||
dsn, err := url.Parse(integrationDSN)
|
||||
require.NoError(t, err)
|
||||
query := dsn.Query()
|
||||
query.Set("search_path", schema)
|
||||
query.Set("TimeZone", timezoneName)
|
||||
dsn.RawQuery = query.Encode()
|
||||
db, err := sql.Open("postgres", dsn.String())
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
require.NoError(t, db.PingContext(context.Background()))
|
||||
return db
|
||||
}
|
||||
|
||||
func execGroupUsageRollupSQL(t *testing.T, ctx context.Context, db *sql.DB, query string) {
|
||||
t.Helper()
|
||||
_, err := db.ExecContext(ctx, query)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// waitForBlockedGroupUsageRollupStatement 等待某个后端在执行包含 fragment 的语句时进入锁等待。
|
||||
func waitForBlockedGroupUsageRollupStatement(t *testing.T, ctx context.Context, fragment string) {
|
||||
t.Helper()
|
||||
ticker := time.NewTicker(10 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
var blocked bool
|
||||
require.NoError(t, integrationDB.QueryRowContext(ctx, `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM pg_stat_activity
|
||||
WHERE wait_event_type = 'Lock'
|
||||
AND position($1 in query) > 0
|
||||
)
|
||||
`, fragment).Scan(&blocked))
|
||||
if blocked {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-ticker.C:
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("等待语句进入锁等待超时: %s", fragment)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// requireGroupUsageRollupsMatchUsageLogs 断言 [retainedFrom 所在日, todayStart) 的日桶与 usage_logs 明细逐日一致。
|
||||
func requireGroupUsageRollupsMatchUsageLogs(t *testing.T, ctx context.Context, db *sql.DB, timezoneName string, retainedFrom, todayStart time.Time) {
|
||||
t.Helper()
|
||||
expected := collectGroupUsageRollupBuckets(t, ctx, db, `
|
||||
SELECT (created_at AT TIME ZONE $3::text)::date::text, group_id, SUM(actual_cost)::float8
|
||||
FROM usage_logs
|
||||
WHERE group_id IS NOT NULL
|
||||
AND created_at >= $1
|
||||
AND created_at < $2
|
||||
GROUP BY 1, 2
|
||||
`, retainedFrom, todayStart, timezoneName)
|
||||
actual := collectGroupUsageRollupBuckets(t, ctx, db, `
|
||||
SELECT bucket_date::text, group_id, actual_cost::float8
|
||||
FROM usage_group_daily_rollups
|
||||
WHERE bucket_date >= ($1::timestamptz AT TIME ZONE $3::text)::date
|
||||
AND bucket_date < ($2::timestamptz AT TIME ZONE $3::text)::date
|
||||
`, retainedFrom, todayStart, timezoneName)
|
||||
require.Equal(t, expected, actual)
|
||||
}
|
||||
|
||||
func collectGroupUsageRollupBuckets(t *testing.T, ctx context.Context, db *sql.DB, query string, args ...any) map[string]float64 {
|
||||
t.Helper()
|
||||
rows, err := db.QueryContext(ctx, query, args...)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = rows.Close() }()
|
||||
buckets := make(map[string]float64)
|
||||
for rows.Next() {
|
||||
var bucketDate string
|
||||
var groupID int64
|
||||
var cost float64
|
||||
require.NoError(t, rows.Scan(&bucketDate, &groupID, &cost))
|
||||
buckets[fmt.Sprintf("%s/%d", bucketDate, groupID)] = cost
|
||||
}
|
||||
require.NoError(t, rows.Err())
|
||||
return buckets
|
||||
}
|
||||
|
||||
// groupUsageSummaryByGroup 返回 group_id → [total, today, yesterday]。
|
||||
func groupUsageSummaryByGroup(t *testing.T, ctx context.Context, db *sql.DB, todayStart time.Time) map[int64][3]float64 {
|
||||
t.Helper()
|
||||
result, err := newUsageLogRepositoryWithSQL(nil, db).GetAllGroupUsageSummary(ctx, todayStart)
|
||||
require.NoError(t, err)
|
||||
summary := make(map[int64][3]float64, len(result))
|
||||
for _, row := range result {
|
||||
summary[row.GroupID] = [3]float64{row.TotalCost, row.TodayCost, row.YesterdayCost}
|
||||
}
|
||||
return summary
|
||||
}
|
||||
|
||||
// 重建进行中的大批量删除:脏日期已覆盖的行不写状态行,状态行在事务内只更新一次。
|
||||
func TestGroupUsageRollupBulkDeleteDuringBuildWritesStateOnce(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema)
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
require.NoError(t, setGroupUsageRollupTriggerTimeZone(ctx, tx, "Asia/Shanghai"))
|
||||
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO groups (id) VALUES (10);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at)
|
||||
SELECT n, 1, 10, 1, TIMESTAMPTZ '2020-01-15 08:00:00+08' + n * INTERVAL '1 second'
|
||||
FROM generate_series(1, 2000) AS n;
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2020-01-10',
|
||||
building_until = DATE '2020-02-01'
|
||||
WHERE id = 1;
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
|
||||
var updatesBefore int64
|
||||
require.NoError(t, tx.QueryRowContext(ctx, `
|
||||
SELECT n_tup_upd FROM pg_stat_xact_user_tables
|
||||
WHERE schemaname = current_schema() AND relname = 'usage_group_rollup_state'
|
||||
`).Scan(&updatesBefore))
|
||||
|
||||
_, err = tx.ExecContext(ctx, `DELETE FROM usage_logs`)
|
||||
require.NoError(t, err)
|
||||
|
||||
var updatesAfter int64
|
||||
require.NoError(t, tx.QueryRowContext(ctx, `
|
||||
SELECT n_tup_upd FROM pg_stat_xact_user_tables
|
||||
WHERE schemaname = current_schema() AND relname = 'usage_group_rollup_state'
|
||||
`).Scan(&updatesAfter))
|
||||
require.Equal(t, int64(1), updatesAfter-updatesBefore)
|
||||
|
||||
state := readGroupUsageRollupTestStateTx(t, ctx, tx)
|
||||
require.Equal(t, "2020-01-10", state.closedBefore)
|
||||
require.Equal(t, "2020-01-15", state.buildDirtyFrom.String)
|
||||
}
|
||||
|
||||
// 应用侧失效的起点早于保留下界时,从保留下界所在日开始失效。
|
||||
func TestGroupUsageRollupInvalidateAtStartsFromExpiredFloor(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
tx := beginGroupUsageRollupTriggerTestTx(t, ctx, schema)
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2020-03-01',
|
||||
expired_before = TIMESTAMPTZ '2020-02-01 00:00:00+08'
|
||||
WHERE id = 1;
|
||||
SELECT invalidate_group_usage_rollups_at(TIMESTAMPTZ '2020-01-10 08:00:00+08', 'Asia/Shanghai');
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "2020-02-01", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore)
|
||||
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
SELECT invalidate_group_usage_rollups_at(TIMESTAMPTZ '2020-02-10 08:00:00+08', 'Asia/Shanghai')
|
||||
`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "2020-02-01", readGroupUsageRollupTestStateTx(t, ctx, tx).closedBefore)
|
||||
}
|
||||
|
||||
// 夏令时在零点跳变的日期(America/Santiago 2026-09-06 没有 00:00):从该日续建时不覆盖前一天的日桶。
|
||||
func TestGroupUsageRollupSyncKeepsPreviousDayBucketAcrossMidnightDSTGap(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
useGroupUsageRepositoryTestTimezone(t, "America/Santiago")
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, false)
|
||||
db := openGroupUsageRollupSchemaDB(t, schema, "America/Santiago")
|
||||
santiago, err := time.LoadLocation("America/Santiago")
|
||||
require.NoError(t, err)
|
||||
todayStart := time.Date(2026, 9, 8, 0, 0, 0, 0, santiago)
|
||||
|
||||
execGroupUsageRollupSQL(t, ctx, db, `
|
||||
INSERT INTO groups (id) VALUES (10);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES
|
||||
(1, 1, 10, 1, TIMESTAMPTZ '2026-09-06 02:30:00+00'),
|
||||
(2, 1, 10, 2, TIMESTAMPTZ '2026-09-06 03:30:00+00'),
|
||||
(3, 1, 10, 4, TIMESTAMPTZ '2026-09-06 05:00:00+00'),
|
||||
(4, 1, 10, 8, TIMESTAMPTZ '2026-09-07 13:00:00+00');
|
||||
INSERT INTO usage_group_daily_rollups (bucket_date, group_id, actual_cost)
|
||||
VALUES (DATE '2026-09-05', 10, 3);
|
||||
UPDATE usage_group_rollup_state
|
||||
SET closed_before = DATE '2026-09-06',
|
||||
retained_from = TIMESTAMPTZ '2026-09-06 02:30:00+00',
|
||||
timezone_name = 'America/Santiago'
|
||||
WHERE id = 1;
|
||||
`)
|
||||
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart))
|
||||
|
||||
state := readGroupUsageRollupTestState(t, ctx, db)
|
||||
require.Equal(t, "2026-09-08", state.closedBefore)
|
||||
requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "America/Santiago", state.retainedFrom, todayStart)
|
||||
var previousDay float64
|
||||
require.NoError(t, db.QueryRowContext(ctx, `
|
||||
SELECT actual_cost::float8 FROM usage_group_daily_rollups
|
||||
WHERE bucket_date = DATE '2026-09-05' AND group_id = 10
|
||||
`).Scan(&previousDay))
|
||||
require.InDelta(t, 3, previousDay, 1e-9)
|
||||
}
|
||||
|
||||
// 有长读者持有 usage_logs 的 ACCESS SHARE 时,删除分区在锁等待超时后跳过;
|
||||
// 过期记录由按行删除清理,清理整体成功,分组日汇总保持一致。
|
||||
func TestGroupUsageRollupRetentionCleanupSkipsPartitionDropOnLockTimeout(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
useGroupUsageRepositoryTestTimezone(t, "Asia/Shanghai")
|
||||
schema := createGroupUsageRollupTriggerTestSchema(t, ctx, true)
|
||||
db := openGroupUsageRollupSchemaDB(t, schema, "Asia/Shanghai")
|
||||
todayStart := time.Date(2026, 8, 9, 16, 0, 0, 0, time.UTC)
|
||||
|
||||
execGroupUsageRollupSQL(t, ctx, db, `
|
||||
CREATE TABLE usage_logs_202605 PARTITION OF usage_logs
|
||||
FOR VALUES FROM ('2026-05-01') TO ('2026-06-01');
|
||||
INSERT INTO groups (id) VALUES (10);
|
||||
INSERT INTO users (id) VALUES (1);
|
||||
INSERT INTO usage_logs (id, user_id, group_id, actual_cost, created_at) VALUES
|
||||
(1, 1, 10, 1, TIMESTAMPTZ '2026-05-10 10:00:00+08'),
|
||||
(2, 1, 10, 2, TIMESTAMPTZ '2026-07-20 10:00:00+08'),
|
||||
(3, 1, 10, 4, TIMESTAMPTZ '2026-08-05 10:00:00+08');
|
||||
`)
|
||||
repo := newDashboardAggregationRepositoryWithSQL(db)
|
||||
repo.clock = func() time.Time { return todayStart.Add(10 * time.Hour) }
|
||||
require.NoError(t, repo.SyncGroupUsageRollups(ctx, todayStart))
|
||||
|
||||
reader, err := db.BeginTx(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = reader.Rollback() }()
|
||||
var count int
|
||||
require.NoError(t, reader.QueryRowContext(ctx, "SELECT COUNT(*) FROM usage_logs").Scan(&count))
|
||||
require.Equal(t, 3, count)
|
||||
|
||||
shanghai, err := time.LoadLocation("Asia/Shanghai")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, repo.CleanupUsageLogs(ctx, time.Date(2026, 7, 1, 0, 0, 0, 0, shanghai)))
|
||||
require.NoError(t, reader.Rollback())
|
||||
|
||||
var partitionExists bool
|
||||
require.NoError(t, db.QueryRowContext(ctx, "SELECT to_regclass('usage_logs_202605') IS NOT NULL").Scan(&partitionExists))
|
||||
require.True(t, partitionExists)
|
||||
require.NoError(t, db.QueryRowContext(ctx, "SELECT COUNT(*) FROM usage_logs").Scan(&count))
|
||||
require.Equal(t, 2, count)
|
||||
|
||||
state := readGroupUsageRollupTestState(t, ctx, db)
|
||||
require.Equal(t, "2026-08-10", state.closedBefore)
|
||||
requireGroupUsageRollupsMatchUsageLogs(t, ctx, db, "Asia/Shanghai", state.retainedFrom, todayStart)
|
||||
summary := groupUsageSummaryByGroup(t, ctx, db, todayStart)
|
||||
require.InDelta(t, 6, summary[10][0], 1e-9)
|
||||
}
|
||||
@@ -451,6 +451,7 @@ func createGroupUsageRollupTriggerTestSchema(t *testing.T, ctx context.Context,
|
||||
for _, migrationName := range []string{
|
||||
"222_group_usage_daily_rollups.sql",
|
||||
"223_group_usage_rollup_timezone.sql",
|
||||
"251_group_usage_rollup_nonblocking_build.sql",
|
||||
} {
|
||||
migrationSQL, readErr := migrations.FS.ReadFile(migrationName)
|
||||
require.NoError(t, readErr)
|
||||
|
||||
@@ -63,8 +63,6 @@ const (
|
||||
// 上游域名被解析到 443 不可达的 IP 时(DNS 污染/路由异常),单个账号就要卡满
|
||||
// 内核超时;而多账号故障转移是串行的,一次请求会阻塞数分钟且不写中间错误。
|
||||
defaultUpstreamDialTimeout = 10 * time.Second
|
||||
// defaultUpstreamDialKeepAlive: TCP keepalive 探测间隔,与 Go 默认值保持一致
|
||||
defaultUpstreamDialKeepAlive = 30 * time.Second
|
||||
// defaultUpstreamTLSHandshakeTimeout: TLS 握手超时(10秒)
|
||||
// 与建连超时同量级,避免 TCP 已连通但对端不推进握手时无限等待
|
||||
defaultUpstreamTLSHandshakeTimeout = 10 * time.Second
|
||||
@@ -1365,8 +1363,14 @@ func defaultPoolSettings(cfg *config.Config) poolSettings {
|
||||
// 建连没有任何超时上限,只能等内核 TCP 重传耗尽(Linux 约 130 秒)。
|
||||
func newUpstreamDialer() *net.Dialer {
|
||||
return &net.Dialer{
|
||||
Timeout: defaultUpstreamDialTimeout,
|
||||
KeepAlive: defaultUpstreamDialKeepAlive,
|
||||
Timeout: defaultUpstreamDialTimeout,
|
||||
KeepAliveConfig: net.KeepAliveConfig{
|
||||
Enable: true,
|
||||
Idle: upstreamKeepAliveIdle,
|
||||
Interval: upstreamKeepAliveInterval,
|
||||
Count: upstreamKeepAliveCount,
|
||||
},
|
||||
Control: upstreamDialControl,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ func TestNewUpstreamDialerHasBoundedTimeout(t *testing.T) {
|
||||
|
||||
require.Greater(t, dialer.Timeout, time.Duration(0), "建连超时必须有上限")
|
||||
require.Equal(t, defaultUpstreamDialTimeout, dialer.Timeout)
|
||||
require.Equal(t, defaultUpstreamDialKeepAlive, dialer.KeepAlive)
|
||||
require.Equal(t, net.KeepAliveConfig{Enable: true, Idle: 15 * time.Second, Interval: 5 * time.Second, Count: 3}, dialer.KeepAliveConfig)
|
||||
}
|
||||
|
||||
// 建连超时对 HTTP 代理同样生效:Transport.Proxy 走的仍是 DialContext,
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package repository
|
||||
|
||||
import "time"
|
||||
|
||||
// TCP keep-alive of upstream connections (newUpstreamDialer). A connection
|
||||
// whose peer stops answering is aborted upstreamTCPUserTimeout after its last
|
||||
// received packet: idle 15 s, then 3 probes 5 s apart. With the previous
|
||||
// KeepAlive of 30 s and Go's default interval 15 s and count 9, the same case
|
||||
// took 165 s.
|
||||
//
|
||||
// TCP_USER_TIMEOUT (Linux only, see upstreamDialControl) is set to
|
||||
// idle + interval * count, as Cloudflare's "When TCP sockets refuse to die"
|
||||
// (2019) recommends when both are used: once it is set the kernel aborts on it
|
||||
// rather than on the probe count, so a larger value would add probes and a
|
||||
// smaller one would cut them. It also bounds request data the peer never
|
||||
// acknowledges, where keep-alive does not run. gRPC proposal A18 likewise sets
|
||||
// it only on Linux.
|
||||
const (
|
||||
upstreamKeepAliveIdle = 15 * time.Second
|
||||
upstreamKeepAliveInterval = 5 * time.Second
|
||||
upstreamKeepAliveCount = 3
|
||||
upstreamTCPUserTimeout = upstreamKeepAliveIdle + upstreamKeepAliveInterval*upstreamKeepAliveCount
|
||||
)
|
||||
@@ -0,0 +1,28 @@
|
||||
//go:build linux
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// tcpUserTimeout is TCP_USER_TIMEOUT from Linux include/uapi/linux/tcp.h; the
|
||||
// standard library's syscall package does not define it on linux/amd64.
|
||||
const tcpUserTimeout = 0x12
|
||||
|
||||
// upstreamDialControl sets TCP_USER_TIMEOUT on each upstream socket
|
||||
// before it connects. A failure is logged and the dial goes on without the
|
||||
// option, like the standard library does for the keep-alive options.
|
||||
func upstreamDialControl(network, _ string, raw syscall.RawConn) error {
|
||||
var sockErr error
|
||||
if err := raw.Control(func(fd uintptr) {
|
||||
sockErr = syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, tcpUserTimeout, int(upstreamTCPUserTimeout.Milliseconds()))
|
||||
}); err != nil {
|
||||
sockErr = err
|
||||
}
|
||||
if sockErr != nil {
|
||||
slog.Warn("upstream_tcp_user_timeout_not_set", "network", network, "error", sockErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//go:build linux
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TCP_USER_TIMEOUT in Linux include/uapi/linux/tcp.h.
|
||||
const testTCPUserTimeoutOpt = 0x12
|
||||
|
||||
// A socket dialed by the upstream dialer carries the keep-alive configuration
|
||||
// and TCP_USER_TIMEOUT, read back from the kernel.
|
||||
func TestUpstreamDialerSetsKeepAliveAndUserTimeoutOnTheSocket(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = listener.Close() })
|
||||
accepted := make(chan net.Conn, 1)
|
||||
go func() {
|
||||
server, err := listener.Accept()
|
||||
if err != nil {
|
||||
close(accepted)
|
||||
return
|
||||
}
|
||||
accepted <- server
|
||||
}()
|
||||
|
||||
conn, err := newUpstreamDialer().DialContext(context.Background(), "tcp", listener.Addr().String())
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
if server, ok := <-accepted; ok {
|
||||
t.Cleanup(func() { _ = server.Close() })
|
||||
}
|
||||
tcpConn, ok := conn.(*net.TCPConn)
|
||||
require.True(t, ok, "%T", conn)
|
||||
raw, err := tcpConn.SyscallConn()
|
||||
require.NoError(t, err)
|
||||
|
||||
got := map[string]int{}
|
||||
var readErr error
|
||||
require.NoError(t, raw.Control(func(fd uintptr) {
|
||||
for _, opt := range []struct {
|
||||
name string
|
||||
level, which int
|
||||
}{
|
||||
{"SO_KEEPALIVE", syscall.SOL_SOCKET, syscall.SO_KEEPALIVE},
|
||||
{"TCP_KEEPIDLE", syscall.IPPROTO_TCP, syscall.TCP_KEEPIDLE},
|
||||
{"TCP_KEEPINTVL", syscall.IPPROTO_TCP, syscall.TCP_KEEPINTVL},
|
||||
{"TCP_KEEPCNT", syscall.IPPROTO_TCP, syscall.TCP_KEEPCNT},
|
||||
{"TCP_USER_TIMEOUT", syscall.IPPROTO_TCP, testTCPUserTimeoutOpt},
|
||||
} {
|
||||
value, err := syscall.GetsockoptInt(int(fd), opt.level, opt.which)
|
||||
if err != nil {
|
||||
readErr = err
|
||||
return
|
||||
}
|
||||
got[opt.name] = value
|
||||
}
|
||||
}))
|
||||
require.NoError(t, readErr)
|
||||
require.Equal(t, map[string]int{
|
||||
"SO_KEEPALIVE": 1,
|
||||
"TCP_KEEPIDLE": 15,
|
||||
"TCP_KEEPINTVL": 5,
|
||||
"TCP_KEEPCNT": 3,
|
||||
"TCP_USER_TIMEOUT": 30000,
|
||||
}, got)
|
||||
}
|
||||
|
||||
// A socket option the kernel refuses must not fail the dial: TCP_USER_TIMEOUT
|
||||
// does not apply to a UDP socket, so setting it there returns an error.
|
||||
func TestUpstreamDialerIgnoresUserTimeoutFailure(t *testing.T) {
|
||||
packetConn, err := net.ListenPacket("udp", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = packetConn.Close() })
|
||||
|
||||
conn, err := newUpstreamDialer().DialContext(context.Background(), "udp", packetConn.LocalAddr().String())
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, conn.Close())
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !linux
|
||||
|
||||
package repository
|
||||
|
||||
import "syscall"
|
||||
|
||||
// upstreamDialControl is nil off Linux: TCP_USER_TIMEOUT is a Linux socket
|
||||
// option, and the keep-alive configuration alone bounds idle connections.
|
||||
var upstreamDialControl func(network, address string, c syscall.RawConn) error
|
||||
@@ -36,6 +36,7 @@ const (
|
||||
|
||||
var (
|
||||
integrationDB *sql.DB
|
||||
integrationDSN string
|
||||
integrationEntClient *dbent.Client
|
||||
integrationRedis *redisclient.Client
|
||||
|
||||
@@ -91,6 +92,7 @@ func TestMain(m *testing.M) {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
integrationDSN = dsn
|
||||
integrationDB, err = openSQLWithRetry(ctx, dsn, 30*time.Second)
|
||||
if err != nil {
|
||||
log.Printf("failed to open sql db: %v", err)
|
||||
|
||||
@@ -1483,6 +1483,11 @@ func filterSchedulerCredentials(credentials map[string]any) map[string]any {
|
||||
// Candidate-list admission evaluates the account override before hydrating
|
||||
// the full account. Dropping it silently falls back to the platform threshold.
|
||||
keys := []string{"model_mapping", "compact_model_mapping", "api_key", "project_id", "oauth_type", "plan_type", "account_scheduling_threshold",
|
||||
// OpenAI 端点能力集必须进投影:候选过滤按 SupportsOpenAIEndpointCapability 判
|
||||
// capability_mismatch,而 Seedance 分支直接读该键、不走「未配置即放行」。
|
||||
// 裁掉后 Seedance 账号在选号阶段必然被剔除,表现为 /v1/models 能列出模型、
|
||||
// 建任务恒定 503 seedance_no_eligible_account。
|
||||
"openai_capabilities",
|
||||
// Gemini 显式缓存的候选过滤(GeminiExplicitCacheExclusions)读本投影判定账号是否支持显式缓存:
|
||||
// 官方地址、Vertex 认证方式与上游网关的显式缓存声明。缺这几个键时只能按类型粗筛,
|
||||
// 不支持的账号要逐个选中后才被剔除。
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
//go:build unit
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// buildSchedulerMetadataAccount 是调度候选的唯一投影出口,openAIAccountSkipReason
|
||||
// 按 SupportsOpenAIEndpointCapability 判 capability_mismatch。Seedance 分支直接读
|
||||
// credentials.openai_capabilities 且不走「未配置即放行」,所以该键一旦被裁掉,
|
||||
// Seedance 账号在选号阶段必然被剔除,而 /v1/models 走 DB 全量仍会列出模型。
|
||||
func TestSchedulerMetadataKeepsOpenAICapabilities(t *testing.T) {
|
||||
account := service.Account{
|
||||
ID: 1,
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-test",
|
||||
"base_url": "https://relay.example.com/api/v3",
|
||||
"openai_capabilities": []string{"seedance"},
|
||||
},
|
||||
}
|
||||
|
||||
projected := buildSchedulerMetadataAccount(account)
|
||||
|
||||
require.Equal(t, []string{"seedance"}, projected.Credentials["openai_capabilities"])
|
||||
require.Equal(t, "https://relay.example.com/api/v3", projected.Credentials["base_url"])
|
||||
require.True(t, projected.SupportsOpenAIEndpointCapability(service.OpenAIEndpointCapabilitySeedance))
|
||||
}
|
||||
|
||||
func TestSchedulerMetadataDropsUnlistedCredentials(t *testing.T) {
|
||||
account := service.Account{
|
||||
ID: 2,
|
||||
Platform: service.PlatformOpenAI,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-test",
|
||||
"base_url": "https://relay.example.com/api/v3",
|
||||
"openai_capabilities": []string{"seedance"},
|
||||
"model_mapping": map[string]string{"seedance-2-5": "doubao-seedance-2-5-260628"},
|
||||
"unlisted_secret": "drop-me",
|
||||
},
|
||||
}
|
||||
|
||||
projected := buildSchedulerMetadataAccount(account)
|
||||
|
||||
require.Equal(t, map[string]string{"seedance-2-5": "doubao-seedance-2-5-260628"}, projected.Credentials["model_mapping"])
|
||||
require.NotContains(t, projected.Credentials, "unlisted_secret")
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//go:build integration
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSchedulerSnapshotConfiguredMembership(t *testing.T) {
|
||||
for _, platform := range []string{service.PlatformOpenAI, service.PlatformAnthropic, service.PlatformGemini} {
|
||||
t.Run(platform, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tx := testEntTx(t)
|
||||
client := tx.Client()
|
||||
repo := newAccountRepositoryWithSQL(client, tx, nil)
|
||||
group := mustCreateGroup(t, client, &service.Group{Name: "snapshot-pool", Platform: platform})
|
||||
other := mustCreateGroup(t, client, &service.Group{Name: "snapshot-other", Platform: platform})
|
||||
future, past := time.Now().Add(time.Hour), time.Now().Add(-time.Hour)
|
||||
ids := make(map[int64]map[string]int64)
|
||||
for _, gid := range []int64{0, group.ID, other.ID} {
|
||||
ids[gid] = make(map[string]int64)
|
||||
for _, kind := range []string{"ready", "cooling", "expired", "manual", "disabled", "deleted", "other_platform", "mixed_on", "mixed_off"} {
|
||||
accountPlatform := platform
|
||||
if kind == "mixed_on" || kind == "mixed_off" {
|
||||
accountPlatform = service.PlatformAntigravity
|
||||
}
|
||||
if kind == "other_platform" {
|
||||
accountPlatform = service.PlatformGrok
|
||||
if platform == accountPlatform {
|
||||
accountPlatform = service.PlatformOpenAI
|
||||
}
|
||||
}
|
||||
create := client.Account.Create().SetName(fmt.Sprintf("%s-%d", kind, gid)).
|
||||
SetPlatform(accountPlatform).SetType(service.AccountTypeAPIKey).
|
||||
SetCredentials(map[string]any{}).SetExtra(map[string]any{"mixed_scheduling": kind == "mixed_on"}).
|
||||
SetStatus(service.StatusActive).SetSchedulable(kind != "manual")
|
||||
switch kind {
|
||||
case "cooling":
|
||||
create.SetRateLimitResetAt(future).SetOverloadUntil(future).SetTempUnschedulableUntil(future)
|
||||
case "expired":
|
||||
create.SetExpiresAt(past).SetAutoPauseOnExpired(true)
|
||||
case "disabled":
|
||||
create.SetStatus(service.StatusDisabled)
|
||||
case "deleted":
|
||||
create.SetDeletedAt(past)
|
||||
}
|
||||
account, err := create.Save(ctx)
|
||||
require.NoError(t, err)
|
||||
ids[gid][kind] = account.ID
|
||||
if gid > 0 {
|
||||
_, err = client.AccountGroup.Create().SetAccountID(account.ID).SetGroupID(gid).Save(ctx)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, scope := range []string{"simple", "group", "ungrouped"} {
|
||||
for _, forced := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("%s/forced=%t", scope, forced), func(t *testing.T) {
|
||||
cfg := &config.Config{RunMode: config.RunModeStandard}
|
||||
cfg.Gateway.Scheduling.DbFallbackEnabled = true
|
||||
var groupID *int64
|
||||
groups := []int64{0}
|
||||
if scope == "group" {
|
||||
groupID, groups = &group.ID, []int64{group.ID}
|
||||
}
|
||||
if scope == "simple" {
|
||||
cfg.RunMode = config.RunModeSimple
|
||||
groupID, groups = &group.ID, []int64{0, group.ID, other.ID}
|
||||
}
|
||||
mixed := platform != service.PlatformOpenAI && !forced
|
||||
var wantReady, wantMembers []int64
|
||||
for _, gid := range groups {
|
||||
wantReady = append(wantReady, ids[gid]["ready"])
|
||||
wantMembers = append(wantMembers, ids[gid]["ready"], ids[gid]["cooling"], ids[gid]["expired"])
|
||||
if mixed {
|
||||
wantReady = append(wantReady, ids[gid]["mixed_on"])
|
||||
wantMembers = append(wantMembers, ids[gid]["mixed_on"])
|
||||
}
|
||||
}
|
||||
cache := NewSchedulerCache(testRedis(t))
|
||||
svc := service.NewSchedulerSnapshotService(cache, nil, repo, nil, cfg)
|
||||
accountIDs := func(accounts []service.Account) []int64 {
|
||||
out := make([]int64, len(accounts))
|
||||
for i := range accounts {
|
||||
out[i] = accounts[i].ID
|
||||
}
|
||||
return out
|
||||
}
|
||||
for range 2 {
|
||||
accounts, useMixed, err := svc.ListSchedulableAccounts(ctx, groupID, platform, forced)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, mixed, useMixed)
|
||||
require.ElementsMatch(t, wantReady, accountIDs(accounts), "both DB fallback and cache hit enforce current eligibility")
|
||||
}
|
||||
bucket := service.SchedulerBucket{Platform: platform, Mode: service.SchedulerModeSingle}
|
||||
if scope == "group" {
|
||||
bucket.GroupID = group.ID
|
||||
}
|
||||
if forced {
|
||||
bucket.Mode = service.SchedulerModeForced
|
||||
} else if mixed {
|
||||
bucket.Mode = service.SchedulerModeMixed
|
||||
}
|
||||
members, hit, err := cache.GetSnapshot(ctx, bucket)
|
||||
require.NoError(t, err)
|
||||
require.True(t, hit)
|
||||
memberIDs := make([]int64, len(members))
|
||||
for i := range members {
|
||||
memberIDs[i] = members[i].ID
|
||||
}
|
||||
require.ElementsMatch(t, wantMembers, memberIDs, "the stored pool retains timed blocks without widening platform/group or manual eligibility")
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -291,9 +291,7 @@ func (r *usageCleanupRepository) DeleteUsageLogsBatch(ctx context.Context, filte
|
||||
return 0, fmt.Errorf("cleanup filters missing time range")
|
||||
}
|
||||
args = append(args, limit)
|
||||
if db, ok := r.sql.(*sql.DB); ok {
|
||||
return r.deleteUsageLogsBatchWithRollupInvalidation(ctx, db, whereClause, args)
|
||||
}
|
||||
// usage_logs 的行级触发器按被删记录的日期使分组日桶失效。
|
||||
query := fmt.Sprintf(`
|
||||
WITH target AS (
|
||||
SELECT id
|
||||
@@ -323,68 +321,6 @@ func (r *usageCleanupRepository) DeleteUsageLogsBatch(ctx context.Context, filte
|
||||
return deleted, nil
|
||||
}
|
||||
|
||||
func (r *usageCleanupRepository) deleteUsageLogsBatchWithRollupInvalidation(ctx context.Context, db *sql.DB, whereClause string, args []any) (int64, error) {
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
rollback := func(err error) (int64, error) {
|
||||
_ = tx.Rollback()
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if err := lockGroupUsageRollupState(ctx, tx); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
query := fmt.Sprintf(`
|
||||
WITH target AS (
|
||||
SELECT id
|
||||
FROM usage_logs
|
||||
WHERE %s
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT $%d
|
||||
)
|
||||
DELETE FROM usage_logs
|
||||
WHERE id IN (SELECT id FROM target)
|
||||
RETURNING created_at
|
||||
`, whereClause, len(args))
|
||||
rows, err := tx.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
|
||||
var deleted int64
|
||||
var earliestDeletedAt time.Time
|
||||
for rows.Next() {
|
||||
var deletedAt time.Time
|
||||
if err := rows.Scan(&deletedAt); err != nil {
|
||||
_ = rows.Close()
|
||||
return rollback(err)
|
||||
}
|
||||
deleted++
|
||||
if earliestDeletedAt.IsZero() || deletedAt.Before(earliestDeletedAt) {
|
||||
earliestDeletedAt = deletedAt
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
return rollback(err)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
|
||||
if deleted > 0 {
|
||||
if err := invalidateGroupUsageRollupsAt(ctx, tx, earliestDeletedAt); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return deleted, nil
|
||||
}
|
||||
|
||||
func buildUsageCleanupWhere(filters service.UsageCleanupFilters) (string, []any) {
|
||||
conditions := make([]string, 0, 8)
|
||||
args := make([]any, 0, 8)
|
||||
|
||||
@@ -418,16 +418,9 @@ func TestUsageCleanupRepositoryDeleteUsageLogsBatch(t *testing.T) {
|
||||
Model: &model,
|
||||
}
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectQuery("DELETE FROM usage_logs").
|
||||
WithArgs(start, end, userID, "gpt-4", 2).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"created_at"}).AddRow(start.Add(time.Hour)).AddRow(start.Add(2 * time.Hour)))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs(start.Add(time.Hour), "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
|
||||
deleted, err := repo.DeleteUsageLogsBatch(context.Background(), filters, 2)
|
||||
require.NoError(t, err)
|
||||
@@ -435,29 +428,22 @@ func TestUsageCleanupRepositoryDeleteUsageLogsBatch(t *testing.T) {
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestUsageCleanupRepositoryDeleteUsageLogsBatchAtomicallyInvalidatesGroupRollups(t *testing.T) {
|
||||
// 分组日桶失效由 usage_logs 的行级触发器完成,删除批次不显式锁定汇总状态行,
|
||||
// 因而不与 usage_logs 写入串行。
|
||||
func TestUsageCleanupRepositoryDeleteUsageLogsBatchDoesNotLockGroupRollupState(t *testing.T) {
|
||||
setUsageCleanupRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := &usageCleanupRepository{sql: db}
|
||||
|
||||
start := time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC)
|
||||
end := start.Add(24 * time.Hour)
|
||||
firstDeletedAt := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC)
|
||||
secondDeletedAt := firstDeletedAt.Add(time.Hour)
|
||||
filters := service.UsageCleanupFilters{StartTime: start, EndTime: end}
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectQuery(`(?s)DELETE FROM usage_logs.*RETURNING created_at`).
|
||||
mock.ExpectQuery(`(?s)WITH target AS.*DELETE FROM usage_logs.*RETURNING created_at`).
|
||||
WithArgs(start, end, 2).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"created_at"}).
|
||||
AddRow(firstDeletedAt).
|
||||
AddRow(secondDeletedAt))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs(firstDeletedAt, "Asia/Shanghai").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
AddRow(start.Add(3 * time.Hour)).
|
||||
AddRow(start.Add(4 * time.Hour)))
|
||||
|
||||
deleted, err := repo.DeleteUsageLogsBatch(context.Background(), filters, 2)
|
||||
require.NoError(t, err)
|
||||
@@ -465,32 +451,6 @@ func TestUsageCleanupRepositoryDeleteUsageLogsBatchAtomicallyInvalidatesGroupRol
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestUsageCleanupRepositoryDeleteUsageLogsBatchRollsBackWhenInvalidationFails(t *testing.T) {
|
||||
setUsageCleanupRollupTestTimezone(t)
|
||||
db, mock := newSQLMock(t)
|
||||
repo := &usageCleanupRepository{sql: db}
|
||||
|
||||
start := time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC)
|
||||
end := start.Add(24 * time.Hour)
|
||||
deletedAt := time.Date(2026, 8, 1, 3, 0, 0, 0, time.UTC)
|
||||
filters := service.UsageCleanupFilters{StartTime: start, EndTime: end}
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectQuery(`(?s)DELETE FROM usage_logs.*RETURNING created_at`).
|
||||
WithArgs(start, end, 1).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"created_at"}).AddRow(deletedAt))
|
||||
mock.ExpectExec(`UPDATE usage_group_rollup_state`).
|
||||
WithArgs(deletedAt, "Asia/Shanghai").
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
mock.ExpectRollback()
|
||||
|
||||
_, err := repo.DeleteUsageLogsBatch(context.Background(), filters, 1)
|
||||
require.ErrorIs(t, err, sql.ErrConnDone)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestUsageCleanupRepositoryDeleteUsageLogsBatchQueryError(t *testing.T) {
|
||||
db, mock := newSQLMock(t)
|
||||
repo := &usageCleanupRepository{sql: db}
|
||||
@@ -499,13 +459,9 @@ func TestUsageCleanupRepositoryDeleteUsageLogsBatchQueryError(t *testing.T) {
|
||||
end := start.Add(24 * time.Hour)
|
||||
filters := service.UsageCleanupFilters{StartTime: start, EndTime: end}
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`SELECT id FROM usage_group_rollup_state.*FOR UPDATE`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectQuery("DELETE FROM usage_logs").
|
||||
WithArgs(start, end, 5).
|
||||
WillReturnError(sql.ErrConnDone)
|
||||
mock.ExpectRollback()
|
||||
|
||||
_, err := repo.DeleteUsageLogsBatch(context.Background(), filters, 5)
|
||||
require.Error(t, err)
|
||||
|
||||
@@ -20,8 +20,8 @@ func TestUsageLogRepositoryGetAllGroupUsageSummaryUsesRollupTail(t *testing.T) {
|
||||
|
||||
// 水位有效:closed_before = 2026-03-07(≤ today),时区与配置一致。
|
||||
mock.ExpectQuery(`(?s)COUNT\(\*\).*usage_group_rollup_state.*WHERE id = 1`).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow(1, "2026-03-07", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "America/New_York"))
|
||||
WillReturnRows(sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}).
|
||||
AddRow(1, "2026-03-07", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "America/New_York", time.Unix(0, 0).UTC()))
|
||||
|
||||
// 尾段起点必须以参数形式进 WHERE —— 这正是把 usage_logs 全表扫换回
|
||||
// idx_usage_logs_created_at 索引扫的那一步。
|
||||
@@ -61,18 +61,18 @@ func TestUsageLogRepositoryGetAllGroupUsageSummaryFallsBackWhenWatermarkInvalid(
|
||||
}{
|
||||
{
|
||||
name: "水位行缺失",
|
||||
rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow(0, nil, nil, nil),
|
||||
rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}).
|
||||
AddRow(0, nil, nil, nil, nil),
|
||||
},
|
||||
{
|
||||
name: "时区与当前配置不一致",
|
||||
rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow(1, "2026-03-07", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "Asia/Shanghai"),
|
||||
rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}).
|
||||
AddRow(1, "2026-03-07", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "Asia/Shanghai", time.Unix(0, 0).UTC()),
|
||||
},
|
||||
{
|
||||
name: "水位位于未来",
|
||||
rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name"}).
|
||||
AddRow(1, "2026-03-10", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "America/New_York"),
|
||||
rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}).
|
||||
AddRow(1, "2026-03-10", time.Date(2026, 2, 1, 5, 0, 0, 0, time.UTC), "America/New_York", time.Unix(0, 0).UTC()),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -94,3 +94,66 @@ func TestUsageLogRepositoryGetAllGroupUsageSummaryFallsBackWhenWatermarkInvalid(
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 尾段不早于保留下界:水位落后于保留下界时(例如清理已推进下界而重建尚未完成),
|
||||
// 尚未删除的过期记录也不计入。
|
||||
func TestUsageLogRepositoryGetAllGroupUsageSummaryTailStartsAtExpiredBefore(t *testing.T) {
|
||||
todayStart := time.Date(2026, 3, 9, 4, 0, 0, 0, time.UTC)
|
||||
yesterdayStart := time.Date(2026, 3, 8, 5, 0, 0, 0, time.UTC)
|
||||
expiredBefore := time.Date(2026, 2, 10, 5, 0, 0, 0, time.UTC)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
rows *sqlmock.Rows
|
||||
valid bool
|
||||
retained string
|
||||
closed string
|
||||
tailStart time.Time
|
||||
}{
|
||||
{
|
||||
name: "水位有效但早于保留下界",
|
||||
rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}).
|
||||
AddRow(1, "2026-02-01", expiredBefore, "America/New_York", expiredBefore),
|
||||
valid: true,
|
||||
retained: "2026-02-10",
|
||||
closed: "2026-02-01",
|
||||
tailStart: expiredBefore,
|
||||
},
|
||||
{
|
||||
name: "retained_from 早于保留下界",
|
||||
rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}).
|
||||
AddRow(1, "2026-03-07", time.Date(2026, 1, 20, 5, 0, 0, 0, time.UTC), "America/New_York", expiredBefore),
|
||||
valid: true,
|
||||
retained: "2026-02-10",
|
||||
closed: "2026-03-07",
|
||||
tailStart: time.Date(2026, 3, 7, 5, 0, 0, 0, time.UTC),
|
||||
},
|
||||
{
|
||||
name: "水位无效",
|
||||
rows: sqlmock.NewRows([]string{"count", "closed_before", "retained_from", "timezone_name", "expired_before"}).
|
||||
AddRow(1, "2026-03-07", expiredBefore, "Asia/Shanghai", expiredBefore),
|
||||
valid: false,
|
||||
retained: "1970-01-01",
|
||||
closed: "1970-01-01",
|
||||
tailStart: expiredBefore,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newUsageLogRepositoryWithSQL(nil, db)
|
||||
useGroupUsageRepositoryTestTimezone(t, "America/New_York")
|
||||
|
||||
mock.ExpectQuery(`(?s)COUNT\(\*\).*MAX\(expired_before\).*usage_group_rollup_state.*WHERE id = 1`).
|
||||
WillReturnRows(tc.rows)
|
||||
mock.ExpectQuery(`(?s)usage_group_daily_rollups.*FROM usage_logs ul\s+WHERE ul\.created_at >= \$7`).
|
||||
WithArgs(todayStart, yesterdayStart, "2026-03-08", tc.valid, tc.retained, tc.closed, tc.tailStart).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"group_id", "total_cost", "today_cost", "yesterday_cost"}))
|
||||
|
||||
_, err := repo.GetAllGroupUsageSummary(context.Background(), todayStart)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1308,34 @@ func (s *UsageLogRepoSuite) TestGetAccountWindowStats() {
|
||||
s.Require().Equal(int64(70), stats.Tokens) // (10+20) + (15+25)
|
||||
}
|
||||
|
||||
func (s *UsageLogRepoSuite) TestActiveFiveHourResetExcludesPreviousWindowCost() {
|
||||
user := mustCreateUser(s.T(), s.client, &service.User{Email: "window-reset@test.com"})
|
||||
apiKey := mustCreateApiKey(s.T(), s.client, &service.APIKey{UserID: user.ID, Key: "sk-window-reset", Name: "k"})
|
||||
start := time.Now().UTC().Truncate(time.Second).Add(-30 * time.Minute)
|
||||
oldStart := start.Add(-5 * time.Hour)
|
||||
end := start.Add(5 * time.Hour)
|
||||
account := mustCreateAccount(s.T(), s.client, &service.Account{
|
||||
Name: "window-reset", Platform: service.PlatformAnthropic, Type: service.AccountTypeOAuth,
|
||||
SessionWindowStart: &oldStart, SessionWindowEnd: &start, SessionWindowStatus: "allowed",
|
||||
Extra: map[string]any{"window_cost_limit": 10.0, "window_cost_sticky_reserve": 1.0},
|
||||
})
|
||||
s.createUsageLog(user, apiKey, account, 10, 20, 20, start.Add(-time.Minute))
|
||||
s.createUsageLog(user, apiKey, account, 10, 20, 2, start.Add(time.Minute))
|
||||
accounts := newAccountRepositoryWithSQL(s.client, s.tx, nil)
|
||||
|
||||
// Active quota reads persist this reset before another model response can
|
||||
// supply session-window headers. Reload as the next scheduler/UI read does.
|
||||
s.Require().NoError(accounts.UpdateSessionWindowEnd(s.ctx, account.ID, end))
|
||||
reloaded, err := accounts.GetByID(s.ctx, account.ID)
|
||||
s.Require().NoError(err)
|
||||
stats, err := s.repo.GetAccountWindowStats(s.ctx, account.ID, reloaded.GetCurrentWindowStartTime())
|
||||
s.Require().NoError(err)
|
||||
s.Require().Equal(int64(1), stats.Requests, "the previous window's request must not count in the new window")
|
||||
s.Require().InDelta(2, stats.StandardCost, 0.000001)
|
||||
s.Require().Equal(service.WindowCostSchedulable, reloaded.CheckWindowCostSchedulability(stats.StandardCost))
|
||||
s.Require().Equal("allowed", reloaded.SessionWindowStatus)
|
||||
}
|
||||
|
||||
// --- GetUserUsageTrendByUserID ---
|
||||
|
||||
func (s *UsageLogRepoSuite) TestGetUserUsageTrendByUserID() {
|
||||
@@ -1449,16 +1477,18 @@ func (s *UsageLogRepoSuite) TestGetModelStatsWithFilters() {
|
||||
|
||||
base := time.Date(2025, 1, 15, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
accountRate := 0.4
|
||||
log1 := &service.UsageLog{
|
||||
UserID: user.ID,
|
||||
APIKeyID: apiKey.ID,
|
||||
AccountID: account.ID,
|
||||
Model: "claude-3-opus",
|
||||
InputTokens: 100,
|
||||
OutputTokens: 200,
|
||||
TotalCost: 0.5,
|
||||
ActualCost: 0.5,
|
||||
CreatedAt: base,
|
||||
UserID: user.ID,
|
||||
APIKeyID: apiKey.ID,
|
||||
AccountID: account.ID,
|
||||
Model: "claude-3-opus",
|
||||
InputTokens: 100,
|
||||
OutputTokens: 200,
|
||||
TotalCost: 0.5,
|
||||
ActualCost: 1.0,
|
||||
AccountRateMultiplier: &accountRate,
|
||||
CreatedAt: base,
|
||||
}
|
||||
_, err := s.repo.Create(s.ctx, log1)
|
||||
s.Require().NoError(err)
|
||||
@@ -1494,6 +1524,12 @@ func (s *UsageLogRepoSuite) TestGetModelStatsWithFilters() {
|
||||
stats, err = s.repo.GetModelStatsWithFilters(s.ctx, startTime, endTime, 0, 0, account.ID, 0, nil, nil, nil)
|
||||
s.Require().NoError(err, "GetModelStatsWithFilters account filter")
|
||||
s.Require().Len(stats, 2)
|
||||
for _, stat := range stats {
|
||||
if stat.Model == "claude-3-opus" {
|
||||
s.Require().InEpsilon(1.0, stat.ActualCost, 0.0001)
|
||||
s.Require().InEpsilon(0.2, stat.AccountCost, 0.0001)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- GetAccountUsageStats ---
|
||||
|
||||
@@ -1187,3 +1187,48 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) {
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func TestUsageLogRepositoryGetModelStatsAccountFilterKeepsActualCost(t *testing.T) {
|
||||
db, mock := newSQLMock(t)
|
||||
repo := &usageLogRepository{sql: db}
|
||||
|
||||
start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
end := start.Add(24 * time.Hour)
|
||||
accountID := int64(42)
|
||||
|
||||
mock.ExpectQuery("COALESCE\\(SUM\\(actual_cost\\), 0\\) as actual_cost,\\s+COALESCE\\(SUM\\(COALESCE\\(account_stats_cost, total_cost\\) \\* COALESCE\\(account_rate_multiplier, 1\\)\\), 0\\) as account_cost").
|
||||
WithArgs(start, end, accountID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{
|
||||
"model", "requests", "input_tokens", "output_tokens",
|
||||
"cache_creation_tokens", "cache_read_tokens", "total_tokens",
|
||||
"cost", "actual_cost", "account_cost",
|
||||
}).AddRow("gemini-4-argon", int64(3), int64(10), int64(20), int64(0), int64(0), int64(30), 6.0, 2.4, 0.9))
|
||||
|
||||
results, err := repo.GetModelStatsWithUsageFiltersBySource(context.Background(), start, end, usagestats.UsageLogFilters{AccountID: accountID}, usagestats.ModelSourceRequested)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, 1)
|
||||
require.Equal(t, 2.4, results[0].ActualCost)
|
||||
require.Equal(t, 0.9, results[0].AccountCost)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestUsageLogRepositoryGetEndpointStatsAccountFilterKeepsActualCost(t *testing.T) {
|
||||
db, mock := newSQLMock(t)
|
||||
repo := &usageLogRepository{sql: db}
|
||||
|
||||
start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
end := start.Add(24 * time.Hour)
|
||||
accountID := int64(42)
|
||||
|
||||
mock.ExpectQuery("COALESCE\\(SUM\\(actual_cost\\), 0\\) as actual_cost,\\s+COALESCE\\(SUM\\(COALESCE\\(account_stats_cost, total_cost\\) \\* COALESCE\\(account_rate_multiplier, 1\\)\\), 0\\) as account_cost").
|
||||
WithArgs(start, end, accountID).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"endpoint", "requests", "total_tokens", "cost", "actual_cost", "account_cost"}).
|
||||
AddRow("/v1beta/models", int64(3), int64(30), 6.0, 2.4, 0.9))
|
||||
|
||||
results, err := repo.GetEndpointStatsWithFilters(context.Background(), start, end, 0, 0, accountID, 0, "", nil, nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, 1)
|
||||
require.Equal(t, 2.4, results[0].ActualCost)
|
||||
require.Equal(t, 0.9, results[0].AccountCost)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
@@ -402,8 +402,8 @@ func (r *usageLogRepository) GetGeminiUsageTotalsBatch(ctx context.Context, acco
|
||||
COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN 0 ELSE 1 END), 0) AS pro_requests,
|
||||
COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN (input_tokens + output_tokens + cache_creation_tokens + cache_read_tokens) ELSE 0 END), 0) AS flash_tokens,
|
||||
COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN 0 ELSE (input_tokens + output_tokens + cache_creation_tokens + cache_read_tokens) END), 0) AS pro_tokens,
|
||||
COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN actual_cost ELSE 0 END), 0) AS flash_cost,
|
||||
COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN 0 ELSE actual_cost END), 0) AS pro_cost
|
||||
COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1) ELSE 0 END), 0) AS flash_cost,
|
||||
COALESCE(SUM(CASE WHEN LOWER(COALESCE(model, '')) LIKE '%flash%' OR LOWER(COALESCE(model, '')) LIKE '%lite%' THEN 0 ELSE COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1) END), 0) AS pro_cost
|
||||
FROM usage_logs
|
||||
WHERE account_id = ANY($1) AND created_at >= $2 AND created_at < $3
|
||||
GROUP BY account_id
|
||||
@@ -736,7 +736,6 @@ func (r *usageLogRepository) GetStatsWithFilters(ctx context.Context, filters Us
|
||||
|
||||
stats := &UsageStats{}
|
||||
var totalAccountCost float64
|
||||
useAccountCostForEndpoint := filters.AccountID > 0 && filters.UserID == 0 && filters.APIKeyID == 0
|
||||
rows, err := r.sql.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -769,10 +768,6 @@ func (r *usageLogRepository) GetStatsWithFilters(ctx context.Context, filters Us
|
||||
}
|
||||
|
||||
totalTokens := inputTokens + outputTokens + cacheCreationTokens + cacheReads
|
||||
endpointActualCost := actualCost
|
||||
if useAccountCostForEndpoint {
|
||||
endpointActualCost = accountCost
|
||||
}
|
||||
|
||||
switch {
|
||||
case inboundGrouped == 1 && upstreamGrouped == 1:
|
||||
@@ -789,17 +784,17 @@ func (r *usageLogRepository) GetStatsWithFilters(ctx context.Context, filters Us
|
||||
case inboundGrouped == 0 && upstreamGrouped == 1:
|
||||
stats.Endpoints = append(stats.Endpoints, EndpointStat{
|
||||
Endpoint: inboundEndpoint.String, Requests: requests, TotalTokens: totalTokens,
|
||||
Cost: cost, ActualCost: endpointActualCost,
|
||||
Cost: cost, ActualCost: actualCost, AccountCost: accountCost,
|
||||
})
|
||||
case inboundGrouped == 1 && upstreamGrouped == 0:
|
||||
stats.UpstreamEndpoints = append(stats.UpstreamEndpoints, EndpointStat{
|
||||
Endpoint: upstreamEndpoint.String, Requests: requests, TotalTokens: totalTokens,
|
||||
Cost: cost, ActualCost: endpointActualCost,
|
||||
Cost: cost, ActualCost: actualCost, AccountCost: accountCost,
|
||||
})
|
||||
case inboundGrouped == 0 && upstreamGrouped == 0:
|
||||
stats.EndpointPaths = append(stats.EndpointPaths, EndpointStat{
|
||||
Endpoint: inboundEndpoint.String + " -> " + upstreamEndpoint.String,
|
||||
Requests: requests, TotalTokens: totalTokens, Cost: cost, ActualCost: endpointActualCost,
|
||||
Requests: requests, TotalTokens: totalTokens, Cost: cost, ActualCost: actualCost, AccountCost: accountCost,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -838,21 +833,17 @@ type AccountUsageStatsResponse = usagestats.AccountUsageStatsResponse
|
||||
type EndpointStat = usagestats.EndpointStat
|
||||
|
||||
func (r *usageLogRepository) getEndpointStatsByColumnWithFilters(ctx context.Context, endpointColumn string, startTime, endTime time.Time, userID, apiKeyID, accountID, groupID int64, model string, modelSource string, requestType *int16, stream *bool, billingType *int8, billingMode string) (results []EndpointStat, err error) {
|
||||
actualCostExpr := "COALESCE(SUM(actual_cost), 0) as actual_cost"
|
||||
if accountID > 0 && userID == 0 && apiKeyID == 0 {
|
||||
actualCostExpr = "COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as actual_cost"
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
SELECT
|
||||
COALESCE(NULLIF(TRIM(%s), ''), 'unknown') AS endpoint,
|
||||
COUNT(*) AS requests,
|
||||
COALESCE(SUM(input_tokens + output_tokens + cache_creation_tokens + cache_read_tokens), 0) AS total_tokens,
|
||||
COALESCE(SUM(total_cost), 0) as cost,
|
||||
%s
|
||||
COALESCE(SUM(actual_cost), 0) as actual_cost,
|
||||
COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as account_cost
|
||||
FROM usage_logs
|
||||
WHERE created_at >= $1 AND created_at < $2
|
||||
`, endpointColumn, actualCostExpr)
|
||||
`, endpointColumn)
|
||||
|
||||
args := []any{startTime, endTime}
|
||||
if userID > 0 {
|
||||
@@ -894,7 +885,7 @@ func (r *usageLogRepository) getEndpointStatsByColumnWithFilters(ctx context.Con
|
||||
results = make([]EndpointStat, 0)
|
||||
for rows.Next() {
|
||||
var row EndpointStat
|
||||
if err := rows.Scan(&row.Endpoint, &row.Requests, &row.TotalTokens, &row.Cost, &row.ActualCost); err != nil {
|
||||
if err := rows.Scan(&row.Endpoint, &row.Requests, &row.TotalTokens, &row.Cost, &row.ActualCost, &row.AccountCost); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
results = append(results, row)
|
||||
|
||||
@@ -449,12 +449,6 @@ func (r *usageLogRepository) GetModelStatsWithUsageFiltersBySource(ctx context.C
|
||||
}
|
||||
|
||||
func (r *usageLogRepository) getModelStatsWithFiltersBySource(ctx context.Context, startTime, endTime time.Time, userID, apiKeyID, accountID, groupID int64, model string, requestType *int16, stream *bool, billingType *int8, source string, billingMode string, upstreamModelMismatch *bool, nativeCompactionV2 *bool) (results []ModelStat, err error) {
|
||||
actualCostExpr := "COALESCE(SUM(actual_cost), 0) as actual_cost"
|
||||
// 当仅按 account_id 聚合时,实际费用使用账号倍率(total_cost * account_rate_multiplier)。
|
||||
if accountID > 0 && userID == 0 && apiKeyID == 0 {
|
||||
actualCostExpr = "COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as actual_cost"
|
||||
}
|
||||
accountCostExpr := "COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as account_cost"
|
||||
modelExpr := resolveModelDimensionExpression(source)
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
@@ -467,11 +461,11 @@ func (r *usageLogRepository) getModelStatsWithFiltersBySource(ctx context.Contex
|
||||
COALESCE(SUM(cache_read_tokens), 0) as cache_read_tokens,
|
||||
COALESCE(SUM(input_tokens + output_tokens + cache_creation_tokens + cache_read_tokens), 0) as total_tokens,
|
||||
COALESCE(SUM(total_cost), 0) as cost,
|
||||
%s,
|
||||
%s
|
||||
COALESCE(SUM(actual_cost), 0) as actual_cost,
|
||||
COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as account_cost
|
||||
FROM usage_logs
|
||||
WHERE created_at >= $1 AND created_at < $2
|
||||
`, modelExpr, actualCostExpr, accountCostExpr)
|
||||
`, modelExpr)
|
||||
|
||||
args := []any{startTime, endTime}
|
||||
if userID > 0 {
|
||||
|
||||
@@ -3,6 +3,7 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
@@ -11,11 +12,55 @@ import (
|
||||
|
||||
type userGroupRateRepository struct {
|
||||
sql sqlExecutor
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
// NewUserGroupRateRepository 创建用户专属分组倍率/RPM 仓储
|
||||
func NewUserGroupRateRepository(sqlDB *sql.DB) service.UserGroupRateRepository {
|
||||
return &userGroupRateRepository{sql: sqlDB}
|
||||
return &userGroupRateRepository{sql: sqlDB, db: sqlDB}
|
||||
}
|
||||
|
||||
func (r *userGroupRateRepository) beginTx(ctx context.Context) (*sql.Tx, error) {
|
||||
if r == nil || r.db == nil {
|
||||
return nil, fmt.Errorf("user group rate repository: database handle is not configured")
|
||||
}
|
||||
return r.db.BeginTx(ctx, nil)
|
||||
}
|
||||
|
||||
// dedupeGroupRateMultiplierEntries 按 user_id 去重,保留最后一次出现的值。
|
||||
// ON CONFLICT DO UPDATE 对同一行出现两次会直接报错,去重后才能安全写入。
|
||||
func dedupeGroupRateMultiplierEntries(entries []service.GroupRateMultiplierInput) []service.GroupRateMultiplierInput {
|
||||
if len(entries) < 2 {
|
||||
return entries
|
||||
}
|
||||
index := make(map[int64]int, len(entries))
|
||||
out := make([]service.GroupRateMultiplierInput, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if pos, ok := index[entry.UserID]; ok {
|
||||
out[pos] = entry
|
||||
continue
|
||||
}
|
||||
index[entry.UserID] = len(out)
|
||||
out = append(out, entry)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func dedupeGroupRPMOverrideEntries(entries []service.GroupRPMOverrideInput) []service.GroupRPMOverrideInput {
|
||||
if len(entries) < 2 {
|
||||
return entries
|
||||
}
|
||||
index := make(map[int64]int, len(entries))
|
||||
out := make([]service.GroupRPMOverrideInput, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if pos, ok := index[entry.UserID]; ok {
|
||||
out[pos] = entry
|
||||
continue
|
||||
}
|
||||
index[entry.UserID] = len(out)
|
||||
out = append(out, entry)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// GetByUserID 获取用户所有专属分组 rate_multiplier(仅返回非 NULL 的条目)
|
||||
@@ -244,14 +289,22 @@ func (r *userGroupRateRepository) SyncUserGroupRates(ctx context.Context, userID
|
||||
// - 未出现在 entries 中的用户行:rate_multiplier 归 NULL;若 rpm_override 也为 NULL 则整行删除。
|
||||
// - 出现的用户行:upsert rate_multiplier。
|
||||
func (r *userGroupRateRepository) SyncGroupRateMultipliers(ctx context.Context, groupID int64, entries []service.GroupRateMultiplierInput) error {
|
||||
entries = dedupeGroupRateMultiplierEntries(entries)
|
||||
|
||||
keepUserIDs := make([]int64, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
keepUserIDs = append(keepUserIDs, e.UserID)
|
||||
}
|
||||
|
||||
tx, err := r.beginTx(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
// 未在 entries 列表中的行:清空 rate_multiplier。
|
||||
if len(keepUserIDs) == 0 {
|
||||
if _, err := r.sql.ExecContext(ctx, `
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE user_group_rate_multipliers
|
||||
SET rate_multiplier = NULL, updated_at = NOW()
|
||||
WHERE group_id = $1
|
||||
@@ -259,7 +312,7 @@ func (r *userGroupRateRepository) SyncGroupRateMultipliers(ctx context.Context,
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if _, err := r.sql.ExecContext(ctx, `
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE user_group_rate_multipliers
|
||||
SET rate_multiplier = NULL, updated_at = NOW()
|
||||
WHERE group_id = $1 AND user_id <> ALL($2)
|
||||
@@ -269,32 +322,33 @@ func (r *userGroupRateRepository) SyncGroupRateMultipliers(ctx context.Context,
|
||||
}
|
||||
|
||||
// 清空后若整行 NULL 则删除。
|
||||
if _, err := r.sql.ExecContext(ctx, `
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM user_group_rate_multipliers
|
||||
WHERE group_id = $1 AND rate_multiplier IS NULL AND rpm_override IS NULL
|
||||
`, groupID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(entries) == 0 {
|
||||
return nil
|
||||
if len(entries) > 0 {
|
||||
userIDs := make([]int64, len(entries))
|
||||
rates := make([]float64, len(entries))
|
||||
for i, e := range entries {
|
||||
userIDs[i] = e.UserID
|
||||
rates[i] = e.RateMultiplier
|
||||
}
|
||||
now := time.Now()
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO user_group_rate_multipliers (user_id, group_id, rate_multiplier, created_at, updated_at)
|
||||
SELECT data.user_id, $1::bigint, data.rate_multiplier, $2::timestamptz, $2::timestamptz
|
||||
FROM unnest($3::bigint[], $4::double precision[]) AS data(user_id, rate_multiplier)
|
||||
ON CONFLICT (user_id, group_id)
|
||||
DO UPDATE SET rate_multiplier = EXCLUDED.rate_multiplier, updated_at = EXCLUDED.updated_at
|
||||
`, groupID, now, pq.Array(userIDs), pq.Array(rates)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
userIDs := make([]int64, len(entries))
|
||||
rates := make([]float64, len(entries))
|
||||
for i, e := range entries {
|
||||
userIDs[i] = e.UserID
|
||||
rates[i] = e.RateMultiplier
|
||||
}
|
||||
now := time.Now()
|
||||
_, err := r.sql.ExecContext(ctx, `
|
||||
INSERT INTO user_group_rate_multipliers (user_id, group_id, rate_multiplier, created_at, updated_at)
|
||||
SELECT data.user_id, $1::bigint, data.rate_multiplier, $2::timestamptz, $2::timestamptz
|
||||
FROM unnest($3::bigint[], $4::double precision[]) AS data(user_id, rate_multiplier)
|
||||
ON CONFLICT (user_id, group_id)
|
||||
DO UPDATE SET rate_multiplier = EXCLUDED.rate_multiplier, updated_at = EXCLUDED.updated_at
|
||||
`, groupID, now, pq.Array(userIDs), pq.Array(rates))
|
||||
return err
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// SyncGroupRPMOverrides 同步分组的 rpm_override 部分(不触动 rate_multiplier)。
|
||||
@@ -302,6 +356,8 @@ func (r *userGroupRateRepository) SyncGroupRateMultipliers(ctx context.Context,
|
||||
// - 未出现的用户行:rpm_override 归 NULL;若 rate_multiplier 也为 NULL 则整行删除。
|
||||
// - 出现的用户行:若 RPMOverride 为 nil 则清空;非 nil 则 upsert。
|
||||
func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, groupID int64, entries []service.GroupRPMOverrideInput) error {
|
||||
entries = dedupeGroupRPMOverrideEntries(entries)
|
||||
|
||||
keepUserIDs := make([]int64, 0, len(entries))
|
||||
var clearUserIDs []int64
|
||||
upsertUserIDs := make([]int64, 0, len(entries))
|
||||
@@ -316,9 +372,15 @@ func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, gro
|
||||
}
|
||||
}
|
||||
|
||||
tx, err := r.beginTx(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
// 未在 entries 列表中的行:清空 rpm_override。
|
||||
if len(keepUserIDs) == 0 {
|
||||
if _, err := r.sql.ExecContext(ctx, `
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE user_group_rate_multipliers
|
||||
SET rpm_override = NULL, updated_at = NOW()
|
||||
WHERE group_id = $1
|
||||
@@ -326,7 +388,7 @@ func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, gro
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if _, err := r.sql.ExecContext(ctx, `
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE user_group_rate_multipliers
|
||||
SET rpm_override = NULL, updated_at = NOW()
|
||||
WHERE group_id = $1 AND user_id <> ALL($2)
|
||||
@@ -337,7 +399,7 @@ func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, gro
|
||||
|
||||
// 显式 clear 的行。
|
||||
if len(clearUserIDs) > 0 {
|
||||
if _, err := r.sql.ExecContext(ctx, `
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE user_group_rate_multipliers
|
||||
SET rpm_override = NULL, updated_at = NOW()
|
||||
WHERE group_id = $1 AND user_id = ANY($2)
|
||||
@@ -347,7 +409,7 @@ func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, gro
|
||||
}
|
||||
|
||||
// 清空后若整行 NULL 则删除。
|
||||
if _, err := r.sql.ExecContext(ctx, `
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM user_group_rate_multipliers
|
||||
WHERE group_id = $1 AND rate_multiplier IS NULL AND rpm_override IS NULL
|
||||
`, groupID); err != nil {
|
||||
@@ -356,19 +418,18 @@ func (r *userGroupRateRepository) SyncGroupRPMOverrides(ctx context.Context, gro
|
||||
|
||||
if len(upsertUserIDs) > 0 {
|
||||
now := time.Now()
|
||||
_, err := r.sql.ExecContext(ctx, `
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO user_group_rate_multipliers (user_id, group_id, rpm_override, created_at, updated_at)
|
||||
SELECT data.user_id, $1::bigint, data.rpm_override, $2::timestamptz, $2::timestamptz
|
||||
FROM unnest($3::bigint[], $4::integer[]) AS data(user_id, rpm_override)
|
||||
ON CONFLICT (user_id, group_id)
|
||||
DO UPDATE SET rpm_override = EXCLUDED.rpm_override, updated_at = EXCLUDED.updated_at
|
||||
`, groupID, now, pq.Array(upsertUserIDs), pq.Array(upsertValues))
|
||||
if err != nil {
|
||||
`, groupID, now, pq.Array(upsertUserIDs), pq.Array(upsertValues)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// ClearGroupRPMOverrides 清空指定分组所有行的 rpm_override。
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSyncGroupRateMultipliersCommitsInOneTransaction(t *testing.T) {
|
||||
db, mock, err := sqlmock.New()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
repo := NewUserGroupRateRepository(db)
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE user_group_rate_multipliers").
|
||||
WithArgs(int64(10), sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec("DELETE FROM user_group_rate_multipliers").
|
||||
WithArgs(int64(10)).
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectExec("INSERT INTO user_group_rate_multipliers").
|
||||
WithArgs(int64(10), sqlmock.AnyArg(), sqlmock.AnyArg(), sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
|
||||
err = repo.SyncGroupRateMultipliers(context.Background(), 10, []service.GroupRateMultiplierInput{
|
||||
{UserID: 1, RateMultiplier: 1.5},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestSyncGroupRateMultipliersRollsBackOnInsertFailure(t *testing.T) {
|
||||
db, mock, err := sqlmock.New()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
repo := NewUserGroupRateRepository(db)
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE user_group_rate_multipliers").
|
||||
WithArgs(int64(10), sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 2))
|
||||
mock.ExpectExec("DELETE FROM user_group_rate_multipliers").
|
||||
WithArgs(int64(10)).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec("INSERT INTO user_group_rate_multipliers").
|
||||
WithArgs(int64(10), sqlmock.AnyArg(), sqlmock.AnyArg(), sqlmock.AnyArg()).
|
||||
WillReturnError(errors.New("insert failed"))
|
||||
mock.ExpectRollback()
|
||||
|
||||
err = repo.SyncGroupRateMultipliers(context.Background(), 10, []service.GroupRateMultiplierInput{
|
||||
{UserID: 1, RateMultiplier: 1.5},
|
||||
})
|
||||
require.ErrorContains(t, err, "insert failed")
|
||||
require.NoError(t, mock.ExpectationsWereMet(), "the destructive UPDATE/DELETE must be rolled back")
|
||||
}
|
||||
|
||||
func TestSyncGroupRPMOverridesCommitsInOneTransaction(t *testing.T) {
|
||||
db, mock, err := sqlmock.New()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
repo := NewUserGroupRateRepository(db)
|
||||
|
||||
override := 5
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE user_group_rate_multipliers").
|
||||
WithArgs(int64(10), sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec("DELETE FROM user_group_rate_multipliers").
|
||||
WithArgs(int64(10)).
|
||||
WillReturnResult(sqlmock.NewResult(0, 0))
|
||||
mock.ExpectExec("INSERT INTO user_group_rate_multipliers").
|
||||
WithArgs(int64(10), sqlmock.AnyArg(), sqlmock.AnyArg(), sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectCommit()
|
||||
|
||||
err = repo.SyncGroupRPMOverrides(context.Background(), 10, []service.GroupRPMOverrideInput{
|
||||
{UserID: 1, RPMOverride: &override},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestSyncGroupRPMOverridesRollsBackOnInsertFailure(t *testing.T) {
|
||||
db, mock, err := sqlmock.New()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
repo := NewUserGroupRateRepository(db)
|
||||
|
||||
override := 5
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE user_group_rate_multipliers").
|
||||
WithArgs(int64(10), sqlmock.AnyArg()).
|
||||
WillReturnResult(sqlmock.NewResult(0, 2))
|
||||
mock.ExpectExec("DELETE FROM user_group_rate_multipliers").
|
||||
WithArgs(int64(10)).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec("INSERT INTO user_group_rate_multipliers").
|
||||
WithArgs(int64(10), sqlmock.AnyArg(), sqlmock.AnyArg(), sqlmock.AnyArg()).
|
||||
WillReturnError(errors.New("insert failed"))
|
||||
mock.ExpectRollback()
|
||||
|
||||
err = repo.SyncGroupRPMOverrides(context.Background(), 10, []service.GroupRPMOverrideInput{
|
||||
{UserID: 1, RPMOverride: &override},
|
||||
})
|
||||
require.ErrorContains(t, err, "insert failed")
|
||||
require.NoError(t, mock.ExpectationsWereMet(), "the destructive UPDATE/DELETE must be rolled back")
|
||||
}
|
||||
|
||||
func TestDedupeGroupRateMultiplierEntriesKeepsLastValue(t *testing.T) {
|
||||
got := dedupeGroupRateMultiplierEntries([]service.GroupRateMultiplierInput{
|
||||
{UserID: 1, RateMultiplier: 1},
|
||||
{UserID: 2, RateMultiplier: 2},
|
||||
{UserID: 1, RateMultiplier: 3},
|
||||
})
|
||||
require.Equal(t, []service.GroupRateMultiplierInput{
|
||||
{UserID: 1, RateMultiplier: 3},
|
||||
{UserID: 2, RateMultiplier: 2},
|
||||
}, got)
|
||||
}
|
||||
|
||||
func TestDedupeGroupRPMOverrideEntriesKeepsLastValue(t *testing.T) {
|
||||
five := 5
|
||||
got := dedupeGroupRPMOverrideEntries([]service.GroupRPMOverrideInput{
|
||||
{UserID: 1},
|
||||
{UserID: 2, RPMOverride: &five},
|
||||
{UserID: 1, RPMOverride: &five},
|
||||
})
|
||||
require.Len(t, got, 2)
|
||||
require.Equal(t, int64(1), got[0].UserID)
|
||||
require.Equal(t, &five, got[0].RPMOverride)
|
||||
require.Equal(t, int64(2), got[1].UserID)
|
||||
}
|
||||
@@ -2047,6 +2047,10 @@ func (s *stubAccountRepo) ClearModelRateLimits(ctx context.Context, id int64) er
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (s *stubAccountRepo) ClearModelRateLimit(ctx context.Context, id int64, scope string) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (s *stubAccountRepo) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
@@ -2415,10 +2415,8 @@ const (
|
||||
// 三态:default(跟随渠道)/ enabled(强制开启)/ disabled(强制关闭)。
|
||||
// 兼容旧 bool 值:true→enabled, false→default(并记录 debug 日志)。
|
||||
func (a *Account) GetWebSearchEmulationMode() string {
|
||||
// OpenAI API Key accounts reach this via /v1/messages; their upstreams
|
||||
// (DeepSeek etc. over Chat Completions) have no web_search tool.
|
||||
if a == nil || a.Type != AccountTypeAPIKey || a.Extra == nil ||
|
||||
(a.Platform != PlatformAnthropic && a.Platform != PlatformOpenAI) {
|
||||
!webSearchEmulationPlatformEnabled(a.Platform) {
|
||||
return WebSearchModeDefault
|
||||
}
|
||||
raw := a.Extra[featureKeyWebSearchEmulation]
|
||||
@@ -2442,6 +2440,17 @@ func (a *Account) GetWebSearchEmulationMode() string {
|
||||
}
|
||||
}
|
||||
|
||||
// webSearchEmulationPlatformEnabled reports whether API key accounts of the
|
||||
// platform can set the account-level web search emulation mode. Keep it in sync
|
||||
// with WEB_SEARCH_EMULATION_PLATFORMS in frontend/src/views/admin/ChannelsView.vue.
|
||||
func webSearchEmulationPlatformEnabled(platform string) bool {
|
||||
switch platform {
|
||||
case PlatformAnthropic, PlatformOpenAI, PlatformZhipu, PlatformCommandCode, PlatformOpenCodeGo, PlatformMiniMax:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsCodexCLIOnlyEnabled 返回 OpenAI OAuth 账号是否启用"仅允许 Codex 官方客户端"。
|
||||
// 字段:accounts.extra.codex_cli_only。
|
||||
// 字段缺失或类型不正确时,按 false(关闭)处理。
|
||||
|
||||
@@ -375,9 +375,15 @@ func cnProviderThresholdCandidates(account *Account, provider string) []*account
|
||||
return candidates
|
||||
}
|
||||
|
||||
// cnQuotaHasMonthlyWindow 报告供应商的额度快照是否含月度窗口(OpenCode Go、Command Code)。
|
||||
// cnQuotaHasMonthlyWindow 报告供应商的额度快照是否含月度窗口(OpenCode Go、
|
||||
// Command Code 与 Kimi 新套餐)。
|
||||
func cnQuotaHasMonthlyWindow(provider string) bool {
|
||||
return provider == PlatformOpenCodeGo || provider == PlatformCommandCode
|
||||
switch provider {
|
||||
case PlatformOpenCodeGo, PlatformCommandCode, PlatformKimi:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func cnThresholdCandidate(extra map[string]any, provider, window string) *accountSchedulingThresholdCandidate {
|
||||
|
||||
@@ -94,8 +94,8 @@ type AccountRepository interface {
|
||||
ListSchedulableUngroupedByPlatforms(ctx context.Context, platforms []string) ([]Account, error)
|
||||
// ListModelAvailabilityCandidates returns accounts that are enabled by
|
||||
// persistent configuration (active + schedulable) for model-support
|
||||
// diagnosis. It deliberately does not filter transient runtime state such
|
||||
// as rate-limit, overload, temporary-unschedulable, or expiry windows.
|
||||
// diagnosis and scheduler snapshot membership. It deliberately does not
|
||||
// filter rate-limit, overload, temporary-unschedulable, or expiry windows.
|
||||
// When groupID is nil, includeGrouped controls whether the query scans all
|
||||
// matching accounts or only accounts without a group binding.
|
||||
ListModelAvailabilityCandidates(ctx context.Context, groupID *int64, platforms []string, includeGrouped bool) ([]Account, error)
|
||||
@@ -108,6 +108,9 @@ type AccountRepository interface {
|
||||
ClearRateLimit(ctx context.Context, id int64) error
|
||||
ClearAntigravityQuotaScopes(ctx context.Context, id int64) error
|
||||
ClearModelRateLimits(ctx context.Context, id int64) error
|
||||
// ClearModelRateLimit 只清除指定 scope 的模型级限流,用于单个模型窗口恢复后
|
||||
// 定向解封,不影响其他模型与并发生效的限流。
|
||||
ClearModelRateLimit(ctx context.Context, id int64, scope string) error
|
||||
UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error
|
||||
// UpdateSessionWindowEnd 仅更新 5h 窗口的结束时间,不动 start / status。
|
||||
// 用于 active poll 拿到新 ResetsAt 后回写,避免覆盖请求路径上记录的 status。
|
||||
|
||||
@@ -195,6 +195,10 @@ func (s *accountRepoStub) ClearModelRateLimits(ctx context.Context, id int64) er
|
||||
panic("unexpected ClearModelRateLimits call")
|
||||
}
|
||||
|
||||
func (s *accountRepoStub) ClearModelRateLimit(ctx context.Context, id int64, scope string) error {
|
||||
panic("unexpected ClearModelRateLimit call")
|
||||
}
|
||||
|
||||
func (s *accountRepoStub) UpdateSessionWindow(ctx context.Context, id int64, start, end *time.Time, status string) error {
|
||||
panic("unexpected UpdateSessionWindow call")
|
||||
}
|
||||
|
||||
@@ -287,8 +287,20 @@ type ClaudeUsageResponse struct {
|
||||
} `json:"seven_day_sonnet"`
|
||||
// Fable 专属 7d 窗口(对应响应头 7d_oi,claim 名为 seven_day_overage_included,
|
||||
// 见 anthropic-ratelimit-unified-representative-claim 头)。上游 usage API
|
||||
// 若不下发该字段,GetUsage 会用被动采样数据回填。
|
||||
// 若不下发该字段,先读取 limits[],仍缺失时 GetUsage 用被动采样回填。
|
||||
SevenDayOverageIncluded ClaudeUsageWindow `json:"seven_day_overage_included"`
|
||||
Limits []struct {
|
||||
Kind string `json:"kind"`
|
||||
Group string `json:"group"`
|
||||
Percent *float64 `json:"percent"`
|
||||
ResetsAt string `json:"resets_at"`
|
||||
Scope struct {
|
||||
Model struct {
|
||||
DisplayName string `json:"display_name"`
|
||||
} `json:"model"`
|
||||
Surface json.RawMessage `json:"surface"`
|
||||
} `json:"scope"`
|
||||
} `json:"limits"`
|
||||
}
|
||||
|
||||
// ClaudeUsageFetchOptions 包含获取 Claude 用量数据所需的所有选项
|
||||
@@ -483,8 +495,9 @@ func (s *AccountUsageService) getUsageForAccount(ctx context.Context, account *A
|
||||
// 4. 添加窗口统计(有独立缓存,1 分钟)
|
||||
s.addWindowStats(ctx, account, usage)
|
||||
|
||||
// 5. 将主动查询结果同步到被动缓存,下次 passive 加载即为最新值
|
||||
s.syncActiveToPassive(ctx, account.ID, usage)
|
||||
// 5. 将主动查询结果同步到被动缓存,下次 passive 加载即为最新值;
|
||||
// 其中还会在上游明确给出已回落的 7d_oi 用量时撤销窗口耗尽写入的模型级限流。
|
||||
s.syncActiveToPassive(ctx, account, usage)
|
||||
|
||||
// 6. 上游 usage API 目前不一定下发 Fable 7d 窗口;缺失时回填被动采样
|
||||
// (7d_oi 响应头)的数据,避免主动查询后 7d F 进度条丢失。
|
||||
@@ -715,7 +728,15 @@ func buildPassiveUsageWindow(extra map[string]any, utilKey, resetKey string) *Us
|
||||
|
||||
// syncActiveToPassive 将主动查询的最新数据回写到 Extra 被动缓存,
|
||||
// 这样下次被动加载时能看到最新值。
|
||||
func (s *AccountUsageService) syncActiveToPassive(ctx context.Context, accountID int64, usage *UsageInfo) {
|
||||
//
|
||||
// 主动查询是“重置卡生效后额度已恢复”最直接的观测点:这里在拿到 API 明确回报的
|
||||
// 7d_oi 用量后,顺手撤销窗口耗尽写入的模型级限流。回填被动采样发生在调用方,
|
||||
// 因此本函数的 usage.SevenDayFable 一定是上游返回值,不会把旧采样当成恢复依据。
|
||||
func (s *AccountUsageService) syncActiveToPassive(ctx context.Context, account *Account, usage *UsageInfo) {
|
||||
if account == nil {
|
||||
return
|
||||
}
|
||||
accountID := account.ID
|
||||
extraUpdates := make(map[string]any, 4)
|
||||
|
||||
if usage.FiveHour != nil {
|
||||
@@ -748,6 +769,10 @@ func (s *AccountUsageService) syncActiveToPassive(ctx context.Context, accountID
|
||||
slog.Warn("sync_active_to_passive_session_window_end_failed", "account_id", accountID, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
if usage.SevenDayFable != nil {
|
||||
recoverAnthropicFableWindowLimit(ctx, s.accountRepo, account, usage.SevenDayFable.Utilization/100)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AccountUsageService) getOpenAIUsage(ctx context.Context, account *Account, force bool) (*UsageInfo, error) {
|
||||
@@ -1773,7 +1798,26 @@ func (s *AccountUsageService) buildUsageInfo(resp *ClaudeUsageResponse, updatedA
|
||||
}
|
||||
|
||||
// 7天Fable窗口(响应头 7d_oi 对应的窗口)
|
||||
if fable := resp.SevenDayOverageIncluded; fable.ResetsAt != "" {
|
||||
fable := resp.SevenDayOverageIncluded
|
||||
if fable.ResetsAt == "" {
|
||||
// 新版 usage 将模型周窗口放在 limits[]。仅投影无 surface 限定的
|
||||
// Fable 周额度;percent 已是百分比,显式 0 也必须覆盖旧被动采样。
|
||||
for _, limit := range resp.Limits {
|
||||
if limit.Kind != "weekly_scoped" || limit.Group != "weekly" ||
|
||||
limit.Scope.Model.DisplayName != "Fable" || limit.Percent == nil || *limit.Percent < 0 {
|
||||
continue
|
||||
}
|
||||
if surface := bytes.TrimSpace(limit.Scope.Surface); len(surface) > 0 && !bytes.Equal(surface, []byte("null")) {
|
||||
continue
|
||||
}
|
||||
if _, err := parseTime(limit.ResetsAt); err != nil {
|
||||
continue
|
||||
}
|
||||
fable = ClaudeUsageWindow{Utilization: *limit.Percent, ResetsAt: limit.ResetsAt}
|
||||
break
|
||||
}
|
||||
}
|
||||
if fable.ResetsAt != "" {
|
||||
if fableReset, err := parseTime(fable.ResetsAt); err == nil {
|
||||
info.SevenDayFable = &UsageProgress{
|
||||
Utilization: fable.Utilization,
|
||||
|
||||
@@ -2,6 +2,8 @@ package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -56,6 +58,61 @@ func TestBuildUsageInfo_SevenDayFable(t *testing.T) {
|
||||
require.Nil(t, info.SevenDayFable)
|
||||
}
|
||||
|
||||
func TestBuildUsageInfo_ScopedFableLimits(t *testing.T) {
|
||||
resetAt := time.Now().Add(72 * time.Hour).In(time.FixedZone("UTC+8", 8*60*60)).Truncate(time.Microsecond)
|
||||
entry := fmt.Sprintf(`{"kind":"weekly_scoped","group":"weekly","percent":5.25,"resets_at":%q,"scope":{"model":{"display_name":"Fable"},"surface":null},"is_active":false}`, resetAt.Format(time.RFC3339Nano))
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
limits string
|
||||
legacy string
|
||||
wantWindow bool
|
||||
wantUsage float64
|
||||
}{
|
||||
{name: "inactive scoped window", limits: entry, wantWindow: true, wantUsage: 5.25},
|
||||
{name: "active scoped window", limits: strings.Replace(entry, `"is_active":false`, `"is_active":true`, 1), wantWindow: true, wantUsage: 5.25},
|
||||
{name: "omitted surface", limits: strings.Replace(entry, `,"surface":null`, ``, 1), wantWindow: true, wantUsage: 5.25},
|
||||
{name: "zero percent", limits: strings.Replace(entry, `"percent":5.25`, `"percent":0`, 1), wantWindow: true},
|
||||
{name: "over quota percent", limits: strings.Replace(entry, `"percent":5.25`, `"percent":105.25`, 1), wantWindow: true, wantUsage: 105.25},
|
||||
{name: "legacy takes precedence", limits: entry, legacy: fmt.Sprintf(`{"utilization":56,"resets_at":%q}`, resetAt.Format(time.RFC3339Nano)), wantWindow: true, wantUsage: 56},
|
||||
{name: "null legacy", limits: entry, legacy: "null", wantWindow: true, wantUsage: 5.25},
|
||||
{name: "other model", limits: strings.Replace(entry, `"Fable"`, `"Sonnet"`, 1)},
|
||||
{name: "unscoped weekly", limits: strings.Replace(entry, `"weekly_scoped"`, `"weekly"`, 1)},
|
||||
{name: "other group", limits: strings.Replace(entry, `"group":"weekly"`, `"group":"daily"`, 1)},
|
||||
{name: "missing model", limits: strings.Replace(entry, `{"display_name":"Fable"}`, `null`, 1)},
|
||||
{name: "surface restricted", limits: strings.Replace(entry, `"surface":null`, `"surface":{"display_name":"Claude Code"}`, 1)},
|
||||
{name: "missing percent", limits: strings.Replace(entry, `"percent":5.25,`, ``, 1)},
|
||||
{name: "null percent", limits: strings.Replace(entry, `"percent":5.25`, `"percent":null`, 1)},
|
||||
{name: "negative percent", limits: strings.Replace(entry, `"percent":5.25`, `"percent":-1`, 1)},
|
||||
{name: "missing reset", limits: strings.Replace(entry, resetAt.Format(time.RFC3339Nano), "", 1)},
|
||||
{name: "invalid reset", limits: strings.Replace(entry, resetAt.Format(time.RFC3339Nano), "not-a-time", 1)},
|
||||
{name: "invalid entry before valid", limits: strings.Replace(entry, resetAt.Format(time.RFC3339Nano), "not-a-time", 1) + "," + entry, wantWindow: true, wantUsage: 5.25},
|
||||
{name: "unknown entry before valid", limits: `null,{"kind":"future_limit"},` + entry, wantWindow: true, wantUsage: 5.25},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
legacy := tc.legacy
|
||||
if legacy == "" {
|
||||
legacy = "null"
|
||||
}
|
||||
raw := fmt.Sprintf(`{"five_hour":{"utilization":12},"seven_day":{"utilization":34,"resets_at":%q},"seven_day_overage_included":%s,"limits":[%s]}`, resetAt.Format(time.RFC3339Nano), legacy, tc.limits)
|
||||
var resp ClaudeUsageResponse
|
||||
require.NoError(t, json.Unmarshal([]byte(raw), &resp))
|
||||
now := time.Now()
|
||||
info := (&AccountUsageService{}).buildUsageInfo(&resp, &now)
|
||||
require.Equal(t, 12.0, info.FiveHour.Utilization)
|
||||
require.Equal(t, 34.0, info.SevenDay.Utilization)
|
||||
if !tc.wantWindow {
|
||||
require.Nil(t, info.SevenDayFable)
|
||||
return
|
||||
}
|
||||
require.NotNil(t, info.SevenDayFable)
|
||||
require.Equal(t, tc.wantUsage, info.SevenDayFable.Utilization)
|
||||
require.NotNil(t, info.SevenDayFable.ResetsAt)
|
||||
require.True(t, resetAt.Equal(*info.SevenDayFable.ResetsAt))
|
||||
require.Positive(t, info.SevenDayFable.RemainingSeconds)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildPassiveUsageWindow(t *testing.T) {
|
||||
future := time.Now().Add(48 * time.Hour).Unix()
|
||||
|
||||
@@ -106,7 +163,7 @@ func TestSyncActiveToPassive_WritesFableExtras(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
svc.syncActiveToPassive(t.Context(), 1, usage)
|
||||
svc.syncActiveToPassive(t.Context(), &Account{ID: 1}, usage)
|
||||
|
||||
select {
|
||||
case updates := <-repo.updateExtraCh:
|
||||
|
||||
@@ -97,7 +97,7 @@ func TestSyncActiveToPassive_WritesFiveHourSessionWindowEnd(t *testing.T) {
|
||||
repo := &sessionWindowSyncRepo{}
|
||||
svc := &AccountUsageService{accountRepo: repo}
|
||||
resetsAt := time.Now().Add(3 * time.Hour).UTC().Truncate(time.Second)
|
||||
svc.syncActiveToPassive(context.Background(), 42, &UsageInfo{
|
||||
svc.syncActiveToPassive(context.Background(), &Account{ID: 42}, &UsageInfo{
|
||||
FiveHour: &UsageProgress{
|
||||
Utilization: 53,
|
||||
ResetsAt: &resetsAt,
|
||||
@@ -123,7 +123,7 @@ func TestSyncActiveToPassive_SkipsSessionWindowEndWhenResetMissing(t *testing.T)
|
||||
|
||||
repo := &sessionWindowSyncRepo{}
|
||||
svc := &AccountUsageService{accountRepo: repo}
|
||||
svc.syncActiveToPassive(context.Background(), 99, &UsageInfo{
|
||||
svc.syncActiveToPassive(context.Background(), &Account{ID: 99}, &UsageInfo{
|
||||
FiveHour: &UsageProgress{Utilization: 10},
|
||||
})
|
||||
|
||||
|
||||
@@ -48,6 +48,10 @@ func (r *accountRepoStubForClearAccountError) ClearModelRateLimits(ctx context.C
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *accountRepoStubForClearAccountError) ClearModelRateLimit(ctx context.Context, id int64, scope string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *accountRepoStubForClearAccountError) ClearTempUnschedulable(ctx context.Context, id int64) error {
|
||||
r.clearTempUnschedCalls++
|
||||
r.account.TempUnschedulableUntil = nil
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
)
|
||||
|
||||
// antigravityCompatCommittedNoContentError reports a compat stream that
|
||||
// committed HTTP 200 (pre-content keepalive) and then ended or timed out
|
||||
// without any content. The response can no longer fail over, so the client
|
||||
// retries; the handler releases the session's sticky account so that retry is
|
||||
// scheduled afresh instead of returning to the account that just failed.
|
||||
type antigravityCompatCommittedNoContentError struct {
|
||||
msg string
|
||||
}
|
||||
|
||||
func newAntigravityCompatCommittedNoContentError(msg string) error {
|
||||
return &antigravityCompatCommittedNoContentError{msg: msg}
|
||||
}
|
||||
|
||||
func (e *antigravityCompatCommittedNoContentError) Error() string { return e.msg }
|
||||
|
||||
// IsAntigravityCompatCommittedNoContent reports whether err is a compat stream
|
||||
// that committed its response and then produced no content.
|
||||
func IsAntigravityCompatCommittedNoContent(err error) bool {
|
||||
var target *antigravityCompatCommittedNoContentError
|
||||
return errors.As(err, &target)
|
||||
}
|
||||
|
||||
// ReleaseStickySessionAfterCommittedNoContent removes the session's sticky
|
||||
// binding when err is a committed no-content compat stream and the session is
|
||||
// still bound to accountID. Only this session is affected: the account is not
|
||||
// cooled or excluded for anyone else. Returns true when a binding was removed.
|
||||
func (s *GatewayService) ReleaseStickySessionAfterCommittedNoContent(ctx context.Context, groupID *int64, sessionHash string, accountID int64, err error) bool {
|
||||
if sessionHash == "" || accountID <= 0 || s.cache == nil || !IsAntigravityCompatCommittedNoContent(err) {
|
||||
return false
|
||||
}
|
||||
gid := derefGroupID(groupID)
|
||||
bound, getErr := s.cache.GetSessionAccountID(ctx, gid, sessionHash)
|
||||
if getErr != nil || bound != accountID {
|
||||
return false
|
||||
}
|
||||
if delErr := s.cache.DeleteSessionAccountID(ctx, gid, sessionHash); delErr != nil {
|
||||
slog.Warn("antigravity_compat_sticky_release_failed", "group_id", gid, "account_id", accountID, "error", delErr)
|
||||
return false
|
||||
}
|
||||
slog.Info("antigravity_compat_sticky_released", "group_id", gid, "account_id", accountID, "reason", err.Error())
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// runCompatStreamToEnd drives the compat stream handler with an upstream that
|
||||
// sends nothing and closes after closeAfter.
|
||||
func runCompatStreamToEnd(t *testing.T, keepaliveInterval, maxWait, closeAfter time.Duration) error {
|
||||
t.Helper()
|
||||
svc := newAntigravityCompatService(config.GatewayConfig{
|
||||
MaxLineSize: defaultMaxLineSize, StreamDataIntervalTimeout: 30, StreamKeepaliveInterval: 0,
|
||||
}, nil)
|
||||
c, _ := newAntigravityCompatContext(http.MethodPost, "/v1/responses", nil)
|
||||
reader, pipeWriter := io.Pipe()
|
||||
defer func() { _ = reader.Close() }()
|
||||
resp := &http.Response{StatusCode: http.StatusOK, Body: reader}
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := svc.handleAntigravityCompatStreamWithKeepaliveInterval(
|
||||
c, resp, time.Now(), "gemini-4-hydrogen-high",
|
||||
newAntigravityResponsesStreamAdapter("gemini-4-hydrogen-high"), "test", keepaliveInterval, maxWait,
|
||||
)
|
||||
done <- err
|
||||
}()
|
||||
time.Sleep(closeAfter)
|
||||
_ = pipeWriter.Close()
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("compat stream handler did not return")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityCompatEmptyStreamAfterKeepaliveIsCommittedNoContent(t *testing.T) {
|
||||
err := runCompatStreamToEnd(t, 10*time.Millisecond, time.Second, 50*time.Millisecond)
|
||||
require.Error(t, err)
|
||||
require.True(t, IsAntigravityCompatCommittedNoContent(err), "got %v", err)
|
||||
}
|
||||
|
||||
func TestAntigravityCompatPreContentTimeoutAfterKeepaliveIsCommittedNoContent(t *testing.T) {
|
||||
err := runCompatStreamToEnd(t, 10*time.Millisecond, 40*time.Millisecond, 200*time.Millisecond)
|
||||
require.Error(t, err)
|
||||
require.ErrorContains(t, err, "pre-content stream timeout")
|
||||
require.True(t, IsAntigravityCompatCommittedNoContent(err), "got %v", err)
|
||||
}
|
||||
|
||||
func TestAntigravityCompatEmptyStreamBeforeKeepaliveStaysFailover(t *testing.T) {
|
||||
err := runCompatStreamToEnd(t, time.Second, 2*time.Second, 10*time.Millisecond)
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.True(t, errors.As(err, &failoverErr), "got %v", err)
|
||||
require.False(t, IsAntigravityCompatCommittedNoContent(err))
|
||||
}
|
||||
|
||||
func TestReleaseStickySessionAfterCommittedNoContent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
groupID := int64(10)
|
||||
committed := &antigravityCompatCommittedNoContentError{msg: "empty Antigravity compatibility stream after keepalive"}
|
||||
|
||||
t.Run("unbinds the session from the account that failed", func(t *testing.T) {
|
||||
cache := &stubGatewayCache{sessionBindings: map[string]int64{"sess": 5}}
|
||||
svc := &GatewayService{cache: cache}
|
||||
require.True(t, svc.ReleaseStickySessionAfterCommittedNoContent(ctx, &groupID, "sess", 5, committed))
|
||||
_, bound := cache.sessionBindings["sess"]
|
||||
require.False(t, bound)
|
||||
})
|
||||
|
||||
t.Run("keeps a binding that already moved to another account", func(t *testing.T) {
|
||||
cache := &stubGatewayCache{sessionBindings: map[string]int64{"sess": 6}}
|
||||
svc := &GatewayService{cache: cache}
|
||||
require.False(t, svc.ReleaseStickySessionAfterCommittedNoContent(ctx, &groupID, "sess", 5, committed))
|
||||
require.Equal(t, int64(6), cache.sessionBindings["sess"])
|
||||
})
|
||||
|
||||
t.Run("ignores other errors", func(t *testing.T) {
|
||||
cache := &stubGatewayCache{sessionBindings: map[string]int64{"sess": 5}}
|
||||
svc := &GatewayService{cache: cache}
|
||||
require.False(t, svc.ReleaseStickySessionAfterCommittedNoContent(ctx, &groupID, "sess", 5, errors.New("stream data interval timeout")))
|
||||
require.Equal(t, int64(5), cache.sessionBindings["sess"])
|
||||
})
|
||||
|
||||
t.Run("no session hash is a no-op", func(t *testing.T) {
|
||||
cache := &stubGatewayCache{sessionBindings: map[string]int64{"sess": 5}}
|
||||
svc := &GatewayService{cache: cache}
|
||||
require.False(t, svc.ReleaseStickySessionAfterCommittedNoContent(ctx, &groupID, "", 5, committed))
|
||||
require.Equal(t, int64(5), cache.sessionBindings["sess"])
|
||||
})
|
||||
}
|
||||
@@ -259,7 +259,7 @@ func (s *AntigravityGatewayService) prepareAntigravityCompatCall(
|
||||
mappedModel := s.getMappedModelForThinkingLevel(
|
||||
account,
|
||||
request.originalModel,
|
||||
geminiThinkingLevelFromClaudeThinking(claudeRequest.Thinking),
|
||||
geminiThinkingLevelFromClaudeBody(request.claudeBody, claudeRequest.Thinking),
|
||||
)
|
||||
if mappedModel == "" {
|
||||
MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalFeatureGate)
|
||||
@@ -322,6 +322,7 @@ func (s *AntigravityGatewayService) buildAntigravityCompatGeminiBody(
|
||||
return nil, err
|
||||
}
|
||||
body = ensureGeminiFunctionCallThoughtSignatures(body)
|
||||
body = applyGeminiCompatThinkingConfig(body, claudeBody, mappedModel, claudeRequest != nil && claudeRequest.Stream)
|
||||
body, err = injectIdentityPatchToGeminiRequest(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -154,9 +154,9 @@ func (s *antigravityCompatStreamSession) hasMeaningfulData() bool {
|
||||
}
|
||||
|
||||
func (s *antigravityCompatStreamSession) writePreContentKeepalive(now time.Time) {
|
||||
// Intentional tradeoff: this commits HTTP 200 after 15s, so later upstream
|
||||
// Intentional tradeoff: this commits HTTP 200 after the keepalive interval, so later upstream
|
||||
// failures cannot fail over; report them as SSE errors to the client instead.
|
||||
if s.hasMeaningfulData() || s.writer.Disconnected() || now.Sub(s.startTime) < s.preContentKeepaliveInterval {
|
||||
if s.hasMeaningfulData() || s.writer.Disconnected() || (!s.preContentKeepaliveSent && now.Sub(s.startTime) < s.preContentKeepaliveInterval) {
|
||||
return
|
||||
}
|
||||
if s.writer.Write([]byte(": ping\n\n")) {
|
||||
@@ -171,7 +171,7 @@ func (s *antigravityCompatStreamSession) finish() (*antigravityStreamResult, err
|
||||
if !s.hasMeaningfulData() && !s.writer.Disconnected() {
|
||||
if s.preContentKeepaliveSent {
|
||||
s.adapter.WriteError(s.writer, "empty_stream")
|
||||
return s.result(false), errors.New("empty Antigravity compatibility stream after keepalive")
|
||||
return s.result(false), newAntigravityCompatCommittedNoContentError("empty Antigravity compatibility stream after keepalive")
|
||||
}
|
||||
return nil, antigravityCompatEmptyStreamError()
|
||||
}
|
||||
@@ -282,12 +282,52 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStream(
|
||||
adapter antigravityCompatStreamAdapter,
|
||||
prefix string,
|
||||
) (*antigravityStreamResult, error) {
|
||||
return s.handleAntigravityCompatStreamWithKeepaliveInterval(c, resp, startTime, originalModel, adapter, prefix, antigravityCompatPreContentKeepaliveInterval, antigravityCompatPreContentMaxWait)
|
||||
return s.handleAntigravityCompatStreamWithKeepaliveInterval(
|
||||
c,
|
||||
resp,
|
||||
startTime,
|
||||
originalModel,
|
||||
adapter,
|
||||
prefix,
|
||||
antigravityCompatPreContentKeepaliveInterval,
|
||||
s.antigravityCompatPreContentMaxWait(),
|
||||
)
|
||||
}
|
||||
|
||||
// handleAntigravityCompatStreamAfterHeaders starts reading an upstream HTTP 200 SSE
|
||||
// stream while keeping startTime for TTFT measurement and anchoring the pre-content
|
||||
// deadline at response-header arrival rather than request start.
|
||||
func (s *AntigravityGatewayService) handleAntigravityCompatStreamAfterHeaders(
|
||||
c *gin.Context,
|
||||
resp *http.Response,
|
||||
startTime time.Time,
|
||||
originalModel string,
|
||||
adapter antigravityCompatStreamAdapter,
|
||||
prefix string,
|
||||
) (*antigravityStreamResult, error) {
|
||||
return s.handleAntigravityCompatStreamWithTiming(
|
||||
c,
|
||||
resp,
|
||||
startTime,
|
||||
time.Now(),
|
||||
originalModel,
|
||||
adapter,
|
||||
prefix,
|
||||
s.antigravityCompatPreContentKeepaliveInterval(),
|
||||
s.antigravityCompatPreContentMaxWait(),
|
||||
)
|
||||
}
|
||||
|
||||
func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveInterval(
|
||||
c *gin.Context, resp *http.Response, startTime time.Time, originalModel string,
|
||||
adapter antigravityCompatStreamAdapter, prefix string, interval, maxPreContentWait time.Duration,
|
||||
) (*antigravityStreamResult, error) {
|
||||
return s.handleAntigravityCompatStreamWithTiming(c, resp, startTime, startTime, originalModel, adapter, prefix, interval, maxPreContentWait)
|
||||
}
|
||||
|
||||
func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithTiming(
|
||||
c *gin.Context, resp *http.Response, startTime, streamStart time.Time, originalModel string,
|
||||
adapter antigravityCompatStreamAdapter, prefix string, interval, maxPreContentWait time.Duration,
|
||||
) (*antigravityStreamResult, error) {
|
||||
flusher, ok := c.Writer.(http.Flusher)
|
||||
if !ok {
|
||||
@@ -303,6 +343,7 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
session := newAntigravityCompatStreamSession(originalModel, startTime, adapter, writer)
|
||||
session.preContentKeepaliveSent = IsResponseCommitted(c) && c.Writer.Written()
|
||||
session.preContentKeepaliveInterval = interval
|
||||
events, stopScanner, maxLineSize, queueBudget := s.startAntigravityCompatScanner(resp.Body)
|
||||
defer stopScanner()
|
||||
@@ -316,13 +357,17 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn
|
||||
if keepaliveTicker != nil {
|
||||
defer keepaliveTicker.Stop()
|
||||
}
|
||||
preContentDelay := time.Until(startTime.Add(interval))
|
||||
keepaliveStart := startTime
|
||||
if session.preContentKeepaliveSent {
|
||||
keepaliveStart = streamStart
|
||||
}
|
||||
preContentDelay := time.Until(keepaliveStart.Add(interval))
|
||||
if preContentDelay < 0 {
|
||||
preContentDelay = 0
|
||||
}
|
||||
preContentTimer := time.NewTimer(preContentDelay)
|
||||
defer preContentTimer.Stop()
|
||||
preContentDeadline := startTime.Add(maxPreContentWait)
|
||||
preContentDeadline := streamStart.Add(maxPreContentWait)
|
||||
deadlineDelay := time.Until(preContentDeadline)
|
||||
if deadlineDelay < 0 {
|
||||
deadlineDelay = 0
|
||||
@@ -332,7 +377,7 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn
|
||||
preContentTimeout := func() (*antigravityStreamResult, error) {
|
||||
if session.preContentKeepaliveSent {
|
||||
writeAntigravityCompatStreamError(c, adapter, writer, "stream_timeout")
|
||||
return session.collectResult(false), fmt.Errorf("pre-content stream timeout")
|
||||
return session.collectResult(false), newAntigravityCompatCommittedNoContentError("pre-content stream timeout")
|
||||
}
|
||||
return nil, antigravityCompatEmptyStreamError()
|
||||
}
|
||||
@@ -393,7 +438,7 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn
|
||||
func handleAntigravityCompatEmptyStream(c *gin.Context, session *antigravityCompatStreamSession) (*antigravityStreamResult, error) {
|
||||
if session.preContentKeepaliveSent {
|
||||
writeAntigravityCompatStreamError(c, session.adapter, session.writer, "empty_stream")
|
||||
return session.collectResult(false), errors.New("empty Antigravity compatibility stream after keepalive")
|
||||
return session.collectResult(false), newAntigravityCompatCommittedNoContentError("empty Antigravity compatibility stream after keepalive")
|
||||
}
|
||||
return nil, antigravityCompatEmptyStreamError()
|
||||
}
|
||||
@@ -447,6 +492,24 @@ func (s *AntigravityGatewayService) antigravityCompatStreamTimeout() time.Durati
|
||||
return time.Duration(s.settingService.cfg.Gateway.StreamDataIntervalTimeout) * time.Second
|
||||
}
|
||||
|
||||
func (s *AntigravityGatewayService) antigravityCompatPreContentKeepaliveInterval() time.Duration {
|
||||
interval := antigravityCompatPreContentKeepaliveInterval
|
||||
if s.settingService != nil && s.settingService.cfg != nil {
|
||||
configured := time.Duration(s.settingService.cfg.Gateway.StreamKeepaliveInterval) * time.Second
|
||||
if configured > 0 && configured < interval {
|
||||
interval = configured
|
||||
}
|
||||
}
|
||||
return interval
|
||||
}
|
||||
|
||||
func (s *AntigravityGatewayService) antigravityCompatPreContentMaxWait() time.Duration {
|
||||
if timeout := s.antigravityCompatStreamTimeout(); timeout > antigravityCompatPreContentMaxWait {
|
||||
return timeout
|
||||
}
|
||||
return antigravityCompatPreContentMaxWait
|
||||
}
|
||||
|
||||
func (s *AntigravityGatewayService) newAntigravityCompatKeepaliveTicker() (*time.Ticker, <-chan time.Time) {
|
||||
if s.settingService == nil || s.settingService.cfg == nil {
|
||||
return nil, nil
|
||||
@@ -532,7 +595,7 @@ func (s *AntigravityGatewayService) handleChatCompletionsStreamingFromAntigravit
|
||||
originalModel string,
|
||||
includeUsage bool,
|
||||
) (*antigravityStreamResult, error) {
|
||||
return s.handleAntigravityCompatStream(
|
||||
return s.handleAntigravityCompatStreamAfterHeaders(
|
||||
c,
|
||||
resp,
|
||||
startTime,
|
||||
@@ -548,7 +611,7 @@ func (s *AntigravityGatewayService) handleResponsesStreamingFromAntigravity(
|
||||
startTime time.Time,
|
||||
originalModel string,
|
||||
) (*antigravityStreamResult, error) {
|
||||
return s.handleAntigravityCompatStream(
|
||||
return s.handleAntigravityCompatStreamAfterHeaders(
|
||||
c,
|
||||
resp,
|
||||
startTime,
|
||||
|
||||
@@ -132,6 +132,74 @@ func antigravityCompatSuccessResponse() *http.Response {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityCompatToolSchemaItemsMatchSelectedType(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
const schema = `{"type":"object","properties":{
|
||||
"uri":{"type":["string","array"],"items":{"type":"string"}},
|
||||
"paths":{"type":["array","string"],"items":{"type":"integer"}},
|
||||
"nested":{"type":"array","items":{"type":"object","properties":{
|
||||
"uri":{"type":["string","array"],"items":{"type":"string"}}
|
||||
}}},
|
||||
"fallback":{"type":"array","items":17},
|
||||
"inferred":{"items":{"type":"integer"}},
|
||||
"items":{"type":"string"}
|
||||
}}`
|
||||
const expected = `{"type":"object","properties":{
|
||||
"uri":{"type":"string"},
|
||||
"paths":{"type":"array","items":{"type":"integer"}},
|
||||
"nested":{"type":"array","items":{"type":"object","properties":{
|
||||
"uri":{"type":"string"}
|
||||
}}},
|
||||
"fallback":{"type":"array","items":{"type":"string"}},
|
||||
"inferred":{"type":"array","items":{"type":"integer"}},
|
||||
"items":{"type":"string"}
|
||||
}}`
|
||||
for _, protocol := range []string{"chat", "responses", "messages"} {
|
||||
t.Run(protocol, func(t *testing.T) {
|
||||
var parameters map[string]any
|
||||
require.NoError(t, json.Unmarshal([]byte(schema), ¶meters))
|
||||
tool := map[string]any{"name": "inspect", "parameters": parameters}
|
||||
request := map[string]any{"model": "gemini-3.1-pro-high", "max_tokens": 128}
|
||||
switch protocol {
|
||||
case "chat":
|
||||
request["messages"] = []map[string]any{{"role": "user", "content": "inspect URI"}}
|
||||
request["tools"] = []any{map[string]any{"type": "function", "function": tool}}
|
||||
case "responses":
|
||||
request["input"] = "inspect URI"
|
||||
tool["type"] = "function"
|
||||
request["tools"] = []any{tool}
|
||||
case "messages":
|
||||
request["messages"] = []map[string]any{{"role": "user", "content": "inspect URI"}}
|
||||
request["tools"] = []any{map[string]any{"name": "inspect", "input_schema": parameters}}
|
||||
}
|
||||
body, err := json.Marshal(request)
|
||||
require.NoError(t, err)
|
||||
var forwarded []byte
|
||||
upstream := &queuedHTTPUpstreamStub{
|
||||
responses: []*http.Response{antigravityCompatSuccessResponse()},
|
||||
onCall: func(req *http.Request, _ *queuedHTTPUpstreamStub) {
|
||||
forwarded, err = io.ReadAll(req.Body)
|
||||
require.NoError(t, err)
|
||||
},
|
||||
}
|
||||
svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream)
|
||||
account := newAntigravityCompatAccount(AccountTypeOAuth)
|
||||
c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/"+protocol, body)
|
||||
switch protocol {
|
||||
case "chat":
|
||||
_, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, nil)
|
||||
case "responses":
|
||||
_, err = svc.ForwardAsResponses(context.Background(), c, account, body, nil)
|
||||
case "messages":
|
||||
_, err = svc.Forward(context.Background(), c, account, body, false)
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, recorder.Code)
|
||||
require.JSONEq(t, expected, gjson.GetBytes(forwarded, "request.tools.0.functionDeclarations.0.parameters").Raw)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravitySystemIdentityAcrossProtocols(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
const task = "\nKeep GPT-5.6, gpt-6 and Claude model ids unchanged."
|
||||
@@ -1256,3 +1324,209 @@ func TestAntigravityCompatEmptyAfterKeepaliveReportsStreamError(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityCompatGeminiThinkingConfig(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
t.Run("streaming responses tier suffix enables includeThoughts without thinkingLevel", func(t *testing.T) {
|
||||
upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}}
|
||||
svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream)
|
||||
account := newAntigravityCompatAccount(AccountTypeOAuth)
|
||||
mapping, ok := account.Credentials["model_mapping"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
mapping["gemini-4-argon-high"] = "gemini-4-argon-high"
|
||||
|
||||
body := []byte(`{"model":"gemini-4-argon-high","stream":true,"input":"inspect repository"}`)
|
||||
c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/responses", body)
|
||||
|
||||
_, err := svc.ForwardAsResponses(context.Background(), c, account, body, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, recorder.Code)
|
||||
require.Len(t, upstream.requestBodies, 1)
|
||||
|
||||
cfg := gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig")
|
||||
require.True(t, cfg.Get("includeThoughts").Bool(), "thinkingConfig=%s", cfg.Raw)
|
||||
require.False(t, cfg.Get("thinkingLevel").Exists(), "tier-suffixed model must not set thinkingLevel: %s", cfg.Raw)
|
||||
require.False(t, cfg.Get("thinkingBudget").Exists(), "tier-suffixed model must not set thinkingBudget: %s", cfg.Raw)
|
||||
})
|
||||
|
||||
t.Run("streaming chat completions tier suffix enables includeThoughts without thinkingLevel", func(t *testing.T) {
|
||||
upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}}
|
||||
svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream)
|
||||
account := newAntigravityCompatAccount(AccountTypeOAuth)
|
||||
mapping, ok := account.Credentials["model_mapping"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
mapping["gemini-4-argon-high"] = "gemini-4-argon-high"
|
||||
|
||||
body := []byte(`{"model":"gemini-4-argon-high","stream":true,"messages":[{"role":"user","content":"inspect repository"}]}`)
|
||||
c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/chat/completions", body)
|
||||
|
||||
_, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, recorder.Code)
|
||||
require.Len(t, upstream.requestBodies, 1)
|
||||
|
||||
cfg := gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig")
|
||||
require.True(t, cfg.Get("includeThoughts").Bool(), "thinkingConfig=%s", cfg.Raw)
|
||||
require.False(t, cfg.Get("thinkingLevel").Exists(), "thinkingConfig=%s", cfg.Raw)
|
||||
})
|
||||
|
||||
t.Run("streaming responses bare model with low effort selects low variant and enables includeThoughts", func(t *testing.T) {
|
||||
upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}}
|
||||
svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream)
|
||||
account := newAntigravityCompatAccount(AccountTypeOAuth)
|
||||
mapping, ok := account.Credentials["model_mapping"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
mapping["gemini-4-argon-low"] = "gemini-4-argon-low"
|
||||
mapping["gemini-4-argon-high"] = "gemini-4-argon-high"
|
||||
|
||||
body := []byte(`{"model":"gemini-4-argon","stream":true,"reasoning":{"effort":"low"},"input":"quick check"}`)
|
||||
c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/responses", body)
|
||||
|
||||
result, err := svc.ForwardAsResponses(context.Background(), c, account, body, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, recorder.Code)
|
||||
require.Len(t, upstream.requestBodies, 1)
|
||||
require.Equal(t, "gemini-4-argon-low", gjson.GetBytes(upstream.requestBodies[0], "model").String())
|
||||
require.Equal(t, "gemini-4-argon-low", result.UpstreamModel)
|
||||
|
||||
cfg := gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig")
|
||||
require.True(t, cfg.Get("includeThoughts").Bool(), "thinkingConfig=%s", cfg.Raw)
|
||||
require.False(t, cfg.Get("thinkingLevel").Exists(), "thinkingConfig=%s", cfg.Raw)
|
||||
})
|
||||
|
||||
t.Run("streaming responses explicit bare model sets thinkingLevel and includeThoughts", func(t *testing.T) {
|
||||
upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}}
|
||||
svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream)
|
||||
account := newAntigravityCompatAccount(AccountTypeOAuth)
|
||||
mapping, ok := account.Credentials["model_mapping"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
mapping["gemini-3.5-flash"] = "gemini-3.5-flash"
|
||||
|
||||
body := []byte(`{"model":"gemini-3.5-flash","stream":true,"reasoning":{"effort":"medium"},"input":"check"}`)
|
||||
c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/responses", body)
|
||||
|
||||
_, err := svc.ForwardAsResponses(context.Background(), c, account, body, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, recorder.Code)
|
||||
require.Len(t, upstream.requestBodies, 1)
|
||||
|
||||
cfg := gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig")
|
||||
require.Equal(t, "medium", cfg.Get("thinkingLevel").String(), "thinkingConfig=%s", cfg.Raw)
|
||||
require.True(t, cfg.Get("includeThoughts").Bool(), "thinkingConfig=%s", cfg.Raw)
|
||||
})
|
||||
|
||||
t.Run("non-streaming responses do not force includeThoughts", func(t *testing.T) {
|
||||
upstream := &queuedHTTPUpstreamStub{responses: []*http.Response{antigravityCompatSuccessResponse()}}
|
||||
svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream)
|
||||
account := newAntigravityCompatAccount(AccountTypeOAuth)
|
||||
mapping, ok := account.Credentials["model_mapping"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
mapping["gemini-4-argon-high"] = "gemini-4-argon-high"
|
||||
|
||||
nonStreamBody := []byte(`{"model":"gemini-4-argon-high","stream":false,"input":"inspect"}`)
|
||||
c, rec := newAntigravityCompatContext(http.MethodPost, "/v1/responses", nonStreamBody)
|
||||
_, err := svc.ForwardAsResponses(context.Background(), c, account, nonStreamBody, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Len(t, upstream.requestBodies, 1)
|
||||
require.False(t, gjson.GetBytes(upstream.requestBodies[0], "request.generationConfig.thinkingConfig.includeThoughts").Bool())
|
||||
})
|
||||
}
|
||||
|
||||
func TestAntigravityCompatHeaderWaitExceedingPreContentLimitDoesNotAbortStream(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, protocol := range []antigravityCompatProtocol{antigravityCompatResponses, antigravityCompatChatCompletions} {
|
||||
name := "responses"
|
||||
path := "/v1/responses"
|
||||
wantDone := "event: response.completed"
|
||||
if protocol == antigravityCompatChatCompletions {
|
||||
name = "chat_completions"
|
||||
path = "/v1/chat/completions"
|
||||
wantDone = "data: [DONE]"
|
||||
}
|
||||
for _, committedKeepalive := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("%s/keepalive=%t", name, committedKeepalive), func(t *testing.T) {
|
||||
svc := newAntigravityCompatService(config.GatewayConfig{
|
||||
MaxLineSize: defaultMaxLineSize,
|
||||
StreamDataIntervalTimeout: 180,
|
||||
StreamKeepaliveInterval: 10,
|
||||
}, nil)
|
||||
c, recorder := newAntigravityCompatContext(http.MethodPost, path, nil)
|
||||
if committedKeepalive {
|
||||
c.Header("Content-Type", "text/event-stream")
|
||||
c.Status(http.StatusOK)
|
||||
MarkResponseCommitted(c)
|
||||
_, err := c.Writer.Write([]byte(": ping\n\n"))
|
||||
require.NoError(t, err)
|
||||
c.Writer.Flush()
|
||||
}
|
||||
|
||||
requestStart := time.Now().Add(-3 * time.Minute)
|
||||
call := &antigravityCompatUpstreamCall{
|
||||
request: antigravityCompatRequest{
|
||||
protocol: protocol,
|
||||
originalModel: "gemini-4-argon-high",
|
||||
clientStream: true,
|
||||
startTime: requestStart,
|
||||
},
|
||||
billingModel: "gemini-4-argon-high",
|
||||
prefix: "test-long-header-wait",
|
||||
}
|
||||
|
||||
result, err := svc.consumeAntigravityCompatResponse(
|
||||
c.Request.Context(),
|
||||
c,
|
||||
newAntigravityCompatAccount(AccountTypeOAuth),
|
||||
call,
|
||||
antigravityCompatSuccessResponse(),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.NotNil(t, result.FirstTokenMs)
|
||||
require.GreaterOrEqual(t, *result.FirstTokenMs, int((3*time.Minute - time.Second).Milliseconds()))
|
||||
require.Contains(t, recorder.Body.String(), wantDone)
|
||||
require.NotContains(t, recorder.Body.String(), "stream_timeout")
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityCompatInterleavedThoughtChunksResetIdleTimeout(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
svc := newAntigravityCompatService(config.GatewayConfig{
|
||||
MaxLineSize: defaultMaxLineSize,
|
||||
StreamDataIntervalTimeout: 1,
|
||||
}, nil)
|
||||
c, recorder := newAntigravityCompatContext(http.MethodPost, "/v1/responses", nil)
|
||||
reader, writer := io.Pipe()
|
||||
defer func() { _ = reader.Close() }()
|
||||
resp := &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: reader,
|
||||
}
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := svc.handleResponsesStreamingFromAntigravity(c, resp, time.Now(), "gemini-4-argon-high")
|
||||
done <- err
|
||||
}()
|
||||
|
||||
_, err := io.WriteString(writer, `data: {"response":{"responseId":"resp_44276","candidates":[{"content":{"role":"model","parts":[{"text":"Checking files..."}]}}]}}`+"\n\n")
|
||||
require.NoError(t, err)
|
||||
for i := 0; i < 4; i++ {
|
||||
time.Sleep(350 * time.Millisecond)
|
||||
_, err = io.WriteString(writer, fmt.Sprintf(`data: {"response":{"responseId":"resp_44276","candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"step %d "}]}}]}}`+"\n\n", i+1))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
_, err = io.WriteString(writer, `data: {"response":{"responseId":"resp_44276","candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"sig_done","functionCall":{"name":"exec_command","args":{"cmd":"ls"},"id":"call_1"}}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":20,"thoughtsTokenCount":50}}}`+"\n\n")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, writer.Close())
|
||||
|
||||
require.NoError(t, <-done)
|
||||
out := recorder.Body.String()
|
||||
require.Contains(t, out, "event: response.reasoning_summary_text.delta")
|
||||
require.Contains(t, out, "event: response.completed")
|
||||
require.NotContains(t, out, "stream_timeout")
|
||||
}
|
||||
@@ -85,6 +85,22 @@ func geminiThinkingLevelFromBody(body []byte) string {
|
||||
}
|
||||
}
|
||||
|
||||
// geminiThinkingLevelFromClaudeBody 结合兼容层转换后的 output_config.effort 与 thinking 配置推导档位。
|
||||
// OpenAI Responses / Chat Completions 在 effort=low/minimal/none 时可能只写 output_config.effort 而不写 thinking,
|
||||
// 优先读取显式 effort 可避免裸 Gemini 模型被默认归入 high 变体。
|
||||
func geminiThinkingLevelFromClaudeBody(claudeBody []byte, thinking *antigravity.ThinkingConfig) string {
|
||||
switch parseClaudeThinkingIntent(claudeBody).tier {
|
||||
case "minimal", "low":
|
||||
return "low"
|
||||
case "medium":
|
||||
return "medium"
|
||||
case "high":
|
||||
return "high"
|
||||
default:
|
||||
return geminiThinkingLevelFromClaudeThinking(thinking)
|
||||
}
|
||||
}
|
||||
|
||||
// geminiThinkingLevelFromClaudeThinking 用 Claude Messages 协议的 thinking 配置推导档位,
|
||||
// 阈值与 geminiThinkingLevelFromBody 保持一致,使同一请求无论走 Gemini 原生还是
|
||||
// Chat Completions / Messages 兼容层都落到同一个上游变体。
|
||||
|
||||
@@ -1057,6 +1057,9 @@ func (s *AuthService) shouldApplyEmailFirstBindDefaults(
|
||||
identity *dbent.AuthIdentity,
|
||||
created bool,
|
||||
) bool {
|
||||
if identity == nil {
|
||||
return false
|
||||
}
|
||||
source := emailAuthIdentitySource(identity.Metadata)
|
||||
if source == "auth_service_login_backfill" {
|
||||
return false
|
||||
@@ -1064,7 +1067,7 @@ func (s *AuthService) shouldApplyEmailFirstBindDefaults(
|
||||
if created {
|
||||
return true
|
||||
}
|
||||
if s == nil || s.entClient == nil || userID <= 0 || identity == nil || identity.UserID != userID {
|
||||
if s == nil || s.entClient == nil || userID <= 0 || identity.UserID != userID {
|
||||
return false
|
||||
}
|
||||
if source != "auth_service_dual_write" {
|
||||
|
||||
@@ -259,6 +259,53 @@ func TestAuthServiceRecordSuccessfulLoginBackfillsEmailIdentity(t *testing.T) {
|
||||
require.Equal(t, user.ID, identity.UserID)
|
||||
}
|
||||
|
||||
func TestAuthServiceRecordSuccessfulLogin_EmailIdentityOwnedByAnotherUser(t *testing.T) {
|
||||
assigner := &authIdentityDefaultSubAssignerStub{}
|
||||
svc, _, client := newAuthServiceWithEnt(t, map[string]string{
|
||||
service.SettingKeyRegistrationEnabled: "true",
|
||||
service.SettingKeyAuthSourceDefaultEmailBalance: "8.5",
|
||||
service.SettingKeyAuthSourceDefaultEmailGrantOnFirstBind: "true",
|
||||
}, assigner)
|
||||
ctx := context.Background()
|
||||
|
||||
// users.email 唯一索引区分大小写,email 身份按小写邮箱唯一:只差大小写的两个账号共用一条身份。
|
||||
owner, err := client.User.Create().
|
||||
SetEmail("Shared@Example.com").
|
||||
SetPasswordHash("hash").
|
||||
SetBalance(1).
|
||||
SetConcurrency(1).
|
||||
SetRole(service.RoleUser).
|
||||
SetStatus(service.StatusActive).
|
||||
Save(ctx)
|
||||
require.NoError(t, err)
|
||||
user, err := client.User.Create().
|
||||
SetEmail("shared@example.com").
|
||||
SetPasswordHash("hash").
|
||||
SetBalance(1).
|
||||
SetConcurrency(1).
|
||||
SetRole(service.RoleUser).
|
||||
SetStatus(service.StatusActive).
|
||||
Save(ctx)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, client.AuthIdentity.Create().
|
||||
SetUserID(owner.ID).
|
||||
SetProviderType("email").
|
||||
SetProviderKey("email").
|
||||
SetProviderSubject("shared@example.com").
|
||||
SetVerifiedAt(time.Now().UTC()).
|
||||
SetMetadata(map[string]any{"source": "auth_service_dual_write"}).
|
||||
Exec(ctx))
|
||||
|
||||
require.NotPanics(t, func() { svc.RecordSuccessfulLogin(ctx, user.ID) })
|
||||
|
||||
storedUser, err := client.User.Get(ctx, user.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, storedUser.LastLoginAt)
|
||||
require.Equal(t, 1.0, storedUser.Balance)
|
||||
require.Empty(t, assigner.calls)
|
||||
require.Equal(t, 0, countProviderGrantRecords(t, client, user.ID, "email", "first_bind"))
|
||||
}
|
||||
|
||||
func TestAuthServiceLogin_DoesNotApplyEmailFirstBindDefaultsWhenBackfillingLegacyEmailIdentity(t *testing.T) {
|
||||
assigner := &authIdentityDefaultSubAssignerStub{}
|
||||
svc, _, client := newAuthServiceWithEnt(t, map[string]string{
|
||||
|
||||
@@ -940,7 +940,7 @@ func (s *BillingCacheService) checkRPM(ctx context.Context, user *User, group *G
|
||||
if group != nil {
|
||||
// 解析 override:优先从 auth cache snapshot;snapshot 未确认该分组时回退 DB。
|
||||
var override *int
|
||||
if user.UserGroupRPMOverride != nil || user.UserGroupRPMOverrideGroupID == group.ID {
|
||||
if user.UserGroupRPMOverrideGroupID == group.ID {
|
||||
override = user.UserGroupRPMOverride
|
||||
} else if s.userGroupRateRepo != nil {
|
||||
dbOverride, err := s.userGroupRateRepo.GetRPMOverrideByUserAndGroup(ctx, user.ID, group.ID)
|
||||
|
||||
@@ -359,8 +359,8 @@ func TestInflightEstimate_AccountLevelMappingFallsBackLikeBilling(t *testing.T)
|
||||
groupID := int64(31)
|
||||
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-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"}}},
|
||||
{ID: 1, Platform: PlatformAnthropic, Status: StatusActive, Schedulable: true, Credentials: map[string]any{"model_mapping": map[string]any{"acct-alias-31": "claude-sonnet-4-5"}}},
|
||||
{ID: 2, Platform: PlatformAnthropic, Status: StatusActive, Schedulable: true, 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}}
|
||||
@@ -468,7 +468,7 @@ func TestInflightEstimate_AccountMappingNoDBAndBoundedMemory(t *testing.T) {
|
||||
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"}}},
|
||||
{ID: 1, Platform: PlatformAnthropic, Status: StatusActive, Schedulable: true, 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}}
|
||||
@@ -493,7 +493,7 @@ func TestInflightEstimate_AccountMappingNoNegativeCaching(t *testing.T) {
|
||||
|
||||
_, 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"}}}})
|
||||
snap.set(groupID, PlatformAnthropic, []Account{{ID: 9, Platform: PlatformAnthropic, Status: StatusActive, Schedulable: true, 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)
|
||||
|
||||
@@ -98,15 +98,16 @@ type BillingCache interface {
|
||||
type ModelPricing struct {
|
||||
// UltrafastMultiplier is model-owned and independent of operator Fast pricing.
|
||||
UltrafastMultiplier float64
|
||||
InputPricePerToken float64 // 每token输入价格 (USD)
|
||||
InputPricePerTokenPriority float64 // priority service tier 下每token输入价格 (USD)
|
||||
ImageInputPricePerToken float64 // 图片输入 token 价格 (USD),用于多模态 embedding 等图文不同价场景;为 0 时回退到 InputPricePerToken
|
||||
ImageCacheReadPricePerToken float64 // 图片缓存输入价格;无独立价格时沿用缓存读取价
|
||||
OutputPricePerToken float64 // 每token输出价格 (USD)
|
||||
OutputPricePerTokenPriority float64 // priority service tier 下每token输出价格 (USD)
|
||||
CacheCreationPricePerToken float64 // 缓存创建每token价格 (USD)
|
||||
CacheCreationPricePerTokenPriority float64 // priority service tier 下缓存创建每token价格 (USD)
|
||||
CacheCreationPriceExplicit bool // 是否由渠道/区间定价显式设定(为 true 时即使 == 0 也不回退)
|
||||
InputPricePerToken float64 // 每token输入价格 (USD)
|
||||
InputPricePerTokenPriority float64 // priority service tier 下每token输入价格 (USD)
|
||||
ImageInputPricePerToken float64 // 图片输入 token 价格 (USD),用于多模态 embedding 等图文不同价场景;为 0 时回退到 InputPricePerToken
|
||||
ImageCacheReadPricePerToken float64 // 图片缓存输入价格;无独立价格时沿用缓存读取价
|
||||
OutputPricePerToken float64 // 每token输出价格 (USD)
|
||||
OutputPricePerTokenPriority float64 // priority service tier 下每token输出价格 (USD)
|
||||
CacheCreationPricePerToken float64 // 缓存创建每token价格 (USD)
|
||||
CacheCreationPricePerTokenPriority float64 // priority service tier 下缓存创建每token价格 (USD)
|
||||
CacheCreationPriceExplicit bool // 是否由渠道/区间定价显式设定(为 true 时即使 == 0 也不回退)
|
||||
priceOverrides tokenPriceOverrides
|
||||
CacheReadPricePerToken float64 // 缓存读取每token价格 (USD)
|
||||
CacheReadPricePerTokenPriority float64 // priority service tier 下缓存读取每token价格 (USD)
|
||||
FastMultiplier *float64 // 渠道显式 Fast/priority 倍率;nil 时沿用模型目录行为
|
||||
@@ -1454,6 +1455,7 @@ func (s *BillingService) getModelPricingAt(model string, pricingAt time.Time) (*
|
||||
price1h := litellmPricing.CacheCreationInputTokenCostAbove1hr
|
||||
enableBreakdown := price1h > 0 && price1h > price5m
|
||||
return s.applyModelSpecificPricingPolicyEx(model, &ModelPricing{
|
||||
priceOverrides: litellmPricing.priceOverrides,
|
||||
InputPricePerToken: litellmPricing.InputCostPerToken,
|
||||
InputPricePerTokenPriority: litellmPricing.InputCostPerTokenPriority,
|
||||
OutputPricePerToken: litellmPricing.OutputCostPerToken,
|
||||
@@ -1676,13 +1678,19 @@ func (s *BillingService) calculateTokenCost(resolved *ResolvedPricing, input Cos
|
||||
// DeepSeek 模型默认价卡按官方峰谷口径调整:高峰时段(01:00–04:00 与
|
||||
// 06:00–10:00 UTC,仅工作日;北京时间周末全天低谷)按 2× 低谷价计费。
|
||||
// 仅作用于默认价卡(Source=LiteLLM,无分组/渠道自定义定价)——分组/渠道
|
||||
// 自定义定价保持运营者语义,不叠加。先克隆再乘,避免污染共享 fallbackPrices 指针。
|
||||
// 自定义定价及 override_file 显式覆盖的字段不叠加。先克隆再乘,避免污染共享价卡。
|
||||
if resolved.Source == PricingSourceLiteLLM && isDeepSeekModel(input.Model) {
|
||||
if mult := deepseekPeakMultiplierAt(pricingAt); mult > 1 {
|
||||
cloned := *pricing
|
||||
cloned.InputPricePerToken *= mult
|
||||
cloned.OutputPricePerToken *= mult
|
||||
cloned.CacheReadPricePerToken *= mult
|
||||
if !cloned.priceOverrides.input {
|
||||
cloned.InputPricePerToken *= mult
|
||||
}
|
||||
if !cloned.priceOverrides.output {
|
||||
cloned.OutputPricePerToken *= mult
|
||||
}
|
||||
if !cloned.priceOverrides.cacheRead {
|
||||
cloned.CacheReadPricePerToken *= mult
|
||||
}
|
||||
pricing = &cloned
|
||||
}
|
||||
}
|
||||
@@ -1986,7 +1994,7 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing
|
||||
if pricing == nil {
|
||||
return nil
|
||||
}
|
||||
// DeepSeek 模型:无论 JSON/远端价格表给什么价,一律强制官方低谷价
|
||||
// DeepSeek 模型:目录/回退数据使用官方低谷价;override_file 显式覆盖的字段保留。
|
||||
// (Flash 三档为 2026-09-10 官方降价后口径)。这是覆盖远端旧价的关键——远端
|
||||
// 仓库不可改,生产会先拉到旧价,必须在此兜底修正;克隆后再覆盖,避免污染
|
||||
// 共享 fallbackPrices 指针。
|
||||
@@ -1997,16 +2005,18 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing
|
||||
// 对默认价卡另行叠加(分组/渠道自定义定价不叠加)。
|
||||
if forceDeepSeekRates && isDeepSeekModel(model) {
|
||||
cloned := *pricing
|
||||
inputPrice, outputPrice, cacheReadPrice := deepseekFlashOffPeakInputPrice, deepseekFlashOffPeakOutputPrice, deepseekFlashOffPeakCacheRead
|
||||
if isDeepSeekProModel(model) {
|
||||
cloned.InputPricePerToken = deepseekProOffPeakInputPrice
|
||||
cloned.OutputPricePerToken = deepseekProOffPeakOutputPrice
|
||||
cloned.CacheReadPricePerToken = deepseekProOffPeakCacheRead
|
||||
} else {
|
||||
// deepseek-flash(= V4.1-Flash)、deepseek-v4-flash /
|
||||
// deepseek-v4-flash-vision-exp 与其余 deepseek-* 共用 flash 价。
|
||||
cloned.InputPricePerToken = deepseekFlashOffPeakInputPrice
|
||||
cloned.OutputPricePerToken = deepseekFlashOffPeakOutputPrice
|
||||
cloned.CacheReadPricePerToken = deepseekFlashOffPeakCacheRead
|
||||
inputPrice, outputPrice, cacheReadPrice = deepseekProOffPeakInputPrice, deepseekProOffPeakOutputPrice, deepseekProOffPeakCacheRead
|
||||
}
|
||||
if !cloned.priceOverrides.input {
|
||||
cloned.InputPricePerToken = inputPrice
|
||||
}
|
||||
if !cloned.priceOverrides.output {
|
||||
cloned.OutputPricePerToken = outputPrice
|
||||
}
|
||||
if !cloned.priceOverrides.cacheRead {
|
||||
cloned.CacheReadPricePerToken = cacheReadPrice
|
||||
}
|
||||
return &cloned
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// withChatCompletionsMetadataUserID carries the client's top-level
|
||||
// metadata.user_id of a Chat Completions request into the Anthropic body
|
||||
// converted from it. ChatCompletionsRequest and ResponsesRequest have no
|
||||
// metadata field, so the conversion never sets AnthropicRequest.Metadata and
|
||||
// without this the Anthropic request never sees the id the client sent.
|
||||
//
|
||||
// Only a string user_id that ParseMetadataUserID accepts (JSON form with
|
||||
// non-empty device_id and session_id, or the legacy form) is carried, as the
|
||||
// raw JSON string token of the original body, so its bytes do not change.
|
||||
// Every other metadata key is dropped. In every other case anthropicBody is
|
||||
// returned as it is.
|
||||
func withChatCompletionsMetadataUserID(chatBody, anthropicBody []byte) []byte {
|
||||
userID := gjson.GetBytes(chatBody, "metadata.user_id")
|
||||
if userID.Type != gjson.String {
|
||||
return anthropicBody
|
||||
}
|
||||
if parsed := ParseMetadataUserID(userID.String()); parsed == nil || parsed.SessionID == "" {
|
||||
return anthropicBody
|
||||
}
|
||||
out, err := sjson.SetRawBytes(anthropicBody, "metadata", []byte(`{"user_id":`+userID.Raw+`}`))
|
||||
if err != nil {
|
||||
return anthropicBody
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
const (
|
||||
chatMetaSessionID = "3f0c9a52-7b1e-4d6a-9c38-5e2f0a1b7c44"
|
||||
chatMetaJSONUserID = `{"device_id":"device-1","session_id":"` + chatMetaSessionID + `"}`
|
||||
chatMetaLegacyUser = "user_a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2_account__session_" + chatMetaSessionID
|
||||
chatMetaConverted = `{"model":"claude-sonnet-4-5","max_tokens":64,"messages":[{"role":"user","content":"hi"}],"stream":true}`
|
||||
chatMetaChatPrefix = `{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}],`
|
||||
chatMetaNoMetaChat = `{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}]}`
|
||||
chatMetaOnlyUserKey = `{"user_id":`
|
||||
)
|
||||
|
||||
func chatMetaQuote(t *testing.T, s string) string {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(s)
|
||||
require.NoError(t, err)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func TestWithChatCompletionsMetadataUserID_Carries(t *testing.T) {
|
||||
for name, userID := range map[string]string{"json": chatMetaJSONUserID, "legacy": chatMetaLegacyUser} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
quoted := chatMetaQuote(t, userID)
|
||||
chat := []byte(chatMetaChatPrefix + `"metadata":{"user_id":` + quoted + `}}`)
|
||||
out := withChatCompletionsMetadataUserID(chat, []byte(chatMetaConverted))
|
||||
|
||||
require.Equal(t, chatMetaOnlyUserKey+quoted+`}`, gjson.GetBytes(out, "metadata").Raw)
|
||||
require.Equal(t, userID, gjson.GetBytes(out, "metadata.user_id").String())
|
||||
rest, err := sjson.DeleteBytes(out, "metadata")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, chatMetaConverted, string(rest), "everything but metadata is unchanged")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithChatCompletionsMetadataUserID_KeepsEscapesAndOtherKeysOut(t *testing.T) {
|
||||
// The id is carried as the client's own string token, escapes included.
|
||||
userID := `{"device_id":"dév","session_id":"` + chatMetaSessionID + `"}`
|
||||
chat := []byte(chatMetaChatPrefix + `"metadata":{"trace":"x","user_id":"{\"device_id\":\"dév\",\"session_id\":\"` + chatMetaSessionID + `\"}","other":{"a":1}}}`)
|
||||
out := withChatCompletionsMetadataUserID(chat, []byte(chatMetaConverted))
|
||||
require.Equal(t, `{"user_id":"{\"device_id\":\"dév\",\"session_id\":\"`+chatMetaSessionID+`\"}"}`, gjson.GetBytes(out, "metadata").Raw)
|
||||
require.Equal(t, userID, gjson.GetBytes(out, "metadata.user_id").String())
|
||||
require.False(t, gjson.GetBytes(out, "metadata.trace").Exists())
|
||||
require.False(t, gjson.GetBytes(out, "metadata.other").Exists())
|
||||
}
|
||||
|
||||
func TestWithChatCompletionsMetadataUserID_LeavesBodyAlone(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"no metadata": chatMetaNoMetaChat,
|
||||
"metadata string": chatMetaChatPrefix + `"metadata":"x"}`,
|
||||
"metadata array": chatMetaChatPrefix + `"metadata":[{"user_id":` + chatMetaQuote(t, chatMetaJSONUserID) + `}]}`,
|
||||
"metadata null": chatMetaChatPrefix + `"metadata":null}`,
|
||||
"metadata without id": chatMetaChatPrefix + `"metadata":{"trace":"x"}}`,
|
||||
"user_id number": chatMetaChatPrefix + `"metadata":{"user_id":12345}}`,
|
||||
"user_id object": chatMetaChatPrefix + `"metadata":{"user_id":` + chatMetaJSONUserID + `}}`,
|
||||
"user_id array": chatMetaChatPrefix + `"metadata":{"user_id":[` + chatMetaQuote(t, chatMetaJSONUserID) + `]}}`,
|
||||
"user_id null": chatMetaChatPrefix + `"metadata":{"user_id":null}}`,
|
||||
"user_id empty": chatMetaChatPrefix + `"metadata":{"user_id":""}}`,
|
||||
"user_id bare uuid": chatMetaChatPrefix + `"metadata":{"user_id":"` + chatMetaSessionID + `"}}`,
|
||||
"user_id free text": chatMetaChatPrefix + `"metadata":{"user_id":"alice"}}`,
|
||||
"json without device_id": chatMetaChatPrefix + `"metadata":{"user_id":` + chatMetaQuote(t, `{"session_id":"`+chatMetaSessionID+`"}`) + `}}`,
|
||||
"json empty device_id": chatMetaChatPrefix + `"metadata":{"user_id":` + chatMetaQuote(t, `{"device_id":"","session_id":"`+chatMetaSessionID+`"}`) + `}}`,
|
||||
"json without session_id": chatMetaChatPrefix + `"metadata":{"user_id":` + chatMetaQuote(t, `{"device_id":"device-1"}`) + `}}`,
|
||||
"json empty session_id": chatMetaChatPrefix + `"metadata":{"user_id":` + chatMetaQuote(t, `{"device_id":"device-1","session_id":""}`) + `}}`,
|
||||
"json malformed": chatMetaChatPrefix + `"metadata":{"user_id":"{\"device_id\":"}}`,
|
||||
"legacy short session": chatMetaChatPrefix + `"metadata":{"user_id":"user_a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2_account__session_123"}}`,
|
||||
"top-level user only": chatMetaChatPrefix + `"user":` + chatMetaQuote(t, chatMetaJSONUserID) + `}`,
|
||||
}
|
||||
for name, chat := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
out := withChatCompletionsMetadataUserID([]byte(chat), []byte(chatMetaConverted))
|
||||
require.Equal(t, chatMetaConverted, string(out))
|
||||
require.False(t, gjson.GetBytes(out, "metadata").Exists())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func chatMetaStreamUpstream() *httpUpstreamRecorder {
|
||||
return &httpUpstreamRecorder{resp: nativeAnthropicStreamResponse()}
|
||||
}
|
||||
|
||||
func chatMetaRequestBody(userID string) []byte {
|
||||
return []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}],"stream":true,` +
|
||||
`"metadata":{"trace":"x","user_id":` + userID + `}}`)
|
||||
}
|
||||
|
||||
func chatMetaContext(body []byte) *gin.Context {
|
||||
gin.SetMode(gin.TestMode)
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(string(body)))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
return c
|
||||
}
|
||||
|
||||
// The Anthropic-platform path (GatewayService.ForwardAsChatCompletions).
|
||||
func TestForwardAsChatCompletions_CarriesMetadataUserID(t *testing.T) {
|
||||
for name, tc := range map[string]struct {
|
||||
userID string
|
||||
want bool
|
||||
}{
|
||||
"json": {chatMetaQuote(t, chatMetaJSONUserID), true},
|
||||
"legacy": {chatMetaQuote(t, chatMetaLegacyUser), true},
|
||||
"bare id": {chatMetaQuote(t, chatMetaSessionID), false},
|
||||
"number": {`12345`, false},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
body := chatMetaRequestBody(tc.userID)
|
||||
upstream := chatMetaStreamUpstream()
|
||||
svc := &GatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
account := &Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk-test"}}
|
||||
_, err := svc.ForwardAsChatCompletions(context.Background(), chatMetaContext(body), account, body, nil)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, upstream.lastBody)
|
||||
if !tc.want {
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "metadata").Exists(), string(upstream.lastBody))
|
||||
return
|
||||
}
|
||||
require.Equal(t, `{"user_id":`+tc.userID+`}`, gjson.GetBytes(upstream.lastBody, "metadata").Raw, string(upstream.lastBody))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// OAuth accounts keep the id the mimicry synthesizes: the client's id is not carried.
|
||||
func TestForwardAsChatCompletions_OAuthAccountKeepsSynthesizedMetadataUserID(t *testing.T) {
|
||||
forward := func(t *testing.T, body []byte) []byte {
|
||||
t.Helper()
|
||||
upstream := chatMetaStreamUpstream()
|
||||
svc := &GatewayService{
|
||||
cfg: rawChatCompletionsTestConfig(),
|
||||
httpUpstream: upstream,
|
||||
identityService: NewIdentityService(&stubIdentityCache{fingerprint: &Fingerprint{
|
||||
UserAgent: "claude-cli/2.9.0 (external, cli)", ClientID: "test-client", UpdatedAt: time.Now().Unix(),
|
||||
}}),
|
||||
}
|
||||
account := &Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeOAuth, Credentials: map[string]any{"access_token": "tok"}}
|
||||
_, err := svc.ForwardAsChatCompletions(context.Background(), chatMetaContext(body), account, body, nil)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, upstream.lastBody)
|
||||
return upstream.lastBody
|
||||
}
|
||||
|
||||
withID := forward(t, chatMetaRequestBody(chatMetaQuote(t, chatMetaJSONUserID)))
|
||||
withoutID := forward(t, []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}],"stream":true,"metadata":{"trace":"x"}}`))
|
||||
|
||||
require.NotEmpty(t, gjson.GetBytes(withoutID, "metadata.user_id").String(), string(withoutID))
|
||||
require.Equal(t, gjson.GetBytes(withoutID, "metadata").Raw, gjson.GetBytes(withID, "metadata").Raw, string(withID))
|
||||
require.NotContains(t, string(withID), "device-1")
|
||||
}
|
||||
|
||||
// The native Anthropic endpoint path (OpenAIGatewayService.forwardChatCompletionsViaNativeAnthropic).
|
||||
func TestForwardChatCompletionsViaNativeAnthropic_CarriesMetadataUserID(t *testing.T) {
|
||||
for name, tc := range map[string]struct {
|
||||
userID string
|
||||
want bool
|
||||
}{
|
||||
"json": {chatMetaQuote(t, chatMetaJSONUserID), true},
|
||||
"legacy": {chatMetaQuote(t, chatMetaLegacyUser), true},
|
||||
"bare id": {chatMetaQuote(t, chatMetaSessionID), false},
|
||||
"number": {`12345`, false},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
body := chatMetaRequestBody(tc.userID)
|
||||
upstream := chatMetaStreamUpstream()
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
_, err := svc.forwardChatCompletionsViaNativeAnthropic(context.Background(), chatMetaContext(body), nativeAnthropicTestAccount(), body, "")
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, upstream.lastBody)
|
||||
if !tc.want {
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "metadata").Exists(), string(upstream.lastBody))
|
||||
return
|
||||
}
|
||||
require.Equal(t, `{"user_id":`+tc.userID+`}`, gjson.GetBytes(upstream.lastBody, "metadata").Raw, string(upstream.lastBody))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
@@ -268,10 +269,27 @@ func (s *CNProviderQuotaService) queryUsageForAccount(ctx context.Context, accou
|
||||
result.PlanLevel = strings.TrimSpace(gjson.GetBytes(bodyBytes, "current_subscribe_title").String())
|
||||
}
|
||||
result.Tiers = tiers
|
||||
// 2xx 但一个可用窗口都解析不出来,通常意味着上游报文改版/字段改名,而不是
|
||||
// 「额度无限」。必须按失败处理:保留旧快照、不写成功时间;否则下面的缺席
|
||||
// 清理会把 5h/weekly/monthly 全写 nil,调度层看到「没有窗口」就会解除预停调,
|
||||
// 让仍处于耗尽的账号回池撞 429。
|
||||
if len(tiers) == 0 {
|
||||
result.Error = fmt.Sprintf(
|
||||
"quota response for %s contains no recognized usage window (upstream schema may have changed); keeping the previous snapshot",
|
||||
provider)
|
||||
slog.Warn("cn_quota_no_recognized_window",
|
||||
"account_id", account.ID, "provider", provider, "http_status", resp.StatusCode)
|
||||
return result, nil
|
||||
}
|
||||
result.Success = true
|
||||
result.CredentialValid = true
|
||||
|
||||
updates := cnQuotaExtraUpdates(provider, tiers, now)
|
||||
// 只对 5h/weekly/monthly 三档通吃的供应商清理缺席窗口;Command Code 与
|
||||
// Cline 走各自的取舍(抓取失败时保留月度),不在这里处理。
|
||||
if provider == PlatformKimi || provider == PlatformZhipu || provider == PlatformMiniMax || provider == PlatformOpenCodeGo {
|
||||
clearAbsentCNQuotaWindows(provider, tiers, updates)
|
||||
}
|
||||
if err := s.accountRepo.UpdateExtra(ctx, account.ID, updates); err != nil {
|
||||
slog.Warn("cn_quota_persist_failed", "account_id", account.ID, "provider", provider, "error", err)
|
||||
} else {
|
||||
@@ -379,59 +397,119 @@ func zhipuQuotaHost(baseURL string) string {
|
||||
|
||||
// parseKimiUsageTiers 解析 Kimi For Coding 的 /usages 响应。
|
||||
//
|
||||
// - limits[].detail.{limit,remaining,resetTime} → 5h 窗口(取首个 detail)
|
||||
// - usage.{limit,remaining,resetTime} → 周窗口
|
||||
// Kimi 目前并存两种套餐形态:
|
||||
//
|
||||
// utilization = (limit-remaining)/limit*100。
|
||||
// - 老套餐(5h + 7d):limits[].detail.{limit,remaining,resetTime} → 5h
|
||||
// (取首个 detail),顶层 usage.{limit,remaining,resetTime} → 周窗口,
|
||||
// utilization = (limit-remaining)/limit*100。
|
||||
// - 新套餐(5h + 月度):不再有顶层 usage,改由 usages.limit_5h /
|
||||
// usages.limit_7d / usages.limit_month_total / usages.limit_month_code
|
||||
// 以 used_ratio(0-1)+ reset_time 上报。月度 total 与 code 任一耗尽都会
|
||||
// 限流,因此 monthly 取两者较大用量、较早重置时间。
|
||||
//
|
||||
// 两者同时出现时 used_ratio 优先(比 counts 更贴近官方口径),顶层 usage 仅兜底;
|
||||
// usages.limit_5h 只在 limits[] 没有 detail 时补位,避免重复产出 5h 档。
|
||||
func parseKimiUsageTiers(body []byte) []CNQuotaTier {
|
||||
var tiers []CNQuotaTier
|
||||
|
||||
hasFiveHour := false
|
||||
if limits := gjson.GetBytes(body, "limits"); limits.IsArray() {
|
||||
limits.ForEach(func(_, item gjson.Result) bool {
|
||||
detail := item.Get("detail")
|
||||
if !detail.Exists() {
|
||||
return true
|
||||
}
|
||||
limit, _ := cnParseF64(detail.Get("limit").Value())
|
||||
remaining, _ := cnParseF64(detail.Get("remaining").Value())
|
||||
used := limit - remaining
|
||||
if used < 0 {
|
||||
used = 0
|
||||
}
|
||||
var util float64
|
||||
if limit > 0 {
|
||||
util = used / limit * 100
|
||||
// 字段节点存在不等于数值可信:limit/remaining 必须可解析、limit>0、
|
||||
// remaining 落在 [0, limit],否则跳过该条(`{"detail":{}}` 或 limit=0
|
||||
// 不能产出一个「已用 0%」的伪窗口,那会掩盖真实的额度耗尽状态)。
|
||||
limit, okLimit := cnParseF64(detail.Get("limit").Value())
|
||||
remaining, okRemaining := cnParseF64(detail.Get("remaining").Value())
|
||||
if !okLimit || !okRemaining || limit <= 0 || remaining < 0 || remaining > limit {
|
||||
return true
|
||||
}
|
||||
util := (limit - remaining) / limit * 100
|
||||
tiers = append(tiers, CNQuotaTier{
|
||||
Window: "5h",
|
||||
UsedPercent: util,
|
||||
ResetAt: cnNormalizeResetTime(detail.Get("resetTime").Value()),
|
||||
})
|
||||
return false // 取首个 detail 作为 5h 窗口
|
||||
hasFiveHour = true
|
||||
return false // 取首个有效 detail 作为 5h 窗口
|
||||
})
|
||||
}
|
||||
if !hasFiveHour {
|
||||
if tier, ok := kimiUsedRatioTier(body, "limit_5h", "5h"); ok {
|
||||
tiers = append(tiers, tier)
|
||||
hasFiveHour = true
|
||||
}
|
||||
}
|
||||
|
||||
if usage := gjson.GetBytes(body, "usage"); usage.Exists() {
|
||||
limit, _ := cnParseF64(usage.Get("limit").Value())
|
||||
remaining, _ := cnParseF64(usage.Get("remaining").Value())
|
||||
used := limit - remaining
|
||||
if used < 0 {
|
||||
used = 0
|
||||
// 周窗口:usages.limit_7d 优先,顶层 usage(老套餐单数)兜底。
|
||||
if tier, ok := kimiUsedRatioTier(body, "limit_7d", "weekly"); ok {
|
||||
tiers = append(tiers, tier)
|
||||
} else if usage := gjson.GetBytes(body, "usage"); usage.Exists() {
|
||||
limit, okLimit := cnParseF64(usage.Get("limit").Value())
|
||||
remaining, okRemaining := cnParseF64(usage.Get("remaining").Value())
|
||||
if okLimit && okRemaining && limit > 0 && remaining >= 0 && remaining <= limit {
|
||||
tiers = append(tiers, CNQuotaTier{
|
||||
Window: "weekly",
|
||||
UsedPercent: (limit - remaining) / limit * 100,
|
||||
ResetAt: cnNormalizeResetTime(usage.Get("resetTime").Value()),
|
||||
})
|
||||
}
|
||||
var util float64
|
||||
if limit > 0 {
|
||||
util = used / limit * 100
|
||||
}
|
||||
|
||||
// 月度限额(新套餐):total 与 code 是两个**独立**的限流窗口,任一耗尽都会限流。
|
||||
// 用量取两者较大值;重置时间取**较晚**者——取较早会在另一个窗口仍耗尽时提前
|
||||
// 解除预停调(例如 total 到 11-26 才恢复、code 到 11-20 恢复)。宁可晚回池,
|
||||
// 不可提前撞 429。
|
||||
total, hasTotal := kimiUsedRatioTier(body, "limit_month_total", "monthly")
|
||||
code, hasCode := kimiUsedRatioTier(body, "limit_month_code", "monthly")
|
||||
if hasTotal || hasCode {
|
||||
monthly := total
|
||||
if !hasTotal {
|
||||
monthly = code
|
||||
} else if hasCode {
|
||||
if code.UsedPercent > monthly.UsedPercent {
|
||||
monthly.UsedPercent = code.UsedPercent
|
||||
}
|
||||
if code.ResetAt != "" && (monthly.ResetAt == "" || code.ResetAt > monthly.ResetAt) {
|
||||
monthly.ResetAt = code.ResetAt
|
||||
}
|
||||
}
|
||||
tiers = append(tiers, CNQuotaTier{
|
||||
Window: "weekly",
|
||||
UsedPercent: util,
|
||||
ResetAt: cnNormalizeResetTime(usage.Get("resetTime").Value()),
|
||||
})
|
||||
tiers = append(tiers, monthly)
|
||||
}
|
||||
|
||||
return tiers
|
||||
}
|
||||
|
||||
// kimiUsedRatioTier 解析 usages.<key>.{used_ratio,reset_time} 为窗口档位。
|
||||
// used_ratio 是 0-1 比例,输出换算为百分比;键缺失、不可解析或越界返回 false。
|
||||
func kimiUsedRatioTier(body []byte, key, window string) (CNQuotaTier, bool) {
|
||||
node := gjson.GetBytes(body, "usages."+key)
|
||||
if !node.Exists() {
|
||||
return CNQuotaTier{}, false
|
||||
}
|
||||
ratioNode := node.Get("used_ratio")
|
||||
if !ratioNode.Exists() {
|
||||
return CNQuotaTier{}, false
|
||||
}
|
||||
ratio, ok := cnParseF64(ratioNode.Value())
|
||||
if !ok {
|
||||
return CNQuotaTier{}, false
|
||||
}
|
||||
// 必须落在上游声明区间 [0,1]:越界值(例如把百分数 65 直接塞进 used_ratio)
|
||||
// 会算出 6500%,NaN/Inf 同理不可信。
|
||||
if ratio < 0 || ratio > 1 {
|
||||
return CNQuotaTier{}, false
|
||||
}
|
||||
return CNQuotaTier{
|
||||
Window: window,
|
||||
UsedPercent: ratio * 100,
|
||||
ResetAt: cnNormalizeResetTime(node.Get("reset_time").Value()),
|
||||
}, true
|
||||
}
|
||||
|
||||
// parseMiniMaxUsageTiers 解析 MiniMax Token Plan / Coding Plan remains 响应。
|
||||
//
|
||||
// 只取 model_name == "general"(编程套餐),跳过 video。字段是剩余百分比,
|
||||
@@ -574,9 +652,11 @@ func parseZhipuTokenTiers(data gjson.Result) []CNQuotaTier {
|
||||
if limitType != "TOKENS_LIMIT" && limitType != "CREDIT_LIMIT" {
|
||||
return true
|
||||
}
|
||||
percentage := 0.0
|
||||
if p, ok := cnParseF64(item.Get("percentage").Value()); ok {
|
||||
percentage = p
|
||||
// percentage 缺失/非数字/NaN/越界时不能默认 0:那会产出一个「已用 0%」的
|
||||
// 合法窗口,既掩盖真实耗尽状态,也会被缺席清理当成有效快照落库。
|
||||
percentage, okPercentage := cnParseF64(item.Get("percentage").Value())
|
||||
if !okPercentage || percentage < 0 || percentage > 100 {
|
||||
return true
|
||||
}
|
||||
var (
|
||||
resetMs int64
|
||||
@@ -671,6 +751,35 @@ func cnQuotaExtraUpdates(provider string, tiers []CNQuotaTier, now time.Time) ma
|
||||
return updates
|
||||
}
|
||||
|
||||
// clearAbsentCNQuotaWindows 把本次探测缺席的窗口显式写 nil(JSONB 合并语义下等于
|
||||
// 移除按键):账号 extra 的更新走 `extra || $1`,只"不写"会保留旧值。上游改套餐
|
||||
// (Kimi 老套餐 7d → 新套餐月度)后旧窗口不再上报,不清理就会把切换前的用量永久
|
||||
// 冻结在快照里(生产实测冻结 13 天,列表一直显示过期的 7D 用量)。
|
||||
//
|
||||
// 仅供 5h/weekly/monthly 三档通吃的供应商调用;Command Code / Cline 有自己的
|
||||
// 取舍(周期端点抓取失败时保留月度值),不在此列。
|
||||
func clearAbsentCNQuotaWindows(provider string, tiers []CNQuotaTier, updates map[string]any) {
|
||||
present := make(map[string]CNQuotaTier, len(tiers))
|
||||
for _, tier := range tiers {
|
||||
present[tier.Window] = tier
|
||||
}
|
||||
for _, window := range []struct{ name, used, reset string }{
|
||||
{"5h", cnExtraSuffix5hUsed, cnExtraSuffix5hReset},
|
||||
{"weekly", cnExtraSuffixWeeklyUsed, cnExtraSuffixWeeklyReset},
|
||||
{"monthly", cnExtraSuffixMonthlyUsed, cnExtraSuffixMonthlyReset},
|
||||
} {
|
||||
tier, ok := present[window.name]
|
||||
if !ok {
|
||||
updates[cnExtraKey(provider, window.used)] = nil
|
||||
updates[cnExtraKey(provider, window.reset)] = nil
|
||||
continue
|
||||
}
|
||||
if tier.ResetAt == "" {
|
||||
updates[cnExtraKey(provider, window.reset)] = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// parseOpenCodeGoUsageTiers 解析 OpenCode Go GET /usage 响应。
|
||||
//
|
||||
// 结构对齐 cc-switch extractor:
|
||||
@@ -718,24 +827,37 @@ func parseOpenCodeGoUsageTiers(body []byte) []CNQuotaTier {
|
||||
|
||||
// cnParseF64 把 JSON 数值或字符串解析为 float64(兼容 "100" 与 100)。
|
||||
func cnParseF64(raw any) (float64, bool) {
|
||||
var value float64
|
||||
switch v := raw.(type) {
|
||||
case float64:
|
||||
return v, true
|
||||
value = v
|
||||
case float32:
|
||||
return float64(v), true
|
||||
value = float64(v)
|
||||
case int:
|
||||
return float64(v), true
|
||||
value = float64(v)
|
||||
case int64:
|
||||
return float64(v), true
|
||||
value = float64(v)
|
||||
case json.Number:
|
||||
f, err := v.Float64()
|
||||
return f, err == nil
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
value = f
|
||||
case string:
|
||||
f, err := strconv.ParseFloat(strings.TrimSpace(v), 64)
|
||||
return f, err == nil
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
value = f
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
// strconv.ParseFloat 接受 "NaN"/"Inf",JSON 的 1e999 也会得到 +Inf;
|
||||
// 这类值参与百分比与阈值比较会让停调判定失效,一律视为不可解析。
|
||||
if math.IsNaN(value) || math.IsInf(value, 0) {
|
||||
return 0, false
|
||||
}
|
||||
return value, true
|
||||
}
|
||||
|
||||
// cnNormalizeResetTime 把上游重置时间(ISO8601 字符串 / 秒级 / 毫秒级数字)归一化为
|
||||
|
||||
@@ -103,8 +103,84 @@ func TestParseKimiUsageTiers_LimitZero(t *testing.T) {
|
||||
t.Parallel()
|
||||
body := []byte(`{"limits":[{"detail":{"limit":0,"remaining":0,"resetTime":"2026-08-14T15:00:00Z"}}]}`)
|
||||
tiers := parseKimiUsageTiers(body)
|
||||
// limit=0 无法计算利用率:不能产出「已用 0%」的伪窗口(那会把额度耗尽
|
||||
// 显示成完全没用),该条目应被跳过。
|
||||
require.Len(t, tiers, 0)
|
||||
}
|
||||
|
||||
// TestParseKimiUsageTiers_MonthlyPlan 新套餐形态(5h + 月度限额):不再有顶层
|
||||
// usage,改由 usages.limit_5h / limit_month_total / limit_month_code 以
|
||||
// used_ratio(0-1)+ reset_time 上报。monthly 取两条月度键的较大用量 + 较早重置。
|
||||
func TestParseKimiUsageTiers_MonthlyPlan(t *testing.T) {
|
||||
t.Parallel()
|
||||
body := []byte(`{
|
||||
"limits": [{
|
||||
"window": {"duration": 300, "timeUnit": "TIME_UNIT_MINUTE"},
|
||||
"detail": {"limit": "100", "used": "10", "remaining": "90", "resetTime": "2026-11-13T16:10:29.523075Z"}
|
||||
}],
|
||||
"usages": {
|
||||
"limit_5h": {"used_ratio": 0.0982, "reset_time": "2026-11-13T16:10:28Z"},
|
||||
"limit_month_total": {"used_ratio": 0.6564, "reset_time": "2026-11-26T00:00:00Z"},
|
||||
"limit_month_code": {"used_ratio": 0.6252, "reset_time": "2026-11-26T00:00:00Z"}
|
||||
}
|
||||
}`)
|
||||
tiers := parseKimiUsageTiers(body)
|
||||
require.Len(t, tiers, 2, "新套餐应为 5h + monthly,且不得产出已废弃的 weekly")
|
||||
|
||||
require.Equal(t, "5h", tiers[0].Window)
|
||||
require.InDelta(t, 10.0, tiers[0].UsedPercent, 1e-9, "5h 用 limits[].detail 的绝对计数")
|
||||
require.Equal(t, "2026-11-13T16:10:29Z", tiers[0].ResetAt)
|
||||
|
||||
require.Equal(t, "monthly", tiers[1].Window)
|
||||
require.InDelta(t, 65.64, tiers[1].UsedPercent, 1e-9, "used_ratio 0-1 换算为百分比")
|
||||
require.Equal(t, "2026-11-26T00:00:00Z", tiers[1].ResetAt)
|
||||
}
|
||||
|
||||
// TestParseKimiUsageTiers_MonthlyPicksMaxUsage total/code 任一耗尽都会限流:
|
||||
// monthly 取较大用量;重置时间取较早者(先恢复额度,避免过度停调)。
|
||||
func TestParseKimiUsageTiers_MonthlyPicksMaxUsage(t *testing.T) {
|
||||
t.Parallel()
|
||||
body := []byte(`{"usages":{
|
||||
"limit_month_total":{"used_ratio":0.4,"reset_time":"2026-11-26T00:00:00Z"},
|
||||
"limit_month_code":{"used_ratio":0.9,"reset_time":"2026-11-20T00:00:00Z"}}}`)
|
||||
tiers := parseKimiUsageTiers(body)
|
||||
require.Len(t, tiers, 1)
|
||||
require.InDelta(t, 0.0, tiers[0].UsedPercent, 1e-9)
|
||||
require.Equal(t, "monthly", tiers[0].Window)
|
||||
require.InDelta(t, 90.0, tiers[0].UsedPercent, 1e-9)
|
||||
// total 与 code 是两个独立限流窗口:reset 必须取较晚者,否则 code 先到期的
|
||||
// 11-20 会让仍处于 40% 的 total 窗口提前放行。
|
||||
require.Equal(t, "2026-11-26T00:00:00Z", tiers[0].ResetAt)
|
||||
|
||||
// 两窗口同为 100% 时也不得取更早的 reset。
|
||||
bothFull := parseKimiUsageTiers([]byte(`{"usages":{
|
||||
"limit_month_total":{"used_ratio":1,"reset_time":"2026-11-26T00:00:00Z"},
|
||||
"limit_month_code":{"used_ratio":1,"reset_time":"2026-11-20T00:00:00Z"}}}`))
|
||||
require.Len(t, bothFull, 1)
|
||||
require.Equal(t, "2026-11-26T00:00:00Z", bothFull[0].ResetAt)
|
||||
|
||||
onlyCode := parseKimiUsageTiers([]byte(`{"usages":{"limit_month_code":{"used_ratio":0.5,"reset_time":"2026-11-20T00:00:00Z"}}}`))
|
||||
require.Len(t, onlyCode, 1)
|
||||
require.Equal(t, "monthly", onlyCode[0].Window)
|
||||
require.InDelta(t, 50.0, onlyCode[0].UsedPercent, 1e-9)
|
||||
}
|
||||
|
||||
// TestParseKimiUsageTiers_LegacyWithUsedRatio 老套餐(顶层 usage)同时携带
|
||||
// usages.limit_7d 时,weekly 以 used_ratio 为准、不重复产出 weekly 档。
|
||||
func TestParseKimiUsageTiers_LegacyWithUsedRatio(t *testing.T) {
|
||||
t.Parallel()
|
||||
body := []byte(`{
|
||||
"usage": {"limit": "100", "remaining": "80", "resetTime": "2026-10-07T05:04:39.713183Z"},
|
||||
"usages": {
|
||||
"limit_5h": {"used_ratio": 0, "reset_time": "2026-10-04T11:04:38Z"},
|
||||
"limit_7d": {"used_ratio": 0.203912, "reset_time": "2026-10-07T05:04:38Z"}
|
||||
}
|
||||
}`)
|
||||
tiers := parseKimiUsageTiers(body)
|
||||
require.Len(t, tiers, 2)
|
||||
require.Equal(t, "5h", tiers[0].Window)
|
||||
require.Equal(t, "weekly", tiers[1].Window)
|
||||
require.InDelta(t, 20.3912, tiers[1].UsedPercent, 1e-9)
|
||||
require.Equal(t, "2026-10-07T05:04:38Z", tiers[1].ResetAt)
|
||||
}
|
||||
|
||||
// TestParseZhipuTokenTiers_UnitClassification 显式 unit(3=5h / 6=weekly)优先分类,
|
||||
@@ -231,6 +307,107 @@ func TestCNQuotaExtraUpdates(t *testing.T) {
|
||||
require.Equal(t, now.Format(time.RFC3339), updates["kimi_usage_updated_at"])
|
||||
}
|
||||
|
||||
// 缺席窗口必须显式写 nil:extra 走 JSONB 合并(`extra || $1`),只"不写"会保留
|
||||
// 旧值。Kimi 老套餐 → 新套餐(月度)切换后 weekly 不再上报,不清理就会把切换前
|
||||
// 的用量永久冻结在快照里(生产实测冻结 13 天)。
|
||||
func TestCNQuotaExtraUpdatesClearsAbsentWindows(t *testing.T) {
|
||||
t.Parallel()
|
||||
now := time.Date(2026, 11, 13, 0, 0, 0, 0, time.UTC)
|
||||
tiers := []CNQuotaTier{
|
||||
{Window: "5h", UsedPercent: 10, ResetAt: "2026-11-13T16:10:29Z"},
|
||||
{Window: "monthly", UsedPercent: 65.64, ResetAt: "2026-11-26T00:00:00Z"},
|
||||
}
|
||||
updates := cnQuotaExtraUpdates(PlatformKimi, tiers, now)
|
||||
clearAbsentCNQuotaWindows(PlatformKimi, tiers, updates)
|
||||
|
||||
value, present := updates["kimi_weekly_used_percent"]
|
||||
require.True(t, present, "缺席的 weekly 必须显式出现在更新里")
|
||||
require.Nil(t, value)
|
||||
_, resetPresent := updates["kimi_weekly_reset_at"]
|
||||
require.True(t, resetPresent)
|
||||
|
||||
require.Equal(t, 10.0, updates["kimi_5h_used_percent"])
|
||||
require.Equal(t, 65.64, updates["kimi_monthly_used_percent"])
|
||||
require.Equal(t, "2026-11-26T00:00:00Z", updates["kimi_monthly_reset_at"])
|
||||
}
|
||||
|
||||
// TestParseKimiUsageTiers_RejectsMalformedWindows 受损/改版结构不得产出伪窗口。
|
||||
// 这类窗口一旦被当成有效快照落库,缺席清理会把其他窗口写成 nil,
|
||||
// 调度层看到「没有窗口」就会解除预停调。
|
||||
func TestParseKimiUsageTiers_RejectsMalformedWindows(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := map[string]struct {
|
||||
body []byte
|
||||
}{
|
||||
"empty object": {[]byte(`{}`)},
|
||||
"empty detail": {[]byte(`{"limits":[{"detail":{}}]}`)},
|
||||
"limit zero": {[]byte(`{"limits":[{"detail":{"limit":0,"remaining":0}}]}`)},
|
||||
"remaining exceeds": {[]byte(`{"limits":[{"detail":{"limit":100,"remaining":200}}]}`)},
|
||||
"limit not a number": {[]byte(`{"limits":[{"detail":{"limit":"abc","remaining":"1"}}]}`)},
|
||||
"empty usage": {[]byte(`{"usage":{}}`)},
|
||||
"ratio out of range": {[]byte(`{"usages":{"limit_5h":{"used_ratio":65}}}`)},
|
||||
"ratio NaN": {[]byte(`{"usages":{"limit_5h":{"used_ratio":"NaN"}}}`)},
|
||||
"ratio negative": {[]byte(`{"usages":{"limit_5h":{"used_ratio":-0.2}}}`)},
|
||||
"renamed top level key": {[]byte(`{"limits_v2":[{"detail":{"limit":100,"remaining":50}}]}`)},
|
||||
}
|
||||
for name, tc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
tiers := parseKimiUsageTiers(tc.body)
|
||||
require.Empty(t, tiers, "受损结构不得产出窗口:%s", string(tc.body))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseKimiUsageTiers_KeepsLegalEdgeValues 合法边界(0%、满额、单窗口、整数)不得被误伤。
|
||||
func TestParseKimiUsageTiers_KeepsLegalEdgeValues(t *testing.T) {
|
||||
t.Parallel()
|
||||
// remaining == limit → 合法的 0%。
|
||||
tiers := parseKimiUsageTiers([]byte(`{"limits":[{"detail":{"limit":100,"remaining":100}}]}`))
|
||||
require.Len(t, tiers, 1)
|
||||
require.InDelta(t, 0.0, tiers[0].UsedPercent, 1e-9)
|
||||
|
||||
// remaining == 0 → 100%。
|
||||
tiers = parseKimiUsageTiers([]byte(`{"limits":[{"detail":{"limit":100,"remaining":0}}]}`))
|
||||
require.Len(t, tiers, 1)
|
||||
require.InDelta(t, 100.0, tiers[0].UsedPercent, 1e-9)
|
||||
|
||||
// used_ratio == 0 / 1 同样合法。
|
||||
tiers = parseKimiUsageTiers([]byte(`{"usages":{"limit_5h":{"used_ratio":0}}}`))
|
||||
require.Len(t, tiers, 1)
|
||||
require.InDelta(t, 0.0, tiers[0].UsedPercent, 1e-9)
|
||||
|
||||
tiers = parseKimiUsageTiers([]byte(`{"usages":{"limit_5h":{"used_ratio":1}}}`))
|
||||
require.Len(t, tiers, 1)
|
||||
require.InDelta(t, 100.0, tiers[0].UsedPercent, 1e-9)
|
||||
|
||||
// 首个 detail 坏、后续合法 → 采用首个有效条目。
|
||||
tiers = parseKimiUsageTiers([]byte(`{"limits":[{"detail":{}},{"detail":{"limit":100,"remaining":60}}]}`))
|
||||
require.Len(t, tiers, 1)
|
||||
require.InDelta(t, 40.0, tiers[0].UsedPercent, 1e-9)
|
||||
}
|
||||
|
||||
// TestParseZhipuTokenTiers_SkipsMissingPercentage percentage 缺失/非法不得伪造 0% 窗口。
|
||||
func TestParseZhipuTokenTiers_SkipsMissingPercentage(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := map[string]struct {
|
||||
body string
|
||||
wantTiers int
|
||||
}{
|
||||
"missing percentage": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3}]}`, 0},
|
||||
"non numeric": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":"abc"}]}`, 0},
|
||||
"negative": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":-5}]}`, 0},
|
||||
"over 100": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":120}]}`, 0},
|
||||
"legal zero": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":0}]}`, 1},
|
||||
"legal five hour": {`{"limits":[{"type":"TOKENS_LIMIT","unit":3,"percentage":42}]}`, 1},
|
||||
}
|
||||
for name, tc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
tiers := parseZhipuTokenTiers(gjson.Parse(tc.body))
|
||||
require.Len(t, tiers, tc.wantTiers, "输入:%s", tc.body)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseOpenCodeGoUsageTiers(t *testing.T) {
|
||||
t.Parallel()
|
||||
body := []byte(`{
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// WithResolvedTargetPlatform stores the concrete provider chosen for a request
|
||||
@@ -73,6 +75,33 @@ func RequestedPublicModelFromContext(ctx context.Context) (string, bool) {
|
||||
return model, true
|
||||
}
|
||||
|
||||
// compositeClientModel returns the public model the client asked for when a
|
||||
// composite route sent a different model upstream, and fallback otherwise. The
|
||||
// response reports that public name whatever model the upstream says served it.
|
||||
func compositeClientModel(ctx context.Context, fallback string) string {
|
||||
publicModel, ok := RequestedPublicModelFromContext(ctx)
|
||||
if !ok {
|
||||
return fallback
|
||||
}
|
||||
if upstreamModel, ok := ResolvedUpstreamModelFromContext(ctx); !ok || upstreamModel == publicModel {
|
||||
return fallback
|
||||
}
|
||||
return publicModel
|
||||
}
|
||||
|
||||
// restoreCompositeClientModel reports the client's public model in an Anthropic
|
||||
// response body when a composite route rewrote the model.
|
||||
func restoreCompositeClientModel(ctx context.Context, body []byte) []byte {
|
||||
clientModel := compositeClientModel(ctx, "")
|
||||
if clientModel == "" || !gjson.GetBytes(body, "model").Exists() {
|
||||
return body
|
||||
}
|
||||
if rewritten, err := sjson.SetBytes(body, "model", clientModel); err == nil {
|
||||
return rewritten
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func CompositeRouteSourceFromContext(ctx context.Context) (string, bool) {
|
||||
if ctx == nil {
|
||||
return "", false
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// publicModelRoute serves requests for public-model with claude-opus-5-5.
|
||||
func publicModelRoute() CompositeModelRoute {
|
||||
return CompositeModelRoute{
|
||||
ID: 1,
|
||||
GroupID: 11,
|
||||
PublicModel: "public-model",
|
||||
MatchType: CompositeRouteMatchExact,
|
||||
TargetPlatform: PlatformAnthropic,
|
||||
UpstreamModel: "claude-opus-5-5",
|
||||
Endpoint: CompositeRouteEndpointAny,
|
||||
Priority: 100,
|
||||
Enabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
// routeCompositeBody resolves body's model against route and rewrites the
|
||||
// model the way the composite middleware does before any handler runs.
|
||||
func routeCompositeBody(t *testing.T, route CompositeModelRoute, endpoint string, body []byte) (context.Context, []byte) {
|
||||
t.Helper()
|
||||
resolver := NewCompositeRouteResolver(compositeRouteRepoStub{routes: []CompositeModelRoute{route}})
|
||||
decision, err := resolver.Resolve(context.Background(), route.GroupID, gjson.GetBytes(body, "model").String(), endpoint)
|
||||
require.NoError(t, err)
|
||||
require.True(t, decision.Matched)
|
||||
body, err = sjson.SetBytes(body, "model", decision.UpstreamModel)
|
||||
require.NoError(t, err)
|
||||
return WithCompositeRouteDecision(context.Background(), decision), body
|
||||
}
|
||||
|
||||
func anthropicMessageStartModel(t *testing.T, sse string) string {
|
||||
t.Helper()
|
||||
for _, line := range strings.Split(sse, "\n") {
|
||||
data, ok := strings.CutPrefix(line, "data: ")
|
||||
if ok && gjson.Get(data, "type").String() == "message_start" {
|
||||
return gjson.Get(data, "message.model").String()
|
||||
}
|
||||
}
|
||||
t.Fatalf("no message_start event in stream:\n%s", sse)
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestCompositeRouteRestoresPublicModelOnAnthropicForward(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
accounts := map[string]func() *Account{
|
||||
"oauth": newAnthropicOAuthAccountForPartialUsageTest,
|
||||
"apikey-passthrough": newAnthropicAPIKeyAccountForTest,
|
||||
}
|
||||
for accountName, newAccount := range accounts {
|
||||
for _, stream := range []bool{false, true} {
|
||||
t.Run(accountName+"/stream="+strconv.FormatBool(stream), func(t *testing.T) {
|
||||
client := []byte(`{"model":"public-model","max_tokens":16,"stream":` + strconv.FormatBool(stream) +
|
||||
`,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
ctx, body := routeCompositeBody(t, publicModelRoute(), CompositeRouteEndpointMessages, client)
|
||||
|
||||
// The upstream reports its own dated id: the client still sees
|
||||
// the public name it asked for.
|
||||
upstreamBody := `{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5-20260901","content":[{"type":"text","text":"hi"}],"usage":{"input_tokens":1,"output_tokens":1}}`
|
||||
contentType := "application/json"
|
||||
if stream {
|
||||
upstreamBody = strings.Join([]string{
|
||||
`event: message_start`,
|
||||
`data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5-20260901","content":[],"usage":{"input_tokens":1}}}`,
|
||||
"",
|
||||
`event: message_delta`,
|
||||
`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`,
|
||||
"",
|
||||
`event: message_stop`,
|
||||
`data: {"type":"message_stop"}`,
|
||||
"",
|
||||
"",
|
||||
}, "\n")
|
||||
contentType = "text/event-stream"
|
||||
}
|
||||
upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{contentType}},
|
||||
Body: io.NopCloser(strings.NewReader(upstreamBody)),
|
||||
}}
|
||||
svc := newForwardPartialUsageServiceForTest(upstream)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil).WithContext(ctx)
|
||||
parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), PlatformAnthropic)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = svc.Forward(ctx, c, newAccount(), parsed)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, "claude-opus-5-5", gjson.GetBytes(upstream.lastBody, "model").String())
|
||||
if stream {
|
||||
require.Equal(t, "public-model", anthropicMessageStartModel(t, rec.Body.String()))
|
||||
} else {
|
||||
require.Equal(t, "public-model", gjson.GetBytes(rec.Body.Bytes(), "model").String())
|
||||
require.Equal(t, "hi", gjson.GetBytes(rec.Body.Bytes(), "content.0.text").String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompositeRouteRestoresPublicModelOnResponsesBridge(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
route := publicModelRoute()
|
||||
route.TargetPlatform = PlatformOpenAI
|
||||
route.UpstreamModel = "gpt-5.6-sol"
|
||||
for _, stream := range []bool{false, true} {
|
||||
t.Run("stream="+strconv.FormatBool(stream), func(t *testing.T) {
|
||||
client := []byte(`{"model":"public-model","max_tokens":16,"stream":` + strconv.FormatBool(stream) +
|
||||
`,"messages":[{"role":"user","content":"hello"}]}`)
|
||||
ctx, body := routeCompositeBody(t, route, CompositeRouteEndpointMessages, client)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(string(body))).WithContext(ctx)
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
upstream := &httpUpstreamRecorder{resp: openAICompatSSECompletedResponse("resp_route", route.UpstreamModel)}
|
||||
upstream.resp.Body = io.NopCloser(io.MultiReader(
|
||||
strings.NewReader(`data: {"type":"response.created","response":{"id":"resp_route","model":"`+route.UpstreamModel+`"}}`+"\n\n"),
|
||||
upstream.resp.Body,
|
||||
))
|
||||
svc := &OpenAIGatewayService{httpUpstream: upstream, cfg: rawChatCompletionsTestConfig()}
|
||||
|
||||
_, err := svc.ForwardAsAnthropic(ctx, c, rawGPT56ResponsesOAuthAccount(route.UpstreamModel, route.UpstreamModel), body, "", "")
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, route.UpstreamModel, gjson.GetBytes(upstream.lastBody, "model").String())
|
||||
if stream {
|
||||
require.Equal(t, "public-model", anthropicMessageStartModel(t, rec.Body.String()))
|
||||
} else {
|
||||
require.Equal(t, "public-model", gjson.GetBytes(rec.Body.Bytes(), "model").String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompositeRouteRestoresPublicModelOnChatCompletionsBridge(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
route := publicModelRoute()
|
||||
route.TargetPlatform = PlatformOpenAI
|
||||
route.UpstreamModel = "gpt-5.6-luna"
|
||||
for _, stream := range []bool{false, true} {
|
||||
t.Run("stream="+strconv.FormatBool(stream), func(t *testing.T) {
|
||||
client := []byte(`{"model":"public-model","max_tokens":16,"messages":[{"role":"user","content":"hello"}],"stream":` + strconv.FormatBool(stream) + `}`)
|
||||
ctx, body := routeCompositeBody(t, route, CompositeRouteEndpointMessages, client)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(string(body))).WithContext(ctx)
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
upstreamBody := `{"id":"chatcmpl_route","object":"chat.completion","model":"gpt-5.6-luna","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}`
|
||||
contentType := "application/json"
|
||||
if stream {
|
||||
upstreamBody = strings.Join([]string{
|
||||
`data: {"id":"chatcmpl_route","object":"chat.completion.chunk","model":"gpt-5.6-luna","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"},"finish_reason":null}]}`,
|
||||
"",
|
||||
`data: {"id":"chatcmpl_route","object":"chat.completion.chunk","model":"gpt-5.6-luna","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}`,
|
||||
"",
|
||||
"data: [DONE]",
|
||||
"",
|
||||
}, "\n")
|
||||
contentType = "text/event-stream"
|
||||
}
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{contentType}},
|
||||
Body: io.NopCloser(strings.NewReader(upstreamBody)),
|
||||
}}
|
||||
account := forceChatMessagesFallbackAccount()
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
|
||||
_, err := svc.ForwardAsAnthropic(ctx, c, account, body, "", "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "gpt-5.6-luna", gjson.GetBytes(upstream.lastBody, "model").String())
|
||||
if stream {
|
||||
require.Equal(t, "public-model", anthropicMessageStartModel(t, rec.Body.String()))
|
||||
} else {
|
||||
require.Equal(t, "public-model", gjson.GetBytes(rec.Body.Bytes(), "model").String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreCompositeClientModelOnlyWhenRouteRewroteModel(t *testing.T) {
|
||||
body := []byte(`{"id":"msg_1","type":"message","model":"claude-opus-5-5-20260901"}`)
|
||||
route := publicModelRoute()
|
||||
|
||||
renamedCtx, _ := routeCompositeBody(t, route, CompositeRouteEndpointMessages, []byte(`{"model":"public-model"}`))
|
||||
require.Equal(t, "public-model", gjson.GetBytes(restoreCompositeClientModel(renamedCtx, body), "model").String())
|
||||
require.Equal(t, "public-model", compositeClientModel(renamedCtx, "claude-opus-5-5"))
|
||||
|
||||
route.PublicModel = route.UpstreamModel
|
||||
sameCtx, _ := routeCompositeBody(t, route, CompositeRouteEndpointMessages, []byte(`{"model":"claude-opus-5-5"}`))
|
||||
require.Equal(t, string(body), string(restoreCompositeClientModel(sameCtx, body)))
|
||||
require.Equal(t, "claude-opus-5-5", compositeClientModel(sameCtx, "claude-opus-5-5"))
|
||||
|
||||
require.Equal(t, string(body), string(restoreCompositeClientModel(context.Background(), body)))
|
||||
require.Equal(t, "claude-opus-5-5", compositeClientModel(context.Background(), "claude-opus-5-5"))
|
||||
|
||||
noModel := []byte(`{"type":"error"}`)
|
||||
require.Equal(t, string(noModel), string(restoreCompositeClientModel(renamedCtx, noModel)))
|
||||
}
|
||||
|
||||
func forwardCompositeAnthropicStream(t *testing.T, newAccount func() *Account, upstreamSSE string) string {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
client := []byte(`{"model":"public-model","max_tokens":16,"stream":true,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
ctx, body := routeCompositeBody(t, publicModelRoute(), CompositeRouteEndpointMessages, client)
|
||||
upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(upstreamSSE)),
|
||||
}}
|
||||
svc := newForwardPartialUsageServiceForTest(upstream)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil).WithContext(ctx)
|
||||
parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), PlatformAnthropic)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = svc.Forward(ctx, c, newAccount(), parsed)
|
||||
require.NoError(t, err)
|
||||
return rec.Body.String()
|
||||
}
|
||||
|
||||
func anthropicStreamEventData(t *testing.T, sse, eventType string) string {
|
||||
t.Helper()
|
||||
for _, line := range strings.Split(sse, "\n") {
|
||||
data, ok := strings.CutPrefix(line, "data:")
|
||||
data = strings.TrimSpace(data)
|
||||
if ok && gjson.Get(data, "type").String() == eventType {
|
||||
return data
|
||||
}
|
||||
}
|
||||
t.Fatalf("no %s event in stream:\n%s", eventType, sse)
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestCompositeRouteStreamRewritesOnlyMessageStartModel(t *testing.T) {
|
||||
accounts := map[string]func() *Account{
|
||||
"oauth": newAnthropicOAuthAccountForPartialUsageTest,
|
||||
"apikey-passthrough": newAnthropicAPIKeyAccountForTest,
|
||||
}
|
||||
for accountName, newAccount := range accounts {
|
||||
t.Run(accountName, func(t *testing.T) {
|
||||
sse := forwardCompositeAnthropicStream(t, newAccount, strings.Join([]string{
|
||||
`event: message_start`,
|
||||
`data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5-20260901","content":[],"usage":{"input_tokens":1}}}`,
|
||||
"",
|
||||
`event: ping`,
|
||||
`data: {"type":"ping","message":{"model":"other-model"}}`,
|
||||
"",
|
||||
`event: message_delta`,
|
||||
`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`,
|
||||
"",
|
||||
`event: message_stop`,
|
||||
`data: {"type":"message_stop"}`,
|
||||
"",
|
||||
"",
|
||||
}, "\n"))
|
||||
|
||||
require.Equal(t, "public-model", gjson.Get(anthropicStreamEventData(t, sse, "message_start"), "message.model").String())
|
||||
require.Equal(t, "other-model", gjson.Get(anthropicStreamEventData(t, sse, "ping"), "message.model").String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompositeRoutePassthroughStreamKeepsMessageStartWithoutModel(t *testing.T) {
|
||||
sse := forwardCompositeAnthropicStream(t, newAnthropicAPIKeyAccountForTest, strings.Join([]string{
|
||||
`event: message_start`,
|
||||
`data:{"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"usage":{"input_tokens":1}}}`,
|
||||
"",
|
||||
`event: message_stop`,
|
||||
`data: {"type":"message_stop"}`,
|
||||
"",
|
||||
"",
|
||||
}, "\n"))
|
||||
|
||||
require.False(t, gjson.Get(anthropicStreamEventData(t, sse, "message_start"), "message.model").Exists())
|
||||
}
|
||||
@@ -21,12 +21,14 @@ func GroupUsageTimezoneName() string {
|
||||
|
||||
// GroupUsageTodayStart 返回指定时刻在服务端配置时区内的自然日 UTC 起点。
|
||||
func GroupUsageTodayStart(at time.Time) time.Time {
|
||||
return appTimezone.StartOfDay(at).UTC()
|
||||
year, month, day := at.In(appTimezone.Location()).Date()
|
||||
return groupUsageDayStart(year, month, day).UTC()
|
||||
}
|
||||
|
||||
// GroupUsageYesterdayStart 返回指定时刻前一个本地日历日的 UTC 起点。
|
||||
func GroupUsageYesterdayStart(at time.Time) time.Time {
|
||||
return appTimezone.StartOfDay(at).AddDate(0, 0, -1).UTC()
|
||||
// 任一本地日至少 22 小时,当日起点前 12 小时必落在前一个日历日内。
|
||||
return GroupUsageTodayStart(GroupUsageTodayStart(at).Add(-12 * time.Hour))
|
||||
}
|
||||
|
||||
// GroupUsageDate 返回指定时刻在服务端配置时区内的日期。
|
||||
@@ -34,7 +36,44 @@ func GroupUsageDate(at time.Time) string {
|
||||
return at.In(appTimezone.Location()).Format(groupUsageDateFormat)
|
||||
}
|
||||
|
||||
// ParseGroupUsageDate 解析服务端配置时区内的日期并返回其零点。
|
||||
// ParseGroupUsageDate 解析服务端配置时区内的日期并返回该日期的起点。
|
||||
func ParseGroupUsageDate(value string) (time.Time, error) {
|
||||
return appTimezone.ParseInLocation(groupUsageDateFormat, value)
|
||||
date, err := time.Parse(groupUsageDateFormat, value)
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
year, month, day := date.Date()
|
||||
return groupUsageDayStart(year, month, day), nil
|
||||
}
|
||||
|
||||
// groupUsageDayStart 返回本地日期 year-month-day 的第一个时刻(服务端配置时区)。
|
||||
// 夏令时在零点跳变的日期,00:00 可能不存在或出现两次,此时返回该日期实际开始的时刻。
|
||||
func groupUsageDayStart(year int, month time.Month, day int) time.Time {
|
||||
loc := appTimezone.Location()
|
||||
target := groupUsageDateOrdinal(year, month, day)
|
||||
start := time.Date(year, month, day, 0, 0, 0, 0, loc)
|
||||
if localGroupUsageDateOrdinal(start) == target && localGroupUsageDateOrdinal(start.Add(-time.Nanosecond)) < target {
|
||||
return start
|
||||
}
|
||||
// 在 [前一日正午, 当日正午] 内二分出本地日期首次到达目标日期的时刻。
|
||||
low := time.Date(year, month, day-1, 12, 0, 0, 0, loc)
|
||||
high := time.Date(year, month, day, 12, 0, 0, 0, loc)
|
||||
for high.Sub(low) > time.Nanosecond {
|
||||
mid := low.Add(high.Sub(low) / 2)
|
||||
if localGroupUsageDateOrdinal(mid) >= target {
|
||||
high = mid
|
||||
} else {
|
||||
low = mid
|
||||
}
|
||||
}
|
||||
return high
|
||||
}
|
||||
|
||||
func localGroupUsageDateOrdinal(at time.Time) int {
|
||||
year, month, day := at.In(appTimezone.Location()).Date()
|
||||
return groupUsageDateOrdinal(year, month, day)
|
||||
}
|
||||
|
||||
func groupUsageDateOrdinal(year int, month time.Month, day int) int {
|
||||
return year*10000 + int(month)*100 + day
|
||||
}
|
||||
@@ -373,13 +373,18 @@ func (s *DashboardAggregationService) maybeCleanupRetention(ctx context.Context,
|
||||
}
|
||||
hourlyCutoff := now.AddDate(0, 0, -s.cfg.Retention.HourlyDays)
|
||||
dailyCutoff := now.AddDate(0, 0, -s.cfg.Retention.DailyDays)
|
||||
usageCutoff := now.AddDate(0, 0, -usageDays)
|
||||
// usage_logs 按服务端配置时区整日保留,与分组日桶的日界对齐。
|
||||
usageCutoff := GroupUsageTodayStart(now.AddDate(0, 0, -usageDays))
|
||||
dedupDays := s.cfg.Retention.UsageBillingDedupDays
|
||||
if dedupDays <= 0 {
|
||||
dedupDays = 365
|
||||
}
|
||||
dedupDays = max(dedupDays, usageDays)
|
||||
// 计费去重记录的保留不短于 usage_logs。
|
||||
dedupCutoff := now.AddDate(0, 0, -dedupDays)
|
||||
if usageDays > 0 && dedupCutoff.After(usageCutoff) {
|
||||
dedupCutoff = usageCutoff
|
||||
}
|
||||
|
||||
var aggErr, usageErr, dedupErr error
|
||||
if s.cfg.Enabled {
|
||||
|
||||
@@ -442,3 +442,115 @@ func TestCalculateCostUnified_DeepseekProRetainsRatesAfterSeptember14(t *testing
|
||||
require.InDelta(t, proTotal, versioned.TotalCost, 1e-10,
|
||||
"versioned pro names must retain Pro rates on September 14")
|
||||
}
|
||||
|
||||
// Explicit override-file token prices are final operator rates, including zero.
|
||||
// Fields absent from that patch still use the official default and peak policy.
|
||||
func TestDeepseekOverrideFileTokenPrices(t *testing.T) {
|
||||
type prices struct{ input, output, cacheRead float64 }
|
||||
official := prices{1.5e-7, 6e-7, 3e-9}
|
||||
officialPeak := prices{3e-7, 1.2e-6, 6e-9}
|
||||
custom := prices{2e-6, 3e-6, 4e-7}
|
||||
fullPatch := `{"input_cost_per_token":0.000002,"output_cost_per_token":0.000003,"cache_read_input_token_cost":0.0000004}`
|
||||
cases := []struct {
|
||||
name, model, layer, patch string
|
||||
offPeak, peak prices
|
||||
}{
|
||||
{"flash full", "deepseek-flash", "catalog", fullPatch, custom, custom},
|
||||
{"pro full", "deepseek-v4-pro", "catalog", fullPatch, custom, custom},
|
||||
{"versioned pro full", "deepseek-v4-pro-0813", "catalog", fullPatch, custom, custom},
|
||||
{"fallback full", "deepseek-flash", "fallback", fullPatch, custom, custom},
|
||||
{"custom model override only", "deepseek-custom", "override", fullPatch, custom, custom},
|
||||
{"override only", "deepseek-flash", "override", fullPatch, custom, custom},
|
||||
{"input only", "deepseek-flash", "catalog", `{"input_cost_per_token":0.000002}`, prices{2e-6, 6e-7, 3e-9}, prices{2e-6, 1.2e-6, 6e-9}},
|
||||
{"zero input", "deepseek-flash", "catalog", `{"input_cost_per_token":0}`, prices{0, 6e-7, 3e-9}, prices{0, 1.2e-6, 6e-9}},
|
||||
{"zero output", "deepseek-flash", "catalog", `{"output_cost_per_token":0}`, prices{1.5e-7, 0, 3e-9}, prices{3e-7, 0, 6e-9}},
|
||||
{"zero cache read", "deepseek-flash", "catalog", `{"cache_read_input_token_cost":0}`, prices{1.5e-7, 6e-7, 0}, prices{3e-7, 1.2e-6, 0}},
|
||||
{"metadata only", "deepseek-flash", "catalog", `{"supports_prompt_caching":true}`, official, officialPeak},
|
||||
{"null input", "deepseek-flash", "catalog", `{"input_cost_per_token":null}`, official, officialPeak},
|
||||
{"negative input", "deepseek-flash", "catalog", `{"input_cost_per_token":-0.000002}`, official, officialPeak},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := &config.Config{}
|
||||
cfg.Pricing.DataDir = dir
|
||||
cfg.Pricing.OverrideFile = filepath.Join(dir, "overrides.json")
|
||||
require.NoError(t, os.WriteFile(cfg.Pricing.OverrideFile, []byte(`{"`+tc.model+`":`+tc.patch+`}`), 0644))
|
||||
// Deliberately stale catalog rates must still be corrected for every
|
||||
// field that the operator did not explicitly override.
|
||||
catalog := []byte(`{"` + tc.model + `":{"input_cost_per_token":0.00001,"output_cost_per_token":0.00002,"cache_read_input_token_cost":0.000001}}`)
|
||||
if tc.layer == "fallback" {
|
||||
cfg.Pricing.FallbackFile = filepath.Join(dir, "fallback.json")
|
||||
require.NoError(t, os.WriteFile(cfg.Pricing.FallbackFile, catalog, 0644))
|
||||
}
|
||||
if tc.layer != "catalog" {
|
||||
catalog = []byte(`{"other-model":{"input_cost_per_token":0.000001}}`)
|
||||
}
|
||||
svc := &PricingService{cfg: cfg}
|
||||
require.NoError(t, os.WriteFile(svc.getPricingFilePath(), catalog, 0644))
|
||||
require.NoError(t, svc.loadPricingData(svc.getPricingFilePath()))
|
||||
billing := NewBillingService(cfg, svc)
|
||||
resolver := NewModelPricingResolver(nil, billing)
|
||||
tokens := UsageTokens{InputTokens: 1000, OutputTokens: 500, CacheReadTokens: 2000}
|
||||
for _, slot := range []struct {
|
||||
name string
|
||||
at time.Time
|
||||
want prices
|
||||
}{
|
||||
{"off peak", time.Date(2026, 8, 24, 12, 0, 0, 0, time.UTC), tc.offPeak},
|
||||
{"peak", time.Date(2026, 8, 24, 2, 0, 0, 0, time.UTC), tc.peak},
|
||||
} {
|
||||
t.Run(slot.name, func(t *testing.T) {
|
||||
cost, err := billing.CalculateCostUnified(CostInput{
|
||||
Ctx: context.Background(), Model: tc.model, Tokens: tokens, RateMultiplier: 1.25,
|
||||
Resolver: resolver, PricingAt: slot.at,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, 1000*slot.want.input, cost.InputCost, 1e-12)
|
||||
require.InDelta(t, 500*slot.want.output, cost.OutputCost, 1e-12)
|
||||
require.InDelta(t, 2000*slot.want.cacheRead, cost.CacheReadCost, 1e-12)
|
||||
want := 1000*slot.want.input + 500*slot.want.output + 2000*slot.want.cacheRead
|
||||
require.InDelta(t, want, cost.TotalCost, 1e-12)
|
||||
require.InDelta(t, want*1.25, cost.ActualCost, 1e-12)
|
||||
stats := tryModelFilePricing(billing, tc.model, tokens, "", slot.at, false)
|
||||
require.NotNil(t, stats)
|
||||
require.InDelta(t, want, *stats, 1e-12, "account statistics use the same override rates")
|
||||
})
|
||||
}
|
||||
// Catalog lookup and legacy estimates also retain the override.
|
||||
pricing, err := billing.GetModelPricing(tc.model)
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, tc.offPeak.input, pricing.InputPricePerToken, 1e-15)
|
||||
require.InDelta(t, tc.offPeak.output, pricing.OutputPricePerToken, 1e-15)
|
||||
require.InDelta(t, tc.offPeak.cacheRead, pricing.CacheReadPricePerToken, 1e-15)
|
||||
estimate, err := billing.CalculateCost(tc.model, tokens, 1)
|
||||
require.NoError(t, err)
|
||||
want := 1000*tc.offPeak.input + 500*tc.offPeak.output + 2000*tc.offPeak.cacheRead
|
||||
require.InDelta(t, want, estimate.TotalCost, 1e-12)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeepseekOverrideFileReloadRestoresOfficialPolicy(t *testing.T) {
|
||||
svc := newHotReloadPricingService(t, `{"deepseek-flash":{"input_cost_per_token":0.00001,"output_cost_per_token":0.00002}}`,
|
||||
`{"deepseek-flash":{"input_cost_per_token":0.000002,"output_cost_per_token":0.000003,"cache_read_input_token_cost":0}}`)
|
||||
billing := NewBillingService(svc.cfg, svc)
|
||||
resolver := NewModelPricingResolver(nil, billing)
|
||||
check := func(wantInput, wantOutput, wantCacheRead float64) {
|
||||
t.Helper()
|
||||
cost, err := billing.CalculateCostUnified(CostInput{Ctx: context.Background(), Model: "deepseek-flash",
|
||||
Tokens: UsageTokens{InputTokens: 1000, OutputTokens: 500, CacheReadTokens: 2000}, RateMultiplier: 1,
|
||||
Resolver: resolver, PricingAt: time.Date(2026, 8, 24, 2, 0, 0, 0, time.UTC)})
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, wantInput, cost.InputCost, 1e-12)
|
||||
require.InDelta(t, wantOutput, cost.OutputCost, 1e-12)
|
||||
require.InDelta(t, wantCacheRead, cost.CacheReadCost, 1e-12)
|
||||
}
|
||||
check(0.002, 0.0015, 0)
|
||||
require.NoError(t, os.WriteFile(svc.cfg.Pricing.OverrideFile, []byte(`{"deepseek-flash":{"output_cost_per_token":0}}`), 0644))
|
||||
svc.reloadIfCustomFilesChanged()
|
||||
check(0.0003, 0, 0.000012)
|
||||
require.NoError(t, os.Remove(svc.cfg.Pricing.OverrideFile))
|
||||
svc.reloadIfCustomFilesChanged()
|
||||
check(0.0003, 0.0006, 0.000012)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/apicompat"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAnthropicCompatUpstreamObservation(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, protocol := range []string{"chat", "responses"} {
|
||||
for _, streaming := range []bool{false, true} {
|
||||
for _, scenario := range []string{"normal", "missing", "conflict", "partial-error"} {
|
||||
t.Run(fmt.Sprintf("%s/stream=%t/%s", protocol, streaming, scenario), func(t *testing.T) {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
|
||||
beginUpstreamResponseModelObservation(c).Observe("stale-model", false)
|
||||
body := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"actual-model\",\"usage\":{\"input_tokens\":3,\"speed\":\"fast\"}}}\n\nevent: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"
|
||||
|
||||
expectedModel, expectedTier := "actual-model", "fast"
|
||||
switch scenario {
|
||||
case "missing":
|
||||
body = strings.ReplaceAll(body, `,"model":"actual-model"`, "")
|
||||
body = strings.ReplaceAll(body, `,"speed":"fast"`, "")
|
||||
expectedModel, expectedTier = "", ""
|
||||
case "conflict":
|
||||
body = strings.Replace(body, `"type":"message_delta","delta"`, `"type":"message_delta","model":"other-model","delta"`, 1)
|
||||
case "partial-error":
|
||||
body = body[:strings.Index(body, "event: message_delta")]
|
||||
}
|
||||
resp := &http.Response{Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}
|
||||
svc := &GatewayService{}
|
||||
var result *ForwardResult
|
||||
var err error
|
||||
if protocol == "chat" {
|
||||
if streaming {
|
||||
result, err = svc.handleCCStreamingFromAnthropic(resp, c, "public-model", "sent-model", nil, time.Now())
|
||||
} else {
|
||||
result, err = svc.handleCCBufferedFromAnthropic(resp, c, "public-model", "sent-model", nil, time.Now())
|
||||
}
|
||||
} else {
|
||||
if streaming {
|
||||
result, err = svc.handleResponsesStreamingResponse(resp, c, "public-model", "sent-model", nil, time.Now(), apicompat.ResponsesClientToolMapping{})
|
||||
} else {
|
||||
result, err = svc.handleResponsesBufferedStreamingResponse(resp, c, "public-model", "sent-model", nil, time.Now(), apicompat.ResponsesClientToolMapping{})
|
||||
}
|
||||
}
|
||||
if scenario == "partial-error" {
|
||||
require.Error(t, err)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
require.NotNil(t, result)
|
||||
require.Equal(t, expectedModel, result.UpstreamResponseModel)
|
||||
require.Equal(t, expectedTier, result.UpstreamResponseServiceTier)
|
||||
require.Equal(t, scenario == "conflict", result.UpstreamResponseModelConflict)
|
||||
require.Equal(t, "sent-model", result.UpstreamModel)
|
||||
require.Equal(t, "public-model", result.Model)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -501,6 +501,7 @@ func (s *GatewayService) handleStreamingResponseAnthropicAPIKeyPassthrough(
|
||||
keepaliveTimer.Reset(keepaliveInterval)
|
||||
}
|
||||
inPartialEvent := false
|
||||
clientModel := compositeClientModel(ctx, "")
|
||||
|
||||
for {
|
||||
select {
|
||||
@@ -560,8 +561,14 @@ func (s *GatewayService) handleStreamingResponseAnthropicAPIKeyPassthrough(
|
||||
}
|
||||
}
|
||||
|
||||
if data, ok := extractAnthropicSSEDataLine(line); ok && clientModel != "" && gjson.Get(data, "type").String() == "message_start" && gjson.Get(data, "message.model").Exists() {
|
||||
if rewritten, err := sjson.Set(data, "message.model", clientModel); err == nil {
|
||||
line = "data: " + rewritten
|
||||
}
|
||||
}
|
||||
|
||||
if !clientDisconnected {
|
||||
restored := string(reverseToolNamesIfPresent(c, []byte(line)))
|
||||
restored := reverseToolNamesIfPresentString(c, line)
|
||||
if _, err := io.WriteString(w, restored); err != nil {
|
||||
clientDisconnected = true
|
||||
logger.LegacyPrintf("service.gateway", "[Anthropic passthrough] Client disconnected during streaming, continue draining upstream for usage: account=%d", account.ID)
|
||||
@@ -894,6 +901,7 @@ func (s *GatewayService) handleNonStreamingResponseAnthropicAPIKeyPassthrough(
|
||||
if contentType == "" {
|
||||
contentType = "application/json"
|
||||
}
|
||||
body = restoreCompositeClientModel(ctx, body)
|
||||
body = reverseToolNamesIfPresent(c, body)
|
||||
c.Data(resp.StatusCode, contentType, body)
|
||||
return usage, nil
|
||||
|
||||
@@ -130,9 +130,7 @@ func (s *GatewayService) forwardBedrock(
|
||||
|
||||
// 错误/failover 处理
|
||||
if resp.StatusCode >= 400 {
|
||||
// 账号状态按模型隔离时用调度器的模型键(账号映射后的模型名),不是发往上游的 Bedrock 模型 ID;
|
||||
// 两者不一致会让模型级冷却写到调度器不会读取的键上。
|
||||
return s.handleBedrockUpstreamErrors(ctx, resp, c, account, account.GetMappedModel(reqModel))
|
||||
return s.handleBedrockUpstreamErrors(ctx, resp, c, account, bedrockSchedulingModelKey(ctx, account, reqModel))
|
||||
}
|
||||
|
||||
// Bedrock 分支绕过通用 Forward 成功路径,这里保持上游接受回调语义一致。
|
||||
@@ -147,6 +145,10 @@ func (s *GatewayService) forwardBedrock(
|
||||
if reqStream {
|
||||
streamResult, err := s.handleBedrockStreamingResponse(ctx, resp, c, account, startTime, reqModel)
|
||||
if err != nil {
|
||||
// 流中断时保留已观测到的 usage 与错误一起返回,handler 照常提交 usage 记录。
|
||||
if partial := partialStreamUsageResult(c, resp, streamResult, reqModel, mappedModel, startTime, err); partial != nil {
|
||||
return partial, err
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
usage = streamResult.usage
|
||||
@@ -274,6 +276,16 @@ func (s *GatewayService) handleBedrockUpstreamErrors(
|
||||
account *Account,
|
||||
modelKey string,
|
||||
) (*ForwardResult, error) {
|
||||
// 内容过滤由请求内容决定,换号结果相同:不换号,按普通错误返回客户端。
|
||||
if resp.StatusCode >= http.StatusInternalServerError {
|
||||
respBody, _ := s.readUpstreamErrorBody(resp)
|
||||
_ = resp.Body.Close()
|
||||
resp.Body = io.NopCloser(bytes.NewReader(respBody))
|
||||
if isBedrockContentFilterError(resp.StatusCode, respBody) {
|
||||
return s.handleErrorResponse(ctx, resp, c, account, modelKey)
|
||||
}
|
||||
}
|
||||
|
||||
// retry exhausted + failover
|
||||
if s.shouldRetryUpstreamError(account, resp.StatusCode) {
|
||||
if s.shouldFailoverUpstreamError(resp.StatusCode) {
|
||||
|
||||
@@ -44,12 +44,17 @@ func syncBillingHeaderVersion(body []byte, userAgent string) []byte {
|
||||
}
|
||||
|
||||
replacement := "cc_version=" + version
|
||||
// The fingerprint depends only on the original messages and version, so it
|
||||
// is the same for every billing block. Compute it lazily, at most once.
|
||||
fingerprintedReplacement := ""
|
||||
idx := 0
|
||||
systemResult.ForEach(func(_, item gjson.Result) bool {
|
||||
text := item.Get("text")
|
||||
if text.Exists() && text.Type == gjson.String &&
|
||||
strings.HasPrefix(text.String(), "x-anthropic-billing-header") {
|
||||
fingerprintedReplacement := replacement + "." + computeClaudeCodeFingerprint(body, version)
|
||||
if fingerprintedReplacement == "" {
|
||||
fingerprintedReplacement = replacement + "." + computeClaudeCodeFingerprint(body, version)
|
||||
}
|
||||
newText := ccVersionWithFingerprintInBillingRe.ReplaceAllString(text.String(), fingerprintedReplacement)
|
||||
newText = ccVersionInBillingRe.ReplaceAllString(newText, replacement)
|
||||
if newText != text.String() {
|
||||
|
||||
@@ -307,7 +307,8 @@ func normalizeClaudeOAuthRequestBody(body []byte, modelID string, opts claudeOAu
|
||||
// applyToolNameRewriteToBody 同步映射为假名
|
||||
// - 其他形态(auto/any/none)原样透传
|
||||
// 如果 body 里完全没有 tools(空数组),tool_choice 没意义时才删除
|
||||
if !gjson.GetBytes(out, "tools").IsArray() || len(gjson.GetBytes(out, "tools").Array()) == 0 {
|
||||
toolsResult := gjson.GetBytes(out, "tools")
|
||||
if !toolsResult.IsArray() || !toolsResult.Get("0").Exists() {
|
||||
if !isClaude55SignedThinkingModel(modelID) && gjson.GetBytes(out, "tool_choice").Exists() {
|
||||
if next, ok := deleteJSONPathBytes(out, "tool_choice"); ok {
|
||||
out = next
|
||||
@@ -1059,9 +1060,37 @@ func collectCacheControlPaths(body []byte) (invalidThinking []cacheControlPath,
|
||||
return invalidThinking, messagePaths, toolPaths, systemPaths
|
||||
}
|
||||
|
||||
var (
|
||||
cacheControlKeyBytes = []byte(`"cache_control"`)
|
||||
thinkingBlockTypeBytes = []byte(`"thinking"`)
|
||||
cacheTTL1hJSONBytes = []byte(`"1h"`)
|
||||
jsonUnicodeEscapeBytes = []byte(`\u`)
|
||||
)
|
||||
|
||||
// enforceCacheControlLimit 让出站 cache_control 满足上游约束:
|
||||
// 先执行块数量限制,再修正 TTL 顺序。
|
||||
//
|
||||
// 大多数请求的 cache_control 块不超过 4 个、没有 thinking 块、也没有 1h TTL,
|
||||
// 此时两步都是 no-op。用字节级预检查跳过两次 collectCacheControlPaths 遍历。
|
||||
// 预检查只会多算(把请求送回原路径),不会漏判;含 \u 转义的 body 可能把
|
||||
// 键名或值写成转义形式,字节匹配看不到,因此直接走原路径。
|
||||
func enforceCacheControlLimit(body []byte) []byte {
|
||||
if len(body) == 0 {
|
||||
return body
|
||||
}
|
||||
if bytes.Contains(body, jsonUnicodeEscapeBytes) {
|
||||
return normalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body))
|
||||
}
|
||||
if !bytes.Contains(body, cacheControlKeyBytes) {
|
||||
return body
|
||||
}
|
||||
if bytes.Count(body, cacheControlKeyBytes) <= maxCacheControlBlocks &&
|
||||
!bytes.Contains(body, thinkingBlockTypeBytes) {
|
||||
if !bytes.Contains(body, cacheTTL1hJSONBytes) {
|
||||
return body
|
||||
}
|
||||
return normalizeCacheControlTTLOrder(body)
|
||||
}
|
||||
return normalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body))
|
||||
}
|
||||
|
||||
|
||||
@@ -448,11 +448,11 @@ func (s *GatewayService) buildCountTokensRequestAnthropicAPIKeyPassthrough(
|
||||
// targetURL 的 base 取值),其余保持 extra/default 行为。
|
||||
setAnthropicAPIKeyAuthHeader(req.Header, account, token, baseURL)
|
||||
|
||||
if req.Header.Get("content-type") == "" {
|
||||
req.Header.Set("content-type", "application/json")
|
||||
if getHeaderRaw(req.Header, "content-type") == "" {
|
||||
setHeaderRaw(req.Header, "content-type", "application/json")
|
||||
}
|
||||
if req.Header.Get("anthropic-version") == "" {
|
||||
req.Header.Set("anthropic-version", "2023-06-01")
|
||||
if getHeaderRaw(req.Header, "anthropic-version") == "" {
|
||||
setHeaderRaw(req.Header, "anthropic-version", "2023-06-01")
|
||||
}
|
||||
|
||||
// 账号级请求头覆写(最终生效,覆盖上面所有来源的同名头)
|
||||
@@ -614,7 +614,7 @@ func (s *GatewayService) buildCountTokensRequest(ctx context.Context, c *gin.Con
|
||||
filterSonnet55ToolsetBetaHeader(req.Header, body, modelID)
|
||||
|
||||
if c != nil && tokenType == "oauth" {
|
||||
c.Set(claudeMimicDebugInfoKey, buildClaudeMimicDebugLine(req, body, account, tokenType, mimicClaudeCode))
|
||||
c.Set(claudeMimicDebugInfoKey, newClaudeMimicDebugLine(req, body, account, tokenType, mimicClaudeCode))
|
||||
}
|
||||
if s.debugClaudeMimicEnabled() {
|
||||
logClaudeMimicDebug(req, body, account, tokenType, mimicClaudeCode)
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func headerKeysFold(h http.Header, name string) []string {
|
||||
var keys []string
|
||||
for k := range h {
|
||||
if strings.EqualFold(k, name) {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// The count_tokens passthrough builder copies client headers under their wire casing
|
||||
// (lowercase content-type / anthropic-version). It must look those up under the same
|
||||
// key before filling in defaults, so the upstream request carries exactly one of each.
|
||||
func TestCountTokensPassthroughSendsOneContentTypeAndVersion(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
clientSends bool
|
||||
wantType string
|
||||
wantVersion string
|
||||
}{
|
||||
{"client sent both", true, "application/json; charset=utf-8", "2024-01-01"},
|
||||
{"client sent neither", false, "application/json", "2023-06-01"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", nil)
|
||||
if tt.clientSends {
|
||||
c.Request.Header.Set("Anthropic-Version", tt.wantVersion)
|
||||
c.Request.Header.Set("Content-Type", tt.wantType)
|
||||
}
|
||||
account := &Account{
|
||||
ID: 1,
|
||||
Platform: PlatformAnthropic,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "test-key"},
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
}
|
||||
svc := &GatewayService{cfg: &config.Config{}}
|
||||
body := []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}]}`)
|
||||
|
||||
req, err := svc.buildCountTokensRequestAnthropicAPIKeyPassthrough(context.Background(), c, account, body, "test-key")
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, []string{"content-type"}, headerKeysFold(req.Header, "content-type"))
|
||||
require.Equal(t, []string{tt.wantType}, req.Header["content-type"])
|
||||
require.Equal(t, []string{"anthropic-version"}, headerKeysFold(req.Header, "anthropic-version"))
|
||||
require.Equal(t, []string{tt.wantVersion}, req.Header["anthropic-version"])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The Claude mimic debug line must report headers stored under their wire casing.
|
||||
func TestBuildClaudeMimicDebugLineReadsRawCasedHeaders(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodPost, "https://upstream.example/v1/messages", nil)
|
||||
setHeaderRaw(req.Header, "anthropic-version", "2023-06-01")
|
||||
setHeaderRaw(req.Header, "anthropic-beta", "beta-a")
|
||||
setHeaderRaw(req.Header, "content-type", "application/json")
|
||||
setHeaderRaw(req.Header, "x-app", "cli")
|
||||
setHeaderRaw(req.Header, "X-Stainless-OS", "Linux")
|
||||
|
||||
line := buildClaudeMimicDebugLine(req, []byte(`{}`), nil, "oauth", true)
|
||||
|
||||
require.Contains(t, line, `anthropic-version="2023-06-01"`)
|
||||
require.Contains(t, line, `anthropic-beta="beta-a"`)
|
||||
require.Contains(t, line, `content-type="application/json"`)
|
||||
require.Contains(t, line, `x-app="cli"`)
|
||||
require.Contains(t, line, `x-stainless-os="Linux"`)
|
||||
}
|
||||
@@ -53,6 +53,37 @@ func (s *GatewayService) shouldFailoverUpstreamError(statusCode int) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// rotatedClaudeAccessToken recovers a token rotated while this request was in
|
||||
// flight. Compare against the token actually sent, which may have come from the
|
||||
// cache rather than the account snapshot. Never refresh or persist credentials
|
||||
// here: an unchanged token must retain the normal 401 policy.
|
||||
func (s *GatewayService) rotatedClaudeAccessToken(ctx context.Context, account *Account, rejectedToken string) string {
|
||||
if account == nil || account.Platform != PlatformAnthropic || account.Type != AccountTypeOAuth ||
|
||||
s.accountRepo == nil || rejectedToken == "" || ctx.Err() != nil {
|
||||
return ""
|
||||
}
|
||||
latest, err := s.accountRepo.GetByID(ctx, account.ID)
|
||||
if err != nil {
|
||||
slog.Warn("claude_oauth_401_reload_failed", "account_id", account.ID, "error", err)
|
||||
return ""
|
||||
}
|
||||
if latest == nil || latest.Platform != PlatformAnthropic || latest.Type != AccountTypeOAuth ||
|
||||
latest.Status != StatusActive || !latest.Schedulable {
|
||||
return ""
|
||||
}
|
||||
token := strings.TrimSpace(latest.GetCredential("access_token"))
|
||||
if token == "" || token == rejectedToken {
|
||||
return ""
|
||||
}
|
||||
if p := s.claudeTokenProvider; p != nil && p.tokenCache != nil {
|
||||
if err := p.tokenCache.DeleteAccessToken(ctx, ClaudeTokenCacheKey(latest)); err != nil {
|
||||
slog.Warn("claude_oauth_401_invalidate_cache_failed", "account_id", account.ID, "error", err)
|
||||
}
|
||||
}
|
||||
slog.Info("claude_oauth_rotated_token_retry", "account_id", account.ID)
|
||||
return token
|
||||
}
|
||||
|
||||
func retryBackoffDelay(attempt int) time.Duration {
|
||||
// attempt 从 1 开始,表示第 attempt 次请求刚失败,需要等待后进行第 attempt+1 次请求。
|
||||
if attempt <= 0 {
|
||||
@@ -387,6 +418,7 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A
|
||||
var resp *http.Response
|
||||
lastWireBody := body
|
||||
retryStart := time.Now()
|
||||
retriedRotatedToken := false
|
||||
for attempt := 1; attempt <= maxRetryAttempts; attempt++ {
|
||||
// 构建上游请求(每次重试需要重新构建,因为请求体需要重新读取)
|
||||
upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, reqStream)
|
||||
@@ -409,6 +441,16 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A
|
||||
})
|
||||
}
|
||||
|
||||
if resp.StatusCode == http.StatusUnauthorized && !retriedRotatedToken &&
|
||||
attempt < maxRetryAttempts && time.Since(retryStart) < maxRetryElapsed {
|
||||
if rotatedToken := s.rotatedClaudeAccessToken(ctx, account, token); rotatedToken != "" {
|
||||
_ = resp.Body.Close()
|
||||
token = rotatedToken
|
||||
retriedRotatedToken = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// 优先检测thinking block签名错误(400)并重试一次
|
||||
if resp.StatusCode == 400 {
|
||||
respBody, readErr := s.readUpstreamErrorBody(resp)
|
||||
|
||||
@@ -94,6 +94,10 @@ func (s *GatewayService) ForwardAsChatCompletions(
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal anthropic request: %w", err)
|
||||
}
|
||||
if !account.IsOAuth() {
|
||||
// OAuth accounts get their id from the mimicry below.
|
||||
anthropicBody = withChatCompletionsMetadataUserID(body, anthropicBody)
|
||||
}
|
||||
|
||||
// 6. Apply Claude Code mimicry for OAuth accounts.
|
||||
// Chat Completions 协议进来的请求永远不是 Claude Code 客户端,所以对 OAuth 账号
|
||||
@@ -122,30 +126,43 @@ func (s *GatewayService) ForwardAsChatCompletions(
|
||||
proxyURL = account.Proxy.URL()
|
||||
}
|
||||
|
||||
// 10. Build upstream request
|
||||
upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, reqStream)
|
||||
upstreamReq, forwardedBody, err := s.buildUpstreamRequest(upstreamCtx, c, account, anthropicBody, token, tokenType, mappedModel, reqStream, shouldMimicClaudeCode)
|
||||
releaseUpstreamCtx()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build upstream request: %w", err)
|
||||
// 10. Build and send the request, recovering a concurrent token rotation once.
|
||||
var upstreamReq *http.Request
|
||||
var forwardedBody []byte
|
||||
var resp *http.Response
|
||||
for retriedRotatedToken := false; ; {
|
||||
upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, reqStream)
|
||||
upstreamReq, forwardedBody, err = s.buildUpstreamRequest(upstreamCtx, c, account, anthropicBody, token, tokenType, mappedModel, reqStream, shouldMimicClaudeCode)
|
||||
releaseUpstreamCtx()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build upstream request: %w", err)
|
||||
}
|
||||
resp, err = s.httpUpstream.DoWithTLS(upstreamReq, proxyURL, account.ID, account.Concurrency, s.tlsFPProfileService.ResolveTLSProfile(account))
|
||||
if err != nil {
|
||||
if resp != nil && resp.Body != nil {
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
return nil, s.handleUpstreamTransportError(ctx, c, account, err, OpsUpstreamErrorEvent{
|
||||
UpstreamURL: safeUpstreamURL(upstreamReq.URL.String()),
|
||||
})
|
||||
}
|
||||
if resp.StatusCode == http.StatusUnauthorized && !retriedRotatedToken {
|
||||
if rotatedToken := s.rotatedClaudeAccessToken(ctx, account, token); rotatedToken != "" {
|
||||
_ = resp.Body.Close()
|
||||
token = rotatedToken
|
||||
retriedRotatedToken = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// Bill the final Anthropic effort after conversion and account normalization.
|
||||
// For example, OpenAI xhigh is forwarded as output_config.effort=max.
|
||||
reasoningEffort := NormalizeClaudeOutputEffort(gjson.GetBytes(forwardedBody, "output_config.effort").String())
|
||||
reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, forwardedBody, mappedModel)
|
||||
|
||||
// 11. Send request
|
||||
resp, err := s.httpUpstream.DoWithTLS(upstreamReq, proxyURL, account.ID, account.Concurrency, s.tlsFPProfileService.ResolveTLSProfile(account))
|
||||
if err != nil {
|
||||
if resp != nil && resp.Body != nil {
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
return nil, s.handleUpstreamTransportError(ctx, c, account, err, OpsUpstreamErrorEvent{
|
||||
UpstreamURL: safeUpstreamURL(upstreamReq.URL.String()),
|
||||
})
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 12. Handle error response with failover
|
||||
if resp.StatusCode >= 400 {
|
||||
respBody, _ := s.readUpstreamErrorBody(resp)
|
||||
@@ -236,6 +253,7 @@ func (s *GatewayService) handleCCBufferedFromAnthropic(
|
||||
reasoningEffort *string,
|
||||
startTime time.Time,
|
||||
) (*ForwardResult, error) {
|
||||
observer := beginUpstreamResponseModelObservation(c)
|
||||
requestID := resp.Header.Get("x-request-id")
|
||||
|
||||
scanner := bufio.NewScanner(resp.Body)
|
||||
@@ -271,6 +289,7 @@ func (s *GatewayService) handleCCBufferedFromAnthropic(
|
||||
continue
|
||||
}
|
||||
|
||||
observer.ObserveAnthropic([]byte(payload))
|
||||
streamStatus.observe(&event, payload)
|
||||
if streamStatus.upstreamErrType != "" {
|
||||
break
|
||||
@@ -323,7 +342,10 @@ func (s *GatewayService) handleCCBufferedFromAnthropic(
|
||||
_ = resp.Body.Close()
|
||||
writeGatewayCCError(c, http.StatusBadGateway, "server_error", failure.message)
|
||||
return &ForwardResult{
|
||||
RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage,
|
||||
UpstreamResponseModel: observer.Model(),
|
||||
UpstreamResponseModelConflict: observer.Conflict(),
|
||||
UpstreamResponseServiceTier: observer.ServiceTier(),
|
||||
RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage,
|
||||
Model: originalModel, UpstreamModel: mappedModel, ReasoningEffort: reasoningEffort,
|
||||
Duration: time.Since(startTime),
|
||||
}, failure.err
|
||||
@@ -367,14 +389,17 @@ func (s *GatewayService) handleCCBufferedFromAnthropic(
|
||||
}
|
||||
|
||||
return &ForwardResult{
|
||||
RequestID: requestID,
|
||||
UpstreamHeaders: resp.Header,
|
||||
Usage: usage,
|
||||
Model: originalModel,
|
||||
UpstreamModel: mappedModel,
|
||||
ReasoningEffort: reasoningEffort,
|
||||
Stream: false,
|
||||
Duration: time.Since(startTime),
|
||||
UpstreamResponseModel: observer.Model(),
|
||||
UpstreamResponseModelConflict: observer.Conflict(),
|
||||
UpstreamResponseServiceTier: observer.ServiceTier(),
|
||||
RequestID: requestID,
|
||||
UpstreamHeaders: resp.Header,
|
||||
Usage: usage,
|
||||
Model: originalModel,
|
||||
UpstreamModel: mappedModel,
|
||||
ReasoningEffort: reasoningEffort,
|
||||
Stream: false,
|
||||
Duration: time.Since(startTime),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -388,6 +413,7 @@ func (s *GatewayService) handleCCStreamingFromAnthropic(
|
||||
reasoningEffort *string,
|
||||
startTime time.Time,
|
||||
) (*ForwardResult, error) {
|
||||
observer := beginUpstreamResponseModelObservation(c)
|
||||
requestID := resp.Header.Get("x-request-id")
|
||||
|
||||
if s.responseHeaderFilter != nil {
|
||||
@@ -415,16 +441,19 @@ func (s *GatewayService) handleCCStreamingFromAnthropic(
|
||||
|
||||
resultWithUsage := func() *ForwardResult {
|
||||
return &ForwardResult{
|
||||
RequestID: requestID,
|
||||
UpstreamHeaders: resp.Header,
|
||||
Usage: usage,
|
||||
Model: originalModel,
|
||||
UpstreamModel: mappedModel,
|
||||
ReasoningEffort: reasoningEffort,
|
||||
Stream: true,
|
||||
Duration: time.Since(startTime),
|
||||
FirstTokenMs: firstTokenMs,
|
||||
ClientDisconnect: stream.clientDisconnected,
|
||||
UpstreamResponseModel: observer.Model(),
|
||||
UpstreamResponseModelConflict: observer.Conflict(),
|
||||
UpstreamResponseServiceTier: observer.ServiceTier(),
|
||||
RequestID: requestID,
|
||||
UpstreamHeaders: resp.Header,
|
||||
Usage: usage,
|
||||
Model: originalModel,
|
||||
UpstreamModel: mappedModel,
|
||||
ReasoningEffort: reasoningEffort,
|
||||
Stream: true,
|
||||
Duration: time.Since(startTime),
|
||||
FirstTokenMs: firstTokenMs,
|
||||
ClientDisconnect: stream.clientDisconnected,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,7 +464,7 @@ func (s *GatewayService) handleCCStreamingFromAnthropic(
|
||||
}
|
||||
// Reverse tool name mapping: fake → real, per-chunk bytes.Replace.
|
||||
// c 可能持有请求侧注入的 ToolNameRewrite;无则仅做静态前缀还原。
|
||||
out := string(reverseToolNamesIfPresent(c, []byte(sse)))
|
||||
out := reverseToolNamesIfPresentString(c, sse)
|
||||
if _, err := fmt.Fprint(c.Writer, out); err != nil {
|
||||
return true // client disconnected
|
||||
}
|
||||
@@ -522,6 +551,7 @@ func (s *GatewayService) handleCCStreamingFromAnthropic(
|
||||
// The intermediate Responses converter synthesizes usage even when absent.
|
||||
ccState.IncludeUsage = ccState.IncludeUsage || anthropicChatStreamHasUsage(&event, payload)
|
||||
|
||||
observer.ObserveAnthropic([]byte(payload))
|
||||
stream.observe(&event, payload)
|
||||
if stream.upstreamErrType != "" {
|
||||
break
|
||||
|
||||
@@ -133,30 +133,43 @@ func (s *GatewayService) ForwardAsResponses(
|
||||
proxyURL = account.Proxy.URL()
|
||||
}
|
||||
|
||||
// 10. Build upstream request
|
||||
upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, reqStream)
|
||||
upstreamReq, forwardedBody, err := s.buildUpstreamRequest(upstreamCtx, c, account, anthropicBody, token, tokenType, mappedModel, reqStream, shouldMimicClaudeCode)
|
||||
releaseUpstreamCtx()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build upstream request: %w", err)
|
||||
// 10. Build and send the request, recovering a concurrent token rotation once.
|
||||
var upstreamReq *http.Request
|
||||
var forwardedBody []byte
|
||||
var resp *http.Response
|
||||
for retriedRotatedToken := false; ; {
|
||||
upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, reqStream)
|
||||
upstreamReq, forwardedBody, err = s.buildUpstreamRequest(upstreamCtx, c, account, anthropicBody, token, tokenType, mappedModel, reqStream, shouldMimicClaudeCode)
|
||||
releaseUpstreamCtx()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build upstream request: %w", err)
|
||||
}
|
||||
resp, err = s.httpUpstream.DoWithTLS(upstreamReq, proxyURL, account.ID, account.Concurrency, s.tlsFPProfileService.ResolveTLSProfile(account))
|
||||
if err != nil {
|
||||
if resp != nil && resp.Body != nil {
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
return nil, s.handleUpstreamTransportError(ctx, c, account, err, OpsUpstreamErrorEvent{
|
||||
UpstreamURL: safeUpstreamURL(upstreamReq.URL.String()),
|
||||
})
|
||||
}
|
||||
if resp.StatusCode == http.StatusUnauthorized && !retriedRotatedToken {
|
||||
if rotatedToken := s.rotatedClaudeAccessToken(ctx, account, token); rotatedToken != "" {
|
||||
_ = resp.Body.Close()
|
||||
token = rotatedToken
|
||||
retriedRotatedToken = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// Bill the final Anthropic effort after conversion and account normalization.
|
||||
// For example, OpenAI xhigh is forwarded as output_config.effort=max.
|
||||
reasoningEffort := NormalizeClaudeOutputEffort(gjson.GetBytes(forwardedBody, "output_config.effort").String())
|
||||
reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, forwardedBody, mappedModel)
|
||||
|
||||
// 11. Send request
|
||||
resp, err := s.httpUpstream.DoWithTLS(upstreamReq, proxyURL, account.ID, account.Concurrency, s.tlsFPProfileService.ResolveTLSProfile(account))
|
||||
if err != nil {
|
||||
if resp != nil && resp.Body != nil {
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
return nil, s.handleUpstreamTransportError(ctx, c, account, err, OpsUpstreamErrorEvent{
|
||||
UpstreamURL: safeUpstreamURL(upstreamReq.URL.String()),
|
||||
})
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// 12. Handle error response with failover
|
||||
if resp.StatusCode >= 400 {
|
||||
respBody, _ := s.readUpstreamErrorBody(resp)
|
||||
@@ -385,6 +398,7 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse(
|
||||
startTime time.Time,
|
||||
clientToolMapping apicompat.ResponsesClientToolMapping,
|
||||
) (*ForwardResult, error) {
|
||||
observer := beginUpstreamResponseModelObservation(c)
|
||||
requestID := resp.Header.Get("x-request-id")
|
||||
|
||||
scanner := bufio.NewScanner(resp.Body)
|
||||
@@ -427,6 +441,7 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse(
|
||||
continue
|
||||
}
|
||||
|
||||
observer.ObserveAnthropic([]byte(payload))
|
||||
streamStatus.observe(&event, payload)
|
||||
if streamStatus.upstreamErrType != "" {
|
||||
break
|
||||
@@ -483,7 +498,10 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse(
|
||||
_ = resp.Body.Close()
|
||||
writeResponsesError(c, http.StatusBadGateway, "server_error", failure.message)
|
||||
return &ForwardResult{
|
||||
RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage,
|
||||
UpstreamResponseModel: observer.Model(),
|
||||
UpstreamResponseModelConflict: observer.Conflict(),
|
||||
UpstreamResponseServiceTier: observer.ServiceTier(),
|
||||
RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage,
|
||||
Model: originalModel, UpstreamModel: mappedModel, ReasoningEffort: reasoningEffort,
|
||||
Duration: time.Since(startTime),
|
||||
}, failure.err
|
||||
@@ -532,14 +550,17 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse(
|
||||
}
|
||||
|
||||
return &ForwardResult{
|
||||
RequestID: requestID,
|
||||
UpstreamHeaders: resp.Header,
|
||||
Usage: usage,
|
||||
Model: originalModel,
|
||||
UpstreamModel: mappedModel,
|
||||
ReasoningEffort: reasoningEffort,
|
||||
Stream: false,
|
||||
Duration: time.Since(startTime),
|
||||
UpstreamResponseModel: observer.Model(),
|
||||
UpstreamResponseModelConflict: observer.Conflict(),
|
||||
UpstreamResponseServiceTier: observer.ServiceTier(),
|
||||
RequestID: requestID,
|
||||
UpstreamHeaders: resp.Header,
|
||||
Usage: usage,
|
||||
Model: originalModel,
|
||||
UpstreamModel: mappedModel,
|
||||
ReasoningEffort: reasoningEffort,
|
||||
Stream: false,
|
||||
Duration: time.Since(startTime),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -554,6 +575,7 @@ func (s *GatewayService) handleResponsesStreamingResponse(
|
||||
startTime time.Time,
|
||||
clientToolMapping apicompat.ResponsesClientToolMapping,
|
||||
) (*ForwardResult, error) {
|
||||
observer := beginUpstreamResponseModelObservation(c)
|
||||
requestID := resp.Header.Get("x-request-id")
|
||||
|
||||
if s.responseHeaderFilter != nil {
|
||||
@@ -579,16 +601,19 @@ func (s *GatewayService) handleResponsesStreamingResponse(
|
||||
|
||||
resultWithUsage := func() *ForwardResult {
|
||||
return &ForwardResult{
|
||||
RequestID: requestID,
|
||||
UpstreamHeaders: resp.Header,
|
||||
Usage: usage,
|
||||
Model: originalModel,
|
||||
UpstreamModel: mappedModel,
|
||||
ReasoningEffort: reasoningEffort,
|
||||
Stream: true,
|
||||
Duration: time.Since(startTime),
|
||||
FirstTokenMs: firstTokenMs,
|
||||
ClientDisconnect: stream.clientDisconnected,
|
||||
UpstreamResponseModel: observer.Model(),
|
||||
UpstreamResponseModelConflict: observer.Conflict(),
|
||||
UpstreamResponseServiceTier: observer.ServiceTier(),
|
||||
RequestID: requestID,
|
||||
UpstreamHeaders: resp.Header,
|
||||
Usage: usage,
|
||||
Model: originalModel,
|
||||
UpstreamModel: mappedModel,
|
||||
ReasoningEffort: reasoningEffort,
|
||||
Stream: true,
|
||||
Duration: time.Since(startTime),
|
||||
FirstTokenMs: firstTokenMs,
|
||||
ClientDisconnect: stream.clientDisconnected,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -666,7 +691,7 @@ func (s *GatewayService) handleResponsesStreamingResponse(
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
out := string(reverseToolNamesIfPresent(c, []byte(sse)))
|
||||
out := reverseToolNamesIfPresentString(c, sse)
|
||||
fmt.Fprint(c.Writer, out) //nolint:errcheck
|
||||
}
|
||||
c.Writer.Flush()
|
||||
@@ -705,6 +730,7 @@ func (s *GatewayService) handleResponsesStreamingResponse(
|
||||
continue
|
||||
}
|
||||
|
||||
observer.ObserveAnthropic([]byte(payload))
|
||||
stream.observe(&event, payload)
|
||||
if stream.upstreamErrType != "" {
|
||||
break
|
||||
|
||||
@@ -5,8 +5,10 @@ package service
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
@@ -17,7 +19,7 @@ import (
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// message-level output_config ↔ mid-conversation-output-config beta
|
||||
// message-level output_config ↔ mid-conversation-output-config / per-turn-control beta
|
||||
// ============================================================================
|
||||
//
|
||||
// 背景:pi-ai(Harness 使用的 Anthropic provider)会为 opus5 生成形如
|
||||
@@ -32,11 +34,11 @@ import (
|
||||
// "output_config: Extra inputs are not permitted"
|
||||
//
|
||||
// 修复策略(剥字段,不注入 beta):
|
||||
// - header 缺该 token:仅为携带 message-level output_config 的消息剥此字段;
|
||||
// - header 缺这两种 token:仅为携带 message-level output_config 的消息剥此字段;
|
||||
// role=system 且 content 无正文(缺失 / null / 空 string / 空 array / 仅空
|
||||
// text 块)时整条删除;system 有正文保留正文与其余字段;user/assistant 只剥
|
||||
// 字段,绝不整条删除。
|
||||
// - header 含该 token:完全保留。
|
||||
// - header 含任一 token:完全保留。
|
||||
// - 无任何 message-level output_config:字节 no-op。
|
||||
// - 顶层 output_config / effort 不受该 beta 约束,本增量不触碰。
|
||||
//
|
||||
@@ -154,10 +156,120 @@ func TestSanitizeAnthropicBodyForBetaTokens_MidConversationOutputConfig_SystemWi
|
||||
// header 含该 beta → 完全保留,字节 no-op(即使是空控制 system 消息)。
|
||||
func TestSanitizeAnthropicBodyForBetaTokens_MidConversationOutputConfig_ByteNoopWhenBetaPresent(t *testing.T) {
|
||||
body := []byte(`{"model":"claude-opus-5","output_config":{"effort":"high"},"messages":[{"role":"system","content":[],"output_config":{"effort":"high"}},{"role":"user","content":"hi"}]}`)
|
||||
out, changed := sanitizeAnthropicBodyForBetaTokens(body,
|
||||
"claude-code-20250219,oauth-2025-04-20,"+claude.BetaMidConversationOutputConfig)
|
||||
require.False(t, changed, "header 含 mid-conversation-output-config beta → 完全保留")
|
||||
require.True(t, bytes.Equal(body, out), "含 beta 时必须字节 no-op")
|
||||
for _, beta := range []string{
|
||||
claude.BetaMidConversationOutputConfig,
|
||||
"per-turn-control-2026-07-01",
|
||||
"per-turn-control-2026-07-01," + claude.BetaMidConversationOutputConfig,
|
||||
} {
|
||||
t.Run(beta, func(t *testing.T) {
|
||||
out, changed := sanitizeAnthropicBodyForBetaTokens(body, "claude-code-20250219, "+beta+" ")
|
||||
require.False(t, changed, "a supported beta must preserve message-level output_config")
|
||||
require.True(t, bytes.Equal(body, out), "含 beta 时必须字节 no-op")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestForward_PerTurnControlMessageOutputConfig(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
const perTurnBeta = "per-turn-control-2026-07-01"
|
||||
const body = `{"model":"claude-opus-5","max_tokens":256,"output_config":{"effort":"high"},` +
|
||||
`"metadata":{"user_id":"user_a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2_account_550e8400-e29b-41d4-a716-446655440000_session_123e4567-e89b-12d3-a456-426614174000"},` +
|
||||
`"messages":[{"role":"user","content":"Hello"},{"role":"assistant","content":"Hi"},` +
|
||||
`{"role":"system","content":[],"output_config":{"effort":"low"}},` +
|
||||
`{"role":"user","content":"Summarize that in one sentence."}]}`
|
||||
for _, mode := range []string{"oauth_claude_code", "oauth_mimic", "apikey", "apikey_passthrough"} {
|
||||
for _, withBeta := range []bool{true, false} {
|
||||
name := "without_beta"
|
||||
if withBeta {
|
||||
name = "with_beta"
|
||||
}
|
||||
t.Run(mode+"/"+name, func(t *testing.T) {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body))
|
||||
c.Request.Header.Set("User-Agent", "claude-cli/2.1.321")
|
||||
if mode == "oauth_mimic" {
|
||||
c.Request.Header.Set("User-Agent", "third-party-client/1.0")
|
||||
}
|
||||
if withBeta {
|
||||
c.Request.Header.Set("Anthropic-Beta", "claude-code-20250219,"+perTurnBeta)
|
||||
}
|
||||
account := newAnthropicAPIKeyAccountForTest()
|
||||
account.Extra["anthropic_passthrough"] = mode == "apikey_passthrough"
|
||||
if strings.HasPrefix(mode, "oauth") {
|
||||
account = newAnthropicOAuthAccountForPartialUsageTest()
|
||||
}
|
||||
upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"id":"msg_test","type":"message","role":"assistant",` +
|
||||
`"model":"claude-opus-5","content":[{"type":"text","text":"OK"}],"stop_reason":"end_turn",` +
|
||||
`"usage":{"input_tokens":10,"output_tokens":1}}`)),
|
||||
}}
|
||||
parsed, err := ParseGatewayRequest(NewRequestBodyRef([]byte(body)), PlatformAnthropic)
|
||||
require.NoError(t, err)
|
||||
svc := newForwardPartialUsageServiceForTest(upstream)
|
||||
_, err = svc.Forward(context.Background(), c, account, parsed)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, upstream.lastReq)
|
||||
|
||||
beta := getHeaderRaw(upstream.lastReq.Header, "anthropic-beta")
|
||||
require.Equal(t, withBeta && mode != "oauth_mimic", anthropicBetaTokensContains(beta, perTurnBeta))
|
||||
wantControl := withBeta || mode == "oauth_mimic"
|
||||
messages := gjson.GetBytes(upstream.lastBody, "messages").Array()
|
||||
if wantControl {
|
||||
require.Len(t, messages, 4)
|
||||
require.Equal(t, "system", messages[2].Get("role").String())
|
||||
require.Equal(t, "[]", messages[2].Get("content").Raw)
|
||||
require.Equal(t, "low", messages[2].Get("output_config.effort").String())
|
||||
} else {
|
||||
require.Len(t, messages, 3)
|
||||
}
|
||||
require.Equal(t, "Hello", messages[0].Get("content").String())
|
||||
require.Equal(t, "Hi", messages[1].Get("content").String())
|
||||
require.Equal(t, "Summarize that in one sentence.", messages[len(messages)-1].Get("content").String())
|
||||
require.Equal(t, "high", gjson.GetBytes(upstream.lastBody, "output_config.effort").String())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUpstreamRequest_PerTurnControlPolicyFilter(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
const perTurnBeta = "per-turn-control-2026-07-01"
|
||||
const midConversationBeta = "mid-conversation-output-config-2026-07-01"
|
||||
body := []byte(`{"model":"claude-opus-5","messages":[{"role":"user","content":"Hello"},` +
|
||||
`{"role":"system","content":[],"output_config":{"effort":"low"}}]}`)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
drop []string
|
||||
keep bool
|
||||
}{
|
||||
{"drop_per_turn_only", []string{perTurnBeta}, true},
|
||||
{"drop_mid_conversation_only", []string{midConversationBeta}, true},
|
||||
{"drop_both", []string{perTurnBeta, midConversationBeta}, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
|
||||
c.Request.Header.Set("Anthropic-Beta", "claude-code-20250219,"+perTurnBeta+","+midConversationBeta)
|
||||
c.Set(betaPolicyFilterSetKey, buildBetaTokenSet(tc.drop))
|
||||
svc := &GatewayService{cfg: &config.Config{}}
|
||||
req, _, err := svc.buildUpstreamRequest(context.Background(), c,
|
||||
newAnthropicOAuthAccountForPartialUsageTest(), body,
|
||||
"oauth-token", "oauth", "claude-opus-5", false, false)
|
||||
require.NoError(t, err)
|
||||
for _, token := range tc.drop {
|
||||
require.False(t, anthropicBetaTokensContains(getHeaderRaw(req.Header, "anthropic-beta"), token))
|
||||
}
|
||||
out := readUpstreamBodyForTest(t, req)
|
||||
require.Equal(t, tc.keep, gjson.GetBytes(out, "messages.1.output_config").Exists())
|
||||
if tc.keep {
|
||||
require.Equal(t, "low", gjson.GetBytes(out, "messages.1.output_config.effort").String())
|
||||
} else {
|
||||
require.Len(t, gjson.GetBytes(out, "messages").Array(), 1)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 无 message-level output_config(仅有顶层 output_config,或完全没有)→ 字节 no-op。
|
||||
|
||||
Loaded 100 of 197 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user