Created
March 18, 2021 16:56
-
-
Save gsscoder/5a1b03c588373e709ea5cefd1d0f4195 to your computer and use it in GitHub Desktop.
Basic IHealthCheck implementation that injects chaos
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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