fix: harden websocket heartbeat under load
This commit is contained in:
@@ -84,3 +84,58 @@ func TestWSClientReadLoopClosesConnectionAfterDecodeError(t *testing.T) {
|
||||
t.Fatal("read loop exited without closing the underlying connection")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWSClientDataCallbackDoesNotBlockPong(t *testing.T) {
|
||||
pong := make(chan struct{}, 1)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := (&websocket.Upgrader{}).Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetPongHandler(func(string) error {
|
||||
select {
|
||||
case pong <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err = conn.WriteJSON(map[string]any{"data": map[string]any{
|
||||
"topic": "grp-test", "seq": 1, "head": map[string]any{}, "content": map[string]any{},
|
||||
}}); err != nil {
|
||||
return
|
||||
}
|
||||
if err = conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(time.Second)); err != nil {
|
||||
return
|
||||
}
|
||||
conn.SetReadDeadline(time.Now().Add(time.Second))
|
||||
for {
|
||||
if _, _, readErr := conn.ReadMessage(); readErr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
conn, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http"), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
blocked := make(chan struct{})
|
||||
client := &WSClient{
|
||||
conn: conn, waits: make(map[string]chan ctrlPacket), done: make(chan struct{}),
|
||||
onData: func(AccountRecord, dataPacket) { <-blocked },
|
||||
}
|
||||
client.startDataProcessor()
|
||||
go client.readLoop()
|
||||
defer func() {
|
||||
close(blocked)
|
||||
client.Close()
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-pong:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("pong was blocked by the data callback")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user