Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add global rate limiting sample #619

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Giraffe.sln
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "ResponseCachingApp", "sampl
EndProject
Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "NewtonsoftJson", "samples\NewtonsoftJson\NewtonsoftJson.fsproj", "{A08230F1-DA24-4059-A7F9-4743B36DD3E9}"
EndProject
Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "RateLimiting", "samples\RateLimiting\RateLimiting.fsproj", "{D5916FAA-2EBB-4FDD-B474-9DE37B60D641}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -104,6 +106,18 @@ Global
{A08230F1-DA24-4059-A7F9-4743B36DD3E9}.Release|x64.Build.0 = Release|Any CPU
{A08230F1-DA24-4059-A7F9-4743B36DD3E9}.Release|x86.ActiveCfg = Release|Any CPU
{A08230F1-DA24-4059-A7F9-4743B36DD3E9}.Release|x86.Build.0 = Release|Any CPU
{D5916FAA-2EBB-4FDD-B474-9DE37B60D641}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D5916FAA-2EBB-4FDD-B474-9DE37B60D641}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D5916FAA-2EBB-4FDD-B474-9DE37B60D641}.Debug|x64.ActiveCfg = Debug|Any CPU
{D5916FAA-2EBB-4FDD-B474-9DE37B60D641}.Debug|x64.Build.0 = Debug|Any CPU
{D5916FAA-2EBB-4FDD-B474-9DE37B60D641}.Debug|x86.ActiveCfg = Debug|Any CPU
{D5916FAA-2EBB-4FDD-B474-9DE37B60D641}.Debug|x86.Build.0 = Debug|Any CPU
{D5916FAA-2EBB-4FDD-B474-9DE37B60D641}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D5916FAA-2EBB-4FDD-B474-9DE37B60D641}.Release|Any CPU.Build.0 = Release|Any CPU
{D5916FAA-2EBB-4FDD-B474-9DE37B60D641}.Release|x64.ActiveCfg = Release|Any CPU
{D5916FAA-2EBB-4FDD-B474-9DE37B60D641}.Release|x64.Build.0 = Release|Any CPU
{D5916FAA-2EBB-4FDD-B474-9DE37B60D641}.Release|x86.ActiveCfg = Release|Any CPU
{D5916FAA-2EBB-4FDD-B474-9DE37B60D641}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -118,5 +132,6 @@ Global
{0E15F922-7A44-4116-9DAB-FAEB94392FEC} = {B9B26DDC-608C-42FE-9AB9-6CF0EE4920CD}
{FA102AC4-4608-42F9-86C1-1472B416A76E} = {9E6451FB-26E0-4AE4-A469-847F9602E999}
{A08230F1-DA24-4059-A7F9-4743B36DD3E9} = {9E6451FB-26E0-4AE4-A469-847F9602E999}
{D5916FAA-2EBB-4FDD-B474-9DE37B60D641} = {9E6451FB-26E0-4AE4-A469-847F9602E999}
EndGlobalSection
EndGlobal
56 changes: 56 additions & 0 deletions samples/RateLimiting/Program.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
open System
open Microsoft.AspNetCore.Http
open Microsoft.AspNetCore.Builder
open Microsoft.Extensions.DependencyInjection
open Microsoft.Extensions.Hosting
open Giraffe
open Giraffe.EndpointRouting
open Microsoft.AspNetCore.RateLimiting
open System.Threading.RateLimiting

let endpoints: list<Endpoint> = [ GET [ route "/" (text "Hello World") ] ]

let notFoundHandler = text "Not Found" |> RequestErrors.notFound

let configureApp (appBuilder: IApplicationBuilder) =
appBuilder
.UseRouting()
.UseRateLimiter()
.UseGiraffe(endpoints)
.UseGiraffe(notFoundHandler)

let configureServices (services: IServiceCollection) =
// From https://blog.maartenballiauw.be/post/2022/09/26/aspnet-core-rate-limiting-middleware.html
let configureRateLimiter (options: RateLimiterOptions) =
options.RejectionStatusCode <- StatusCodes.Status429TooManyRequests

options.GlobalLimiter <-
PartitionedRateLimiter.Create<HttpContext, string>(fun httpContext ->
RateLimitPartition.GetFixedWindowLimiter(
partitionKey = httpContext.Request.Headers.Host.ToString(),
factory =
(fun _partition ->
new FixedWindowRateLimiterOptions(
AutoReplenishment = true,
PermitLimit = 10,
QueueLimit = 0,
Window = TimeSpan.FromSeconds(1)
)
)
)
)

services.AddRateLimiter(configureRateLimiter).AddRouting().AddGiraffe()
|> ignore

[<EntryPoint>]
let main args =
let builder = WebApplication.CreateBuilder(args)
configureServices builder.Services

let app = builder.Build()

configureApp app
app.Run()

0
17 changes: 17 additions & 0 deletions samples/RateLimiting/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Rate Limiting Sample

This sample project shows how one can configure ASP.NET's built-in [rate limiting middleware](https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit?view=aspnetcore-8.0).

Notice that this rate limiting configuration is very simple, and for real life scenarios you'll need to figure out what is the best strategy to use for your server.

To make it easier to test this project locally, and see the rate limiting middleware working, you can use the `rate-limiting-test.fsx` script:

```bash
# start the server
dotnet run .
# if you want to keep using the same terminal, just start this process in the background

# then, you can use this script to test the server, and confirm that the rate-limiting
# middleware is really working
dotnet fsi rate-limiting-test.fsx
```
16 changes: 16 additions & 0 deletions samples/RateLimiting/RateLimiting.fsproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Compile Include="Program.fs" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="../../src/Giraffe/Giraffe.fsproj" />
</ItemGroup>

</Project>
20 changes: 20 additions & 0 deletions samples/RateLimiting/rate-limiting-test.fsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
open System
open System.IO
open System.Net.Http

let request = new HttpClient(BaseAddress = new Uri("http://localhost:5000"))

#time

seq { 1..100 }
|> Seq.map (fun _ -> request.GetAsync "/" |> Async.AwaitTask)
|> Async.Parallel
|> Async.RunSynchronously
|> Seq.iteri (fun i response ->
printfn "\nResponse %i status code: %A" i response.StatusCode

let responseReader = new StreamReader(response.Content.ReadAsStream())
printfn "Response %i content: %A" i (responseReader.ReadToEnd())
)

#time
Loading