run_hot.dart 54.2 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
// @dart = 2.8

7
import 'dart:async';
8

9
import 'package:meta/meta.dart';
10
import 'package:package_config/package_config.dart';
11
import 'package:pool/pool.dart';
12
import 'package:vm_service/vm_service.dart' as vm_service;
13

14
import 'base/common.dart';
15
import 'base/context.dart';
16
import 'base/file_system.dart';
17
import 'base/logger.dart';
18
import 'base/platform.dart';
19
import 'base/utils.dart';
20
import 'build_info.dart';
21
import 'bundle.dart';
22
import 'compile.dart';
23
import 'convert.dart';
24
import 'dart/package_map.dart';
25
import 'devfs.dart';
26
import 'device.dart';
27
import 'features.dart';
28
import 'globals.dart' as globals;
29
import 'project.dart';
30
import 'reporting/reporting.dart';
31
import 'resident_devtools_handler.dart';
32
import 'resident_runner.dart';
33
import 'vmservice.dart';
34

35
ProjectFileInvalidator get projectFileInvalidator => context.get<ProjectFileInvalidator>() ?? ProjectFileInvalidator(
36 37 38
  fileSystem: globals.fs,
  platform: globals.platform,
  logger: globals.logger,
39
);
40 41 42

HotRunnerConfig get hotRunnerConfig => context.get<HotRunnerConfig>();

43 44 45
class HotRunnerConfig {
  /// Should the hot runner assume that the minimal Dart dependencies do not change?
  bool stableDartDependencies = false;
46 47 48 49

  /// Whether the hot runner should scan for modified files asynchronously.
  bool asyncScanning = false;

50 51 52 53 54
  /// A hook for implementations to perform any necessary initialization prior
  /// to a hot restart. Should return true if the hot restart should continue.
  Future<bool> setupHotRestart() async {
    return true;
  }
55 56 57 58 59 60 61 62 63 64 65 66

  /// A hook for implementations to perform any necessary initialization prior
  /// to a hot reload. Should return true if the hot restart should continue.
  Future<bool> setupHotReload() async {
    return true;
  }

  /// A hook for implementations to perform any necessary cleanup after the
  /// devfs sync is complete. At this point the flutter_tools no longer needs to
  /// access the source files and assets.
  void updateDevFSComplete() {}

67 68 69 70 71
  /// A hook for implementations to perform any necessary operations right
  /// before the runner is about to be shut down.
  Future<void> runPreShutdownOperations() async {
    return;
  }
72 73
}

74 75
const bool kHotReloadDefault = true;

76 77 78 79
class DeviceReloadReport {
  DeviceReloadReport(this.device, this.reports);

  FlutterDevice device;
80
  List<vm_service.ReloadReport> reports; // List has one report per Flutter view.
81 82
}

83 84
class HotRunner extends ResidentRunner {
  HotRunner(
85
    List<FlutterDevice> devices, {
86
    @required String target,
87
    @required DebuggingOptions debuggingOptions,
88
    this.benchmarkMode = false,
89
    this.applicationBinary,
90
    this.hostIsIde = false,
91
    String projectRootPath,
92
    String dillOutputPath,
93 94
    bool stayResident = true,
    bool ipv6 = false,
95
    bool machine = false,
96
    this.multidexEnabled = false,
97
    ResidentDevtoolsHandlerFactory devtoolsHandler = createDefaultHandler,
98 99 100 101 102 103 104
    StopwatchFactory stopwatchFactory = const StopwatchFactory(),
    ReloadSourcesHelper reloadSourcesHelper = _defaultReloadSourcesHelper,
    ReassembleHelper reassembleHelper = _defaultReassembleHelper,
  }) : _stopwatchFactory = stopwatchFactory,
       _reloadSourcesHelper = reloadSourcesHelper,
       _reassembleHelper = reassembleHelper,
       super(
105 106 107 108 109 110 111 112 113
          devices,
          target: target,
          debuggingOptions: debuggingOptions,
          projectRootPath: projectRootPath,
          stayResident: stayResident,
          hotMode: true,
          dillOutputPath: dillOutputPath,
          ipv6: ipv6,
          machine: machine,
114
          devtoolsHandler: devtoolsHandler,
115
        );
116

117 118 119 120
  final StopwatchFactory _stopwatchFactory;
  final ReloadSourcesHelper _reloadSourcesHelper;
  final ReassembleHelper _reassembleHelper;

121
  final bool benchmarkMode;
122
  final File applicationBinary;
123
  final bool hostIsIde;
124
  final bool multidexEnabled;
125 126 127 128 129 130 131 132 133 134 135 136 137 138

  /// When performing a hot restart, the tool needs to upload a new main.dart.dill to
  /// each attached device's devfs. Replacing the existing file is not safe and does
  /// not work at all on the windows embedder, because the old dill file will still be
  /// memory-mapped by the embedder. To work around this issue, the tool will alternate
  /// names for the uploaded dill, sometimes inserting `.swap`. Since the active dill will
  /// never be replaced, there is no risk of writing the file while the embedder is attempting
  /// to read from it. This also avoids filling up the devfs, if a incrementing counter was
  /// used instead.
  ///
  /// This is only used for hot restart, incremental dills uploaded as part of the hot
  /// reload process do not have this issue.
  bool _swap = false;

139
  /// Whether the resident runner has correctly attached to the running application.
140
  bool _didAttach = false;
141

142
  final Map<String, List<int>> benchmarkData = <String, List<int>>{};
143

144
  DateTime firstBuildTime;
145

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
  String _targetPlatform;
  String _sdkName;
  bool _emulator;

