From 0853405c0324eb290628fc324fae5dbde7dfe185 Mon Sep 17 00:00:00 2001 From: pippellia-btc Date: Wed, 7 May 2025 10:34:05 -0300 Subject: [PATCH] probably fixing race condition. --- relay.go | 39 +++++++++++++-------------------------- 1 file changed, 13 insertions(+), 26 deletions(-) diff --git a/relay.go b/relay.go index 18ba906..377bffc 100644 --- a/relay.go +++ b/relay.go @@ -142,34 +142,24 @@ func (r *Relay) ConnectWithTLS(ctx context.Context, tlsConfig *tls.Config) error // ping every 29 seconds ticker := time.NewTicker(29 * time.Second) - // to be used when the connection is closed - go func() { - <-r.connectionContext.Done() - - // stop the ticker - ticker.Stop() - - // nil the connection - r.Connection = nil - - // close all subscriptions - for _, sub := range r.Subscriptions.Range { - sub.unsub(fmt.Errorf("relay connection closed: %w / %w", context.Cause(r.connectionContext), r.ConnectionError)) - } - }() - // queue all write operations here so we don't do mutex spaghetti go func() { for { select { + case <-r.connectionContext.Done(): + ticker.Stop() + r.Connection = nil + + for _, sub := range r.Subscriptions.Range { + sub.unsub(fmt.Errorf("relay connection closed: %w / %w", context.Cause(r.connectionContext), r.ConnectionError)) + } + return case <-ticker.C: - if r.Connection != nil { - err := r.Connection.Ping(r.connectionContext) - if err != nil && !strings.Contains(err.Error(), "failed to wait for pong") { - InfoLogger.Printf("{%s} error writing ping: %v; closing websocket", r.URL, err) - r.Close() // this should trigger a context cancelation - return - } + err := r.Connection.Ping(r.connectionContext) + if err != nil && !strings.Contains(err.Error(), "failed to wait for pong") { + InfoLogger.Printf("{%s} error writing ping: %v; closing websocket", r.URL, err) + r.Close() // this should trigger a context cancelation + return } case writeRequest := <-r.writeQueue: // all write requests will go through this to prevent races @@ -178,9 +168,6 @@ func (r *Relay) ConnectWithTLS(ctx context.Context, tlsConfig *tls.Config) error writeRequest.answer <- err } close(writeRequest.answer) - case <-r.connectionContext.Done(): - // stop here - return } } }()