probably fixing race condition.

This commit is contained in:
pippellia-btc
2025-05-07 10:34:05 -03:00
committed by fiatjaf
parent a983fc74b5
commit 0853405c03

View File

@@ -142,35 +142,25 @@ func (r *Relay) ConnectWithTLS(ctx context.Context, tlsConfig *tls.Config) error
// ping every 29 seconds // ping every 29 seconds
ticker := time.NewTicker(29 * time.Second) 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 // queue all write operations here so we don't do mutex spaghetti
go func() { go func() {
for { for {
select { 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: case <-ticker.C:
if r.Connection != nil {
err := r.Connection.Ping(r.connectionContext) err := r.Connection.Ping(r.connectionContext)
if err != nil && !strings.Contains(err.Error(), "failed to wait for pong") { if err != nil && !strings.Contains(err.Error(), "failed to wait for pong") {
InfoLogger.Printf("{%s} error writing ping: %v; closing websocket", r.URL, err) InfoLogger.Printf("{%s} error writing ping: %v; closing websocket", r.URL, err)
r.Close() // this should trigger a context cancelation r.Close() // this should trigger a context cancelation
return return
} }
}
case writeRequest := <-r.writeQueue: case writeRequest := <-r.writeQueue:
// all write requests will go through this to prevent races // all write requests will go through this to prevent races
debugLogf("{%s} sending %v\n", r.URL, string(writeRequest.msg)) debugLogf("{%s} sending %v\n", r.URL, string(writeRequest.msg))
@@ -178,9 +168,6 @@ func (r *Relay) ConnectWithTLS(ctx context.Context, tlsConfig *tls.Config) error
writeRequest.answer <- err writeRequest.answer <- err
} }
close(writeRequest.answer) close(writeRequest.answer)
case <-r.connectionContext.Done():
// stop here
return
} }
} }
}() }()