Beispiel #1
0
 public static async IAsyncEnumerable <string> GetAllKeysAsync(this ICacheClientAsync cache)
 {
     await foreach (var key in cache.GetKeysByPatternAsync("*"))
     {
         yield return(key);
     }
 }
Beispiel #2
0
 public static async IAsyncEnumerable <string> GetKeysStartingWithAsync(this ICacheClientAsync cache, string prefix)
 {
     await foreach (var key in cache.GetKeysByPatternAsync(prefix + "*"))
     {
         yield return(key);
     }
 }
Beispiel #3
0
        public static async Task <T> GetOrCreateSessionAsync <T>(ICacheClientAsync cache = null, IRequest httpReq = null, IResponse httpRes = null, CancellationToken token = default)
        {
            if (httpReq == null)
            {
                httpReq = HostContext.GetCurrentRequest();
            }

            var iSession = await httpReq.GetSessionAsync(reload : false, token).ConfigAwait();

            if (iSession is T variable)
            {
                return(variable);
            }

            var sessionId  = httpReq.GetSessionId();
            var sessionKey = GetSessionKey(sessionId);

            if (sessionKey != null)
            {
                var session = await(cache ?? httpReq.GetCacheClientAsync()).GetAsync <T>(sessionKey, token).ConfigAwait();
                if (!Equals(session, default(T)))
                {
                    return((T)HostContext.AppHost.OnSessionFilter(httpReq, (IAuthSession)session, sessionId));
                }
            }

            return((T)CreateNewSession(httpReq, sessionId));
        }
Beispiel #4
0
        /// <summary>
        /// Removes items from the cache based on the specified regular expression pattern
        /// </summary>
        /// <param name="cacheClient">Cache client</param>
        /// <param name="regex">Regular expression pattern to search cache keys</param>
        public static Task RemoveByRegexAsync(this ICacheClientAsync cacheClient, string regex)
        {
            if (!(cacheClient is IRemoveByPatternAsync canRemoveByPattern))
            {
                throw new NotImplementedException("IRemoveByPattern is not implemented by: " + cacheClient.GetType().FullName);
            }

            return(canRemoveByPattern.RemoveByRegexAsync(regex));
        }
Beispiel #5
0
        public async Task OnBeforeEachTest()
        {
            if (cacheClient is object)
            {
                await cacheClient.DisposeAsync();
            }

            cacheClient = new RedisClient(TestConfig.SingleHost);
            await cacheClient.FlushAllAsync();
        }
Beispiel #6
0
        /// <summary>
        /// Removes items from cache that have keys matching the specified wildcard pattern
        /// </summary>
        /// <param name="cacheClient">Cache client</param>
        /// <param name="pattern">The wildcard, where "*" means any sequence of characters and "?" means any single character.</param>
        /// <param name="token"></param>
        public static Task RemoveByPatternAsync(this ICacheClientAsync cacheClient, string pattern, CancellationToken token = default)
        {
            if (!(cacheClient is IRemoveByPatternAsync canRemoveByPattern))
            {
                throw new NotImplementedException(
                          "IRemoveByPattern is not implemented on: " + cacheClient.GetType().FullName);
            }

            return(canRemoveByPattern.RemoveByPatternAsync(pattern, token));
        }
Beispiel #7
0
 public static async Task CacheSetAsync <T>(this ICacheClientAsync cache, string key, T value, TimeSpan?expiresIn, CancellationToken token = default)
 {
     if (expiresIn.HasValue)
     {
         await cache.SetAsync(key, value, expiresIn.Value, token).ConfigAwait();
     }
     else
     {
         await cache.SetAsync(key, value, token).ConfigAwait();
     }
 }
Beispiel #8
0
 public static async Task SetAsync <T>(this ICacheClientAsync cache, string cacheKey, T value, TimeSpan?expireCacheIn, CancellationToken token = default)
 {
     if (expireCacheIn.HasValue)
     {
         await cache.SetAsync(cacheKey, value, expireCacheIn.Value, token);
     }
     else
     {
         await cache.SetAsync(cacheKey, value, token);
     }
 }
