2018-06-21 19:40:22 +02:00
|
|
|
package dht
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2019-10-10 05:07:33 +02:00
|
|
|
"github.com/lbryio/lbry.go/v2/dht/bits"
|
|
|
|
"github.com/lbryio/lbry.go/v2/extras/stop"
|
2018-06-21 19:40:22 +02:00
|
|
|
)
|
|
|
|
|
2018-06-22 15:30:16 +02:00
|
|
|
// TODO: this should be moved out of dht and into node, and it should be completely hidden inside node. dht should not need to know about tokens
|
|
|
|
|
2018-06-21 19:40:22 +02:00
|
|
|
type tokenCacheEntry struct {
|
|
|
|
token string
|
|
|
|
receivedAt time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
type tokenCache struct {
|
|
|
|
node *Node
|
|
|
|
tokens map[string]tokenCacheEntry
|
|
|
|
expiration time.Duration
|
|
|
|
lock *sync.RWMutex
|
|
|
|
}
|
|
|
|
|
|
|
|
func newTokenCache(node *Node, expiration time.Duration) *tokenCache {
|
|
|
|
tc := &tokenCache{}
|
|
|
|
tc.node = node
|
|
|
|
tc.tokens = make(map[string]tokenCacheEntry)
|
|
|
|
tc.expiration = expiration
|
|
|
|
tc.lock = &sync.RWMutex{}
|
|
|
|
return tc
|
|
|
|
}
|
|
|
|
|
2018-06-26 16:58:19 +02:00
|
|
|
// TODO: if store fails, get new token. can happen if a node restarts but we have the token cached
|
|
|
|
|
2018-06-25 22:49:40 +02:00
|
|
|
func (tc *tokenCache) Get(c Contact, hash bits.Bitmap, cancelCh stop.Chan) string {
|
2018-06-21 19:40:22 +02:00
|
|
|
tc.lock.RLock()
|
|
|
|
token, exists := tc.tokens[c.String()]
|
|
|
|
tc.lock.RUnlock()
|
|
|
|
|
|
|
|
if exists && time.Since(token.receivedAt) < tc.expiration {
|
|
|
|
return token.token
|
|
|
|
}
|
|
|
|
|
2018-06-25 21:56:45 +02:00
|
|
|
resCh := tc.node.SendAsync(c, Request{
|
2018-06-21 19:40:22 +02:00
|
|
|
Method: findValueMethod,
|
|
|
|
Arg: &hash,
|
|
|
|
})
|
|
|
|
|
|
|
|
var res *Response
|
|
|
|
|
|
|
|
select {
|
|
|
|
case res = <-resCh:
|
|
|
|
case <-cancelCh:
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
if res == nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
tc.lock.Lock()
|
|
|
|
tc.tokens[c.String()] = tokenCacheEntry{
|
|
|
|
token: res.Token,
|
|
|
|
receivedAt: time.Now(),
|
|
|
|
}
|
|
|
|
tc.lock.Unlock()
|
|
|
|
|
|
|
|
return res.Token
|
|
|
|
}
|