2019-06-09 07:24:20 +00:00
|
|
|
package pstoremem
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
2019-10-04 15:21:24 +00:00
|
|
|
peer "github.com/libp2p/go-libp2p-core/peer"
|
|
|
|
pstore "github.com/libp2p/go-libp2p-core/peerstore"
|
2019-06-09 07:24:20 +00:00
|
|
|
)
|
|
|
|
|
2019-10-04 15:21:24 +00:00
|
|
|
var internKeys = map[string]bool{
|
|
|
|
"AgentVersion": true,
|
|
|
|
"ProtocolVersion": true,
|
|
|
|
}
|
|
|
|
|
2019-06-09 07:24:20 +00:00
|
|
|
type metakey struct {
|
|
|
|
id peer.ID
|
|
|
|
key string
|
|
|
|
}
|
|
|
|
|
|
|
|
type memoryPeerMetadata struct {
|
|
|
|
// store other data, like versions
|
|
|
|
//ds ds.ThreadSafeDatastore
|
2019-10-04 15:21:24 +00:00
|
|
|
ds map[metakey]interface{}
|
|
|
|
dslock sync.RWMutex
|
|
|
|
interned map[string]interface{}
|
2019-06-09 07:24:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var _ pstore.PeerMetadata = (*memoryPeerMetadata)(nil)
|
|
|
|
|
2021-06-16 20:19:45 +00:00
|
|
|
func NewPeerMetadata() *memoryPeerMetadata {
|
2019-06-09 07:24:20 +00:00
|
|
|
return &memoryPeerMetadata{
|
2019-10-04 15:21:24 +00:00
|
|
|
ds: make(map[metakey]interface{}),
|
|
|
|
interned: make(map[string]interface{}),
|
2019-06-09 07:24:20 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ps *memoryPeerMetadata) Put(p peer.ID, key string, val interface{}) error {
|
2021-06-16 20:19:45 +00:00
|
|
|
if err := p.Validate(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-06-09 07:24:20 +00:00
|
|
|
ps.dslock.Lock()
|
|
|
|
defer ps.dslock.Unlock()
|
2019-10-04 15:21:24 +00:00
|
|
|
if vals, ok := val.(string); ok && internKeys[key] {
|
|
|
|
if interned, ok := ps.interned[vals]; ok {
|
|
|
|
val = interned
|
|
|
|
} else {
|
|
|
|
ps.interned[vals] = val
|
|
|
|
}
|
|
|
|
}
|
2019-06-09 07:24:20 +00:00
|
|
|
ps.ds[metakey{p, key}] = val
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ps *memoryPeerMetadata) Get(p peer.ID, key string) (interface{}, error) {
|
2021-06-16 20:19:45 +00:00
|
|
|
if err := p.Validate(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-06-09 07:24:20 +00:00
|
|
|
ps.dslock.RLock()
|
|
|
|
defer ps.dslock.RUnlock()
|
|
|
|
i, ok := ps.ds[metakey{p, key}]
|
|
|
|
if !ok {
|
|
|
|
return nil, pstore.ErrNotFound
|
|
|
|
}
|
|
|
|
return i, nil
|
|
|
|
}
|