| | | 1 | | using System.Text.Json; |
| | | 2 | | using FastEndpoints; |
| | | 3 | | using Microsoft.Extensions.Caching.Memory; |
| | | 4 | | using static Elsa.Resilience.Endpoints.SimulateResponse.StatusCodeMessageLookup; |
| | | 5 | | |
| | | 6 | | namespace Elsa.Resilience.Endpoints.SimulateResponse; |
| | | 7 | | |
| | 1 | 8 | | public class SimulateResponseEndpoint(IMemoryCache memoryCache) : EndpointWithoutRequest<SimulatedResponse> |
| | | 9 | | { |
| | 0 | 10 | | private static readonly TimeSpan SlidingExpirationTimeSpan = TimeSpan.FromMinutes(15); |
| | | 11 | | |
| | | 12 | | public override void Configure() |
| | | 13 | | { |
| | 1 | 14 | | Get("/simulate-response"); |
| | 1 | 15 | | AllowAnonymous(); |
| | 1 | 16 | | } |
| | | 17 | | |
| | | 18 | | public override async Task HandleAsync(CancellationToken ct) |
| | | 19 | | { |
| | 0 | 20 | | var sessionId = HttpContext.Request.Query["sessionId"].FirstOrDefault() ?? "default"; |
| | 0 | 21 | | var codes = GetCodes(); |
| | 0 | 22 | | var cacheKey = $"status-simulation-session-{sessionId}"; |
| | 0 | 23 | | var nextIndex = memoryCache.GetOrCreate(cacheKey, entry => |
| | 0 | 24 | | { |
| | 0 | 25 | | entry.SlidingExpiration = SlidingExpirationTimeSpan; |
| | 0 | 26 | | return 0; |
| | 0 | 27 | | }); |
| | | 28 | | |
| | 0 | 29 | | var currentCode = nextIndex < codes.Length ? codes[nextIndex] : codes[^1]; |
| | 0 | 30 | | var message = StatusMessages.TryGetValue(currentCode, out var reason) |
| | 0 | 31 | | ? reason |
| | 0 | 32 | | : $"Status Code {currentCode}"; |
| | | 33 | | |
| | 0 | 34 | | if (nextIndex + 1 >= codes.Length) |
| | | 35 | | { |
| | 0 | 36 | | memoryCache.Remove(cacheKey); |
| | | 37 | | } |
| | | 38 | | else |
| | | 39 | | { |
| | 0 | 40 | | memoryCache.Set(cacheKey, nextIndex + 1, new MemoryCacheEntryOptions |
| | 0 | 41 | | { |
| | 0 | 42 | | SlidingExpiration = SlidingExpirationTimeSpan |
| | 0 | 43 | | }); |
| | | 44 | | } |
| | | 45 | | |
| | 0 | 46 | | await Send.ResponseAsync(new(message), currentCode, ct); |
| | 0 | 47 | | } |
| | | 48 | | |
| | | 49 | | private int[] GetCodes() |
| | | 50 | | { |
| | 0 | 51 | | var codesParam = HttpContext.Request.Query["codes"].FirstOrDefault(); |
| | 0 | 52 | | int[] defaultCodes = [429, 503, 200]; |
| | 0 | 53 | | return string.IsNullOrWhiteSpace(codesParam) ? defaultCodes : JsonSerializer.Deserialize<int[]>(codesParam)!; |
| | | 54 | | } |
| | | 55 | | } |