Skip to content

Commit ba60b91

Browse files
committed
[flutter_tools] Simplify extension protocol to JSON-RPC notifications and post-handshake isolate exit handling
Simplifies the extension protocol changes to focus on bidirectional JSON-RPC 2.0 notification support and resilient post-handshake isolate exit and error handling, removing request cancellation and heartbeat APIs. Part of flutter#190755 Part of flutter#190746
1 parent 87b0ede commit ba60b91

6 files changed

Lines changed: 158 additions & 511 deletions

File tree

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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,6 @@ base class ExtensionBuildManager {
9494
required String mainPath,
9595
required Uri projectRoot,
9696
required String targetName,
97-
Duration inactivityTimeout = const Duration(minutes: 2),
9897
}) async {
9998
if (!projectRoot.hasAbsolutePath) {
10099
throw ArgumentError.value(projectRoot, 'projectRoot', 'Must be an absolute path.');
@@ -129,15 +128,17 @@ base class ExtensionBuildManager {
129128
}
130129

131130
try {
132-
final Object? result = await connection.sendLongRunningRequest(
131+
final Object? result = await connection.sendRequest(
133132
BuildService.buildMethod,
134133
params: <String, Object?>{
135134
BuildService.buildModeParam: buildMode.cliName,
136135
BuildService.mainPathParam: mainPath,
137136
BuildService.projectRootParam: projectRoot.toString(),
138137
BuildService.targetNameParam: targetName,
139138
},
140-
inactivityTimeout: inactivityTimeout,
139+
// TODO(bkonyi): Support heartbeat / liveness monitoring for long-running RPCs,
140+
// https://github.com/flutter/flutter/issues/193955.
141+
timeout: null,
141142
);
142143
if (result case final Map<String, Object?> resultMap) {
143144
return ExtensionBuildResult.fromJson(resultMap);

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

Lines changed: 43 additions & 159 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import 'dart:async';
66
import 'dart:isolate';
77

8-
import 'package:flutter_tools_core/flutter_tools_core.dart';
98
import 'package:flutter_tools_extension/flutter_tools_extension.dart';
109
import 'package:json_rpc_2/json_rpc_2.dart' as json_rpc;
1110
import 'package:stream_channel/isolate_channel.dart';
@@ -15,26 +14,45 @@ import '../base/logger.dart';
1514
/// Typedef for an extension isolate entrypoint function.
1615
typedef 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.
2318
class 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.

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

Lines changed: 1 addition & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import 'dart:async';
66
import 'dart:isolate';
77

8-
import 'package:flutter_tools_core/flutter_tools_core.dart';
98
import 'package:json_rpc_2/json_rpc_2.dart' as json_rpc;
109
import 'package:stream_channel/isolate_channel.dart';
1110

@@ -20,13 +19,6 @@ class ToolExtensionEntryPoint {
2019
/// The reserved JSON-RPC method name used to query extension capabilities.
2120
static const String getCapabilitiesMethod = 'extension.getCapabilities';
2221

23-
static const _reservedMethods = <String>{
24-
getCapabilitiesMethod,
25-
ToolExtensionService.progressNotificationMethod,
26-
ToolExtensionService.heartbeatNotificationMethod,
27-
ToolExtensionService.cancelRequestNotificationMethod,
28-
};
29-
3022
/// Entrypoint function to serve [services] over the Isolate [sendPort].
3123
///
3224
/// If provided, [extensionName] should be the name of the extension package
@@ -48,7 +40,7 @@ class ToolExtensionEntryPoint {
4840
final Map<String, ExtensionRpcHandler> handlers = await service.initialize();
4941
handlers.forEach((String method, ExtensionRpcHandler handler) {
5042
final fullMethod = '${service.namespace}.$method';
51-
if (_reservedMethods.contains(fullMethod)) {
43+
if (fullMethod == getCapabilitiesMethod) {
5244
throw StateError('Reserved RPC method registered: "$fullMethod"');
5345
}
5446
if (rpcHandlers.containsKey(fullMethod)) {
@@ -80,25 +72,6 @@ class ToolExtensionEntryPoint {
8072
return capabilities.toMap();
8173
});
8274

83-
peer.registerMethod(ToolExtensionService.cancelRequestNotificationMethod, (
84-
json_rpc.Parameters params,
85-
) async {
86-
final Object? rawValue = params.value;
87-
final Map<String, Object?> paramMap = rawValue is Map
88-
? rawValue.cast<String, Object?>()
89-
: <String, Object?>{};
90-
final Object requestId;
91-
try {
92-
requestId = paramMap.requiredField<Object>(ToolExtensionService.requestIdKey);
93-
} on FormatException catch (e) {
94-
throw json_rpc.RpcException.invalidParams(e.message);
95-
}
96-
logger?.call(
97-
'[ToolExtensionIsolate] Handling ${ToolExtensionService.cancelRequestNotificationMethod} for "$requestId".',
98-
);
99-
await Future.wait(services.map((ToolExtensionService s) => s.onCancelRequest(requestId)));
100-
});
101-
10275
rpcHandlers.forEach((String fullMethod, ExtensionRpcHandler handler) {
10376
peer.registerMethod(fullMethod, (json_rpc.Parameters params) async {
10477
logger?.call('[ToolExtensionIsolate] Handling RPC request "$fullMethod"...');

0 commit comments

Comments
 (0)