selectBestRelay method

String? selectBestRelay(
  1. List<String> availableRelays
)

Get the best relay based on health and load (round-robin with health awareness).

Implementation

String? selectBestRelay(List<String> availableRelays) {
  final healthyRelays = availableRelays
      .where((url) => _relayHealth[url]?.isHealthy ?? true)
      .toList();

  if (healthyRelays.isEmpty) {
    logger.log('No healthy relays available, falling back to all relays');
    return availableRelays.isNotEmpty ? availableRelays.first : null;
  }

  // Select relay with least active connections (load balancing)
  healthyRelays.sort((a, b) {
    final aConnections = getActiveConnections(a);
    final bConnections = getActiveConnections(b);
    return aConnections.compareTo(bConnections);
  });

  return healthyRelays.first;
}