Private/Application/MapFeedRefresh.ps1

function Save-MapImageFile {
    [CmdletBinding()]
    param([Parameter(Mandatory)][string]$Uri, [Parameter(Mandatory)][string]$Path)

    $temporaryPath = "$Path.$([guid]::NewGuid().ToString('N')).tmp"
    try {
        Invoke-WebRequest -Uri $Uri -OutFile $temporaryPath -UseBasicParsing -TimeoutSec 60 -ErrorAction Stop
        $stream = [System.IO.File]::OpenRead($temporaryPath)
        try {
            if ($stream.ReadByte() -ne 255 -or $stream.ReadByte() -ne 216 -or $stream.ReadByte() -ne 255) {
                throw 'The map source did not return a JPEG image.'
            }
            $stream.Position = 0
            Add-Type -AssemblyName System.Drawing.Common
            $image = [System.Drawing.Image]::FromStream($stream, $false, $true)
            try {
                if ($image.Width -lt 1 -or $image.Height -lt 1) { throw 'The map image has no usable pixels.' }
            }
            finally { $image.Dispose() }
        }
        finally { $stream.Dispose() }
        [System.IO.File]::Move($temporaryPath, $Path, $true)
        $Path
    }
    finally {
        if ([System.IO.File]::Exists($temporaryPath)) { [System.IO.File]::Delete($temporaryPath) }
    }
}

function New-LiveMapRefreshState {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$Definitions,
        [Parameter(Mandatory)][string]$DataDirectory,
        [Parameter(Mandatory)][string]$ImageDirectory,
        [Parameter(Mandatory)][pscustomobject]$SourceRegister
    )

    $profiles = @{
        Earthquakes = @{ Source = 'USGS'; SourceIds = @('usgs-earthquakes'); CacheName = 'earthquakeData' }
        Volcanoes = @{
            Source = 'Smithsonian GVP'; SourceIds = @('smithsonian-volcanoes'); CacheName = 'volcanoData'
            MinimumIntervalMinutes = 1440
        }
        NaturalEvents = @{
            Source = 'Natural event feeds'; SourceIds = @('gdacs', 'nasa-eonet'); CacheName = 'naturalEventData'
            MinimumIntervalMinutes = 15
        }
        NightSatellite = @{
            Source = 'NASA Earth at Night'; SourceIds = @('nasa-earth-at-night'); Path = Join-Path $ImageDirectory 'worldmap.jpg'
            Uri = 'https://eoimages.gsfc.nasa.gov/images/imagerecords/79000/79765/dnb_land_ocean_ice.2012.3600x1800.jpg'
        }
        BlueMarble = @{
            Source = 'NASA Blue Marble'; SourceIds = @('nasa-blue-marble'); Path = Join-Path $ImageDirectory 'bluemarble.jpg'
            Uri = 'https://eoimages.gsfc.nasa.gov/images/imagerecords/73000/73909/world.topo.bathy.200412.3x5400x2700.jpg'
        }
    }
    $entries = @{}
    foreach ($kind in $profiles.Keys) {
        $entries[$kind] = [pscustomobject]@{
            Profile = $profiles[$kind]; Enabled = $false; Request = $null; StopOperation = $null
            Cache = @{
                Data = $null; LastFetch = [datetime]::MinValue; LastAttempt = [datetime]::MinValue
                Status = 'Unavailable'; IsRefreshing = $false; Error = $null
            }
        }
    }
    @{
        Definitions = $Definitions; DataDirectory = $DataDirectory; SourceRegister = $SourceRegister
        Entries = $entries; Coordinator = $null
        Worker = {
            param($definitions, $kind, $dataDir, $profile, $previousData)
            . ([scriptblock]::Create($definitions))
            $script:mapFeedFailures = @()
            $script:mapFeedErrors = @()
            $script:mapFeedSuccesses = 0
            $script:mapMaximumEvents = 75
            try {
                if ($profile.Path) {
                    $data = Save-MapImageFile -Uri $profile.Uri -Path $profile.Path
                }
                else {
                    Set-Variable -Name $profile.CacheName -Scope Script -Value $null
                    Invoke-LiveFeedFetch -Layer $kind
                    if (-not $script:mapFeedSuccesses) {
                        $message = if ($script:mapFeedErrors.Count) { $script:mapFeedErrors -join '; ' }
                            else { 'No enabled map source was fetched.' }
                        throw $message
                    }
                    $data = @((Get-Variable -Name $profile.CacheName -Scope Script).Value)
                    if ($kind -eq 'NaturalEvents' -and $script:mapFeedFailures.Count) {
                        $data = @($data | Where-Object { $_.Source -notin $script:mapFeedFailures })
                        $cached = @(
                            foreach ($record in $previousData) {
                                if ($record.Source -notin $script:mapFeedFailures) { continue }
                                $copy = $record | Select-Object * -ExcludeProperty SourceCached
                                $copy | Add-Member -NotePropertyName SourceCached -NotePropertyValue $true
                                $copy
                            }
                        )
                        $data = @(@($data + $cached) | Sort-Object Updated -Descending |
                            Select-Object -First $script:mapMaximumEvents)
                    }
                }
                [pscustomobject]@{
                    Data = $data; LastFetch = [datetime]::UtcNow
                    Status = $(if ($script:mapFeedFailures.Count) { 'Partial' } else { 'Fetched' })
                    Error = $(if ($script:mapFeedErrors.Count) {
                        ConvertTo-SanitizedDiagnosticText -Text ($script:mapFeedErrors -join '; ')
                    } else { $null })
                }
            }
            catch {
                [pscustomobject]@{
                    Data = $null; LastFetch = [datetime]::MinValue; Status = 'Unavailable'
                    Error = ConvertTo-SanitizedDiagnosticText -Text $_.Exception.Message
                }
            }
        }
    }
}

