lbry.go/dht/store.go

56 lines
1 KiB
Go
Raw Normal View History

2018-03-07 22:15:58 +01:00
package dht
2018-03-08 01:49:33 +01:00
import "sync"
2018-03-07 22:15:58 +01:00
type peer struct {
2018-03-09 22:43:30 +01:00
node Node
//<lastPublished>,
//<originallyPublished>
// <originalPublisherID>
2018-03-07 22:15:58 +01:00
}
type peerStore struct {
nodeIDs map[string]map[bitmap]bool
nodeInfo map[bitmap]peer
lock sync.RWMutex
2018-03-07 22:15:58 +01:00
}
func newPeerStore() *peerStore {
return &peerStore{
nodeIDs: make(map[string]map[bitmap]bool),
nodeInfo: make(map[bitmap]peer),
2018-03-07 22:15:58 +01:00
}
}
func (s *peerStore) Upsert(key string, node Node) {
2018-03-07 22:15:58 +01:00
s.lock.Lock()
defer s.lock.Unlock()
if _, ok := s.nodeIDs[key]; !ok {
s.nodeIDs[key] = make(map[bitmap]bool)
2018-03-07 22:15:58 +01:00
}
s.nodeIDs[key][node.id] = true
s.nodeInfo[node.id] = peer{node: node}
2018-03-07 22:15:58 +01:00
}
2018-03-09 22:43:30 +01:00
func (s *peerStore) Get(key string) []Node {
2018-03-07 22:15:58 +01:00
s.lock.RLock()
defer s.lock.RUnlock()
2018-03-09 22:43:30 +01:00
var nodes []Node
if ids, ok := s.nodeIDs[key]; ok {
for id := range ids {
peer, ok := s.nodeInfo[id]
if !ok {
panic("node id in IDs list, but not in nodeInfo")
}
nodes = append(nodes, peer.node)
2018-03-07 22:15:58 +01:00
}
}
return nodes
}
func (s *peerStore) CountKnownNodes() int {
s.lock.RLock()
defer s.lock.RUnlock()
return len(s.nodeInfo)
}