  Future<void> _calculateTargetPlatform() async {
    if (_targetPlatform != null) {
      return;
    }

    if (flutterDevices.length == 1) {
      final Device device = flutterDevices.first.device;
      _targetPlatform = getNameForTargetPlatform(await device.targetPlatform);
      _sdkName = await device.sdkNameAndVersion;
      _emulator = await device.isLocalEmulator;
    } else if (flutterDevices.length > 1) {
      _targetPlatform = 'multiple';
      _sdkName = 'multiple';
      _emulator = false;
    } else {
      _targetPlatform = 'unknown';
      _sdkName = 'unknown';
      _emulator = false;
    }
  }

171 172 173 174 175
  void _addBenchmarkData(String name, int value) {
    benchmarkData[name] ??= <int>[];
    benchmarkData[name].add(value);
  }

176 177 178 179 180
  Future<void> _reloadSourcesService(
    String isolateId, {
    bool force = false,
    bool pause = false,
  }) async {
181
    final OperationResult result = await restart(pause: pause);
182
    if (!result.isOk) {
183
      throw vm_service.RPCError(
184
        'Unable to reload sources',
185 186
        RPCErrorCodes.kInternalError,
        '',
187 188 189 190
      );
    }
  }

191 192
  Future<void> _restartService({ bool pause = false }) async {
    final OperationResult result =
193
      await restart(fullRestart: true, pause: pause);
194
    if (!result.isOk) {
195
      throw vm_service.RPCError(
196
        'Unable to restart',
197 198
        RPCErrorCodes.kInternalError,
        '',
199 200 201 202
      );
    }
  }

203 204 205 206 207 208 209 210 211
  Future<String> _compileExpressionService(
    String isolateId,
    String expression,
    List<String> definitions,
    List<String> typeDefinitions,
    String libraryUri,
    String klass,
    bool isStatic,
  ) async {
212
    for (final FlutterDevice device in flutterDevices) {
213 214 215 216
      if (device.generator != null) {
        final CompilerOutput compilerOutput =
            await device.generator.compileExpression(expression, definitions,
                typeDefinitions, libraryUri, klass, isStatic);
217 218
        if (compilerOutput != null && compilerOutput.expressionData != null) {
          return base64.encode(compilerOutput.expressionData);
219 220 221
        }
      }
    }
222
    throw 'Failed to compile $expression';
223 224
  }

225
  // Returns the exit code of the flutter tool process, like [run].
226
  @override
227
  Future<int> attach({
228
    Completer<DebugConnectionInfo> connectionInfoCompleter,
229
    Completer<void> appStartedCompleter,
230
    bool allowExistingDdsInstance = false,
231
    bool enableDevTools = false,
232
  }) async {
233
    _didAttach = true;
234
    try {
235 236 237 238 239 240 241
      await connectToServiceProtocol(
        reloadSources: _reloadSourcesService,
        restart: _restartService,
        compileExpression: _compileExpressionService,
        getSkSLMethod: writeSkSL,
        allowExistingDdsInstance: allowExistingDdsInstance,
      );
242 243 244 245 246
    // Catches all exceptions, non-Exception objects are rethrown.
    } catch (error) { // ignore: avoid_catches_without_on_clauses
      if (error is! Exception && error is! String) {
        rethrow;
      }
247
      globals.printError('Error connecting to the service protocol: $error');
248 249 250
      return 2;
    }

251 252
    if (enableDevTools) {
      // The method below is guaranteed never to return a failing future.
253
      unawaited(residentDevtoolsHandler.serveAndAnnounceDevTools(
254
        devToolsServerAddress: debuggingOptions.devToolsServerAddress,
255
        flutterDevices: flutterDevices,
256 257 258
      ));
    }

259
    for (final FlutterDevice device in flutterDevices) {
260
      await device.initLogReader();
261
    }
262
    try {
263
      final List<Uri> baseUris = await _initDevFS();
264
      if (connectionInfoCompleter != null) {
265
        // Only handle one debugger connection.
266
        connectionInfoCompleter.complete(
267
          DebugConnectionInfo(
268 269
            httpUri: flutterDevices.first.vmService.httpAddress,
            wsUri: flutterDevices.first.vmService.wsAddress,
270
            baseUri: baseUris.first.toString(),
271
          ),
272 273
        );
      }
274
    } on DevFSException catch (error) {
275
      globals.printError('Error initializing DevFS: $error');
276 277
      return 3;
    }
278

279
    final Stopwatch initialUpdateDevFSsTimer = Stopwatch()..start();
280
    final UpdateFSReport devfsResult = await _updateDevFS(fullRestart: true);
281 282 283 284
    _addBenchmarkData(
      'hotReloadInitialDevFSSyncMilliseconds',
      initialUpdateDevFSsTimer.elapsed.inMilliseconds,
    );
285
    if (!devfsResult.success) {
286
      return 3;
287
    }
288

289
    for (final FlutterDevice device in flutterDevices) {
290 291
      // VM must have accepted the kernel binary, there will be no reload
      // report, so we let incremental compiler know that source code was accepted.
292
      if (device.generator != null) {
293
        device.generator.accept();
294
      }
295 296
      final List<FlutterView> views = await device.vmService.getFlutterViews();
      for (final FlutterView view in views) {
297
        globals.printTrace('Connected to $view.');
298
      }
299
    }
300

301 302 303 304 305 306 307 308 309 310 311
    // In fast-start mode, apps are initialized from a placeholder splashscreen
    // app. We must do a restart here to load the program and assets for the
    // real app.
    if (debuggingOptions.fastStart) {
      await restart(
        fullRestart: true,
        reason: 'restart',
        silent: true,
      );
    }

312 313 314
    appStartedCompleter?.complete();

    if (benchmarkMode) {
315 316
      // Wait multiple seconds for the isolate to have fully started.
      await Future<void>.delayed(const Duration(seconds: 10));
317
      // We are running in benchmark mode.
318
      globals.printStatus('Running in benchmark mode.');
319
      // Measure time to perform a hot restart.
320
      globals.printStatus('Benchmarking hot restart');
321
      await restart(fullRestart: true);
322
      // Wait multiple seconds to stabilize benchmark on slower device lab hardware.
323 324 325 326
      // Hot restart finishes when the new isolate is started, not when the new isolate
      // is ready. This process can actually take multiple seconds.
      await Future<void>.delayed(const Duration(seconds: 10));

327
      globals.printStatus('Benchmarking hot reload');
328
      // Measure time to perform a hot reload.
329
      await restart();
330 331 332
      if (stayResident) {
        await waitForAppToFinish();
      } else {
333
        globals.printStatus('Benchmark completed. Exiting application.');
334 335
        await _cleanupDevFS();
        await stopEchoingDeviceLog();
336
        await exitApp();
337
      }
338
      final File benchmarkOutput = globals.fs.file('hot_benchmark.json');
339
      benchmarkOutput.writeAsStringSync(toPrettyJson(benchmarkData));
340
      return 0;
341
    }
342
    writeVmServiceFile();
343

344
    int result = 0;
345
    if (stayResident) {
346
      result = await waitForAppToFinish();
347
    }
348
    await cleanupAtFinish();
349
    return result;
350 351
  }

352 353
  @override
  Future<int> run({
354
    Completer<DebugConnectionInfo> connectionInfoCompleter,
355
    Completer<void> appStartedCompleter,
356
    bool enableDevTools = false,
357
    String route,
358
  }) async {
359 360 361
    await _calculateTargetPlatform();

    final Stopwatch appStartedTimer = Stopwatch()..start();
362
    final File mainFile = globals.fs.file(mainPath);
363
    firstBuildTime = DateTime.now();
364

365 366 367
    Duration totalCompileTime = Duration.zero;
    Duration totalLaunchAppTime = Duration.zero;

368
    final List<Future<bool>> startupTasks = <Future<bool>>[];
369
    for (final FlutterDevice device in flutterDevices) {
370 371 372 373
      // Here we initialize the frontend_server concurrently with the platform
      // build, reducing overall initialization time. This is safe because the first
      // invocation of the frontend server produces a full dill file that the
      // subsequent invocation in devfs will not overwrite.
374
      await runSourceGenerators();
375
      if (device.generator != null) {
376
        final Stopwatch compileTimer = Stopwatch()..start();
377 378
        startupTasks.add(
          device.generator.recompile(
379
            mainFile.uri,
380
            <Uri>[],
381 382 383 384 385
            // When running without a provided applicationBinary, the tool will
            // simultaneously run the initial frontend_server compilation and
            // the native build step. If there is a Dart compilation error, it
            // should only be displayed once.
            suppressErrors: applicationBinary == null,
386
            checkDartPluginRegistry: true,
387
            outputPath: dillOutputPath ??
388 389 390
              getDefaultApplicationKernelPath(
                trackWidgetCreation: debuggingOptions.buildInfo.trackWidgetCreation,
              ),
391
            packageConfig: debuggingOptions.buildInfo.packageConfig,
392 393
            projectRootPath: FlutterProject.current().directory.absolute.path,
            fs: globals.fs,
394 395 396 397 398
          ).then((CompilerOutput output) {
            compileTimer.stop();
            totalCompileTime += compileTimer.elapsed;
            return output?.errorCount == 0;
          })
399 400
        );
      }
401 402

      final Stopwatch launchAppTimer = Stopwatch()..start();
403
      startupTasks.add(device.runHot(
404 405
        hotRunner: this,
        route: route,
406 407 408 409
      ).then((int result) {
        totalLaunchAppTime += launchAppTimer.elapsed;
        return result == 0;
      }));
410
    }
411 412 413 414 415

    unawaited(appStartedCompleter?.future?.then((_) => HotEvent('reload-ready',
      targetPlatform: _targetPlatform,
      sdkName: _sdkName,
      emulator: _emulator,
416 417
      fullRestart: false,
      fastReassemble: false,
418 419 420 421 422
      overallTimeInMs: appStartedTimer.elapsed.inMilliseconds,
      compileTimeInMs: totalCompileTime.inMilliseconds,
      transferTimeInMs: totalLaunchAppTime.inMilliseconds,
    )?.send()));

423 424 425
    try {
      final List<bool> results = await Future.wait(startupTasks);
      if (!results.every((bool passed) => passed)) {
426
        appFailedToStart();
427
        return 1;
428
      }
429
      cacheInitialDillCompilation();
430 431
    } on Exception catch (err) {
      globals.printError(err.toString());
432
      appFailedToStart();
433
      return 1;
434 435
    }

436 437
    return attach(
      connectionInfoCompleter: connectionInfoCompleter,
438
      appStartedCompleter: appStartedCompleter,
439
      enableDevTools: enableDevTools,
440
    );
441 442
  }

443
  Future<List<Uri>> _initDevFS() async {
444
    final String fsName = globals.fs.path.basename(projectRootPath);
445
    return <Uri>[
446
      for (final FlutterDevice device in flutterDevices)
447 448
        await device.setupDevFS(
          fsName,
449
          globals.fs.directory(projectRootPath),
450 451
        ),
    ];
452
  }
453

454
  Future<UpdateFSReport> _updateDevFS({ bool fullRestart = false }) async {
455
    final bool isFirstUpload = !assetBundle.wasBuiltOnce();
456
    final bool rebuildBundle = assetBundle.needsBuild();
457
    if (rebuildBundle) {
458
      globals.printTrace('Updating assets');
459
      final int result = await assetBundle.build(packagesPath: '.packages');
460
      if (result != 0) {
461
        return UpdateFSReport();
462
      }
463
    }
464

465
    final Stopwatch findInvalidationTimer = _stopwatchFactory.createStopwatch('updateDevFS')..start();
466
    final InvalidationResult invalidationResult = await projectFileInvalidator.findInvalidated(
467
      lastCompiled: flutterDevices[0].devFS.lastCompiled,
468 469
      urisToMonitor: flutterDevices[0].devFS.sources,
      packagesPath: packagesFilePath,
470
      asyncScanning: hotRunnerConfig.asyncScanning,
471 472
      packageConfig: flutterDevices[0].devFS.lastPackageConfig
          ?? debuggingOptions.buildInfo.packageConfig,
473
    );
474
    findInvalidationTimer.stop();
475 476 477 478 479 480 481 482 483
    final File entrypointFile = globals.fs.file(mainPath);
    if (!entrypointFile.existsSync()) {
      globals.printError(
        'The entrypoint file (i.e. the file with main()) ${entrypointFile.path} '
        'cannot be found. Moving or renaming this file will prevent changes to '
        'its contents from being discovered during hot reload/restart until '
        'flutter is restarted or the file is restored.'
      );
    }
484 485 486 487 488
    final UpdateFSReport results = UpdateFSReport(
      success: true,
      scannedSourcesCount: flutterDevices[0].devFS.sources.length,
      findInvalidatedDuration: findInvalidationTimer.elapsed,
    );
489
    for (final FlutterDevice device in flutterDevices) {
490
      results.incorporateResults(await device.updateDevFS(
491
        mainUri: entrypointFile.absolute.uri,
492
        target: target,
493
        bundle: assetBundle,
494 495
        firstBuildTime: firstBuildTime,
        bundleFirstUpload: isFirstUpload,
496
        bundleDirty: !isFirstUpload && rebuildBundle,
497 498
        fullRestart: fullRestart,
        projectRootPath: projectRootPath,
499
        pathToReload: getReloadPath(fullRestart: fullRestart, swap: _swap),
500 501
        invalidatedFiles: invalidationResult.uris,
        packageConfig: invalidationResult.packageConfig,
502
        dillOutputPath: dillOutputPath,
503 504
      ));
    }
505
    return results;
506 507
  }

508
  void _resetDirtyAssets() {
509
    for (final FlutterDevice device in flutterDevices) {
510
      device.devFS.assetPathsToEvict.clear();
511
    }
512 513
  }

514
  Future<void> _cleanupDevFS() async {
515
    final List<Future<void>> futures = <Future<void>>[];
516
    for (final FlutterDevice device in flutterDevices) {
517
      if (device.devFS != null) {
518 519
        // Cleanup the devFS, but don't wait indefinitely.
        // We ignore any errors, because it's not clear what we would do anyway.
520
        futures.add(device.devFS.destroy()
521 522
          .timeout(const Duration(milliseconds: 250))
          .catchError((dynamic error) {
523
            globals.printTrace('Ignored error while cleaning up DevFS: $error');
524
          }));
525 526 527
      }
      device.devFS = null;
    }
528
    await Future.wait(futures);
529 530
  }

531 532
  Future<void> _launchInView(
    FlutterDevice device,
533 534 535
    Uri main,
    Uri assetsDirectory,
  ) async {
536
    final List<FlutterView> views = await device.vmService.getFlutterViews();
537
    await Future.wait(<Future<void>>[
538
      for (final FlutterView view in views)
539 540 541 542 543
        device.vmService.runInView(
          viewId: view.id,
          main: main,
          assetsDirectory: assetsDirectory,
        ),
544
    ]);
545 546
  }

547
  Future<void> _launchFromDevFS() async {
548
    final List<Future<void>> futures = <Future<void>>[];
549
    for (final FlutterDevice device in flutterDevices) {
550
      final Uri deviceEntryUri = device.devFS.baseUri.resolve(_swap ? 'main.dart.swap.dill' : 'main.dart.dill');
551
      final Uri deviceAssetsDirectoryUri = device.devFS.baseUri.resolveUri(
552
        globals.fs.path.toUri(getAssetBuildDirectory()));
553
      futures.add(_launchInView(device,
554
                          deviceEntryUri,
555
                          deviceAssetsDirectoryUri));
556
    }
557
    await Future.wait(futures);
558 559
  }

560 561 562
  Future<OperationResult> _restartFromSources({
    String reason,
  }) async {
563
    final Stopwatch restartTimer = Stopwatch()..start();
564 565 566 567 568 569
    UpdateFSReport updatedDevFS;
    try {
      updatedDevFS = await _updateDevFS(fullRestart: true);
    } finally {
      hotRunnerConfig.updateDevFSComplete();
    }
570
    if (!updatedDevFS.success) {
571
      for (final FlutterDevice device in flutterDevices) {
572
        if (device.generator != null) {
573
          await device.generator.reject();
574
        }
575
      }
576
      return OperationResult(1, 'DevFS synchronization failed');
577 578
    }
    _resetDirtyAssets();
579
    for (final FlutterDevice device in flutterDevices) {
580 581
      // VM must have accepted the kernel binary, there will be no reload
      // report, so we let incremental compiler know that source code was accepted.
582
      if (device.generator != null) {
583
        device.generator.accept();
584
      }
585
    }
586
    // Check if the isolate is paused and resume it.
587
    final List<Future<void>> operations = <Future<void>>[];
588
    for (final FlutterDevice device in flutterDevices) {
589
      final Set<String> uiIsolatesIds = <String>{};
590 591
      final List<FlutterView> views = await device.vmService.getFlutterViews();
      for (final FlutterView view in views) {
592 593
        if (view.uiIsolate == null) {
          continue;
594
        }
595
        uiIsolatesIds.add(view.uiIsolate.id);
596
        // Reload the isolate.
597 598 599 600
        final Future<vm_service.Isolate> reloadIsolate = device.vmService
          .getIsolateOrNull(view.uiIsolate.id);
        operations.add(reloadIsolate.then((vm_service.Isolate isolate) async {
          if ((isolate != null) && isPauseEvent(isolate.pauseEvent.kind)) {
601 602 603
            // The embedder requires that the isolate is unpaused, because the
            // runInView method requires interaction with dart engine APIs that
            // are not thread-safe, and thus must be run on the same thread that
604
            // would be blocked by the pause. Simply un-pausing is not sufficient,
605 606 607 608 609 610
            // because this does not prevent the isolate from immediately hitting
            // a breakpoint, for example if the breakpoint was placed in a loop
            // or in a frequently called method. Instead, all breakpoints are first
            // disabled and then the isolate resumed.
            final List<Future<void>> breakpointRemoval = <Future<void>>[
              for (final vm_service.Breakpoint breakpoint in isolate.breakpoints)
611
                device.vmService.service.removeBreakpoint(isolate.id, breakpoint.id)
612 613
            ];
            await Future.wait(breakpointRemoval);
614
            await device.vmService.service.resume(view.uiIsolate.id);
615 616
          }
        }));
617
      }
618

619 620
      // The engine handles killing and recreating isolates that it has spawned
      // ("uiIsolates"). The isolates that were spawned from these uiIsolates
621
      // will not be restarted, and so they must be manually killed.
622
      final vm_service.VM vm = await device.vmService.service.getVM();
623 624 625
      for (final vm_service.IsolateRef isolateRef in vm.isolates) {
        if (uiIsolatesIds.contains(isolateRef.id)) {
          continue;
626
        }
627
        operations.add(device.vmService.service.kill(isolateRef.id)
628 629 630
          .catchError((dynamic error, StackTrace stackTrace) {
            // Do nothing on a SentinelException since it means the isolate
            // has already been killed.
631 632 633 634 635
            // Error code 105 indicates the isolate is not yet runnable, and might
            // be triggered if the tool is attempting to kill the asset parsing
            // isolate before it has finished starting up.
          }, test: (dynamic error) => error is vm_service.SentinelException
            || (error is vm_service.RPCError && error.code == 105)));
636
      }
637
    }
638
    await Future.wait(operations);
639

640
    await _launchFromDevFS();
641
    restartTimer.stop();
642
    globals.printTrace('Hot restart performed in ${getElapsedAsMilliseconds(restartTimer.elapsed)}.');
643 644
    _addBenchmarkData('hotRestartMillisecondsToFrame',
        restartTimer.elapsed.inMilliseconds);
645 646

    // Send timing analytics.
647
    globals.flutterUsage.sendTiming('hot', 'restart', restartTimer.elapsed);
648

649 650 651
    // Toggle the main dill name after successfully uploading.
    _swap =! _swap;

652 653 654 655 656
    return OperationResult(
      OperationResult.ok.code,
      OperationResult.ok.message,
      updateFSReport: updatedDevFS,
    );
657 658 659
  }

