Skip to content

Commit

Permalink
feat: enhance singleton and tests
Browse files Browse the repository at this point in the history
Signed-off-by: YUE Daian <[email protected]>
  • Loading branch information
sheepduke committed Sep 7, 2023
1 parent 9f779b3 commit 3a655bf
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 4 deletions.
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,8 @@ TBD

## Pending Feature List

- [ ] Provider hooks (2.3.*)

- Some requirements of Flag Evaluation API.
- Provider hooks (2.3)
- Evaluation context levels and merging (3.2)
- Hooks (4)
- Events (5)
34 changes: 33 additions & 1 deletion src/api/api.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::sync::{Arc, RwLock};
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};

use lazy_static::lazy_static;

Expand All @@ -24,6 +24,14 @@ pub struct OpenFeature {
}

impl OpenFeature {
pub fn singleton() -> RwLockReadGuard<'static, Self> {
SINGLETON.read().unwrap()
}

pub fn singleton_mut() -> RwLockWriteGuard<'static, Self> {
SINGLETON.write().unwrap()
}

pub fn set_provider<T>(&mut self, provider: T)
where
T: FeatureProvider,
Expand All @@ -46,6 +54,8 @@ impl OpenFeature {

#[cfg(test)]
mod tests {
use std::thread;

use super::*;
use crate::provider::*;

Expand All @@ -69,4 +79,26 @@ mod tests {

assert_eq!(true, value);
}

#[tokio::test]
async fn test_singleton_multi_thread() {
let reader1 = thread::spawn(|| {
let _ = OpenFeature::singleton().provider_metadata();
});

let writer = thread::spawn(|| {
OpenFeature::singleton_mut().set_provider(FixedValueProvider::default());
});

let reader2 = thread::spawn(|| {
let _ = OpenFeature::singleton().provider_metadata();
});

let _ = (reader1.join(), reader2.join(), writer.join());

assert_eq!(
"Fixed Value",
OpenFeature::singleton().provider_metadata().name
);
}
}
2 changes: 1 addition & 1 deletion src/provider/feature_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ pub trait FeatureProvider: Send + Sync + 'static {
#[derive(Clone, TypedBuilder, Default, Debug)]
pub struct ProviderMetadata {
#[builder(setter(into))]
name: String,
pub name: String,
}

impl ProviderMetadata {
Expand Down

0 comments on commit 3a655bf

Please sign in to comment.