Skip to content

Collect heartbeat in android #3120

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

Merged
merged 9 commits into from
Nov 25, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions firebase-common/firebase-common.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ dependencies {
testImplementation "com.google.truth:truth:$googleTruthVersion"
testImplementation 'org.mockito:mockito-core:2.25.0'
testImplementation 'androidx.test:core:1.2.0'
testImplementation 'org.json:json:20210307'

annotationProcessor 'com.google.auto.value:auto-value:1.6.5'

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,8 @@ public void testInvokeAfterDeleteThrows() throws Exception {
int modifiers = method.getModifiers();
if (Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers)) {
try {
if (!allowedToCallAfterDelete.contains(method.getName())) {
if (!allowedToCallAfterDelete.contains(method.getName())
&& !(method.getName().contains("$"))) {
invokePublicInstanceMethodWithDefaultValues(firebaseApp, method);
fail("Method expected to throw, but didn't " + method.getName());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import com.google.firebase.components.ComponentRuntime;
import com.google.firebase.components.Lazy;
import com.google.firebase.events.Publisher;
import com.google.firebase.heartbeatinfo.DefaultHeartBeatController;
import com.google.firebase.inject.Provider;
import com.google.firebase.internal.DataCollectionConfigStorage;
import java.nio.charset.Charset;
Expand Down Expand Up @@ -114,7 +115,7 @@ public class FirebaseApp {
private final AtomicBoolean automaticResourceManagementEnabled = new AtomicBoolean(false);
private final AtomicBoolean deleted = new AtomicBoolean();
private final Lazy<DataCollectionConfigStorage> dataCollectionConfigStorage;

private final Provider<DefaultHeartBeatController> defaultHeartBeatController;
private final List<BackgroundStateChangeListener> backgroundStateChangeListeners =
new CopyOnWriteArrayList<>();
private final List<FirebaseAppLifecycleListener> lifecycleListeners =
Expand Down Expand Up @@ -200,6 +201,7 @@ public static FirebaseApp getInstance(@NonNull String name) {
synchronized (LOCK) {
FirebaseApp firebaseApp = INSTANCES.get(normalize(name));
if (firebaseApp != null) {
firebaseApp.defaultHeartBeatController.get().registerHeartBeat();
return firebaseApp;
}

Expand Down Expand Up @@ -433,6 +435,14 @@ protected FirebaseApp(Context applicationContext, String name, FirebaseOptions o
applicationContext,
getPersistenceKey(),
componentRuntime.get(Publisher.class)));
defaultHeartBeatController = componentRuntime.getProvider(DefaultHeartBeatController.class);

addBackgroundStateChangeListener(
background -> {
if (!background) {
defaultHeartBeatController.get().registerHeartBeat();
}
});
}

private void checkNotDeleted() {
Expand Down Expand Up @@ -582,6 +592,7 @@ private void initializeAllApis() {
} else {
Log.i(LOG_TAG, "Device unlocked: initializing all Firebase APIs for app " + getName());
componentRuntime.initializeEagerComponents(isDefaultApp());
defaultHeartBeatController.get().registerHeartBeat();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import android.os.Build;
import com.google.firebase.components.Component;
import com.google.firebase.components.ComponentRegistrar;
import com.google.firebase.heartbeatinfo.DefaultHeartBeatController;
import com.google.firebase.heartbeatinfo.DefaultHeartBeatInfo;
import com.google.firebase.platforminfo.DefaultUserAgentPublisher;
import com.google.firebase.platforminfo.KotlinDetector;
Expand All @@ -44,6 +45,7 @@ public List<Component<?>> getComponents() {
List<Component<?>> result = new ArrayList<>();
result.add(DefaultUserAgentPublisher.component());
result.add(DefaultHeartBeatInfo.component());
result.add(DefaultHeartBeatController.component());
result.add(
LibraryVersionComponent.create(FIREBASE_ANDROID, String.valueOf(Build.VERSION.SDK_INT)));
result.add(LibraryVersionComponent.create(FIREBASE_COMMON, BuildConfig.VERSION_NAME));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.heartbeatinfo;

import android.content.Context;
import android.util.Base64;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import androidx.core.os.UserManagerCompat;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.FirebaseApp;
import com.google.firebase.components.Component;
import com.google.firebase.components.Dependency;
import com.google.firebase.inject.Provider;
import com.google.firebase.platforminfo.UserAgentPublisher;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.json.JSONArray;
import org.json.JSONObject;

/** Provides a function to store heartbeats and another function to retrieve stored heartbeats. */
public class DefaultHeartBeatController implements HeartBeatController {

private final Provider<HeartBeatInfoStorage> storageProvider;

private Context applicationContext;

private final Provider<UserAgentPublisher> userAgentProvider;

private final Set<HeartBeatConsumer> consumers;

private final Executor backgroundExecutor;

private static final ThreadFactory THREAD_FACTORY =
r -> new Thread(r, "heartbeat-information-executor");

public Task<Void> registerHeartBeat() {
if (consumers.size() <= 0) {
return Tasks.forResult(null);
}
boolean inDirectBoot = !UserManagerCompat.isUserUnlocked(applicationContext);
if (inDirectBoot) {
return Tasks.forResult(null);
}

return Tasks.call(
backgroundExecutor,
() -> {
synchronized (DefaultHeartBeatController.this) {
this.storageProvider
.get()
.storeHeartBeat(
System.currentTimeMillis(), this.userAgentProvider.get().getUserAgent());
}

return null;
});
}

@Override
public Task<String> getHeartBeatsHeader() {
boolean inDirectBoot = !UserManagerCompat.isUserUnlocked(applicationContext);
if (inDirectBoot) {
return Tasks.forResult("");
}
return Tasks.call(
backgroundExecutor,
() -> {
synchronized (DefaultHeartBeatController.this) {
HeartBeatInfoStorage storage = this.storageProvider.get();
List<HeartBeatResult> allHeartBeats = storage.getAllHeartBeats();
storage.deleteAllHeartBeats();
JSONArray array = new JSONArray();
for (int i = 0; i < allHeartBeats.size(); i++) {
HeartBeatResult result = allHeartBeats.get(i);
JSONObject obj = new JSONObject();
obj.put("agent", result.getUserAgent());
obj.put("date", result.getUsedDates());
array.put(obj);
}
JSONObject output = new JSONObject();
output.put("heartbeats", array);
output.put("version", "2");
return Base64.encodeToString(output.toString().getBytes(), Base64.DEFAULT);
}
});
}

private DefaultHeartBeatController(
Context context,
String persistenceKey,
Set<HeartBeatConsumer> consumers,
Provider<UserAgentPublisher> userAgentProvider) {
this(
() -> new HeartBeatInfoStorage(context, persistenceKey),
consumers,
new ThreadPoolExecutor(
0, 1, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), THREAD_FACTORY),
userAgentProvider);
this.applicationContext = context;
}

@VisibleForTesting
DefaultHeartBeatController(
Provider<HeartBeatInfoStorage> testStorage,
Set<HeartBeatConsumer> consumers,
Executor executor,
Provider<UserAgentPublisher> userAgentProvider) {
storageProvider = testStorage;
this.consumers = consumers;
this.backgroundExecutor = executor;
this.userAgentProvider = userAgentProvider;
}

public static @NonNull Component<DefaultHeartBeatController> component() {
return Component.builder(DefaultHeartBeatController.class, HeartBeatController.class)
.add(Dependency.required(Context.class))
.add(Dependency.required(FirebaseApp.class))
.add(Dependency.setOf(HeartBeatConsumer.class))
.add(Dependency.requiredProvider(UserAgentPublisher.class))
.factory(
c ->
new DefaultHeartBeatController(
c.get(Context.class),
c.get(FirebaseApp.class).getPersistenceKey(),
c.setOf(HeartBeatConsumer.class),
c.getProvider(UserAgentPublisher.class)))
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,10 @@
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.FirebaseApp;
import com.google.firebase.components.Component;
import com.google.firebase.components.Dependency;
import com.google.firebase.components.Lazy;
import com.google.firebase.inject.Provider;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
Expand All @@ -44,11 +40,12 @@ public class DefaultHeartBeatInfo implements HeartBeatInfo {
private static final ThreadFactory THREAD_FACTORY =
r -> new Thread(r, "heartbeat-information-executor");

private DefaultHeartBeatInfo(Context context, Set<HeartBeatConsumer> consumers) {
private DefaultHeartBeatInfo(
Context context, String persistenceKey, Set<HeartBeatConsumer> consumers) {
// It is very important the executor is single threaded as otherwise it would lead to
// race conditions.
this(
new Lazy<>(() -> HeartBeatInfoStorage.getInstance(context)),
() -> new HeartBeatInfoStorage(context, persistenceKey),
consumers,
new ThreadPoolExecutor(
0, 1, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), THREAD_FACTORY));
Expand Down Expand Up @@ -80,64 +77,17 @@ private DefaultHeartBeatInfo(Context context, Set<HeartBeatConsumer> consumers)
return HeartBeat.NONE;
}

@Override
public Task<List<HeartBeatResult>> getAndClearStoredHeartBeatInfo() {
return Tasks.call(
backgroundExecutor,
() -> {
ArrayList<HeartBeatResult> heartBeatResults = new ArrayList<>();
boolean shouldSendGlobalHeartBeat = false;
HeartBeatInfoStorage storage = storageProvider.get();
List<SdkHeartBeatResult> sdkHeartBeatResults = storage.getStoredHeartBeats(true);
long lastGlobalHeartBeat = storage.getLastGlobalHeartBeat();
HeartBeat heartBeat;
for (SdkHeartBeatResult sdkHeartBeatResult : sdkHeartBeatResults) {
shouldSendGlobalHeartBeat =
HeartBeatInfoStorage.isSameDateUtc(
lastGlobalHeartBeat, sdkHeartBeatResult.getMillis());
if (shouldSendGlobalHeartBeat) {
heartBeat = HeartBeat.COMBINED;
} else {
heartBeat = HeartBeat.SDK;
}
if (shouldSendGlobalHeartBeat) {
lastGlobalHeartBeat = sdkHeartBeatResult.getMillis();
}
heartBeatResults.add(
HeartBeatResult.create(
sdkHeartBeatResult.getSdkName(), sdkHeartBeatResult.getMillis(), heartBeat));
}
if (lastGlobalHeartBeat > 0) {
storage.updateGlobalHeartBeat(lastGlobalHeartBeat);
}
return heartBeatResults;
});
}

@Override
public Task<Void> storeHeartBeatInfo(@NonNull String heartBeatTag) {
if (consumers.size() <= 0) {
return Tasks.forResult(null);
}
return Tasks.call(
backgroundExecutor,
() -> {
long presentTime = System.currentTimeMillis();
boolean shouldSendSdkHB =
storageProvider.get().shouldSendSdkHeartBeat(heartBeatTag, presentTime);
if (shouldSendSdkHB) {
storageProvider.get().storeHeartBeatInformation(heartBeatTag, presentTime);
}
return null;
});
}

public static @NonNull Component<HeartBeatInfo> component() {
return Component.builder(HeartBeatInfo.class)
.add(Dependency.required(Context.class))
.add(Dependency.required(FirebaseApp.class))
.add(Dependency.setOf(HeartBeatConsumer.class))
.factory(
c -> new DefaultHeartBeatInfo(c.get(Context.class), c.setOf(HeartBeatConsumer.class)))
c ->
new DefaultHeartBeatInfo(
c.get(Context.class),
c.get(FirebaseApp.class).getPersistenceKey(),
c.setOf(HeartBeatConsumer.class)))
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.heartbeatinfo;

import com.google.android.gms.tasks.Task;

/**
* Class provides information about heartbeats.
*
* <p>This exposes a function which returns a base-64 encoded string based on the stored heartbeats.
*/
public interface HeartBeatController {
Task<String> getHeartBeatsHeader();
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
package com.google.firebase.heartbeatinfo;

import androidx.annotation.NonNull;
import com.google.android.gms.tasks.Task;
import java.util.List;

/**
* Class provides information about heartbeats.
Expand Down Expand Up @@ -49,10 +47,4 @@ public int getCode() {

@NonNull
HeartBeat getHeartBeatCode(@NonNull String heartBeatTag);

@NonNull
Task<Void> storeHeartBeatInfo(@NonNull String heartBeatTag);

@NonNull
Task<List<HeartBeatResult>> getAndClearStoredHeartBeatInfo();
}
Loading