Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(media type formatter): add SystemTextJsonFormatter #86

Merged
merged 7 commits into from
Jul 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
### Features
- **http client builder:** configurable http version/policy via `WithVersion`, `WithVersionPolicy`
- **http client builder:** defaults to http version http2.0
- **media type formatter:** add `SystemTextJsonFormatter` `.ConfigureFormatters(x => x.Default = x.Formatters.SystemTextJsonFormatter())`

### Performance
- **logging:** middleware loggings changed to compile-time logging
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,8 @@ httpClientBuilder.WithRequestBuilderDefaults(builder => builder.AsPut());
// formatters - used for content negotiation, for "Accept" and body media formats. e.g. JSON, XML, etc...
httpClientBuilder.ConfigureFormatters(opts =>
{
opts.Default = new MessagePackMediaTypeFormatter();
opts.Default = new MessagePackMediaTypeFormatter(); // use messagepack
opts.Default = opts.Formatters.SystemTextJsonFormatter(); // use system.text.json
opts.Formatters.Add(new CustomFormatter());
});

Expand Down
60 changes: 35 additions & 25 deletions benchmark/Benchmarking.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using FluentlyHttpClient.MediaFormatters;
using FluentlyHttpClient.Middleware;
using FluentlyHttpClient.Test;
using MessagePack.Resolvers;
Expand All @@ -16,8 +17,16 @@ namespace FluentlyHttpClient.Benchmarks;
public class Benchmarking
{
private IFluentHttpClient? _jsonHttpClient;
private IFluentHttpClient? _systemTextJsonHttpClient;
private IFluentHttpClient? _messagePackHttpClient;

private readonly Hero _request = new()
{
Key = "valeera",
Name = "Valeera",
Title = "Shadow of the Uncrowned"
};

private IServiceProvider BuildContainer()
{
Log.Logger = new LoggerConfiguration()
Expand All @@ -44,7 +53,7 @@ public void Setup()
var fluentHttpClientFactory = BuildContainer()
.GetRequiredService<IFluentHttpClientFactory>();

var clientBuilder = fluentHttpClientFactory.CreateBuilder("sketch7")
var clientBuilder = fluentHttpClientFactory.CreateBuilder("newtonsoft")
.WithBaseUrl("https://sketch7.com")
.UseLogging(new LoggerHttpMiddlewareOptions
{
Expand All @@ -55,33 +64,32 @@ public void Setup()
.WithMessageHandler(mockHttp)
;

_jsonHttpClient = fluentHttpClientFactory.Add(clientBuilder);
_jsonHttpClient = clientBuilder
.ConfigureFormatters(x => x.Default = x.Formatters.JsonFormatter)
.Build();

clientBuilder = fluentHttpClientFactory.CreateBuilder("msgpacks")
.WithBaseUrl("https://sketch7.com")
.UseLogging(new LoggerHttpMiddlewareOptions
{
//ShouldLogDetailedRequest = true,
//ShouldLogDetailedResponse = true
})
.UseTimer()
.WithMessageHandler(mockHttp)
_messagePackHttpClient = clientBuilder.WithIdentifier("msgpacks")
.ConfigureFormatters(x => x.Default = new MessagePackMediaTypeFormatter(ContractlessStandardResolver.Options))
.Build()
;
_messagePackHttpClient = fluentHttpClientFactory.Add(clientBuilder);

_systemTextJsonHttpClient = clientBuilder.WithIdentifier("system.text.json")
.ConfigureFormatters(x => x.Default = x.Formatters.SystemTextJsonFormatter())
.Build()
;

Console.WriteLine($"Setup Complete");
Console.WriteLine($" - _jsonHttpClient: {_jsonHttpClient.DefaultFormatter.GetType().Name}");
Console.WriteLine($" - _messagePackHttpClient: {_messagePackHttpClient.DefaultFormatter.GetType().Name}");
Console.WriteLine($" - _systemTextJsonHttpClient: {_systemTextJsonHttpClient.DefaultFormatter.GetType().Name}");
}

[Benchmark]
public Task<Hero> PostAsJson()
{
return _jsonHttpClient.CreateRequest("/api/json")
.AsPost()
.WithBody(new Hero
{
Key = "valeera",
Name = "Valeera",
Title = "Shadow of the Uncrowned"
})
.WithBody(_request)
.Return<Hero>();
}

Expand All @@ -90,14 +98,16 @@ public Task<Hero> PostAsMessagePack()
{
return _messagePackHttpClient.CreateRequest("/api/msgpack")
.AsPost()
.WithBody(new Hero
{
Key = "valeera",
Name = "Valeera",
Title = "Shadow of the Uncrowned"
})
.WithBody(_request)
.Return<Hero>();
}


[Benchmark]
public Task<Hero> PostAsSystemTextJson()
{
return _systemTextJsonHttpClient.CreateRequest("/api/json")
.AsPost()
.WithBody(_request)
.Return<Hero>();
}
}
7 changes: 6 additions & 1 deletion samples/FluentlyHttpClient.Sample.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@

using Microsoft.AspNetCore.Server.Kestrel.Core;

namespace FluentlyHttpClient.Sample.Api;

public class Program
Expand All @@ -10,7 +12,10 @@ public static IHostBuilder CreateHostBuilder(string[] args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseUrls("http://localhost:5500/")
.UseUrls("http://localhost:5500/", "https://localhost:5510")
.ConfigureKestrel(opts => opts
.ConfigureEndpointDefaults(lo => lo.Protocols = HttpProtocols.Http1AndHttp2AndHttp3)
)
.UseStartup<Startup>()
;
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
Expand All @@ -12,7 +12,7 @@
"FluentlyHttpClient.Sample.Api": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/values",
"launchUrl": "api/heroes",
"applicationUrl": "http://localhost:5500",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
Expand Down
4 changes: 2 additions & 2 deletions src/FluentlyHttpClient/FluentlyHttpClient.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<!-- <TargetFramework>netstandard2.0</TargetFramework> -->
Expand All @@ -12,7 +12,7 @@
<PackageReference Include="Microsoft.Extensions.Http" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
<PackageReference Include="Microsoft.AspNet.WebApi.Client" />
<PackageReference Include="MimeTypesMap"/>
<PackageReference Include="MimeTypesMap" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using System.Net;
using System.Text.Json;

namespace FluentlyHttpClient.MediaFormatters;

// todo: move to separate lib?
public class SystemTextJsonMediaTypeFormatter : MediaTypeFormatter
{
private const string MediaType = "application/json";
private readonly JsonSerializerOptions _options;

/// <summary>
/// Initializes a new instance with default formatter resolver.
/// </summary>
public SystemTextJsonMediaTypeFormatter()
: this(null)
{
}

/// <summary>
/// Initializes a new instance with the provided formatter resolver.
/// </summary>
/// <param name="options"></param>
public SystemTextJsonMediaTypeFormatter(JsonSerializerOptions? options)
{
SupportedMediaTypes.Add(new(MediaType));
_options = options ?? new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
}

public override bool CanReadType(Type type)
{
ArgumentNullException.ThrowIfNull(type, nameof(type));
return IsAllowedType(type);
}

public override bool CanWriteType(Type type)
{
ArgumentNullException.ThrowIfNull(type, nameof(type));
return IsAllowedType(type);
}

private static bool IsAllowedType(Type t)
{
if (t is { IsAbstract: false, IsInterface: false, IsNotPublic: false })
return true;

if (typeof(IEnumerable<>).IsAssignableFrom(t))
return true;

return false;
}

public override async Task<object?> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
=> await JsonSerializer.DeserializeAsync(readStream, type, _options);

public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,
TransportContext transportContext)
=> await JsonSerializer.SerializeAsync(writeStream, value, type, _options);
}

public static partial class MediaTypeFormattingExtensions
{
/// <summary>
/// Create new System.Text.Json media type formatter.
/// </summary>
/// <param name="formatters"></param>
/// <param name="options">Json serialization options.</param>
public static SystemTextJsonMediaTypeFormatter SystemTextJsonFormatter(
this MediaTypeFormatterCollection formatters,
JsonSerializerOptions? options = null
) => new(options);
}
20 changes: 20 additions & 0 deletions test/FluentHttpClientFactoryTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,26 @@ public void ShouldSetDefaultFormatter()
Assert.Equal(httpClient.Formatters.XmlFormatter, httpClient.DefaultFormatter);
}

[Fact]
public void SetDefaultFormatterMany_ShouldBeSetCorrectly()
{
var clientBuilder = GetNewClientFactory()
.CreateBuilder("abc")
.WithBaseUrl("http://abc.com")
;
var httpClient = clientBuilder
.ConfigureFormatters(opts => opts.Default = opts.Formatters.XmlFormatter)
.Build()
;
var httpClient2 = clientBuilder
.ConfigureFormatters(opts => opts.Default = opts.Formatters.FormUrlEncodedFormatter)
.Build()
;

Assert.Equal(httpClient.Formatters.XmlFormatter, httpClient.DefaultFormatter);
Assert.Equal(httpClient2.Formatters.FormUrlEncodedFormatter, httpClient2.DefaultFormatter);
}

[Fact]
public void ShouldAutoRegisterDefault()
{
Expand Down
108 changes: 108 additions & 0 deletions test/Integration/LoadTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using System.Net;

namespace FluentlyHttpClient.Test.Integration;

public record MimirGqlSchema
{
public List<UniverseModel> UniversesIndex { get; set; }
}

public record UniverseModel
{
public string Id { get; set; }
public string Key { get; set; }
public string Name { get; set; }
}

public class LoadTest
{
private static IServiceProvider BuildContainer()
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.Debug()
.CreateLogger();
var container = new ServiceCollection()
.AddFluentlyHttpClient()
.AddLogging(x => x.AddSerilog());
return container.BuildServiceProvider();
}

[Fact]
[Trait("Category", "e2e")]
public async void GqlHttp2Test()
{
var socketsHandler = new SocketsHttpHandler
{
PooledConnectionIdleTimeout = Timeout.InfiniteTimeSpan,
KeepAlivePingDelay = TimeSpan.FromSeconds(60),
KeepAlivePingTimeout = TimeSpan.FromSeconds(30),
EnableMultipleHttp2Connections = true,
};
var httpClient = BuildContainer()
.GetRequiredService<IFluentHttpClientFactory>()
.CreateBuilder("mimir")
.WithBaseUrl("XXX/v1/api/graphql")
.WithBaseUrlTrailingSlash(false)
.UseLogging()
.UseTimer()
.ConfigureFormatters(opts =>
{
//opts.Default = opts.Formatters.SystemTextJsonFormatter();
})
//.WithRequestBuilderDefaults(x => x.WithVersion(HttpVersion.Version11))
.WithMessageHandler(socketsHandler)
.Build();

for (int i = 0; i < 1; i++)
{
var tasks = Enumerable.Range(0, 1800)
.Select(async (i) =>
{
var response = await httpClient.CreateGqlRequest(new()
{
//OperationName = "universe",
//Variables =
Query = @"
query universes_getByIndex($input: UniverseIndexQuery) {
universesIndex(input: $input) {
...Universe
}
}

fragment Universe on Universe {
id
key
name
isArchived

heroes @include(if: true) {
id
name
}

}
"
})//CreateRequest("/api/heroes/azmodan")
.ReturnAsGqlResponse<MimirGqlSchema>();
//response.Message.Dispose();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
return response;
}
);
await Task.WhenAll(tasks);
}


//var response = await httpClient.CreateRequest("/api/heroes/azmodan")
// .ReturnAsResponse<Hero>();
////response.Message.Dispose();

//Assert.Equal(HttpStatusCode.OK, response.StatusCode);
//Assert.Equal("azmodan", response.Data.Key);
//Assert.Equal("Azmodan", response.Data.Name);
//Assert.Equal("Lord of Sin", response.Data.Title);
}
}
2 changes: 1 addition & 1 deletion test/Integration/MessagePackIntegrationTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public async void ShouldMakeRequest_Get()
.UseTimer()
.ConfigureFormatters(opts =>
{
opts.Default = _messagePackMediaTypeFormatter;
//opts.Default = opts.Formatters.SystemTextJsonFormatter();
})
.Build();

Expand Down
Loading