fix(claude): 修复版本同步契约测试和缓存刷新

This commit is contained in:
shaw committed 2026-09-23 14:39:29 +08:00
1 parent ca08825935
commit 6452aeffa1
7 files changed
+105 -15

No files matched your search

@@ -953,6 +953,9 @@ func TestAPIContracts(t *testing.T) {
"openai_codex_client_version": "",
"openai_codex_client_version_synced": "",
"openai_codex_version_auto_sync_enabled": true,
"claude_code_client_version": "",
"claude_code_client_version_synced": "",
"claude_code_version_auto_sync_enabled": true,
"openai_fast_policy_settings": {
"rules": []
},
@@ -1270,6 +1273,9 @@ func TestAPIContracts(t *testing.T) {
"openai_codex_client_version": "",
"openai_codex_client_version_synced": "",
"openai_codex_version_auto_sync_enabled": true,
"claude_code_client_version": "",
"claude_code_client_version_synced": "",
"claude_code_version_auto_sync_enabled": true,
"openai_fast_policy_settings": {
"rules": []
},
@@ -2,6 +2,7 @@ package service
import (
"context"
"errors"
"log/slog"
"strings"
"sync"
@@ -129,7 +130,13 @@ func (s *ClaudeCodeVersionSyncService) runOnce() {
return
}
current := NormalizeClaudeCodeClientVersion(s.currentSyncedVersion(ctx))
current, err := s.settingRepo.GetValue(ctx, SettingKeyClaudeCodeClientVersionSynced)
if err != nil && !errors.Is(err, ErrSettingNotFound) {
// 无法确认已有版本时跳过写入,避免数据库短暂故障导致版本降级。
slog.Warn("claude_code_version_sync_current_read_failed", "error", err)
return
}
current = NormalizeClaudeCodeClientVersion(current)
// 只向前推进:上游偶发返回旧数据或重新发布历史 tag 时不把已同步的版本号降级。
if current != "" && CompareVersions(latest, current) <= 0 {
return
@@ -184,14 +191,6 @@ func (s *ClaudeCodeVersionSyncService) autoSyncEnabled(ctx context.Context) bool
return strings.TrimSpace(value) == "true"
}
func (s *ClaudeCodeVersionSyncService) currentSyncedVersion(ctx context.Context) string {
value, err := s.settingRepo.GetValue(ctx, SettingKeyClaudeCodeClientVersionSynced)
if err != nil {
return ""
}
return value
}
// latestClaudeCodeStableReleaseVersion 从 release 列表里挑出最大的稳定版 CLI 版本号。
// 过滤条件:tag 前缀为 v、非草稿、非预发布、版本号须通过 NormalizeClaudeCodeClientVersion
// (严格三段纯数字 semver,且不低于内置基线)。取最大值而非最新发布,
@@ -18,6 +18,7 @@ type claudeCodeVersionSyncSettingRepoStub struct {
mu sync.Mutex
values map[string]string
getErr error
getErrKey string
setErr error
updatedAt time.Time
writes []string
@@ -33,10 +34,14 @@ func newClaudeCodeVersionSyncSettingRepoStub(values map[string]string) *claudeCo
func (r *claudeCodeVersionSyncSettingRepoStub) GetValue(_ context.Context, key string) (string, error) {
r.mu.Lock()
defer r.mu.Unlock()
if r.getErr != nil {
if r.getErr != nil && (r.getErrKey == "" || r.getErrKey == key) {
return "", r.getErr
}
return r.values[key], nil
value, ok := r.values[key]
if !ok {
return "", ErrSettingNotFound
}
return value, nil
}
func (r *claudeCodeVersionSyncSettingRepoStub) Set(_ context.Context, key, value string) error {
@@ -182,6 +187,7 @@ func TestClaudeCodeVersionSyncEnabledByDefaultOrOnError(t *testing.T) {
SettingKeyClaudeCodeVersionAutoSyncEnabled: tt.value,
})
repo.getErr = tt.getErr
repo.getErrKey = SettingKeyClaudeCodeVersionAutoSyncEnabled
github := &claudeCodeVersionSyncGitHubStub{releases: []*GitHubRelease{{TagName: "v2.1.280"}}}
newClaudeCodeVersionSyncService(repo, github).runOnce()
@@ -191,6 +197,20 @@ func TestClaudeCodeVersionSyncEnabledByDefaultOrOnError(t *testing.T) {
}
}
func TestClaudeCodeVersionSyncKeepsValueOnCurrentVersionReadError(t *testing.T) {
repo := newClaudeCodeVersionSyncSettingRepoStub(map[string]string{
SettingKeyClaudeCodeClientVersionSynced: "2.1.281",
})
repo.getErr = errors.New("读取已有版本失败")
repo.getErrKey = SettingKeyClaudeCodeClientVersionSynced
github := &claudeCodeVersionSyncGitHubStub{latest: &GitHubRelease{TagName: "v2.1.280"}}
newClaudeCodeVersionSyncService(repo, github).runOnce()
require.Empty(t, repo.syncedWrites(), "无法确认已有版本时不得覆盖同步值")
require.Equal(t, "2.1.281", repo.values[SettingKeyClaudeCodeClientVersionSynced])
}
// 抓取失败保持既有值,不清空、不降级。两条取数路径都失败才算真正拿不到。
func TestClaudeCodeVersionSyncKeepsValueOnFetchError(t *testing.T) {
repo := newClaudeCodeVersionSyncSettingRepoStub(map[string]string{
@@ -0,0 +1,64 @@
//go:build unit
package service
import (
"context"
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/claude"
"github.com/stretchr/testify/require"
)
func TestGetClaudeCodeClientVersionPriority(t *testing.T) {
for _, tt := range []struct {
name string
manual string
synced string
want string
}{
{name: "手动值优先", manual: "2.1.280", synced: "2.1.281", want: "2.1.280"},
{name: "归一化手动值", manual: " v2.1.280 ", synced: "2.1.281", want: "2.1.280"},
{name: "跟随同步值", synced: "2.1.281", want: "2.1.281"},
{name: "无效手动值回退", manual: "invalid", synced: "2.1.281", want: "2.1.281"},
{name: "无效同步值回退", synced: "2.1.9", want: claude.CLIVersion()},
{name: "未配置时回退", want: claude.CLIVersion()},
} {
t.Run(tt.name, func(t *testing.T) {
repo := &authSourceDefaultsRepoStub{values: map[string]string{
SettingKeyClaudeCodeClientVersion: tt.manual,
SettingKeyClaudeCodeClientVersionSynced: tt.synced,
}}
svc := NewSettingService(repo, &config.Config{})
require.Equal(t, tt.want, svc.GetClaudeCodeClientVersion(context.Background()))
})
}
}
func TestUpdateSettingsClaudeCodeVersionTakesEffectImmediately(t *testing.T) {
ctx := context.Background()
repo := &authSourceDefaultsRepoStub{values: map[string]string{
SettingKeyClaudeCodeClientVersionSynced: "2.1.281",
}}
svc := NewSettingService(repo, &config.Config{})
resetGatewayForwardingSettingsCacheForTest(t)
defer svc.refreshCachedSettings(&SystemSettings{})
require.Equal(t, "2.1.281", svc.GetClaudeCodeClientVersion(ctx))
settings := &SystemSettings{
ClaudeCodeClientVersion: "2.1.280",
ClaudeCodeVersionAutoSyncEnabled: true,
}
require.NoError(t, svc.UpdateSettings(ctx, settings))
require.Equal(t, "2.1.280", svc.GetClaudeCodeClientVersion(ctx), "保存手动版本后应立即生效")
require.NotContains(t, repo.updates, SettingKeyClaudeCodeClientVersionSynced)
require.Equal(t, "2.1.281", repo.values[SettingKeyClaudeCodeClientVersionSynced])
// 清空手动值并关闭后续同步时,仍保留并使用已有同步值。
settings.ClaudeCodeClientVersion = ""
settings.ClaudeCodeVersionAutoSyncEnabled = false
require.NoError(t, svc.UpdateSettings(ctx, settings))
require.Equal(t, "2.1.281", svc.GetClaudeCodeClientVersion(ctx))
require.Equal(t, "false", repo.values[SettingKeyClaudeCodeVersionAutoSyncEnabled])
}
@@ -746,6 +746,7 @@ func (s *SettingService) refreshCachedSettings(settings *SystemSettings) {
// 版本号缓存只做失效,不在此重算:生效值还取决于自动同步写入的 synced 键,
// 这里没有它的最新值,重算会把同步结果覆盖成陈旧值。
s.InvalidateOpenAICodexClientVersionCache()
s.InvalidateClaudeCodeClientVersionCache()
openAIAdvancedSchedulerSettingSF.Forget(openAIAdvancedSchedulerSettingKey)
openAIAdvancedSchedulerSettingCache.Store(&cachedOpenAIAdvancedSchedulerSetting{
lowUpstreamRatePriorityEnabled: settings.OpenAILowUpstreamRatePriorityEnabled,
@@ -543,9 +543,9 @@ export default {
openaiCodexVersionAutoSyncHint: 'Fetches the latest stable client version from the official repository every 6 hours, so you never need to upgrade this service just to keep the version current. When disabled, only the version above or the built-in default is used.',
openaiCodexVersionSyncedValue: 'Currently synced: {version}',
claudeCodeClientVersion: 'Claude Code client version',
claudeCodeClientVersionHint: "The client version this gateway declares upstream when impersonating the official Claude Code CLI. Leave empty to use the auto-synced latest official release; setting a value pins it and stops following auto-sync. The SUB2API_CLAUDE_CLI_VERSION environment variable still acts as a fallback and takes priority over this setting.",
claudeCodeClientVersionHint: "The client version this gateway declares upstream when impersonating the official Claude Code CLI. Leave empty to use the auto-synced latest official release; setting a value pins it and stops following auto-sync. The SUB2API_CLAUDE_CLI_VERSION environment variable or built-in version is used only when neither the manual nor synced value is valid.",
claudeCodeVersionAutoSync: 'Auto-sync Claude Code version',
claudeCodeVersionAutoSyncHint: 'Fetches the latest Claude Code client version from the official release channel every hour, so you never need to upgrade this service just to keep the version current. When disabled, only the version above or the environment-variable fallback is used.',
claudeCodeVersionAutoSyncHint: 'Fetches the latest Claude Code client version from the official release channel every hour, so you never need to upgrade this service just to keep the version current. When disabled, fetching stops but the previously synced version remains available. The manual version above always takes priority.',
claudeCodeVersionSyncedValue: 'Currently synced: {version}',
codexHardeningTitle: "Codex Settings",
codexClientRestrictionTitle: "Codex client restriction",
@@ -536,9 +536,9 @@ export default {
openaiCodexVersionAutoSyncHint: '每 6 小时从官方仓库获取最新稳定版客户端版本号,无需为了跟版本而升级本服务。关闭后仅使用上方手填版本或内置版本。',
openaiCodexVersionSyncedValue: '当前同步到:{version}',
claudeCodeClientVersion: 'Claude Code 客户端版本号',
claudeCodeClientVersionHint: '网关伪装为官方 Claude Code CLI 时对上游声明的客户端版本号。留空表示使用自动同步到的官方最新版本;填写后固定为该版本,不再跟随同步。环境变量 SUB2API_CLAUDE_CLI_VERSION 仍作为兜底,优先级高于此处配置。',
claudeCodeClientVersionHint: '网关伪装为官方 Claude Code CLI 时对上游声明的客户端版本号。留空表示使用自动同步到的官方最新版本;填写后固定为该版本,不再跟随同步。仅在手填值和同步值均不可用时,才回退到环境变量 SUB2API_CLAUDE_CLI_VERSION 或内置版本。',
claudeCodeVersionAutoSync: '自动同步 Claude Code 版本号',
claudeCodeVersionAutoSyncHint: '每小时从官方发布渠道获取最新版本的 Claude Code 客户端版本号,无需为了跟版本而升级本服务。关闭后仅使用上方手填版本或环境变量兜底。',
claudeCodeVersionAutoSyncHint: '每小时从官方发布渠道获取最新版本的 Claude Code 客户端版本号,无需为了跟版本而升级本服务。关闭后停止获取新版本,已同步的版本仍可使用;上方手填版本始终优先。',
claudeCodeVersionSyncedValue: '当前同步到:{version}',
codexHardeningTitle: 'Codex 设置',
codexClientRestrictionTitle: 'Codex 客户端限制',