예제 #1
0
        private static void RunInstance1(ICacheStore cache)
        {
            var instanceId = 1;

            Console.WriteLine($"{instanceId}: ------- instance started -------");

            Console.WriteLine($"{instanceId}: get requst");
            Thread.Sleep(100);
            var lease   = cache.TryGetLease(TimeSpan.FromSeconds(20));
            var counter = cache.Get <int>(CounterKeyName);

            counter++;
            cache.Set(CounterKeyName, counter);
            cache.ReleaseLease(lease);
            Console.WriteLine($"{instanceId}: processed");
            Thread.Sleep(300);

            Console.WriteLine($"{instanceId}: get requst");
            Thread.Sleep(150);
            lease   = cache.TryGetLease(TimeSpan.FromSeconds(20));
            counter = cache.Get <int>(CounterKeyName);
            counter++;
            cache.Set(CounterKeyName, counter);
            cache.ReleaseLease(lease);
            Console.WriteLine($"{instanceId}: processed");

            Console.WriteLine($"{instanceId}: access count: {cache.Get<int>(CounterKeyName)}");
            Console.WriteLine($"{instanceId}: ------- instance shutdown -------");
        }
예제 #2
0
        public async Task <object> Create(Intervention intervention)
        {
            var ods = await _odsApiClientProvider.NewResourcesClient();

            var response = await ods.Post("interventions", intervention);

            var createdInterventionId = await ods.HandleHttpResponseGetCreatedResourceId(response);

            var createdIntervention = await ods.Get <Intervention>($"interventions/{createdInterventionId}");

            var cachedInterventions = await _cacheProvider.Get <IList <Intervention> >(CacheKeys.Interventions);

            cachedInterventions.Add(createdIntervention);
            await _cacheProvider.TrySet(CacheKeys.Interventions, cachedInterventions);

            return(createdIntervention);
        }
예제 #3
0
        /// <summary>
        /// checks current cachestore for a cached response and returns it
        /// </summary>
        /// <param name="context"></param>
        /// <returns>cached response or null</returns>
        private static Response CheckCache(NancyContext context)
        {
            if (context.Request.Query is DynamicDictionary dict)
            {
                if (dict.ContainsKey(NoRequestQueryKey))
                {
                    return(null);
                }
            }

            string key = _cacheKeyGenerator.Get(context.Request);

            if (string.IsNullOrEmpty(key))
            {
                return(null);
            }

            var removeRapid = context.Request.Query.removeRapid;

            if (removeRapid != null && removeRapid)
            {
                _cacheStore.Remove(key);
                return(null);
            }

            var response = _cacheStore.Get(key);

            if (response == null || response.Expiration < DateTime.UtcNow)
            {
                return(null);
            }

            new Thread(() => HandleRequest(context.Request, key))
            .Start();

            //make damn sure the pre-requirements are met before returning a cached response
            var preResponse = InvokePreRequirements(context);

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

            return(response);
        }
예제 #4
0
        private async Task <object> TaskFetchAsync(ICacheTask task, string cacheKey)
        {
            if (!_store.Has(cacheKey) || task.IsExpired(this))
            {
                await task.Run(this, (k, v) => _store.Save(k, v)).ConfigureAwait(false);
            }

            return(_store.Get(cacheKey));
        }
예제 #5
0
        public async Task DeleteStudentAssessment(string studentAssessmentId, string uniqueSectionCode, string identifier)
        {
            var ods = await _odsApiClientProvider.NewResourcesClient();

            if (!string.IsNullOrWhiteSpace(studentAssessmentId))
            {
                await ods.Delete($"studentAssessments/{studentAssessmentId}");
            }

            var key = CacheKeys.Composed(CacheKeys.AssessmentScoringsBySectionUniqueId, uniqueSectionCode);

            if (await _cache.TryHasKey(key))
            {
                var students = await _cache.Get <IEnumerable <ScoringAssessmentDTO> >(key);

                students = students.Select(dto =>
                {
                    _mapper.MapStudentDTO(dto.Student);
                    dto.Student = _mapper.SecuredStudentDTO(dto.Student);

                    if (string.IsNullOrWhiteSpace(studentAssessmentId))
                    {
                        dto.Associations = dto.Associations.Where(association => association.AssociationModel.Identifier != identifier).ToList();
                    }
                    else
                    {
                        dto.Associations = dto.Associations.Where(association => association.AssociationModel.Id != studentAssessmentId).ToList();
                    }

                    return(dto);
                }).ToList();

                try
                {
                    await _cache.Set(key, students);
                }
                catch (Exception ex)
                {
                    // Sometimes caching takes too long so request timeout will expire
                    // causing the method th throw an exception. Catch the error to return
                    // the scorings back to the frontend even though this error happens
                }
            }
        }
