Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion .github/workflows/dart.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ class BuildPackageWatcher {
Stream<AssetChange> watch() {
_watcher = _strategy(buildPackage.path);
final events = _watcher.events;
return events.map((e) => AssetChange.fromEvent(buildPackage, e));
return events.map((e) {
++watcherEventCount;
return AssetChange.fromEvent(buildPackage, e);
});
}
}

/// DO NOT MERGE: count of watcher events, read by the merged directory probe.
int watcherEventCount = 0;
162 changes: 154 additions & 8 deletions build_runner/lib/src/io/create_merged_dir.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import 'package:pool/pool.dart';

import '../build_plan/build_directory.dart';
import '../build_plan/build_packages.dart';
import '../commands/watch/build_package_watcher.dart';
import '../logging/build_log.dart';
import '../logging/timed_activities.dart';
import 'build_output_reader.dart';
Expand All @@ -21,6 +22,76 @@ import 'build_output_reader.dart';
final _descriptorPool = Pool(32);

const _manifestName = '.build.manifest';

/// DO NOT MERGE: timings for measuring the merged directory on CI.
class _Timing {
final total = Stopwatch()..start();
final lap = Stopwatch()..start();
final parts = <String, int>{};
int readUs = 0;
int createUs = 0;
int writeUs = 0;
int filesDeleted = 0;
int dirsDeleted = 0;
int assets = 0;
final createUsList = <int>[];
final writeUsList = <int>[];
final startEvents = watcherEventCount;
int inFlight = 0;
int maxInFlight = 0;

// Event loop lag: a 5ms periodic timer that records how late it fires.
final _lagClock = Stopwatch()..start();
int _lastTick = 0;
int maxLagMs = 0;
int sumLagMs = 0;
int ticks = 0;
late final Timer _lagTimer;

_Timing() {
_lagTimer = Timer.periodic(const Duration(milliseconds: 5), (_) {
final now = _lagClock.elapsedMilliseconds;
final lag = now - _lastTick - 5;
_lastTick = now;
++ticks;
if (lag > 0) {
sumLagMs += lag;
if (lag > maxLagMs) maxLagMs = lag;
}
});
}

void stop() => _lagTimer.cancel();

static String _percentiles(String name, List<int> us) {
if (us.isEmpty) return '${name}_n=0';
final sorted = [...us]..sort();
int at(double q) => sorted[((sorted.length - 1) * q).round()] ~/ 1000;
return '${name}_p50=${at(.5)}ms ${name}_p90=${at(.9)}ms '
'${name}_p99=${at(.99)}ms ${name}_max=${at(1)}ms';
}

void mark(String name) {
parts[name] = lap.elapsedMilliseconds;
lap.reset();
}

@override
String toString() =>
'MERGED_TIMING total=${total.elapsedMilliseconds}ms '
'${[for (final e in parts.entries) '${e.key}=${e.value}ms'].join(' ')} '
'sum_read=${readUs ~/ 1000}ms sum_create=${createUs ~/ 1000}ms '
'sum_write=${writeUs ~/ 1000}ms assets=$assets '
'files_deleted=$filesDeleted dirs_deleted=$dirsDeleted '
'pid=$pid at=${DateTime.now().toIso8601String()} '
'watcher_events=${watcherEventCount - startEvents} '
'max_in_flight=$maxInFlight '
'lag_ticks=$ticks lag_max=${maxLagMs}ms lag_sum=${sumLagMs}ms '
'${_percentiles('create', createUsList)} '
'${_percentiles('write', writeUsList)}';
}

_Timing? _timing;
const _manifestSeparator = '\n';

