Add simulated latency middleware

A new middleware, SimulatedLatencyMiddleware, has been added to simulate latency in a designated range. This can be used for testing purposes by delaying a request for a random amount of time. Additionally, an extension method for IApplicationBuilder has been implemented to conveniently add this functionality to the application's pipeline.
This commit is contained in:
Sipke Schoorstra 2024-02-21 09:25:59 +01:00
parent 26518a3759
commit 662a076726
2 changed files with 62 additions and 0 deletions

View file

@ -0,0 +1,56 @@
using JetBrains.Annotations;
namespace Elsa.Server.Web.Middleware;
/// <summary>
/// Simulates latency by delaying the request for a random amount of time between the specified minimum and maximum durations.
/// </summary>
/// <param name="next"></param>
/// <param name="min"></param>
/// <param name="max"></param>
[UsedImplicitly]
public class SimulatedLatencyMiddleware(
RequestDelegate next,
TimeSpan min,
TimeSpan max)
{
private readonly int _minDelayInMs = (int)min.TotalMilliseconds;
private readonly int _maxDelayInMs = (int)max.TotalMilliseconds;
private readonly ThreadLocal<Random> _random = new(() => new Random());
/// <summary>
/// Invokes the middleware.
/// </summary>
/// <param name="context"></param>
[UsedImplicitly]
public async Task Invoke(HttpContext context)
{
int delayInMs = _random.Value!.Next(
_minDelayInMs,
_maxDelayInMs
);
await Task.Delay(delayInMs);
await next(context);
}
}
/// <summary>
/// Provides extension methods for the <see cref="IApplicationBuilder"/> interface.
/// </summary>
public static class AppBuilderExtensions
{
/// <summary>
/// Adds the <see cref="SimulatedLatencyMiddleware"/> to the application's request pipeline.
/// </summary>
/// <param name="app"></param>
/// <param name="min"></param>
/// <param name="max"></param>
public static IApplicationBuilder UseSimulatedLatency(
this IApplicationBuilder app,
TimeSpan min,
TimeSpan max)
{
return app.UseMiddleware<SimulatedLatencyMiddleware>(min, max);
}
}

View file

@ -16,6 +16,7 @@ using Elsa.MongoDb.Modules.Identity;
using Elsa.MongoDb.Modules.Management;
using Elsa.MongoDb.Modules.Runtime;
using Elsa.Server.Web;
using Elsa.Server.Web.Middleware;
using Elsa.Workflows.Management.Compression;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Options;
@ -249,6 +250,11 @@ services.AddCors(cors => cors.AddDefaultPolicy(policy => policy.AllowAnyHeader()
// Build the web application.
var app = builder.Build();
// app.UseSimulatedLatency(
// TimeSpan.FromMilliseconds(1000),
// TimeSpan.FromMilliseconds(3000)
// );
// Configure the pipeline.
if (app.Environment.IsDevelopment())
app.UseDeveloperExceptionPage();