Ejemplo n.º 1
0
        ///// <summary>
        ///// Initializes a new instance of Unleash client.
        ///// </summary>
        public Unleash(UnleashSettings settings, IUnleashServices services, IUnleashContextProvider contextProvider)
        {
            this.settings        = settings;
            this.services        = services ?? throw new ArgumentNullException(nameof(services));
            this.contextProvider = contextProvider ?? throw new ArgumentNullException(nameof(contextProvider));

            Logger.Info($"UNLEASH: Unleash is initialized and configured with: {settings}");
        }
        private static string PrependFileName(this UnleashSettings unleashSettings, string filename)
        {
            var invalidFileNameChars = Path.GetInvalidFileNameChars();

            var extension = Path.GetExtension(filename);
            var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filename);

            return(new string($"{fileNameWithoutExtension}-{unleashSettings.AppName}-{unleashSettings.InstanceTag}-{SdkVersionHelper.SdkVersion}{extension}"
                              .Where(c => !invalidFileNameChars.Contains(c))
                              .ToArray()));
        }
Ejemplo n.º 3
0
        ///// <summary>
        ///// Initializes a new instance of Unleash client.
        ///// </summary>
        ///// <param name="config">Unleash settings</param>
        ///// <param name="strategies">Available strategies. When none defined, all default strategies will be added.</param>
        public DefaultUnleash(UnleashSettings settings, params IStrategy[] strategies)
        {
            var settingsValidator = new UnleashSettingsValidator();

            settingsValidator.Validate(settings);

            strategyMap = BuildStrategyMap(DefaultStragegies, strategies);

            services = new UnleashServices(settings, strategyMap);

            Logger.Info($"UNLEASH: Unleash is initialized and configured with: {settings}");
        }
        internal static IUnleashServiceCollection AddUnleash(this IServiceCollection serviceCollection, Action <UnleashSettings> settingsInitializer, IConfiguration configuration, Action <UnleashSettings> settingsOverrider)
        {
            if (serviceCollection == null)
            {
                throw new ArgumentNullException(nameof(serviceCollection));
            }

            var result = new UnleashServiceCollection(serviceCollection, configuration);

            var settings = new UnleashSettings();

            settingsInitializer?.Invoke(settings);
            configuration?.Bind(settings);
            settingsOverrider?.Invoke(settings);
            SettingsValidator.Validate(settings);

            var unleashApiClientRequestHeaders = new UnleashApiClientRequestHeaders
            {
                AppName           = settings.AppName,
                CustomHttpHeaders = settings.CustomHttpHeaders,
                InstanceTag       = settings.InstanceTag
            };

            serviceCollection.AddSingleton(settings);
            serviceCollection.AddSingleton <IRandom>(new UnleashRandom());
            serviceCollection.AddSingleton(serviceProvider => serviceProvider.GetService <IEnumerable <IStrategy> >()?.ToArray() ?? Array.Empty <IStrategy>());

            // Internal services
            serviceCollection.AddSingleton <NewtonsoftJsonSerializerSettings>();
            serviceCollection.AddSingleton <IJsonSerializer, NewtonsoftJsonSerializer>();
            serviceCollection.AddSingleton(unleashApiClientRequestHeaders);

            serviceCollection.AddSingleton <IHttpClientFactory, DefaultHttpClientFactory>();
            serviceCollection.AddSingleton <IUnleashApiClientFactory, DefaultUnleashApiClientFactory>();

            serviceCollection.AddSingleton <IUnleashApiClient, UnleashApiClient>();

            serviceCollection.AddSingleton <IUnleashServices, UnleashServices>();

            // Default: SystemTimer scheduled task manager
            serviceCollection.AddSingleton <IUnleashScheduledTaskManager, SystemTimerScheduledTaskManager>();

            // Default: Disk-based JSON toggle collection cache
            serviceCollection.AddSingleton <IFileSystem, FileSystem>();
            serviceCollection.AddSingleton <IToggleCollectionCache, FileSystemToggleCollectionCache>();

            serviceCollection.AddScoped <IUnleashContextProvider, DefaultUnleashContextProvider>();
            serviceCollection.AddScoped <IUnleash, Unleash>();

            return(result);
        }
        public UnleashContext ApplyStaticFields(UnleashSettings settings)
        {
            var builder = new Builder(this);

            if (string.IsNullOrEmpty(Environment))
            {
                builder.Environment(settings.Environment);
            }

            if (string.IsNullOrEmpty(AppName))
            {
                builder.AppName(settings.AppName);
            }

            return(builder.Build());
        }
