2023-07-27 17:04:08 +00:00
|
|
|
package rendezvous
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math/rand"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/libp2p/go-libp2p/core/peer"
|
|
|
|
"github.com/libp2p/go-libp2p/p2p/discovery/backoff"
|
|
|
|
)
|
|
|
|
|
2023-07-31 18:58:50 +00:00
|
|
|
// RendezvousPoint is a structure that represent a node that can be used to discover new peers
|
2023-07-27 17:04:08 +00:00
|
|
|
type RendezvousPoint struct {
|
|
|
|
sync.RWMutex
|
|
|
|
|
|
|
|
id peer.ID
|
|
|
|
cookie []byte
|
|
|
|
|
|
|
|
bkf backoff.BackoffStrategy
|
|
|
|
nextTry time.Time
|
|
|
|
}
|
|
|
|
|
2023-07-31 18:58:50 +00:00
|
|
|
// NewRendezvousPoint is used to create a RendezvousPoint
|
2023-07-27 17:04:08 +00:00
|
|
|
func NewRendezvousPoint(peerID peer.ID) *RendezvousPoint {
|
|
|
|
rngSrc := rand.NewSource(rand.Int63())
|
|
|
|
minBackoff, maxBackoff := time.Second*30, time.Hour
|
|
|
|
bkf := backoff.NewExponentialBackoff(minBackoff, maxBackoff, backoff.FullJitter, time.Second, 5.0, 0, rand.New(rngSrc))
|
|
|
|
|
|
|
|
now := time.Now()
|
|
|
|
|
|
|
|
rp := &RendezvousPoint{
|
|
|
|
id: peerID,
|
|
|
|
nextTry: now,
|
|
|
|
bkf: bkf(),
|
|
|
|
}
|
|
|
|
|
|
|
|
return rp
|
|
|
|
}
|
|
|
|
|
2023-07-31 18:58:50 +00:00
|
|
|
// Delay is used to indicate that the connection to a rendezvous point failed
|
2023-07-27 17:04:08 +00:00
|
|
|
func (rp *RendezvousPoint) Delay() {
|
|
|
|
rp.Lock()
|
|
|
|
defer rp.Unlock()
|
|
|
|
|
|
|
|
rp.nextTry = time.Now().Add(rp.bkf.Delay())
|
|
|
|
}
|
|
|
|
|
2023-07-31 18:58:50 +00:00
|
|
|
// SetSuccess is used to indicate that a connection to a rendezvous point was succesful
|
2023-07-27 17:04:08 +00:00
|
|
|
func (rp *RendezvousPoint) SetSuccess(cookie []byte) {
|
|
|
|
rp.Lock()
|
|
|
|
defer rp.Unlock()
|
|
|
|
|
|
|
|
rp.bkf.Reset()
|
2023-07-31 18:58:50 +00:00
|
|
|
rp.nextTry = time.Now()
|
2023-07-27 17:04:08 +00:00
|
|
|
rp.cookie = cookie
|
|
|
|
}
|
|
|
|
|
2023-07-31 18:58:50 +00:00
|
|
|
// NextTry returns when can a rendezvous point be used again
|
2023-07-27 17:04:08 +00:00
|
|
|
func (rp *RendezvousPoint) NextTry() time.Time {
|
|
|
|
rp.RLock()
|
|
|
|
defer rp.RUnlock()
|
|
|
|
return rp.nextTry
|
|
|
|
}
|