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

Added benchmarks Added a feature flag to enable/disable PerformanceBehaviour #608

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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 .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,4 @@ terraform.rc*
!terraform.tfvars.example
.terraform/
backend.vars
/Benchmarks/Dfe.PersonsApi.Benchmarks/BenchmarkDotNet.Artifacts/results
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
using AutoMapper;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using Dfe.Academies.Application.Common.Behaviours;
using Dfe.Academies.Application.Constituencies.Queries.GetMemberOfParliamentByConstituencies;
using Dfe.Academies.Application.Constituencies.Queries.GetMemberOfParliamentByConstituency;
using Dfe.Academies.Application.MappingProfiles;
using Dfe.Academies.Domain.Interfaces.Caching;
using Dfe.Academies.Domain.Interfaces.Repositories;
using Dfe.Academies.Infrastructure;
using Dfe.Academies.Infrastructure.Caching;
using Dfe.Academies.Infrastructure.Repositories;
using Dfe.Academies.Testing.Common.Helpers;
using Dfe.Academies.Utils.Caching;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Dfe.PersonsApi.Benchmarks
{
[MemoryDiagnoser]
[SimpleJob(launchCount: 1, warmupCount: 2, iterationCount: 10, invocationCount: 50)]
public class ConstituencyQueryHandlerBenchmark
{
[Params("Test Constituency 1")]
public string? ConstituencyName;

[Params(true, false)]
public bool IncludePerformanceBehaviour;

private IMediator? _mediator;
private GetMembersOfParliamentByConstituenciesQuery? _query;
private IConstituencyRepository? _realRepository;
private ICacheService? _cacheService;
private IMapper? _mapper;

[GlobalSetup]
public void Setup()
{
var services = new ServiceCollection();

var dbContext = DbContextHelper<MopContext>.CreateDbContext(services);
_realRepository = new ConstituencyRepository(dbContext);

var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<ConstituencyProfile>();
});
_mapper = config.CreateMapper();

var httpContextAccessor = new HttpContextAccessor
{
HttpContext = new DefaultHttpContext()
};

var memoryCache = new MemoryCache(new MemoryCacheOptions());
var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
var logger = loggerFactory.CreateLogger<MemoryCacheService>();

var cacheSettings = Options.Create(new CacheSettings
{
DefaultDurationInSeconds = 600, // 10 minutes
Durations = new Dictionary<string, int>
{
{ nameof(GetMemberOfParliamentByConstituencyQueryHandler), 300 } // 5 minutes
}
});

_cacheService = new MemoryCacheService(memoryCache, logger, cacheSettings);

services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssembly(typeof(GetMemberOfParliamentByConstituencyQueryHandler).Assembly);

if (IncludePerformanceBehaviour)
{
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(PerformanceBehaviour<,>));
}
});

services.AddSingleton(loggerFactory);
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.AddSingleton(_realRepository);
services.AddSingleton(_cacheService);
services.AddSingleton(_mapper);
services.AddSingleton<IHttpContextAccessor>(httpContextAccessor);

var provider = services.BuildServiceProvider();
_mediator = provider.GetRequiredService<IMediator>();

_query = new GetMembersOfParliamentByConstituenciesQuery(dbContext.Constituencies.Select(x => x.ConstituencyName).Take(100).ToList());
}

[Benchmark]
public async Task RunHandlerWithCacheAsync()
{
await _mediator?.Send(_query!)!;
}

[Benchmark]
public async Task RunHandlerWithoutCacheAsync()
{
var cacheKey = $"MemberOfParliament_{CacheKeyHelper.GenerateHashedCacheKey(_query?.ConstituencyNames!)}";
_cacheService?.Remove(cacheKey);
await _mediator?.Send(_query!)!;
}

public static class Program
{
public static void Main(string[] args)
{
BenchmarkRunner.Run<ConstituencyQueryHandlerBenchmark>();
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<OutputType>Exe</OutputType>
<SkipBuild>true</SkipBuild>
</PropertyGroup>

<ItemGroup>
<None Remove="appsettings.json" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.14.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\Dfe.Academies.Domain\Dfe.Academies.Domain.csproj" />
<ProjectReference Include="..\..\Tests\Dfe.Academies.Testing.Common\Dfe.Academies.Testing.Common.csproj" />
</ItemGroup>

<ItemGroup>
<None Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
5 changes: 5 additions & 0 deletions Benchmarks/Dfe.PersonsApi.Benchmarks/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=sip;User ID=sa;Password=StrongPassword905;TrustServerCertificate=True"
Dismissed Show dismissed Hide dismissed
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,20 @@ public static IServiceCollection AddApplicationDependencyGroup(
public static IServiceCollection AddPersonsApiApplicationDependencyGroup(
this IServiceCollection services, IConfiguration config)
{
var performanceLoggingEnabled = config.GetValue<bool>("Features:PerformanceLoggingEnabled");

services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());

services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(UnhandledExceptionBehaviour<,>));
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>));
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(PerformanceBehaviour<,>));

if (performanceLoggingEnabled)
{
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(PerformanceBehaviour<,>));
}
});

return services;
Expand Down
3 changes: 3 additions & 0 deletions PersonsApi/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,8 @@
"TenantId": "9c7d9dd3-840c-4b3f-818e-552865082e16",
"ClientId": "930a077f-43d0-48cb-9316-1e0430eeaf6b",
"Audience": "api://930a077f-43d0-48cb-9316-1e0430eeaf6b"
},
"Features": {
"PerformanceLoggingEnabled": true
}
}
3 changes: 3 additions & 0 deletions PersonsApi/appsettings.Production.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,8 @@
"TenantId": "9c7d9dd3-840c-4b3f-818e-552865082e16",
"ClientId": "abae81d8-c7e3-4f28-8349-c43f554a712b",
"Audience": "api://abae81d8-c7e3-4f28-8349-c43f554a712b"
},
"Features": {
"PerformanceLoggingEnabled": false
}
}
3 changes: 3 additions & 0 deletions PersonsApi/appsettings.Test.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,8 @@
"TenantId": "9c7d9dd3-840c-4b3f-818e-552865082e16",
"ClientId": "930a077f-43d0-48cb-9316-1e0430eeaf6b",
"Audience": "api://930a077f-43d0-48cb-9316-1e0430eeaf6b"
},
"Features": {
"PerformanceLoggingEnabled": true
}
}
Loading
Loading