-
Notifications
You must be signed in to change notification settings - Fork 127
Add SecondaryRateLimitHandler to int tests #1423
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
Closed
Closed
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
671ab1c
Add SecondaryRateLimitHandler to int tests
begonaguereca 4cc38b2
Fix by injecting HttpClient into AdoToGithub and add SecondaryRateLim…
begonaguereca b86dad8
Add retry mechanism
begonaguereca c788e4a
Fix formatting
begonaguereca 143c7e0
fix formatting issues
begonaguereca 9adaa79
Formatting change
begonaguereca dd05584
add more backing off mechanisms
begonaguereca 136dd3c
Fix linter errors'
begonaguereca e2d7060
formatting
begonaguereca File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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,156 @@ | ||
| // src/Octoshift/Services/SecondaryRateLimitHandler.cs | ||
| using System; | ||
| using System.Linq; | ||
| using System.Net; | ||
| using System.Net.Http; | ||
| using System.Security.Cryptography; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace OctoshiftCLI.Services | ||
| { | ||
| /// <summary> | ||
| /// Handles GitHub secondary rate-limit / abuse-detection 403s by | ||
| /// respecting Retry-After (when present) and otherwise using | ||
| /// exponential backoff with jitter. Clones the request to safely | ||
| /// resend POSTs with content. | ||
| /// </summary> | ||
| public sealed class SecondaryRateLimitHandler : DelegatingHandler | ||
| { | ||
| private readonly int _maxAttempts; | ||
| private readonly TimeSpan _initialBackoff; | ||
| private readonly TimeSpan _maxBackoff; | ||
|
|
||
| public SecondaryRateLimitHandler( | ||
| HttpMessageHandler innerHandler, | ||
| int maxAttempts = 6, | ||
| int initialBackoffSeconds = 15, | ||
| int maxBackoffSeconds = 900) | ||
| : base(innerHandler) | ||
| { | ||
| _maxAttempts = maxAttempts; | ||
| _initialBackoff = TimeSpan.FromSeconds(initialBackoffSeconds); | ||
| _maxBackoff = TimeSpan.FromSeconds(maxBackoffSeconds); | ||
| } | ||
|
|
||
| protected override async Task<HttpResponseMessage> SendAsync( | ||
| HttpRequestMessage request, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| if (request == null) | ||
| { | ||
| throw new ArgumentNullException(nameof(request)); | ||
| } | ||
|
|
||
| var attempt = 0; | ||
| var delay = _initialBackoff; | ||
|
|
||
| // Buffer original content (if any) so we can safely clone the request for retries. | ||
| byte[] bufferedContent = null; | ||
| string contentType = null; | ||
|
|
||
| if (request.Content != null) | ||
| { | ||
| bufferedContent = await request.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); | ||
| contentType = request.Content.Headers.ContentType?.ToString(); | ||
| } | ||
|
|
||
| while (true) | ||
| { | ||
| cancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| using var cloned = CloneRequest(request, bufferedContent, contentType); | ||
| var response = await base.SendAsync(cloned, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| if (response.StatusCode != HttpStatusCode.Forbidden) | ||
| { | ||
| return response; | ||
| } | ||
|
|
||
| // Look for known secondary rate limit / abuse messages in body. | ||
| var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); | ||
| var looksLikeSecondary = | ||
| body.Contains("secondary rate limit", StringComparison.OrdinalIgnoreCase) || | ||
| body.Contains("abuse detection", StringComparison.OrdinalIgnoreCase) || | ||
| body.Contains("rate limit", StringComparison.OrdinalIgnoreCase); | ||
|
|
||
| if (!looksLikeSecondary) | ||
| { | ||
| return response; // Some other 403 — don't loop. | ||
| } | ||
|
|
||
| attempt++; | ||
| if (attempt >= _maxAttempts) | ||
| { | ||
| return response; // Give up; caller/policy will surface it. | ||
| } | ||
|
|
||
| // Prefer server-provided delay if present. | ||
| if (response.Headers.TryGetValues("Retry-After", out var values) && | ||
| int.TryParse(values.FirstOrDefault(), out var secs) && | ||
| secs > 0) | ||
| { | ||
| delay = TimeSpan.FromSeconds(secs); | ||
| } | ||
|
|
||
| // Add secure jitter (0–1000ms) to spread retries. | ||
| var jitterMs = RandomNumberGenerator.GetInt32(0, 1000); | ||
| var totalDelay = delay + TimeSpan.FromMilliseconds(jitterMs); | ||
|
|
||
| await Task.Delay(totalDelay, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| // Exponential backoff, capped. | ||
| var nextSeconds = Math.Min(delay.TotalSeconds * 2, _maxBackoff.TotalSeconds); | ||
| delay = TimeSpan.FromSeconds(nextSeconds); | ||
| // Loop and retry with a freshly cloned request. | ||
| } | ||
| } | ||
|
|
||
| private static HttpRequestMessage CloneRequest(HttpRequestMessage original, byte[] bufferedContent, string contentType) | ||
| { | ||
| var clone = new HttpRequestMessage(original.Method, original.RequestUri) | ||
| { | ||
| Version = original.Version, | ||
| VersionPolicy = original.VersionPolicy | ||
| }; | ||
|
|
||
| // Copy headers | ||
| foreach (var header in original.Headers) | ||
| { | ||
| clone.Headers.TryAddWithoutValidation(header.Key, header.Value); | ||
| } | ||
|
|
||
| // Copy content | ||
| if (bufferedContent != null) | ||
| { | ||
| var content = new ByteArrayContent(bufferedContent); | ||
| if (!string.IsNullOrEmpty(contentType)) | ||
| { | ||
| content.Headers.TryAddWithoutValidation("Content-Type", contentType); | ||
| } | ||
|
|
||
| if (original.Content != null) | ||
| { | ||
| foreach (var h in original.Content.Headers) | ||
| { | ||
| if (!string.Equals(h.Key, "Content-Type", StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| content.Headers.TryAddWithoutValidation(h.Key, h.Value); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| clone.Content = content; | ||
| } | ||
|
|
||
| #if NET6_0_OR_GREATER | ||
| foreach (var opt in original.Options) | ||
| { | ||
| clone.Options.Set(new(opt.Key), opt.Value); | ||
| } | ||
| #endif | ||
|
|
||
| return clone; | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check notice
Code scanning / CodeQL
Missed opportunity to use Where Note
Copilot Autofix
AI 4 months ago
The best way to fix the problem is to use the
.Where(...)method from LINQ to filter out any headers with key "Content-Type" before entering the loop. This means replacing the block:with:
No new methods, definitions, or imports are needed, as
System.Linqis already imported and the method is used in a local scope.Edit only the lines covering the above code block in src/Octoshift/Services/SecondaryRateLimitHandler.cs, replacing the loop as described.