后端 - 新增 proxy/convert 三协议(chat/messages/responses)请求、响应与 SSE 流式互转, 以 Chat 为中间模型;usage.go 统一提取三协议 token 用量(含单测) - gateway: 跨协议调度(渠道未声明客户端协议时转为渠道首选格式), streamResponse 按 \n\n 分块逐行转换直通,bufferResponse 转换失败时剥非 JSON 前缀 - gateway: 新增 SetUsageRecorder 注入异步用量记录器 - auth_llm: 修复 key_prefix 查询长度错配([:8] vs 存储的 [:12])导致全部 401; 修复长度 8-11 的 key 切片越界 panic;统一 unauthorized 响应 - usage: 日报表改为增量累加 upsert,避免多次 flush 互相清零;记录协议/错误码/时延等字段 - channel: 新增渠道并发槽 TryAcquire;健康检查支持可配置参数 - api: 新增 admin 渠道/模型/系统配置管理端点(旧端点保留兼容) 前端 - 新增渠道管理、模型管理、系统配置视图与 ChannelModelsDrawer - 新增 ui 基础组件(Button/Badge/Input/Modal)与 protocol.ts - 调整 Toast 样式、密钥页、路由菜单;dev 代理默认指向 3000 端口
215 lines
6.6 KiB
Go
215 lines
6.6 KiB
Go
package router
|
|
|
|
import (
|
|
"context"
|
|
"embed"
|
|
"fmt"
|
|
"io/fs"
|
|
"log"
|
|
"net/http"
|
|
"opencatd-open/internal/api"
|
|
"opencatd-open/internal/channel"
|
|
"opencatd-open/internal/dao"
|
|
"opencatd-open/internal/proxy"
|
|
"opencatd-open/internal/usage"
|
|
"opencatd-open/middleware"
|
|
"opencatd-open/pkg/config"
|
|
"os"
|
|
"os/signal"
|
|
"sync"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func SetRouter(cfg *config.Config, db *gorm.DB, web *embed.FS) {
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
var wg sync.WaitGroup
|
|
|
|
if cfg == nil || db == nil {
|
|
panic("cfg or db is nil")
|
|
}
|
|
|
|
sqlDB, err := db.DB()
|
|
if err != nil {
|
|
log.Fatalf("Failed to get underlying *sql.DB: %v", err)
|
|
}
|
|
|
|
// Initialize DAOs
|
|
userDAO := dao.NewUserDAO(db)
|
|
apiKeyDAO := dao.NewApiKeyDAO(db)
|
|
usageDAO := dao.NewUsageDAO(db)
|
|
dailyDAO := dao.NewDailyUsageDAO(db)
|
|
channelDAO := dao.NewChannelDAO(db)
|
|
modelDAO := dao.NewModelDAO(db)
|
|
|
|
// Initialize channel service
|
|
channelSvc := channel.NewService(channelDAO, modelDAO)
|
|
|
|
// Initialize health checker and start periodic checks
|
|
healthChecker := channel.NewHealthChecker(channelDAO, channelSvc)
|
|
go healthChecker.StartPeriodicCheck(ctx)
|
|
|
|
// Initialize usage recorder and start background worker
|
|
usageRecorder := usage.NewRecorder(usageDAO, dailyDAO)
|
|
usageRecorder.Start(ctx)
|
|
defer usageRecorder.Stop()
|
|
|
|
// Initialize gateway
|
|
gateway := proxy.NewGateway(ctx, cfg, db, &wg, userDAO, apiKeyDAO, usageDAO, dailyDAO)
|
|
gateway.SetChannelService(channelSvc)
|
|
gateway.SetUsageRecorder(usageRecorder)
|
|
// Initialize API handler
|
|
apiHandler := api.NewHandler(db)
|
|
|
|
r := gin.Default()
|
|
r.Use(middleware.CORS())
|
|
|
|
// Public auth routes
|
|
public := r.Group("/api/auth")
|
|
{
|
|
public.POST("/register", apiHandler.Register)
|
|
public.POST("/login", apiHandler.Login)
|
|
}
|
|
|
|
// API routes (authenticated)
|
|
apiGroup := r.Group("/api", middleware.Auth(db))
|
|
{
|
|
// User profile
|
|
apiGroup.GET("/me", apiHandler.Me)
|
|
apiGroup.GET("/profile", apiHandler.Me)
|
|
apiGroup.POST("/profile/update", apiHandler.UpdateProfile)
|
|
apiGroup.POST("/profile/update/password", apiHandler.UpdatePassword)
|
|
|
|
// User management (admin)
|
|
apiGroup.GET("/users", apiHandler.ListUsers)
|
|
apiGroup.GET("/users/:id", apiHandler.GetUser)
|
|
apiGroup.POST("/users", apiHandler.CreateUser)
|
|
apiGroup.PUT("/users/:id", apiHandler.UpdateUser)
|
|
apiGroup.DELETE("/users/:id", apiHandler.DeleteUser)
|
|
apiGroup.POST("/users/batch/:option", apiHandler.BatchUsers)
|
|
|
|
// API Key management
|
|
apiGroup.GET("/keys", apiHandler.ListApiKeys)
|
|
apiGroup.GET("/keys/:id", apiHandler.GetApiKey)
|
|
apiGroup.POST("/keys", apiHandler.CreateApiKey)
|
|
apiGroup.PUT("/keys/:id", apiHandler.UpdateApiKey)
|
|
apiGroup.DELETE("/keys/:id", apiHandler.DeleteApiKey)
|
|
apiGroup.POST("/keys/batch/:option", apiHandler.BatchApiKeys)
|
|
|
|
// Channel management (legacy endpoints)
|
|
apiGroup.GET("/channels", apiHandler.ListChannels)
|
|
apiGroup.POST("/channels", apiHandler.CreateChannel)
|
|
apiGroup.PUT("/channels/:id", apiHandler.UpdateChannel)
|
|
apiGroup.DELETE("/channels/:id", apiHandler.DeleteChannel)
|
|
apiGroup.GET("/channels/:id/models", apiHandler.GetChannelModels)
|
|
apiGroup.POST("/channels/:id/models", apiHandler.BindChannelModels)
|
|
|
|
// Model management (legacy endpoints)
|
|
apiGroup.GET("/models", apiHandler.ListModels)
|
|
apiGroup.POST("/models", apiHandler.CreateModel)
|
|
apiGroup.PUT("/models/:id", apiHandler.UpdateModel)
|
|
apiGroup.DELETE("/models/:id", apiHandler.DeleteModel)
|
|
|
|
// Admin channel management (enhanced)
|
|
apiGroup.GET("/admin/channels", apiHandler.AdminChannels)
|
|
apiGroup.POST("/admin/channels", apiHandler.AdminCreateChannel)
|
|
apiGroup.PUT("/admin/channels/:id", apiHandler.AdminUpdateChannel)
|
|
apiGroup.DELETE("/admin/channels/:id", apiHandler.AdminDeleteChannel)
|
|
apiGroup.POST("/admin/channels/:id/test", apiHandler.AdminTestChannel)
|
|
apiGroup.GET("/admin/channels/:id/models/remote", apiHandler.AdminChannelRemoteModels)
|
|
apiGroup.GET("/admin/channels/:id/models", apiHandler.AdminChannelModels)
|
|
apiGroup.POST("/admin/channels/:id/models", apiHandler.AdminChannelAddModel)
|
|
apiGroup.PATCH("/admin/channels/:id/models/:bid", apiHandler.AdminChannelUpdateModel)
|
|
apiGroup.DELETE("/admin/channels/:id/models/:bid", apiHandler.AdminChannelDeleteModel)
|
|
|
|
// Admin model management (enhanced)
|
|
apiGroup.GET("/admin/models", apiHandler.AdminModels)
|
|
apiGroup.DELETE("/admin/models/unused", apiHandler.AdminDeleteUnusedModels)
|
|
apiGroup.POST("/admin/models", apiHandler.AdminCreateModel)
|
|
apiGroup.PUT("/admin/models/:id", apiHandler.AdminUpdateModel)
|
|
apiGroup.DELETE("/admin/models/:id", apiHandler.AdminDeleteModel)
|
|
apiGroup.POST("/admin/models/:id/bindings", apiHandler.AdminCreateModelBinding)
|
|
apiGroup.DELETE("/admin/models/:id/bindings/:bid", apiHandler.AdminDeleteModelBinding)
|
|
|
|
// Admin system config
|
|
apiGroup.GET("/admin/config", apiHandler.AdminGetConfig)
|
|
apiGroup.PUT("/admin/config", apiHandler.AdminUpdateConfig)
|
|
apiGroup.GET("/admin/config/registration", apiHandler.AdminGetRegistration)
|
|
apiGroup.PUT("/admin/config/registration", apiHandler.AdminUpdateRegistration)
|
|
apiGroup.GET("/admin/config/password-login", apiHandler.AdminGetPasswordLogin)
|
|
apiGroup.PUT("/admin/config/password-login", apiHandler.AdminUpdatePasswordLogin)
|
|
}
|
|
|
|
// LLM proxy routes
|
|
v1 := r.Group("/v1")
|
|
v1.Use(middleware.AuthLLM(db))
|
|
{
|
|
v1.POST("/chat/completions", gateway.HandleChat)
|
|
v1.POST("/messages", gateway.HandleMessages)
|
|
v1.POST("/responses", gateway.HandleResponses)
|
|
v1.GET("/models", gateway.HandleModels)
|
|
}
|
|
|
|
// SPA fallback
|
|
idxFS, err := fs.Sub(web, "dist")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
assetsFS, err := fs.Sub(web, "dist/assets")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
r.StaticFS("/assets", http.FS(assetsFS))
|
|
|
|
r.NoRoute(func(c *gin.Context) {
|
|
if c.Writer.Status() == http.StatusNotFound {
|
|
c.FileFromFS("/", http.FS(idxFS))
|
|
}
|
|
})
|
|
|
|
srv := &http.Server{
|
|
Addr: fmt.Sprintf(":%d", cfg.Port),
|
|
Handler: r,
|
|
}
|
|
|
|
go func() {
|
|
fmt.Println("Starting server at port:", cfg.Port)
|
|
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
log.Fatalf("listen: %s\n", err)
|
|
}
|
|
}()
|
|
|
|
quit := make(chan os.Signal, 1)
|
|
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
|
<-quit
|
|
fmt.Println("\nShutdown Server ...")
|
|
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer shutdownCancel()
|
|
|
|
if err := srv.Shutdown(shutdownCtx); err != nil {
|
|
log.Fatalln("Server Shutdown:", err)
|
|
}
|
|
|
|
cancel()
|
|
sqlDB.Close()
|
|
|
|
waitChan := make(chan struct{})
|
|
go func() {
|
|
wg.Wait()
|
|
close(waitChan)
|
|
}()
|
|
|
|
select {
|
|
case <-waitChan:
|
|
fmt.Println("All goroutines have finished")
|
|
case <-shutdownCtx.Done():
|
|
fmt.Println("⚠️ Shutdown timeout")
|
|
}
|
|
|
|
fmt.Println("Server exited")
|
|
}
|