Beispiel #9
0
        public static async Task <T> GetOrCreateAsync <T>(this ICacheClientAsync cache,
                                                          string key, TimeSpan expiresIn, Func <Task <T> > createFn)
        {
            var value = await cache.GetAsync <T>(key);

            if (Equals(value, default(T)))
            {
                value = await createFn().ConfigAwait();

                await cache.SetAsync(key, value, expiresIn);
            }
            return(value);
        }
        /// <summary>
        /// Returning the most optimized result based on the MimeType and CompressionType from the IRequest.
        /// <param name="expireCacheIn">How long to cache for, null is no expiration</param>
        /// </summary>
        public static async Task <object> ToOptimizedResultUsingCacheAsync <T>(
            this IRequest req, ICacheClientAsync cacheClient, string cacheKey,
            TimeSpan?expireCacheIn, Func <T> factoryFn, CancellationToken token = default)
        {
            var cacheResult = await cacheClient.ResolveFromCacheAsync(cacheKey, req, token).ConfigAwait();

            if (cacheResult != null)
            {
                return(cacheResult);
            }

            cacheResult = await cacheClient.CacheAsync(cacheKey, factoryFn(), req, expireCacheIn, token).ConfigAwait();

            return(cacheResult);
        }
Beispiel #11
0
        public static async Task <ValidCache> HasValidCacheAsync(this ICacheClientAsync cache, IRequest req, string cacheKey, DateTime?checkLastModified,
                                                                 CancellationToken token = default)
        {
            if (!HostContext.GetPlugin <HttpCacheFeature>().ShouldAddLastModifiedToOptimizedResults())
            {
                return(ValidCache.NotValid);
            }

            var ticks = await cache.GetAsync <long>(DateCacheKey(cacheKey), token).ConfigAwait();

            if (ticks > 0)
            {
                if (checkLastModified == null)
                {
                    return(ValidCache.NotValid);
                }

                var lastModified = new DateTime(ticks, DateTimeKind.Utc);
                return(new ValidCache(checkLastModified.Value <= lastModified, lastModified));
            }

            return(ValidCache.NotValid);
        }
Beispiel #12
0
        public static async Task <IAuthSession> GetUntypedSessionAsync(this ICacheClientAsync cache,
                                                                       IRequest httpReq = null, IResponse httpRes = null, CancellationToken token = default)
        {
            var sessionKey = GetSessionKey(httpReq);

            if (sessionKey != null)
            {
                var userSession = await cache.GetAsync <IAuthSession>(sessionKey, token);

                if (!Equals(userSession, default(AuthUserSession)))
                {
                    return(userSession);
                }
            }

            if (sessionKey == null)
            {
                SessionFeature.CreateSessionIds(httpReq, httpRes);
            }

            var unAuthorizedSession = (IAuthSession)typeof(AuthUserSession).CreateInstance();

            return(unAuthorizedSession);
        }
Beispiel #13
0
 public CacheClientWithPrefixAsync(ICacheClientAsync cache, string prefix)
 {
     this.prefix = prefix;
     this.cache  = cache;
 }
 /// <summary>
 /// Returns underlying wrapped sync ICacheClient or ICacheClient API if cache implements it
 /// </summary>
 public static ICacheClient AsSync(this ICacheClientAsync cache) => cache is CacheClientAsyncWrapper wrapper
Beispiel #15
0
 /// <summary>
 /// Decorates the ICacheClient (and its siblings) prefixing every key with the given prefix
 ///
 /// Useful for multi-tenant environments
 /// </summary>
 public static ICacheClientAsync WithPrefix(this ICacheClientAsync cache, string prefix)
 {
     return(new CacheClientWithPrefixAsync(cache, prefix));
 }
