start method

Future<void> start({
  1. Duration timeout = const Duration(seconds: 15),
})

Pushes the dex, starts the server, and connects; throws AndroidServerError naming the step that failed.

Implementation

Future<void> start({Duration timeout = const Duration(seconds: 15)}) async {
  final push = await runBounded(adbPath, ['-s', serial, 'push', dexPath, _deviceDex],
      timeout: const Duration(seconds: 20), phase: 'adb push of the Android server');
  if (push.exitCode != 0) {
    throw AndroidServerError('adb push of the server failed: ${'${push.stderr}'.trim()}');
  }
  await runBounded(adbPath, ['-s', serial, 'shell', 'pkill', '-f', _socketName],
      timeout: const Duration(seconds: 10), phase: 'adb pkill of the old server');
  final process = await startHelper(
      'android-server',
      adbPath,
      [
        '-s',
        serial,
        'shell',
        'CLASSPATH=$_deviceDex',
        'app_process',
        '/',
        'dev.glint.server.Server',
        _socketName,
      ],
      device: serial,
      owner: 'android:$serial',
      life: HelperLife.attachment);
  _process = process;
  final stderr = StringBuffer();
  process.stderr.transform(utf8.decoder).listen(stderr.write);
  final ready = Completer<int?>();
  process.stdout.transform(utf8.decoder).transform(const LineSplitter()).listen((line) {
    final m = RegExp(r'^ready (\d+)').firstMatch(line);
    if (m != null && !ready.isCompleted) ready.complete(int.parse(m.group(1)!));
  });
  unawaited(process.exitCode.then((_) {
    if (!ready.isCompleted) ready.complete(null);
  }));
  final protocol = await ready.future.timeout(timeout, onTimeout: () => null);
  if (protocol == null) {
    await stop();
    final why = stderr.toString().trim().split('\n').where((l) => l.isNotEmpty).take(3).join(' | ');
    throw AndroidServerError('the server did not start${why.isEmpty ? '' : ': $why'}');
  }
  if (protocol != expectedAndroidServerProtocol) {
    await stop();
    throw AndroidServerError('the server speaks protocol $protocol, glint expects $expectedAndroidServerProtocol');
  }
  final fwd = await runBounded(adbPath, ['-s', serial, 'forward', 'tcp:0', 'localabstract:$_socketName'],
      timeout: const Duration(seconds: 10), phase: 'adb forward');
  _port = int.tryParse('${fwd.stdout}'.trim());
  if (fwd.exitCode != 0 || _port == null) {
    await stop();
    throw AndroidServerError('adb forward failed: ${'${fwd.stderr}'.trim()}');
  }
  final socket = await Socket.connect('127.0.0.1', _port!, timeout: timeout);
  _socket = socket;
  _lines = StreamIterator(socket.cast<List<int>>().transform(utf8.decoder).transform(const LineSplitter()));
  CallProgress.release(process);
}