Ejemplo n.º 6
0
        public UnleashServices(UnleashSettings settings, Dictionary <string, IStrategy> strategyMap)
        {
            var fileSystem = settings.FileSystem ?? new FileSystem(settings.Encoding);

            var backupFile     = settings.GetFeatureToggleFilePath();
            var etagBackupFile = settings.GetFeatureToggleETagFilePath();

            // Cancellation
            CancellationToken = cancellationTokenSource.Token;
            ContextProvider   = settings.UnleashContextProvider;


            var loader            = new CachedFilesLoader(settings.JsonSerializer, fileSystem, backupFile, etagBackupFile);
            var cachedFilesResult = loader.EnsureExistsAndLoad();

            ToggleCollection = new ThreadSafeToggleCollection
            {
                Instance = cachedFilesResult.InitialToggleCollection ?? new ToggleCollection()
            };

            MetricsBucket = new ThreadSafeMetricsBucket();

            IUnleashApiClient apiClient;

            if (settings.UnleashApiClient == null)
            {
                var httpClient = settings.HttpClientFactory.Create(settings.UnleashApi);
                apiClient = new UnleashApiClient(httpClient, settings.JsonSerializer, new UnleashApiClientRequestHeaders()
                {
                    AppName           = settings.AppName,
                    InstanceTag       = settings.InstanceTag,
                    CustomHttpHeaders = settings.CustomHttpHeaders
                });
                if (settings.LoadTogglesImmediately)
                {
                    var toggles = apiClient.FetchToggles("", CancellationToken.None);
                    ToggleCollection.Instance = toggles.Result.ToggleCollection;
                }
            }
            else
            {
                // Mocked backend: fill instance collection
                apiClient = settings.UnleashApiClient;
                var toggles = apiClient.FetchToggles("", CancellationToken.None);
                ToggleCollection.Instance = toggles.Result.ToggleCollection;
            }

            scheduledTaskManager = settings.ScheduledTaskManager;

            IsMetricsDisabled = settings.SendMetricsInterval == null;

            var fetchFeatureTogglesTask = new FetchFeatureTogglesTask(
                apiClient,
                ToggleCollection,
                settings.JsonSerializer,
                fileSystem,
                backupFile,
                etagBackupFile)
            {
                ExecuteDuringStartup = true,
                Interval             = settings.FetchTogglesInterval,
                Etag = cachedFilesResult.InitialETag
            };

            var scheduledTasks = new List <IUnleashScheduledTask>()
            {
                fetchFeatureTogglesTask
            };

            if (settings.SendMetricsInterval != null)
            {
                var clientRegistrationBackgroundTask = new ClientRegistrationBackgroundTask(
                    apiClient,
                    settings,
                    strategyMap.Select(pair => pair.Key).ToList())
                {
                    Interval             = TimeSpan.Zero,
                    ExecuteDuringStartup = true
                };

                scheduledTasks.Add(clientRegistrationBackgroundTask);

                var clientMetricsBackgroundTask = new ClientMetricsBackgroundTask(
                    apiClient,
                    settings,
                    MetricsBucket)
                {
                    ExecuteDuringStartup = false,
                    Interval             = settings.SendMetricsInterval.Value
                };

                scheduledTasks.Add(clientMetricsBackgroundTask);
            }

            scheduledTaskManager.Configure(scheduledTasks, CancellationToken);
        }
 public static string GetFeatureToggleFilePath(this UnleashSettings unleashSettings)
 {
     return(Path.Combine(unleashSettings.LocalStorageFolder, unleashSettings.PrependFileName(unleashSettings.FeatureToggleFilename)));
 }
Ejemplo n.º 8
0
 ///// <summary>
 ///// Initializes a new instance of Unleash client with a set of default strategies.
 ///// </summary>
 ///// <param name="config">Unleash settings</param>
 ///// <param name="strategies">Additional custom strategies.</param>
 public DefaultUnleash(UnleashSettings settings, params IStrategy[] strategies)
     : this(settings, overrideDefaultStrategies : false, strategies)
 {
 }