forked from flutter/devtools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_api_client.dart
More file actions
204 lines (177 loc) · 6.34 KB
/
Copy pathserver_api_client.dart
File metadata and controls
204 lines (177 loc) · 6.34 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
// Copyright 2019 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:convert';
import 'package:devtools_app_shared/ui.dart' show isEmbedded;
import 'package:devtools_shared/devtools_shared.dart';
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import '../config_specific/notifications/notifications.dart';
import '../framework/framework_controller.dart';
import '../globals.dart';
import 'server.dart';
final _log = Logger('lib/src/shared/server_api_client');
/// This class coordinates the connection between the DevTools server and the
/// DevTools web app.
///
/// See `package:dds/src/devtools/client.dart`.
class DevToolsServerConnection {
DevToolsServerConnection._(this.sseClient) {
sseClient.stream!.listen((msg) {
_handleMessage(msg);
});
initFrameworkController();
}
/// Returns a URI for the backend ./api folder for a DevTools page being hosted
/// at `baseUri`. Trailing slashes are important to support Path-URL Strategy:
///
/// - http://foo/devtools/ => http://foo/devtools/api
/// - http://foo/devtools/inspector => http://foo/devtools/api
///
/// For compatibility with any tools that might construct URIs ending with
/// "/devtools" without the trailing slash, URIs ending with `devtools` (such
/// as when hosted by DDS) are handled specially:
///
/// - http://foo/devtools => http://foo/devtools/api
@visibleForTesting
static Uri apiUriFor(Uri baseUri) => baseUri.path.endsWith('devtools')
? baseUri.resolve('devtools/api/')
: baseUri.resolve('api/');
/// Connects to the legacy SSE API.
///
/// Callers should first ensure the DevTools server is available (for example
/// by calling [checkServerHttpApiAvailable] or verifying that it was
/// successfull by using [isDevToolsServerAvailable])
static Future<DevToolsServerConnection?> connect() async {
// Don't connect SSE when running embedded because the API does not provide
// anything that is used when embedded but it ties up one of the limited
// number of connections to the server.
// https://github.com/flutter/devtools/issues/8298
if (isEmbedded()) {
return null;
}
final serverUri = Uri.parse(devToolsServerUriAsString);
final apiUri = apiUriFor(serverUri);
final sseUri = apiUri.resolve('sse');
final client = SseClient(sseUri.toString(), debugKey: 'DevToolsServer');
return DevToolsServerConnection._(client);
}
final SseClient sseClient;
int _nextRequestId = 0;
Notification? _lastNotification;
final _completers = <String, Completer<Object?>>{};
/// Tie the DevTools server connection to the framework controller.
///
/// This is called once, sometime after the `DevToolsServerConnection`
/// instance is created.
void initFrameworkController() {
frameworkController.onConnected.listen((vmServiceUri) {
_notifyConnected(vmServiceUri);
});
frameworkController.onPageChange.listen((page) {
_notifyCurrentPage(page);
});
frameworkController.onDisconnected.listen((_) {
_notifyDisconnected();
});
}
Future<void> notify() async {
final permission = await Notification.requestPermission();
if (permission != 'granted') {
return;
}
// Dismiss any earlier notifications first so they don't build up in the
// notifications list if the user presses the button multiple times.
dismissNotifications();
_lastNotification = Notification(
'Dart DevTools',
body: 'DevTools is available in this existing browser window',
);
}
void dismissNotifications() {
_lastNotification?.close();
}
Future<T> _callMethod<T>(String method, [Map<String, dynamic>? params]) {
final id = '${_nextRequestId++}';
final json = jsonEncode({
'jsonrpc': '2.0',
'id': id,
'method': method,
'params': ?params,
});
final completer = Completer<T>();
_completers[id] = completer;
sseClient.sink!.add(json);
return completer.future;
}
void _handleMessage(String msg) {
try {
final Map request = jsonDecode(msg);
if (request.containsKey('method')) {
final String method = request['method'];
final Map<String, dynamic> params = request['params'] ?? {};
_handleMethod(method, params);
} else if (request.containsKey('id')) {
_handleResponse(request['id']!, request['result']);
} else {
_log.info('Unable to parse API message from server:\n\n$msg');
}
} catch (e) {
_log.info('Failed to handle API message from server:\n\n$msg\n\n$e');
}
}
void _handleMethod(String method, Map<String, dynamic> params) {
switch (method) {
case 'connectToVm':
final String uri = params['uri'];
final notify = params['notify'] == true;
frameworkController.notifyConnectToVmEvent(
Uri.parse(uri),
notify: notify,
);
return;
case 'showPage':
final String pageId = params['page'];
frameworkController.notifyShowPageId(pageId);
return;
case 'enableNotifications':
unawaited(Notification.requestPermission());
return;
case 'notify':
unawaited(notify());
return;
case 'ping':
ping();
return;
default:
_log.info('Unknown request $method from server');
}
}
void _handleResponse(String id, Object? result) {
final completer = _completers.remove(id);
completer?.complete(result);
}
void _notifyConnected(String vmServiceUri) {
unawaited(_callMethod('connected', {'uri': vmServiceUri}));
}
void _notifyCurrentPage(PageChangeEvent page) {
unawaited(
_callMethod('currentPage', {
'id': page.id,
// TODO(kenz): see if we need to change the client code on the
// DevTools server to be aware of the type of embedded mode (many vs.
// one).
'embedded': page.embedMode.embedded,
}),
);
}
void _notifyDisconnected() {
unawaited(_callMethod('disconnected'));
}
/// Allows the server to ping the client to see that it is definitely still
/// active and doesn't just appear to be connected because of SSE timeouts.
void ping() {
unawaited(_callMethod('pingResponse'));
}
}