  /// Returns [true] if the reload was successful.
660
  /// Prints errors if [printErrors] is [true].
661
  static bool validateReloadReport(
662
    vm_service.ReloadReport reloadReport, {
663 664
    bool printErrors = true,
  }) {
665
    if (reloadReport == null) {
666
      if (printErrors) {
667
        globals.printError('Hot reload did not receive reload report.');
668
      }
669 670
      return false;
    }
671 672
    final ReloadReportContents contents = ReloadReportContents.fromReloadReport(reloadReport);
    if (!reloadReport.success) {
673
      if (printErrors) {
674
        globals.printError('Hot reload was rejected:');
675 676
        for (final ReasonForCancelling reason in contents.notices) {
          globals.printError(reason.toString());
677
        }
678
      }
679 680 681 682 683
      return false;
    }
    return true;
  }

684
  @override
685 686 687
  Future<OperationResult> restart({
    bool fullRestart = false,
    String reason,
688 689
    bool silent = false,
    bool pause = false,
690
  }) async {
691 692 693
    if (flutterDevices.any((FlutterDevice device) => device.devFS == null)) {
      return OperationResult(1, 'Device initialization has not completed.');
    }
694
    await _calculateTargetPlatform();
695
    final Stopwatch timer = Stopwatch()..start();
696 697 698 699

    // Run source generation if needed.
    await runSourceGenerators();

700
    if (fullRestart) {
701
      final OperationResult result = await _fullRestartHelper(
702 703 704
        targetPlatform: _targetPlatform,
        sdkName: _sdkName,
        emulator: _emulator,
705
        reason: reason,
706
        silent: silent,
707
      );
708
      if (!silent) {
709
        globals.printStatus('Restarted application in ${getElapsedAsMilliseconds(timer.elapsed)}.');
710
      }
711
      unawaited(residentDevtoolsHandler.hotRestart(flutterDevices));
712 713 714
      return result;
    }
    final OperationResult result = await _hotReloadHelper(
715 716 717
      targetPlatform: _targetPlatform,
      sdkName: _sdkName,
      emulator: _emulator,
718
      reason: reason,
719
      pause: pause,
720 721 722
    );
    if (result.isOk) {
      final String elapsed = getElapsedAsMilliseconds(timer.elapsed);
723
      if (!silent) {
724
        globals.printStatus('${result.message} in $elapsed.');
725
      }
726 727 728 729 730 731 732 733 734
    }
    return result;
  }

