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: add DebugLogger to Confidence #165

Merged
merged 12 commits into from
Jun 19, 2024
35 changes: 28 additions & 7 deletions Confidence/src/main/java/com/spotify/confidence/Confidence.kt
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ class Confidence internal constructor(
initialContext: Map<String, ConfidenceValue> = mapOf(),
private val flagApplierClient: FlagApplierClient,
private val parent: ConfidenceContextProvider? = null,
private val region: ConfidenceRegion = ConfidenceRegion.GLOBAL
private val region: ConfidenceRegion = ConfidenceRegion.GLOBAL,
private val debugLogger: DebugLogger?
) : Contextual, EventSender {
private val removedKeys = mutableListOf<String>()
private val contextMap = MutableStateFlow(initialContext)
Expand Down Expand Up @@ -64,8 +65,14 @@ class Confidence internal constructor(
)

private suspend fun resolve(flags: List<String>): Result<FlagResolution> {
debugLogger?.let {
for (flag in flags) {
debugLogger.logFlags("ResolveFlag", flag)
}
}
return flagResolver.resolve(flags, getContext())
}

suspend fun awaitReconciliation() {
if (currentFetchJob != null) {
currentFetchJob?.join()
Expand All @@ -75,6 +82,7 @@ class Confidence internal constructor(

fun apply(flagName: String, resolveToken: String) {
flagApplier.apply(flagName, resolveToken)
debugLogger?.logFlags("ApplyFlag", flagName)
}

fun <T> getValue(key: String, default: T) = getFlag(key, default).value
Expand All @@ -97,13 +105,15 @@ class Confidence internal constructor(
val map = contextMap.value.toMutableMap()
map[key] = value
contextMap.value = map
debugLogger?.logContext(contextMap.value)
}

@Synchronized
override fun putContext(context: Map<String, ConfidenceValue>) {
val map = contextMap.value.toMutableMap()
map += context
contextMap.value = map
debugLogger?.logContext(contextMap.value)
}

fun isStorageEmpty(): Boolean = diskStorage.read() == FlagResolution.EMPTY
Expand All @@ -117,6 +127,7 @@ class Confidence internal constructor(
}
this.removedKeys.addAll(removedKeys)
contextMap.value = map
debugLogger?.logContext(contextMap.value)
}

@Synchronized
Expand All @@ -125,6 +136,7 @@ class Confidence internal constructor(
map.remove(key)
removedKeys.add(key)
contextMap.value = map
debugLogger?.logContext(contextMap.value)
}

override fun getContext(): Map<String, ConfidenceValue> =
Expand All @@ -142,7 +154,8 @@ class Confidence internal constructor(
mapOf(),
flagApplierClient,
this,
region
region,
debugLogger
).also {
it.putContext(context)
}
Expand Down Expand Up @@ -238,22 +251,28 @@ object ConfidenceFactory {
sdk: SdkMetadata = SdkMetadata(SDK_ID, BuildConfig.SDK_VERSION),
initialContext: Map<String, ConfidenceValue> = mapOf(),
region: ConfidenceRegion = ConfidenceRegion.GLOBAL,
dispatcher: CoroutineDispatcher = Dispatchers.IO
dispatcher: CoroutineDispatcher = Dispatchers.IO,
debugLoggerLevel: DebugLoggerLevel = DebugLoggerLevel.NONE
): Confidence {
val debugLogger: DebugLogger? = if (debugLoggerLevel == DebugLoggerLevel.NONE) {
null
} else {
DebugLoggerImpl(debugLoggerLevel)
}
val engine = EventSenderEngineImpl.instance(
context,
clientSecret,
flushPolicies = listOf(minBatchSizeFlushPolicy),
sdkMetadata = sdk,
dispatcher = dispatcher
sdkMetadata = SdkMetadata(SDK_ID, BuildConfig.SDK_VERSION),
dispatcher = dispatcher,
debugLogger = debugLogger
)
val flagApplierClient = FlagApplierClientImpl(
clientSecret,
sdk,
region,
dispatcher
)

val flagResolver = RemoteFlagResolver(
clientSecret = clientSecret,
region = region,
Expand All @@ -264,6 +283,7 @@ object ConfidenceFactory {
val visitorId = ConfidenceValue.String(VisitorUtil.getId(context))
val initContext = initialContext.toMutableMap()
initContext[VISITOR_ID_CONTEXT_KEY] = visitorId
debugLogger?.logContext(initContext)

return Confidence(
clientSecret,
Expand All @@ -273,7 +293,8 @@ object ConfidenceFactory {
region = region,
flagResolver = flagResolver,
diskStorage = FileDiskStorage.create(context),
flagApplierClient = flagApplierClient
flagApplierClient = flagApplierClient,
debugLogger = debugLogger
)
}
}
Expand Down
46 changes: 46 additions & 0 deletions Confidence/src/main/java/com/spotify/confidence/DebugLogger.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.spotify.confidence

import android.util.Log

internal interface DebugLogger {
fun logEvent(tag: String, event: EngineEvent, details: String)
fun logMessage(tag: String, message: String, isWarning: Boolean = false)
fun logFlags(tag: String, flag: String)
fun logContext(context: Map<String, ConfidenceValue>)
}

internal class DebugLoggerImpl(private val level: DebugLoggerLevel) : DebugLogger {
override fun logEvent(tag: String, event: EngineEvent, details: String) {
log(tag, details + event.toString())
}

override fun logMessage(tag: String, message: String, isWarning: Boolean) {
if (!isWarning) {
log(tag, message)
} else {
Log.w(tag, message)
}
}

override fun logFlags(tag: String, flag: String) {
log(tag, flag)
}

override fun logContext(context: Map<String, ConfidenceValue>) {
log("CurrentContext", context.toString())
}

private fun log(tag: String, message: String) {
when (level) {
DebugLoggerLevel.VERBOSE -> Log.v(tag, message)
DebugLoggerLevel.DEBUG -> Log.d(tag, message)
DebugLoggerLevel.NONE -> {
// do nothing
}
}
}
}

enum class DebugLoggerLevel {
VERBOSE, DEBUG, NONE
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import java.io.File

private const val className = "ConfidenceEventSender"

internal interface EventSenderEngine {
fun onLowMemoryChannel(): Channel<List<File>>
fun emit(eventName: String, data: ConfidenceFieldsType, context: Map<String, ConfidenceValue>)
Expand All @@ -29,7 +31,8 @@ internal class EventSenderEngineImpl(
private val flushPolicies: MutableList<FlushPolicy> = mutableListOf(),
private val clock: Clock = Clock.CalendarBacked.systemUTC(),
private val dispatcher: CoroutineDispatcher = Dispatchers.IO,
private val sdkMetadata: SdkMetadata
private val sdkMetadata: SdkMetadata,
private val debugLogger: DebugLogger?
) : EventSenderEngine {
private val writeReqChannel: Channel<EngineEvent> = Channel()
private val sendChannel: Channel<String> = Channel()
Expand All @@ -50,6 +53,7 @@ internal class EventSenderEngineImpl(
if (event.eventDefinition != manualFlushEvent.eventDefinition) {
// skip storing manual flush event
eventStorage.writeEvent(event)
debugLogger?.logEvent(tag = className, event = event, details = "Event written to disk ")
}
for (policy in flushPolicies) {
policy.hit(event)
Expand All @@ -58,6 +62,10 @@ internal class EventSenderEngineImpl(
if (shouldFlush) {
for (policy in flushPolicies) {
policy.reset()
debugLogger?.logMessage(
tag = className,
message = "Flush policy $policy triggered to flush. Flushing."
)
}
sendChannel.send(SEND_SIG)
}
Expand Down Expand Up @@ -86,6 +94,7 @@ internal class EventSenderEngineImpl(
)
runCatching {
val shouldCleanup = uploader.upload(batch)
debugLogger?.logMessage(tag = className, message = "Uploading batched events")
if (shouldCleanup) {
readyFile.delete()
}
Expand All @@ -96,8 +105,10 @@ internal class EventSenderEngineImpl(
}

override fun onLowMemoryChannel(): Channel<List<File>> {
debugLogger?.logMessage(tag = className, message = "Low memory", isWarning = true)
return eventStorage.onLowMemoryChannel()
}

override fun emit(
eventName: String,
data: ConfidenceFieldsType,
Expand All @@ -111,18 +122,21 @@ internal class EventSenderEngineImpl(
payload = payload
)
writeReqChannel.send(event)
debugLogger?.logEvent(tag = className, event = event, details = "Emitting event ")
}
}

override fun flush() {
coroutineScope.launch {
writeReqChannel.send(manualFlushEvent)
debugLogger?.logEvent(tag = className, event = manualFlushEvent, details = "Event flushed ")
}
}

override fun stop() {
coroutineScope.cancel()
eventStorage.stop()
debugLogger?.logMessage(tag = className, message = "$className closed ")
}

companion object {
Expand All @@ -133,7 +147,8 @@ internal class EventSenderEngineImpl(
clientSecret: String,
sdkMetadata: SdkMetadata,
flushPolicies: List<FlushPolicy> = listOf(),
dispatcher: CoroutineDispatcher = Dispatchers.IO
dispatcher: CoroutineDispatcher = Dispatchers.IO,
debugLogger: DebugLogger?
): EventSenderEngine {
return Instance ?: run {
EventSenderEngineImpl(
Expand All @@ -142,7 +157,8 @@ internal class EventSenderEngineImpl(
uploader = EventSenderUploaderImpl(OkHttpClient(), dispatcher),
flushPolicies = flushPolicies.toMutableList(),
dispatcher = dispatcher,
sdkMetadata = sdkMetadata
sdkMetadata = sdkMetadata,
debugLogger = debugLogger
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import org.mockito.kotlin.mock
class ConfidenceContextualTests {
@Test
fun test_forking_context_works() {
val debugLogger = DebugLoggerMock()
val confidence = Confidence(
"",
Dispatchers.IO,
Expand All @@ -18,7 +19,8 @@ class ConfidenceContextualTests {
mapOf(),
mock(),
mock(),
ConfidenceRegion.EUROPE
ConfidenceRegion.EUROPE,
debugLogger
)

val mutableMap = mutableMapOf<String, ConfidenceValue>()
Expand All @@ -27,15 +29,18 @@ class ConfidenceContextualTests {
mutableMap["NN"] = ConfidenceValue.Double(20.0)
mutableMap["my_struct"] = ConfidenceValue.Struct(mapOf("x" to ConfidenceValue.Double(2.0)))
confidence.putContext(mutableMap)
Assert.assertEquals(1, debugLogger.contextLogs)
val eventSender = confidence.withContext(mapOf("my_value" to ConfidenceValue.String("my value")))
Assert.assertEquals(mutableMap, confidence.getContext())
Assert.assertTrue(mutableMap.all { eventSender.getContext().containsKey(it.key) })
Assert.assertTrue(eventSender.getContext().containsKey("my_value"))
Assert.assertTrue(eventSender.getContext()["my_value"] == ConfidenceValue.String("my value"))
Assert.assertEquals(2, debugLogger.contextLogs)
}

@Test
fun removing_context_will_skip_the_context_coming_from_parent() {
val debugLogger = DebugLoggerMock()
val confidence = Confidence(
"",
Dispatchers.IO,
Expand All @@ -46,7 +51,8 @@ class ConfidenceContextualTests {
mapOf(),
mock(),
mock(),
ConfidenceRegion.EUROPE
ConfidenceRegion.EUROPE,
debugLogger
)

val mutableMap = mutableMapOf<String, ConfidenceValue>()
Expand All @@ -55,7 +61,9 @@ class ConfidenceContextualTests {
mutableMap["NN"] = ConfidenceValue.Double(20.0)
mutableMap["my_struct"] = ConfidenceValue.Struct(mapOf("x" to ConfidenceValue.Double(2.0)))
confidence.putContext(mutableMap)
Assert.assertEquals(1, debugLogger.contextLogs)
val eventSender = confidence.withContext(mapOf("my_value" to ConfidenceValue.String("my value")))
Assert.assertEquals(2, debugLogger.contextLogs)
Assert.assertEquals(mutableMap, confidence.getContext())
Assert.assertTrue(mutableMap.all { eventSender.getContext().containsKey(it.key) })
Assert.assertTrue(eventSender.getContext().containsKey("my_value"))
Expand All @@ -64,6 +72,7 @@ class ConfidenceContextualTests {
// remove the screen
Assert.assertTrue(eventSender.getContext().containsKey("screen"))
eventSender.removeContext("screen")
Assert.assertEquals(3, debugLogger.contextLogs)
Assert.assertTrue(!eventSender.getContext().containsKey("screen"))
}
}
Loading
Loading