Simmy Chaos Engine for .NET – Part 6, Configuring Policies Dynamically

Full source code here.

Simmy chaos policies have configurable options, via these options the polices can be turned on or off, have the rate at which they fire set, and in the case of the latency policy, the injected delay.

Here is an example of the fault policy –

AsyncInjectOutcomePolicy<HttpResponseMessage> faultPolicy = MonkeyPolicy.InjectFaultAsync<HttpResponseMessage>(
	new HttpRequestException("Simmy threw an exception, you should probably handle it in some way."),
	injectionRate: .5, //can be set through configuration
	enabled: () => true //can be set through configuration
);

And here is the latency policy –

var latencyPolicy = MonkeyPolicy.InjectLatencyAsync<HttpResponseMessage>(
	TimeSpan.FromSeconds(3), //can be set through configuration
	0.5, //can be set through configuration
	enabled: () => true); //can be set through configuration

This post shows how to set the all these settings via the appsettings.json file, but you could just as easily use a key store such as Consul or those provided by AWS and Azure. When you are using the application, change the values in appsettings.json and you will see the policies behave differently, try turning then on and off, changing the injection rate, and increasing/decreasing the delay.

In the appsettings.json I have something like –

{
  "SimmySettings": {
    "FaultPolicySettings": {
      "Enabled": false,
      "InjectionRate": 0.1
    },
    "LatencyPolicySettings": {
      "Enabled": true,
      "Latency": 3,
      "InjectionRate": 0.99
    }
  }
}

A matching FaultOptions.cs class.

namespace SimmyConfigurePolicies
{
    public class FaultOptions
    {
        public LatencyPolicySettings LatencyPolicySettings { get; set; }
        public FaultPolicySettings FaultPolicySettings { get; set; }
    }

    public class LatencyPolicySettings
    {
        public bool Enabled { get; set; }
        public double Latency { get; set; }
        public double InjectionRate { get; set; }

    }
    public class FaultPolicySettings
    {
        public bool Enabled { get; set; }
        public double InjectionRate { get; set; }
    }
}

The ConfigureServices method looks like this –

public void ConfigureServices(IServiceCollection services)
{
	services.AddOptions();

	services.Configure<FaultOptions>(Configuration.GetSection("SimmySettings"));
	services.AddPolicyRegistry();

	// Add the HttpClientFactory
	services.AddHttpClient("OpenBreweryDb", client =>
	{
		client.BaseAddress = new Uri("https://api.openbrewerydb.org/breweries/");
		client.DefaultRequestHeaders.Add("Accept", "application/json");
	});

	services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

Note the services.AddOptions, Microsoft recommends adding this, but I have found it works fine without.
Also notice that I have NOT added any policies to the registry, if you have been following along with this series of blog posts you might have noticed that I usually add the policies inside ConfigureServices.

Instead I have moved the policies to the Configure method because I need to get at the instance of FaultOptions that is inside the service collection. There are ways to do this from inside ConfigureServices, but Microsoft warns you not to do this.
But accessing the FaultOptions from inside Configure is just fine. I define the policies and use the value inside the FaultOptions to configure the two policies.

For the fault policy I added a methods to make accessing the FaultOptions easier (you can see these in the attached source code), and for the latency policy I access the values directly.

Then add the policies to the registry.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
	_faultOptions = app.ApplicationServices.GetService<IOptionsMonitor<FaultOptions>>();

	AsyncInjectOutcomePolicy<HttpResponseMessage> faultPolicy = MonkeyPolicy.InjectFaultAsync<HttpResponseMessage>(
		FaultToThrow, // 
		FaultPolicyInjectionRate,
		FaultPolicyEnabled
	 );

	AsyncInjectLatencyPolicy<HttpResponseMessage> latencyPolicy = MonkeyPolicy.InjectLatencyAsync<HttpResponseMessage>(
		 TimeSpan.FromSeconds(_faultOptions.CurrentValue.LatencyPolicySettings.Latency),
		 _faultOptions.CurrentValue.LatencyPolicySettings.InjectionRate,
		 () => _faultOptions.CurrentValue.LatencyPolicySettings.Enabled);

	var registry = app.ApplicationServices.GetRequiredService<IPolicyRegistry<string>>();
	registry.Add("FaultPolicy", faultPolicy);
	registry.Add("LatencyPolicy", latencyPolicy);
	if (env.IsDevelopment())
	{
		app.UseDeveloperExceptionPage();
	}

	app.UseMvc();
}

