/// <summary>
 /// Returns the global <see cref="ICacheConfiguration.AugmentWeakFingerprintPathSetThreshold"/>
 /// if weak fingerprint augmentation is on,
 /// or <see cref="Process.DefaultAugmentWeakFingerprintPathSetThreshold"/> if the process pip is
 /// configured to enforce weak fingerprint augmentation
 /// </summary>
 public static int AugmentWeakFingerprintPathSetThreshold(
     this Process process,
     ICacheConfiguration cacheConfiguration) =>
 (process.ProcessOptions & Process.Options.EnforceWeakFingerprintAugmentation) != 0 &&
 cacheConfiguration.AugmentWeakFingerprintPathSetThreshold == 0 ?
 Process.DefaultAugmentWeakFingerprintPathSetThreshold :
 cacheConfiguration.AugmentWeakFingerprintPathSetThreshold;
Example #2
0
        public static Task <T> GetOrSetAsync <T>(ICacheConfiguration cacheConfiguration, string key, Func <Task <T> > func, int retryCount = 1)
            where T : class
        {
            return(Task.Factory.StartNew(() =>
            {
                try
                {
                    return Policy.Handle <RedisException>().Retry(retryCount).Execute(() =>
                    {
                        using var redis = new RedisCacheService(cacheConfiguration);
                        if (redis.Exists(key))
                        {
                            return redis.GetValue <T>(key);
                        }

                        var task = func();
                        task.Wait();
                        T result = task.Result;

                        redis.SetValue(key, result);

                        return result;
                    });
                }
                catch (RedisException)
                {
                    return null;
                }
            }));
        }
Example #3
0
        /// <nodoc />
        public CacheConfiguration(ICacheConfiguration template, PathRemapper pathRemapper)
        {
            Contract.Assume(template != null);
            Contract.Assume(pathRemapper != null);

            CacheConfigFile            = pathRemapper.Remap(template.CacheConfigFile);
            CacheLogFilePath           = pathRemapper.Remap(template.CacheLogFilePath);
            Incremental                = template.Incremental;
            CacheGraph                 = template.CacheGraph;
            CachedGraphPathToLoad      = pathRemapper.Remap(template.CachedGraphPathToLoad);
            CachedGraphIdToLoad        = template.CachedGraphIdToLoad;
            CachedGraphLastBuildLoad   = template.CachedGraphLastBuildLoad;
            CacheSpecs                 = template.CacheSpecs;
            CacheMemoryUsage           = template.CacheMemoryUsage;
            CacheSessionName           = template.CacheSessionName;
            ArtificialCacheMissOptions = template.ArtificialCacheMissOptions == null ? null : new ArtificialCacheMissConfig(template.ArtificialCacheMissOptions);
            CacheSalt             = template.CacheSalt;
            DeterminismProbe      = template.DeterminismProbe;
            HistoricMetadataCache = template.HistoricMetadataCache;
            AllowFetchingCachedGraphFromContentCache = template.AllowFetchingCachedGraphFromContentCache;
            MinimumReplicaCountForStrongGuarantee    = template.MinimumReplicaCountForStrongGuarantee;
            StrongContentGuaranteeRefreshProbability = template.StrongContentGuaranteeRefreshProbability;
            FileChangeTrackingExclusionRoots         = pathRemapper.Remap(template.FileChangeTrackingExclusionRoots);
            FileChangeTrackingInclusionRoots         = pathRemapper.Remap(template.FileChangeTrackingInclusionRoots);
            UseDedupStore = template.UseDedupStore;
            ReplaceExistingFileOnMaterialization = template.ReplaceExistingFileOnMaterialization;
            VfsCasRoot = pathRemapper.Remap(template.VfsCasRoot);
        }
