|
| 1 | +// Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file |
| 2 | +// for details. All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +import 'dart:async'; |
| 6 | +import 'dart:convert'; |
| 7 | +import 'dart:io'; |
| 8 | + |
| 9 | +import 'package:http_multi_server/http_multi_server.dart'; |
| 10 | +import 'package:path/path.dart' as p; |
| 11 | +import 'package:shelf/shelf.dart' as shelf; |
| 12 | +import 'package:shelf/shelf_io.dart' as shelf_io; |
| 13 | +import 'package:shelf_packages_handler/shelf_packages_handler.dart'; |
| 14 | +import 'package:shelf_static/shelf_static.dart'; |
| 15 | +import 'package:shelf_web_socket/shelf_web_socket.dart'; |
| 16 | +import 'package:test_api/backend.dart' show StackTraceMapper, SuitePlatform; |
| 17 | +import 'package:test_core/src/runner/configuration.dart'; // ignore: implementation_imports |
| 18 | +import 'package:test_core/src/runner/dart2js_compiler_pool.dart'; // ignore: implementation_imports |
| 19 | +import 'package:test_core/src/runner/package_version.dart'; // ignore: implementation_imports |
| 20 | +import 'package:test_core/src/runner/suite.dart'; // ignore: implementation_imports |
| 21 | +import 'package:test_core/src/util/io.dart'; // ignore: implementation_imports |
| 22 | +import 'package:test_core/src/util/package_config.dart'; // ignore: implementation_imports |
| 23 | +import 'package:test_core/src/util/stack_trace_mapper.dart'; // ignore: implementation_imports |
| 24 | +import 'package:web_socket_channel/web_socket_channel.dart'; |
| 25 | + |
| 26 | +import '../../../util/math.dart'; |
| 27 | +import '../../../util/one_off_handler.dart'; |
| 28 | +import '../../../util/package_map.dart'; |
| 29 | +import '../../../util/path_handler.dart'; |
| 30 | +import 'compiler_support.dart'; |
| 31 | + |
| 32 | +/// Support for Dart2Js compiled tests. |
| 33 | +class Dart2JsSupport implements CompilerSupport { |
| 34 | + /// Whether [close] has been called. |
| 35 | + bool _closed = false; |
| 36 | + |
| 37 | + /// The temporary directory in which compiled JS is emitted. |
| 38 | + final _compiledDir = createTempDir(); |
| 39 | + |
| 40 | + /// A map from test suite paths to Futures that will complete once those |
| 41 | + /// suites are finished compiling. |
| 42 | + /// |
| 43 | + /// This is used to make sure that a given test suite is only compiled once |
| 44 | + /// per run, rather than once per browser per run. |
| 45 | + final _compileFutures = <String, Future<void>>{}; |
| 46 | + |
| 47 | + /// The [Dart2JsCompilerPool] managing active instances of `dart2js`. |
| 48 | + final _compilerPool = Dart2JsCompilerPool(); |
| 49 | + |
| 50 | + /// The global test runner configuration. |
| 51 | + final Configuration _config; |
| 52 | + |
| 53 | + /// The default template path. |
| 54 | + final String _defaultTemplatePath; |
| 55 | + |
| 56 | + /// Mappers for Dartifying stack traces, indexed by test path. |
| 57 | + final _mappers = <String, StackTraceMapper>{}; |
| 58 | + |
| 59 | + /// A [PathHandler] used to serve test specific artifacts. |
| 60 | + final _pathHandler = PathHandler(); |
| 61 | + |
| 62 | + /// The root directory served statically by this server. |
| 63 | + final String _root; |
| 64 | + |
| 65 | + /// Each compiler serves its tests under a different randomly-generated |
| 66 | + /// secret URI to ensure that other users on the same system can't snoop |
| 67 | + /// on data being served through this server, as well as distinguish tests |
| 68 | + /// from different compilers from each other. |
| 69 | + final String _secret = randomUrlSecret(); |
| 70 | + |
| 71 | + /// The underlying server. |
| 72 | + final shelf.Server _server; |
| 73 | + |
| 74 | + /// A [OneOffHandler] for servicing WebSocket connections for |
| 75 | + /// [BrowserManager]s. |
| 76 | + /// |
| 77 | + /// This is one-off because each [BrowserManager] can only connect to a single |
| 78 | + /// WebSocket. |
| 79 | + final _webSocketHandler = OneOffHandler(); |
| 80 | + |
| 81 | + @override |
| 82 | + Uri get serverUrl => _server.url.resolve('$_secret/'); |
| 83 | + |
| 84 | + Dart2JsSupport._(this._config, this._defaultTemplatePath, this._server, |
| 85 | + this._root, String faviconPath) { |
| 86 | + var cascade = shelf.Cascade() |
| 87 | + .add(_webSocketHandler.handler) |
| 88 | + .add(packagesDirHandler()) |
| 89 | + .add(_pathHandler.handler) |
| 90 | + .add(createStaticHandler(_root)) |
| 91 | + .add(_wrapperHandler); |
| 92 | + |
| 93 | + var pipeline = const shelf.Pipeline() |
| 94 | + .addMiddleware(PathHandler.nestedIn(_secret)) |
| 95 | + .addHandler(cascade.handler); |
| 96 | + |
| 97 | + _server.mount(shelf.Cascade() |
| 98 | + .add(createFileHandler(faviconPath)) |
| 99 | + .add(pipeline) |
| 100 | + .handler); |
| 101 | + } |
| 102 | + |
| 103 | + static Future<Dart2JsSupport> start({ |
| 104 | + required Configuration config, |
| 105 | + required String defaultTemplatePath, |
| 106 | + required String root, |
| 107 | + required String faviconPath, |
| 108 | + }) async { |
| 109 | + var server = shelf_io.IOServer(await HttpMultiServer.loopback(0)); |
| 110 | + return Dart2JsSupport._( |
| 111 | + config, defaultTemplatePath, server, root, faviconPath); |
| 112 | + } |
| 113 | + |
| 114 | + /// A handler that serves wrapper files used to bootstrap tests. |
| 115 | + shelf.Response _wrapperHandler(shelf.Request request) { |
| 116 | + var path = p.fromUri(request.url); |
| 117 | + |
| 118 | + if (path.endsWith('.html')) { |
| 119 | + var test = p.setExtension(path, '.dart'); |
| 120 | + var scriptBase = htmlEscape.convert(p.basename(test)); |
| 121 | + var link = '<link rel="x-dart-test" href="$scriptBase">'; |
| 122 | + var testName = htmlEscape.convert(test); |
| 123 | + var template = _config.customHtmlTemplatePath ?? _defaultTemplatePath; |
| 124 | + var contents = File(template).readAsStringSync(); |
| 125 | + var processedContents = contents |
| 126 | + // Checked during loading phase that there is only one {{testScript}} placeholder. |
| 127 | + .replaceFirst('{{testScript}}', link) |
| 128 | + .replaceAll('{{testName}}', testName); |
| 129 | + return shelf.Response.ok(processedContents, |
| 130 | + headers: {'Content-Type': 'text/html'}); |
| 131 | + } |
| 132 | + |
| 133 | + return shelf.Response.notFound('Not found.'); |
| 134 | + } |
| 135 | + |
| 136 | + @override |
| 137 | + Future<void> compileSuite( |
| 138 | + String dartPath, SuiteConfiguration suiteConfig, SuitePlatform platform) { |
| 139 | + return _compileFutures.putIfAbsent(dartPath, () async { |
| 140 | + var dir = Directory(_compiledDir).createTempSync('test_').path; |
| 141 | + var jsPath = p.join(dir, '${p.basename(dartPath)}.browser_test.dart.js'); |
| 142 | + var bootstrapContent = ''' |
| 143 | + ${suiteConfig.metadata.languageVersionComment ?? await rootPackageLanguageVersionComment} |
| 144 | + import "package:test/src/bootstrap/browser.dart"; |
| 145 | +
|
| 146 | + import "${p.toUri(p.absolute(dartPath))}" as test; |
| 147 | +
|
| 148 | + void main() { |
| 149 | + internalBootstrapBrowserTest(() => test.main); |
| 150 | + } |
| 151 | + '''; |
| 152 | + |
| 153 | + await _compilerPool.compile(bootstrapContent, jsPath, suiteConfig); |
| 154 | + if (_closed) return; |
| 155 | + |
| 156 | + var bootstrapUrl = '${p.toUri(p.relative(dartPath, from: _root)).path}' |
| 157 | + '.browser_test.dart'; |
| 158 | + _pathHandler.add(bootstrapUrl, (request) { |
| 159 | + return shelf.Response.ok(bootstrapContent, |
| 160 | + headers: {'Content-Type': 'application/dart'}); |
| 161 | + }); |
| 162 | + |
| 163 | + var jsUrl = '${p.toUri(p.relative(dartPath, from: _root)).path}' |
| 164 | + '.browser_test.dart.js'; |
| 165 | + _pathHandler.add(jsUrl, (request) { |
| 166 | + return shelf.Response.ok(File(jsPath).readAsStringSync(), |
| 167 | + headers: {'Content-Type': 'application/javascript'}); |
| 168 | + }); |
| 169 | + |
| 170 | + var mapUrl = '${p.toUri(p.relative(dartPath, from: _root)).path}' |
| 171 | + '.browser_test.dart.js.map'; |
| 172 | + _pathHandler.add(mapUrl, (request) { |
| 173 | + return shelf.Response.ok(File('$jsPath.map').readAsStringSync(), |
| 174 | + headers: {'Content-Type': 'application/json'}); |
| 175 | + }); |
| 176 | + |
| 177 | + if (suiteConfig.jsTrace) return; |
| 178 | + var mapPath = '$jsPath.map'; |
| 179 | + _mappers[dartPath] = JSStackTraceMapper(File(mapPath).readAsStringSync(), |
| 180 | + mapUrl: p.toUri(mapPath), |
| 181 | + sdkRoot: Uri.parse('org-dartlang-sdk:///sdk'), |
| 182 | + packageMap: (await currentPackageConfig).toPackageMap()); |
| 183 | + }); |
| 184 | + } |
| 185 | + |
| 186 | + @override |
| 187 | + Future<void> close() async { |
| 188 | + if (_closed) return; |
| 189 | + _closed = true; |
| 190 | + await Future.wait([ |
| 191 | + Directory(_compiledDir).deleteWithRetry(), |
| 192 | + _compilerPool.close(), |
| 193 | + _server.close(), |
| 194 | + ]); |
| 195 | + } |
| 196 | + |
| 197 | + @override |
| 198 | + StackTraceMapper? stackTraceMapperForPath(String dartPath) => |
| 199 | + _mappers[dartPath]; |
| 200 | + |
| 201 | + @override |
| 202 | + (Uri, Future<WebSocketChannel>) get webSocket { |
| 203 | + var completer = Completer<WebSocketChannel>.sync(); |
| 204 | + var path = _webSocketHandler.create(webSocketHandler(completer.complete)); |
| 205 | + var webSocketUrl = serverUrl.replace(scheme: 'ws').resolve(path); |
| 206 | + return (webSocketUrl, completer.future); |
| 207 | + } |
| 208 | +} |
0 commit comments