Public/Definitions/Resolve-EwArtifact.ps1

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

function Resolve-EwArtifact {
    <#
    .SYNOPSIS
        Resolves the latest Evergreen artifact for an App.json definition.
    .DESCRIPTION
        Applies a supported Application.Filter query when present, otherwise
        queries Evergreen using Application.Name. Selects the latest artifact
        matching Application.Architecture, preferring Application.Language.
        When Evergreen omits architecture metadata, the resolved artifact uses
        the application's declared architecture from the definition.
        Filter predicates are evaluated without executing stored commands.
        Results are cached using the definition's
        SHA256 hash and expire after 24 hours by default.
    .PARAMETER DefinitionPath
        Path to an App.json definition.
    .PARAMETER CachePath
        Cache directory. Defaults to the user's local EvergreenWorkbench cache.
    .PARAMETER CacheMaxAgeHours
        Maximum age of a cached result. Use zero to always query Evergreen.
    .PARAMETER NoCache
        Queries Evergreen and skips cache reads and writes.
    .EXAMPLE
        Resolve-EwArtifact -DefinitionPath .\Definitions\Example\App.json
    .OUTPUTS
        System.Management.Automation.PSCustomObject
    .NOTES
        Without a filter, Application.Name must be an Evergreen catalog name. RequirementRule.Architecture
        controls OS eligibility during installation and publishing, not artifact selection.
    #>

    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param(
        [Parameter(Mandatory, Position = 0)]
        [ValidateNotNullOrEmpty()]
        [string]$DefinitionPath,

        [Parameter()]
        [string]$CachePath,

        [Parameter()]
        [ValidateRange(0, 8760)]
        [int]$CacheMaxAgeHours = 24,

        [Parameter()]
        [switch]$NoCache
    )

    $fail = {
        param([string]$Message)
        Write-Verbose -Message "EvergreenUI: $Message"
        [PSCustomObject]@{
            Succeeded        = $false
            Version          = ''
            URI              = ''
            ResolvedArtifact = $null
            FilterExpression = ''
            Error            = $Message
            IsFromCache      = $false
            CacheFile        = ''
        }
    }

    if (-not (Test-Path -LiteralPath $DefinitionPath -PathType Leaf)) {
        return (& $fail "Definition file was not found: $DefinitionPath")
    }

    $resolutionPolicy = 'ApplicationFilterArchitectureFallback'
    $filterExpression = ''
    try {
        $definition = Get-Content -LiteralPath $DefinitionPath -Raw -ErrorAction Stop |
            ConvertFrom-Json -ErrorAction Stop
        $application = Get-EwObjectPropertyValue -Object $definition -Name 'Application'
        $appName = if ($null -ne $application) {
            [string](Get-EwObjectPropertyValue -Object $application -Name 'Name' -Default '')
        } else { '' }
        $filterExpression = [string](Get-EwObjectPropertyValue -Object $application -Name 'Filter' -Default '')
        if (-not [string]::IsNullOrWhiteSpace($filterExpression)) {
            $query = ConvertFrom-EwDefinitionFilter -Filter $filterExpression
            $appName = $query.AppName
        }
        elseif ([string]::IsNullOrWhiteSpace($appName)) {
            return (& $fail 'Application.Name is empty or missing. Specify an Evergreen catalog name.')
        }
        else {
            $appName = $appName.Trim()
            $query = [PSCustomObject]@{ CommandName = 'Get-EvergreenApp'; AppName = $appName }
        }
    }
    catch {
        return (& $fail "Failed to read definition application: $($_.Exception.Message)")
    }

    $CachePath = Get-EwCachePath -CachePath $CachePath
    $cacheFile = Join-Path -Path $CachePath -ChildPath 'definition-artifact-cache.json'
    $definitionHash = Get-EwDefinitionFileHash -DefinitionPath $DefinitionPath
    $resolvedPath = [System.IO.Path]::GetFullPath($DefinitionPath)

    $cacheEpoch = $null
    if (-not $NoCache) {
        try {
            $snapshot = Invoke-EwDefinitionCache -Action Read -CachePath $CachePath -ErrorAction Stop
            $cacheEpoch = $snapshot.Epoch
            $entry = $snapshot.Entries | Where-Object {
                [string]$_.DefinitionPath -ieq $resolvedPath -and
                [string]$_.DefinitionHash -eq $definitionHash -and
                $null -ne $_.PSObject.Properties['ResolutionPolicy'] -and
                [string]$_.ResolutionPolicy -eq $resolutionPolicy
            } | Select-Object -First 1
            if ($null -ne $entry -and $CacheMaxAgeHours -gt 0) {
                $retrievedAt = [DateTimeOffset]::MinValue
                $timestampValid = $false
                if ($entry.RetrievedAt -is [DateTimeOffset]) {
                    $retrievedAt = [DateTimeOffset]$entry.RetrievedAt
                    $timestampValid = $true
                }
                elseif ($entry.RetrievedAt -is [DateTime]) {
                    $retrievedAt = [DateTimeOffset]([DateTime]$entry.RetrievedAt)
                    $timestampValid = $true
                }
                else {
                    $timestampValid = [DateTimeOffset]::TryParse(
                        [string]$entry.RetrievedAt,
                        [System.Globalization.CultureInfo]::InvariantCulture,
                        [System.Globalization.DateTimeStyles]::RoundtripKind,
                        [ref]$retrievedAt
                    )
                }
                if ($timestampValid) {
                    $age = [DateTimeOffset]::UtcNow - $retrievedAt.ToUniversalTime()
                    $application = $definition.Application
                    $architecture = [string](Get-EwObjectPropertyValue -Object $application -Name 'Architecture' -Default '')
                    $cachedArchitecture = if ($null -ne $entry.ResolvedArtifact) {
                        [string](Get-EwObjectPropertyValue -Object $entry.ResolvedArtifact -Name 'Architecture' -Default '')
                    } else { '' }
                    $architectureMatches = [string]::IsNullOrWhiteSpace($architecture) -or $architecture.Trim() -eq '-' -or
                        -not $entry.Succeeded -or $cachedArchitecture.Trim() -ieq $architecture.Trim()
                    if ($age.TotalHours -le $CacheMaxAgeHours -and $age.TotalMinutes -ge 0 -and $architectureMatches) {
                        Write-Verbose -Message "EvergreenUI: Definition artifact cache hit (age: $([Math]::Round($age.TotalMinutes, 1)) minutes)."
                        return [PSCustomObject]@{
                            Succeeded        = [bool]$entry.Succeeded
                            Version          = [string]$entry.Version
                            URI              = [string]$entry.URI
                            ResolvedArtifact = $entry.ResolvedArtifact
                            FilterExpression = $filterExpression
                            Error            = [string]$entry.Error
                            IsFromCache      = $true
                            CacheFile        = $cacheFile
                        }
                    }
                }
            }
        }
        catch {
            Write-Verbose -Message "EvergreenUI: Definition artifact cache could not be read; querying Evergreen: $($_.Exception.Message)"
        }
    }

    Write-Verbose -Message "EvergreenUI: Definition artifact cache miss or bypass (NoCache: $($NoCache.IsPresent)); querying Evergreen application '$appName' for '$resolvedPath'"
    try {
        $artifacts = @(Invoke-EwDefinitionQuery -Query $query -NoCache:$NoCache)
        if (-not [string]::IsNullOrWhiteSpace($filterExpression)) {
            if ($null -ne $query.Predicate) {
                $artifacts = @($artifacts | Where-Object {
                    [bool](Get-EwFilterLiteralValue -Expression $query.Predicate -Artifact $_)
                })
            }
            if ($query.SelectFirst) {
                $artifacts = @($artifacts | Select-Object -First 1)
            }
            Write-Verbose -Message "EvergreenUI: Application.Filter selected $($artifacts.Count) artifacts for '$resolvedPath'."
            if ($artifacts.Count -eq 0) {
                throw 'No artifact matches Application.Filter.'
            }
        }
        $preferredArchitecture = if ($null -ne $application.PSObject.Properties['Architecture']) {
            [string]$application.Architecture
        } else { '' }
        $preferredLanguage = if ($null -ne $application.PSObject.Properties['Language']) {
            [string]$application.Language
        } else { '' }
        if ($artifacts.Count -eq 0) {
            throw "Evergreen application '$appName' did not return any artifacts."
        }
        $hasDeclaredArchitecture = -not [string]::IsNullOrWhiteSpace($preferredArchitecture) -and $preferredArchitecture.Trim() -ne '-'
        if ($hasDeclaredArchitecture) {
            $artifacts = @($artifacts | Where-Object {
                $value = [string](Get-EwObjectPropertyValue -Object $_ -Name 'Architecture' -Default '')
                [string]::IsNullOrWhiteSpace($value) -or $value.Trim() -ieq $preferredArchitecture.Trim()
            })
            if ($artifacts.Count -eq 0) {
                throw "No artifact matches Application.Architecture '$preferredArchitecture'."
            }
        }
        if (-not [string]::IsNullOrWhiteSpace($preferredLanguage)) {
            $preferredMatches = @($artifacts | Where-Object {
                $null -ne $_.PSObject.Properties['Language'] -and
                [string]$_.PSObject.Properties['Language'].Value -ieq $preferredLanguage
            })
            if ($preferredMatches.Count -gt 0) {
                $artifacts = $preferredMatches
            }
        }

        $best = $null
        $bestVersion = [version]'0.0'
        foreach ($artifact in $artifacts) {
            $versionText = ([string]$artifact.Version) -replace '^[^0-9]*', '' -replace '[^0-9\.].*$', ''
            $candidateVersion = [version]'0.0'
            if ([version]::TryParse($versionText, [ref]$candidateVersion) -and
                ($null -eq $best -or $candidateVersion -gt $bestVersion)) {
                $best = $artifact
                $bestVersion = $candidateVersion
            }
            elseif ($null -eq $best) {
                $best = $artifact
            }
        }
        if ($null -eq $best) {
            throw 'No suitable artifact was found.'
        }
        $artifactArchitecture = [string](Get-EwObjectPropertyValue -Object $best -Name 'Architecture' -Default '')
        if ($hasDeclaredArchitecture -and [string]::IsNullOrWhiteSpace($artifactArchitecture)) {
            $best = $best.PSObject.Copy()
            $best | Add-Member -NotePropertyName Architecture -NotePropertyValue $preferredArchitecture.Trim() -Force
            Write-Verbose -Message "EvergreenUI: Using declared application architecture '$($preferredArchitecture.Trim())'; Evergreen did not supply artifact architecture for '$appName'."
        }

        $uri = ''
        foreach ($propertyName in @('URI', 'Uri', 'URL', 'Url', 'DownloadUri', 'DownloadUrl')) {
            $property = $best.PSObject.Properties[$propertyName]
            if ($null -ne $property -and -not [string]::IsNullOrWhiteSpace([string]$property.Value)) {
                $uri = [string]$property.Value
                break
            }
        }
        if ([string]::IsNullOrWhiteSpace($uri)) {
            throw 'Resolved artifact does not contain a download URI.'
        }

        $result = [PSCustomObject]@{
            Succeeded        = $true
            Version          = [string]$best.Version
            URI              = $uri
            ResolvedArtifact = $best
            FilterExpression = $filterExpression
            Error            = ''
            IsFromCache      = $false
            CacheFile        = $cacheFile
        }
        Write-Verbose -Message "EvergreenUI: Definition artifact resolved for '$resolvedPath'; version '$($result.Version)'"
    }
    catch {
        $result = & $fail "Artifact resolution failed: $($_.Exception.Message)"
        $result.CacheFile = $cacheFile
    }

    if (-not $NoCache -and $null -ne $cacheEpoch) {
        try {
            $entry = [PSCustomObject]@{
                DefinitionPath   = $resolvedPath
                DefinitionHash   = $definitionHash
                ResolutionPolicy = $resolutionPolicy
                RetrievedAt      = [DateTimeOffset]::UtcNow.ToString('o')
                Succeeded        = $result.Succeeded
                Version          = $result.Version
                URI              = $result.URI
                ResolvedArtifact = $result.ResolvedArtifact
                Error            = $result.Error
            }
            Invoke-EwDefinitionCache -Action Write -CachePath $CachePath -Epoch $cacheEpoch -Entry $entry -ErrorAction Stop
        }
        catch {
            Write-Verbose -Message "EvergreenUI: Definition artifact cache write failed: $($_.Exception.Message)"
        }
    }

    return $result
}