The policies are used in the BreweryController, in the constructor I add the HttpClientFactory and the policy registry.
In the action method grab the policy from the registry and use it to make the request to the remote service.

public class BreweryController : Controller
{
	private readonly IHttpClientFactory _httpClientFactory;
	private readonly IPolicyRegistry<string> _policyRegistry;
	public BreweryController(IHttpClientFactory httpClientFactory, IPolicyRegistry<string> policyRegistry)
	{
		_policyRegistry = policyRegistry;
		_httpClientFactory = httpClientFactory;
	}

	public async Task<IActionResult> Get(string state = "Massachusetts", string name = "night shift brewing")
	{
		var simmyPolicy = _policyRegistry.Get<AsyncMonkeyPolicy<HttpResponseMessage>>("LatencyPolicy");
		//var simmyPolicy = _policyRegistry.Get<AsyncMonkeyPolicy<HttpResponseMessage>>("FaultPolicy");
		string requestEndpoint = $"?by_state={state}&by_name={name}";

		var httpClient = _httpClientFactory.CreateClient("OpenBreweryDb");

		var response =  await simmyPolicy.ExecuteAsync( async () => await httpClient.GetAsync(requestEndpoint));
		if (response.IsSuccessStatusCode)
		{
			var breweries = await response.Content.ReadAsAsync<List<Brewery>>();
			return Ok(breweries);
		}

		return StatusCode((int)response.StatusCode, await response.Content.ReadAsStringAsync());
	}
}

There are a few improvements that can be made to this and I’ll show them over the next few posts, one is to select a random chaos policy from the registry and the second is to apply the chaos policies to HttpClientFactory policy selector.

Full source code here.

Passing Configuration Options Into Middleware, Services and Controllers in ASP.NET Core 3.1

Full source code here.

I recently hit a problem where I needed to reload configuration settings as they changed, fortunately this is relatively straightforward when using the IOptionsMonitor, in .NET Core.

Add a few lines to ConfigureServices, pass the configuration options as a scoped service to the controller or into another service and everything works.

Here is all you need in the ConfigureServices method –

public void ConfigureServices(IServiceCollection services)
{
	services.AddOptions();
	services.Configure<WeatherOptions>(Configuration.GetSection("WeatherOptions"));
	services.AddScoped<ISomeService, SomeService>();

Here’s the service that takes the IOptionsMonitor

public class SomeService : ISomeService
{
	private readonly WeatherOptions _weatherOptions;

	public SomeService(IOptionsMonitor<WeatherOptions> weatherOptions)
	{
		_weatherOptions = weatherOptions.CurrentValue;
	}
// snip..

And here is the controller taking the IOptionsMonitor and the service that also uses the options, this is of course contrived and you almost certainly would not want to take both constructor parameters –

public class WeatherForecastController : ControllerBase
{
	private readonly WeatherOptions _weatherOptions;
	private readonly ISomeService _someService;
	public WeatherForecastController(IOptionsMonitor<WeatherOptions> weatherOptions, ISomeService someService)
	{
		_someService = someService;
		_weatherOptions = weatherOptions.CurrentValue;
	}

But what if you also had to pass those configuration settings into a piece of middleware that executes on each request and if they configuration values change you want to be reflected in the execution of the middleware. This is not so easy because the constructor of a middleware class can only have singletons injected into it, same applies to the Configure method Startup.

Fortunately, the Invoke method can have a scoped service injected into it, see here for more.

public class SomeMiddleware
{
	private readonly RequestDelegate _next;

	public SomeMiddleware(RequestDelegate next)
	{
		_next = next;
	}

	public async Task InvokeAsync(HttpContext context, ISomeService someService)
	{
		someService.DoSomething("Middleware - ");
		await _next(context);
	}
}

To use the middleware, add a single line to the Configure method –

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	app.UseMiddleware<SomeMiddleware>();
	//snip..

That’s it.

Full source code here.