예제 #6
0
        /// <summary>
        /// checks current cachestore for a cached response and returns it
        /// </summary>
        /// <param name="context"></param>
        /// <returns>cached response or null</returns>
        private static Response CheckCache(NancyContext context)
        {
            if (context.Request.Query is DynamicDictionary dict)
            {
                if (DisableCache.Enabled && dict.ContainsKey(DisableCache.Key))
                {
                    return(null);
                }
            }

            string key = _cacheKeyGenerator.Get(context.Request);

            if (string.IsNullOrEmpty(key))
            {
                return(null);
            }

            if (context.Request.Query is DynamicDictionary rmv)
            {
                if (RemoveCache.Enabled && rmv.ContainsKey(RemoveCache.Key))
                {
                    _cacheStore.Remove(key);
                    return(null);
                }
            }

            var response = _cacheStore.Get(key);

            if (response == null || response.Expiration < DateTime.UtcNow)
            {
                return(null);
            }

            //make damn sure the pre-requirements are met before returning a cached response
            var preResponse = InvokePreRequirements(context);

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

            return(response);
        }
예제 #7
0
        public async Task <Assessment> Create(Assessment assessment)
        {
            assessment.Identifier        = Guid.NewGuid().ToString();
            assessment.NamespaceProperty = await _odsApiSettingsProvider.GetAssessmentNamespace();

            var ods = await _odsApiClientProvider.NewResourcesClient();

            var response = await ods.Post("assessments", assessment);

            var createdAssessmentId = await ods.HandleHttpResponseGetCreatedResourceId(response);

            var createdAssessment = await ods.Get <Assessment>($"assessments/{createdAssessmentId}");

            var cachedAssessments = await _cacheProvider.Get <IList <Assessment> >(CacheKeys.Assessments);

            cachedAssessments.Add(createdAssessment);

            await _cacheProvider.TrySet(CacheKeys.Assessments, cachedAssessments);

            return(createdAssessment);
        }
        public async Task <string> Handle(GetQRFileQuery query, CancellationToken token)
        {
            var cacheKey = $"file-{query.FileId}";
            var result   = await _store.Get <string>(cacheKey, token);

            if (result == null)
            {
                throw new UnknownQRFileException(query.FileId);
            }

            return(result);
        }
예제 #9
0
        public List <ConversionRate> GetConversionRates()
        {
            ConversionRatesCache ratesCache = _cacheStore.Get(new ConversionRatesCacheKey());

            if (ratesCache != null)
            {
                return(ratesCache.Rates);
            }

            List <ConversionRate> rates = GetConversionRatesFromExternalApi();

            _cacheStore.Add(new ConversionRatesCache(rates), new ConversionRatesCacheKey(),
                            DateTime.Now.Date.AddDays(1));

            return(rates);
        }
예제 #10
0
        protected async Task HandleQuery(HttpContext context)
        {
            using (var memoryStream = new MemoryStream())
            {
                var bodyStream = context.Response.Body;
                context.Response.Body = memoryStream;

                var url = context.Request.Path;
                _logger.Information($"GET request recieved ({url}), checking cache...");
                var resp = await _store.Get(url);

                if (resp == null)
                {
                    _logger.Information("No cache entry found, invoke next");
                    await _next.Invoke(context);

                    //add response body to the store
                    if (context.Response.ContentType.StartsWith("application/json") && context.Response.StatusCode == 200)
                    {
                        var jsonResponse = string.Empty;
                        using (var sr = new StreamReader(memoryStream)){
                            memoryStream.Seek(0, SeekOrigin.Begin);
                            jsonResponse = await sr.ReadToEndAsync();

                            memoryStream.Seek(0, SeekOrigin.Begin);
                            await _store.Set(url, jsonResponse, DateTime.Now.AddHours(1));

                            await memoryStream.CopyToAsync(bodyStream);
                        }
                        return;
                    }
                    else
                    {
                        _logger.Information($"Entry not cached, content type: ({context.Response.ContentType}), response code: ({context.Response.StatusCode})");
                    }
                }
                _logger.Information($"Found cache entry {url} returning");
                //await context.Response.WriteAsync(resp);
                await context.Response.WriteAsync(resp);

                context.Response.ContentType = "application/json";
                memoryStream.Seek(0, SeekOrigin.Begin);
                await memoryStream.CopyToAsync(bodyStream);
            }
        }
        public virtual async Task <object> Get(string key)
        {
            Condition.Requires(key, nameof(key)).IsNotNull();

            var prefixedKey = CreateKey(key);
            var value       = await _store.Get(prefixedKey);

            if (value == null)
            {
                Interlocked.Increment(ref _misses);
            }
            else
            {
                Interlocked.Increment(ref _hits);
            }

            return(value);
        }
예제 #12
0
        /// <summary>
        /// 校验验证码有效性
        /// </summary>
        /// <param name="code">要校验的验证码</param>
        /// <param name="id">验证码编号</param>
        /// <param name="removeIfSuccess">验证成功时是否移除</param>
        /// <returns></returns>
        public virtual async Task <bool> CheckCodeAsync(string id, string code, bool removeIfSuccess = true)
        {
            if (string.IsNullOrEmpty(code))
            {
                return(false);
            }

            var  entry     = CacheEntryCollection.GetVerifyCodeEntry(id);
            var  validCode = _store.Get <string>(entry);
            bool flag      = code.Equals(validCode, StringComparison.InvariantCultureIgnoreCase);

            if (removeIfSuccess && flag)
            {
                await _store.RemoveAsync(entry.Key);
            }

            return(flag);
        }
