connect method

Future<void> connect({
  1. String? authKey,
  2. Uri? controlUrl,
})

Implementation

Future<void> connect({String? authKey, Uri? controlUrl}) async {
  try {
    if (_state == NodeState.running) {
      return;
    }

    final status = await _engine.up(
      hostname: clientId,
      authKey: authKey,
      controlUrl: controlUrl ?? defaultControlUrlOverride,
    );
    _updateState(status.state);

    if (status.state != NodeState.running) {
      await _awaitState(
        NodeState.running,
      ).timeout(const Duration(seconds: 20));
    }
    _peerCache.clear();
    _statusCache.clear();

    await _server.start();
    _httpServer = await _engine.http.bind(port: 80);
    _httpBridgeSubscription = _httpServer!.requests.listen(
      (request) => unawaited(_forwardTailnetHttpRequest(request)),
    );

    _syncPoller.duration = const Duration(seconds: 2);
    Future.delayed(const Duration(seconds: 20), () {
      _syncPoller.duration = const Duration(seconds: 5);
    });
    _syncPoller.start();
  } catch (error) {
    logger.log('Error connecting: $error');

    try {
      final status = await _engine.status();
      if (status.state == NodeState.noState) {
        await logout();
      } else {
        await disconnect();
      }
    } catch (cleanupError) {
      logger.log('Error cleaning up failed connection: $cleanupError');
    }

    if (error is DuneException) {
      throw error;
    }

    throw DuneException(
      code: DuneExceptionCode.networkConnectionFailed,
      message: 'Failed to connect Dune network.',
    );
  }
}