mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
fix(pricing): check remote hash in background at startup
Initialize waited on the remote hash fetch before the server started listening, so when the hash request hung, startup stayed blocked until the client timeout (10 s). The local price file is already loaded at that point, so the hash check and any download now run in a goroutine; the periodic scheduler is unchanged. The model-count log in Initialize reads pricingData under the read lock because a background download may replace it.
This commit is contained in:
1 parent
530c5e3a4f
commit
c45ef4116f
2 files changed
+162
-19
No files matched your search
@@ -343,7 +343,10 @@ func (s *PricingService) Initialize() error {
|
||||
// 启动定时更新
|
||||
s.startUpdateScheduler()
|
||||
|
||||
logger.LegacyPrintf("service.pricing", "[Pricing] Service initialized with %d models", len(s.pricingData))
|
||||
s.mu.RLock()
|
||||
modelCount := len(s.pricingData)
|
||||
s.mu.RUnlock()
|
||||
logger.LegacyPrintf("service.pricing", "[Pricing] Service initialized with %d models", modelCount)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -416,25 +419,10 @@ func (s *PricingService) checkAndUpdatePricing() error {
|
||||
return s.downloadPricingData()
|
||||
}
|
||||
|
||||
// 如果配置了哈希URL,通过远程哈希检查是否有更新
|
||||
// 如果配置了哈希URL,通过远程哈希检查是否有更新。本地文件已加载,服务已可用,
|
||||
// 校验放到后台做:远端慢或不通时不挡启动与监听(fetchRemoteHash 请求挂住时会一直等到客户端超时)。
|
||||
if s.cfg.Pricing.HashURL != "" {
|
||||
remoteHash, err := s.fetchRemoteHash()
|
||||
if err != nil {
|
||||
logger.LegacyPrintf("service.pricing", "[Pricing] Failed to fetch remote hash on startup: %v", err)
|
||||
return nil // 已加载本地文件,哈希获取失败不影响启动
|
||||
}
|
||||
|
||||
s.mu.RLock()
|
||||
localHash := s.localHash
|
||||
s.mu.RUnlock()
|
||||
|
||||
if localHash == "" || remoteHash != localHash {
|
||||
logger.LegacyPrintf("service.pricing", "[Pricing] Remote hash differs on startup (local=%s remote=%s), downloading...",
|
||||
localHash[:min(8, len(localHash))], remoteHash[:min(8, len(remoteHash))])
|
||||
if err := s.downloadPricingData(); err != nil {
|
||||
logger.LegacyPrintf("service.pricing", "[Pricing] Download failed, using existing file: %v", err)
|
||||
}
|
||||
}
|
||||
go s.checkRemoteHashOnStartup()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -457,6 +445,27 @@ func (s *PricingService) checkAndUpdatePricing() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkRemoteHashOnStartup 启动后在后台比对远程哈希,不同则下载;失败只记日志,沿用已加载的本地文件。
|
||||
func (s *PricingService) checkRemoteHashOnStartup() {
|
||||
remoteHash, err := s.fetchRemoteHash()
|
||||
if err != nil {
|
||||
logger.LegacyPrintf("service.pricing", "[Pricing] Failed to fetch remote hash on startup: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
s.mu.RLock()
|
||||
localHash := s.localHash
|
||||
s.mu.RUnlock()
|
||||
|
||||
if localHash == "" || remoteHash != localHash {
|
||||
logger.LegacyPrintf("service.pricing", "[Pricing] Remote hash differs on startup (local=%s remote=%s), downloading...",
|
||||
localHash[:min(8, len(localHash))], remoteHash[:min(8, len(remoteHash))])
|
||||
if err := s.downloadPricingData(); err != nil {
|
||||
logger.LegacyPrintf("service.pricing", "[Pricing] Download failed, using existing file: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// syncWithRemote 与远程同步(基于哈希校验)
|
||||
func (s *PricingService) syncWithRemote() error {
|
||||
// 如果配置了哈希URL,从远程获取哈希进行比对
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// blockingHashRemoteClient 的 FetchHashText 一直阻塞到 release 关闭,模拟远端不可达时等满超时。
|
||||
type blockingHashRemoteClient struct {
|
||||
started chan struct{}
|
||||
release chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (c *blockingHashRemoteClient) FetchPricingJSON(context.Context, string) ([]byte, error) {
|
||||
return nil, context.DeadlineExceeded
|
||||
}
|
||||
|
||||
func (c *blockingHashRemoteClient) FetchHashText(context.Context, string) (string, error) {
|
||||
c.once.Do(func() { close(c.started) })
|
||||
<-c.release
|
||||
return "", context.DeadlineExceeded
|
||||
}
|
||||
|
||||
// failingHashRemoteClient 的哈希请求立即失败,下载请求只计数。
|
||||
type failingHashRemoteClient struct {
|
||||
mu sync.Mutex
|
||||
hashCalls int
|
||||
downloads int
|
||||
}
|
||||
|
||||
func (c *failingHashRemoteClient) FetchPricingJSON(context.Context, string) ([]byte, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.downloads++
|
||||
return nil, errors.New("unexpected download")
|
||||
}
|
||||
|
||||
func (c *failingHashRemoteClient) FetchHashText(context.Context, string) (string, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.hashCalls++
|
||||
return "", errors.New("hash endpoint unreachable")
|
||||
}
|
||||
|
||||
func (c *failingHashRemoteClient) counts() (hashCalls, downloads int) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.hashCalls, c.downloads
|
||||
}
|
||||
|
||||
func newStartupPricingService(t *testing.T, remote PricingRemoteClient) *PricingService {
|
||||
t.Helper()
|
||||
svc := NewPricingService(&config.Config{Pricing: config.PricingConfig{
|
||||
DataDir: t.TempDir(),
|
||||
RemoteURL: "https://example.com/pricing.json",
|
||||
HashURL: "https://example.com/pricing.sha256",
|
||||
}}, remote)
|
||||
require.NoError(t, os.WriteFile(svc.getPricingFilePath(), []byte(hotReloadCatalogJSON), 0644))
|
||||
return svc
|
||||
}
|
||||
|
||||
// 本地价格文件已在时,启动检查不得等远端哈希:远端不可达也要立即返回,价格表已可用。
|
||||
func TestPricingStartupDoesNotWaitForRemoteHash(t *testing.T) {
|
||||
remote := &blockingHashRemoteClient{started: make(chan struct{}), release: make(chan struct{})}
|
||||
t.Cleanup(func() { close(remote.release) })
|
||||
svc := newStartupPricingService(t, remote)
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- svc.checkAndUpdatePricing() }()
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
require.NoError(t, err)
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("startup must not block on the remote hash fetch")
|
||||
}
|
||||
require.NotNil(t, svc.GetModelPricing("remote-model"), "本地价格表启动即可用")
|
||||
select {
|
||||
case <-remote.started:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("remote hash check must still run in the background")
|
||||
}
|
||||
}
|
||||
|
||||
// 后台哈希校验发现远端哈希不同时,仍要下载并替换价格表。
|
||||
func TestPricingStartupBackgroundCheckDownloadsWhenHashDiffers(t *testing.T) {
|
||||
newBody := `{` + hotReloadModelJSON("remote-model", 3e-6, 6e-6) + `}`
|
||||
newHash := fmt.Sprintf("%x", sha256.Sum256([]byte(newBody)))
|
||||
remote := &stubPricingRemoteClient{body: newBody, hash: newHash}
|
||||
svc := newStartupPricingService(t, remote)
|
||||
|
||||
require.NoError(t, svc.checkAndUpdatePricing())
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
p := svc.GetModelPricing("remote-model")
|
||||
return p != nil && p.InputCostPerToken == 3e-6
|
||||
}, 2*time.Second, 10*time.Millisecond, "后台校验应下载并替换价格表")
|
||||
svc.mu.RLock()
|
||||
require.Equal(t, newHash, svc.localHash)
|
||||
svc.mu.RUnlock()
|
||||
saved, err := os.ReadFile(svc.getPricingFilePath())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, newBody, string(saved))
|
||||
}
|
||||
|
||||
// 后台哈希获取失败时沿用已加载的本地价格表,只记日志,不触发下载。
|
||||
func TestPricingStartupBackgroundCheckKeepsLocalDataWhenHashFetchFails(t *testing.T) {
|
||||
logs, restore := captureStructuredLog(t)
|
||||
defer restore()
|
||||
remote := &failingHashRemoteClient{}
|
||||
svc := newStartupPricingService(t, remote)
|
||||
|
||||
require.NoError(t, svc.checkAndUpdatePricing())
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
return logs.ContainsMessage("Failed to fetch remote hash on startup: hash endpoint unreachable")
|
||||
}, 2*time.Second, 10*time.Millisecond, "哈希获取失败应记日志")
|
||||
hashCalls, downloads := remote.counts()
|
||||
require.Equal(t, 1, hashCalls)
|
||||
require.Zero(t, downloads)
|
||||
p := svc.GetModelPricing("remote-model")
|
||||
require.NotNil(t, p)
|
||||
require.InDelta(t, 1e-6, p.InputCostPerToken, 1e-12)
|
||||
}
|
||||
Reference in new issue
Block a user