tomSecretsStartService function

Future<TomSecretsStartResult> tomSecretsStartService({
  1. required String executable,
  2. List<String> arguments = const [],
  3. required String bootstrap,
  4. Map<String, String>? environment,
  5. Duration timeout = const Duration(seconds: 60),
})

Starts the service executable (with arguments) for bootstrap, detached; waits up to timeout for its answer line.

Implementation

Future<TomSecretsStartResult> tomSecretsStartService({
  required String executable,
  List<String> arguments = const [],
  required String bootstrap,
  Map<String, String>? environment,
  Duration timeout = const Duration(seconds: 60),
}) async {
  final key = tomSecretsRandomBytes();
  final process = await Process.start(
    executable,
    arguments,
    mode: ProcessStartMode.detachedWithStdio,
    environment: environment,
  );
  process.stdin.writeln(
    TomSecretsHandover(
      adminKey: key,
      bootstrap: bootstrap,
      starterPid: pid,
    ).toLine(),
  );
  await process.stdin.flush();
  await process.stdin.close();
  final String line;
  try {
    line = await process.stdout
        .transform(utf8.decoder)
        .transform(const LineSplitter())
        .first
        .timeout(timeout);
  } on Object {
    return const TomSecretsStartFailed(
      'no_answer',
      'the service did not answer',
    );
  } finally {
    unawaited(process.stderr.drain<void>());
  }
  final Object? decoded;
  try {
    decoded = jsonDecode(line);
  } on FormatException {
    return const TomSecretsStartFailed(
      'no_answer',
      'the service answered something that is not its status line',
    );
  }
  if (decoded is! Map) {
    return const TomSecretsStartFailed(
      'no_answer',
      'the service answered something that is not its status line',
    );
  }
  final answer = decoded;
  return switch (answer['status']) {
    'ready' => TomSecretsStarted(key),
    'already_running' => const TomSecretsAlreadyStarted(),
    _ => TomSecretsStartFailed(
      '${answer['code'] ?? 'error'}',
      '${answer['message'] ?? ''}',
    ),
  };
}