  Future<OperationResult> _fullRestartHelper({
    String targetPlatform,
    String sdkName,
    bool emulator,
    String reason,
735
    bool silent,
736
  }) async {
737
    if (!supportsRestart) {
738 739
      return OperationResult(1, 'hotRestart not supported');
    }
740 741
    Status status;
    if (!silent) {
742
      status = globals.logger.startProgress(
743 744 745 746
        'Performing hot restart...',
        progressId: 'hot.restart',
      );
    }
747
    OperationResult result;
748
    String restartEvent;
749
    try {
750
      final Stopwatch restartTimer = _stopwatchFactory.createStopwatch('fullRestartHelper')..start();
751 752
      if (!(await hotRunnerConfig.setupHotRestart())) {
        return OperationResult(1, 'setupHotRestart failed');
Devon Carew's avatar
Devon Carew committed
753
      }
754 755
      result = await _restartFromSources(reason: reason);
      restartTimer.stop();
756 757
      if (!result.isOk) {
        restartEvent = 'restart-failed';
758 759 760 761 762 763 764
      } else {
        HotEvent('restart',
          targetPlatform: targetPlatform,
          sdkName: sdkName,
          emulator: emulator,
          fullRestart: true,
          reason: reason,
765
          fastReassemble: false,
766 767 768 769 770 771 772 773
          overallTimeInMs: restartTimer.elapsed.inMilliseconds,
          syncedBytes: result.updateFSReport?.syncedBytes,
          invalidatedSourcesCount: result.updateFSReport?.invalidatedSourcesCount,
          transferTimeInMs: result.updateFSReport?.transferDuration?.inMilliseconds,
          compileTimeInMs: result.updateFSReport?.compileDuration?.inMilliseconds,
          findInvalidatedTimeInMs: result.updateFSReport?.findInvalidatedDuration?.inMilliseconds,
          scannedSourcesCount: result.updateFSReport?.scannedSourcesCount,
        ).send();
774
      }
775 776 777 778
    } on vm_service.SentinelException catch (err, st) {
      restartEvent = 'exception';
      return OperationResult(1, 'hot restart failed to complete: $err\n$st', fatal: true);
    } on vm_service.RPCError  catch (err, st) {
779
      restartEvent = 'exception';
780
      return OperationResult(1, 'hot restart failed to complete: $err\n$st', fatal: true);
781
    } finally {
782 783 784 785 786 787 788 789 790
      // The `restartEvent` variable will be null if restart succeeded. We will
      // only handle the case when it failed here.
      if (restartEvent != null) {
        HotEvent(restartEvent,
          targetPlatform: targetPlatform,
          sdkName: sdkName,
          emulator: emulator,
          fullRestart: true,
          reason: reason,
791
          fastReassemble: false,
792 793
        ).send();
      }
794
      status?.cancel();
795
    }
796
    return result;
797
  }
798

799 800 801 802 803
  Future<OperationResult> _hotReloadHelper({
    String targetPlatform,
    String sdkName,
    bool emulator,
    String reason,
804
    bool pause,
805
  }) async {
806
    Status status = globals.logger.startProgress(
807
      'Performing hot reload...',
808 809 810 811 812 813 814 815 816
      progressId: 'hot.reload',
    );
    OperationResult result;
    try {
      result = await _reloadSources(
        targetPlatform: targetPlatform,
        sdkName: sdkName,
        emulator: emulator,
        reason: reason,
817
        pause: pause,
818 819
        onSlow: (String message) {
          status?.cancel();
820
          status = globals.logger.startProgress(
821 822 823 824 825
            message,
            progressId: 'hot.reload',
          );
        },
      );
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
    } on vm_service.RPCError catch (error) {
      String errorMessage = 'hot reload failed to complete';
      int errorCode = 1;
      if (error.code == kIsolateReloadBarred) {
        errorCode = error.code;
        errorMessage = 'Unable to hot reload application due to an unrecoverable error in '
                      'the source code. Please address the error and then use "R" to '
                      'restart the app.\n'
                      '${error.message} (error code: ${error.code})';
        HotEvent('reload-barred',
          targetPlatform: targetPlatform,
          sdkName: sdkName,
          emulator: emulator,
          fullRestart: false,
          reason: reason,
841
          fastReassemble: false,
842 843 844 845 846 847 848 849
        ).send();
      } else {
        HotEvent('exception',
          targetPlatform: targetPlatform,
          sdkName: sdkName,
          emulator: emulator,
          fullRestart: false,
          reason: reason,
850
          fastReassemble: false,
851 852 853
        ).send();
      }
      return OperationResult(errorCode, errorMessage, fatal: true);
854 855
    } finally {
      status.cancel();
856
    }
857 858 859 860 861 862 863 864 865
    return result;
  }

