user_msg_queue_helper.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. package handler
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "sync"
  7. "time"
  8. "github.com/Wei-Shaw/sub2api/internal/service"
  9. "github.com/gin-gonic/gin"
  10. "go.uber.org/zap"
  11. )
  12. // UserMsgQueueHelper 用户消息串行队列 Handler 层辅助
  13. // 复用 ConcurrencyHelper 的退避 + SSE ping 模式
  14. type UserMsgQueueHelper struct {
  15. queueService *service.UserMessageQueueService
  16. pingFormat SSEPingFormat
  17. pingInterval time.Duration
  18. }
  19. // NewUserMsgQueueHelper 创建用户消息串行队列辅助
  20. func NewUserMsgQueueHelper(
  21. queueService *service.UserMessageQueueService,
  22. pingFormat SSEPingFormat,
  23. pingInterval time.Duration,
  24. ) *UserMsgQueueHelper {
  25. if pingInterval <= 0 {
  26. pingInterval = defaultPingInterval
  27. }
  28. return &UserMsgQueueHelper{
  29. queueService: queueService,
  30. pingFormat: pingFormat,
  31. pingInterval: pingInterval,
  32. }
  33. }
  34. // AcquireWithWait 等待获取串行锁,流式请求期间发送 SSE ping
  35. // 返回的 releaseFunc 内部使用 sync.Once,确保只执行一次释放
  36. func (h *UserMsgQueueHelper) AcquireWithWait(
  37. c *gin.Context,
  38. accountID int64,
  39. baseRPM int,
  40. isStream bool,
  41. streamStarted *bool,
  42. timeout time.Duration,
  43. reqLog *zap.Logger,
  44. ) (releaseFunc func(), err error) {
  45. ctx, cancel := context.WithTimeout(c.Request.Context(), timeout)
  46. defer cancel()
  47. // 先尝试立即获取
  48. result, err := h.queueService.TryAcquire(ctx, accountID)
  49. if err != nil {
  50. return nil, err // fail-open 已在 service 层处理
  51. }
  52. if result.Acquired {
  53. // 获取成功,执行 RPM 自适应延迟
  54. if err := h.queueService.EnforceDelay(ctx, accountID, baseRPM); err != nil {
  55. if ctx.Err() != nil {
  56. // 延迟期间 context 取消,释放锁
  57. bgCtx, bgCancel := context.WithTimeout(context.Background(), 5*time.Second)
  58. _ = h.queueService.Release(bgCtx, accountID, result.RequestID)
  59. bgCancel()
  60. return nil, ctx.Err()
  61. }
  62. }
  63. reqLog.Debug("gateway.umq_lock_acquired", zap.Int64("account_id", accountID))
  64. return h.makeReleaseFunc(accountID, result.RequestID, reqLog), nil
  65. }
  66. // 需要等待:指数退避轮询
  67. return h.waitForLockWithPing(c, ctx, accountID, baseRPM, isStream, streamStarted, reqLog)
  68. }
  69. // waitForLockWithPing 等待获取锁,流式请求期间发送 SSE ping
  70. func (h *UserMsgQueueHelper) waitForLockWithPing(
  71. c *gin.Context,
  72. ctx context.Context,
  73. accountID int64,
  74. baseRPM int,
  75. isStream bool,
  76. streamStarted *bool,
  77. reqLog *zap.Logger,
  78. ) (func(), error) {
  79. needPing := isStream && h.pingFormat != ""
  80. var flusher http.Flusher
  81. if needPing {
  82. var ok bool
  83. flusher, ok = c.Writer.(http.Flusher)
  84. if !ok {
  85. needPing = false
  86. }
  87. }
  88. var pingCh <-chan time.Time
  89. if needPing {
  90. pingTicker := time.NewTicker(h.pingInterval)
  91. defer pingTicker.Stop()
  92. pingCh = pingTicker.C
  93. }
  94. backoff := initialBackoff
  95. timer := time.NewTimer(backoff)
  96. defer timer.Stop()
  97. for {
  98. select {
  99. case <-ctx.Done():
  100. return nil, fmt.Errorf("umq wait timeout for account %d", accountID)
  101. case <-pingCh:
  102. if !*streamStarted {
  103. c.Header("Content-Type", "text/event-stream")
  104. c.Header("Cache-Control", "no-cache")
  105. c.Header("Connection", "keep-alive")
  106. c.Header("X-Accel-Buffering", "no")
  107. *streamStarted = true
  108. }
  109. written, err := fmt.Fprint(c.Writer, string(h.pingFormat))
  110. if err != nil {
  111. return nil, err
  112. }
  113. recordGatewayStreamHeartbeat(c, written)
  114. flusher.Flush()
  115. case <-timer.C:
  116. result, err := h.queueService.TryAcquire(ctx, accountID)
  117. if err != nil {
  118. return nil, err
  119. }
  120. if result.Acquired {
  121. // 获取成功,执行 RPM 自适应延迟
  122. if delayErr := h.queueService.EnforceDelay(ctx, accountID, baseRPM); delayErr != nil {
  123. if ctx.Err() != nil {
  124. bgCtx, bgCancel := context.WithTimeout(context.Background(), 5*time.Second)
  125. _ = h.queueService.Release(bgCtx, accountID, result.RequestID)
  126. bgCancel()
  127. return nil, ctx.Err()
  128. }
  129. }
  130. reqLog.Debug("gateway.umq_lock_acquired", zap.Int64("account_id", accountID))
  131. return h.makeReleaseFunc(accountID, result.RequestID, reqLog), nil
  132. }
  133. backoff = nextBackoff(backoff)
  134. timer.Reset(backoff)
  135. }
  136. }
  137. }
  138. // makeReleaseFunc 创建锁释放函数(使用 sync.Once 确保只执行一次)
  139. func (h *UserMsgQueueHelper) makeReleaseFunc(accountID int64, requestID string, reqLog *zap.Logger) func() {
  140. var once sync.Once
  141. return func() {
  142. once.Do(func() {
  143. bgCtx, bgCancel := context.WithTimeout(context.Background(), 5*time.Second)
  144. defer bgCancel()
  145. if err := h.queueService.Release(bgCtx, accountID, requestID); err != nil {
  146. reqLog.Warn("gateway.umq_release_failed",
  147. zap.Int64("account_id", accountID),
  148. zap.Error(err),
  149. )
  150. } else {
  151. reqLog.Debug("gateway.umq_lock_released", zap.Int64("account_id", accountID))
  152. }
  153. })
  154. }
  155. }
  156. // ThrottleWithPing 软性限速模式:施加 RPM 自适应延迟,流式期间发送 SSE ping
  157. // 不获取串行锁,不阻塞并发。返回后即可转发请求。
  158. func (h *UserMsgQueueHelper) ThrottleWithPing(
  159. c *gin.Context,
  160. accountID int64,
  161. baseRPM int,
  162. isStream bool,
  163. streamStarted *bool,
  164. timeout time.Duration,
  165. reqLog *zap.Logger,
  166. ) error {
  167. ctx, cancel := context.WithTimeout(c.Request.Context(), timeout)
  168. defer cancel()
  169. delay := h.queueService.CalculateRPMAwareDelay(ctx, accountID, baseRPM)
  170. if delay <= 0 {
  171. return nil
  172. }
  173. reqLog.Debug("gateway.umq_throttle_delay",
  174. zap.Int64("account_id", accountID),
  175. zap.Duration("delay", delay),
  176. )
  177. // 延迟期间发送 SSE ping(复用 waitForLockWithPing 的 ping 逻辑)
  178. needPing := isStream && h.pingFormat != ""
  179. var flusher http.Flusher
  180. if needPing {
  181. flusher, _ = c.Writer.(http.Flusher)
  182. if flusher == nil {
  183. needPing = false
  184. }
  185. }
  186. var pingCh <-chan time.Time
  187. if needPing {
  188. pingTicker := time.NewTicker(h.pingInterval)
  189. defer pingTicker.Stop()
  190. pingCh = pingTicker.C
  191. }
  192. timer := time.NewTimer(delay)
  193. defer timer.Stop()
  194. for {
  195. select {
  196. case <-ctx.Done():
  197. return ctx.Err()
  198. case <-pingCh:
  199. // SSE ping 逻辑(与 waitForLockWithPing 一致)
  200. if !*streamStarted {
  201. c.Header("Content-Type", "text/event-stream")
  202. c.Header("Cache-Control", "no-cache")
  203. c.Header("Connection", "keep-alive")
  204. c.Header("X-Accel-Buffering", "no")
  205. *streamStarted = true
  206. }
  207. written, err := fmt.Fprint(c.Writer, string(h.pingFormat))
  208. if err != nil {
  209. return err
  210. }
  211. recordGatewayStreamHeartbeat(c, written)
  212. flusher.Flush()
  213. case <-timer.C:
  214. return nil
  215. }
  216. }
  217. }