Skip to content

Commit

Permalink
refactor(performance)!: rework as part of #6979 (#7391)
Browse files Browse the repository at this point in the history
Co-authored-by: Elliot Hesp <[email protected]>
Co-authored-by: Salakar <[email protected]>
  • Loading branch information
3 people committed Dec 7, 2021
1 parent e62a003 commit e5fdc0e
Show file tree
Hide file tree
Showing 59 changed files with 2,534 additions and 1,432 deletions.
6 changes: 1 addition & 5 deletions docs/performance/overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,4 @@ $ flutter run

## Next Steps

Once installed, you're ready to start using Performance Monitoring in your Flutter Project.

> Additional documentation will be available once the Firebase Performance Monitoring plugin update lands as part of the [FlutterFire roadmap](https://github.com/FirebaseExtended/flutterfire/issues/2582).
<!-- View the [Usage documentation](usage.mdx) to get started. -->
Once installed, head over to the [Usage](./usage.mdx) documentation to learn more.
123 changes: 122 additions & 1 deletion docs/performance/usage.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,125 @@ title: Performance Monitoring
sidebar_label: Usage
---

Performance Monitoring usage
To start using Performance Monitoring for Firebase package within your project, import it at the top of your project files:

```dart
import 'package:firebase_performance/firebase_performance.dart';
```

Before using Performance Monitoring, you must first have ensured you have [initialized FlutterFire](overview#initializing-flutterfire).

To create a new Performance Monitoring for Firebase instance, call the [`instance`](!firebase_performance.FirebasePerformance.instance) getter on [`FirebaseFunctions`](!firebase_performance.FirebasePerformance):

```dart
FirebasePerformance performance = FirebasePerformance.instance;
```

By default, this allows you to interact with Performance Monitoring using the default Firebase App.

## Automatic Tracing

When installed, Android & iOS will automatically report metrics such as application start time, network requests and other useful data.

## Custom tracing

You can create your own traces to monitor performance data associated with specific code in your app. With a custom code trace, you can
measure how long it takes your app to complete a specific task or a set of tasks, for example loading a set of images or querying your database.

To setup a custom trace, create a new `Trace` instance by calling the `newTrace()` method:

```dart
FirebasePerformance performance = FirebasePerformance.instance;
Trace trace = performance.newTrace('custom-trace');
```

The name provided will appear within the Firebase Console, allowing you to provide unique names for different trace metrics.

When it makes sense to start a trace, call the `start()` method on the `Trace` instance. Once started, you can apply custom metric
data to the trace by calling `setMetric()`:

```dart
Trace trace = performance.newTrace('custom-trace');
await trace.start();
// Set metrics you wish to track
trace.setMetric('sum', 200);
trace.setMetric('time', 342340435);
```

The API also allows you to increment metric data:

```dart
trace.setMetric('sum', 200);
// `sum` will be incremented to 201
trace.incrementMetric('sum', 1);
```

You can also set non-metric related data, such as a user id on the trace by calling the `putAttribute()` method. Note,
each trace supports up to 5 attributes.

```dart
trace.putAttribute('userId', '1234');
```

Once your trace has completed, call the `stop()` method. The data will then be sent to the Firebase Console:

```dart
await trace.stop();
```

## HTTP Request Tracing

The network request traces automatically collected by Performance Monitoring include most network requests for your app.

Some requests might not be reported or you might use a different library to make network requests. In these cases,
you can use the Performance Monitoring API to manually instrument custom network request traces. Custom network request traces
are only supported for Apple and Android platforms. To setup a custom network request trace, see below:

```dart
// Using http package to make a network request
import 'package:http/http.dart' as http;
FirebasePerformance performance = FirebasePerformance.instance;
// Create a `HttpMetric` instance using the URL you're requesting as well as the type of request
String url = 'https://firebase.flutter.dev';
HttpMetric metric = performance
.newHttpMetric(url, HttpMethod.Get);
// You may also assign up to 5 attributes for each trace
metric.putAttribute('foo', 'bar');
// Start the trace
await metric.start();
// Make the request
Uri url = Uri.parse(url);
var response = await http.get(url);
// Set specific headers to be collated
metric.responseContentType = response.headers['Content-Type'];
metric.httpResponseCode = response.statusCode;
metric.responsePayloadSize = response.contentLength;
// Stops the trace. This is when the data is sent to the Firebase server and it will appear in your Firebase console
await metric.stop();
```

## Stop Automatic Data Collection

To stop automatic data collection, you can call `setPerformanceCollectionEnabled` like in the example:

```dart
FirebasePerformance performance = FirebasePerformance.instance;
// Custom data collection is, by default, enabled
bool isEnabled = await performance.isPerformanceCollectionEnabled();
// Set data collection to `false`
await performance.setPerformanceCollectionEnabled(false);
```
1 change: 1 addition & 0 deletions docs/sidebars.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ module.exports = {
],
"Performance Monitoring": [
"performance/overview",
"performance/usage",
toReferenceAPI("firebase_performance"),
toGithubExample("firebase_performance"),
],
Expand Down
23 changes: 23 additions & 0 deletions packages/firebase_performance/firebase_performance/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,26 @@
## UNRELEASED

The Firebase Performance plugin has been heavily reworked to bring it inline with the federated plugin setup along with adding new features,
documentation and updating unit and end-to-end tests.

- General
- Collecting metric and attribute data was previously an asynchronous task. The API has been reworked to better reflect other Firebase APIs, whereby
setting such data is now a synchronous task. Once a trace or HTTP metric stops, data will be sent to the Firebase services in a single operation.
Because of this, breaking changes are introduced to support the new API.

- **`FirebasePerformance`**
- **BREAKING**: `HttpMetric().putAttribute()` method is now synchronous.
- **BREAKING**: `HttpMetric().removeAttribute()` method is now synchronous.
- **BREAKING**: `HttpMetric().getAttribute()` method is now synchronous.
- **BREAKING**: `HttpMetric().getAttributes()` method is now synchronous.
- **BREAKING**: `Trace().putAttribute()` method is now synchronous.
- **BREAKING**: `Trace().removeAttribute()` method is now synchronous.
- **BREAKING**: `Trace().getAttribute()` method is now synchronous.
- **BREAKING**: `Trace().getAttributes()` method is now synchronous.
- **BREAKING**: `Trace().incrementMetric()` method is now synchronous.
- **BREAKING**: `Trace().setMetric()` method is now synchronous.
- **BREAKING**: `Trace().getMetric()` method is now synchronous.

## 0.7.1+5

- Update a dependency to the latest release.
Expand Down
106 changes: 9 additions & 97 deletions packages/firebase_performance/firebase_performance/README.md
Original file line number Diff line number Diff line change
@@ -1,113 +1,25 @@
# Google Performance Monitoring for Firebase
# Firebase Performance Plugin for Flutter

[![pub package](https://img.shields.io/pub/v/firebase_performance.svg)](https://pub.dev/packages/firebase_performance)

A Flutter plugin to use the [Google Performance Monitoring for Firebase API](https://firebase.google.com/docs/perf-mon/).

For Flutter plugins for other Firebase products, see [README.md](https://github.com/FirebaseExtended/flutterfire/blob/master/README.md).

## Usage

To use this plugin, first connect to Firebase by following the instructions for [Android](https://firebase.flutter.dev/docs/installation/android) / [iOS](https://firebase.flutter.dev/docs/installation/ios) / [Web](https://firebase.flutter.dev/docs/installation/web). Then add this plugin by following [these instructions](https://firebase.flutter.dev/docs/performance/overview). See [`example/lib/main.dart`](example/lib/main.dart) for details on the API usage.

You can confirm that Performance Monitoring results appear in the [Firebase Performance Monitoring console](https://console.firebase.google.com/project/_/performance). Results should appear within a few minutes.

> :warning: **Note:** *First Paint* and *First Contentful Paint* metrics of web page load trace will not be collected; automatic network request traces and screen traces will not always be collected for mobile apps.

### Define a Custom Trace

A custom trace is a report of performance data associated with some of the code in your app. To learn more about custom traces, see the [Performance Monitoring overview](https://firebase.google.com/docs/perf-mon/custom-code-traces).

```dart
final Trace myTrace = FirebasePerformance.instance.newTrace("test_trace");
await myTrace.start();
final Item item = cache.fetch("item");
if (item != null) {
await myTrace.incrementMetric("item_cache_hit", 1);
} else {
await myTrace.incrementMetric("item_cache_miss", 1);
}
await myTrace.stop();
```
A Flutter plugin to use the [Firebase Performance API](https://firebase.google.com/docs/perf-mon/).

### Add monitoring for specific network requests (mobile only)
To learn more about Firebase Performance, please visit the [Firebase website](https://firebase.google.com/products/performance)

Performance Monitoring collects network requests automatically. Although this includes most network requests for your app, some might not be reported. To include specific network requests in Performance Monitoring, add the following code to your app:

```dart
class _MetricHttpClient extends BaseClient {
_MetricHttpClient(this._inner);
final Client _inner;
@override
Future<StreamedResponse> send(BaseRequest request) async {
final HttpMetric metric = FirebasePerformance.instance
.newHttpMetric(request.url.toString(), HttpMethod.Get);
await metric.start();
StreamedResponse response;
try {
response = await _inner.send(request);
metric
..responsePayloadSize = response.contentLength
..responseContentType = response.headers['Content-Type']
..requestPayloadSize = request.contentLength
..httpResponseCode = response.statusCode;
} finally {
await metric.stop();
}
[![pub package](https://img.shields.io/pub/v/firebase_performance.svg)](https://pub.dev/packages/firebase_performance)

return response;
}
}
## Getting Started

class _MyAppState extends State<MyApp> {
.
.
.
Future<void> testHttpMetric() async {
final _MetricHttpClient metricHttpClient = _MetricHttpClient(Client());
To get started with Firebase Performance for Flutter, please [see the documentation](https://firebase.flutter.dev/docs/performance/overview).

final Request request =
Request("SEND", Uri.parse("https://www.google.com"));
## Usage

metricHttpClient.send(request);
}
.
.
.
}
```
To use this plugin, please visit the [Firebase Performance Usage documentation](https://firebase.flutter.dev/docs/performance/usage)

## Issues and feedback

Please file FlutterFire specific issues, bugs, or feature requests in our [issue tracker](https://github.com/FirebaseExtended/flutterfire/issues/new).

Plugin issues that are not specific to Flutterfire can be filed in the [Flutter issue tracker](https://github.com/flutter/flutter/issues/new).

## Contribution
Plugin issues that are not specific to FlutterFire can be filed in the [Flutter issue tracker](https://github.com/flutter/flutter/issues/new).

To contribute a change to this plugin,
please review our [contribution guide](https://github.com/FirebaseExtended/flutterfire/blob/master/CONTRIBUTING.md)
and open a [pull request](https://github.com/FirebaseExtended/flutterfire/pulls).

### Testing

The unit test is in `test` directory which you can run using `flutter test`.

The integration test is in `example/test_driver/firebase_performance_e2e.dart` which you can run on an emulator:
```
cd example
flutter drive --target=./test_driver/firebase_performance_e2e.dart
```

To test the web implementation, [download and run ChromeDriver](https://flutter.dev/docs/testing/integration-tests#running-in-a-browser), and then run `flutter_drive`:

```
flutter drive --target=./test_driver/firebase_performance_e2e.dart -d web-server --release --browser-name=chrome --web-port=8080
```
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ android {
implementation 'com.google.firebase:firebase-perf'
implementation 'androidx.annotation:annotation:1.1.0'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}


Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.firebaseperformance">
package="io.flutter.plugins.firebase.performance">

<uses-permission android:name="android.permission.INTERNET" />
<application>
<service android:name="com.google.firebase.components.ComponentDiscoveryService">
<meta-data android:name="com.google.firebase.components:io.flutter.plugins.firebaseperformance.FlutterFirebaseAppRegistrar"
<meta-data android:name="com.google.firebase.components:io.flutter.plugins.firebase.performance.FlutterFirebaseAppRegistrar"
android:value="com.google.firebase.components.ComponentRegistrar" />
</service>
</application>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Copyright 2019 The Chromium Authors. All rights reserved.
// Copyright 2021 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.

package io.flutter.plugins.firebaseperformance;
package io.flutter.plugins.firebase.performance;

import androidx.annotation.Keep;
import com.google.firebase.components.Component;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package io.flutter.plugins.firebaseperformance;
package io.flutter.plugins.firebase.performance;

import com.google.firebase.perf.FirebasePerformance;
import com.google.firebase.perf.metrics.HttpMetric;
Expand Down Expand Up @@ -36,10 +36,10 @@ private static String parseHttpMethod(String httpMethod) {
}
}

private final FirebasePerformancePlugin plugin;
private final FlutterFirebasePerformancePlugin plugin;
private final FirebasePerformance performance;

FlutterFirebasePerformance(FirebasePerformancePlugin plugin) {
FlutterFirebasePerformance(FlutterFirebasePerformancePlugin plugin) {
this.plugin = plugin;
this.performance = FirebasePerformance.getInstance();
}
Expand Down
Loading

0 comments on commit e5fdc0e

Please sign in to comment.