  Future<OperationResult> _reloadSources({
    String targetPlatform,
    String sdkName,
    bool emulator,
    bool pause = false,
    String reason,
866
    void Function(String message) onSlow,
867
  }) async {
868
    final Map<FlutterDevice, List<FlutterView>> viewCache = <FlutterDevice, List<FlutterView>>{};
869
    for (final FlutterDevice device in flutterDevices) {
870
      final List<FlutterView> views = await device.vmService.getFlutterViews();
871
      viewCache[device] = views;
872
      for (final FlutterView view in views) {
873
        if (view.uiIsolate == null) {
874
          return OperationResult(2, 'Application isolate not found', fatal: true);
875
        }
876 877
      }
    }
878

879
    final Stopwatch reloadTimer = _stopwatchFactory.createStopwatch('reloadSources:reload')..start();
880 881 882
    if (!(await hotRunnerConfig.setupHotReload())) {
      return OperationResult(1, 'setupHotReload failed');
    }
883
    final Stopwatch devFSTimer = Stopwatch()..start();
884 885 886 887 888 889
    UpdateFSReport updatedDevFS;
    try {
      updatedDevFS= await _updateDevFS();
    } finally {
      hotRunnerConfig.updateDevFSComplete();
    }
890
    // Record time it took to synchronize to DevFS.
891
    bool shouldReportReloadTime = true;
892
    _addBenchmarkData('hotReloadDevFSSyncMilliseconds', devFSTimer.elapsed.inMilliseconds);
893
    if (!updatedDevFS.success) {
894
      return OperationResult(1, 'DevFS synchronization failed');
895
    }
896
    String reloadMessage = 'Reloaded 0 libraries';
897
    final Stopwatch reloadVMTimer = _stopwatchFactory.createStopwatch('reloadSources:vm')..start();
898 899 900
    final Map<String, Object> firstReloadDetails = <String, Object>{};
    if (updatedDevFS.invalidatedSourcesCount > 0) {
      final OperationResult result = await _reloadSourcesHelper(
901 902
        this,
        flutterDevices,
903 904 905 906 907 908
        pause,
        firstReloadDetails,
        targetPlatform,
        sdkName,
        emulator,
        reason,
909
      );
910 911
      if (result.code != 0) {
        return result;
912
      }
913
      reloadMessage = result.message;
914 915
    } else {
      _addBenchmarkData('hotReloadVMReloadMilliseconds', 0);
916
    }
917
    reloadVMTimer.stop();
918

919
    await evictDirtyAssets();
920

921
    final Stopwatch reassembleTimer = _stopwatchFactory.createStopwatch('reloadSources:reassemble')..start();
922

923 924 925 926 927 928
    final ReassembleResult reassembleResult = await _reassembleHelper(
      flutterDevices,
      viewCache,
      onSlow,
      reloadMessage,
      updatedDevFS.fastReassembleClassName,
929
    );
930 931 932 933
    shouldReportReloadTime = reassembleResult.shouldReportReloadTime;
    if (reassembleResult.reassembleViews.isEmpty) {
      return OperationResult(OperationResult.ok.code, reloadMessage);
    }
934
    // Record time it took for Flutter to reassemble the application.
935
    reassembleTimer.stop();
936
    _addBenchmarkData('hotReloadFlutterReassembleMilliseconds', reassembleTimer.elapsed.inMilliseconds);
937

938
    reloadTimer.stop();
939 940 941
    final Duration reloadDuration = reloadTimer.elapsed;
    final int reloadInMs = reloadDuration.inMilliseconds;

942 943 944 945 946 947 948 949 950 951 952 953
    // Collect stats that help understand scale of update for this hot reload request.
    // For example, [syncedLibraryCount]/[finalLibraryCount] indicates how
    // many libraries were affected by the hot reload request.
    // Relation of [invalidatedSourcesCount] to [syncedLibraryCount] should help
    // understand sync/transfer "overhead" of updating this number of source files.
    HotEvent('reload',
      targetPlatform: targetPlatform,
      sdkName: sdkName,
      emulator: emulator,
      fullRestart: false,
      reason: reason,
      overallTimeInMs: reloadInMs,
954 955 956 957
      finalLibraryCount: firstReloadDetails['finalLibraryCount'] as int ?? 0,
      syncedLibraryCount: firstReloadDetails['receivedLibraryCount'] as int ?? 0,
      syncedClassesCount: firstReloadDetails['receivedClassesCount'] as int ?? 0,
      syncedProceduresCount: firstReloadDetails['receivedProceduresCount'] as int ?? 0,
958 959
      syncedBytes: updatedDevFS.syncedBytes,
      invalidatedSourcesCount: updatedDevFS.invalidatedSourcesCount,
960
      transferTimeInMs: updatedDevFS.transferDuration.inMilliseconds,
961 962 963
      fastReassemble: featureFlags.isSingleWidgetReloadEnabled
        ? updatedDevFS.fastReassembleClassName != null
        : null,
964 965 966 967 968
      compileTimeInMs: updatedDevFS.compileDuration.inMilliseconds,
      findInvalidatedTimeInMs: updatedDevFS.findInvalidatedDuration.inMilliseconds,
      scannedSourcesCount: updatedDevFS.scannedSourcesCount,
      reassembleTimeInMs: reassembleTimer.elapsed.inMilliseconds,
      reloadVMTimeInMs: reloadVMTimer.elapsed.inMilliseconds,
969
    ).send();
970

971
    if (shouldReportReloadTime) {
972
      globals.printTrace('Hot reload performed in ${getElapsedAsMilliseconds(reloadDuration)}.');
973 974 975 976
      // Record complete time it took for the reload.
      _addBenchmarkData('hotReloadMillisecondsToFrame', reloadInMs);
    }
    // Only report timings if we reloaded a single view without any errors.
977
    if ((reassembleResult.reassembleViews.length == 1) && !reassembleResult.failedReassemble && shouldReportReloadTime) {
978
      globals.flutterUsage.sendTiming('hot', 'reload', reloadDuration);
979
    }
980
    return OperationResult(
981
      reassembleResult.failedReassemble ? 1 : OperationResult.ok.code,
982
      reloadMessage,
983
    );
984 985 986
  }

