Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Created March 18, 2021 16:56
Show Gist options
  • Save gsscoder/5a1b03c588373e709ea5cefd1d0f4195 to your computer and use it in GitHub Desktop.
Save gsscoder/5a1b03c588373e709ea5cefd1d0f4195 to your computer and use it in GitHub Desktop.
Basic IHealthCheck implementation that injects chaos
using System;
using System.Threading;
using System.Threading.Tasks;
using Polly.Contrib.Simmy;
using Polly.Contrib.Simmy.Outcomes;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using CSharpx;
sealed class ChaosHealthCheck : IHealthCheck
{
readonly MonkeyPolicy _faultPolicy;
readonly Random _random = new CryptoRandom();
readonly double _raiseInjection;
public ChaosHealthCheck(double faultInjection, double raiseInjection)
{
_faultPolicy = MonkeyPolicy.InjectException(with =>
with.Fault(new Exception("Something gone wrong."))
.InjectionRate(faultInjection)
.Enabled());
_raiseInjection = raiseInjection;
}
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken))
{
var outcome = _faultPolicy.ExecuteAndCapture(() => HealthCheckResult.Healthy());
return (outcome.FinalException == null) switch
{
false => (_random.NextDouble() < _raiseInjection) switch
{
false => Task.FromResult(HealthCheckResult.Unhealthy()),
_ => throw outcome.FinalException
},
_ => Task.FromResult(outcome.Result)
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment