Exemple #1
0
        /// <summary>
        /// Creates a new client to connect to LaunchDarkly with a custom configuration.
        /// </summary>
        /// <remarks>
        /// <para>
        /// Applications should instantiate a single instance for the lifetime of the application. In
        /// unusual cases where an application needs to evaluate feature flags from different LaunchDarkly
        /// projects or environments, you may create multiple clients, but they should still be retained
        /// for the lifetime of the application rather than created per request or per thread.
        /// </para>
        /// <para>
        /// Normally, the client will begin attempting to connect to LaunchDarkly as soon as you call the
        /// constructor. The constructor returns as soon as any of the following things has happened:
        /// </para>
        /// <list type="number">
        /// <item><description> It has successfully connected to LaunchDarkly and received feature flag data. In this
        /// case, <see cref="Initialized"/> will be true, and the <see cref="DataSourceStatusProvider"/>
        /// will return a state of <see cref="DataSourceState.Valid"/>. </description></item>
        /// <item><description> It has not succeeded in connecting within the <see cref="ConfigurationBuilder.StartWaitTime(TimeSpan)"/>
        /// timeout (the default for this is 5 seconds). This could happen due to a network problem or a
        /// temporary service outage. In this case, <see cref="Initialized"/> will be false, and the
        /// <see cref="DataSourceStatusProvider"/> will return a state of <see cref="DataSourceState.Initializing"/>,
        /// indicating that the SDK will still continue trying to connect in the background. </description></item>
        /// <item><description> It has encountered an unrecoverable error: for instance, LaunchDarkly has rejected the
        /// SDK key. Since an invalid key will not become valid, the SDK will not retry in this case.
        /// <see cref="Initialized"/> will be false, and the <see cref="DataSourceStatusProvider"/> will
        /// return a state of <see cref="DataSourceState.Off"/>. </description></item>
        /// </list>
        /// <para>
        /// If you have specified <see cref="ConfigurationBuilder.Offline"/> mode or
        /// <see cref="Components.ExternalUpdatesOnly"/>, the constructor returns immediately without
        /// trying to connect to LaunchDarkly.
        /// </para>
        /// <para>
        /// Failure to connect to LaunchDarkly will never cause the constructor to throw an exception.
        /// Under any circumstance where it is not able to get feature flag data from LaunchDarkly (and
        /// therefore <see cref="Initialized"/> is false), if it does not have any other source of data
        /// (such as a persistent data store) then feature flag evaluations will behave the same as if
        /// the flags were not found: that is, they will return whatever default value is specified in
        /// your code.
        /// </para>
        /// </remarks>
        /// <param name="config">a client configuration object (which includes an SDK key)</param>
        /// <example>
        /// <code>
        ///     var config = Configuration.Builder("my-sdk-key")
        ///         .AllAttributesPrivate(true)
        ///         .EventCapacity(1000)
        ///         .Build();
        ///     var client = new LDClient(config);
        /// </code>
        /// </example>
        /// <seealso cref="LdClient.LdClient(string)"/>
        public LdClient(Configuration config)
        {
            _configuration = config;

            var logConfig = (config.LoggingConfigurationFactory ?? Components.Logging())
                            .CreateLoggingConfiguration();

            _log = logConfig.LogAdapter.Logger(logConfig.BaseLoggerName ?? LogNames.DefaultBase);
            _log.Info("Starting LaunchDarkly client {0}",
                      AssemblyVersions.GetAssemblyVersionStringForType(typeof(LdClient)));
            _evalLog = _log.SubLogger(LogNames.EvaluationSubLog);

            var basicConfig = new BasicConfiguration(config, _log);
            var httpConfig  = (config.HttpConfigurationFactory ?? Components.HttpConfiguration())
                              .CreateHttpConfiguration(basicConfig);
            ServerDiagnosticStore diagnosticStore = _configuration.DiagnosticOptOut ? null :
                                                    new ServerDiagnosticStore(_configuration, basicConfig, httpConfig);

            var taskExecutor = new TaskExecutor(this, _log);

            var clientContext = new LdClientContext(basicConfig, httpConfig, diagnosticStore, taskExecutor);

            var dataStoreUpdates = new DataStoreUpdatesImpl(taskExecutor, _log.SubLogger(LogNames.DataStoreSubLog));

            _dataStore = (_configuration.DataStoreFactory ?? Components.InMemoryDataStore)
                         .CreateDataStore(clientContext, dataStoreUpdates);
            _dataStoreStatusProvider = new DataStoreStatusProviderImpl(_dataStore, dataStoreUpdates);

            var bigSegmentsConfig = (_configuration.BigSegmentsConfigurationFactory ?? Components.BigSegments(null))
                                    .CreateBigSegmentsConfiguration(clientContext);

            _bigSegmentStoreWrapper = bigSegmentsConfig.Store is null ? null :
                                      new BigSegmentStoreWrapper(
                bigSegmentsConfig,
                taskExecutor,
                _log.SubLogger(LogNames.BigSegmentsSubLog)
                );
            _bigSegmentStoreStatusProvider = new BigSegmentStoreStatusProviderImpl(_bigSegmentStoreWrapper);

            _evaluator = new Evaluator(
                GetFlag,
                GetSegment,
                _bigSegmentStoreWrapper == null ? (Func <string, BigSegmentsInternalTypes.BigSegmentsQueryResult>)null :
                _bigSegmentStoreWrapper.GetUserMembership,
                _log
                );

            var eventProcessorFactory =
                config.Offline ? Components.NoEvents :
                (_configuration.EventProcessorFactory ?? Components.SendEvents());

            _eventProcessor = eventProcessorFactory.CreateEventProcessor(clientContext);

            var dataSourceUpdates = new DataSourceUpdatesImpl(_dataStore, _dataStoreStatusProvider,
                                                              taskExecutor, _log, logConfig.LogDataSourceOutageAsErrorAfter);
            IDataSourceFactory dataSourceFactory =
                config.Offline ? Components.ExternalUpdatesOnly :
                (_configuration.DataSourceFactory ?? Components.StreamingDataSource());

            _dataSource = dataSourceFactory.CreateDataSource(clientContext, dataSourceUpdates);
            _dataSourceStatusProvider = new DataSourceStatusProviderImpl(dataSourceUpdates);
            _flagTracker = new FlagTrackerImpl(dataSourceUpdates,
                                               (string key, User user) => JsonVariation(key, user, LdValue.Null));

            var initTask = _dataSource.Start();

            if (!(_dataSource is ComponentsImpl.NullDataSource))
            {
                _log.Info("Waiting up to {0} milliseconds for LaunchDarkly client to start...",
                          _configuration.StartWaitTime.TotalMilliseconds);
            }

            try
            {
                var success = initTask.Wait(_configuration.StartWaitTime);
                if (!success)
                {
                    _log.Warn("Timeout encountered waiting for LaunchDarkly client initialization");
                }
            }
            catch (AggregateException)
            {
                // StreamProcessor may throw an exception if initialization fails, because we want that behavior
                // in the Xamarin client. However, for backward compatibility we do not want to throw exceptions
                // from the LdClient constructor in the .NET client, so we'll just swallow this.
            }
        }
