Skip to content

Commit a92f79b

Browse files
authored
Merge pull request #477 from libp2p/feat/cancel-dht-context
Close context correctly
2 parents da53c0b + 1442210 commit a92f79b

File tree

2 files changed

+37
-9
lines changed

2 files changed

+37
-9
lines changed

dht.go

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -111,12 +111,6 @@ func New(ctx context.Context, h host.Host, options ...opts.Option) (*IpfsDHT, er
111111
// register for network notifs.
112112
dht.host.Network().Notify((*netNotifiee)(dht))
113113

114-
dht.proc = goprocessctx.WithContextAndTeardown(ctx, func() error {
115-
// remove ourselves from network notifs.
116-
dht.host.Network().StopNotify((*netNotifiee)(dht))
117-
return nil
118-
})
119-
120114
dht.proc.AddChild(dht.providers.Process())
121115
dht.Validator = cfg.Validator
122116

@@ -172,16 +166,26 @@ func makeDHT(ctx context.Context, h host.Host, cfg *opts.Options) *IpfsDHT {
172166
peerstore: h.Peerstore(),
173167
host: h,
174168
strmap: make(map[peer.ID]*messageSender),
175-
ctx: ctx,
176-
providers: providers.NewProviderManager(ctx, h.ID(), cfg.Datastore),
177169
birth: time.Now(),
178170
routingTable: rt,
179171
protocols: cfg.Protocols,
180172
bucketSize: cfg.BucketSize,
181173
triggerRtRefresh: make(chan chan<- error),
182174
}
183175

184-
dht.ctx = dht.newContextWithLocalTags(ctx)
176+
// create a DHT proc with the given teardown
177+
dht.proc = goprocess.WithTeardown(func() error {
178+
// remove ourselves from network notifs.
179+
dht.host.Network().StopNotify((*netNotifiee)(dht))
180+
return nil
181+
})
182+
183+
// create a tagged context derived from the original context
184+
ctxTags := dht.newContextWithLocalTags(ctx)
185+
// the DHT context should be done when the process is closed
186+
dht.ctx = goprocessctx.WithProcessClosing(ctxTags, dht.proc)
187+
188+
dht.providers = providers.NewProviderManager(dht.ctx, h.ID(), cfg.Datastore)
185189

186190
return dht
187191
}

dht_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,30 @@ func TestValueSetInvalid(t *testing.T) {
402402
testSetGet("valid", true, "newer", nil)
403403
}
404404

405+
func TestContextShutDown(t *testing.T) {
406+
ctx, cancel := context.WithCancel(context.Background())
407+
defer cancel()
408+
409+
dht := setupDHT(ctx, t, false)
410+
411+
// context is alive
412+
select {
413+
case <-dht.Context().Done():
414+
t.Fatal("context should not be done")
415+
default:
416+
}
417+
418+
// shut down dht
419+
require.NoError(t, dht.Close())
420+
421+
// now context should be done
422+
select {
423+
case <-dht.Context().Done():
424+
default:
425+
t.Fatal("context should be done")
426+
}
427+
}
428+
405429
func TestSearchValue(t *testing.T) {
406430
ctx, cancel := context.WithCancel(context.Background())
407431
defer cancel()

0 commit comments

Comments
 (0)