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

Feat: Measure app start time #1487

Merged
merged 23 commits into from
Jun 11, 2021
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

* Feat: App start up metrics (#1487)
marandaneto marked this conversation as resolved.
Show resolved Hide resolved

## 5.0.1

* Fix: Sources and Javadoc artifacts were mixed up (#1515)
Expand Down
11 changes: 11 additions & 0 deletions sentry-android-core/api/sentry-android-core.api
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,17 @@ public final class io/sentry/android/core/SentryInitProvider : android/content/C
public fun update (Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I
}

public final class io/sentry/android/core/SentryPerformanceProvider : android/content/ContentProvider {
public fun <init> ()V
public fun attachInfo (Landroid/content/Context;Landroid/content/pm/ProviderInfo;)V
public fun delete (Landroid/net/Uri;Ljava/lang/String;[Ljava/lang/String;)I
public fun getType (Landroid/net/Uri;)Ljava/lang/String;
public fun insert (Landroid/net/Uri;Landroid/content/ContentValues;)Landroid/net/Uri;
public fun onCreate ()Z
public fun query (Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;
public fun update (Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I
}

public final class io/sentry/android/core/SystemEventsBreadcrumbsIntegration : io/sentry/Integration, java/io/Closeable {
public fun <init> (Landroid/content/Context;)V
public fun <init> (Landroid/content/Context;Ljava/util/List;)V
Expand Down
6 changes: 6 additions & 0 deletions sentry-android-core/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,11 @@
android:name=".SentryInitProvider"
android:authorities="${applicationId}.SentryInitProvider"
android:exported="false"/>

<provider
android:name=".SentryPerformanceProvider"
android:authorities="${applicationId}.SentryPerformanceProvider"
android:initOrder="200"
android:exported="false"/>
</application>
</manifest>
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import androidx.annotation.Nullable;
import io.sentry.Breadcrumb;
import io.sentry.IHub;
import io.sentry.ISpan;
import io.sentry.ITransaction;
import io.sentry.Integration;
import io.sentry.Scope;
Expand All @@ -17,6 +18,7 @@
import io.sentry.util.Objects;
import java.io.Closeable;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.WeakHashMap;
import org.jetbrains.annotations.NotNull;
Expand All @@ -26,6 +28,8 @@
public final class ActivityLifecycleIntegration
implements Integration, Closeable, Application.ActivityLifecycleCallbacks {

private static final String NAV_OP = "navigation";

private final @NotNull Application application;
private @Nullable IHub hub;
private @Nullable SentryAndroidOptions options;
Expand All @@ -34,6 +38,11 @@ public final class ActivityLifecycleIntegration

private boolean isAllActivityCallbacksAvailable;

private boolean firstActivityCreated = false;
private boolean firstActivityResumed = false;

private @Nullable ISpan appStartSpan;

// WeakHashMap isn't thread safe but ActivityLifecycleCallbacks is only called from the
// main-thread
private final @NotNull WeakHashMap<Activity, ITransaction> activitiesWithOngoingTransactions =
Expand Down Expand Up @@ -116,8 +125,21 @@ private void startTracing(final @NonNull Activity activity) {
stopPreviousTransactions();

// we can only bind to the scope if there's no running transaction
final ITransaction transaction =
hub.startTransaction(getActivityName(activity), "navigation");
ITransaction transaction;
final String activityName = getActivityName(activity);

final Date appStartTime = AppStartState.getInstance().getAppStartTime();

// in case appStartTime isn't available, we don't create a span for it.
if (firstActivityCreated || appStartTime == null) {
transaction = hub.startTransaction(activityName, NAV_OP);
} else {
// start transaction with app start timestamp
transaction = hub.startTransaction(activityName, NAV_OP, appStartTime);
// start specific span for app start
// TODO: add description cold/warm
marandaneto marked this conversation as resolved.
Show resolved Hide resolved
appStartSpan = transaction.startChild("app.start", appStartTime);
marandaneto marked this conversation as resolved.
Show resolved Hide resolved
}

// lets bind to the scope so other integrations can pick it up
hub.configureScope(
Expand Down Expand Up @@ -186,12 +208,19 @@ public synchronized void onActivityPreCreated(
@Override
public synchronized void onActivityCreated(
final @NonNull Activity activity, final @Nullable Bundle savedInstanceState) {
if (!firstActivityCreated && performanceEnabled) {
// if Activity has savedInstanceState then its a warm start
marandaneto marked this conversation as resolved.
Show resolved Hide resolved
// https://developer.android.com/topic/performance/vitals/launch-time#warm
AppStartState.getInstance().setColdStart(savedInstanceState == null);
}

addBreadcrumb(activity, "created");

// fallback call for API < 29 compatibility, otherwise it happens on onActivityPreCreated
if (!isAllActivityCallbacksAvailable) {
startTracing(activity);
}
firstActivityCreated = true;
}

@Override
Expand All @@ -201,6 +230,17 @@ public synchronized void onActivityStarted(final @NonNull Activity activity) {

@Override
public synchronized void onActivityResumed(final @NonNull Activity activity) {
if (!firstActivityResumed && performanceEnabled) {
// sets App start as finished when the very first activity calls onResume
AppStartState.getInstance().setAppStartEnd();

// finishes app start span
if (appStartSpan != null) {
appStartSpan.finish();
}
firstActivityResumed = true;
}

addBreadcrumb(activity, "resumed");

// fallback call for API < 29 compatibility, otherwise it happens on onActivityPostResumed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ static void init(
readDefaultOptionValues(options, context);

options.addEventProcessor(new DefaultAndroidEventProcessor(context, logger, buildInfoProvider));
options.addEventProcessor(new PerformanceAndroidEventProcessor(options));

options.setTransportGate(new AndroidTransportGate(context, options.getLogger()));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package io.sentry.android.core;

import android.os.SystemClock;
import java.util.Date;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

/** AppStartState holds the state of the App Start metric and appStartTime */
final class AppStartState {
marandaneto marked this conversation as resolved.
Show resolved Hide resolved

private static @NotNull AppStartState instance = new AppStartState();

private @Nullable Long appStartMillis;

private @Nullable Long appStartEndMillis;

/** The type of App start coldStart=true -> Cold start, coldStart=false -> Warm start */
private boolean coldStart;

/** appStart as a Date used in the App's Context */
private @Nullable Date appStartTime;
marandaneto marked this conversation as resolved.
Show resolved Hide resolved

private AppStartState() {}

static @NotNull AppStartState getInstance() {
return instance;
}

@TestOnly
void resetInstance() {
instance = new AppStartState();
}

void setAppStartEnd() {
setAppStartEnd(SystemClock.uptimeMillis());
}

@TestOnly
void setAppStartEnd(final long appStartEndMillis) {
this.appStartEndMillis = appStartEndMillis;
}

@Nullable
Long getAppStartInterval() {
if (appStartMillis == null || appStartEndMillis == null) {
return null;
}
return appStartEndMillis - appStartMillis;
}

boolean isColdStart() {
return coldStart;
}

void setColdStart(final boolean coldStart) {
this.coldStart = coldStart;
}

@Nullable
Date getAppStartTime() {
return appStartTime;
}

synchronized void setAppStartTime(final long appStartMillis, final @NotNull Date appStartTime) {
// method is synchronized because the SDK may by init. on a background thread.
marandaneto marked this conversation as resolved.
Show resolved Hide resolved
if (this.appStartTime != null && this.appStartMillis != null) {
return;
}
this.appStartTime = appStartTime;
this.appStartMillis = appStartMillis;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,6 @@ final class DefaultAndroidEventProcessor implements EventProcessor {
@TestOnly static final String EMULATOR = "emulator";
@TestOnly static final String SIDE_LOADED = "sideLoaded";

// it could also be a parameter and get from Sentry.init(...)
private static final @Nullable Date appStartTime = DateUtils.getCurrentDateTime();

@TestOnly final Context context;

@TestOnly final Future<Map<String, Object>> contextData;
Expand Down Expand Up @@ -299,7 +296,7 @@ private void mergeDebugImages(final @NotNull SentryEvent event) {

private void setAppExtras(final @NotNull App app) {
app.setAppName(getApplicationName());
app.setAppStartTime(appStartTime);
app.setAppStartTime(AppStartState.getInstance().getAppStartTime());
}

@SuppressWarnings("deprecation")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package io.sentry.android.core;

import io.sentry.EventProcessor;
import io.sentry.protocol.MeasurementValue;
import io.sentry.protocol.SentryTransaction;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/** Event Processor responsible for adding Android metrics to transactions */
final class PerformanceAndroidEventProcessor implements EventProcessor {

private final boolean tracingEnabled;

private boolean sentStartMeasurement = false;

// transactions may be started in parallel, locking it so sentStartMeasurement
private final @NotNull Object measurementLock = new Object();

PerformanceAndroidEventProcessor(final @NotNull SentryAndroidOptions options) {
tracingEnabled = options.isTracingEnabled();
}

@Override
public @NotNull SentryTransaction process(
@NotNull SentryTransaction transaction, @Nullable Object hint) {
// the app start metric is sent only once when the 1st transaction happens
// after the app start is collected.
marandaneto marked this conversation as resolved.
Show resolved Hide resolved
synchronized (measurementLock) {
marandaneto marked this conversation as resolved.
Show resolved Hide resolved
if (!sentStartMeasurement && tracingEnabled) {
marandaneto marked this conversation as resolved.
Show resolved Hide resolved
final Long appStartUpInterval = AppStartState.getInstance().getAppStartInterval();
// if appStartUpInterval is null, metrics are not ready to be sent
if (appStartUpInterval != null) {
final MeasurementValue value = new MeasurementValue((float) appStartUpInterval);

final String appStartKey =
AppStartState.getInstance().isColdStart() ? "app_start_cold" : "app_start_warm";

transaction.getMeasurements().put(appStartKey, value);
sentStartMeasurement = true;
}
}
}

return transaction;
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
package io.sentry.android.core;

import android.content.Context;
import android.os.SystemClock;
import io.sentry.DateUtils;
import io.sentry.ILogger;
import io.sentry.OptionsContainer;
import io.sentry.Sentry;
import io.sentry.SentryLevel;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import org.jetbrains.annotations.NotNull;

/** Sentry initialization class */
public final class SentryAndroid {

// static to rely on Class load init.
private static final @NotNull Date appStartTime = DateUtils.getCurrentDateTime();
// SystemClock.uptimeMillis() isn't affected by phone provider or clock changes.
private static final long appStart = SystemClock.uptimeMillis();

private SentryAndroid() {}

/**
Expand Down Expand Up @@ -51,10 +59,14 @@ public static void init(
* @param logger your custom logger that implements ILogger
* @param configuration Sentry.OptionsConfiguration configuration handler
*/
public static void init(
public static synchronized void init(
@NotNull final Context context,
@NotNull ILogger logger,
@NotNull Sentry.OptionsConfiguration<SentryAndroidOptions> configuration) {
// if SentryPerformanceProvider was disabled or removed, we set the App Start when
// the SDK is called.
AppStartState.getInstance().setAppStartTime(appStart, appStartTime);

try {
Sentry.init(
OptionsContainer.create(SentryAndroidOptions.class),
Expand Down
Loading