Skip to content

Commit 4222c49

Browse files
Alan Shawjacobheun
Alan Shaw
andcommitted
fix: stop discoveries (#530)
* fix: stop discoveries * test: add discovery stop test * chore: fix lint Co-authored-by: Jacob Heun <jacobheun@gmail.com>
1 parent 2f2ba42 commit 4222c49

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/index.js

+7
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,14 @@ class Libp2p extends EventEmitter {
218218
log('libp2p is stopping')
219219

220220
try {
221+
for (const service of this._discovery.values()) {
222+
service.removeListener('peer', this._onDiscoveryPeer)
223+
}
224+
225+
await Promise.all(Array.from(this._discovery.values(), s => s.stop()))
226+
221227
this.connectionManager.stop()
228+
222229
await Promise.all([
223230
this.pubsub && this.pubsub.stop(),
224231
this._dht && this._dht.stop(),

test/peer-discovery/index.spec.js

+26
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,32 @@ describe('peer discovery', () => {
6565

6666
expect(discoverySpy.called).to.eql(false)
6767
})
68+
69+
it('should stop discovery on libp2p start/stop', async () => {
70+
const mockDiscovery = {
71+
tag: 'mock',
72+
start: () => {},
73+
stop: () => {},
74+
on: () => {},
75+
removeListener: () => {}
76+
}
77+
const startSpy = sinon.spy(mockDiscovery, 'start')
78+
const stopSpy = sinon.spy(mockDiscovery, 'stop')
79+
80+
libp2p = new Libp2p(mergeOptions(baseOptions, {
81+
peerInfo,
82+
modules: {
83+
peerDiscovery: [mockDiscovery]
84+
}
85+
}))
86+
87+
await libp2p.start()
88+
expect(startSpy).to.have.property('callCount', 1)
89+
expect(stopSpy).to.have.property('callCount', 0)
90+
await libp2p.stop()
91+
expect(startSpy).to.have.property('callCount', 1)
92+
expect(stopSpy).to.have.property('callCount', 1)
93+
})
6894
})
6995

7096
describe('discovery modules from transports', () => {

0 commit comments

Comments
 (0)