close method

  1. @override
Future<void> close()
override

Close stops the identify service.

Implementation

@override
Future<void> close() async {
  _log.fine('IdentifyService.close: Closing identify service.');
  if (_closed) {
    _log.fine('IdentifyService.close: Already closed.');
    return;
  }

  // Signal shutdown to prevent new PUSH operations
  _shutdownInProgress = true;
  _log.fine('IdentifyService.close: Shutdown signal set, stopping new PUSH operations.');

  // Wait for active PUSH operations to complete or timeout
  final activePushFutures = <Future<void>>[];
  await _pushOperationsMutex.synchronized(() async {
    activePushFutures.addAll(_activePushOperations.values);
    _log.fine('IdentifyService.close: Found ${activePushFutures.length} active PUSH operations to wait for.');
  });

  if (activePushFutures.isNotEmpty) {
    _log.fine('IdentifyService.close: Waiting for ${activePushFutures.length} active PUSH operations to complete...');
    try {
      // Wait for all PUSH operations with a reasonable timeout
      await Future.wait(activePushFutures).timeout(const Duration(seconds: 5));
      _log.fine('IdentifyService.close: All active PUSH operations completed.');
    } catch (e) {
      _log.warning('IdentifyService.close: Some PUSH operations did not complete within timeout: $e');
      // Continue with shutdown - PUSH operations should handle their own cleanup
    }
  }

  _closed = true;

  if (!disableObservedAddrManager) {
    _log.finer('IdentifyService.close: Closing ObservedAddrManager and NATEmitter.');
    await _observedAddrMgr?.close(); // Use null-safe operator
    await _natEmitter?.close();    // Use null-safe operator
  }

  // Cancel event bus subscription
  if (_eventBusSubscription != null) {
    await _eventBusSubscription!.close(); // Changed cancel() to close()
    _eventBusSubscription = null;
    _log.fine('IdentifyService.close: Closed event bus subscription.');
  }

  // Close trigger push stream controller
  if (_triggerPushController != null) {
    await _triggerPushController!.close();
    _triggerPushController = null;
    _log.fine('IdentifyService.close: Closed triggerPush StreamController.');
  }

  _log.finer('IdentifyService.close: Completing _closedCompleter.');
  _closedCompleter.complete();
  await _closedCompleter.future;
  _log.fine('IdentifyService.close: Identify service closed.');
}