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

Metrics performance improvements #157

Merged
merged 16 commits into from
Nov 13, 2024
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -400,48 +400,4 @@ public void uniqueEventUpdateAttributes() {

assertEquals(expectedValue, backtraceClient.metrics.getUniqueEvents().getLast().getAttributes().get(expectedKey));
}

@Test
public void uniqueEventEmptyAttributeValueShouldNotOverridePreviousValueOnUpdate() {
konraddysput marked this conversation as resolved.
Show resolved Hide resolved
backtraceClient.metrics.enable(new BacktraceMetricsSettings(credentials, defaultBaseUrl, 0));

String expectedKey = "foo";
String expectedValue = "bar";

backtraceClient.attributes.put(expectedKey, expectedValue);
assertTrue(backtraceClient.metrics.addUniqueEvent(uniqueAttributeName[0]));

assertEquals(uniqueAttributeName[0], backtraceClient.metrics.getUniqueEvents().getLast().getName());
assertEquals(expectedValue, backtraceClient.metrics.getUniqueEvents().getLast().getAttributes().get(expectedKey));

backtraceClient.attributes.put(expectedKey, "");
assertEquals("", backtraceClient.attributes.get(expectedKey));

// Force update
backtraceClient.metrics.send();

assertEquals(expectedValue, backtraceClient.metrics.getUniqueEvents().getLast().getAttributes().get(expectedKey));
}

