@@ -66,17 +66,21 @@ func API_ask(c *gin.Context) {
66
66
})
67
67
return
68
68
}
69
+ connectionPool .Mu .RUnlock ()
69
70
if request .ConversationId == "" {
70
71
// Retry 3 times before giving up
72
+ var succeeded bool = false
71
73
for i := 0 ; i < 3 ; i ++ {
72
74
// Find connection with the lowest load and where heartbeat is after last message time
75
+ connectionPool .Mu .RLock ()
73
76
for _ , conn := range connectionPool .Connections {
74
77
if connection == nil || conn .LastMessageTime .Before (connection .LastMessageTime ) {
75
78
if conn .Heartbeat .After (conn .LastMessageTime ) {
76
79
connection = conn
77
80
}
78
81
}
79
82
}
83
+ connectionPool .Mu .RUnlock ()
80
84
// Check if connection was found
81
85
if connection == nil {
82
86
c .JSON (503 , gin.H {
@@ -87,11 +91,21 @@ func API_ask(c *gin.Context) {
87
91
// Ping before sending request
88
92
if ! ping (connection .Id ) {
89
93
// Ping failed. Try again
94
+ println ("Ping failed" )
90
95
continue
96
+ } else {
97
+ println ("Ping succeeded" )
91
98
}
92
99
// Ping succeeded. Break the loop
100
+ succeeded = true
93
101
break
94
102
}
103
+ if ! succeeded {
104
+ c .JSON (503 , gin.H {
105
+ "error" : "Ping failed" ,
106
+ })
107
+ return
108
+ }
95
109
} else {
96
110
// Check if conversation exists
97
111
conversation , ok := conversationPool .Get (request .ConversationId )
@@ -122,7 +136,6 @@ func API_ask(c *gin.Context) {
122
136
return
123
137
}
124
138
}
125
- connectionPool .Mu .RUnlock ()
126
139
message := types.Message {
127
140
Id : utils .GenerateId (),
128
141
Message : "ChatGptRequest" ,
@@ -205,6 +218,7 @@ func API_getConnections(c *gin.Context) {
205
218
}
206
219
207
220
func ping (connection_id string ) bool {
221
+ println ("Starting ping" )
208
222
// Get connection
209
223
connection , ok := connectionPool .Get (connection_id )
210
224
// Send "ping" to the connection
@@ -214,7 +228,9 @@ func ping(connection_id string) bool {
214
228
Id : id ,
215
229
Message : "ping" ,
216
230
}
231
+ connection .Ws .SetReadDeadline (time .Now ().Add (5 * time .Second ))
217
232
err := connection .Ws .WriteJSON (send )
233
+ println ("Sent ping" )
218
234
if err != nil {
219
235
// Delete connection
220
236
connectionPool .Delete (connection_id )
@@ -224,9 +240,10 @@ func ping(connection_id string) bool {
224
240
for {
225
241
// Read message
226
242
var receive types.Message
227
- connection .Ws .SetReadDeadline (time .Now ().Add (5 * time .Second ))
228
243
err = connection .Ws .ReadJSON (& receive )
244
+ println ("Received ping response" )
229
245
if err != nil {
246
+ println ("There was an error" )
230
247
// Delete connection
231
248
connectionPool .Delete (connection_id )
232
249
return false
0 commit comments