Skip to content

Commit 633db93

Browse files
authored
[flutter_tools] Add JSON-RPC notification support and post-handshake isolate exit handling to ExtensionConnection (flutter#194961)
Adds extension-to-host JSON-RPC notification support (`ToolExtensionService.sendNotification` and `ExtensionConnection.onNotification`, first consumed by device log streaming in flutter#194964) and keeps `onError`/`onExit` ports open after the handshake so unexpected isolate exits or unhandled errors immediately fail pending `sendRequest(..., timeout: null)` calls and close notification streams instead of hanging forever. Part of flutter#190755 Part of flutter#190746
1 parent 7cf3308 commit 633db93

4 files changed

Lines changed: 347 additions & 21 deletions

File tree

‎packages/flutter_tools/lib/src/experimental/extension_discovery.dart‎

Lines changed: 116 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -17,19 +17,33 @@ typedef ExtensionEntryPoint = void Function(SendPort sendPort);
1717
/// Represents an active host-side connection to a running tool extension isolate.
1818
class ExtensionConnection {
1919
ExtensionConnection._({
20-
required Isolate this._isolate,
21-
required this._peer,
2220
required this.capabilities,
2321
required this.extensionName,
22+
required this._errorPort,
23+
required this._exitPort,
24+
required Isolate this._isolate,
2425
required this._logger,
26+
required this._peer,
27+
required this._receivePort,
2528
});
2629

2730
/// Fallback extension name used when an extension does not report one in its capabilities.
2831
static const defaultExtensionName = 'unknown_extension';
2932

3033
Isolate? _isolate;
31-
final json_rpc.Peer _peer;
34+
35+
/// Port receiving uncaught async errors (`[String error, String? stackTrace]`)
36+
/// from the extension isolate.
37+
final ReceivePort _errorPort;
38+
39+
/// Port notified when the extension isolate terminates so the host can close
40+
/// [_receivePort] and fail any in-flight RPCs instead of hanging.
41+
final ReceivePort _exitPort;
42+
3243
final Logger _logger;
44+
final json_rpc.Peer _peer;
45+
final ReceivePort _receivePort;
46+
final _notificationControllers = <String, StreamController<Map<String, Object?>>>{};
3347

3448
/// The capabilities and supported service namespaces of the extension.
3549
final ToolExtensionCapabilities capabilities;
@@ -39,6 +53,64 @@ class ExtensionConnection {
3953

4054
bool _isDisposed = false;
4155

56+
/// Handles uncaught async errors from the extension isolate after handshake.
57+
///
58+
/// Per [Isolate.addErrorListener], `dart:isolate` delivers uncaught errors on
59+
/// the `onError` port as a two-element `List<Object?>` containing
60+
/// `[String errorDescription, String? stackTrace]`. Logging them here surfaces
61+
/// uncaught extension isolate errors that occur outside an active JSON-RPC
62+
/// request handler.
63+
void _handleIsolateError(Object? error) {
64+
if (error case [final Object? errorDescription, final Object? stackTrace]) {
65+
_logger.printError('Extension isolate "$extensionName" unhandled error: $errorDescription');
66+
if (stackTrace != null) {
67+
_logger.printTrace('$stackTrace');
68+
}
69+
} else {
70+
_logger.printError('Extension isolate "$extensionName" unhandled error: $error');
71+
}
72+
}
73+
74+
/// Handles unexpected extension isolate termination after handshake.
75+
///
76+
/// `IsolateChannel` (backed by a `ReceivePort`/`SendPort` pair) does not
77+
/// automatically close when the remote isolate exits. Closing [_receivePort]
78+
/// when the `onExit` port fires causes the JSON-RPC [json_rpc.Peer] to close
79+
/// immediately, failing any in-flight [sendRequest] calls (such as
80+
/// long-running `timeout: null` build requests) with a [StateError] and
81+
/// closing active notification streams instead of hanging indefinitely.
82+
void _handleIsolateExit() {
83+
_logger.printTrace('Extension isolate "$extensionName" exited unexpectedly.');
84+
unawaited(dispose());
85+
}
86+
87+
/// Returns a broadcast stream of JSON-RPC 2.0 notifications sent by the
88+
/// extension isolate for [method].
89+
Stream<Map<String, Object?>> onNotification(String method) {
90+
if (_isDisposed) {
91+
throw StateError('ExtensionConnection has been disposed.');
92+
}
93+
final StreamController<Map<String, Object?>>
94+
controller = _notificationControllers.putIfAbsent(method, () {
95+
final newController = StreamController<Map<String, Object?>>.broadcast();
96+
_peer.registerMethod(method, (json_rpc.Parameters params) {
97+
if (newController.isClosed) {
98+
return;
99+
}
100+
final Object? rawValue = params.value;
101+
if (rawValue is! Map<String, Object?>) {
102+
_logger.printWarning(
103+
'Extension "$extensionName" sent malformed notification for "$method": expected Map<String, Object?>.',
104+
);
105+
return;
106+
}
107+
newController.add(rawValue);
108+
});
109+
return newController;
110+
});
111+
return controller.stream;
112+
}
113+
42114
/// Sends an RPC request to the extension isolate.
43115
Future<Object?> sendRequest(
44116
String method, {
@@ -68,27 +140,38 @@ class ExtensionConnection {
68140
}) async {
69141
logger.printTrace('ExtensionConnection spawning extension isolate...');
70142
final receivePort = ReceivePort();
71-
final errorPort = RawReceivePort();
72-
final exitPort = RawReceivePort();
143+
final errorPort = ReceivePort();
144+
final exitPort = ReceivePort();
73145
final errorCompleter = Completer<Never>();
146+
ExtensionConnection? connection;
74147

75-
errorPort.handler = (Object? error) {
148+
// Isolate.spawn delivers uncaught isolate errors as a two-element list:
149+
// `[String errorDescription, String? stackTrace]`.
150+
errorPort.listen((Object? error) {
151+
if (connection case final ExtensionConnection activeConnection) {
152+
activeConnection._handleIsolateError(error);
153+
return;
154+
}
76155
if (!errorCompleter.isCompleted) {
77-
if (error is List && error.isNotEmpty) {
78-
errorCompleter.completeError(StateError('Extension isolate error: ${error[0]}'));
79-
} else {
80-
errorCompleter.completeError(StateError('Extension isolate error: $error'));
81-
}
156+
final Object? errorDescription = switch (error) {
157+
[final Object? description, _] => description,
158+
_ => error,
159+
};
160+
errorCompleter.completeError(StateError('Extension isolate error: $errorDescription'));
82161
}
83-
};
162+
});
84163

85-
exitPort.handler = (Object? _) {
164+
exitPort.listen((Object? _) {
165+
if (connection case final ExtensionConnection activeConnection) {
166+
activeConnection._handleIsolateExit();
167+
return;
168+
}
86169
if (!errorCompleter.isCompleted) {
87170
errorCompleter.completeError(
88171
StateError('Extension isolate exited unexpectedly before handshake completed.'),
89172
);
90173
}
91-
};
174+
});
92175

93176
Isolate? isolate;
94177

@@ -120,26 +203,30 @@ class ExtensionConnection {
120203
'ExtensionConnection handshake complete. Capabilities: ${capabilities.services}',
121204
);
122205

123-
return ExtensionConnection._(
124-
isolate: isolate,
125-
peer: peer,
206+
return connection = ExtensionConnection._(
126207
capabilities: capabilities,
127208
extensionName: capabilities.extensionName ?? defaultExtensionName,
209+
errorPort: errorPort,
210+
exitPort: exitPort,
211+
isolate: isolate,
128212
logger: logger,
213+
peer: peer,
214+
receivePort: receivePort,
129215
);
130216
} on TimeoutException {
131217
logger.printTrace('ExtensionConnection handshake timed out.');
132218
receivePort.close();
219+
errorPort.close();
220+
exitPort.close();
133221
isolate?.kill(priority: Isolate.immediate);
134222
throw TimeoutException('Handshake with tool extension isolate timed out.');
135223
} on Object catch (error) {
136224
logger.printTrace('ExtensionConnection spawn failed with error: $error');
137225
receivePort.close();
138-
isolate?.kill(priority: Isolate.immediate);
139-
rethrow;
140-
} finally {
141226
errorPort.close();
142227
exitPort.close();
228+
isolate?.kill(priority: Isolate.immediate);
229+
rethrow;
143230
}
144231
}
145232

@@ -150,6 +237,14 @@ class ExtensionConnection {
150237
}
151238
_isDisposed = true;
152239
_logger.printTrace('ExtensionConnection disposing isolate connection.');
240+
_errorPort.close();
241+
_exitPort.close();
242+
_receivePort.close();
243+
for (final StreamController<Map<String, Object?>> controller
244+
in _notificationControllers.values) {
245+
await controller.close();
246+
}
247+
_notificationControllers.clear();
153248
try {
154249
await _peer.close();
155250
} on Object catch (error) {
@@ -166,7 +261,7 @@ class ExtensionDiscovery {
166261
/// Creates an [ExtensionDiscovery] instance with required [_logger].
167262
ExtensionDiscovery({required this._logger});
168263

169-
final List<ExtensionConnection> _connections = <ExtensionConnection>[];
264+
final _connections = <ExtensionConnection>[];
170265
final Logger _logger;
171266

172267
/// Active extension connections.

‎packages/flutter_tools/packages/flutter_tools_extension/lib/src/protocol_base/provider.dart‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,10 @@ class ToolExtensionEntryPoint {
6363
final channel = IsolateChannel<Object?>.connectSend(sendPort);
6464
final peer = json_rpc.Peer.withoutJson(channel);
6565

66+
for (final service in services) {
67+
service.notificationSender = peer.sendNotification;
68+
}
69+
6670
peer.registerMethod(getCapabilitiesMethod, () {
6771
logger?.call('[ToolExtensionIsolate] Handling extension.getCapabilities query.');
6872
return capabilities.toMap();

‎packages/flutter_tools/packages/flutter_tools_extension/lib/src/protocol_base/service.dart‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,22 @@ import 'package:meta/meta.dart';
1010
/// Typedef for an extension RPC handler function.
1111
typedef ExtensionRpcHandler = FutureOr<Object?> Function(Map<String, Object?> params);
1212

13+
/// Callback signature for sending a JSON-RPC 2.0 notification from an extension
14+
/// service to the host tool.
15+
typedef ExtensionNotificationSender = void Function(String method, Map<String, Object?> params);
16+
1317
/// Represents a logical service exposed by a Flutter Tool Extension.
1418
///
1519
/// Extension authors implement this class to group related RPC endpoints under
1620
/// a specific [namespace] (e.g. `diagnostics`, `configuration`, `device`, `build`, `templates`).
1721
abstract class ToolExtensionService {
22+
/// Internal JSON-RPC notification sender callback used by [sendNotification].
23+
///
24+
/// Wired by `ToolExtensionEntryPoint.run` before the extension peer begins
25+
/// listening for RPC requests.
26+
@internal
27+
ExtensionNotificationSender? notificationSender;
28+
1829
/// The namespace string of the service (e.g. `'diagnostics'`).
1930
String get namespace;
2031

@@ -23,6 +34,21 @@ abstract class ToolExtensionService {
2334
/// The returned map maps method names (without namespace prefix) to handler functions.
2435
Future<Map<String, ExtensionRpcHandler>> initialize();
2536

37+
/// Sends a fire-and-forget JSON-RPC 2.0 notification with [method] and
38+
/// [params] to the host tool.
39+
///
40+
/// Throws a [StateError] if called before this service has been attached to
41+
/// an active extension peer by `ToolExtensionEntryPoint.run`.
42+
void sendNotification(String method, Map<String, Object?> params) {
43+
final ExtensionNotificationSender? sender = notificationSender;
44+
if (sender == null) {
45+
throw StateError(
46+
'Cannot send notification "$method": service "$namespace" is not attached to an active peer.',
47+
);
48+
}
49+
sender(method, params);
50+
}
51+
2652
/// Cleans up resources held by the service when the extension is shut down.
2753
Future<void> shutdown() async {}
2854
}

0 commit comments

Comments
 (0)