little rate limiting for twitter auth

This commit is contained in:
Vincent Cloutier 2023-03-27 19:48:35 -04:00
parent fe1dce6300
commit f554269cba
2 changed files with 30 additions and 16 deletions

View file

@ -7,6 +7,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" />
<PackageReference Include="System.Threading.RateLimiting" Version="7.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View file

@ -8,6 +8,7 @@ using Microsoft.Extensions.Logging;
using System.Net.Http; using System.Net.Http;
using System.Net; using System.Net;
using System.Text.Json; using System.Text.Json;
using System.Threading.RateLimiting;
namespace BirdsiteLive.Twitter.Tools namespace BirdsiteLive.Twitter.Tools
{ {
@ -27,6 +28,8 @@ namespace BirdsiteLive.Twitter.Tools
private List<HttpClient> _twitterClients = new List<HttpClient>(); private List<HttpClient> _twitterClients = new List<HttpClient>();
private List<String> _tokens = new List<string>(); private List<String> _tokens = new List<string>();
static Random rnd = new Random(); static Random rnd = new Random();
private RateLimiter _rateLimiter;
static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
private const int _targetClients = 3; private const int _targetClients = 3;
public String BearerToken { public String BearerToken {
get { return "AAAAAAAAAAAAAAAAAAAAAPYXBAAAAAAACLXUNDekMxqa8h%2F40K4moUkGsoc%3DTYfbDKbT3jJPCEVnMYqilB28NHfOPqkca3qaAxGfsyKCs0wRbw"; } get { return "AAAAAAAAAAAAAAAAAAAAAPYXBAAAAAAACLXUNDekMxqa8h%2F40K4moUkGsoc%3DTYfbDKbT3jJPCEVnMYqilB28NHfOPqkca3qaAxGfsyKCs0wRbw"; }
@ -68,6 +71,10 @@ namespace BirdsiteLive.Twitter.Tools
} }
private async Task RefreshCred() private async Task RefreshCred()
{
await semaphoreSlim.WaitAsync();
try
{ {
(string bearer, string guest) = await GetCred(); (string bearer, string guest) = await GetCred();
@ -86,6 +93,12 @@ namespace BirdsiteLive.Twitter.Tools
_twitterClients.RemoveAt(0); _twitterClients.RemoveAt(0);
_tokens.RemoveAt(0); _tokens.RemoveAt(0);
} }
}
finally
{
semaphoreSlim.Release();
}
} }
private async Task<(string, string)> GetCred() private async Task<(string, string)> GetCred()