Example #4
0
        /// <nodoc />
        public CacheConfiguration(ICacheConfiguration template, PathRemapper pathRemapper)
        {
            Contract.Assume(template != null);
            Contract.Assume(pathRemapper != null);

            CacheConfigFile            = pathRemapper.Remap(template.CacheConfigFile);
            CacheLogFilePath           = pathRemapper.Remap(template.CacheLogFilePath);
            Incremental                = template.Incremental;
            CacheGraph                 = template.CacheGraph;
            CachedGraphPathToLoad      = pathRemapper.Remap(template.CachedGraphPathToLoad);
            CachedGraphIdToLoad        = template.CachedGraphIdToLoad;
            CachedGraphLastBuildLoad   = template.CachedGraphLastBuildLoad;
            CacheSpecs                 = template.CacheSpecs;
            CacheSessionName           = template.CacheSessionName;
            ArtificialCacheMissOptions = template.ArtificialCacheMissOptions == null ? null : new ArtificialCacheMissConfig(template.ArtificialCacheMissOptions);
            CacheSalt        = template.CacheSalt;
            DeterminismProbe = template.DeterminismProbe;
            DisableDeterminismProbeLogging           = template.DisableDeterminismProbeLogging;
            HistoricMetadataCache                    = template.HistoricMetadataCache;
            AllowFetchingCachedGraphFromContentCache = template.AllowFetchingCachedGraphFromContentCache;
            MinimumReplicaCountForStrongGuarantee    = template.MinimumReplicaCountForStrongGuarantee;
            StrongContentGuaranteeRefreshProbability = template.StrongContentGuaranteeRefreshProbability;
            FileChangeTrackingExclusionRoots         = pathRemapper.Remap(template.FileChangeTrackingExclusionRoots);
            FileChangeTrackingInclusionRoots         = pathRemapper.Remap(template.FileChangeTrackingInclusionRoots);
            UseDedupStore = template.UseDedupStore;
            ReplaceExistingFileOnMaterialization = template.ReplaceExistingFileOnMaterialization;
            VfsCasRoot            = pathRemapper.Remap(template.VfsCasRoot);
            VirtualizeUnknownPips = template.VirtualizeUnknownPips;
            ElideMinimalGraphEnumerationAbsentPathProbes        = template.ElideMinimalGraphEnumerationAbsentPathProbes;
            AugmentWeakFingerprintPathSetThreshold              = template.AugmentWeakFingerprintPathSetThreshold;
            AugmentWeakFingerprintRequiredPathCommonalityFactor = template.AugmentWeakFingerprintRequiredPathCommonalityFactor;
            MonitorAugmentedPathSets = template.MonitorAugmentedPathSets;
            UseLocalOnly             = template.UseLocalOnly;
        }
