- 新增 RoutingCache 组件,使用 sync.Map 缓存 Provider 和 Model - 新增 StatsBuffer 组件,使用 sync.Map + atomic.Int64 缓冲统计数据 - 扩展 StatsRepository.BatchUpdate 支持批量增量更新 - 改造 RoutingService/StatsService/ProviderService/ModelService 集成缓存 - 更新 usage-statistics spec,新增 routing-cache 和 stats-buffer spec - 新增单元测试覆盖缓存命中/失效/并发场景
86 lines
2.3 KiB
Go
86 lines
2.3 KiB
Go
package service
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"nex/backend/pkg/modelid"
|
|
|
|
"nex/backend/internal/domain"
|
|
"nex/backend/internal/repository"
|
|
appErrors "nex/backend/pkg/errors"
|
|
)
|
|
|
|
type providerService struct {
|
|
providerRepo repository.ProviderRepository
|
|
modelRepo repository.ModelRepository
|
|
cache *RoutingCache
|
|
}
|
|
|
|
func NewProviderService(providerRepo repository.ProviderRepository, modelRepo repository.ModelRepository, cache *RoutingCache) ProviderService {
|
|
return &providerService{providerRepo: providerRepo, modelRepo: modelRepo, cache: cache}
|
|
}
|
|
|
|
func (s *providerService) Create(provider *domain.Provider) error {
|
|
if err := modelid.ValidateProviderID(provider.ID); err != nil {
|
|
return appErrors.ErrInvalidProviderID
|
|
}
|
|
provider.Enabled = true
|
|
err := s.providerRepo.Create(provider)
|
|
if err != nil {
|
|
if isUniqueConstraintError(err) {
|
|
return appErrors.ErrConflict
|
|
}
|
|
return err
|
|
}
|
|
s.cache.SetProvider(provider)
|
|
return nil
|
|
}
|
|
|
|
func (s *providerService) Get(id string) (*domain.Provider, error) {
|
|
return s.providerRepo.GetByID(id)
|
|
}
|
|
|
|
func (s *providerService) List() ([]domain.Provider, error) {
|
|
return s.providerRepo.List()
|
|
}
|
|
|
|
func (s *providerService) Update(id string, updates map[string]interface{}) error {
|
|
if _, ok := updates["id"]; ok {
|
|
return appErrors.ErrImmutableField
|
|
}
|
|
err := s.providerRepo.Update(id, updates)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.cache.InvalidateProvider(id)
|
|
return nil
|
|
}
|
|
|
|
func (s *providerService) Delete(id string) error {
|
|
err := s.providerRepo.Delete(id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.cache.InvalidateProvider(id)
|
|
return nil
|
|
}
|
|
|
|
// ListEnabledModels 返回所有启用的模型(用于 Models 接口本地聚合)
|
|
func (s *providerService) ListEnabledModels() ([]domain.Model, error) {
|
|
return s.modelRepo.ListEnabled()
|
|
}
|
|
|
|
// GetModelByProviderAndName 按 provider_id 和 model_name 查询模型(用于 ModelInfo 接口本地查询)
|
|
func (s *providerService) GetModelByProviderAndName(providerID, modelName string) (*domain.Model, error) {
|
|
return s.modelRepo.FindByProviderAndModelName(providerID, modelName)
|
|
}
|
|
|
|
// isUniqueConstraintError 判断是否为数据库唯一约束冲突错误
|
|
func isUniqueConstraintError(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
msg := strings.ToLower(err.Error())
|
|
return strings.Contains(msg, "unique constraint") || strings.Contains(msg, "duplicate")
|
|
}
|