chore: apply suggestions from code review

Co-authored-by: Irakli Gozalishvili <contact@gozala.io>
This commit is contained in:
Vasco Santos 2021-04-20 11:23:31 +02:00
parent 828a32d4f5
commit 3ffeb4ebe6
3 changed files with 18 additions and 6 deletions

View File

@ -31,6 +31,7 @@ const {
*
* @typedef {Object} AutoRelayOptions
* @property {number} [maxListeners = 1] - maximum number of relays to listen.
* @property {(error: Error, msg?: string) => {}} [onError]
*/
class AutoRelay {
@ -40,7 +41,7 @@ class AutoRelay {
* @class
* @param {AutoRelayProperties & AutoRelayOptions} props
*/
constructor ({ libp2p, maxListeners = 1 }) {
constructor ({ libp2p, maxListeners = 1, onError }) {
this._libp2p = libp2p
this._peerId = libp2p.peerId
this._peerStore = libp2p.peerStore
@ -60,6 +61,15 @@ class AutoRelay {
this._peerStore.on('change:protocols', this._onProtocolChange)
this._connectionManager.on('peer:disconnect', this._onPeerDisconnected)
/**
* @param {Error} error
* @param {string} [msg]
*/
this._onError = (error, msg) => {
log.error(msg || error)
onError && onError(error, msg)
}
}
/**
@ -107,7 +117,7 @@ class AutoRelay {
await this._addListenRelay(connection, id)
}
} catch (err) {
log.error(err)
this._onError(err)
}
}
@ -160,7 +170,7 @@ class AutoRelay {
await this._transportManager.listen([new Multiaddr(listenAddr)])
// Announce multiaddrs will update on listen success by TransportManager event being triggered
} catch (err) {
log.error(err)
this._onError(err)
this._listenRelays.delete(id)
}
}
@ -258,7 +268,7 @@ class AutoRelay {
}
}
} catch (err) {
log.error(err)
this._onError(err)
}
}
@ -270,7 +280,7 @@ class AutoRelay {
const connection = await this._libp2p.dial(peerId)
await this._addListenRelay(connection, peerId.toB58String())
} catch (err) {
log.error(`could not connect and listen on known hop relay ${peerId.toB58String()}`)
this._onError(err, `could not connect and listen on known hop relay ${peerId.toB58String()}`)
}
}
}

View File

@ -229,7 +229,7 @@ class AddressBook extends Book {
const addresses = this._toAddresses(multiaddrs)
const id = peerId.toB58String()
// Not add unavailable addresses
// No addresses to be added
if (!addresses.length) {
return this
}

View File

@ -359,6 +359,7 @@ describe('auto-relay', () => {
expect(relayLibp2p1.connectionManager.size).to.equal(1)
// Spy on dial
sinon.spy(autoRelay1, '_tryToListenOnRelay')
sinon.spy(relayLibp2p1, 'dial')
// Remove peer used as relay from peerStore and disconnect it
@ -369,6 +370,7 @@ describe('auto-relay', () => {
// Wait for other peer connected to be added as listen addr
await pWaitFor(() => relayLibp2p1.transportManager.listen.callCount === 2)
expect(autoRelay1._tryToListenOnRelay.callCount).to.equal(1)
expect(autoRelay1._listenRelays.size).to.equal(1)
expect(relayLibp2p1.connectionManager.size).to.eql(1)
})