-
Notifications
You must be signed in to change notification settings - Fork 165
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: DismissedLight <[email protected]>
- Loading branch information
1 parent
ed5821c
commit 4c2f2a0
Showing
5 changed files
with
58 additions
and
75 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
25 changes: 25 additions & 0 deletions
25
src/Starward/Services/Download/TokenBucketRateLimiterExtension.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
using System; | ||
using System.Threading; | ||
using System.Threading.RateLimiting; | ||
using System.Runtime.CompilerServices; | ||
|
||
namespace Starward.Services.Download; | ||
|
||
internal static class TokenBucketRateLimiterExtension | ||
{ | ||
// IMPORTANT: acquired can be none 0 values if false is returned | ||
public static bool TryAcquire(this TokenBucketRateLimiter rateLimiter, int permits, out int acquired, out TimeSpan retryAfter) | ||
{ | ||
lock (PrivateGetLock(rateLimiter)) | ||
acquired = Math.Min(permits, (int)Volatile.Read(ref PrivateGetTokenCount(rateLimiter))); | ||
return rateLimiter.AttemptAcquire(acquired).TryGetMetadata(MetadataName.RetryAfter, out retryAfter); | ||
} | ||
|
||
// private object Lock → _queue | ||
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "get_Lock")] | ||
private static extern object PrivateGetLock(TokenBucketRateLimiter rateLimiter); | ||
|
||
// private double _tokenCount; | ||
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_tokenCount")] | ||
private static extern ref double PrivateGetTokenCount(TokenBucketRateLimiter rateLimiter); | ||
} |