mirror of
https://github.com/tendermint/tendermint.git
synced 2026-08-20 14:16:22 +00:00
p2p: tighten up and test PeerManager (#6034)
This tightens up the `PeerManager` and related code, adds a ton of tests, and fixes a bunch of inconsistencies and bugs.
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
package sync
|
||||
|
||||
// Waker is used to wake up a sleeper when some event occurs. It debounces
|
||||
// multiple wakeup calls occurring between each sleep, and wakeups are
|
||||
// non-blocking to avoid having to coordinate goroutines.
|
||||
type Waker struct {
|
||||
wakeCh chan struct{}
|
||||
}
|
||||
|
||||
// NewWaker creates a new Waker.
|
||||
func NewWaker() *Waker {
|
||||
return &Waker{
|
||||
wakeCh: make(chan struct{}, 1), // buffer used for debouncing
|
||||
}
|
||||
}
|
||||
|
||||
// Sleep returns a channel that blocks until Wake() is called.
|
||||
func (w *Waker) Sleep() <-chan struct{} {
|
||||
return w.wakeCh
|
||||
}
|
||||
|
||||
// Wake wakes up the sleeper.
|
||||
func (w *Waker) Wake() {
|
||||
// A non-blocking send with a size 1 buffer ensures that we never block, and
|
||||
// that we queue up at most a single wakeup call between each Sleep().
|
||||
select {
|
||||
case w.wakeCh <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package sync_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
tmsync "github.com/tendermint/tendermint/libs/sync"
|
||||
)
|
||||
|
||||
func TestWaker(t *testing.T) {
|
||||
|
||||
// A new waker should block when sleeping.
|
||||
waker := tmsync.NewWaker()
|
||||
|
||||
select {
|
||||
case <-waker.Sleep():
|
||||
require.Fail(t, "unexpected wakeup")
|
||||
default:
|
||||
}
|
||||
|
||||
// Wakeups should not block, and should cause the next sleeper to awaken.
|
||||
waker.Wake()
|
||||
|
||||
select {
|
||||
case <-waker.Sleep():
|
||||
default:
|
||||
require.Fail(t, "expected wakeup, but sleeping instead")
|
||||
}
|
||||
|
||||
// Multiple wakeups should only wake a single sleeper.
|
||||
waker.Wake()
|
||||
waker.Wake()
|
||||
waker.Wake()
|
||||
|
||||
select {
|
||||
case <-waker.Sleep():
|
||||
default:
|
||||
require.Fail(t, "expected wakeup, but sleeping instead")
|
||||
}
|
||||
|
||||
select {
|
||||
case <-waker.Sleep():
|
||||
require.Fail(t, "unexpected wakeup")
|
||||
default:
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user