Skip to content
This repository has been archived by the owner on Feb 12, 2024. It is now read-only.

Commit

Permalink
refactor: convert ping API to async/await (#2671)
Browse files Browse the repository at this point in the history
  • Loading branch information
Alan Shaw authored Dec 13, 2019
1 parent 21e62cb commit 0921a82
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 120 deletions.
1 change: 1 addition & 0 deletions src/core/components/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
exports.add = require('./add')
exports.config = require('./config')
exports.init = require('./init')
exports.ping = require('./ping')
exports.start = require('./start')
exports.stop = require('./stop')

Expand Down
100 changes: 0 additions & 100 deletions src/core/components/ping-pull-stream.js

This file was deleted.

7 changes: 0 additions & 7 deletions src/core/components/ping-readable-stream.js

This file was deleted.

52 changes: 39 additions & 13 deletions src/core/components/ping.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,44 @@
'use strict'

const promisify = require('promisify-es6')
const pull = require('pull-stream/pull')

module.exports = function ping (self) {
return promisify((peerId, opts, callback) => {
if (typeof opts === 'function') {
callback = opts
opts = {}
const PeerId = require('peer-id')
const basePacket = { success: true, time: 0, text: '' }

module.exports = ({ libp2p }) => {
return async function * (peerId, options) {
options = options || {}
options.count = options.count || 10

if (!PeerId.isPeerId(peerId)) {
peerId = PeerId.createFromCID(peerId)
}

pull(
self.pingPullStream(peerId, opts),
pull.collect(callback)
)
})
let peerInfo
if (libp2p.peerStore.has(peerId)) {
peerInfo = libp2p.peerStore.get(peerId)
} else {
yield { ...basePacket, text: `Looking up peer ${peerId}` }
peerInfo = await libp2p.peerRouting.findPeer(peerId)
}

yield { ...basePacket, text: `PING ${peerInfo.id.toB58String()}` }

let packetCount = 0
let totalTime = 0

for (let i = 0; i < options.count; i++) {
try {
const time = libp2p.ping(peerInfo)
totalTime += time
packetCount++
yield { ...basePacket, time }
} catch (err) {
yield { ...basePacket, success: false, text: err.toString() }
}
}

if (packetCount) {
const average = totalTime / packetCount
yield { ...basePacket, text: `Average latency: ${average}ms` }
}
}
}
1 change: 1 addition & 0 deletions src/core/components/start.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ function createApi ({
add,
config: Commands.config({ repo }),
init: () => { throw new AlreadyInitializedError() },
ping: Commands.ping({ libp2p }),
start: () => apiManager.api,
stop
}
Expand Down

0 comments on commit 0921a82

Please sign in to comment.