public void Can_get_formatter_by_media_type()
        {
            // Arrange
            var formatters = new MetricsFormatterCollection();

            formatters.TryAdd(new MetricsJsonOutputFormatter());
            formatters.TryAdd(new MetricsTextOutputFormatter());
            var mediaType = new MetricsMediaTypeValue("text", "vnd.appmetrics.metrics", "v1", "plain");

            // Act
            var result = formatters.GetType(mediaType);

            // Assert
            result.Should().BeOfType(typeof(MetricsTextOutputFormatter));
        }
        public void Can_remove_formatter_by_media_type()
        {
            // Arrange
            var formatters = new MetricsFormatterCollection();

            formatters.TryAdd(new MetricsJsonOutputFormatter());
            formatters.TryAdd(new MetricsTextOutputFormatter());
            var mediaType = new MetricsMediaTypeValue("application", "vnd.appmetrics.metrics", "v1", "json");

            // Act
            formatters.RemoveType(mediaType);

            // Assert
            formatters.Single().Should().BeOfType(typeof(MetricsTextOutputFormatter));
        }
        public async Task <HttpWriteResult> WriteAsync(
            string payload,
            MetricsMediaTypeValue mediaType,
            CancellationToken cancellationToken = default)
        {
            if (NeedToBackoff())
            {
                return(new HttpWriteResult(false, $"Too many failures in writing to {_httpSettings.RequestUri}, Circuit Opened"));
            }

            try
            {
                var message = new HttpRequestMessage(HttpMethod.Post, _httpSettings.RequestUri)
                {
                    Content = new StringContent(payload, Encoding.UTF8, mediaType.ContentType)
                };

                var response = await _httpClient.SendAsync(message, cancellationToken);

                if (!response.IsSuccessStatusCode)
                {
                    Interlocked.Increment(ref _failureAttempts);

                    var errorMessage =
                        $"Failed to write to {_httpSettings.RequestUri} - StatusCode: {response.StatusCode} Reason: {response.ReasonPhrase}";
                    Logger.Error(errorMessage);

                    return(new HttpWriteResult(false, errorMessage));
                }

                Logger.Trace($"Successful write to {_httpSettings.RequestUri}");

                return(new HttpWriteResult(true));
            }
            catch (Exception ex)
            {
                Interlocked.Increment(ref _failureAttempts);
                Logger.Error(ex, $"Failed to write to {_httpSettings.RequestUri}");
                return(new HttpWriteResult(false, ex.ToString()));
            }
        }
 public TestMetricsFormatter()
 {
     MediaType = new MetricsMediaTypeValue("test", "test", "v1", "format");
 }