// openapi_handler.go Day 46:外部 HTTP API 提交入口(SMS_HTTP_1.6 协议)。 // 挂载于网关根组 /sms/api(独立于 /api/v1 JWT 域): // 全局 IP 桶(静态)→ MD5 验签(401)→ 账号桶(动态 speed_limit)→ 提交。 package v1 import ( "bytes" "encoding/json" "io" "net/http" "strconv" "strings" "github.com/gin-gonic/gin" "github.com/redis/go-redis/v9" "go-sms/internal/middleware" "go-sms/internal/service/openapi" ) // openapiAuthKey gin.Context 注入键(验签中间件→业务 handler)。 const openapiAuthKey = "openapi.auth" // openapiPhoneCountKey 验签中间件解析的 phoneList 数量(限流扣费数)。 const openapiPhoneCountKey = "openapi.phonecount" // openapiPhoneCount Day50:限流令牌扣费数=请求号码数(缺省 1)。 // 批量接口按号码/秒口径限速——每请求 1 令牌时 100 号/req 的限速形同虚设。 // 全局 IP 桶先于验签执行:现场读 body 计数并回填(账号桶经 context 复用,零二次解析)。 func openapiPhoneCount(c *gin.Context) int64 { if v, ok := c.Get(openapiPhoneCountKey); ok { if n, ok2 := v.(int64); ok2 && n > 0 { return n } } if c.Request != nil && c.Request.Body != nil { if raw, err := io.ReadAll(c.Request.Body); err == nil { c.Request.Body = io.NopCloser(bytes.NewReader(raw)) var b struct { PhoneList []string `json:"phoneList"` } if json.Unmarshal(raw, &b) == nil && len(b.PhoneList) > 0 { n := int64(len(b.PhoneList)) c.Set(openapiPhoneCountKey, n) return n } } } return 1 } // OpenAPIDeps 外部 API 装配依赖。 type OpenAPIDeps struct { Auth *openapi.Authenticator Svc *openapi.Service Redis redis.UniversalClient // nil=限流降级放行 Global middleware.RateLimitConfig // 全局 IP 桶(容量/速率来自配置 rate_limit) } // RegisterOpenAPI 挂载外部协议路由(engine 根组)。 func RegisterOpenAPI(r *gin.Engine, deps OpenAPIDeps) { if deps.Auth == nil || deps.Svc == nil { return } g := r.Group("/sms/api") // ① 全局 IP 桶(静态容量;Redis 缺失时 middleware 内部放行) if deps.Redis != nil && deps.Global.Capacity > 0 { cfg := deps.Global cfg.KeyFunc = middleware.ByClientIP cfg.KeyPrefix = "go-sms:ratelimit:openapi:global" cfg.CountOf = openapiPhoneCount g.Use(middleware.RateLimit(deps.Redis, cfg)) } // ② MD5 验签(注入 AuthContext;失败 401+协议体) g.Use(openapiAuth(deps.Auth)) // ③ 账号桶(动态容量=账号 speed_limit;验签后账号 ID 维度; // Day48:容量经 BackpressureShrink 包装——消费侧 lag≥L2 时收紧至 Σ通道speed; // Day50 压测修复:令牌桶稳态吞吐由 rate 决定,仅收容量对持续流量无效—— // RateOf 复用同一 shrink 实例(共享 1s 本地缓存),L2 时容量+速率同步收紧)。 if deps.Redis != nil { baseCap := func(c *gin.Context) int64 { if a, ok := c.Get(openapiAuthKey); ok { if ac, ok2 := a.(*openapi.AuthContext); ok2 && ac.Config != nil { return int64(ac.Config.SpeedLimit) } } return 0 // 0=用缺省兜底 } shrink := middleware.BackpressureShrink(deps.Redis, baseCap) g.Use(middleware.RateLimitDynamic(deps.Redis, middleware.RateLimitDynamicConfig{ KeyFunc: func(c *gin.Context) string { if a, ok := c.Get(openapiAuthKey); ok { if ac, ok2 := a.(*openapi.AuthContext); ok2 { return strconv.FormatInt(ac.AccountID, 10) } } return "anon" }, CapacityOf: shrink, RateOf: shrink, CountOf: openapiPhoneCount, })) } h := &openapiHandler{svc: deps.Svc} g.POST("/sendMessageMass", h.mass) g.POST("/sendMessageOne", h.one) } // openapiAuth 验签中间件:失败→401+协议体(code 1/2/3/4/16),成功注入上下文。 // 注意:绑定后须回填 body(后续业务 handler 需再次解析全量字段)。 func openapiAuth(a *openapi.Authenticator) gin.HandlerFunc { return func(c *gin.Context) { raw, err := io.ReadAll(c.Request.Body) if err != nil { c.JSON(http.StatusBadRequest, gin.H{ "code": openapi.CodeOther, "message": "请求体读取失败"}) c.Abort() return } c.Request.Body = io.NopCloser(bytes.NewReader(raw)) var body struct { UserName string `json:"userName"` Timestamp string `json:"timestamp"` Sign string `json:"sign"` PhoneList []string `json:"phoneList"` // Day50:限流扣费数(按号码数;解析失败不阻塞验签语义) } if err := json.Unmarshal(raw, &body); err != nil { c.JSON(http.StatusBadRequest, gin.H{ "code": openapi.CodeOther, "message": "请求体须为 JSON:" + err.Error()}) c.Abort() return } c.Set(openapiPhoneCountKey, int64(len(body.PhoneList))) if !strings.Contains(c.GetHeader("Content-Type"), "json") { c.JSON(http.StatusBadRequest, gin.H{ "code": openapi.CodeOther, "message": "Content-Type 须为 application/json"}) c.Abort() return } auth, code, msg := a.Authenticate(c.Request.Context(), body.UserName, body.Timestamp, body.Sign, c.ClientIP()) if code != openapi.CodeOK { c.JSON(http.StatusUnauthorized, gin.H{"code": code, "message": msg}) c.Abort() return } c.Set(openapiAuthKey, auth) c.Next() } } // openapiHandler 业务 handler(验签/限流已由中间件完成)。 type openapiHandler struct{ svc *openapi.Service } // authFromCtx 取验签上下文(中间件保证非空)。 func authFromCtx(c *gin.Context) *openapi.AuthContext { v, _ := c.Get(openapiAuthKey) a, _ := v.(*openapi.AuthContext) return a } // mass POST /sms/api/sendMessageMass。 func (h *openapiHandler) mass(c *gin.Context) { var req openapi.MassReq if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusOK, gin.H{"code": openapi.CodeOther, "message": "请求体解析失败:" + err.Error()}) return } c.JSON(http.StatusOK, h.svc.SendMass(c.Request.Context(), authFromCtx(c), &req, c.ClientIP())) } // one POST /sms/api/sendMessageOne。 func (h *openapiHandler) one(c *gin.Context) { var req openapi.OneReq if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusOK, gin.H{"code": openapi.CodeOther, "message": "请求体解析失败:" + err.Error()}) return } c.JSON(http.StatusOK, h.svc.SendOne(c.Request.Context(), authFromCtx(c), &req, c.ClientIP())) }