Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 53 additions & 3 deletions eng/Find-UpstreamUpdate.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
and than the highest version published on nuget.org. Old-series maintenance releases are therefore skipped, and the
manifest never goes down. Output order is ascending by NuGet version, stable first. No update prints [].
Each item: channel, tag, binVersion, version. A GitHub API failure exits non-zero; it never prints [].
Honours $env:GITHUB_TOKEN. -SelfTest runs built-in cases against mock data (no network) and exits 1 if one fails.
Transient failures (HTTP 500/502/503/504, connection errors) are retried, 3 attempts in all. Honours $env:GITHUB_TOKEN. -SelfTest runs built-in cases against mock data (no network) and exits 1 if one fails.
#>
[CmdletBinding()]
param(
Expand Down Expand Up @@ -85,11 +85,15 @@ function Select-LatestStableRelease($Releases) {
$best
}

function Invoke-GitHubApi([string]$Path) {
function Invoke-GitHubApi([string]$Path, [scriptblock]$Send, [scriptblock]$Sleep) {
$headers = @{ Accept = 'application/vnd.github+json'; 'User-Agent' = 'OpenSlideSharp-upstream-sync' }
if ($env:GITHUB_TOKEN) { $headers.Authorization = "Bearer $($env:GITHUB_TOKEN)" }
$url = "https://api.github.com/$Path"
$r = Invoke-WebRequest -Uri $url -Headers $headers -SkipHttpErrorCheck
$retry = @{}
if ($Send) { $retry.Send = $Send }
if ($Sleep) { $retry.Sleep = $Sleep }
# Retries HTTP 500/502/503/504 and connection errors (3 attempts in all), never 4xx.
$r = Invoke-WebRequestWithRetry -Uri $url -Headers $headers @retry
if ($r.StatusCode -ne 200) { throw "GET $url returned HTTP $($r.StatusCode)." }
$r.Content | ConvertFrom-Json -NoEnumerate
}
Expand Down Expand Up @@ -164,6 +168,52 @@ if ($SelfTest) {
(Compare-NuGetVersion '4.0.1.3-nightly.20261102.g174630bf' '4.0.1.3') -eq -1 }
Test-Case 'Compare 1.1.2 < 4.0.1.2' { (Compare-NuGetVersion '1.1.2' '4.0.1.2') -eq -1 }

# GetNewClosure() copies only the variables of the scope it is called in, and on some PowerShell versions the closure
# cannot see the script's functions or outer variables. So each mock copies this helper into a local ($respond) first.
$newResponse = { param([int]$Status, [string]$Content = '[]') [pscustomobject]@{ StatusCode = $Status; Content = $Content } }
function New-Sender($Script) {
# A mock Send that serves the given statuses in order, repeating the last (a string is a thrown connection error), and counts its calls.
$state = @{ Calls = 0; Waits = [System.Collections.Generic.List[int]]::new() }
$respond = $newResponse
$state.Send = { param($Params) $i = $state.Calls++; $x = $Script[[Math]::Min($i, $Script.Count - 1)]; if ($x -is [string]) { throw $x }; & $respond $x }.GetNewClosure()
$state.Sleep = { param($Seconds) $state.Waits.Add($Seconds) }.GetNewClosure()
$state
}
function Get-ApiOutcome($State) {
# 'ok' or the error message; -WarningAction Ignore keeps the retry warnings out of the self-test output.
try { $null = Invoke-GitHubApi 'x' -Send $State.Send -Sleep $State.Sleep -WarningAction Ignore; 'ok' } catch { $_.Exception.Message }
}
Test-Case 'retry: 502 then 200 succeeds after exactly one retry' {
$s = New-Sender @(502, 200)
(Get-ApiOutcome $s) -eq 'ok' -and $s.Calls -eq 2 -and ($s.Waits -join ',') -eq '5' }
Test-Case 'retry: 502 x3 fails with HTTP 502 after 3 attempts and waits 5 s, 15 s' {
$s = New-Sender @(502)
(Get-ApiOutcome $s) -match 'returned HTTP 502\.$' -and $s.Calls -eq 3 -and ($s.Waits -join ',') -eq '5,15' }
Test-Case 'retry: 404 fails at once without a retry' {
$s = New-Sender @(404, 200)
(Get-ApiOutcome $s) -match 'returned HTTP 404\.$' -and $s.Calls -eq 1 -and $s.Waits.Count -eq 0 }
Test-Case 'retry: 403 fails at once without a retry' {
$s = New-Sender @(403, 200)
(Get-ApiOutcome $s) -match 'returned HTTP 403\.$' -and $s.Calls -eq 1 }
Test-Case 'retry: a connection error then 200 succeeds after one retry' {
$s = New-Sender @('The operation was canceled.', 200)
$respond = $newResponse
$s.Send = { param($Params) if ($s.Calls++ -eq 0) { throw 'The operation was canceled.' }; & $respond 200 }.GetNewClosure()
(Get-ApiOutcome $s) -eq 'ok' -and $s.Calls -eq 2 }
Test-Case 'retry: connection errors x3 are rethrown after 3 attempts' {
$s = New-Sender @('boom')
(Get-ApiOutcome $s) -match 'boom' -and $s.Calls -eq 3 }
Test-Case 'retry: nuget.org 503 then 200 succeeds' {
$s = New-Sender @(503)
$respond = $newResponse
$s.Send = { param($Params) if ($s.Calls++ -eq 0) { & $respond 503 } else { & $respond 200 '{"versions":["1.1.2"]}' } }.GetNewClosure()
$v = @(Get-PublishedNuGetVersions -Send $s.Send -Sleep $s.Sleep -WarningAction Ignore)
$v.Count -eq 1 -and $v[0] -eq '1.1.2' -and $s.Calls -eq 2 }
Test-Case 'retry: nuget.org 404 stays an error and is not retried' {
$s = New-Sender @(404)
$msg = try { $null = Get-PublishedNuGetVersions -Send $s.Send -Sleep $s.Sleep; 'no error' } catch { $_.Exception.Message }
$msg -match 'returned HTTP 404\.$' -and $s.Calls -eq 1 }

foreach ($r in $results) { Write-Host ("{0} {1}" -f ($r.Ok ? 'PASS' : 'FAIL'), $r.Name) }
$failed = @($results | Where-Object { -not $_.Ok }).Count
Write-Host "$($results.Count - $failed) passed, $failed failed"
Expand Down
45 changes: 41 additions & 4 deletions eng/NuGetVersion.psm1
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#requires -Version 7
# NuGet version parsing and ordering, shared by Get-ReleaseVersion.ps1 and Find-UpstreamUpdate.ps1.
# NuGet version parsing and ordering, shared by Get-ReleaseVersion.ps1 and Find-UpstreamUpdate.ps1, plus the retrying web request the sync scripts share.
Set-StrictMode -Version Latest

function ConvertTo-NuGetVersion {
Expand Down Expand Up @@ -64,12 +64,49 @@ function Get-MaxNuGetVersion {
$max
}

function Invoke-WebRequestWithRetry {
<# Invoke-WebRequest (-SkipHttpErrorCheck, so the caller checks the status) that retries HTTP 500/502/503/504 and connection or timeout
errors. Total attempts = $DelaySeconds.Count + 1 (default 3, waiting 5 s then 15 s); each retry logs a warning with the reason.
Any other status, 4xx included, is returned at once. After the last attempt the last response is returned (or the last error rethrown).
-Send (takes the Invoke-WebRequest parameter hashtable) and -Sleep (takes seconds) exist so self-tests need neither network nor waiting. #>
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Uri,
[hashtable]$Headers,
[string]$OutFile,
[int[]]$DelaySeconds = @(5, 15),
[scriptblock]$Send = { param($Params) Invoke-WebRequest @Params },
[scriptblock]$Sleep = { param($Seconds) Start-Sleep -Seconds $Seconds }
)
$params = @{ Uri = $Uri; SkipHttpErrorCheck = $true }
if ($Headers) { $params.Headers = $Headers }
if ($OutFile) { $params.OutFile = $OutFile; $params.PassThru = $true }
$attempts = $DelaySeconds.Count + 1
for ($attempt = 1; ; $attempt++) {
$response = $null; $failure = $null
try { $response = & $Send $params } catch { $failure = $_ }
$reason = if ($failure) { "connection error: $($failure.Exception.Message)" }
elseif ([int]$response.StatusCode -in 500, 502, 503, 504) { "HTTP $([int]$response.StatusCode)" }
else { return $response }
if ($attempt -ge $attempts) {
if ($failure) { throw $failure }
return $response
}
$delay = $DelaySeconds[$attempt - 1]
Write-Warning "GET $Uri failed ($reason); attempt $attempt of $attempts, retrying in $delay s."
& $Sleep $delay
}
}

function Get-PublishedNuGetVersions {
<# All versions of a package on nuget.org (flat container, lower-case ids and versions). 404, any other non-200 status and an empty list are errors. #>
[CmdletBinding()]
param([string]$PackageId = 'openslidesharp')
param([string]$PackageId = 'openslidesharp', [scriptblock]$Send, [scriptblock]$Sleep)
$url = "https://api.nuget.org/v3-flatcontainer/$($PackageId.ToLowerInvariant())/index.json"
$r = Invoke-WebRequest -Uri $url -SkipHttpErrorCheck -Headers @{ 'User-Agent' = 'OpenSlideSharp-release' }
$retry = @{}
if ($Send) { $retry.Send = $Send }
if ($Sleep) { $retry.Sleep = $Sleep }
$r = Invoke-WebRequestWithRetry -Uri $url -Headers @{ 'User-Agent' = 'OpenSlideSharp-release' } @retry
if ($r.StatusCode -ne 200) { throw "GET $url returned HTTP $($r.StatusCode)." }
$json = $r.Content | ConvertFrom-Json
if ($null -eq $json -or -not ($json.PSObject.Properties.Name -contains 'versions')) { throw "GET $url returned no 'versions' list." }
Expand All @@ -86,4 +123,4 @@ function Assert-PublishedNuGetVersions {
[string[]]@($Versions)
}

Export-ModuleMember -Function ConvertTo-NuGetVersion, Compare-NuGetVersion, Get-MaxNuGetVersion, Get-PublishedNuGetVersions, Assert-PublishedNuGetVersions
Export-ModuleMember -Function ConvertTo-NuGetVersion, Compare-NuGetVersion, Get-MaxNuGetVersion, Invoke-WebRequestWithRetry, Get-PublishedNuGetVersions, Assert-PublishedNuGetVersions
11 changes: 9 additions & 2 deletions eng/Update-OpenSlideManifest.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ param(
)
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
Import-Module (Join-Path $PSScriptRoot 'NuGetVersion.psm1') -Force

$repoRoot = Split-Path -Parent $PSScriptRoot
if (-not $OutFile) { $OutFile = Join-Path $repoRoot 'eng/openslide.json' }
Expand All @@ -33,7 +34,10 @@ $assetSuffixes = [ordered]@{
function Invoke-GitHubApi([string]$Path) {
$headers = @{ Accept = 'application/vnd.github+json'; 'User-Agent' = 'OpenSlideSharp-manifest' }
if ($env:GITHUB_TOKEN) { $headers.Authorization = "Bearer $($env:GITHUB_TOKEN)" }
Invoke-RestMethod -Uri "https://api.github.com/$Path" -Headers $headers
$url = "https://api.github.com/$Path"
$r = Invoke-WebRequestWithRetry -Uri $url -Headers $headers
if ($r.StatusCode -ne 200) { throw "GET $url returned HTTP $($r.StatusCode)." }
$r.Content | ConvertFrom-Json
}

function Get-Sha256([string]$Path) { (Get-FileHash $Path -Algorithm SHA256).Hash.ToLowerInvariant() }
Expand Down Expand Up @@ -77,7 +81,10 @@ function Get-VerifiedAsset($Asset) {
# Download to .part and rename only after the hash checks out, so a failed download is never cached.
$part = "$path.part"
Remove-Item $part -Force -ErrorAction SilentlyContinue
try { Invoke-WebRequest -Uri $url -OutFile $part }
try {
$response = Invoke-WebRequestWithRetry -Uri $url -OutFile $part
if ($response.StatusCode -ne 200) { throw "GET $url returned HTTP $($response.StatusCode)." }
}
catch { Remove-Item $part -Force -ErrorAction SilentlyContinue; throw }
$actual = Get-Sha256 $part
if ($actual -ne $expected) {
Expand Down
Loading