blob: 6680c782ec388616d3f42d68e6973fe18b936649 [file]
// 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.
import 'dart:async';
import 'package:dwds/dwds.dart';
import 'package:meta/meta.dart';
import 'package:package_config/package_config.dart';
import 'package:process/process.dart';
import 'package:vm_service/vm_service.dart' as vm_service;
import '../artifacts.dart';
import '../asset.dart';
import '../base/common.dart';
import '../base/config.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
import '../base/net.dart';
import '../base/platform.dart';
import '../build_info.dart';
import '../build_system/tools/asset_transformer.dart';
import '../build_system/tools/shader_compiler.dart';
import '../compile.dart';
import '../context/tool_context.dart';
import '../devfs.dart';
import '../project.dart';
import '../vmservice.dart';
import '../web/bootstrap.dart';
import '../web/chrome.dart';
import '../web/web_debug_config.dart';
import '../web_template.dart';
import 'web_asset_server.dart';
const kLuciEnvName = 'LUCI_CONTEXT';
/// A web server which handles serving JavaScript and assets.
///
/// This is only used in development mode.
class ConnectionResult {
ConnectionResult(this.appConnection, this.debugConnection, this.vmService);
final AppConnection? appConnection;
final DebugConnection? debugConnection;
final vm_service.VmService vmService;
}
typedef VmServiceFactory = Future<vm_service.VmService> Function(
Uri, {
CompressionOptions compression,
required Logger logger,
});
/// The web specific DevFS implementation.
class WebDevFS implements DevFS {
/// Create a new [WebDevFS] instance.
///
/// [testMode] is true, do not actually initialize dwds or the shelf static
/// server.
WebDevFS({
required this.packagesFilePath,
required this.urlTunneller,
required this.buildInfo,
required this.enableDwds,
required this.ddsConfig,
required this.entrypoint,
required this.expressionCompiler,
required this.chromiumLauncher,
required this.webConfig,
required this.useLocalCanvasKit,
required this.rootDirectory,
required this._toolContext,
this.useDwdsWebSocketConnection = false,
this.testMode = false,
}) {
final ToolContext(
:Artifacts artifacts,
:FileSystem fs,
:Logger logger,
:ProcessManager processManager,
) = _toolContext;
_assetTransformer = DevelopmentAssetTransformer(
transformer: AssetTransformer(
processManager: processManager,
fileSystem: fs,
dartBinaryPath: artifacts.getArtifactPath(Artifact.engineDartBinary),
buildMode: buildInfo.mode,
),
fileSystem: fs,
logger: logger,
);
}
final Uri entrypoint;
final String packagesFilePath;
final UrlTunneller? urlTunneller;
final BuildInfo buildInfo;
final bool enableDwds;
final DartDevelopmentServiceConfiguration ddsConfig;
final bool testMode;
final ExpressionCompiler? expressionCompiler;
final ChromiumLauncher? chromiumLauncher;
late final DevelopmentAssetTransformer _assetTransformer;
final bool useLocalCanvasKit;
final bool useDwdsWebSocketConnection;
final WebDebugConfig webConfig;
final ToolContext _toolContext;
late WebAssetServer webAssetServer;
Dwds get dwds => webAssetServer.dwds;
// A flag to indicate whether we have called `setAssetDirectory` on the target device.
@override
bool hasSetAssetDirectory = false;
@override
bool didUpdateFontManifest = false;
final Set<String> _shaderPathsToEvict = <String>{};
final Set<String> _assetPathsToEvict = <String>{};
Future<DebugConnection>? _cachedExtensionFuture;
StreamSubscription<void>? _connectedApps;
/// Connect and retrieve the [DebugConnection] for the current application.
///
/// Only calls [AppConnection.runMain] on the subsequent connections. This
/// should be called before the browser is launched to make sure the listener
/// is registered early enough.
Future<ConnectionResult?> connect(
bool useDebugExtension, {
@visibleForTesting VmServiceFactory vmServiceFactory = createVmServiceDelegate,
}) {
final Logger logger = _toolContext.logger;
final firstConnection = Completer<ConnectionResult>();
// Note there is an asynchronous gap between this being set to true and
// [firstConnection] completing; thus test the boolean to determine if
// the current connection is the first.
var foundFirstConnection = false;
_connectedApps = dwds.connectedApps.listen(
(AppConnection appConnection) async {
try {
final DebugConnection debugConnection = useDebugExtension
? await (_cachedExtensionFuture ??= dwds.extensionDebugConnections.stream.first)
: await dwds.debugConnection(appConnection);
if (foundFirstConnection) {
appConnection.runMain();
} else {
foundFirstConnection = true;
final vm_service.VmService vmService = await vmServiceFactory(
Uri.parse(debugConnection.uri),
logger: logger,
);
firstConnection.complete(ConnectionResult(appConnection, debugConnection, vmService));
}
} on Exception catch (error, stackTrace) {
if (!firstConnection.isCompleted) {
firstConnection.completeError(error, stackTrace);
}
}
},
onError: (Object error, StackTrace stackTrace) {
logger.printError('Unknown error while waiting for debug connection:$error\n$stackTrace');
if (!firstConnection.isCompleted) {
firstConnection.completeError(error, stackTrace);
}
},
);
return firstConnection.future;
}
@override
List<Uri> sources = <Uri>[];
@override
DateTime? lastCompiled;
@override
PackageConfig? lastPackageConfig;
@override
Set<String> get assetPathsToEvict => _assetPathsToEvict;
@override
Uri get baseUri => webAssetServer.baseUri;
@override
Future<Uri> create() async {
webAssetServer = await WebAssetServer.start(
chromiumLauncher,
urlTunneller,
buildInfo,
enableDwds,
ddsConfig,
entrypoint,
expressionCompiler,
useLocalCanvasKit: useLocalCanvasKit,
testMode: testMode,
webConfig: webConfig,
useDwdsWebSocketConnection: useDwdsWebSocketConnection,
toolContext: _toolContext,
);
return baseUri;
}
/// Signal that the underlying web asset server is ready to handle requests.
///
/// The HTTP server starts listening early during [create] so the port and URI
/// are known before compilation. However, incoming HTTP requests are held
/// until initial compilation completes and the DWDS connection listener is
/// registered so clients do not load incomplete assets or miss connection events.
void markReady() {
webAssetServer.markReady();
}
@override
Future<void> destroy() async {
await webAssetServer.dispose();
await _connectedApps?.cancel();
}
@override
Uri deviceUriToHostUri(Uri deviceUri) {
return deviceUri;
}
@override
String get fsName => 'web_asset';
@override
final Directory rootDirectory;
Future<void> _validateTemplateFile(String filename) async {
final File file = _toolContext.fs.currentDirectory.childDirectory('web').childFile(filename);
if (!file.existsSync()) {
return;
}
final template = WebTemplate(await file.readAsString());
for (final WebTemplateWarning warning in template.getWarnings()) {
_toolContext.logger.printWarning(
'Warning: In $filename:${warning.lineNumber}: ${warning.warningText}',
);
}
}
@override
Future<UpdateFSReport> update({
required Uri mainUri,
required ResidentCompiler generator,
required bool trackWidgetCreation,
required String pathToReload,
required List<Uri> invalidatedFiles,
required PackageConfig packageConfig,
required String dillOutputPath,
required DevelopmentShaderCompiler shaderCompiler,
DevFSWriter? devFSWriter,
String? target,
AssetBundle? bundle,
bool bundleFirstUpload = false,
bool fullRestart = false,
bool resetCompiler = false,
String? projectRootPath,
File? dartPluginRegistrant,
}) async {
final ToolContext(:Config config, :FileSystem fs, :Logger logger, :Platform platform) =
_toolContext;
_shaderPathsToEvict.clear();
_assetPathsToEvict.clear();
lastPackageConfig = packageConfig;
final File mainFile = fs.file(mainUri);
final String outputDirectoryPath = mainFile.parent.path;
if (bundleFirstUpload) {
webAssetServer.entrypointCacheDirectory = fs.directory(outputDirectoryPath);
generator.addFileSystemRoot(outputDirectoryPath);
final String entrypoint = fs.path.basename(mainFile.path);
webAssetServer.writeBytes(entrypoint, mainFile.readAsBytesSync());
webAssetServer.writeBytes('ddc_module_loader.js', ddcModuleLoaderJS.readAsBytesSync());
webAssetServer.writeBytes('flutter.js', flutterJs.readAsBytesSync());
webAssetServer.writeBytes('stack_trace_mapper.js', stackTraceMapper.readAsBytesSync());
webAssetServer.writeFile('manifest.json', '{"info":"manifest not generated in run mode."}');
webAssetServer.writeFile(
'version.json',
FlutterProject.current(fs, logger: logger).getVersionInfo(),
);
webAssetServer.writeFile(
'main.dart.js',
generateDDCLibraryBundleBootstrapScript(
ddcModuleLoaderUrl: 'ddc_module_loader.js',
mapperUrl: 'stack_trace_mapper.js',
generateLoadingIndicator: true,
isWindows: platform.isWindows,
),
);
const onLoadEndBootstrap = 'on_load_end_bootstrap.js';
webAssetServer.writeFile(onLoadEndBootstrap, generateDDCLibraryBundleOnLoadEndBootstrap());
webAssetServer.writeFile(
'main_module.bootstrap.js',
generateDDCLibraryBundleMainModule(
entrypoint: entrypoint,
nativeNullAssertions: webConfig.nativeNullAssertions,
onLoadEndBootstrap: onLoadEndBootstrap,
isCi: platform.environment.containsKey(kLuciEnvName),
),
);
}
var syncedBytes = 0;
if (bundle != null) {
final String assetDirectory = fs.path.absolute(getAssetBuildDirectory(config, fs));
final Directory assetDir = fs.directory(assetDirectory);
if (bundleFirstUpload && assetDir.existsSync()) {
try {
assetDir.deleteSync(recursive: true);
} on FileSystemException catch (err) {
logger.printWarning(
'Failed to clean up asset directory ${assetDir.path}: $err\n'
'To clean build artifacts, use the command "flutter clean".',
);
}
}
assetDir.createSync(recursive: true);
final dirtyEntries = <Uri, DevFSContent>{};
try {
final int bundleSyncedBytes = await DevFS.updateBundle(
bundle: bundle,
dirtyEntries: dirtyEntries,
assetDirectory: assetDirectory,
assetTransformer: _assetTransformer,
shaderCompiler: shaderCompiler,
fileSystem: fs,
rootDirectoryPath: rootDirectory.path,
assetPathsToEvict: _assetPathsToEvict,
shaderPathsToEvict: _shaderPathsToEvict,
bundleFirstUpload: bundleFirstUpload,
invalidatedFiles: invalidatedFiles,
syncAllAssetsOnFirstUpload: true,
onFontManifestUpdated: () => didUpdateFontManifest = true,
);
syncedBytes += bundleSyncedBytes;
_assetTransformer.pruneDependencies(bundle.entries.keys.toSet());
} on Exception catch (err, stackTrace) {
logger.printError('Error updating bundle: $err');
logger.printTrace('$stackTrace');
return UpdateFSReport();
}
if (dirtyEntries.isNotEmpty) {
await LocalDevFSWriter(fileSystem: fs).write(dirtyEntries, fs.path.toUri(assetDirectory));
}
}
await _validateTemplateFile('index.html');
await _validateTemplateFile('flutter_bootstrap.js');
final candidateCompileTime = DateTime.now();
if (resetCompiler) {
generator.reset();
}
// The tool generates an entrypoint file in a temp directory to handle
// the web specific bootstrap logic. To make it easier for DWDS to handle
// mapping the file name, this is done via an additional file root and
// special hard-coded scheme.
final CompilerOutput? compilerOutput = await generator.recompile(
Uri(
scheme: 'org-dartlang-app',
// An empty String here causes the URI to appear with three slashes and
// matches the pattern the infra creates for other modules in the app.
// Ex: org-dartlang-app:///main.dart
host: '',
path: '/${mainUri.pathSegments.last}',
),
invalidatedFiles,
outputPath: dillOutputPath,
packageConfig: packageConfig,
projectRootPath: projectRootPath,
fs: fs,
dartPluginRegistrant: dartPluginRegistrant,
recompileRestart: fullRestart,
);
if (compilerOutput == null || compilerOutput.errorCount > 0) {
return UpdateFSReport(
// TODO(srujzs): We're currently reliant on compile error string parsing
// as hot reload rejections are sent to stderr just like other
// compilation errors. Ideally, we should have some shared parsing
// functionality, but that would require a shared package.
// See https://github.com/dart-lang/sdk/issues/60275.
hotReloadRejected: compilerOutput?.errorMessage?.contains('Hot reload rejected') ?? false,
);
}
// Only update the last compiled time if we successfully compiled.
lastCompiled = candidateCompileTime;
// list of sources that needs to be monitored are in [compilerOutput.sources]
sources = <Uri>{
...compilerOutput.sources,
..._assetTransformer.dependencies.values.expand((Set<Uri> uris) => uris),
}.toList();
late File codeFile;
File manifestFile;
File sourcemapFile;
File metadataFile;
late List<String> modules;
try {
final Directory parentDirectory = fs.directory(outputDirectoryPath);
codeFile = parentDirectory.childFile('${compilerOutput.outputFilename}.sources');
manifestFile = parentDirectory.childFile('${compilerOutput.outputFilename}.json');
sourcemapFile = parentDirectory.childFile('${compilerOutput.outputFilename}.map');
metadataFile = parentDirectory.childFile('${compilerOutput.outputFilename}.metadata');
modules = webAssetServer.webMemoryFS.write(
codeFile,
manifestFile,
sourcemapFile,
metadataFile,
);
} on FileSystemException catch (err) {
throwToolExit('Failed to load recompiled sources:\n$err');
}
webAssetServer.updateModulesAndDigests(modules);
if (!bundleFirstUpload) {
webAssetServer.writeReloadedSources(modules);
}
return UpdateFSReport(
success: true,
syncedBytes: codeFile.lengthSync() + syncedBytes,
invalidatedSourcesCount: invalidatedFiles.length,
);
}
@visibleForTesting
File get ddcModuleLoaderJS {
final ToolContext(:Artifacts artifacts, :FileSystem fs) = _toolContext;
return fs.file(
fs.path.join(
artifacts.getArtifactPath(
Artifact.engineDartSdkPath,
platform: TargetPlatform.web_javascript,
),
'lib',
'dev_compiler',
'ddc',
'ddc_module_loader.js',
),
);
}
@visibleForTesting
File get flutterJs {
final ToolContext(:Artifacts artifacts, :FileSystem fs) = _toolContext;
return fs.file(
fs.path.join(artifacts.getHostArtifact(HostArtifact.flutterJsDirectory).path, 'flutter.js'),
);
}
@visibleForTesting
File get stackTraceMapper {
final ToolContext(:Artifacts artifacts, :FileSystem fs) = _toolContext;
return fs.file(
fs.path.join(
artifacts.getArtifactPath(
Artifact.engineDartSdkPath,
platform: TargetPlatform.web_javascript,
),
'lib',
'dev_compiler',
'web',
'dart_stack_trace_mapper.js',
),
);
}
@override
void resetLastCompiled() {
// Not used for web compilation.
}
// Shaders are not supported during hot reload on the web yet.
// See https://github.com/flutter/flutter/issues/137265
@override
Set<String> get shaderPathsToEvict => _shaderPathsToEvict;
}