Skip to content

Commit 1d1b1cd

Browse files
authored
[flutter_tools] Do not mistake server-initiated requests for responses to client requests in AnalysisServer (flutter#192546)
In JSON-RPC 2.0, server-to-client requests (such as `window/workDoneProgress/create`) include an ID allocated by the server along with a method. Previously, `AnalysisServer._handleServerResponse` checked `_outstandingRequests` for any message containing an ID before checking whether the message was a request or notification. If a server request happened to share an ID with an outstanding client request (e.g. `dart/workspace/analysis/complete` sent during `waitForAnalysis`), the server request was mistaken for an invalid response to the client request, causing an uncaught `StateError` that crashed the Flutter tool process and flaked tests in `widget_preview_detection_test.dart`. This change separates the handling of incoming server messages (`method != null`) from responses to client requests (`method == null`), ensuring `_outstandingRequests` is only looked up for actual response messages. Fixes flutter#192471
1 parent 9fc84fa commit 1d1b1cd

3 files changed

Lines changed: 103 additions & 12 deletions

File tree

‎packages/flutter_tools/lib/src/dart/analysis.dart‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -255,18 +255,6 @@ class AnalysisServer {
255255
final Object? response = json.decode(line);
256256

257257
if (response is Map<String, Object?>) {
258-
final Object? id = response['id'];
259-
final Completer<Map<String, Object?>?>? completer = _outstandingRequests.remove(id);
260-
if (completer != null) {
261-
if (response case {'result': final Map<String, Object?>? result}) {
262-
completer.complete(result);
263-
} else if (response case {'error': final Map<String, Object?> error}) {
264-
completer.completeError(error['message'] ?? error);
265-
} else {
266-
completer.completeError('Response for unknown request received: $response');
267-
}
268-
}
269-
270258
final method = response['method'] as String?;
271259
if (method != null) {
272260
final Object? id = response['id'];
@@ -293,6 +281,18 @@ class AnalysisServer {
293281
_handleShowMessage(paramsMap);
294282
}
295283
}
284+
} else {
285+
final Object? id = response['id'];
286+
final Completer<Map<String, Object?>?>? completer = _outstandingRequests.remove(id);
287+
if (completer != null) {
288+
if (response case {'result': final Map<String, Object?>? result}) {
289+
completer.complete(result);
290+
} else if (response case {'error': final Map<String, Object?> error}) {
291+
completer.completeError(error['message'] ?? error);
292+
} else {
293+
completer.completeError('Response for unknown request received: $response');
294+
}
295+
}
296296
}
297297
}
298298
}

‎packages/flutter_tools/test/commands.shard/hermetic/analysis_server_mock.dart‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,28 @@ class MockLspServerProcess extends test_process_manager.FakeProcess {
6868
_writeRawOutput('The Dart VM service is listening on http://127.0.0.1:65155/ZkxDXuYz2Aw=/\n');
6969
}
7070

71+
/// Starts simulated analysis on the server.
72+
void startSimulatedAnalysis() {
73+
_simulateAnalysisStart();
74+
}
75+
76+
/// Ends simulated analysis on the server.
77+
void endSimulatedAnalysis() {
78+
_simulateAnalysisEnd();
79+
}
80+
81+
/// Sends a request from the server to the client.
82+
void sendServerRequest(String method, Map<String, Object?> params, {required Object id}) {
83+
_writeAsLspToStdout(
84+
jsonEncode(<String, Object?>{'jsonrpc': '2.0', 'id': id, 'method': method, 'params': params}),
85+
);
86+
}
87+
88+
/// Optional callback invoked when the mock receives a request on stdin.
89+
void Function(Map<String, Object?> request)? onRequest;
90+
7191
Future<void> _handleRequest(Map<String, Object?> request) async {
92+
onRequest?.call(request);
7293
switch (request['method']) {
7394
case 'initialize':
7495
_initializeRequestCompleter.complete(request);

‎packages/flutter_tools/test/commands.shard/hermetic/analyze_continuously_test.dart‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,76 @@ void main() {
119119
expect(processManager, hasNoRemainingExpectations);
120120
});
121121

122+
testUsingContext(
123+
'AnalysisServer handles server-initiated requests with same ID as outstanding request',
124+
() async {
125+
final Directory tempDir = fileSystem.systemTempDirectory.createTempSync(
126+
'flutter_analysis_test.',
127+
);
128+
createSampleProject(tempDir);
129+
130+
final process = MockLspServerProcess();
131+
final processManager = FakeProcessManager.list(<FakeCommand>[
132+
FakeCommand(
133+
command: <String>[
134+
fileSystem.path.join('Artifact.engineDartSdkPath', 'bin', 'dart'),
135+
'language-server',
136+
'--dart-sdk',
137+
'Artifact.engineDartSdkPath',
138+
'--disable-server-feature-completion',
139+
'--disable-server-feature-search',
140+
'--suppress-analytics',
141+
],
142+
process: process,
143+
),
144+
]);
145+
146+
final server = AnalysisServer(
147+
'Artifact.engineDartSdkPath',
148+
<String>[tempDir.path],
149+
fileSystem: fileSystem,
150+
platform: FakePlatform(),
151+
processManager: processManager,
152+
logger: logger,
153+
terminal: terminal,
154+
suppressAnalytics: true,
155+
);
156+
157+
await server.start();
158+
// Start simulated analysis so dart/workspace/analysis/complete will wait for it.
159+
process.startSimulatedAnalysis();
160+
161+
final analysisCompleteReceived = Completer<int>();
162+
process.onRequest = (Map<String, Object?> request) {
163+
if (request['method'] == 'dart/workspace/analysis/complete') {
164+
analysisCompleteReceived.complete(request['id']! as int);
165+
}
166+
};
167+
168+
// Start waiting for analysis. The client sends dart/workspace/analysis/complete.
169+
final Future<void> waitFuture = server.waitForAnalysis(delay: Duration.zero);
170+
final int requestId = await analysisCompleteReceived.future;
171+
172+
// Simulate server sending a request to the client (e.g. window/workDoneProgress/create)
173+
// with the same ID while client request is still outstanding.
174+
process.sendServerRequest('window/workDoneProgress/create', <String, Object?>{
175+
'token': 'ANALYZING',
176+
}, id: requestId);
177+
178+
await pumpEventQueue();
179+
180+
// Finish simulated analysis, allowing the server to respond to client request.
181+
process.endSimulatedAnalysis();
182+
183+
// The client's waitForAnalysis future should complete successfully and not fail
184+
// due to the server's request being mistaken for a response.
185+
await expectLater(waitFuture, completes);
186+
187+
await server.dispose();
188+
expect(processManager, hasNoRemainingExpectations);
189+
},
190+
);
191+
122192
testUsingContext('AnalysisServer handles non-ASCII project path', () async {
123193
final Directory tempDir = fileSystem.systemTempDirectory.createTempSync(
124194
'flutter_analysis_test_’_dir.',

0 commit comments

Comments
 (0)