From 62f2a095a1ad10eba03dc71f5c26959c4e5c5445 Mon Sep 17 00:00:00 2001
From: Leo Balduf <balduf@hm.edu>
Date: Wed, 17 Aug 2016 17:11:11 -0400
Subject: [PATCH] memory: fix garbage collection, add config check

---
 storage/memory/peer_store.go      | 11 ++++++++++-
 storage/memory/peer_store_test.go |  4 +++-
 2 files changed, 13 insertions(+), 2 deletions(-)

diff --git a/storage/memory/peer_store.go b/storage/memory/peer_store.go
index b53aca3..02211a1 100644
--- a/storage/memory/peer_store.go
+++ b/storage/memory/peer_store.go
@@ -2,6 +2,7 @@ package memory
 
 import (
 	"encoding/binary"
+	"errors"
 	"log"
 	"net"
 	"runtime"
@@ -12,6 +13,10 @@ import (
 	"github.com/chihaya/chihaya/storage"
 )
 
+// ErrInvalidGCInterval is returned for a GarbageCollectionInterval that is
+// less than or equal to zero.
+var ErrInvalidGCInterval = errors.New("invalid garbage collection interval")
+
 // Config holds the configuration of a memory PeerStore.
 type Config struct {
 	GarbageCollectionInterval time.Duration `yaml:"gc_interval"`
@@ -27,6 +32,10 @@ func New(cfg Config) (storage.PeerStore, error) {
 		shardCount = cfg.ShardCount
 	}
 
+	if cfg.GarbageCollectionInterval <= 0 {
+		return nil, ErrInvalidGCInterval
+	}
+
 	ps := &peerStore{
 		shards:     make([]*peerShard, shardCount*2),
 		closed:     make(chan struct{}),
@@ -43,7 +52,7 @@ func New(cfg Config) (storage.PeerStore, error) {
 			case <-ps.closed:
 				return
 			case <-time.After(cfg.GarbageCollectionInterval):
-				before := time.Now().Add(-cfg.GarbageCollectionInterval)
+				before := time.Now().Add(-cfg.PeerLifetime)
 				log.Println("memory: purging peers with no announces since ", before)
 				ps.collectGarbage(before)
 			}
diff --git a/storage/memory/peer_store_test.go b/storage/memory/peer_store_test.go
index 677fd53..aed60d2 100644
--- a/storage/memory/peer_store_test.go
+++ b/storage/memory/peer_store_test.go
@@ -3,11 +3,13 @@ package memory
 import (
 	"testing"
 
+	"time"
+
 	s "github.com/chihaya/chihaya/storage"
 )
 
 func createNew() s.PeerStore {
-	ps, err := New(Config{ShardCount: 1024})
+	ps, err := New(Config{ShardCount: 1024, GarbageCollectionInterval: 10 * time.Minute})
 	if err != nil {
 		panic(err)
 	}