public string CreateToken(UserModel userModel)
        {
            _counter.Inc(1);

            var sw = Stopwatch.StartNew();

            sw.Start();
            var r = _service.CreateToken(userModel);

            sw.Stop();

            _summary.Observe(sw.ElapsedMilliseconds);

            return(r);
        }
            /// <inheritdoc />
            public void Dispose()
            {
                //                _watch.Stop();
                var delta = _watch.Subtract(DateTime.UtcNow);

                _summary.Observe(delta.TotalMilliseconds);
            }
    // Use metrics
    private void MagicFunc(InputMessage input)
    {
        if (input.FancyText == "")
        {
            _counter?.Inc();
        }

        _simpleSummary?.Observe(input.FancyNumber);

        var success = false;

        /*
         * With AutoObserveStopwatch, the metrics are still collected,
         * even if an exception is thrown within the using scope.
         * For histograms, AutoObserve can be used as a more generic approach.
         *
         * When using the Rider IDE, you might see a warning here, regarding possible
         * modifications of the variable `success` in the outer scope. Because this is
         * exactly what we want to achieve here, you can simply ignore this warning.
         * Applying the fix suggested by Rider would even break the functionality.
         */
        using (new AutoObserveStopwatch(() => _labeledSummary?.WithLabels(success.ToString())))
        {
            success = LongRunningDangerousCheck(input);
        }

        _serviceInDifferentNamespace.CountInDifferentNamespace();
    }
 public void Observe()
 {
     for (var i = 0; i < _opIterations; i++)
     {
         _summary.Observe(_dataset[i]);
     }
 }
        public async Task <UserModel> CreateAsync(UserModel user)
        {
            _counter.Inc(Increment);

            var sw = Stopwatch.StartNew();

            sw.Start();
            var r = await _service.CreateAsync(user);

            sw.Stop();

            _summary.Observe(sw.ElapsedMilliseconds);

            return(r);
        }
        // Use metrics
        private void MagicFunc(InputMessage input)
        {
            if (input.FancyText == "")
            {
                _counter?.Inc();
            }

            _summary?.Observe(input.FancyNumber);

            _serviceInDifferentNamespace.CountInDifferentNamespace();
        }
Example #7
0
        /// <summary>
        /// Validates a token that has already been granted
        /// </summary>
        /// <param name="context">The HTTP Context that generated the request</param>
        private async Task ValidateTokenAsync(HttpContext context)
        {
            var failedAuthentication = true;

            using (_logger.BeginScope("Validate Token"))
            {
                if (context.Request.Headers.ContainsKey(_authorizationHeaderName))
                {
                    var accessToken = context.Request.Headers[_authorizationHeaderName][0];

                    if (accessToken.StartsWith("Bearer "))
                    {
                        accessToken = accessToken.Substring("Bearer ".Length);

                        if (SharedAccessTokens.DecomposeSasToken(accessToken, out var resourceUri, out var policyName, out var expiresAt, out var stringToValidate, out var signature))
                        {
                            if (string.Equals(policyName, _sasTokenPolicyName, StringComparison.Ordinal))
                            {
                                if (SharedAccessTokens.IsSignatureValid(signature, _sasSigningKey, stringToValidate))
                                {
                                    if (DateTime.UtcNow < expiresAt)
                                    {
                                        context.Request.Headers.Add(_resourceUriHeaderName, resourceUri);
                                        context.Request.Headers.Add(_authorizationPolicyHeaderName, policyName);

                                        await _next.Invoke(context).ConfigureAwait(true);

                                        failedAuthentication = false;
                                        _authenticationSuccess.Observe(1.0);
                                    }
                                }
                            }
                        }
                    }
                }

                if (failedAuthentication)
                {
                    _authenticationFailure.Observe(1.0);
                    _logger.LogInformation("Attempted authentication failed");

                    context.Response.StatusCode  = (int)HttpStatusCode.Unauthorized;
                    context.Response.ContentType = ContentType;
                    await context.Response.WriteAsync(FailureResponse).ConfigureAwait(true);

                    _validateFailure.Observe(1.0);
                }
                else
                {
                    _validateSuccess.Observe(1.0);
                }
            }
        }
        public async Task SendEmailAsync(string email, string subject, string message)
        {
            _counter.Inc(Increment);

            var sw = Stopwatch.StartNew();

            sw.Start();
            await _service.SendEmailAsync(email, subject, message);

            sw.Stop();

            _summary.Observe(sw.ElapsedMilliseconds);
        }
Example #9
0
        public async Task PublishMessageAsync(MotorCloudEvent <TOutput> cloudEvent, CancellationToken token = default)
        {
            var watch = Stopwatch.StartNew();

            byte[] bytes;
            try
            {
                bytes = _messageSerializer.Serialize(cloudEvent.TypedData);
            }
            finally
            {
                watch.Stop();
                _messageSerialization?.Observe(watch.ElapsedMilliseconds);
            }

            var bytesEvent = cloudEvent.CreateNew(bytes, true);
            await _bytesMessagePublisher.PublishMessageAsync(bytesEvent, token);
        }
        public async Task <IEnumerable <UserModel> > FindAsync()
        {
            _counter.Inc(Increment);

            var sw = Stopwatch.StartNew();

            sw.Start();
            var r = await _repo.FindAsync();

            sw.Stop();

            _summary.Observe(sw.ElapsedMilliseconds);

            return(r);
        }
        public async Task <ProcessedMessageStatus> HandleMessageAsync(MotorCloudEvent <TInput> dataCloudEvent,
                                                                      CancellationToken token = default)
        {
            try
            {
                var watch = new Stopwatch();
                watch.Start();
                IEnumerable <MotorCloudEvent <TOutput> > convertedMessages;
                try
                {
                    convertedMessages = await _converter.ConvertMessageAsync(dataCloudEvent, token)
                                        .ConfigureAwait(false);
                }
                finally
                {
                    watch.Stop();
                    _messageProcessing?.Observe(watch.ElapsedMilliseconds);
                }

                foreach (var publishEvent in convertedMessages.Where(t => t.Data != null))
                {
                    await _publisher.PublishMessageAsync(publishEvent, token)
                    .ConfigureAwait(false);
                }

                return(ProcessedMessageStatus.Success);
            }
            catch (ArgumentException)
            {
                throw;
            }
            catch (Exception e)
            {
                _logger.LogError(LogEvents.ProcessingFailed, e, "Processing failed.");
                return(ProcessedMessageStatus.TemporaryFailure);
            }
        }
 public static void Observe(this ISummary observer, double val, DateTimeOffset timestamp)
 {
     observer.Observe(val, timestamp.ToUnixTimeMilliseconds());
 }
 /// <inheritdoc />
 public void Dispose()
 {
     _watch.Stop();
     _summary.Observe(_watch.ElapsedMilliseconds);
 }
 public Task <MotorCloudEvent <ByteData>?> ConvertMessageAsync(MotorCloudEvent <ByteData> dataCloudEvent,
                                                               CancellationToken token = default)
 {
     summary.Observe(dataCloudEvent.TypedData?.data.Length ?? 0);
     return(Task.FromResult <MotorCloudEvent <ByteData>?>(dataCloudEvent.CreateNew(dataCloudEvent.TypedData, true)));
 }