Skip to content

Commit

Permalink
Fix unused servers cleanup
Browse files Browse the repository at this point in the history
- in cleanup loop check if a connection
failed to a server
- after add a foreign server connection
force to keep it minimum 5 sec
  • Loading branch information
pappz committed Nov 1, 2024
1 parent ad4f0a6 commit 4047e8f
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
18 changes: 17 additions & 1 deletion relay/client/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (

var (
relayCleanupInterval = 60 * time.Second
keepUnusedServerTime = 5 * time.Second

ErrRelayClientNotConnected = fmt.Errorf("relay client not connected")
)
Expand All @@ -27,10 +28,13 @@ type RelayTrack struct {
sync.RWMutex
relayClient *Client
err error
created time.Time
}

func NewRelayTrack() *RelayTrack {
return &RelayTrack{}
return &RelayTrack{
created: time.Now(),
}
}

type OnServerCloseListener func()
Expand Down Expand Up @@ -302,6 +306,18 @@ func (m *Manager) cleanUpUnusedRelays() {

for addr, rt := range m.relayClients {
rt.Lock()
// if the connection failed to the server the relay client will be nil
// but the instance will be kept in the relayClients until the next locking
if rt.err != nil {
rt.Unlock()
continue
}

if time.Since(rt.created) <= keepUnusedServerTime {
rt.Unlock()
continue
}

if rt.relayClient.HasConns() {
rt.Unlock()
continue
Expand Down
5 changes: 3 additions & 2 deletions relay/client/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -288,8 +288,9 @@ func TestForeginAutoClose(t *testing.T) {
t.Fatalf("failed to close connection: %s", err)
}

t.Logf("waiting for relay cleanup: %s", relayCleanupInterval+1*time.Second)
time.Sleep(relayCleanupInterval + 1*time.Second)
timeout := relayCleanupInterval + keepUnusedServerTime + 1*time.Second
t.Logf("waiting for relay cleanup: %s", timeout)
time.Sleep(timeout)
if len(mgr.relayClients) != 0 {
t.Errorf("expected 0, got %d", len(mgr.relayClients))
}
Expand Down
3 changes: 1 addition & 2 deletions relay/client/picker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"errors"
"testing"
"time"
)

func TestServerPicker_UnavailableServers(t *testing.T) {
Expand All @@ -13,7 +12,7 @@ func TestServerPicker_UnavailableServers(t *testing.T) {
PeerID: "test",
}

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), connectionTimeout+1)
defer cancel()

go func() {
Expand Down

0 comments on commit 4047e8f

Please sign in to comment.