forked from dart-lang/webdev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdev_handler.dart
648 lines (602 loc) · 24.1 KB
/
dev_handler.dart
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:dwds/data/build_result.dart';
import 'package:dwds/data/connect_request.dart';
import 'package:dwds/data/debug_event.dart';
import 'package:dwds/data/devtools_request.dart';
import 'package:dwds/data/error_response.dart';
import 'package:dwds/data/isolate_events.dart';
import 'package:dwds/data/register_event.dart';
import 'package:dwds/data/serializers.dart';
import 'package:dwds/src/connections/app_connection.dart';
import 'package:dwds/src/connections/debug_connection.dart';
import 'package:dwds/src/debugging/execution_context.dart';
import 'package:dwds/src/debugging/remote_debugger.dart';
import 'package:dwds/src/debugging/webkit_debugger.dart';
import 'package:dwds/src/dwds_vm_client.dart';
import 'package:dwds/src/events.dart';
import 'package:dwds/src/handlers/injector.dart';
import 'package:dwds/src/handlers/socket_connections.dart';
import 'package:dwds/src/loaders/require.dart';
import 'package:dwds/src/loaders/strategy.dart';
import 'package:dwds/src/readers/asset_reader.dart';
import 'package:dwds/src/servers/devtools.dart';
import 'package:dwds/src/servers/extension_backend.dart';
import 'package:dwds/src/services/app_debug_services.dart';
import 'package:dwds/src/services/debug_service.dart';
import 'package:dwds/src/services/expression_compiler.dart';
import 'package:dwds/src/utilities/shared.dart';
import 'package:logging/logging.dart';
import 'package:shelf/shelf.dart';
import 'package:sse/server/sse_handler.dart';
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart';
/// When enabled, this logs VM service protocol and Chrome debug protocol
/// traffic to disk.
///
/// Note: this should not be checked in enabled.
const _enableLogging = false;
final _logger = Logger('DevHandler');
/// SSE handler to enable development features like hot reload and
/// opening DevTools.
class DevHandler {
final _subs = <StreamSubscription>[];
final _sseHandlers = <String, SocketHandler>{};
final _injectedConnections = <SocketConnection>{};
final DevTools? _devTools;
final AssetReader _assetReader;
final LoadStrategy _loadStrategy;
final String _hostname;
final _connectedApps = StreamController<AppConnection>.broadcast();
final _servicesByAppId = <String, AppDebugServices>{};
final _appConnectionByAppId = <String, AppConnection>{};
final Stream<BuildResult> buildResults;
final Future<ChromeConnection> Function() _chromeConnection;
final ExtensionBackend? _extensionBackend;
final StreamController<DebugConnection> extensionDebugConnections =
StreamController<DebugConnection>();
final UrlEncoder? _urlEncoder;
final bool _useSseForDebugProxy;
final bool _useSseForInjectedClient;
final bool _spawnDds;
final bool _launchDevToolsInNewWindow;
final ExpressionCompiler? _expressionCompiler;
final DwdsInjector _injected;
/// Null until [close] is called.
///
/// All subsequent calls to [close] will return this future.
Future<void>? _closed;
Stream<AppConnection> get connectedApps => _connectedApps.stream;
DevHandler(
this._chromeConnection,
this.buildResults,
this._devTools,
this._assetReader,
this._loadStrategy,
this._hostname,
this._extensionBackend,
this._urlEncoder,
this._useSseForDebugProxy,
this._useSseForInjectedClient,
this._expressionCompiler,
this._injected,
this._spawnDds,
this._launchDevToolsInNewWindow,
) {
_subs.add(buildResults.listen(_emitBuildResults));
_listen();
if (_extensionBackend != null) {
_listenForDebugExtension();
}
}
Handler get handler => (request) async {
final path = request.requestedUri.path;
final sseHandler = _sseHandlers[path];
if (sseHandler != null) {
return sseHandler.handler(request);
}
return Response.notFound('');
};
Future<void> close() => _closed ??= () async {
for (var sub in _subs) {
await sub.cancel();
}
for (var handler in _sseHandlers.values) {
handler.shutdown();
}
await Future.wait(
_servicesByAppId.values.map((service) => service.close()));
_servicesByAppId.clear();
}();
void _emitBuildResults(BuildResult result) {
if (result.status != BuildStatus.succeeded) return;
for (var injectedConnection in _injectedConnections) {
injectedConnection.sink.add(jsonEncode(serializers.serialize(result)));
}
}
/// Starts a [DebugService] for local debugging.
Future<DebugService> _startLocalDebugService(
ChromeConnection chromeConnection, AppConnection appConnection) async {
ChromeTab? appTab;
ExecutionContext? executionContext;
WipConnection? tabConnection;
final appInstanceId = appConnection.request.instanceId;
for (var tab in await chromeConnection.getTabs()) {
if (tab.isChromeExtension || tab.isBackgroundPage) continue;
final connection = tabConnection = await tab.connect();
if (_enableLogging) {
connection.onSend.listen((message) {
_log(' wip', '==> $message');
});
connection.onReceive.listen((message) {
_log(' wip', '<== $message');
});
connection.onNotification.listen((message) {
_log(' wip', '<== $message');
});
}
final contextIds = connection.runtime.onExecutionContextCreated
.map((context) => context.id)
// There is no way to calculate the number of existing execution
// contexts so keep receiving them until there is a 50ms gap after
// receiving the last one.
.takeUntilGap(const Duration(milliseconds: 50));
// We enqueue this work as we need to begin listening (`.hasNext`)
// before events are received.
safeUnawaited(Future.microtask(connection.runtime.enable));
await for (var contextId in contextIds) {
final result = await connection.sendCommand('Runtime.evaluate', {
'expression': r'window["$dartAppInstanceId"];',
'contextId': contextId,
});
final evaluatedAppId = result.result?['result']?['value'];
if (evaluatedAppId == appInstanceId) {
appTab = tab;
executionContext = RemoteDebuggerExecutionContext(
contextId, WebkitDebugger(WipDebugger(connection)));
break;
}
}
if (appTab != null) break;
safeUnawaited(connection.close());
}
if (appTab == null || tabConnection == null || executionContext == null) {
throw AppConnectionException(
'Could not connect to application with appInstanceId: '
'$appInstanceId');
}
final webkitDebugger = WebkitDebugger(WipDebugger(tabConnection));
return DebugService.start(
// We assume the user will connect to the debug service on the same
// machine. This allows consumers of DWDS to provide a `hostname` for
// debugging through the Dart Debug Extension without impacting the local
// debug workflow.
'localhost',
webkitDebugger,
executionContext,
basePathForServerUri(appTab.url),
_assetReader,
_loadStrategy,
appConnection,
_urlEncoder,
onResponse: (response) {
if (response['error'] == null) return;
_logger.finest('VmService proxy responded with an error:\n$response');
if (_enableLogging) {
_log('vm', '<== ${response.toString().replaceAll('\n', ' ')}');
}
},
onRequest: (request) {
if (_enableLogging) {
_log('vm', '==> ${request.toString().replaceAll('\n', ' ')}');
}
},
// This will provide a websocket based service.
useSse: false,
expressionCompiler: _expressionCompiler,
spawnDds: _spawnDds,
);
}
void _log(String type, String message) {
final logFile = File('${Platform.environment['HOME']}/dwds_log.txt');
final time = (DateTime.now().millisecondsSinceEpoch % 1000000) / 1000.0;
logFile.writeAsStringSync(
'[${time.toStringAsFixed(3).padLeft(7)}s] $type $message\n',
mode: FileMode.append,
);
}
Future<AppDebugServices> loadAppServices(AppConnection appConnection) async {
final appId = appConnection.request.appId;
var appServices = _servicesByAppId[appId];
if (appServices == null) {
final debugService = await _startLocalDebugService(
await _chromeConnection(), appConnection);
appServices = await _createAppDebugServices(
appConnection.request.appId, debugService);
safeUnawaited(appServices.chromeProxyService.remoteDebugger.onClose.first
.whenComplete(() async {
await appServices?.close();
_servicesByAppId.remove(appConnection.request.appId);
_logger.info('Stopped debug service on '
'ws://${debugService.hostname}:${debugService.port}\n');
}));
_servicesByAppId[appId] = appServices;
}
return appServices;
}
void _handleConnection(SocketConnection injectedConnection) {
_injectedConnections.add(injectedConnection);
AppConnection? appConnection;
injectedConnection.stream.listen((data) async {
try {
final message = serializers.deserialize(jsonDecode(data));
if (message is ConnectRequest) {
if (appConnection != null) {
throw StateError('Duplicate connection request from the same app. '
'Please file an issue at '
'https://github.com/dart-lang/webdev/issues/new.');
}
appConnection =
await _handleConnectRequest(message, injectedConnection);
} else {
final connection = appConnection;
if (connection == null) {
throw StateError('Not connected to an application.');
}
if (message is DevToolsRequest) {
await _handleDebugRequest(connection, injectedConnection);
} else if (message is IsolateExit) {
_handleIsolateExit(connection);
} else if (message is IsolateStart) {
await _handleIsolateStart(connection, injectedConnection);
} else if (message is BatchedDebugEvents) {
_servicesByAppId[connection.request.appId]
?.chromeProxyService
.parseBatchedDebugEvents(message);
} else if (message is DebugEvent) {
_servicesByAppId[connection.request.appId]
?.chromeProxyService
.parseDebugEvent(message);
} else if (message is RegisterEvent) {
_servicesByAppId[connection.request.appId]
?.chromeProxyService
.parseRegisterEvent(message);
}
}
} catch (e, s) {
// Most likely the app disconnected in the middle of us responding,
// but we will try and send an error response back to the page just in
// case it is still running.
try {
injectedConnection.sink
.add(jsonEncode(serializers.serialize(ErrorResponse((b) => b
..error = '$e'
..stackTrace = '$s'))));
} on StateError catch (_) {
// The sink has already closed (app is disconnected), swallow the
// error.
}
}
});
safeUnawaited(injectedConnection.sink.done.then((_) {
_injectedConnections.remove(injectedConnection);
final connection = appConnection;
if (connection != null) {
_appConnectionByAppId.remove(connection.request.appId);
final services = _servicesByAppId[connection.request.appId];
if (services != null) {
if (services.connectedInstanceId == null ||
services.connectedInstanceId == connection.request.instanceId) {
services.connectedInstanceId = null;
services.chromeProxyService.destroyIsolate();
}
}
}
}));
}
Future<void> _handleDebugRequest(
AppConnection appConnection, SocketConnection sseConnection) async {
if (_devTools == null) {
sseConnection.sink
.add(jsonEncode(serializers.serialize(DevToolsResponse((b) => b
..success = false
..promptExtension = false
..error = 'Debugging is not enabled.\n\n'
'If you are using webdev please pass the --debug flag.\n'
'Otherwise check the docs for the tool you are using.'))));
return;
}
final debuggerStart = DateTime.now();
AppDebugServices appServices;
try {
appServices = await loadAppServices(appConnection);
} catch (_) {
final error = 'Unable to connect debug services to your '
'application. Most likely this means you are trying to '
'load in a different Chrome window than was launched by '
'your development tool.';
var response = DevToolsResponse((b) => b
..success = false
..promptExtension = false
..error = error);
if (_extensionBackend != null) {
response = response.rebuild((b) => b
..promptExtension = true
..error = '$error\n\n'
'Your workflow alternatively supports debugging through the '
'Dart Debug Extension.\n\n'
'Would you like to install the extension?');
}
sseConnection.sink.add(jsonEncode(serializers.serialize(response)));
return;
}
// Check if we are already running debug services for a different
// instance of this app.
if (appServices.connectedInstanceId != null &&
appServices.connectedInstanceId != appConnection.request.instanceId) {
sseConnection.sink
.add(jsonEncode(serializers.serialize(DevToolsResponse((b) => b
..success = false
..promptExtension = false
..error = 'This app is already being debugged in a different tab. '
'Please close that tab or switch to it.'))));
return;
}
sseConnection.sink
.add(jsonEncode(serializers.serialize(DevToolsResponse((b) => b
..success = true
..promptExtension = false))));
appServices.connectedInstanceId = appConnection.request.instanceId;
appServices.dwdsStats.updateLoadTime(
debuggerStart: debuggerStart,
devToolsStart: DateTime.now(),
);
if (_devTools != null) {
await _launchDevTools(
appServices.chromeProxyService.remoteDebugger,
_constructDevToolsUri(appServices.debugService.uri,
ideQueryParam: 'Dwds'));
}
}
Future<AppConnection> _handleConnectRequest(
ConnectRequest message, SocketConnection sseConnection) async {
// After a page refresh, reconnect to the same app services if they
// were previously launched and create the new isolate.
final services = _servicesByAppId[message.appId];
final existingConnection = _appConnectionByAppId[message.appId];
final connection = AppConnection(message, sseConnection);
// We can take over a connection if there is no connectedInstanceId (this
// means the client completely disconnected), or if the existing
// AppConnection is in the KeepAlive state (this means it disconnected but
// is still waiting for a possible reconnect - this happens during a page
// reload).
final canReuseConnection = services != null &&
(services.connectedInstanceId == null ||
existingConnection?.isInKeepAlivePeriod == true);
if (canReuseConnection) {
// Disconnect any old connection (eg. those in the keep-alive waiting
// state when reloading the page).
existingConnection?.shutDown();
services.chromeProxyService.destroyIsolate();
// Reconnect to existing service.
services.connectedInstanceId = message.instanceId;
await services.chromeProxyService.createIsolate(connection);
}
_appConnectionByAppId[message.appId] = connection;
_connectedApps.add(connection);
return connection;
}
void _handleIsolateExit(AppConnection appConnection) {
_servicesByAppId[appConnection.request.appId]
?.chromeProxyService
.destroyIsolate();
}
Future<void> _handleIsolateStart(
AppConnection appConnection, SocketConnection sseConnection) async {
await _servicesByAppId[appConnection.request.appId]
?.chromeProxyService
.createIsolate(appConnection);
}
void _listen() {
_subs.add(_injected.devHandlerPaths.listen((devHandlerPath) async {
final uri = Uri.parse(devHandlerPath);
if (!_sseHandlers.containsKey(uri.path)) {
final handler = _useSseForInjectedClient
? SseSocketHandler(
// We provide an essentially indefinite keep alive duration because
// the underlying connection could be lost while the application
// is paused. The connection will get re-established after a resume
// or cleaned up on a full page refresh.
SseHandler(uri, keepAlive: const Duration(days: 3000)))
: WebSocketSocketHandler();
_sseHandlers[uri.path] = handler;
final injectedConnections = handler.connections;
while (await injectedConnections.hasNext) {
_handleConnection(await injectedConnections.next);
}
}
}));
}
Future<AppDebugServices> _createAppDebugServices(
String appId, DebugService debugService) async {
final dwdsStats = DwdsStats();
final webdevClient = await DwdsVmClient.create(debugService, dwdsStats);
if (_spawnDds) {
await debugService.startDartDevelopmentService();
}
final appDebugService =
AppDebugServices(debugService, webdevClient, dwdsStats);
final encodedUri = await debugService.encodedUri;
_logger.info('Debug service listening on $encodedUri\n');
await appDebugService.chromeProxyService.remoteDebugger
.sendCommand('Runtime.evaluate', params: {
'expression': 'console.log('
'"This app is linked to the debug service: $encodedUri"'
');',
});
return appDebugService;
}
Future<void> _listenForDebugExtension() async {
while (await _extensionBackend!.connections.hasNext) {
await _startExtensionDebugService();
}
}
/// Starts a [DebugService] for Dart Debug Extension.
Future<void> _startExtensionDebugService() async {
final extensionDebugger = await _extensionBackend!.extensionDebugger;
// Waits for a `DevToolsRequest` to be sent from the extension background
// when the extension is clicked.
extensionDebugger.devToolsRequestStream.listen((devToolsRequest) async {
// TODO(grouma) - Ideally we surface those warnings to the extension so
// that it can be displayed to the user through an alert.
final tabUrl = devToolsRequest.tabUrl;
final appId = devToolsRequest.appId;
if (tabUrl == null) {
_logger.warning('Failed to start extension debug service. '
'Missing tab url in DevTools request for app with id: $appId');
return;
}
final connection = _appConnectionByAppId[appId];
if (connection == null) {
_logger.warning('Failed to start extension debug service. '
'Not connected to an app with id: $appId');
return;
}
final executionContext = extensionDebugger.executionContext;
if (executionContext == null) {
_logger.warning('Failed to start extension debug service. '
'No execution context for app with id: $appId');
return;
}
final debuggerStart = DateTime.now();
var appServices = _servicesByAppId[appId];
if (appServices == null) {
final debugService = await DebugService.start(
_hostname,
extensionDebugger,
executionContext,
basePathForServerUri(tabUrl),
_assetReader,
_loadStrategy,
connection,
_urlEncoder,
onResponse: (response) {
if (response['error'] == null) return;
_logger
.finest('VmService proxy responded with an error:\n$response');
},
useSse: _useSseForDebugProxy,
expressionCompiler: _expressionCompiler,
spawnDds: _spawnDds,
);
appServices = await _createAppDebugServices(
devToolsRequest.appId,
debugService,
);
final encodedUri = await debugService.encodedUri;
extensionDebugger.sendEvent('dwds.encodedUri', encodedUri);
safeUnawaited(appServices
.chromeProxyService.remoteDebugger.onClose.first
.whenComplete(() async {
appServices?.chromeProxyService.destroyIsolate();
await appServices?.close();
_servicesByAppId.remove(devToolsRequest.appId);
_logger.info('Stopped debug service on '
'${await appServices?.debugService.encodedUri}\n');
}));
extensionDebugConnections.add(DebugConnection(appServices));
_servicesByAppId[appId] = appServices;
}
// If we don't have a DevTools instance, then are connecting to an IDE.
// Therefore return early instead of opening DevTools:
if (_devTools == null) return;
final encodedUri = await appServices.debugService.encodedUri;
appServices.dwdsStats.updateLoadTime(
debuggerStart: debuggerStart, devToolsStart: DateTime.now());
// TODO(elliette): Remove handling requests from the MV2 extension after
// MV3 release.
// If we only want the URI, this means the Dart Debug Extension should
// handle how to open it. Therefore return early before opening a new
// tab or window:
if (devToolsRequest.uriOnly ?? false) {
final devToolsUri = _constructDevToolsUri(
encodedUri,
ideQueryParam: 'ChromeDevTools',
);
return extensionDebugger.sendEvent('dwds.devtoolsUri', devToolsUri);
}
// Otherwise, launch DevTools in a new tab / window:
await _launchDevTools(
extensionDebugger,
_constructDevToolsUri(
encodedUri,
ideQueryParam: 'DebugExtension',
),
);
});
}
DevTools _ensureDevTools() {
final devTools = _devTools;
if (devTools == null) {
throw StateError('DevHandler: DevTools is not available');
}
return devTools;
}
Future<void> _launchDevTools(
RemoteDebugger remoteDebugger, String devToolsUri) async {
// TODO(annagrin): move checking whether devtools should be started
// and the creation of the uri logic here so it is easier to follow.
_ensureDevTools();
// TODO(grouma) - We may want to log the debugServiceUri if we don't launch
// DevTools so that users can manually connect.
emitEvent(DwdsEvent.devtoolsLaunch());
await remoteDebugger.sendCommand('Target.createTarget', params: {
'newWindow': _launchDevToolsInNewWindow,
'url': devToolsUri,
});
}
String _constructDevToolsUri(
String debugServiceUri, {
String ideQueryParam = '',
}) {
final devTools = _ensureDevTools();
return Uri(
scheme: 'http',
host: devTools.hostname,
port: devTools.port,
queryParameters: {
'uri': debugServiceUri,
if (ideQueryParam.isNotEmpty) 'ide': ideQueryParam,
}).toString();
}
}
class AppConnectionException implements Exception {
final String details;
AppConnectionException(this.details);
}
extension<T> on Stream<T> {
/// Forwards events from the original stream until a period of at least [gap]
/// occurs in between events, in which case the returned stream will end.
Stream<T> takeUntilGap(Duration gap) {
final controller = isBroadcast
? StreamController<T>.broadcast(sync: true)
: StreamController<T>(sync: true);
late StreamSubscription<T> subscription;
Timer? gapTimer;
controller.onListen = () {
subscription = listen((e) {
controller.add(e);
gapTimer?.cancel();
gapTimer = Timer(gap, () {
subscription.cancel();
controller.close();
});
}, onError: controller.addError, onDone: controller.close);
};
// Not handling pause/resume
return controller.stream;
}
}