public async Task Should_Not_Remove_Still_Valid_Grant(TestDatabase testDb)
        {
            var validGrant = new Models.PersistedGrant
            {
                Key        = Guid.NewGuid().ToString(),
                ClientId   = "test-app",
                Type       = "reference",
                SubjectId  = "42",
                Expiration = DateTime.UtcNow.AddDays(3),
                Data       = "testdata"
            };

            using (var session = testDb.OpenSession())
            {
                await session.SaveAsync(validGrant.ToEntity());

                await session.FlushAsync();
            }

            await CreateTokenCleanupServiceSut(testDb, TestOperationalStoreOptions).RemoveExpiredGrantsAsync();

            using (var session = testDb.OpenSession())
            {
                (await session.GetAsync <PersistedGrant>(validGrant.Key)).Should().NotBeNull();
            }

            await CleanupTestDataAsync(testDb);
        }
        public async Task StoreAsync(Models.PersistedGrant grant)
        {
            try
            {
                if (grant == null)
                {
                    throw new ArgumentNullException("grant cant be null");
                }

                var ncachePersistantGrant = grant.ToEntity();

                await _repository.AddAsync(ncachePersistantGrant);

                if (_isDebugLoggingEnabled)
                {
                    _logger.LogDebug("Grant {key} stored", grant.Key);
                }
            }
            catch (Exception ex)
            {
                if (_isErrorLoggingEnabled)
                {
                    _logger.LogError(
                        ex,
                        $"something went wrong with StoreAsync for " +
                        $"grant key {grant.Key}");
                }
                throw;
            }
        }
        public void ToEntity_MapsKeyWithDefaultHash()
        {
            const string key = "some-key";

            var persistedGrant = new Models.PersistedGrant()
            {
                Key = key
            };

            var entity = persistedGrant.ToEntity();

            var expectedKeyValue = CryptographyHelper.CreateHash(key);

            Assert.Equal(expectedKeyValue, entity.Key);
        }
        public async Task StoreAsync(Models.PersistedGrant grant)
        {
            try
            {
                if (grant == null)
                {
                    throw new ArgumentNullException(
                              nameof(grant),
                              "grant cant be null");
                }

                await _inner.StoreAsync(grant);

                var cacheKey = Utilities.CreateCachedPersistedGrantStoreKey(grant);
                var item     = new CacheItem(grant.ToEntity())
                {
                    Tags       = Utilities.CreateCachePersistedGrantStoreTags(grant),
                    Expiration =
                        Utilities.DetermineCachePersistedGrantStoreExpiration(
                            grant, _handle.options)
                };

                var result = await _setFallBackPolicy
                             .ExecuteAsync(async() =>
                {
                    await _handle.cache.InsertAsync(cacheKey, item)
                    .ConfigureAwait(false);
                    return(true);
                }).ConfigureAwait(false);


                if (result)
                {
                    if (_debugLoggingEnabled)
                    {
                        _logger.LogDebug(
                            $"Persisted grant with key {grant.Key} " +
                            $"successfully stored");
                    }
                }
                else
                {
                    if (_errorLoggingEnabled)
                    {
                        _logger.LogError(
                            $"Caching problems with persistant store cache");
                    }
                }
            }
            catch (Exception ex)
            {
                if (_errorLoggingEnabled)
                {
                    _logger.LogError(
                        ex,
                        $"something went wrong with StoreAsync " +
                        $"for  grant key {grant.Key}");
                }
                throw;
            }
        }
        public async Task <Models.PersistedGrant> GetAsync(string key)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(key))
                {
                    throw new ArgumentNullException(
                              "key cant be null or white space", nameof(key));
                }

                var cacheKey = Utilities.CreateCachedPersistedGrantStoreKey(key);

                var cachedPersistedGrant = await _getPersistedGrantPolicy
                                           .ExecuteAsync(async() =>
                {
                    return(await Task.Run(() =>
                                          _handle.cache.Get <PersistedGrant>(cacheKey)
                                          ).ConfigureAwait(false));
                }).ConfigureAwait(false);

                Models.PersistedGrant persistedGrant = null;

                if (cachedPersistedGrant == null)
                {
                    persistedGrant = await _inner.GetAsync(key);

                    if (persistedGrant != null)
                    {
                        if (_debugLoggingEnabled)
                        {
                            _logger.LogDebug(
                                $"Cache Miss: Persisted grant {key}" +
                                $"acquired from IPersistedGrantStore");
                        }
                        var item = new CacheItem(persistedGrant.ToEntity())
                        {
                            Tags =
                                Utilities.CreateCachePersistedGrantStoreTags(
                                    persistedGrant),
                            Expiration =
                                Utilities.DetermineCachePersistedGrantStoreExpiration
                                (
                                    persistedGrant,
                                    _handle.options)
                        };

                        bool result = await _setFallBackPolicy
                                      .ExecuteAsync(async() =>
                        {
                            await _handle.cache.InsertAsync(cacheKey, item)
                            .ConfigureAwait(false);
                            return(true);
                        }).ConfigureAwait(false);

                        if (_errorLoggingEnabled && !result)
                        {
                            _logger.LogError(
                                $"Caching problems with persistant store cache");
                        }
                    }
                    else
                    {
                        if (_debugLoggingEnabled)
                        {
                            _logger.LogDebug(
                                $"Persisted grant {key} not found");
                        }
                    }
                }
                else
                {
                    persistedGrant = cachedPersistedGrant.ToModel();
                    if (_debugLoggingEnabled)
                    {
                        _logger.LogDebug(
                            $"Cache Hit: Persisted grant {key}" +
                            $"acquired from NCache");
                    }
                }

                return(persistedGrant);
            }
            catch (Exception ex)
            {
                if (_errorLoggingEnabled)
                {
                    _logger.LogError(
                        ex,
                        $"something went wrong with GetAsync for {key}");
                }
                throw;
            }
        }