shouldConnect method

bool shouldConnect({
  1. required NodeRole localRole,
  2. required List<String>? localGroupIds,
  3. required EndpointMetadata remote,
})

Decides whether this node should connect to a discovered peer based on their respective metadata.

Connection rules:

  1. Always connect if either node is NodeRole.global — globals bridge all groups.
  2. Connect if the nodes share ANY common group ID.
  3. Reject if no groups overlap and neither is global.

Implementation

bool shouldConnect({
  required NodeRole localRole,
  required List<String>? localGroupIds,
  required EndpointMetadata remote,
}) {
  // Rule 1: Globals connect to everyone.
  if (localRole == NodeRole.global || remote.role == NodeRole.global) {
    return true;
  }

  // Rule 2: If we are ungrouped, we should connect to peers to discover the mesh
  // and receive global broadcasts.
  if (localGroupIds == null || localGroupIds.isEmpty) {
    return true;
  }

  // Rule 3: If the remote is ungrouped, we can connect to them so they can join the mesh.
  if (remote.groupIds.contains('*')) {
    return true;
  }

  // Rule 4: Any overlapping group.
  for (final localGroup in localGroupIds) {
    if (remote.groupIds.contains(localGroup)) {
      return true;
    }
  }

  // Rule 5: No overlap, neither is global, neither is ungrouped — skip.
  return false;
}