Skip to content

Commit

Permalink
fixed: correctly cancel context during retries
Browse files Browse the repository at this point in the history
The loop handling reconnection was using the main context, never
canceling pending requests, that could end up in a connection storm and
filling of the incoming message channel.
  • Loading branch information
primalmotion committed Jun 15, 2023
1 parent f18c2ce commit 5ca5b7c
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion client/subscribe_ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,11 @@ func SubscribeWS(ctx context.Context, url string, tlsConfig *tls.Config) (chan [
}
isReconnect = true

wsctx, cancel := context.WithCancel(ctx)
defer cancel()

conn, resp, err := wsc.Connect(
ctx,
wsctx,
strings.Replace(url+"/subscribe/ws", "https", "wss", 1),
wsc.Config{
TLSConfig: tlsConfig,
Expand All @@ -52,11 +55,13 @@ func SubscribeWS(ctx context.Context, url string, tlsConfig *tls.Config) (chan [
)
if err != nil {
log.Printf("unable to connect to ws (retrying): %s", err)
cancel()
continue
}

if resp.StatusCode != http.StatusSwitchingProtocols {
log.Printf("server rejected ws connection (retrying): %s", err)
cancel()
continue
}

Expand All @@ -71,6 +76,7 @@ func SubscribeWS(ctx context.Context, url string, tlsConfig *tls.Config) (chan [
} else {
log.Println("ws server gone. reconnecting...")
}
cancel()
continue MAINWS

case data := <-conn.Read():
Expand Down

0 comments on commit 5ca5b7c

Please sign in to comment.