-
Notifications
You must be signed in to change notification settings - Fork 390
Expand file tree
/
Copy pathisolate_manager.dart
More file actions
379 lines (325 loc) · 12.8 KB
/
isolate_manager.dart
File metadata and controls
379 lines (325 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// Copyright 2018 The Flutter Authors
// 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 'dart:async';
import 'dart:core';
import 'package:collection/collection.dart' show IterableExtension;
import 'package:dds_service_extensions/dds_service_extensions.dart';
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import 'package:vm_service/vm_service.dart' hide Error;
import '../utils/auto_dispose.dart';
import '../utils/list.dart';
import '../utils/utils.dart';
import 'isolate_state.dart';
import 'service_extensions.dart' as extensions;
final _log = Logger('isolate_manager');
@visibleForTesting
base mixin TestIsolateManager implements IsolateManager {}
final class IsolateManager with DisposerMixin {
final _isolateStates = <IsolateRef, IsolateState>{};
/// The amount of time we will wait for the main isolate to become non-null
/// when calling [waitForMainIsolateState].
static const _waitForMainIsolateStateTimeout = Duration(seconds: 3);
/// Signifies whether the main isolate should be selected if it is started.
///
/// This is used to make sure the the main isolate remains selected after
/// a hot restart.
bool _shouldReselectMainIsolate = false;
VmService? _service;
final _isolateCreatedController = StreamController<IsolateRef?>.broadcast();
final _isolateExitedController = StreamController<IsolateRef?>.broadcast();
ValueListenable<IsolateRef?> get selectedIsolate => _selectedIsolate;
final _selectedIsolate = ValueNotifier<IsolateRef?>(null);
int _lastIsolateIndex = 0;
final _isolateIndexMap = <String?, int>{};
ValueListenable<List<IsolateRef>> get isolates => _isolates;
final _isolates = ListValueNotifier(const <IsolateRef>[]);
ValueListenable<IsolateRef?> get mainIsolate => _mainIsolate;
final _mainIsolate = ValueNotifier<IsolateRef?>(null);
final _isolateRunnableCompleters = <String?, Completer<void>>{};
// TODO(https://github.com/flutter/flutter/issues/134470): Track hot-restarts
// triggered by other clients.
bool hotRestartInProgress = false;
Future<void> init(List<IsolateRef> isolates) async {
await initIsolates(isolates);
}
IsolateState? get mainIsolateState {
return _mainIsolate.value != null
? _isolateStates[_mainIsolate.value!]
: null;
}
Future<IsolateState?> waitForMainIsolateState() async {
final mainIsolateRef = await whenValueNonNull<IsolateRef?>(
mainIsolate,
timeout: _waitForMainIsolateStateTimeout,
);
if (mainIsolateRef == null) return null;
final state = mainIsolateState;
await state?.waitForIsolateLoad();
return state;
}
/// Return a unique, monotonically increasing number for this Isolate.
int? isolateIndex(IsolateRef isolateRef) {
if (!_isolateIndexMap.containsKey(isolateRef.id)) {
_isolateIndexMap[isolateRef.id] = ++_lastIsolateIndex;
}
return _isolateIndexMap[isolateRef.id];
}
void selectIsolate(IsolateRef? isolateRef) {
_setSelectedIsolate(isolateRef);
}
@protected
Future<void> initIsolates(List<IsolateRef> isolates) async {
_clearIsolateStates();
await [
for (final isolateRef in isolates) _registerIsolate(isolateRef),
].wait;
// It is critical that the _serviceExtensionManager is already listening
// for events indicating that new extension rpcs are registered before this
// call otherwise there is a race condition where service extensions are not
// described in the selectedIsolate or received as an event. It is ok if a
// service extension is included in both places as duplicate extensions are
// handled gracefully.
await _initSelectedIsolate();
}
Future<void> _registerIsolate(IsolateRef isolateRef) async {
assert(!_isolateStates.containsKey(isolateRef));
_isolateStates[isolateRef] = IsolateState(isolateRef);
_isolates.add(isolateRef);
isolateIndex(isolateRef);
await _loadIsolateState(isolateRef);
// If the flag pause-breakpoints-on-start was successfully set, then each
// new isolate will start paused. Therefore resume it (unless it is the
// current isolate, in which case the breakpoint manager will resume it
// after setting breakpoints):
final selectedIsolateId = selectedIsolate.value?.id;
if (selectedIsolateId != null && selectedIsolateId != isolateRef.id) {
await resumeIsolate(isolateRef);
}
}
Future<void> _loadIsolateState(IsolateRef isolateRef) async {
try {
final service = _service;
var isolate = await _service!.getIsolate(isolateRef.id!);
if (isolate.runnable == false) {
final isolateRunnableCompleter = _isolateRunnableCompleters.putIfAbsent(
isolate.id,
() => Completer<void>(),
);
if (!isolateRunnableCompleter.isCompleted) {
await isolateRunnableCompleter.future;
isolate = await _service!.getIsolate(isolate.id!);
}
}
if (service != _service) return;
final state = _isolateStates[isolateRef];
if (state != null) {
// Isolate might have already been closed.
state.handleIsolateLoad(isolate);
}
} on SentinelException catch (_) {
// Isolate doesn't exist anymore, nothing to do.
_log.info(
'isolateRef($isolateRef) ceased to exist while loading isolate state',
);
}
}
Future<void> _handleIsolateEvent(Event event) async {
if (event.kind == EventKind.kIsolateRunnable) {
final isolateRunnable = _isolateRunnableCompleters.putIfAbsent(
event.isolate!.id,
() => Completer<void>(),
);
isolateRunnable.complete();
if (hotRestartInProgress) {
hotRestartInProgress = false;
}
} else if (event.kind == EventKind.kIsolateStart &&
!event.isolate!.isSystemIsolate!) {
await _registerIsolate(event.isolate!);
_isolateCreatedController.add(event.isolate);
// Recompute whenever a new isolate starts so test connections can move
// from the runner isolate to the user test-suite isolate when available.
final previousMain = _mainIsolate.value;
final computedMain = await _computeMainIsolate();
if (computedMain != null) {
_mainIsolate.value = computedMain;
} else if (_mainIsolate.value == null) {
_mainIsolate.value = event.isolate;
}
if (_mainIsolate.value != null &&
(_shouldReselectMainIsolate ||
_selectedIsolate.value == null ||
_selectedIsolate.value == previousMain)) {
// If the previous main exited and returned (hot restart) or we were
// following the previous main, follow the newly computed main isolate.
_shouldReselectMainIsolate = false;
_setSelectedIsolate(_mainIsolate.value);
}
} else if (event.kind == EventKind.kServiceExtensionAdded) {
// Check to see if there is a new isolate.
if (_selectedIsolate.value == null &&
extensions.isFlutterExtension(event.extensionRPC!)) {
_setSelectedIsolate(event.isolate);
}
} else if (event.kind == EventKind.kIsolateExit) {
_isolateStates.remove(event.isolate)?.dispose();
if (event.isolate != null) _isolates.remove(event.isolate!);
_isolateExitedController.add(event.isolate);
if (_mainIsolate.value == event.isolate) {
if (_selectedIsolate.value == _mainIsolate.value) {
// If the main isolate was selected and exits, then assume that a hot
// restart is happening. So reselect when the main isolate comes back.
_shouldReselectMainIsolate = true;
}
_mainIsolate.value = null;
}
if (_selectedIsolate.value == event.isolate) {
_selectedIsolate.value = _isolateStates.keys.firstOrNull;
}
_isolateRunnableCompleters.remove(event.isolate!.id);
}
}
Future<void> _initSelectedIsolate() async {
if (_isolateStates.isEmpty) {
return;
}
_mainIsolate.value = null;
final service = _service;
final mainIsolate = await _computeMainIsolate();
if (service != _service) return;
_mainIsolate.value = mainIsolate;
_setSelectedIsolate(_mainIsolate.value);
}
Future<IsolateRef?> _computeMainIsolate() async {
if (_isolateStates.isEmpty) return null;
final service = _service;
for (final isolateState in _isolateStates.values) {
final isolate = await isolateState.isolate;
if (service != _service) return null;
for (final extensionName in isolate?.extensionRPCs ?? <String>[]) {
if (extensions.isFlutterExtension(extensionName)) {
return isolateState.isolateRef;
}
}
}
final ref = _isolateStates.keys.firstWhereOrNull((IsolateRef ref) {
// 'foo.dart:main()'
return ref.name?.contains(':main(') ?? false;
});
if (ref == null) {
final rootLibraryTestSuiteRef =
await _findTestSuiteByRootLibrary(service);
if (rootLibraryTestSuiteRef != null) return rootLibraryTestSuiteRef;
// When connecting to a test run, the test package (package:test_core)
// spawns each test suite in a separate isolate with a debug name
// prefixed with 'test_suite:'. DevTools should connect to this isolate
// rather than the test runner isolate ('main'), since the test suite
// isolate is where user code actually runs.
// See: https://github.com/flutter/devtools/issues/9747
final testSuiteRef = _isolateStates.keys.firstWhereOrNull(
(IsolateRef ref) => ref.name?.startsWith('test_suite:') ?? false,
);
if (testSuiteRef != null) return testSuiteRef;
}
return ref ?? _isolateStates.keys.first;
}
Future<IsolateRef?> _findTestSuiteByRootLibrary(VmService? service) async {
for (final isolateState in _isolateStates.values) {
final isolate = await isolateState.isolate;
if (service != _service) return null;
final rootLibraryUri = isolate?.rootLib?.uri;
if (rootLibraryUri == null) continue;
if (_isDartTestRunnerRootLibrary(rootLibraryUri)) continue;
if (_isLikelyUserTestRootLibrary(rootLibraryUri)) {
return isolateState.isolateRef;
}
}
return null;
}
bool _isDartTestRunnerRootLibrary(String uri) {
return uri.contains('dart_test.kernel') ||
uri.startsWith('package:test_core/') ||
uri.startsWith('package:test_api/');
}
bool _isLikelyUserTestRootLibrary(String uri) {
return (uri.endsWith('_test.dart') ||
uri.contains('/test/') ||
uri.contains('\\test\\')) &&
!uri.startsWith('dart:');
}
void _setSelectedIsolate(IsolateRef? ref) {
_selectedIsolate.value = ref;
}
void handleVmServiceClosed() {
cancelStreamSubscriptions();
_selectedIsolate.value = null;
_service = null;
_lastIsolateIndex = 0;
_setSelectedIsolate(null);
_isolateIndexMap.clear();
_clearIsolateStates();
_mainIsolate.value = null;
_isolateRunnableCompleters.clear();
}
/// Resumes the isolate by calling [DdsExtension.readyToResume].
///
/// CAUTION: This should only be used for a tool-initiated resume, not a user-
/// initiated resume. See:
/// https://github.com/dart-lang/sdk/commit/5536951738ba599d96e075b7140e52b28e233
Future<void> resumeIsolate(IsolateRef isolateRef) async {
if (isolateRef.id == null || _service == null) return;
final isolateId = isolateRef.id!;
try {
await _readyToResume(isolateId);
} catch (error) {
_log.warning(error);
}
}
Future<void> _readyToResume(String isolateId) async {
final service = _service!;
try {
await service.readyToResume(isolateId);
} on UnimplementedError {
// Fallback to a regular resume if the DDS version doesn't support
// `readyToResume`:
await service.resume(isolateId);
}
}
void _clearIsolateStates() {
for (final isolateState in _isolateStates.values) {
isolateState.dispose();
}
_isolateStates.clear();
_isolates.clear();
}
void vmServiceOpened(VmService service) {
_selectedIsolate.value = null;
cancelStreamSubscriptions();
_service = service;
autoDisposeStreamSubscription(
service.onIsolateEvent.listen(_handleIsolateEvent),
);
autoDisposeStreamSubscription(
service.onDebugEvent.listen(_handleDebugEvent),
);
// We don't know the main isolate yet.
_mainIsolate.value = null;
}
IsolateState isolateState(IsolateRef isolateRef) {
return _isolateStates.putIfAbsent(
isolateRef,
() => IsolateState(isolateRef),
);
}
void _handleDebugEvent(Event event) {
final isolate = event.isolate;
if (isolate == null) return;
final isolateState = _isolateStates[isolate];
if (isolateState == null) {
return;
}
isolateState.handleDebugEvent(event.kind);
}
}