Example #5
0
        public static BaseCacheStore Create(ICacheConfiguration cacheConfiguration)
        {
            if (cacheConfiguration == null)
            {
                throw new ArgumentNullException("cacheConfiguration");
            }

            if (_instance == null)
            {
                Type providerType = Type.GetType(cacheConfiguration.ProviderType);
                if (providerType == null)
                {
                    throw new InvalidConfigurationException("Could not locate Cache Provider :" +
                                                            cacheConfiguration.ProviderType);
                }

                if (!providerType.ImplementsClass <BaseCacheStore>())
                {
                    throw new InvalidConfigurationException("Cache Provider does not implement BaseCacheStore:" +
                                                            cacheConfiguration.ProviderType);
                }

                _instance = (BaseCacheStore)Activator.CreateInstance(providerType, cacheConfiguration);
            }

            return(_instance);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="KeyVaultCachedSecretProvider"/> class
 /// with standard generated <see cref="MemoryCache"/> and custom <paramref name="cacheConfiguration"/>.
 /// </summary>
 /// <param name="secretProvider">The inner Azure Key Vault secret provider to retrieve secrets.</param>
 /// <param name="cacheConfiguration">The custom caching configuration that defines how the cache works.</param>
 /// <exception cref="ArgumentNullException">Thrown when the <paramref name="secretProvider"/> or the <paramref name="cacheConfiguration"/> is <c>null</c>.</exception>
 public KeyVaultCachedSecretProvider(KeyVaultSecretProvider secretProvider, ICacheConfiguration cacheConfiguration)
     : base(secretProvider, cacheConfiguration)
 {
     Guard.NotNull(secretProvider, nameof(secretProvider), "Requires an Azure Key Vault secret provider to provide additional caching operations");
     Guard.NotNull(cacheConfiguration, nameof(cacheConfiguration), "Requires a custom caching configuration instance for the cached Azure Key Vault secret provider");
     _secretProvider = secretProvider;
 }
 /// <summary>
 /// Returns the global <see cref="ICacheConfiguration.AugmentWeakFingerprintRequiredPathCommonalityFactor"/>
 /// if weak fingerprint augmentation is on, or
 /// <see cref="Process.DefaultAugmentWeakFingerprintRequiredPathCommonalityFactor"/> if the process pip is
 /// configured to enforce weak fingerprint augmentation
 /// </summary>
 public static double AugmentWeakFingerprintRequiredPathCommonalityFactor(
     this Process process,
     ICacheConfiguration cacheConfiguration) =>
 (process.ProcessOptions & Process.Options.EnforceWeakFingerprintAugmentation) != 0 &&
 cacheConfiguration.AugmentWeakFingerprintPathSetThreshold == 0 ?
 Process.DefaultAugmentWeakFingerprintRequiredPathCommonalityFactor :
 cacheConfiguration.AugmentWeakFingerprintRequiredPathCommonalityFactor;
Example #8
0
 public CacheController(ICacheEngine cacheEngine,
                        ICacheConfiguration cacheConfiguration,
                        IReceptionServiceIssueCache issueCache)
 {
     _cacheEngine        = cacheEngine;
     _cacheConfiguration = cacheConfiguration;
     _issueCache         = issueCache;
 }
 public CurrencyRateCache(ICacheConfiguration cacheConfiguration)
 {
     memoryCache = new MemoryCache(new MemoryCacheOptions
     {
         ExpirationScanFrequency = cacheConfiguration.ExpirationScanFrequency,
         SizeLimit = cacheConfiguration.MaxCachedQueries
     });
     this.cacheConfiguration = cacheConfiguration;
 }
Example #10
0
        /// <summary>
        /// Gets an instance of <see cref="ICacheConfigData"/> from cache configuration.
        /// </summary>
        internal static Possible <ICacheConfigData> TryGetCacheConfigData(
            PathTable pathTable,
            string cacheDirectory,
            ICacheConfiguration config,
            RootTranslator rootTranslator = null)
        {
            Contract.Requires(pathTable != null);
            Contract.Requires(pathTable.IsValid);
            Contract.Requires(config != null);
            Contract.Requires(config.CacheLogFilePath.IsValid);
            Contract.Requires(config.CacheConfigFile.IsValid);
            Contract.Requires(!string.IsNullOrWhiteSpace(cacheDirectory));

            Possible <string> maybeConfigData = TryReadCacheConfigFile(config.CacheConfigFile.ToString(pathTable));

            if (!maybeConfigData.Succeeded)
            {
                return(maybeConfigData.Failure);
            }

            // Update the cache config to dynamically set the cache path if it is configured to use the per-invocation path.
            // TODO: Ideally this would be exposed as config constructor parameters to BuildXL to not require manipulating the json config.
            //       But for now we just modify the config text before passing it along to the cache.
            string cacheConfigContent = maybeConfigData.Result;

            cacheConfigContent = cacheConfigContent.Replace("[DominoSelectedLogPath]", config.CacheLogFilePath.ToString(pathTable).Replace(@"\", @"\\"));  // Escape path separation chars to json format
            cacheConfigContent = cacheConfigContent.Replace("[BuildXLSelectedLogPath]", config.CacheLogFilePath.ToString(pathTable).Replace(@"\", @"\\")); // Escape path separation chars to json format
            cacheConfigContent = cacheConfigContent.Replace("[DominoSelectedRootPath]", cacheDirectory.Replace(@"\", @"\\"));
            cacheConfigContent = cacheConfigContent.Replace("[BuildXLSelectedRootPath]", cacheDirectory.Replace(@"\", @"\\"));
            cacheConfigContent = cacheConfigContent.Replace("[UseDedupStore]", config.UseDedupStore.ToString());
            cacheConfigContent = cacheConfigContent.Replace("[ReplaceExistingFileOnMaterialization]", config.ReplaceExistingFileOnMaterialization.ToString());

            var vfsCasRoot = config.VfsCasRoot.IsValid
                ? config.VfsCasRoot.ToString(pathTable)
                : "";

            if (rootTranslator != null && !string.IsNullOrEmpty(vfsCasRoot))
            {
                // VFS needs real path so use root translator to resolve to real path.
                vfsCasRoot = rootTranslator.Translate(vfsCasRoot);
            }

            // Escape path separation chars to json format
            vfsCasRoot = vfsCasRoot.Replace(@"\", @"\\");

            cacheConfigContent = cacheConfigContent.Replace("[VfsCasRoot]", vfsCasRoot);

            ICacheConfigData cacheConfigData;
            Exception        exception;

            if (!CacheFactory.TryCreateCacheConfigData(cacheConfigContent, out cacheConfigData, out exception))
            {
                return(new Failure <string>(I($"Unable to create cache config data: {exception.GetLogEventMessage()}")));
            }

            return(new Possible <ICacheConfigData>(cacheConfigData));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="KeyVaultCachedSecretProvider"/> class.
        /// </summary>
        /// <param name="secretProvider">The inner Azure Key Vault secret provider to provide secrets.</param>
        /// <param name="cacheConfiguration">The custom caching configuration that defines how the cache works.</param>
        /// <param name="memoryCache">The custom memory cache implementation that stores the cached secrets in memory.</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown when the <paramref name="secretProvider"/>, <paramref name="cacheConfiguration"/>, or <paramref name="memoryCache"/> is <c>null</c>.
        /// </exception>
        public KeyVaultCachedSecretProvider(KeyVaultSecretProvider secretProvider, ICacheConfiguration cacheConfiguration, IMemoryCache memoryCache)
            : base(secretProvider, cacheConfiguration, memoryCache)
        {
            Guard.NotNull(secretProvider, nameof(secretProvider), "Requires an Azure Key Vault secret provider to provide additional caching operations");
            Guard.NotNull(cacheConfiguration, nameof(cacheConfiguration), "Requires a custom caching configuration instance for the cached Azure Key Vault secret provider");
            Guard.NotNull(memoryCache, nameof(memoryCache), "Requires a custom memory cache implementation to store the Azure Key Vault secrets in memory");

            _secretProvider = secretProvider;
        }
        private LocalCacheStore GetLocalCacheStore()
        {
            var log = GetLog();

            ICacheConfiguration cacheConfiguration = GetConfiguration();

            LocalCacheStore localCache = new LocalCacheStore(cacheConfiguration, log);

            return(localCache);
        }
        private DistributedCacheStore GetDistributedCacheStore()
        {
            var log = GetLog();

            ICacheConfiguration cacheConfiguration = GetConfiguration();

            DistributedCacheStore localCache = new DistributedCacheStore(cacheConfiguration, log);

            return(localCache);
        }
Example #14
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="RedisCacheContext" /> class.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        public RedisCacheContext(ICacheConfiguration configuration)
        {
            //_redisConnection = ConnectionMultiplexer.Connect(configuration.CacheConfigurationString);
            var configurationOptions = ConfigurationOptions.Parse(configuration.CacheConfigurationString);

            configurationOptions.ConnectTimeout  = 60000;
            configurationOptions.ResponseTimeout = 30000;
            configurationOptions.SyncTimeout     = 30000;
            _redisConnection = ConnectionMultiplexer.Connect(configurationOptions);
        }
        private ICacheStoreAccelerator GetCacheStoreAccelerator()
        {
            var log = GetLog();

            ICacheConfiguration cacheConfiguration = GetConfiguration();

            ICacheStoreAccelerator cacheStoreAccelerator = new CacheStoreAccelerator(cacheConfiguration, log);

            return(cacheStoreAccelerator);
        }
Example #16
0
 public CachingInterceptor(ILoggerFactory loggerFactory, ICacheFactory cacheFactory)
 {
     _cacheFactory = cacheFactory;
     _logger       = loggerFactory.Create(GetType());
     //ICacheConfiguration在这里不能注入,会导致循环注入异常
     using (var scope = ObjectContainer.Current.BeginLifetimeScope())
     {
         _cacheConfiguration = scope.Resolve <ICacheConfiguration>();
     }
 }
Example #17
0
        /// <summary>
        /// Creating a new CachedSecretProvider with all required information
        /// </summary>
        /// <param name="secretProvider">The internal <see cref="ISecretProvider"/> used to retrieve the actual Secret Value, when not cached</param>
        /// <param name="cacheConfiguration">The <see cref="ICacheConfiguration"/> which defines how the cache works</param>
        /// <param name="memoryCache">A <see cref="IMemoryCache"/> implementation that can cache data in memory.</param>
        /// <exception cref="ArgumentNullException">The secretProvider and memoryCache parameters must not be null</exception>
        public CachedSecretProvider(ISecretProvider secretProvider, ICacheConfiguration cacheConfiguration, IMemoryCache memoryCache)
        {
            Guard.NotNull(secretProvider, nameof(secretProvider));
            Guard.NotNull(memoryCache, nameof(memoryCache));
            Guard.NotNull(cacheConfiguration, nameof(cacheConfiguration));

            _secretProvider     = secretProvider;
            _memoryCache        = memoryCache;
            _cacheConfiguration = cacheConfiguration;
        }
Example #18
0
        protected BaseCacheStore(ICacheConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            _configuration = configuration;
            _enabled       = configuration.Enabled;
        }
Example #19
0
 public KafkaOptions(
     Uri kafkaServerUri = null,
     IConnectionConfiguration connectionConfiguration = null,
     ICacheConfiguration cacheConfiguration           = null,
     IConnectionFactory connectionFactory             = null,
     IPartitionSelector partitionSelector             = null,
     IProducerConfiguration producerConfiguration     = null,
     IConsumerConfiguration consumerConfiguration     = null,
     ILog log = null)
     : this(ImmutableList <Uri> .Empty.AddNotNull(kafkaServerUri), connectionConfiguration, cacheConfiguration, connectionFactory, partitionSelector, producerConfiguration, consumerConfiguration, log)
 {
 }
Example #20
0
            /// <exception cref="System.Exception"></exception>
            public virtual void Test()
            {
                if (CommonAndLocalConfigurationTestSuite.Subject() is IClientConfiguration)
                {
                    return;
                }
                IFileConfigurationProvider config     = ((IFileConfigurationProvider)Subject());
                IFileConfiguration         fileConfig = config.File;
                Config4Impl legacyConfig = Db4oLegacyConfigurationBridge.AsLegacy(config);

                fileConfig.BlockSize = 42;
                Assert.AreEqual(42, legacyConfig.BlockSize());
                fileConfig.DatabaseGrowthSize = 42;
                Assert.AreEqual(42, legacyConfig.DatabaseGrowthSize());
                fileConfig.DisableCommitRecovery();
                Assert.IsTrue(legacyConfig.CommitRecoveryDisabled());
                fileConfig.Freespace.DiscardSmallerThan(8);
                Assert.AreEqual(8, legacyConfig.DiscardFreeSpace());
                fileConfig.GenerateUUIDs = ConfigScope.Globally;
                Assert.AreEqual(ConfigScope.Globally, legacyConfig.GenerateUUIDs());
                fileConfig.GenerateCommitTimestamps = true;
                Assert.IsTrue(legacyConfig.GenerateCommitTimestamps().DefiniteYes());
                IStorage storageFactory = new FileStorage();

                fileConfig.Storage = storageFactory;
                Assert.AreSame(storageFactory, legacyConfig.Storage);
                Assert.AreSame(storageFactory, fileConfig.Storage);
                fileConfig.LockDatabaseFile = true;
                Assert.IsTrue(legacyConfig.LockFile());
                fileConfig.ReserveStorageSpace = 1024;
                Assert.AreEqual(1024, legacyConfig.ReservedStorageSpace());
                fileConfig.BlobPath = Path.GetTempPath();
                Assert.AreEqual(Path.GetTempPath(), legacyConfig.BlobPath());
                fileConfig.ReadOnly = true;
                Assert.IsTrue(legacyConfig.IsReadOnly());
                ICacheConfigurationProvider cacheProvider = ((ICacheConfigurationProvider)Subject
                                                                 ());
                ICacheConfiguration            cache = cacheProvider.Cache;
                IIdSystemConfigurationProvider idSystemConfigurationProvider = ((IIdSystemConfigurationProvider
                                                                                 )Subject());
                IIdSystemConfiguration idSystemConfiguration = idSystemConfigurationProvider.IdSystem;

                Assert.AreEqual(StandardIdSystemFactory.Default, legacyConfig.IdSystemType());
                idSystemConfiguration.UseStackedBTreeSystem();
                Assert.AreEqual(StandardIdSystemFactory.StackedBtree, legacyConfig.IdSystemType()
                                );
                idSystemConfiguration.UsePointerBasedSystem();
                Assert.AreEqual(StandardIdSystemFactory.PointerBased, legacyConfig.IdSystemType()
                                );
            }
Example #21
0
        public CacheStoreAccelerator(ICacheConfiguration cacheConfiguration, ILog log)
        {
            if (cacheConfiguration == null)
            {
                throw new ArgumentNullException("cacheConfiguration");
            }
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }

            this.cacheConfiguration = cacheConfiguration;
            this.log = log;
        }
        public DistributedCacheStore(ICacheConfiguration cacheConfiguration, ILog log)
        {
            if (cacheConfiguration == null)
            {
                throw new ArgumentNullException("cacheConfiguration");
            }
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }
            this.cacheConfiguration = cacheConfiguration;
            this.log = log;

            lockTimeout = cacheConfiguration.DistributedCacheTimeout;
        }
Example #23
0
        public InMemoryCacheStore(ICacheConfiguration cacheConfiguration)
            : base(cacheConfiguration)
        {
            var args = new CommandArgs(Configuration.Parameters);

            _durationInSeconds = int.Parse(args.GetValue("duration", "30"));
            _mode = args.GetValue("mode", CacheMode.Absolute.ToString()).ToEnum <CacheMode>();

            _itemRemovedCallback = x => OnItemRemoved(new CacheItemRemovedArgs
            {
                CacheKey     = x.CacheItem.Key,
                Value        = x.CacheItem.Value,
                RemoveReason = x.RemovedReason.ToString()
            });
        }
        /// <summary>
        /// Adds Azure Key Vault as a secret source which uses Managed Identity authentication.
        /// </summary>
        /// <param name="builder">The builder to create the secret store.</param>
        /// <param name="rawVaultUri">The Uri of the Azure Key Vault you want to connect to.</param>
        /// <param name="cacheConfiguration">The configuration to control how the caching will be done.</param>
        /// <param name="connectionString">The connection string to use to authenticate, if applicable.</param>
        /// <param name="azureADInstance">The azure AD instance to use to authenticate, if applicable.</param>
        public static SecretStoreBuilder AddAzureKeyVaultWithManagedServiceIdentity(
            this SecretStoreBuilder builder,
            string rawVaultUri,
            ICacheConfiguration cacheConfiguration,
            string connectionString = null,
            string azureADInstance  = null)
        {
            Guard.NotNull(rawVaultUri, nameof(rawVaultUri));

            return(AddAzureKeyVault(
                       builder,
                       new ManagedServiceIdentityAuthentication(connectionString, azureADInstance),
                       new KeyVaultConfiguration(rawVaultUri),
                       cacheConfiguration));
        }
Example #25
0
        /// <summary>
        /// Creating a new CachedSecretProvider with all required information
        /// </summary>
        /// <param name="secretProvider">The internal <see cref="ISecretProvider"/> used to retrieve the actual Secret Value, when not cached</param>
        /// <param name="cacheConfiguration">The <see cref="ICacheConfiguration"/> which defines how the cache works</param>
        /// <param name="memoryCache">A <see cref="IMemoryCache"/> implementation that can cache data in memory.</param>
        /// <exception cref="ArgumentNullException">The secretProvider and memoryCache parameters must not be null</exception>
        public CachedSecretProvider(ISecretProvider secretProvider, ICacheConfiguration cacheConfiguration, IMemoryCache memoryCache)
        {
            Guard.NotNull(secretProvider, nameof(secretProvider));
            Guard.NotNull(memoryCache, nameof(memoryCache));
            Guard.NotNull(cacheConfiguration, nameof(cacheConfiguration));

            _secretProvider     = secretProvider;
            _cacheConfiguration = cacheConfiguration;

            MemoryCache = memoryCache;

            CacheEntry = new MemoryCacheEntryOptions()
                         // Keep in cache for this time, reset time if accessed.
                         .SetSlidingExpiration(Configuration.Duration);
        }
        /// <summary>
        /// Adds Azure Key Vault as a secret source which uses certificate authentication.
        /// </summary>
        /// <param name="builder">The builder to create the secret store.</param>
        /// <param name="rawVaultUri">The Uri of the Azure Key Vault you want to connect to.</param>
        /// <param name="clientId">The identifier of the application requesting the authentication token.</param>
        /// <param name="certificate">The certificate that is used as credential.</param>
        /// <param name="cacheConfiguration">The configuration to control how the caching will be done.</param>
        public static SecretStoreBuilder AddAzureKeyVaultWithCertificate(
            this SecretStoreBuilder builder,
            string rawVaultUri,
            string clientId,
            X509Certificate2 certificate,
            ICacheConfiguration cacheConfiguration)
        {
            Guard.NotNull(rawVaultUri, nameof(rawVaultUri));
            Guard.NotNull(clientId, nameof(clientId));
            Guard.NotNull(certificate, nameof(certificate));

            return(AddAzureKeyVault(
                       builder,
                       new CertificateBasedAuthentication(clientId, certificate),
                       new KeyVaultConfiguration(rawVaultUri),
                       cacheConfiguration: cacheConfiguration));
        }
        /// <summary>
        /// Adds Azure Key Vault as a secret source which uses client secret authentication.
        /// </summary>
        /// <param name="builder">The builder to create the secret store.</param>
        /// <param name="rawVaultUri">The Uri of the Azure Key Vault you want to connect to.</param>
        /// <param name="clientId">The ClientId of the service principal, used to connect to Azure Key Vault</param>
        /// <param name="clientKey">The Secret ClientKey of the service principal, used to connect to Azure Key Vault</param>
        /// <param name="cacheConfiguration">The configuration to control how the caching will be done.</param>
        public static SecretStoreBuilder AddAzureKeyVaultWithServicePrincipal(
            this SecretStoreBuilder builder,
            string rawVaultUri,
            string clientId,
            string clientKey,
            ICacheConfiguration cacheConfiguration)
        {
            Guard.NotNull(rawVaultUri, nameof(rawVaultUri));
            Guard.NotNullOrEmpty(clientId, nameof(clientId));
            Guard.NotNullOrEmpty(clientKey, nameof(clientKey));

            return(AddAzureKeyVault(
                       builder,
                       new ServicePrincipalAuthentication(clientId, clientKey),
                       new KeyVaultConfiguration(rawVaultUri),
                       cacheConfiguration: cacheConfiguration));
        }
        /// <summary>
        /// Creating a new <see cref="CachedSecretProvider"/> with all required information.
        /// </summary>
        /// <param name="secretProvider">The internal <see cref="ISecretProvider"/> used to retrieve the actual Secret Value, when not cached</param>
        /// <param name="cacheConfiguration">The <see cref="ICacheConfiguration"/> which defines how the cache works</param>
        /// <param name="memoryCache">A <see cref="IMemoryCache"/> implementation that can cache data in memory.</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown when the <paramref name="secretProvider"/>, <paramref name="memoryCache"/>, or <paramref name="cacheConfiguration"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when the <see cref="ICacheConfiguration.Duration"/> is not a positive time duration.</exception>
        public CachedSecretProvider(ISecretProvider secretProvider, ICacheConfiguration cacheConfiguration, IMemoryCache memoryCache)
        {
            Guard.NotNull(secretProvider, nameof(secretProvider), "Requires a secret provider instance to include caching while retrieving secrets");
            Guard.NotNull(memoryCache, nameof(memoryCache), "Requires a memory caching implementation to include caching while retrieving secrets");
            Guard.NotNull(cacheConfiguration, nameof(cacheConfiguration), "Requires a configuration instance to influence the caching during the retrieval of secrets");
            Guard.NotLessThan(cacheConfiguration.Duration, TimeSpan.Zero, nameof(cacheConfiguration),
                              "Requires a positive time duration in the cache configuration in which the caching should take place");

            _secretProvider     = secretProvider;
            _cacheConfiguration = cacheConfiguration;

            MemoryCache = memoryCache;

            CacheEntry = new MemoryCacheEntryOptions()
                         // Keep in cache for this time, reset time if accessed.
                         .SetSlidingExpiration(Configuration.Duration);
        }
Example #29
0
        public InRoleCacheStore(ICacheConfiguration configuration)
            : base(configuration)
        {
            var args = new CommandArgs(configuration.Parameters);

            if (_cacheFactory == null)
            {
                _cacheFactory = new DataCacheFactory();
            }

            _cache = args.ContainsKey("cacheName")
                ? _cacheFactory.GetCache(args.GetValue("cacheName", "default"))
                : _cacheFactory.GetDefaultCache();

            _policy            = args.GetValue("policy", CachePolicy.AlwaysLive.ToString()).ToEnum <CachePolicy>();
            _durationInMinutes = int.Parse(args.GetValue("duration", "10"));
        }
Example #30
0
        public LocalCacheStore(ICacheConfiguration cacheConfiguration, ILog log)
        {
            // if (localCacheAccelerator == null) throw new ArgumentNullException("localCacheAccelerator");
            if (cacheConfiguration == null)
            {
                throw new ArgumentNullException("cacheConfiguration");
            }
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }

            //this.localCacheAccelerator = localCacheAccelerator;
            this.cacheConfiguration = cacheConfiguration;
            this.log = log;

            lockTimeout = this.cacheConfiguration.LocalCacheTimeout;
        }
Example #31
0
        public static BaseCacheStore Create(ICacheConfiguration cacheConfiguration)
        {
            if (cacheConfiguration == null)
                throw new ArgumentNullException("cacheConfiguration");

            if (_instance == null)
            {
                Type providerType = Type.GetType(cacheConfiguration.ProviderType);
                if (providerType == null)
                    throw new InvalidConfigurationException("Could not locate Cache Provider :" +
                                                            cacheConfiguration.ProviderType);

                if (!providerType.ImplementsClass<BaseCacheStore>())
                    throw new InvalidConfigurationException("Cache Provider does not implement BaseCacheStore:" +
                                                            cacheConfiguration.ProviderType);

                _instance = (BaseCacheStore) Activator.CreateInstance(providerType, cacheConfiguration);
            }

            return _instance;
        }
 /// <summary>
 /// 初始化一个新的<see cref="DotPlatformMemoryCacheManager"/>实例
 /// </summary>
 /// <param name="cacheConfiguration">缓存配置</param>
 public DotPlatformMemoryCacheManager(ICacheConfiguration cacheConfiguration) : base(cacheConfiguration)
 {
 }
Example #33
0
 protected CacheManagerBase(ICacheConfiguration cacheConfiguration)
 {
     Configuration = cacheConfiguration;
 }
Example #34
0
        /// <summary>
        /// 初始化一个新的<see cref="RedisCacheManager"/>实例
        /// </summary>
        /// <param name="cacheConfiguration">缓存配置对象</param>
        public RedisCacheManager(ICacheConfiguration cacheConfiguration) 
            : base(cacheConfiguration)
        {

        }