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,74 @@
package backtraceio.library.common;
konraddysput marked this conversation as resolved.
Show resolved Hide resolved
BartoszLitwiniuk marked this conversation as resolved.
Show resolved Hide resolved

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

import backtraceio.library.logger.BacktraceLogger;

public class ApplicationHelper {
BartoszLitwiniuk marked this conversation as resolved.
Show resolved Hide resolved
private static final transient String LOG_TAG = ApplicationHelper.class.getSimpleName();
/**
* Cached application name
*/
private static String applicationName;

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

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

/**
* Retrieves application name from context. The name will be cached over checks
* @param context application context
* @return application name
*/
public static String getApplicationName(Context context) {
BartoszLitwiniuk marked this conversation as resolved.
Show resolved Hide resolved
if(!BacktraceStringHelper.isNullOrEmpty(applicationName)) {
return applicationName;
}

applicationName = context.getApplicationInfo().loadLabel(context.getPackageManager()).toString();
return applicationName;
}

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

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

/**
* Retrieves package name from the context.
* @param context application context
* @return current package name.
*/
public static String getPackageName(Context context) {
if(!BacktraceStringHelper.isNullOrEmpty(packageName)) {
return packageName;
}
packageName = context.getApplicationContext().getPackageName();

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 guid;
konraddysput marked this conversation as resolved.
Show resolved Hide resolved

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(guid)) {
return guid;
}

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
guid = 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 guid;
}

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
Expand Up @@ -15,18 +15,16 @@
import java.util.UUID;

import backtraceio.library.BacktraceClient;
import backtraceio.library.common.ApplicationHelper;
import backtraceio.library.common.BacktraceStringHelper;
import backtraceio.library.common.DeviceAttributesHelper;
import backtraceio.library.common.TypeHelper;
import backtraceio.library.enums.ScreenOrientation;
import backtraceio.library.logger.BacktraceLogger;
import backtraceio.library.models.Tuple;

/**
* Class instance to get a built-in attributes from current application
*/
public class BacktraceAttributes {
private static final transient String LOG_TAG = BacktraceAttributes.class.getSimpleName();

/**
* Get built-in primitive attributes
*/
Expand All @@ -42,15 +40,10 @@ public class BacktraceAttributes {
*/
private final Context context;

/**
* Are metrics enabled?
*/
private static boolean isMetricsEnabled = false;

/**
* Metrics session ID
*/
private static String sessionId = UUID.randomUUID().toString();
private final static String sessionId = UUID.randomUUID().toString();

/**
* Create instance of Backtrace Attribute
Expand Down Expand Up @@ -110,10 +103,9 @@ private void setDeviceInformation(Boolean includeDynamicAttributes) {
}

private void setAppInformation() {
this.attributes.put("application.package", this.context.getApplicationContext()
.getPackageName());
this.attributes.put("application", getApplicationName());
String version = getApplicationVersionOrEmpty();
this.attributes.put("application.package", ApplicationHelper.getPackageName(this.context));
this.attributes.put("application", ApplicationHelper.getApplicationName(this.context));
String version = ApplicationHelper.getApplicationVersion(this.context);
if (!BacktraceStringHelper.isNullOrEmpty(version)) {
// We want to standardize application.version attribute name
this.attributes.put("application.version", version);
Expand Down Expand Up @@ -211,41 +203,12 @@ private void convertReportAttributes(BacktraceReport report) {
}
}

/**
* Divide custom user attributes into primitive and complex attributes and add to this object
*
* @param attributes client's attributes
*/
private void convertAttributes(Map<String, Object> attributes) {
for (Map.Entry<String, Object> entry : attributes.entrySet()) {
Object value = entry.getValue();
if (value == null) {
continue;
}
Class type = value.getClass();
if (TypeHelper.isPrimitiveOrPrimitiveWrapperOrString(type)) {
this.attributes.put(entry.getKey(), value.toString());
} else {
this.complexAttributes.put(entry.getKey(), value);
}
}
}

public String getApplicationName() {
return this.context.getApplicationInfo().loadLabel(this.context
.getPackageManager()).toString();
private void convertAttributes(Map<String, Object> clientAttributes) {
Tuple<Map<String, String>, Map<String, Object>> reportData = ReportDataBuilder.getReportAttribues(clientAttributes);
this.attributes.putAll(reportData.first);
konraddysput marked this conversation as resolved.
Show resolved Hide resolved
this.complexAttributes.putAll(reportData.second);
}

public String getApplicationVersionOrEmpty() {
try {
return this.context.getPackageManager()
.getPackageInfo(this.context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
BacktraceLogger.e(LOG_TAG, "Could not resolve application version");
e.printStackTrace();
}
return "";
}

public Map<String, Object> getAllAttributes() {
Map<String, Object> attributes = new HashMap<String, Object>();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package backtraceio.library.models.json;
konraddysput marked this conversation as resolved.
Show resolved Hide resolved
import java.util.HashMap;
import java.util.Map;

import backtraceio.library.common.TypeHelper;
import backtraceio.library.models.Tuple;

public class ReportDataBuilder {

/**
* Divide custom user attributes into primitive and complex attributes and add to this object
*
* @param attributes client's attributes
*/
public static Tuple<Map<String, String>, Map<String, Object>> getReportAttribues(Map<String, Object> attributes) {
konraddysput marked this conversation as resolved.
Show resolved Hide resolved
perf2711 marked this conversation as resolved.
Show resolved Hide resolved
HashMap<String, String> reportAttributes = new HashMap<>();
HashMap<String, Object> reportAnnotations = new HashMap<>();

if(attributes == null) {
konraddysput marked this conversation as resolved.
Show resolved Hide resolved
return new Tuple<>(reportAttributes, reportAnnotations);
}

for (Map.Entry<String, Object> entry : attributes.entrySet()) {
Object value = entry.getValue();
if (value == null) {
reportAttributes.put(entry.getKey(), "null");
konraddysput marked this conversation as resolved.
Show resolved Hide resolved
continue;
}
Class type = value.getClass();
if (TypeHelper.isPrimitiveOrPrimitiveWrapperOrString(type)) {
reportAttributes.put(entry.getKey(), value.toString());
} else {
reportAnnotations.put(entry.getKey(), value);
}
}

return new Tuple<>(reportAttributes, reportAnnotations);

}
}
Loading
Loading