api_request.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. package channel
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. common2 "one-api/common"
  9. "one-api/relay/common"
  10. "one-api/relay/constant"
  11. "one-api/relay/helper"
  12. "one-api/service"
  13. "one-api/setting/operation_setting"
  14. "sync"
  15. "time"
  16. "github.com/bytedance/gopkg/util/gopool"
  17. "github.com/gin-gonic/gin"
  18. "github.com/gorilla/websocket"
  19. )
  20. func SetupApiRequestHeader(info *common.RelayInfo, c *gin.Context, req *http.Header) {
  21. if info.RelayMode == constant.RelayModeAudioTranscription || info.RelayMode == constant.RelayModeAudioTranslation {
  22. // multipart/form-data
  23. } else if info.RelayMode == constant.RelayModeRealtime {
  24. // websocket
  25. } else {
  26. req.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  27. req.Set("Accept", c.Request.Header.Get("Accept"))
  28. if info.IsStream && c.Request.Header.Get("Accept") == "" {
  29. req.Set("Accept", "text/event-stream")
  30. }
  31. }
  32. }
  33. func DoApiRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  34. fullRequestURL, err := a.GetRequestURL(info)
  35. if err != nil {
  36. return nil, fmt.Errorf("get request url failed: %w", err)
  37. }
  38. if common2.DebugEnabled {
  39. println("fullRequestURL:", fullRequestURL)
  40. }
  41. req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
  42. if err != nil {
  43. return nil, fmt.Errorf("new request failed: %w", err)
  44. }
  45. err = a.SetupRequestHeader(c, &req.Header, info)
  46. if err != nil {
  47. return nil, fmt.Errorf("setup request header failed: %w", err)
  48. }
  49. resp, err := doRequest(c, req, info)
  50. if err != nil {
  51. return nil, fmt.Errorf("do request failed: %w", err)
  52. }
  53. return resp, nil
  54. }
  55. func DoFormRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  56. fullRequestURL, err := a.GetRequestURL(info)
  57. if err != nil {
  58. return nil, fmt.Errorf("get request url failed: %w", err)
  59. }
  60. if common2.DebugEnabled {
  61. println("fullRequestURL:", fullRequestURL)
  62. }
  63. req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
  64. if err != nil {
  65. return nil, fmt.Errorf("new request failed: %w", err)
  66. }
  67. // set form data
  68. req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  69. err = a.SetupRequestHeader(c, &req.Header, info)
  70. if err != nil {
  71. return nil, fmt.Errorf("setup request header failed: %w", err)
  72. }
  73. resp, err := doRequest(c, req, info)
  74. if err != nil {
  75. return nil, fmt.Errorf("do request failed: %w", err)
  76. }
  77. return resp, nil
  78. }
  79. func DoWssRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*websocket.Conn, error) {
  80. fullRequestURL, err := a.GetRequestURL(info)
  81. if err != nil {
  82. return nil, fmt.Errorf("get request url failed: %w", err)
  83. }
  84. targetHeader := http.Header{}
  85. err = a.SetupRequestHeader(c, &targetHeader, info)
  86. if err != nil {
  87. return nil, fmt.Errorf("setup request header failed: %w", err)
  88. }
  89. targetHeader.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  90. targetConn, _, err := websocket.DefaultDialer.Dial(fullRequestURL, targetHeader)
  91. if err != nil {
  92. return nil, fmt.Errorf("dial failed to %s: %w", fullRequestURL, err)
  93. }
  94. // send request body
  95. //all, err := io.ReadAll(requestBody)
  96. //err = service.WssString(c, targetConn, string(all))
  97. return targetConn, nil
  98. }
  99. func startPingKeepAlive(c *gin.Context, pingInterval time.Duration) context.CancelFunc {
  100. pingerCtx, stopPinger := context.WithCancel(context.Background())
  101. gopool.Go(func() {
  102. defer func() {
  103. // 增加panic恢复处理
  104. if r := recover(); r != nil {
  105. if common2.DebugEnabled {
  106. println("SSE ping goroutine panic recovered:", fmt.Sprintf("%v", r))
  107. }
  108. }
  109. if common2.DebugEnabled {
  110. println("SSE ping goroutine stopped.")
  111. }
  112. }()
  113. if pingInterval <= 0 {
  114. pingInterval = helper.DefaultPingInterval
  115. }
  116. ticker := time.NewTicker(pingInterval)
  117. // 确保在任何情况下都清理ticker
  118. defer func() {
  119. ticker.Stop()
  120. if common2.DebugEnabled {
  121. println("SSE ping ticker stopped")
  122. }
  123. }()
  124. var pingMutex sync.Mutex
  125. if common2.DebugEnabled {
  126. println("SSE ping goroutine started")
  127. }
  128. // 增加超时控制,防止goroutine长时间运行
  129. maxPingDuration := 120 * time.Minute // 最大ping持续时间
  130. pingTimeout := time.NewTimer(maxPingDuration)
  131. defer pingTimeout.Stop()
  132. for {
  133. select {
  134. // 发送 ping 数据
  135. case <-ticker.C:
  136. if err := sendPingData(c, &pingMutex); err != nil {
  137. if common2.DebugEnabled {
  138. println("SSE ping error, stopping goroutine:", err.Error())
  139. }
  140. return
  141. }
  142. // 收到退出信号
  143. case <-pingerCtx.Done():
  144. return
  145. // request 结束
  146. case <-c.Request.Context().Done():
  147. return
  148. // 超时保护,防止goroutine无限运行
  149. case <-pingTimeout.C:
  150. if common2.DebugEnabled {
  151. println("SSE ping goroutine timeout, stopping")
  152. }
  153. return
  154. }
  155. }
  156. })
  157. return stopPinger
  158. }
  159. func sendPingData(c *gin.Context, mutex *sync.Mutex) error {
  160. // 增加超时控制,防止锁死等待
  161. done := make(chan error, 1)
  162. go func() {
  163. mutex.Lock()
  164. defer mutex.Unlock()
  165. err := helper.PingData(c)
  166. if err != nil {
  167. common2.LogError(c, "SSE ping error: "+err.Error())
  168. done <- err
  169. return
  170. }
  171. if common2.DebugEnabled {
  172. println("SSE ping data sent.")
  173. }
  174. done <- nil
  175. }()
  176. // 设置发送ping数据的超时时间
  177. select {
  178. case err := <-done:
  179. return err
  180. case <-time.After(10 * time.Second):
  181. return errors.New("SSE ping data send timeout")
  182. case <-c.Request.Context().Done():
  183. return errors.New("request context cancelled during ping")
  184. }
  185. }
  186. func DoRequest(c *gin.Context, req *http.Request, info *common.RelayInfo) (*http.Response, error) {
  187. return doRequest(c, req, info)
  188. }
  189. func doRequest(c *gin.Context, req *http.Request, info *common.RelayInfo) (*http.Response, error) {
  190. var client *http.Client
  191. var err error
  192. if info.ChannelSetting.Proxy != "" {
  193. client, err = service.NewProxyHttpClient(info.ChannelSetting.Proxy)
  194. if err != nil {
  195. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  196. }
  197. } else {
  198. client = service.GetHttpClient()
  199. }
  200. var stopPinger context.CancelFunc
  201. if info.IsStream {
  202. helper.SetEventStreamHeaders(c)
  203. // 处理流式请求的 ping 保活
  204. generalSettings := operation_setting.GetGeneralSetting()
  205. if generalSettings.PingIntervalEnabled {
  206. pingInterval := time.Duration(generalSettings.PingIntervalSeconds) * time.Second
  207. stopPinger = startPingKeepAlive(c, pingInterval)
  208. // 使用defer确保在任何情况下都能停止ping goroutine
  209. defer func() {
  210. if stopPinger != nil {
  211. stopPinger()
  212. if common2.DebugEnabled {
  213. println("SSE ping goroutine stopped by defer")
  214. }
  215. }
  216. }()
  217. }
  218. }
  219. resp, err := client.Do(req)
  220. if err != nil {
  221. return nil, err
  222. }
  223. if resp == nil {
  224. return nil, errors.New("resp is nil")
  225. }
  226. _ = req.Body.Close()
  227. _ = c.Request.Body.Close()
  228. return resp, nil
  229. }
  230. func DoTaskApiRequest(a TaskAdaptor, c *gin.Context, info *common.TaskRelayInfo, requestBody io.Reader) (*http.Response, error) {
  231. fullRequestURL, err := a.BuildRequestURL(info)
  232. if err != nil {
  233. return nil, err
  234. }
  235. req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
  236. if err != nil {
  237. return nil, fmt.Errorf("new request failed: %w", err)
  238. }
  239. req.GetBody = func() (io.ReadCloser, error) {
  240. return io.NopCloser(requestBody), nil
  241. }
  242. err = a.BuildRequestHeader(c, req, info)
  243. if err != nil {
  244. return nil, fmt.Errorf("setup request header failed: %w", err)
  245. }
  246. resp, err := doRequest(c, req, info.RelayInfo)
  247. if err != nil {
  248. return nil, fmt.Errorf("do request failed: %w", err)
  249. }
  250. return resp, nil
  251. }