forked from datalust/seqcli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFaultInjectionMiddleware.cs
More file actions
73 lines (62 loc) · 1.89 KB
/
FaultInjectionMiddleware.cs
File metadata and controls
73 lines (62 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Roastery.Util;
using Serilog;
namespace Roastery.Web;
class FaultInjectionMiddleware: HttpServer
{
readonly ILogger _logger;
readonly HttpServer _next;
readonly Func<HttpRequest, Task<HttpResponse>>[] _faults;
public FaultInjectionMiddleware(ILogger logger, HttpServer next)
{
_logger = logger.ForContext<FaultInjectionMiddleware>();
_next = next;
_faults =
[
Unauthorized,
Unauthorized,
Unauthorized,
Timeout,
Timeout,
Disposed
];
}
Task<HttpResponse> Unauthorized(HttpRequest request)
{
_logger.Debug("Could not validate authentication token: token is expired");
return Task.FromResult(new HttpResponse(HttpStatusCode.Unauthorized, "Please log in."));
}
static async Task<HttpResponse> Timeout(HttpRequest request)
{
using var cts = new CancellationTokenSource();
cts.CancelAfter(5000);
await Task.Delay(-1, cts.Token);
throw new InvalidOperationException("Should never reach this.");
}
static Task<HttpResponse> Disposed(HttpRequest request)
{
throw new ObjectDisposedException("TcpConnection");
}
static Task<HttpResponse> Dropped()
{
throw new IOException("An operation was attempted on a nonexistent network connection.");
}
public override async Task<HttpResponse> InvokeAsync(HttpRequest request)
{
if (Distribution.OnceIn(220))
{
var fault = Distribution.Uniform(_faults);
return await fault(request);
}
var result = await _next.InvokeAsync(request);
if (Distribution.OnceIn(280))
{
return await Dropped();
}
return result;
}
}