Skip to content

Commit

Permalink
chore: add typedefs
Browse files Browse the repository at this point in the history
  • Loading branch information
vasco-santos committed Nov 25, 2020
1 parent c6fd23a commit 1c54160
Show file tree
Hide file tree
Showing 30 changed files with 383 additions and 184 deletions.
20 changes: 11 additions & 9 deletions src/address-manager/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,19 @@ log.error = debug('libp2p:addresses:error')
const multiaddr = require('multiaddr')

/**
* Responsible for managing the peer addresses.
* Peers can specify their listen and announce addresses.
* The listen addresses will be used by the libp2p transports to listen for new connections,
* while the announce addresses will be used for the peer addresses' to other peers in the network.
* @typedef {Object} AddressManagerOptions
* @property {Array<string>} [listen = []] - list of multiaddrs string representation to listen.
* @property {Array<string>} [announce = []] - list of multiaddrs string representation to announce.
*/
class AddressManager {
/**
* Responsible for managing the peer addresses.
* Peers can specify their listen and announce addresses.
* The listen addresses will be used by the libp2p transports to listen for new connections,
* while the announce addresses will be used for the peer addresses' to other peers in the network.
*
* @class
* @param {object} [options]
* @param {Array<string>} [options.listen = []] - list of multiaddrs string representation to listen.
* @param {Array<string>} [options.announce = []] - list of multiaddrs string representation to announce.
* @param {AddressManagerOptions} [options]
*/
constructor ({ listen = [], announce = [] } = {}) {
this.listen = new Set(listen)
Expand All @@ -27,7 +29,7 @@ class AddressManager {
/**
* Get peer listen multiaddrs.
*
* @returns {Array<Multiaddr>}
* @returns {Array<multiaddr>}
*/
getListenAddrs () {
return Array.from(this.listen).map((a) => multiaddr(a))
Expand All @@ -36,7 +38,7 @@ class AddressManager {
/**
* Get peer announcing multiaddrs.
*
* @returns {Array<Multiaddr>}
* @returns {Array<multiaddr>}
*/
getAnnounceAddrs () {
return Array.from(this.announce).map((a) => multiaddr(a))
Expand Down
17 changes: 14 additions & 3 deletions src/circuit/auto-relay.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,25 @@ const {
RELAY_RENDEZVOUS_NS
} = require('./constants')

/**
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
* @typedef {import('../peer-store/address-book').Address} Address
*/

/**
* @typedef {Object} AutoRelayProperties
* @property {import('../')} libp2p
*
* @typedef {Object} AutoRelayOptions
* @property {number} [maxListeners = 1] - maximum number of relays to listen.
*/

class AutoRelay {
/**
* Creates an instance of AutoRelay.
*
* @class
* @param {object} props
* @param {Libp2p} props.libp2p
* @param {number} [props.maxListeners = 1] - maximum number of relays to listen.
* @param {AutoRelayProperties & AutoRelayOptions} props
*/
constructor ({ libp2p, maxListeners = 1 }) {
this._libp2p = libp2p
Expand Down
17 changes: 17 additions & 0 deletions src/circuit/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,23 @@ const {
RELAY_RENDEZVOUS_NS
} = require('./constants')

/**
* @typedef {import('../')} Libp2p
*
* @typedef {Object} RelayAdvertiseOptions
* @property {number} [bootDelay = ADVERTISE_BOOT_DELAY]
* @property {boolean} [enabled = true]
* @property {number} [ttl = ADVERTISE_TTL]
*
* @typedef {Object} HopOptions
* @property {boolean} [enabled = false]
* @property {boolean} [active = false]
*
* @typedef {Object} AutoRelayOptions
* @property {number} [maxListeners = 2] - maximum number of relays to listen.
* @property {boolean} [enabled = false]
*/

class Relay {
/**
* Creates an instance of Relay.
Expand Down
43 changes: 26 additions & 17 deletions src/connection-manager/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,29 +31,40 @@ const defaultOptions = {
}

/**
* Responsible for managing known connections.
* @typedef {import('../')} Libp2p
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
*/

/**
* @typedef {Object} ConnectionManagerOptions
* @property {number} [maxConnections = Infinity] - The maximum number of connections allowed.
* @property {number} [minConnections = 0] - The minimum number of connections to avoid pruning.
* @property {number} [maxData = Infinity] - The max data (in and out), per average interval to allow.
* @property {number} [maxSentData = Infinity] - The max outgoing data, per average interval to allow.
* @property {number} [maxReceivedData = Infinity] - The max incoming data, per average interval to allow.
* @property {number} [maxEventLoopDelay = Infinity] - The upper limit the event loop can take to run.
* @property {number} [pollInterval = 2000] - How often, in milliseconds, metrics and latency should be checked.
* @property {number} [movingAverageInterval = 60000] - How often, in milliseconds, to compute averages.
* @property {number} [defaultPeerValue = 1] - The value of the peer.
* @property {boolean} [autoDial = true] - Should preemptively guarantee connections are above the low watermark.
* @property {number} [autoDialInterval = 10000] - How often, in milliseconds, it should preemptively guarantee connections are above the low watermark.
*/

/**
* @extends {EventEmitter}
*
* @fires ConnectionManager#peer:connect Emitted when a new peer is connected.
* @fires ConnectionManager#peer:disconnect Emitted when a peer is disconnected.
*/
class ConnectionManager extends EventEmitter {
/**
* Responsible for managing known connections.
*
* @class
* @param {Libp2p} libp2p
* @param {object} options
* @param {number} options.maxConnections - The maximum number of connections allowed. Default=Infinity
* @param {number} options.minConnections - The minimum number of connections to avoid pruning. Default=0
* @param {number} options.maxData - The max data (in and out), per average interval to allow. Default=Infinity
* @param {number} options.maxSentData - The max outgoing data, per average interval to allow. Default=Infinity
* @param {number} options.maxReceivedData - The max incoming data, per average interval to allow.. Default=Infinity
* @param {number} options.maxEventLoopDelay - The upper limit the event loop can take to run. Default=Infinity
* @param {number} options.pollInterval - How often, in milliseconds, metrics and latency should be checked. Default=2000
* @param {number} options.movingAverageInterval - How often, in milliseconds, to compute averages. Default=60000
* @param {number} options.defaultPeerValue - The value of the peer. Default=1
* @param {boolean} options.autoDial - Should preemptively guarantee connections are above the low watermark. Default=true
* @param {number} options.autoDialInterval - How often, in milliseconds, it should preemptively guarantee connections are above the low watermark. Default=10000
* @param {ConnectionManagerOptions} options
*/
constructor (libp2p, options) {
constructor (libp2p, options = {}) {
super()

this._libp2p = libp2p
Expand All @@ -66,8 +77,6 @@ class ConnectionManager extends EventEmitter {

log('options: %j', this._options)

this._libp2p = libp2p

/**
* Map of peer identifiers to their peer value for pruning connections.
*
Expand All @@ -78,7 +87,7 @@ class ConnectionManager extends EventEmitter {
/**
* Map of connections per peer
*
* @type {Map<string, Array<conn>>}
* @type {Map<string, Array<Connection>>}
*/
this.connections = new Map()

Expand Down
18 changes: 12 additions & 6 deletions src/connection-manager/latency-monitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

/* global window */
const globalThis = require('ipfs-utils/src/globalthis')
const EventEmitter = require('events')
const { EventEmitter } = require('events')
const VisibilityChangeEmitter = require('./visibility-change-emitter')
const debug = require('debug')('latency-monitor:LatencyMonitor')

Expand All @@ -17,13 +17,21 @@ const debug = require('debug')('latency-monitor:LatencyMonitor')
* @property {number} maxMS What was the max time for a cb to be called
* @property {number} avgMs What was the average time for a cb to be called
* @property {number} lengthMs How long this interval was in ms
*
* @typedef {Object} LatencyMonitorOptions
* @property {number} [latencyCheckIntervalMs=500] - How often to add a latency check event (ms)
* @property {number} [dataEmitIntervalMs=5000] - How often to summarize latency check events. null or 0 disables event firing
* @property {Function} [asyncTestFn] - What cb-style async function to use
* @property {number} [latencyRandomPercentage=5] - What percent (+/-) of latencyCheckIntervalMs should we randomly use? This helps avoid alignment to other events.
*/

/**
* A class to monitor latency of any async function which works in a browser or node. This works by periodically calling
* the asyncTestFn and timing how long it takes the callback to be called. It can also periodically emit stats about this.
* This can be disabled and stats can be pulled via setting dataEmitIntervalMs = 0.
*
* @extends {EventEmitter}
*
* The default implementation is an event loop latency monitor. This works by firing periodic events into the event loop
* and timing how long it takes to get back.
*
Expand All @@ -37,11 +45,8 @@ const debug = require('debug')('latency-monitor:LatencyMonitor')
*/
class LatencyMonitor extends EventEmitter {
/**
* @param {object} [options]
* @param {number} [options.latencyCheckIntervalMs=500] - How often to add a latency check event (ms)
* @param {number} [options.dataEmitIntervalMs=5000] - How often to summarize latency check events. null or 0 disables event firing
* @param {Function} [options.asyncTestFn] - What cb-style async function to use
* @param {number} [options.latencyRandomPercentage=5] - What percent (+/-) of latencyCheckIntervalMs should we randomly use? This helps avoid alignment to other events.
* @class
* @param {LatencyMonitorOptions} [options]
*/
constructor ({ latencyCheckIntervalMs, dataEmitIntervalMs, asyncTestFn, latencyRandomPercentage } = {}) {
super()
Expand Down Expand Up @@ -91,6 +96,7 @@ class LatencyMonitor extends EventEmitter {
// See: http://stackoverflow.com/questions/6032429/chrome-timeouts-interval-suspended-in-background-tabs
if (isBrowser()) {
that._visibilityChangeEmitter = new VisibilityChangeEmitter()

that._visibilityChangeEmitter.on('visibilityChange', (pageInFocus) => {
if (pageInFocus) {
that._startTimers()
Expand Down
13 changes: 9 additions & 4 deletions src/connection-manager/visibility-change-emitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@
* This code is based on `latency-monitor` (https://github.com/mlucool/latency-monitor) by `mlucool` (https://github.com/mlucool), available under Apache License 2.0 (https://github.com/mlucool/latency-monitor/blob/master/LICENSE)
*/
'use strict'
const EventEmitter = require('events')

const { EventEmitter } = require('events')

const debug = require('debug')('latency-monitor:VisibilityChangeEmitter')

/**
* Listen to page visibility change events (i.e. when the page is focused / blurred) by an event emitter.
*
* @extends {EventEmitter}
*
* Warning: This does not work on all browsers, but should work on all modern browsers
*
* @example
Expand All @@ -29,12 +32,12 @@ const debug = require('debug')('latency-monitor:VisibilityChangeEmitter')
* });
* // To access the visibility state directly, call:
* console.log('Am I focused now? ' + myVisibilityEmitter.isVisible());
*
* @class VisibilityChangeEmitter
*/
module.exports = class VisibilityChangeEmitter extends EventEmitter {
class VisibilityChangeEmitter extends EventEmitter {
/**
* Creates a VisibilityChangeEmitter
*
* @class
*/
constructor () {
super()
Expand Down Expand Up @@ -119,3 +122,5 @@ module.exports = class VisibilityChangeEmitter extends EventEmitter {
this.emit('visibilityChange', visible)
}
}

module.exports = VisibilityChangeEmitter
7 changes: 6 additions & 1 deletion src/content-routing.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ const { messages, codes } = require('./errors')
const all = require('it-all')
const pAny = require('p-any')

/**
* @typedef {import('peer-id')} PeerId
* @typedef {import('multiaddr')} multiaddr
*/

module.exports = (node) => {
const routers = node._modules.contentRouting || []
const dht = node._dht
Expand All @@ -24,7 +29,7 @@ module.exports = (node) => {
* @param {object} [options]
* @param {number} [options.timeout] - How long the query should run
* @param {number} [options.maxNumProviders] - maximum number of providers to find
* @returns {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>}
* @returns {AsyncIterable<{ id: PeerId, multiaddrs: Array<multiaddr> }>}
*/
async * findProviders (key, options) {
if (!routers.length) {
Expand Down
20 changes: 14 additions & 6 deletions src/dialer/dial-request.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ log.error = debug('libp2p:dialer:request:error')
const FIFO = require('p-fifo')
const pAny = require('p-any')

/**
* @typedef {import('./')} Dialer
*/

/**
* @typedef {Object} DialRequestOptions
* @property {Multiaddr[]} addrs
* @property {function(Multiaddr):Promise<Connection>} dialAction
* @property {Dialer} dialer
*/
class DialRequest {
/**
* Manages running the `dialAction` on multiple provided `addrs` in parallel
Expand All @@ -17,10 +27,8 @@ class DialRequest {
* started using `DialRequest.run(options)`. Once a single dial has succeeded,
* all other dials in the request will be cancelled.
*
* @param {object} options
* @param {Multiaddr[]} options.addrs
* @param {function(Multiaddr):Promise<Connection>} options.dialAction
* @param {Dialer} options.dialer
* @class
* @param {DialRequestOptions} options
*/
constructor ({
addrs,
Expand All @@ -34,8 +42,8 @@ class DialRequest {

/**
* @async
* @param {object} options
* @param {AbortSignal} options.signal - An AbortController signal
* @param {object} [options]
* @param {AbortSignal} [options.signal] - An AbortController signal
* @returns {Connection}
*/
async run (options) {
Expand Down
Loading

0 comments on commit 1c54160

Please sign in to comment.