Beispiel #16
0
        public static async Task<bool> HandleValidCache(this IRequest req, CacheInfo cacheInfo, CancellationToken token=default)
        {
            if (cacheInfo == null)
                return false;

            ICacheClient cache;
            ICacheClientAsync cacheAsync = null; // only non-null if native ICacheClientAsync exists
            if (cacheInfo.LocalCache)
                cache = HostContext.AppHost.GetMemoryCacheClient(req);
            else
                HostContext.AppHost.TryGetNativeCacheClient(req, out cache, out cacheAsync);

            var cacheControl = HostContext.GetPlugin<HttpCacheFeature>().BuildCacheControlHeader(cacheInfo);

            var res = req.Response;
            DateTime? lastModified = null;

            var doHttpCaching = cacheInfo.MaxAge != null || cacheInfo.CacheControl != CacheControl.None;
            if (doHttpCaching)
            {
                lastModified = cacheAsync != null 
                    ? await cacheAsync.GetAsync<DateTime?>(cacheInfo.LastModifiedKey(), token).ConfigAwait()
                    : cache.Get<DateTime?>(cacheInfo.LastModifiedKey());
                if (req.HasValidCache(lastModified))
                {
                    if (cacheControl != null)
                        res.AddHeader(HttpHeaders.CacheControl, cacheControl);

                    res.EndNotModified();
                    return true;
                }
            }

            var encoding = !cacheInfo.NoCompression 
                ? req.GetCompressionType()
                : null;

            var useCacheKey = encoding != null
                ? cacheInfo.CacheKey + "." + encoding
                : cacheInfo.CacheKey;
            
            var responseBytes = cacheAsync != null
                ? await cacheAsync.GetAsync<byte[]>(useCacheKey, token).ConfigAwait()
                : cache.Get<byte[]>(useCacheKey);

            if (responseBytes != null)
            {
                if (encoding != null)
                    res.AddHeader(HttpHeaders.ContentEncoding, encoding);
                if (cacheInfo.VaryByUser)
                    res.AddHeader(HttpHeaders.Vary, "Cookie");

                if (cacheControl != null)
                    res.AddHeader(HttpHeaders.CacheControl, cacheControl);

                if (!doHttpCaching)
                {
                    lastModified = cacheAsync != null ?
                        await cacheAsync.GetAsync<DateTime?>(cacheInfo.LastModifiedKey(), token).ConfigAwait() :
                        cache.Get<DateTime?>(cacheInfo.LastModifiedKey());
                }

                if (lastModified != null)
                    res.AddHeader(HttpHeaders.LastModified, lastModified.Value.ToUniversalTime().ToString("r"));

                await res.WriteBytesToResponse(responseBytes, req.ResponseContentType, token).ConfigAwait();
                return true;
            }

            return false;
        }
Beispiel #17
0
 protected CacheClientTestsAsyncBase()
 {
     Cache = CreateClient();
 }
Beispiel #18
0
 public SessionCacheClientAsync(ICacheClientAsync cacheClient, string sessionId)
 {
     this.cacheClient = cacheClient;
     this.prefixNs    = "sess:" + sessionId + ":";
 }
Beispiel #19
0
 public async Task OnOneTimeSetUp()
 {
     cache = (ICacheClientAsync)CreateCacheClient();
 }