function Set-LiveMapRefreshFailure {
    param([hashtable]$Cache, [string]$Message)
    $Cache.Status = if ($Cache.LastFetch -ne [datetime]::MinValue) { 'Cached' } else { 'Unavailable' }
    $Cache.Error = ConvertTo-SanitizedDiagnosticText -Text $Message
    Write-Verbose "Map refresh failed: $($Cache.Error)"
}

function Request-LiveMapRefresh {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][hashtable]$State,
        [AllowEmptyCollection()][string[]]$EnabledLayers = @()
    )

    foreach ($kind in $EnabledLayers) {
        if (-not $State.Entries.ContainsKey($kind)) { throw "Unknown live map layer '$kind'." }
    }
    foreach ($kind in $State.Entries.Keys) {
        $entry = $State.Entries[$kind]
        $cache = $entry.Cache
        $entry.Enabled = $kind -in $EnabledLayers
        if (-not $entry.Enabled) {
            if ($entry.Request -and -not $entry.Request.AsyncResult.IsCompleted -and -not $entry.StopOperation) {
                $entry.Request.StopReason = 'cancelled'
                try { $entry.StopOperation = $entry.Request.PowerShell.BeginStop($null, $null) }
                catch { Set-LiveMapRefreshFailure -Cache $cache -Message $_.Exception.Message }
            }
            continue
        }
        $deniedSources = @(
            foreach ($sourceId in $entry.Profile.SourceIds) {
                $displayDecision = Get-SourcePolicyDecision -Sources $State.SourceRegister.sources `
                    -SourceId $sourceId -Use display
                $persistenceDecision = Get-SourcePolicyDecision -Sources $State.SourceRegister.sources `
                    -SourceId $sourceId -Use persistence
                if (-not $displayDecision.allowed -or -not $persistenceDecision.allowed) {
                    "$sourceId ($($displayDecision.reason ?? $persistenceDecision.reason))"
                }
            }
        )
        if ($deniedSources.Count -gt 0) {
            $cache.Data = $null
            $cache.LastFetch = [datetime]::MinValue
            $cache.Status = 'Unavailable'
            $cache.Error = "Source use is disabled until display, cache, and retention rights are approved: $($deniedSources -join ', ')."
            $cache.IsRefreshing = $false
            continue
        }
        if ($entry.Request) { continue }
        if ($entry.Profile.Path -and [System.IO.File]::Exists($entry.Profile.Path)) { continue }
        # Source terms set polling floors (e.g. Smithsonian GVP at most daily, EONET/GDACS every 15 minutes).
        $minimumMinutes = if ($entry.Profile.MinimumIntervalMinutes) { [double]$entry.Profile.MinimumIntervalMinutes } else { 5 }
        if (([datetime]::UtcNow - $cache.LastFetch).TotalMinutes -lt $minimumMinutes -or
            ([datetime]::UtcNow - $cache.LastAttempt).TotalMinutes -lt $minimumMinutes) { continue }
        $cache.LastAttempt = [datetime]::UtcNow
        $cache.IsRefreshing = $true
        $cache.Error = $null
        try {
            if (-not $State.Coordinator) { $State.Coordinator = New-RefreshCoordinator -MaxConcurrency 3 }
            $entry.Request = Start-RefreshRequest -Coordinator $State.Coordinator -Key $kind `
                -SourceId $kind -WorkerScript $State.Worker `
                -ArgumentList @($State.Definitions, $kind, $State.DataDirectory, $entry.Profile, @($cache.Data))
        }
        catch {
            $cache.IsRefreshing = $false
            Set-LiveMapRefreshFailure -Cache $cache -Message $_.Exception.Message
        }
    }
}

function Receive-LiveMapRefresh {
    [CmdletBinding()]
    param([Parameter(Mandatory)][hashtable]$State)

    foreach ($kind in $State.Entries.Keys) {
        $entry = $State.Entries[$kind]
        $cache = $entry.Cache
        if (-not $entry.Request -or -not $entry.Request.AsyncResult.IsCompleted -or
            ($entry.StopOperation -and -not $entry.StopOperation.IsCompleted)) { continue }
        try {
            try {
                if ($entry.StopOperation) { $entry.Request.PowerShell.EndStop($entry.StopOperation) }
            }
            finally { $completed = Receive-RefreshRequest -Request $entry.Request }
            if ($completed.status -eq 'cancelled') {
                $cache.LastAttempt = [datetime]::MinValue
            }
            elseif ($entry.Enabled) {
                if ($completed.status -ne 'completed') { throw "Map refresh ended with status '$($completed.status)'." }
                $result = $completed.result
                if (-not $result -or $result.Status -notin @('Fetched', 'Partial', 'Unavailable') -or
                    $result.LastFetch -isnot [datetime]) { throw 'Map refresh returned an invalid result.' }
                if ($result.Status -eq 'Unavailable') {
                    Set-LiveMapRefreshFailure -Cache $cache -Message $result.Error
                }
                elseif ($result.LastFetch -eq [datetime]::MinValue) {
                    throw 'Map refresh returned no successful acquisition timestamp.'
                }
                else {
                    $cache.Data = $result.Data
                    $cache.LastFetch = $result.LastFetch
                    $cache.Status = $result.Status
                    $cache.Error = $result.Error
                }
            }
        }
        catch { Set-LiveMapRefreshFailure -Cache $cache -Message $_.Exception.Message }
        finally {
            $entry.Request = $null
            $entry.StopOperation = $null
            $cache.IsRefreshing = $false
        }
        $kind
    }
}