Accept parent ctx in constructor, simplify TTL loop

This commit is contained in:
Cole Brown 2018-06-11 19:54:17 -04:00
parent 04773c03ee
commit 2d0ebcedd7
2 changed files with 7 additions and 10 deletions

View File

@ -18,10 +18,10 @@ type DatastoreAddrManager struct {
addrSubs map[peer.ID][]*addrSub addrSubs map[peer.ID][]*addrSub
} }
func NewDatastoreAddrManager(ds ds.Datastore, ttlInterval time.Duration) *DatastoreAddrManager { func NewDatastoreAddrManager(ctx context.Context, ds ds.Datastore, ttlInterval time.Duration) *DatastoreAddrManager {
mgr := &DatastoreAddrManager{ mgr := &DatastoreAddrManager{
ds: ds, ds: ds,
ttlManager: newTTLManager(context.Background(), ds, ttlInterval), ttlManager: newTTLManager(ctx, ds, ttlInterval),
addrSubs: make(map[peer.ID][]*addrSub), addrSubs: make(map[peer.ID][]*addrSub),
} }
return mgr return mgr
@ -158,20 +158,16 @@ func newTTLManager(parent context.Context, d ds.Datastore, tick time.Duration) *
} }
go func() { go func() {
stop := false
for { for {
select { select {
case <-mgr.ctx.Done(): case <-mgr.ctx.Done():
stop = true mgr.ticker.Stop()
mgr.done <- struct{}{}
return
case <-mgr.ticker.C: case <-mgr.ticker.C:
mgr.tick() mgr.tick()
} }
if stop {
break
}
} }
mgr.done <- struct{}{}
}() }()
return mgr return mgr

View File

@ -10,6 +10,7 @@ import (
"github.com/ipfs/go-ds-badger" "github.com/ipfs/go-ds-badger"
"github.com/libp2p/go-libp2p-peer" "github.com/libp2p/go-libp2p-peer"
ma "github.com/multiformats/go-multiaddr" ma "github.com/multiformats/go-multiaddr"
"context"
) )
func IDS(t *testing.T, ids string) peer.ID { func IDS(t *testing.T, ids string) peer.ID {
@ -77,7 +78,7 @@ func setupDatastoreAddrManager(t *testing.T) (*DatastoreAddrManager, func()) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
mgr := NewDatastoreAddrManager(ds, 100*time.Microsecond) mgr := NewDatastoreAddrManager(context.Background(), ds, 100*time.Microsecond)
closer := func() { closer := func() {
mgr.Stop() mgr.Stop()
ds.Close() ds.Close()