Support hot restart for DDC library bundle format (#162123)

https://github.com/dart-lang/webdev/issues/2516
https://github.com/dart-lang/webdev/issues/2561

- Adds logic to emit newly compiled sources to a file that can be read
by the bootstrapper.
- Adds bootstrapping logic to reload scripts as needed. This involves
implementing the necessary hot restart callback, fetching and processing
the emitted file of newly compiled sources, cache busting, and loading
the scripts onto the page. A lot of this logic is similar or identical
to what we have for internal hot restart support.
- Runs existing hot restart tests with the new bundle format.
- Adds meta tag to run with utf-8 like in
https://github.com/flutter/flutter/pull/161493.
- Uses DWDS 24.3.3.

## Pre-launch Checklist

- [X] I read the [Contributor Guide] and followed the process outlined
there for submitting PRs.
- [X] I read the [Tree Hygiene] wiki page, which explains my
responsibilities.
- [X] I read and followed the [Flutter Style Guide], including [Features
we expect every widget to implement].
- [X] I signed the [CLA].
- [X] I listed at least one issue that this PR fixes in the description
above.
- [X] I updated/added relevant documentation (doc comments with `///`).
- [X] I added new tests to check the change I am making, or this PR is
[test-exempt].
- [X] I followed the [breaking change policy] and added [Data Driven
Fixes] where supported.
- [ ] All existing and new tests are passing.
This commit is contained in:
Srujan Gaddam
2025-01-28 11:10:20 -08:00
committed by GitHub
parent dc580aff78
commit 6d2792de5c
10 changed files with 217 additions and 33 deletions

View File

@@ -146,9 +146,19 @@ class WebAssetServer implements AssetReader {
final Map<String, String> _modules;
final Map<String, String> _digests;
// The generation number that maps to the number of hot restarts. This is used
// to suffix a query to source paths in order to cache-bust.
int _hotRestartGeneration = 0;
int get selectedPort => _httpServer.port;
void performRestart(List<String> modules) {
/// Given a list of [modules] that need to be loaded, compute module names and
/// digests.
///
/// If [writeRestartScripts] is true, writes a list of sources mapped to their
/// ids to the file system that can then be consumed by the hot restart
/// callback.
void performRestart(List<String> modules, {required bool writeRestartScripts}) {
for (final String module in modules) {
// We skip computing the digest by using the hashCode of the underlying buffer.
// Whenever a file is updated, the corresponding Uint8List.view it corresponds
@@ -159,6 +169,14 @@ class WebAssetServer implements AssetReader {
_modules[name] = path;
_digests[name] = _webMemoryFS.files[moduleName].hashCode.toString();
}
if (writeRestartScripts && _hotRestartGeneration > 0) {
final List<Map<String, String>> srcIdsList = <Map<String, String>>[];
for (final String src in modules) {
srcIdsList.add(<String, String>{'src': '$src?gen=$_hotRestartGeneration', 'id': src});
}
writeFile('main.dart.js.restartScripts', json.encode(srcIdsList));
}
_hotRestartGeneration++;
}
@visibleForTesting
@@ -241,8 +259,8 @@ class WebAssetServer implements AssetReader {
}
final PackageConfig packageConfig = buildInfo.packageConfig;
final Map<String, String> digests = <String, String>{};
final Map<String, String> modules = <String, String>{};
final Map<String, String> digests = <String, String>{};
final WebAssetServer server = WebAssetServer(
httpServer,
packageConfig,
@@ -784,6 +802,7 @@ class WebDevFS implements DevFS {
required this.isWasm,
required this.useLocalCanvasKit,
required this.rootDirectory,
required this.isWindows,
this.testMode = false,
}) : _port = port {
// TODO(srujzs): Remove this assertion when the library bundle format is
@@ -818,6 +837,7 @@ class WebDevFS implements DevFS {
final WebRendererMode webRenderer;
final bool isWasm;
final bool useLocalCanvasKit;
final bool isWindows;
late WebAssetServer webAssetServer;
@@ -1014,6 +1034,7 @@ class WebDevFS implements DevFS {
ddcModuleLoaderUrl: 'ddc_module_loader.js',
mapperUrl: 'stack_trace_mapper.js',
generateLoadingIndicator: enableDwds,
isWindows: isWindows,
)
: generateBootstrapScript(
requireUrl: 'require.js',
@@ -1101,7 +1122,8 @@ class WebDevFS implements DevFS {
} on FileSystemException catch (err) {
throwToolExit('Failed to load recompiled sources:\n$err');
}
webAssetServer.performRestart(modules);
webAssetServer.performRestart(modules, writeRestartScripts: ddcModuleSystem);
return UpdateFSReport(
success: true,
syncedBytes: codeFile.lengthSync(),

View File

@@ -319,6 +319,7 @@ Please provide a valid TCP port (an integer between 0 and 65535, inclusive).
isWasm: debuggingOptions.webUseWasm,
useLocalCanvasKit: debuggingOptions.buildInfo.useLocalCanvasKit,
rootDirectory: fileSystem.directory(projectRootPath),
isWindows: globals.platform.isWindows,
);
Uri url = await device!.devFS!.create();
if (debuggingOptions.tlsCertKeyPath != null && debuggingOptions.tlsCertPath != null) {

View File

@@ -145,23 +145,24 @@ String generateDDCLibraryBundleBootstrapScript({
required String ddcModuleLoaderUrl,
required String mapperUrl,
required bool generateLoadingIndicator,
String appRootDirectory = '/',
required bool isWindows,
}) {
return '''
${generateLoadingIndicator ? _generateLoadingIndicator() : ""}
// TODO(markzipan): This is safe if Flutter app roots are always equal to the
// host root '/'. Validate if this is true.
var _currentDirectory = "$appRootDirectory";
// Save the current directory so we can access it in a closure.
var _currentDirectory = (function () {
var _url = document.currentScript.src;
var lastSlash = _url.lastIndexOf('/');
if (lastSlash == -1) return _url;
var currentDirectory = _url.substring(0, lastSlash + 1);
return currentDirectory;
})();
$_simpleLoaderScript
// A map containing the URLs for the bootstrap scripts in debug.
let _scriptUrls = {
"mapper": "$mapperUrl",
"moduleLoader": "$ddcModuleLoaderUrl"
};
(function() {
let appName = "org-dartlang-app:/$entrypoint";
// Load pre-requisite DDC scripts. We intentionally use invalid names to avoid
// namespace clashes.
let prerequisiteScripts = [
@@ -182,6 +183,17 @@ let _scriptUrls = {
}
Promise.all(prerequisiteLoads).then((_) => afterPrerequisiteLogic());
// Save the current script so we can access it in a closure.
var _currentScript = document.currentScript;
// Create a policy if needed to load the files during a hot restart.
let policy = {
createScriptURL: function(src) {return src;}
};
if (self.trustedTypes && self.trustedTypes.createPolicy) {
policy = self.trustedTypes.createPolicy('dartDdcModuleUrl', policy);
}
var afterPrerequisiteLogic = function() {
window.\$dartLoader.rootDirectories.push(_currentDirectory);
let scripts = [
@@ -196,6 +208,8 @@ let _scriptUrls = {
];
let loadConfig = new window.\$dartLoader.LoadConfiguration();
// TODO(srujzs): Verify this is sufficient for Windows.
loadConfig.isWindows = $isWindows;
loadConfig.bootstrapScript = scripts[scripts.length - 1];
loadConfig.loadScriptFn = function(loader) {
@@ -216,11 +230,82 @@ let _scriptUrls = {
window.\$dartLoader.loadConfig = loadConfig;
window.\$dartLoader.loader = loader;
// TODO(srujzs): Support hot restart.
// Begin loading libraries
loader.nextAttempt();
}
// Set up stack trace mapper.
if (window.\$dartStackTraceUtility &&
!window.\$dartStackTraceUtility.ready) {
window.\$dartStackTraceUtility.ready = true;
window.\$dartStackTraceUtility.setSourceMapProvider(function(url) {
var baseUrl = window.location.protocol + '//' + window.location.host;
url = url.replace(baseUrl + '/', '');
if (url == 'dart_sdk.js') {
return dartDevEmbedder.debugger.getSourceMap('dart_sdk');
}
url = url.replace(".lib.js", "");
return dartDevEmbedder.debugger.getSourceMap(url);
});
}
let currentUri = _currentScript.src;
// We should have written a file containing all the scripts that need to be
// reloaded into the page. This is then read when a hot restart is triggered
// in DDC via the `\$dartReloadModifiedModules` callback.
let restartScripts = currentUri + '.restartScripts';
if (!window.\$dartReloadModifiedModules) {
window.\$dartReloadModifiedModules = (function(appName, callback) {
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
xhttp.onreadystatechange = function() {
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
if (this.readyState == 4 && this.status == 200 || this.status == 304) {
var scripts = JSON.parse(this.responseText);
var numToLoad = 0;
var numLoaded = 0;
for (var i = 0; i < scripts.length; i++) {
var script = scripts[i];
if (script.id == null) continue;
var src = _currentDirectory + script.src.toString();
var oldSrc = window.\$dartLoader.moduleIdToUrl.get(script.id);
// Only compare the search parameters which contain the cache
// busting portion of the uri. The path might be different if the
// script is loaded from a different application on the page.
if (window.\$dartLoader.moduleIdToUrl.has(script.id) &&
new URL(oldSrc).search == new URL(src).search) continue;
// We might actually load from a different uri, delete the old one
// just to be sure.
window.\$dartLoader.urlToModuleId.delete(oldSrc);
window.\$dartLoader.moduleIdToUrl.set(script.id, src);
window.\$dartLoader.urlToModuleId.set(src, script.id);
numToLoad++;
var el = document.getElementById(script.id);
if (el) el.remove();
el = window.\$dartCreateScript();
el.src = policy.createScriptURL(src);
el.async = false;
el.defer = true;
el.id = script.id;
el.onload = function() {
numLoaded++;
if (numToLoad == numLoaded) callback();
};
document.head.appendChild(el);
}
// Call `callback` right away if we found no updated scripts.
if (numToLoad == 0) callback();
}
};
xhttp.open("GET", restartScripts, true);
xhttp.send();
});
}
};
})();
''';
}

View File

@@ -196,12 +196,11 @@ void main() {
ddcModuleLoaderUrl: 'ddc_module_loader.js',
mapperUrl: 'mapper.js',
generateLoadingIndicator: true,
isWindows: false,
);
// ddc module loader js source is interpolated correctly.
expect(result, contains('"moduleLoader": "ddc_module_loader.js"'));
expect(result, contains('"src": "ddc_module_loader.js"'));
// stack trace mapper source is interpolated correctly.
expect(result, contains('"mapper": "mapper.js"'));
expect(result, contains('"src": "mapper.js"'));
// data-main is set to correct bootstrap module.
expect(result, contains('"src": "main_module.bootstrap.js"'));
@@ -214,6 +213,7 @@ void main() {
ddcModuleLoaderUrl: 'ddc_module_loader.js',
mapperUrl: 'mapper.js',
generateLoadingIndicator: true,
isWindows: false,
);
// LoadConfiguration and DDCLoader objects must be constructed.
expect(result, contains(r'new window.$dartLoader.LoadConfiguration('));
@@ -234,6 +234,7 @@ void main() {
ddcModuleLoaderUrl: 'ddc_module_loader.js',
mapperUrl: 'mapper.js',
generateLoadingIndicator: true,
isWindows: false,
);
expect(result, contains('"flutter-loader"'));
expect(result, contains('"indeterminate"'));
@@ -245,6 +246,7 @@ void main() {
ddcModuleLoaderUrl: 'ddc_module_loader.js',
mapperUrl: 'mapper.js',
generateLoadingIndicator: false,
isWindows: false,
);
expect(result, isNot(contains('"flutter-loader"')));
expect(result, isNot(contains('"indeterminate"')));
@@ -257,6 +259,7 @@ void main() {
ddcModuleLoaderUrl: 'ddc_module_loader.js',
mapperUrl: 'mapper.js',
generateLoadingIndicator: true,
isWindows: false,
);
// See: https://regexr.com/6q0ft

View File

@@ -817,6 +817,7 @@ void main() {
isWasm: false,
useLocalCanvasKit: false,
rootDirectory: globals.fs.currentDirectory,
isWindows: false,
);
webDevFS.ddcModuleLoaderJS.createSync(recursive: true);
webDevFS.flutterJs.createSync(recursive: true);
@@ -944,6 +945,7 @@ void main() {
isWasm: false,
useLocalCanvasKit: false,
rootDirectory: globals.fs.currentDirectory,
isWindows: false,
);
webDevFS.ddcModuleLoaderJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true);
@@ -1019,6 +1021,7 @@ void main() {
isWasm: false,
useLocalCanvasKit: false,
rootDirectory: globals.fs.currentDirectory,
isWindows: false,
);
webDevFS.ddcModuleLoaderJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true);
@@ -1069,6 +1072,7 @@ void main() {
isWasm: false,
useLocalCanvasKit: false,
rootDirectory: globals.fs.currentDirectory,
isWindows: false,
);
webDevFS.ddcModuleLoaderJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true);
@@ -1120,6 +1124,7 @@ void main() {
isWasm: false,
useLocalCanvasKit: false,
rootDirectory: globals.fs.currentDirectory,
isWindows: false,
);
webDevFS.ddcModuleLoaderJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true);
@@ -1171,6 +1176,7 @@ void main() {
isWasm: false,
useLocalCanvasKit: false,
rootDirectory: globals.fs.currentDirectory,
isWindows: false,
);
webDevFS.ddcModuleLoaderJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true);
@@ -1335,6 +1341,7 @@ void main() {
isWasm: false,
useLocalCanvasKit: false,
rootDirectory: globals.fs.currentDirectory,
isWindows: false,
);
webDevFS.ddcModuleLoaderJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true);

View File

@@ -995,6 +995,7 @@ void main() {
isWasm: false,
useLocalCanvasKit: false,
rootDirectory: globals.fs.currentDirectory,
isWindows: false,
);
webDevFS.requireJS.createSync(recursive: true);
webDevFS.flutterJs.createSync(recursive: true);
@@ -1114,6 +1115,7 @@ void main() {
isWasm: false,
useLocalCanvasKit: false,
rootDirectory: globals.fs.currentDirectory,
isWindows: false,
);
webDevFS.requireJS.createSync(recursive: true);
webDevFS.flutterJs.createSync(recursive: true);
@@ -1239,6 +1241,7 @@ void main() {
isWasm: false,
useLocalCanvasKit: false,
rootDirectory: globals.fs.currentDirectory,
isWindows: false,
);
webDevFS.requireJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true);
@@ -1317,6 +1320,7 @@ void main() {
isWasm: false,
useLocalCanvasKit: false,
rootDirectory: globals.fs.currentDirectory,
isWindows: false,
);
webDevFS.requireJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true);
@@ -1370,6 +1374,7 @@ void main() {
isWasm: false,
useLocalCanvasKit: false,
rootDirectory: globals.fs.currentDirectory,
isWindows: false,
);
webDevFS.requireJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true);
@@ -1424,6 +1429,7 @@ void main() {
isWasm: false,
useLocalCanvasKit: false,
rootDirectory: globals.fs.currentDirectory,
isWindows: false,
);
webDevFS.requireJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true);
@@ -1478,6 +1484,7 @@ void main() {
isWasm: false,
useLocalCanvasKit: false,
rootDirectory: globals.fs.currentDirectory,
isWindows: false,
);
webDevFS.requireJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true);
@@ -1652,6 +1659,7 @@ void main() {
isWasm: false,
useLocalCanvasKit: false,
rootDirectory: globals.fs.currentDirectory,
isWindows: false,
);
webDevFS.requireJS.createSync(recursive: true);
webDevFS.stackTraceMapper.createSync(recursive: true);