  @override
987
  void printHelp({ @required bool details }) {
988
    globals.printStatus('Flutter run key commands.');
989
    commandHelp.r.print();
990
    if (supportsRestart) {
991
      commandHelp.R.print();
992
    }
993 994 995 996 997 998
    if (details) {
      printHelpDetails();
      commandHelp.hWithDetails.print();
    } else {
      commandHelp.hWithoutDetails.print();
    }
999
    if (_didAttach) {
1000
      commandHelp.d.print();
1001
    }
1002
    commandHelp.c.print();
1003
    commandHelp.q.print();
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
    globals.printStatus('');
    if (debuggingOptions.buildInfo.nullSafetyMode ==  NullSafetyMode.sound) {
      globals.printStatus('💪 Running with sound null safety 💪', emphasis: true);
    } else {
      globals.printStatus(
        'Running with unsound null safety',
        emphasis: true,
      );
      globals.printStatus(
        'For more information see https://dart.dev/null-safety/unsound-null-safety',
      );
    }
1016 1017
    globals.printStatus('');
    printDebuggerList();
1018 1019
  }

1020 1021
  @visibleForTesting
  Future<void> evictDirtyAssets() async {
1022
    final List<Future<Map<String, dynamic>>> futures = <Future<Map<String, dynamic>>>[];
1023
    for (final FlutterDevice device in flutterDevices) {
1024
      if (device.devFS.assetPathsToEvict.isEmpty) {
1025
        continue;
1026
      }
1027
      final List<FlutterView> views = await device.vmService.getFlutterViews();
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044

      // If this is the first time we update the assets, make sure to call the setAssetDirectory
      if (!device.devFS.hasSetAssetDirectory) {
        final Uri deviceAssetsDirectoryUri = device.devFS.baseUri.resolveUri(globals.fs.path.toUri(getAssetBuildDirectory()));
        await Future.wait<void>(views.map<Future<void>>(
          (FlutterView view) => device.vmService.setAssetDirectory(
            assetsDirectory: deviceAssetsDirectoryUri,
            uiIsolateId: view.uiIsolate.id,
            viewId: view.id,
          )
        ));
        for (final FlutterView view in views) {
          globals.printTrace('Set asset directory in $view.');
        }
        device.devFS.hasSetAssetDirectory = true;
      }

1045
      if (views.first.uiIsolate == null) {
1046
        globals.printError('Application isolate not found for $device');
1047 1048
        continue;
      }
1049
      for (final String assetPath in device.devFS.assetPathsToEvict) {
1050
        futures.add(
1051
          device.vmService
1052 1053
            .flutterEvictAsset(
              assetPath,
1054
              isolateId: views.first.uiIsolate.id,
1055 1056
            )
        );
1057 1058 1059 1060 1061 1062
      }
      device.devFS.assetPathsToEvict.clear();
    }
    return Future.wait<Map<String, dynamic>>(futures);
  }

1063
  @override
1064
  Future<void> cleanupAfterSignal() async {
1065
    await stopEchoingDeviceLog();
1066
    await hotRunnerConfig.runPreShutdownOperations();
1067 1068 1069
    if (_didAttach) {
      appFinished();
    } else {
1070
      await exitApp();
1071
    }
1072 1073
  }

1074
  @override
1075
  Future<void> preExit() async {
1076 1077
    await _cleanupDevFS();
    await hotRunnerConfig.runPreShutdownOperations();
1078
    await super.preExit();
1079
  }
1080

1081
  @override
1082
  Future<void> cleanupAtFinish() async {
1083
    for (final FlutterDevice flutterDevice in flutterDevices) {
1084
      await flutterDevice.device.dispose();
1085
    }
1086
    await _cleanupDevFS();
1087
    await residentDevtoolsHandler.shutdown();
1088 1089 1090
    await stopEchoingDeviceLog();
  }
}
1091

1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
typedef ReloadSourcesHelper = Future<OperationResult> Function(
  HotRunner hotRunner,
  List<FlutterDevice> flutterDevices,
  bool pause,
  Map<String, dynamic> firstReloadDetails,
  String targetPlatform,
  String sdkName,
  bool emulator,
  String reason,
);

Future<OperationResult> _defaultReloadSourcesHelper(
  HotRunner hotRunner,
  List<FlutterDevice> flutterDevices,
  bool pause,
  Map<String, dynamic> firstReloadDetails,
  String targetPlatform,
  String sdkName,
  bool emulator,
  String reason,
) async {
  final Stopwatch vmReloadTimer = Stopwatch()..start();
  const String entryPath = 'main.dart.incremental.dill';
  final List<Future<DeviceReloadReport>> allReportsFutures = <Future<DeviceReloadReport>>[];

  for (final FlutterDevice device in flutterDevices) {
    final List<Future<vm_service.ReloadReport>> reportFutures = await _reloadDeviceSources(
      device,
      entryPath,
      pause: pause,
    );
    allReportsFutures.add(Future.wait(reportFutures).then(
      (List<vm_service.ReloadReport> reports) async {
        // TODO(aam): Investigate why we are validating only first reload report,
        // which seems to be current behavior
        final vm_service.ReloadReport firstReport = reports.first;
        // Don't print errors because they will be printed further down when
        // `validateReloadReport` is called again.
        await device.updateReloadStatus(
          HotRunner.validateReloadReport(firstReport, printErrors: false),
        );
        return DeviceReloadReport(device, reports);
      },
    ));
  }
  final List<DeviceReloadReport> reports = await Future.wait(allReportsFutures);
  final vm_service.ReloadReport reloadReport = reports.first.reports[0];
  if (!HotRunner.validateReloadReport(reloadReport)) {
    // Reload failed.
    HotEvent('reload-reject',
      targetPlatform: targetPlatform,
      sdkName: sdkName,
      emulator: emulator,
      fullRestart: false,
      reason: reason,
1147
      fastReassemble: false,
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    ).send();
    // Reset devFS lastCompileTime to ensure the file will still be marked
    // as dirty on subsequent reloads.
    _resetDevFSCompileTime(flutterDevices);
    final ReloadReportContents contents = ReloadReportContents.fromReloadReport(reloadReport);
    return OperationResult(1, 'Reload rejected: ${contents.notices.join("\n")}');
  }
  // Collect stats only from the first device. If/when run -d all is
  // refactored, we'll probably need to send one hot reload/restart event
  // per device to analytics.
  firstReloadDetails.addAll(castStringKeyedMap(reloadReport.json['details']));
1159 1160 1161
  final Map<String, dynamic> details = reloadReport.json['details'] as Map<String, dynamic>;
  final int loadedLibraryCount = details['loadedLibraryCount'] as int;
  final int finalLibraryCount = details['finalLibraryCount'] as int;
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
  globals.printTrace('reloaded $loadedLibraryCount of $finalLibraryCount libraries');
  // reloadMessage = 'Reloaded $loadedLibraryCount of $finalLibraryCount libraries';
  // Record time it took for the VM to reload the sources.
  hotRunner._addBenchmarkData('hotReloadVMReloadMilliseconds', vmReloadTimer.elapsed.inMilliseconds);
  return OperationResult(0, 'Reloaded $loadedLibraryCount of $finalLibraryCount libraries');
}