@Test
public void uniqueEventNullAttributeValueShouldNotOverridePreviousValueOnUpdate() {
backtraceClient.metrics.enable(new BacktraceMetricsSettings(credentials, defaultBaseUrl, 0));

String expectedKey = "foo";
String expectedValue = "bar";

backtraceClient.attributes.put(expectedKey, expectedValue);
assertTrue(backtraceClient.metrics.addUniqueEvent(uniqueAttributeName[0]));

assertEquals(uniqueAttributeName[0], backtraceClient.metrics.getUniqueEvents().getLast().getName());
assertEquals(expectedValue, backtraceClient.metrics.getUniqueEvents().getLast().getAttributes().get(expectedKey));

backtraceClient.attributes.put(expectedKey, null);
assertNull(backtraceClient.attributes.get(expectedKey));

// Force update
backtraceClient.metrics.send();

assertEquals(expectedValue, backtraceClient.metrics.getUniqueEvents().getLast().getAttributes().get(expectedKey));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public void setUp() {
@Test
public void addAttributesSummedEvent() {
SummedEvent summedEvent = new SummedEvent(summedEventName, null);
Map<String, Object> attributes = new HashMap<String, Object>() {{
Map<String, String> attributes = new HashMap<String, String>() {{
put("foo", "bar");
}};
summedEvent.addAttributes(attributes);
Expand All @@ -67,7 +67,7 @@ public void addAttributesSummedEvent() {
@Test
public void addAttributesUniqueEvent() {
UniqueEvent uniqueEvent = new UniqueEvent(uniqueAttributeName[0], null);
Map<String, Object> attributes = new HashMap<String, Object>() {{
Map<String, String> attributes = new HashMap<String, String>() {{
put("foo", "bar");
}};
uniqueEvent.update(BacktraceTimeHelper.getTimestampSeconds(), attributes);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package backtraceio.library.common;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import backtraceio.library.logger.BacktraceLogger;

public class ApplicationMetadataCache {

private static final transient String LOG_TAG = ApplicationMetadataCache.class.getSimpleName();

private static ApplicationMetadataCache instance;

/**
* Cached application name
*/
private String applicationName;

/**
* Cached application version
*/
private String applicationVersion;

/**
* Cached package name
*/
private String packageName;

/**
* Returns current application cache. This instance is a singleton since we can only operate
* in a single application scope.
*
* @param context Application context
* @return Application metadata cache
*/
public static ApplicationMetadataCache getInstance(Context context) {
BartoszLitwiniuk marked this conversation as resolved.
Show resolved Hide resolved
if (instance == null) {
instance = new ApplicationMetadataCache(context);
}
return instance;
perf2711 marked this conversation as resolved.
Show resolved Hide resolved
}
perf2711 marked this conversation as resolved.
Show resolved Hide resolved

private final Context context;

public ApplicationMetadataCache(Context context) {
konraddysput marked this conversation as resolved.
Show resolved Hide resolved
this.context = context;
}

/**
* Retrieves application name from context. The name will be cached over checks
*
* @return application name
*/
public String getApplicationName() {
if (!BacktraceStringHelper.isNullOrEmpty(applicationName)) {
return applicationName;
}

applicationName = context.getApplicationInfo().loadLabel(context.getPackageManager()).toString();
BartoszLitwiniuk marked this conversation as resolved.
Show resolved Hide resolved
return applicationName;
}

/**
* Retrieves application version from the context. If the version name is not defined, the version code will be used instead.
*
* @return current application version.
*/
public String getApplicationVersion() {
if (!BacktraceStringHelper.isNullOrEmpty(applicationVersion)) {
return applicationVersion;
}
try {
PackageInfo info = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
applicationVersion = BacktraceStringHelper.isNullOrEmpty(info.versionName) ? String.valueOf(info.versionCode) : info.versionName;
BartoszLitwiniuk marked this conversation as resolved.
Show resolved Hide resolved

return applicationVersion;
} catch (PackageManager.NameNotFoundException e) {
BacktraceLogger.e(LOG_TAG, "Could not resolve application version", e);
return "";
}
}

/**
* Retrieves package name from the context.
*
* @return current package name.
*/
public String getPackageName() {
if (!BacktraceStringHelper.isNullOrEmpty(packageName)) {
return packageName;
}
packageName = context.getApplicationContext().getPackageName();
BartoszLitwiniuk marked this conversation as resolved.
Show resolved Hide resolved

return packageName;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.UUID;

Expand All @@ -36,6 +36,11 @@
public class DeviceAttributesHelper {
private final Context context;

/*
* Current Device id
*/
private static String uuid;

public DeviceAttributesHelper(Context context) {
this.context = context;
}
Expand All @@ -61,15 +66,17 @@ public HashMap<String, String> getDeviceAttributes(Boolean includeDynamicAttribu
result.put("device.cpu.temperature", String.valueOf(getCpuTemperature()));
result.put("device.is_power_saving_mode", String.valueOf(isPowerSavingMode()));
result.put("device.wifi.status", getWifiStatus().toString());
result.put("system.memory.total", getMaxRamSize());
result.put("system.memory.free", getDeviceFreeRam());
result.put("system.memory.active", getDeviceActiveRam());
result.put("app.storage_used", getAppUsedStorageSize());
result.put("battery.level", String.valueOf(getBatteryLevel()));
result.put("battery.state", getBatteryState().toString());
result.put("cpu.boottime", String.valueOf(java.lang.System.currentTimeMillis() - android.os.SystemClock
.elapsedRealtime()));


ActivityManager.MemoryInfo memoryInfo = getMemoryInformation();
result.put("system.memory.total", Long.toString(memoryInfo.totalMem));
result.put("system.memory.free", Long.toString(memoryInfo.availMem));
result.put("system.memory.active", Long.toString(memoryInfo.totalMem - memoryInfo.availMem));
return result;
}

Expand Down Expand Up @@ -144,14 +151,14 @@ private BluetoothStatus isBluetoothEnabled() {
private float getCpuTemperature() {
Process p;
try {
p = Runtime.getRuntime().exec("cat sys/class/thermal/thermal_zone0/temp");
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

BufferedReader reader = new BufferedReader(new FileReader("/sys/class/thermal/thermal_zone0/temp"));
String line = reader.readLine();
if (line == null) {
return 0.0f;
}
reader.close();

return Float.parseFloat(line) / 1000.0f;
} catch (Exception e) {
return 0.0f;
Expand Down Expand Up @@ -255,33 +262,20 @@ private BatteryState getBatteryState() {
* @return unique device identifier
*/
private String generateDeviceId() {
String androidId = Settings.Secure.getString(this.context.getContentResolver(),
Settings.Secure.ANDROID_ID);

if (TextUtils.isEmpty(androidId)) {
return null;
if (!BacktraceStringHelper.isNullOrEmpty(uuid)) {
return uuid;
}

return UUID.nameUUIDFromBytes(androidId.getBytes()).toString();
}

/**
* Get RAM size of current device
* available from API 16
*
* @return device RAM size
*/
private String getMaxRamSize() {
return Long.toString(getMemoryInformation().totalMem);
}
String androidId = Settings.Secure.getString(this.context.getContentResolver(),
Settings.Secure.ANDROID_ID);

private String getDeviceFreeRam() {
return Long.toString(getMemoryInformation().availMem);
}
// if the android id is not defined we want to cache at least guid
BartoszLitwiniuk marked this conversation as resolved.
Show resolved Hide resolved
// for the current session
uuid = TextUtils.isEmpty(androidId)
? UUID.randomUUID().toString()
: UUID.nameUUIDFromBytes(androidId.getBytes()).toString();

private String getDeviceActiveRam() {
ActivityManager.MemoryInfo mi = getMemoryInformation();
return Long.toString(mi.totalMem - mi.availMem);
return uuid;
}

private ActivityManager.MemoryInfo getMemoryInformation() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package backtraceio.library.models;

public class Tuple<T1, T2> {
konraddysput marked this conversation as resolved.
Show resolved Hide resolved
public final T1 first;
public final T2 second;

public Tuple(T1 first, T2 second) {
this.first = first;
this.second = second;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package backtraceio.library.models.attributes;

import java.util.HashMap;

public class ReportDataAttributes {
private final HashMap<String, String> reportAttributes = new HashMap<>();
konraddysput marked this conversation as resolved.
Show resolved Hide resolved

private final HashMap<String, Object> reportAnnotations = new HashMap<>();


public void addAnnotation(String key, Object value) {
reportAnnotations.put(key, value);
}

public void addAttribute(String key, String value) {
reportAttributes.put(key, value);
}

public HashMap<String, String> getAttributes() {
return reportAttributes;
}

public HashMap<String, Object> getAnnotations() {
return reportAnnotations;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package backtraceio.library.models.attributes;

import java.util.Map;

import backtraceio.library.common.TypeHelper;

public class ReportDataBuilder {

/**
* Divide custom user attributes into primitive and complex attributes and add to this object. By default nullable values will be included.
*
* @param attributes client's attributes
* @return Report data attributes divided into attributes and annotations
*/
public static ReportDataAttributes getReportAttributes(Map<String, Object> attributes) {
return getReportAttributes(attributes, false);
}

/**
* Divide custom user attributes into primitive and complex attributes and add to this object
*
* @param attributes client's attributes
* @param skipNullable define attributes behavior on nullable value. By default all nullable attributes
* will be included in the report. For some features like metrics, we don't want to send
* nullable values, because they can generate invalid behavior/incorrect information.
* @return Report data attributes divided into attributes and annotations
*/
public static ReportDataAttributes getReportAttributes(Map<String, Object> attributes, boolean skipNullable) {
perf2711 marked this conversation as resolved.
Show resolved Hide resolved
ReportDataAttributes reportDataAttributes = new ReportDataAttributes();

if (attributes == null) {
return reportDataAttributes;
}

for (Map.Entry<String, Object> entry : attributes.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value == null) {
if (!skipNullable) {
reportDataAttributes.addAttribute(key, null);
}
continue;
}
if (TypeHelper.isPrimitiveOrPrimitiveWrapperOrString(value.getClass())) {
reportDataAttributes.addAttribute(key, value.toString());
} else {
reportDataAttributes.addAnnotation(key, value);
}
}

return reportDataAttributes;

konraddysput marked this conversation as resolved.
Show resolved Hide resolved
}
}
Loading
Loading