按性能分析逐项落地,实测对比(16 并发、mock 上游零延迟、SQLite): - 每请求 SQL 10 → 2:模型/渠道目录(模型行、绑定、渠道行)进程内缓存 10s, 运行期状态(冷却、健康)仍每次实时判定;管理端写操作经中间件、 健康状态变化经回调立即失效。新增 TestProxyRequestSQLBudget 钉住预算。 - 端到端 p50 1.3–1.6ms → 0.66–0.70ms,RPS 3.5–8.9k → 16–18k。 - 流式正文累积:字符串 += 改 strings.Builder(原为 O(n²)), 逐行 JSON 提取改字节快路径,并加廉价的子串预过滤、拿到输出 usage 后停累积。 500 块:949µs/7.9MB 分配 → 83µs/136KB。 - 请求体定点改写:模型映射从整包 unmarshal/marshal 改为顶层字段替换 (100KB:585µs → 29µs),stream_options 注入同理;requestText 改为 只在「上游没报用量」时按需提取,亲和键改用原始体前缀。 - 渠道满载背压:新增 Acquire 有界排队(OT_PROXY_CHANNEL_ACQUIRE_WAIT, 默认 150ms);排队仍满时返回 503 + Retry-After 而不是 502。 实测渠道上限 4、16 并发:无排队 81 次 503;排队 150ms 后 400/400 成功。 - 记账按批聚合:同批同用户一次扣款、流水批量插入、日表按 (user,model,日期) 聚合,替代每行 5 条语句;幂等仍靠 ref_id 唯一索引兜底。 - gorm 开启 PrepareStmt(SQL 解析此前占 CPU 15%);tiktoken 编码器按模型复用。 - 管理端用量列表不再返回原始请求/响应体(可能几十 MB), 改为 has_raw 标记 + GET /admin/usage/:id 按需拉取,前端弹窗打开时取。 验证:go vet、go test ./...、go test -race(proxy/channel/usage/tokenizer)、 vue-tsc、eslint、vite build 全绿;本地起 mock 上游实测列表/详情接口与 管理页弹窗按需加载。
273 lines
8.3 KiB
Go
273 lines
8.3 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/mail"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/openteam/server/internal/pkg/resp"
|
|
"github.com/openteam/server/internal/store"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
)
|
|
|
|
// AdminUsers GET /api/v1/admin/users — 用户列表(搜索、分页)。
|
|
func (h *Handler) AdminUsers(c *gin.Context) {
|
|
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
|
size, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
|
if page < 1 {
|
|
page = 1
|
|
}
|
|
if size < 1 || size > 100 {
|
|
size = 20
|
|
}
|
|
q := h.a.DB.Model(&store.User{})
|
|
if kw := c.Query("q"); kw != "" {
|
|
q = q.Where("username LIKE ? OR email LIKE ?", "%"+kw+"%", "%"+kw+"%")
|
|
}
|
|
var total int64
|
|
q.Count(&total)
|
|
var users []store.User
|
|
q.Order("id DESC").Offset((page - 1) * size).Limit(size).Find(&users)
|
|
out := make([]gin.H, 0, len(users))
|
|
for _, u := range users {
|
|
out = append(out, h.publicUser(&u))
|
|
}
|
|
resp.OK(c, gin.H{"items": out, "total": total, "page": page, "page_size": size})
|
|
}
|
|
|
|
// AdminPatchUser PATCH /api/v1/admin/users/:id — 角色/状态。
|
|
func (h *Handler) AdminPatchUser(c *gin.Context) {
|
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
if err != nil {
|
|
resp.Fail(c, http.StatusBadRequest, "invalid user id")
|
|
return
|
|
}
|
|
var req struct {
|
|
Username *string `json:"username"`
|
|
Email *string `json:"email"`
|
|
Password *string `json:"password"`
|
|
Role *string `json:"role"`
|
|
Status *string `json:"status"`
|
|
AllowedModels *[]string `json:"allowed_models"`
|
|
DeniedModels *[]string `json:"denied_models"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
resp.Fail(c, http.StatusBadRequest, "invalid input")
|
|
return
|
|
}
|
|
updates := map[string]any{}
|
|
if req.Username != nil {
|
|
u := strings.TrimSpace(*req.Username)
|
|
if len(u) < 3 || len(u) > 32 {
|
|
resp.Fail(c, http.StatusBadRequest, "username must be 3-32 chars")
|
|
return
|
|
}
|
|
var n int64
|
|
h.a.DB.Model(&store.User{}).Where("username = ? AND id != ?", u, id).Count(&n)
|
|
if n > 0 {
|
|
resp.Fail(c, http.StatusConflict, "username already taken")
|
|
return
|
|
}
|
|
updates["username"] = u
|
|
}
|
|
if req.Email != nil {
|
|
e := strings.ToLower(strings.TrimSpace(*req.Email))
|
|
if _, err := mail.ParseAddress(e); err != nil {
|
|
resp.Fail(c, http.StatusBadRequest, "invalid email")
|
|
return
|
|
}
|
|
var n int64
|
|
h.a.DB.Model(&store.User{}).Where("email = ? AND id != ?", e, id).Count(&n)
|
|
if n > 0 {
|
|
resp.Fail(c, http.StatusConflict, "email already taken")
|
|
return
|
|
}
|
|
updates["email"] = e
|
|
}
|
|
if req.Password != nil && *req.Password != "" {
|
|
if len(*req.Password) < 8 {
|
|
resp.Fail(c, http.StatusBadRequest, "password must be at least 8 chars")
|
|
return
|
|
}
|
|
hash, err := h.a.Hasher.HashPassword(*req.Password)
|
|
if err != nil {
|
|
resp.Fail(c, http.StatusInternalServerError, "failed to hash password")
|
|
return
|
|
}
|
|
updates["password_hash"] = hash
|
|
}
|
|
if req.Role != nil {
|
|
if *req.Role != store.RoleUser && *req.Role != store.RoleAdmin {
|
|
resp.Fail(c, http.StatusBadRequest, "role must be user or admin")
|
|
return
|
|
}
|
|
updates["role"] = *req.Role
|
|
}
|
|
if req.Status != nil {
|
|
if *req.Status != store.UserStatusActive && *req.Status != store.UserStatusDisabled {
|
|
resp.Fail(c, http.StatusBadRequest, "status must be active or disabled")
|
|
return
|
|
}
|
|
updates["status"] = *req.Status
|
|
}
|
|
// 最后一个启用的管理员不可被降级/禁用:否则管理面被锁死,
|
|
// 且 reset-admin-password CLI 只在 admin 角色里找目标,救不回来。
|
|
if req.Role != nil || req.Status != nil {
|
|
var target store.User
|
|
if err := h.a.DB.First(&target, id).Error; err != nil {
|
|
resp.Fail(c, http.StatusNotFound, "user not found")
|
|
return
|
|
}
|
|
if target.Role == store.RoleAdmin && target.Status == store.UserStatusActive {
|
|
newRole, newStatus := target.Role, target.Status
|
|
if req.Role != nil {
|
|
newRole = *req.Role
|
|
}
|
|
if req.Status != nil {
|
|
newStatus = *req.Status
|
|
}
|
|
if newRole != store.RoleAdmin || newStatus != store.UserStatusActive {
|
|
var admins int64
|
|
h.a.DB.Model(&store.User{}).
|
|
Where("role = ? AND status = ? AND id != ?", store.RoleAdmin, store.UserStatusActive, id).
|
|
Count(&admins)
|
|
if admins == 0 {
|
|
resp.Fail(c, http.StatusBadRequest, "cannot demote or disable the last active admin")
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// 模型限制(jsonb):手动序列化
|
|
if req.AllowedModels != nil {
|
|
raw, _ := json.Marshal(*req.AllowedModels)
|
|
updates["allowed_models"] = string(raw)
|
|
}
|
|
if req.DeniedModels != nil {
|
|
raw, _ := json.Marshal(*req.DeniedModels)
|
|
updates["denied_models"] = string(raw)
|
|
}
|
|
if len(updates) == 0 {
|
|
resp.OK(c, gin.H{"ok": true})
|
|
return
|
|
}
|
|
res := h.a.DB.Model(&store.User{}).Where("id = ?", id).Updates(updates)
|
|
if res.Error != nil {
|
|
resp.Fail(c, http.StatusInternalServerError, "failed to update user")
|
|
return
|
|
}
|
|
if res.RowsAffected == 0 {
|
|
resp.Fail(c, http.StatusNotFound, "user not found")
|
|
return
|
|
}
|
|
resp.OK(c, gin.H{"ok": true})
|
|
}
|
|
|
|
// AdminAdjustBalance POST /api/v1/admin/users/:id/balance — 手动调余额(写流水)。
|
|
func (h *Handler) AdminAdjustBalance(c *gin.Context) {
|
|
admin := sessionUser(c)
|
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
if err != nil {
|
|
resp.Fail(c, http.StatusBadRequest, "invalid user id")
|
|
return
|
|
}
|
|
var req struct {
|
|
Amount float64 `json:"amount" binding:"required"`
|
|
Remark string `json:"remark"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
resp.Fail(c, http.StatusBadRequest, "invalid input: amount required")
|
|
return
|
|
}
|
|
if req.Amount == 0 {
|
|
resp.Fail(c, http.StatusBadRequest, "amount must not be zero")
|
|
return
|
|
}
|
|
|
|
err = h.a.DB.Transaction(func(tx *gorm.DB) error {
|
|
var u store.User
|
|
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&u, id).Error; err != nil {
|
|
return err
|
|
}
|
|
// SQL 侧原子加减:SQLite 驱动不支持行锁,Go 侧读-改-写会与记账扣费互相覆盖
|
|
if err := tx.Model(&store.User{}).Where("id = ?", id).Update("balance", gorm.Expr("balance + ?", req.Amount)).Error; err != nil {
|
|
return err
|
|
}
|
|
// ref_id 有单列唯一索引,秒级时间戳同一秒第二次调整必撞;纳秒粒度避免
|
|
ref := "admin:" + strconv.FormatUint(u.ID, 10) + ":" + strconv.FormatInt(time.Now().UnixNano(), 10)
|
|
_ = admin.ID // 流水里不冗余管理员 ID;需要时再加
|
|
return tx.Create(&store.BalanceLog{
|
|
UserID: u.ID,
|
|
Change: req.Amount,
|
|
BalanceAfter: u.Balance + req.Amount,
|
|
Type: store.BalanceTypeAdminAdjust,
|
|
RefID: ref,
|
|
Remark: req.Remark,
|
|
}).Error
|
|
})
|
|
if err != nil {
|
|
resp.Fail(c, http.StatusNotFound, "user not found or failed to adjust")
|
|
return
|
|
}
|
|
resp.OK(c, gin.H{"ok": true})
|
|
}
|
|
|
|
// AdminConfig GET /api/v1/admin/config — 全部系统配置。
|
|
func (h *Handler) AdminConfig(c *gin.Context) {
|
|
var cfgs []store.SystemConfig
|
|
if err := h.a.DB.Find(&cfgs).Error; err != nil {
|
|
resp.Fail(c, http.StatusInternalServerError, "failed to load config")
|
|
return
|
|
}
|
|
out := gin.H{}
|
|
for _, cfg := range cfgs {
|
|
out[cfg.Key] = json.RawMessage(cfg.Value)
|
|
}
|
|
resp.OK(c, gin.H{"config": out})
|
|
}
|
|
|
|
// AdminPutConfig PUT /api/v1/admin/config — 整表覆盖(upsert)。
|
|
func (h *Handler) AdminPutConfig(c *gin.Context) {
|
|
var req map[string]json.RawMessage
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
resp.Fail(c, http.StatusBadRequest, "invalid input")
|
|
return
|
|
}
|
|
err := h.a.DB.Transaction(func(tx *gorm.DB) error {
|
|
for k, v := range req {
|
|
cfg := store.SystemConfig{Key: k, Value: string(v)}
|
|
if err := tx.Save(&cfg).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
resp.Fail(c, http.StatusInternalServerError, "failed to save config")
|
|
return
|
|
}
|
|
// 模型限制等策略可能变化,立即失效缓存
|
|
if h.gw != nil {
|
|
h.gw.ResetModelPolicy()
|
|
}
|
|
resp.OK(c, gin.H{"ok": true})
|
|
}
|
|
|
|
// InvalidateCatalogOnWrite 管理端写操作成功后清空网关的模型/渠道目录缓存。
|
|
// 缓存 TTL 只有 10s,但「改完渠道立刻生效」是管理员的合理预期;
|
|
// 用中间件统一处理,避免每个写 handler 都要记得调一次。
|
|
func (h *Handler) InvalidateCatalogOnWrite(c *gin.Context) {
|
|
c.Next()
|
|
switch c.Request.Method {
|
|
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
|
|
if h.gw != nil && c.Writer.Status() < 400 {
|
|
h.gw.InvalidateCatalog()
|
|
}
|
|
}
|
|
}
|