Exemple #2
0
        LdClient(Configuration configuration, User user, TimeSpan startWaitTime)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            _config = configuration ?? throw new ArgumentNullException(nameof(configuration));
            var diagnosticStore = _config.DiagnosticOptOut ? null :
                                  new ClientDiagnosticStore(_config, startWaitTime);
            var diagnosticDisabler = _config.DiagnosticOptOut ? null :
                                     new DiagnosticDisablerImpl();

            _context      = new LdClientContext(configuration, this, diagnosticStore, diagnosticDisabler);
            _log          = _context.BaseLogger;
            _taskExecutor = _context.TaskExecutor;
            diagnosticStore?.SetContext(_context);

            _log.Info("Starting LaunchDarkly Client {0}", Version);

            var persistenceConfiguration = (configuration.PersistenceConfigurationBuilder ?? Components.Persistence())
                                           .CreatePersistenceConfiguration(_context);

            _dataStore = new FlagDataManager(
                configuration.MobileKey,
                persistenceConfiguration,
                _log.SubLogger(LogNames.DataStoreSubLog)
                );

            _userDecorator = new UserDecorator(configuration.DeviceInfo ?? new DefaultDeviceInfo(),
                                               _dataStore.PersistentStore);
            _user = _userDecorator.DecorateUser(user);

            // If we had cached data for the new user, set the current in-memory flag data state to use
            // that data, so that any Variation calls made before Identify has completed will use the
            // last known values.
            var cachedData = _dataStore.GetCachedData(_user);

            if (cachedData != null)
            {
                _log.Debug("Cached flag data is available for this user");
                _dataStore.Init(_user, cachedData.Value, false); // false means "don't rewrite the flags to persistent storage"
            }

            var dataSourceUpdateSink = new DataSourceUpdateSinkImpl(
                _dataStore,
                configuration.Offline,
                _taskExecutor,
                _log.SubLogger(LogNames.DataSourceSubLog)
                );

            _dataSourceUpdateSink = dataSourceUpdateSink;

            _dataSourceStatusProvider = new DataSourceStatusProviderImpl(dataSourceUpdateSink);
            _flagTracker = new FlagTrackerImpl(dataSourceUpdateSink);

            var dataSourceFactory = configuration.DataSourceFactory ?? Components.StreamingDataSource();

            _connectivityStateManager = Factory.CreateConnectivityStateManager(configuration);
            var isConnected = _connectivityStateManager.IsConnected;

            diagnosticDisabler?.SetDisabled(!isConnected || configuration.Offline);

            _eventProcessor = (configuration.EventProcessorFactory ?? Components.SendEvents())
                              .CreateEventProcessor(_context);
            _eventProcessor.SetOffline(configuration.Offline || !isConnected);

            _connectionManager = new ConnectionManager(
                _context,
                dataSourceFactory,
                _dataSourceUpdateSink,
                _eventProcessor,
                diagnosticDisabler,
                configuration.EnableBackgroundUpdating,
                _user,
                _log
                );
            _connectionManager.SetForceOffline(configuration.Offline);
            _connectionManager.SetNetworkEnabled(isConnected);
            if (configuration.Offline)
            {
                _log.Info("Starting LaunchDarkly client in offline mode");
            }

            _connectivityStateManager.ConnectionChanged += networkAvailable =>
            {
                _log.Debug("Setting online to {0} due to a connectivity change event", networkAvailable);
                _ = _connectionManager.SetNetworkEnabled(networkAvailable);  // do not await the result
            };

            // Send an initial identify event, but only if we weren't explicitly set to be offline

            if (!configuration.Offline)
            {
                _eventProcessor.RecordIdentifyEvent(new EventProcessorTypes.IdentifyEvent
                {
                    Timestamp = UnixMillisecondTime.Now,
                    User      = user
                });
            }

            _backgroundModeManager = _config.BackgroundModeManager ?? new DefaultBackgroundModeManager();
            _backgroundModeManager.BackgroundModeChanged += OnBackgroundModeChanged;
        }