findPeerDispatcher function

void findPeerDispatcher(
  1. BackoffCache c,
  2. Stream<AddrInfo> peerStream
)

Dispatches peers from a discovery query to all registered channels

Implementation

void findPeerDispatcher(BackoffCache c, Stream<AddrInfo> peerStream) async {
  try {
    await for (final ai in peerStream) {
      // If we receive the same peer multiple times return the address union
      AddrInfo sendAi;
      if (c.peers.containsKey(ai.id)) {
        final prevAi = c.peers[ai.id]!;
        final combinedAi = AddrInfo.mergeAddrInfos(prevAi, ai);
        if (combinedAi != null) {
          sendAi = combinedAi;
        } else {
          continue;
        }
      } else {
        sendAi = ai;
      }

      c.peers[ai.id] = sendAi;

      for (final entry in c.sendingChs.entries) {
        final ch = entry.key;
        final rem = entry.value;
        if (rem == null || rem > 0) {
          ch.add(sendAi);
          if (rem != null) {
            c.sendingChs[ch] = rem - 1;
          }
        }
      }
    }
  } finally {
    // If the peer addresses have changed reset the backoff
    if (checkUpdates(c.prevPeers, c.peers)) {
      c.strat.reset();
      c.prevPeers = Map.from(c.peers);
    }
    c.nextDiscover = c.clock.now().add(c.strat.delay());

    c.ongoing = false;
    c.peers = {};

    for (final ch in c.sendingChs.keys) {
      await ch.close();
    }
    c.sendingChs = {};
  }
}