diff --git a/packages/devtools_app/lib/src/extensions/extension_service.dart b/packages/devtools_app/lib/src/extensions/extension_service.dart index 2ba343c34cd..6e153a4cb6d 100644 --- a/packages/devtools_app/lib/src/extensions/extension_service.dart +++ b/packages/devtools_app/lib/src/extensions/extension_service.dart @@ -34,22 +34,21 @@ typedef DevToolsExtensionsGroup = ({ class ExtensionService extends DisposableController with AutoDisposeControllerMixin { - ExtensionService({this.fixedAppRoot, this.ignoreServiceConnection = false}); - - /// The fixed (unchanging) root file:// URI for the application this - /// [ExtensionService] will manage DevTools extensions for. + /// Detects runtime and static DevTools extensions. /// - /// When null, [_appRoot] will be calculated from the - /// `serviceConnection.serviceManager`'s currently connected app. - final Uri? fixedAppRoot; + /// When [fixedVmServiceUri] is provided, runtime extensions are detected for + /// that VM service instead of listening to `serviceConnection.serviceManager`. + ExtensionService({String? fixedVmServiceUri}) + : _fixedVmServiceUri = fixedVmServiceUri, + _useGlobalServiceConnection = fixedVmServiceUri == null; - /// Whether to ignore the VM service connection for the context of this - /// service. - final bool ignoreServiceConnection; + /// Detects static DevTools extensions for the IDE workspace only. + ExtensionService.forWorkspace() + : _fixedVmServiceUri = null, + _useGlobalServiceConnection = false; - /// The root file:// URI for the Dart / Flutter application this - /// [ExtensionService] will manage DevTools extensions for. - Uri? _appRoot; + final String? _fixedVmServiceUri; + final bool _useGlobalServiceConnection; /// A listenable for the current set of DevTools extensions. /// @@ -132,10 +131,7 @@ class ExtensionService extends DisposableController await _refresh(); cancelListeners(); - // We only need to add VM service manager related listeners when we are - // interacting with the currently connected app (i.e. when - // [fixedAppRootUri] is null). - if (fixedAppRoot == null && !ignoreServiceConnection) { + if (_useGlobalServiceConnection) { addAutoDisposeListener( serviceConnection.serviceManager.connectedState, () async { @@ -171,16 +167,12 @@ class ExtensionService extends DisposableController _log.fine('refreshing the ExtensionService'); _reset(); - _appRoot = null; - if (fixedAppRoot != null) { - _appRoot = fixedAppRoot; - } else if (!ignoreServiceConnection && - serviceConnection.serviceManager.connectedState.value.connected && - serviceConnection.serviceManager.isolateManager.mainIsolate.value != - null) { - _appRoot = await serviceConnection.serviceManager.connectedAppPackageRoot( - dtdManager, - ); + String? vmServiceUri; + if (_fixedVmServiceUri != null) { + vmServiceUri = _fixedVmServiceUri; + } else if (_useGlobalServiceConnection && + serviceConnection.serviceManager.connectedState.value.connected) { + vmServiceUri = serviceConnection.serviceManager.serviceUri; } // TODO(kenz): gracefully handle app connections / disconnects when there @@ -188,7 +180,9 @@ class ExtensionService extends DisposableController // when connection states change or hot restarts occur. _refreshInProgress.value = true; - final allExtensions = await server.refreshAvailableExtensions(_appRoot); + final allExtensions = await server.refreshAvailableExtensions( + vmServiceUri: vmServiceUri, + ); runtimeExtensions = allExtensions .where((e) => !e.detectedFromStaticContext) .toList(); @@ -336,7 +330,6 @@ class ExtensionService extends DisposableController void _reset() { _log.fine('resetting the ExtensionService'); - _appRoot = null; runtimeExtensions.clear(); staticExtensions.clear(); _ignoredStaticExtensionsByHashCode.clear(); diff --git a/packages/devtools_app/lib/src/shared/server/_extensions_api.dart b/packages/devtools_app/lib/src/shared/server/_extensions_api.dart index 290abeacd49..b8cc6b9265d 100644 --- a/packages/devtools_app/lib/src/shared/server/_extensions_api.dart +++ b/packages/devtools_app/lib/src/shared/server/_extensions_api.dart @@ -7,24 +7,19 @@ part of 'server.dart'; /// Makes a request to the server to refresh the list of available extensions, /// serve their assets on the server, and return the list of available /// extensions here. -Future> refreshAvailableExtensions( - // TODO(https://github.com/flutter/devtools/issues/7944): pass the URI to the - // package config file instead of passing the app root and rebulding the URI - // to the package config file. - Uri? appRoot, -) async { - _log.fine('refreshAvailableExtensions for app root: ${appRoot.toString()}'); +Future> refreshAvailableExtensions({ + String? vmServiceUri, +}) async { + _log.fine('refreshAvailableExtensions for vmServiceUri: $vmServiceUri'); if (debugDevToolsExtensions) { return debugHandleRefreshAvailableExtensions( - includeRuntime: appRoot != null, + includeRuntime: !vmServiceUri.isNullOrEmpty, ); } if (isDevToolsServerAvailable) { final uri = Uri( path: ExtensionsApi.apiServeAvailableExtensions, - queryParameters: { - ExtensionsApi.packageRootUriPropertyName: appRoot?.toString(), - }, + queryParameters: {ExtensionsApi.vmServiceUriPropertyName: vmServiceUri}, ); final resp = await request(uri.toString()); if (resp?.statusOk ?? false) { diff --git a/packages/devtools_app/lib/src/standalone_ui/vs_code/devtools/sidebar_extensions_controller.dart b/packages/devtools_app/lib/src/standalone_ui/vs_code/devtools/sidebar_extensions_controller.dart index 1dc6e7e63dd..b43cbf40498 100644 --- a/packages/devtools_app/lib/src/standalone_ui/vs_code/devtools/sidebar_extensions_controller.dart +++ b/packages/devtools_app/lib/src/standalone_ui/vs_code/devtools/sidebar_extensions_controller.dart @@ -133,17 +133,22 @@ class SidebarDevToolsExtensionsController extends DisposableController ); } - // Pass a null project root URI to initialize the set of extensions - // available for the entire workspace. - await _detectExtensions(null); + // Initialize extensions available for the entire workspace. + await _detectExtensions(); } Future _initExtensionsForDebugSessions() async { for (final debugSession in _debugSessions.values) { final fileUri = debugSession.projectRootFileUri; - if (fileUri != null && !_searchedProjectRoots.contains(fileUri)) { + final vmServiceUri = debugSession.vmServiceUri; + if (fileUri != null && + vmServiceUri != null && + !_searchedProjectRoots.contains(fileUri)) { _searchedProjectRoots.add(fileUri); - await _detectExtensions(fileUri); + await _detectExtensions( + projectRootUri: fileUri, + vmServiceUri: vmServiceUri, + ); } } } @@ -162,16 +167,19 @@ class SidebarDevToolsExtensionsController extends DisposableController // the workspace or for a debug session changes. We will likely need some // watch event from the IDE or analysis server to signal when any // package_config.json file in the workspace changes. - Future _detectExtensions(Uri? projectRootUri) async { - final extensionService = projectRootUri == null - ? - // A null [projectRootUri] indicates that this is an extensions lookup - // for the entire workspace, not a debug session with a fixed root URI. - ExtensionService(ignoreServiceConnection: true) - : ExtensionService( - fixedAppRoot: projectRootUri, - ignoreServiceConnection: true, - ); + Future _detectExtensions({ + Uri? projectRootUri, + String? vmServiceUri, + }) async { + assert( + (projectRootUri == null) == (vmServiceUri == null), + 'projectRootUri ($projectRootUri) and vmServiceUri ($vmServiceUri) ' + 'must either both be null (workspace lookup) or both be non-null ' + '(debug session lookup).', + ); + final extensionService = vmServiceUri == null + ? ExtensionService.forWorkspace() + : ExtensionService(fixedVmServiceUri: vmServiceUri); assert( !_extensionServiceByRootUri.containsKey(projectRootUri), 'The initialization for the ExtensionService for root uri ' diff --git a/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md b/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md index 1dfdcb637d3..9bf254debd6 100644 --- a/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md +++ b/packages/devtools_app/release_notes/NEXT_RELEASE_NOTES.md @@ -114,6 +114,10 @@ TODO: Remove this section if there are not any updates. * Validated DevTools extension version strings and prevented extension identifier collisions when serving extension assets. [#10090](https://github.com/flutter/devtools/pull/10090) +* Resolved the connected application's package root on the DevTools server via + the VM service URI when serving DevTools extensions instead of accepting a + package root file URI from the client. + [#10097](https://github.com/flutter/devtools/pull/10097) ## Advanced developer mode updates diff --git a/packages/devtools_app/test/extensions/extension_screen_test.dart b/packages/devtools_app/test/extensions/extension_screen_test.dart index 036c5985fa0..ec26155d7fa 100644 --- a/packages/devtools_app/test/extensions/extension_screen_test.dart +++ b/packages/devtools_app/test/extensions/extension_screen_test.dart @@ -36,9 +36,7 @@ void main() { setGlobal( ExtensionService, - ExtensionService( - fixedAppRoot: Uri.parse('file:///Users/me/package_root_1'), - ), + ExtensionService(fixedVmServiceUri: 'ws://127.0.0.1:8181/ws'), ); await extensionService.initialize(); expect(extensionService.staticExtensions.length, 4); diff --git a/packages/devtools_app/test/extensions/extension_service_test.dart b/packages/devtools_app/test/extensions/extension_service_test.dart index fea1cc26ace..28c04326f6d 100644 --- a/packages/devtools_app/test/extensions/extension_service_test.dart +++ b/packages/devtools_app/test/extensions/extension_service_test.dart @@ -34,9 +34,9 @@ void main() { resetDevToolsExtensionEnabledStates(); }); - test('initialize when connected', () async { + test('initialize with fixedVmServiceUri', () async { final service = ExtensionService( - fixedAppRoot: Uri.parse('file:///Users/me/package_root_1'), + fixedVmServiceUri: 'ws://127.0.0.1:8181/ws', ); expect(service.availableExtensions, isEmpty); expect(service.staticExtensions, isEmpty); @@ -61,12 +61,12 @@ void main() { expect(ignoredRuntimeExtensions.length, 0); }); - test('initialize with ignoreServiceConnection', () async { + test('initialize with forWorkspace', () async { when( mockServiceManager.connectedState, ).thenReturn(ValueNotifier(const ConnectedState(false))); - final service = ExtensionService(ignoreServiceConnection: true); + final service = ExtensionService.forWorkspace(); expect(service.staticExtensions, isEmpty); expect(service.runtimeExtensions, isEmpty); expect(service.availableExtensions, isEmpty); @@ -87,7 +87,7 @@ void main() { test('setExtensionEnabledState', () async { final service = ExtensionService( - fixedAppRoot: Uri.parse('file:///Users/me/package_root_1'), + fixedVmServiceUri: 'ws://127.0.0.1:8181/ws', ); await service.initialize(); expect(service.staticExtensions.length, 4); diff --git a/packages/devtools_app/test/extensions/extension_settings_test.dart b/packages/devtools_app/test/extensions/extension_settings_test.dart index 9e172184c88..0ed74c1b0b0 100644 --- a/packages/devtools_app/test/extensions/extension_settings_test.dart +++ b/packages/devtools_app/test/extensions/extension_settings_test.dart @@ -36,9 +36,7 @@ void main() { setGlobal( ExtensionService, - ExtensionService( - fixedAppRoot: Uri.parse('file:///Users/me/package_root_1'), - ), + ExtensionService(fixedVmServiceUri: 'ws://127.0.0.1:8181/ws'), ); await extensionService.initialize(); expect(extensionService.staticExtensions.length, 4); diff --git a/packages/devtools_app_shared/CHANGELOG.md b/packages/devtools_app_shared/CHANGELOG.md index ee3e1246427..f12fddc7fd5 100644 --- a/packages/devtools_app_shared/CHANGELOG.md +++ b/packages/devtools_app_shared/CHANGELOG.md @@ -19,6 +19,8 @@ found in the LICENSE file or at https://developers.google.com/open-source/licens such as the `file:` URI of a Dart CLI app started with `dart run`. Previously it was the scheme of the URI, such as `file:`, which is not a package. * Updates `devtools_shared` constraint to `^14.0.1`. +* Deprecate `ServiceManager.connectedAppPackageRoot` in favor of + `VmService.rootPackageDirectoryForMainIsolate` from `devtools_shared`. ## 0.5.1 * Add DevTools-styled text field `DevToolsTextField`. diff --git a/packages/devtools_app_shared/lib/src/service/service_manager.dart b/packages/devtools_app_shared/lib/src/service/service_manager.dart index da70413c75a..394647715ac 100644 --- a/packages/devtools_app_shared/lib/src/service/service_manager.dart +++ b/packages/devtools_app_shared/lib/src/service/service_manager.dart @@ -5,20 +5,16 @@ import 'dart:async'; import 'dart:core'; -import 'package:collection/collection.dart'; import 'package:dds_service_extensions/dds_service_extensions.dart'; import 'package:devtools_shared/devtools_shared.dart'; import 'package:flutter/foundation.dart'; import 'package:logging/logging.dart'; import 'package:meta/meta.dart'; -import 'package:path/path.dart' as path; import 'package:vm_service/vm_service.dart' hide Error; -import '../utils/auto_dispose.dart'; import '../utils/utils.dart'; import 'connected_app.dart'; import 'dtd_manager.dart'; -import 'eval_on_dart_library.dart' hide SentinelException; import 'flutter_version.dart'; import 'isolate_manager.dart'; import 'isolate_state.dart'; @@ -506,121 +502,19 @@ class ServiceManager { /// `flutter test`). This is because the main isolate for test targets is /// running the test runner, and not the test library itself, so we have to do /// some extra work to find the package root of the test target. + // TODO(johnpryan): remove this in the next breaking release. + @Deprecated( + 'Use VmService.rootPackageDirectoryForMainIsolate from devtools_shared instead.', + ) Future connectedAppPackageRoot(DTDManager dtdManager) async { - var packageRootUriString = await rootPackageDirectoryForMainIsolate( - dtdManager, - ); - _log.fine( - '[connectedAppPackageRoot] root package directory for main isolate: ' - '$packageRootUriString', - ); - - // If a Dart library URI was returned, this may be a test target (i.e. a - // VM service connection spawned from `dart test` or `flutter test`). - if (packageRootUriString?.endsWith('.dart') ?? false) { - final rootLibrary = await _mainIsolateRootLibrary(); - if (rootLibrary != null) { - packageRootUriString = - (await _lookupPackageRootByEval(rootLibrary)) ?? - // TODO(kenz): remove this fallback once all test bootstrap - // generators include the `packageConfigLocation` constant we - // can evaluate. - await _lookupPackageRootByImportPrefix(rootLibrary, dtdManager); - } - } - _log.fine( - '[connectedAppPackageRoot] package root for test target: ' - '$packageRootUriString', - ); + final packageRootUriString = await service + ?.rootPackageDirectoryForMainIsolate(dtd: dtdManager.connection.value); + _log.fine('[connectedAppPackageRoot] package root: $packageRootUriString'); return packageRootUriString == null ? null : Uri.parse(packageRootUriString); } - Future _lookupPackageRootByEval(Library rootLibrary) async { - final eval = EvalOnDartLibrary( - rootLibrary.uri!, - service! as VmService, - serviceManager: this, - // Swallow exceptions since this evaluation may be called on an older - // version of package:test where we do not expect the evaluation to - // succeed. - logExceptions: false, - ); - final evalDisposable = Disposable(); - try { - final packageConfig = (await eval.evalInstance( - 'packageConfigLocation', - isAlive: evalDisposable, - )).valueAsString; - - // TODO(https://github.com/flutter/devtools/issues/7944): return the - // unmodified package config location. For this case, be sure to handle - // invalid values like the empty String or 'null'. - final packageConfigIdentifier = path.join( - '.dart_tool', - 'package_config.json', - ); - if (packageConfig?.endsWith(packageConfigIdentifier) ?? false) { - _log.fine( - '[connectedAppPackageRoot] detected test package config from root ' - 'library eval: $packageConfig.', - ); - return packageConfig!.substring( - 0, - // Minus 1 to remove the trailing slash. - packageConfig.length - packageConfigIdentifier.length - 1, - ); - } - } catch (_) { - // Fail gracefully if the evaluation fails. - } finally { - evalDisposable.dispose(); - } - return null; - } - - Future _lookupPackageRootByImportPrefix( - Library rootLibrary, - DTDManager dtdManager, - ) async { - final testTargetFileUriString = - (rootLibrary.dependencies ?? []) - .firstWhereOrNull((dep) => dep.prefix == 'test') - ?.target - ?.uri; - if (testTargetFileUriString != null) { - _log.fine( - '[connectedAppPackageRoot] detected test library from root library ' - 'imports: $testTargetFileUriString', - ); - // TODO(https://github.com/flutter/devtools/issues/7944): return the - // unmodified package config location. - return await packageRootFromFileUriString( - testTargetFileUriString, - dtd: dtdManager.connection.value, - ); - } - return null; - } - - Future _mainIsolateRootLibrary() async { - final ref = - (await isolateManager.waitForMainIsolateState())?.isolateNow?.rootLib; - if (ref == null) return null; - try { - final library = await service!.getObject( - isolateManager.mainIsolate.value!.id!, - ref.id!, - ); - assert(library is Library); - return library as Library; - } on SentinelException catch (_) { - // Fail gracefully if the request to get the Library object fails. - return null; - } - } - // TODO(kenz): consider caching this value for the duration of the VM service // connection. /// Returns a file URI String for the root library of the connected app's main diff --git a/packages/devtools_app_shared/pubspec.yaml b/packages/devtools_app_shared/pubspec.yaml index 786defea6ca..5c6312247b4 100644 --- a/packages/devtools_app_shared/pubspec.yaml +++ b/packages/devtools_app_shared/pubspec.yaml @@ -22,7 +22,6 @@ dependencies: logging: ^1.1.1 material_ui: ^1.4.0 meta: ^1.9.1 - path: ^1.8.0 pointer_interceptor: ^0.10.1+1 url_launcher: ^6.1.0 vm_service: '>=13.0.0 <16.0.0' diff --git a/packages/devtools_shared/CHANGELOG.md b/packages/devtools_shared/CHANGELOG.md index 50bc259549b..383137873c1 100644 --- a/packages/devtools_shared/CHANGELOG.md +++ b/packages/devtools_shared/CHANGELOG.md @@ -35,6 +35,12 @@ found in the LICENSE file or at https://developers.google.com/open-source/licens recursive directory creation when looking up `devtools_options.yaml`. * Restrict `normalizeVmServiceUri` to allowed VM service schemes (`http`, `https`, `ws`, `wss`, `sse`, `sses`) and loopback hosts (`localhost`, `127.0.0.0/8`, `::1`). +* Add `ExtensionsApi.vmServiceUriPropertyName`, deprecate + `ExtensionsApi.packageRootUriPropertyName`, and resolve the connected + application's package root on the server from `vmServiceUri` in + `api/serveAvailableExtensions`. +* Add `VmServicePackageRootExtension.rootPackageDirectoryForMainIsolate` to + `devtools_shared.dart`. # 14.0.0 diff --git a/packages/devtools_shared/lib/src/devtools_api.dart b/packages/devtools_shared/lib/src/devtools_api.dart index c3d9a7e393f..f50595d077b 100644 --- a/packages/devtools_shared/lib/src/devtools_api.dart +++ b/packages/devtools_shared/lib/src/devtools_api.dart @@ -112,11 +112,18 @@ abstract class ExtensionsApi { static const apiServeAvailableExtensions = '${apiPrefix}serveAvailableExtensions'; + /// The property name for the query parameter passed along with + /// [apiServeAvailableExtensions] requests to the server that specifies the + /// VM service URI of the connected application whose runtime extensions are + /// being queried. + static const vmServiceUriPropertyName = 'vmServiceUri'; + /// The property name for the query parameter passed along with /// extension-related requests to the server that describes the package root /// for the app whose extensions are being queried. /// /// This field is a `file://` URI string and NOT a path. + @Deprecated('Use vmServiceUriPropertyName instead.') static const packageRootUriPropertyName = 'packageRootUri'; /// The property name for the query parameter, passed along with diff --git a/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart b/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart index af2b3f33957..39ffa3d839f 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_devtools_extensions.dart @@ -13,7 +13,7 @@ extension _ExtensionsApiHandler on Never { DtdInfo? dtd, ) async { final missingRequiredParams = ServerApi._checkRequiredParameters( - [ExtensionsApi.packageRootUriPropertyName], + const [ExtensionsApi.vmServiceUriPropertyName], queryParams: queryParams, api: api, requestName: ExtensionsApi.apiServeAvailableExtensions, @@ -21,31 +21,59 @@ extension _ExtensionsApiHandler on Never { if (missingRequiredParams != null) return missingRequiredParams; final logs = []; - final rootFileUriString = - queryParams[ExtensionsApi.packageRootUriPropertyName]; - if (rootFileUriString != null && rootFileUriString.isNotEmpty) { - final rootFileUri = Uri.tryParse(rootFileUriString); - if (!rootFileUriString.startsWith('file://') || - rootFileUri == null || - rootFileUri.scheme != 'file' || - rootFileUri.host.isNotEmpty) { + final warnings = []; + final vmServiceUriString = + queryParams[ExtensionsApi.vmServiceUriPropertyName]; + String? rootFileUriString; + if (vmServiceUriString != null && vmServiceUriString.isNotEmpty) { + final vmServiceUri = normalizeVmServiceUri(vmServiceUriString); + if (vmServiceUri == null) { return api.badRequest( - 'Invalid ${ExtensionsApi.packageRootUriPropertyName}: must be a ' - 'file:// URI with an empty host.', + 'Cannot normalize VM service URI: $vmServiceUriString', ); } + + DartToolingDaemon? dartToolingDaemon; + try { + final dtdUri = dtd?.localUri; + if (dtdUri != null) { + dartToolingDaemon = await DartToolingDaemon.connect(dtdUri); + } + final detectRootResponse = + await VmServiceHandler.detectRootPackageForVmService( + vmServiceUriAsString: vmServiceUriString, + vmServiceUri: vmServiceUri, + connected: true, + dtd: dartToolingDaemon, + ); + if (!detectRootResponse.success) { + warnings.add( + detectRootResponse.message ?? + 'Failed to detect root package for VM service ' + '($vmServiceUriString).', + ); + } else { + rootFileUriString = detectRootResponse.uri?.toString(); + } + } catch (e) { + warnings.add('$e'); + } finally { + await dartToolingDaemon?.close(); + } } + final rootDetectionFailed = warnings.isNotEmpty; final result = {}; /// Helper to return a success response with all available extensions /// detected by [extensionsManager]. - shelf.Response succeedWithAvailableExtensions({String? warning}) { + shelf.Response succeedWithAvailableExtensions() { final extensions = extensionsManager.devtoolsExtensions .map((p) => p.toJson()) .toList(); result[ExtensionsApi.extensionsResultPropertyName] = extensions; - if (warning != null) { - result[ExtensionsApi.extensionsResultWarningPropertyName] = warning; + if (warnings.isNotEmpty) { + result[ExtensionsApi.extensionsResultWarningPropertyName] = warnings + .join('\n'); } return ServerApi._encodeResponse( ServerApi._wrapWithLogs(result, logs), @@ -62,14 +90,19 @@ extension _ExtensionsApiHandler on Never { } on ExtensionParsingException catch (e) { // For [ExtensionParsingException]s, we should return a success response // with a warning message. - result[ExtensionsApi.extensionsResultWarningPropertyName] = e.message; + warnings.add(e.message); } catch (e) { + warnings.add('$e'); // If any extensions were successfully detected, return a success response // with a warning. if (extensionsManager.devtoolsExtensions.isNotEmpty) { - return succeedWithAvailableExtensions(warning: '$e'); + return succeedWithAvailableExtensions(); } - return api.serverError('$e', logs); + return api.serverError(warnings.join('\n'), logs); + } + + if (rootDetectionFailed && extensionsManager.devtoolsExtensions.isEmpty) { + return api.serverError(warnings.join('\n'), logs); } return succeedWithAvailableExtensions(); diff --git a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart index 94fd867e199..1c767c5a3d2 100644 --- a/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart +++ b/packages/devtools_shared/lib/src/server/handlers/_vm_service.dart @@ -18,6 +18,30 @@ extension VmServiceHandler on Never { /// never be used. static final _packageRootsForVmServiceConnections = {}; + /// Caches [rootPackageUri] for [vmServiceUriAsString] in tests. + @visibleForTesting + static void setPackageRootForVmServiceForTesting( + String vmServiceUriAsString, + Uri rootPackageUri, + ) { + final normalizedUri = normalizeVmServiceUri(vmServiceUriAsString); + if (normalizedUri == null) { + throw ArgumentError.value( + vmServiceUriAsString, + 'vmServiceUriAsString', + 'Cannot normalize VM service URI', + ); + } + _packageRootsForVmServiceConnections[normalizedUri.toString()] = + rootPackageUri; + } + + /// Clears cached package roots between tests. + @visibleForTesting + static void clearPackageRootsForTesting() { + _packageRootsForVmServiceConnections.clear(); + } + static Future handleNotifyForVmServiceConnection( ServerApi api, Map queryParams, @@ -110,13 +134,16 @@ extension VmServiceHandler on Never { required String vmServiceUriAsString, required Uri vmServiceUri, required bool connected, - required DartToolingDaemon dtd, + required DartToolingDaemon? dtd, }) async { + final normalizedUriAsString = vmServiceUri.toString(); final Uri rootPackageUri; if (connected) { - // TODO(kenz): should we first try to lookup the root from - // [_packageRootsForVmServiceConnections]? Could the root library of the - // main isolate change during the lifetime of a VM service instance? + final cachedRoot = + _packageRootsForVmServiceConnections[normalizedUriAsString]; + if (cachedRoot != null) { + return (success: true, message: null, uri: cachedRoot); + } VmService? vmService; try { @@ -126,7 +153,9 @@ extension VmServiceHandler on Never { serviceFactory: VmService.defaultFactory, ); - final root = await vmService.rootPackageDirectoryForMainIsolate(dtd); + final root = await vmService.rootPackageDirectoryForMainIsolate( + dtd: dtd, + ); if (root == null) { return ( success: false, @@ -137,7 +166,7 @@ extension VmServiceHandler on Never { ); } rootPackageUri = Uri.parse(root); - _packageRootsForVmServiceConnections[vmServiceUriAsString] = + _packageRootsForVmServiceConnections[normalizedUriAsString] = rootPackageUri; } catch (e) { return ( @@ -150,8 +179,8 @@ extension VmServiceHandler on Never { vmService = null; } } else { - final cachedRootForVmService = - _packageRootsForVmServiceConnections[vmServiceUriAsString]; + final cachedRootForVmService = _packageRootsForVmServiceConnections + .remove(normalizedUriAsString); if (cachedRootForVmService == null) { // If there is no root to remove, there is nothing for us to do. return (success: true, message: null, uri: null); @@ -181,61 +210,5 @@ extension VmServiceHandler on Never { } } -extension on VmService { - Future rootPackageDirectoryForMainIsolate( - DartToolingDaemon dtd, - ) async { - final fileUriString = await _rootLibraryForMainIsolate; - return fileUriString != null - ? await packageRootFromFileUriString(fileUriString, dtd: dtd) - : null; - } - - Future get _rootLibraryForMainIsolate async { - final mainIsolate = await _detectMainIsolate; - final rootLib = mainIsolate.rootLib?.uri; - if (rootLib == null) return null; - - final fileUriAsString = (await lookupResolvedPackageUris(mainIsolate.id!, [ - rootLib, - ])).uris?.first; - return fileUriAsString; - } - - /// Uses heuristics to detect the main isolate. - /// - /// Assumes an isolate is the main isolate if it meets any of the criteria in - /// the following order: - /// - /// 1. The isolate is the main Flutter isolate. - /// 2. The isolate has ':main(' in its name. - /// 3. The isolate is the first in the list of isolates on the VM. - Future get _detectMainIsolate async { - final isolateRefs = (await getVM()).isolates!; - final isolateCandidates = await isolateRefs - .map((ref) async => (ref: ref, isolate: await getIsolate(ref.id!))) - .wait; - - Isolate? mainIsolate; - for (final isolate in isolateCandidates) { - final isFlutterIsolate = (isolate.isolate.extensionRPCs ?? []).any( - (ext) => ext.startsWith('ext.flutter'), - ); - if (isFlutterIsolate) { - mainIsolate = isolate.isolate; - break; - } - } - mainIsolate ??= isolateCandidates - .firstWhereOrNull((isolate) => isolate.ref.name!.contains(':main(')) - ?.isolate; - - // Fallback to selecting the first isolate in the list. - mainIsolate ??= isolateCandidates.first.isolate; - - return mainIsolate; - } -} - @visibleForTesting typedef DetectRootPackageResponse = ({bool success, String? message, Uri? uri}); diff --git a/packages/devtools_shared/lib/src/server/server_api.dart b/packages/devtools_shared/lib/src/server/server_api.dart index f284d7f281f..854eb5bb9cd 100644 --- a/packages/devtools_shared/lib/src/server/server_api.dart +++ b/packages/devtools_shared/lib/src/server/server_api.dart @@ -23,7 +23,6 @@ import '../extensions/extension_enablement.dart'; import '../extensions/extension_manager.dart'; import '../service/service.dart'; import '../service_utils.dart'; -import '../utils/file_utils.dart'; import 'devtools_store.dart'; import 'file_system.dart'; import 'flutter_store.dart'; diff --git a/packages/devtools_shared/lib/src/service/service.dart b/packages/devtools_shared/lib/src/service/service.dart index 00fadb001e5..c290eaeb69e 100644 --- a/packages/devtools_shared/lib/src/service/service.dart +++ b/packages/devtools_shared/lib/src/service/service.dart @@ -55,6 +55,7 @@ Future _connectWithWebSocket({ // the VM service. uri = convertToWebSocketUrl(serviceProtocolUrl: uri); final ws = WebSocketChannel.connect(uri); + await ws.ready; final stream = ws.stream.handleError(onError); final service = serviceFactory( inStream: stream, diff --git a/packages/devtools_shared/lib/src/service_utils.dart b/packages/devtools_shared/lib/src/service_utils.dart index 83ddbc1e2af..fab729680a1 100644 --- a/packages/devtools_shared/lib/src/service_utils.dart +++ b/packages/devtools_shared/lib/src/service_utils.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd. +import 'package:collection/collection.dart'; +import 'package:dtd/dtd.dart'; +import 'package:path/path.dart' as p; +import 'package:vm_service/vm_service.dart'; + +import 'utils/file_utils.dart'; + class RegisteredService { const RegisteredService({required this.service, required this.title}); @@ -85,3 +92,138 @@ Uri? normalizeVmServiceUri(String value) { if (uri.path.endsWith('/')) return uri; return uri.replace(path: uri.path); } + +/// Extension methods on [VmService] for detecting the package root directory of +/// the connected application. +extension VmServicePackageRootExtension on VmService { + /// Returns the package root directory file URI string for the main isolate, + /// or `null` if it cannot be determined. + /// + /// This should be the directory up the tree from the debugging target that + /// contains the `.dart_tool/package_config.json` file. + /// + /// This method contains special logic for detecting the package root for + /// test targets (i.e., a VM service connection spawned from `dart test` or + /// `flutter test`). This is because the main isolate for test targets is + /// running the test runner, and not the test library itself, so extra work + /// is needed to find the package root of the test target. + Future rootPackageDirectoryForMainIsolate({ + DartToolingDaemon? dtd, + }) async { + final mainIsolate = await _detectMainIsolate; + final rootLib = mainIsolate?.rootLib; + final rootLibUri = rootLib?.uri; + if (mainIsolate == null || rootLibUri == null) return null; + + final fileUriString = (await lookupResolvedPackageUris(mainIsolate.id!, [ + rootLibUri, + ])).uris?.first; + if (fileUriString == null) return null; + + var packageRootUriString = await packageRootFromFileUriString( + fileUriString, + dtd: dtd, + ); + + // If a Dart library URI was returned, this may be a test target (i.e. a + // VM service connection spawned from `dart test` or `flutter test`). + if (packageRootUriString.endsWith('.dart') && rootLib?.id != null) { + packageRootUriString = + (await _lookupTestTargetPackageRoot( + isolateId: mainIsolate.id!, + rootLibraryId: rootLib!.id!, + dtd: dtd, + )) ?? + packageRootUriString; + } + + return packageRootUriString; + } + + Future _lookupTestTargetPackageRoot({ + required String isolateId, + required String rootLibraryId, + required DartToolingDaemon? dtd, + }) async { + try { + final obj = await getObject(isolateId, rootLibraryId); + if (obj is! Library) return null; + + try { + final evalResult = await evaluate( + isolateId, + rootLibraryId, + 'packageConfigLocation', + ); + if (evalResult is InstanceRef) { + final packageConfig = evalResult.valueAsString; + final packageConfigSuffix = p.posix.join( + '.dart_tool', + 'package_config.json', + ); + if (packageConfig != null && + packageConfig.endsWith(packageConfigSuffix)) { + return p.posix.dirname(p.posix.dirname(packageConfig)); + } + } + } catch (_) { + // Older versions of package:test don't define `packageConfigLocation`; + // fall back to checking the `test` import prefix below. + } + + final testTargetUri = (obj.dependencies ?? []) + .firstWhereOrNull((dep) => dep.prefix == 'test') + ?.target + ?.uri; + if (testTargetUri != null) { + final resolvedTargetUri = (await lookupResolvedPackageUris(isolateId, [ + testTargetUri, + ])).uris?.first; + if (resolvedTargetUri != null) { + return await packageRootFromFileUriString( + resolvedTargetUri, + dtd: dtd, + ); + } + } + } catch (_) { + // Ignore errors; the caller will fall back to the root library URI. + } + return null; + } + + /// Uses heuristics to detect the main isolate. + /// + /// Assumes an isolate is the main isolate if it meets any of the criteria in + /// the following order: + /// + /// 1. The isolate is the main Flutter isolate. + /// 2. The isolate has ':main(' in its name. + /// 3. The isolate is the first in the list of isolates on the VM. + Future get _detectMainIsolate async { + final isolateRefs = (await getVM()).isolates; + if (isolateRefs == null || isolateRefs.isEmpty) return null; + final isolateCandidates = await isolateRefs + .map((ref) async => (ref: ref, isolate: await getIsolate(ref.id!))) + .wait; + + Isolate? mainIsolate; + for (final isolate in isolateCandidates) { + final isFlutterIsolate = (isolate.isolate.extensionRPCs ?? []).any( + (ext) => ext.startsWith('ext.flutter'), + ); + if (isFlutterIsolate) { + mainIsolate = isolate.isolate; + break; + } + } + mainIsolate ??= isolateCandidates + .firstWhereOrNull((isolate) => isolate.ref.name!.contains(':main(')) + ?.isolate; + + // Fallback to selecting the first isolate in the list. + mainIsolate ??= isolateCandidates.first.isolate; + + return mainIsolate; + } +} diff --git a/packages/devtools_shared/test/server/devtools_extensions_api_test.dart b/packages/devtools_shared/test/server/devtools_extensions_api_test.dart index 044d88620bd..d50505effc2 100644 --- a/packages/devtools_shared/test/server/devtools_extensions_api_test.dart +++ b/packages/devtools_shared/test/server/devtools_extensions_api_test.dart @@ -33,7 +33,10 @@ void main() { testDtdConnection = await DartToolingDaemon.connect(dtd!.info!.localUri); }); + const fakeRuntimeVmServiceUri = 'ws://127.0.0.1:8181/fake-runtime-app=/ws'; + tearDown(() async { + VmServiceHandler.clearPackageRootsForTesting(); await testDtdConnection?.close(); dtd?.process?.kill(); await dtd?.process?.exitCode; @@ -52,6 +55,10 @@ void main() { includeBadExtension: includeBadExtension, includeSpoofedExtension: includeSpoofedExtension, ); + VmServiceHandler.setPackageRootForVmServiceForTesting( + fakeRuntimeVmServiceUri, + Uri.parse(extensionTestManager.runtimeAppRoot), + ); await testDtdConnection!.setIDEWorkspaceRoots(dtd!.info!.secret!, [ extensionTestManager.packagesRootUri, ]); @@ -60,7 +67,7 @@ void main() { Future serveExtensions( ExtensionsManager manager, { bool includeRuntimeRoot = true, - String? packageRootUriOverride, + String? vmServiceUriOverride, }) async { final request = Request( 'post', @@ -69,9 +76,9 @@ void main() { host: 'localhost', path: ExtensionsApi.apiServeAvailableExtensions, queryParameters: { - ExtensionsApi.packageRootUriPropertyName: - packageRootUriOverride ?? - (includeRuntimeRoot ? extensionTestManager.runtimeAppRoot : null), + ExtensionsApi.vmServiceUriPropertyName: + vmServiceUriOverride ?? + (includeRuntimeRoot ? fakeRuntimeVmServiceUri : null), }, ), headers: const {devToolsRequestHeader: '1'}, @@ -180,18 +187,68 @@ void main() { }, ); + test('returns static extensions with a warning for an uncached unreachable ' + 'loopback vmServiceUri', () async { + await initializeTestDirectory(); + const unreachableVmServiceUri = 'ws://127.0.0.1:1/ws'; + final response = await serveExtensions( + extensionsManager, + vmServiceUriOverride: unreachableVmServiceUri, + ); + expect(response.statusCode, HttpStatus.ok); + _verifyAllExtensions(extensionsManager, includeRuntime: false); + + final parsedResponse = json.decode(await response.readAsString()) as Map; + final warning = + parsedResponse[ExtensionsApi.extensionsResultWarningPropertyName]; + expect( + warning, + contains('Error detecting project roots ($unreachableVmServiceUri)'), + ); + }); + + test('fails with server error for an uncached unreachable loopback ' + 'vmServiceUri when no static extensions exist', () async { + await initializeTestDirectory(includeDependenciesWithExtensions: false); + const unreachableVmServiceUri = 'ws://127.0.0.1:1/ws'; + final response = await serveExtensions( + extensionsManager, + vmServiceUriOverride: unreachableVmServiceUri, + ); + expect(response.statusCode, HttpStatus.internalServerError); + expect(extensionsManager.devtoolsExtensions, isEmpty); + + final parsedResponse = json.decode(await response.readAsString()) as Map; + final error = parsedResponse['error']; + expect( + error, + contains('Error detecting project roots ($unreachableVmServiceUri)'), + ); + }); + test( - 'rejects packageRootUri with non-empty host (Windows UNC path)', + 'rejects non-loopback or invalid vmServiceUri and UNC packageRootUri', () async { await initializeTestDirectory(); - const uncUri = 'file://remotehost/share/app'; - final response = await serveExtensions( - extensionsManager, - packageRootUriOverride: uncUri, - ); - expect(response.statusCode, HttpStatus.badRequest); - expect(extensionsManager.devtoolsExtensions, isEmpty); + for (final invalidVmServiceUri in [ + 'file://remotehost/share/app', + 'file:///Users/me/app', + 'ws://evil.host:8181/ws', + 'not_a_uri', + ]) { + final response = await serveExtensions( + extensionsManager, + vmServiceUriOverride: invalidVmServiceUri, + ); + expect( + response.statusCode, + HttpStatus.badRequest, + reason: 'Expected $invalidVmServiceUri to be rejected', + ); + expect(extensionsManager.devtoolsExtensions, isEmpty); + } + const uncUri = 'file://remotehost/share/app'; await expectLater( extensionsManager.serveAvailableExtensions(uncUri, [], null), throwsArgumentError, diff --git a/packages/devtools_shared/test/server/general_api_test.dart b/packages/devtools_shared/test/server/general_api_test.dart index f0902307d63..43f5c23cc83 100644 --- a/packages/devtools_shared/test/server/general_api_test.dart +++ b/packages/devtools_shared/test/server/general_api_test.dart @@ -790,6 +790,21 @@ void main() { disconnectResponse.uri!.toFilePath(), endsWith(app!.directory.path), ); + + // Disconnecting again should be a no-op since the cache entry was + // already removed. + final secondDisconnectResponse = + await server.VmServiceHandler.detectRootPackageForVmService( + vmServiceUriAsString: vmServiceUriString!, + vmServiceUri: vmServiceUri, + connected: false, + dtd: testDtdConnection!, + ); + expect(secondDisconnectResponse, ( + success: true, + message: null, + uri: null, + )); }, ); });