chore: address review

This commit is contained in:
Vasco Santos
2020-11-25 17:58:52 +01:00
parent 26c40c8dfd
commit 7e05c4a43b
25 changed files with 138 additions and 91 deletions

View File

@ -61,7 +61,7 @@
"it-pipe": "^1.1.0", "it-pipe": "^1.1.0",
"it-protocol-buffers": "^0.2.0", "it-protocol-buffers": "^0.2.0",
"libp2p-crypto": "^0.18.0", "libp2p-crypto": "^0.18.0",
"libp2p-interfaces": "^0.7.2", "libp2p-interfaces": "libp2p/js-libp2p-interfaces#chore/add-duplex-iterable-type-to-connection",
"libp2p-utils": "^0.2.2", "libp2p-utils": "^0.2.2",
"mafmt": "^8.0.0", "mafmt": "^8.0.0",
"merge-options": "^2.0.0", "merge-options": "^2.0.0",

View File

@ -6,10 +6,14 @@ log.error = debug('libp2p:addresses:error')
const multiaddr = require('multiaddr') const multiaddr = require('multiaddr')
/**
* @typedef {import('multiaddr')} Multiaddr
*/
/** /**
* @typedef {Object} AddressManagerOptions * @typedef {Object} AddressManagerOptions
* @property {Array<string>} [listen = []] - list of multiaddrs string representation to listen. * @property {string[]} [listen = []] - list of multiaddrs string representation to listen.
* @property {Array<string>} [announce = []] - list of multiaddrs string representation to announce. * @property {string[]} [announce = []] - list of multiaddrs string representation to announce.
*/ */
class AddressManager { class AddressManager {
/** /**
@ -29,7 +33,7 @@ class AddressManager {
/** /**
* Get peer listen multiaddrs. * Get peer listen multiaddrs.
* *
* @returns {Array<multiaddr>} * @returns {Multiaddr[]}
*/ */
getListenAddrs () { getListenAddrs () {
return Array.from(this.listen).map((a) => multiaddr(a)) return Array.from(this.listen).map((a) => multiaddr(a))
@ -38,7 +42,7 @@ class AddressManager {
/** /**
* Get peer announcing multiaddrs. * Get peer announcing multiaddrs.
* *
* @returns {Array<multiaddr>} * @returns {Multiaddr[]}
*/ */
getAnnounceAddrs () { getAnnounceAddrs () {
return Array.from(this.announce).map((a) => multiaddr(a)) return Array.from(this.announce).map((a) => multiaddr(a))

View File

@ -69,7 +69,7 @@ class AutoRelay {
* *
* @param {Object} props * @param {Object} props
* @param {PeerId} props.peerId * @param {PeerId} props.peerId
* @param {Array<string>} props.protocols * @param {string[]} props.protocols
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async _onProtocolChange ({ peerId, protocols }) { async _onProtocolChange ({ peerId, protocols }) {
@ -182,7 +182,7 @@ class AutoRelay {
* 2. Dial and try to listen on the peers we know that support hop but are not connected. * 2. Dial and try to listen on the peers we know that support hop but are not connected.
* 3. Search the network. * 3. Search the network.
* *
* @param {Array<string>} [peersToIgnore] * @param {string[]} [peersToIgnore]
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async _listenOnAvailableHopRelays (peersToIgnore = []) { async _listenOnAvailableHopRelays (peersToIgnore = []) {

View File

@ -18,14 +18,19 @@ const { handleCanHop, handleHop, hop } = require('./circuit/hop')
const { handleStop } = require('./circuit/stop') const { handleStop } = require('./circuit/stop')
const StreamHandler = require('./circuit/stream-handler') const StreamHandler = require('./circuit/stream-handler')
/**
* @typedef {import('multiaddr')} Multiaddr
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
*/
class Circuit { class Circuit {
/** /**
* Creates an instance of the Circuit Transport. * Creates an instance of the Circuit Transport.
* *
* @class * @class
* @param {object} options * @param {object} options
* @param {Libp2p} options.libp2p * @param {import('../')} options.libp2p
* @param {Upgrader} options.upgrader * @param {import('../upgrader')} options.upgrader
*/ */
constructor ({ libp2p, upgrader }) { constructor ({ libp2p, upgrader }) {
this._dialer = libp2p.dialer this._dialer = libp2p.dialer
@ -101,7 +106,7 @@ class Circuit {
/** /**
* Dial a peer over a relay * Dial a peer over a relay
* *
* @param {multiaddr} ma - the multiaddr of the peer to dial * @param {Multiaddr} ma - the multiaddr of the peer to dial
* @param {Object} options - dial options * @param {Object} options - dial options
* @param {AbortSignal} [options.signal] - An optional abort signal * @param {AbortSignal} [options.signal] - An optional abort signal
* @returns {Connection} - the connection * @returns {Connection} - the connection
@ -176,8 +181,8 @@ class Circuit {
/** /**
* Filter check for all Multiaddrs that this transport can dial on * Filter check for all Multiaddrs that this transport can dial on
* *
* @param {Array<Multiaddr>} multiaddrs * @param {Multiaddr[]} multiaddrs
* @returns {Array<Multiaddr>} * @returns {Multiaddr[]}
*/ */
filter (multiaddrs) { filter (multiaddrs) {
multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs] multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]

View File

@ -51,7 +51,7 @@ const defaultOptions = {
*/ */
/** /**
* @extends {EventEmitter} * @extends EventEmitter
* *
* @fires ConnectionManager#peer:connect Emitted when a new peer is connected. * @fires ConnectionManager#peer:connect Emitted when a new peer is connected.
* @fires ConnectionManager#peer:disconnect Emitted when a peer is disconnected. * @fires ConnectionManager#peer:disconnect Emitted when a peer is disconnected.
@ -87,7 +87,7 @@ class ConnectionManager extends EventEmitter {
/** /**
* Map of connections per peer * Map of connections per peer
* *
* @type {Map<string, Array<Connection>>} * @type {Map<string, Connection[]>}
*/ */
this.connections = new Map() this.connections = new Map()
@ -168,6 +168,7 @@ class ConnectionManager extends EventEmitter {
* *
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {number} value - A number between 0 and 1 * @param {number} value - A number between 0 and 1
* @returns {void}
*/ */
setPeerValue (peerId, value) { setPeerValue (peerId, value) {
if (value < 0 || value > 1) { if (value < 0 || value > 1) {
@ -201,6 +202,7 @@ class ConnectionManager extends EventEmitter {
* Tracks the incoming connection and check the connection limit * Tracks the incoming connection and check the connection limit
* *
* @param {Connection} connection * @param {Connection} connection
* @returns {void}
*/ */
onConnect (connection) { onConnect (connection) {
const peerId = connection.remotePeer const peerId = connection.remotePeer
@ -227,6 +229,7 @@ class ConnectionManager extends EventEmitter {
* Removes the connection from tracking * Removes the connection from tracking
* *
* @param {Connection} connection * @param {Connection} connection
* @returns {void}
*/ */
onDisconnect (connection) { onDisconnect (connection) {
const peerId = connection.remotePeer.toB58String() const peerId = connection.remotePeer.toB58String()
@ -260,7 +263,7 @@ class ConnectionManager extends EventEmitter {
* Get all open connections with a peer. * Get all open connections with a peer.
* *
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Array<Connection>} * @returns {Connection[]}
*/ */
getAll (peerId) { getAll (peerId) {
if (!PeerId.isPeerId(peerId)) { if (!PeerId.isPeerId(peerId)) {

View File

@ -8,7 +8,13 @@ const pAny = require('p-any')
/** /**
* @typedef {import('peer-id')} PeerId * @typedef {import('peer-id')} PeerId
* @typedef {import('multiaddr')} multiaddr * @typedef {import('multiaddr')} Multiaddr
*/
/**
* @typedef {Object} GetData
* @property {PeerId} from
* @property {Uint8Array} val
*/ */
module.exports = (node) => { module.exports = (node) => {
@ -29,7 +35,7 @@ module.exports = (node) => {
* @param {object} [options] * @param {object} [options]
* @param {number} [options.timeout] - How long the query should run * @param {number} [options.timeout] - How long the query should run
* @param {number} [options.maxNumProviders] - maximum number of providers to find * @param {number} [options.maxNumProviders] - maximum number of providers to find
* @returns {AsyncIterable<{ id: PeerId, multiaddrs: Array<multiaddr> }>} * @returns {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>}
*/ */
async * findProviders (key, options) { async * findProviders (key, options) {
if (!routers.length) { if (!routers.length) {
@ -91,7 +97,7 @@ module.exports = (node) => {
* @param {Uint8Array} key * @param {Uint8Array} key
* @param {Object} [options] - get options * @param {Object} [options] - get options
* @param {number} [options.timeout] - optional timeout (default: 60000) * @param {number} [options.timeout] - optional timeout (default: 60000)
* @returns {Promise<{from: PeerId, val: Uint8Array}>} * @returns {Promise<GetData>}
*/ */
async get (key, options) { // eslint-disable-line require-await async get (key, options) { // eslint-disable-line require-await
if (!node.isStarted() || !dht.isStarted) { if (!node.isStarted() || !dht.isStarted) {
@ -108,7 +114,7 @@ module.exports = (node) => {
* @param {number} nVals * @param {number} nVals
* @param {Object} [options] - get options * @param {Object} [options] - get options
* @param {number} [options.timeout] - optional timeout (default: 60000) * @param {number} [options.timeout] - optional timeout (default: 60000)
* @returns {Promise<Array<{from: PeerId, val: Uint8Array}>>} * @returns {Promise<GetData[]>}
*/ */
async getMany (key, nVals, options) { // eslint-disable-line require-await async getMany (key, nVals, options) { // eslint-disable-line require-await
if (!node.isStarted() || !dht.isStarted) { if (!node.isStarted() || !dht.isStarted) {

View File

@ -11,6 +11,7 @@ const pAny = require('p-any')
/** /**
* @typedef {import('./')} Dialer * @typedef {import('./')} Dialer
* @typedef {import('multiaddr')} Multiaddr
*/ */
/** /**

View File

@ -20,6 +20,7 @@ const {
} = require('../constants') } = require('../constants')
/** /**
* @typedef {import('multiaddr')} Multiaddr
* @typedef {import('peer-id')} PeerId * @typedef {import('peer-id')} PeerId
* @typedef {import('../peer-store')} PeerStore * @typedef {import('../peer-store')} PeerStore
* @typedef {import('../transport-manager')} TransportManager * @typedef {import('../transport-manager')} TransportManager
@ -32,7 +33,7 @@ const {
* @property {TransportManager} transportManager * @property {TransportManager} transportManager
* *
* @typedef {Object} DialerOptions * @typedef {Object} DialerOptions
* @param {(addresses: Array<Address) => Array<Address>} [options.addressSorter = publicAddressesFirst] - Sort the known addresses of a peer before trying to dial. * @param {(addresses: Address[]) => Address[]} [options.addressSorter = publicAddressesFirst] - Sort the known addresses of a peer before trying to dial.
* @property {number} [concurrency = MAX_PARALLEL_DIALS] - Number of max concurrent dials. * @property {number} [concurrency = MAX_PARALLEL_DIALS] - Number of max concurrent dials.
* @property {number} [perPeerLimit = MAX_PER_PEER_DIALS] - Number of max concurrent dials per peer. * @property {number} [perPeerLimit = MAX_PER_PEER_DIALS] - Number of max concurrent dials per peer.
* @property {number} [timeout = DIAL_TIMEOUT] - How long a dial attempt is allowed to take. * @property {number} [timeout = DIAL_TIMEOUT] - How long a dial attempt is allowed to take.
@ -40,7 +41,7 @@ const {
* *
* @typedef DialTarget * @typedef DialTarget
* @property {string} id * @property {string} id
* @property {Array<multiaddr>} addrs * @property {Multiaddr[]} addrs
* *
* @typedef PendingDial * @typedef PendingDial
* @property {DialRequest} dialRequest * @property {DialRequest} dialRequest
@ -96,7 +97,7 @@ class Dialer {
* The dial to the first address that is successfully able to upgrade a connection * The dial to the first address that is successfully able to upgrade a connection
* will be used. * will be used.
* *
* @param {PeerId|multiaddr|string} peer - The peer to dial * @param {PeerId|Multiaddr|string} peer - The peer to dial
* @param {object} [options] * @param {object} [options]
* @param {AbortSignal} [options.signal] - An AbortController signal * @param {AbortSignal} [options.signal] - An AbortController signal
* @returns {Promise<Connection>} * @returns {Promise<Connection>}
@ -131,7 +132,7 @@ class Dialer {
* If a multiaddr is received it should be the first address attempted. * If a multiaddr is received it should be the first address attempted.
* *
* @private * @private
* @param {PeerId|multiaddr|string} peer - A PeerId or Multiaddr * @param {PeerId|Multiaddr|string} peer - A PeerId or Multiaddr
* @returns {Promise<DialTarget>} * @returns {Promise<DialTarget>}
*/ */
async _createDialTarget (peer) { async _createDialTarget (peer) {
@ -219,8 +220,8 @@ class Dialer {
/** /**
* Resolve multiaddr recursively. * Resolve multiaddr recursively.
* *
* @param {multiaddr} ma * @param {Multiaddr} ma
* @returns {Promise<Array<multiaddr>>} * @returns {Promise<Multiaddr[]>}
*/ */
async _resolve (ma) { async _resolve (ma) {
// TODO: recursive logic should live in multiaddr once dns4/dns6 support is in place // TODO: recursive logic should live in multiaddr once dns4/dns6 support is in place
@ -248,8 +249,8 @@ class Dialer {
/** /**
* Resolve a given multiaddr. If this fails, an empty array will be returned * Resolve a given multiaddr. If this fails, an empty array will be returned
* *
* @param {multiaddr} ma * @param {Multiaddr} ma
* @returns {Promise<Array<multiaddr>>} * @returns {Promise<Multiaddr[]>}
*/ */
async _resolveRecord (ma) { async _resolveRecord (ma) {
try { try {

View File

@ -8,7 +8,7 @@ const { codes } = require('./errors')
/** /**
* @typedef {import('peer-id')} PeerId * @typedef {import('peer-id')} PeerId
* @typedef {import('multiaddr')} multiaddr * @typedef {import('multiaddr')} Multiaddr
*/ */
/** /**
@ -16,7 +16,7 @@ const { codes } = require('./errors')
* If a multiaddr is received, the addressBook is updated. * If a multiaddr is received, the addressBook is updated.
* *
* @param {PeerId|multiaddr|string} peer * @param {PeerId|multiaddr|string} peer
* @returns {{ id: PeerId, multiaddrs: Array<multiaddr> }} * @returns {{ id: PeerId, multiaddrs: Multiaddr[] }}
*/ */
function getPeer (peer) { function getPeer (peer) {
if (typeof peer === 'string') { if (typeof peer === 'string') {

View File

@ -30,16 +30,15 @@ const {
const { codes } = require('../errors') const { codes } = require('../errors')
/** /**
* @typedef {import('../')} Libp2p
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
* @typedef {import('../').DuplexIterable} DuplexIterable * @typedef {import('libp2p-interfaces/src/connection/connection').DuplexIterableStream} DuplexIterableStream
*/ */
class IdentifyService { class IdentifyService {
/** /**
* @class * @class
* @param {Object} options * @param {Object} options
* @param {Libp2p} options.libp2p * @param {import('../')} options.libp2p
*/ */
constructor ({ libp2p }) { constructor ({ libp2p }) {
this._libp2p = libp2p this._libp2p = libp2p
@ -74,7 +73,7 @@ class IdentifyService {
/** /**
* Send an Identify Push update to the list of connections * Send an Identify Push update to the list of connections
* *
* @param {Array<Connection>} connections * @param {Connection[]} connections
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async push (connections) { async push (connections) {
@ -204,7 +203,7 @@ class IdentifyService {
* *
* @param {Object} options * @param {Object} options
* @param {string} options.protocol * @param {string} options.protocol
* @param {DuplexIterable} options.stream * @param {DuplexIterableStream} options.stream
* @param {Connection} options.connection * @param {Connection} options.connection
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
@ -225,7 +224,7 @@ class IdentifyService {
* *
* @private * @private
* @param {Object} options * @param {Object} options
* @param {DuplexIterable} options.stream * @param {DuplexIterableStream} options.stream
* @param {Connection} options.connection * @param {Connection} options.connection
*/ */
async _handleIdentify ({ connection, stream }) { async _handleIdentify ({ connection, stream }) {
@ -264,7 +263,7 @@ class IdentifyService {
* *
* @private * @private
* @param {object} options * @param {object} options
* @param {DuplexIterable} options.stream * @param {DuplexIterableStream} options.stream
* @param {Connection} options.connection * @param {Connection} options.connection
*/ */
async _handlePush ({ connection, stream }) { async _handlePush ({ connection, stream }) {

View File

@ -34,6 +34,10 @@ const {
multicodecs: IDENTIFY_PROTOCOLS multicodecs: IDENTIFY_PROTOCOLS
} = require('./identify') } = require('./identify')
/**
* @typedef {import('multiaddr')} Multiaddr
*/
/** /**
* @typedef {Object} PeerStoreOptions * @typedef {Object} PeerStoreOptions
* @property {boolean} persistence * @property {boolean} persistence
@ -55,7 +59,7 @@ const {
* @property {Object} [transport] transport options indexed by transport key * @property {Object} [transport] transport options indexed by transport key
* *
* @typedef {Object} Libp2pOptions * @typedef {Object} Libp2pOptions
* @property {Array<Object>} modules libp2p modules to use * @property {Object[]} modules libp2p modules to use
* @property {import('./address-manager').AddressManagerOptions} [addresses] * @property {import('./address-manager').AddressManagerOptions} [addresses]
* @property {import('./connection-manager').ConnectionManagerOptions} [connectionManager] * @property {import('./connection-manager').ConnectionManagerOptions} [connectionManager]
* @property {import('./dialer').DialerOptions} [dialer] * @property {import('./dialer').DialerOptions} [dialer]
@ -399,7 +403,7 @@ class Libp2p extends EventEmitter {
* by transports to listen with the announce addresses. * by transports to listen with the announce addresses.
* Duplicated addresses and noAnnounce addresses are filtered out. * Duplicated addresses and noAnnounce addresses are filtered out.
* *
* @returns {Array<Multiaddr>} * @returns {Multiaddr[]}
*/ */
get multiaddrs () { get multiaddrs () {
const announceAddrs = this.addressManager.getAnnounceAddrs() const announceAddrs = this.addressManager.getAnnounceAddrs()
@ -416,7 +420,7 @@ class Libp2p extends EventEmitter {
/** /**
* Disconnects all connections to the given `peer` * Disconnects all connections to the given `peer`
* *
* @param {PeerId|multiaddr|string} peer - the peer to close connections to * @param {PeerId|Multiaddr|string} peer - the peer to close connections to
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async hangUp (peer) { async hangUp (peer) {
@ -544,7 +548,7 @@ class Libp2p extends EventEmitter {
* Known peers may be emitted. * Known peers may be emitted.
* *
* @private * @private
* @param {{ id: PeerId, multiaddrs: Array<Multiaddr>, protocols: Array<string> }} peer * @param {{ id: PeerId, multiaddrs: Multiaddr[], protocols: string[] }} peer
*/ */
_onDiscoveryPeer (peer) { _onDiscoveryPeer (peer) {
if (peer.id.toB58String() === this.peerId.toB58String()) { if (peer.id.toB58String() === this.peerId.toB58String()) {
@ -654,10 +658,4 @@ Libp2p.create = async function create (options = {}) {
return new Libp2p(options) return new Libp2p(options)
} }
/**
* @typedef {Object} DuplexIterable
* @property {(source: AsyncIterator<*>) => Promise} sink
* @property {AsyncIterator<*>} source
*/
module.exports = Libp2p module.exports = Libp2p

View File

@ -25,7 +25,7 @@ function lpEncodeExchange (exchange) {
* *
* @param {PeerId} localId * @param {PeerId} localId
* @param {Connection} conn * @param {Connection} conn
* @param {PeerId} remoteId * @param {PeerId} [remoteId]
*/ */
async function encrypt (localId, conn, remoteId) { async function encrypt (localId, conn, remoteId) {
const shake = handshake(conn) const shake = handshake(conn)

View File

@ -17,6 +17,10 @@ const directionToEvent = {
out: 'dataSent' out: 'dataSent'
} }
/**
* @typedef {import('peer-id')} PeerId
*/
/** /**
* @typedef MetricsProperties * @typedef MetricsProperties
* @property {ConnectionManager} connectionManager * @property {ConnectionManager} connectionManager
@ -24,7 +28,7 @@ const directionToEvent = {
* @typedef MetricsOptions * @typedef MetricsOptions
* @property {number} [computeThrottleMaxQueueSize = defaultOptions.computeThrottleMaxQueueSize] * @property {number} [computeThrottleMaxQueueSize = defaultOptions.computeThrottleMaxQueueSize]
* @property {number} [computeThrottleTimeout = defaultOptions.computeThrottleTimeout] * @property {number} [computeThrottleTimeout = defaultOptions.computeThrottleTimeout]
* @property {Array<number>} [movingAverageIntervals = defaultOptions.movingAverageIntervals] * @property {number[]} [movingAverageIntervals = defaultOptions.movingAverageIntervals]
* @property {number} [maxOldPeersRetention = defaultOptions.maxOldPeersRetention] * @property {number} [maxOldPeersRetention = defaultOptions.maxOldPeersRetention]
*/ */
@ -82,7 +86,7 @@ class Metrics {
/** /**
* Returns a list of `PeerId` strings currently being tracked * Returns a list of `PeerId` strings currently being tracked
* *
* @returns {Array<string>} * @returns {string[]}
*/ */
get peers () { get peers () {
return Array.from(this._peerStats.keys()) return Array.from(this._peerStats.keys())
@ -103,7 +107,7 @@ class Metrics {
/** /**
* Returns a list of all protocol strings currently being tracked. * Returns a list of all protocol strings currently being tracked.
* *
* @returns {Array<string>} * @returns {string[]}
*/ */
get protocols () { get protocols () {
return Array.from(this._protocolStats.keys()) return Array.from(this._protocolStats.keys())
@ -182,6 +186,7 @@ class Metrics {
* *
* @param {PeerId} placeholder - A peerId string * @param {PeerId} placeholder - A peerId string
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {void}
*/ */
updatePlaceholder (placeholder, peerId) { updatePlaceholder (placeholder, peerId) {
if (!this._running) return if (!this._running) return

View File

@ -8,7 +8,7 @@ const retimer = require('retimer')
/** /**
* A queue based manager for stat processing * A queue based manager for stat processing
* *
* @param {Array<string>} initialCounters * @param {string[]} initialCounters
* @param {any} options * @param {any} options
*/ */
class Stats extends EventEmitter { class Stats extends EventEmitter {
@ -77,7 +77,7 @@ class Stats extends EventEmitter {
/** /**
* Returns a clone of the internal movingAverages * Returns a clone of the internal movingAverages
* *
* @returns {Array<MovingAverage>} * @returns {MovingAverage[]}
*/ */
get movingAverages () { get movingAverages () {
return Object.assign({}, this._movingAverages) return Object.assign({}, this._movingAverages)
@ -229,7 +229,7 @@ class Stats extends EventEmitter {
* will be updated or initialized if they don't already exist. * will be updated or initialized if they don't already exist.
* *
* @private * @private
* @param {Array<string, number>} op * @param {{string, number}[]} op
* @throws {InvalidNumber} * @throws {InvalidNumber}
* @returns {void} * @returns {void}
*/ */

View File

@ -16,10 +16,6 @@ const {
* @typedef {import('peer-id')} PeerId * @typedef {import('peer-id')} PeerId
* @typedef {import('multiaddr')} Multiaddr * @typedef {import('multiaddr')} Multiaddr
*/ */
/**
* Responsible for managing the usage of the available Peer Routing modules.
*/
class PeerRouting { class PeerRouting {
/** /**
* @class * @class
@ -73,6 +69,7 @@ class PeerRouting {
clearDelayedInterval(this._timeoutId) clearDelayedInterval(this._timeoutId)
} }
<<<<<<< HEAD
/** /**
* Iterates over all peer routers in series to find the given peer. * Iterates over all peer routers in series to find the given peer.
* *
@ -92,6 +89,20 @@ class PeerRouting {
// If we don't have a result, we need to provide an error to keep trying // If we don't have a result, we need to provide an error to keep trying
if (!result || Object.keys(result).length === 0) { if (!result || Object.keys(result).length === 0) {
throw errCode(new Error('not found'), 'NOT_FOUND') throw errCode(new Error('not found'), 'NOT_FOUND')
=======
return {
/**
* Iterates over all peer routers in series to find the given peer.
*
* @param {string} id - The id of the peer to find
* @param {object} [options]
* @param {number} [options.timeout] - How long the query should run
* @returns {Promise<{ id: PeerId, multiaddrs: Multiaddr[] }>}
*/
findPeer: async (id, options) => { // eslint-disable-line require-await
if (!routers.length) {
throw errCode(new Error('No peer routers available'), 'NO_ROUTERS_AVAILABLE')
>>>>>>> chore: address review
} }
return result return result

View File

@ -16,11 +16,15 @@ const {
} = require('../errors') } = require('../errors')
const Envelope = require('../record/envelope') const Envelope = require('../record/envelope')
/**
* @typedef {import('multiaddr')} Multiaddr
*/
/** /**
* Address object * Address object
* *
* @typedef {Object} Address * @typedef {Object} Address
* @property {multiaddr} multiaddr peer multiaddr. * @property {Multiaddr} multiaddr peer multiaddr.
* @property {boolean} isCertified obtained from a signed peer record. * @property {boolean} isCertified obtained from a signed peer record.
*/ */
@ -36,7 +40,7 @@ const Envelope = require('../record/envelope')
* Entry object for the addressBook * Entry object for the addressBook
* *
* @typedef {Object} Entry * @typedef {Object} Entry
* @property {Array<Address>} addresses peer Addresses. * @property {Address[]} addresses peer Addresses.
* @property {CertifiedRecord} record certified peer record. * @property {CertifiedRecord} record certified peer record.
*/ */
@ -71,7 +75,7 @@ class AddressBook extends Book {
/** /**
* Map known peers to their known Address Entries. * Map known peers to their known Address Entries.
* *
* @type {Map<string, Array<Entry>>} * @type {Map<string, Entry[]>}
*/ */
this.data = new Map() this.data = new Map()
} }
@ -172,7 +176,7 @@ class AddressBook extends Book {
* *
* @override * @override
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {Array<multiaddr>} multiaddrs * @param {Multiaddr[]} multiaddrs
* @returns {AddressBook} * @returns {AddressBook}
*/ */
set (peerId, multiaddrs) { set (peerId, multiaddrs) {
@ -222,7 +226,7 @@ class AddressBook extends Book {
* If the peer is not known, it is set with the given addresses. * If the peer is not known, it is set with the given addresses.
* *
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {Array<multiaddr>} multiaddrs * @param {Multiaddr[]} multiaddrs
* @returns {AddressBook} * @returns {AddressBook}
*/ */
add (peerId, multiaddrs) { add (peerId, multiaddrs) {
@ -271,7 +275,7 @@ class AddressBook extends Book {
* *
* @override * @override
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Array<Address>|undefined} * @returns {Address[]|undefined}
*/ */
get (peerId) { get (peerId) {
if (!PeerId.isPeerId(peerId)) { if (!PeerId.isPeerId(peerId)) {
@ -287,9 +291,9 @@ class AddressBook extends Book {
* Transforms received multiaddrs into Address. * Transforms received multiaddrs into Address.
* *
* @private * @private
* @param {Array<multiaddr>} multiaddrs * @param {Multiaddr[]} multiaddrs
* @param {boolean} [isCertified] * @param {boolean} [isCertified]
* @returns {Array<Address>} * @returns {Address[]}
*/ */
_toAddresses (multiaddrs, isCertified = false) { _toAddresses (multiaddrs, isCertified = false) {
if (!multiaddrs) { if (!multiaddrs) {
@ -320,8 +324,8 @@ class AddressBook extends Book {
* Returns `undefined` if there are no known multiaddrs for the given peer. * Returns `undefined` if there are no known multiaddrs for the given peer.
* *
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {(addresses: Array<Address) => Array<Address>} [addressSorter] * @param {(addresses: Address[]) => Address[]} [addressSorter]
* @returns {Array<Multiaddr>|undefined} * @returns {Multiaddr[]|undefined}
*/ */
getMultiaddrsForPeer (peerId, addressSorter = (ms) => ms) { getMultiaddrsForPeer (peerId, addressSorter = (ms) => ms) {
if (!PeerId.isPeerId(peerId)) { if (!PeerId.isPeerId(peerId)) {

View File

@ -13,12 +13,14 @@ class Book {
/** /**
* The Book is the skeleton for the PeerStore books. * The Book is the skeleton for the PeerStore books.
* *
* @template T
*
* @class * @class
* @param {Object} properties * @param {Object} properties
* @param {PeerStore} properties.peerStore - PeerStore instance. * @param {PeerStore} properties.peerStore - PeerStore instance.
* @param {string} properties.eventName - Name of the event to emit by the PeerStore. * @param {string} properties.eventName - Name of the event to emit by the PeerStore.
* @param {string} properties.eventProperty - Name of the property to emit by the PeerStore. * @param {string} properties.eventProperty - Name of the property to emit by the PeerStore.
* @param {(data: *) => Array<*>} [properties.eventTransformer] - Transformer function of the provided data for being emitted. * @param {(data: T) => T[]} [properties.eventTransformer] - Transformer function of the provided data for being emitted.
*/ */
constructor ({ peerStore, eventName, eventProperty, eventTransformer = passthrough }) { constructor ({ peerStore, eventName, eventProperty, eventTransformer = passthrough }) {
this._ps = peerStore this._ps = peerStore
@ -29,7 +31,7 @@ class Book {
/** /**
* Map known peers to their data. * Map known peers to their data.
* *
* @type {Map<string, Array<*>} * @type {Map<string, T[]}
*/ */
this.data = new Map() this.data = new Map()
} }
@ -38,7 +40,7 @@ class Book {
* Set known data of a provided peer. * Set known data of a provided peer.
* *
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {Array<Data>|Data} data * @param {T[]|T} data
*/ */
set (peerId, data) { set (peerId, data) {
throw errcode(new Error('set must be implemented by the subclass'), 'ERR_NOT_IMPLEMENTED') throw errcode(new Error('set must be implemented by the subclass'), 'ERR_NOT_IMPLEMENTED')
@ -49,7 +51,7 @@ class Book {
* *
* @private * @private
* @param {PeerId} peerId - peerId of the data to store * @param {PeerId} peerId - peerId of the data to store
* @param {*} data - data to store. * @param {T} data - data to store.
* @param {Object} [options] - storing options. * @param {Object} [options] - storing options.
* @param {boolean} [options.emit = true] - emit the provided data. * @param {boolean} [options.emit = true] - emit the provided data.
* @returns {void} * @returns {void}
@ -69,7 +71,7 @@ class Book {
* *
* @private * @private
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {*} data * @param {T} data
*/ */
_emit (peerId, data) { _emit (peerId, data) {
this._ps.emit(this.eventName, { this._ps.emit(this.eventName, {
@ -83,7 +85,7 @@ class Book {
* Returns `undefined` if there is no available data for the given peer. * Returns `undefined` if there is no available data for the given peer.
* *
* @param {PeerId} peerId * @param {PeerId} peerId
* @returns {Array<Data>|undefined} * @returns {T[]|undefined}
*/ */
get (peerId) { get (peerId) {
if (!PeerId.isPeerId(peerId)) { if (!PeerId.isPeerId(peerId)) {

View File

@ -17,6 +17,10 @@ const {
ERR_INVALID_PARAMETERS ERR_INVALID_PARAMETERS
} = require('../errors') } = require('../errors')
/**
* @typedef {import('./address-book').Address} Address
*/
/** /**
* @extends {EventEmitter} * @extends {EventEmitter}
* *
@ -32,9 +36,9 @@ class PeerStore extends EventEmitter {
* *
* @typedef {Object} Peer * @typedef {Object} Peer
* @property {PeerId} id peer's peer-id instance. * @property {PeerId} id peer's peer-id instance.
* @property {Array<Address>} addresses peer's addresses containing its multiaddrs and metadata. * @property {Address[]} addresses peer's addresses containing its multiaddrs and metadata.
* @property {Array<string>} protocols peer's supported protocols. * @property {string[]} protocols peer's supported protocols.
* @property {Map<string, Buffer>} metadata peer's metadata map. * @property {Map<string, Uint8Array>} metadata peer's metadata map.
*/ */
/** /**

View File

@ -53,7 +53,7 @@ class MetadataBook extends Book {
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {string} key - metadata key * @param {string} key - metadata key
* @param {Uint8Array} value - metadata value * @param {Uint8Array} value - metadata value
* @returns {ProtoBook} * @returns {MetadataBook}
*/ */
set (peerId, key, value) { set (peerId, key, value) {
if (!PeerId.isPeerId(peerId)) { if (!PeerId.isPeerId(peerId)) {

View File

@ -52,7 +52,7 @@ class ProtoBook extends Book {
* *
* @override * @override
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {Array<string>} protocols * @param {string[]} protocols
* @returns {ProtoBook} * @returns {ProtoBook}
*/ */
set (peerId, protocols) { set (peerId, protocols) {
@ -90,7 +90,7 @@ class ProtoBook extends Book {
* If the peer was not known before, it will be added. * If the peer was not known before, it will be added.
* *
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {Array<string>} protocols * @param {string[]} protocols
* @returns {ProtoBook} * @returns {ProtoBook}
*/ */
add (peerId, protocols) { add (peerId, protocols) {
@ -125,7 +125,7 @@ class ProtoBook extends Book {
* If the protocols did not exist before, nothing will be done. * If the protocols did not exist before, nothing will be done.
* *
* @param {PeerId} peerId * @param {PeerId} peerId
* @param {Array<string>} protocols * @param {string[]} protocols
* @returns {ProtoBook} * @returns {ProtoBook}
*/ */
remove (peerId, protocols) { remove (peerId, protocols) {

View File

@ -14,7 +14,7 @@ const { PROTOCOL, PING_LENGTH } = require('./constants')
/** /**
* @typedef {import('../')} Libp2p * @typedef {import('../')} Libp2p
* @typedef {import('multiaddr')} multiaddr * @typedef {import('multiaddr')} Multiaddr
* @typedef {import('peer-id')} PeerId * @typedef {import('peer-id')} PeerId
*/ */
@ -22,7 +22,7 @@ const { PROTOCOL, PING_LENGTH } = require('./constants')
* Ping a given peer and wait for its response, getting the operation latency. * Ping a given peer and wait for its response, getting the operation latency.
* *
* @param {Libp2p} node * @param {Libp2p} node
* @param {PeerId|multiaddr} peer * @param {PeerId|Multiaddr} peer
* @returns {Promise<number>} * @returns {Promise<number>}
*/ */
async function ping (node, peer) { async function ping (node, peer) {

View File

@ -21,7 +21,7 @@ log.error = debug('libp2p:pnet:err')
/** /**
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
* @typedef {import('../').DuplexIterable} DuplexIterable * @typedef {import('libp2p-interfaces/src/connection/connection').DuplexIterableStream} DuplexIterableStream
*/ */
class Protector { class Protector {
@ -44,7 +44,7 @@ class Protector {
* created with. * created with.
* *
* @param {Connection} connection - The connection to protect * @param {Connection} connection - The connection to protect
* @returns {DuplexIterable} A protected duplex iterable * @returns {DuplexIterableStream} A protected duplex iterable
*/ */
async protect (connection) { async protect (connection) {
if (!connection) { if (!connection) {

View File

@ -1,5 +1,9 @@
'use strict' 'use strict'
/**
* @typedef {import('libp2p-interfaces/src/pubsub').InMessage} InMessage
*/
// Pubsub adapter to keep API with handlers while not removed. // Pubsub adapter to keep API with handlers while not removed.
module.exports = (PubsubRouter, libp2p, options) => { module.exports = (PubsubRouter, libp2p, options) => {
class Pubsub extends PubsubRouter { class Pubsub extends PubsubRouter {

View File

@ -13,7 +13,7 @@ const {
/** /**
* @typedef {import('peer-id')} PeerId * @typedef {import('peer-id')} PeerId
* @typedef {import('multiaddr')} multiaddr * @typedef {import('multiaddr')} Multiaddr
*/ */
/** /**
@ -27,7 +27,7 @@ class PeerRecord extends Record {
* @class * @class
* @param {Object} params * @param {Object} params
* @param {PeerId} params.peerId * @param {PeerId} params.peerId
* @param {Array<multiaddr>} params.multiaddrs - addresses of the associated peer. * @param {Multiaddr[]} params.multiaddrs - addresses of the associated peer.
* @param {number} [params.seqNumber] - monotonically-increasing sequence counter that's used to order PeerRecords in time. * @param {number} [params.seqNumber] - monotonically-increasing sequence counter that's used to order PeerRecords in time.
*/ */
constructor ({ peerId, multiaddrs = [], seqNumber = Date.now() }) { constructor ({ peerId, multiaddrs = [], seqNumber = Date.now() }) {

View File

@ -10,7 +10,7 @@ log.error = debug('libp2p:transports:error')
const { updateSelfPeerRecord } = require('./record/utils') const { updateSelfPeerRecord } = require('./record/utils')
/** /**
* @typedef {import('multiaddr')} multiaddr * @typedef {import('multiaddr')} Multiaddr
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
* *
* @typedef {Object} TransportManagerProperties * @typedef {Object} TransportManagerProperties
@ -90,7 +90,7 @@ class TransportManager {
/** /**
* Dials the given Multiaddr over it's supported transport * Dials the given Multiaddr over it's supported transport
* *
* @param {multiaddr} ma * @param {Multiaddr} ma
* @param {*} options * @param {*} options
* @returns {Promise<Connection>} * @returns {Promise<Connection>}
*/ */
@ -111,7 +111,7 @@ class TransportManager {
/** /**
* Returns all Multiaddr's the listeners are using * Returns all Multiaddr's the listeners are using
* *
* @returns {Array<multiaddr>} * @returns {Multiaddr[]}
*/ */
getAddrs () { getAddrs () {
let addrs = [] let addrs = []
@ -135,7 +135,7 @@ class TransportManager {
/** /**
* Finds a transport that matches the given Multiaddr * Finds a transport that matches the given Multiaddr
* *
* @param {multiaddr} ma * @param {Multiaddr} ma
* @returns {Transport|null} * @returns {Transport|null}
*/ */
transportForMultiaddr (ma) { transportForMultiaddr (ma) {
@ -150,7 +150,7 @@ class TransportManager {
* Starts listeners for each listen Multiaddr. * Starts listeners for each listen Multiaddr.
* *
* @async * @async
* @param {Array<multiaddr>} addrs - addresses to attempt to listen on * @param {Multiaddr[]} addrs - addresses to attempt to listen on
*/ */
async listen (addrs) { async listen (addrs) {
if (!addrs || addrs.length === 0) { if (!addrs || addrs.length === 0) {