Future<List<Future<vm_service.ReloadReport>>> _reloadDeviceSources(
  FlutterDevice device,
  String entryPath, {
  bool pause = false,
}) async {
  final String deviceEntryUri = device.devFS.baseUri
    .resolve(entryPath).toString();
  final vm_service.VM vm = await device.vmService.service.getVM();
  return <Future<vm_service.ReloadReport>>[
    for (final vm_service.IsolateRef isolateRef in vm.isolates)
      device.vmService.service.reloadSources(
        isolateRef.id,
        pause: pause,
        rootLibUri: deviceEntryUri,
      )
  ];
}

void _resetDevFSCompileTime(List<FlutterDevice> flutterDevices) {
  for (final FlutterDevice device in flutterDevices) {
    device.devFS.resetLastCompiled();
  }
}

@visibleForTesting
class ReassembleResult {
  ReassembleResult(this.reassembleViews, this.failedReassemble, this.shouldReportReloadTime);
  final Map<FlutterView, FlutterVmService> reassembleViews;
  final bool failedReassemble;
  final bool shouldReportReloadTime;
}

typedef ReassembleHelper = Future<ReassembleResult> Function(
  List<FlutterDevice> flutterDevices,
  Map<FlutterDevice, List<FlutterView>> viewCache,
  void Function(String message) onSlow,
  String reloadMessage,
  String fastReassembleClassName,
);

Future<ReassembleResult> _defaultReassembleHelper(
  List<FlutterDevice> flutterDevices,
  Map<FlutterDevice, List<FlutterView>> viewCache,
  void Function(String message) onSlow,
  String reloadMessage,
  String fastReassembleClassName,
) async {
  // Check if any isolates are paused and reassemble those that aren't.
  final Map<FlutterView, FlutterVmService> reassembleViews = <FlutterView, FlutterVmService>{};
  final List<Future<void>> reassembleFutures = <Future<void>>[];
  String serviceEventKind;
  int pausedIsolatesFound = 0;
  bool failedReassemble = false;
  bool shouldReportReloadTime = true;
  for (final FlutterDevice device in flutterDevices) {
    final List<FlutterView> views = viewCache[device];
    for (final FlutterView view in views) {
      // Check if the isolate is paused, and if so, don't reassemble. Ignore the
      // PostPauseEvent event - the client requesting the pause will resume the app.
      final vm_service.Isolate isolate = await device.vmService
        .getIsolateOrNull(view.uiIsolate.id);
      final vm_service.Event pauseEvent = isolate?.pauseEvent;
      if (pauseEvent != null
        && isPauseEvent(pauseEvent.kind)
        && pauseEvent.kind != vm_service.EventKind.kPausePostRequest) {
        pausedIsolatesFound += 1;
        if (serviceEventKind == null) {
          serviceEventKind = pauseEvent.kind;
        } else if (serviceEventKind != pauseEvent.kind) {
          serviceEventKind = ''; // many kinds
        }
      } else {
        reassembleViews[view] = device.vmService;
        // If the tool identified a change in a single widget, do a fast instead
        // of a full reassemble.
        Future<void> reassembleWork;
        if (fastReassembleClassName != null) {
          reassembleWork = device.vmService.flutterFastReassemble(
            isolateId: view.uiIsolate.id,
            className: fastReassembleClassName,
          );
        } else {
          reassembleWork = device.vmService.flutterReassemble(
            isolateId: view.uiIsolate.id,
          );
        }
        reassembleFutures.add(reassembleWork.catchError((dynamic error) {
          failedReassemble = true;
          globals.printError('Reassembling ${view.uiIsolate.name} failed: $error');
        }, test: (dynamic error) => error is Exception));
      }
    }
  }
  if (pausedIsolatesFound > 0) {
    if (onSlow != null) {
      onSlow('${_describePausedIsolates(pausedIsolatesFound, serviceEventKind)}; interface might not update.');
    }
    if (reassembleViews.isEmpty) {
      globals.printTrace('Skipping reassemble because all isolates are paused.');
      return ReassembleResult(reassembleViews, failedReassemble, shouldReportReloadTime);
    }
  }
  assert(reassembleViews.isNotEmpty);

  globals.printTrace('Reassembling application');

  final Future<void> reassembleFuture = Future.wait<void>(reassembleFutures);
  await reassembleFuture.timeout(
    const Duration(seconds: 2),
    onTimeout: () async {
      if (pausedIsolatesFound > 0) {
        shouldReportReloadTime = false;
        return; // probably no point waiting, they're probably deadlocked and we've already warned.
      }
      // Check if any isolate is newly paused.
      globals.printTrace('This is taking a long time; will now check for paused isolates.');
      int postReloadPausedIsolatesFound = 0;
      String serviceEventKind;
      for (final FlutterView view in reassembleViews.keys) {
        final vm_service.Isolate isolate = await reassembleViews[view]
          .getIsolateOrNull(view.uiIsolate.id);
        if (isolate == null) {
          continue;
        }
        if (isolate.pauseEvent != null && isPauseEvent(isolate.pauseEvent.kind)) {
          postReloadPausedIsolatesFound += 1;
          if (serviceEventKind == null) {
            serviceEventKind = isolate.pauseEvent.kind;
          } else if (serviceEventKind != isolate.pauseEvent.kind) {
            serviceEventKind = ''; // many kinds
          }
        }
      }
      globals.printTrace('Found $postReloadPausedIsolatesFound newly paused isolate(s).');
      if (postReloadPausedIsolatesFound == 0) {
        await reassembleFuture; // must just be taking a long time... keep waiting!
        return;
      }
      shouldReportReloadTime = false;
      if (onSlow != null) {
        onSlow('${_describePausedIsolates(postReloadPausedIsolatesFound, serviceEventKind)}.');
      }
    },
  );
  return ReassembleResult(reassembleViews, failedReassemble, shouldReportReloadTime);
}

String _describePausedIsolates(int pausedIsolatesFound, String serviceEventKind) {
  assert(pausedIsolatesFound > 0);
  final StringBuffer message = StringBuffer();
  bool plural;
  if (pausedIsolatesFound == 1) {
    message.write('The application is ');
    plural = false;
  } else {
    message.write('$pausedIsolatesFound isolates are ');
    plural = true;
  }
  assert(serviceEventKind != null);
  switch (serviceEventKind) {
    case vm_service.EventKind.kPauseStart:
      message.write('paused (probably due to --start-paused)');
      break;
    case vm_service.EventKind.kPauseExit:
      message.write('paused because ${ plural ? 'they have' : 'it has' } terminated');
      break;
    case vm_service.EventKind.kPauseBreakpoint:
      message.write('paused in the debugger on a breakpoint');
      break;
    case vm_service.EventKind.kPauseInterrupted:
      message.write('paused due in the debugger');
      break;
    case vm_service.EventKind.kPauseException:
      message.write('paused in the debugger after an exception was thrown');
      break;
    case vm_service.EventKind.kPausePostRequest:
      message.write('paused');
      break;
    case '':
      message.write('paused for various reasons');
      break;
    default:
      message.write('paused');
  }
  return message.toString();
}

