runAsWorker method

void runAsWorker({
  1. required bool enableLogFiles,
  2. required String outLog,
  3. required String errLog,
  4. required Logger loggerStd,
  5. required Logger loggerFile,
  6. required bool exitAfterBody,
  7. required bool isChildProcess,
  8. required ExitFunc? onExit,
})

Implementation

void runAsWorker({
  required bool enableLogFiles,
  required String outLog,
  required String errLog,
  required Logger loggerStd,
  required Logger loggerFile,
  required bool exitAfterBody,
  required bool isChildProcess,
  required ExitFunc? onExit,
}) async {
  if (enableLogFiles) {
    // Override stdout and stderr with custom
    // file writer implementations
    IOOverrides.global = FileIOOverrides(
      File(outLog),
      File(errLog),
      stdLogger: loggerStd,
      fileLogger: loggerFile,
    );

    // For some reason, the child quits abruptly
    // if [stdout.done] is not listened to
    stdout.done.then((_) {});
  }

  Future<void> workerProgram() async {
    Future<void> customExit() async {
      if (_isExiting) return;

      _isExiting = true;
      _isRunning = false;
      var exitCode = onExit != null ? await onExit() : 0;
      exit(exitCode);
    }

    Future.any([
      Bootstrapper._exitController.stream.first,
      ..._awaitSignals(signals),
    ]).then((_) => customExit());

    if (isChildProcess && onExit != null) {
      _watchForParentExit(customExit);
    }

    await body(args);
    if (exitAfterBody) {
      exit(0);
    }
  }

  void onError(e, s) {
    stderr.writeln(e);
    stderr.writeln(s);
    Bootstrapper.exitGracefully();
  }

  var printToStdout = ZoneSpecification(
    print: (_, __, ___, line) => stdout.writeln(line),
  );

  if (!isChildProcess) {
    return runZoned(workerProgram, zoneSpecification: printToStdout);
  }

  // Run program with custom print function
  return runZonedGuarded(
    workerProgram,
    onError,
    zoneSpecification: printToStdout,
  );
}