From 928b3ad5dba2c46c1aa874d6ebc9a7818a5a060b Mon Sep 17 00:00:00 2001 From: Yegor Date: Tue, 29 Jun 2021 12:58:01 -0700 Subject: [PATCH] [web] felt --watch fixes (flutter/engine#27009) * make processes interruptible * make --watch compatible with Windows: * add 'q' shortcut to quit (Ctrl + C on Windows is wonky) * use package:path for cross-platform path processing --- engine/src/flutter/lib/web_ui/dev/build.dart | 72 +++-- engine/src/flutter/lib/web_ui/dev/felt.dart | 2 +- .../flutter/lib/web_ui/dev/macos_info.dart | 25 +- .../flutter/lib/web_ui/dev/test_runner.dart | 71 +++-- engine/src/flutter/lib/web_ui/dev/utils.dart | 248 +++++++++++++----- .../src/flutter/lib/web_ui/dev/watcher.dart | 122 ++++++++- 6 files changed, 412 insertions(+), 128 deletions(-) diff --git a/engine/src/flutter/lib/web_ui/dev/build.dart b/engine/src/flutter/lib/web_ui/dev/build.dart index f246d0c270..97829f364d 100644 --- a/engine/src/flutter/lib/web_ui/dev/build.dart +++ b/engine/src/flutter/lib/web_ui/dev/build.dart @@ -36,45 +36,69 @@ class BuildCommand extends Command with ArgUtils { FutureOr run() async { final FilePath libPath = FilePath.fromWebUi('lib'); final Pipeline buildPipeline = Pipeline(steps: [ - gn, - ninja, + GnPipelineStep(), + NinjaPipelineStep(), ]); await buildPipeline.start(); if (isWatchMode) { print('Initial build done!'); print('Watching directory: ${libPath.relativeToCwd}/'); - PipelineWatcher( + await PipelineWatcher( dir: libPath.absolute, pipeline: buildPipeline, // Ignore font files that are copied whenever tests run. ignore: (event) => event.path.endsWith('.ttf'), ).start(); - // Return a never-ending future. - return Completer().future; - } else { - return true; } + return true; } } -Future gn() { - print('Running gn...'); - return runProcess( - path.join(environment.flutterDirectory.path, 'tools', 'gn'), - [ - '--unopt', - if (Platform.isMacOS) '--xcode-symlinks', - '--full-dart-sdk', - ], - ); +/// Runs `gn`. +/// +/// Not safe to interrupt as it may leave the `out/` directory in a corrupted +/// state. GN is pretty quick though, so it's OK to not support interruption. +class GnPipelineStep extends ProcessStep { + @override + String get name => 'gn'; + + @override + bool get isSafeToInterrupt => false; + + @override + Future createProcess() { + print('Running gn...'); + return startProcess( + path.join(environment.flutterDirectory.path, 'tools', 'gn'), + [ + '--unopt', + if (Platform.isMacOS) '--xcode-symlinks', + '--full-dart-sdk', + ], + ); + } } -// TODO(mdebbar): Make the ninja step interruptable in the pipeline. -Future ninja() { - print('Running autoninja...'); - return runProcess('autoninja', [ - '-C', - environment.hostDebugUnoptDir.path, - ]); +/// Runs `autoninja`. +/// +/// Can be safely interrupted. +class NinjaPipelineStep extends ProcessStep { + @override + String get name => 'ninja'; + + @override + bool get isSafeToInterrupt => true; + + @override + Future createProcess() { + print('Running autoninja...'); + return startProcess( + 'autoninja', + [ + '-C', + environment.hostDebugUnoptDir.path, + ], + ); + } } diff --git a/engine/src/flutter/lib/web_ui/dev/felt.dart b/engine/src/flutter/lib/web_ui/dev/felt.dart index d326905623..f99c0ac3be 100644 --- a/engine/src/flutter/lib/web_ui/dev/felt.dart +++ b/engine/src/flutter/lib/web_ui/dev/felt.dart @@ -54,7 +54,7 @@ void main(List rawArgs) async { 'executable: ${e.executable} ' 'arguments: ${e.arguments} ' 'exit code: ${e.exitCode}'); - exitCode = e.exitCode; + exitCode = e.exitCode ?? 1; } catch (e) { rethrow; } finally { diff --git a/engine/src/flutter/lib/web_ui/dev/macos_info.dart b/engine/src/flutter/lib/web_ui/dev/macos_info.dart index 6dcb547e37..9d77c2d9df 100644 --- a/engine/src/flutter/lib/web_ui/dev/macos_info.dart +++ b/engine/src/flutter/lib/web_ui/dev/macos_info.dart @@ -33,8 +33,12 @@ class MacOSInfo { /// Print information on applications in the system that contains string /// `Safari`. Future _printSafariApplications() async { - final String systemProfileJson = await evalProcess( - 'system_profiler', ['SPApplicationsDataType', '-json']); + final ProcessManager systemProfiler = await startProcess( + 'system_profiler', + ['SPApplicationsDataType', '-json'], + evalOutput: true, + ); + final String systemProfileJson = await systemProfiler.evalStdout(); final Map json = jsonDecode(systemProfileJson) as Map; @@ -52,20 +56,21 @@ class MacOSInfo { /// Print all the defaults in the system related to Safari. Future _printSafariDefaults() async { - final String defaults = - await evalProcess('/usr/bin/defaults', ['find', 'Safari']); - - print('Safari related defaults:\n $defaults'); + final ProcessManager defaults = await startProcess( + '/usr/bin/defaults', + ['find', 'Safari'], + ); + print('Safari related defaults:\n ${await defaults.evalStdout()}'); } /// Print user limits (file and process). Future _printUserLimits() async { - final String fileLimit = await evalProcess('ulimit', ['-n']); - + ProcessManager ulimit = await startProcess('ulimit', ['-n']); + final String fileLimit = await ulimit.evalStdout(); print('MacOS file limit: $fileLimit'); - final String processLimit = await evalProcess('ulimit', ['-u']); - + ulimit = await startProcess('ulimit', ['-u']); + final String processLimit = await ulimit.evalStdout(); print('MacOS process limit: $processLimit'); } } diff --git a/engine/src/flutter/lib/web_ui/dev/test_runner.dart b/engine/src/flutter/lib/web_ui/dev/test_runner.dart index 7dd95fa565..ee76a38f5b 100644 --- a/engine/src/flutter/lib/web_ui/dev/test_runner.dart +++ b/engine/src/flutter/lib/web_ui/dev/test_runner.dart @@ -194,8 +194,8 @@ class TestCommand extends Command with ArgUtils { } final Pipeline testPipeline = Pipeline(steps: [ - () async => clearTerminalScreen(), - () => runTests(), + ClearTerminalScreenStep(), + TestRunnerStep(this), ]); await testPipeline.start(); @@ -206,7 +206,7 @@ class TestCommand extends Command with ArgUtils { print( 'Watching ${dir.relativeToCwd}/lib and ${dir.relativeToCwd}/test to re-run tests'); print(''); - PipelineWatcher( + await PipelineWatcher( dir: dir.absolute, pipeline: testPipeline, ignore: (event) { @@ -215,31 +215,18 @@ class TestCommand extends Command with ArgUtils { return true; } - // Ignore auto-generated JS files. - // The reason we are using `.contains()` instead of `.endsWith()` is - // because the auto-generated files could end with any of the - // following: - // - // - browser_test.dart.js - // - browser_test.dart.js.map - // - browser_test.dart.js.deps - if (event.path.contains('browser_test.dart.js')) { - return true; - } - // React to changes in lib/ and test/ folders. final String relativePath = path.relative(event.path, from: dir.absolute); - if (relativePath.startsWith('lib/') || - relativePath.startsWith('test/')) { + if (path.isWithin('lib', relativePath) || + path.isWithin('test', relativePath)) { return false; } // Ignore anything else. return true; }).start(); - // Return a never-ending future. - return Completer().future; + return true; } else { if (!allShardsPassed) { io.stderr.writeln(_createFailedShardsMessage()); @@ -822,3 +809,49 @@ class NameOnlyReporter implements hack.Reporter { @override void resume() {} } + +/// Clears the terminal screen and places the cursor at the top left corner. +/// +/// This works on Linux and Mac. On Windows, it's a no-op. +class ClearTerminalScreenStep implements PipelineStep { + @override + String get name => 'clearing terminal screen'; + + @override + bool get isSafeToInterrupt => false; + + @override + Future interrupt() async {} + + @override + Future run() async { + if (!io.Platform.isWindows) { + // See: https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences + print("\x1B[2J\x1B[1;2H"); + } + } +} + +/// Runs tests by calling [TestCommand.runTests]. +class TestRunnerStep implements PipelineStep { + TestRunnerStep(this.testCommand); + + TestCommand testCommand; + + @override + String get name => 'test runner'; + + @override + Future interrupt() async { + // Interrupt this step by killing all spawned processes (browsers, web drivers, etc). + cleanup(); + } + + @override + bool get isSafeToInterrupt => true; + + @override + Future run() async { + await testCommand.runTests(); + } +} diff --git a/engine/src/flutter/lib/web_ui/dev/utils.dart b/engine/src/flutter/lib/web_ui/dev/utils.dart index ec86d8ddcc..e3ab776954 100644 --- a/engine/src/flutter/lib/web_ui/dev/utils.dart +++ b/engine/src/flutter/lib/web_ui/dev/utils.dart @@ -3,6 +3,7 @@ // found in the LICENSE file. import 'dart:async'; +import 'dart:convert' show utf8, LineSplitter; import 'dart:io' as io; import 'package:args/args.dart'; @@ -13,16 +14,6 @@ import 'package:path/path.dart' as path; import 'environment.dart'; import 'exceptions.dart'; -/// Clears the terminal screen and places the cursor at the top left corner. -/// -/// This works on Linux and Mac. On Windows, it's a no-op. -void clearTerminalScreen() { - if (!io.Platform.isWindows) { - // See: https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences - print("\x1B[2J\x1B[1;2H"); - } -} - class FilePath { FilePath.fromCwd(String relativePath) : _absolutePath = path.absolute(relativePath); @@ -50,7 +41,39 @@ Future runProcess( String executable, List arguments, { String? workingDirectory, - bool mustSucceed: false, + bool failureIsSuccess = false, + Map environment = const {}, +}) async { + final ProcessManager manager = await startProcess( + executable, + arguments, + workingDirectory: workingDirectory, + failureIsSuccess: failureIsSuccess, + environment: environment, + ); + return manager.wait(); +} + +/// Starts a process using the [executable], passing it [arguments]. +/// +/// Returns a process manager that decorates the process with extra +/// functionality. See [ProcessManager] for what it can do. +/// +/// If [workingDirectory] is not null makes it the current working directory of +/// the process. Otherwise, the process inherits this processes working +/// directory. +/// +/// If [failureIsSuccess] is set to true, the returned [ProcessManager] treats +/// non-zero exit codes as success, and zero exit code as failure. +/// +/// If [evalOutput] is set to true, collects and decodes the process' standard +/// streams into in-memory strings. +Future startProcess( + String executable, + List arguments, { + String? workingDirectory, + bool failureIsSuccess = false, + bool evalOutput = false, Map environment = const {}, }) async { final io.Process process = await io.Process.start( @@ -60,64 +83,155 @@ Future runProcess( // Running the process in a system shell for Windows. Otherwise // the process is not able to get Dart from path. runInShell: io.Platform.isWindows, - mode: io.ProcessStartMode.inheritStdio, + mode: io.ProcessStartMode.normal, environment: environment, ); - final int exitCode = await process.exitCode; - if (mustSucceed && exitCode != 0) { + processesToCleanUp.add(process); + + return ProcessManager._( + executable: executable, + arguments: arguments, + workingDirectory: workingDirectory, + process: process, + evalOutput: evalOutput, + failureIsSuccess: failureIsSuccess, + ); +} + +/// Manages a process running outside `felt`. +class ProcessManager { + /// Creates a process manager that manages [process]. + ProcessManager._({ + required this.executable, + required this.arguments, + required this.workingDirectory, + required this.process, + required bool evalOutput, + required bool failureIsSuccess, + }) : _evalOutput = evalOutput, _failureIsSuccess = failureIsSuccess { + if (_evalOutput) { + _forwardStream(process.stdout, _stdout); + _forwardStream(process.stderr, _stderr); + } else { + _forwardStream(process.stdout, io.stdout); + _forwardStream(process.stderr, io.stderr); + } + } + + /// The executable, from which the process was spawned. + final String executable; + + /// The arguments passed to the prcess. + final List arguments; + + /// The current working directory (CWD) of the child process. + /// + /// If null, the child process inherits `felt`'s CWD. + final String? workingDirectory; + + /// The process being managed by this manager. + final io.Process process; + + /// Whether the standard output and standard error should be decoded into + /// strings while running the process. + final bool _evalOutput; + + /// Whether non-zero exit code is considered successful completion of the + /// process. + /// + /// See also [wait]. + final bool _failureIsSuccess; + + final StringBuffer _stdout = StringBuffer(); + final StringBuffer _stderr = StringBuffer(); + + void _forwardStream(Stream> stream, StringSink buffer) { + stream + .transform(utf8.decoder) + .transform(const LineSplitter()) + .listen(buffer.writeln); + } + + /// Waits for the [process] to exit. Returns the exit code. + /// + /// The returned future completes successfully if: + /// + /// * [failureIsSuccess] is false and the process exited with exit code 0. + /// * [failureIsSuccess] is true and the process exited with a non-zero exit code. + /// + /// In all other cicumstances the future completes with an error. + Future wait() async { + final int exitCode = await process.exitCode; + if (!_failureIsSuccess && exitCode != 0) { + _throwProcessException( + description: 'Sub-process failed.', + exitCode: exitCode, + ); + } + return exitCode; + } + + /// If [evalOutput] is true, wait for the process to finish then returns the + /// decoded standard streams. + Future eval() async { + if (!_evalOutput) { + kill(); + _throwProcessException( + description: 'Cannot eval process output. The process was launched ' + 'with `evalOutput` set to false.', + ); + } + final int exitCode = await wait(); + return ProcessOutput( + exitCode: exitCode, + stdout: _stdout.toString(), + stderr: _stderr.toString(), + ); + } + + /// A convenience method on top of [eval] that only extracts standard output. + Future evalStdout() async { + return (await eval()).stdout; + } + + /// A convenience method on top of [eval] that only extracts standard error. + Future evalStderr() async { + return (await eval()).stderr; + } + + @alwaysThrows + void _throwProcessException({required String description, int? exitCode}) { throw ProcessException( - description: 'Sub-process failed.', + description: description, executable: executable, arguments: arguments, workingDirectory: workingDirectory, exitCode: exitCode, ); } - return exitCode; -} -/// Runs [executable]. Do not follow the exit code or the output. -Future startProcess( - String executable, - List arguments, { - String? workingDirectory, - bool mustSucceed: false, -}) async { - final io.Process process = await io.Process.start( - executable, - arguments, - workingDirectory: workingDirectory, - // Running the process in a system shell for Windows. Otherwise - // the process is not able to get Dart from path. - runInShell: io.Platform.isWindows, - mode: io.ProcessStartMode.inheritStdio, - ); - processesToCleanUp.add(process); -} - -/// Runs [executable] and returns its standard output as a string. -/// -/// If the process fails, throws a [ProcessException]. -Future evalProcess( - String executable, - List arguments, { - String? workingDirectory, -}) async { - final io.ProcessResult result = await io.Process.run( - executable, - arguments, - workingDirectory: workingDirectory, - ); - if (result.exitCode != 0) { - throw ProcessException( - description: result.stderr as String, - executable: executable, - arguments: arguments, - workingDirectory: workingDirectory, - exitCode: result.exitCode, - ); + /// Kills the [process] by sending it the [signal]. + bool kill([io.ProcessSignal signal = io.ProcessSignal.sigterm]) { + return process.kill(signal); } - return result.stdout as String; +} + +/// Stringified standard output and standard error streams from a process. +class ProcessOutput { + ProcessOutput({ + required this.exitCode, + required this.stdout, + required this.stderr, + }); + + /// The exit code of the process. + final int exitCode; + + /// Standard output of the process decoded as a string. + final String stdout; + + /// Standard error of the process decoded as a string. + final String stderr; } Future runFlutter( @@ -140,6 +254,7 @@ Future runFlutter( } } +/// An exception related to an attempt to spawn a sub-process. @immutable class ProcessException implements Exception { ProcessException({ @@ -147,14 +262,20 @@ class ProcessException implements Exception { required this.executable, required this.arguments, required this.workingDirectory, - required this.exitCode, + this.exitCode, }); final String description; final String executable; final List arguments; final String? workingDirectory; - final int exitCode; + + /// The exit code of the process. + /// + /// The value is null if the exception is thrown before the process exits. + /// For example, this can happen on invalid attempts to start a process, or + /// when a process is stuck and is unable to exit. + final int? exitCode; @override String toString() { @@ -162,9 +283,10 @@ class ProcessException implements Exception { message ..writeln(description) ..writeln('Command: $executable ${arguments.join(' ')}') - ..writeln( - 'Working directory: ${workingDirectory ?? io.Directory.current.path}') - ..writeln('Exit code: $exitCode'); + ..writeln('Working directory: ${workingDirectory ?? io.Directory.current.path}'); + if (exitCode != null) { + message.writeln('Exit code: $exitCode'); + } return '$message'; } } diff --git a/engine/src/flutter/lib/web_ui/dev/watcher.dart b/engine/src/flutter/lib/web_ui/dev/watcher.dart index 07978735f2..04e903440b 100644 --- a/engine/src/flutter/lib/web_ui/dev/watcher.dart +++ b/engine/src/flutter/lib/web_ui/dev/watcher.dart @@ -3,20 +3,88 @@ // found in the LICENSE file. import 'dart:async'; +import 'dart:io' as io; import 'package:path/path.dart' as path; import 'package:watcher/watcher.dart'; +import 'utils.dart'; + enum PipelineStatus { + /// The pipeline has not started yet. + /// + /// This is the initial state of the pipeline. idle, + + /// The pipeline is running build steps. started, + + /// The pipeline is stopping. stopping, - stopped, + + /// The pipeline is not running anything because it has been interrupted. + interrupted, + + /// The pipeline is not running anything because it encountered an error. error, + + /// The pipeline is not running anything because it finished all build steps successfully. done, } -typedef PipelineStep = Future Function(); +/// A step in the build pipeline. +abstract class PipelineStep { + /// The name of this step. + /// + /// This value appears in logs, so it should be descriptive and human-readable. + String get name; + + /// Whether it is safe to interrupt this step while it's running. + bool get isSafeToInterrupt; + + /// Runs this step. + /// + /// The returned future is completed when the step is finished. The future + /// completes with an error if the step failed. + Future run(); + + /// Interrupts this step, if it's already running. + /// + /// [Pipeline] only calls this if [isSafeToInterrupt] returns true. + Future interrupt(); +} + +/// A helper class for implementing [PipelineStep] in terms of a process. +abstract class ProcessStep implements PipelineStep { + ProcessManager? _process; + bool _isInterrupted = false; + + /// Starts and returns the process that implements the logic of this pipeline + /// step. + Future createProcess(); + + @override + Future interrupt() async { + _isInterrupted = true; + _process?.kill(); + } + + @override + Future run() async { + final ProcessManager process = await createProcess(); + + if (_isInterrupted) { + // If the step was interrupted while creating the process, the + // `interrupt` won't kill the process; it must be done here. + process.kill(); + return; + } + + _process = process; + await process.wait(); + _process = null; + } +} /// Represents a sequence of asynchronous tasks to be executed. /// @@ -30,7 +98,8 @@ class Pipeline { final Iterable steps; - Future? _currentStepFuture; + PipelineStep? _currentStep; + Future? _currentStepFuture; PipelineStatus get status => _status; PipelineStatus _status = PipelineStatus.idle; @@ -45,7 +114,8 @@ class Pipeline { if (status != PipelineStatus.started) { break; } - _currentStepFuture = step(); + _currentStep = step; + _currentStepFuture = step.run(); await _currentStepFuture; } _status = PipelineStatus.done; @@ -54,18 +124,31 @@ class Pipeline { print('Error in the pipeline: $error'); print(stackTrace); } finally { - _currentStepFuture = null; + _currentStep = null; } } /// Stops executing any more tasks in the pipeline. /// - /// If a task is already being executed, it won't be interrupted. - Future stop() { + /// Tasks that are safe to interrupt (according to [PipelineStep.isSafeToInterrupt]), + /// are interrupted. Otherwise, waits for the current step to finish before + /// interrupting the pipeline. + Future stop() async { _status = PipelineStatus.stopping; - return (_currentStepFuture ?? Future.value(null)).then((_) { - _status = PipelineStatus.stopped; - }); + final PipelineStep? step = _currentStep; + if (step == null) { + _status = PipelineStatus.interrupted; + return; + } + if (step.isSafeToInterrupt) { + print('Interrupting ${step.name}'); + await step.interrupt(); + _status = PipelineStatus.interrupted; + return; + } + print('${step.name} cannot be interrupted. Waiting for it to complete.'); + await _currentStepFuture; + _status = PipelineStatus.interrupted; } } @@ -98,8 +181,25 @@ class PipelineWatcher { final WatchEventPredicate? ignore; /// Activates the watcher. - void start() { + Future start() async { watcher.events.listen(_onEvent); + + // Listen to the `q` key stroke to stop the pipeline. + print('Press \'q\' to exit felt'); + + // Key strokes should be reported immediately and one at a time rather than + // wait for the user to hit ENTER and report the whole line. To achieve + // that, echo mode and line mode must be disabled. + io.stdin.echoMode = false; + io.stdin.lineMode = false; + + await io.stdin.firstWhere((List event) { + const int qKeyCode = 113; + final bool qEntered = event.isNotEmpty && event.first == qKeyCode; + return qEntered; + }); + print('Stopping felt'); + await pipeline.stop(); } int _pipelineRunCount = 0;