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: listen for changes in the provider for the context changes #133

Merged
merged 15 commits into from
Apr 26, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
32 changes: 22 additions & 10 deletions Provider/src/main/java/com/spotify/confidence/Confidence.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import com.spotify.confidence.client.FlagApplierClientImpl
import com.spotify.confidence.client.SdkMetadata
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.drop
import okhttp3.OkHttpClient

class Confidence internal constructor(
Expand All @@ -23,7 +27,13 @@ class Confidence internal constructor(
private val region: ConfidenceRegion = ConfidenceRegion.GLOBAL
) : Contextual, EventSender {
private val removedKeys = mutableListOf<String>()
private var contextMap: MutableMap<String, ConfidenceValue> = mutableMapOf()
private var contextMap = MutableStateFlow(mapOf<String, ConfidenceValue>())

// only return changes not the initial value
// only return distinct value
internal val contextChanges: Flow<Map<String, ConfidenceValue>> = contextMap
.drop(1)
.distinctUntilChanged()

private val flagApplier = FlagApplierWithRetries(
client = flagApplierClient,
Expand All @@ -48,26 +58,28 @@ class Confidence internal constructor(
}

override fun putContext(key: String, value: ConfidenceValue) {
contextMap[key] = value
val map = contextMap.value.toMutableMap()
map[key] = value
contextMap.value = map
}

override fun putContext(context: Map<String, ConfidenceValue>) {
contextMap += context
}

override fun setContext(context: Map<String, ConfidenceValue>) {
contextMap = context.toMutableMap()
val map = contextMap.value.toMutableMap()
map += context
contextMap.value = map
}

override fun removeContext(key: String) {
val map = contextMap.value.toMutableMap()
map.remove(key)
contextMap.value = map
removedKeys.add(key)
contextMap.remove(key)
}

override fun getContext(): Map<String, ConfidenceValue> =
this.parent?.let {
it.getContext().filterKeys { key -> !removedKeys.contains(key) } + contextMap
} ?: contextMap
it.getContext().filterKeys { key -> !removedKeys.contains(key) } + contextMap.value
} ?: contextMap.value

override fun withContext(context: Map<String, ConfidenceValue>): Confidence = Confidence(
clientSecret,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ interface Contextual : ConfidenceContextProvider {
fun withContext(context: Map<String, ConfidenceValue>): Contextual

fun putContext(context: Map<String, ConfidenceValue>)
fun setContext(context: Map<String, ConfidenceValue>)
fun putContext(key: String, value: ConfidenceValue)
fun removeContext(key: String)
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,52 +49,59 @@ class ConfidenceFeatureProvider private constructor(
}
}

private fun startListeningForContext() {
coroutineScope.launch {
confidence.contextChanges
.collect {
resolve(InitialisationStrategy.FetchAndActivate)
fabriziodemaria marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

override fun initialize(initialContext: EvaluationContext?) {
initialContext?.let {
internalInitialize(
initialContext,
initialisationStrategy
)
// refresh cache with the last stored data
storage.read().let(providerCache::refresh)
if (initialisationStrategy == InitialisationStrategy.ActivateAndFetchAsync) {
eventHandler.publish(OpenFeatureEvents.ProviderReady)
}

coroutineScope.launch(networkExceptionHandler) {
val context = initialContext.toConfidenceContext()
for (entry in context.map) {
confidence.putContext(entry.key, entry.value)
}
resolve(initialisationStrategy)
startListeningForContext()
}
}
}

private fun internalInitialize(
initialContext: EvaluationContext,
strategy: InitialisationStrategy
) {
// refresh cache with the last stored data
storage.read().let(providerCache::refresh)
if (strategy == InitialisationStrategy.ActivateAndFetchAsync) {
eventHandler.publish(OpenFeatureEvents.ProviderReady)
}
private suspend fun resolve(strategy: InitialisationStrategy) {
try {
val resolveResponse = confidence.resolve(listOf())
fabriziodemaria marked this conversation as resolved.
Show resolved Hide resolved
if (resolveResponse is Result.Success) {
// we store the flag anyways except when the response was not modified
if (resolveResponse.data != FlagResolution.EMPTY) {
storage.store(resolveResponse.data)
}

coroutineScope.launch(networkExceptionHandler) {
confidence.putContext(OPEN_FEATURE_CONTEXT_KEY, initialContext.toConfidenceContext())
try {
val resolveResponse = confidence.resolve(listOf())
if (resolveResponse is Result.Success) {
// we store the flag anyways except when the response was not modified
if (resolveResponse.data != FlagResolution.EMPTY) {
storage.store(resolveResponse.data)
when (strategy) {
InitialisationStrategy.FetchAndActivate -> {
// refresh the cache from the stored data
providerCache.refresh(resolveResponse.data)
eventHandler.publish(OpenFeatureEvents.ProviderReady)
}

when (strategy) {
InitialisationStrategy.FetchAndActivate -> {
// refresh the cache from the stored data
providerCache.refresh(resolveResponse.data)
eventHandler.publish(OpenFeatureEvents.ProviderReady)
}

InitialisationStrategy.ActivateAndFetchAsync -> {
// do nothing
}
InitialisationStrategy.ActivateAndFetchAsync -> {
// do nothing
}
} else {
eventHandler.publish(OpenFeatureEvents.ProviderReady)
}
} catch (e: ParseError) {
throw OpenFeatureError.ParseError(e.message)
} else {
eventHandler.publish(OpenFeatureEvents.ProviderReady)
}
} catch (e: ParseError) {
throw OpenFeatureError.ParseError(e.message)
}
}

Expand All @@ -106,13 +113,15 @@ class ConfidenceFeatureProvider private constructor(
oldContext: EvaluationContext?,
newContext: EvaluationContext
) {
if (newContext != oldContext) {
// on the new context we want to fetch new values and update
// the storage & cache right away which is why we pass `InitialisationStrategy.FetchAndActivate`
internalInitialize(
newContext,
InitialisationStrategy.FetchAndActivate
)
val context = newContext.toConfidenceContext()
for (entry in context.map) {
confidence.putContext(entry.key, entry.value)
vahidlazio marked this conversation as resolved.
Show resolved Hide resolved
}

oldContext?.let { old ->
old.asMap().keys.minus(newContext.asMap().keys).forEach {
confidence.removeContext(it)
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,7 @@ internal class ConfidenceFeatureProviderTests {
)
fabriziodemaria marked this conversation as resolved.
Show resolved Hide resolved
assertEquals(newContextEval.reason, Reason.STALE.name)
assertEquals(newContextEval.value, "red")
verify(flagResolverClient, times(2)).resolve(any(), any())
}

@Test
Expand Down
Loading