55import 'dart:async' ;
66import 'dart:isolate' ;
77
8- import 'package:flutter_tools_core/flutter_tools_core.dart' ;
98import 'package:flutter_tools_extension/flutter_tools_extension.dart' ;
109import 'package:json_rpc_2/json_rpc_2.dart' as json_rpc;
1110import 'package:stream_channel/isolate_channel.dart' ;
@@ -15,26 +14,45 @@ import '../base/logger.dart';
1514/// Typedef for an extension isolate entrypoint function.
1615typedef ExtensionEntryPoint = void Function (SendPort sendPort);
1716
18- /// Callback signature invoked when an extension reports progress for a
19- /// long-running request.
20- typedef ExtensionProgressCallback = void Function (String ? message, double ? progress);
21-
2217/// Represents an active host-side connection to a running tool extension isolate.
2318class ExtensionConnection {
2419 ExtensionConnection ._({
25- required Isolate this ._isolate,
26- required this ._peer,
2720 required this .capabilities,
2821 required this .extensionName,
22+ required this ._errorPort,
23+ required this ._exitPort,
24+ required Isolate this ._isolate,
2925 required this ._logger,
30- });
26+ required this ._peer,
27+ required this ._receivePort,
28+ }) {
29+ _errorPort.handler = (Object ? error) {
30+ if (_isDisposed) {
31+ return ;
32+ }
33+ final Object ? message = error is List && error.isNotEmpty ? error[0 ] : error;
34+ _logger.printTrace ('Extension isolate "$extensionName " unhandled error: $message ' );
35+ _receivePort.close ();
36+ };
37+
38+ _exitPort.handler = (Object ? _) {
39+ if (_isDisposed) {
40+ return ;
41+ }
42+ _logger.printTrace ('Extension isolate "$extensionName " exited unexpectedly.' );
43+ _receivePort.close ();
44+ };
45+ }
3146
3247 /// Fallback extension name used when an extension does not report one in its capabilities.
3348 static const defaultExtensionName = 'unknown_extension' ;
3449
3550 Isolate ? _isolate;
36- final json_rpc.Peer _peer;
51+ final RawReceivePort _errorPort;
52+ final RawReceivePort _exitPort;
3753 final Logger _logger;
54+ final json_rpc.Peer _peer;
55+ final ReceivePort _receivePort;
3856 final _notificationControllers = < String , StreamController <Map <String , Object ?>>> {};
3957
4058 /// The capabilities and supported service namespaces of the extension.
@@ -60,9 +78,9 @@ class ExtensionConnection {
6078 return ;
6179 }
6280 final Object ? rawValue = params.value;
63- final Map <String , Object ?> payload = rawValue is Map
64- ? rawValue. cast < String , Object ?>()
65- : < String , Object ? > {} ;
81+ final Map <String , Object ?> payload = rawValue is Map < String , Object ?>
82+ ? rawValue
83+ : (rawValue is Map ? rawValue. cast <String , Object ?>() : const < String , Object ? > {}) ;
6684 newController.add (payload);
6785 });
6886 return newController;
@@ -71,147 +89,6 @@ class ExtensionConnection {
7189 return controller.stream;
7290 }
7391
74- /// Sends a cooperative cancellation notification to the extension isolate for
75- /// the in-flight request identified by [requestId] .
76- void cancelRequest (Object requestId) {
77- if (_isDisposed) {
78- return ;
79- }
80- _logger.printTrace ('ExtensionConnection sending cancelRequest for "$requestId "...' );
81- _peer.sendNotification (ToolExtensionService .cancelRequestNotificationMethod, < String , Object ? > {
82- ToolExtensionService .requestIdKey: requestId,
83- });
84- }
85-
86- /// Sends a long-running RPC request to the extension isolate with a sliding
87- /// [inactivityTimeout] that resets whenever a
88- /// [ToolExtensionService.progressNotificationMethod] or
89- /// [ToolExtensionService.heartbeatNotificationMethod] notification is received.
90- ///
91- /// If [onProgress] is provided, it is invoked with the optional status
92- /// `message` and `progress` value (`0.0` to `1.0` ) from each
93- /// [ToolExtensionService.progressNotificationMethod] notification.
94- ///
95- /// If no progress or heartbeat notification arrives within
96- /// [inactivityTimeout] , sends a cooperative
97- /// [ToolExtensionService.cancelRequestNotificationMethod] notification via
98- /// [cancelRequest] and completes with a [TimeoutException] .
99- Future <Object ?> sendLongRunningRequest (
100- String method, {
101- Duration inactivityTimeout = const Duration (minutes: 2 ),
102- ExtensionProgressCallback ? onProgress,
103- Map <String , Object ?>? params,
104- }) async {
105- if (_isDisposed) {
106- throw StateError ('ExtensionConnection has been disposed.' );
107- }
108- _logger.printTrace (
109- 'ExtensionConnection sending long-running RPC request "$method " '
110- '(inactivityTimeout: ${inactivityTimeout .inSeconds }s)...' ,
111- );
112-
113- final Object ? explicitRequestId = params? [ToolExtensionService .requestIdKey];
114- final Object requestId = explicitRequestId ?? method;
115- final completer = Completer <Object ?>();
116- Timer ? inactivityTimer;
117-
118- void resetInactivityTimer () {
119- inactivityTimer? .cancel ();
120- if (completer.isCompleted) {
121- return ;
122- }
123- inactivityTimer = Timer (inactivityTimeout, () {
124- if (! completer.isCompleted) {
125- _logger.printTrace (
126- 'ExtensionConnection RPC request "$method " timed out after '
127- '${inactivityTimeout .inSeconds } seconds of inactivity; cancelling "$requestId ".' ,
128- );
129- cancelRequest (requestId);
130- completer.completeError (
131- TimeoutException (
132- 'Request "$method " timed out after ${inactivityTimeout .inSeconds } seconds of inactivity.' ,
133- inactivityTimeout,
134- ),
135- );
136- }
137- });
138- }
139-
140- bool matchesRequest (Map <String , Object ?> notificationParams) {
141- if (explicitRequestId == null ) {
142- return true ;
143- }
144- final Object ? notificationRequestId = notificationParams[ToolExtensionService .requestIdKey];
145- return notificationRequestId == null ||
146- notificationRequestId == explicitRequestId ||
147- notificationRequestId == method;
148- }
149-
150- final StreamSubscription <Map <String , Object ?>> progressSubscription =
151- onNotification (ToolExtensionService .progressNotificationMethod)
152- .listen ((Map <String , Object ?> notificationParams) {
153- if (! matchesRequest (notificationParams)) {
154- return ;
155- }
156- resetInactivityTimer ();
157- if (onProgress != null ) {
158- try {
159- final String ? message = notificationParams.nullableField <String >(
160- ToolExtensionService .messageKey,
161- );
162- final double ? progress = notificationParams
163- .nullableField <num >(ToolExtensionService .progressKey)
164- ? .toDouble ();
165- onProgress (message, progress);
166- } on FormatException catch (error) {
167- _logger.printTrace ('Ignoring malformed progress notification: $error ' );
168- }
169- }
170- });
171-
172- final StreamSubscription <Map <String , Object ?>> heartbeatSubscription =
173- onNotification (ToolExtensionService .heartbeatNotificationMethod)
174- .listen ((Map <String , Object ?> notificationParams) {
175- if (! matchesRequest (notificationParams)) {
176- return ;
177- }
178- resetInactivityTimer ();
179- });
180-
181- resetInactivityTimer ();
182-
183- unawaited (
184- _peer
185- .sendRequest (method, params)
186- .then <void >(
187- (Object ? result) {
188- if (! completer.isCompleted) {
189- _logger.printTrace (
190- 'ExtensionConnection received response for long-running RPC request "$method ".' ,
191- );
192- completer.complete (result);
193- }
194- },
195- onError: (Object error, StackTrace stackTrace) {
196- if (! completer.isCompleted) {
197- _logger.printTrace (
198- 'ExtensionConnection long-running RPC request "$method " failed with error: $error ' ,
199- );
200- completer.completeError (error, stackTrace);
201- }
202- },
203- ),
204- );
205-
206- try {
207- return await completer.future;
208- } finally {
209- inactivityTimer? .cancel ();
210- await progressSubscription.cancel ();
211- await heartbeatSubscription.cancel ();
212- }
213- }
214-
21592 /// Sends an RPC request to the extension isolate.
21693 Future <Object ?> sendRequest (
21794 String method, {
@@ -294,25 +171,29 @@ class ExtensionConnection {
294171 );
295172
296173 return ExtensionConnection ._(
297- isolate: isolate,
298- peer: peer,
299174 capabilities: capabilities,
300175 extensionName: capabilities.extensionName ?? defaultExtensionName,
176+ errorPort: errorPort,
177+ exitPort: exitPort,
178+ isolate: isolate,
301179 logger: logger,
180+ peer: peer,
181+ receivePort: receivePort,
302182 );
303183 } on TimeoutException {
304184 logger.printTrace ('ExtensionConnection handshake timed out.' );
305185 receivePort.close ();
186+ errorPort.close ();
187+ exitPort.close ();
306188 isolate? .kill (priority: Isolate .immediate);
307189 throw TimeoutException ('Handshake with tool extension isolate timed out.' );
308190 } on Object catch (error) {
309191 logger.printTrace ('ExtensionConnection spawn failed with error: $error ' );
310192 receivePort.close ();
311- isolate? .kill (priority: Isolate .immediate);
312- rethrow ;
313- } finally {
314193 errorPort.close ();
315194 exitPort.close ();
195+ isolate? .kill (priority: Isolate .immediate);
196+ rethrow ;
316197 }
317198 }
318199
@@ -323,6 +204,9 @@ class ExtensionConnection {
323204 }
324205 _isDisposed = true ;
325206 _logger.printTrace ('ExtensionConnection disposing isolate connection.' );
207+ _errorPort.close ();
208+ _exitPort.close ();
209+ _receivePort.close ();
326210 for (final StreamController <Map <String , Object ?>> controller
327211 in _notificationControllers.values) {
328212 await controller.close ();
@@ -344,7 +228,7 @@ class ExtensionDiscovery {
344228 /// Creates an [ExtensionDiscovery] instance with required [_logger] .
345229 ExtensionDiscovery ({required this ._logger});
346230
347- final List < ExtensionConnection > _connections = < ExtensionConnection > [];
231+ final _connections = < ExtensionConnection > [];
348232 final Logger _logger;
349233
350234 /// Active extension connections.
0 commit comments