Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Offline support for Network page #8332

Open
wants to merge 35 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
fe11d5b
added initial implementation
hrajwade96 Sep 21, 2024
6c140b4
adding constants file
hrajwade96 Sep 29, 2024
0c1f414
updated NEXT_RELEASE_NOTES.md
hrajwade96 Sep 30, 2024
e7eeecb
Revert "updated NEXT_RELEASE_NOTES.md"
hrajwade96 Sep 30, 2024
c5ec6f6
used constants, added util for header size calc, added params
hrajwade96 Oct 2, 2024
131cde6
Merge branch 'master' into network_screen_offline_support
hrajwade96 Oct 2, 2024
2a9c4cb
param renamed, used _log
hrajwade96 Oct 2, 2024
4f473be
Merge remote-tracking branch 'origin/network_screen_offline_support' …
hrajwade96 Oct 2, 2024
ae58738
added copyright header
hrajwade96 Oct 2, 2024
2bfbe1c
setup changes implemented
hrajwade96 Oct 3, 2024
857cfbe
put class name in square brackets
hrajwade96 Oct 3, 2024
7150436
added isNullOrEmpty check
hrajwade96 Oct 3, 2024
da11a67
added exit offline cta, hiding other controls, removed json string
hrajwade96 Oct 4, 2024
941ec88
fix for request selection
hrajwade96 Oct 4, 2024
852b144
comments resolved
hrajwade96 Oct 8, 2024
433af38
removing getFullRequestData section
hrajwade96 Oct 8, 2024
4644b00
using updateOrAddAll for setting data
hrajwade96 Oct 8, 2024
6fd98d0
Wrapped with OfflineAwareControls, removed if-else.
hrajwade96 Oct 8, 2024
665ea0d
removed addAutoDisposeListener as we are using OfflineAwareControls
hrajwade96 Oct 8, 2024
b6df572
removed try-catch
hrajwade96 Oct 8, 2024
be63db4
code refactoring
hrajwade96 Oct 9, 2024
91505b5
added enum
hrajwade96 Oct 9, 2024
0715379
code refactoring, reverting changes on network service
hrajwade96 Oct 10, 2024
ade8b5f
using values from enum
hrajwade96 Oct 10, 2024
f21a4f6
delegating toJson using extension methods, code refactoring
hrajwade96 Oct 23, 2024
454ca92
socket data de-serialisation changes
hrajwade96 Oct 27, 2024
b7b9679
Merge branch 'master' into network_screen_offline_support
hrajwade96 Oct 27, 2024
ac726e8
used factory constructor, made enum private
hrajwade96 Nov 4, 2024
2ea3044
reorder params, used isEmpty
hrajwade96 Nov 4, 2024
e01bc3c
added tests, minor fixes
hrajwade96 Nov 17, 2024
e7b5c90
removed repetitive expect statements
hrajwade96 Nov 21, 2024
6ab0884
Merge remote-tracking branch 'upstream/master' into network_screen_of…
hrajwade96 Nov 22, 2024
4f31b92
minor fix
hrajwade96 Nov 22, 2024
04c8b41
added timelineMicrosOffset to offline data
hrajwade96 Nov 24, 2024
ab8c519
added timelineMicrosOffset to tests
hrajwade96 Nov 24, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import 'dart:convert';

import '../../screens/network/utils/http_utils.dart';
import '../../shared/http/http_request_data.dart';
import '../../shared/primitives/utils.dart';
import 'constants.dart';
Expand Down Expand Up @@ -131,7 +132,7 @@ class HarDataEntry {
NetworkEventKeys.text.name: e.requestBody,
},
NetworkEventKeys.headersSize.name:
_calculateHeadersSize(e.requestHeaders),
calculateHeadersSize(e.requestHeaders),
NetworkEventKeys.bodySize.name: _calculateBodySize(e.requestBody),
},
// Response
Expand All @@ -150,7 +151,7 @@ class HarDataEntry {
},
NetworkEventKeys.redirectURL.name: '',
NetworkEventKeys.headersSize.name:
_calculateHeadersSize(e.responseHeaders),
calculateHeadersSize(e.responseHeaders),
NetworkEventKeys.bodySize.name: _calculateBodySize(e.responseBody),
},
// Cache
Expand Down Expand Up @@ -263,27 +264,6 @@ class HarDataEntry {
}
}

