(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo, dataHandler func(data string) bool)
| 26 | ) |
| 27 | |
| 28 | func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo, dataHandler func(data string) bool) { |
| 29 | |
| 30 | if resp == nil || dataHandler == nil { |
| 31 | return |
| 32 | } |
| 33 | |
| 34 | // 确保响应体总是被关闭 |
| 35 | defer func() { |
| 36 | if resp.Body != nil { |
| 37 | resp.Body.Close() |
| 38 | } |
| 39 | }() |
| 40 | |
| 41 | streamingTimeout := time.Duration(constant.StreamingTimeout) * time.Second |
| 42 | if strings.HasPrefix(info.UpstreamModelName, "o") { |
| 43 | // twice timeout for thinking model |
| 44 | streamingTimeout *= 2 |
| 45 | } |
| 46 | |
| 47 | var ( |
| 48 | stopChan = make(chan bool, 3) // 增加缓冲区避免阻塞 |
| 49 | scanner = bufio.NewScanner(resp.Body) |
| 50 | ticker = time.NewTicker(streamingTimeout) |
| 51 | pingTicker *time.Ticker |
| 52 | writeMutex sync.Mutex // Mutex to protect concurrent writes |
| 53 | wg sync.WaitGroup // 用于等待所有 goroutine 退出 |
| 54 | ) |
| 55 | |
| 56 | generalSettings := operation_setting.GetGeneralSetting() |
| 57 | pingEnabled := generalSettings.PingIntervalEnabled |
| 58 | pingInterval := time.Duration(generalSettings.PingIntervalSeconds) * time.Second |
| 59 | if pingInterval <= 0 { |
| 60 | pingInterval = DefaultPingInterval |
| 61 | } |
| 62 | |
| 63 | if pingEnabled { |
| 64 | pingTicker = time.NewTicker(pingInterval) |
| 65 | } |
| 66 | |
| 67 | if common.DebugEnabled { |
| 68 | // print timeout and ping interval for debugging |
| 69 | println("relay timeout seconds:", common.RelayTimeout) |
| 70 | println("streaming timeout seconds:", int64(streamingTimeout.Seconds())) |
| 71 | println("ping interval seconds:", int64(pingInterval.Seconds())) |
| 72 | } |
| 73 | |
| 74 | // 改进资源清理,确保所有 goroutine 正确退出 |
| 75 | defer func() { |
| 76 | // 通知所有 goroutine 停止 |
| 77 | common.SafeSendBool(stopChan, true) |
| 78 | |
| 79 | ticker.Stop() |
| 80 | if pingTicker != nil { |
| 81 | pingTicker.Stop() |
| 82 | } |
| 83 | |
| 84 | // 等待所有 goroutine 退出,最多等待5秒 |
| 85 | done := make(chan struct{}) |
no test coverage detected