2024-05-17 17:43:28 +02:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2024-07-29 21:53:07 +02:00
|
|
|
// Store is a thread-safe store of peers
|
|
|
|
// It is used to store the peers that are connected to the relay server
|
2024-05-17 17:43:28 +02:00
|
|
|
type Store struct {
|
2024-05-23 13:24:02 +02:00
|
|
|
peers map[string]*Peer // consider to use [32]byte as key. The Peer(id string) would be faster
|
|
|
|
peersLock sync.RWMutex
|
2024-05-17 17:43:28 +02:00
|
|
|
}
|
|
|
|
|
2024-07-29 21:53:07 +02:00
|
|
|
// NewStore creates a new Store instance
|
2024-05-17 17:43:28 +02:00
|
|
|
func NewStore() *Store {
|
|
|
|
return &Store{
|
|
|
|
peers: make(map[string]*Peer),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-29 21:53:07 +02:00
|
|
|
// AddPeer adds a peer to the store
|
|
|
|
// It distinguishes the peers by their ID
|
2024-05-17 17:43:28 +02:00
|
|
|
func (s *Store) AddPeer(peer *Peer) {
|
|
|
|
s.peersLock.Lock()
|
|
|
|
defer s.peersLock.Unlock()
|
2024-05-23 13:24:02 +02:00
|
|
|
s.peers[peer.String()] = peer
|
2024-05-17 17:43:28 +02:00
|
|
|
}
|
|
|
|
|
2024-07-29 21:53:07 +02:00
|
|
|
// DeletePeer deletes a peer from the store
|
2024-05-23 13:24:02 +02:00
|
|
|
func (s *Store) DeletePeer(peer *Peer) {
|
2024-05-17 17:43:28 +02:00
|
|
|
s.peersLock.Lock()
|
|
|
|
defer s.peersLock.Unlock()
|
2024-05-23 13:24:02 +02:00
|
|
|
delete(s.peers, peer.String())
|
2024-05-17 17:43:28 +02:00
|
|
|
}
|
|
|
|
|
2024-07-29 21:53:07 +02:00
|
|
|
// Peer returns a peer by its ID
|
2024-05-23 13:24:02 +02:00
|
|
|
func (s *Store) Peer(id string) (*Peer, bool) {
|
|
|
|
s.peersLock.RLock()
|
|
|
|
defer s.peersLock.RUnlock()
|
2024-05-17 17:43:28 +02:00
|
|
|
|
2024-05-23 13:24:02 +02:00
|
|
|
p, ok := s.peers[id]
|
|
|
|
return p, ok
|
2024-05-17 17:43:28 +02:00
|
|
|
}
|
2024-06-05 19:49:30 +02:00
|
|
|
|
2024-07-29 21:53:07 +02:00
|
|
|
// Peers returns all the peers in the store
|
2024-06-05 19:49:30 +02:00
|
|
|
func (s *Store) Peers() []*Peer {
|
|
|
|
s.peersLock.RLock()
|
|
|
|
defer s.peersLock.RUnlock()
|
|
|
|
|
|
|
|
peers := make([]*Peer, 0, len(s.peers))
|
|
|
|
for _, p := range s.peers {
|
|
|
|
peers = append(peers, p)
|
|
|
|
}
|
|
|
|
return peers
|
|
|
|
}
|