Skip to content

Commit 596d781

Browse files
authored
Merge pull request #473 from hookdeck/fix/websocket-keepalive
fix(listen): stop reconnecting when a websocket pong is a little late
2 parents 4a867a2 + 38d4d07 commit 596d781

2 files changed

Lines changed: 121 additions & 3 deletions

File tree

‎pkg/websocket/client.go‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -227,13 +227,27 @@ func (c *Client) Run(ctx context.Context) {
227227
"prefix": "websocket.client.Run",
228228
}).Debug("Disconnected from Hookdeck")
229229

230-
c.ConnectionLost()
231230
close(c.stopReadPump)
232231
close(c.stopWritePump)
232+
c.closeForReconnect()
233+
c.ConnectionLost()
233234
c.wg.Wait()
234235
}
235236
}
236237

238+
// closeForReconnect drops the socket without a close frame so the CLI can
239+
// reconnect. Otherwise the socket stays open until the server's idle check
240+
// notices it is dead.
241+
//
242+
// It must not send a 1000 close like Stop does. The server treats a 1000 close
243+
// as an intentional shutdown and deletes the session immediately, whereas an
244+
// abnormal close (1006) keeps the session for the reconnect grace window.
245+
func (c *Client) closeForReconnect() {
246+
c.stateMu.Lock()
247+
defer c.stateMu.Unlock()
248+
_ = c.conn.Close()
249+
}
250+
237251
// ConnectionLost sends NotifyExpired
238252
func (c *Client) ConnectionLost() {
239253
c.NotifyExpired <- struct{}{}
@@ -518,6 +532,12 @@ func (c *Client) readPump() {
518532
return
519533
}
520534

535+
// Any frame proves the connection is alive, so a busy connection
536+
// doesn't drop just because a pong arrived late.
537+
if err := c.conn.SetReadDeadline(time.Now().Add(c.cfg.PongWait)); err != nil {
538+
c.cfg.Log.Debug("SetReadDeadline error: ", err)
539+
}
540+
521541
c.cfg.Log.WithFields(log.Fields{
522542
"prefix": "websocket.Client.readPump",
523543
"message": string(data),
@@ -638,7 +658,7 @@ func NewClient(url string, webSocketID string, CLIKey string, teamID string, con
638658
}
639659

640660
if cfg.PingPeriod == 0 {
641-
cfg.PingPeriod = (cfg.PongWait * 9) / 10
661+
cfg.PingPeriod = min(defaultPingPeriod, (cfg.PongWait*9)/10)
642662
}
643663

644664
if cfg.WriteWait == 0 {
@@ -672,7 +692,13 @@ func NewClient(url string, webSocketID string, CLIKey string, teamID string, con
672692
const (
673693
defaultConnectAttemptWait = 10 * time.Second
674694

675-
defaultPongWait = 10 * time.Second
695+
// defaultPongWait leaves room for a few late pongs (slow network, busy
696+
// server) before the connection is treated as dead.
697+
defaultPongWait = 30 * time.Second
698+
699+
// defaultPingPeriod stays well under the server's idle check so the server
700+
// keeps seeing the connection as alive.
701+
defaultPingPeriod = 10 * time.Second
676702

677703
defaultWriteWait = 10 * time.Second
678704

‎pkg/websocket/client_test.go‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,3 +292,95 @@ func TestLastConnectErr(t *testing.T) {
292292
}
293293
})
294294
}
295+
296+
// serverWithoutPongs upgrades the connection and reads from it without
297+
// answering pings, as a server would when its pongs are delayed.
298+
func serverWithoutPongs(t *testing.T, onConn func(conn *ws.Conn)) *httptest.Server {
299+
t.Helper()
300+
var captured http.Header
301+
return upgradeTestServer(t, &captured, func(conn *ws.Conn) {
302+
conn.SetPingHandler(func(string) error { return nil })
303+
onConn(conn)
304+
})
305+
}
306+
307+
// Data frames prove the connection is alive, so a connection that keeps
308+
// receiving messages must not drop when pongs are late.
309+
func TestIncomingMessagesKeepConnectionAlive(t *testing.T) {
310+
server := serverWithoutPongs(t, func(conn *ws.Conn) {
311+
go func() {
312+
for {
313+
if _, _, err := conn.ReadMessage(); err != nil {
314+
return
315+
}
316+
}
317+
}()
318+
for i := 0; i < 10; i++ {
319+
if err := conn.WriteMessage(ws.TextMessage, []byte(`{}`)); err != nil {
320+
return
321+
}
322+
time.Sleep(100 * time.Millisecond)
323+
}
324+
})
325+
defer server.Close()
326+
327+
client := NewClient(wsURL(server), "cses_test", "cli-key", "tm_test", nil, "", &Config{
328+
PongWait: 300 * time.Millisecond,
329+
PingPeriod: 100 * time.Millisecond,
330+
})
331+
startClient(t, client)
332+
333+
select {
334+
case <-client.NotifyExpired:
335+
t.Fatal("client dropped a connection that was receiving messages")
336+
case <-time.After(900 * time.Millisecond):
337+
}
338+
}
339+
340+
// When the read deadline expires, the client must close its socket before
341+
// reconnecting rather than leave it open for the server to reap.
342+
func TestReadTimeoutClosesSocket(t *testing.T) {
343+
serverReadErr := make(chan error, 1)
344+
server := serverWithoutPongs(t, func(conn *ws.Conn) {
345+
for {
346+
if _, _, err := conn.ReadMessage(); err != nil {
347+
serverReadErr <- err
348+
return
349+
}
350+
}
351+
})
352+
defer server.Close()
353+
354+
client := NewClient(wsURL(server), "cses_test", "cli-key", "tm_test", nil, "", &Config{
355+
PongWait: 300 * time.Millisecond,
356+
PingPeriod: 100 * time.Millisecond,
357+
})
358+
startClient(t, client)
359+
360+
select {
361+
case <-client.NotifyExpired:
362+
case <-time.After(5 * time.Second):
363+
t.Fatal("client did not report connection loss after the read deadline")
364+
}
365+
366+
select {
367+
case err := <-serverReadErr:
368+
// A 1000 close would make the server delete the session instead of
369+
// keeping it for the reconnect.
370+
if !ws.IsCloseError(err, ws.CloseAbnormalClosure) {
371+
t.Fatalf("server saw %v, want an abnormal close (1006) so the session survives the reconnect", err)
372+
}
373+
case <-time.After(2 * time.Second):
374+
t.Fatal("client left the old socket open after the read deadline")
375+
}
376+
}
377+
378+
func TestDefaultKeepalive(t *testing.T) {
379+
client := NewClient("ws://127.0.0.1:1", "cses_test", "cli-key", "tm_test", nil, "", nil)
380+
if client.cfg.PongWait != 30*time.Second {
381+
t.Errorf("PongWait = %s, want 30s", client.cfg.PongWait)
382+
}
383+
if client.cfg.PingPeriod != 10*time.Second {
384+
t.Errorf("PingPeriod = %s, want 10s", client.cfg.PingPeriod)
385+
}
386+
}

0 commit comments

Comments
 (0)