예제 #13
0
        private async Task HandleQueryRequest(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var url = context.Controller.GetType() + "|" + context.ActionDescriptor.DisplayName;

            _logger.LogWarning($"GET request recieved ({url}), checking cache...");

            var resp = await _store.Get(url);

            if (resp == null)
            {
                await next();
            }
            else
            {
                context.Result = new JsonResult(JsonConvert.DeserializeObject(resp));
                _logger.LogWarning($"Found cache entry {url} returning");
            }
        }
        public async Task <OdsApiSettings> GetOdsApiSettingsForHostedMode()
        {
            var edFiVersion = await _cacheProvider.GetOrDefault <string>(CacheKeys.EdFiVersion);

            if (edFiVersion == null)
            {
                throw new EdFiVersionNotSetException();
            }

            var odsApiSettingsKey = CacheKeys.Composed(CacheKeys.OdsApiSettings, edFiVersion);
            var odsApiSettings    = await _cacheProvider.Get <OdsApiSettings>(odsApiSettingsKey);

            if (!_environmentProvider.IsEnvironmentLocal)
            {
                odsApiSettings.ClientSecret = await _keyVaultProvider.GetClientSecret(odsApiSettings.Version);
            }

            return(odsApiSettings);
        }
        private async Task <IEnumerable <StudentInterventionsDTO> > GetStudentInterventionsDTOFromCacheOrDefaultOrThrowJsonReaderException(string uniqueSectionCode)
        {
            string key = CacheKeys.Composed(CacheKeys.InterventionScoringsBySectionUniqueId, uniqueSectionCode);

            if (!(await _cache.HasKey(key)))
            {
                return(null);
            }

            var studentInterventionsFromCache = await _cache.Get <IEnumerable <StudentInterventionsDTO> >(key);

            studentInterventionsFromCache = studentInterventionsFromCache.Select(dto =>
            {
                dto.Student = _mapper.SecuredStudentDTO(dto.Student);
                return(dto);
            }).ToList();

            return(studentInterventionsFromCache
                   .OrderBy(student => student.Student.LastSurname)
                   .ToList());
        }
예제 #16
0
        public async Task <ActionResult <IEnumerable <Country> > > GetCountriesUsingCacheStore()
        {
            // Tratar de obtener el Dato (La Lista de Paises) desde el cache
            List <Country> countries = _cacheStore.Get <List <Country> >("Countries");

            // Validar si el dato NO esta en el cache
            if (countries is null)
            {
                // Obtener el dato desde la Fuente
                countries = await GetCountries();

                // Adicionar el dato al cache
                _cacheStore.Add <List <Country> >("Countries", countries);
            }
            else
            {
                Console.WriteLine("Trayendo datos del Cache");
            }

            return(countries);
        }
예제 #17
0
        /// <summary>
        /// checks current cachestore for a cached response and returns it
        /// </summary>
        /// <param name="context"></param>
        /// <returns>cached response or null</returns>
        private static Response CheckCache(NancyContext context)
        {
            if (context.Request.Query is DynamicDictionary)
            {
                if ((context.Request.Query as DynamicDictionary).ContainsKey(NO_REQUEST_CACHE_KEY))
                {
                    return(null);
                }
            }

            var key = GetCacheKey(context.Request);

            if (string.IsNullOrEmpty(key))
            {
                return(null);
            }

            var response = _cacheStore.Get(key);

            if (response == null)
            {
                return(null);
            }

            if (response.Expiration < DateTime.Now)
            {
                var t = new Thread(HandleRequestAsync);
                t.Start(context.Request);
            }

            //make damn sure the pre-requirements are met before returning a cached response
            var preResponse = InvokePreRequirements(context);

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

            return(response);
        }
예제 #18
0
        public async Task <Intervention> GetByIdentificationCode(string identificationCode)
        {
            var key = CacheKeys.Composed(CacheKeys.InterventionByIdentificationCode, identificationCode);

            if (await _cache.TryHasKey(key))
            {
                return(await _cache.Get <Intervention>(key));
            }

            var odsApi = await _odsApiClientProvider.NewResourcesClient();

            var interventionsv3 = await odsApi.Get <IList <InterventionModelv3> >("interventions", new Dictionary <string, string>
            {
                { "interventionIdentificationCode", identificationCode },
            });

            var interventionv2 = interventionsv3.First().MapToInterventionV2();

            await _cache.Set(key, interventionv2);

            return(interventionv2);
        }
예제 #19
0
 public object Get(string key)
 {
     return(_syncCacheStore.Get(key));
 }
 public async Task <object> Get(string key)
 {
     return(await _cacheProvider.Get <object>(key));
 }
예제 #21
0
 public TValue Get <TValue>(string key) where TValue : class
 {
     return(_inner.Get <TValue>(_prefix + key));
 }