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');
  }

  // Calculate weights for each proxy
  final weights = <double>[];
  double totalWeight = 0;

  for (final proxy in proxies) {
    final weight = _calculateWeight(proxy);
    weights.add(weight);
    totalWeight += weight;
  }

  // If all weights are zero, use equal weights
  if (totalWeight <= 0) {
    final equalWeight = 1.0 / proxies.length;
    for (int i = 0; i < weights.length; i++) {
      weights[i] = equalWeight;
    }
    totalWeight = 1.0;
  }

  // Select a proxy based on its weight
  double randomValue = _random.nextDouble() * totalWeight;
  double cumulativeWeight = 0;

  for (int i = 0; i < proxies.length; i++) {
    cumulativeWeight += weights[i];
    if (randomValue <= cumulativeWeight) {
      return proxies[i];
    }
  }

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