Collect chrome://tracing data in Web benchmarks (#53879)
Collect chrome://tracing data in Web benchmarks
This commit is contained in:
@@ -191,31 +191,54 @@ class BenchTextCachedLayout extends RawRecorder {
|
||||
/// build are unique.
|
||||
int _counter = 0;
|
||||
|
||||
/// Measures how expensive it is to construct material checkboxes.
|
||||
/// Which mode to run [BenchBuildColorsGrid] in.
|
||||
enum _TestMode {
|
||||
/// Uses the HTML rendering backend with the canvas 2D text layout.
|
||||
useCanvasTextLayout,
|
||||
|
||||
/// Uses the HTML rendering backend with the DOM text layout.
|
||||
useDomTextLayout,
|
||||
|
||||
/// Uses CanvasKit for everything.
|
||||
useCanvasKit,
|
||||
}
|
||||
|
||||
/// Measures how expensive it is to construct a realistic text-heavy piece of UI.
|
||||
///
|
||||
/// Creates a 10x10 grid of tristate checkboxes.
|
||||
/// The benchmark constructs a tabbed view, where each tab displays a list of
|
||||
/// colors. Each color's description is made of several [Text] nodes.
|
||||
class BenchBuildColorsGrid extends WidgetBuildRecorder {
|
||||
BenchBuildColorsGrid({@required this.useCanvas})
|
||||
: super(name: useCanvas ? canvasBenchmarkName : domBenchmarkName);
|
||||
BenchBuildColorsGrid.canvas()
|
||||
: mode = _TestMode.useCanvasTextLayout, super(name: canvasBenchmarkName);
|
||||
BenchBuildColorsGrid.dom()
|
||||
: mode = _TestMode.useDomTextLayout, super(name: domBenchmarkName);
|
||||
BenchBuildColorsGrid.canvasKit()
|
||||
: mode = _TestMode.useCanvasKit, super(name: canvasKitBenchmarkName);
|
||||
|
||||
static const String domBenchmarkName = 'text_dom_color_grid';
|
||||
static const String canvasBenchmarkName = 'text_canvas_color_grid';
|
||||
static const String canvasKitBenchmarkName = 'text_canvas_kit_color_grid';
|
||||
|
||||
/// Whether to use the new canvas-based text measurement implementation.
|
||||
final bool useCanvas;
|
||||
final _TestMode mode;
|
||||
|
||||
num _textLayoutMicros = 0;
|
||||
|
||||
@override
|
||||
void setUpAll() {
|
||||
_useCanvasText(useCanvas);
|
||||
Future<void> setUpAll() async {
|
||||
if (mode == _TestMode.useCanvasTextLayout) {
|
||||
_useCanvasText(true);
|
||||
}
|
||||
if (mode == _TestMode.useDomTextLayout) {
|
||||
_useCanvasText(false);
|
||||
}
|
||||
_onBenchmark((String name, num value) {
|
||||
_textLayoutMicros += value;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void tearDownAll() {
|
||||
Future<void> tearDownAll() async {
|
||||
_useCanvasText(null);
|
||||
_onBenchmark(null);
|
||||
}
|
||||
@@ -230,7 +253,8 @@ class BenchBuildColorsGrid extends WidgetBuildRecorder {
|
||||
void frameDidDraw() {
|
||||
// We need to do this before calling [super.frameDidDraw] because the latter
|
||||
// updates the value of [showWidget] in preparation for the next frame.
|
||||
if (showWidget) {
|
||||
// TODO(yjbanov): https://github.com/flutter/flutter/issues/53877
|
||||
if (showWidget && mode != _TestMode.useCanvasKit) {
|
||||
profile.addDataPoint(
|
||||
'text_layout',
|
||||
Duration(microseconds: _textLayoutMicros.toInt()),
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:html' as html;
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui';
|
||||
|
||||
@@ -28,6 +29,8 @@ const int kMaxSampleCount = 10 * kMinSampleCount;
|
||||
|
||||
/// The number of samples used to extract metrics, such as noise, means,
|
||||
/// max/min values.
|
||||
///
|
||||
/// Keep this constant in sync with the same constant defined in `dev/devicelab/lib/framework/browser.dart`.
|
||||
const int _kMeasuredSampleCount = 10;
|
||||
|
||||
/// Maximum tolerated noise level.
|
||||
@@ -44,6 +47,50 @@ Duration timeAction(VoidCallback action) {
|
||||
return stopwatch.elapsed;
|
||||
}
|
||||
|
||||
/// A function that performs asynchronous work.
|
||||
typedef AsyncVoidCallback = Future<void> Function();
|
||||
|
||||
/// Runs the benchmark using the given [recorder].
|
||||
///
|
||||
/// Notifies about "set up" and "tear down" events via the [setUpAllDidRun]
|
||||
/// and [tearDownAllWillRun] callbacks.
|
||||
@sealed
|
||||
class Runner {
|
||||
/// Creates a runner for the [recorder].
|
||||
///
|
||||
/// All arguments must not be null.
|
||||
Runner({
|
||||
@required this.recorder,
|
||||
@required this.setUpAllDidRun,
|
||||
@required this.tearDownAllWillRun,
|
||||
});
|
||||
|
||||
/// The recorder that will run and record the benchmark.
|
||||
final Recorder recorder;
|
||||
|
||||
/// Called immediately after [Recorder.setUpAll] future is resolved.
|
||||
///
|
||||
/// This is useful, for example, to kick off a profiler or a tracer such that
|
||||
/// the "set up" computations are not included in the metrics.
|
||||
final AsyncVoidCallback setUpAllDidRun;
|
||||
|
||||
/// Called just before calling [Recorder.tearDownAll].
|
||||
///
|
||||
/// This is useful, for example, to stop a profiler or a tracer such that
|
||||
/// the "tear down" computations are not included in the metrics.
|
||||
final AsyncVoidCallback tearDownAllWillRun;
|
||||
|
||||
/// Runs the benchmark and reports the results.
|
||||
Future<Profile> run() async {
|
||||
await recorder.setUpAll();
|
||||
await setUpAllDidRun();
|
||||
final Profile profile = await recorder.run();
|
||||
await tearDownAllWillRun();
|
||||
await recorder.tearDownAll();
|
||||
return profile;
|
||||
}
|
||||
}
|
||||
|
||||
/// Base class for benchmark recorders.
|
||||
///
|
||||
/// Each benchmark recorder has a [name] and a [run] method at a minimum.
|
||||
@@ -56,8 +103,20 @@ abstract class Recorder {
|
||||
/// prefix.
|
||||
final String name;
|
||||
|
||||
/// Called once before all runs of this benchmark recorder.
|
||||
///
|
||||
/// This is useful for doing one-time setup work that's needed for the
|
||||
/// benchmark.
|
||||
Future<void> setUpAll() async {}
|
||||
|
||||
/// The implementation of the benchmark that will produce a [Profile].
|
||||
Future<Profile> run();
|
||||
|
||||
/// Called once after all runs of this benchmark recorder.
|
||||
///
|
||||
/// This is useful for doing one-time clean up work after the benchmark is
|
||||
/// complete.
|
||||
Future<void> tearDownAll() async {}
|
||||
}
|
||||
|
||||
/// A recorder for benchmarking raw execution of Dart code.
|
||||
@@ -86,18 +145,6 @@ abstract class Recorder {
|
||||
abstract class RawRecorder extends Recorder {
|
||||
RawRecorder({@required String name}) : super._(name);
|
||||
|
||||
/// Called once before all runs of this benchmark recorder.
|
||||
///
|
||||
/// This is useful for doing one-time setup work that's needed for the
|
||||
/// benchmark.
|
||||
void setUpAll() {}
|
||||
|
||||
/// Called once after all runs of this benchmark recorder.
|
||||
///
|
||||
/// This is useful for doing one-time clean up work after the benchmark is
|
||||
/// complete.
|
||||
void tearDownAll() {}
|
||||
|
||||
/// The body of the benchmark.
|
||||
///
|
||||
/// This is the part that records measurements of the benchmark.
|
||||
@@ -107,12 +154,10 @@ abstract class RawRecorder extends Recorder {
|
||||
@nonVirtual
|
||||
Future<Profile> run() async {
|
||||
final Profile profile = Profile(name: name);
|
||||
setUpAll();
|
||||
do {
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
body(profile);
|
||||
} while (profile.shouldContinue());
|
||||
tearDownAll();
|
||||
return profile;
|
||||
}
|
||||
}
|
||||
@@ -162,24 +207,36 @@ abstract class SceneBuilderRecorder extends Recorder {
|
||||
final Profile profile = Profile(name: name);
|
||||
|
||||
window.onBeginFrame = (_) {
|
||||
onBeginFrame();
|
||||
try {
|
||||
startMeasureFrame();
|
||||
onBeginFrame();
|
||||
} catch (error, stackTrace) {
|
||||
profileCompleter.completeError(error, stackTrace);
|
||||
rethrow;
|
||||
}
|
||||
};
|
||||
window.onDrawFrame = () {
|
||||
profile.record('drawFrameDuration', () {
|
||||
final SceneBuilder sceneBuilder = SceneBuilder();
|
||||
onDrawFrame(sceneBuilder);
|
||||
profile.record('sceneBuildDuration', () {
|
||||
final Scene scene = sceneBuilder.build();
|
||||
profile.record('windowRenderDuration', () {
|
||||
window.render(scene);
|
||||
try {
|
||||
profile.record('drawFrameDuration', () {
|
||||
final SceneBuilder sceneBuilder = SceneBuilder();
|
||||
onDrawFrame(sceneBuilder);
|
||||
profile.record('sceneBuildDuration', () {
|
||||
final Scene scene = sceneBuilder.build();
|
||||
profile.record('windowRenderDuration', () {
|
||||
window.render(scene);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
endMeasureFrame();
|
||||
|
||||
if (profile.shouldContinue()) {
|
||||
window.scheduleFrame();
|
||||
} else {
|
||||
profileCompleter.complete(profile);
|
||||
if (profile.shouldContinue()) {
|
||||
window.scheduleFrame();
|
||||
} else {
|
||||
profileCompleter.complete(profile);
|
||||
}
|
||||
} catch (error, stackTrace) {
|
||||
profileCompleter.completeError(error, stackTrace);
|
||||
rethrow;
|
||||
}
|
||||
};
|
||||
window.scheduleFrame();
|
||||
@@ -270,12 +327,14 @@ abstract class WidgetRecorder extends Recorder
|
||||
@override
|
||||
@mustCallSuper
|
||||
void frameWillDraw() {
|
||||
startMeasureFrame();
|
||||
_drawFrameStopwatch = Stopwatch()..start();
|
||||
}
|
||||
|
||||
@override
|
||||
@mustCallSuper
|
||||
void frameDidDraw() {
|
||||
endMeasureFrame();
|
||||
profile.addDataPoint('drawFrameDuration', _drawFrameStopwatch.elapsed);
|
||||
|
||||
if (profile.shouldContinue()) {
|
||||
@@ -323,18 +382,6 @@ abstract class WidgetBuildRecorder extends Recorder
|
||||
/// consider using [WidgetRecorder].
|
||||
Widget createWidget();
|
||||
|
||||
/// Called once before all runs of this benchmark recorder.
|
||||
///
|
||||
/// This is useful for doing one-time setup work that's needed for the
|
||||
/// benchmark.
|
||||
void setUpAll() {}
|
||||
|
||||
/// Called once after all runs of this benchmark recorder.
|
||||
///
|
||||
/// This is useful for doing one-time clean up work after the benchmark is
|
||||
/// complete.
|
||||
void tearDownAll() {}
|
||||
|
||||
@override
|
||||
Profile profile;
|
||||
|
||||
@@ -361,7 +408,10 @@ abstract class WidgetBuildRecorder extends Recorder
|
||||
@override
|
||||
@mustCallSuper
|
||||
void frameWillDraw() {
|
||||
_drawFrameStopwatch = Stopwatch()..start();
|
||||
if (showWidget) {
|
||||
startMeasureFrame();
|
||||
_drawFrameStopwatch = Stopwatch()..start();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -369,6 +419,7 @@ abstract class WidgetBuildRecorder extends Recorder
|
||||
void frameDidDraw() {
|
||||
// Only record frames that show the widget.
|
||||
if (showWidget) {
|
||||
endMeasureFrame();
|
||||
profile.addDataPoint('drawFrameDuration', _drawFrameStopwatch.elapsed);
|
||||
}
|
||||
|
||||
@@ -388,13 +439,11 @@ abstract class WidgetBuildRecorder extends Recorder
|
||||
@override
|
||||
Future<Profile> run() {
|
||||
profile = Profile(name: name);
|
||||
setUpAll();
|
||||
final _RecordingWidgetsBinding binding =
|
||||
_RecordingWidgetsBinding.ensureInitialized();
|
||||
binding._beginRecording(this, _WidgetBuildRecorderHost(this));
|
||||
|
||||
_profileCompleter.future.whenComplete(() {
|
||||
tearDownAll();
|
||||
profile = null;
|
||||
});
|
||||
return _profileCompleter.future;
|
||||
@@ -433,7 +482,9 @@ class _WidgetBuildRecorderHostState extends State<_WidgetBuildRecorderHost> {
|
||||
/// calculations will only apply to the latest [_kMeasuredSampleCount] data
|
||||
/// points.
|
||||
class Timeseries {
|
||||
Timeseries();
|
||||
Timeseries(this.name);
|
||||
|
||||
final String name;
|
||||
|
||||
/// List of all the values that have been recorded.
|
||||
///
|
||||
@@ -450,14 +501,28 @@ class Timeseries {
|
||||
/// because of the sample size limit.
|
||||
int get count => _allValues.length;
|
||||
|
||||
double get average => _computeMean(_measuredValues);
|
||||
/// Computes the average value of the measured values.
|
||||
double get average => _computeAverage(name, _measuredValues);
|
||||
|
||||
/// Computes the standard deviation of the measured values.
|
||||
double get standardDeviation =>
|
||||
_computeStandardDeviationForPopulation(_measuredValues);
|
||||
_computeStandardDeviationForPopulation(name, _measuredValues);
|
||||
|
||||
double get noise => standardDeviation / average;
|
||||
/// Computes noise as a multiple of the [average] value.
|
||||
///
|
||||
/// This value can be multiplied by 100.0 to get noise as a percentage of
|
||||
/// the average.
|
||||
///
|
||||
/// If [average] is zero, treats the result as perfect score, returns zero.
|
||||
double get noise => average > 0.0 ? standardDeviation / average : 0.0;
|
||||
|
||||
/// Adds a value to this timeseries.
|
||||
void add(num value) {
|
||||
if (value < 0.0) {
|
||||
throw StateError(
|
||||
'Timeseries $name: negative metric values are not supported. Got: $value',
|
||||
);
|
||||
}
|
||||
_measuredValues.add(value);
|
||||
_allValues.add(value);
|
||||
// Don't let the [_measuredValues] list grow beyond [_kMeasuredSampleCount].
|
||||
@@ -488,7 +553,7 @@ class Profile {
|
||||
}
|
||||
|
||||
void addDataPoint(String key, Duration duration) {
|
||||
scoreData.putIfAbsent(key, () => Timeseries()).add(duration.inMicroseconds);
|
||||
scoreData.putIfAbsent(key, () => Timeseries(key)).add(duration.inMicroseconds);
|
||||
}
|
||||
|
||||
/// Decides whether the data collected so far is sufficient to stop, or
|
||||
@@ -599,7 +664,11 @@ class Profile {
|
||||
}
|
||||
|
||||
/// Computes the arithmetic mean (or average) of given [values].
|
||||
double _computeMean(Iterable<num> values) {
|
||||
double _computeAverage(String label, Iterable<num> values) {
|
||||
if (values.isEmpty) {
|
||||
throw StateError('$label: attempted to compute an average of an empty value list.');
|
||||
}
|
||||
|
||||
final num sum = values.reduce((num a, num b) => a + b);
|
||||
return sum / values.length;
|
||||
}
|
||||
@@ -611,8 +680,11 @@ double _computeMean(Iterable<num> values) {
|
||||
/// See also:
|
||||
///
|
||||
/// * https://en.wikipedia.org/wiki/Standard_deviation
|
||||
double _computeStandardDeviationForPopulation(Iterable<num> population) {
|
||||
final double mean = _computeMean(population);
|
||||
double _computeStandardDeviationForPopulation(String label, Iterable<num> population) {
|
||||
if (population.isEmpty) {
|
||||
throw StateError('$label: attempted to compute the standard deviation of empty population.');
|
||||
}
|
||||
final double mean = _computeAverage(label, population);
|
||||
final double sumOfSquaredDeltas = population.fold<double>(
|
||||
0.0,
|
||||
(double previous, num value) => previous += math.pow(value - mean, 2),
|
||||
@@ -676,17 +748,21 @@ class _RecordingWidgetsBinding extends BindingBase
|
||||
|
||||
// Fail hard and fast on errors. Benchmarks should not have any errors.
|
||||
FlutterError.onError = (FlutterErrorDetails details) {
|
||||
if (_hasErrored) {
|
||||
return;
|
||||
}
|
||||
_listener._onError(details.exception, details.stack);
|
||||
_hasErrored = true;
|
||||
_haltBenchmarkWithError(details.exception, details.stack);
|
||||
originalOnError(details);
|
||||
};
|
||||
_listener = recorder;
|
||||
runApp(widget);
|
||||
}
|
||||
|
||||
void _haltBenchmarkWithError(dynamic error, StackTrace stackTrace) {
|
||||
if (_hasErrored) {
|
||||
return;
|
||||
}
|
||||
_listener._onError(error, stackTrace);
|
||||
_hasErrored = true;
|
||||
}
|
||||
|
||||
/// To avoid calling [Profile.shouldContinue] every time [scheduleFrame] is
|
||||
/// called, we cache this value at the beginning of the frame.
|
||||
bool _benchmarkStopped = false;
|
||||
@@ -697,8 +773,13 @@ class _RecordingWidgetsBinding extends BindingBase
|
||||
if (_hasErrored) {
|
||||
return;
|
||||
}
|
||||
_benchmarkStopped = !_listener.profile.shouldContinue();
|
||||
super.handleBeginFrame(rawTimeStamp);
|
||||
try {
|
||||
_benchmarkStopped = !_listener.profile.shouldContinue();
|
||||
super.handleBeginFrame(rawTimeStamp);
|
||||
} catch (error, stackTrace) {
|
||||
_haltBenchmarkWithError(error, stackTrace);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -715,8 +796,40 @@ class _RecordingWidgetsBinding extends BindingBase
|
||||
if (_hasErrored) {
|
||||
return;
|
||||
}
|
||||
_listener.frameWillDraw();
|
||||
super.handleDrawFrame();
|
||||
_listener.frameDidDraw();
|
||||
try {
|
||||
_listener.frameWillDraw();
|
||||
super.handleDrawFrame();
|
||||
_listener.frameDidDraw();
|
||||
} catch (error, stackTrace) {
|
||||
_haltBenchmarkWithError(error, stackTrace);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int _currentFrameNumber = 1;
|
||||
|
||||
/// Adds a marker indication the beginning of frame rendering.
|
||||
///
|
||||
/// This adds an event to the performance trace used to find measured frames in
|
||||
/// Chrome tracing data. The tracing data contains all frames, but some
|
||||
/// benchmarks are only interested in a subset of frames. For example,
|
||||
/// [WidgetBuildRecorder] only measures frames that build widgets, and ignores
|
||||
/// frames that clear the screen.
|
||||
void startMeasureFrame() {
|
||||
html.window.performance.mark('measured_frame_start#$_currentFrameNumber');
|
||||
}
|
||||
|
||||
/// Signals the end of a measured frame.
|
||||
///
|
||||
/// See [startMeasureFrame] for details on what this instrumentation is used
|
||||
/// for.
|
||||
void endMeasureFrame() {
|
||||
html.window.performance.mark('measured_frame_end#$_currentFrameNumber');
|
||||
html.window.performance.measure(
|
||||
'measured_frame',
|
||||
'measured_frame_start#$_currentFrameNumber',
|
||||
'measured_frame_end#$_currentFrameNumber',
|
||||
);
|
||||
_currentFrameNumber += 1;
|
||||
}
|
||||
|
||||
@@ -32,6 +32,8 @@ final Map<String, RecorderFactory> benchmarks = <String, RecorderFactory>{
|
||||
BenchSimpleLazyTextScroll.benchmarkName: () => BenchSimpleLazyTextScroll(),
|
||||
BenchBuildMaterialCheckbox.benchmarkName: () => BenchBuildMaterialCheckbox(),
|
||||
BenchDynamicClipOnStaticPicture.benchmarkName: () => BenchDynamicClipOnStaticPicture(),
|
||||
if (isCanvasKit)
|
||||
BenchBuildColorsGrid.canvasKitBenchmarkName: () => BenchBuildColorsGrid.canvasKit(),
|
||||
|
||||
// Benchmarks that we don't want to run using CanvasKit.
|
||||
if (!isCanvasKit) ...<String, RecorderFactory>{
|
||||
@@ -39,37 +41,23 @@ final Map<String, RecorderFactory> benchmarks = <String, RecorderFactory>{
|
||||
BenchTextLayout.canvasBenchmarkName: () => BenchTextLayout(useCanvas: true),
|
||||
BenchTextCachedLayout.domBenchmarkName: () => BenchTextCachedLayout(useCanvas: false),
|
||||
BenchTextCachedLayout.canvasBenchmarkName: () => BenchTextCachedLayout(useCanvas: true),
|
||||
BenchBuildColorsGrid.domBenchmarkName: () => BenchBuildColorsGrid(useCanvas: false),
|
||||
BenchBuildColorsGrid.canvasBenchmarkName: () => BenchBuildColorsGrid(useCanvas: true),
|
||||
BenchBuildColorsGrid.domBenchmarkName: () => BenchBuildColorsGrid.dom(),
|
||||
BenchBuildColorsGrid.canvasBenchmarkName: () => BenchBuildColorsGrid.canvas(),
|
||||
}
|
||||
};
|
||||
|
||||
/// Whether we fell back to manual mode.
|
||||
///
|
||||
/// This happens when you run benchmarks using plain `flutter run` rather than
|
||||
/// devicelab test harness. The test harness spins up a special server that
|
||||
/// provides API for automatically picking the next benchmark to run.
|
||||
bool isInManualMode = false;
|
||||
final LocalBenchmarkServerClient _client = LocalBenchmarkServerClient();
|
||||
|
||||
Future<void> main() async {
|
||||
// Check if the benchmark server wants us to run a specific benchmark.
|
||||
final html.HttpRequest request = await requestXhr(
|
||||
'/next-benchmark',
|
||||
method: 'POST',
|
||||
mimeType: 'application/json',
|
||||
sendData: json.encode(benchmarks.keys.toList()),
|
||||
);
|
||||
final String nextBenchmark = await _client.requestNextBenchmark();
|
||||
|
||||
// 404 is expected in the following cases:
|
||||
// - The benchmark is ran using plain `flutter run`, which does not provide "next-benchmark" handler.
|
||||
// - We ran all benchmarks and the benchmark is telling us there are no more benchmarks to run.
|
||||
if (request.status == 404) {
|
||||
if (nextBenchmark == LocalBenchmarkServerClient.kManualFallback) {
|
||||
_fallbackToManual('The server did not tell us which benchmark to run next.');
|
||||
return;
|
||||
}
|
||||
|
||||
final String benchmarkName = request.responseText;
|
||||
await _runBenchmark(benchmarkName);
|
||||
await _runBenchmark(nextBenchmark);
|
||||
html.window.location.reload();
|
||||
}
|
||||
|
||||
@@ -81,44 +69,36 @@ Future<void> _runBenchmark(String benchmarkName) async {
|
||||
return;
|
||||
}
|
||||
|
||||
final Recorder recorder = recorderFactory();
|
||||
|
||||
try {
|
||||
final Profile profile = await recorder.run();
|
||||
if (!isInManualMode) {
|
||||
final html.HttpRequest request = await html.HttpRequest.request(
|
||||
'/profile-data',
|
||||
method: 'POST',
|
||||
mimeType: 'application/json',
|
||||
sendData: json.encode(profile.toJson()),
|
||||
);
|
||||
if (request.status != 200) {
|
||||
throw Exception(
|
||||
'Failed to report profile data to benchmark server. '
|
||||
'The server responded with status code ${request.status}.'
|
||||
);
|
||||
}
|
||||
final Runner runner = Runner(
|
||||
recorder: recorderFactory(),
|
||||
setUpAllDidRun: () async {
|
||||
if (!_client.isInManualMode) {
|
||||
await _client.startPerformanceTracing(benchmarkName);
|
||||
}
|
||||
},
|
||||
tearDownAllWillRun: () async {
|
||||
if (!_client.isInManualMode) {
|
||||
await _client.stopPerformanceTracing();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
final Profile profile = await runner.run();
|
||||
if (!_client.isInManualMode) {
|
||||
await _client.sendProfileData(profile);
|
||||
} else {
|
||||
print(profile);
|
||||
}
|
||||
} catch (error, stackTrace) {
|
||||
if (isInManualMode) {
|
||||
if (_client.isInManualMode) {
|
||||
rethrow;
|
||||
}
|
||||
await html.HttpRequest.request(
|
||||
'/on-error',
|
||||
method: 'POST',
|
||||
mimeType: 'application/json',
|
||||
sendData: json.encode(<String, dynamic>{
|
||||
'error': '$error',
|
||||
'stackTrace': '$stackTrace',
|
||||
}),
|
||||
);
|
||||
await _client.reportError(error, stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
void _fallbackToManual(String error) {
|
||||
isInManualMode = true;
|
||||
html.document.body.appendHtml('''
|
||||
<div id="manual-panel">
|
||||
<h3>$error</h3>
|
||||
@@ -146,50 +126,157 @@ void _fallbackToManual(String error) {
|
||||
}
|
||||
}
|
||||
|
||||
Future<html.HttpRequest> requestXhr(
|
||||
String url, {
|
||||
String method,
|
||||
bool withCredentials,
|
||||
String responseType,
|
||||
String mimeType,
|
||||
Map<String, String> requestHeaders,
|
||||
dynamic sendData,
|
||||
}) {
|
||||
final Completer<html.HttpRequest> completer = Completer<html.HttpRequest>();
|
||||
final html.HttpRequest xhr = html.HttpRequest();
|
||||
/// Implements the client REST API for the local benchmark server.
|
||||
///
|
||||
/// The local server is optional. If it is not available the benchmark UI must
|
||||
/// implement a manual fallback. This allows debugging benchmarks using plain
|
||||
/// `flutter run`.
|
||||
class LocalBenchmarkServerClient {
|
||||
/// This value is returned by [requestNextBenchmark].
|
||||
static const String kManualFallback = '__manual_fallback__';
|
||||
|
||||
method ??= 'GET';
|
||||
xhr.open(method, url, async: true);
|
||||
/// Whether we fell back to manual mode.
|
||||
///
|
||||
/// This happens when you run benchmarks using plain `flutter run` rather than
|
||||
/// devicelab test harness. The test harness spins up a special server that
|
||||
/// provides API for automatically picking the next benchmark to run.
|
||||
bool isInManualMode;
|
||||
|
||||
if (withCredentials != null) {
|
||||
xhr.withCredentials = withCredentials;
|
||||
/// Asks the local server for the name of the next benchmark to run.
|
||||
///
|
||||
/// Returns [kManualFallback] if local server is not available (uses 404 as a
|
||||
/// signal).
|
||||
Future<String> requestNextBenchmark() async {
|
||||
final html.HttpRequest request = await _requestXhr(
|
||||
'/next-benchmark',
|
||||
method: 'POST',
|
||||
mimeType: 'application/json',
|
||||
sendData: json.encode(benchmarks.keys.toList()),
|
||||
);
|
||||
|
||||
// 404 is expected in the following cases:
|
||||
// - The benchmark is ran using plain `flutter run`, which does not provide "next-benchmark" handler.
|
||||
// - We ran all benchmarks and the benchmark is telling us there are no more benchmarks to run.
|
||||
if (request.status == 404) {
|
||||
isInManualMode = true;
|
||||
return kManualFallback;
|
||||
}
|
||||
|
||||
isInManualMode = false;
|
||||
return request.responseText;
|
||||
}
|
||||
|
||||
if (responseType != null) {
|
||||
xhr.responseType = responseType;
|
||||
void _checkNotManualMode() {
|
||||
if (isInManualMode) {
|
||||
throw StateError('Operation not supported in manual fallback mode.');
|
||||
}
|
||||
}
|
||||
|
||||
if (mimeType != null) {
|
||||
xhr.overrideMimeType(mimeType);
|
||||
/// Asks the local server to begin tracing performance.
|
||||
///
|
||||
/// This uses the chrome://tracing tracer, which is not available from within
|
||||
/// the page itself, and therefore must be controlled from outside using the
|
||||
/// DevTools Protocol.
|
||||
Future<void> startPerformanceTracing(String benchmarkName) async {
|
||||
_checkNotManualMode();
|
||||
await html.HttpRequest.request(
|
||||
'/start-performance-tracing?label=$benchmarkName',
|
||||
method: 'POST',
|
||||
mimeType: 'application/json',
|
||||
);
|
||||
}
|
||||
|
||||
if (requestHeaders != null) {
|
||||
requestHeaders.forEach((String header, String value) {
|
||||
xhr.setRequestHeader(header, value);
|
||||
/// Stops the performance tracing session started by [startPerformanceTracing].
|
||||
Future<void> stopPerformanceTracing() async {
|
||||
_checkNotManualMode();
|
||||
await html.HttpRequest.request(
|
||||
'/stop-performance-tracing',
|
||||
method: 'POST',
|
||||
mimeType: 'application/json',
|
||||
);
|
||||
}
|
||||
|
||||
/// Sends the profile data collected by the benchmark to the local benchmark
|
||||
/// server.
|
||||
Future<void> sendProfileData(Profile profile) async {
|
||||
_checkNotManualMode();
|
||||
final html.HttpRequest request = await html.HttpRequest.request(
|
||||
'/profile-data',
|
||||
method: 'POST',
|
||||
mimeType: 'application/json',
|
||||
sendData: json.encode(profile.toJson()),
|
||||
);
|
||||
if (request.status != 200) {
|
||||
throw Exception(
|
||||
'Failed to report profile data to benchmark server. '
|
||||
'The server responded with status code ${request.status}.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports an error to the benchmark server.
|
||||
///
|
||||
/// The server will halt the devicelab task and log the error.
|
||||
Future<void> reportError(dynamic error, StackTrace stackTrace) async {
|
||||
_checkNotManualMode();
|
||||
await html.HttpRequest.request(
|
||||
'/on-error',
|
||||
method: 'POST',
|
||||
mimeType: 'application/json',
|
||||
sendData: json.encode(<String, dynamic>{
|
||||
'error': '$error',
|
||||
'stackTrace': '$stackTrace',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/// This is the same as calling [html.HttpRequest.request] but it doesn't
|
||||
/// crash on 404, which we use to detect `flutter run`.
|
||||
Future<html.HttpRequest> _requestXhr(
|
||||
String url, {
|
||||
String method,
|
||||
bool withCredentials,
|
||||
String responseType,
|
||||
String mimeType,
|
||||
Map<String, String> requestHeaders,
|
||||
dynamic sendData,
|
||||
}) {
|
||||
final Completer<html.HttpRequest> completer = Completer<html.HttpRequest>();
|
||||
final html.HttpRequest xhr = html.HttpRequest();
|
||||
|
||||
method ??= 'GET';
|
||||
xhr.open(method, url, async: true);
|
||||
|
||||
if (withCredentials != null) {
|
||||
xhr.withCredentials = withCredentials;
|
||||
}
|
||||
|
||||
if (responseType != null) {
|
||||
xhr.responseType = responseType;
|
||||
}
|
||||
|
||||
if (mimeType != null) {
|
||||
xhr.overrideMimeType(mimeType);
|
||||
}
|
||||
|
||||
if (requestHeaders != null) {
|
||||
requestHeaders.forEach((String header, String value) {
|
||||
xhr.setRequestHeader(header, value);
|
||||
});
|
||||
}
|
||||
|
||||
xhr.onLoad.listen((html.ProgressEvent e) {
|
||||
completer.complete(xhr);
|
||||
});
|
||||
|
||||
xhr.onError.listen(completer.completeError);
|
||||
|
||||
if (sendData != null) {
|
||||
xhr.send(sendData);
|
||||
} else {
|
||||
xhr.send();
|
||||
}
|
||||
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
xhr.onLoad.listen((html.ProgressEvent e) {
|
||||
completer.complete(xhr);
|
||||
});
|
||||
|
||||
xhr.onError.listen(completer.completeError);
|
||||
|
||||
if (sendData != null) {
|
||||
xhr.send(sendData);
|
||||
} else {
|
||||
xhr.send();
|
||||
}
|
||||
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user