github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/netsync/chainmgr/peers.go (about)

     1  package chainmgr
     2  
     3  import (
     4  	"errors"
     5  	"sync"
     6  )
     7  
     8  var errNoValidFastSyncPeer = errors.New("no valid fast sync peer")
     9  
    10  type fastSyncPeers struct {
    11  	peers map[string]bool
    12  	mtx   sync.RWMutex
    13  }
    14  
    15  func newFastSyncPeers() *fastSyncPeers {
    16  	return &fastSyncPeers{
    17  		peers: make(map[string]bool),
    18  	}
    19  }
    20  
    21  func (fs *fastSyncPeers) add(peerID string) {
    22  	fs.mtx.Lock()
    23  	defer fs.mtx.Unlock()
    24  
    25  	if _, ok := fs.peers[peerID]; ok {
    26  		return
    27  	}
    28  
    29  	fs.peers[peerID] = false
    30  }
    31  
    32  func (fs *fastSyncPeers) delete(peerID string) {
    33  	fs.mtx.Lock()
    34  	defer fs.mtx.Unlock()
    35  
    36  	delete(fs.peers, peerID)
    37  }
    38  
    39  func (fs *fastSyncPeers) selectIdlePeers() []string {
    40  	fs.mtx.Lock()
    41  	defer fs.mtx.Unlock()
    42  
    43  	peers := make([]string, 0)
    44  	for peerID, isBusy := range fs.peers {
    45  		if isBusy {
    46  			continue
    47  		}
    48  
    49  		fs.peers[peerID] = true
    50  		peers = append(peers, peerID)
    51  	}
    52  
    53  	return peers
    54  }
    55  
    56  func (fs *fastSyncPeers) selectIdlePeer() (string, error) {
    57  	fs.mtx.Lock()
    58  	defer fs.mtx.Unlock()
    59  
    60  	for peerID, isBusy := range fs.peers {
    61  		if isBusy {
    62  			continue
    63  		}
    64  
    65  		fs.peers[peerID] = true
    66  		return peerID, nil
    67  	}
    68  
    69  	return "", errNoValidFastSyncPeer
    70  }
    71  
    72  func (fs *fastSyncPeers) setIdle(peerID string) {
    73  	fs.mtx.Lock()
    74  	defer fs.mtx.Unlock()
    75  
    76  	if _, ok := fs.peers[peerID]; !ok {
    77  		return
    78  	}
    79  
    80  	fs.peers[peerID] = false
    81  }
    82  
    83  func (fs *fastSyncPeers) size() int {
    84  	fs.mtx.RLock()
    85  	defer fs.mtx.RUnlock()
    86  
    87  	return len(fs.peers)
    88  }