Private/Application/DashboardMarketRefresh.ps1
|
function New-DashboardMarketRefreshState { [CmdletBinding()] param( [Parameter(Mandatory)] [string]$Definitions, [Parameter(Mandatory)] [hashtable]$Caches, [Parameter(Mandatory)] [pscustomobject]$SourceRegister, [Parameter()] [switch]$UseFixtureData ) $profiles = @{ FX = @{ Command = 'Invoke-ForexFetch'; CacheName = 'fxCache'; Minutes = 10; Source = 'Frankfurter / ECB'; SourceId = 'forex-reference'; RightsSourceIds = @('frankfurter', 'ecb-reference-rates', 'alpha-vantage'); Expected = 0; IntervalSeconds = 0 } Crypto = @{ Command = 'Invoke-CryptoFetch'; CacheName = 'cryptoCache'; Minutes = 15; Source = 'CoinMarketCap Basic'; SourceId = 'coinmarketcap-basic'; RightsSourceIds = @('coinmarketcap-basic'); Expected = 10; IntervalSeconds = 900 } Indices = @{ Command = 'Invoke-IndicesFetch'; CacheName = 'indicesCache'; Minutes = 60; Source = 'FRED (St. Louis Fed)'; SourceId = 'fred'; RightsSourceIds = @('fred', 'alpha-vantage'); Expected = 8; IntervalSeconds = 0 } Commodities = @{ Command = 'Invoke-CommoditiesFetch'; CacheName = 'commoditiesCache'; Minutes = 60; Source = 'FRED (St. Louis Fed)'; SourceId = 'fred'; RightsSourceIds = @('fred', 'ecb-reference-rates'); Expected = 10; IntervalSeconds = 0 } } $entries = @{} foreach ($kind in $profiles.Keys) { if ($Caches[$kind] -isnot [hashtable]) { throw "A market cache is required for '$kind'." } $cache = $Caches[$kind] $cache.Key = $null $cache.LastAttempt = [datetime]::MinValue $cache.Status = 'Unavailable' $cache.IsRefreshing = $false $cache.Error = $null $cache.RetryAtUtc = $null $entries[$kind] = [pscustomobject]@{ Profile = $profiles[$kind] Cache = $cache DesiredKey = $null RequestKey = $null Request = $null StopOperation = $null } } @{ Definitions = $Definitions SourceRegister = $SourceRegister UseFixtureData = $UseFixtureData.IsPresent Coordinator = $null Entries = $entries Worker = { param($definitions, $command, $cacheName, $arguments, $expectedCount) . ([scriptblock]::Create($definitions)) $cache = @{ Data = $null; LastFetch = [datetime]::MinValue; Currency = $null } Set-Variable -Name $cacheName -Scope Script -Value $cache try { $data = & $command @arguments $count = if ($command -eq 'Invoke-ForexFetch') { @($data.Rates).Count } else { @($data).Count } if (-not $data -or $count -eq 0) { throw 'The source returned no usable data; check provider health, credentials and quota.' } $message = $null if ($expectedCount -gt 0 -and $count -lt $expectedCount) { $message = "Only $count of $expectedCount requested instruments were returned." } if ($command -eq 'Invoke-CommoditiesFetch' -and $cache.Currency -ne $arguments[1]) { $message = "Requested currency unavailable; prices are shown in $($cache.Currency)." } [pscustomobject]@{ Data = $data LastFetch = $cache.LastFetch Currency = $cache.Currency Status = $(if ($message) { 'Partial' } else { 'Fetched' }) Error = $message } } catch { [pscustomobject]@{ Data = $null; LastFetch = [datetime]::MinValue; Currency = $null Status = 'Unavailable' Error = ConvertTo-SanitizedDiagnosticText -Text $_.Exception.Message -SensitiveValues @($arguments) } } } } } function Initialize-DashboardMarketFixtureData { [CmdletBinding()] param( [Parameter(Mandatory)] [hashtable]$State ) $now = [datetime]::Now $fixtures = @{ FX = [pscustomobject]@{ Base = 'USD' Date = $now.ToString('yyyy-MM-dd') Rates = @( [pscustomobject]@{ Currency = 'EUR'; Rate = 0.92; Source = 'TEST FIXTURE' } [pscustomobject]@{ Currency = 'GBP'; Rate = 0.79; Source = 'TEST FIXTURE' } [pscustomobject]@{ Currency = 'JPY'; Rate = 149.25; Source = 'TEST FIXTURE' } [pscustomobject]@{ Currency = 'CAD'; Rate = 1.36; Source = 'TEST FIXTURE' } ) } Crypto = @( [pscustomobject]@{ Symbol = 'BTC'; Name = 'Bitcoin'; Price = 67250.00; Change24h = 1.8; MarketCap = 1320000000000 } [pscustomobject]@{ Symbol = 'ETH'; Name = 'Ethereum'; Price = 3525.50; Change24h = -0.6; MarketCap = 423000000000 } [pscustomobject]@{ Symbol = 'SOL'; Name = 'Solana'; Price = 148.20; Change24h = 2.4; MarketCap = 68000000000 } ) Indices = @( [pscustomobject]@{ Symbol = 'SP500'; Name = 'S&P 500'; Price = 5520.25; Change = 0.7; AsOf = $now.ToString('yyyy-MM-dd') } [pscustomobject]@{ Symbol = 'DJIA'; Name = 'Dow Jones Industrial Average'; Price = 39010.10; Change = 0.3; AsOf = $now.ToString('yyyy-MM-dd') } [pscustomobject]@{ Symbol = 'NASDAQCOM'; Name = 'NASDAQ Composite'; Price = 17447.80; Change = 1.1; AsOf = $now.ToString('yyyy-MM-dd') } [pscustomobject]@{ Symbol = 'NIKKEI225'; Name = 'Nikkei 225'; Price = 38790.40; Change = -0.2; AsOf = $now.ToString('yyyy-MM-dd') } ) Commodities = @( [pscustomobject]@{ Symbol = 'DCOILWTICO'; Name = 'Crude Oil WTI (daily, per barrel)'; Price = 78.30; Change = -0.4; Currency = 'USD'; AsOf = $now.ToString('yyyy-MM-dd') } [pscustomobject]@{ Symbol = 'DCOILBRENTEU'; Name = 'Crude Oil Brent (daily, per barrel)'; Price = 82.10; Change = -0.3; Currency = 'USD'; AsOf = $now.ToString('yyyy-MM-dd') } [pscustomobject]@{ Symbol = 'DHHNGSP'; Name = 'Natural Gas Henry Hub (daily, per MMBtu)'; Price = 2.85; Change = 1.2; Currency = 'USD'; AsOf = $now.ToString('yyyy-MM-dd') } [pscustomobject]@{ Symbol = 'PCOPPUSDM'; Name = 'Copper (monthly, per tonne)'; Price = 9450.00; Change = 0.5; Currency = 'USD'; AsOf = $now.ToString('yyyy-MM-01') } [pscustomobject]@{ Symbol = 'PWHEAMTUSDM'; Name = 'Wheat (monthly, per tonne)'; Price = 240.50; Change = -0.1; Currency = 'USD'; AsOf = $now.ToString('yyyy-MM-01') } ) } foreach ($kind in $fixtures.Keys) { $cache = $State.Entries[$kind].Cache $cache.Data = $fixtures[$kind] $cache.LastFetch = $now $cache.Status = 'Fixture' $cache.IsRefreshing = $false $cache.Error = $null if ($kind -eq 'Commodities') { $cache.Currency = 'USD' } } } function Set-DashboardMarketRefreshFailure { [CmdletBinding()] param( [Parameter(Mandatory)] [hashtable]$Cache, [Parameter(Mandatory)] [string]$Message, [string[]]$SensitiveValues = @() ) $Cache.Status = if ($Cache.Data) { 'Cached' } else { 'Unavailable' } $Cache.Error = ConvertTo-SanitizedDiagnosticText -Text $Message -SensitiveValues $SensitiveValues Write-Verbose "Market refresh failed: $($Cache.Error)" } function Get-MarketQuoteObservationSummary { [CmdletBinding()] param( [AllowEmptyCollection()][object[]]$Quotes = @(), [datetimeoffset]$NowUtc = [datetimeoffset]::UtcNow, [ValidateRange(1, 1440)][int]$StaleAfterMinutes = 30 ) $observed = [System.Collections.Generic.List[datetimeoffset]]::new() $missing = 0 $stale = 0 $labels = @( foreach ($quote in $Quotes) { $observedAt = $quote.ObservedAtUtc if ($null -eq $observedAt) { $missing++ [pscustomobject]@{ State = 'missing'; Text = 'Provider observation time: missing' } continue } $observedAt = [datetimeoffset]$observedAt $observed.Add($observedAt) $isStale = ($NowUtc - $observedAt).TotalMinutes -gt $StaleAfterMinutes if ($isStale) { $stale++ } [pscustomobject]@{ State = if ($isStale) { 'stale' } else { 'fresh' } Text = "Provider observation time: $($observedAt.UtcDateTime.ToString('yyyy-MM-dd HH:mm')) UTC$(if ($isStale) { ' (stale)' })" } } ) $parts = @( if ($observed.Count) { $newest = ($observed | Measure-Object -Property UtcTicks -Maximum).Maximum "Observed: $([datetime]::new([long]$newest, [System.DateTimeKind]::Utc).ToString('HH:mm')) UTC" } if ($stale) { "$stale stale quote(s) older than $StaleAfterMinutes min" } if ($missing) { "$missing quote(s) without provider timestamp" } ) [pscustomobject]@{ Text = if ($parts.Count) { $parts -join ' | ' } else { 'Observed: no quotes' } Labels = $labels MissingCount = $missing StaleCount = $stale } } function Get-DashboardMarketData { [CmdletBinding()] param( [Parameter(Mandatory)] [hashtable]$State, [Parameter(Mandatory)] [ValidateSet('FX', 'Crypto', 'Indices', 'Commodities')] [string]$Kind, [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string]$Key, [object[]]$ArgumentList = @() ) $entry = $State.Entries[$Kind] $cache = $entry.Cache if ($State.UseFixtureData) { return $cache.Data } $eligibleSourceIds = [System.Collections.Generic.List[string]]::new() $sourceFailures = @{} foreach ($sourceId in $entry.Profile.RightsSourceIds) { $displayDecision = Get-SourcePolicyDecision -Sources $State.SourceRegister.sources ` -SourceId $sourceId -Use display $persistenceDecision = Get-SourcePolicyDecision -Sources $State.SourceRegister.sources ` -SourceId $sourceId -Use persistence if ($displayDecision.allowed -and $persistenceDecision.allowed) { $eligibleSourceIds.Add($sourceId) } else { $sourceFailures[$sourceId] = "$sourceId ($($displayDecision.reason ?? $persistenceDecision.reason))" } } $requiredSourceIds = switch ($Kind) { 'FX' { @() } 'Commodities' { @('fred') } 'Indices' { @('fred') } default { @($entry.Profile.RightsSourceIds) } } $deniedSources = @($requiredSourceIds | Where-Object { $_ -notin $eligibleSourceIds } | ForEach-Object { if ($sourceFailures.ContainsKey($_)) { $sourceFailures[$_] } else { "$_ (source-unknown)" } }) if (($Kind -eq 'FX' -and $eligibleSourceIds.Count -eq 0) -or $deniedSources.Count -gt 0) { if ($Kind -eq 'FX' -and $eligibleSourceIds.Count -eq 0) { $deniedSources = @($sourceFailures.Values) } $cache.Data = $null $cache.LastFetch = [datetime]::MinValue $cache.Status = 'Unavailable' $cache.Error = "Source data is unavailable and cached values are cleared because required rights are not approved: $($deniedSources -join ', ')." $cache.IsRefreshing = $false return $null } if ($entry.DesiredKey -ne $Key) { $entry.DesiredKey = $Key $cache.Key = $Key $cache.Data = $null $cache.LastFetch = [datetime]::MinValue $cache.LastAttempt = [datetime]::MinValue $cache.Status = 'Unavailable' $cache.Error = $null $cache.RetryAtUtc = $null 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-DashboardMarketRefreshFailure -Cache $cache -Message $_.Exception.Message } } } if ($entry.Request) { return $cache.Data } if ($cache.Data -and ([datetime]::Now - $cache.LastFetch).TotalMinutes -lt $entry.Profile.Minutes) { return $cache.Data } if (([datetime]::Now - $cache.LastAttempt).TotalMinutes -lt 1) { return $cache.Data } $cache.Status = if ($cache.Data) { 'Cached' } else { 'Unavailable' } $lastStarted = if ($State.Coordinator) { $State.Coordinator.LastStartedBySource[$entry.Profile.SourceId] } else { $null } if ($lastStarted -and $entry.Profile.IntervalSeconds -gt 0) { $retryAt = $lastStarted.AddSeconds($entry.Profile.IntervalSeconds) if ([datetimeoffset]::UtcNow -lt $retryAt) { $cache.RetryAtUtc = $retryAt return $cache.Data } } $cache.RetryAtUtc = $null $cache.LastAttempt = [datetime]::Now $cache.IsRefreshing = $true $cache.Error = $null try { if (-not $State.Coordinator) { $State.Coordinator = New-RefreshCoordinator -MaxConcurrency 2 } $workerArguments = @($ArgumentList) if ($Kind -in @('FX', 'Commodities', 'Indices')) { # Pass the eligible source list as one array argument; += would flatten it into positional values. $workerArguments += , @($eligibleSourceIds) } $entry.RequestKey = $Key $entry.Request = Start-RefreshRequest -Coordinator $State.Coordinator -Key "$Kind`:$Key" ` -SourceId $entry.Profile.SourceId -WorkerScript $State.Worker ` -ArgumentList @($State.Definitions, $entry.Profile.Command, $entry.Profile.CacheName, $workerArguments, $entry.Profile.Expected) } catch { $cache.IsRefreshing = $false Set-DashboardMarketRefreshFailure -Cache $cache -Message $_.Exception.Message -SensitiveValues @($ArgumentList) } return $cache.Data } function Receive-DashboardMarketRefresh { [CmdletBinding()] param( [Parameter(Mandatory)] [hashtable]$State ) foreach ($kind in $State.Entries.Keys) { $entry = $State.Entries[$kind] $cache = $entry.Cache if (-not $entry.Request) { if ($cache.RetryAtUtc -and [datetimeoffset]::UtcNow -ge $cache.RetryAtUtc) { $cache.RetryAtUtc = $null $kind } continue } if (-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 ($entry.RequestKey -eq $entry.DesiredKey) { if ($completed.status -ne 'completed') { throw "Market 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 'Market refresh returned an invalid result.' } if ($result.Status -eq 'Unavailable') { Set-DashboardMarketRefreshFailure -Cache $cache -Message $result.Error } elseif (-not $result.Data -or $result.LastFetch -eq [datetime]::MinValue) { throw 'Market refresh returned no timestamped data.' } else { $cache.Data = $result.Data $cache.LastFetch = $result.LastFetch $cache.Currency = $result.Currency $cache.Status = $result.Status $cache.Error = $result.Error } } } catch { if ($entry.RequestKey -eq $entry.DesiredKey) { Set-DashboardMarketRefreshFailure -Cache $cache -Message $_.Exception.Message } } finally { $entry.Request = $null $entry.StopOperation = $null $cache.IsRefreshing = $false } $kind } } |