1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
/// The result of an invalidation check from [ProjectFileInvalidator].
class InvalidationResult {
  const InvalidationResult({
    this.uris,
    this.packageConfig,
  });

  final List<Uri> uris;
  final PackageConfig packageConfig;
}

1367 1368
/// The [ProjectFileInvalidator] track the dependencies for a running
/// application to determine when they are dirty.
1369
class ProjectFileInvalidator {
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
  ProjectFileInvalidator({
    @required FileSystem fileSystem,
    @required Platform platform,
    @required Logger logger,
  }): _fileSystem = fileSystem,
      _platform = platform,
      _logger = logger;

  final FileSystem _fileSystem;
  final Platform _platform;
  final Logger _logger;
1381

1382
  static const String _pubCachePathLinuxAndMac = '.pub-cache';
1383 1384
  static const String _pubCachePathWindows = 'Pub/Cache';

1385
  // As of writing, Dart supports up to 32 asynchronous I/O threads per
1386
  // isolate. We also want to avoid hitting platform limits on open file
1387 1388 1389 1390 1391 1392
  // handles/descriptors.
  //
  // This value was chosen based on empirical tests scanning a set of
  // ~2000 files.
  static const int _kMaxPendingStats = 8;

1393
  Future<InvalidationResult> findInvalidated({
1394 1395 1396
    @required DateTime lastCompiled,
    @required List<Uri> urisToMonitor,
    @required String packagesPath,
1397
    @required PackageConfig packageConfig,
1398 1399
    bool asyncScanning = false,
  }) async {
1400 1401 1402 1403
    assert(urisToMonitor != null);
    assert(packagesPath != null);

    if (lastCompiled == null) {
1404
      // Initial load.
1405
      assert(urisToMonitor.isEmpty);
1406
      return InvalidationResult(
1407
        packageConfig: packageConfig,
1408
        uris: <Uri>[],
1409
      );
1410 1411
    }

1412
    final Stopwatch stopwatch = Stopwatch()..start();
1413 1414
    final List<Uri> urisToScan = <Uri>[
      // Don't watch pub cache directories to speed things up a little.
1415
      for (final Uri uri in urisToMonitor)
1416
        if (_isNotInPubCache(uri)) uri,
1417 1418
    ];
    final List<Uri> invalidatedFiles = <Uri>[];
1419 1420 1421 1422 1423
    if (asyncScanning) {
      final Pool pool = Pool(_kMaxPendingStats);
      final List<Future<void>> waitList = <Future<void>>[];
      for (final Uri uri in urisToScan) {
        waitList.add(pool.withResource<void>(
1424 1425 1426 1427 1428
          // Calling fs.stat() is more performant than fs.file().stat(), but
          // uri.toFilePath() does not work with MultiRootFileSystem.
          () => (uri.hasScheme && uri.scheme != 'file'
            ? _fileSystem.file(uri).stat()
            :  _fileSystem.stat(uri.toFilePath(windows: _platform.isWindows)))
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
            .then((FileStat stat) {
              final DateTime updatedAt = stat.modified;
              if (updatedAt != null && updatedAt.isAfter(lastCompiled)) {
                invalidatedFiles.add(uri);
              }
            })
        ));
      }
      await Future.wait<void>(waitList);
    } else {
      for (final Uri uri in urisToScan) {
1440 1441 1442 1443 1444
        // Calling fs.statSync() is more performant than fs.file().statSync(), but
        // uri.toFilePath() does not work with MultiRootFileSystem.
        final DateTime updatedAt = uri.hasScheme && uri.scheme != 'file'
          ? _fileSystem.file(uri).statSync().modified
          : _fileSystem.statSync(uri.toFilePath(windows: _platform.isWindows)).modified;
1445 1446 1447
        if (updatedAt != null && updatedAt.isAfter(lastCompiled)) {
          invalidatedFiles.add(uri);
        }
1448 1449
      }
    }
1450
    // We need to check the .packages file too since it is not used in compilation.
1451 1452 1453
    final File packageFile = _fileSystem.file(packagesPath);
    final Uri packageUri = packageFile.uri;
    final DateTime updatedAt = packageFile.statSync().modified;
1454 1455 1456
    if (updatedAt != null && updatedAt.isAfter(lastCompiled)) {
      invalidatedFiles.add(packageUri);
      packageConfig = await _createPackageConfig(packagesPath);
1457 1458
      // The frontend_server might be monitoring the package_config.json file,
      // Pub should always produce both files.
1459
      // TODO(zanderso): remove after https://github.com/flutter/flutter/issues/55249
1460 1461 1462 1463 1464 1465 1466 1467
      if (_fileSystem.path.basename(packagesPath) == '.packages') {
        final File packageConfigFile = _fileSystem.file(packagesPath)
          .parent.childDirectory('.dart_tool')
          .childFile('package_config.json');
        if (packageConfigFile.existsSync()) {
          invalidatedFiles.add(packageConfigFile.uri);
        }
      }
1468 1469
    }

1470
    _logger.printTrace(
1471
      'Scanned through ${urisToScan.length} files in '
1472 1473
      '${stopwatch.elapsedMilliseconds}ms'
      '${asyncScanning ? " (async)" : ""}',
1474
    );
1475 1476 1477 1478
    return InvalidationResult(
      packageConfig: packageConfig,
      uris: invalidatedFiles,
    );
1479
  }
1480

1481 1482
  bool _isNotInPubCache(Uri uri) {
    return !(_platform.isWindows && uri.path.contains(_pubCachePathWindows))
1483 1484
        && !uri.path.contains(_pubCachePathLinuxAndMac);
  }
1485 1486

  Future<PackageConfig> _createPackageConfig(String packagesPath) {
1487
    return loadPackageConfigWithLogging(
1488
      _fileSystem.file(packagesPath),
1489
      logger: _logger,
1490 1491
    );
  }
1492
}
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543

/// Additional serialization logic for a hot reload response.
class ReloadReportContents {
  factory ReloadReportContents.fromReloadReport(vm_service.ReloadReport report) {
    final List<ReasonForCancelling> reasons = <ReasonForCancelling>[];
    final Object notices = report.json['notices'];
    if (notices is! List<dynamic>) {
      return ReloadReportContents._(report.success, reasons, report);
    }
    for (final Object obj in notices as List<dynamic>) {
      if (obj is! Map<String, dynamic>) {
        continue;
      }
      final Map<String, dynamic> notice = obj as Map<String, dynamic>;
      reasons.add(ReasonForCancelling(
        message: notice['message'] is String
          ? notice['message'] as String
          : 'Unknown Error',
      ));
    }

    return ReloadReportContents._(report.success, reasons, report);
  }

  ReloadReportContents._(
    this.success,
    this.notices,
    this.report,
  );

  final bool success;
  final List<ReasonForCancelling> notices;
  final vm_service.ReloadReport report;
}

/// A serialization class for hot reload rejection reasons.
///
/// Injects an additional error message that a hot restart will
/// resolve the issue.
class ReasonForCancelling {
  ReasonForCancelling({
    this.message,
  });

  final String message;

  @override
  String toString() {
    return '$message.\nTry performing a hot restart instead.';
  }
}