diff --git a/src/bundles/Elsa.Server.Web/Middleware/SimulatedLatencyMiddleware.cs b/src/bundles/Elsa.Server.Web/Middleware/SimulatedLatencyMiddleware.cs new file mode 100644 index 000000000..d2191383d --- /dev/null +++ b/src/bundles/Elsa.Server.Web/Middleware/SimulatedLatencyMiddleware.cs @@ -0,0 +1,56 @@ +using JetBrains.Annotations; + +namespace Elsa.Server.Web.Middleware; + +/// +/// Simulates latency by delaying the request for a random amount of time between the specified minimum and maximum durations. +/// +/// +/// +/// +[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 = new(() => new Random()); + + /// + /// Invokes the middleware. + /// + /// + [UsedImplicitly] + public async Task Invoke(HttpContext context) + { + int delayInMs = _random.Value!.Next( + _minDelayInMs, + _maxDelayInMs + ); + + await Task.Delay(delayInMs); + await next(context); + } +} + +/// +/// Provides extension methods for the interface. +/// +public static class AppBuilderExtensions +{ + /// + /// Adds the to the application's request pipeline. + /// + /// + /// + /// + public static IApplicationBuilder UseSimulatedLatency( + this IApplicationBuilder app, + TimeSpan min, + TimeSpan max) + { + return app.UseMiddleware(min, max); + } +} \ No newline at end of file diff --git a/src/bundles/Elsa.Server.Web/Program.cs b/src/bundles/Elsa.Server.Web/Program.cs index 978680966..c0bdc67f0 100644 --- a/src/bundles/Elsa.Server.Web/Program.cs +++ b/src/bundles/Elsa.Server.Web/Program.cs @@ -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();