int _calculateHeadersSize(Map<String, Object?>? headers) {
if (headers == null) return -1;

// Combine headers into a single string with CRLF endings
String headersString = headers.entries.map((entry) {
final key = entry.key;
var value = entry.value;
// If the value is a List, join it with a comma
if (value is List<String>) {
value = value.join(', ');
}
return '$key: $value\r\n';
}).join();

// Add final CRLF to indicate end of headers
headersString += '\r\n';

// Calculate the byte length of the headers string
return utf8.encode(headersString).length;
}

int _calculateBodySize(String? requestBody) {
if (requestBody.isNullOrEmpty) {
return 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ import 'dart:convert';

import 'package:devtools_app_shared/utils.dart';
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import 'package:vm_service/vm_service.dart';

import '../../shared/config_specific/import_export/import_export.dart';
import '../../shared/config_specific/logger/allowed_error.dart';
import '../../shared/globals.dart';
import '../../shared/http/http_request_data.dart';
import '../../shared/http/http_service.dart' as http_service;
import '../../shared/offline_data.dart';
import '../../shared/primitives/utils.dart';
import '../../shared/ui/filter.dart';
import '../../shared/ui/search.dart';
Expand All @@ -22,6 +24,9 @@ import 'har_network_data.dart';
import 'network_model.dart';
import 'network_screen.dart';
import 'network_service.dart';
import 'offline_network_data.dart';

final _log = Logger('http_request_data');

/// Different types of Network Response which can be used to visualise response
/// on Response tab
Expand Down Expand Up @@ -49,10 +54,12 @@ class NetworkController extends DisposableController
with
SearchControllerMixin<NetworkRequest>,
FilterControllerMixin<NetworkRequest>,
OfflineScreenControllerMixin,
AutoDisposeControllerMixin {
NetworkController() {
_networkService = NetworkService(this);
_currentNetworkRequests = CurrentNetworkRequests();
_initHelper();
addAutoDisposeListener(
_currentNetworkRequests,
_filterAndRefreshSearchMatches,
Expand Down Expand Up @@ -160,6 +167,58 @@ class NetworkController extends DisposableController
@visibleForTesting
bool get isPolling => _pollingTimer != null;

void _initHelper() async {
try {
hrajwade96 marked this conversation as resolved.
Show resolved Hide resolved
if (offlineDataController.showingOfflineData.value == true) {
kenzieschmoll marked this conversation as resolved.
Show resolved Hide resolved
await maybeLoadOfflineData(
NetworkScreen.id,
createData: (json) => OfflineNetworkData.fromJson(json),
shouldLoad: (data) => !data.isEmpty,
loadData: (data) => loadOfflineData(data),
);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the code after this if statement should be put in an else block

Copy link
Contributor Author

@hrajwade96 hrajwade96 Oct 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not using else was an oversight, added else block now, and also now there is no code outside.

cancelListeners();
hrajwade96 marked this conversation as resolved.
Show resolved Hide resolved
if (!offlineDataController.showingOfflineData.value) {
kenzieschmoll marked this conversation as resolved.
Show resolved Hide resolved
unawaited(startRecording());
kenzieschmoll marked this conversation as resolved.
Show resolved Hide resolved
debugPrint('started recording');
kenzieschmoll marked this conversation as resolved.
Show resolved Hide resolved
addAutoDisposeListener(
serviceConnection.serviceManager.isolateManager.mainIsolate,
() {
if (serviceConnection
.serviceManager.isolateManager.mainIsolate.value !=
null) {
unawaited(startRecording());
}
},
);
}
} catch (e) {
_log.shout('Could not load offline data: $e');
}
}

Future<void> loadOfflineData(OfflineNetworkData offlineData) async {
// Set filtered data to the requests available in offline data.
filteredData
..clear()
..addAll(offlineData.requests);
kenzieschmoll marked this conversation as resolved.
Show resolved Hide resolved

// If a selectedRequestId is available, select it in offline mode.
if (offlineData.selectedRequestId != null) {
final selected = offlineData.getRequest(offlineData.selectedRequestId!);
if (selected != null) {
selectedRequest.value = selected;
if (selectedRequest.value is DartIOHttpRequestData) {
unawaited(
(selectedRequest.value as DartIOHttpRequestData)
.getFullRequestData(),
);
}
hrajwade96 marked this conversation as resolved.
Show resolved Hide resolved
resetDropDown();
}
}
}

@visibleForTesting
void processNetworkTrafficHelper(
List<SocketStatistic> sockets,
Expand Down Expand Up @@ -388,6 +447,19 @@ class NetworkController extends DisposableController
}
}

@override
OfflineScreenData prepareOfflineScreenData() {
final offlineData = OfflineNetworkData(
requests: filteredData.value.whereType<DartIOHttpRequestData>().toList(),
hrajwade96 marked this conversation as resolved.
Show resolved Hide resolved
selectedRequestId: selectedRequest.value?.id,
);

return OfflineScreenData(
screenId: NetworkScreen.id,
data: offlineData.toJson(),
);
}

Future<void> _fetchFullDataBeforeExport() => Future.wait(
filteredData.value
.whereType<DartIOHttpRequestData>()
Expand Down
114 changes: 57 additions & 57 deletions packages/devtools_app/lib/src/screens/network/network_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -123,19 +123,6 @@ class _NetworkScreenBodyState extends State<NetworkScreenBody>
void didChangeDependencies() {
super.didChangeDependencies();
if (!initController()) return;
kenzieschmoll marked this conversation as resolved.
Show resolved Hide resolved
unawaited(controller.startRecording());

cancelListeners();

addAutoDisposeListener(
serviceConnection.serviceManager.isolateManager.mainIsolate,
() {
if (serviceConnection.serviceManager.isolateManager.mainIsolate.value !=
null) {
unawaited(controller.startRecording());
}
},
);
}

@override
Expand All @@ -150,7 +137,10 @@ class _NetworkScreenBodyState extends State<NetworkScreenBody>
Widget build(BuildContext context) {
return Column(
children: [
_NetworkProfilerControls(controller: controller),
_NetworkProfilerControls(
kenzieschmoll marked this conversation as resolved.
Show resolved Hide resolved
controller: controller,
offline: offlineDataController.showingOfflineData.value,
),
const SizedBox(height: intermediateSpacing),
Expanded(
child: _NetworkProfilerBody(controller: controller),
Expand All @@ -165,12 +155,15 @@ class _NetworkScreenBodyState extends State<NetworkScreenBody>
class _NetworkProfilerControls extends StatefulWidget {
const _NetworkProfilerControls({
required this.controller,
required this.offline,
});

static const _includeTextWidth = 810.0;

final NetworkController controller;

final bool offline;

@override
State<_NetworkProfilerControls> createState() =>
_NetworkProfilerControlsState();
Expand All @@ -187,7 +180,7 @@ class _NetworkProfilerControlsState extends State<_NetworkProfilerControls>
@override
void initState() {
super.initState();

addAutoDisposeListener(offlineDataController.showingOfflineData);
hrajwade96 marked this conversation as resolved.
Show resolved Hide resolved
_recording = widget.controller.recordingNotifier.value;
addAutoDisposeListener(widget.controller.recordingNotifier, () {
setState(() {
Expand All @@ -214,48 +207,55 @@ class _NetworkProfilerControlsState extends State<_NetworkProfilerControls>
final hasRequests = _filteredRequests.isNotEmpty;
return Row(
children: [
StartStopRecordingButton(
recording: _recording,
onPressed: () async =>
await widget.controller.togglePolling(!_recording),
tooltipOverride: _recording
? 'Stop recording network traffic'
: 'Resume recording network traffic',
minScreenWidthForTextBeforeScaling: double.infinity,
gaScreen: gac.network,
gaSelection: _recording ? gac.pause : gac.resume,
),
const SizedBox(width: denseSpacing),
ClearButton(
minScreenWidthForTextBeforeScaling:
_NetworkProfilerControls._includeTextWidth,
gaScreen: gac.network,
gaSelection: gac.clear,
onPressed: widget.controller.clear,
),
const SizedBox(width: defaultSpacing),
DownloadButton(
minScreenWidthForTextBeforeScaling:
_NetworkProfilerControls._includeTextWidth,
onPressed: widget.controller.exportAsHarFile,
gaScreen: gac.network,
gaSelection: gac.NetworkEvent.downloadAsHar.name,
),
const SizedBox(width: defaultSpacing),
const Expanded(child: SizedBox()),
// TODO(kenz): fix focus issue when state is refreshed
SearchField<NetworkController>(
searchController: widget.controller,
searchFieldEnabled: hasRequests,
searchFieldWidth: screenWidth <= MediaSize.xs
? defaultSearchFieldWidth
: wideSearchFieldWidth,
),
const SizedBox(width: denseSpacing),
DevToolsFilterButton(
onPressed: _showFilterDialog,
isFilterActive: _filteredRequests.length != _requests.length,
),
if (widget.offline)
Padding(
padding: const EdgeInsets.only(right: defaultSpacing),
child: ExitOfflineButton(gaScreen: gac.cpuProfiler),
)
else ...[
StartStopRecordingButton(
recording: _recording,
onPressed: () async =>
await widget.controller.togglePolling(!_recording),
tooltipOverride: _recording
? 'Stop recording network traffic'
: 'Resume recording network traffic',
minScreenWidthForTextBeforeScaling: double.infinity,
gaScreen: gac.network,
gaSelection: _recording ? gac.pause : gac.resume,
),
const SizedBox(width: denseSpacing),
ClearButton(
minScreenWidthForTextBeforeScaling:
_NetworkProfilerControls._includeTextWidth,
gaScreen: gac.network,
gaSelection: gac.clear,
onPressed: widget.controller.clear,
),
const SizedBox(width: defaultSpacing),
DownloadButton(
minScreenWidthForTextBeforeScaling:
_NetworkProfilerControls._includeTextWidth,
onPressed: widget.controller.exportAsHarFile,
gaScreen: gac.network,
gaSelection: gac.NetworkEvent.downloadAsHar.name,
),
const SizedBox(width: defaultSpacing),
const Expanded(child: SizedBox()),
// TODO(kenz): fix focus issue when state is refreshed
SearchField<NetworkController>(
searchController: widget.controller,
searchFieldEnabled: hasRequests,
searchFieldWidth: screenWidth <= MediaSize.xs
? defaultSearchFieldWidth
: wideSearchFieldWidth,
),
const SizedBox(width: denseSpacing),
DevToolsFilterButton(
onPressed: _showFilterDialog,
isFilterActive: _filteredRequests.length != _requests.length,
),
hrajwade96 marked this conversation as resolved.
Show resolved Hide resolved
],
],
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright 2024 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 'package:devtools_shared/devtools_shared.dart';

import '../../shared/http/http_request_data.dart';
import '../../shared/primitives/utils.dart';
import 'network_model.dart';

/// Class to encapsulate offline data for the [NetworkController].
kenzieschmoll marked this conversation as resolved.
Show resolved Hide resolved
/// It is responsible for serializing and deserializing offline network data.
class OfflineNetworkData with Serializable {
OfflineNetworkData({
required this.requests,
this.selectedRequestId,
this.recording = false,
});

/// Creates an instance of [OfflineNetworkData] from a JSON map.
factory OfflineNetworkData.fromJson(Map<String, dynamic> json) {
final List<dynamic> requestsJson = json['requests'] ?? [];
final requests = requestsJson
hrajwade96 marked this conversation as resolved.
Show resolved Hide resolved
.map(
(e) => DartIOHttpRequestData.fromJson(
e as Map<String, dynamic>,
null,
null,
),
)
.toList();

return OfflineNetworkData(
requests: requests,
selectedRequestId: json['selectedRequestId'] as String?,
recording: json['recording'] as bool? ?? false,
);
}
bool get isEmpty => requests.isNullOrEmpty;

/// List of current [DartIOHttpRequestData] network requests.
final List<DartIOHttpRequestData> requests;

/// Get a request by matching its `id` field.
// Temporarily added to check selection in the filtered requests data,
// until we have current requests data in place
NetworkRequest? getRequest(String id) {
// Search through the list of requests and return the one with the matching ID.
return requests.firstWhere(
(request) => request.id == id,
);
}

/// The ID of the currently selected request, if any.
final String? selectedRequestId;

/// Whether the recording state is enabled.
final bool recording;
kenzieschmoll marked this conversation as resolved.
Show resolved Hide resolved

/// Converts the current offline data to a JSON format.
@override
Map<String, dynamic> toJson() {
return {
'requests': requests.map((request) => request.toJson()).toList(),
'selectedRequestId': selectedRequestId,
hrajwade96 marked this conversation as resolved.
Show resolved Hide resolved
'recording': recording,
};
}
}
Loading