-
Notifications
You must be signed in to change notification settings - Fork 11
feat: Centralize event distribution #246
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
Open
maxnrp
wants to merge
6
commits into
open-feature:main
Choose a base branch
from
maxnrp:centralized-event-distribution
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
59db46c
Centralize event distribution to avoid overhead
maxnrp e10a003
feat!: Remove deprecated ProviderNotReady event (#239)
maxnrp aabe828
Merge branch 'main' into centralized-event-distribution
maxnrp 9d77aa7
Use Default Dispatcher instead of Unchained
maxnrp 2aefe74
Cancel handleProviderEventsJob on shutdown
maxnrp 1dc461b
Remove unnused parameter in setProviderAndWait
maxnrp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,25 +14,39 @@ import kotlinx.coroutines.flow.Flow | |
| import kotlinx.coroutines.flow.FlowCollector | ||
| import kotlinx.coroutines.flow.MutableSharedFlow | ||
| import kotlinx.coroutines.flow.MutableStateFlow | ||
| import kotlinx.coroutines.flow.SharingStarted | ||
| import kotlinx.coroutines.flow.distinctUntilChanged | ||
| import kotlinx.coroutines.flow.filterIsInstance | ||
| import kotlinx.coroutines.flow.flatMapLatest | ||
| import kotlinx.coroutines.flow.shareIn | ||
| import kotlinx.coroutines.launch | ||
| import kotlinx.coroutines.sync.Mutex | ||
| import kotlinx.coroutines.sync.withLock | ||
| import kotlin.PublishedApi | ||
|
|
||
| @Suppress("TooManyFunctions") | ||
| object OpenFeatureAPI { | ||
| private var setProviderJob: Job? = null | ||
| private var setEvaluationContextJob: Job? = null | ||
| private var observeProviderEventsJob: Job? = null | ||
|
|
||
| private val providerMutex = Mutex() | ||
| private val NOOP_PROVIDER = NoOpProvider() | ||
| private var provider: FeatureProvider = NOOP_PROVIDER | ||
| private var context: EvaluationContext? = null | ||
| val providersFlow: MutableStateFlow<FeatureProvider> = MutableStateFlow(NOOP_PROVIDER) | ||
|
|
||
| /** | ||
| * [Dispatchers.Unconfined] keeps the shared [observe] collector on the emitting thread when possible. | ||
| */ | ||
| private val providerEventsScope = CoroutineScope(SupervisorJob() + Dispatchers.Unconfined) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We should not hardcode any dispatchers to make the code testable. In #243 this |
||
|
|
||
| @PublishedApi | ||
| @OptIn(ExperimentalCoroutinesApi::class) | ||
| internal val sharedProviderEvents = | ||
| providersFlow | ||
| .flatMapLatest { it.observe() } | ||
| .shareIn(providerEventsScope, SharingStarted.Eagerly, replay = 0) | ||
|
maxnrp marked this conversation as resolved.
|
||
|
|
||
| private val _statusFlow: MutableSharedFlow<OpenFeatureStatus> = | ||
| MutableSharedFlow<OpenFeatureStatus>(replay = 1, extraBufferCapacity = 5) | ||
| .apply { | ||
|
|
@@ -44,6 +58,35 @@ object OpenFeatureAPI { | |
| var hooks: List<Hook<*>> = listOf() | ||
| private set | ||
|
|
||
| /** | ||
| * Aligning the state management to | ||
| * https://openfeature.dev/specification/sections/events#requirement-535 | ||
| */ | ||
| private val handleProviderEvents: FlowCollector<OpenFeatureProviderEvents> = FlowCollector { providerEvent -> | ||
| when (providerEvent) { | ||
| is OpenFeatureProviderEvents.ProviderReady -> { | ||
| _statusFlow.emit(OpenFeatureStatus.Ready) | ||
| } | ||
|
|
||
| is OpenFeatureProviderEvents.ProviderStale -> { | ||
| _statusFlow.emit(OpenFeatureStatus.Stale) | ||
| } | ||
|
|
||
| is OpenFeatureProviderEvents.ProviderError -> { | ||
| _statusFlow.emit(providerEvent.toOpenFeatureStatusError()) | ||
| } | ||
|
|
||
| else -> { // All other states should not be emitted from here | ||
| } | ||
| } | ||
| } | ||
|
|
||
| init { | ||
| providerEventsScope.launch { | ||
|
maxnrp marked this conversation as resolved.
Outdated
|
||
| sharedProviderEvents.collect(handleProviderEvents) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Set the [FeatureProvider] for the SDK. This method will return immediately and initialize the provider in a coroutine scope | ||
| * When the provider is successfully initialized it will set the status to Ready. | ||
|
|
@@ -63,7 +106,7 @@ object OpenFeatureAPI { | |
| ) { | ||
| setProviderJob?.cancel(CancellationException("Provider set job was cancelled due to new provider")) | ||
| this.setProviderJob = CoroutineScope(SupervisorJob() + dispatcher).launch { | ||
| setProviderInternal(provider, dispatcher, initialContext) | ||
| setProviderInternal(provider, initialContext) | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -72,26 +115,19 @@ object OpenFeatureAPI { | |
| * | ||
| * @param provider the [FeatureProvider] to set | ||
| * @param initialContext the initial [EvaluationContext] to use for the provider initialization. Defaults to an null context if not set. | ||
| * @param dispatcher retained for API compatibility (no longer used for a separate provider observe job). | ||
|
maxnrp marked this conversation as resolved.
Outdated
|
||
| */ | ||
| @Suppress("UNUSED_PARAMETER") | ||
| suspend fun setProviderAndWait( | ||
| provider: FeatureProvider, | ||
| initialContext: EvaluationContext? = null, | ||
| dispatcher: CoroutineDispatcher = Dispatchers.Default | ||
| ) { | ||
| setProviderInternal(provider, dispatcher, initialContext) | ||
| } | ||
|
|
||
| private fun listenToProviderEvents(provider: FeatureProvider, dispatcher: CoroutineDispatcher) { | ||
| observeProviderEventsJob?.cancel(CancellationException("Provider job was cancelled due to new provider")) | ||
| this.observeProviderEventsJob = CoroutineScope(SupervisorJob() + dispatcher).launch { | ||
| provider.observe().collect(handleProviderEvents) | ||
| } | ||
| setProviderInternal(provider, initialContext) | ||
| } | ||
|
|
||
| @OptIn(ExperimentalCoroutinesApi::class) | ||
| private suspend fun setProviderInternal( | ||
| provider: FeatureProvider, | ||
| dispatcher: CoroutineDispatcher, | ||
| initialContext: EvaluationContext? = null | ||
| ) { | ||
| // Atomically swap the old and new provider to prevent race conditions | ||
|
|
@@ -113,7 +149,6 @@ object OpenFeatureAPI { | |
|
|
||
| // Initialize the new provider | ||
| tryWithStatusEmitErrorHandling { | ||
| listenToProviderEvents(provider, dispatcher) | ||
| getProvider().initialize(context) | ||
| _statusFlow.emit(OpenFeatureStatus.Ready) | ||
| } | ||
|
|
@@ -249,9 +284,6 @@ object OpenFeatureAPI { | |
| clearHooks() | ||
| setEvaluationContextJob?.cancel(CancellationException("Set context job was cancelled due to shutdown")) | ||
| setProviderJob?.cancel(CancellationException("Provider set job was cancelled due to shutdown")) | ||
| observeProviderEventsJob?.cancel( | ||
| CancellationException("Provider event observe job was cancelled due to shutdown") | ||
| ) | ||
| clearProvider() | ||
| } | ||
|
|
||
|
|
@@ -263,30 +295,6 @@ object OpenFeatureAPI { | |
| /** | ||
| * Observe events of type [T] from the currently configured [FeatureProvider]. | ||
| */ | ||
| @OptIn(ExperimentalCoroutinesApi::class) | ||
| inline fun <reified T : OpenFeatureProviderEvents> observe(): Flow<T> = providersFlow | ||
| .flatMapLatest { it.observe() }.filterIsInstance() | ||
|
|
||
| /** | ||
| * Aligning the state management to | ||
| * https://openfeature.dev/specification/sections/events#requirement-535 | ||
| */ | ||
| private val handleProviderEvents: FlowCollector<OpenFeatureProviderEvents> = FlowCollector { providerEvent -> | ||
| when (providerEvent) { | ||
| is OpenFeatureProviderEvents.ProviderReady -> { | ||
| _statusFlow.emit(OpenFeatureStatus.Ready) | ||
| } | ||
|
|
||
| is OpenFeatureProviderEvents.ProviderStale -> { | ||
| _statusFlow.emit(OpenFeatureStatus.Stale) | ||
| } | ||
|
|
||
| is OpenFeatureProviderEvents.ProviderError -> { | ||
| _statusFlow.emit(providerEvent.toOpenFeatureStatusError()) | ||
| } | ||
|
|
||
| else -> { // All other states should not be emitted from here | ||
| } | ||
| } | ||
| } | ||
| inline fun <reified T : OpenFeatureProviderEvents> observe(): Flow<T> = | ||
| sharedProviderEvents.filterIsInstance() | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using
Dispatchers.Unconfinedfor a global event scope can lead to unpredictable behavior if subscribers perform heavy work or cause recursive emissions, as they will execute on the emitting thread. Consider usingDispatchers.Defaultto offload this work and ensure the provider remains responsive.Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've tried with
Defaultbefore (can check gemini's insights on this marked as resolved above), but tests looked messy, and I thought thatUnconfinedwasn't a bad option, may seen unstable but the jumping from thread to thread is kinda appealing, isn't?Though as you suggested in a comment, now that API is becoming a class we could just pass
Dispatcheras an argument eventually. I've updated the tests, just to keep the PR merge-ready, if #243 goes first, we may retouch it again.