stream_scanner.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package helper
  2. import (
  3. "bufio"
  4. "context"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "one-api/common"
  9. "one-api/constant"
  10. relaycommon "one-api/relay/common"
  11. "one-api/setting/operation_setting"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/bytedance/gopkg/util/gopool"
  16. "github.com/gin-gonic/gin"
  17. )
  18. const (
  19. InitialScannerBufferSize = 64 << 10 // 64KB (64*1024)
  20. MaxScannerBufferSize = 10 << 20 // 10MB (10*1024*1024)
  21. DefaultPingInterval = 10 * time.Second
  22. )
  23. func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo, dataHandler func(data string) bool) {
  24. if resp == nil || dataHandler == nil {
  25. return
  26. }
  27. // 确保响应体总是被关闭
  28. defer func() {
  29. if resp.Body != nil {
  30. resp.Body.Close()
  31. }
  32. }()
  33. streamingTimeout := time.Duration(constant.StreamingTimeout) * time.Second
  34. var (
  35. stopChan = make(chan bool, 3) // 增加缓冲区避免阻塞
  36. scanner = bufio.NewScanner(resp.Body)
  37. ticker = time.NewTicker(streamingTimeout)
  38. pingTicker *time.Ticker
  39. writeMutex sync.Mutex // Mutex to protect concurrent writes
  40. wg sync.WaitGroup // 用于等待所有 goroutine 退出
  41. )
  42. generalSettings := operation_setting.GetGeneralSetting()
  43. pingEnabled := generalSettings.PingIntervalEnabled && !info.DisablePing
  44. pingInterval := time.Duration(generalSettings.PingIntervalSeconds) * time.Second
  45. if pingInterval <= 0 {
  46. pingInterval = DefaultPingInterval
  47. }
  48. if pingEnabled {
  49. pingTicker = time.NewTicker(pingInterval)
  50. }
  51. if common.DebugEnabled {
  52. // print timeout and ping interval for debugging
  53. println("relay timeout seconds:", common.RelayTimeout)
  54. println("streaming timeout seconds:", int64(streamingTimeout.Seconds()))
  55. println("ping interval seconds:", int64(pingInterval.Seconds()))
  56. }
  57. // 改进资源清理,确保所有 goroutine 正确退出
  58. defer func() {
  59. // 通知所有 goroutine 停止
  60. common.SafeSendBool(stopChan, true)
  61. ticker.Stop()
  62. if pingTicker != nil {
  63. pingTicker.Stop()
  64. }
  65. // 等待所有 goroutine 退出,最多等待5秒
  66. done := make(chan struct{})
  67. go func() {
  68. wg.Wait()
  69. close(done)
  70. }()
  71. select {
  72. case <-done:
  73. case <-time.After(5 * time.Second):
  74. common.LogError(c, "timeout waiting for goroutines to exit")
  75. }
  76. close(stopChan)
  77. }()
  78. scanner.Buffer(make([]byte, InitialScannerBufferSize), MaxScannerBufferSize)
  79. scanner.Split(bufio.ScanLines)
  80. SetEventStreamHeaders(c)
  81. ctx, cancel := context.WithCancel(context.Background())
  82. defer cancel()
  83. ctx = context.WithValue(ctx, "stop_chan", stopChan)
  84. // Handle ping data sending with improved error handling
  85. if pingEnabled && pingTicker != nil {
  86. wg.Add(1)
  87. gopool.Go(func() {
  88. defer func() {
  89. wg.Done()
  90. if r := recover(); r != nil {
  91. common.LogError(c, fmt.Sprintf("ping goroutine panic: %v", r))
  92. common.SafeSendBool(stopChan, true)
  93. }
  94. if common.DebugEnabled {
  95. println("ping goroutine exited")
  96. }
  97. }()
  98. // 添加超时保护,防止 goroutine 无限运行
  99. maxPingDuration := 30 * time.Minute // 最大 ping 持续时间
  100. pingTimeout := time.NewTimer(maxPingDuration)
  101. defer pingTimeout.Stop()
  102. for {
  103. select {
  104. case <-pingTicker.C:
  105. // 使用超时机制防止写操作阻塞
  106. done := make(chan error, 1)
  107. go func() {
  108. writeMutex.Lock()
  109. defer writeMutex.Unlock()
  110. done <- PingData(c)
  111. }()
  112. select {
  113. case err := <-done:
  114. if err != nil {
  115. common.LogError(c, "ping data error: "+err.Error())
  116. return
  117. }
  118. if common.DebugEnabled {
  119. println("ping data sent")
  120. }
  121. case <-time.After(10 * time.Second):
  122. common.LogError(c, "ping data send timeout")
  123. return
  124. case <-ctx.Done():
  125. return
  126. case <-stopChan:
  127. return
  128. }
  129. case <-ctx.Done():
  130. return
  131. case <-stopChan:
  132. return
  133. case <-c.Request.Context().Done():
  134. // 监听客户端断开连接
  135. return
  136. case <-pingTimeout.C:
  137. common.LogError(c, "ping goroutine max duration reached")
  138. return
  139. }
  140. }
  141. })
  142. }
  143. // Scanner goroutine with improved error handling
  144. wg.Add(1)
  145. common.RelayCtxGo(ctx, func() {
  146. defer func() {
  147. wg.Done()
  148. if r := recover(); r != nil {
  149. common.LogError(c, fmt.Sprintf("scanner goroutine panic: %v", r))
  150. }
  151. common.SafeSendBool(stopChan, true)
  152. if common.DebugEnabled {
  153. println("scanner goroutine exited")
  154. }
  155. }()
  156. for scanner.Scan() {
  157. // 检查是否需要停止
  158. select {
  159. case <-stopChan:
  160. return
  161. case <-ctx.Done():
  162. return
  163. case <-c.Request.Context().Done():
  164. return
  165. default:
  166. }
  167. ticker.Reset(streamingTimeout)
  168. data := scanner.Text()
  169. if common.DebugEnabled {
  170. println(data)
  171. }
  172. if len(data) < 6 {
  173. continue
  174. }
  175. if data[:5] != "data:" && data[:6] != "[DONE]" {
  176. continue
  177. }
  178. data = data[5:]
  179. data = strings.TrimLeft(data, " ")
  180. data = strings.TrimSuffix(data, "\r")
  181. if !strings.HasPrefix(data, "[DONE]") {
  182. info.SetFirstResponseTime()
  183. // 使用超时机制防止写操作阻塞
  184. done := make(chan bool, 1)
  185. go func() {
  186. writeMutex.Lock()
  187. defer writeMutex.Unlock()
  188. done <- dataHandler(data)
  189. }()
  190. select {
  191. case success := <-done:
  192. if !success {
  193. return
  194. }
  195. case <-time.After(10 * time.Second):
  196. common.LogError(c, "data handler timeout")
  197. return
  198. case <-ctx.Done():
  199. return
  200. case <-stopChan:
  201. return
  202. }
  203. } else {
  204. // done, 处理完成标志,直接退出停止读取剩余数据防止出错
  205. if common.DebugEnabled {
  206. println("received [DONE], stopping scanner")
  207. }
  208. return
  209. }
  210. }
  211. if err := scanner.Err(); err != nil {
  212. if err != io.EOF {
  213. common.LogError(c, "scanner error: "+err.Error())
  214. }
  215. }
  216. })
  217. // 主循环等待完成或超时
  218. select {
  219. case <-ticker.C:
  220. // 超时处理逻辑
  221. common.LogError(c, "streaming timeout")
  222. case <-stopChan:
  223. // 正常结束
  224. common.LogInfo(c, "streaming finished")
  225. case <-c.Request.Context().Done():
  226. // 客户端断开连接
  227. common.LogInfo(c, "client disconnected")
  228. }
  229. }