View File

@@ -10,6 +10,7 @@ import 'deferred_components_config.dart';
const String _kDefaultHtml = '''
<html>
<head>
<meta charset='utf-8'>
<title>Hello, World</title>
</head>
<body>

View File

@@ -0,0 +1,14 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@Tags(<String>['flutter-test-driver'])
library;
import '../src/common.dart';
import 'test_data/hot_restart_web_utils.dart';
void main() async {
await testAll(useDDCLibraryBundleFormat: false);
}

View File

@@ -0,0 +1,14 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@Tags(<String>['flutter-test-driver'])
library;
import '../src/common.dart';
import 'test_data/hot_restart_web_utils.dart';
void main() async {
await testAll(useDDCLibraryBundleFormat: true);
}

View File

@@ -2,61 +2,84 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@Tags(<String>['flutter-test-driver'])
library;
import 'dart:async';
import 'package:file/file.dart';
import '../integration.shard/test_data/hot_reload_project.dart';
import '../integration.shard/test_driver.dart';
import '../integration.shard/test_utils.dart';
import '../src/common.dart';
import '../../integration.shard/test_data/hot_reload_project.dart';
import '../../integration.shard/test_driver.dart';
import '../../integration.shard/test_utils.dart';
import '../../src/common.dart';
import 'test_data/hot_reload_index_html_samples.dart';
import 'hot_reload_index_html_samples.dart';
void main() async {
await _testProject(HotReloadProject()); // default
await testAll(useDDCLibraryBundleFormat: false);
}
Future<void> testAll({required bool useDDCLibraryBundleFormat}) async {
await _testProject(
HotReloadProject(),
useDDCLibraryBundleFormat: useDDCLibraryBundleFormat,
); // default
await _testProject(
HotReloadProject(constApp: true),
name: 'Default) (with `const MyApp()`)',
useDDCLibraryBundleFormat: useDDCLibraryBundleFormat,
); // runApp(const MyApp());
await _testProject(
HotReloadProject(indexHtml: indexHtmlFlutterJsCallback),
name: 'flutter.js (callback)',
useDDCLibraryBundleFormat: useDDCLibraryBundleFormat,
);
await _testProject(
HotReloadProject(indexHtml: indexHtmlFlutterJsPromisesFull),
name: 'flutter.js (promises)',
useDDCLibraryBundleFormat: useDDCLibraryBundleFormat,
);
await _testProject(
HotReloadProject(indexHtml: indexHtmlFlutterJsPromisesShort),
name: 'flutter.js (promises, short)',
useDDCLibraryBundleFormat: useDDCLibraryBundleFormat,
);
await _testProject(
HotReloadProject(indexHtml: indexHtmlFlutterJsLoad),
name: 'flutter.js (load)',
useDDCLibraryBundleFormat: useDDCLibraryBundleFormat,
);
await _testProject(
HotReloadProject(indexHtml: indexHtmlNoFlutterJs),
name: 'No flutter.js',
useDDCLibraryBundleFormat: useDDCLibraryBundleFormat,
);
await _testProject(HotReloadProject(indexHtml: indexHtmlNoFlutterJs), name: 'No flutter.js');
await _testProject(
HotReloadProject(indexHtml: indexHtmlWithFlutterBootstrapScriptTag),
name: 'Using flutter_bootstrap.js script tag',
useDDCLibraryBundleFormat: useDDCLibraryBundleFormat,
);
await _testProject(
HotReloadProject(indexHtml: indexHtmlWithInlinedFlutterBootstrapScript),
name: 'Using inlined flutter_bootstrap.js',
useDDCLibraryBundleFormat: useDDCLibraryBundleFormat,
);
}
Future<void> _testProject(HotReloadProject project, {String name = 'Default'}) async {
Future<void> _testProject(
HotReloadProject project, {
String name = 'Default',
required bool useDDCLibraryBundleFormat,
}) async {
late Directory tempDir;
late FlutterRunTestDriver flutter;
final String testName = 'Hot reload (index.html: $name)';
final String testName = 'Hot restart (index.html: $name)';
final List<String> additionalCommandArgs =
useDDCLibraryBundleFormat
? <String>['--extra-front-end-options=--dartdevc-canary,--dartdevc-module-format=ddc']
: <String>[];
setUp(() async {
tempDir = createResolvedTempDirectorySync('hot_reload_test.');
tempDir = createResolvedTempDirectorySync('hot_restart_test.');
await project.setUpIn(tempDir);
flutter = FlutterRunTestDriver(tempDir);
});
@@ -69,7 +92,10 @@ Future<void> _testProject(HotReloadProject project, {String name = 'Default'}) a
testWithoutContext('$testName: hot restart works without error', () async {
flutter.stdout.listen(printOnFailure);
await flutter.run(chrome: true, additionalCommandArgs: <String>['--verbose']);
await flutter.run(
chrome: true,
additionalCommandArgs: <String>['--verbose', ...additionalCommandArgs],
);
await flutter.hotRestart();
});
@@ -83,7 +109,10 @@ Future<void> _testProject(HotReloadProject project, {String name = 'Default'}) a
completer.complete();
}
});
await flutter.run(chrome: true, additionalCommandArgs: <String>['--verbose']);
await flutter.run(
chrome: true,
additionalCommandArgs: <String>['--verbose', ...additionalCommandArgs],
);
project.uncommentHotReloadPrint();
try {
await flutter.hotRestart();