feat: 前端搭建-未完成
This commit is contained in:
2
.gitignore
vendored
2
.gitignore
vendored
@@ -228,3 +228,5 @@ charts/*.tgz
|
||||
run-local.sh
|
||||
start-local.sh
|
||||
dev-setup.sh
|
||||
|
||||
cmd/gpt-load/dist
|
||||
|
93
Dockerfile
93
Dockerfile
@@ -1,62 +1,81 @@
|
||||
# 多阶段构建 Dockerfile for OpenAI 多密钥代理服务器 (Go版本)
|
||||
# --- Stage 1: Frontend Builder ---
|
||||
FROM node:20-alpine AS frontend-builder
|
||||
|
||||
# 构建阶段
|
||||
FROM golang:1.21-alpine AS builder
|
||||
WORKDIR /app/web
|
||||
|
||||
# Copy web project files
|
||||
COPY web/package.json web/package-lock.json ./
|
||||
COPY web/tsconfig.json web/tsconfig.node.json web/tsconfig.app.json ./
|
||||
COPY web/vite.config.ts ./
|
||||
|
||||
# Install dependencies
|
||||
RUN npm install
|
||||
|
||||
# Copy the rest of the web source code
|
||||
COPY web/ ./
|
||||
|
||||
# Build the frontend application
|
||||
RUN npm run build
|
||||
|
||||
# --- Stage 2: Backend Builder ---
|
||||
FROM golang:1.22-alpine AS backend-builder
|
||||
|
||||
# 设置工作目录
|
||||
WORKDIR /app
|
||||
|
||||
# 安装必要的包
|
||||
RUN apk add --no-cache git ca-certificates tzdata
|
||||
# Install build tools
|
||||
RUN apk add --no-cache git build-base
|
||||
|
||||
# 复制 go mod 文件
|
||||
# Copy Go module files and download dependencies
|
||||
COPY go.mod go.sum ./
|
||||
|
||||
# 下载依赖
|
||||
RUN go mod download
|
||||
|
||||
# 复制源代码
|
||||
# Copy the entire Go project source code
|
||||
COPY . .
|
||||
|
||||
# 构建应用 - 支持多平台
|
||||
ARG TARGETOS
|
||||
ARG TARGETARCH
|
||||
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build \
|
||||
-ldflags="-w -s -X main.Version=2.0.0" \
|
||||
-o gpt-load \
|
||||
./cmd/gpt-load/main.go
|
||||
# Copy the built frontend from the previous stage
|
||||
COPY --from=frontend-builder /app/web/dist ./web/dist
|
||||
|
||||
# 运行阶段
|
||||
# Build the Go application
|
||||
# We use CGO_ENABLED=0 to create a static binary
|
||||
# -ldflags="-w -s" strips debug information and symbols to reduce binary size
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build \
|
||||
-ldflags="-w -s" \
|
||||
-o /gpt-load \
|
||||
./cmd/gpt-load
|
||||
|
||||
# --- Stage 3: Final Image ---
|
||||
FROM alpine:latest
|
||||
|
||||
# 安装必要的包
|
||||
RUN apk --no-cache add ca-certificates curl
|
||||
# Install necessary runtime dependencies
|
||||
# ca-certificates for HTTPS connections
|
||||
# tzdata for time zone information
|
||||
RUN apk --no-cache add ca-certificates tzdata
|
||||
|
||||
# 创建非 root 用户
|
||||
RUN addgroup -g 1001 -S appgroup && \
|
||||
adduser -S appuser -u 1001 -G appgroup
|
||||
# Create a non-root user and group for security
|
||||
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
|
||||
|
||||
# 设置工作目录
|
||||
# Set the working directory
|
||||
WORKDIR /app
|
||||
|
||||
# 从构建阶段复制二进制文件
|
||||
COPY --from=builder /app/gpt-load .
|
||||
# Copy the compiled binary from the backend-builder stage
|
||||
COPY --from=backend-builder /gpt-load .
|
||||
|
||||
# 复制配置文件模板
|
||||
COPY --from=builder /app/.env.example .
|
||||
# Copy the configuration file example
|
||||
COPY .env.example .
|
||||
|
||||
# 设置权限
|
||||
# Set ownership of the app directory to the non-root user
|
||||
RUN chown -R appuser:appgroup /app
|
||||
|
||||
# 切换到非 root 用户
|
||||
# Switch to the non-root user
|
||||
USER appuser
|
||||
|
||||
# 暴露端口
|
||||
EXPOSE 3000
|
||||
# Expose the application port
|
||||
# This should match the port defined in the configuration
|
||||
EXPOSE 8080
|
||||
|
||||
# 健康检查
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD curl -f http://localhost:3000/health || exit 1
|
||||
# Healthcheck to ensure the application is running
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD [ "wget", "-q", "--spider", "http://localhost:8080/health" ] || exit 1
|
||||
|
||||
# 启动命令
|
||||
CMD ["./gpt-load"]
|
||||
# Set the entrypoint for the container
|
||||
ENTRYPOINT ["/app/gpt-load"]
|
||||
|
11
Makefile
11
Makefile
@@ -44,9 +44,16 @@ build-all: clean
|
||||
|
||||
# 运行
|
||||
.PHONY: run
|
||||
.PHONY: run
|
||||
|
||||
run:
|
||||
@echo "🚀 启动服务器..."
|
||||
go run $(MAIN_PATH)
|
||||
@echo "--- Building frontend... ---"
|
||||
cd web && npm install && npm run build
|
||||
@echo "--- Preparing backend... ---"
|
||||
@rm -rf cmd/gpt-load/dist
|
||||
@cp -r web/dist cmd/gpt-load/dist
|
||||
@echo "--- Starting backend... ---"
|
||||
cd $(MAIN_PATH) && go run .
|
||||
|
||||
# 开发模式运行
|
||||
.PHONY: dev
|
||||
|
6
cmd/gpt-load/embed.go
Normal file
6
cmd/gpt-load/embed.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package main
|
||||
|
||||
import "embed"
|
||||
|
||||
//go:embed all:dist
|
||||
var WebUI embed.FS
|
@@ -5,22 +5,27 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"gpt-load/internal/config"
|
||||
"gpt-load/internal/db"
|
||||
"gpt-load/internal/handler"
|
||||
"gpt-load/internal/keymanager"
|
||||
"gpt-load/internal/middleware"
|
||||
"gpt-load/internal/models"
|
||||
"gpt-load/internal/proxy"
|
||||
"gpt-load/internal/types"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -33,28 +38,33 @@ func main() {
|
||||
// Setup logger
|
||||
setupLogger(configManager)
|
||||
|
||||
// Initialize database
|
||||
database, err := db.InitDB()
|
||||
if err != nil {
|
||||
logrus.Fatalf("Failed to initialize database: %v", err)
|
||||
}
|
||||
|
||||
// Display startup information
|
||||
displayStartupInfo(configManager)
|
||||
|
||||
// Create key manager
|
||||
keyManager, err := keymanager.NewManager(configManager.GetKeysConfig())
|
||||
if err != nil {
|
||||
logrus.Fatalf("Failed to create key manager: %v", err)
|
||||
}
|
||||
defer keyManager.Close()
|
||||
|
||||
// --- Asynchronous Request Logging Setup ---
|
||||
requestLogChan := make(chan models.RequestLog, 1000)
|
||||
go startRequestLogger(database, requestLogChan)
|
||||
// ---
|
||||
|
||||
// Create proxy server
|
||||
proxyServer, err := proxy.NewProxyServer(keyManager, configManager)
|
||||
proxyServer, err := proxy.NewProxyServer(database, requestLogChan)
|
||||
if err != nil {
|
||||
logrus.Fatalf("Failed to create proxy server: %v", err)
|
||||
}
|
||||
defer proxyServer.Close()
|
||||
|
||||
// Create handlers
|
||||
handlers := handler.NewHandler(keyManager, configManager)
|
||||
serverHandler := handler.NewServer(database, configManager)
|
||||
|
||||
// Setup routes
|
||||
router := setupRoutes(handlers, proxyServer, configManager)
|
||||
router := setupRoutes(serverHandler, proxyServer, configManager)
|
||||
|
||||
// Create HTTP server with optimized timeout configuration
|
||||
serverConfig := configManager.GetServerConfig()
|
||||
@@ -73,8 +83,6 @@ func main() {
|
||||
logrus.Infof("Server address: http://%s:%d", serverConfig.Host, serverConfig.Port)
|
||||
logrus.Infof("Statistics: http://%s:%d/stats", serverConfig.Host, serverConfig.Port)
|
||||
logrus.Infof("Health check: http://%s:%d/health", serverConfig.Host, serverConfig.Port)
|
||||
logrus.Infof("Reset keys: http://%s:%d/reset-keys", serverConfig.Host, serverConfig.Port)
|
||||
logrus.Infof("Blacklist query: http://%s:%d/blacklist", serverConfig.Host, serverConfig.Port)
|
||||
logrus.Info("")
|
||||
|
||||
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
@@ -101,7 +109,7 @@ func main() {
|
||||
}
|
||||
|
||||
// setupRoutes configures the HTTP routes
|
||||
func setupRoutes(handlers *handler.Handler, proxyServer *proxy.ProxyServer, configManager types.ConfigManager) *gin.Engine {
|
||||
func setupRoutes(serverHandler *handler.Server, proxyServer *proxy.ProxyServer, configManager types.ConfigManager) *gin.Engine {
|
||||
// Set Gin mode
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
|
||||
@@ -127,21 +135,57 @@ func setupRoutes(handlers *handler.Handler, proxyServer *proxy.ProxyServer, conf
|
||||
}
|
||||
|
||||
// Management endpoints
|
||||
router.GET("/health", handlers.Health)
|
||||
router.GET("/stats", handlers.Stats)
|
||||
router.GET("/blacklist", handlers.Blacklist)
|
||||
router.GET("/reset-keys", handlers.ResetKeys)
|
||||
router.GET("/config", handlers.GetConfig) // Debug endpoint
|
||||
router.GET("/health", serverHandler.Health)
|
||||
router.GET("/stats", serverHandler.Stats)
|
||||
router.GET("/config", serverHandler.GetConfig) // Debug endpoint
|
||||
|
||||
// Register API routes for group and key management
|
||||
api := router.Group("/api")
|
||||
serverHandler.RegisterAPIRoutes(api)
|
||||
|
||||
// Register the main proxy route
|
||||
proxy := router.Group("/proxy")
|
||||
proxyServer.RegisterProxyRoutes(proxy)
|
||||
|
||||
// Handle 405 Method Not Allowed
|
||||
router.NoMethod(handlers.MethodNotAllowed)
|
||||
router.NoMethod(serverHandler.MethodNotAllowed)
|
||||
|
||||
// Proxy all other requests (this handles 404 as well)
|
||||
router.NoRoute(proxyServer.HandleProxy)
|
||||
// Serve the frontend UI for all other requests
|
||||
router.NoRoute(ServeUI())
|
||||
|
||||
return router
|
||||
}
|
||||
|
||||
// ServeUI returns a gin.HandlerFunc to serve the embedded frontend UI.
|
||||
func ServeUI() gin.HandlerFunc {
|
||||
subFS, err := fs.Sub(WebUI, "dist")
|
||||
if err != nil {
|
||||
// This should not happen at runtime if embed is correct.
|
||||
// Panic is acceptable here as it's a startup failure.
|
||||
panic(fmt.Sprintf("Failed to create sub filesystem for UI: %v", err))
|
||||
}
|
||||
fileServer := http.FileServer(http.FS(subFS))
|
||||
|
||||
return func(c *gin.Context) {
|
||||
// Clean the path to prevent directory traversal attacks.
|
||||
upath := path.Clean(c.Request.URL.Path)
|
||||
if !strings.HasPrefix(upath, "/") {
|
||||
upath = "/" + upath
|
||||
}
|
||||
|
||||
// Check if the file exists in the embedded filesystem.
|
||||
_, err := subFS.Open(strings.TrimPrefix(upath, "/"))
|
||||
if os.IsNotExist(err) {
|
||||
// The file does not exist, so we serve index.html for SPA routing.
|
||||
// This allows the Vue router to handle the path.
|
||||
c.Request.URL.Path = "/"
|
||||
}
|
||||
|
||||
// Let the http.FileServer handle the request.
|
||||
fileServer.ServeHTTP(c.Writer, c.Request)
|
||||
}
|
||||
}
|
||||
|
||||
// setupLogger configures the logging system
|
||||
func setupLogger(configManager types.ConfigManager) {
|
||||
logConfig := configManager.GetLogConfig()
|
||||
@@ -232,3 +276,42 @@ func displayStartupInfo(configManager types.ConfigManager) {
|
||||
}
|
||||
logrus.Infof(" Request logging: %s", requestLogStatus)
|
||||
}
|
||||
|
||||
// startRequestLogger runs a background goroutine to batch-insert request logs.
|
||||
func startRequestLogger(db *gorm.DB, logChan <-chan models.RequestLog) {
|
||||
ticker := time.NewTicker(5 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
logBuffer := make([]models.RequestLog, 0, 100)
|
||||
|
||||
for {
|
||||
select {
|
||||
case logEntry, ok := <-logChan:
|
||||
if !ok {
|
||||
// Channel closed, flush remaining logs and exit
|
||||
if len(logBuffer) > 0 {
|
||||
if err := db.Create(&logBuffer).Error; err != nil {
|
||||
logrus.Errorf("Failed to write remaining request logs: %v", err)
|
||||
}
|
||||
}
|
||||
logrus.Info("Request logger stopped.")
|
||||
return
|
||||
}
|
||||
logBuffer = append(logBuffer, logEntry)
|
||||
if len(logBuffer) >= 100 {
|
||||
if err := db.Create(&logBuffer).Error; err != nil {
|
||||
logrus.Errorf("Failed to write request logs: %v", err)
|
||||
}
|
||||
logBuffer = make([]models.RequestLog, 0, 100) // Reset buffer
|
||||
}
|
||||
case <-ticker.C:
|
||||
// Flush logs periodically
|
||||
if len(logBuffer) > 0 {
|
||||
if err := db.Create(&logBuffer).Error; err != nil {
|
||||
logrus.Errorf("Failed to write request logs on tick: %v", err)
|
||||
}
|
||||
logBuffer = make([]models.RequestLog, 0, 100) // Reset buffer
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,20 +1,70 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
gpt-load:
|
||||
image: ghcr.io/tbphp/gpt-load:latest
|
||||
container_name: gpt-load
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: gpt-load-app
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
# 挂载密钥文件(只读)
|
||||
- ./keys.txt:/app/keys.txt:ro
|
||||
restart: unless-stopped
|
||||
- "8080:8080"
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
# Override or set environment variables here
|
||||
- DB_HOST=db
|
||||
- DB_PORT=3306
|
||||
- DB_USER=${DB_USER}
|
||||
- DB_PASSWORD=${DB_PASSWORD}
|
||||
- DB_NAME=${DB_NAME}
|
||||
- GIN_MODE=release
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_started
|
||||
networks:
|
||||
- gpt-load-net
|
||||
|
||||
# 健康检查
|
||||
db:
|
||||
image: mysql:8.0
|
||||
container_name: gpt-load-db
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
MYSQL_DATABASE: ${DB_NAME}
|
||||
MYSQL_USER: ${DB_USER}
|
||||
MYSQL_PASSWORD: ${DB_PASSWORD}
|
||||
MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
|
||||
volumes:
|
||||
- db-data:/var/lib/mysql
|
||||
ports:
|
||||
- "3306:3306"
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 40s
|
||||
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "${DB_USER}", "-p${DB_PASSWORD}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
networks:
|
||||
- gpt-load-net
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
container_name: gpt-load-redis
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "6379:6379"
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
networks:
|
||||
- gpt-load-net
|
||||
|
||||
volumes:
|
||||
db-data:
|
||||
|
||||
networks:
|
||||
gpt-load-net:
|
||||
driver: bridge
|
||||
|
8
go.mod
8
go.mod
@@ -6,9 +6,12 @@ require (
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
gorm.io/driver/mysql v1.6.0
|
||||
gorm.io/gorm v1.30.0
|
||||
)
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
github.com/bytedance/sonic v1.9.1 // indirect
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
||||
@@ -16,7 +19,10 @@ require (
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.14.0 // indirect
|
||||
github.com/go-sql-driver/mysql v1.8.1 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
|
||||
github.com/leodido/go-urn v1.2.4 // indirect
|
||||
@@ -30,7 +36,7 @@ require (
|
||||
golang.org/x/crypto v0.9.0 // indirect
|
||||
golang.org/x/net v0.10.0 // indirect
|
||||
golang.org/x/sys v0.8.0 // indirect
|
||||
golang.org/x/text v0.9.0 // indirect
|
||||
golang.org/x/text v0.20.0 // indirect
|
||||
google.golang.org/protobuf v1.30.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
16
go.sum
16
go.sum
@@ -1,3 +1,5 @@
|
||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
|
||||
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
|
||||
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
|
||||
@@ -21,12 +23,18 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=
|
||||
github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
|
||||
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
@@ -76,8 +84,8 @@ golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
|
||||
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
@@ -88,4 +96,8 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
|
||||
gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
|
||||
gorm.io/gorm v1.30.0 h1:qbT5aPv1UH8gI99OsRlvDToLxW5zR7FzS9acZDOZcgs=
|
||||
gorm.io/gorm v1.30.0/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
|
14
internal/channel/channel.go
Normal file
14
internal/channel/channel.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package channel
|
||||
|
||||
import (
|
||||
"gpt-load/internal/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ChannelProxy defines the interface for different API channel proxies.
|
||||
type ChannelProxy interface {
|
||||
// Handle takes a context, an API key, and the original request,
|
||||
// then forwards the request to the upstream service.
|
||||
Handle(c *gin.Context, apiKey *models.APIKey, group *models.Group)
|
||||
}
|
18
internal/channel/factory.go
Normal file
18
internal/channel/factory.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package channel
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gpt-load/internal/models"
|
||||
)
|
||||
|
||||
// GetChannel returns a channel proxy based on the group's channel type.
|
||||
func GetChannel(group *models.Group) (ChannelProxy, error) {
|
||||
switch group.ChannelType {
|
||||
case "openai":
|
||||
return NewOpenAIChannel(group)
|
||||
case "gemini":
|
||||
return NewGeminiChannel(group)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported channel type: %s", group.ChannelType)
|
||||
}
|
||||
}
|
55
internal/channel/gemini_channel.go
Normal file
55
internal/channel/gemini_channel.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package channel
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gpt-load/internal/models"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const GeminiBaseURL = "https://generativelanguage.googleapis.com"
|
||||
|
||||
type GeminiChannel struct {
|
||||
BaseURL *url.URL
|
||||
}
|
||||
|
||||
func NewGeminiChannel(group *models.Group) (*GeminiChannel, error) {
|
||||
baseURL, err := url.Parse(GeminiBaseURL)
|
||||
if err != nil {
|
||||
return nil, err // Should not happen with a constant
|
||||
}
|
||||
return &GeminiChannel{BaseURL: baseURL}, nil
|
||||
}
|
||||
|
||||
func (ch *GeminiChannel) Handle(c *gin.Context, apiKey *models.APIKey, group *models.Group) {
|
||||
proxy := httputil.NewSingleHostReverseProxy(ch.BaseURL)
|
||||
|
||||
proxy.Director = func(req *http.Request) {
|
||||
// Gemini API key is passed as a query parameter
|
||||
originalPath := c.Param("path")
|
||||
newPath := fmt.Sprintf("%s?key=%s", originalPath, apiKey.KeyValue)
|
||||
|
||||
req.URL.Scheme = ch.BaseURL.Scheme
|
||||
req.URL.Host = ch.BaseURL.Host
|
||||
req.URL.Path = newPath
|
||||
req.Host = ch.BaseURL.Host
|
||||
// Remove the Authorization header if it was passed by the client
|
||||
req.Header.Del("Authorization")
|
||||
}
|
||||
|
||||
proxy.ModifyResponse = func(resp *http.Response) error {
|
||||
// Log the response, etc.
|
||||
return nil
|
||||
}
|
||||
|
||||
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
logrus.Errorf("Proxy error to Gemini: %v", err)
|
||||
// Handle error, maybe update key status
|
||||
}
|
||||
|
||||
proxy.ServeHTTP(c.Writer, c.Request)
|
||||
}
|
55
internal/channel/openai_channel.go
Normal file
55
internal/channel/openai_channel.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package channel
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"gpt-load/internal/models"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type OpenAIChannel struct {
|
||||
BaseURL *url.URL
|
||||
}
|
||||
|
||||
type OpenAIChannelConfig struct {
|
||||
BaseURL string `json:"base_url"`
|
||||
}
|
||||
|
||||
func NewOpenAIChannel(group *models.Group) (*OpenAIChannel, error) {
|
||||
var config OpenAIChannelConfig
|
||||
if err := json.Unmarshal([]byte(group.Config), &config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
baseURL, err := url.Parse(config.BaseURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &OpenAIChannel{BaseURL: baseURL}, nil
|
||||
}
|
||||
|
||||
func (ch *OpenAIChannel) Handle(c *gin.Context, apiKey *models.APIKey, group *models.Group) {
|
||||
proxy := httputil.NewSingleHostReverseProxy(ch.BaseURL)
|
||||
proxy.Director = func(req *http.Request) {
|
||||
req.URL.Scheme = ch.BaseURL.Scheme
|
||||
req.URL.Host = ch.BaseURL.Host
|
||||
req.URL.Path = c.Param("path")
|
||||
req.Host = ch.BaseURL.Host
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey.KeyValue)
|
||||
}
|
||||
|
||||
proxy.ModifyResponse = func(resp *http.Response) error {
|
||||
// Log the response, etc.
|
||||
return nil
|
||||
}
|
||||
|
||||
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
logrus.Errorf("Proxy error: %v", err)
|
||||
// Handle error, maybe update key status
|
||||
}
|
||||
|
||||
proxy.ServeHTTP(c.Writer, c.Request)
|
||||
}
|
@@ -55,6 +55,15 @@ type Config struct {
|
||||
|
||||
// NewManager creates a new configuration manager
|
||||
func NewManager() (types.ConfigManager, error) {
|
||||
manager := &Manager{}
|
||||
if err := manager.ReloadConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return manager, nil
|
||||
}
|
||||
|
||||
// ReloadConfig reloads the configuration from environment variables
|
||||
func (m *Manager) ReloadConfig() error {
|
||||
// Try to load .env file
|
||||
if err := godotenv.Load(); err != nil {
|
||||
logrus.Info("Info: Create .env file to support environment variable configuration")
|
||||
@@ -104,15 +113,17 @@ func NewManager() (types.ConfigManager, error) {
|
||||
EnableRequest: parseBoolean(os.Getenv("LOG_ENABLE_REQUEST"), true),
|
||||
},
|
||||
}
|
||||
|
||||
manager := &Manager{config: config}
|
||||
m.config = config
|
||||
|
||||
// Validate configuration
|
||||
if err := manager.Validate(); err != nil {
|
||||
return nil, err
|
||||
if err := m.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return manager, nil
|
||||
logrus.Info("Configuration reloaded successfully")
|
||||
m.DisplayConfig()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetServerConfig returns server configuration
|
||||
|
62
internal/db/database.go
Normal file
62
internal/db/database.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gpt-load/internal/models"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
var DB *gorm.DB
|
||||
|
||||
func InitDB() (*gorm.DB, error) {
|
||||
// TODO: 从配置中心读取DSN
|
||||
dsn := "root:1236@tcp(127.0.0.1:3306)/gpt_load?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
|
||||
newLogger := logger.New(
|
||||
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
|
||||
logger.Config{
|
||||
SlowThreshold: time.Second, // Slow SQL threshold
|
||||
LogLevel: logger.Info, // Log level
|
||||
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
|
||||
Colorful: true, // Disable color
|
||||
},
|
||||
)
|
||||
|
||||
var err error
|
||||
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
|
||||
Logger: newLogger,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to connect to database: %w", err)
|
||||
}
|
||||
|
||||
sqlDB, err := DB.DB()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get sql.DB: %w", err)
|
||||
}
|
||||
|
||||
// Set connection pool parameters
|
||||
sqlDB.SetMaxIdleConns(10)
|
||||
sqlDB.SetMaxOpenConns(100)
|
||||
sqlDB.SetConnMaxLifetime(time.Hour)
|
||||
|
||||
// Auto-migrate models
|
||||
err = DB.AutoMigrate(
|
||||
&models.SystemSetting{},
|
||||
&models.Group{},
|
||||
&models.APIKey{},
|
||||
&models.RequestLog{},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to auto-migrate database: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println("Database connection initialized and models migrated.")
|
||||
return DB, nil
|
||||
}
|
62
internal/handler/dashboard_handler.go
Normal file
62
internal/handler/dashboard_handler.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gpt-load/internal/db"
|
||||
"gpt-load/internal/models"
|
||||
"gpt-load/internal/response"
|
||||
)
|
||||
|
||||
// GetDashboardStats godoc
|
||||
// @Summary Get dashboard statistics
|
||||
// @Description Get statistics for the dashboard, including total requests, success rate, and group distribution.
|
||||
// @Tags Dashboard
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} models.DashboardStats
|
||||
// @Router /api/dashboard/stats [get]
|
||||
func GetDashboardStats(c *gin.Context) {
|
||||
var totalRequests, successRequests int64
|
||||
var groupStats []models.GroupRequestStat
|
||||
|
||||
// Get total requests
|
||||
if err := db.DB.Model(&models.RequestLog{}).Count(&totalRequests).Error; err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "Failed to get total requests")
|
||||
return
|
||||
}
|
||||
|
||||
// Get success requests (status code 2xx)
|
||||
if err := db.DB.Model(&models.RequestLog{}).Where("status_code >= ? AND status_code < ?", 200, 300).Count(&successRequests).Error; err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "Failed to get success requests")
|
||||
return
|
||||
}
|
||||
|
||||
// Calculate success rate
|
||||
var successRate float64
|
||||
if totalRequests > 0 {
|
||||
successRate = float64(successRequests) / float64(totalRequests)
|
||||
}
|
||||
|
||||
// Get group stats
|
||||
err := db.DB.Table("request_logs").
|
||||
Select("groups.name as group_name, count(request_logs.id) as request_count").
|
||||
Joins("join groups on groups.id = request_logs.group_id").
|
||||
Group("groups.name").
|
||||
Order("request_count desc").
|
||||
Scan(&groupStats).Error
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "Failed to get group stats")
|
||||
return
|
||||
}
|
||||
|
||||
stats := models.DashboardStats{
|
||||
TotalRequests: totalRequests,
|
||||
SuccessRequests: successRequests,
|
||||
SuccessRate: successRate,
|
||||
GroupStats: groupStats,
|
||||
}
|
||||
|
||||
response.Success(c, stats)
|
||||
}
|
125
internal/handler/group_handler.go
Normal file
125
internal/handler/group_handler.go
Normal file
@@ -0,0 +1,125 @@
|
||||
// Package handler provides HTTP handlers for the application
|
||||
package handler
|
||||
|
||||
import (
|
||||
"gpt-load/internal/models"
|
||||
"gpt-load/internal/response"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CreateGroup handles the creation of a new group.
|
||||
func (s *Server) CreateGroup(c *gin.Context) {
|
||||
var group models.Group
|
||||
if err := c.ShouldBindJSON(&group); err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "Invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.DB.Create(&group).Error; err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "Failed to create group")
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, group)
|
||||
}
|
||||
|
||||
// ListGroups handles listing all groups.
|
||||
func (s *Server) ListGroups(c *gin.Context) {
|
||||
var groups []models.Group
|
||||
if err := s.DB.Find(&groups).Error; err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "Failed to list groups")
|
||||
return
|
||||
}
|
||||
response.Success(c, groups)
|
||||
}
|
||||
|
||||
// GetGroup handles getting a single group by its ID.
|
||||
func (s *Server) GetGroup(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "Invalid group ID")
|
||||
return
|
||||
}
|
||||
|
||||
var group models.Group
|
||||
if err := s.DB.Preload("APIKeys").First(&group, id).Error; err != nil {
|
||||
response.Error(c, http.StatusNotFound, "Group not found")
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, group)
|
||||
}
|
||||
|
||||
// UpdateGroup handles updating an existing group.
|
||||
func (s *Server) UpdateGroup(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "Invalid group ID")
|
||||
return
|
||||
}
|
||||
|
||||
var group models.Group
|
||||
if err := s.DB.First(&group, id).Error; err != nil {
|
||||
response.Error(c, http.StatusNotFound, "Group not found")
|
||||
return
|
||||
}
|
||||
|
||||
var updateData models.Group
|
||||
if err := c.ShouldBindJSON(&updateData); err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "Invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
// We only allow updating certain fields
|
||||
group.Name = updateData.Name
|
||||
group.Description = updateData.Description
|
||||
group.ChannelType = updateData.ChannelType
|
||||
group.Config = updateData.Config
|
||||
|
||||
if err := s.DB.Save(&group).Error; err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "Failed to update group")
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, group)
|
||||
}
|
||||
|
||||
// DeleteGroup handles deleting a group.
|
||||
func (s *Server) DeleteGroup(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "Invalid group ID")
|
||||
return
|
||||
}
|
||||
|
||||
// Use a transaction to ensure atomicity
|
||||
tx := s.DB.Begin()
|
||||
if tx.Error != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "Failed to start transaction")
|
||||
return
|
||||
}
|
||||
|
||||
// Also delete associated API keys
|
||||
if err := tx.Where("group_id = ?", id).Delete(&models.APIKey{}).Error; err != nil {
|
||||
tx.Rollback()
|
||||
response.Error(c, http.StatusInternalServerError, "Failed to delete associated API keys")
|
||||
return
|
||||
}
|
||||
|
||||
if err := tx.Delete(&models.Group{}, id).Error; err != nil {
|
||||
tx.Rollback()
|
||||
response.Error(c, http.StatusInternalServerError, "Failed to delete group")
|
||||
return
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
tx.Rollback()
|
||||
response.Error(c, http.StatusInternalServerError, "Failed to commit transaction")
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, gin.H{"message": "Group and associated keys deleted successfully"})
|
||||
}
|
@@ -6,35 +6,80 @@ import (
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"gpt-load/internal/models"
|
||||
"gpt-load/internal/types"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Handler contains dependencies for HTTP handlers
|
||||
type Handler struct {
|
||||
keyManager types.KeyManager
|
||||
// Server contains dependencies for HTTP handlers
|
||||
type Server struct {
|
||||
DB *gorm.DB
|
||||
config types.ConfigManager
|
||||
}
|
||||
|
||||
// NewHandler creates a new handler instance
|
||||
func NewHandler(keyManager types.KeyManager, config types.ConfigManager) *Handler {
|
||||
return &Handler{
|
||||
keyManager: keyManager,
|
||||
// NewServer creates a new handler instance
|
||||
func NewServer(db *gorm.DB, config types.ConfigManager) *Server {
|
||||
return &Server{
|
||||
DB: db,
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterAPIRoutes registers all API routes under a given router group
|
||||
func (s *Server) RegisterAPIRoutes(api *gin.RouterGroup) {
|
||||
// Group management routes
|
||||
groups := api.Group("/groups")
|
||||
{
|
||||
groups.POST("", s.CreateGroup)
|
||||
groups.GET("", s.ListGroups)
|
||||
groups.GET("/:id", s.GetGroup)
|
||||
groups.PUT("/:id", s.UpdateGroup)
|
||||
groups.DELETE("/:id", s.DeleteGroup)
|
||||
|
||||
// Key management routes within a group
|
||||
keys := groups.Group("/:id/keys")
|
||||
{
|
||||
keys.POST("", s.CreateKeysInGroup)
|
||||
keys.GET("", s.ListKeysInGroup)
|
||||
}
|
||||
}
|
||||
|
||||
// Key management routes
|
||||
api.PUT("/keys/:key_id", s.UpdateKey)
|
||||
api.DELETE("/keys", s.DeleteKeys)
|
||||
|
||||
// Dashboard and logs routes
|
||||
dashboard := api.Group("/dashboard")
|
||||
{
|
||||
dashboard.GET("/stats", GetDashboardStats)
|
||||
}
|
||||
|
||||
api.GET("/logs", GetLogs)
|
||||
|
||||
// Settings routes
|
||||
settings := api.Group("/settings")
|
||||
{
|
||||
settings.GET("", GetSettings)
|
||||
settings.PUT("", UpdateSettings)
|
||||
}
|
||||
|
||||
// Reload route
|
||||
api.POST("/reload", s.ReloadConfig)
|
||||
}
|
||||
|
||||
// Health handles health check requests
|
||||
func (h *Handler) Health(c *gin.Context) {
|
||||
stats := h.keyManager.GetStats()
|
||||
func (s *Server) Health(c *gin.Context) {
|
||||
var totalKeys, healthyKeys int64
|
||||
s.DB.Model(&models.APIKey{}).Count(&totalKeys)
|
||||
s.DB.Model(&models.APIKey{}).Where("status = ?", "active").Count(&healthyKeys)
|
||||
|
||||
status := "healthy"
|
||||
httpStatus := http.StatusOK
|
||||
|
||||
// Check if there are any healthy keys
|
||||
if stats.HealthyKeys == 0 {
|
||||
if healthyKeys == 0 && totalKeys > 0 {
|
||||
status = "unhealthy"
|
||||
httpStatus = http.StatusServiceUnavailable
|
||||
}
|
||||
@@ -50,15 +95,23 @@ func (h *Handler) Health(c *gin.Context) {
|
||||
c.JSON(httpStatus, gin.H{
|
||||
"status": status,
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339),
|
||||
"healthy_keys": stats.HealthyKeys,
|
||||
"total_keys": stats.TotalKeys,
|
||||
"healthy_keys": healthyKeys,
|
||||
"total_keys": totalKeys,
|
||||
"uptime": uptime,
|
||||
})
|
||||
}
|
||||
|
||||
// Stats handles statistics requests
|
||||
func (h *Handler) Stats(c *gin.Context) {
|
||||
stats := h.keyManager.GetStats()
|
||||
func (s *Server) Stats(c *gin.Context) {
|
||||
var totalKeys, healthyKeys, disabledKeys int64
|
||||
s.DB.Model(&models.APIKey{}).Count(&totalKeys)
|
||||
s.DB.Model(&models.APIKey{}).Where("status = ?", "active").Count(&healthyKeys)
|
||||
s.DB.Model(&models.APIKey{}).Where("status != ?", "active").Count(&disabledKeys)
|
||||
|
||||
// TODO: Get request counts from the database
|
||||
var successCount, failureCount int64
|
||||
s.DB.Model(&models.RequestLog{}).Where("status_code = ?", http.StatusOK).Count(&successCount)
|
||||
s.DB.Model(&models.RequestLog{}).Where("status_code != ?", http.StatusOK).Count(&failureCount)
|
||||
|
||||
// Add additional system information
|
||||
var m runtime.MemStats
|
||||
@@ -66,15 +119,14 @@ func (h *Handler) Stats(c *gin.Context) {
|
||||
|
||||
response := gin.H{
|
||||
"keys": gin.H{
|
||||
"total": stats.TotalKeys,
|
||||
"healthy": stats.HealthyKeys,
|
||||
"blacklisted": stats.BlacklistedKeys,
|
||||
"current_index": stats.CurrentIndex,
|
||||
"total": totalKeys,
|
||||
"healthy": healthyKeys,
|
||||
"disabled": disabledKeys,
|
||||
},
|
||||
"requests": gin.H{
|
||||
"success_count": stats.SuccessCount,
|
||||
"failure_count": stats.FailureCount,
|
||||
"total_count": stats.SuccessCount + stats.FailureCount,
|
||||
"success_count": successCount,
|
||||
"failure_count": failureCount,
|
||||
"total_count": successCount + failureCount,
|
||||
},
|
||||
"memory": gin.H{
|
||||
"alloc_mb": bToMb(m.Alloc),
|
||||
@@ -95,48 +147,9 @@ func (h *Handler) Stats(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, response)
|
||||
}
|
||||
|
||||
// Blacklist handles blacklist requests
|
||||
func (h *Handler) Blacklist(c *gin.Context) {
|
||||
blacklist := h.keyManager.GetBlacklist()
|
||||
|
||||
response := gin.H{
|
||||
"blacklisted_keys": blacklist,
|
||||
"count": len(blacklist),
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response)
|
||||
}
|
||||
|
||||
// ResetKeys handles key reset requests
|
||||
func (h *Handler) ResetKeys(c *gin.Context) {
|
||||
// Reset blacklist
|
||||
h.keyManager.ResetBlacklist()
|
||||
|
||||
// Reload keys from file
|
||||
if err := h.keyManager.LoadKeys(); err != nil {
|
||||
logrus.Errorf("Failed to reload keys: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Failed to reload keys",
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
stats := h.keyManager.GetStats()
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "Keys reset and reloaded successfully",
|
||||
"total_keys": stats.TotalKeys,
|
||||
"healthy_keys": stats.HealthyKeys,
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339),
|
||||
})
|
||||
|
||||
logrus.Info("Keys reset and reloaded successfully")
|
||||
}
|
||||
|
||||
// MethodNotAllowed handles 405 requests
|
||||
func (h *Handler) MethodNotAllowed(c *gin.Context) {
|
||||
func (s *Server) MethodNotAllowed(c *gin.Context) {
|
||||
c.JSON(http.StatusMethodNotAllowed, gin.H{
|
||||
"error": "Method not allowed",
|
||||
"path": c.Request.URL.Path,
|
||||
@@ -146,7 +159,7 @@ func (h *Handler) MethodNotAllowed(c *gin.Context) {
|
||||
}
|
||||
|
||||
// GetConfig returns configuration information (for debugging)
|
||||
func (h *Handler) GetConfig(c *gin.Context) {
|
||||
func (s *Server) GetConfig(c *gin.Context) {
|
||||
// Only allow in development mode or with special header
|
||||
if c.GetHeader("X-Debug-Config") != "true" {
|
||||
c.JSON(http.StatusForbidden, gin.H{
|
||||
@@ -155,13 +168,13 @@ func (h *Handler) GetConfig(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
serverConfig := h.config.GetServerConfig()
|
||||
keysConfig := h.config.GetKeysConfig()
|
||||
openaiConfig := h.config.GetOpenAIConfig()
|
||||
authConfig := h.config.GetAuthConfig()
|
||||
corsConfig := h.config.GetCORSConfig()
|
||||
perfConfig := h.config.GetPerformanceConfig()
|
||||
logConfig := h.config.GetLogConfig()
|
||||
serverConfig := s.config.GetServerConfig()
|
||||
keysConfig := s.config.GetKeysConfig()
|
||||
openaiConfig := s.config.GetOpenAIConfig()
|
||||
authConfig := s.config.GetAuthConfig()
|
||||
corsConfig := s.config.GetCORSConfig()
|
||||
perfConfig := s.config.GetPerformanceConfig()
|
||||
logConfig := s.config.GetLogConfig()
|
||||
|
||||
// Sanitize sensitive information
|
||||
sanitizedConfig := gin.H{
|
||||
|
119
internal/handler/key_handler.go
Normal file
119
internal/handler/key_handler.go
Normal file
@@ -0,0 +1,119 @@
|
||||
// Package handler provides HTTP handlers for the application
|
||||
package handler
|
||||
|
||||
import (
|
||||
"gpt-load/internal/models"
|
||||
"gpt-load/internal/response"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type CreateKeysRequest struct {
|
||||
Keys []string `json:"keys" binding:"required"`
|
||||
}
|
||||
|
||||
// CreateKeysInGroup handles creating new keys within a specific group.
|
||||
func (s *Server) CreateKeysInGroup(c *gin.Context) {
|
||||
groupID, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "Invalid group ID")
|
||||
return
|
||||
}
|
||||
|
||||
var req CreateKeysRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "Invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
var newKeys []models.APIKey
|
||||
for _, keyVal := range req.Keys {
|
||||
newKeys = append(newKeys, models.APIKey{
|
||||
GroupID: uint(groupID),
|
||||
KeyValue: keyVal,
|
||||
Status: "active",
|
||||
})
|
||||
}
|
||||
|
||||
if err := s.DB.Create(&newKeys).Error; err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "Failed to create keys")
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, newKeys)
|
||||
}
|
||||
|
||||
// ListKeysInGroup handles listing all keys within a specific group.
|
||||
func (s *Server) ListKeysInGroup(c *gin.Context) {
|
||||
groupID, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "Invalid group ID")
|
||||
return
|
||||
}
|
||||
|
||||
var keys []models.APIKey
|
||||
if err := s.DB.Where("group_id = ?", groupID).Find(&keys).Error; err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "Failed to list keys")
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, keys)
|
||||
}
|
||||
|
||||
// UpdateKey handles updating a specific key.
|
||||
func (s *Server) UpdateKey(c *gin.Context) {
|
||||
keyID, err := strconv.Atoi(c.Param("key_id"))
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "Invalid key ID")
|
||||
return
|
||||
}
|
||||
|
||||
var key models.APIKey
|
||||
if err := s.DB.First(&key, keyID).Error; err != nil {
|
||||
response.Error(c, http.StatusNotFound, "Key not found")
|
||||
return
|
||||
}
|
||||
|
||||
var updateData struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&updateData); err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "Invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
key.Status = updateData.Status
|
||||
if err := s.DB.Save(&key).Error; err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "Failed to update key")
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, key)
|
||||
}
|
||||
|
||||
type DeleteKeysRequest struct {
|
||||
KeyIDs []uint `json:"key_ids" binding:"required"`
|
||||
}
|
||||
|
||||
// DeleteKeys handles deleting one or more keys.
|
||||
func (s *Server) DeleteKeys(c *gin.Context) {
|
||||
var req DeleteKeysRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.Error(c, http.StatusBadRequest, "Invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
if len(req.KeyIDs) == 0 {
|
||||
response.Error(c, http.StatusBadRequest, "No key IDs provided")
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.DB.Delete(&models.APIKey{}, req.KeyIDs).Error; err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "Failed to delete keys")
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, gin.H{"message": "Keys deleted successfully"})
|
||||
}
|
79
internal/handler/log_handler.go
Normal file
79
internal/handler/log_handler.go
Normal file
@@ -0,0 +1,79 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gpt-load/internal/db"
|
||||
"gpt-load/internal/models"
|
||||
"gpt-load/internal/response"
|
||||
)
|
||||
|
||||
// GetLogs godoc
|
||||
// @Summary Get request logs
|
||||
// @Description Get request logs with pagination and filtering
|
||||
// @Tags Logs
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param page query int false "Page number"
|
||||
// @Param size query int false "Page size"
|
||||
// @Param group_id query int false "Group ID"
|
||||
// @Param start_time query string false "Start time (RFC3339)"
|
||||
// @Param end_time query string false "End time (RFC3339)"
|
||||
// @Param status_code query int false "Status code"
|
||||
// @Success 200 {array} models.RequestLog
|
||||
// @Router /api/logs [get]
|
||||
func GetLogs(c *gin.Context) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
|
||||
offset := (page - 1) * size
|
||||
|
||||
query := db.DB.Model(&models.RequestLog{})
|
||||
|
||||
if groupIDStr := c.Query("group_id"); groupIDStr != "" {
|
||||
groupID, err := strconv.Atoi(groupIDStr)
|
||||
if err == nil {
|
||||
query = query.Where("group_id = ?", groupID)
|
||||
}
|
||||
}
|
||||
|
||||
if startTimeStr := c.Query("start_time"); startTimeStr != "" {
|
||||
startTime, err := time.Parse(time.RFC3339, startTimeStr)
|
||||
if err == nil {
|
||||
query = query.Where("timestamp >= ?", startTime)
|
||||
}
|
||||
}
|
||||
|
||||
if endTimeStr := c.Query("end_time"); endTimeStr != "" {
|
||||
endTime, err := time.Parse(time.RFC3339, endTimeStr)
|
||||
if err == nil {
|
||||
query = query.Where("timestamp <= ?", endTime)
|
||||
}
|
||||
}
|
||||
|
||||
if statusCodeStr := c.Query("status_code"); statusCodeStr != "" {
|
||||
statusCode, err := strconv.Atoi(statusCodeStr)
|
||||
if err == nil {
|
||||
query = query.Where("status_code = ?", statusCode)
|
||||
}
|
||||
}
|
||||
|
||||
var logs []models.RequestLog
|
||||
var total int64
|
||||
|
||||
query.Count(&total)
|
||||
err := query.Order("timestamp desc").Offset(offset).Limit(size).Find(&logs).Error
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, "Failed to get logs")
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"total": total,
|
||||
"page": page,
|
||||
"size": size,
|
||||
"data": logs,
|
||||
})
|
||||
}
|
26
internal/handler/reload_handler.go
Normal file
26
internal/handler/reload_handler.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"gpt-load/internal/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// ReloadConfig handles the POST /api/reload request.
|
||||
// It triggers a configuration reload.
|
||||
func (s *Server) ReloadConfig(c *gin.Context) {
|
||||
if s.config == nil {
|
||||
response.InternalError(c, "Configuration manager is not initialized")
|
||||
return
|
||||
}
|
||||
|
||||
err := s.config.ReloadConfig()
|
||||
if err != nil {
|
||||
logrus.Errorf("Failed to reload config: %v", err)
|
||||
response.InternalError(c, "Failed to reload config")
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, gin.H{"message": "Configuration reloaded successfully"})
|
||||
}
|
62
internal/handler/settings_handler.go
Normal file
62
internal/handler/settings_handler.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"gpt-load/internal/db"
|
||||
"gpt-load/internal/models"
|
||||
"gpt-load/internal/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// GetSettings handles the GET /api/settings request.
|
||||
// It retrieves all system settings from the database and returns them as a key-value map.
|
||||
func GetSettings(c *gin.Context) {
|
||||
var settings []models.SystemSetting
|
||||
if err := db.DB.Find(&settings).Error; err != nil {
|
||||
response.InternalError(c, "Failed to retrieve settings")
|
||||
return
|
||||
}
|
||||
|
||||
settingsMap := make(map[string]string)
|
||||
for _, s := range settings {
|
||||
settingsMap[s.SettingKey] = s.SettingValue
|
||||
}
|
||||
|
||||
response.Success(c, settingsMap)
|
||||
}
|
||||
|
||||
// UpdateSettings handles the PUT /api/settings request.
|
||||
// It receives a key-value JSON object and updates or creates settings in the database.
|
||||
func UpdateSettings(c *gin.Context) {
|
||||
var settingsMap map[string]string
|
||||
if err := c.ShouldBindJSON(&settingsMap); err != nil {
|
||||
response.BadRequest(c, "Invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
var settingsToUpdate []models.SystemSetting
|
||||
for key, value := range settingsMap {
|
||||
settingsToUpdate = append(settingsToUpdate, models.SystemSetting{
|
||||
SettingKey: key,
|
||||
SettingValue: value,
|
||||
})
|
||||
}
|
||||
|
||||
if len(settingsToUpdate) == 0 {
|
||||
response.Success(c, nil)
|
||||
return
|
||||
}
|
||||
|
||||
// Using OnConflict to perform an "upsert" operation.
|
||||
// If a setting with the same key exists, it will be updated. Otherwise, a new one will be created.
|
||||
if err := db.DB.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "setting_key"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"setting_value"}),
|
||||
}).Create(&settingsToUpdate).Error; err != nil {
|
||||
response.InternalError(c, "Failed to update settings")
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, nil)
|
||||
}
|
66
internal/models/types.go
Normal file
66
internal/models/types.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// SystemSetting 对应 system_settings 表
|
||||
type SystemSetting struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
SettingKey string `gorm:"type:varchar(255);not null;unique" json:"setting_key"`
|
||||
SettingValue string `gorm:"type:text;not null" json:"setting_value"`
|
||||
Description string `gorm:"type:varchar(512)" json:"description"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// Group 对应 groups 表
|
||||
type Group struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
Name string `gorm:"type:varchar(255);not null;unique" json:"name"`
|
||||
Description string `gorm:"type:varchar(512)" json:"description"`
|
||||
ChannelType string `gorm:"type:varchar(50);not null" json:"channel_type"`
|
||||
Config string `gorm:"type:json" json:"config"`
|
||||
APIKeys []APIKey `gorm:"foreignKey:GroupID" json:"api_keys"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// APIKey 对应 api_keys 表
|
||||
type APIKey struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
GroupID uint `gorm:"not null" json:"group_id"`
|
||||
KeyValue string `gorm:"type:varchar(512);not null" json:"key_value"`
|
||||
Status string `gorm:"type:varchar(50);not null;default:'active'" json:"status"`
|
||||
RequestCount int64 `gorm:"not null;default:0" json:"request_count"`
|
||||
FailureCount int64 `gorm:"not null;default:0" json:"failure_count"`
|
||||
LastUsedAt *time.Time `json:"last_used_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// RequestLog 对应 request_logs 表
|
||||
type RequestLog struct {
|
||||
ID string `gorm:"type:varchar(36);primaryKey" json:"id"`
|
||||
Timestamp time.Time `gorm:"type:datetime(3);not null" json:"timestamp"`
|
||||
GroupID uint `gorm:"not null" json:"group_id"`
|
||||
KeyID uint `gorm:"not null" json:"key_id"`
|
||||
SourceIP string `gorm:"type:varchar(45)" json:"source_ip"`
|
||||
StatusCode int `gorm:"not null" json:"status_code"`
|
||||
RequestPath string `gorm:"type:varchar(1024)" json:"request_path"`
|
||||
RequestBodySnippet string `gorm:"type:text" json:"request_body_snippet"`
|
||||
}
|
||||
|
||||
// GroupRequestStat 用于表示每个分组的请求统计
|
||||
type GroupRequestStat struct {
|
||||
GroupName string `json:"group_name"`
|
||||
RequestCount int64 `json:"request_count"`
|
||||
}
|
||||
|
||||
// DashboardStats 用于仪表盘的统计数据
|
||||
type DashboardStats struct {
|
||||
TotalRequests int64 `json:"total_requests"`
|
||||
SuccessRequests int64 `json:"success_requests"`
|
||||
SuccessRate float64 `json:"success_rate"`
|
||||
GroupStats []GroupRequestStat `json:"group_stats"`
|
||||
}
|
@@ -2,498 +2,118 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"gpt-load/internal/channel"
|
||||
"gpt-load/internal/models"
|
||||
"gpt-load/internal/response"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gpt-load/internal/errors"
|
||||
"gpt-load/internal/types"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// A list of errors that are considered normal during streaming when a client disconnects.
|
||||
var ignorableStreamErrors = []string{
|
||||
"context canceled",
|
||||
"connection reset by peer",
|
||||
"broken pipe",
|
||||
"use of closed network connection",
|
||||
}
|
||||
|
||||
// isIgnorableStreamError checks if the error is a common, non-critical error that can occur
|
||||
// when a client disconnects during a streaming response.
|
||||
func isIgnorableStreamError(err error) bool {
|
||||
errStr := err.Error()
|
||||
for _, ignorableError := range ignorableStreamErrors {
|
||||
if strings.Contains(errStr, ignorableError) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ProxyServer represents the proxy server
|
||||
type ProxyServer struct {
|
||||
keyManager types.KeyManager
|
||||
configManager types.ConfigManager
|
||||
httpClient *http.Client
|
||||
streamClient *http.Client // Dedicated client for streaming
|
||||
requestCount int64
|
||||
startTime time.Time
|
||||
DB *gorm.DB
|
||||
groupCounters sync.Map // For round-robin key selection
|
||||
requestLogChan chan models.RequestLog
|
||||
}
|
||||
|
||||
// NewProxyServer creates a new proxy server
|
||||
func NewProxyServer(keyManager types.KeyManager, configManager types.ConfigManager) (*ProxyServer, error) {
|
||||
openaiConfig := configManager.GetOpenAIConfig()
|
||||
perfConfig := configManager.GetPerformanceConfig()
|
||||
|
||||
// Create high-performance HTTP client
|
||||
transport := &http.Transport{
|
||||
MaxIdleConns: 100,
|
||||
MaxIdleConnsPerHost: 20,
|
||||
MaxConnsPerHost: 0,
|
||||
IdleConnTimeout: time.Duration(openaiConfig.IdleConnTimeout) * time.Second,
|
||||
TLSHandshakeTimeout: 15 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
DisableCompression: !perfConfig.EnableGzip,
|
||||
ForceAttemptHTTP2: true,
|
||||
WriteBufferSize: 32 * 1024,
|
||||
ReadBufferSize: 32 * 1024,
|
||||
}
|
||||
|
||||
// Create dedicated transport for streaming, optimize TCP parameters
|
||||
streamTransport := &http.Transport{
|
||||
MaxIdleConns: 200,
|
||||
MaxIdleConnsPerHost: 40,
|
||||
MaxConnsPerHost: 0,
|
||||
IdleConnTimeout: time.Duration(openaiConfig.IdleConnTimeout) * time.Second,
|
||||
TLSHandshakeTimeout: 15 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
DisableCompression: true,
|
||||
ForceAttemptHTTP2: true,
|
||||
WriteBufferSize: 0,
|
||||
ReadBufferSize: 0,
|
||||
ResponseHeaderTimeout: time.Duration(openaiConfig.ResponseTimeout) * time.Second,
|
||||
}
|
||||
|
||||
httpClient := &http.Client{
|
||||
Transport: transport,
|
||||
Timeout: time.Duration(openaiConfig.RequestTimeout) * time.Second,
|
||||
}
|
||||
|
||||
// Streaming client without overall timeout
|
||||
streamClient := &http.Client{
|
||||
Transport: streamTransport,
|
||||
}
|
||||
|
||||
func NewProxyServer(db *gorm.DB, requestLogChan chan models.RequestLog) (*ProxyServer, error) {
|
||||
return &ProxyServer{
|
||||
keyManager: keyManager,
|
||||
configManager: configManager,
|
||||
httpClient: httpClient,
|
||||
streamClient: streamClient,
|
||||
startTime: time.Now(),
|
||||
DB: db,
|
||||
groupCounters: sync.Map{},
|
||||
requestLogChan: requestLogChan,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// HandleProxy handles proxy requests
|
||||
// RegisterProxyRoutes registers the main proxy route under a given router group
|
||||
func (ps *ProxyServer) RegisterProxyRoutes(proxy *gin.RouterGroup) {
|
||||
proxy.Any("/:group_name/*path", ps.HandleProxy)
|
||||
}
|
||||
|
||||
// HandleProxy handles the main proxy logic
|
||||
func (ps *ProxyServer) HandleProxy(c *gin.Context) {
|
||||
startTime := time.Now()
|
||||
groupName := c.Param("group_name")
|
||||
|
||||
// Increment request count
|
||||
atomic.AddInt64(&ps.requestCount, 1)
|
||||
|
||||
// Cache all request body upfront
|
||||
var bodyBytes []byte
|
||||
if c.Request.Body != nil {
|
||||
var err error
|
||||
bodyBytes, err = io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
logrus.Errorf("Failed to read request body: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Failed to read request body",
|
||||
"code": errors.ErrProxyRequest,
|
||||
})
|
||||
// 1. Find the group by name
|
||||
var group models.Group
|
||||
if err := ps.DB.Preload("APIKeys").Where("name = ?", groupName).First(&group).Error; err != nil {
|
||||
response.Error(c, http.StatusNotFound, fmt.Sprintf("Group '%s' not found", groupName))
|
||||
return
|
||||
}
|
||||
|
||||
// 2. Select an available API key from the group
|
||||
apiKey, err := ps.selectAPIKey(&group)
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusServiceUnavailable, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Determine if this is a streaming request using cached data
|
||||
isStreamRequest := ps.isStreamRequest(bodyBytes, c)
|
||||
// 3. Get the appropriate channel handler from the factory
|
||||
channelHandler, err := channel.GetChannel(&group)
|
||||
if err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, fmt.Sprintf("Failed to get channel for group '%s': %v", groupName, err))
|
||||
return
|
||||
}
|
||||
|
||||
// Execute request with retry
|
||||
ps.executeRequestWithRetry(c, startTime, bodyBytes, isStreamRequest, 0, nil)
|
||||
// 4. Forward the request using the channel handler
|
||||
channelHandler.Handle(c, apiKey, &group)
|
||||
|
||||
// 5. Log the request asynchronously
|
||||
go ps.logRequest(c, &group, apiKey, startTime)
|
||||
}
|
||||
|
||||
// isStreamRequest determines if this is a streaming request
|
||||
func (ps *ProxyServer) isStreamRequest(bodyBytes []byte, c *gin.Context) bool {
|
||||
// Check for Gemini streaming endpoint
|
||||
if strings.HasSuffix(c.Request.URL.Path, ":streamGenerateContent") {
|
||||
return true
|
||||
}
|
||||
|
||||
// Check Accept header
|
||||
if strings.Contains(c.GetHeader("Accept"), "text/event-stream") {
|
||||
return true
|
||||
}
|
||||
|
||||
// Check URL query parameter
|
||||
if c.Query("stream") == "true" {
|
||||
return true
|
||||
}
|
||||
|
||||
// Check stream parameter in request body
|
||||
if len(bodyBytes) > 0 {
|
||||
var bodyJSON map[string]interface{}
|
||||
if err := json.Unmarshal(bodyBytes, &bodyJSON); err == nil {
|
||||
if stream, ok := bodyJSON["stream"].(bool); ok && stream {
|
||||
return true
|
||||
}
|
||||
// selectAPIKey selects an API key from a group using round-robin
|
||||
func (ps *ProxyServer) selectAPIKey(group *models.Group) (*models.APIKey, error) {
|
||||
activeKeys := make([]models.APIKey, 0, len(group.APIKeys))
|
||||
for _, key := range group.APIKeys {
|
||||
if key.Status == "active" {
|
||||
activeKeys = append(activeKeys, key)
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
if len(activeKeys) == 0 {
|
||||
return nil, fmt.Errorf("no active API keys available in group '%s'", group.Name)
|
||||
}
|
||||
|
||||
// Get the current counter for the group
|
||||
counter, _ := ps.groupCounters.LoadOrStore(group.ID, uint64(0))
|
||||
currentCounter := counter.(uint64)
|
||||
|
||||
// Select the key and increment the counter
|
||||
selectedKey := activeKeys[int(currentCounter%uint64(len(activeKeys)))]
|
||||
ps.groupCounters.Store(group.ID, currentCounter+1)
|
||||
|
||||
return &selectedKey, nil
|
||||
}
|
||||
|
||||
// executeRequestWithRetry executes request with retry logic
|
||||
func (ps *ProxyServer) executeRequestWithRetry(c *gin.Context, startTime time.Time, bodyBytes []byte, isStreamRequest bool, retryCount int, retryErrors []types.RetryError) {
|
||||
keysConfig := ps.configManager.GetKeysConfig()
|
||||
|
||||
if retryCount > keysConfig.MaxRetries {
|
||||
logrus.Debugf("Max retries exceeded (%d)", retryCount-1)
|
||||
|
||||
errorResponse := gin.H{
|
||||
"error": "Max retries exceeded",
|
||||
"code": errors.ErrProxyRetryExhausted,
|
||||
"retry_count": retryCount - 1,
|
||||
"retry_errors": retryErrors,
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339),
|
||||
func (ps *ProxyServer) logRequest(c *gin.Context, group *models.Group, key *models.APIKey, startTime time.Time) {
|
||||
logEntry := models.RequestLog{
|
||||
ID: fmt.Sprintf("req_%d", time.Now().UnixNano()),
|
||||
Timestamp: startTime,
|
||||
GroupID: group.ID,
|
||||
KeyID: key.ID,
|
||||
SourceIP: c.ClientIP(),
|
||||
StatusCode: c.Writer.Status(),
|
||||
RequestPath: c.Request.URL.Path,
|
||||
RequestBodySnippet: "", // Can be implemented later if needed
|
||||
}
|
||||
|
||||
statusCode := http.StatusBadGateway
|
||||
if len(retryErrors) > 0 && retryErrors[len(retryErrors)-1].StatusCode > 0 {
|
||||
statusCode = retryErrors[len(retryErrors)-1].StatusCode
|
||||
}
|
||||
|
||||
c.JSON(statusCode, errorResponse)
|
||||
return
|
||||
}
|
||||
|
||||
// Get key information
|
||||
keyInfo, err := ps.keyManager.GetNextKey()
|
||||
if err != nil {
|
||||
logrus.Errorf("Failed to get key: %v", err)
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{
|
||||
"error": "No API keys available",
|
||||
"code": errors.ErrNoKeysAvailable,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Set key information to context (for logging)
|
||||
c.Set("keyIndex", keyInfo.Index)
|
||||
c.Set("keyPreview", keyInfo.Preview)
|
||||
|
||||
// Set retry information to context
|
||||
if retryCount > 0 {
|
||||
c.Set("retryCount", retryCount)
|
||||
}
|
||||
|
||||
// Get a base URL from the config manager (handles round-robin)
|
||||
openaiConfig := ps.configManager.GetOpenAIConfig()
|
||||
upstreamURL, err := url.Parse(openaiConfig.BaseURL)
|
||||
if err != nil {
|
||||
logrus.Errorf("Failed to parse upstream URL: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Invalid upstream URL configured",
|
||||
"code": errors.ErrConfigInvalid,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Build upstream request URL
|
||||
targetURL := *upstreamURL
|
||||
// Correctly append path instead of replacing it
|
||||
if strings.HasSuffix(targetURL.Path, "/") {
|
||||
targetURL.Path = targetURL.Path + strings.TrimPrefix(c.Request.URL.Path, "/")
|
||||
} else {
|
||||
targetURL.Path = targetURL.Path + c.Request.URL.Path
|
||||
}
|
||||
targetURL.RawQuery = c.Request.URL.RawQuery
|
||||
|
||||
// Use different timeout strategies for streaming and non-streaming requests
|
||||
var ctx context.Context
|
||||
var cancel context.CancelFunc
|
||||
|
||||
if isStreamRequest {
|
||||
// Streaming requests only set response header timeout, no overall timeout
|
||||
ctx, cancel = context.WithCancel(c.Request.Context())
|
||||
} else {
|
||||
// Non-streaming requests use configured timeout from the already fetched config
|
||||
timeout := time.Duration(openaiConfig.RequestTimeout) * time.Second
|
||||
ctx, cancel = context.WithTimeout(c.Request.Context(), timeout)
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
// Create request using cached bodyBytes
|
||||
req, err := http.NewRequestWithContext(
|
||||
ctx,
|
||||
c.Request.Method,
|
||||
targetURL.String(),
|
||||
bytes.NewReader(bodyBytes),
|
||||
)
|
||||
if err != nil {
|
||||
logrus.Errorf("Failed to create upstream request: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Failed to create upstream request",
|
||||
"code": errors.ErrProxyRequest,
|
||||
})
|
||||
return
|
||||
}
|
||||
req.ContentLength = int64(len(bodyBytes))
|
||||
|
||||
// Copy request headers
|
||||
for key, values := range c.Request.Header {
|
||||
if key != "Host" {
|
||||
for _, value := range values {
|
||||
req.Header.Add(key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if c.GetHeader("Authorization") != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+keyInfo.Key)
|
||||
req.Header.Del("X-Goog-Api-Key")
|
||||
} else if c.GetHeader("X-Goog-Api-Key") != "" {
|
||||
req.Header.Set("X-Goog-Api-Key", keyInfo.Key)
|
||||
req.Header.Del("Authorization")
|
||||
} else if c.Query("key") != "" {
|
||||
q := req.URL.Query()
|
||||
q.Set("key", keyInfo.Key)
|
||||
req.URL.RawQuery = q.Encode()
|
||||
} else {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"error": "API key required. Please provide a key in 'Authorization' or 'X-Goog-Api-Key' header.",
|
||||
"code": errors.ErrAuthMissing,
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Choose appropriate client based on request type
|
||||
var client *http.Client
|
||||
if isStreamRequest {
|
||||
client = ps.streamClient
|
||||
// Add header to disable nginx buffering
|
||||
req.Header.Set("X-Accel-Buffering", "no")
|
||||
} else {
|
||||
client = ps.httpClient
|
||||
}
|
||||
|
||||
// Send request
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
responseTime := time.Since(startTime)
|
||||
|
||||
// Log failure
|
||||
if retryCount > 0 {
|
||||
logrus.Warnf("Retry request failed (attempt %d): %v (response time: %v)", retryCount+1, err, responseTime)
|
||||
} else {
|
||||
logrus.Warnf("Initial request failed: %v (response time: %v)", err, responseTime)
|
||||
}
|
||||
|
||||
// Record failure asynchronously
|
||||
go ps.keyManager.RecordFailure(keyInfo.Key, err)
|
||||
|
||||
// Record retry error information
|
||||
if retryErrors == nil {
|
||||
retryErrors = make([]types.RetryError, 0)
|
||||
}
|
||||
retryErrors = append(retryErrors, types.RetryError{
|
||||
StatusCode: 0, // Network error, no HTTP status code
|
||||
ErrorMessage: err.Error(),
|
||||
KeyIndex: keyInfo.Index,
|
||||
Attempt: retryCount + 1,
|
||||
})
|
||||
|
||||
// Retry
|
||||
ps.executeRequestWithRetry(c, startTime, bodyBytes, isStreamRequest, retryCount+1, retryErrors)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
responseTime := time.Since(startTime)
|
||||
|
||||
// Check if HTTP status code requires retry
|
||||
if resp.StatusCode >= 400 {
|
||||
// Log failure
|
||||
if retryCount > 0 {
|
||||
logrus.Debugf("Retry request returned error %d (attempt %d) (response time: %v)", resp.StatusCode, retryCount+1, responseTime)
|
||||
} else {
|
||||
logrus.Debugf("Initial request returned error %d (response time: %v)", resp.StatusCode, responseTime)
|
||||
}
|
||||
|
||||
// Read response body to get error information
|
||||
var errorMessage string
|
||||
bodyBytes, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
errorMessage = fmt.Sprintf("HTTP %d (failed to read body: %v)", resp.StatusCode, err)
|
||||
} else {
|
||||
if resp.Header.Get("Content-Encoding") == "gzip" {
|
||||
reader, gErr := gzip.NewReader(bytes.NewReader(bodyBytes))
|
||||
if gErr != nil {
|
||||
errorMessage = fmt.Sprintf("gzip reader error: %v", gErr)
|
||||
} else {
|
||||
uncompressedBytes, rErr := io.ReadAll(reader)
|
||||
reader.Close()
|
||||
if rErr != nil {
|
||||
errorMessage = fmt.Sprintf("gzip read error: %v", rErr)
|
||||
} else {
|
||||
errorMessage = string(uncompressedBytes)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
errorMessage = string(bodyBytes)
|
||||
}
|
||||
}
|
||||
|
||||
var jsonError struct {
|
||||
Error struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal([]byte(errorMessage), &jsonError); err == nil && jsonError.Error.Message != "" {
|
||||
logrus.Warnf("Http Error: %s", jsonError.Error.Message)
|
||||
} else {
|
||||
logrus.Warnf("Http Error: %s", errorMessage)
|
||||
}
|
||||
|
||||
// Record failure asynchronously
|
||||
go ps.keyManager.RecordFailure(keyInfo.Key, fmt.Errorf("HTTP %d", resp.StatusCode))
|
||||
|
||||
// Record retry error information
|
||||
if retryErrors == nil {
|
||||
retryErrors = make([]types.RetryError, 0)
|
||||
}
|
||||
retryErrors = append(retryErrors, types.RetryError{
|
||||
StatusCode: resp.StatusCode,
|
||||
ErrorMessage: errorMessage,
|
||||
KeyIndex: keyInfo.Index,
|
||||
Attempt: retryCount + 1,
|
||||
})
|
||||
|
||||
// Retry
|
||||
ps.executeRequestWithRetry(c, startTime, bodyBytes, isStreamRequest, retryCount+1, retryErrors)
|
||||
return
|
||||
}
|
||||
|
||||
// Success - record success asynchronously
|
||||
go ps.keyManager.RecordSuccess(keyInfo.Key)
|
||||
|
||||
// Log final success result
|
||||
if retryCount > 0 {
|
||||
logrus.Debugf("Request succeeded after %d retries (response time: %v)", retryCount, responseTime)
|
||||
} else {
|
||||
logrus.Debugf("Request succeeded on first attempt (response time: %v)", responseTime)
|
||||
}
|
||||
|
||||
// Copy response headers
|
||||
for key, values := range resp.Header {
|
||||
for _, value := range values {
|
||||
c.Header(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
// Set status code
|
||||
c.Status(resp.StatusCode)
|
||||
|
||||
// Handle streaming and non-streaming responses
|
||||
if isStreamRequest {
|
||||
ps.handleStreamingResponse(c, resp)
|
||||
} else {
|
||||
ps.handleNormalResponse(c, resp)
|
||||
// Send to the logging channel without blocking
|
||||
select {
|
||||
case ps.requestLogChan <- logEntry:
|
||||
default:
|
||||
logrus.Warn("Request log channel is full. Dropping log entry.")
|
||||
}
|
||||
}
|
||||
|
||||
var newline = []byte("\n")
|
||||
|
||||
// handleStreamingResponse handles streaming responses
|
||||
func (ps *ProxyServer) handleStreamingResponse(c *gin.Context, resp *http.Response) {
|
||||
// Set headers for streaming
|
||||
c.Header("Cache-Control", "no-cache")
|
||||
c.Header("Connection", "keep-alive")
|
||||
c.Header("Content-Type", "text/event-stream")
|
||||
c.Header("X-Accel-Buffering", "no")
|
||||
|
||||
flusher, ok := c.Writer.(http.Flusher)
|
||||
if !ok {
|
||||
logrus.Error("Streaming unsupported")
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Streaming unsupported",
|
||||
"code": errors.ErrServerInternal,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
scanner := bufio.NewScanner(resp.Body)
|
||||
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
|
||||
|
||||
for scanner.Scan() {
|
||||
lineBytes := scanner.Bytes()
|
||||
if _, err := c.Writer.Write(lineBytes); err != nil {
|
||||
if isIgnorableStreamError(err) {
|
||||
logrus.Debugf("Stream closed by client: %v", err)
|
||||
} else {
|
||||
logrus.Errorf("Failed to write streaming data: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if _, err := c.Writer.Write(newline); err != nil {
|
||||
if isIgnorableStreamError(err) {
|
||||
logrus.Debugf("Stream closed by client: %v", err)
|
||||
} else {
|
||||
logrus.Errorf("Failed to write streaming data: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
flusher.Flush()
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
if isIgnorableStreamError(err) {
|
||||
logrus.Debugf("Stream closed by client or network: %v", err)
|
||||
} else {
|
||||
logrus.Errorf("Error reading streaming response: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleNormalResponse handles normal responses
|
||||
func (ps *ProxyServer) handleNormalResponse(c *gin.Context, resp *http.Response) {
|
||||
// Copy response body
|
||||
if _, err := io.Copy(c.Writer, resp.Body); err != nil {
|
||||
logrus.Errorf("Failed to copy response body: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Close closes the proxy server and cleans up resources
|
||||
// Close cleans up resources
|
||||
func (ps *ProxyServer) Close() {
|
||||
// Close HTTP clients if needed
|
||||
if ps.httpClient != nil {
|
||||
ps.httpClient.CloseIdleConnections()
|
||||
}
|
||||
if ps.streamClient != nil {
|
||||
ps.streamClient.CloseIdleConnections()
|
||||
}
|
||||
// Nothing to close for now
|
||||
}
|
||||
|
48
internal/response/response.go
Normal file
48
internal/response/response.go
Normal file
@@ -0,0 +1,48 @@
|
||||
// Package response provides standardized JSON response helpers.
|
||||
package response
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Response defines the standard JSON response structure.
|
||||
type Response struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// Success sends a standardized success response.
|
||||
func Success(c *gin.Context, data interface{}) {
|
||||
c.JSON(http.StatusOK, Response{
|
||||
Code: 0,
|
||||
Message: "Success",
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
// Error sends a standardized error response.
|
||||
func Error(c *gin.Context, code int, message string) {
|
||||
c.JSON(code, Response{
|
||||
Code: code,
|
||||
Message: message,
|
||||
Data: nil,
|
||||
})
|
||||
}
|
||||
|
||||
// BadRequest sends a 400 Bad Request error response.
|
||||
func BadRequest(c *gin.Context, message string) {
|
||||
Error(c, http.StatusBadRequest, message)
|
||||
}
|
||||
|
||||
// NotFound sends a 404 Not Found error response.
|
||||
func NotFound(c *gin.Context, message string) {
|
||||
Error(c, http.StatusNotFound, message)
|
||||
}
|
||||
|
||||
// InternalError sends a 500 Internal Server Error response.
|
||||
func InternalError(c *gin.Context, message string) {
|
||||
Error(c, http.StatusInternalServerError, message)
|
||||
}
|
@@ -18,6 +18,7 @@ type ConfigManager interface {
|
||||
GetLogConfig() LogConfig
|
||||
Validate() error
|
||||
DisplayConfig()
|
||||
ReloadConfig() error
|
||||
}
|
||||
|
||||
// KeyManager defines the interface for API key management
|
||||
|
24
web/.gitignore
vendored
Normal file
24
web/.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
5
web/README.md
Normal file
5
web/README.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Vue 3 + TypeScript + Vite
|
||||
|
||||
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
|
||||
|
||||
Learn more about the recommended Project Setup and IDE Support in the [Vue Docs TypeScript Guide](https://vuejs.org/guide/typescript/overview.html#project-setup).
|
13
web/index.html
Normal file
13
web/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Vite + Vue + TS</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
2159
web/package-lock.json
generated
Normal file
2159
web/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
27
web/package.json
Normal file
27
web/package.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "web",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc -b && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.10.0",
|
||||
"echarts": "^5.6.0",
|
||||
"element-plus": "^2.10.2",
|
||||
"pinia": "^3.0.3",
|
||||
"vue": "^3.5.17",
|
||||
"vue-router": "^4.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.0.7",
|
||||
"@vitejs/plugin-vue": "^6.0.0",
|
||||
"@vue/tsconfig": "^0.7.0",
|
||||
"typescript": "~5.8.3",
|
||||
"vite": "^7.0.0",
|
||||
"vue-tsc": "^2.2.10"
|
||||
}
|
||||
}
|
7
web/src/App.vue
Normal file
7
web/src/App.vue
Normal file
@@ -0,0 +1,7 @@
|
||||
<template>
|
||||
<MainLayout />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import MainLayout from './layouts/MainLayout.vue';
|
||||
</script>
|
6
web/src/api/dashboard.ts
Normal file
6
web/src/api/dashboard.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import request from './index';
|
||||
import type { DashboardStats } from '@/types/models';
|
||||
|
||||
export const getDashboardStats = (): Promise<DashboardStats> => {
|
||||
return request.get('/api/dashboard/stats');
|
||||
};
|
42
web/src/api/groups.ts
Normal file
42
web/src/api/groups.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import apiClient from './index';
|
||||
import type { Group } from '../types/models';
|
||||
|
||||
/**
|
||||
* 获取所有分组列表
|
||||
*/
|
||||
export const fetchGroups = (): Promise<Group[]> => {
|
||||
return apiClient.get('/groups').then(res => res.data.data);
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取单个分组的详细信息
|
||||
* @param id 分组ID
|
||||
*/
|
||||
export const fetchGroup = (id: string): Promise<Group> => {
|
||||
return apiClient.get(`/groups/${id}`).then(res => res.data.data);
|
||||
};
|
||||
|
||||
/**
|
||||
* 创建一个新的分组
|
||||
* @param groupData 新分组的数据
|
||||
*/
|
||||
export const createGroup = (groupData: Omit<Group, 'id' | 'created_at' | 'updated_at'>): Promise<Group> => {
|
||||
return apiClient.post('/groups', groupData).then(res => res.data.data);
|
||||
};
|
||||
|
||||
/**
|
||||
* 更新一个已存在的分组
|
||||
* @param id 分组ID
|
||||
* @param groupData 要更新的数据
|
||||
*/
|
||||
export const updateGroup = (id: string, groupData: Partial<Omit<Group, 'id' | 'created_at' | 'updated_at'>>): Promise<Group> => {
|
||||
return apiClient.put(`/groups/${id}`, groupData).then(res => res.data.data);
|
||||
};
|
||||
|
||||
/**
|
||||
* 删除一个分组
|
||||
* @param id 分组ID
|
||||
*/
|
||||
export const deleteGroup = (id: string): Promise<void> => {
|
||||
return apiClient.delete(`/groups/${id}`).then(res => res.data);
|
||||
};
|
14
web/src/api/index.ts
Normal file
14
web/src/api/index.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import axios from "axios";
|
||||
|
||||
const apiClient = axios.create({
|
||||
baseURL: "/",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
// 可以添加请求和响应拦截器
|
||||
// apiClient.interceptors.request.use(...)
|
||||
// apiClient.interceptors.response.use(...)
|
||||
|
||||
export default apiClient;
|
36
web/src/api/keys.ts
Normal file
36
web/src/api/keys.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import apiClient from './index';
|
||||
import type { Key } from '../types/models';
|
||||
|
||||
/**
|
||||
* 获取指定分组下的所有密钥列表
|
||||
* @param groupId 分组ID
|
||||
*/
|
||||
export const fetchKeysInGroup = (groupId: string): Promise<Key[]> => {
|
||||
return apiClient.get(`/groups/${groupId}/keys`).then(res => res.data.data);
|
||||
};
|
||||
|
||||
/**
|
||||
* 在指定分组下创建一个新的密钥
|
||||
* @param groupId 分组ID
|
||||
* @param keyData 新密钥的数据
|
||||
*/
|
||||
export const createKey = (groupId: string, keyData: Omit<Key, 'id' | 'group_id' | 'usage' | 'created_at' | 'updated_at'>): Promise<Key> => {
|
||||
return apiClient.post(`/groups/${groupId}/keys`, keyData).then(res => res.data.data);
|
||||
};
|
||||
|
||||
/**
|
||||
* 更新一个已存在的密钥
|
||||
* @param id 密钥ID
|
||||
* @param keyData 要更新的数据
|
||||
*/
|
||||
export const updateKey = (id: string, keyData: Partial<Omit<Key, 'id' | 'group_id' | 'usage' | 'created_at' | 'updated_at'>>): Promise<Key> => {
|
||||
return apiClient.put(`/keys/${id}`, keyData).then(res => res.data.data);
|
||||
};
|
||||
|
||||
/**
|
||||
* 删除一个密钥
|
||||
* @param id 密钥ID
|
||||
*/
|
||||
export const deleteKey = (id: string): Promise<void> => {
|
||||
return apiClient.delete(`/keys/${id}`).then(res => res.data);
|
||||
};
|
24
web/src/api/logs.ts
Normal file
24
web/src/api/logs.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import request from './index';
|
||||
import type { RequestLog } from '@/types/models';
|
||||
|
||||
export type { RequestLog };
|
||||
|
||||
export interface LogQuery {
|
||||
page?: number;
|
||||
size?: number;
|
||||
group_id?: number;
|
||||
start_time?: string;
|
||||
end_time?: string;
|
||||
status_code?: number;
|
||||
}
|
||||
|
||||
export interface PaginatedLogs {
|
||||
total: number;
|
||||
page: number;
|
||||
size: number;
|
||||
data: RequestLog[];
|
||||
}
|
||||
|
||||
export const getLogs = (query: LogQuery): Promise<PaginatedLogs> => {
|
||||
return request.get('/api/logs', { params: query });
|
||||
};
|
10
web/src/api/settings.ts
Normal file
10
web/src/api/settings.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import request from './index';
|
||||
import type { Setting } from '@/types/models';
|
||||
|
||||
export function getSettings() {
|
||||
return request.get<Setting[]>('/api/settings');
|
||||
}
|
||||
|
||||
export function updateSettings(settings: Setting[]) {
|
||||
return request.put('/api/settings', settings);
|
||||
}
|
1
web/src/assets/vue.svg
Normal file
1
web/src/assets/vue.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>
|
After Width: | Height: | Size: 496 B |
80
web/src/components/GroupConfigForm.vue
Normal file
80
web/src/components/GroupConfigForm.vue
Normal file
@@ -0,0 +1,80 @@
|
||||
<template>
|
||||
<div class="group-config-form">
|
||||
<el-card v-if="groupStore.selectedGroupDetails" shadow="never">
|
||||
<template #header>
|
||||
<div class="card-header">
|
||||
<span>分组配置</span>
|
||||
<el-button type="primary" @click="handleSave" :loading="isSaving">保存</el-button>
|
||||
</div>
|
||||
</template>
|
||||
<el-form :model="formData" label-width="120px" ref="formRef">
|
||||
<el-form-item label="分组名称" prop="name" :rules="[{ required: true, message: '请输入分组名称' }]">
|
||||
<el-input v-model="formData.name"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="描述" prop="description">
|
||||
<el-input v-model="formData.description" type="textarea"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="设为默认" prop="is_default">
|
||||
<el-switch v-model="formData.is_default"></el-switch>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
<el-empty v-else description="请先从左侧选择一个分组"></el-empty>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, reactive } from 'vue';
|
||||
import { useGroupStore } from '@/stores/groupStore';
|
||||
import { updateGroup } from '@/api/groups';
|
||||
import { ElCard, ElForm, ElFormItem, ElInput, ElButton, ElSwitch, ElMessage, ElEmpty } from 'element-plus';
|
||||
import type { FormInstance } from 'element-plus';
|
||||
|
||||
const groupStore = useGroupStore();
|
||||
const formRef = ref<FormInstance>();
|
||||
const isSaving = ref(false);
|
||||
|
||||
const formData = reactive({
|
||||
name: '',
|
||||
description: '',
|
||||
is_default: false,
|
||||
});
|
||||
|
||||
watch(() => groupStore.selectedGroupDetails, (newGroup) => {
|
||||
if (newGroup) {
|
||||
formData.name = newGroup.name;
|
||||
formData.description = newGroup.description;
|
||||
formData.is_default = newGroup.is_default;
|
||||
}
|
||||
}, { immediate: true, deep: true });
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!formRef.value || !groupStore.selectedGroupId) return;
|
||||
|
||||
try {
|
||||
await formRef.value.validate();
|
||||
isSaving.value = true;
|
||||
await updateGroup(groupStore.selectedGroupId, {
|
||||
name: formData.name,
|
||||
description: formData.description,
|
||||
is_default: formData.is_default,
|
||||
});
|
||||
ElMessage.success('保存成功');
|
||||
// 刷新列表以获取最新数据
|
||||
await groupStore.fetchGroups();
|
||||
} catch (error) {
|
||||
console.error('Failed to save group config:', error);
|
||||
ElMessage.error('保存失败,请查看控制台');
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.card-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
</style>
|
61
web/src/components/GroupList.vue
Normal file
61
web/src/components/GroupList.vue
Normal file
@@ -0,0 +1,61 @@
|
||||
<template>
|
||||
<div class="group-list" v-loading="groupStore.isLoading">
|
||||
<el-menu
|
||||
:default-active="groupStore.selectedGroupId || undefined"
|
||||
@select="handleSelect"
|
||||
>
|
||||
<el-menu-item
|
||||
v-for="group in groupStore.groups"
|
||||
:key="group.id"
|
||||
:index="group.id"
|
||||
>
|
||||
<template #title>
|
||||
<span>{{ group.name }}</span>
|
||||
<el-tag v-if="group.is_default" size="small" style="margin-left: 8px"
|
||||
>默认</el-tag
|
||||
>
|
||||
</template>
|
||||
</el-menu-item>
|
||||
</el-menu>
|
||||
<div
|
||||
v-if="!groupStore.isLoading && groupStore.groups.length === 0"
|
||||
class="empty-state"
|
||||
>
|
||||
暂无分组
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from "vue";
|
||||
import { useGroupStore } from "@/stores/groupStore";
|
||||
import { ElMenu, ElMenuItem, ElTag, vLoading } from "element-plus";
|
||||
|
||||
const groupStore = useGroupStore();
|
||||
|
||||
onMounted(() => {
|
||||
// 组件挂载时获取分组数据
|
||||
if (groupStore.groups.length === 0) {
|
||||
groupStore.fetchGroups();
|
||||
}
|
||||
});
|
||||
|
||||
const handleSelect = (index: string) => {
|
||||
groupStore.selectGroup(index);
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.group-list {
|
||||
border-right: 1px solid var(--el-border-color);
|
||||
height: 100%;
|
||||
}
|
||||
.el-menu {
|
||||
border-right: none;
|
||||
}
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
color: var(--el-text-color-secondary);
|
||||
padding-top: 20px;
|
||||
}
|
||||
</style>
|
219
web/src/components/KeyTable.vue
Normal file
219
web/src/components/KeyTable.vue
Normal file
@@ -0,0 +1,219 @@
|
||||
<template>
|
||||
<div class="key-table">
|
||||
<el-card shadow="never">
|
||||
<template #header>
|
||||
<div class="card-header">
|
||||
<span>密钥管理</span>
|
||||
<el-button type="primary" @click="handleAddKey" :disabled="!groupStore.selectedGroupId">添加密钥</el-button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<el-table :data="keyStore.keys" v-loading="keyStore.isLoading" style="width: 100%">
|
||||
<el-table-column prop="api_key" label="API Key (部分)" min-width="180">
|
||||
<template #default="scope">
|
||||
{{ scope.row.api_key.substring(0, 3) }}...{{ scope.row.api_key.slice(-4) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="platform" label="平台" width="100" />
|
||||
<el-table-column prop="model_types" label="可用模型" min-width="150">
|
||||
<template #default="scope">
|
||||
<el-tag v-for="model in scope.row.model_types" :key="model" style="margin-right: 5px;">{{ model }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="rate_limit" label="速率限制" width="120">
|
||||
<template #default="scope">
|
||||
{{ scope.row.rate_limit }} / {{ scope.row.rate_limit_unit }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="is_active" label="状态" width="80">
|
||||
<template #default="scope">
|
||||
<el-tag :type="scope.row.is_active ? 'success' : 'danger'">
|
||||
{{ scope.row.is_active ? '启用' : '禁用' }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="150" fixed="right">
|
||||
<template #default="scope">
|
||||
<el-button size="small" @click="handleEditKey(scope.row)">编辑</el-button>
|
||||
<el-popconfirm
|
||||
title="确定要删除这个密钥吗?"
|
||||
@confirm="handleDeleteKey(scope.row.id)"
|
||||
>
|
||||
<template #reference>
|
||||
<el-button size="small" type="danger">删除</el-button>
|
||||
</template>
|
||||
</el-popconfirm>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<el-empty v-if="!keyStore.isLoading && keyStore.keys.length === 0" description="该分组下暂无密钥"></el-empty>
|
||||
</el-card>
|
||||
|
||||
<!-- Add/Edit Dialog -->
|
||||
<el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
|
||||
<el-form :model="keyFormData" label-width="120px" ref="keyFormRef" :rules="keyFormRules">
|
||||
<el-form-item label="API Key" prop="api_key">
|
||||
<el-input v-model="keyFormData.api_key" placeholder="请输入完整的API Key"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="平台" prop="platform">
|
||||
<el-select v-model="keyFormData.platform" placeholder="请选择平台">
|
||||
<el-option label="OpenAI" value="OpenAI"></el-option>
|
||||
<el-option label="Gemini" value="Gemini"></el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="可用模型" prop="model_types">
|
||||
<el-select
|
||||
v-model="keyFormData.model_types"
|
||||
multiple
|
||||
filterable
|
||||
allow-create
|
||||
default-first-option
|
||||
placeholder="请输入或选择可用模型">
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="速率限制" prop="rate_limit">
|
||||
<el-input-number v-model="keyFormData.rate_limit" :min="0"></el-input-number>
|
||||
</el-form-item>
|
||||
<el-form-item label="限制单位" prop="rate_limit_unit">
|
||||
<el-select v-model="keyFormData.rate_limit_unit">
|
||||
<el-option label="分钟" value="minute"></el-option>
|
||||
<el-option label="小时" value="hour"></el-option>
|
||||
<el-option label="天" value="day"></el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="启用状态" prop="is_active">
|
||||
<el-switch v-model="keyFormData.is_active"></el-switch>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<span class="dialog-footer">
|
||||
<el-button @click="dialogVisible = false">取消</el-button>
|
||||
<el-button type="primary" @click="handleConfirmSave" :loading="isSaving">确定</el-button>
|
||||
</span>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, computed } from 'vue';
|
||||
import { useKeyStore } from '@/stores/keyStore';
|
||||
import { useGroupStore } from '@/stores/groupStore';
|
||||
import * as keyApi from '@/api/keys';
|
||||
import type { Key } from '@/types/models';
|
||||
import { ElCard, ElTable, ElTableColumn, ElButton, ElTag, ElPopconfirm, ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElSwitch, ElMessage, ElEmpty, ElInputNumber } from 'element-plus';
|
||||
import type { FormInstance, FormRules } from 'element-plus';
|
||||
|
||||
const keyStore = useKeyStore();
|
||||
const groupStore = useGroupStore();
|
||||
|
||||
const dialogVisible = ref(false);
|
||||
const isSaving = ref(false);
|
||||
const isEdit = ref(false);
|
||||
const currentKeyId = ref<string | null>(null);
|
||||
const keyFormRef = ref<FormInstance>();
|
||||
|
||||
const dialogTitle = computed(() => (isEdit.value ? '编辑密钥' : '添加密钥'));
|
||||
|
||||
const initialFormData: Omit<Key, 'id' | 'group_id' | 'usage' | 'created_at' | 'updated_at'> = {
|
||||
api_key: '',
|
||||
platform: 'OpenAI',
|
||||
model_types: [],
|
||||
rate_limit: 60,
|
||||
rate_limit_unit: 'minute',
|
||||
is_active: true,
|
||||
};
|
||||
|
||||
const keyFormData = reactive({ ...initialFormData });
|
||||
|
||||
const keyFormRules = reactive<FormRules>({
|
||||
api_key: [{ required: true, message: '请输入API Key', trigger: 'blur' }],
|
||||
platform: [{ required: true, message: '请选择平台', trigger: 'change' }],
|
||||
model_types: [{ required: true, message: '请至少输入一个可用模型', trigger: 'change' }],
|
||||
});
|
||||
|
||||
|
||||
const resetForm = () => {
|
||||
Object.assign(keyFormData, initialFormData);
|
||||
currentKeyId.value = null;
|
||||
};
|
||||
|
||||
const handleAddKey = () => {
|
||||
isEdit.value = false;
|
||||
resetForm();
|
||||
dialogVisible.value = true;
|
||||
};
|
||||
|
||||
const handleEditKey = (key: Key) => {
|
||||
isEdit.value = true;
|
||||
resetForm();
|
||||
currentKeyId.value = key.id;
|
||||
// 只填充表单所需字段
|
||||
keyFormData.api_key = key.api_key;
|
||||
keyFormData.platform = key.platform;
|
||||
keyFormData.model_types = key.model_types;
|
||||
keyFormData.rate_limit = key.rate_limit;
|
||||
keyFormData.rate_limit_unit = key.rate_limit_unit;
|
||||
keyFormData.is_active = key.is_active;
|
||||
dialogVisible.value = true;
|
||||
};
|
||||
|
||||
const handleDeleteKey = async (id: string) => {
|
||||
try {
|
||||
await keyApi.deleteKey(id);
|
||||
ElMessage.success('删除成功');
|
||||
if (groupStore.selectedGroupId) {
|
||||
keyStore.fetchKeys(groupStore.selectedGroupId);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to delete key:', error);
|
||||
ElMessage.error('删除失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handleConfirmSave = async () => {
|
||||
if (!keyFormRef.value || !groupStore.selectedGroupId) return;
|
||||
|
||||
try {
|
||||
await keyFormRef.value.validate();
|
||||
isSaving.value = true;
|
||||
|
||||
const dataToSave = {
|
||||
api_key: keyFormData.api_key,
|
||||
platform: keyFormData.platform,
|
||||
model_types: keyFormData.model_types,
|
||||
rate_limit: keyFormData.rate_limit,
|
||||
rate_limit_unit: keyFormData.rate_limit_unit,
|
||||
is_active: keyFormData.is_active,
|
||||
};
|
||||
|
||||
if (isEdit.value && currentKeyId.value) {
|
||||
await keyApi.updateKey(currentKeyId.value, dataToSave);
|
||||
} else {
|
||||
await keyApi.createKey(groupStore.selectedGroupId, dataToSave);
|
||||
}
|
||||
|
||||
ElMessage.success('保存成功');
|
||||
dialogVisible.value = false;
|
||||
await keyStore.fetchKeys(groupStore.selectedGroupId);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Failed to save key:', error);
|
||||
ElMessage.error('保存失败,请检查表单或查看控制台');
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.card-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
.el-table {
|
||||
margin-top: 16px;
|
||||
}
|
||||
</style>
|
66
web/src/components/LogFilter.vue
Normal file
66
web/src/components/LogFilter.vue
Normal file
@@ -0,0 +1,66 @@
|
||||
<template>
|
||||
<el-form :inline="true" :model="filterData" class="log-filter-form">
|
||||
<el-form-item label="分组">
|
||||
<el-select v-model="filterData.group_id" placeholder="所有分组" clearable>
|
||||
<el-option v-for="group in groups" :key="group.id" :label="group.name" :value="group.id" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="时间范围">
|
||||
<el-date-picker
|
||||
v-model="dateRange"
|
||||
type="datetimerange"
|
||||
range-separator="至"
|
||||
start-placeholder="开始日期"
|
||||
end-placeholder="结束日期"
|
||||
@change="handleDateChange"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="状态码">
|
||||
<el-input v-model.number="filterData.status_code" placeholder="例如 200" clearable />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="applyFilters">查询</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, onMounted } from 'vue';
|
||||
import { useLogStore } from '@/stores/logStore';
|
||||
import { useGroupStore } from '@/stores/groupStore';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import type { LogQuery } from '@/api/logs';
|
||||
|
||||
const logStore = useLogStore();
|
||||
const groupStore = useGroupStore();
|
||||
const { groups } = storeToRefs(groupStore);
|
||||
|
||||
const filterData = reactive<LogQuery>({});
|
||||
const dateRange = ref<[Date, Date] | null>(null);
|
||||
|
||||
onMounted(() => {
|
||||
groupStore.fetchGroups();
|
||||
});
|
||||
|
||||
const handleDateChange = (dates: [Date, Date] | null) => {
|
||||
if (dates) {
|
||||
filterData.start_time = dates[0].toISOString();
|
||||
filterData.end_time = dates[1].toISOString();
|
||||
} else {
|
||||
filterData.start_time = undefined;
|
||||
filterData.end_time = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const applyFilters = () => {
|
||||
logStore.setFilters(filterData);
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.log-filter-form {
|
||||
padding: 20px;
|
||||
background-color: #f5f7fa;
|
||||
border-radius: 4px;
|
||||
}
|
||||
</style>
|
52
web/src/components/StatsChart.vue
Normal file
52
web/src/components/StatsChart.vue
Normal file
@@ -0,0 +1,52 @@
|
||||
<template>
|
||||
<div ref="chart" style="width: 100%; height: 400px;"></div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, watch } from 'vue';
|
||||
import * as echarts from 'echarts';
|
||||
import type { GroupRequestStat } from '@/types/models';
|
||||
|
||||
const props = defineProps<{
|
||||
data: GroupRequestStat[];
|
||||
}>();
|
||||
|
||||
const chart = ref<HTMLElement | null>(null);
|
||||
let myChart: echarts.ECharts | null = null;
|
||||
|
||||
const initChart = () => {
|
||||
if (chart.value) {
|
||||
myChart = echarts.init(chart.value);
|
||||
updateChart();
|
||||
}
|
||||
};
|
||||
|
||||
const updateChart = () => {
|
||||
if (!myChart) return;
|
||||
myChart.setOption({
|
||||
title: {
|
||||
text: '各分组请求量',
|
||||
},
|
||||
tooltip: {},
|
||||
xAxis: {
|
||||
data: props.data.map(item => item.group_name),
|
||||
},
|
||||
yAxis: {},
|
||||
series: [
|
||||
{
|
||||
name: '请求量',
|
||||
type: 'bar',
|
||||
data: props.data.map(item => item.request_count),
|
||||
},
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
initChart();
|
||||
});
|
||||
|
||||
watch(() => props.data, () => {
|
||||
updateChart();
|
||||
}, { deep: true });
|
||||
</script>
|
54
web/src/layouts/MainLayout.vue
Normal file
54
web/src/layouts/MainLayout.vue
Normal file
@@ -0,0 +1,54 @@
|
||||
<template>
|
||||
<el-container style="height: 100vh;">
|
||||
<el-aside width="200px">
|
||||
<el-menu
|
||||
:default-active="activeIndex"
|
||||
class="el-menu-vertical-demo"
|
||||
@select="handleSelect"
|
||||
router
|
||||
>
|
||||
<el-menu-item index="/dashboard">
|
||||
<template #title>
|
||||
<span>Dashboard</span>
|
||||
</template>
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/groups">
|
||||
<template #title>
|
||||
<span>Groups</span>
|
||||
</template>
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/logs">
|
||||
<template #title>
|
||||
<span>Logs</span>
|
||||
</template>
|
||||
</el-menu-item>
|
||||
<el-menu-item index="/settings">
|
||||
<template #title>
|
||||
<span>Settings</span>
|
||||
</template>
|
||||
</el-menu-item>
|
||||
</el-menu>
|
||||
</el-aside>
|
||||
<el-main>
|
||||
<router-view></router-view>
|
||||
</el-main>
|
||||
</el-container>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { ref } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
|
||||
const route = useRoute()
|
||||
const activeIndex = ref(route.path)
|
||||
|
||||
const handleSelect = (key: string, keyPath: string[]) => {
|
||||
console.log(key, keyPath)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.el-menu-vertical-demo {
|
||||
height: 100%;
|
||||
}
|
||||
</style>
|
14
web/src/main.ts
Normal file
14
web/src/main.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
|
||||
const app = createApp(App)
|
||||
|
||||
app.use(createPinia())
|
||||
app.use(router)
|
||||
app.use(ElementPlus)
|
||||
|
||||
app.mount('#app')
|
39
web/src/router/index.ts
Normal file
39
web/src/router/index.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router';
|
||||
import Dashboard from '../views/Dashboard.vue';
|
||||
|
||||
const routes = [
|
||||
{
|
||||
path: '/',
|
||||
redirect: '/dashboard',
|
||||
},
|
||||
{
|
||||
path: '/dashboard',
|
||||
name: 'Dashboard',
|
||||
component: Dashboard,
|
||||
},
|
||||
{
|
||||
path: '/groups',
|
||||
name: 'Groups',
|
||||
// route level code-splitting
|
||||
// this generates a separate chunk (About.[hash].js) for this route
|
||||
// which is lazy-loaded when the route is visited.
|
||||
component: () => import('../views/Groups.vue'),
|
||||
},
|
||||
{
|
||||
path: '/logs',
|
||||
name: 'Logs',
|
||||
component: () => import('../views/Logs.vue'),
|
||||
},
|
||||
{
|
||||
path: '/settings',
|
||||
name: 'Settings',
|
||||
component: () => import('../views/Settings.vue'),
|
||||
},
|
||||
];
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes,
|
||||
});
|
||||
|
||||
export default router;
|
27
web/src/stores/dashboardStore.ts
Normal file
27
web/src/stores/dashboardStore.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref } from 'vue';
|
||||
import { getDashboardStats } from '@/api/dashboard';
|
||||
import type { DashboardStats } from '@/types/models';
|
||||
|
||||
export const useDashboardStore = defineStore('dashboard', () => {
|
||||
const stats = ref<DashboardStats | null>(null);
|
||||
const loading = ref(false);
|
||||
|
||||
const fetchStats = async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
const response = await getDashboardStats();
|
||||
stats.value = response;
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch dashboard stats:', error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
stats,
|
||||
loading,
|
||||
fetchStats,
|
||||
};
|
||||
});
|
52
web/src/stores/groupStore.ts
Normal file
52
web/src/stores/groupStore.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref, computed } from 'vue';
|
||||
import * as groupApi from '@/api/groups';
|
||||
import type { Group } from '@/types/models';
|
||||
|
||||
export const useGroupStore = defineStore('group', () => {
|
||||
// State
|
||||
const groups = ref<Group[]>([]);
|
||||
const selectedGroupId = ref<string | null>(null);
|
||||
const isLoading = ref(false);
|
||||
|
||||
// Getters
|
||||
const selectedGroupDetails = computed(() => {
|
||||
if (!selectedGroupId.value) {
|
||||
return null;
|
||||
}
|
||||
return groups.value.find(g => g.id === selectedGroupId.value) || null;
|
||||
});
|
||||
|
||||
// Actions
|
||||
async function fetchGroups() {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
groups.value = await groupApi.fetchGroups();
|
||||
// 默认选中第一个分组
|
||||
if (groups.value.length > 0 && !selectedGroupId.value) {
|
||||
selectedGroupId.value = groups.value[0].id;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch groups:', error);
|
||||
// 这里可以添加更复杂的错误处理逻辑,例如用户通知
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function selectGroup(id: string | null) {
|
||||
selectedGroupId.value = id;
|
||||
}
|
||||
|
||||
return {
|
||||
// State
|
||||
groups,
|
||||
selectedGroupId,
|
||||
isLoading,
|
||||
// Getters
|
||||
selectedGroupDetails,
|
||||
// Actions
|
||||
fetchGroups,
|
||||
selectGroup,
|
||||
};
|
||||
});
|
46
web/src/stores/keyStore.ts
Normal file
46
web/src/stores/keyStore.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref, watch } from 'vue';
|
||||
import * as keyApi from '@/api/keys';
|
||||
import type { Key } from '@/types/models';
|
||||
import { useGroupStore } from './groupStore';
|
||||
|
||||
export const useKeyStore = defineStore('key', () => {
|
||||
// State
|
||||
const keys = ref<Key[]>([]);
|
||||
const isLoading = ref(false);
|
||||
const groupStore = useGroupStore();
|
||||
|
||||
// Actions
|
||||
async function fetchKeys(groupId: string) {
|
||||
if (!groupId) {
|
||||
keys.value = [];
|
||||
return;
|
||||
}
|
||||
isLoading.value = true;
|
||||
try {
|
||||
keys.value = await keyApi.fetchKeysInGroup(groupId);
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch keys for group ${groupId}:`, error);
|
||||
keys.value = []; // 出错时清空列表
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Watch for changes in the selected group and fetch keys accordingly
|
||||
watch(() => groupStore.selectedGroupId, (newGroupId) => {
|
||||
if (newGroupId) {
|
||||
fetchKeys(newGroupId);
|
||||
} else {
|
||||
keys.value = [];
|
||||
}
|
||||
}, { immediate: true }); // immediate: true ensures it runs on initialization
|
||||
|
||||
return {
|
||||
// State
|
||||
keys,
|
||||
isLoading,
|
||||
// Actions
|
||||
fetchKeys,
|
||||
};
|
||||
});
|
61
web/src/stores/logStore.ts
Normal file
61
web/src/stores/logStore.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref, reactive } from 'vue';
|
||||
import { getLogs } from '@/api/logs';
|
||||
import type { RequestLog, LogQuery, PaginatedLogs } from '@/api/logs';
|
||||
|
||||
export const useLogStore = defineStore('logs', () => {
|
||||
const logs = ref<RequestLog[]>([]);
|
||||
const loading = ref(false);
|
||||
const pagination = reactive({
|
||||
page: 1,
|
||||
size: 10,
|
||||
total: 0,
|
||||
});
|
||||
const filters = reactive<LogQuery>({});
|
||||
|
||||
const fetchLogs = async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
const query: LogQuery = {
|
||||
...filters,
|
||||
page: pagination.page,
|
||||
size: pagination.size,
|
||||
};
|
||||
const response: PaginatedLogs = await getLogs(query);
|
||||
logs.value = response.data;
|
||||
pagination.total = response.total;
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch logs:', error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const setFilters = (newFilters: LogQuery) => {
|
||||
Object.assign(filters, newFilters);
|
||||
pagination.page = 1;
|
||||
fetchLogs();
|
||||
};
|
||||
|
||||
const setPage = (page: number) => {
|
||||
pagination.page = page;
|
||||
fetchLogs();
|
||||
};
|
||||
|
||||
const setSize = (size: number) => {
|
||||
pagination.size = size;
|
||||
pagination.page = 1;
|
||||
fetchLogs();
|
||||
};
|
||||
|
||||
return {
|
||||
logs,
|
||||
loading,
|
||||
pagination,
|
||||
filters,
|
||||
fetchLogs,
|
||||
setFilters,
|
||||
setPage,
|
||||
setSize,
|
||||
};
|
||||
});
|
47
web/src/stores/settingStore.ts
Normal file
47
web/src/stores/settingStore.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { getSettings, updateSettings as apiUpdateSettings } from '@/api/settings';
|
||||
import type { Setting } from '@/types/models';
|
||||
import { ElMessage } from 'element-plus';
|
||||
|
||||
interface SettingState {
|
||||
settings: Setting[];
|
||||
loading: boolean;
|
||||
error: any;
|
||||
}
|
||||
|
||||
export const useSettingStore = defineStore('setting', {
|
||||
state: (): SettingState => ({
|
||||
settings: [],
|
||||
loading: false,
|
||||
error: null,
|
||||
}),
|
||||
actions: {
|
||||
async fetchSettings() {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
try {
|
||||
const response = await getSettings();
|
||||
this.settings = response.data;
|
||||
} catch (error) {
|
||||
this.error = error;
|
||||
ElMessage.error('Failed to fetch settings.');
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
async updateSettings(settingsToUpdate: Setting[]) {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
try {
|
||||
await apiUpdateSettings(settingsToUpdate);
|
||||
await this.fetchSettings(); // Refresh the settings after update
|
||||
ElMessage.success('Settings updated successfully.');
|
||||
} catch (error) {
|
||||
this.error = error;
|
||||
ElMessage.error('Failed to update settings.');
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
79
web/src/style.css
Normal file
79
web/src/style.css
Normal file
@@ -0,0 +1,79 @@
|
||||
:root {
|
||||
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||
line-height: 1.5;
|
||||
font-weight: 400;
|
||||
|
||||
color-scheme: light dark;
|
||||
color: rgba(255, 255, 255, 0.87);
|
||||
background-color: #242424;
|
||||
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
a {
|
||||
font-weight: 500;
|
||||
color: #646cff;
|
||||
text-decoration: inherit;
|
||||
}
|
||||
a:hover {
|
||||
color: #535bf2;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
place-items: center;
|
||||
min-width: 320px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 3.2em;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
button {
|
||||
border-radius: 8px;
|
||||
border: 1px solid transparent;
|
||||
padding: 0.6em 1.2em;
|
||||
font-size: 1em;
|
||||
font-weight: 500;
|
||||
font-family: inherit;
|
||||
background-color: #1a1a1a;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.25s;
|
||||
}
|
||||
button:hover {
|
||||
border-color: #646cff;
|
||||
}
|
||||
button:focus,
|
||||
button:focus-visible {
|
||||
outline: 4px auto -webkit-focus-ring-color;
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
#app {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root {
|
||||
color: #213547;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
a:hover {
|
||||
color: #747bff;
|
||||
}
|
||||
button {
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
}
|
59
web/src/types/models.ts
Normal file
59
web/src/types/models.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
// Based on internal/models/types.go
|
||||
|
||||
export interface Key {
|
||||
id: string;
|
||||
group_id: string;
|
||||
api_key: string;
|
||||
platform: 'OpenAI' | 'Gemini';
|
||||
model_types: string[];
|
||||
rate_limit: number;
|
||||
rate_limit_unit: 'minute' | 'hour' | 'day';
|
||||
usage: number;
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface Group {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
is_default: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface GroupWithKeys extends Group {
|
||||
keys: Key[];
|
||||
}
|
||||
|
||||
export interface GroupRequestStat {
|
||||
group_name: string;
|
||||
request_count: number;
|
||||
}
|
||||
|
||||
export interface DashboardStats {
|
||||
total_requests: number;
|
||||
success_requests: number;
|
||||
success_rate: number;
|
||||
group_stats: GroupRequestStat[];
|
||||
}
|
||||
|
||||
export interface RequestLog {
|
||||
id: string;
|
||||
timestamp: string;
|
||||
group_id: number;
|
||||
key_id: number;
|
||||
source_ip: string;
|
||||
status_code: number;
|
||||
request_path: string;
|
||||
request_body_snippet: string;
|
||||
}
|
||||
export interface Setting {
|
||||
key: string;
|
||||
value: string;
|
||||
}
|
||||
export interface Setting {
|
||||
key: string;
|
||||
value: string;
|
||||
}
|
53
web/src/views/Dashboard.vue
Normal file
53
web/src/views/Dashboard.vue
Normal file
@@ -0,0 +1,53 @@
|
||||
<template>
|
||||
<div class="dashboard-page">
|
||||
<h1>仪表盘</h1>
|
||||
<div v-if="loading">加载中...</div>
|
||||
<div v-if="stats" class="stats-grid">
|
||||
<el-card>
|
||||
<el-statistic title="总请求数" :value="stats.total_requests" />
|
||||
</el-card>
|
||||
<el-card>
|
||||
<el-statistic title="成功请求数" :value="stats.success_requests" />
|
||||
</el-card>
|
||||
<el-card>
|
||||
<el-statistic title="成功率" :value="stats.success_rate" :formatter="rateFormatter" />
|
||||
</el-card>
|
||||
</div>
|
||||
<el-card v-if="stats && stats.group_stats.length > 0" class="chart-card">
|
||||
<StatsChart :data="stats.group_stats" />
|
||||
</el-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { useDashboardStore } from '@/stores/dashboardStore';
|
||||
import StatsChart from '@/components/StatsChart.vue';
|
||||
|
||||
const dashboardStore = useDashboardStore();
|
||||
const { stats, loading } = storeToRefs(dashboardStore);
|
||||
|
||||
onMounted(() => {
|
||||
dashboardStore.fetchStats();
|
||||
});
|
||||
|
||||
const rateFormatter = (rate: number) => {
|
||||
return `${(rate * 100).toFixed(2)}%`;
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.dashboard-page {
|
||||
padding: 20px;
|
||||
}
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.chart-card {
|
||||
margin-top: 20px;
|
||||
}
|
||||
</style>
|
53
web/src/views/Groups.vue
Normal file
53
web/src/views/Groups.vue
Normal file
@@ -0,0 +1,53 @@
|
||||
<template>
|
||||
<div class="groups-view">
|
||||
<el-row :gutter="20" class="main-layout">
|
||||
<el-col :span="6" class="left-panel">
|
||||
<group-list />
|
||||
</el-col>
|
||||
<el-col :span="18" class="right-panel">
|
||||
<div class="config-section">
|
||||
<group-config-form />
|
||||
</div>
|
||||
<div class="keys-section">
|
||||
<key-table />
|
||||
</div>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import GroupList from '@/components/GroupList.vue';
|
||||
import GroupConfigForm from '@/components/GroupConfigForm.vue';
|
||||
import KeyTable from '@/components/KeyTable.vue';
|
||||
import { ElRow, ElCol } from 'element-plus';
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.groups-view {
|
||||
height: 100%;
|
||||
padding: 20px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.main-layout, .left-panel, .right-panel {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.left-panel {
|
||||
background-color: #fff;
|
||||
border-radius: 4px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.right-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.config-section, .keys-section {
|
||||
background-color: #fff;
|
||||
border-radius: 4px;
|
||||
}
|
||||
</style>
|
63
web/src/views/Logs.vue
Normal file
63
web/src/views/Logs.vue
Normal file
@@ -0,0 +1,63 @@
|
||||
<template>
|
||||
<div class="logs-page">
|
||||
<h1>日志查询</h1>
|
||||
<LogFilter />
|
||||
<el-table :data="logs" v-loading="loading" style="width: 100%">
|
||||
<el-table-column prop="timestamp" label="时间" width="180" :formatter="formatDate" />
|
||||
<el-table-column prop="group_id" label="分组ID" width="100" />
|
||||
<el-table-column prop="key_id" label="密钥ID" width="100" />
|
||||
<el-table-column prop="source_ip" label="源IP" width="150" />
|
||||
<el-table-column prop="status_code" label="状态码" width="100" />
|
||||
<el-table-column prop="request_path" label="请求路径" />
|
||||
<el-table-column prop="request_body_snippet" label="请求体片段" />
|
||||
</el-table>
|
||||
<el-pagination
|
||||
background
|
||||
layout="prev, pager, next, sizes"
|
||||
:total="pagination.total"
|
||||
:page-size="pagination.size"
|
||||
:current-page="pagination.page"
|
||||
@current-change="handlePageChange"
|
||||
@size-change="handleSizeChange"
|
||||
class="pagination-container"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { useLogStore } from '@/stores/logStore';
|
||||
import LogFilter from '@/components/LogFilter.vue';
|
||||
import type { RequestLog } from '@/types/models';
|
||||
|
||||
const logStore = useLogStore();
|
||||
const { logs, loading, pagination } = storeToRefs(logStore);
|
||||
|
||||
onMounted(() => {
|
||||
logStore.fetchLogs();
|
||||
});
|
||||
|
||||
const handlePageChange = (page: number) => {
|
||||
logStore.setPage(page);
|
||||
};
|
||||
|
||||
const handleSizeChange = (size: number) => {
|
||||
logStore.setSize(size);
|
||||
};
|
||||
|
||||
const formatDate = (_row: RequestLog, _column: any, cellValue: string) => {
|
||||
return new Date(cellValue).toLocaleString();
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.logs-page {
|
||||
padding: 20px;
|
||||
}
|
||||
.pagination-container {
|
||||
margin-top: 20px;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
</style>
|
44
web/src/views/Settings.vue
Normal file
44
web/src/views/Settings.vue
Normal file
@@ -0,0 +1,44 @@
|
||||
<template>
|
||||
<div v-loading="loading">
|
||||
<h1>Settings</h1>
|
||||
<el-form :model="form" label-width="200px">
|
||||
<el-form-item v-for="setting in settings" :key="setting.key" :label="setting.key">
|
||||
<el-input v-model="form[setting.key]"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="saveSettings">Save</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, watch } from 'vue';
|
||||
import { useSettingStore } from '@/stores/settingStore';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import type { Setting } from '@/types/models';
|
||||
|
||||
const settingStore = useSettingStore();
|
||||
const { settings, loading } = storeToRefs(settingStore);
|
||||
|
||||
const form = ref<Record<string, string>>({});
|
||||
|
||||
onMounted(() => {
|
||||
settingStore.fetchSettings();
|
||||
});
|
||||
|
||||
watch(settings, (newSettings) => {
|
||||
form.value = newSettings.reduce((acc, setting) => {
|
||||
acc[setting.key] = setting.value;
|
||||
return acc;
|
||||
}, {} as Record<string, string>);
|
||||
}, { immediate: true, deep: true });
|
||||
|
||||
const saveSettings = () => {
|
||||
const settingsToUpdate: Setting[] = Object.entries(form.value).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
settingStore.updateSettings(settingsToUpdate);
|
||||
};
|
||||
</script>
|
1
web/src/vite-env.d.ts
vendored
Normal file
1
web/src/vite-env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
19
web/tsconfig.app.json
Normal file
19
web/tsconfig.app.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"extends": "@vue/tsconfig/tsconfig.dom.json",
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["src/*"]
|
||||
},
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
|
||||
}
|
7
web/tsconfig.json
Normal file
7
web/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
25
web/tsconfig.node.json
Normal file
25
web/tsconfig.node.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
17
web/vite.config.ts
Normal file
17
web/vite.config.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import { fileURLToPath, URL } from 'url'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url))
|
||||
}
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist'
|
||||
},
|
||||
base: './'
|
||||
})
|
Reference in New Issue
Block a user