|
| 1 | +using System.Net.Http.Headers; |
| 2 | +using System.Text.Json; |
| 3 | + |
| 4 | +namespace NuGetDashboard; |
| 5 | + |
| 6 | +public sealed class GitHubClient : IDisposable |
| 7 | +{ |
| 8 | + private readonly HttpClient _http; |
| 9 | + private const string Repo = "NuGet/NuGet.Client"; |
| 10 | + private int _rateLimitRemaining = int.MaxValue; |
| 11 | + |
| 12 | + public int RateLimitRemaining => _rateLimitRemaining; |
| 13 | + |
| 14 | + /// <summary> |
| 15 | + /// Calls /rate_limit (free — not counted against quota) and returns |
| 16 | + /// the core API remaining budget, which is what timeline/review calls consume. |
| 17 | + /// </summary> |
| 18 | + public async Task<(int remaining, int limit)> GetCoreRateLimitAsync() |
| 19 | + { |
| 20 | + using var resp = await _http.GetAsync("rate_limit"); |
| 21 | + if (!resp.IsSuccessStatusCode) return (int.MaxValue, int.MaxValue); |
| 22 | + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); |
| 23 | + var core = doc.RootElement.GetProperty("resources").GetProperty("core"); |
| 24 | + return (core.GetProperty("remaining").GetInt32(), core.GetProperty("limit").GetInt32()); |
| 25 | + } |
| 26 | + |
| 27 | + public GitHubClient(string? token = null) |
| 28 | + { |
| 29 | + _http = new HttpClient { BaseAddress = new Uri("https://api.github.com/") }; |
| 30 | + _http.DefaultRequestHeaders.UserAgent.ParseAdd("NuGetDashboardCli/1.0"); |
| 31 | + // Include mockingbird preview to ensure timeline events are returned |
| 32 | + _http.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github.mockingbird-preview+json"); |
| 33 | + _http.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github+json"); |
| 34 | + _http.DefaultRequestHeaders.Add("X-GitHub-Api-Version", "2022-11-28"); |
| 35 | + if (token is not null) |
| 36 | + _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); |
| 37 | + } |
| 38 | + |
| 39 | + public async Task<List<RawPR>> SearchMergedPRsAsync(DateTime since, DateTime until) |
| 40 | + { |
| 41 | + var results = new List<RawPR>(); |
| 42 | + var q = Uri.EscapeDataString($"repo:{Repo} is:pr is:merged merged:{since:yyyy-MM-dd}..{until:yyyy-MM-dd}"); |
| 43 | + |
| 44 | + for (var page = 1; ; page++) |
| 45 | + { |
| 46 | + using var resp = await _http.GetAsync($"search/issues?q={q}&per_page=100&page={page}"); |
| 47 | + TrackRateLimit(resp); |
| 48 | + resp.EnsureSuccessStatusCode(); |
| 49 | + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); |
| 50 | + var items = doc.RootElement.GetProperty("items"); |
| 51 | + foreach (var item in items.EnumerateArray()) |
| 52 | + results.Add(ParseRawPR(item)); |
| 53 | + if (items.GetArrayLength() < 100) break; |
| 54 | + } |
| 55 | + return results; |
| 56 | + } |
| 57 | + |
| 58 | + /// <summary> |
| 59 | + /// Returns the time the PR became ready for review: |
| 60 | + /// first ready_for_review event → first review_requested event → null (caller falls back to created_at). |
| 61 | + /// </summary> |
| 62 | + public async Task<DateTime?> GetReadyTimeAsync(int prNumber) |
| 63 | + { |
| 64 | + using var resp = await _http.GetAsync( |
| 65 | + $"repos/{Repo}/issues/{prNumber}/timeline?per_page=100"); |
| 66 | + TrackRateLimit(resp); |
| 67 | + await ThrowIfErrorAsync(resp, $"timeline for PR #{prNumber}"); |
| 68 | + if (!resp.IsSuccessStatusCode) return null; |
| 69 | + |
| 70 | + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); |
| 71 | + |
| 72 | + DateTime? readyForReview = null; |
| 73 | + DateTime? firstReviewRequest = null; |
| 74 | + |
| 75 | + foreach (var ev in doc.RootElement.EnumerateArray()) |
| 76 | + { |
| 77 | + if (!ev.TryGetProperty("event", out var evProp)) continue; |
| 78 | + if (!ev.TryGetProperty("created_at", out var tsProp)) continue; |
| 79 | + if (!tsProp.TryGetDateTime(out var ts)) continue; |
| 80 | + |
| 81 | + switch (evProp.GetString()) |
| 82 | + { |
| 83 | + case "ready_for_review": |
| 84 | + if (readyForReview is null || ts < readyForReview) |
| 85 | + readyForReview = ts; |
| 86 | + break; |
| 87 | + case "review_requested": |
| 88 | + if (firstReviewRequest is null || ts < firstReviewRequest) |
| 89 | + firstReviewRequest = ts; |
| 90 | + break; |
| 91 | + } |
| 92 | + } |
| 93 | + return readyForReview ?? firstReviewRequest; |
| 94 | + } |
| 95 | + |
| 96 | + /// <summary>Returns the DateTime of the first APPROVED review, or null.</summary> |
| 97 | + public async Task<DateTime?> GetFirstApprovalAtAsync(int prNumber) |
| 98 | + { |
| 99 | + using var resp = await _http.GetAsync($"repos/{Repo}/pulls/{prNumber}/reviews"); |
| 100 | + TrackRateLimit(resp); |
| 101 | + await ThrowIfErrorAsync(resp, $"reviews for PR #{prNumber}"); |
| 102 | + if (!resp.IsSuccessStatusCode) return null; |
| 103 | + |
| 104 | + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); |
| 105 | + DateTime? firstApproval = null; |
| 106 | + |
| 107 | + foreach (var r in doc.RootElement.EnumerateArray()) |
| 108 | + { |
| 109 | + if (r.GetProperty("state").GetString() != "APPROVED") continue; |
| 110 | + if (!r.TryGetProperty("submitted_at", out var el)) continue; |
| 111 | + if (!el.TryGetDateTime(out var t)) continue; |
| 112 | + if (firstApproval is null || t < firstApproval) firstApproval = t; |
| 113 | + } |
| 114 | + return firstApproval; |
| 115 | + } |
| 116 | + |
| 117 | + private void TrackRateLimit(HttpResponseMessage resp) |
| 118 | + { |
| 119 | + if (resp.Headers.TryGetValues("X-RateLimit-Remaining", out var vals) && |
| 120 | + int.TryParse(vals.FirstOrDefault(), out var remaining)) |
| 121 | + _rateLimitRemaining = remaining; |
| 122 | + } |
| 123 | + |
| 124 | + private static async Task ThrowIfErrorAsync(HttpResponseMessage resp, string context) |
| 125 | + { |
| 126 | + if (resp.IsSuccessStatusCode) return; |
| 127 | + |
| 128 | + var body = await resp.Content.ReadAsStringAsync(); |
| 129 | + |
| 130 | + // Distinguish the three common failure modes from the response body |
| 131 | + if (body.Contains("secondary rate limit", StringComparison.OrdinalIgnoreCase) || |
| 132 | + resp.Headers.Contains("Retry-After")) |
| 133 | + { |
| 134 | + throw new InvalidOperationException( |
| 135 | + $"GitHub secondary rate limit (abuse detection) hit fetching {context}.\n" + |
| 136 | + $" → Wait a minute then retry."); |
| 137 | + } |
| 138 | + |
| 139 | + if (resp.Headers.TryGetValues("X-RateLimit-Remaining", out var v) && v.FirstOrDefault() == "0") |
| 140 | + { |
| 141 | + throw new InvalidOperationException( |
| 142 | + $"GitHub primary rate limit exhausted fetching {context}.\n" + |
| 143 | + $" → Wait until the hour resets, or use a different token."); |
| 144 | + } |
| 145 | + |
| 146 | + if (body.Contains("Resource not accessible by integration", StringComparison.OrdinalIgnoreCase) || |
| 147 | + body.Contains("must have push access", StringComparison.OrdinalIgnoreCase)) |
| 148 | + { |
| 149 | + throw new InvalidOperationException( |
| 150 | + $"Permission denied fetching {context}.\n" + |
| 151 | + $" Your token is a fine-grained PAT — it needs these permissions:\n" + |
| 152 | + $" • Issues: Read\n" + |
| 153 | + $" • Pull requests: Read\n" + |
| 154 | + $" → Edit the token at github.com/settings/tokens and add those, then retry.\n" + |
| 155 | + $" → Or use a classic token (github.com/settings/tokens/new?type=classic) with no scopes.\n" + |
| 156 | + $" Raw error: {body}"); |
| 157 | + } |
| 158 | + |
| 159 | + if (body.Contains("forbids access via a fine-grained personal access token", StringComparison.OrdinalIgnoreCase)) |
| 160 | + { |
| 161 | + throw new InvalidOperationException( |
| 162 | + $"The NuGet org blocks fine-grained PATs with lifetime > 7 days.\n" + |
| 163 | + $" → Use a classic token instead (recommended — no scopes needed):\n" + |
| 164 | + $" github.com/settings/tokens/new?type=classic\n" + |
| 165 | + $" → Or shorten your fine-grained PAT's lifetime to ≤7 days at:\n" + |
| 166 | + $" github.com/settings/personal-access-tokens"); |
| 167 | + } |
| 168 | + |
| 169 | + throw new InvalidOperationException( |
| 170 | + $"GitHub API {(int)resp.StatusCode} error fetching {context}.\n Body: {body}"); |
| 171 | + } |
| 172 | + |
| 173 | + private static RawPR ParseRawPR(JsonElement item) |
| 174 | + { |
| 175 | + var pr = item.GetProperty("pull_request"); |
| 176 | + return new RawPR( |
| 177 | + Number: item.GetProperty("number").GetInt32(), |
| 178 | + Title: item.GetProperty("title").GetString()!, |
| 179 | + Url: item.GetProperty("html_url").GetString()!, |
| 180 | + Author: item.GetProperty("user").GetProperty("login").GetString()!, |
| 181 | + CreatedAt: item.GetProperty("created_at").GetDateTime(), |
| 182 | + MergedAt: pr.GetProperty("merged_at").GetDateTime()); |
| 183 | + } |
| 184 | + |
| 185 | + public void Dispose() => _http.Dispose(); |
| 186 | +} |
0 commit comments