getFallbackRelay method
Get fallback relay (healthy alternative relay).
Implementation
String? getFallbackRelay({
required String primaryRelayUrl,
required List<String> availableRelays,
}) {
final healthyRelays = availableRelays
.where((url) =>
url != primaryRelayUrl &&
getCircuitBreakerState(url) != CircuitBreakerState.open)
.toList();
if (healthyRelays.isEmpty) {
logger.log('No healthy fallback relay found for $primaryRelayUrl');
return null;
}
// Sort by error count (prefer relays with fewer recent errors)
healthyRelays.sort((a, b) {
final aErrors = _errorHistory
.where((e) =>
e.relayUrl == a &&
DateTime.now().difference(e.timestamp).inMinutes < 5)
.length;
final bErrors = _errorHistory
.where((e) =>
e.relayUrl == b &&
DateTime.now().difference(e.timestamp).inMinutes < 5)
.length;
return aErrors.compareTo(bErrors);
});
logger.log(
'Fallback relay selected: ${healthyRelays.first} for $primaryRelayUrl');
return healthyRelays.first;
}