/// Creates merged output directories for each [OutputLocation].
Expand Down Expand Up @@ -83,6 +154,7 @@ Future<bool> _createMergedOutputDir({
required bool hoist,
required BuildOutputReader buildOutputReader,
}) async {
final timing = _timing = _Timing();
try {
final outputRootPackage = buildPackages[buildPackages.outputRoot]!;
final absoluteRoot = p.join(outputRootPackage.path, root);
Expand All @@ -98,7 +170,10 @@ Future<bool> _createMergedOutputDir({
if (outputDirExists) {
if (!await _cleanUpOutputDir(outputDir)) return false;
}
timing.mark('clean');
final builtAssets = buildOutputReader.allAssets(rootDir: root).toList();
timing.assets = builtAssets.length;
timing.mark('list');
if (root != '' &&
!builtAssets
.where((id) => id.package == buildPackages.outputRoot)
Expand Down Expand Up @@ -131,6 +206,7 @@ Future<bool> _createMergedOutputDir({
),
]),
);
timing.mark('write');

if (!hoist) {
for (final dir in _findRootDirs(builtAssets, outputPath)) {
Expand All @@ -147,6 +223,16 @@ Future<bool> _createMergedOutputDir({
.map((path) => path.replaceAll(r'\', '/'))
.join(_manifestSeparator);
await _writeAsString(outputDir, _manifestName, content);
timing.mark('links_and_manifest');
timing.stop();
buildLog.info('$timing');
buildLog.info(
await _probeDummyWrites(
outputPaths,
'${outputDir.path}.probe',
Directory.systemTemp.createTempSync('merged_probe_').path,
),
);

return true;
} on FileSystemException catch (e) {
Expand Down Expand Up @@ -247,11 +333,27 @@ Future<String> _writeAsset(
_filePathFor(outputDir, assetPath),
).create(buildOutputReader.pathFor(id), recursive: true);
} else {
await _writeAsBytes(
outputDir,
assetPath,
(await buildOutputReader.read(id)).bytes,
);
final timing = _timing;
if (timing != null) {
++timing.inFlight;
if (timing.inFlight > timing.maxInFlight) {
timing.maxInFlight = timing.inFlight;
}
}
final watch = Stopwatch()..start();
final bytes = (await buildOutputReader.read(id)).bytes;
_timing?.readUs += watch.elapsedMicroseconds;
watch.reset();
final file = await File(
_filePathFor(outputDir, assetPath),
).create(recursive: true);
_timing?.createUs += watch.elapsedMicroseconds;
_timing?.createUsList.add(watch.elapsedMicroseconds);
watch.reset();
await file.writeAsBytes(bytes);
_timing?.writeUs += watch.elapsedMicroseconds;
_timing?.writeUsList.add(watch.elapsedMicroseconds);
if (timing != null) --timing.inFlight;
}
} on AssetNotFoundException catch (e) {
if (!p.basename(id.path).startsWith('.')) {
Expand All @@ -268,9 +370,6 @@ Future<String> _writeAsset(
});
}

Future<void> _writeAsBytes(Directory outputDir, String path, List<int> bytes) =>
_fileFor(outputDir, path).then((file) => file.writeAsBytes(bytes));

Future<void> _writeAsString(
Directory outputDir,
String path,
Expand Down Expand Up @@ -306,12 +405,17 @@ Future<bool> _cleanUpOutputDir(Directory outputDir) async {
_manifestSeparator,
);

final watch = Stopwatch()..start();
for (final path in previousOutputs) {
final file = File(p.join(outputPath, path));
if (!_existsResolvedWithin(file, outputPath)) continue;
file.deleteSync();
_timing?.filesDeleted++;
}
_timing?.parts['clean_files'] = watch.elapsedMilliseconds;
watch.reset();
_cleanEmptyDirectories(outputPath, previousOutputs);
_timing?.parts['clean_dirs'] = watch.elapsedMilliseconds;
}
return true;
}
Expand Down Expand Up @@ -341,6 +445,7 @@ void _deleteUp(String from, String to) {
return;
}
directory.deleteSync();
_timing?.dirsDeleted++;
directoryPath = p.dirname(directoryPath);
}
}
Expand All @@ -349,3 +454,44 @@ bool _existsResolvedWithin(FileSystemEntity entity, String rootPath) {
if (!entity.existsSync()) return false;
return p.isWithin(rootPath, entity.resolveSymbolicLinksSync());
}

/// DO NOT MERGE: writes a 4 KB dummy file for each of [relativePaths] under
/// each root, the same way `_writeAsset` writes, and times it, so that the
/// merged directory write can be compared with plain writes in the same
/// process at the same moment.
Future<String> _probeDummyWrites(
List<String> relativePaths,
String besideRoot,
String tempRoot,
) async {
final bytes = List<int>.filled(4096, 42);
final result = StringBuffer('MERGED_PROBE pid=$pid');
for (final MapEntry(key: name, value: root) in {
'beside': besideRoot,
'temp': tempRoot,
}.entries) {
final createUs = <int>[];
final writeUs = <int>[];
final total = Stopwatch()..start();
await Future.wait([
for (final path in relativePaths)
_descriptorPool.withResource(() async {
final watch = Stopwatch()..start();
final file = await File(p.join(root, path)).create(recursive: true);
createUs.add(watch.elapsedMicroseconds);
watch.reset();
await file.writeAsBytes(bytes);
writeUs.add(watch.elapsedMicroseconds);
}),
]);
result.write(
' ${name}_total=${total.elapsedMilliseconds}ms '
'${_Timing._percentiles('${name}_create', createUs)} '
'${_Timing._percentiles('${name}_write', writeUs)}',
);
total.reset();
Directory(root).deleteSync(recursive: true);
result.write(' ${name}_delete=${total.elapsedMilliseconds}ms');
}
return result.toString();
}
23 changes: 14 additions & 9 deletions build_runner/test/common/build_runner_tester.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,24 @@ import 'fixture_packages.dart';

/// End to end tester for `build_runner`.
///
/// Creates a workspace under system temp, fills it with Dart packages, and runs
/// commands in it.
/// Creates a workspace in a temp directory, fills it with Dart packages, and
/// runs commands in it.
class BuildRunnerTester {
final Pubspecs pubspecs;
final Directory tempDirectory;

BuildRunnerTester(Pubspecs pubspecs)
: this._(
pubspecs,
Directory.systemTemp.createTempSync('BuildRunnerTester-'),
);
: this._(pubspecs, _tempParent.createTempSync('BuildRunnerTester-'));

/// Where test workspaces are created.
///
/// On GitHub Actions this is `RUNNER_TEMP`. On Windows runners that is on the
/// D: drive, where file creation is several times faster than in the default
/// temp directory on C:.
static Directory get _tempParent {
final runnerTemp = Platform.environment['RUNNER_TEMP'];
return runnerTemp == null ? Directory.systemTemp : Directory(runnerTemp);
}

BuildRunnerTester._(this.pubspecs, this.tempDirectory) {
addTearDown(() async {
Expand All @@ -52,9 +59,7 @@ class BuildRunnerTester {
/// Copies the entire workspace, returns a new `BuildRunnerTester` using
/// the copy.
BuildRunnerTester copyWorkspace() {
final newTemp = Directory.systemTemp.createTempSync(
'BuildRunnerTester-copy-',
);
final newTemp = _tempParent.createTempSync('BuildRunnerTester-copy-');
copyPathSync(tempDirectory.path, newTemp.path);
return BuildRunnerTester._(pubspecs, newTemp);
}
Expand Down
Loading
Loading