Skip to content

Commit

Permalink
do not start new relay if one already exists
Browse files Browse the repository at this point in the history
  • Loading branch information
sukunrt committed Feb 14, 2023
1 parent 235f25b commit e5442ec
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
10 changes: 7 additions & 3 deletions p2p/host/relaysvc/relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,18 @@ func (m *RelayManager) background(ctx context.Context) {
func (m *RelayManager) reachabilityChanged(r network.Reachability) error {
switch r {
case network.ReachabilityPublic:
m.mutex.Lock()
defer m.mutex.Unlock()
// ignore events with no reachability change
if m.relay != nil {
return nil
}
relay, err := relayv2.New(m.host, m.opts...)
if err != nil {
return err
}
m.mutex.Lock()
defer m.mutex.Unlock()
m.relay = relay
case network.ReachabilityPrivate:
default:
m.mutex.Lock()
defer m.mutex.Unlock()
if m.relay != nil {
Expand Down
29 changes: 29 additions & 0 deletions p2p/host/relaysvc/relay_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package relaysvc

import (
"testing"

"github.com/libp2p/go-libp2p/core/network"
bhost "github.com/libp2p/go-libp2p/p2p/host/blank"
swarmt "github.com/libp2p/go-libp2p/p2p/net/swarm/testing"
"github.com/stretchr/testify/require"
)

func TestReachabilityChangeEvent(t *testing.T) {
h := bhost.NewBlankHost(swarmt.GenSwarm(t))
rmgr := NewRelayManager(h)
rmgr.reachabilityChanged(network.ReachabilityPublic)
require.NotNil(t, rmgr.relay, "relay should be set on public reachability")

rmgr.reachabilityChanged(network.ReachabilityPrivate)
require.Nil(t, rmgr.relay, "relay should be nil on private reachability")

rmgr.reachabilityChanged(network.ReachabilityPublic)
rmgr.reachabilityChanged(network.ReachabilityUnknown)
require.Nil(t, rmgr.relay, "relay should be nil on unknown reachability")

rmgr.reachabilityChanged(network.ReachabilityPublic)
relay := rmgr.relay
rmgr.reachabilityChanged(network.ReachabilityPublic)
require.Equal(t, relay, rmgr.relay, "relay should not be started on receiving the same event")
}

0 comments on commit e5442ec

Please sign in to comment.