waitForManagedProcess function

Future<ManagedProcessExit> waitForManagedProcess(
  1. Process process, {
  2. Duration? timeout,
  3. Duration? startupTimeout,
  4. Future<void>? timeoutStartsAfter,
  5. Duration terminationGracePeriod = const Duration(seconds: 3),
  6. Future<ProcessSignal>? interruption,
  7. ProcessSignal? terminateOnStart,
  8. bool signalSender(
    1. ProcessSignal signal
    )?,
  9. Future<List<int>> descendantResolver(
    1. int rootPid
    )?,
})

Waits for process, terminating it on timeout, interruption, or request.

A stuck child is force-killed after terminationGracePeriod. Both termination paths share the process exit future and are bounded even when the operating system does not report the final exit code.

Implementation

Future<ManagedProcessExit> waitForManagedProcess(
  Process process, {
  Duration? timeout,
  Duration? startupTimeout,
  Future<void>? timeoutStartsAfter,
  Duration terminationGracePeriod = const Duration(seconds: 3),
  Future<ProcessSignal>? interruption,

  /// Sends this signal immediately after installing the exit and interruption
  /// handlers. This lets owners request teardown while still snapshotting and
  /// cleaning descendants before the root exits.
  ProcessSignal? terminateOnStart,
  bool Function(ProcessSignal signal)? signalSender,
  Future<List<int>> Function(int rootPid)? descendantResolver,
}) {
  final result = Completer<ManagedProcessExit>();
  final processExit = process.exitCode;
  Timer? timer;
  var timedOut = false;
  var interrupted = false;
  var terminating = false;
  int? observedExitCode;
  final sendSignal = signalSender ?? process.kill;

  void complete(int exitCode) {
    timer?.cancel();
    if (!result.isCompleted) {
      result.complete(ManagedProcessExit(
        exitCode: exitCode,
        timedOut: timedOut,
        interrupted: interrupted,
      ));
    }
  }

  Future<void> terminate(
    ProcessSignal signal, {
    required bool timeout,
    bool interruption = false,
  }) async {
    if (result.isCompleted || terminating) return;
    // The first termination trigger owns the outcome classification. A later
    // timeout or parent interruption can arrive while cleanup awaits process
    // discovery, but must not rewrite the cause selected by this invocation.
    terminating = true;
    timedOut = timeout;
    interrupted = interruption;
    final resolveDescendants = descendantResolver ?? _processDescendants;
    final descendants = <int>{};
    Future<List<int>> descendantsSnapshot(int rootPid, Duration budget) async {
      try {
        final resolution = Future<List<int>>.sync(
          () => resolveDescendants(rootPid),
        ).then<List<int>>(
          (descendants) => descendants,
          onError: (Object _, StackTrace __) => const <int>[],
        );
        return await resolution.timeout(
          budget,
          onTimeout: () => const [],
        );
      } on Object {
        // Descendant discovery is best-effort. A process-table failure must
        // never prevent signaling the managed root or completing its wait.
        return const [];
      }
    }

    descendants.addAll(
      await descendantsSnapshot(process.pid, terminationGracePeriod),
    );
    try {
      sendSignal(signal);
    } catch (_) {
      // A failed graceful signal must not strand the caller. Continue to the
      // forced-kill path and retain the same bounded exit wait.
    }
    // A worker can spawn a subprocess from its SIGTERM handler. Keep sampling
    // while the root is alive so those late descendants are not orphaned when
    // the root is force-killed at the end of the grace period.
    final graceDeadline = DateTime.now().add(terminationGracePeriod);
    while (observedExitCode == null && DateTime.now().isBefore(graceDeadline)) {
      await Future<void>.delayed(const Duration(milliseconds: 25));
      if (observedExitCode != null) break;
      final remaining = graceDeadline.difference(DateTime.now());
      if (remaining <= Duration.zero) break;
      descendants.addAll(await descendantsSnapshot(process.pid, remaining));
    }

    var exitCode = observedExitCode;
    if (exitCode == null) {
      // A child that survives SIGKILL, or whose exit notification is lost,
      // must not block suite teardown indefinitely. A platform-level kill
      // error is equivalent to a missing exit notification at this point.
      try {
        sendSignal(ProcessSignal.sigkill);
      } catch (_) {
        exitCode = -1;
      }
      exitCode ??= await processExit.timeout(
        terminationGracePeriod,
        onTimeout: () => -1,
      );
    }
    await _terminateDescendants(
        descendants.toList(growable: false), signal, terminationGracePeriod);
    complete(exitCode);
  }

  void armTimeout(Duration duration) {
    timer?.cancel();
    timer =
        Timer(duration, () => terminate(ProcessSignal.sigterm, timeout: true));
  }

  processExit.then((exitCode) {
    observedExitCode = exitCode;
    if (!terminating) complete(exitCode);
  });
  interruption?.then(
    (signal) => terminate(signal, timeout: false, interruption: true),
    onError: (Object _, StackTrace __) {
      // Signal delivery is best-effort. A failed signal source must not
      // surface as an unhandled asynchronous error while the managed child
      // continues to its normal exit or configured timeout.
    },
  );
  if (timeoutStartsAfter != null) {
    final startupBudget = startupTimeout ?? timeout;
    if (startupBudget != null) armTimeout(startupBudget);
    timeoutStartsAfter.then((_) {
      if (timeout != null && !result.isCompleted && !terminating) {
        armTimeout(timeout);
      } else if (timeout == null) {
        timer?.cancel();
      }
    });
  } else if (timeout != null) {
    armTimeout(timeout);
  }
  if (terminateOnStart != null) {
    unawaited(terminate(terminateOnStart, timeout: false));
  }
  return result.future;
}