Skip to content

Commit

Permalink
add global rate limiting sample
Browse files Browse the repository at this point in the history
  • Loading branch information
64J0 committed Oct 24, 2024
1 parent 7d085c5 commit d3d34d7
Show file tree
Hide file tree
Showing 5 changed files with 124 additions and 0 deletions.
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}") = "GlobalRateLimiting", "samples\GlobalRateLimiting\GlobalRateLimiting.fsproj", "{C5E71E00-4DD0-4ED8-B781-7DB63B7565E4}"
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
{C5E71E00-4DD0-4ED8-B781-7DB63B7565E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C5E71E00-4DD0-4ED8-B781-7DB63B7565E4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C5E71E00-4DD0-4ED8-B781-7DB63B7565E4}.Debug|x64.ActiveCfg = Debug|Any CPU
{C5E71E00-4DD0-4ED8-B781-7DB63B7565E4}.Debug|x64.Build.0 = Debug|Any CPU
{C5E71E00-4DD0-4ED8-B781-7DB63B7565E4}.Debug|x86.ActiveCfg = Debug|Any CPU
{C5E71E00-4DD0-4ED8-B781-7DB63B7565E4}.Debug|x86.Build.0 = Debug|Any CPU
{C5E71E00-4DD0-4ED8-B781-7DB63B7565E4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C5E71E00-4DD0-4ED8-B781-7DB63B7565E4}.Release|Any CPU.Build.0 = Release|Any CPU
{C5E71E00-4DD0-4ED8-B781-7DB63B7565E4}.Release|x64.ActiveCfg = Release|Any CPU
{C5E71E00-4DD0-4ED8-B781-7DB63B7565E4}.Release|x64.Build.0 = Release|Any CPU
{C5E71E00-4DD0-4ED8-B781-7DB63B7565E4}.Release|x86.ActiveCfg = Release|Any CPU
{C5E71E00-4DD0-4ED8-B781-7DB63B7565E4}.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}
{C5E71E00-4DD0-4ED8-B781-7DB63B7565E4} = {9E6451FB-26E0-4AE4-A469-847F9602E999}
EndGlobalSection
EndGlobal
16 changes: 16 additions & 0 deletions samples/GlobalRateLimiting/GlobalRateLimiting.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>
56 changes: 56 additions & 0 deletions samples/GlobalRateLimiting/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/GlobalRateLimiting/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Global 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 `global-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 global-rate-limiting-test.fsx
```
20 changes: 20 additions & 0 deletions samples/GlobalRateLimiting/global-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

0 comments on commit d3d34d7

Please sign in to comment.