reconnectConnection method

Future<bool> reconnectConnection(
  1. RelayConnectionKey key, {
  2. required ConnectionSource connectionSource,
  3. bool force = false,
})

Reconnects the connection identified by key, if it is closed. An authenticated connection comes back authenticated or not at all.

Implementation

Future<bool> reconnectConnection(
  RelayConnectionKey key, {
  required ConnectionSource connectionSource,
  bool force = false,
}) async {
  final inFlightConnect = _connectReadyCompleters[key];
  if (inFlightConnect != null) {
    final connected = await inFlightConnect.future;
    updateRelayConnectivity();
    return connected;
  }

  RelayConnectivity? relayConnectivity = globalState.relays[key];
  if (relayConnectivity != null && relayConnectivity.relayTransport != null) {
    try {
      final opened = await _waitForTransportOpen(
        relayConnectivity.relayTransport!,
        timeoutSeconds: DEFAULT_WEB_SOCKET_CONNECT_TIMEOUT,
      );
      if (opened && relayConnectivity.relayTransport!.isOpen()) {
        updateRelayConnectivity();
        return true;
      }
    } catch (error) {
      Logger.log.e(() => "error connecting to $key: $error");
    }
  }
  if (relayConnectivity == null ||
      relayConnectivity.relayTransport == null ||
      !relayConnectivity.relayTransport!.isOpen()) {
    if (!force &&
        (relayConnectivity != null &&
            !relayConnectivity.relay.wasLastConnectTryLongerThanSeconds(
              FAIL_RELAY_CONNECT_TRY_AFTER_SECONDS,
            ))) {
      // don't try too often
      updateRelayConnectivity();
      return false;
    }

    if (!key.isAnonymous) {
      final account = _accounts?.accounts[key.pubkey];
      if (account == null) {
        Logger.log.w(() => "No account left to reconnect $key");
        return false;
      }
      return await openConnectionAs(
            key.url,
            account,
            connectionSource: connectionSource,
          ) !=
          null;
    }

    if (!(await connectRelay(
      dirtyUrl: key.url,
      connectionSource: connectionSource,
    ))
        .first) {
      // could not connect
      return false;
    }
    relayConnectivity = globalState.relays[key];
    if (relayConnectivity == null ||
        relayConnectivity.relayTransport == null ||
        !relayConnectivity.relayTransport!.isOpen()) {
      // web socket is not open
      return false;
    }
  }
  return true;
}