Unverified Commit 40e1c947 authored by vyzo's avatar vyzo Committed by GitHub

Merge pull request #258 from aarshkshah1992/feat/blacklist-timecache

Replace LRU cache blacklist implementation with a time cache
parents 25c434f5 6eeed58a
package pubsub package pubsub
import ( import (
lru "github.com/hashicorp/golang-lru" "sync"
"time"
"github.com/libp2p/go-libp2p-core/peer" "github.com/libp2p/go-libp2p-core/peer"
"github.com/whyrusleeping/timecache"
) )
// Blacklist is an interface for peer blacklisting. // Blacklist is an interface for peer blacklisting.
...@@ -28,26 +31,28 @@ func (b MapBlacklist) Contains(p peer.ID) bool { ...@@ -28,26 +31,28 @@ func (b MapBlacklist) Contains(p peer.ID) bool {
return ok return ok
} }
// LRUBlacklist is a blacklist implementation using an LRU cache // TimeCachedBlacklist is a blacklist implementation using a time cache
type LRUBlacklist struct { type TimeCachedBlacklist struct {
lru *lru.Cache sync.RWMutex
tc *timecache.TimeCache
} }
// NewLRUBlacklist creates a new LRUBlacklist with capacity cap // NewTimeCachedBlacklist creates a new TimeCachedBlacklist with the given expiry duration
func NewLRUBlacklist(cap int) (Blacklist, error) { func NewTimeCachedBlacklist(expiry time.Duration) (Blacklist, error) {
c, err := lru.New(cap) b := &TimeCachedBlacklist{tc: timecache.NewTimeCache(expiry)}
if err != nil {
return nil, err
}
b := &LRUBlacklist{lru: c}
return b, nil return b, nil
} }
func (b LRUBlacklist) Add(p peer.ID) { func (b *TimeCachedBlacklist) Add(p peer.ID) {
b.lru.Add(p, nil) b.Lock()
defer b.Unlock()
b.tc.Add(p.String())
} }
func (b LRUBlacklist) Contains(p peer.ID) bool { func (b *TimeCachedBlacklist) Contains(p peer.ID) bool {
return b.lru.Contains(p) b.RLock()
defer b.RUnlock()
return b.tc.Has(p.String())
} }
...@@ -20,8 +20,8 @@ func TestMapBlacklist(t *testing.T) { ...@@ -20,8 +20,8 @@ func TestMapBlacklist(t *testing.T) {
} }
func TestLRUBlacklist(t *testing.T) { func TestTimeCachedBlacklist(t *testing.T) {
b, err := NewLRUBlacklist(10) b, err := NewTimeCachedBlacklist(10 * time.Minute)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
...@@ -32,7 +32,6 @@ func TestLRUBlacklist(t *testing.T) { ...@@ -32,7 +32,6 @@ func TestLRUBlacklist(t *testing.T) {
if !b.Contains(p) { if !b.Contains(p) {
t.Fatal("peer not in the blacklist") t.Fatal("peer not in the blacklist")
} }
} }
func TestBlacklist(t *testing.T) { func TestBlacklist(t *testing.T) {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment