@projectlibertylabs/p2p-peer-test
Version:
CLI tool to test libp2p connections and discover peer protocols
52 lines (43 loc) • 1.71 kB
JavaScript
import { testLibp2pConnection } from './libp2p-connection.js';
/**
* Pure function to generate attempt numbers
* @param {number} retries - Number of retry attempts
* @returns {number[]} Array of attempt numbers starting from 1
*/
const generateAttempts = (retries) => Array.from({ length: retries + 1 }, (_, i) => i + 1);
/**
* Pure function to process attempt results
* @param {Array} results - Array of connection attempt results
* @returns {Object} Processed result with total attempts and final status
*/
const processAttemptResults = (results) => ({
...results[results.length - 1],
totalAttempts: results.length,
attempts: results
});
/**
* Higher-order function for retry logic
* @param {Function} testFn - The connection test function
* @returns {Function} Function that performs connection testing with retries
*/
const withRetries = (testFn) => async (multiaddr, options) => {
const { timeout, retries } = options;
const attempts = generateAttempts(retries);
const results = [];
for (const attemptNumber of attempts) {
const result = await testFn(multiaddr, timeout);
const attemptResult = { attempt: attemptNumber, ...result };
results.push(attemptResult);
if (result.success) break;
}
return processAttemptResults(results);
};
/**
* Tests libp2p connection with retry mechanism
* @param {string} multiaddr - The multiaddr to connect to
* @param {Object} options - Connection options
* @param {number} options.timeout - Connection timeout in milliseconds
* @param {number} options.retries - Number of retry attempts
* @returns {Promise<Object>} Connection result with retry information
*/
export const testWithRetries = withRetries(testLibp2pConnection);