2018-09-05 01:07:44 +08:00
|
|
|
package pstoremem
|
2018-08-29 22:12:41 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
2019-05-31 21:51:16 +08:00
|
|
|
peer "github.com/libp2p/go-libp2p-core/peer"
|
|
|
|
pstore "github.com/libp2p/go-libp2p-core/peerstore"
|
2018-08-29 22:12:41 +08:00
|
|
|
)
|
|
|
|
|
2019-05-28 05:41:29 +08:00
|
|
|
var internKeys = map[string]bool{
|
|
|
|
"AgentVersion": true,
|
|
|
|
"ProtocolVersion": true,
|
|
|
|
}
|
|
|
|
|
2019-04-23 15:10:05 +08:00
|
|
|
type metakey struct {
|
|
|
|
id peer.ID
|
|
|
|
key string
|
|
|
|
}
|
|
|
|
|
2018-08-29 22:12:41 +08:00
|
|
|
type memoryPeerMetadata struct {
|
|
|
|
// store other data, like versions
|
|
|
|
//ds ds.ThreadSafeDatastore
|
2019-05-28 05:41:29 +08:00
|
|
|
ds map[metakey]interface{}
|
|
|
|
dslock sync.RWMutex
|
|
|
|
interned map[string]interface{}
|
2018-08-29 22:12:41 +08:00
|
|
|
}
|
|
|
|
|
2018-09-28 21:04:52 +08:00
|
|
|
var _ pstore.PeerMetadata = (*memoryPeerMetadata)(nil)
|
|
|
|
|
2020-03-06 20:07:36 +08:00
|
|
|
func NewPeerMetadata() *memoryPeerMetadata {
|
2018-08-29 22:12:41 +08:00
|
|
|
return &memoryPeerMetadata{
|
2019-06-01 09:31:04 +08:00
|
|
|
ds: make(map[metakey]interface{}),
|
|
|
|
interned: make(map[string]interface{}),
|
2018-08-29 22:12:41 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ps *memoryPeerMetadata) Put(p peer.ID, key string, val interface{}) error {
|
|
|
|
ps.dslock.Lock()
|
|
|
|
defer ps.dslock.Unlock()
|
2019-05-28 05:41:29 +08:00
|
|
|
if vals, ok := val.(string); ok && internKeys[key] {
|
|
|
|
if interned, ok := ps.interned[vals]; ok {
|
|
|
|
val = interned
|
|
|
|
} else {
|
|
|
|
ps.interned[vals] = val
|
|
|
|
}
|
|
|
|
}
|
2019-04-23 15:10:05 +08:00
|
|
|
ps.ds[metakey{p, key}] = val
|
2018-08-29 22:12:41 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ps *memoryPeerMetadata) Get(p peer.ID, key string) (interface{}, error) {
|
2019-04-28 03:19:49 +08:00
|
|
|
ps.dslock.RLock()
|
|
|
|
defer ps.dslock.RUnlock()
|
2019-04-23 15:10:05 +08:00
|
|
|
i, ok := ps.ds[metakey{p, key}]
|
2018-08-29 22:12:41 +08:00
|
|
|
if !ok {
|
2018-08-30 21:13:27 +08:00
|
|
|
return nil, pstore.ErrNotFound
|
2018-08-29 22:12:41 +08:00
|
|
|
}
|
|
|
|
return i, nil
|
|
|
|
}
|