connect method

  1. @override
Future<void> connect(
  1. AddrInfo pi, {
  2. Context? context,
})
override

Connect ensures there is a connection between this host and the peer with given peer.ID. Connect will absorb the addresses in pi into its internal peerstore. If there is not an active connection, Connect will issue a h.Network.Dial, and block until a connection is open, or an error is returned.

If context is not provided, a new Context will be created.

Implementation

@override
Future<void> connect(AddrInfo pi, {Context? context}) async {
  final startTime = DateTime.now();


  // Prevent self-dialing
  if (pi.id == id) {
    _log.info('Preventing self-dial attempt to ${pi.id}');
    return;
  }

  // Phase 1: Address Filtering and Peerstore Update

  final filterStartTime = DateTime.now();

  final filteredAddrs = _addrsFactory(pi.addrs);


  await peerStore.addrBook.addAddrs(pi.id, filteredAddrs, Duration(minutes: 5));

  final filterTime = DateTime.now().difference(filterStartTime);


  // Phase 2: Connection Check

  final connectedness = _network.connectedness(pi.id);


  if (connectedness == Connectedness.connected) {
    final totalTime = DateTime.now().difference(startTime);

    return;
  }

  // Phase 3: Context Creation

  final ctx = context ?? Context();


  // Phase 4: Dial Peer

  final dialStartTime = DateTime.now();

  try {
    await _dialPeer(pi.id, ctx);

    final dialTime = DateTime.now().difference(dialStartTime);
    final totalTime = DateTime.now().difference(startTime);


  } on IdentifyTimeoutException catch (e, stackTrace) {
    // Handle identify timeout gracefully - log warning instead of error
    final dialTime = DateTime.now().difference(dialStartTime);
    final totalTime = DateTime.now().difference(startTime);
    _log.warning('⏱️ [CONNECT-TIMEOUT] Connection to ${pi.id} timed out during identify after ${totalTime.inMilliseconds}ms (dial: ${dialTime.inMilliseconds}ms): $e');
    // Rethrow the typed exception so callers can handle it specifically
    rethrow;
  } on IdentifyException catch (e, stackTrace) {
    // Handle other identify exceptions
    final dialTime = DateTime.now().difference(dialStartTime);
    final totalTime = DateTime.now().difference(startTime);
    _log.severe('❌ [CONNECT-IDENTIFY-ERROR] Connection failed due to identify error after ${totalTime.inMilliseconds}ms (dial: ${dialTime.inMilliseconds}ms): $e\n$stackTrace');
    rethrow;
  } catch (e, stackTrace) {
    final dialTime = DateTime.now().difference(dialStartTime);
    final totalTime = DateTime.now().difference(startTime);
    _log.severe('❌ [CONNECT-ERROR] Connection failed after ${totalTime.inMilliseconds}ms (dial: ${dialTime.inMilliseconds}ms): $e\n$stackTrace');
    rethrow;
  }
}