Skip to content

Commit 628d744

Browse files
derekxu16Commit Queue
authored andcommitted
[dart:developer][VM/Service] Add APIs to dart:developer for recording HTTP profiling information, and for later retrieving that information
The APIs mentioned above are `addHttpClientProfilingData` and `getHttpClientProfilingData`. This CL also makes it so that profiling information recorded using `addHttpClientProfilingData` is included in dart:io service extension responses. TEST= pkg/vm_service/test/get_http_profile_test.dart Change-Id: I892a7a8485369bb92cbb0c086b93498bcec25d5f Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/341440 Reviewed-by: Sigmund Cherem <[email protected]> Commit-Queue: Derek Xu <[email protected]> Reviewed-by: Ömer Ağacan <[email protected]> Reviewed-by: Siva Annamalai <[email protected]> Reviewed-by: Leaf Petersen <[email protected]> Reviewed-by: Ben Konyi <[email protected]>
1 parent 9415aba commit 628d744

5 files changed

Lines changed: 112 additions & 41 deletions

File tree

‎pkg/vm_service/test/get_http_profile_test.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,8 +242,8 @@ Future<void> hasValidHttpRequests(HttpProfile profile, String method) async {
242242
if (method == 'POST') {
243243
// add() was used
244244
expect(
245-
<int>[0, 1, 2],
246245
fullRequest.requestBody!,
246+
<int>[0, 1, 2],
247247
);
248248
} else {
249249
// write() was used.

‎sdk/lib/_http/http_impl.dart‎

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,19 +24,16 @@ abstract final class HttpProfiler {
2424

2525
static void clear() => _profile.clear();
2626

27-
static String toJson(int? updatedSince) {
28-
return json.encode({
29-
'type': _kType,
30-
'timestamp': DateTime.now().microsecondsSinceEpoch,
31-
'requests': [
32-
for (final request in _profile.values.where(
33-
(e) {
34-
return (updatedSince == null) || e.lastUpdateTime >= updatedSince;
35-
},
36-
))
37-
request.toJson(),
38-
],
39-
});
27+
/// Returns a list of Maps, where each map conforms to the @HttpProfileRequest
28+
/// type defined in the dart:io service extension spec.
29+
static List<Map<String, dynamic>> serializeHttpProfileRequests(
30+
int? updatedSince) {
31+
return _profile.values
32+
.where(
33+
(e) => (updatedSince == null) || e.lastUpdateTime >= updatedSince,
34+
)
35+
.map((e) => e.toJson(ref: true))
36+
.toList();
4037
}
4138
}
4239

@@ -223,7 +220,7 @@ class _HttpProfileData {
223220
_updated();
224221
}
225222

226-
Map<String, dynamic> toJson({bool ref = true}) {
223+
Map<String, dynamic> toJson({required bool ref}) {
227224
return <String, dynamic>{
228225
'type': '${ref ? '@' : ''}HttpProfileRequest',
229226
'id': id,

‎sdk/lib/developer/developer.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ import 'dart:convert';
8080
import 'dart:isolate' show Isolate, RawReceivePort, SendPort;
8181

8282
part 'extension.dart';
83+
part 'http_profiling.dart';
8384
part 'profiler.dart';
8485
part 'service.dart';
8586
part 'timeline.dart';
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file
2+
// for details. All rights reserved. Use of this source code is governed by a
3+
// BSD-style license that can be found in the LICENSE file.
4+
5+
part of dart.developer;
6+
7+
// package:http_profile adds HTTP profiling information to this list by using
8+
// the [addHttpClientProfilingData] API below.
9+
List<Map<String, dynamic>> _developerProfilingData = <Map<String, dynamic>>[];
10+
11+
/// Records the data associated with an HTTP request for profiling purposes.
12+
///
13+
/// This function should never be called directly. Instead, use
14+
/// [package:http_profile](https://pub.dev/packages/http_profile).
15+
@Since('3.4')
16+
void addHttpClientProfilingData(Map<String, dynamic> requestProfile) {
17+
_developerProfilingData.add(requestProfile);
18+
requestProfile['id'] = 'from_package/${_developerProfilingData.length}';
19+
}
20+
21+
/// Returns the data added through [addHttpClientProfilingData].
22+
///
23+
/// This function is only meant for use by networking profilers and the format
24+
/// of the returned data may change over time.
25+
@Since('3.4')
26+
List<Map<String, dynamic>> getHttpClientProfilingData() {
27+
return UnmodifiableListView(_developerProfilingData);
28+
}

‎sdk/lib/io/network_profiling.dart‎

Lines changed: 71 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,39 @@ const int _versionMinor = 0;
1111
const String _tcpSocket = 'tcp';
1212
const String _udpSocket = 'udp';
1313

14+
// Creates a Map conforming to the HttpProfileRequest type defined in the
15+
// dart:io service extension spec from an element of dart:developer's
16+
// [_developerProfilingData].
17+
Future<Map<String, dynamic>> _createHttpProfileRequestFromProfileMap(
18+
Map<String, dynamic> requestProfile,
19+
{required bool ref}) async {
20+
final responseData = requestProfile['responseData'] as Map<String, dynamic>;
21+
22+
return <String, dynamic>{
23+
'type': '${ref ? '@' : ''}HttpProfileRequest',
24+
'id': requestProfile['id']!,
25+
'isolateId': requestProfile['isolateId']!,
26+
'method': requestProfile['requestMethod']!,
27+
'uri': requestProfile['requestUri']!,
28+
'events': requestProfile['events']!,
29+
'startTime': requestProfile['requestStartTimestamp']!,
30+
if (requestProfile['requestEndTimestamp'] != null)
31+
'endTime': requestProfile['requestEndTimestamp'],
32+
'request': requestProfile['requestData']!,
33+
'response': responseData,
34+
if (!ref && requestProfile['requestEndTimestamp'] != null)
35+
'requestBody':
36+
await (requestProfile['_requestBodyStream'] as Stream<List<int>>)
37+
.expand((List<int> i) => i)
38+
.toList(),
39+
if (!ref && responseData['endTime'] != null)
40+
'responseBody':
41+
await (requestProfile['_responseBodyStream'] as Stream<List<int>>)
42+
.expand((List<int> i) => i)
43+
.toList(),
44+
};
45+
}
46+
1447
@pragma('vm:entry-point', !const bool.fromEnvironment("dart.vm.product"))
1548
abstract class _NetworkProfiling {
1649
// Http relative RPCs
@@ -43,7 +76,7 @@ abstract class _NetworkProfiling {
4376
}
4477

4578
static Future<ServiceExtensionResponse> _serviceExtensionHandler(
46-
String method, Map<String, String> parameters) {
79+
String method, Map<String, String> parameters) async {
4780
try {
4881
String responseJson;
4982
switch (method) {
@@ -54,14 +87,25 @@ abstract class _NetworkProfiling {
5487
responseJson = _getHttpEnableTimelineLogging();
5588
break;
5689
case _kGetHttpProfileRPC:
57-
responseJson = HttpProfiler.toJson(
58-
parameters.containsKey('updatedSince')
59-
? int.tryParse(parameters['updatedSince']!)
60-
: null,
61-
);
90+
final updatedSince = parameters.containsKey('updatedSince')
91+
? int.tryParse(parameters['updatedSince']!)
92+
: null;
93+
responseJson = json.encode({
94+
'type': 'HttpProfile',
95+
'timestamp': DateTime.now().microsecondsSinceEpoch,
96+
'requests': [
97+
...HttpProfiler.serializeHttpProfileRequests(updatedSince),
98+
...await Future.wait(getHttpClientProfilingData()
99+
.where((final Map<String, dynamic> p) =>
100+
updatedSince == null ||
101+
(p['_lastUpdateTime'] as int) >= updatedSince)
102+
.map((p) =>
103+
_createHttpProfileRequestFromProfileMap(p, ref: true)))
104+
],
105+
});
62106
break;
63107
case _kGetHttpProfileRequestRPC:
64-
responseJson = _getHttpProfileRequest(parameters);
108+
responseJson = await _getHttpProfileRequest(parameters);
65109
break;
66110
case _kClearHttpProfileRPC:
67111
HttpProfiler.clear();
@@ -80,22 +124,16 @@ abstract class _NetworkProfiling {
80124
responseJson = getVersion();
81125
break;
82126
default:
83-
return Future.value(
84-
ServiceExtensionResponse.error(
85-
ServiceExtensionResponse.extensionError,
86-
'Method $method does not exist',
87-
),
127+
return ServiceExtensionResponse.error(
128+
ServiceExtensionResponse.extensionError,
129+
'Method $method does not exist',
88130
);
89131
}
90-
return Future.value(
91-
ServiceExtensionResponse.result(responseJson),
92-
);
132+
return ServiceExtensionResponse.result(responseJson);
93133
} catch (errorMessage) {
94-
return Future.value(
95-
ServiceExtensionResponse.error(
96-
ServiceExtensionResponse.invalidParams,
97-
errorMessage.toString(),
98-
),
134+
return ServiceExtensionResponse.error(
135+
ServiceExtensionResponse.invalidParams,
136+
errorMessage.toString(),
99137
);
100138
}
101139
}
@@ -134,19 +172,26 @@ String _setHttpEnableTimelineLogging(Map<String, String> parameters) {
134172
return _success();
135173
}
136174

137-
String _getHttpProfileRequest(Map<String, String> parameters) {
175+
Future<String> _getHttpProfileRequest(Map<String, String> parameters) async {
138176
if (!parameters.containsKey('id')) {
139177
throw _missingArgument('id');
140178
}
141-
String id = parameters['id']!;
179+
final id = parameters['id']!;
180+
final request;
181+
if (id.startsWith('from_package/')) {
182+
final profileMap = getHttpClientProfilingData()
183+
.elementAtOrNull(int.parse(id.substring('from_package/'.length)) - 1);
184+
request = profileMap == null
185+
? null
186+
: await _createHttpProfileRequestFromProfileMap(profileMap, ref: false);
187+
} else {
188+
request = HttpProfiler.getHttpProfileRequest(id)?.toJson(ref: false);
189+
}
142190

143-
final request = HttpProfiler.getHttpProfileRequest(id);
144191
if (request == null) {
145192
throw "Unable to find request with id: '$id'";
146193
}
147-
return json.encode(
148-
request.toJson(ref: false),
149-
);
194+
return json.encode(request);
150195
}
151196

152197
String _socketProfilingEnabled(Map<String, String> parameters) {

0 commit comments

Comments
 (0)