Skip to content

Commit

Permalink
enable/disable filter
Browse files Browse the repository at this point in the history
  • Loading branch information
WhoSoup committed May 30, 2019
1 parent c53923a commit eaaf4fd
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
9 changes: 8 additions & 1 deletion util/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
)

type Filter struct {
enabled bool
expiration time.Duration
cleanTimer time.Duration
hashes map[string]time.Time
Expand All @@ -21,16 +22,22 @@ type item struct {

func NewFilter(t time.Duration, ct time.Duration) *Filter {
f := new(Filter)
f.enabled = t > 0
f.expiration = t
f.cleanTimer = ct
f.hashes = make(map[string]time.Time)
f.stop = make(chan bool, 1)
go f.clean()
if f.enabled {
go f.clean()
}
return f
}

// Check returns TRUE if the hash is new, false if the hash is a duplicate
func (f *Filter) Check(hash string) bool {
if !f.enabled {
return true
}
n := time.Now()
cutoff := n.Add(-f.expiration)
f.mtx.Lock()
Expand Down
14 changes: 11 additions & 3 deletions util/filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func TestFilter_Check(t *testing.T) {
f *Filter
hash string
}{
{"1-%d", f, "hash1"},
{"1-%d", f, ""},
{"2-%d", f, "hash2"},
{"3-%d", f, "hash3"},
{"4-%d", f, "hash4"},
Expand All @@ -34,9 +34,9 @@ func TestFilter_Check(t *testing.T) {
}
})
}
time.Sleep(time.Millisecond * 4)
time.Sleep(time.Millisecond * 4) // not quite past first cleanup
f.Check("foo")
time.Sleep(time.Millisecond * 3)
time.Sleep(time.Millisecond * 3) // past first cleanup
for _, tt := range tests {
t.Run(fmt.Sprintf(tt.name, 3), func(t *testing.T) {
if got := tt.f.Check(tt.hash); got != true {
Expand All @@ -49,3 +49,11 @@ func TestFilter_Check(t *testing.T) {
}
f.Stop()
}
func TestFilter_CheckDisabled(t *testing.T) {
f := NewFilter(0, time.Millisecond)
for i := 0; i < 100; i++ {
if !f.Check("foo") {
t.Errorf("Case %d returned false for disabled filter", i)
}
}
}

0 comments on commit eaaf4fd

Please sign in to comment.