isPreviousSessionStale function

Future<bool> isPreviousSessionStale({
  1. Duration controllerTimeout = const Duration(seconds: 3),
})

True when the session dir records a previous run whose app PID is no longer alive or whose controller does not answer a status request.

A session dir without PID / port / VM URI files is not considered stale: there is nothing left running to clean up.

Implementation

Future<bool> isPreviousSessionStale({
  Duration controllerTimeout = const Duration(seconds: 3),
}) async {
  final hasRuntimeState = [
    controllerPidFile,
    controllerPortFile,
    controllerTokenFile,
    pidFile,
    appPidFile,
    logCollectorPidFile,
    vmUriFile,
  ].any((path) => File(path).existsSync());
  if (!hasRuntimeState) return false;

  final appPid = readAppPid();
  if (appPid != null && !isAppPidAlive(appPid)) return true;

  try {
    await sendControllerCommand(ControllerCommand.status, timeout: controllerTimeout);
    return false;
  } on ControllerCommandFailed {
    // The controller answered, just not with success: it is alive.
    return false;
  } on ControllerUnavailable {
    return true;
  } on AppDiedException {
    return true;
  } on SocketException {
    return true;
  }
}