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

78 lines
2.4 KiB
JavaScript
Raw Normal View History

2019-12-03 10:28:52 +01:00
'use strict'
const AbortController = require('abort-controller')
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
}
2019-12-04 23:04:43 +01:00
const tokenHolder = new FIFO()
tokens.forEach(token => tokenHolder.push(token))
const dialAbortControllers = this.addrs.map(() => new AbortController())
2019-12-04 16:33:04 +01:00
let completedDials = 0
2019-12-03 10:28:52 +01:00
try {
return await pAny(this.addrs.map(async (addr, i) => {
2019-12-04 23:04:43 +01:00
const token = await tokenHolder.shift() // get token
let conn
try {
const signal = dialAbortControllers[i].signal
conn = await this.dialAction(addr, { ...options, signal: anySignal([signal, options.signal]) })
2019-12-04 16:59:38 +01:00
// Remove the successful AbortController so it is not aborted
dialAbortControllers.splice(i, 1)
2019-12-04 16:33:04 +01:00
} finally {
completedDials++
// If we have more dials to make, recycle the token, otherwise release it
if (completedDials < this.addrs.length) {
2019-12-04 23:04:43 +01:00
tokenHolder.push(token)
2019-12-04 16:33:04 +01:00
} else {
this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0])
}
}
2019-12-04 16:33:04 +01:00
return conn
}))
2019-12-03 10:28:52 +01:00
} finally {
dialAbortControllers.map(c => c.abort()) // success/failure happened, abort everything else
2019-12-04 23:04:43 +01:00
tokens.forEach(token => this.dialer.releaseToken(token)) // release tokens back to the dialer
2019-12-03 10:28:52 +01:00
}
}
}
module.exports.DialRequest = DialRequest