Beispiel #20
0
        public static async Task <object> ResolveFromCacheAsync(this ICacheClientAsync cache, string cacheKey, IRequest req,
                                                                CancellationToken token = default)
        {
            var checkModifiedSince = GetIfModifiedSince(req);

            if (!req.ResponseContentType.IsBinary())
            {
                string modifiers = null;
                if (req.ResponseContentType == MimeTypes.Json)
                {
                    string jsonp = req.GetJsonpCallback();
                    if (jsonp != null)
                    {
                        modifiers = ".jsonp," + jsonp.SafeVarName();
                    }
                }

                var cacheKeySerialized = GetCacheKeyForSerialized(cacheKey, req.ResponseContentType, modifiers);

                var  compressionType = req.GetCompressionType();
                bool doCompression   = compressionType != null;
                if (doCompression)
                {
                    var cacheKeySerializedZip = GetCacheKeyForCompressed(cacheKeySerialized, compressionType);

                    var validCache = await cache.HasValidCacheAsync(req, cacheKeySerializedZip, checkModifiedSince, token).ConfigAwait();

                    if (validCache.IsValid)
                    {
                        return(HttpResult.NotModified());
                    }

                    DateTime?lastModified = validCache.LastModified;
                    if (req.Response.GetHeader(HttpHeaders.CacheControl) != null)
                    {
                        lastModified = null;
                    }

                    var compressedResult = await cache.GetAsync <byte[]>(cacheKeySerializedZip, token).ConfigAwait();

                    if (compressedResult != null)
                    {
                        return(new CompressedResult(
                                   compressedResult,
                                   compressionType,
                                   req.ResponseContentType)
                        {
                            LastModified = lastModified,
                        });
                    }
                }
                else
                {
                    if ((await cache.HasValidCacheAsync(req, cacheKeySerialized, checkModifiedSince, token).ConfigAwait()).IsValid)
                    {
                        return(HttpResult.NotModified());
                    }

                    var serializedResult = await cache.GetAsync <string>(cacheKeySerialized, token).ConfigAwait();

                    if (serializedResult != null)
                    {
                        return(serializedResult);
                    }
                }
            }
            else
            {
                var cacheKeySerialized = GetCacheKeyForSerialized(cacheKey, req.ResponseContentType, modifiers: null);
                if ((await cache.HasValidCacheAsync(req, cacheKeySerialized, checkModifiedSince, token).ConfigAwait()).IsValid)
                {
                    return(HttpResult.NotModified());
                }

                var serializedResult = await cache.GetAsync <byte[]>(cacheKeySerialized, token).ConfigAwait();

                if (serializedResult != null)
                {
                    return(serializedResult);
                }
            }

            return(null);
        }
Beispiel #21
0
 public SessionFactory(ICacheClient cacheClient, ICacheClientAsync cacheClientAsync)
 {
     this.cacheClient      = cacheClient;
     this.cacheClientAsync = cacheClientAsync ?? cacheClient.AsAsync();
 }
Beispiel #22
0
 public CachedUserSessionManagerAsync(ICacheClientAsync cacheClient)
 {
     this.cacheClient = cacheClient;
 }
Beispiel #23
0
 public static Task ClearSessionAsync(this ICacheClientAsync cache, IRequest httpReq = null, CancellationToken token = default)
 {
     return(cache.RemoveAsync(GetSessionKey(httpReq), token));
 }
Beispiel #24
0
 public static IAsyncEnumerable <string> GetKeysByPatternAsync(this ICacheClientAsync cache, string pattern)
 {
     return(cache.GetKeysByPatternAsync(pattern));
 }
Beispiel #25
0
        public static async Task <TimeSpan?> GetSessionTimeToLiveAsync(this ICacheClientAsync cache, string sessionId, CancellationToken token = default)
        {
            var sessionKey = SessionFeature.GetSessionKey(sessionId);

            return(await cache.GetTimeToLiveAsync(sessionKey, token).ConfigAwait());
        }
Beispiel #26
0
 public static Task <TUserSession> SessionAsAsync <TUserSession>(this ICacheClientAsync cache,
                                                                 IRequest httpReq = null, IResponse httpRes = null, CancellationToken token = default)
 {
     return(SessionFeature.GetOrCreateSessionAsync <TUserSession>(cache, httpReq, httpRes, token));
 }
Beispiel #27
0
 public static async Task ClearCachesAsync(this ICacheClientAsync cache, string[] cacheKeys, CancellationToken token = default)
 {
     var allCacheKeys = GetAllContentCacheKeys(cacheKeys);
     await cache.RemoveAllAsync(allCacheKeys, token);
 }
