M0-M4: 推倒重来基线(基建+用户/密钥/核心代理+前端+管理后台+三协议互转)
- 后端 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>
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
// Package proxy API 网关核心:代理 /v1/chat/completions、/v1/responses、/v1/models。
|
||||
// M1:对 OpenAI 渠道直通(passthrough),不转格式;M3 起加入协议转换。
|
||||
// Package proxy API 网关核心:代理 /v1/chat/completions、/v1/responses、/v1/messages、/v1/models。
|
||||
// M1 直通 OpenAI 渠道;M4 起按客户端协议 × 渠道协议自动转换(见 convert)。
|
||||
package proxy
|
||||
|
||||
import (
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/openteam/server/internal/channel"
|
||||
"github.com/openteam/server/internal/pkg/apikey"
|
||||
"github.com/openteam/server/internal/pkg/crypto"
|
||||
"github.com/openteam/server/internal/proxy/convert"
|
||||
"github.com/openteam/server/internal/store"
|
||||
"github.com/openteam/server/internal/usage"
|
||||
"gorm.io/gorm"
|
||||
@@ -43,29 +44,39 @@ func NewGateway(db *gorm.DB, enc *crypto.Encryptor, rec *usage.Recorder) *Gatewa
|
||||
|
||||
// Auth 代理鉴权中间件:Bearer sk-xxx → 哈希查表 → 校验状态/过期/模型白名单。
|
||||
func (g *Gateway) Auth(c *gin.Context) {
|
||||
// 先按路径确定客户端协议,保证 Auth 阶段错误也按协议格式返回
|
||||
switch c.Request.URL.Path {
|
||||
case "/v1/messages":
|
||||
c.Set("protocol", convert.ProtoMessages)
|
||||
case "/v1/responses":
|
||||
c.Set("protocol", convert.ProtoResponses)
|
||||
default:
|
||||
c.Set("protocol", convert.ProtoChat)
|
||||
}
|
||||
|
||||
auth := c.GetHeader("Authorization")
|
||||
key := strings.TrimPrefix(auth, "Bearer ")
|
||||
key = strings.TrimSpace(key)
|
||||
if !apikey.Valid(key) {
|
||||
openAIError(c, http.StatusUnauthorized, "invalid_api_key", "Invalid API key format. Expected: Bearer sk-...")
|
||||
apiError(c, http.StatusUnauthorized, "invalid_api_key", "Invalid API key format. Expected: Bearer sk-...")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
hash := apikey.Hash(key)
|
||||
var k store.APIKey
|
||||
if err := g.db.Where("key_hash = ? AND status = ?", hash, store.KeyStatusActive).First(&k).Error; err != nil {
|
||||
openAIError(c, http.StatusUnauthorized, "invalid_api_key", "Invalid API key")
|
||||
apiError(c, http.StatusUnauthorized, "invalid_api_key", "Invalid API key")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
var u store.User
|
||||
if err := g.db.First(&u, k.UserID).Error; err != nil || u.Status != store.UserStatusActive {
|
||||
openAIError(c, http.StatusForbidden, "user_disabled", "User account is disabled")
|
||||
apiError(c, http.StatusForbidden, "user_disabled", "User account is disabled")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if k.ExpiresAt != nil && time.Now().After(*k.ExpiresAt) {
|
||||
openAIError(c, http.StatusUnauthorized, "key_expired", "API key has expired")
|
||||
apiError(c, http.StatusUnauthorized, "key_expired", "API key has expired")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
@@ -84,10 +95,12 @@ func (g *Gateway) Handle(c *gin.Context) {
|
||||
g.chatCompletions(c)
|
||||
case c.Request.URL.Path == "/v1/responses":
|
||||
g.responses(c)
|
||||
case c.Request.URL.Path == "/v1/messages":
|
||||
g.messages(c)
|
||||
case c.Request.URL.Path == "/v1/models" && c.Request.Method == http.MethodGet:
|
||||
g.models(c)
|
||||
default:
|
||||
openAIError(c, http.StatusNotFound, "not_found", "Unknown endpoint: "+c.Request.URL.Path)
|
||||
apiError(c, http.StatusNotFound, "not_found", "Unknown endpoint: "+c.Request.URL.Path)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,7 +108,7 @@ func (g *Gateway) Handle(c *gin.Context) {
|
||||
func (g *Gateway) models(c *gin.Context) {
|
||||
var ms []store.Model
|
||||
if err := g.db.Where("enabled = ?", true).Order("sort ASC, id ASC").Find(&ms).Error; err != nil {
|
||||
openAIError(c, http.StatusInternalServerError, "internal_error", "failed to load models")
|
||||
apiError(c, http.StatusInternalServerError, "internal_error", "failed to load models")
|
||||
return
|
||||
}
|
||||
data := make([]gin.H, 0, len(ms))
|
||||
@@ -110,12 +123,22 @@ func (g *Gateway) models(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"object": "list", "data": data})
|
||||
}
|
||||
|
||||
// selectChannel 选渠道:优先按模型绑定解析,退化为全局选渠道。
|
||||
func (g *Gateway) selectChannel(c *gin.Context, model string) (*store.Channel, error) {
|
||||
if model != "" {
|
||||
if ch, _, err := g.ch.ResolveModel(model); err == nil {
|
||||
return ch, nil
|
||||
}
|
||||
}
|
||||
return g.ch.Select()
|
||||
}
|
||||
|
||||
// resolveUser 取当前用户(含余额)。
|
||||
func (g *Gateway) resolveUser(c *gin.Context) (*store.User, bool) {
|
||||
uid, _ := c.Get(CtxUserID)
|
||||
var u store.User
|
||||
if err := g.db.First(&u, uid).Error; err != nil {
|
||||
openAIError(c, http.StatusUnauthorized, "invalid_api_key", "Invalid API key")
|
||||
apiError(c, http.StatusUnauthorized, "invalid_api_key", "Invalid API key")
|
||||
return nil, false
|
||||
}
|
||||
return &u, true
|
||||
@@ -124,10 +147,63 @@ func (g *Gateway) resolveUser(c *gin.Context) (*store.User, bool) {
|
||||
// checkBalance 余额不足返回 402(PLANNING §4.4.3)。
|
||||
func (g *Gateway) checkBalance(c *gin.Context, u *store.User) bool {
|
||||
if u.Balance <= 0 {
|
||||
openAIError(c, http.StatusPaymentRequired, "insufficient_balance", "Insufficient balance. Please recharge or contact admin.")
|
||||
apiError(c, http.StatusPaymentRequired, "insufficient_balance", "Insufficient balance. Please recharge or contact admin.")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 协议分派
|
||||
|
||||
// upstreamProtoFor 根据渠道 provider 与客户端协议确定上游协议与路径。
|
||||
func upstreamProtoFor(provider, clientProto string) string {
|
||||
switch provider {
|
||||
case store.ChannelProviderAnthropic:
|
||||
return convert.ProtoMessages
|
||||
case store.ChannelProviderOpenAI:
|
||||
if clientProto == convert.ProtoMessages {
|
||||
return convert.ProtoChat
|
||||
}
|
||||
return clientProto
|
||||
default: // compatible:假定 OpenAI Chat 形状
|
||||
return convert.ProtoChat
|
||||
}
|
||||
}
|
||||
|
||||
func upstreamPath(proto string) string {
|
||||
switch proto {
|
||||
case convert.ProtoMessages:
|
||||
return "/v1/messages"
|
||||
case convert.ProtoResponses:
|
||||
return "/v1/responses"
|
||||
default:
|
||||
return "/v1/chat/completions"
|
||||
}
|
||||
}
|
||||
|
||||
// upstreamPlan 描述一次代理请求的上游访问方式。
|
||||
type upstreamPlan struct {
|
||||
path string // 上游路径
|
||||
body []byte // 已转换的请求体
|
||||
lineConv func([]byte) []byte // 流式逐行转换(nil=直通)
|
||||
bodyConv func([]byte) ([]byte, error) // 非流式响应体转换(nil=直通)
|
||||
}
|
||||
|
||||
// prepareUpstream 计算上游访问计划:协议匹配直通,否则转换。
|
||||
func prepareUpstream(provider, clientProto string, body []byte) (*upstreamPlan, error) {
|
||||
up := upstreamProtoFor(provider, clientProto)
|
||||
plan := &upstreamPlan{path: upstreamPath(up), body: body}
|
||||
if up != clientProto {
|
||||
converted, err := convert.ConvertRequest(body, clientProto, up)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
plan.body = converted
|
||||
plan.lineConv = convert.NewStreamTransformer(up, clientProto)
|
||||
plan.bodyConv = func(b []byte) ([]byte, error) { return convert.ConvertResponse(b, up, clientProto) }
|
||||
}
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
var errNoChannel = errors.New("no available channel")
|
||||
|
||||
Reference in New Issue
Block a user