Skip to content

Commit 3f32430

Browse files
authored
Feat/add redis example (#1)
* Add WIP Redis example * Fix Redis example * Add Nearform as a known word * Increase the default cache timeout to 5s * Stop storing a manual TTL * Rename 'webfrontend' to 'web' * Disable local cache * Greatly increase the cache timeout to allow for debugging This is a sample, after all * Disable local cache (missed this in f7c6242) * Cleanup * Address static analysis concerns * Address ReSharper issues in Microsoft's template :) * Feat/use di properly (#2) * Switch to properly using DI 🤦‍♂️ * [WIP] Partially fix tests. No compilation errors, but most tests fail * [WIP] Fix some DI * Allow the caller to send in a cancellation token * Fix removal of items in CacheHelperTests * Remove an impossible test DI now handles the cache, we can't set it anymore * [WIP] ? * Fix SlowDownMiddlewareExtensionsTests/SlowDownOptionsTests * Make many of the middleware integration tests work again * [WIP] Attempting to force a 404 * Fix more tests * Remove `AspNetTestServerFixture`, not used * Make /err work! * Address some static analysis finds * Get back to 100% code coverage on AspNetCoreHelper * Static analysis fix * Allow an IP to be passed to CreateXForwardedForHttpRequest() * Suppress an unused warning * Add tests for `CacheHelper`'s `Remove()` and `RemoveAll()` * Remove dead code * Remove the `TimeDelay` check in `CalculateDelay()` A window of 0 is invalid for HybridCache and causes an exception. * Get the middleware back to 100% test coverage. * Static analysis fix * Be consistent * Set the URLs to the Nearform repo * s/Nearform/Nearform Ltd. * Add the README to the generated NuGet package * Remove dead code * Fix some issues in the readme * Add Authors/Company/Copyright to the rest of the project files
1 parent b05ee96 commit 3f32430

File tree

57 files changed

+1832
-406
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

57 files changed

+1832
-406
lines changed

README.md

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -53,16 +53,18 @@ The response will have some additional headers:
5353

5454
| Name | Type | Default Value | Description |
5555
|--------------------------|----------|-----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
56-
| `Delay` | number | `1000` | Base unit of time delay applied to requests. It is expressed in milliseconds. Set to `0` to disable delaying. |
57-
| `DelayAfter` | number | `5` | Number of requests received during `TimeWindow` before starting to delay responses. Set to `0` to disable delaying. |
58-
| `MaxDelay` | number | `int.MaxValue` | The maximum value of delay that a request has after many consecutive attempts. It is an important option for the server when it is running behind a load balancer or reverse proxy, and has a request timeout. Set to `0` to disable delaying. |
59-
| `TimeWindow` | number | `30000` | The duration of the time window during which request counts are kept in memory. It is expressed in milliseconds. Set to `0` to disable delaying. |
60-
| `AddHeaders` | boolean | `true` | Flag to add custom headers `x-slow-down-limit`, `x-slow-down-remaining`, `x-slow-down-delay` for all server responses. |
56+
| `SlowDownEnabled` | bool | `true` | Flag to enable or disable the middleware. |
57+
| `Delay` | int | `1000` | Base unit of time delay applied to requests. It is expressed in milliseconds. Set to `0` to disable delaying. |
58+
| `DelayAfter` | int | `5` | Number of requests received during `TimeWindow` before starting to delay responses. Set to `0` to disable delaying. |
59+
| `MaxDelay` | int | `int.MaxValue` | The maximum value of delay that a request has after many consecutive attempts. It is an important option for the server when it is running behind a load balancer or reverse proxy, and has a request timeout. Set to `0` to disable delaying. |
60+
| `TimeWindow` | int | `30000` | The duration of the time window during which request counts are kept in memory. It is expressed in milliseconds. Set to `0` to disable delaying. |
61+
| `AddHeaders` | bool | `true` | Flag to add custom headers `x-slow-down-limit`, `x-slow-down-remaining`, `x-slow-down-delay` for all server responses. |
6162
| `KeyGenerator` | delegate | (req) => req.ip | Function used to generate keys to uniquely identify requests coming from the same user |
6263
| `OnLimitReached` | delegate | `null` | Function that gets called the first time the limit is reached within `TimeWindow`. |
63-
| `SkipFailedRequests` | boolean | `false` | When `true`, failed requests (status >= 400) won't be counted. |
64-
| `SkipSuccessfulRequests` | boolean | `false` | When `true`, successful requests (status < 400) won't be counted. |
64+
| `SkipFailedRequests` | bool | `false` | When `true`, failed requests (status >= 400) won't be counted. |
65+
| `SkipSuccessfulRequests` | bool | `false` | When `true`, successful requests (status < 400) won't be counted. |
6566
| `Skip` | delegate | `null` | Function used to skip requests. Returning `true` from the function will skip limiting for that request. |
67+
| `CacheTimeout` | int | `5000` | Timeout, in ms, for cache lookups. If exceeded, the request is not delayed. |
6668

6769
## Configuration examples
6870

@@ -136,4 +138,4 @@ Delay remains the same because the value of `MaxDelay` option is `100000`.
136138

137139
## License
138140

139-
Nearform.AspNetCore.SlowDown is released under the MIT License.
141+
`Nearform.AspNetCore.SlowDown` is released under the MIT License.

SlowDown.sln.DotSettings

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
22
<s:Boolean x:Key="/Default/Environment/Filtering/ExcludeCoverageFilters/=BasicSlowDownExample_003B_002A_003B_002A_003B_002A/@EntryIndexedValue">True</s:Boolean>
3+
<s:Boolean x:Key="/Default/UserDictionary/Words/=extexp/@EntryIndexedValue">True</s:Boolean>
34
<s:Boolean x:Key="/Default/UserDictionary/Words/=mundo/@EntryIndexedValue">True</s:Boolean>
45
<s:Boolean x:Key="/Default/UserDictionary/Words/=nearform/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

samples/BasicSlowDownExample/BasicSlowDownExample.csproj

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
<TargetFramework>net9.0</TargetFramework>
55
<Nullable>enable</Nullable>
66
<ImplicitUsings>enable</ImplicitUsings>
7+
<Authors>Ross Nelson</Authors>
8+
<Company>Nearform Ltd.</Company>
9+
<Copyright>Copyright (C) 2024 Nearform Ltd.</Copyright>
710
</PropertyGroup>
811

912
<ItemGroup>

samples/BasicSlowDownExample/Program.cs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,6 @@
22

33
var builder = WebApplication.CreateBuilder(args);
44

5-
#pragma warning disable EXTEXP0018
6-
// Add HybridCache.
7-
builder.Services.AddHybridCache();
8-
#pragma warning restore EXTEXP0018
9-
105
// Add services to the container.
116
builder.Services.AddRazorPages();
127

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>net9.0</TargetFramework>
5+
<ImplicitUsings>enable</ImplicitUsings>
6+
<Nullable>enable</Nullable>
7+
<Authors>Ross Nelson</Authors>
8+
<Company>Nearform Ltd.</Company>
9+
<Copyright>Copyright (C) 2024 Nearform Ltd.</Copyright>
10+
</PropertyGroup>
11+
12+
<ItemGroup>
13+
<ProjectReference Include="..\..\..\src\SlowDown\Nearform.AspNetCore.SlowDown.csproj" />
14+
<ProjectReference Include="..\DistributedCacheSlowDownExample.ServiceDefaults\DistributedCacheSlowDownExample.ServiceDefaults.csproj" />
15+
</ItemGroup>
16+
17+
<ItemGroup>
18+
<PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="9.0.0" />
19+
</ItemGroup>
20+
21+
</Project>
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
using System.Diagnostics.CodeAnalysis;
2+
using Nearform.AspNetCore.SlowDown;
3+
// ReSharper disable HeapView.ObjectAllocation
4+
// ReSharper disable HeapView.ObjectAllocation.Evident
5+
// ReSharper disable HeapView.DelegateAllocation
6+
// ReSharper disable HeapView.ClosureAllocation
7+
8+
var builder = WebApplication.CreateBuilder(args);
9+
10+
// Add service defaults & Aspire components.
11+
builder.AddServiceDefaults();
12+
13+
// Use the Aspire Redis connection
14+
builder.AddRedisClient(connectionName: "cache");
15+
builder.AddRedisDistributedCache(connectionName: "cache");
16+
17+
// Add services to the container.
18+
builder.Services.AddProblemDetails();
19+
20+
var app = builder.Build();
21+
22+
app.UseSlowDown();
23+
24+
// Configure the HTTP request pipeline.
25+
app.UseExceptionHandler();
26+
27+
var summaries = new[]
28+
{
29+
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
30+
};
31+
32+
app.MapGet("/weatherforecast", () =>
33+
{
34+
var forecast = Enumerable.Range(1, 5).Select( index =>
35+
new WeatherForecast
36+
(
37+
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
38+
Random.Shared.Next(-20, 55),
39+
summaries[Random.Shared.Next(summaries.Length)]
40+
))
41+
.ToArray();
42+
return forecast;
43+
});
44+
45+
app.MapDefaultEndpoints();
46+
47+
app.Run();
48+
49+
[SuppressMessage("ReSharper", "NotAccessedPositionalProperty.Global")]
50+
[SuppressMessage("ReSharper", "UnusedMember.Global")]
51+
internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
52+
{
53+
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
54+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
"$schema": "https://json.schemastore.org/launchsettings.json",
3+
"profiles": {
4+
"http": {
5+
"commandName": "Project",
6+
"dotnetRunMessages": true,
7+
"launchBrowser": true,
8+
"launchUrl": "weatherforecast",
9+
"applicationUrl": "http://localhost:5556",
10+
"environmentVariables": {
11+
"ASPNETCORE_ENVIRONMENT": "Development"
12+
}
13+
},
14+
"https": {
15+
"commandName": "Project",
16+
"dotnetRunMessages": true,
17+
"launchBrowser": true,
18+
"launchUrl": "weatherforecast",
19+
"applicationUrl": "https://localhost:7345;http://localhost:5556",
20+
"environmentVariables": {
21+
"ASPNETCORE_ENVIRONMENT": "Development"
22+
}
23+
}
24+
}
25+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning"
6+
}
7+
}
8+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning"
6+
}
7+
},
8+
"AllowedHosts": "*",
9+
"SlowDown": {
10+
"Delay": 5000,
11+
"DelayAfter": 50,
12+
"MaxDelay": 30000,
13+
"TimeWindow": 600000,
14+
"CacheTimeout": 2147483646
15+
}
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>net9.0</TargetFramework>
5+
<Nullable>enable</Nullable>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Authors>Ross Nelson</Authors>
8+
<Company>Nearform Ltd.</Company>
9+
<Copyright>Copyright (C) 2024 Nearform Ltd.</Copyright>
10+
</PropertyGroup>
11+
12+
<ItemGroup>
13+
<ProjectReference Include="..\..\..\src\SlowDown\Nearform.AspNetCore.SlowDown.csproj" />
14+
<ProjectReference Include="..\DistributedCacheSlowDownExample.ServiceDefaults\DistributedCacheSlowDownExample.ServiceDefaults.csproj" />
15+
</ItemGroup>
16+
17+
<ItemGroup>
18+
<PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="9.0.0" />
19+
</ItemGroup>
20+
21+
</Project>

0 commit comments

Comments
 (0)