Skip to main content

launchdarkly_server_sdk/
client.rs

1use eval::Context;
2use parking_lot::RwLock;
3use std::io;
4use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
5use std::sync::{Arc, Mutex};
6use std::time::Duration;
7use tokio::runtime::Runtime;
8
9use launchdarkly_server_sdk_evaluation::{self as eval, Detail, FlagValue, PrerequisiteEvent};
10use serde::Serialize;
11use thiserror::Error;
12use tokio::sync::{broadcast, Semaphore};
13
14use super::config::Config;
15use super::data_source_builders::BuildError as DataSourceError;
16use super::data_system::{DataSystem, FDv1DataSystem};
17use super::data_system_builders::BuildError as DataSystemError;
18use super::evaluation::{FlagDetail, FlagDetailConfig};
19use super::stores::store::DataStore;
20use super::stores::store_builders::BuildError as DataStoreError;
21use crate::config::BuildError as ConfigBuildError;
22use crate::events::event::EventFactory;
23use crate::events::event::InputEvent;
24use crate::events::processor::EventProcessor;
25use crate::events::processor_builders::BuildError as EventProcessorError;
26use crate::{MigrationOpTracker, Stage};
27
28struct EventsScope {
29    disabled: bool,
30    event_factory: EventFactory,
31    prerequisite_event_recorder: Box<dyn eval::PrerequisiteEventRecorder + Send + Sync>,
32}
33
34struct PrerequisiteEventRecorder {
35    event_factory: EventFactory,
36    event_processor: Arc<dyn EventProcessor>,
37}
38
39impl eval::PrerequisiteEventRecorder for PrerequisiteEventRecorder {
40    fn record(&self, event: PrerequisiteEvent) {
41        let evt = self.event_factory.new_eval_event(
42            &event.prerequisite_flag.key,
43            event.context.clone(),
44            &event.prerequisite_flag,
45            event.prerequisite_result,
46            FlagValue::Json(serde_json::Value::Null),
47            Some(event.target_flag_key),
48        );
49
50        self.event_processor.send(evt);
51    }
52}
53
54/// Error type used to represent failures when building a [Client] instance.
55#[non_exhaustive]
56#[derive(Debug, Error)]
57pub enum BuildError {
58    /// Error used when a configuration setting is invalid. This typically indicates an invalid URL.
59    #[error("invalid client config: {0}")]
60    InvalidConfig(String),
61}
62
63impl From<DataSourceError> for BuildError {
64    fn from(error: DataSourceError) -> Self {
65        Self::InvalidConfig(error.to_string())
66    }
67}
68
69impl From<DataSystemError> for BuildError {
70    fn from(error: DataSystemError) -> Self {
71        Self::InvalidConfig(error.to_string())
72    }
73}
74
75impl From<DataStoreError> for BuildError {
76    fn from(error: DataStoreError) -> Self {
77        Self::InvalidConfig(error.to_string())
78    }
79}
80
81impl From<EventProcessorError> for BuildError {
82    fn from(error: EventProcessorError) -> Self {
83        Self::InvalidConfig(error.to_string())
84    }
85}
86
87impl From<ConfigBuildError> for BuildError {
88    fn from(error: ConfigBuildError) -> Self {
89        Self::InvalidConfig(error.to_string())
90    }
91}
92
93/// Error type used to represent failures when starting the [Client].
94#[non_exhaustive]
95#[derive(Debug, Error)]
96pub enum StartError {
97    /// Error used when spawning a background there fails.
98    #[error("couldn't spawn background thread for client: {0}")]
99    SpawnFailed(io::Error),
100}
101
102#[derive(PartialEq, Copy, Clone, Debug)]
103enum ClientInitState {
104    Initializing = 0,
105    Initialized = 1,
106    InitializationFailed = 2,
107}
108
109impl PartialEq<usize> for ClientInitState {
110    fn eq(&self, other: &usize) -> bool {
111        *self as usize == *other
112    }
113}
114
115impl From<usize> for ClientInitState {
116    fn from(val: usize) -> Self {
117        match val {
118            0 => ClientInitState::Initializing,
119            1 => ClientInitState::Initialized,
120            2 => ClientInitState::InitializationFailed,
121            _ => unreachable!(),
122        }
123    }
124}
125
126/// A client for the LaunchDarkly API.
127///
128/// In order to create a client instance, first create a config using [crate::ConfigBuilder].
129///
130/// # Examples
131///
132/// Creating a client, with default configuration.
133/// ```
134/// # use launchdarkly_server_sdk::{Client, ConfigBuilder, BuildError};
135/// # fn main() -> Result<(), BuildError> {
136///     let ld_client = Client::build(ConfigBuilder::new("sdk-key").build()?)?;
137/// #   Ok(())
138/// # }
139/// ```
140///
141/// Creating an instance which connects to a relay proxy.
142/// ```
143/// # use launchdarkly_server_sdk::{Client, ConfigBuilder, ServiceEndpointsBuilder, BuildError};
144/// # fn main() -> Result<(), BuildError> {
145///     let ld_client = Client::build(ConfigBuilder::new("sdk-key")
146///         .service_endpoints(ServiceEndpointsBuilder::new()
147///             .relay_proxy("http://my-relay-hostname:8080")
148///         ).build()?
149///     )?;
150/// #   Ok(())
151/// # }
152/// ```
153///
154/// Each builder type includes usage examples for the builder.
155pub struct Client {
156    event_processor: Arc<dyn EventProcessor>,
157    data_system: Arc<dyn DataSystem>,
158    data_store: Arc<RwLock<dyn DataStore>>,
159    events_default: EventsScope,
160    events_with_reasons: EventsScope,
161    init_notify: Arc<Semaphore>,
162    init_state: Arc<AtomicUsize>,
163    started: AtomicBool,
164    offline: bool,
165    daemon_mode: bool,
166    #[cfg_attr(
167        not(any(feature = "crypto-openssl", feature = "crypto-aws-lc-rs")),
168        allow(dead_code)
169    )]
170    sdk_key: String,
171    shutdown_broadcast: broadcast::Sender<()>,
172    runtime: RwLock<Option<Runtime>>,
173}
174
175impl Client {
176    /// Create a new instance of a [Client] based on the provided [Config] parameter.
177    pub fn build(config: Config) -> Result<Self, BuildError> {
178        if config.offline() {
179            info!("Started LaunchDarkly Client in offline mode");
180        } else if config.daemon_mode() {
181            info!("Started LaunchDarkly Client in daemon mode");
182        }
183
184        let tags = config.application_tag();
185        let instance_id = config.instance_id().to_string();
186
187        let endpoints = config.service_endpoints_builder().build()?;
188
189        let mut event_processor_builder = config.event_processor_builder().to_owned();
190        event_processor_builder.set_instance_id(instance_id.clone());
191        let event_processor =
192            event_processor_builder.build(&endpoints, config.sdk_key(), tags.clone())?;
193
194        let data_system: Arc<dyn DataSystem> = match config.data_system_builder() {
195            Some(data_system_builder) => data_system_builder.build(
196                &endpoints,
197                config.sdk_key(),
198                tags.as_deref(),
199                &instance_id,
200            )?,
201            None => {
202                let mut data_source_builder = config.data_source_builder().to_owned();
203                data_source_builder.set_instance_id(instance_id);
204                let data_source =
205                    data_source_builder.build(&endpoints, config.sdk_key(), tags.clone())?;
206                Arc::new(FDv1DataSystem::new(
207                    data_source,
208                    config.data_store_builder(),
209                )?)
210            }
211        };
212        let data_store = data_system.store();
213
214        let events_default = EventsScope {
215            disabled: config.offline(),
216            event_factory: EventFactory::new(false),
217            prerequisite_event_recorder: Box::new(PrerequisiteEventRecorder {
218                event_factory: EventFactory::new(false),
219                event_processor: event_processor.clone(),
220            }),
221        };
222
223        let events_with_reasons = EventsScope {
224            disabled: config.offline(),
225            event_factory: EventFactory::new(true),
226            prerequisite_event_recorder: Box::new(PrerequisiteEventRecorder {
227                event_factory: EventFactory::new(true),
228                event_processor: event_processor.clone(),
229            }),
230        };
231
232        let (shutdown_tx, _) = broadcast::channel(1);
233
234        Ok(Client {
235            event_processor,
236            data_system,
237            data_store,
238            events_default,
239            events_with_reasons,
240            init_notify: Arc::new(Semaphore::new(0)),
241            init_state: Arc::new(AtomicUsize::new(ClientInitState::Initializing as usize)),
242            started: AtomicBool::new(false),
243            offline: config.offline(),
244            daemon_mode: config.daemon_mode(),
245            sdk_key: config.sdk_key().into(),
246            shutdown_broadcast: shutdown_tx,
247            runtime: RwLock::new(None),
248        })
249    }
250
251    /// Starts a client in the current thread, which must have a default tokio runtime.
252    pub fn start_with_default_executor(&self) {
253        if self.started.load(Ordering::SeqCst) {
254            return;
255        }
256        self.started.store(true, Ordering::SeqCst);
257        self.start_with_default_executor_internal();
258    }
259
260    fn start_with_default_executor_internal(&self) {
261        // These clones are going to move into the closure, we
262        // do not want to move or reference `self`, because
263        // then lifetimes will get involved.
264        let notify = self.init_notify.clone();
265        let init_state = self.init_state.clone();
266
267        self.data_system.start(
268            Arc::new(move |success| {
269                init_state.store(
270                    (if success {
271                        ClientInitState::Initialized
272                    } else {
273                        ClientInitState::InitializationFailed
274                    }) as usize,
275                    Ordering::SeqCst,
276                );
277                notify.add_permits(1);
278            }),
279            self.shutdown_broadcast.subscribe(),
280        );
281    }
282
283    /// Creates a new tokio runtime and then starts the client. Tasks from the client will
284    /// be executed on created runtime.
285    /// If your application already has a tokio runtime, then you can use
286    /// [crate::Client::start_with_default_executor] and the client will dispatch tasks to
287    /// your existing runtime.
288    pub fn start_with_runtime(&self) -> Result<bool, StartError> {
289        if self.started.load(Ordering::SeqCst) {
290            return Ok(true);
291        }
292        self.started.store(true, Ordering::SeqCst);
293
294        let runtime = Runtime::new().map_err(StartError::SpawnFailed)?;
295        let _guard = runtime.enter();
296        self.runtime.write().replace(runtime);
297
298        self.start_with_default_executor_internal();
299
300        Ok(true)
301    }
302
303    /// This is an async method that will resolve once initialization is complete or the specified
304    /// timeout has occurred.
305    ///
306    /// If the timeout is triggered, this method will return `None`. Otherwise, the method will
307    /// return a boolean indicating whether or not the SDK has successfully initialized.
308    pub async fn wait_for_initialization(&self, timeout: Duration) -> Option<bool> {
309        if timeout > Duration::from_secs(60) {
310            warn!("wait_for_initialization was configured to block for up to {} seconds. We recommend blocking no longer than 60 seconds.", timeout.as_secs());
311        }
312
313        let initialized = tokio::time::timeout(timeout, self.initialized_async_internal()).await;
314        initialized.ok()
315    }
316
317    async fn initialized_async_internal(&self) -> bool {
318        if self.offline || self.daemon_mode {
319            return true;
320        }
321
322        // If the client is not initialized, then we need to wait for it to be initialized.
323        // Because we are using atomic types, and not a lock, then there is still the possibility
324        // that the value will change between the read and when we wait. We use a semaphore to wait,
325        // and we do not forget the permit, therefore if the permit has been added, then we will get
326        // it very quickly and reduce blocking.
327        if ClientInitState::Initialized != self.init_state.load(Ordering::SeqCst) {
328            let _permit = self.init_notify.acquire().await;
329        }
330        ClientInitState::Initialized == self.init_state.load(Ordering::SeqCst)
331    }
332
333    /// This function synchronously returns if the SDK is initialized.
334    /// In the case of unrecoverable errors in establishing a connection it is possible for the
335    /// SDK to never become initialized.
336    pub fn initialized(&self) -> bool {
337        self.offline
338            || self.daemon_mode
339            || ClientInitState::Initialized == self.init_state.load(Ordering::SeqCst)
340    }
341
342    /// Close shuts down the LaunchDarkly client. After calling this, the LaunchDarkly client
343    /// should no longer be used. The method will block until all pending analytics events (if any)
344    /// been sent.
345    pub fn close(&self) {
346        self.event_processor.close();
347
348        // If the system is in offline mode or daemon mode, no receiver will be listening to this
349        // broadcast channel, so sending on it would always result in an error.
350        if !self.offline && !self.daemon_mode {
351            if let Err(e) = self.shutdown_broadcast.send(()) {
352                error!("Failed to shutdown client appropriately: {e}");
353            }
354        }
355
356        // Potentially take the runtime we created when starting the client and do nothing with it
357        // so it drops, closing out all spawned tasks.
358        self.runtime.write().take();
359    }
360
361    /// Flush tells the client that all pending analytics events (if any) should be delivered as
362    /// soon as possible. Flushing is asynchronous, so this method will return before it is
363    /// complete. However, if you call [Client::close], events are guaranteed to be sent before
364    /// that method returns.
365    ///
366    /// For more information, see the Reference Guide:
367    /// <https://docs.launchdarkly.com/sdk/features/flush#rust>.
368    pub fn flush(&self) {
369        self.event_processor.flush();
370    }
371
372    /// Flush tells the client that all pending analytics events should be delivered as
373    /// soon as possible, and blocks until delivery is complete or the timeout expires.
374    ///
375    /// This method is particularly useful in short-lived execution environments like AWS Lambda
376    /// where you need to ensure events are sent before the function terminates.
377    ///
378    /// This method triggers a flush of events currently buffered and waits for that specific
379    /// flush to complete. Note that if periodic flushes or other flush operations are in-flight
380    /// when this is called, those may still be completing after this method returns.
381    ///
382    /// # Arguments
383    ///
384    /// * `timeout` - Maximum time to wait for flush to complete. Use `Duration::ZERO` to wait indefinitely.
385    ///
386    /// # Returns
387    ///
388    /// Returns `true` if flush completed successfully, `false` if timeout occurred.
389    ///
390    /// # Examples
391    ///
392    /// ```no_run
393    /// # use launchdarkly_server_sdk::{Client, ConfigBuilder};
394    /// # use std::time::Duration;
395    /// # async fn example() {
396    /// # let client = Client::build(ConfigBuilder::new("sdk-key").build().unwrap()).unwrap();
397    /// // Wait up to 5 seconds for flush to complete
398    /// let success = client.flush_blocking(Duration::from_secs(5)).await;
399    /// if !success {
400    ///     eprintln!("Warning: flush timed out");
401    /// }
402    /// # }
403    /// ```
404    ///
405    /// For more information, see the Reference Guide:
406    /// <https://docs.launchdarkly.com/sdk/features/flush#rust>.
407    pub async fn flush_blocking(&self, timeout: Duration) -> bool {
408        let event_processor = self.event_processor.clone();
409
410        let flush_future =
411            tokio::task::spawn_blocking(move || event_processor.flush_blocking(timeout));
412
413        if timeout == Duration::ZERO {
414            // Wait indefinitely
415            flush_future.await.unwrap_or(false)
416        } else {
417            // Apply timeout at async level too
418            match tokio::time::timeout(timeout, flush_future).await {
419                Ok(Ok(result)) => result,
420                Ok(Err(_)) => false, // spawn_blocking panicked
421                Err(_) => false,     // Timeout
422            }
423        }
424    }
425
426    /// Identify reports details about a context.
427    ///
428    /// For more information, see the Reference Guide:
429    /// <https://docs.launchdarkly.com/sdk/features/identify#rust>
430    pub fn identify(&self, context: Context) {
431        if self.events_default.disabled {
432            return;
433        }
434
435        self.send_internal(self.events_default.event_factory.new_identify(context));
436    }
437
438    /// Returns the value of a boolean feature flag for a given context.
439    ///
440    /// Returns `default` if there is an error, if the flag doesn't exist, or the feature is turned
441    /// off and has no off variation.
442    ///
443    /// For more information, see the Reference Guide:
444    /// <https://docs.launchdarkly.com/sdk/features/evaluating#rust>.
445    pub fn bool_variation(&self, context: &Context, flag_key: &str, default: bool) -> bool {
446        let val = self
447            .variation_internal(
448                context,
449                flag_key,
450                default,
451                &self.events_default,
452                Some(|v| v.as_bool().is_some()),
453            )
454            .0
455            .value
456            .unwrap();
457        val.as_bool().unwrap_or(default)
458    }
459
460    /// Returns the value of a string feature flag for a given context.
461    ///
462    /// Returns `default` if there is an error, if the flag doesn't exist, or the feature is turned
463    /// off and has no off variation.
464    ///
465    /// For more information, see the Reference Guide:
466    /// <https://docs.launchdarkly.com/sdk/features/evaluating#rust>.
467    pub fn str_variation(&self, context: &Context, flag_key: &str, default: String) -> String {
468        let val = self
469            .variation_internal(
470                context,
471                flag_key,
472                default.clone(),
473                &self.events_default,
474                Some(|v| v.as_string().is_some()),
475            )
476            .0
477            .value
478            .unwrap();
479        val.as_string().unwrap_or(default)
480    }
481
482    /// Returns the value of a float feature flag for a given context.
483    ///
484    /// Returns `default` if there is an error, if the flag doesn't exist, or the feature is turned
485    /// off and has no off variation.
486    ///
487    /// For more information, see the Reference Guide:
488    /// <https://docs.launchdarkly.com/sdk/features/evaluating#rust>.
489    pub fn float_variation(&self, context: &Context, flag_key: &str, default: f64) -> f64 {
490        let val = self
491            .variation_internal(
492                context,
493                flag_key,
494                default,
495                &self.events_default,
496                Some(|v| v.as_float().is_some()),
497            )
498            .0
499            .value
500            .unwrap();
501        val.as_float().unwrap_or(default)
502    }
503
504    /// Returns the value of a integer feature flag for a given context.
505    ///
506    /// Returns `default` if there is an error, if the flag doesn't exist, or the feature is turned
507    /// off and has no off variation.
508    ///
509    /// For more information, see the Reference Guide:
510    /// <https://docs.launchdarkly.com/sdk/features/evaluating#rust>.
511    pub fn int_variation(&self, context: &Context, flag_key: &str, default: i64) -> i64 {
512        let val = self
513            .variation_internal(
514                context,
515                flag_key,
516                default,
517                &self.events_default,
518                Some(|v| v.as_int().is_some()),
519            )
520            .0
521            .value
522            .unwrap();
523        val.as_int().unwrap_or(default)
524    }
525
526    /// Returns the value of a feature flag for the given context, allowing the value to be
527    /// of any JSON type.
528    ///
529    /// The value is returned as an [serde_json::Value].
530    ///
531    /// Returns `default` if there is an error, if the flag doesn't exist, or the feature is turned off.
532    ///
533    /// For more information, see the Reference Guide:
534    /// <https://docs.launchdarkly.com/sdk/features/evaluating#rust>.
535    pub fn json_variation(
536        &self,
537        context: &Context,
538        flag_key: &str,
539        default: serde_json::Value,
540    ) -> serde_json::Value {
541        self.variation(context, flag_key, default.clone())
542            .as_json()
543            .unwrap_or(default)
544    }
545
546    /// This method is the same as [Client::bool_variation], but also returns further information
547    /// about how the value was calculated. The "reason" data will also be included in analytics
548    /// events.
549    ///
550    /// For more information, see the Reference Guide:
551    /// <https://docs.launchdarkly.com/sdk/features/evaluation-reasons#rust>.
552    pub fn bool_variation_detail(
553        &self,
554        context: &Context,
555        flag_key: &str,
556        default: bool,
557    ) -> Detail<bool> {
558        self.variation_internal(
559            context,
560            flag_key,
561            default,
562            &self.events_with_reasons,
563            Some(|v| v.as_bool().is_some()),
564        )
565        .0
566        .try_map(|val| val.as_bool(), default, eval::Error::WrongType)
567    }
568
569    /// This method is the same as [Client::str_variation], but also returns further information
570    /// about how the value was calculated. The "reason" data will also be included in analytics
571    /// events.
572    ///
573    /// For more information, see the Reference Guide:
574    /// <https://docs.launchdarkly.com/sdk/features/evaluation-reasons#rust>.
575    pub fn str_variation_detail(
576        &self,
577        context: &Context,
578        flag_key: &str,
579        default: String,
580    ) -> Detail<String> {
581        self.variation_internal(
582            context,
583            flag_key,
584            default.clone(),
585            &self.events_with_reasons,
586            Some(|v| v.as_string().is_some()),
587        )
588        .0
589        .try_map(|val| val.as_string(), default, eval::Error::WrongType)
590    }
591
592    /// This method is the same as [Client::float_variation], but also returns further information
593    /// about how the value was calculated. The "reason" data will also be included in analytics
594    /// events.
595    ///
596    /// For more information, see the Reference Guide:
597    /// <https://docs.launchdarkly.com/sdk/features/evaluation-reasons#rust>.
598    pub fn float_variation_detail(
599        &self,
600        context: &Context,
601        flag_key: &str,
602        default: f64,
603    ) -> Detail<f64> {
604        self.variation_internal(
605            context,
606            flag_key,
607            default,
608            &self.events_with_reasons,
609            Some(|v| v.as_float().is_some()),
610        )
611        .0
612        .try_map(|val| val.as_float(), default, eval::Error::WrongType)
613    }
614
615    /// This method is the same as [Client::int_variation], but also returns further information
616    /// about how the value was calculated. The "reason" data will also be included in analytics
617    /// events.
618    ///
619    /// For more information, see the Reference Guide:
620    /// <https://docs.launchdarkly.com/sdk/features/evaluation-reasons#rust>.
621    pub fn int_variation_detail(
622        &self,
623        context: &Context,
624        flag_key: &str,
625        default: i64,
626    ) -> Detail<i64> {
627        self.variation_internal(
628            context,
629            flag_key,
630            default,
631            &self.events_with_reasons,
632            Some(|v| v.as_int().is_some()),
633        )
634        .0
635        .try_map(|val| val.as_int(), default, eval::Error::WrongType)
636    }
637
638    /// This method is the same as [Client::json_variation], but also returns further information
639    /// about how the value was calculated. The "reason" data will also be included in analytics
640    /// events.
641    ///
642    /// For more information, see the Reference Guide:
643    /// <https://docs.launchdarkly.com/sdk/features/evaluation-reasons#rust>.
644    pub fn json_variation_detail(
645        &self,
646        context: &Context,
647        flag_key: &str,
648        default: serde_json::Value,
649    ) -> Detail<serde_json::Value> {
650        self.variation_detail(context, flag_key, default.clone())
651            .try_map(|val| val.as_json(), default, eval::Error::WrongType)
652    }
653
654    #[cfg(any(feature = "crypto-aws-lc-rs", feature = "crypto-openssl"))]
655    /// Generates the secure mode hash value for a context.
656    ///
657    /// For more information, see the Reference Guide:
658    /// <https://docs.launchdarkly.com/sdk/features/secure-mode#rust>.
659    pub fn secure_mode_hash(&self, context: &Context) -> Result<String, String> {
660        #[cfg(feature = "crypto-aws-lc-rs")]
661        {
662            let key =
663                aws_lc_rs::hmac::Key::new(aws_lc_rs::hmac::HMAC_SHA256, self.sdk_key.as_bytes());
664            let tag = aws_lc_rs::hmac::sign(&key, context.canonical_key().as_bytes());
665
666            Ok(data_encoding::HEXLOWER.encode(tag.as_ref()))
667        }
668        #[cfg(feature = "crypto-openssl")]
669        {
670            use openssl::hash::MessageDigest;
671            use openssl::pkey::PKey;
672            use openssl::sign::Signer;
673
674            let key = PKey::hmac(self.sdk_key.as_bytes())
675                .map_err(|e| format!("Failed to create HMAC key: {e}"))?;
676            let mut signer = Signer::new(MessageDigest::sha256(), &key)
677                .map_err(|e| format!("Failed to create signer: {e}"))?;
678            signer
679                .update(context.canonical_key().as_bytes())
680                .map_err(|e| format!("Failed to update signer: {e}"))?;
681            let hmac = signer
682                .sign_to_vec()
683                .map_err(|e| format!("Failed to sign: {e}"))?;
684
685            Ok(data_encoding::HEXLOWER.encode(&hmac))
686        }
687    }
688
689    /// Returns an object that encapsulates the state of all feature flags for a given context. This
690    /// includes the flag values, and also metadata that can be used on the front end.
691    ///
692    /// The most common use case for this method is to bootstrap a set of client-side feature flags
693    /// from a back-end service.
694    ///
695    /// You may pass any configuration of [FlagDetailConfig] to control what data is included.
696    ///
697    /// For more information, see the Reference Guide:
698    /// <https://docs.launchdarkly.com/sdk/features/all-flags#rust>
699    pub fn all_flags_detail(
700        &self,
701        context: &Context,
702        flag_state_config: FlagDetailConfig,
703    ) -> FlagDetail {
704        if self.offline {
705            warn!(
706                "all_flags_detail() called, but client is in offline mode. Returning empty state"
707            );
708            return FlagDetail::new(false);
709        }
710
711        if !self.initialized() {
712            warn!("all_flags_detail() called before client has finished initializing! Feature store unavailable - returning empty state");
713            return FlagDetail::new(false);
714        }
715
716        let data_store = self.data_store.read();
717
718        let mut flag_detail = FlagDetail::new(true);
719        flag_detail.populate(&*data_store, context, flag_state_config);
720
721        flag_detail
722    }
723
724    /// This method is the same as [Client::variation], but also returns further information about
725    /// how the value was calculated. The "reason" data will also be included in analytics events.
726    ///
727    /// For more information, see the Reference Guide:
728    /// <https://docs.launchdarkly.com/sdk/features/evaluation-reasons#rust>.
729    pub fn variation_detail<T: Into<FlagValue> + Clone>(
730        &self,
731        context: &Context,
732        flag_key: &str,
733        default: T,
734    ) -> Detail<FlagValue> {
735        let (detail, _) =
736            self.variation_internal(context, flag_key, default, &self.events_with_reasons, None);
737        detail
738    }
739
740    /// This is a generic function which returns the value of a feature flag for a given context.
741    ///
742    /// This method is an alternatively to the type specified methods (e.g.
743    /// [Client::bool_variation], [Client::int_variation], etc.).
744    ///
745    /// Returns `default` if there is an error, if the flag doesn't exist, or the feature is turned
746    /// off and has no off variation.
747    ///
748    /// For more information, see the Reference Guide:
749    /// <https://docs.launchdarkly.com/sdk/features/evaluating#rust>.
750    pub fn variation<T: Into<FlagValue> + Clone>(
751        &self,
752        context: &Context,
753        flag_key: &str,
754        default: T,
755    ) -> FlagValue {
756        let (detail, _) =
757            self.variation_internal(context, flag_key, default, &self.events_default, None);
758        detail.value.unwrap()
759    }
760
761    /// This method returns the migration stage of the migration feature flag for the given
762    /// evaluation context.
763    ///
764    /// This method returns the default stage if there is an error or the flag does not exist.
765    pub fn migration_variation(
766        &self,
767        context: &Context,
768        flag_key: &str,
769        default_stage: Stage,
770    ) -> (Stage, Arc<Mutex<MigrationOpTracker>>) {
771        // A stage is a string. A flag with a value of a different type records the default stage
772        // in the analytics event. A string that is not a known stage still records the flag value.
773        let (detail, flag) = self.variation_internal(
774            context,
775            flag_key,
776            default_stage,
777            &self.events_default,
778            Some(|v| v.as_string().is_some()),
779        );
780
781        let migration_detail =
782            detail.try_map(|v| v.try_into().ok(), default_stage, eval::Error::WrongType);
783        let tracker = MigrationOpTracker::new(
784            flag_key.into(),
785            flag,
786            context.clone(),
787            migration_detail.clone(),
788            default_stage,
789        );
790
791        (
792            migration_detail.value.unwrap_or(default_stage),
793            Arc::new(Mutex::new(tracker)),
794        )
795    }
796
797    /// Reports that a context has performed an event.
798    ///
799    /// The `key` parameter is defined by the application and will be shown in analytics reports;
800    /// it normally corresponds to the event name of a metric that you have created through the
801    /// LaunchDarkly dashboard. If you want to associate additional data with this event, use
802    /// [Client::track_data] or [Client::track_metric].
803    ///
804    /// For more information, see the Reference Guide:
805    /// <https://docs.launchdarkly.com/sdk/features/events#rust>.
806    pub fn track_event(&self, context: Context, key: impl Into<String>) {
807        let _ = self.track(context, key, None, serde_json::Value::Null);
808    }
809
810    /// Reports that a context has performed an event, and associates it with custom data.
811    ///
812    /// The `key` parameter is defined by the application and will be shown in analytics reports;
813    /// it normally corresponds to the event name of a metric that you have created through the
814    /// LaunchDarkly dashboard.
815    ///
816    /// `data` parameter is any type that implements [Serialize]. If no such value is needed, use
817    /// [serde_json::Value::Null] (or call [Client::track_event] instead). To send a numeric value
818    /// for experimentation, use [Client::track_metric].
819    ///
820    /// For more information, see the Reference Guide:
821    /// <https://docs.launchdarkly.com/sdk/features/events#rust>.
822    pub fn track_data(
823        &self,
824        context: Context,
825        key: impl Into<String>,
826        data: impl Serialize,
827    ) -> serde_json::Result<()> {
828        self.track(context, key, None, data)
829    }
830
831    /// Reports that a context has performed an event, and associates it with a numeric value. This
832    /// value is used by the LaunchDarkly experimentation feature in numeric custom metrics, and
833    /// will also be returned as part of the custom event for Data Export.
834    ///
835    /// The `key` parameter is defined by the application and will be shown in analytics reports;
836    /// it normally corresponds to the event name of a metric that you have created through the
837    /// LaunchDarkly dashboard.
838    ///
839    /// For more information, see the Reference Guide:
840    /// <https://docs.launchdarkly.com/sdk/features/events#rust>.
841    pub fn track_metric(
842        &self,
843        context: Context,
844        key: impl Into<String>,
845        value: f64,
846        data: impl Serialize,
847    ) {
848        let _ = self.track(context, key, Some(value), data);
849    }
850
851    fn track(
852        &self,
853        context: Context,
854        key: impl Into<String>,
855        metric_value: Option<f64>,
856        data: impl Serialize,
857    ) -> serde_json::Result<()> {
858        if !self.events_default.disabled {
859            let event =
860                self.events_default
861                    .event_factory
862                    .new_custom(context, key, metric_value, data)?;
863
864            self.send_internal(event);
865        }
866
867        Ok(())
868    }
869
870    /// Tracks the results of a migrations operation. This event includes measurements which can be
871    /// used to enhance the observability of a migration within the LaunchDarkly UI.
872    ///
873    /// This event should be generated through [crate::MigrationOpTracker]. If you are using the
874    /// [crate::Migrator] to handle migrations, this event will be created and emitted
875    /// automatically.
876    pub fn track_migration_op(&self, tracker: Arc<Mutex<MigrationOpTracker>>) {
877        if self.events_default.disabled {
878            return;
879        }
880
881        match tracker.lock() {
882            Ok(tracker) => {
883                let event = tracker.build();
884                match event {
885                    Ok(event) => {
886                        self.send_internal(
887                            self.events_default.event_factory.new_migration_op(event),
888                        );
889                    }
890                    Err(e) => error!("Failed to build migration event, no event will be sent: {e}"),
891                }
892            }
893            Err(e) => error!("Failed to lock migration tracker, no event will be sent: {e}"),
894        }
895    }
896
897    fn variation_internal<T: Into<FlagValue> + Clone>(
898        &self,
899        context: &Context,
900        flag_key: &str,
901        default: T,
902        events_scope: &EventsScope,
903        valid_type: Option<fn(&FlagValue) -> bool>,
904    ) -> (Detail<FlagValue>, Option<eval::Flag>) {
905        if self.offline {
906            return (
907                Detail::err_default(eval::Error::ClientNotReady, default.into()),
908                None,
909            );
910        }
911
912        let (flag, mut result) = match self.initialized() {
913            false => (
914                None,
915                Detail::err_default(eval::Error::ClientNotReady, default.clone().into()),
916            ),
917            true => {
918                let data_store = self.data_store.read();
919                match data_store.flag(flag_key) {
920                    Some(flag) => {
921                        let result = eval::evaluate(
922                            data_store.to_store(),
923                            &flag,
924                            context,
925                            Some(&*events_scope.prerequisite_event_recorder),
926                        )
927                        .map(|v| v.clone())
928                        .or(default.clone().into());
929
930                        (Some(flag), result)
931                    }
932                    None => (
933                        None,
934                        Detail::err_default(eval::Error::FlagNotFound, default.clone().into()),
935                    ),
936                }
937            }
938        };
939
940        if let (Some(valid_type), Some(value)) = (valid_type, result.value.as_ref()) {
941            if !valid_type(value) {
942                warn!("typed variation called for a flag with the wrong type {flag_key:?} (got {value:?})");
943                result = Detail::err_default(eval::Error::WrongType, default.clone().into());
944            }
945        }
946
947        if !events_scope.disabled {
948            let event = match &flag {
949                Some(f) => events_scope.event_factory.new_eval_event(
950                    flag_key,
951                    context.clone(),
952                    f,
953                    result.clone(),
954                    default.into(),
955                    None,
956                ),
957                None => events_scope.event_factory.new_unknown_flag_event(
958                    flag_key,
959                    context.clone(),
960                    result.clone(),
961                    default.into(),
962                ),
963            };
964            self.send_internal(event);
965        }
966
967        (result, flag)
968    }
969
970    fn send_internal(&self, event: InputEvent) {
971        self.event_processor.send(event);
972    }
973}
974
975#[cfg(test)]
976mod tests {
977    use assert_json_diff::assert_json_eq;
978    use crossbeam_channel::Receiver;
979    use eval::{ContextBuilder, MultiContextBuilder};
980    use futures::FutureExt;
981    use launchdarkly_server_sdk_evaluation::{Flag, Reason, Segment};
982    use maplit::hashmap;
983    use std::collections::HashMap;
984    use tokio::time::Instant;
985
986    use crate::data_source::MockDataSource;
987    use crate::data_source_builders::MockDataSourceBuilder;
988    use crate::evaluation::FlagFilter;
989    use crate::events::create_event_sender;
990    use crate::events::event::{OutputEvent, VariationKey};
991    use crate::events::processor_builders::EventProcessorBuilder;
992    use crate::stores::persistent_store::tests::InMemoryPersistentDataStore;
993    use crate::stores::store_types::{PatchTarget, StorageItem};
994    use crate::test_common::{
995        self, basic_flag, basic_flag_with_prereq, basic_flag_with_prereqs_and_visibility,
996        basic_flag_with_visibility, basic_int_flag, basic_migration_flag, basic_off_flag,
997    };
998    use crate::test_data::TestData;
999    use crate::{
1000        AllData, ConfigBuilder, DataSystemBuilder, FlagBuilder, MigratorBuilder,
1001        NullEventProcessorBuilder, Operation, Origin, PersistentDataStore,
1002        PersistentDataStoreBuilder, PersistentDataStoreFactory, SerializedItem,
1003    };
1004    use test_case::test_case;
1005
1006    use super::*;
1007
1008    #[derive(Clone, Copy)]
1009    enum TypedVariation {
1010        Bool,
1011        Str,
1012        Float,
1013        Int,
1014    }
1015
1016    impl TypedVariation {
1017        // A flag whose value has the wrong type for this method.
1018        fn wrong_type_flag(self, key: &str) -> Flag {
1019            let mut flag = basic_flag(key);
1020            if let TypedVariation::Bool = self {
1021                // basic_flag has bool values, so give the bool method string values.
1022                let mut json = serde_json::to_value(&flag).unwrap();
1023                json["variations"] = serde_json::json!(["first", "second"]);
1024                flag = serde_json::from_value(json).unwrap();
1025            }
1026            flag.track_events = true;
1027            flag
1028        }
1029
1030        fn default_value(self) -> serde_json::Value {
1031            match self {
1032                TypedVariation::Bool => serde_json::json!(false),
1033                TypedVariation::Str => serde_json::json!("fallback"),
1034                TypedVariation::Float => serde_json::json!(2.5),
1035                TypedVariation::Int => serde_json::json!(3),
1036            }
1037        }
1038
1039        fn call(self, client: &Client, context: &Context, key: &str) -> serde_json::Value {
1040            match self {
1041                TypedVariation::Bool => {
1042                    serde_json::json!(client.bool_variation(context, key, false))
1043                }
1044                TypedVariation::Str => {
1045                    serde_json::json!(client.str_variation(context, key, "fallback".into()))
1046                }
1047                TypedVariation::Float => {
1048                    serde_json::json!(client.float_variation(context, key, 2.5))
1049                }
1050                TypedVariation::Int => serde_json::json!(client.int_variation(context, key, 3)),
1051            }
1052        }
1053
1054        fn call_detail(
1055            self,
1056            client: &Client,
1057            context: &Context,
1058            key: &str,
1059        ) -> Detail<serde_json::Value> {
1060            match self {
1061                TypedVariation::Bool => client
1062                    .bool_variation_detail(context, key, false)
1063                    .map(serde_json::Value::from),
1064                TypedVariation::Str => client
1065                    .str_variation_detail(context, key, "fallback".into())
1066                    .map(serde_json::Value::from),
1067                TypedVariation::Float => client
1068                    .float_variation_detail(context, key, 2.5)
1069                    .map(serde_json::Value::from),
1070                TypedVariation::Int => client
1071                    .int_variation_detail(context, key, 3)
1072                    .map(serde_json::Value::from),
1073            }
1074        }
1075    }
1076
1077    #[test_case(TypedVariation::Bool, false; "bool")]
1078    #[test_case(TypedVariation::Str, false; "string")]
1079    #[test_case(TypedVariation::Float, false; "float")]
1080    #[test_case(TypedVariation::Int, false; "int")]
1081    #[test_case(TypedVariation::Bool, true; "bool detail")]
1082    #[test_case(TypedVariation::Str, true; "string detail")]
1083    #[test_case(TypedVariation::Float, true; "float detail")]
1084    #[test_case(TypedVariation::Int, true; "int detail")]
1085    #[tokio::test]
1086    async fn wrong_type_event_matches_returned_default(variation: TypedVariation, detailed: bool) {
1087        let td = TestData::new();
1088        td.use_preconfigured_flag(variation.wrong_type_flag("myFlag"));
1089        let (client, event_rx) = make_client_with_test_data(&td);
1090        client.start_with_default_executor();
1091        let context = ContextBuilder::new("bob").build().unwrap();
1092        let expected = variation.default_value();
1093
1094        let actual = if detailed {
1095            let detail = variation.call_detail(&client, &context, "myFlag");
1096            assert!(matches!(
1097                detail.reason,
1098                Reason::Error {
1099                    error: eval::Error::WrongType
1100                }
1101            ));
1102            assert_eq!(detail.variation_index, None);
1103            detail.value.unwrap()
1104        } else {
1105            variation.call(&client, &context, "myFlag")
1106        };
1107        assert_eq!(actual, expected);
1108
1109        client.flush();
1110        client.close();
1111        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
1112
1113        let summary = events
1114            .iter()
1115            .find_map(|event| match event {
1116                OutputEvent::Summary(summary) => Some(summary),
1117                _ => None,
1118            })
1119            .expect("summary event");
1120        let counter = &summary.features["myFlag"].counters[&VariationKey {
1121            version: Some(1),
1122            variation: None,
1123        }];
1124        assert_eq!(counter.value, FlagValue::from(expected.clone()));
1125        assert_eq!(counter.count, 1);
1126
1127        let feature = events
1128            .iter()
1129            .find(|e| e.kind() == "feature")
1130            .expect("tracked event");
1131        let json = serde_json::to_value(feature).unwrap();
1132        let expected_json = serde_json::to_value(FlagValue::from(expected)).unwrap();
1133        assert_eq!(json["value"], expected_json);
1134        assert_eq!(json["default"], expected_json);
1135        assert!(json["variation"].is_null());
1136        if detailed {
1137            assert_eq!(json["reason"]["errorKind"], "WRONG_TYPE");
1138        } else {
1139            assert!(json["reason"].is_null());
1140        }
1141    }
1142
1143    fn is_send_and_sync<T: Send + Sync>() {}
1144
1145    #[test]
1146    fn ensure_client_is_send_and_sync() {
1147        is_send_and_sync::<Client>()
1148    }
1149
1150    #[tokio::test]
1151    async fn client_asynchronously_initializes_within_timeout() {
1152        let (client, _event_rx) = make_mocked_client_with_delay(1000, false, false);
1153        client.start_with_default_executor();
1154
1155        let now = Instant::now();
1156        let initialized = client
1157            .wait_for_initialization(Duration::from_millis(1500))
1158            .await;
1159        let elapsed_time = now.elapsed();
1160        // Give ourself a good margin for thread scheduling.
1161        assert!(elapsed_time.as_millis() > 500);
1162        assert_eq!(initialized, Some(true));
1163    }
1164
1165    #[tokio::test]
1166    async fn client_asynchronously_initializes_slower_than_timeout() {
1167        let (client, _event_rx) = make_mocked_client_with_delay(2000, false, false);
1168        client.start_with_default_executor();
1169
1170        let now = Instant::now();
1171        let initialized = client
1172            .wait_for_initialization(Duration::from_millis(500))
1173            .await;
1174        let elapsed_time = now.elapsed();
1175        // Give ourself a good margin for thread scheduling.
1176        assert!(elapsed_time.as_millis() < 750);
1177        assert!(initialized.is_none());
1178    }
1179
1180    #[tokio::test]
1181    async fn client_initializes_immediately_in_offline_mode() {
1182        let (client, _event_rx) = make_mocked_client_with_delay(1000, true, false);
1183        client.start_with_default_executor();
1184
1185        assert!(client.initialized());
1186
1187        let now = Instant::now();
1188        let initialized = client
1189            .wait_for_initialization(Duration::from_millis(2000))
1190            .await;
1191        let elapsed_time = now.elapsed();
1192        assert_eq!(initialized, Some(true));
1193        assert!(elapsed_time.as_millis() < 500)
1194    }
1195
1196    #[tokio::test]
1197    async fn client_initializes_immediately_in_daemon_mode() {
1198        let (client, _event_rx) = make_mocked_client_with_delay(1000, false, true);
1199        client.start_with_default_executor();
1200
1201        assert!(client.initialized());
1202
1203        let now = Instant::now();
1204        let initialized = client
1205            .wait_for_initialization(Duration::from_millis(2000))
1206            .await;
1207        let elapsed_time = now.elapsed();
1208        assert_eq!(initialized, Some(true));
1209        assert!(elapsed_time.as_millis() < 500)
1210    }
1211
1212    #[test_case(basic_flag("myFlag"), false.into(), true.into())]
1213    #[test_case(basic_int_flag("myFlag"), 0.into(), test_common::FLOAT_TO_INT_MAX.into())]
1214    fn client_updates_changes_evaluation_results(
1215        flag: eval::Flag,
1216        default: FlagValue,
1217        expected: FlagValue,
1218    ) {
1219        let context = ContextBuilder::new("foo")
1220            .build()
1221            .expect("Failed to create context");
1222
1223        let (client, _event_rx) = make_mocked_client();
1224
1225        let result = client.variation_detail(&context, "myFlag", default.clone());
1226        assert_eq!(result.value.unwrap(), default);
1227
1228        client.start_with_default_executor();
1229        client
1230            .data_store
1231            .write()
1232            .upsert(
1233                &flag.key,
1234                PatchTarget::Flag(StorageItem::Item(flag.clone())),
1235            )
1236            .expect("patch should apply");
1237
1238        let result = client.variation_detail(&context, "myFlag", default);
1239        assert_eq!(result.value.unwrap(), expected);
1240        assert!(matches!(
1241            result.reason,
1242            Reason::Fallthrough {
1243                in_experiment: false
1244            }
1245        ));
1246    }
1247
1248    #[test]
1249    fn all_flags_detail_is_invalid_when_offline() {
1250        let (client, _event_rx) = make_mocked_offline_client();
1251        client.start_with_default_executor();
1252
1253        let context = ContextBuilder::new("bob")
1254            .build()
1255            .expect("Failed to create context");
1256
1257        let all_flags = client.all_flags_detail(&context, FlagDetailConfig::new());
1258        assert_json_eq!(all_flags, json!({"$valid": false, "$flagsState" : {}}));
1259    }
1260
1261    #[test]
1262    fn all_flags_detail_is_invalid_when_not_initialized() {
1263        let (client, _event_rx) = make_mocked_client();
1264
1265        let context = ContextBuilder::new("bob")
1266            .build()
1267            .expect("Failed to create context");
1268
1269        let all_flags = client.all_flags_detail(&context, FlagDetailConfig::new());
1270        assert_json_eq!(all_flags, json!({"$valid": false, "$flagsState" : {}}));
1271    }
1272
1273    #[tokio::test]
1274    async fn all_flags_detail_returns_flag_states() {
1275        let td = TestData::new();
1276        td.use_preconfigured_flag(basic_flag("myFlag1"));
1277        td.use_preconfigured_flag(basic_flag("myFlag2"));
1278        let (client, _event_rx) = make_client_with_test_data(&td);
1279        client.start_with_default_executor();
1280
1281        let context = ContextBuilder::new("bob")
1282            .build()
1283            .expect("Failed to create context");
1284
1285        let all_flags = client.all_flags_detail(&context, FlagDetailConfig::new());
1286
1287        client.close();
1288
1289        assert_json_eq!(
1290            all_flags,
1291            json!({
1292                "myFlag1": true,
1293                "myFlag2": true,
1294                "$flagsState": {
1295                    "myFlag1": {
1296                        "version": 1,
1297                        "variation": 1
1298                    },
1299                     "myFlag2": {
1300                        "version": 1,
1301                        "variation": 1
1302                    },
1303                },
1304                "$valid": true
1305            })
1306        );
1307    }
1308
1309    #[tokio::test]
1310    async fn all_flags_detail_returns_prerequisite_relations() {
1311        let td = TestData::new();
1312        td.use_preconfigured_flag(basic_flag("prereq1"));
1313        td.use_preconfigured_flag(basic_flag("prereq2"));
1314        td.use_preconfigured_flag(basic_flag_with_prereqs_and_visibility(
1315            "toplevel",
1316            &["prereq1", "prereq2"],
1317            false,
1318            false,
1319        ));
1320        let (client, _event_rx) = make_client_with_test_data(&td);
1321        client.start_with_default_executor();
1322
1323        let context = ContextBuilder::new("bob")
1324            .build()
1325            .expect("Failed to create context");
1326
1327        let all_flags = client.all_flags_detail(&context, FlagDetailConfig::new());
1328
1329        client.close();
1330
1331        assert_json_eq!(
1332            all_flags,
1333            json!({
1334                "prereq1": true,
1335                "prereq2": true,
1336                "toplevel": true,
1337                "$flagsState": {
1338                    "toplevel": {
1339                        "version": 1,
1340                        "variation": 1,
1341                        "prerequisites": ["prereq1", "prereq2"]
1342                    },
1343                    "prereq1": {
1344                        "version": 1,
1345                        "variation": 1
1346                    },
1347                     "prereq2": {
1348                        "version": 1,
1349                        "variation": 1
1350                    },
1351                },
1352                "$valid": true
1353            })
1354        );
1355    }
1356
1357    #[tokio::test]
1358    async fn all_flags_detail_returns_prerequisite_relations_when_not_visible_to_clients() {
1359        let td = TestData::new();
1360        td.use_preconfigured_flag(basic_flag_with_visibility("prereq1", false, false));
1361        td.use_preconfigured_flag(basic_flag_with_visibility("prereq2", false, false));
1362        td.use_preconfigured_flag(basic_flag_with_prereqs_and_visibility(
1363            "toplevel",
1364            &["prereq1", "prereq2"],
1365            true,
1366            false,
1367        ));
1368        let (client, _event_rx) = make_client_with_test_data(&td);
1369        client.start_with_default_executor();
1370
1371        let context = ContextBuilder::new("bob")
1372            .build()
1373            .expect("Failed to create context");
1374
1375        let mut config = FlagDetailConfig::new();
1376        config.flag_filter(FlagFilter::CLIENT);
1377
1378        let all_flags = client.all_flags_detail(&context, config);
1379
1380        client.close();
1381
1382        assert_json_eq!(
1383            all_flags,
1384            json!({
1385                "toplevel": true,
1386                "$flagsState": {
1387                    "toplevel": {
1388                        "version": 1,
1389                        "variation": 1,
1390                        "prerequisites": ["prereq1", "prereq2"]
1391                    },
1392                },
1393                "$valid": true
1394            })
1395        );
1396    }
1397
1398    #[tokio::test]
1399    async fn variation_tracks_events_correctly() {
1400        let td = TestData::new();
1401        td.use_preconfigured_flag(basic_flag("myFlag"));
1402        let (client, event_rx) = make_client_with_test_data(&td);
1403        client.start_with_default_executor();
1404
1405        let context = ContextBuilder::new("bob")
1406            .build()
1407            .expect("Failed to create context");
1408
1409        let flag_value = client.variation(&context, "myFlag", FlagValue::Bool(false));
1410
1411        assert!(flag_value.as_bool().unwrap());
1412        client.flush();
1413        client.close();
1414
1415        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
1416        assert_eq!(events.len(), 2);
1417        assert_eq!(events[0].kind(), "index");
1418        assert_eq!(events[1].kind(), "summary");
1419
1420        if let OutputEvent::Summary(event_summary) = events[1].clone() {
1421            let variation_key = VariationKey {
1422                version: Some(1),
1423                variation: Some(1),
1424            };
1425            let feature = event_summary.features.get("myFlag");
1426            assert!(feature.is_some());
1427
1428            let feature = feature.unwrap();
1429            assert!(feature.counters.contains_key(&variation_key));
1430        } else {
1431            panic!("Event should be a summary type");
1432        }
1433    }
1434
1435    #[test]
1436    fn variation_handles_offline_mode() {
1437        let (client, event_rx) = make_mocked_offline_client();
1438        client.start_with_default_executor();
1439
1440        let context = ContextBuilder::new("bob")
1441            .build()
1442            .expect("Failed to create context");
1443        let flag_value = client.variation(&context, "myFlag", FlagValue::Bool(false));
1444
1445        assert!(!flag_value.as_bool().unwrap());
1446        client.flush();
1447        client.close();
1448
1449        assert_eq!(event_rx.iter().count(), 0);
1450    }
1451
1452    #[test]
1453    fn variation_handles_unknown_flags() {
1454        let (client, event_rx) = make_mocked_client();
1455        client.start_with_default_executor();
1456        let context = ContextBuilder::new("bob")
1457            .build()
1458            .expect("Failed to create context");
1459
1460        let flag_value = client.variation(&context, "non-existent-flag", FlagValue::Bool(false));
1461
1462        assert!(!flag_value.as_bool().unwrap());
1463        client.flush();
1464        client.close();
1465
1466        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
1467        assert_eq!(events.len(), 2);
1468        assert_eq!(events[0].kind(), "index");
1469        assert_eq!(events[1].kind(), "summary");
1470
1471        if let OutputEvent::Summary(event_summary) = events[1].clone() {
1472            let variation_key = VariationKey {
1473                version: None,
1474                variation: None,
1475            };
1476
1477            let feature = event_summary.features.get("non-existent-flag");
1478            assert!(feature.is_some());
1479
1480            let feature = feature.unwrap();
1481            assert!(feature.counters.contains_key(&variation_key));
1482        } else {
1483            panic!("Event should be a summary type");
1484        }
1485    }
1486
1487    #[tokio::test]
1488    async fn variation_detail_handles_debug_events_correctly() {
1489        let td = TestData::new();
1490        let mut flag = basic_flag("myFlag");
1491        flag.debug_events_until_date = Some(64_060_606_800_000); // Jan. 1st, 4000
1492        td.use_preconfigured_flag(flag);
1493        let (client, event_rx) = make_client_with_test_data(&td);
1494        client.start_with_default_executor();
1495
1496        let context = ContextBuilder::new("bob")
1497            .build()
1498            .expect("Failed to create context");
1499
1500        let detail = client.variation_detail(&context, "myFlag", FlagValue::Bool(false));
1501
1502        assert!(detail.value.unwrap().as_bool().unwrap());
1503        assert!(matches!(
1504            detail.reason,
1505            Reason::Fallthrough {
1506                in_experiment: false
1507            }
1508        ));
1509        client.flush();
1510        client.close();
1511
1512        let events = event_rx.try_iter().collect::<Vec<OutputEvent>>();
1513        assert_eq!(events.len(), 3);
1514        assert_eq!(events[0].kind(), "index");
1515        assert_eq!(events[1].kind(), "debug");
1516        assert_eq!(events[2].kind(), "summary");
1517
1518        if let OutputEvent::Summary(event_summary) = events[2].clone() {
1519            let variation_key = VariationKey {
1520                version: Some(1),
1521                variation: Some(1),
1522            };
1523
1524            let feature = event_summary.features.get("myFlag");
1525            assert!(feature.is_some());
1526
1527            let feature = feature.unwrap();
1528            assert!(feature.counters.contains_key(&variation_key));
1529        } else {
1530            panic!("Event should be a summary type");
1531        }
1532    }
1533
1534    #[tokio::test]
1535    async fn variation_detail_tracks_events_correctly() {
1536        let td = TestData::new();
1537        td.use_preconfigured_flag(basic_flag("myFlag"));
1538        let (client, event_rx) = make_client_with_test_data(&td);
1539        client.start_with_default_executor();
1540
1541        let context = ContextBuilder::new("bob")
1542            .build()
1543            .expect("Failed to create context");
1544
1545        let detail = client.variation_detail(&context, "myFlag", FlagValue::Bool(false));
1546
1547        assert!(detail.value.unwrap().as_bool().unwrap());
1548        assert!(matches!(
1549            detail.reason,
1550            Reason::Fallthrough {
1551                in_experiment: false
1552            }
1553        ));
1554        client.flush();
1555        client.close();
1556
1557        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
1558        assert_eq!(events.len(), 2);
1559        assert_eq!(events[0].kind(), "index");
1560        assert_eq!(events[1].kind(), "summary");
1561
1562        if let OutputEvent::Summary(event_summary) = events[1].clone() {
1563            let variation_key = VariationKey {
1564                version: Some(1),
1565                variation: Some(1),
1566            };
1567
1568            let feature = event_summary.features.get("myFlag");
1569            assert!(feature.is_some());
1570
1571            let feature = feature.unwrap();
1572            assert!(feature.counters.contains_key(&variation_key));
1573        } else {
1574            panic!("Event should be a summary type");
1575        }
1576    }
1577
1578    #[test]
1579    fn variation_detail_handles_offline_mode() {
1580        let (client, event_rx) = make_mocked_offline_client();
1581        client.start_with_default_executor();
1582
1583        let context = ContextBuilder::new("bob")
1584            .build()
1585            .expect("Failed to create context");
1586
1587        let detail = client.variation_detail(&context, "myFlag", FlagValue::Bool(false));
1588
1589        assert!(!detail.value.unwrap().as_bool().unwrap());
1590        assert!(matches!(
1591            detail.reason,
1592            Reason::Error {
1593                error: eval::Error::ClientNotReady
1594            }
1595        ));
1596        client.flush();
1597        client.close();
1598
1599        assert_eq!(event_rx.iter().count(), 0);
1600    }
1601
1602    struct InMemoryPersistentDataStoreFactory {
1603        data: AllData<Flag, Segment>,
1604        initialized: bool,
1605    }
1606
1607    impl PersistentDataStoreFactory for InMemoryPersistentDataStoreFactory {
1608        fn create_persistent_data_store(
1609            &self,
1610        ) -> Result<Box<dyn PersistentDataStore + 'static>, std::io::Error> {
1611            let serialized_data =
1612                AllData::<SerializedItem, SerializedItem>::try_from(self.data.clone())?;
1613            Ok(Box::new(InMemoryPersistentDataStore {
1614                data: serialized_data,
1615                initialized: self.initialized,
1616            }))
1617        }
1618    }
1619
1620    #[test]
1621    fn variation_detail_handles_daemon_mode() {
1622        testing_logger::setup();
1623        let factory = InMemoryPersistentDataStoreFactory {
1624            data: AllData {
1625                flags: hashmap!["flag".into() => basic_flag("flag")],
1626                segments: HashMap::new(),
1627            },
1628            initialized: true,
1629        };
1630        let builder = PersistentDataStoreBuilder::new(Arc::new(factory));
1631
1632        let config = ConfigBuilder::new("sdk-key")
1633            .daemon_mode(true)
1634            .data_store(&builder)
1635            .event_processor(&NullEventProcessorBuilder::new())
1636            .build()
1637            .expect("config should build");
1638
1639        let client = Client::build(config).expect("Should be built.");
1640
1641        client.start_with_default_executor();
1642
1643        let context = ContextBuilder::new("bob")
1644            .build()
1645            .expect("Failed to create context");
1646
1647        let detail = client.variation_detail(&context, "flag", FlagValue::Bool(false));
1648
1649        assert!(detail.value.unwrap().as_bool().unwrap());
1650        assert!(matches!(
1651            detail.reason,
1652            Reason::Fallthrough {
1653                in_experiment: false
1654            }
1655        ));
1656        client.flush();
1657        client.close();
1658
1659        testing_logger::validate(|captured_logs| {
1660            assert_eq!(captured_logs.len(), 1);
1661            assert_eq!(
1662                captured_logs[0].body,
1663                "Started LaunchDarkly Client in daemon mode"
1664            );
1665        });
1666    }
1667
1668    #[test]
1669    fn daemon_mode_is_quiet_if_store_is_not_initialized() {
1670        testing_logger::setup();
1671
1672        let factory = InMemoryPersistentDataStoreFactory {
1673            data: AllData {
1674                flags: HashMap::new(),
1675                segments: HashMap::new(),
1676            },
1677            initialized: false,
1678        };
1679        let builder = PersistentDataStoreBuilder::new(Arc::new(factory));
1680
1681        let config = ConfigBuilder::new("sdk-key")
1682            .daemon_mode(true)
1683            .data_store(&builder)
1684            .event_processor(&NullEventProcessorBuilder::new())
1685            .build()
1686            .expect("config should build");
1687
1688        let client = Client::build(config).expect("Should be built.");
1689
1690        client.start_with_default_executor();
1691
1692        let context = ContextBuilder::new("bob")
1693            .build()
1694            .expect("Failed to create context");
1695
1696        client.variation_detail(&context, "flag", FlagValue::Bool(false));
1697
1698        testing_logger::validate(|captured_logs| {
1699            assert_eq!(captured_logs.len(), 1);
1700            assert_eq!(
1701                captured_logs[0].body,
1702                "Started LaunchDarkly Client in daemon mode"
1703            );
1704        });
1705    }
1706
1707    #[tokio::test]
1708    async fn variation_handles_off_flag_without_variation() {
1709        let td = TestData::new();
1710        td.use_preconfigured_flag(basic_off_flag("myFlag"));
1711        let (client, event_rx) = make_client_with_test_data(&td);
1712        client.start_with_default_executor();
1713
1714        let context = ContextBuilder::new("bob")
1715            .build()
1716            .expect("Failed to create context");
1717
1718        let result = client.variation(&context, "myFlag", FlagValue::Bool(false));
1719
1720        assert!(!result.as_bool().unwrap());
1721        client.flush();
1722        client.close();
1723
1724        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
1725        assert_eq!(events.len(), 2);
1726        assert_eq!(events[0].kind(), "index");
1727        assert_eq!(events[1].kind(), "summary");
1728
1729        if let OutputEvent::Summary(event_summary) = events[1].clone() {
1730            let variation_key = VariationKey {
1731                version: Some(1),
1732                variation: None,
1733            };
1734            let feature = event_summary.features.get("myFlag");
1735            assert!(feature.is_some());
1736
1737            let feature = feature.unwrap();
1738            assert!(feature.counters.contains_key(&variation_key));
1739        } else {
1740            panic!("Event should be a summary type");
1741        }
1742    }
1743
1744    #[tokio::test]
1745    async fn variation_detail_tracks_prereq_events_correctly() {
1746        let td = TestData::new();
1747        let mut prereq_flag = basic_flag("prereqFlag");
1748        prereq_flag.track_events = true;
1749        td.use_preconfigured_flag(prereq_flag);
1750
1751        let mut main_flag = basic_flag_with_prereq("myFlag", "prereqFlag");
1752        main_flag.track_events = true;
1753        td.use_preconfigured_flag(main_flag);
1754
1755        let (client, event_rx) = make_client_with_test_data(&td);
1756        client.start_with_default_executor();
1757
1758        let context = ContextBuilder::new("bob")
1759            .build()
1760            .expect("Failed to create context");
1761
1762        let detail = client.variation_detail(&context, "myFlag", FlagValue::Bool(false));
1763
1764        assert!(detail.value.unwrap().as_bool().unwrap());
1765        assert!(matches!(
1766            detail.reason,
1767            Reason::Fallthrough {
1768                in_experiment: false
1769            }
1770        ));
1771        client.flush();
1772        client.close();
1773
1774        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
1775        assert_eq!(events.len(), 4);
1776        assert_eq!(events[0].kind(), "index");
1777        assert_eq!(events[1].kind(), "feature");
1778        assert_eq!(events[2].kind(), "feature");
1779        assert_eq!(events[3].kind(), "summary");
1780
1781        if let OutputEvent::Summary(event_summary) = events[3].clone() {
1782            let variation_key = VariationKey {
1783                version: Some(1),
1784                variation: Some(1),
1785            };
1786            let feature = event_summary.features.get("myFlag");
1787            assert!(feature.is_some());
1788
1789            let feature = feature.unwrap();
1790            assert!(feature.counters.contains_key(&variation_key));
1791
1792            let variation_key = VariationKey {
1793                version: Some(1),
1794                variation: Some(1),
1795            };
1796            let feature = event_summary.features.get("prereqFlag");
1797            assert!(feature.is_some());
1798
1799            let feature = feature.unwrap();
1800            assert!(feature.counters.contains_key(&variation_key));
1801        }
1802    }
1803
1804    #[tokio::test]
1805    async fn variation_handles_failed_prereqs_correctly() {
1806        let td = TestData::new();
1807        let mut prereq_flag = basic_off_flag("prereqFlag");
1808        prereq_flag.track_events = true;
1809        td.use_preconfigured_flag(prereq_flag);
1810
1811        let mut main_flag = basic_flag_with_prereq("myFlag", "prereqFlag");
1812        main_flag.track_events = true;
1813        td.use_preconfigured_flag(main_flag);
1814
1815        let (client, event_rx) = make_client_with_test_data(&td);
1816        client.start_with_default_executor();
1817
1818        let context = ContextBuilder::new("bob")
1819            .build()
1820            .expect("Failed to create context");
1821
1822        let detail = client.variation(&context, "myFlag", FlagValue::Bool(false));
1823
1824        assert!(!detail.as_bool().unwrap());
1825        client.flush();
1826        client.close();
1827
1828        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
1829        assert_eq!(events.len(), 4);
1830        assert_eq!(events[0].kind(), "index");
1831        assert_eq!(events[1].kind(), "feature");
1832        assert_eq!(events[2].kind(), "feature");
1833        assert_eq!(events[3].kind(), "summary");
1834
1835        if let OutputEvent::Summary(event_summary) = events[3].clone() {
1836            let variation_key = VariationKey {
1837                version: Some(1),
1838                variation: Some(0),
1839            };
1840            let feature = event_summary.features.get("myFlag");
1841            assert!(feature.is_some());
1842
1843            let feature = feature.unwrap();
1844            assert!(feature.counters.contains_key(&variation_key));
1845
1846            let variation_key = VariationKey {
1847                version: Some(1),
1848                variation: None,
1849            };
1850            let feature = event_summary.features.get("prereqFlag");
1851            assert!(feature.is_some());
1852
1853            let feature = feature.unwrap();
1854            assert!(feature.counters.contains_key(&variation_key));
1855        }
1856    }
1857
1858    #[test]
1859    fn variation_detail_handles_flag_not_found() {
1860        let (client, event_rx) = make_mocked_client();
1861        client.start_with_default_executor();
1862
1863        let context = ContextBuilder::new("bob")
1864            .build()
1865            .expect("Failed to create context");
1866        let detail = client.variation_detail(&context, "non-existent-flag", FlagValue::Bool(false));
1867
1868        assert!(!detail.value.unwrap().as_bool().unwrap());
1869        assert!(matches!(
1870            detail.reason,
1871            Reason::Error {
1872                error: eval::Error::FlagNotFound
1873            }
1874        ));
1875        client.flush();
1876        client.close();
1877
1878        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
1879        assert_eq!(events.len(), 2);
1880        assert_eq!(events[0].kind(), "index");
1881        assert_eq!(events[1].kind(), "summary");
1882
1883        if let OutputEvent::Summary(event_summary) = events[1].clone() {
1884            let variation_key = VariationKey {
1885                version: None,
1886                variation: None,
1887            };
1888            let feature = event_summary.features.get("non-existent-flag");
1889            assert!(feature.is_some());
1890
1891            let feature = feature.unwrap();
1892            assert!(feature.counters.contains_key(&variation_key));
1893        } else {
1894            panic!("Event should be a summary type");
1895        }
1896    }
1897
1898    #[tokio::test]
1899    async fn variation_detail_handles_client_not_ready() {
1900        let (client, event_rx) = make_mocked_client_with_delay(u64::MAX, false, false);
1901        client.start_with_default_executor();
1902        let context = ContextBuilder::new("bob")
1903            .build()
1904            .expect("Failed to create context");
1905
1906        let detail = client.variation_detail(&context, "non-existent-flag", FlagValue::Bool(false));
1907
1908        assert!(!detail.value.unwrap().as_bool().unwrap());
1909        assert!(matches!(
1910            detail.reason,
1911            Reason::Error {
1912                error: eval::Error::ClientNotReady
1913            }
1914        ));
1915        client.flush();
1916        client.close();
1917
1918        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
1919        assert_eq!(events.len(), 2);
1920        assert_eq!(events[0].kind(), "index");
1921        assert_eq!(events[1].kind(), "summary");
1922
1923        if let OutputEvent::Summary(event_summary) = events[1].clone() {
1924            let variation_key = VariationKey {
1925                version: None,
1926                variation: None,
1927            };
1928            let feature = event_summary.features.get("non-existent-flag");
1929            assert!(feature.is_some());
1930
1931            let feature = feature.unwrap();
1932            assert!(feature.counters.contains_key(&variation_key));
1933        } else {
1934            panic!("Event should be a summary type");
1935        }
1936    }
1937
1938    #[test]
1939    fn identify_sends_identify_event() {
1940        let (client, event_rx) = make_mocked_client();
1941        client.start_with_default_executor();
1942
1943        let context = ContextBuilder::new("bob")
1944            .build()
1945            .expect("Failed to create context");
1946
1947        client.identify(context);
1948        client.flush();
1949        client.close();
1950
1951        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
1952        assert_eq!(events.len(), 1);
1953        assert_eq!(events[0].kind(), "identify");
1954    }
1955
1956    #[test]
1957    fn identify_sends_sends_nothing_in_offline_mode() {
1958        let (client, event_rx) = make_mocked_offline_client();
1959        client.start_with_default_executor();
1960
1961        let context = ContextBuilder::new("bob")
1962            .build()
1963            .expect("Failed to create context");
1964
1965        client.identify(context);
1966        client.flush();
1967        client.close();
1968
1969        assert_eq!(event_rx.iter().count(), 0);
1970    }
1971
1972    #[test]
1973    #[cfg(any(feature = "crypto-aws-lc-rs", feature = "crypto-openssl"))]
1974    fn secure_mode_hash() {
1975        let config = ConfigBuilder::new("secret")
1976            .offline(true)
1977            .build()
1978            .expect("config should build");
1979        let client = Client::build(config).expect("Should be built.");
1980        let context = ContextBuilder::new("Message")
1981            .build()
1982            .expect("Failed to create context");
1983
1984        assert_eq!(
1985            client
1986                .secure_mode_hash(&context)
1987                .expect("Hash should be computed"),
1988            "aa747c502a898200f9e4fa21bac68136f886a0e27aec70ba06daf2e2a5cb5597"
1989        );
1990    }
1991
1992    #[test]
1993    #[cfg(any(feature = "crypto-aws-lc-rs", feature = "crypto-openssl"))]
1994    fn secure_mode_hash_with_multi_kind() {
1995        let config = ConfigBuilder::new("secret")
1996            .offline(true)
1997            .build()
1998            .expect("config should build");
1999        let client = Client::build(config).expect("Should be built.");
2000
2001        let org = ContextBuilder::new("org-key|1")
2002            .kind("org")
2003            .build()
2004            .expect("Failed to create context");
2005        let user = ContextBuilder::new("user-key:2")
2006            .build()
2007            .expect("Failed to create context");
2008
2009        let context = MultiContextBuilder::new()
2010            .add_context(org)
2011            .add_context(user)
2012            .build()
2013            .expect("failed to build multi-context");
2014
2015        assert_eq!(
2016            client
2017                .secure_mode_hash(&context)
2018                .expect("Hash should be computed"),
2019            "5687e6383b920582ed50c2a96c98a115f1b6aad85a60579d761d9b8797415163"
2020        );
2021    }
2022
2023    #[derive(Serialize)]
2024    struct MyCustomData {
2025        pub answer: u32,
2026    }
2027
2028    #[test]
2029    fn track_sends_track_and_index_events() -> serde_json::Result<()> {
2030        let (client, event_rx) = make_mocked_client();
2031        client.start_with_default_executor();
2032
2033        let context = ContextBuilder::new("bob")
2034            .build()
2035            .expect("Failed to create context");
2036
2037        client.track_event(context.clone(), "event-with-null");
2038        client.track_data(context.clone(), "event-with-string", "string-data")?;
2039        client.track_data(context.clone(), "event-with-json", json!({"answer": 42}))?;
2040        client.track_data(
2041            context.clone(),
2042            "event-with-struct",
2043            MyCustomData { answer: 42 },
2044        )?;
2045        client.track_metric(context, "event-with-metric", 42.0, serde_json::Value::Null);
2046
2047        client.flush();
2048        client.close();
2049
2050        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
2051        assert_eq!(events.len(), 6);
2052
2053        let mut events_by_type: HashMap<&str, usize> = HashMap::new();
2054        for event in events {
2055            if let Some(count) = events_by_type.get_mut(event.kind()) {
2056                *count += 1;
2057            } else {
2058                events_by_type.insert(event.kind(), 1);
2059            }
2060        }
2061        assert!(matches!(events_by_type.get("index"), Some(1)));
2062        assert!(matches!(events_by_type.get("custom"), Some(5)));
2063
2064        Ok(())
2065    }
2066
2067    #[test]
2068    fn track_sends_nothing_in_offline_mode() -> serde_json::Result<()> {
2069        let (client, event_rx) = make_mocked_offline_client();
2070        client.start_with_default_executor();
2071
2072        let context = ContextBuilder::new("bob")
2073            .build()
2074            .expect("Failed to create context");
2075
2076        client.track_event(context.clone(), "event-with-null");
2077        client.track_data(context.clone(), "event-with-string", "string-data")?;
2078        client.track_data(context.clone(), "event-with-json", json!({"answer": 42}))?;
2079        client.track_data(
2080            context.clone(),
2081            "event-with-struct",
2082            MyCustomData { answer: 42 },
2083        )?;
2084        client.track_metric(context, "event-with-metric", 42.0, serde_json::Value::Null);
2085
2086        client.flush();
2087        client.close();
2088
2089        assert_eq!(event_rx.iter().count(), 0);
2090
2091        Ok(())
2092    }
2093
2094    #[test]
2095    fn migration_handles_flag_not_found() {
2096        let (client, _event_rx) = make_mocked_client();
2097        client.start_with_default_executor();
2098
2099        let context = ContextBuilder::new("bob")
2100            .build()
2101            .expect("Failed to create context");
2102
2103        let (stage, _tracker) =
2104            client.migration_variation(&context, "non-existent-flag-key", Stage::Off);
2105
2106        assert_eq!(stage, Stage::Off);
2107    }
2108
2109    #[tokio::test]
2110    async fn migration_uses_non_migration_flag() {
2111        let td = TestData::new();
2112        td.use_preconfigured_flag(basic_flag("boolean-flag"));
2113        let (client, _event_rx) = make_client_with_test_data(&td);
2114        client.start_with_default_executor();
2115
2116        let context = ContextBuilder::new("bob")
2117            .build()
2118            .expect("Failed to create context");
2119
2120        let (stage, _tracker) = client.migration_variation(&context, "boolean-flag", Stage::Off);
2121
2122        assert_eq!(stage, Stage::Off);
2123    }
2124
2125    #[tokio::test]
2126    async fn migration_wrong_type_event_records_default_stage() {
2127        let td = TestData::new();
2128        let mut flag = basic_flag("boolean-flag");
2129        flag.track_events = true;
2130        td.use_preconfigured_flag(flag);
2131        let (client, event_rx) = make_client_with_test_data(&td);
2132        client.start_with_default_executor();
2133        let context = ContextBuilder::new("bob").build().unwrap();
2134
2135        let (stage, _tracker) = client.migration_variation(&context, "boolean-flag", Stage::Live);
2136        assert_eq!(stage, Stage::Live);
2137
2138        client.flush();
2139        client.close();
2140        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
2141        let feature = events
2142            .iter()
2143            .find(|e| e.kind() == "feature")
2144            .expect("tracked event");
2145        let json = serde_json::to_value(feature).unwrap();
2146        assert_eq!(json["value"], "live");
2147        assert_eq!(json["default"], "live");
2148        assert!(json["variation"].is_null());
2149
2150        let summary = events
2151            .iter()
2152            .find_map(|event| match event {
2153                OutputEvent::Summary(summary) => Some(summary),
2154                _ => None,
2155            })
2156            .expect("summary event");
2157        let counter = &summary.features["boolean-flag"].counters[&VariationKey {
2158            version: Some(1),
2159            variation: None,
2160        }];
2161        assert_eq!(counter.value, FlagValue::from("live".to_string()));
2162    }
2163
2164    #[test_case(Stage::Off)]
2165    #[test_case(Stage::DualWrite)]
2166    #[test_case(Stage::Shadow)]
2167    #[test_case(Stage::Live)]
2168    #[test_case(Stage::Rampdown)]
2169    #[test_case(Stage::Complete)]
2170    #[tokio::test]
2171    async fn migration_can_determine_correct_stage_from_flag(stage: Stage) {
2172        let td = TestData::new();
2173        td.use_preconfigured_flag(basic_migration_flag("stage-flag", stage));
2174        let (client, _event_rx) = make_client_with_test_data(&td);
2175        client.start_with_default_executor();
2176
2177        let context = ContextBuilder::new("bob")
2178            .build()
2179            .expect("Failed to create context");
2180
2181        let (evaluated_stage, _tracker) =
2182            client.migration_variation(&context, "stage-flag", Stage::Off);
2183
2184        assert_eq!(evaluated_stage, stage);
2185    }
2186
2187    #[tokio::test]
2188    async fn migration_tracks_invoked_correctly() {
2189        migration_tracks_invoked_correctly_driver(Stage::Off, Operation::Read, vec![Origin::Old])
2190            .await;
2191        migration_tracks_invoked_correctly_driver(
2192            Stage::DualWrite,
2193            Operation::Read,
2194            vec![Origin::Old],
2195        )
2196        .await;
2197        migration_tracks_invoked_correctly_driver(
2198            Stage::Shadow,
2199            Operation::Read,
2200            vec![Origin::Old, Origin::New],
2201        )
2202        .await;
2203        migration_tracks_invoked_correctly_driver(
2204            Stage::Live,
2205            Operation::Read,
2206            vec![Origin::Old, Origin::New],
2207        )
2208        .await;
2209        migration_tracks_invoked_correctly_driver(
2210            Stage::Rampdown,
2211            Operation::Read,
2212            vec![Origin::New],
2213        )
2214        .await;
2215        migration_tracks_invoked_correctly_driver(
2216            Stage::Complete,
2217            Operation::Read,
2218            vec![Origin::New],
2219        )
2220        .await;
2221        migration_tracks_invoked_correctly_driver(Stage::Off, Operation::Write, vec![Origin::Old])
2222            .await;
2223        migration_tracks_invoked_correctly_driver(
2224            Stage::DualWrite,
2225            Operation::Write,
2226            vec![Origin::Old, Origin::New],
2227        )
2228        .await;
2229        migration_tracks_invoked_correctly_driver(
2230            Stage::Shadow,
2231            Operation::Write,
2232            vec![Origin::Old, Origin::New],
2233        )
2234        .await;
2235        migration_tracks_invoked_correctly_driver(
2236            Stage::Live,
2237            Operation::Write,
2238            vec![Origin::Old, Origin::New],
2239        )
2240        .await;
2241        migration_tracks_invoked_correctly_driver(
2242            Stage::Rampdown,
2243            Operation::Write,
2244            vec![Origin::Old, Origin::New],
2245        )
2246        .await;
2247        migration_tracks_invoked_correctly_driver(
2248            Stage::Complete,
2249            Operation::Write,
2250            vec![Origin::New],
2251        )
2252        .await;
2253    }
2254
2255    async fn migration_tracks_invoked_correctly_driver(
2256        stage: Stage,
2257        operation: Operation,
2258        origins: Vec<Origin>,
2259    ) {
2260        let td = TestData::new();
2261        td.use_preconfigured_flag(basic_migration_flag("stage-flag", stage));
2262        let (client, event_rx) = make_client_with_test_data(&td);
2263        let client = Arc::new(client);
2264        client.start_with_default_executor();
2265
2266        let mut migrator = MigratorBuilder::new(client.clone())
2267            .read(
2268                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
2269                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
2270                Some(|_, _| true),
2271            )
2272            .write(
2273                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
2274                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
2275            )
2276            .build()
2277            .expect("migrator should build");
2278
2279        let context = ContextBuilder::new("bob")
2280            .build()
2281            .expect("Failed to create context");
2282
2283        if let Operation::Read = operation {
2284            migrator
2285                .read(
2286                    &context,
2287                    "stage-flag".into(),
2288                    Stage::Off,
2289                    serde_json::Value::Null,
2290                )
2291                .await;
2292        } else {
2293            migrator
2294                .write(
2295                    &context,
2296                    "stage-flag".into(),
2297                    Stage::Off,
2298                    serde_json::Value::Null,
2299                )
2300                .await;
2301        }
2302
2303        client.flush();
2304        client.close();
2305
2306        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
2307        assert_eq!(events.len(), 3);
2308        match &events[1] {
2309            OutputEvent::MigrationOp(event) => {
2310                assert!(event.invoked.len() == origins.len());
2311                assert!(event.invoked.iter().all(|i| origins.contains(i)));
2312            }
2313            _ => panic!("Expected migration event"),
2314        }
2315    }
2316
2317    #[tokio::test]
2318    async fn migration_tracks_latency() {
2319        migration_tracks_latency_driver(Stage::Off, Operation::Read, vec![Origin::Old]).await;
2320        migration_tracks_latency_driver(Stage::DualWrite, Operation::Read, vec![Origin::Old]).await;
2321        migration_tracks_latency_driver(
2322            Stage::Shadow,
2323            Operation::Read,
2324            vec![Origin::Old, Origin::New],
2325        )
2326        .await;
2327        migration_tracks_latency_driver(
2328            Stage::Live,
2329            Operation::Read,
2330            vec![Origin::Old, Origin::New],
2331        )
2332        .await;
2333        migration_tracks_latency_driver(Stage::Rampdown, Operation::Read, vec![Origin::New]).await;
2334        migration_tracks_latency_driver(Stage::Complete, Operation::Read, vec![Origin::New]).await;
2335        migration_tracks_latency_driver(Stage::Off, Operation::Write, vec![Origin::Old]).await;
2336        migration_tracks_latency_driver(
2337            Stage::DualWrite,
2338            Operation::Write,
2339            vec![Origin::Old, Origin::New],
2340        )
2341        .await;
2342        migration_tracks_latency_driver(
2343            Stage::Shadow,
2344            Operation::Write,
2345            vec![Origin::Old, Origin::New],
2346        )
2347        .await;
2348        migration_tracks_latency_driver(
2349            Stage::Live,
2350            Operation::Write,
2351            vec![Origin::Old, Origin::New],
2352        )
2353        .await;
2354        migration_tracks_latency_driver(
2355            Stage::Rampdown,
2356            Operation::Write,
2357            vec![Origin::Old, Origin::New],
2358        )
2359        .await;
2360        migration_tracks_latency_driver(Stage::Complete, Operation::Write, vec![Origin::New]).await;
2361    }
2362
2363    async fn migration_tracks_latency_driver(
2364        stage: Stage,
2365        operation: Operation,
2366        origins: Vec<Origin>,
2367    ) {
2368        let td = TestData::new();
2369        td.use_preconfigured_flag(basic_migration_flag("stage-flag", stage));
2370        let (client, event_rx) = make_client_with_test_data(&td);
2371        let client = Arc::new(client);
2372        client.start_with_default_executor();
2373
2374        let mut migrator = MigratorBuilder::new(client.clone())
2375            .track_latency(true)
2376            .read(
2377                |_| {
2378                    async move {
2379                        async_std::task::sleep(Duration::from_millis(100)).await;
2380                        Ok(serde_json::Value::Null)
2381                    }
2382                    .boxed()
2383                },
2384                |_| {
2385                    async move {
2386                        async_std::task::sleep(Duration::from_millis(100)).await;
2387                        Ok(serde_json::Value::Null)
2388                    }
2389                    .boxed()
2390                },
2391                Some(|_, _| true),
2392            )
2393            .write(
2394                |_| {
2395                    async move {
2396                        async_std::task::sleep(Duration::from_millis(100)).await;
2397                        Ok(serde_json::Value::Null)
2398                    }
2399                    .boxed()
2400                },
2401                |_| {
2402                    async move {
2403                        async_std::task::sleep(Duration::from_millis(100)).await;
2404                        Ok(serde_json::Value::Null)
2405                    }
2406                    .boxed()
2407                },
2408            )
2409            .build()
2410            .expect("migrator should build");
2411
2412        let context = ContextBuilder::new("bob")
2413            .build()
2414            .expect("Failed to create context");
2415
2416        if let Operation::Read = operation {
2417            migrator
2418                .read(
2419                    &context,
2420                    "stage-flag".into(),
2421                    Stage::Off,
2422                    serde_json::Value::Null,
2423                )
2424                .await;
2425        } else {
2426            migrator
2427                .write(
2428                    &context,
2429                    "stage-flag".into(),
2430                    Stage::Off,
2431                    serde_json::Value::Null,
2432                )
2433                .await;
2434        }
2435
2436        client.flush();
2437        client.close();
2438
2439        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
2440        assert_eq!(events.len(), 3);
2441        match &events[1] {
2442            OutputEvent::MigrationOp(event) => {
2443                assert!(event.latency.len() == origins.len());
2444                assert!(event
2445                    .latency
2446                    .values()
2447                    .all(|l| l > &Duration::from_millis(100)));
2448            }
2449            _ => panic!("Expected migration event"),
2450        }
2451    }
2452
2453    #[tokio::test]
2454    async fn migration_tracks_read_errors() {
2455        migration_tracks_read_errors_driver(Stage::Off, vec![Origin::Old]).await;
2456        migration_tracks_read_errors_driver(Stage::DualWrite, vec![Origin::Old]).await;
2457        migration_tracks_read_errors_driver(Stage::Shadow, vec![Origin::Old, Origin::New]).await;
2458        migration_tracks_read_errors_driver(Stage::Live, vec![Origin::Old, Origin::New]).await;
2459        migration_tracks_read_errors_driver(Stage::Rampdown, vec![Origin::New]).await;
2460        migration_tracks_read_errors_driver(Stage::Complete, vec![Origin::New]).await;
2461    }
2462
2463    async fn migration_tracks_read_errors_driver(stage: Stage, origins: Vec<Origin>) {
2464        let td = TestData::new();
2465        td.use_preconfigured_flag(basic_migration_flag("stage-flag", stage));
2466        let (client, event_rx) = make_client_with_test_data(&td);
2467        let client = Arc::new(client);
2468        client.start_with_default_executor();
2469
2470        let mut migrator = MigratorBuilder::new(client.clone())
2471            .track_latency(true)
2472            .read(
2473                |_| async move { Err("fail".into()) }.boxed(),
2474                |_| async move { Err("fail".into()) }.boxed(),
2475                Some(|_: &String, _: &String| true),
2476            )
2477            .write(
2478                |_| async move { Err("fail".into()) }.boxed(),
2479                |_| async move { Err("fail".into()) }.boxed(),
2480            )
2481            .build()
2482            .expect("migrator should build");
2483
2484        let context = ContextBuilder::new("bob")
2485            .build()
2486            .expect("Failed to create context");
2487
2488        migrator
2489            .read(
2490                &context,
2491                "stage-flag".into(),
2492                Stage::Off,
2493                serde_json::Value::Null,
2494            )
2495            .await;
2496        client.flush();
2497        client.close();
2498
2499        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
2500        assert_eq!(events.len(), 3);
2501        match &events[1] {
2502            OutputEvent::MigrationOp(event) => {
2503                assert!(event.errors.len() == origins.len());
2504                assert!(event.errors.iter().all(|i| origins.contains(i)));
2505            }
2506            _ => panic!("Expected migration event"),
2507        }
2508    }
2509
2510    #[tokio::test]
2511    async fn migration_tracks_authoritative_write_errors() {
2512        migration_tracks_authoritative_write_errors_driver(Stage::Off, vec![Origin::Old]).await;
2513        migration_tracks_authoritative_write_errors_driver(Stage::DualWrite, vec![Origin::Old])
2514            .await;
2515        migration_tracks_authoritative_write_errors_driver(Stage::Shadow, vec![Origin::Old]).await;
2516        migration_tracks_authoritative_write_errors_driver(Stage::Live, vec![Origin::New]).await;
2517        migration_tracks_authoritative_write_errors_driver(Stage::Rampdown, vec![Origin::New])
2518            .await;
2519        migration_tracks_authoritative_write_errors_driver(Stage::Complete, vec![Origin::New])
2520            .await;
2521    }
2522
2523    async fn migration_tracks_authoritative_write_errors_driver(
2524        stage: Stage,
2525        origins: Vec<Origin>,
2526    ) {
2527        let td = TestData::new();
2528        td.use_preconfigured_flag(basic_migration_flag("stage-flag", stage));
2529        let (client, event_rx) = make_client_with_test_data(&td);
2530        let client = Arc::new(client);
2531        client.start_with_default_executor();
2532
2533        let mut migrator = MigratorBuilder::new(client.clone())
2534            .track_latency(true)
2535            .read(
2536                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
2537                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
2538                None,
2539            )
2540            .write(
2541                |_| async move { Err("fail".into()) }.boxed(),
2542                |_| async move { Err("fail".into()) }.boxed(),
2543            )
2544            .build()
2545            .expect("migrator should build");
2546
2547        let context = ContextBuilder::new("bob")
2548            .build()
2549            .expect("Failed to create context");
2550
2551        migrator
2552            .write(
2553                &context,
2554                "stage-flag".into(),
2555                Stage::Off,
2556                serde_json::Value::Null,
2557            )
2558            .await;
2559
2560        client.flush();
2561        client.close();
2562
2563        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
2564        assert_eq!(events.len(), 3);
2565        match &events[1] {
2566            OutputEvent::MigrationOp(event) => {
2567                assert!(event.errors.len() == origins.len());
2568                assert!(event.errors.iter().all(|i| origins.contains(i)));
2569            }
2570            _ => panic!("Expected migration event"),
2571        }
2572    }
2573
2574    #[tokio::test]
2575    async fn migration_tracks_nonauthoritative_write_errors() {
2576        migration_tracks_nonauthoritative_write_errors_driver(
2577            Stage::DualWrite,
2578            false,
2579            true,
2580            vec![Origin::New],
2581        )
2582        .await;
2583        migration_tracks_nonauthoritative_write_errors_driver(
2584            Stage::Shadow,
2585            false,
2586            true,
2587            vec![Origin::New],
2588        )
2589        .await;
2590        migration_tracks_nonauthoritative_write_errors_driver(
2591            Stage::Live,
2592            true,
2593            false,
2594            vec![Origin::Old],
2595        )
2596        .await;
2597        migration_tracks_nonauthoritative_write_errors_driver(
2598            Stage::Rampdown,
2599            true,
2600            false,
2601            vec![Origin::Old],
2602        )
2603        .await;
2604    }
2605
2606    async fn migration_tracks_nonauthoritative_write_errors_driver(
2607        stage: Stage,
2608        fail_old: bool,
2609        fail_new: bool,
2610        origins: Vec<Origin>,
2611    ) {
2612        let td = TestData::new();
2613        td.use_preconfigured_flag(basic_migration_flag("stage-flag", stage));
2614        let (client, event_rx) = make_client_with_test_data(&td);
2615        let client = Arc::new(client);
2616        client.start_with_default_executor();
2617
2618        let mut migrator = MigratorBuilder::new(client.clone())
2619            .track_latency(true)
2620            .read(
2621                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
2622                |_| async move { Ok(serde_json::Value::Null) }.boxed(),
2623                None,
2624            )
2625            .write(
2626                move |_| {
2627                    async move {
2628                        if fail_old {
2629                            Err("fail".into())
2630                        } else {
2631                            Ok(serde_json::Value::Null)
2632                        }
2633                    }
2634                    .boxed()
2635                },
2636                move |_| {
2637                    async move {
2638                        if fail_new {
2639                            Err("fail".into())
2640                        } else {
2641                            Ok(serde_json::Value::Null)
2642                        }
2643                    }
2644                    .boxed()
2645                },
2646            )
2647            .build()
2648            .expect("migrator should build");
2649
2650        let context = ContextBuilder::new("bob")
2651            .build()
2652            .expect("Failed to create context");
2653
2654        migrator
2655            .write(
2656                &context,
2657                "stage-flag".into(),
2658                Stage::Off,
2659                serde_json::Value::Null,
2660            )
2661            .await;
2662
2663        client.flush();
2664        client.close();
2665
2666        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
2667        assert_eq!(events.len(), 3);
2668        match &events[1] {
2669            OutputEvent::MigrationOp(event) => {
2670                assert!(event.errors.len() == origins.len());
2671                assert!(event.errors.iter().all(|i| origins.contains(i)));
2672            }
2673            _ => panic!("Expected migration event"),
2674        }
2675    }
2676
2677    #[tokio::test]
2678    async fn migration_tracks_consistency() {
2679        migration_tracks_consistency_driver(Stage::Shadow, "same", "same", true).await;
2680        migration_tracks_consistency_driver(Stage::Shadow, "same", "different", false).await;
2681        migration_tracks_consistency_driver(Stage::Live, "same", "same", true).await;
2682        migration_tracks_consistency_driver(Stage::Live, "same", "different", false).await;
2683    }
2684
2685    async fn migration_tracks_consistency_driver(
2686        stage: Stage,
2687        old_return: &'static str,
2688        new_return: &'static str,
2689        expected_consistency: bool,
2690    ) {
2691        let td = TestData::new();
2692        td.use_preconfigured_flag(basic_migration_flag("stage-flag", stage));
2693        let (client, event_rx) = make_client_with_test_data(&td);
2694        let client = Arc::new(client);
2695        client.start_with_default_executor();
2696
2697        let mut migrator = MigratorBuilder::new(client.clone())
2698            .track_latency(true)
2699            .read(
2700                |_| {
2701                    async move {
2702                        async_std::task::sleep(Duration::from_millis(100)).await;
2703                        Ok(serde_json::Value::String(old_return.to_string()))
2704                    }
2705                    .boxed()
2706                },
2707                |_| {
2708                    async move {
2709                        async_std::task::sleep(Duration::from_millis(100)).await;
2710                        Ok(serde_json::Value::String(new_return.to_string()))
2711                    }
2712                    .boxed()
2713                },
2714                Some(|lhs, rhs| lhs == rhs),
2715            )
2716            .write(
2717                |_| {
2718                    async move {
2719                        async_std::task::sleep(Duration::from_millis(100)).await;
2720                        Ok(serde_json::Value::Null)
2721                    }
2722                    .boxed()
2723                },
2724                |_| {
2725                    async move {
2726                        async_std::task::sleep(Duration::from_millis(100)).await;
2727                        Ok(serde_json::Value::Null)
2728                    }
2729                    .boxed()
2730                },
2731            )
2732            .build()
2733            .expect("migrator should build");
2734
2735        let context = ContextBuilder::new("bob")
2736            .build()
2737            .expect("Failed to create context");
2738
2739        migrator
2740            .read(
2741                &context,
2742                "stage-flag".into(),
2743                Stage::Off,
2744                serde_json::Value::Null,
2745            )
2746            .await;
2747
2748        client.flush();
2749        client.close();
2750
2751        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
2752        assert_eq!(events.len(), 3);
2753        match &events[1] {
2754            OutputEvent::MigrationOp(event) => {
2755                assert!(event.consistency_check == Some(expected_consistency))
2756            }
2757            _ => panic!("Expected migration event"),
2758        }
2759    }
2760
2761    #[tokio::test]
2762    async fn client_flush_blocking_completes_successfully() {
2763        let (client, event_rx) = make_mocked_client();
2764        client.start_with_default_executor();
2765        client.wait_for_initialization(Duration::from_secs(1)).await;
2766
2767        let context = ContextBuilder::new("user-key")
2768            .build()
2769            .expect("Failed to create context");
2770
2771        client.identify(context);
2772
2773        let result = client.flush_blocking(Duration::from_secs(5)).await;
2774        assert!(result, "flush_blocking should complete successfully");
2775
2776        client.close();
2777
2778        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
2779        assert!(!events.is_empty(), "Should have received identify event");
2780    }
2781
2782    #[tokio::test]
2783    async fn client_flush_blocking_with_zero_timeout() {
2784        let (client, event_rx) = make_mocked_client();
2785        client.start_with_default_executor();
2786        client.wait_for_initialization(Duration::from_secs(1)).await;
2787
2788        let context = ContextBuilder::new("user-key")
2789            .build()
2790            .expect("Failed to create context");
2791
2792        client.identify(context);
2793
2794        let result = client.flush_blocking(Duration::ZERO).await;
2795        assert!(
2796            result,
2797            "flush_blocking with zero timeout should complete successfully"
2798        );
2799
2800        client.close();
2801
2802        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
2803        assert!(!events.is_empty(), "Should have received identify event");
2804    }
2805
2806    #[tokio::test]
2807    async fn client_flush_blocking_with_no_events() {
2808        let (client, _event_rx) = make_mocked_client();
2809        client.start_with_default_executor();
2810        client.wait_for_initialization(Duration::from_secs(1)).await;
2811
2812        let result = client.flush_blocking(Duration::from_secs(1)).await;
2813        assert!(
2814            result,
2815            "flush_blocking with no events should complete immediately"
2816        );
2817
2818        client.close();
2819    }
2820
2821    #[tokio::test]
2822    async fn client_flush_blocking_multiple_concurrent_calls() {
2823        let (client, event_rx) = make_mocked_client();
2824        client.start_with_default_executor();
2825        client.wait_for_initialization(Duration::from_secs(1)).await;
2826
2827        let context = ContextBuilder::new("user-key")
2828            .build()
2829            .expect("Failed to create context");
2830
2831        client.identify(context);
2832
2833        // Make multiple concurrent flush_blocking calls
2834        let (result1, result2, result3) = tokio::join!(
2835            client.flush_blocking(Duration::from_secs(5)),
2836            client.flush_blocking(Duration::from_secs(5)),
2837            client.flush_blocking(Duration::from_secs(5)),
2838        );
2839
2840        assert!(result1, "First flush_blocking should succeed");
2841        assert!(result2, "Second flush_blocking should succeed");
2842        assert!(result3, "Third flush_blocking should succeed");
2843
2844        client.close();
2845
2846        let events = event_rx.iter().collect::<Vec<OutputEvent>>();
2847        assert!(!events.is_empty(), "Should have received identify event");
2848    }
2849
2850    fn make_mocked_client_with_delay(
2851        delay: u64,
2852        offline: bool,
2853        daemon_mode: bool,
2854    ) -> (Client, Receiver<OutputEvent>) {
2855        let updates = Arc::new(MockDataSource::new_with_init_delay(delay));
2856        let (event_sender, event_rx) = create_event_sender();
2857
2858        let config = ConfigBuilder::new("sdk-key")
2859            .offline(offline)
2860            .daemon_mode(daemon_mode)
2861            .data_source(MockDataSourceBuilder::new().data_source(updates))
2862            .event_processor(
2863                EventProcessorBuilder::<launchdarkly_sdk_transport::HyperTransport>::new()
2864                    .event_sender(Arc::new(event_sender)),
2865            )
2866            .build()
2867            .expect("config should build");
2868
2869        let client = Client::build(config).expect("Should be built.");
2870
2871        (client, event_rx)
2872    }
2873
2874    fn make_mocked_offline_client() -> (Client, Receiver<OutputEvent>) {
2875        make_mocked_client_with_delay(0, true, false)
2876    }
2877
2878    fn make_mocked_client() -> (Client, Receiver<OutputEvent>) {
2879        make_mocked_client_with_delay(0, false, false)
2880    }
2881
2882    fn make_client_with_test_data(td: &TestData) -> (Client, Receiver<OutputEvent>) {
2883        let (event_sender, event_rx) = create_event_sender();
2884        let config = ConfigBuilder::new("sdk-key")
2885            .data_source(td)
2886            .event_processor(
2887                EventProcessorBuilder::<launchdarkly_sdk_transport::HyperTransport>::new()
2888                    .event_sender(Arc::new(event_sender)),
2889            )
2890            .build()
2891            .expect("config should build");
2892        let client = Client::build(config).expect("Should be built.");
2893        (client, event_rx)
2894    }
2895
2896    fn make_client_with_test_data_fdv2(td: &TestData) -> Client {
2897        let mut data_system = DataSystemBuilder::custom();
2898        data_system.synchronizer(td.clone());
2899        let config = ConfigBuilder::new("sdk-key")
2900            .data_system(&data_system)
2901            .event_processor(&NullEventProcessorBuilder::new())
2902            .build()
2903            .expect("config should build");
2904        Client::build(config).expect("Should be built.")
2905    }
2906
2907    /// Polls `condition` until it holds, failing after a bounded wait. FDv2
2908    /// delivers test-data updates asynchronously, so callers wait for them.
2909    async fn wait_until(mut condition: impl FnMut() -> bool) {
2910        for _ in 0..100 {
2911            if condition() {
2912                return;
2913            }
2914            tokio::time::sleep(Duration::from_millis(10)).await;
2915        }
2916        panic!("condition was not met within the timeout");
2917    }
2918
2919    #[tokio::test]
2920    async fn fdv2_test_data_serves_and_updates_flags() {
2921        let td = TestData::new();
2922        td.update(FlagBuilder::new("my-flag").variation_for_all(true));
2923
2924        let client = make_client_with_test_data_fdv2(&td);
2925        client.start_with_default_executor();
2926        client.wait_for_initialization(Duration::from_secs(5)).await;
2927
2928        let context = ContextBuilder::new("user")
2929            .build()
2930            .expect("context should build");
2931
2932        // The initial full payload is served through the FDv2 data system.
2933        assert!(client.bool_variation(&context, "my-flag", false));
2934
2935        // A later update propagates asynchronously to the running client.
2936        td.update(FlagBuilder::new("my-flag").variation_for_all(false));
2937        wait_until(|| !client.bool_variation(&context, "my-flag", true)).await;
2938
2939        client.close();
2940    }
2941
2942    #[test]
2943    fn client_builds_successfully() {
2944        let config = ConfigBuilder::new("sdk-key")
2945            .offline(true)
2946            .build()
2947            .expect("config should build");
2948
2949        let client = Client::build(config).expect("client should build successfully");
2950
2951        assert!(
2952            !client.started.load(Ordering::SeqCst),
2953            "client should not be started yet"
2954        );
2955        assert!(client.offline, "client should be in offline mode");
2956        assert_eq!(client.sdk_key, "sdk-key", "sdk_key should match");
2957    }
2958}