Skip to content
This repository has been archived by the owner on Mar 10, 2020. It is now read-only.

refactor: convert swarm API to async/await #1172

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 16 additions & 24 deletions src/swarm/addrs.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,25 @@
'use strict'

const promisify = require('promisify-es6')
const PeerInfo = require('peer-info')
const PeerId = require('peer-id')
const multiaddr = require('multiaddr')
const configure = require('../lib/configure')

module.exports = (send) => {
return promisify((opts, callback) => {
if (typeof (opts) === 'function') {
callback = opts
opts = {}
}
send({
path: 'swarm/addrs',
qs: opts
}, (err, result) => {
if (err) {
return callback(err)
}
module.exports = configure(({ ky }) => {
return async options => {
options = options || {}

const peers = Object.keys(result.Addrs).map((id) => {
const peerInfo = new PeerInfo(PeerId.createFromB58String(id))
result.Addrs[id].forEach((addr) => {
peerInfo.multiaddrs.add(multiaddr(addr))
})
return peerInfo
})
const res = await ky.post('swarm/addrs', {
timeout: options.timeout,
signal: options.signal,
headers: options.headers,
searchParams: options.searchParams
}).json()

callback(null, peers)
return Object.keys(res.Addrs).map(id => {
const peerInfo = new PeerInfo(PeerId.createFromB58String(id))
res.Addrs[id].forEach(addr => peerInfo.multiaddrs.add(multiaddr(addr)))
return peerInfo
})
})
}
}
})
33 changes: 19 additions & 14 deletions src/swarm/connect.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
'use strict'

const promisify = require('promisify-es6')
const configure = require('../lib/configure')

module.exports = (send) => {
return promisify((args, opts, callback) => {
if (typeof (opts) === 'function') {
callback = opts
opts = {}
}
send({
path: 'swarm/connect',
args: args,
qs: opts
}, callback)
})
}
module.exports = configure(({ ky }) => {
return async (addrs, options) => {
addrs = Array.isArray(addrs) ? addrs : [addrs]
options = options || {}

const searchParams = new URLSearchParams(options.searchParams)
addrs.forEach(addr => searchParams.append('arg', addr))

const res = await ky.post('swarm/connect', {
timeout: options.timeout,
signal: options.signal,
headers: options.headers,
searchParams
}).json()

return res.Strings || []
}
})
33 changes: 19 additions & 14 deletions src/swarm/disconnect.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
'use strict'

const promisify = require('promisify-es6')
const configure = require('../lib/configure')

module.exports = (send) => {
return promisify((args, opts, callback) => {
if (typeof (opts) === 'function') {
callback = opts
opts = {}
}
send({
path: 'swarm/disconnect',
args: args,
qs: opts
}, callback)
})
}
module.exports = configure(({ ky }) => {
return async (addrs, options) => {
addrs = Array.isArray(addrs) ? addrs : [addrs]
options = options || {}

const searchParams = new URLSearchParams(options.searchParams)
addrs.forEach(addr => searchParams.append('arg', addr))

const res = await ky.post('swarm/disconnect', {
timeout: options.timeout,
signal: options.signal,
headers: options.headers,
searchParams
}).json()

return res.Strings || []
}
})
20 changes: 8 additions & 12 deletions src/swarm/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
'use strict'

const moduleConfig = require('../utils/module-config')
const callbackify = require('callbackify')

module.exports = (arg) => {
const send = moduleConfig(arg)

return {
peers: require('./peers')(send),
connect: require('./connect')(send),
disconnect: require('./disconnect')(send),
addrs: require('./addrs')(send),
localAddrs: require('./localAddrs')(send)
}
}
module.exports = config => ({
addrs: callbackify.variadic(require('./addrs')(config)),
connect: callbackify.variadic(require('./connect')(config)),
disconnect: callbackify.variadic(require('./disconnect')(config)),
localAddrs: callbackify.variadic(require('./localAddrs')(config)),
peers: callbackify.variadic(require('./peers')(config))
})
38 changes: 18 additions & 20 deletions src/swarm/localAddrs.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
'use strict'

const promisify = require('promisify-es6')
const multiaddr = require('multiaddr')
const configure = require('../lib/configure')

module.exports = (send) => {
return promisify((opts, callback) => {
if (typeof (opts) === 'function') {
callback = opts
opts = {}
}
send({
path: 'swarm/addrs/local',
qs: opts
}, (err, result) => {
if (err) {
return callback(err)
}
callback(null, result.Strings.map((addr) => {
return multiaddr(addr)
}))
})
})
}
module.exports = configure(({ ky }) => {
return async options => {
options = options || {}

const searchParams = new URLSearchParams(options.searchParams)
if (options.id != null) searchParams.append('id', options.id)

const res = await ky.post('swarm/addrs/local', {
timeout: options.timeout,
signal: options.signal,
headers: options.headers,
searchParams
}).json()

return (res.Strings || []).map(a => multiaddr(a))
}
})
104 changes: 39 additions & 65 deletions src/swarm/peers.js
Original file line number Diff line number Diff line change
@@ -1,74 +1,48 @@
'use strict'

const promisify = require('promisify-es6')
const multiaddr = require('multiaddr')
const PeerId = require('peer-id')
const configure = require('../lib/configure')

module.exports = (send) => {
return promisify((opts, callback) => {
if (typeof (opts) === 'function') {
callback = opts
opts = {}
}
const verbose = opts.v || opts.verbose
send({
path: 'swarm/peers',
qs: opts
}, (err, response) => {
if (err) {
return callback(err)
}
const peerInfo = parsePeersResponse(verbose, response)
callback(null, peerInfo)
})
})
}
module.exports = configure(({ ky }) => {
return async options => {
options = options || {}

function parsePeersResponse (verbose, response) {
// go-ipfs <= 0.4.4
if (Array.isArray(response.Strings)) {
return response.Strings.map(parseLegacyPeer.bind(null, verbose))
}
// go-ipfs >= 0.4.5
if (Array.isArray(response.Peers)) {
return response.Peers.map(parsePeer.bind(null, verbose))
}
return []
}
const searchParams = new URLSearchParams(options.searchParams)
if (options.direction != null) searchParams.append('direction', options.direction)
if (options.latency != null) searchParams.append('latency', options.latency)
if (options.streams != null) searchParams.append('streams', options.streams)
if (options.verbose != null) searchParams.append('verbose', options.verbose)

function parseLegacyPeer (verbose, peer) {
const res = {}
try {
if (verbose) {
const parts = peer.split(' ')
res.addr = multiaddr(parts[0])
res.latency = parts[1]
} else {
res.addr = multiaddr(peer)
}
res.peer = PeerId.createFromB58String(res.addr.getPeerId())
} catch (error) {
res.error = error
res.rawPeerInfo = peer
}
return res
}
const res = await ky.post('swarm/peers', {
timeout: options.timeout,
signal: options.signal,
headers: options.headers,
searchParams
}).json()

function parsePeer (verbose, peer) {
const res = {}
try {
res.addr = multiaddr(peer.Addr)
res.peer = PeerId.createFromB58String(peer.Peer)
res.muxer = peer.Muxer
} catch (error) {
res.error = error
res.rawPeerInfo = peer
}
if (peer.Latency) {
res.latency = peer.Latency
}
if (peer.Streams) {
res.streams = peer.Streams
return (res.Peers || []).map(peer => {
const info = {}
try {
info.addr = multiaddr(peer.Addr)
info.peer = PeerId.createFromB58String(peer.Peer)
} catch (error) {
info.error = error
info.rawPeerInfo = peer
}
if (peer.Muxer) {
info.muxer = peer.Muxer
}
if (peer.Latency) {
info.latency = peer.Latency
}
if (peer.Streams) {
info.streams = peer.Streams
}
if (peer.Direction != null) {
info.direction = peer.Direction
}
return info
})
}
return res
}
})
2 changes: 1 addition & 1 deletion src/utils/load-commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ function requireCommands (send, config) {
refsReadableStream: streamify.readable(refs),
refsPullStream: pullify.source(refs),
_refsAsyncIterator: refs,
swarm: require('../swarm')(config),
getEndpointConfig: require('../get-endpoint-config')(config),
bitswap: require('../bitswap')(config),
block: require('../block')(config),
Expand All @@ -132,7 +133,6 @@ function requireCommands (send, config) {
ping: require('../ping'),
pingReadableStream: require('../ping-readable-stream'),
pingPullStream: require('../ping-pull-stream'),
swarm: require('../swarm'),
pubsub: require('../pubsub'),
dns: require('../dns'),

Expand Down
18 changes: 0 additions & 18 deletions test/node/swarm.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,24 +29,6 @@ describe('.swarm.peers', function () {
expect(scope.isDone()).to.equal(true)
})

it('handles a go-ipfs <= 0.4.4 peer response', async () => {
const response = { Strings: ['/ip4/73.109.217.59/tcp/49311/ipfs/QmWjxEGC7BthJrCf7QTModrcsRweHbupdPTY4oGMVoDZXm'] }

const scope = nock(apiUrl)
.post('/api/v0/swarm/peers')
.query(true)
.reply(200, response)

const res = await ipfs.swarm.peers()

expect(res).to.be.a('array')
expect(res.length).to.equal(1)
expect(res[0].error).to.not.exist()
expect(res[0].addr.toString()).to.equal('/ip4/73.109.217.59/tcp/49311/ipfs/QmWjxEGC7BthJrCf7QTModrcsRweHbupdPTY4oGMVoDZXm')
expect(res[0].peer.toB58String()).to.equal('QmWjxEGC7BthJrCf7QTModrcsRweHbupdPTY4oGMVoDZXm')
expect(scope.isDone()).to.equal(true)
})

it('handles an ip6 quic peer', async () => {
const response = { Peers: [{ Addr: '/ip6/2001:8a0:7ac5:4201:3ac9:86ff:fe31:7095/udp/4001/quic', Peer: 'QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC', Latency: '', Muxer: '', Streams: null }] }

Expand Down