Skip to content

Commit

Permalink
Add simulated latency middleware
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
sfmskywalker committed Feb 21, 2024
1 parent 26518a3 commit 662a076
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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);
}
}
6 changes: 6 additions & 0 deletions src/bundles/Elsa.Server.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
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;
Expand Down Expand Up @@ -249,6 +250,11 @@
// 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();
Expand Down

0 comments on commit 662a076

Please sign in to comment.