Files
sub2api/backend/internal/service/gateway_scheduling_slot_release_test.go
T
lishuangqiang 4ac713c4d4 fix(scheduling): release acquired slot when account hydration fails
newSelectionResult is the only exit for acquired Anthropic/Gemini
selections. When hydrateSelectedAccount failed, the already acquired
Redis concurrency slot was dropped with the error because callers only
receive ReleaseFunc through a successful result.

Release it on the error path, matching the OpenAI path that already does
this via newAcquiredSelectionResult. Without the fix the slot stays
occupied until its TTL expires, so the account can look idle while
requests queue or fail.
2026-11-10 10:55:01 +08:00

51 lines
1.4 KiB
Go

//go:build unit
package service
import (
"context"
"testing"
"github.com/stretchr/testify/require"
)
// hydrate 失败时,已经占用的并发槽位必须在返回前释放,否则调用方拿不到
// ReleaseFunc,槽位会一直泄漏到 TTL 到期。
func TestGatewayServiceNewSelectionResultReleasesSlotOnHydrationError(t *testing.T) {
svc := &GatewayService{
schedulerSnapshot: &SchedulerSnapshotService{},
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
released := 0
selection, err := svc.newSelectionResult(ctx, &Account{ID: 42}, true, func() { released++ }, nil)
require.Error(t, err)
require.Nil(t, selection)
require.Equal(t, 1, released)
}
// hydrate 成功时不能提前释放槽位,ReleaseFunc 应原样交给调用方。
func TestGatewayServiceNewSelectionResultKeepsReleaseOnSuccess(t *testing.T) {
account := &Account{ID: 42, Platform: PlatformAnthropic}
cache := &snapshotHydrationCache{
accounts: map[int64]*Account{account.ID: account},
}
svc := &GatewayService{
schedulerSnapshot: NewSchedulerSnapshotService(cache, nil, nil, nil, nil),
}
released := 0
selection, err := svc.newSelectionResult(context.Background(), account, true, func() { released++ }, nil)
require.NoError(t, err)
require.NotNil(t, selection)
require.Zero(t, released)
require.NotNil(t, selection.ReleaseFunc)
selection.ReleaseFunc()
require.Equal(t, 1, released)
}