Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(share/discovery): Ensure only one instance of EnsurePeers is running #1642

Merged
merged 2 commits into from
Jan 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions share/availability/discovery/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package discovery

import (
"context"
"sync"
"time"

logging "github.com/ipfs/go-log/v2"
Expand Down Expand Up @@ -41,6 +42,8 @@ type Discovery struct {
advertiseInterval time.Duration
// onUpdatedPeers will be called on peer set changes
onUpdatedPeers OnUpdatedPeers
// ensureIsRunning allows only one ensurePeers process to be running
ensurePeersOnce sync.Once
}

type OnUpdatedPeers func(peerID peer.ID, isAdded bool)
Expand All @@ -62,6 +65,7 @@ func NewDiscovery(
discInterval,
advertiseInterval,
func(peer.ID, bool) {},
sync.Once{},
walldiss marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand Down Expand Up @@ -102,6 +106,12 @@ func (d *Discovery) handlePeerFound(ctx context.Context, topic string, peer peer
// It starts peer discovery every 30 seconds until peer cache reaches peersLimit.
// Discovery is restarted if any previously connected peers disconnect.
func (d *Discovery) EnsurePeers(ctx context.Context) {
d.ensurePeersOnce.Do(func() {
go d.ensurePeers(ctx)
})
}

func (d *Discovery) ensurePeers(ctx context.Context) {
if d.peersLimit == 0 {
log.Warn("peers limit is set to 0. Skipping discovery...")
return
Expand Down
2 changes: 1 addition & 1 deletion share/availability/full/availability.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func (fa *ShareAvailability) Start(context.Context) error {
fa.cancel = cancel

go fa.disc.Advertise(ctx)
go fa.disc.EnsurePeers(ctx)
fa.disc.EnsurePeers(ctx)
return nil
}

Expand Down
2 changes: 1 addition & 1 deletion share/availability/light/availability.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func (la *ShareAvailability) Start(context.Context) error {
ctx, cancel := context.WithCancel(context.Background())
la.cancel = cancel

go la.disc.EnsurePeers(ctx)
la.disc.EnsurePeers(ctx)
return nil
}

Expand Down