forked from flutter/devtools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_request_data.dart
More file actions
335 lines (282 loc) · 9.75 KB
/
Copy pathhttp_request_data.dart
File metadata and controls
335 lines (282 loc) · 9.75 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
// Copyright 2019 The Chromium Authors. 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 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import 'package:mime/mime.dart';
import 'package:vm_service/vm_service.dart';
import '../../screens/network/network_model.dart';
import '../globals.dart';
import '../primitives/utils.dart';
import 'http.dart';
final _log = Logger('http_request_data');
/// Used to represent an instant event emitted during an HTTP request.
class DartIOHttpInstantEvent {
DartIOHttpInstantEvent._(this._event);
final HttpProfileRequestEvent _event;
String get name => _event.event;
/// The time the instant event was recorded.
DateTime get timestamp => _event.timestamp;
/// The amount of time since the last instant event completed.
TimeRange? get timeRange => _timeRange;
// This is set from within HttpRequestData.
TimeRange? _timeRange;
}
/// An abstraction of an HTTP request made through dart:io.
class DartIOHttpRequestData extends NetworkRequest {
DartIOHttpRequestData(
this._request, {
bool requestFullDataFromVmService = true,
}) {
if (requestFullDataFromVmService && _request.isResponseComplete) {
unawaited(getFullRequestData());
}
}
factory DartIOHttpRequestData.fromJson(
Map<String, Object?> modifiedRequestData,
Map<String, Object?>? requestPostData,
Map<String, Object?>? responseContent,
) {
return DartIOHttpRequestData(
HttpProfileRequestRef.parse(modifiedRequestData)!,
requestFullDataFromVmService: false,
)
.._responseBody = responseContent?['text'].toString()
.._requestBody = requestPostData?['text'].toString();
}
static const _connectionInfoKey = 'connectionInfo';
static const _contentTypeKey = 'content-type';
static const _localPortKey = 'localPort';
HttpProfileRequestRef _request;
bool isFetchingFullData = false;
Future<void> getFullRequestData() async {
try {
if (isFetchingFullData) return; // We are already fetching
isFetchingFullData = true;
final updated = await serviceConnection.serviceManager.service!
.getHttpProfileRequestWrapper(
_request.isolateId,
_request.id.toString(),
);
_request = updated;
final fullRequest = _request as HttpProfileRequest;
_responseBody = utf8.decode(fullRequest.responseBody!);
_requestBody = utf8.decode(fullRequest.requestBody!);
notifyListeners();
} finally {
isFetchingFullData = false;
}
}
static List<Cookie> _parseCookies(List<String>? cookies) {
if (cookies == null) return [];
return cookies.map((cookie) => Cookie.fromSetCookieValue(cookie)).toList();
}
@override
String get id => _request.id;
bool get _hasError => _request.request?.hasError ?? false;
DateTime? get _endTime =>
_hasError ? _request.endTime : _request.response?.endTime;
@override
Duration? get duration {
if (inProgress || !isValid) return null;
// Timestamps are in microseconds
return _endTime!.difference(_request.startTime);
}
/// Whether the request is safe to display in the UI.
///
/// The dart:io HTTP profiling service extensions should never return invalid
/// requests.
bool get isValid => true;
/// A map of general information associated with an HTTP request.
Map<String, dynamic> get general {
return {
'method': _request.method,
'uri': _request.uri.toString(),
if (!didFail) ...{
'connectionInfo': _request.request?.connectionInfo,
'contentLength': _request.request?.contentLength,
},
if (_request.response != null) ...{
'compressionState': _request.response!.compressionState,
'isRedirect': _request.response!.isRedirect,
'persistentConnection': _request.response!.persistentConnection,
'reasonPhrase': _request.response!.reasonPhrase,
'redirects': _request.response!.redirects,
'statusCode': _request.response!.statusCode,
'queryParameters': _request.uri.queryParameters,
},
};
}
@override
String? get contentType {
final headers = responseHeaders;
if (headers == null || headers[_contentTypeKey] == null) {
return null;
}
return headers[_contentTypeKey].toString();
}
@override
String get type {
var mime = contentType;
if (mime == null) return 'http';
// Extract the MIME from `contentType`.
// Example: "[text/html; charset-UTF-8]" --> "text/html"
mime = mime.split(';').first;
if (mime.startsWith('[')) {
mime = mime.substring(1);
}
if (mime.endsWith(']')) {
mime = mime.substring(0, mime.length - 1);
}
return _extensionFromMime(mime);
}
/// Extracts the extension from [mime], with overrides for shortened
/// extensions of common types (e.g., jpe -> jpeg).
String _extensionFromMime(String mime) {
final extension = extensionFromMime(mime);
if (extension == 'jpe') {
return 'jpeg';
}
if (extension == 'htm') {
return 'html';
}
// text/plain -> conf
if (extension == 'conf') {
return 'txt';
}
return extension;
}
@override
String get method => _request.method;
@override
int? get port {
final Map<String, dynamic>? connectionInfo = general[_connectionInfoKey];
return connectionInfo != null ? connectionInfo[_localPortKey] : null;
}
/// True if the HTTP request hasn't completed yet, determined by the lack of
/// an end time in the response data.
@override
bool get inProgress =>
_hasError ? !_request.isRequestComplete : !_request.isResponseComplete;
/// All instant events logged to the timeline for this HTTP request.
List<DartIOHttpInstantEvent> get instantEvents {
if (_instantEvents == null) {
_instantEvents =
_request.events.map((e) => DartIOHttpInstantEvent._(e)).toList();
_recalculateInstantEventTimes();
}
return _instantEvents!;
}
List<DartIOHttpInstantEvent>? _instantEvents;
/// True if either the request or response contained cookies.
bool get hasCookies =>
requestCookies.isNotEmpty || responseCookies.isNotEmpty;
/// A list of all cookies contained within the request headers.
List<Cookie> get requestCookies => _hasError
? []
: DartIOHttpRequestData._parseCookies(_request.request?.cookies);
/// A list of all cookies contained within the response headers.
List<Cookie> get responseCookies =>
DartIOHttpRequestData._parseCookies(_request.response?.cookies);
/// The request headers for the HTTP request.
Map<String, dynamic>? get requestHeaders =>
_hasError ? null : _request.request?.headers;
/// The response headers for the HTTP request.
Map<String, dynamic>? get responseHeaders => _request.response?.headers;
/// The query parameters for the request.
Map<String, dynamic>? get queryParameters => _request.uri.queryParameters;
@override
bool get didFail {
if (status == null) return false;
if (status == 'Error') return true;
try {
final code = int.parse(status!);
// Status codes 400-499 are client errors and 500-599 are server errors.
if (code >= 400) {
return true;
}
} on Exception catch (e, st) {
_log.shout('Could not parse HTTP request status: $status', e, st);
return true;
}
return false;
}
/// Merges the information from another [HttpRequestData] into this instance.
void merge(DartIOHttpRequestData data) {
_request = data._request;
notifyListeners();
}
@override
DateTime? get endTimestamp => _endTime;
@override
DateTime get startTimestamp => _request.startTime;
@override
String? get status =>
_hasError ? 'Error' : _request.response?.statusCode.toString();
@override
String get uri => _request.uri.toString();
String? get responseBody {
if (_request is! HttpProfileRequest) {
return null;
}
final fullRequest = _request as HttpProfileRequest;
try {
if (!_request.isResponseComplete) return null;
if (_responseBody != null) return _responseBody;
_responseBody = utf8.decode(fullRequest.responseBody!);
return _responseBody;
} on FormatException {
return '<binary data>';
}
}
Uint8List? get encodedResponse {
if (!_request.isResponseComplete) return null;
final fullRequest = _request as HttpProfileRequest;
return fullRequest.responseBody;
}
String? _responseBody;
String? get requestBody {
if (_request is! HttpProfileRequest) {
return null;
}
final fullRequest = _request as HttpProfileRequest;
try {
if (!_request.isResponseComplete) return null;
final acceptedMethods = {'POST', 'PUT', 'PATCH'};
if (!acceptedMethods.contains(_request.method)) return null;
if (_requestBody != null) return _requestBody;
if (fullRequest.requestBody == null) return null;
_requestBody = utf8.decode(fullRequest.requestBody!);
return _requestBody;
} on FormatException {
return '<binary data>';
}
}
String? _requestBody;
void _recalculateInstantEventTimes() {
DateTime lastTime = _request.startTime;
for (final instant in instantEvents) {
final instantTime = instant.timestamp;
instant._timeRange = TimeRange()
..start = Duration(microseconds: lastTime.microsecondsSinceEpoch)
..end = Duration(microseconds: instantTime.microsecondsSinceEpoch);
lastTime = instantTime;
}
}
@override
bool operator ==(Object other) {
return other is DartIOHttpRequestData && id == other.id && super == other;
}
@override
int get hashCode => Object.hash(
id,
method,
uri,
contentType,
type,
port,
startTimestamp,
);
}