Beispiel #1
0
        public async Task <byte[]> GetAsync(string key, CancellationToken token = default)
        {
            using var activity = applicationContextActivityDecorator.StartActivity();
            activity.AddTag("cacheKey", key);

            logger.LogTrace($"Requesting cache for key {key}");

            var cacheResult = BlogConfiguration.ApplicationCacheType switch
            {
                CacheType.InMemory => memoryCache.Get <byte[]>(key),
                CacheType.Distributed => await distributedCache.GetAsync(key, token),
                _ => throw new ArgumentException($"The given cache type '{BlogConfiguration.ApplicationCacheType}' is not known")
            };

            var tags = new[] {
                new KeyValuePair <string, object>("key", key),
                new KeyValuePair <string, object>("type", BlogConfiguration.ApplicationCacheType.ToString())
            }.Concat(MetricTags.GetDefaultTags()).ToArray();

            CacheHitCounter.Add(1, tags);
            CacheHitSuccessCounter.Add(cacheResult == null ? 0 : 1, tags);
            CacheHitFailedCounter.Add(cacheResult == null ? 1 : 0, tags);

            logger.LogDebug($"Hitting cache for key {key} {(cacheResult == null ? "didn't" : "did")} return a value");

            return(cacheResult);
        }
Beispiel #2
0
        public async Task <IReadOnlyList <TModel> > FindAsync()
        {
            var activity = applicationContextActivityDecorator.StartActivity($"{nameof(RelationalDbRepository<TDbModel, TModel>)}.{nameof(FindAsync)}");
            var dbModels = await connectionFactory.Connection.GetAllAsync <TDbModel>();

            return(mapper.Map <List <TModel> >(dbModels.ToList()));
        }
Beispiel #3
0
        public async Task <LoginResponseDto> LoginAsync([FromBody] LoginCredentialsDto credentials)
        {
            using var activity = traceActivityDecorator.StartActivity();
            activity.AddTag("username", credentials.Key);
            activity.AddTag("session", credentials.Session);
            activity.AddTag("type", credentials.Type);

            logger.LogTrace($"Trying to login user {credentials.Key}");

            var response = await RunAllAuthenticationChecksAsync(credentials);

            var tags = new[] {
                new KeyValuePair <string, object>("username", credentials.Key),
                new KeyValuePair <string, object>("session", credentials.Session),
                new KeyValuePair <string, object>("type", credentials.Type)
            }.Concat(MetricTags.GetDefaultTags()).ToArray();

            LoginAttemptsCounter.Add(1, tags);
            LoginSuccessCounter.Add(response.Success ? 1 : 0, tags);
            LoginFailedCounter.Add(response.Success ? 0 : 1, tags);

            if (response.Success && response.Type == LoginResponseType.AuthenticationToken)
            {
                var message = new {
                    User     = credentials.Key,
                    RemoteId = httpContextAccessor?.HttpContext?.Connection?.RemoteIpAddress?.ToString()
                };
                await messageBus.SendMessageAsync("ntfrex.blog.logins", JsonSerializer.Serialize(message));
            }

            logger.LogInformation($"User {credentials.Key} login was {(!response.Success ? "not" : "")} succesfull");
            return(response);
        }
        public async Task <IReadOnlyList <TagModel> > FindByArticleIdAsync(string articleId)
        {
            var activity = applicationContextActivityDecorator.StartActivity($"{nameof(RelationalDbTagRepository)}.{nameof(FindByArticleIdAsync)}");
            var dbModels = await connectionFactory.Connection.GetAllAsync <Models.TagModel>();

            return(mapper.Map <List <TagModel> >(dbModels.Where(x => x.ArticleId == articleId).ToList()));
        }
Beispiel #5
0
        public async Task <IReadOnlyList <CommentDto> > GetAllCommentsAsync()
        {
            using var activity = traceActivityDecorator.StartActivity();
            var cacheKey = CacheKeys.AllComments;

            return(await cache.CacheAsync(cacheKey.Name, cacheKey.TimeToLive, async() =>
            {
                var dbModels = await commentRepository.FindAsync();
                return mapper.Map <List <CommentDto> >(dbModels).ToList();
            }));
        }
        public async Task <ImageModel> FindByNameAsync(string name)
        {
            var activity = applicationContextActivityDecorator.StartActivity($"{nameof(RelationalDbImageRepository)}.{nameof(FindByNameAsync)}");
            var dbModels = await connectionFactory.Connection.GetAllAsync <Models.ImageModel>();

            return(mapper.Map <ImageModel>(dbModels.First(x => x.Name == name)));
        }
        public async Task <long> CountByArticleIdAsync(string id)
        {
            var activity = applicationContextActivityDecorator.StartActivity($"{nameof(RelationalDbVisitorRepository)}.{nameof(CountByArticleIdAsync)}");
            var visitors = await connectionFactory.Connection.GetAllAsync <Models.VisitorModel>();

            var models = mapper.Map <List <VisitorModel> >(visitors);

            return(models.Where(x => x.Article == id).Count(IVisitorRepository.ShouldCountVisitor));
        }
        public async Task Invoke(HttpContext httpContext)
        {
            using var activity = traceActivityDecorator.StartActivity();

            var traceId = httpContext.Items[HttpContextItemNames.TraceId];

            using (logger.BeginScope(traceId))
            {
                logger.LogTrace("Begin request scope");
                await next(httpContext);

                logger.LogTrace("End request scope");
            }
        }
Beispiel #9
0
        protected override Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            using var activity = applicationContextActivityDecorator.StartActivity();

            var authenticationResult = TryAuthenticate();

            var tags = new[] {
                new KeyValuePair <string, object>("scheme", AuthenticationScheme),
                new KeyValuePair <string, object>("principal", authenticationResult?.Principal?.GetIdClaim())
            }.Concat(MetricTags.GetDefaultTags()).ToArray();

            RequestCount.Add(1, tags);
            RequestAuthenticatedCount.Add(authenticationResult.Succeeded ? 1 : 0, tags);
            RequestUnauthenticatedCount.Add(authenticationResult.Succeeded ? 0 : 1, tags);

            return(Task.FromResult(authenticationResult));
        }
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            var healthCheckName = GetType().Name;

            using var activity = traceActivityDecorator.StartActivity();
            activity.AddTag("healthCheckName", healthCheckName);

            var result = await DoCheckHealthAsync(context, cancellationToken);

            var tags = new[] {
                new KeyValuePair <string, object>("name", healthCheckName)
            }.Concat(MetricTags.GetDefaultTags()).ToArray();

            HealthCheckCounter.Add(1, tags);
            DegratedCounter.Add(result.Status == HealthStatus.Degraded ? 1 : 0, tags);
            UnhealthyCounter.Add(result.Status == HealthStatus.Unhealthy ? 1 : 0, tags);
            HealthyCounter.Add(result.Status == HealthStatus.Healthy ? 1 : 0, tags);

            return(result);
        }
Beispiel #11
0
        public async Task <IReadOnlyList <ArticleDto> > GetAllArticlesAsync(bool includeUnpublished)
        {
            using var activity = traceActivityDecorator.StartActivity();
            var cacheKey = includeUnpublished ? CacheKeys.AllArticles : CacheKeys.AllPublishedArticles;

            return(await cache.CacheAsync(
                       cacheKey.Name,
                       cacheKey.TimeToLive,
                       () => FindAsync(includeUnpublished)));
        }