replace lru cache blacklist implementation with a time cache

This commit is contained in:
Aarsh Shah 2020-02-04 20:05:16 +05:30
parent 25c434f5f7
commit 3f48f468ac
2 changed files with 15 additions and 19 deletions

View File

@ -1,8 +1,10 @@
package pubsub
import (
lru "github.com/hashicorp/golang-lru"
"time"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/whyrusleeping/timecache"
)
// Blacklist is an interface for peer blacklisting.
@ -28,26 +30,21 @@ func (b MapBlacklist) Contains(p peer.ID) bool {
return ok
}
// LRUBlacklist is a blacklist implementation using an LRU cache
type LRUBlacklist struct {
lru *lru.Cache
// TimeCachedBlacklist is a blacklist implementation using a time cache
type TimeCachedBlacklist struct {
tc *timecache.TimeCache
}
// NewLRUBlacklist creates a new LRUBlacklist with capacity cap
func NewLRUBlacklist(cap int) (Blacklist, error) {
c, err := lru.New(cap)
if err != nil {
return nil, err
}
b := &LRUBlacklist{lru: c}
// NewTimeCachedBlacklist creates a new TimeCachedBlacklist with the given expiry duration
func NewTimeCachedBlacklist(expiry time.Duration) (Blacklist, error) {
b := &TimeCachedBlacklist{timecache.NewTimeCache(expiry)}
return b, nil
}
func (b LRUBlacklist) Add(p peer.ID) {
b.lru.Add(p, nil)
func (b TimeCachedBlacklist) Add(p peer.ID) {
b.tc.Add(p.String())
}
func (b LRUBlacklist) Contains(p peer.ID) bool {
return b.lru.Contains(p)
func (b TimeCachedBlacklist) Contains(p peer.ID) bool {
return b.tc.Has(p.String())
}

View File

@ -20,8 +20,8 @@ func TestMapBlacklist(t *testing.T) {
}
func TestLRUBlacklist(t *testing.T) {
b, err := NewLRUBlacklist(10)
func TestTimeCachedBlacklist(t *testing.T) {
b, err := NewTimeCachedBlacklist(10 * time.Minute)
if err != nil {
t.Fatal(err)
}
@ -32,7 +32,6 @@ func TestLRUBlacklist(t *testing.T) {
if !b.Contains(p) {
t.Fatal("peer not in the blacklist")
}
}
func TestBlacklist(t *testing.T) {