diff --git a/.github/renovate.json b/.github/renovate.json new file mode 100644 index 0000000..370db06 --- /dev/null +++ b/.github/renovate.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "automerge": true, + "prHourlyLimit": 0, + "autoApprove": true +} diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml new file mode 100644 index 0000000..f190552 --- /dev/null +++ b/.github/workflows/build-and-test.yml @@ -0,0 +1,51 @@ +name: build-and-test +on: + # Testing - run for any PRs. + pull_request: + branches: + - main + +env: + "PipelineEnvironment": true + +jobs: + build-and-test: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Setup .NET 8.0 + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + + - name: Install dependencies with retry + run: | + retries=5 + base_wait_time=15 + exponent=2 + + for i in $(seq 1 $retries); do + if dotnet restore; then + break + fi + + if [ $i -lt $retries ]; then + wait_time=$(awk "BEGIN {print int($base_wait_time * ($exponent ^ ($i - 1)))}") + echo "dotnet restore failed, retrying in $wait_time seconds..." + sleep $wait_time + else + echo "dotnet restore failed after $retries retries." + exit 1 + fi + done + + - name: Build + run: dotnet build --configuration Release --no-restore + + - name: Test + run: dotnet test test/Soenneker.Utils.RateLimiting.Executor.Tests/Soenneker.Utils.RateLimiting.Executor.Tests.csproj --no-restore --verbosity normal + + - name: Pack + run: dotnet pack --no-build --configuration Release --output . diff --git a/.github/workflows/publish-package.yml b/.github/workflows/publish-package.yml new file mode 100644 index 0000000..3a53638 --- /dev/null +++ b/.github/workflows/publish-package.yml @@ -0,0 +1,80 @@ +name: publish-package +on: + push: + branches: + - main + + tags: + - v* + +env: + "PipelineEnvironment": true + +jobs: + publish-package: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Setting up build version + run: | + version=$(($GITHUB_RUN_NUMBER)) + echo "BUILD_VERSION=2.1.$version" >> ${GITHUB_ENV} + + - name: Setup .NET Core 8.0 + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + + - name: Install dependencies with retry + run: | + retries=5 + base_wait_time=15 + exponent=2 + + for i in $(seq 1 $retries); do + if dotnet restore; then + break + fi + + if [ $i -lt $retries ]; then + wait_time=$(awk "BEGIN {print int($base_wait_time * ($exponent ^ ($i - 1)))}") + echo "dotnet restore failed, retrying in $wait_time seconds..." + sleep $wait_time + else + echo "dotnet restore failed after $retries retries." + exit 1 + fi + done + + - name: Build + run: dotnet build --configuration Release --no-restore + + - name: Test + run: dotnet test test/Soenneker.Utils.RateLimiting.Executor.Tests/Soenneker.Utils.RateLimiting.Executor.Tests.csproj --no-restore --verbosity normal + + - name: Pack + run: dotnet pack --no-build --configuration Release --output . + + - name: Publish to NuGet with retry + run: | + nupkg_files=$(find . -name "*.nupkg") + retries=5 + base_wait_time=20 + exponent=3.5 + + for i in $(seq 1 $retries); do + if dotnet nuget push $nupkg_files --source 'https://api.nuget.org/v3/index.json' --api-key ${{secrets.NUGET_TOKEN}} --skip-duplicate; then + break + fi + + if [ $i -lt $retries ]; then + wait_time=$(awk "BEGIN {print int($base_wait_time * ($exponent ^ ($i - 1)))}") + echo "NuGet publish failed, retrying in $wait_time seconds..." + sleep $wait_time + else + echo "NuGet publish failed after $retries retries." + exit 1 + fi + done diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1ee5385 --- /dev/null +++ b/.gitignore @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..e92a603 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,44 @@ +# Contributing to Soenneker.Utils.RateLimiting.Executor + +We're excited that you're interested in contributing! + +## How to Contribute + +1. **Create an Issue** + - If you have a new feature idea, a bug report, or any other improvement suggestion, start by creating an issue on the [Issues](https://github.com/soenneker/soenneker.utils.ratelimiting.executor/issues) page. + - Clearly describe the problem or enhancement you're proposing and provide as much detail as possible. + +1. **Fork the Repository** + - If you want to work on a feature or bug fix, fork the repository's `main` branch to your GitHub account. + +1. **Create a Branch** + - Create a new branch for your contribution. Use a descriptive name that reflects the purpose of your changes. + +1. **Make Changes** + - If you've changed APIs, update the documentation. + - If you've added code that should be tested, add tests. + - Be sure to follow the coding conventions and guidelines of the project. + +1. **Test Your Changes** + - Test your changes thoroughly to ensure that they work as expected. + +1. **Commit Changes** + - Commit your changes with a clear and concise commit message. + +1. **Push Changes** + - Push your changes to your forked repository on GitHub. + +1. **Create a Pull Request** + - Go to the [Pull Requests](https://github.com/soenneker/soenneker.utils.ratelimiting.executor/pulls) page of the original repository. + - Click on "New Pull Request." + - Select your forked repository and the branch with your changes. + - Provide a clear title and description. Include the link of the original issue. + +1. **Code Review** + - Your pull request will be reviewed by the maintainers. + - Be responsive to any feedback and make necessary changes. + - Once your pull request is approved, it will be merged into the main branch. + +## Sponsor us + +If you don't have the time or expertise to contribute code, you can still support us by [sponsoring](https://github.com/sponsors/soenneker). diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7d4bbc2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jake Soenneker + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index b4b7c4c..4eb456d 100644 --- a/README.md +++ b/README.md @@ -1 +1,52 @@ -Standby... \ No newline at end of file +[![](https://img.shields.io/nuget/v/soenneker.utils.ratelimiting.executor.svg?style=for-the-badge)](https://www.nuget.org/packages/soenneker.utils.ratelimiting.executor/) +[![](https://img.shields.io/github/actions/workflow/status/soenneker/soenneker.utils.ratelimiting.executor/publish-package.yml?style=for-the-badge)](https://github.com/soenneker/soenneker.utils.ratelimiting.executor/actions/workflows/publish-package.yml) +[![](https://img.shields.io/nuget/dt/soenneker.utils.ratelimiting.executor.svg?style=for-the-badge)](https://www.nuget.org/packages/soenneker.utils.ratelimiting.executor/) + +# ![](https://user-images.githubusercontent.com/4441470/224455560-91ed3ee7-f510-4041-a8d2-3fc093025112.png) Soenneker.Utils.RateLimiting.Executor +### A thread-safe utility designed to manage the rate at which tasks are executed, ensuring that they are not run more frequently than a specified interval. + +This can be particularly useful when interacting with rate-limited APIs or for throttling the execution of resource-intensive tasks. + +## Installation + +``` +dotnet add package Soenneker.Utils.RateLimiting.Executor +``` + +## Example: Executing a Loop of Tasks with Rate Limiting + +Below is an example demonstrating how to use the RateLimitingExecutor to execute a series of tasks while maintaining a rate limit. + +```csharp +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Soenneker.Utils.RateLimiting.Executor; + +public class Program +{ + public static async Task Main(string[] args) + { + var rateLimitingExecutor = new RateLimitingExecutor(TimeSpan.FromSeconds(2)); + + for (int i = 0; i < 5; i++) + { + await rateLimitingExecutor.Execute(async ct => + { + Console.WriteLine($"Executing Task {i + 1} at {DateTime.Now:HH:mm:ss}"); + await Task.Delay(100); // Simulate some work + }); + } + } +} +``` + +### Console Output + +```csharp +Executing Task 1 at 14:00:00 +Executing Task 2 at 14:00:02 +Executing Task 3 at 14:00:04 +Executing Task 4 at 14:00:06 +Executing Task 5 at 14:00:08 +``` \ No newline at end of file diff --git a/Soenneker.Utils.RateLimiting.Executor.sln b/Soenneker.Utils.RateLimiting.Executor.sln new file mode 100644 index 0000000..200acca --- /dev/null +++ b/Soenneker.Utils.RateLimiting.Executor.sln @@ -0,0 +1,51 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.33209.295 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Soenneker.Utils.RateLimiting.Executor", "src\Soenneker.Utils.RateLimiting.Executor.csproj", "{41850636-33B4-4228-AE59-A2113F66B9FA}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{4E42254D-039C-40ED-B3F4-8C1A94A366D1}" + ProjectSection(SolutionItems) = preProject + .github\renovate.json = .github\renovate.json + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{D786EC1A-4F59-412F-8624-83E6E3525B0C}" + ProjectSection(SolutionItems) = preProject + .github\workflows\build-and-test.yml = .github\workflows\build-and-test.yml + .github\workflows\publish-package.yml = .github\workflows\publish-package.yml + EndProjectSection +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Soenneker.Utils.RateLimiting.Executor.Tests", "test\Soenneker.Utils.RateLimiting.Executor.Tests\Soenneker.Utils.RateLimiting.Executor.Tests.csproj", "{6456E465-9523-4612-9115-9D9B585B42E8}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{81EF41E6-82F4-404F-9FCE-049B4CBCE196}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{47FB874E-6667-4D2D-AB56-2BE057BDE46F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {41850636-33B4-4228-AE59-A2113F66B9FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {41850636-33B4-4228-AE59-A2113F66B9FA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {41850636-33B4-4228-AE59-A2113F66B9FA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {41850636-33B4-4228-AE59-A2113F66B9FA}.Release|Any CPU.Build.0 = Release|Any CPU + {6456E465-9523-4612-9115-9D9B585B42E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6456E465-9523-4612-9115-9D9B585B42E8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6456E465-9523-4612-9115-9D9B585B42E8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6456E465-9523-4612-9115-9D9B585B42E8}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {41850636-33B4-4228-AE59-A2113F66B9FA} = {81EF41E6-82F4-404F-9FCE-049B4CBCE196} + {D786EC1A-4F59-412F-8624-83E6E3525B0C} = {4E42254D-039C-40ED-B3F4-8C1A94A366D1} + {6456E465-9523-4612-9115-9D9B585B42E8} = {47FB874E-6667-4D2D-AB56-2BE057BDE46F} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {B849EC5C-B7B3-4C90-9B66-CBC15CCB776A} + EndGlobalSection +EndGlobal diff --git a/Soenneker.Utils.RateLimiting.Executor.sln.DotSettings b/Soenneker.Utils.RateLimiting.Executor.sln.DotSettings new file mode 100644 index 0000000..501e5e0 --- /dev/null +++ b/Soenneker.Utils.RateLimiting.Executor.sln.DotSettings @@ -0,0 +1,31 @@ + + False + 0 + 0 + NEVER + NEVER + + True + True + UseVarWhenEvident + UseVarWhenEvident + UseVarWhenEvident + ML + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static readonly fields (private)"><ElementKinds><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Private" Description="Constant fields (private)"><ElementKinds><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /></Policy> + <Policy><Descriptor Staticness="Instance" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Instance fields (not private)"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Constant fields (not private)"><ElementKinds><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Static fields (not private)"><ElementKinds><Kind Name="FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></Policy> + True + True + True + True + True + True + 9999 + True + diff --git a/icon.png b/icon.png new file mode 100644 index 0000000..1324943 Binary files /dev/null and b/icon.png differ diff --git a/src/Abstract/IRateLimitingExecutor.cs b/src/Abstract/IRateLimitingExecutor.cs new file mode 100644 index 0000000..5020cdb --- /dev/null +++ b/src/Abstract/IRateLimitingExecutor.cs @@ -0,0 +1,31 @@ +using System; +using System.Threading.Tasks; +using System.Threading; + +namespace Soenneker.Utils.RateLimiting.Executor.Abstract; + +/// +/// A thread-safe utility designed to manage the rate at which tasks are executed, ensuring that they are not run more frequently than a specified interval. +/// +public interface IRateLimitingExecutor : IDisposable, IAsyncDisposable +{ + /// + /// Executes an asynchronous task while respecting the rate limit. + /// + /// A function that takes a and returns a representing the asynchronous operation to execute. + /// A that represents the completion of the execution. + ValueTask Execute(Func valueTask); + + /// + /// Executes an asynchronous task while respecting the rate limit. + /// + /// A function that takes a and returns a representing the asynchronous operation to execute. + /// A that represents the completion of the execution. + ValueTask ExecuteTask(Func task); + + /// + /// Executes a synchronous task while respecting the rate limit. + /// + /// An action that takes a representing the operation to execute. + void Execute(Action action); +} diff --git a/src/RateLimitingExecutor.cs b/src/RateLimitingExecutor.cs new file mode 100644 index 0000000..1e2df44 --- /dev/null +++ b/src/RateLimitingExecutor.cs @@ -0,0 +1,120 @@ +using Soenneker.Utils.RateLimiting.Executor.Abstract; +using System.Threading.Tasks; +using System.Threading; +using System; +using Nito.AsyncEx; +using Soenneker.Extensions.Task; +using Soenneker.Extensions.ValueTask; + +namespace Soenneker.Utils.RateLimiting.Executor; + +/// +public class RateLimitingExecutor : IRateLimitingExecutor +{ + private readonly TimeSpan _executionInterval; + private readonly AsyncLock _asyncLock = new(); + private readonly Lazy _cancellationTokenSource = new(() => new CancellationTokenSource()); + private DateTime _lastExecutionTime = DateTime.MinValue; + + public RateLimitingExecutor(TimeSpan executionInterval) + { + _executionInterval = executionInterval; + } + + public async ValueTask Execute(Func valueTask) + { + _cancellationTokenSource.Value.Token.ThrowIfCancellationRequested(); + + using (await _asyncLock.LockAsync().ConfigureAwait(false)) + { + await WaitForNextExecutionAsync().NoSync(); + + _cancellationTokenSource.Value.Token.ThrowIfCancellationRequested(); + + await valueTask(_cancellationTokenSource.Value.Token).NoSync(); + _lastExecutionTime = DateTime.UtcNow; + } + } + + public async ValueTask ExecuteTask(Func task) + { + _cancellationTokenSource.Value.Token.ThrowIfCancellationRequested(); + + using (await _asyncLock.LockAsync().ConfigureAwait(false)) + { + await WaitForNextExecutionAsync().NoSync(); + + _cancellationTokenSource.Value.Token.ThrowIfCancellationRequested(); + + await task(_cancellationTokenSource.Value.Token).NoSync(); + _lastExecutionTime = DateTime.UtcNow; + } + } + + public void Execute(Action action) + { + _cancellationTokenSource.Value.Token.ThrowIfCancellationRequested(); + + using (_asyncLock.Lock()) + { + WaitForNextExecution(); + + _cancellationTokenSource.Value.Token.ThrowIfCancellationRequested(); + + action(_cancellationTokenSource.Value.Token); + _lastExecutionTime = DateTime.UtcNow; + } + } + + private async Task WaitForNextExecutionAsync() + { + TimeSpan timeSinceLastExecution = DateTime.UtcNow - _lastExecutionTime; + + if (timeSinceLastExecution < _executionInterval) + { + TimeSpan delay = _executionInterval - timeSinceLastExecution; + await Task.Delay(delay, _cancellationTokenSource.Value.Token).NoSync(); + } + } + + private void WaitForNextExecution() + { + TimeSpan timeSinceLastExecution = DateTime.UtcNow - _lastExecutionTime; + + if (timeSinceLastExecution < _executionInterval) + { + TimeSpan delay = _executionInterval - timeSinceLastExecution; + Task.Delay(delay, _cancellationTokenSource.Value.Token).Wait(); + } + } + + public async ValueTask DisposeAsync() + { + GC.SuppressFinalize(this); + + if (_cancellationTokenSource.IsValueCreated && !_cancellationTokenSource.Value.IsCancellationRequested) + { + await _cancellationTokenSource.Value.CancelAsync().NoSync(); + } + + if (_cancellationTokenSource.IsValueCreated) + { + _cancellationTokenSource.Value.Dispose(); + } + } + + public void Dispose() + { + GC.SuppressFinalize(this); + + if (_cancellationTokenSource.IsValueCreated && !_cancellationTokenSource.Value.IsCancellationRequested) + { + _cancellationTokenSource.Value.Cancel(); + } + + if (_cancellationTokenSource.IsValueCreated) + { + _cancellationTokenSource.Value.Dispose(); + } + } +} diff --git a/src/Soenneker.Utils.RateLimiting.Executor.csproj b/src/Soenneker.Utils.RateLimiting.Executor.csproj new file mode 100644 index 0000000..a37e4e8 --- /dev/null +++ b/src/Soenneker.Utils.RateLimiting.Executor.csproj @@ -0,0 +1,50 @@ + + + + net8.0 + enable + AnyCPU + $(NoWarn);1591 + + + + A thread-safe utility designed to manage the rate at which tasks are executed, ensuring that they are not run more frequently than a specified interval. + 2.1.0 + $(BUILD_VERSION) + Soenneker.Utils.RateLimiting.Executor + Soenneker.Utils.RateLimiting.Executor + utils ratelimiting executor rate limiting api limit ratelimitingexecutor util csharp dotnet c# .net + Copyright © 2024 Jake Soenneker + Jake Soenneker + https://soenneker.com + true + true + true + snupkg + true + MIT + https://github.com/soenneker/soenneker.utils.ratelimiting.executor + https://github.com/soenneker/soenneker.utils.ratelimiting.executor + git + main + false + true + latest + README.md + icon.png + + + + + + + + + + + + + + + + diff --git a/test/Soenneker.Utils.RateLimiting.Executor.Tests/Collection.cs b/test/Soenneker.Utils.RateLimiting.Executor.Tests/Collection.cs new file mode 100644 index 0000000..e1060f4 --- /dev/null +++ b/test/Soenneker.Utils.RateLimiting.Executor.Tests/Collection.cs @@ -0,0 +1,13 @@ +using Xunit; + +namespace Soenneker.Utils.RateLimiting.Executor.Tests; + +/// +/// This class has no code, and is never created. Its purpose is simply +/// to be the place to apply [CollectionDefinition] and all the +/// ICollectionFixture interfaces. +/// +[CollectionDefinition("Collection")] +public class Collection : ICollectionFixture +{ +} diff --git a/test/Soenneker.Utils.RateLimiting.Executor.Tests/Fixture.cs b/test/Soenneker.Utils.RateLimiting.Executor.Tests/Fixture.cs new file mode 100644 index 0000000..0219505 --- /dev/null +++ b/test/Soenneker.Utils.RateLimiting.Executor.Tests/Fixture.cs @@ -0,0 +1,28 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Serilog; +using Soenneker.Fixtures.Unit; +using Soenneker.Utils.Test; + +namespace Soenneker.Utils.RateLimiting.Executor.Tests; + +public class Fixture : UnitFixture +{ + public override System.Threading.Tasks.Task InitializeAsync() + { + SetupIoC(Services); + + return base.InitializeAsync(); + } + + private static void SetupIoC(IServiceCollection services) + { + services.AddLogging(builder => + { + builder.AddSerilog(dispose: true); + }); + + IConfiguration config = TestUtil.BuildConfig(); + services.AddSingleton(config); + } +} diff --git a/test/Soenneker.Utils.RateLimiting.Executor.Tests/RateLimitingExecutorTests.cs b/test/Soenneker.Utils.RateLimiting.Executor.Tests/RateLimitingExecutorTests.cs new file mode 100644 index 0000000..25a5016 --- /dev/null +++ b/test/Soenneker.Utils.RateLimiting.Executor.Tests/RateLimitingExecutorTests.cs @@ -0,0 +1,115 @@ +using FluentAssertions; +using Soenneker.Tests.FixturedUnit; +using System.Threading.Tasks; +using System; +using Xunit; +using Xunit.Abstractions; + +namespace Soenneker.Utils.RateLimiting.Executor.Tests; + +[Collection("Collection")] +public class RateLimitingExecutorTests : FixturedUnitTest +{ + public RateLimitingExecutorTests(Fixture fixture, ITestOutputHelper output) : base(fixture, output) + { + } + + [Fact] + public async Task Execute_ShouldRunTaskWithoutDelay_WhenFirstExecution() + { + TimeSpan executionInterval = TimeSpan.FromMilliseconds(500); + var executor = new RateLimitingExecutor(executionInterval); + var taskExecuted = false; + + await executor.Execute(async token => + { + taskExecuted = true; + await Task.CompletedTask; + }); + + taskExecuted.Should().BeTrue(); + } + + [Fact] + public async Task Execute_ShouldRespectExecutionInterval_BetweenTasks() + { + TimeSpan executionInterval = TimeSpan.FromMilliseconds(500); + var executor = new RateLimitingExecutor(executionInterval); + var taskExecuted = false; + + await executor.Execute(async token => + { + taskExecuted = true; + await Task.CompletedTask; + }); + + taskExecuted.Should().BeTrue(); + + taskExecuted = false; + + DateTime startTime = DateTime.UtcNow; + await executor.Execute(async token => + { + taskExecuted = true; + await Task.CompletedTask; + }); + DateTime endTime = DateTime.UtcNow; + + taskExecuted.Should().BeTrue(); + + TimeSpan tolerance = TimeSpan.FromMilliseconds(50); + (endTime - startTime).Should().BeGreaterOrEqualTo(executionInterval - tolerance); + } + + [Fact] + public async Task Execute_ShouldThrowOperationCanceledException_WhenCancelled() + { + TimeSpan executionInterval = TimeSpan.FromMilliseconds(500); + var executor = new RateLimitingExecutor(executionInterval); + + await executor.Execute(async token => + { + await Task.Delay(100, token); + }); + + await executor.DisposeAsync(); + + await FluentActions.Awaiting(async () => + await executor.Execute(async token => + { + await Task.CompletedTask; + })).Should().ThrowAsync(); + } + + [Fact] + public void Execute_Action_ShouldRunWithoutDelay_WhenFirstExecution() + { + TimeSpan executionInterval = TimeSpan.FromMilliseconds(500); + var executor = new RateLimitingExecutor(executionInterval); + var actionExecuted = false; + + executor.Execute(token => + { + actionExecuted = true; + }); + + actionExecuted.Should().BeTrue(); + } + + [Fact] + public async Task DisposeAsync_ShouldCancelPendingTasks() + { + TimeSpan executionInterval = TimeSpan.FromMilliseconds(500); + var executor = new RateLimitingExecutor(executionInterval); + + ValueTask executionTask = executor.Execute(async token => + { + await Task.Delay(1000, token); + }); + + await executor.DisposeAsync(); + + await FluentActions.Awaiting(async () => await executionTask) + .Should().ThrowAsync(); + } +} diff --git a/test/Soenneker.Utils.RateLimiting.Executor.Tests/Soenneker.Utils.RateLimiting.Executor.Tests.csproj b/test/Soenneker.Utils.RateLimiting.Executor.Tests/Soenneker.Utils.RateLimiting.Executor.Tests.csproj new file mode 100644 index 0000000..1301164 --- /dev/null +++ b/test/Soenneker.Utils.RateLimiting.Executor.Tests/Soenneker.Utils.RateLimiting.Executor.Tests.csproj @@ -0,0 +1,37 @@ + + + + net8.0 + enable + false + + + + + + + + + PreserveNewest + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + diff --git a/test/Soenneker.Utils.RateLimiting.Executor.Tests/appsettings.json b/test/Soenneker.Utils.RateLimiting.Executor.Tests/appsettings.json new file mode 100644 index 0000000..2c63c08 --- /dev/null +++ b/test/Soenneker.Utils.RateLimiting.Executor.Tests/appsettings.json @@ -0,0 +1,2 @@ +{ +}