[client] Refactor peer state change subscription mechanism (#3910)

* Refactor peer state change subscription mechanism

Because the code generated new channel for every single event, was easy to miss notification.
Use single channel.

* Fix lint

* Avoid potential deadlock

* Fix test

* Add context

* Fix test
This commit is contained in:
Zoltan Papp
2025-06-03 09:20:33 +02:00
committed by GitHub
parent 35287f8241
commit af27aaf9af
3 changed files with 78 additions and 27 deletions

View File

@@ -1,6 +1,7 @@
package peer
import (
"context"
"errors"
"sync"
"testing"
@@ -86,8 +87,8 @@ func TestGetPeerStateChangeNotifierLogic(t *testing.T) {
status := NewRecorder("https://mgm")
_ = status.AddPeer(key, "abc.netbird", ip)
ch := status.GetPeerStateChangeNotifier(key)
assert.NotNil(t, ch, "channel shouldn't be nil")
sub := status.SubscribeToPeerStateChanges(context.Background(), key)
assert.NotNil(t, sub, "channel shouldn't be nil")
peerState := State{
PubKey: key,
@@ -99,10 +100,12 @@ func TestGetPeerStateChangeNotifierLogic(t *testing.T) {
err := status.UpdatePeerRelayedStateToDisconnected(peerState)
assert.NoError(t, err, "shouldn't return error")
timeoutCtx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
select {
case <-ch:
default:
t.Errorf("channel wasn't closed after update")
case <-sub.eventsChan:
case <-timeoutCtx.Done():
t.Errorf("timed out waiting for event")
}
}