- 后端 Go+Gin+GORM: 配置(OT_ env)/SQLite/Postgres 双驱动、用户体系(argon2id+JWT access/refresh)、 API Key(sk- 48位, 仅存 SHA-256 哈希) - 代理网关: /v1/chat/completions、/v1/responses、/v1/messages、/v1/models;错误按客户端协议返回 - 三协议互转(convert 包): Chat↔Messages↔Responses 请求/响应 + 流式 SSE 逐事件转换(直通优先) - 用量计费: 异步批量记账、余额扣减、balance_logs、usage_daily 日聚合 - 管理 API: 用户/渠道 CRUD+测试+模型导入/模型定价+绑定/统计/系统配置 - 前端 Vue3+TS+Tailwind(taste-skill 设计 tokens): Landing/登录注册/控制台/管理后台, 自建组件+Phosphor 图标+自建 SVG 趋势图, 已过 web-design-guidelines 复查 - mock 上游: OpenAI+Anthropic 双协议模拟(含流式) Co-Authored-By: Claude <noreply@anthropic.com>
63 lines
1.9 KiB
Go
63 lines
1.9 KiB
Go
// Package channel 渠道仓储:选择、密钥加解密、模型解析。
|
|
// M1 实现最小选择逻辑(优先级+权重取第一个健康启用的渠道);
|
|
// 负载均衡/健康检查/故障转移在 M5 完善。
|
|
package channel
|
|
|
|
import (
|
|
"errors"
|
|
|
|
"github.com/openteam/server/internal/pkg/crypto"
|
|
"github.com/openteam/server/internal/store"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
var ErrNoChannel = errors.New("no available channel")
|
|
|
|
type Service struct {
|
|
db *gorm.DB
|
|
enc *crypto.Encryptor
|
|
}
|
|
|
|
func NewService(db *gorm.DB, enc *crypto.Encryptor) *Service {
|
|
return &Service{db: db, enc: enc}
|
|
}
|
|
|
|
// Select 选择处理请求的渠道:启用 + 健康,按 priority 升序、weight 降序。
|
|
func (s *Service) Select() (*store.Channel, error) {
|
|
var chs []store.Channel
|
|
if err := s.db.Where("enabled = ? AND health_status = ?", true, store.ChannelHealthHealthy).
|
|
Order("priority ASC, weight DESC, id ASC").Find(&chs).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
if len(chs) == 0 {
|
|
return nil, ErrNoChannel
|
|
}
|
|
return &chs[0], nil
|
|
}
|
|
|
|
// UpstreamKey 解密渠道上游密钥。
|
|
func (s *Service) UpstreamKey(ch *store.Channel) (string, error) {
|
|
return s.enc.Decrypt(ch.APIKeyEnc)
|
|
}
|
|
|
|
// ResolveModel 按全局模型名找到绑定渠道;M1 简化:返回绑定该模型的第一个健康渠道。
|
|
func (s *Service) ResolveModel(modelName string) (*store.Channel, *store.ChannelModelBinding, error) {
|
|
var m store.Model
|
|
if err := s.db.Where("name = ? AND enabled = ?", modelName, true).First(&m).Error; err != nil {
|
|
return nil, nil, err
|
|
}
|
|
var b store.ChannelModelBinding
|
|
if err := s.db.Where("model_id = ?", m.ID).
|
|
Order("weight DESC, id ASC").First(&b).Error; err != nil {
|
|
return nil, nil, err
|
|
}
|
|
var ch store.Channel
|
|
if err := s.db.First(&ch, b.ChannelID).Error; err != nil {
|
|
return nil, nil, err
|
|
}
|
|
if !ch.Enabled || ch.HealthStatus != store.ChannelHealthHealthy {
|
|
return nil, nil, ErrNoChannel
|
|
}
|
|
return &ch, &b, nil
|
|
}
|