Beispiel #28
0
        public static async Task <object> CacheAsync(this ICacheClientAsync cache,
                                                     string cacheKey,
                                                     object responseDto,
                                                     IRequest req,
                                                     TimeSpan?expireCacheIn  = null,
                                                     CancellationToken token = default)
        {
            req.Response.Dto = responseDto;
            await cache.SetAsync(cacheKey, responseDto, expireCacheIn, token).ConfigAwait();

            if (!req.ResponseContentType.IsBinary())
            {
                string serializedDto = SerializeToString(req, responseDto);

                string modifiers = null;
                if (req.ResponseContentType.MatchesContentType(MimeTypes.Json))
                {
                    var jsonp = req.GetJsonpCallback();
                    if (jsonp != null)
                    {
                        modifiers     = ".jsonp," + jsonp.SafeVarName();
                        serializedDto = jsonp + "(" + serializedDto + ")";

                        //Add a default expire timespan for jsonp requests,
                        //because they aren't cleared when calling ClearCaches()
                        if (expireCacheIn == null)
                        {
                            expireCacheIn = HostContext.Config.DefaultJsonpCacheExpiration;
                        }
                    }
                }

                var cacheKeySerialized = GetCacheKeyForSerialized(cacheKey, req.ResponseContentType, modifiers);
                await cache.SetAsync(cacheKeySerialized, serializedDto, expireCacheIn, token).ConfigAwait();

                var  compressionType = req.GetCompressionType();
                bool doCompression   = compressionType != null;
                if (doCompression)
                {
                    var lastModified = HostContext.GetPlugin <HttpCacheFeature>().ShouldAddLastModifiedToOptimizedResults() &&
                                       string.IsNullOrEmpty(req.Response.GetHeader(HttpHeaders.CacheControl))
                        ? DateTime.UtcNow
                        : (DateTime?)null;

                    var cacheKeySerializedZip = GetCacheKeyForCompressed(cacheKeySerialized, compressionType);

                    byte[] compressedSerializedDto = serializedDto.Compress(compressionType);
                    await cache.SetAsync(cacheKeySerializedZip, compressedSerializedDto, expireCacheIn, token).ConfigAwait();

                    if (lastModified != null)
                    {
                        await cache.SetAsync(DateCacheKey(cacheKeySerializedZip), lastModified.Value.Ticks, expireCacheIn, token).ConfigAwait();
                    }

                    return(compressedSerializedDto != null
                        ? new CompressedResult(compressedSerializedDto, compressionType, req.ResponseContentType)
                    {
                        Status = req.Response.StatusCode,
                        LastModified = lastModified,
                    }
                        : null);
                }

                return(serializedDto);
            }
            else
            {
                string modifiers          = null;
                byte[] serializedDto      = HostContext.ContentTypes.SerializeToBytes(req, responseDto);
                var    cacheKeySerialized = GetCacheKeyForSerialized(cacheKey, req.ResponseContentType, modifiers);
                await cache.SetAsync(cacheKeySerialized, serializedDto, expireCacheIn, token).ConfigAwait();

                return(serializedDto);
            }
        }
Beispiel #29
0
 public CachedUserSessionManagerAsync GetCacheManager(ICacheClientAsync cacheClient)
 {
     return(new CachedUserSessionManagerAsync(cacheClient));
 }
 /// <summary>
 /// Returning the most optimized result based on the MimeType and CompressionType from the IRequest.
 /// </summary>
 public static Task <object> ToOptimizedResultUsingCacheAsync <T>(
     this IRequest req, ICacheClientAsync cacheClient, string cacheKey, Func <T> factoryFn, CancellationToken token = default)
 {
     return(req.ToOptimizedResultUsingCacheAsync(cacheClient, cacheKey, null, factoryFn, token));
 }