isServerAvailable method

Future<bool> isServerAvailable(
  1. PeerId serverId
)

Check if a server is available

A server we are connected to is available. Otherwise the check dials the server. It does not open a stream: an MMA stream closed with no request is an error on the server (op=unrouted).

Implementation

Future<bool> isServerAvailable(PeerId serverId) async {
  try {
    // Fast path: we already have a live connection to this peer.
    if (_isConnected(serverId)) {
      _unavailableServers.remove(serverId.toString());
      return true;
    }

    // Slow path: not currently connected — refresh peerstore address TTL
    // before dialing, in case the address has expired since initialization.
    final knownAddr = _knownServerAddresses[serverId.toString()];
    if (knownAddr != null) {
      await host.peerStore.addrBook.addAddr(
        serverId, knownAddr, const Duration(hours: 1),
      );
      _logger.fine('Refreshed peerstore address for ${serverId.toString().substring(0, 12)}...');
    }

    // A concurrent dial to the same peer joins this one (dart_libp2p
    // 4.1.6 and later), so this does not open a second connection.
    await host
        .connect(AddrInfo(serverId, knownAddr != null ? [knownAddr] : const []))
        .timeout(const Duration(seconds: 10));
    _unavailableServers.remove(serverId.toString());
    return true;

  } catch (e) {
    _logger.fine('Server unavailable: ${serverId.toString().substring(0, 12)}... ($e)');
    return false;
  }
}