MCPcopy Create free account
hub / github.com/aiprodcoder/MIXAPI / startPingKeepAlive

Function startPingKeepAlive

relay/channel/api_request.go:107–173  ·  view source on GitHub ↗
(c *gin.Context, pingInterval time.Duration)

Source from the content-addressed store, hash-verified

105}
106
107func startPingKeepAlive(c *gin.Context, pingInterval time.Duration) context.CancelFunc {
108 pingerCtx, stopPinger := context.WithCancel(context.Background())
109
110 gopool.Go(func() {
111 defer func() {
112 // 增加panic恢复处理
113 if r := recover(); r != nil {
114 if common2.DebugEnabled {
115 println("SSE ping goroutine panic recovered:", fmt.Sprintf("%v", r))
116 }
117 }
118 if common2.DebugEnabled {
119 println("SSE ping goroutine stopped.")
120 }
121 }()
122
123 if pingInterval <= 0 {
124 pingInterval = helper.DefaultPingInterval
125 }
126
127 ticker := time.NewTicker(pingInterval)
128 // 确保在任何情况下都清理ticker
129 defer func() {
130 ticker.Stop()
131 if common2.DebugEnabled {
132 println("SSE ping ticker stopped")
133 }
134 }()
135
136 var pingMutex sync.Mutex
137 if common2.DebugEnabled {
138 println("SSE ping goroutine started")
139 }
140
141 // 增加超时控制,防止goroutine长时间运行
142 maxPingDuration := 120 * time.Minute // 最大ping持续时间
143 pingTimeout := time.NewTimer(maxPingDuration)
144 defer pingTimeout.Stop()
145
146 for {
147 select {
148 // 发送 ping 数据
149 case <-ticker.C:
150 if err := sendPingData(c, &pingMutex); err != nil {
151 if common2.DebugEnabled {
152 println("SSE ping error, stopping goroutine:", err.Error())
153 }
154 return
155 }
156 // 收到退出信号
157 case <-pingerCtx.Done():
158 return
159 // request 结束
160 case <-c.Request.Context().Done():
161 return
162 // 超时保护,防止goroutine无限运行
163 case <-pingTimeout.C:
164 if common2.DebugEnabled {

Callers 1

doRequestFunction · 0.85

Calls 2

sendPingDataFunction · 0.85
ErrorMethod · 0.80

Tested by

no test coverage detected