Skip to content

Commit

Permalink
refactor: replace gson with moshi
Browse files Browse the repository at this point in the history
  • Loading branch information
fractalwrench committed Dec 19, 2023
1 parent 832869d commit 8907f3b
Show file tree
Hide file tree
Showing 126 changed files with 957 additions and 915 deletions.
3 changes: 3 additions & 0 deletions buildSrc/src/main/kotlin/io/embrace/gradle/Versions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,7 @@ object Versions {

@JvmField
val openTelemetry = "1.29.0"

@JvmField
val moshi = "1.12.0"
}
9 changes: 9 additions & 0 deletions embrace-android-sdk/api/embrace-android-sdk.api
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,15 @@ public final class io/embrace/android/embracesdk/spans/EmbraceSpanEvent$Companio
public final fun create (Ljava/lang/String;JLjava/util/Map;)Lio/embrace/android/embracesdk/spans/EmbraceSpanEvent;
}

public final class io/embrace/android/embracesdk/spans/EmbraceSpanEventJsonAdapter : com/squareup/moshi/JsonAdapter {
public fun <init> (Lcom/squareup/moshi/Moshi;)V
public fun fromJson (Lcom/squareup/moshi/JsonReader;)Lio/embrace/android/embracesdk/spans/EmbraceSpanEvent;
public synthetic fun fromJson (Lcom/squareup/moshi/JsonReader;)Ljava/lang/Object;
public fun toJson (Lcom/squareup/moshi/JsonWriter;Lio/embrace/android/embracesdk/spans/EmbraceSpanEvent;)V
public synthetic fun toJson (Lcom/squareup/moshi/JsonWriter;Ljava/lang/Object;)V
public fun toString ()Ljava/lang/String;
}

