selectProxy method

  1. @override
Proxy selectProxy(
  1. List<Proxy> proxies
)
override

Selects the next proxy from the given list

Implementation

@override
Proxy selectProxy(List<Proxy> proxies) {
  if (proxies.isEmpty) {
    throw ArgumentError('Proxy list cannot be empty');
  }

  final now = DateTime.now().millisecondsSinceEpoch;

  // Try to find a suitable proxy
  for (int i = 0; i < proxies.length; i++) {
    final index = (_currentIndex + i) % proxies.length;
    final proxy = proxies[index];
    final proxyKey = '${proxy.ip}:${proxy.port}';

    // Check if the proxy has too many consecutive failures
    final failures = _failureCount[proxyKey] ?? 0;
    if (failures >= maxConsecutiveFailures) {
      continue;
    }

    // Check if the proxy was used too recently
    final lastUsed = _lastUsedTime[proxyKey] ?? 0;
    if (now - lastUsed < minTimeBetweenUses) {
      continue;
    }

    // Update the current index and last used time
    _currentIndex = (index + 1) % proxies.length;
    _lastUsedTime[proxyKey] = now;

    return proxy;
  }

  // If no suitable proxy was found, reset failure counts and try again
  if (_allProxiesHaveTooManyFailures()) {
    _failureCount.clear();
    return selectProxy(proxies);
  }

  // If all proxies were used too recently, use the least recently used one
  final leastRecentlyUsed = _getLeastRecentlyUsedProxy();
  if (leastRecentlyUsed != null) {
    final proxyKey = '${leastRecentlyUsed.ip}:${leastRecentlyUsed.port}';
    _lastUsedTime[proxyKey] = now;
    return leastRecentlyUsed;
  }

  // Fallback to the first proxy
  return proxies.first;
}