diff --git a/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromCache.ps1 b/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromCache.ps1 index b75bf35de1..57a6e2e102 100644 --- a/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromCache.ps1 +++ b/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromCache.ps1 @@ -13,7 +13,7 @@ - Singleton records for tenant-level config resources (e.g. policies/authorizationPolicy) - Collection records for plain collection reads (e.g. users, servicePrincipals) - GitHub cache keys ({ApiVersion}|{AbsoluteUri}) yield External records for the + Legacy and metadata GitHub REST cache keys yield External records for the organization or repository addressed by the request. This is a run-level view (what data the run touched), not per-test attribution. @@ -164,10 +164,17 @@ if ($__MtSession.GitHubCache) { foreach ($key in $__MtSession.GitHubCache.Keys) { - # Key format: {ApiVersion}|{AbsoluteUri} - $uri = ($key -split '\|', 2)[-1] - if ($uri -notmatch '^https://[^/]+/(.+)$') { continue } - $path = (($Matches[1]) -split '\?', 2)[0].TrimEnd('/') + # Recognize only the REST namespaces; GraphQL keys contain opaque request data. + # Pagination options belong to the cache key, never to the resource URI. + if ($key -match '^Metadata\|GET\|\d{4}-\d{2}-\d{2}\|(?[^|]+)\|Paginate=(?:True|False)(?:\|MaxPages=[1-9][0-9]*)?$' -or + $key -match '^\d{4}-\d{2}-\d{2}\|(?[^|]+)(?:\|MaxPages=[1-9][0-9]*)?$') { + $uri = $Matches.uri + } else { continue } + $parsedUri = $null + if ($uri -match '\s' -or -not [uri]::TryCreate($uri, [UriKind]::Absolute, [ref]$parsedUri) -or + $parsedUri.Scheme -ne 'https' -or -not $parsedUri.Host -or $parsedUri.UserInfo -or $parsedUri.Fragment) { continue } + $path = $parsedUri.AbsolutePath.Trim('/') + if (-not $path) { continue } $segments = $path -split '/' $type = $null diff --git a/powershell/internal/services/github/Get-MtGitHubErrorStatusCode.ps1 b/powershell/internal/services/github/Get-MtGitHubErrorStatusCode.ps1 index d1769dfc2a..32a3ade15a 100644 --- a/powershell/internal/services/github/Get-MtGitHubErrorStatusCode.ps1 +++ b/powershell/internal/services/github/Get-MtGitHubErrorStatusCode.ps1 @@ -8,6 +8,7 @@ $null for transport failures where no HTTP response was produced. #> param([Parameter(Mandatory)] $ErrorRecord) + if ($ErrorRecord.Exception.Data['GitHubRateLimit']) { return $ErrorRecord.Exception.Data['GitHubRateLimit'].HttpStatus } try { if ($ErrorRecord.Exception.Response -and $ErrorRecord.Exception.Response.StatusCode) { return [int]$ErrorRecord.Exception.Response.StatusCode diff --git a/powershell/internal/services/github/Get-MtGitHubRateLimit.ps1 b/powershell/internal/services/github/Get-MtGitHubRateLimit.ps1 new file mode 100644 index 0000000000..e57fa10bb4 --- /dev/null +++ b/powershell/internal/services/github/Get-MtGitHubRateLimit.ps1 @@ -0,0 +1,71 @@ +function Get-MtGitHubRateLimit { + <# + .SYNOPSIS + Internal: Classifies GitHub primary/secondary limits without parsing Maester diagnostic text. + .DESCRIPTION + Returns a separate record for each observed limit. Primary REST and GraphQL quotas are separate; + secondary limits can be shared across both APIs, with their own deadline. + Uses response headers, documented API error messages and GraphQL RATE_LIMITED errors. + An unknown primary reset requires a new connection; no retry time is invented for it. + #> + [CmdletBinding()] + param( + [object] $ErrorRecord, + [AllowNull()] [object] $Headers, + [int] $StatusCode = 200, + [ValidateSet('REST', 'GraphQL')] [string] $Api = 'REST', + [switch] $GraphQLRateLimited, + [string] $Message + ) + if ($ErrorRecord) { + if ($ErrorRecord.Exception.Data['GitHubRateLimits']) { return $ErrorRecord.Exception.Data['GitHubRateLimits'] } + if ($ErrorRecord.Exception.Data['GitHubRateLimit']) { return $ErrorRecord.Exception.Data['GitHubRateLimit'] } + $StatusCode = Get-MtGitHubErrorStatusCode -ErrorRecord $ErrorRecord + if ($StatusCode -notin 403, 429) { return $null } + $Headers = $ErrorRecord.Exception.Response.Headers + $Message = Get-MtGitHubErrorMessage -ErrorRecord $ErrorRecord + } + $remaining = Get-MtGitHubResponseHeaderValue -Headers $Headers -Name 'x-ratelimit-remaining' + $remainingValue = 0 + $primary = $null -ne $remaining -and [int]::TryParse([string]$remaining, [ref]$remainingValue) -and $remainingValue -eq 0 + $retryAfter = Get-MtGitHubResponseHeaderValue -Headers $Headers -Name 'retry-after' + $secondary = $Message -match '(?i)secondary\s+rate\s+limit|abuse\s+detection' -or (($StatusCode -in 403, 429 -or $GraphQLRateLimited) -and $null -ne $retryAfter) + if (-not $primary -and -not $secondary -and $StatusCode -ne 429 -and -not $GraphQLRateLimited) { return $null } + if ($StatusCode -notin 200, 403, 429) { return $null } + + $now = [DateTimeOffset]::UtcNow + $reset = Get-MtGitHubResponseHeaderValue -Headers $Headers -Name 'x-ratelimit-reset' + $resetSeconds = 0L + $resetUtc = $null + if ($null -ne $reset -and [long]::TryParse([string]$reset, [ref]$resetSeconds)) { + try { $resetUtc = [DateTimeOffset]::FromUnixTimeSeconds($resetSeconds) } catch { Write-Debug 'GitHub returned an out-of-range reset epoch.' } + } + $retrySeconds = 0L + $retryUtc = $null + if ($null -ne $retryAfter -and [long]::TryParse([string]$retryAfter, [ref]$retrySeconds) -and $retrySeconds -ge 0) { + try { $retryUtc = $now.AddSeconds($retrySeconds) } catch { Write-Debug 'GitHub returned an out-of-range retry interval.' } + } + $resource = Get-MtGitHubResponseHeaderValue -Headers $Headers -Name 'x-ratelimit-resource' + if ($primary) { + # An unknown reset blocks only the exhausted API, not the other primary quota. + $resumeUtc = if ($null -eq $resetUtc -or $resetUtc -ge [DateTimeOffset]::MaxValue.AddSeconds(-1)) { [DateTimeOffset]::MaxValue } + else { $resetUtc.AddSeconds(1) } + $resetText = if ($resetUtc) { $resetUtc.LocalDateTime } else { 'unknown' } + [pscustomobject]@{ + Kind = 'Primary'; Scope = $Api; HttpStatus = $StatusCode; Resource = $resource + RetryAfterSeconds = $null; ResetUtc = $resetUtc; ResumeUtc = $resumeUtc + Message = "GitHub API rate limit encountered (HTTP $StatusCode). Resets at: $resetText" + } + } + if ($secondary -or -not $primary) { + # A simultaneous primary reset must neither extend nor shorten the shared cooldown. + $resumeUtc = if ($retryUtc) { $retryUtc } else { $now.AddSeconds(60) } + $diagnostic = if ($retryUtc) { "GitHub secondary rate limit encountered (HTTP $StatusCode). Retry after: ${retrySeconds}s" } + else { "GitHub secondary rate limit encountered (HTTP $StatusCode). Retry after at least 60s." } + [pscustomobject]@{ + Kind = 'Secondary'; Scope = 'All'; HttpStatus = $StatusCode; Resource = $resource + RetryAfterSeconds = $(if ($retryUtc) { $retrySeconds } else { $null }) + ResetUtc = $null; ResumeUtc = $resumeUtc; Message = $diagnostic + } + } +} diff --git a/powershell/internal/services/github/Get-MtGitHubRateLimitMessage.ps1 b/powershell/internal/services/github/Get-MtGitHubRateLimitMessage.ps1 index f55609689d..7d123281cb 100644 --- a/powershell/internal/services/github/Get-MtGitHubRateLimitMessage.ps1 +++ b/powershell/internal/services/github/Get-MtGitHubRateLimitMessage.ps1 @@ -1,75 +1,12 @@ -function Get-MtGitHubRateLimitMessage { +function Get-MtGitHubRateLimitMessage { <# .SYNOPSIS - Internal: Returns a GitHub rate-limit message for an ErrorRecord, or $null when the - error is not a rate-limit response. - + Internal: Returns a GitHub rate-limit diagnostic, or null for ordinary HTTP errors. .DESCRIPTION - Mirrors the rate-limit detection in Invoke-MtGitHubRequest so that bootstrap callers - (Connect-MtGitHub) can distinguish HTTP 403/429 caused by rate limiting from - permission, token, or org-access failures. - - Returns: - - "GitHub API rate limit encountered (HTTP ). Resets at: