1
0
mirror of https://github.com/fluencelabs/js-libp2p synced 2025-04-12 20:26:04 +00:00

72 lines
2.1 KiB
JavaScript
Raw Normal View History

2019-12-03 10:28:52 +01:00
'use strict'
const AbortController = require('abort-controller')
const AggregateError = require('aggregate-error')
2019-12-04 15:59:01 +01:00
const anySignal = require('any-signal')
2019-12-03 10:28:52 +01:00
const debug = require('debug')
const errCode = require('err-code')
2019-12-03 10:28:52 +01:00
const log = debug('libp2p:dialer:request')
log.error = debug('libp2p:dialer:request:error')
const FIFO = require('p-fifo')
const pAny = require('p-any')
2019-12-03 10:28:52 +01:00
class DialRequest {
/**
*
* @param {object} options
* @param {Multiaddr[]} options.addrs
* @param {TransportManager} options.transportManager
* @param {Dialer} options.dialer
*/
constructor ({
addrs,
dialAction,
dialer
}) {
this.addrs = addrs
this.dialer = dialer
this.dialAction = dialAction
}
/**
* @async
* @param {object} options
* @param {AbortSignal} options.signal An AbortController signal
* @param {number} options.timeout The max dial time for each request
* @returns {Connection}
*/
async run (options) {
const tokens = this.dialer.getTokens(this.addrs.length)
2019-12-03 10:28:52 +01:00
// If no tokens are available, throw
if (tokens.length < 1) {
throw errCode(new Error('No dial tokens available'), 'ERR_NO_DIAL_TOKENS')
2019-12-03 10:28:52 +01:00
}
const th = new FIFO()
tokens.forEach(t => th.push(t))
const dialAbortControllers = this.addrs.map(() => new AbortController())
2019-12-03 10:28:52 +01:00
try {
return await pAny(this.addrs.map(async (addr, i) => {
const token = await th.shift() // get token
let conn
try {
const signal = dialAbortControllers[i].signal
conn = await this.dialAction(addr, { ...options, signal: anySignal([signal, options.signal]) })
// Remove the successful AbortController so it is no aborted
dialAbortControllers.splice(i, 1)
} catch (err) {
th.push(token) // return to token holder on error so another ma can be attempted
throw err
}
return conn
}))
2019-12-03 10:28:52 +01:00
} finally {
dialAbortControllers.map(c => c.abort()) // success/failure happened, abort everything else
tokens.forEach(t => this.dialer.releaseToken(t)) // release tokens back to the dialer
2019-12-03 10:28:52 +01:00
}
}
}
module.exports.DialRequest = DialRequest