connectRelay method

Future<Tuple<bool, String>> connectRelay({
  1. required String dirtyUrl,
  2. required ConnectionSource connectionSource,
  3. int connectTimeout = DEFAULT_WEB_SOCKET_CONNECT_TIMEOUT,
})

Connects to a relay to the relay pool. Returns a tuple with the first element being a boolean indicating success \ and the second element being a string with the error message if any.

Implementation

Future<Tuple<bool, String>> connectRelay({
  required String dirtyUrl,
  required ConnectionSource connectionSource,
  int connectTimeout = DEFAULT_WEB_SOCKET_CONNECT_TIMEOUT,
}) async {
  String? url = cleanRelayUrl(dirtyUrl);
  if (url == null) {
    return Tuple(false, "unclean url");
  }
  if (globalState.blockedRelays.contains(url)) {
    return Tuple(false, "relay is blocked");
  }

  if (isRelayConnected(url)) {
    Logger.log.t("relay already connected: $url");
    return Tuple(true, "");
  }
  RelayConnectivity? relayConnectivity = globalState.relays[url];

  try {
    if (relayConnectivity == null) {
      relayConnectivity = RelayConnectivity<T>(
        relay: Relay(
          url: url,
          connectionSource: connectionSource,
        ),
        specificEngineData: engineAdditionalDataFactory?.call(),
      );
      globalState.relays[url] = relayConnectivity;
    }
    ;
    relayConnectivity.relay.tryingToConnect();

    /// TO BE REMOVED, ONCE WE FIND A WAY OF AVOIDING PROBLEM WHEN CONNECTING TO THIS
    if (url.startsWith("wss://brb.io")) {
      relayConnectivity.relay.failedToConnect();
      return Tuple(false, "bad relay");
    }

    Logger.log.f("connecting to relay $dirtyUrl");

    relayConnectivity.relayTransport = nostrTransportFactory(url);
    await relayConnectivity.relayTransport!.ready
        .timeout(Duration(seconds: connectTimeout), onTimeout: () {
      print("timed out connecting to relay $url");
      return Tuple(false, "timed out connecting to relay $url");
    });

    _startListeningToSocket(relayConnectivity);

    developer.log("connected to relay: $url");
    relayConnectivity.relay.succeededToConnect();
    relayConnectivity.stats.connections++;
    getRelayInfo(url).then((info) {
      relayConnectivity!.relayInfo = info;
    });
    return Tuple(true, "");
  } catch (e) {
    print("!! could not connect to $url -> $e");
    relayConnectivity!.relayTransport == null;
  }
  relayConnectivity.relay.failedToConnect();
  relayConnectivity.stats.connectionErrors++;
  return Tuple(false, "could not connect to $url");
}