using System; using CacheManager.Core; using Kreta.BusinessLogic.Interfaces; using Kreta.Core; using Kreta.Framework.Caching; namespace Kreta.BusinessLogic.Caching { public class FileServiceCache : GenericCache { private static readonly string PublicTokenCache = $"{Constants.Cache.CacheKeyPrefix}{nameof(PublicTokenCache)}"; private static readonly string PrivateTokenCache = $"{Constants.Cache.CacheKeyPrefix}{nameof(PrivateTokenCache)}"; public FileServiceCache(Framework.Caching.CacheManager cacheManager) : base(cacheManager, nameof(FileServiceCache)) { } public string GetPublicToken(ITokenServiceHelper tokenServiceHelper, bool forceUpdate = false) => !forceUpdate ? Get(PublicTokenCache) ?? SetPublicTokenFromService(tokenServiceHelper) : SetPublicTokenFromService(tokenServiceHelper); public string GetPrivateToken(ITokenServiceHelper tokenServiceHelper, bool forceUpdate = false) => !forceUpdate ? Get(PrivateTokenCache) ?? SetPrivateTokenFromService(tokenServiceHelper) : SetPrivateTokenFromService(tokenServiceHelper); private string SetPrivateTokenFromService(ITokenServiceHelper tokenServiceHelper) { var (token, expiresIn) = tokenServiceHelper.GetPrivateTokenWithExpiresIn(); AddTokentToCache(PrivateTokenCache, token, expiresIn); return token; } private string SetPublicTokenFromService(ITokenServiceHelper tokenServiceHelper) { var (token, expiresIn) = tokenServiceHelper.GetPublicTokenWithExpiresIn(); AddTokentToCache(PublicTokenCache, token, expiresIn); return token; } private void AddTokentToCache(string key, string token, int expiresIn) { AddOrUpdate(key, token, oldValue => token); Expire(key, ExpirationMode.Absolute, GetExpirationTime(expiresIn)); } private TimeSpan GetExpirationTime(int expiresIn) { var timeout = new TimeSpan(0, 0, expiresIn); var offsetTime = new TimeSpan(0, 1, 0); if (timeout > offsetTime) { timeout -= offsetTime; } return timeout; } } }