public final class io/embrace/android/embracesdk/spans/ErrorCode : java/lang/Enum, io/embrace/android/embracesdk/internal/spans/EmbraceAttributes$Attribute {
public static final field FAILURE Lio/embrace/android/embracesdk/spans/ErrorCode;
public static final field UNKNOWN Lio/embrace/android/embracesdk/spans/ErrorCode;
Expand Down
7 changes: 6 additions & 1 deletion embrace-android-sdk/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import io.embrace.gradle.Versions
plugins {
id "internal-embrace-plugin"
id("org.jetbrains.kotlinx.kover") version "0.7.1"
id "org.jetbrains.kotlin.kapt"
}

description = "Embrace Android SDK: Core"
Expand Down Expand Up @@ -81,7 +82,10 @@ koverReport {
dependencies {
implementation "androidx.lifecycle:lifecycle-common-java8:2.5.0"
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
implementation "com.google.code.gson:gson:2.9.0"

// json
implementation("com.squareup.moshi:moshi:${Versions.moshi}")
kapt("com.squareup.moshi:moshi-kotlin-codegen:${Versions.moshi}")

implementation "io.opentelemetry:opentelemetry-api:${Versions.openTelemetry}"
implementation "io.opentelemetry:opentelemetry-sdk:${Versions.openTelemetry}"
Expand Down Expand Up @@ -112,6 +116,7 @@ dependencies {
androidTestImplementation "androidx.appcompat:appcompat:1.1.0"
androidTestImplementation "com.squareup.okhttp3:mockwebserver:4.9.3"
androidTestImplementation "androidx.test.ext:junit:1.1.3"
androidTestImplementation "com.google.code.gson:gson:2.9.0"
androidTestImplementation project(path: ":embrace-android-sdk")
}

Expand Down
3 changes: 2 additions & 1 deletion embrace-android-sdk/config/detekt/baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<CurrentIssues>
<ID>DataClassContainsFunctions:ExceptionError.kt$ExceptionError$fun addException(ex: Throwable?, appState: String?, clock: Clock)</ID>
<ID>DataClassContainsFunctions:ExceptionError.kt$ExceptionError$private fun getExceptionInfo(ex: Throwable?): List&lt;ExceptionInfo&gt;</ID>
<ID>DataClassShouldBeImmutable:ExceptionError.kt$ExceptionError$@SerializedName("c") var occurrences = 0</ID>
<ID>DataClassShouldBeImmutable:ExceptionError.kt$ExceptionError$@Json(name = "c") var occurrences = 0</ID>
<ID>DataClassShouldBeImmutable:ExceptionError.kt$ExceptionError$@Json(name = "rep") var exceptionErrors = mutableListOf&lt;ExceptionErrorInfo&gt;()</ID>
</CurrentIssues>
</SmellBaseline>
11 changes: 0 additions & 11 deletions embrace-android-sdk/embrace-proguard.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,6 @@
-dontwarn okhttp3.**
-dontwarn okio.**

## Proguard configuration for Gson
-keepattributes Signature
-keepattributes *Annotation*
-dontwarn sun.misc.**
-keep class com.google.gson.examples.android.model.** { *; }
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer
-keep class com.google.gson.reflect.TypeToken { *; }
-keep class * extends com.google.gson.reflect.TypeToken

## Proguard configuration for Arrow
-keep class java9.** { *; }
-dontwarn java9.**
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package io.embrace.android.embracesdk
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.squareup.moshi.Types
import io.embrace.android.embracesdk.BaseTest
import io.embrace.android.embracesdk.Embrace
import io.embrace.android.embracesdk.internal.serialization.EmbraceSerializer
Expand Down Expand Up @@ -165,7 +166,8 @@ internal class AnrIntegrationTest : BaseTest() {
) {
val interval = intervals[index]
val errMsg: String by lazy {
"Assertion failed for interval $index. ${serializer.toJson(intervals)}"
val type = Types.newParameterizedType(List::class.java, AnrInterval::class.java)
"Assertion failed for interval $index. ${serializer.toJson(intervals, type)}"
}

// validate interval code
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ProcessLifecycleOwnerAccess
import androidx.test.platform.app.InstrumentationRegistry
import com.google.gson.Gson
import io.embrace.android.embracesdk.config.local.BaseUrlLocalConfig
import io.embrace.android.embracesdk.config.local.NetworkLocalConfig
import io.embrace.android.embracesdk.config.local.SdkLocalConfig
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package io.embrace.android.embracesdk

import com.google.gson.annotations.SerializedName
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import io.embrace.android.embracesdk.EmbraceEvent.Type
import io.embrace.android.embracesdk.annotation.InternalApi

/**
* Wraps the event [Type]. This class is purely used for backwards-compatibility.
*/
internal class EmbraceEvent private constructor() {
@JsonClass(generateAdapter = true)
internal class EmbraceEvent internal constructor() {

Check warning on line 12 in embrace-android-sdk/src/main/java/io/embrace/android/embracesdk/EmbraceEvent.kt

View check run for this annotation

Codecov / codecov/patch

embrace-android-sdk/src/main/java/io/embrace/android/embracesdk/EmbraceEvent.kt#L12

Added line #L12 was not covered by tests

/**
* This actually belongs in [Event], but to maintain backwards-compatibility of the API,
Expand All @@ -25,31 +27,31 @@ internal class EmbraceEvent private constructor() {
val abbreviation: String
) {

@SerializedName("start")
@Json(name = "start")
START("s"),

@SerializedName("late")
@Json(name = "late")
LATE("l"),

@SerializedName("interrupt")
@Json(name = "interrupt")
INTERRUPT("i"),

@SerializedName("crash")
@Json(name = "crash")
CRASH("c"),

@SerializedName("end")
@Json(name = "end")
END("e"),

@SerializedName("info")
@Json(name = "info")
INFO_LOG("il"),

@SerializedName("error")
@Json(name = "error")
ERROR_LOG("el"),

@SerializedName("warning")
@Json(name = "warning")
WARNING_LOG("wl"),

@SerializedName("network")
@Json(name = "network")
NETWORK_LOG("n");

companion object {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package io.embrace.android.embracesdk.comms.api

import com.squareup.moshi.JsonClass
import io.embrace.android.embracesdk.BuildConfig
import io.embrace.android.embracesdk.network.http.HttpMethod
import java.io.IOException

@JsonClass(generateAdapter = true)
internal data class ApiRequest(
val contentType: String = "application/json",

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package io.embrace.android.embracesdk.comms.delivery

import io.embrace.android.embracesdk.internal.serialization.EmbraceSerializer
import io.embrace.android.embracesdk.internal.utils.threadLocal
import io.embrace.android.embracesdk.logging.InternalEmbraceLogger
import io.embrace.android.embracesdk.payload.SessionMessage
import io.embrace.android.embracesdk.session.SessionMessageSerializer
import java.io.File
import java.io.FileNotFoundException
import java.util.regex.Pattern
Expand All @@ -20,10 +18,6 @@ internal class EmbraceCacheService(

private val storageDir: File by fileProvider

private val sessionMessageSerializer by threadLocal {
SessionMessageSerializer(serializer)
}

override fun cacheBytes(name: String, bytes: ByteArray?) {
logger.logDeveloper(TAG, "Attempting to write bytes to $name")
if (bytes != null) {
Expand Down Expand Up @@ -151,9 +145,7 @@ internal class EmbraceCacheService(
try {
logger.logDeveloper(TAG, "Attempting to write bytes to $name")
val file = File(storageDir, EMBRACE_PREFIX + name)
file.bufferedWriter().use {
sessionMessageSerializer.serialize(sessionMessage, it)
}
serializer.toJson(sessionMessage, SessionMessage::class.java, file.outputStream())
logger.logDeveloper(TAG, "Bytes cached")
} catch (ex: Throwable) {
logger.logWarning("Failed to write session with buffered writer", ex)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@ package io.embrace.android.embracesdk.comms.delivery
import io.embrace.android.embracesdk.internal.clock.Clock
import io.embrace.android.embracesdk.internal.serialization.EmbraceSerializer
import io.embrace.android.embracesdk.internal.utils.Uuid
import io.embrace.android.embracesdk.internal.utils.threadLocal
import io.embrace.android.embracesdk.logging.InternalEmbraceLogger
import io.embrace.android.embracesdk.payload.BackgroundActivityMessage
import io.embrace.android.embracesdk.payload.EventMessage
import io.embrace.android.embracesdk.payload.SessionMessage
import io.embrace.android.embracesdk.session.SessionMessageSerializer
import io.embrace.android.embracesdk.session.SessionSnapshotType
import java.io.Closeable
import java.util.concurrent.ExecutorService
Expand Down Expand Up @@ -48,10 +46,6 @@ internal class EmbraceDeliveryCacheManager(
private const val TAG = "DeliveryCacheManager"
}

private val sessionMessageSerializer by threadLocal {
SessionMessageSerializer(serializer)
}

// The session id is used as key for this map
// This list is initialized when getAllCachedSessions() is called.
private val cachedSessions = mutableMapOf<String, CachedSession>()
Expand All @@ -68,7 +62,7 @@ internal class EmbraceDeliveryCacheManager(
null
}
else -> {
val sessionBytes: ByteArray = sessionMessageSerializer.serialize(sessionMessage).toByteArray()
val sessionBytes: ByteArray = serializer.toJson(sessionMessage).toByteArray()
saveSessionImpl(sessionMessage, snapshotType == SessionSnapshotType.JVM_CRASH) { filename ->
cacheService.cacheBytes(filename, sessionBytes)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package io.embrace.android.embracesdk.comms.delivery

import com.google.gson.annotations.SerializedName
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import io.embrace.android.embracesdk.comms.api.ApiRequest

/**
* A pending API call.
*/
@JsonClass(generateAdapter = true)
internal data class PendingApiCall(
@SerializedName("apiRequest") val apiRequest: ApiRequest,
@SerializedName("cachedPayload") val cachedPayloadFilename: String,
@SerializedName("queueTime") val queueTime: Long? = null
@Json(name = "apiRequest") val apiRequest: ApiRequest,
@Json(name = "cachedPayload") val cachedPayloadFilename: String,
@Json(name = "queueTime") val queueTime: Long? = null
)
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package io.embrace.android.embracesdk.comms.delivery

import com.google.gson.annotations.SerializedName
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import io.embrace.android.embracesdk.comms.api.EmbraceApiService.Companion.Endpoint
import java.util.concurrent.ConcurrentHashMap

/**
* A map containing a queue of pending API calls for each endpoint.
*/
@JsonClass(generateAdapter = true)
internal class PendingApiCalls(
@SerializedName("pendingApiCallsMap")
@Json(name = "pendingApiCallsMap")
internal val pendingApiCallsMap: MutableMap<Endpoint, MutableList<PendingApiCall>> = ConcurrentHashMap<
Endpoint, MutableList<PendingApiCall>>()
) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package io.embrace.android.embracesdk.config.local

import com.google.gson.annotations.SerializedName
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass

@JsonClass(generateAdapter = true)
internal class AnrLocalConfig(
@SerializedName("capture_google")
@Json(name = "capture_google")
val captureGoogle: Boolean? = null,

@SerializedName("capture_unity_thread")
@Json(name = "capture_unity_thread")
val captureUnityThread: Boolean? = null
)
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package io.embrace.android.embracesdk.config.local

import com.google.gson.annotations.SerializedName
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass

@JsonClass(generateAdapter = true)
internal class AppExitInfoLocalConfig(
/**
* Defines the max size of bytes to allow capturing AppExitInfo ndk/anr traces
*/
@SerializedName("app_exit_info_traces_limit")
@Json(name = "app_exit_info_traces_limit")
val appExitInfoTracesLimit: Int? = null,

@SerializedName("aei_enabled")
@Json(name = "aei_enabled")
val aeiCaptureEnabled: Boolean? = null
)
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package io.embrace.android.embracesdk.config.local

import com.google.gson.annotations.SerializedName
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass

@JsonClass(generateAdapter = true)
internal class AppLocalConfig(

@SerializedName("report_disk_usage")
@Json(name = "report_disk_usage")
val reportDiskUsage: Boolean? = null
)
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
package io.embrace.android.embracesdk.config.local

import com.google.gson.annotations.SerializedName
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass

@JsonClass(generateAdapter = true)
internal class AutomaticDataCaptureLocalConfig(
@SerializedName("memory_info")
@Json(name = "memory_info")
val memoryServiceEnabled: Boolean? = null,

@SerializedName("power_save_mode_info")
@Json(name = "power_save_mode_info")
val powerSaveModeServiceEnabled: Boolean? = null,

@SerializedName("network_connectivity_info")
@Json(name = "network_connectivity_info")
val networkConnectivityServiceEnabled: Boolean? = null,

@SerializedName("anr_info")
@Json(name = "anr_info")
val anrServiceEnabled: Boolean? = null
)
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
package io.embrace.android.embracesdk.config.local

import com.google.gson.annotations.SerializedName
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass

/**
* Represents the background activity configuration element specified in the Embrace config file.
*/
@JsonClass(generateAdapter = true)
internal class BackgroundActivityLocalConfig(
@SerializedName("capture_enabled")
@Json(name = "capture_enabled")
val backgroundActivityCaptureEnabled: Boolean? = null,

@SerializedName("manual_background_activity_limit")
@Json(name = "manual_background_activity_limit")
val manualBackgroundActivityLimit: Int? = null,

@SerializedName("min_background_activity_duration")
@Json(name = "min_background_activity_duration")
val minBackgroundActivityDuration: Long? = null,

@SerializedName("max_cached_activities")
@Json(name = "max_cached_activities")
val maxCachedActivities: Int? = null
)
Loading

0 comments on commit 8907f3b

Please sign in to comment.