找出RTT最短的IP地址

预计阅读时间: 小于 1 分钟

题目描述

有很多IP地址,如何最快找出RTT最短的IP地址呢?

假设最大并发数为10

解题思路

  1. 将IP地址分组,每组10个IP地址
  2. 对每组IP地址进行并发请求,设置超时时间为当前最短RTT
  3. 如果有IP地址的RTT小于当前最短RTT,则更新最短RTT
  4. 返回RTT最短的IP地址

代码

function chunk(arr, size) {
  return Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );
}

async function race(ips, maxTime) {
  return new Promise((resolve) => {
    const controller = new AbortController();
    const signal = controller.signal;
    setTimeout(() => {
      resolve(null);
      // 取消请求
      controller.abort();
    }, maxTime)
    let start = Date.now();
    for (const ip of ips) {
      fetch(`http://${ip}`, {signal}).then((res) => {
        const rtt = Date.now() - start;
        resolve({
          rtt,
          ip
        })
        controller.abort();
      })
    }
  })
}


async function findShortestRTT(ips, parallelCount = 10) {
  // 对IP地址分组 [ [ip1, ip2, ip3], [ip4, ip5, ip6], ... ]
  const ipChunks = chunk(ips, parallelCount);
  let result = {
    rtt: Infinity,
    ip: ''
  }

  for (const chunk of ipChunks) {
    const temp = await race(chunk, result.rtt)
    if (temp) {
      result = temp;
    }
  }

  return result.ip;
}