Private/Application/HistoricalSeriesService.ps1

function Get-HistoricalRangeRequest {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNull()]
        [pscustomobject]$Capability,

        [Parameter(Mandatory)]
        [ValidateSet('1d', '1w', '1m', '3m', '6m', '1y', '5y', 'custom')]
        [string]$Range,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Interval,

        [Parameter(Mandatory)]
        [DateTimeOffset]$AsOfUtc,

        [Parameter()]
        [DateTimeOffset]$CustomStartUtc = [DateTimeOffset]::MinValue,

        [Parameter()]
        [DateTimeOffset]$CustomEndUtc = [DateTimeOffset]::MinValue
    )

    $endUtc = $AsOfUtc.ToUniversalTime()
    $startUtc = switch ($Range) {
        '1d' { $endUtc.AddDays(-1) }
        '1w' { $endUtc.AddDays(-7) }
        '1m' { $endUtc.AddMonths(-1) }
        '3m' { $endUtc.AddMonths(-3) }
        '6m' { $endUtc.AddMonths(-6) }
        '1y' { $endUtc.AddYears(-1) }
        '5y' { $endUtc.AddYears(-5) }
        'custom' {
            if ($CustomStartUtc -eq [DateTimeOffset]::MinValue -or
                $CustomEndUtc -eq [DateTimeOffset]::MinValue) {
                $null
            }
            else {
                $endUtc = $CustomEndUtc.ToUniversalTime()
                $CustomStartUtc.ToUniversalTime()
            }
        }
    }

    $reason = $null
    if ($null -eq $startUtc) {
        $reason = 'A custom range requires both start and end dates.'
    }
    elseif ($startUtc -ge $endUtc) {
        $reason = 'The range start must be earlier than its end.'
    }
    elseif ($null -ne $Capability.PSObject.Properties['IsSupported'] -and
        -not $Capability.IsSupported) {
        $reason = if ([string]::IsNullOrWhiteSpace([string]$Capability.Reason)) {
            'The provider reports no verified history coverage for this instrument.'
        }
        else {
            [string]$Capability.Reason
        }
    }
    elseif ($Interval -notin @($Capability.Intervals)) {
        $reason = "Interval '$Interval' is not supported for this instrument."
    }
    else {
        $capabilityStart = [DateTimeOffset]::Parse(
            [string]$Capability.HistoryStartUtc,
            [System.Globalization.CultureInfo]::InvariantCulture
        ).ToUniversalTime()
        $capabilityEnd = [DateTimeOffset]::Parse(
            [string]$Capability.HistoryEndUtc,
            [System.Globalization.CultureInfo]::InvariantCulture
        ).ToUniversalTime()
        if ($startUtc -lt $capabilityStart -or $endUtc -gt $capabilityEnd) {
            $reason = "Requested dates are outside the verified history bounds ($($capabilityStart.ToString('u')) to $($capabilityEnd.ToString('u')))."
        }
    }

    [pscustomobject][ordered]@{
        range = $Range
        startUtc = $startUtc
        endUtc = $endUtc
        interval = $Interval
        sourceId = [string]$Capability.SourceId
        upstreamSourceIds = @($Capability.UpstreamSourceIds)
        isSupported = [string]::IsNullOrWhiteSpace($reason)
        reason = $reason
    }
}

function Get-HistoricalSeriesCacheKey {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$SourceId,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$InstrumentId,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Interval,

        [Parameter(Mandatory)]
        [DateTimeOffset]$RangeStartUtc,

        [Parameter(Mandatory)]
        [DateTimeOffset]$RangeEndUtc
    )

    New-CacheKey -SourceId $SourceId -DataKind 'market-history' `
        -InstrumentId $InstrumentId -Interval $Interval `
        -RangeStartUtc $RangeStartUtc -RangeEndUtc $RangeEndUtc
}

function New-HistoricalSeries {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Instrument,

        [Parameter(Mandatory)]
        [pscustomobject]$Source,

        [Parameter(Mandatory)]
        [pscustomobject]$SourceRegister,

        [Parameter(Mandatory)]
        [pscustomobject]$Request,

        [Parameter()]
        [AllowEmptyCollection()]
        [object[]]$Observations = @(),

        [Parameter(Mandatory)]
        [DateTimeOffset]$NowUtc,

        [Parameter()]
        [switch]$IsCached,

        [Parameter()]
        [DateTimeOffset]$FetchedAtUtc = [DateTimeOffset]::MinValue,

        [Parameter()]
        [string]$StatusMessage
    )

    $reason = $null
    if (-not $Request.isSupported) {
        $reason = $Request.reason
    }
    elseif ($Request.sourceId -ne $Source.sourceId -or $Source.sourceId -notin @($Instrument.sourceIds)) {
        $reason = 'The requested source is not declared for this instrument.'
    }
    else {
        $displayDecision = Get-SourcePolicyDecision -Sources $SourceRegister.sources `
            -SourceId $Source.sourceId -Use display
        $persistenceDecision = Get-SourcePolicyDecision -Sources $SourceRegister.sources `
            -SourceId $Source.sourceId -Use persistence
        if (-not $displayDecision.allowed -or -not $persistenceDecision.allowed) {
            $reason = "Source rights do not permit historical display and persistence ($($displayDecision.reason ?? $persistenceDecision.reason))."
        }
    }

    $upstreamSourceIds = [System.Collections.Generic.List[string]]::new()
    $seenUpstreamSourceIds = [System.Collections.Generic.HashSet[string]]::new(
        [System.StringComparer]::OrdinalIgnoreCase
    )
    $upstreamCandidates = @($Request.upstreamSourceIds) + @(
        foreach ($observation in $Observations) {
            [string]$observation.upstreamSourceId
        }
    )
    foreach ($upstreamSourceId in $upstreamCandidates) {
        $upstreamSourceId = [string]$upstreamSourceId
        if (-not [string]::IsNullOrWhiteSpace($upstreamSourceId) -and
            $seenUpstreamSourceIds.Add($upstreamSourceId)) {
            $upstreamSourceIds.Add($upstreamSourceId)
        }
    }

    $upstreamSources = [System.Collections.Generic.List[object]]::new()
    foreach ($upstreamSourceId in $upstreamSourceIds) {
        $upstreamMatches = @($SourceRegister.sources | Where-Object sourceId -eq $upstreamSourceId)
        if ($upstreamMatches.Count -ne 1) {
            if (-not $reason) {
                $reason = "Upstream source '$upstreamSourceId' is unknown or ambiguous."
            }
            continue
        }
        $upstreamSource = $upstreamMatches[0]
        $upstreamSources.Add($upstreamSource)
        if (-not $reason) {
            $upstreamDisplayDecision = Get-SourcePolicyDecision -Sources $upstreamMatches `
                -SourceId $upstreamSourceId -Use display
            $upstreamPersistenceDecision = Get-SourcePolicyDecision -Sources $upstreamMatches `
                -SourceId $upstreamSourceId -Use persistence
            if (-not $upstreamDisplayDecision.allowed -or -not $upstreamPersistenceDecision.allowed) {
                $reason = "Upstream source '$upstreamSourceId' rights do not permit historical display and persistence."
            }
        }
    }

    $attributionParts = [System.Collections.Generic.List[string]]::new()
    foreach ($attribution in @(
            [string]$Source.attribution
            @($upstreamSources | ForEach-Object { [string]$_.attribution })
        )) {
        if (-not [string]::IsNullOrWhiteSpace($attribution)) {
            $attributionParts.Add($attribution)
        }
    }
    $seriesAttribution = @($attributionParts) -join '; '
    $upstreamSourceNames = @($upstreamSources | ForEach-Object { [string]$_.name })

    if ($reason) {
        return [pscustomobject][ordered]@{
            instrumentId = $Instrument.instrumentId
            symbol = $Instrument.symbol
            displayName = $Instrument.displayName
            quoteCurrency = $Instrument.quoteCurrency
            unit = $Instrument.unit
            isProxy = $Instrument.isProxy
            proxyFor = $Instrument.proxyFor
            sourceId = $Source.sourceId
            sourceName = $Source.name
            upstreamSourceIds = @($upstreamSources | ForEach-Object { [string]$_.sourceId })
            upstreamSourceNames = $upstreamSourceNames
            attribution = $seriesAttribution
            range = $Request.range
            startUtc = $Request.startUtc
            endUtc = $Request.endUtc
            interval = $Request.interval
            observations = @()
            gaps = @()
            status = 'unavailable'
            freshness = 'unavailable'
            reason = $reason
        }
    }

    $validObservations = [System.Collections.Generic.List[object]]::new()
    foreach ($observation in $Observations) {
        $observedAtUtc = [DateTimeOffset]::Parse(
            [string]$observation.observedAtUtc,
            [System.Globalization.CultureInfo]::InvariantCulture
        ).ToUniversalTime()
        if ($observation.instrumentId -ne $Instrument.instrumentId -or
            $observation.sourceId -ne $Source.sourceId -or
            $observation.interval -ne $Request.interval) {
            throw 'Historical observation identity or interval does not match the request.'
        }
        if ($observedAtUtc -ge $Request.startUtc -and $observedAtUtc -le $Request.endUtc) {
            $validObservations.Add($observation)
        }
    }

    $orderedObservations = @($validObservations | Sort-Object {
            [DateTimeOffset]::Parse(
                [string]$_.observedAtUtc,
                [System.Globalization.CultureInfo]::InvariantCulture
            ).ToUniversalTime()
        })
    $gaps = [System.Collections.Generic.List[object]]::new()
    if ($Request.interval -match '^(\d+)(m|h)$') {
        $unitLength = [int]$Matches[1]
        $step = if ($Matches[2] -eq 'm') {
            [TimeSpan]::FromMinutes($unitLength)
        }
        else {
            [TimeSpan]::FromHours($unitLength)
        }
        for ($index = 1; $index -lt $orderedObservations.Count; $index++) {
            $previousUtc = [DateTimeOffset]::Parse(
                [string]$orderedObservations[$index - 1].observedAtUtc,
                [System.Globalization.CultureInfo]::InvariantCulture
            ).ToUniversalTime()
            $currentUtc = [DateTimeOffset]::Parse(
                [string]$orderedObservations[$index].observedAtUtc,
                [System.Globalization.CultureInfo]::InvariantCulture
            ).ToUniversalTime()
            $missingIntervals = [int][math]::Floor(($currentUtc - $previousUtc).Ticks / $step.Ticks) - 1
            if ($missingIntervals -gt 0) {
                $gaps.Add([pscustomobject]@{
                    afterUtc = $previousUtc
                    beforeUtc = $currentUtc
                    missingIntervals = $missingIntervals
                })
            }
        }
    }

    $freshness = if ($IsCached.IsPresent -or
        @($orderedObservations | Where-Object freshness -eq 'cached').Count -gt 0) {
        'cached'
    }
    elseif (@($orderedObservations | Where-Object freshness -in @('partial', 'unavailable')).Count -gt 0) {
        'partial'
    }
    elseif (@($orderedObservations | Where-Object freshness -eq 'delayed').Count -gt 0) {
        'delayed'
    }
    else {
        'live'
    }
    $status = if ($gaps.Count -gt 0 -or $freshness -eq 'partial') {
        'partial'
    }
    elseif ($freshness -eq 'cached') {
        'cached'
    }
    elseif ($freshness -eq 'delayed') {
        'delayed'
    }
    elseif ($orderedObservations.Count -gt 0) {
        'live'
    }
    else {
        'unavailable'
    }
    $emptyReason = if ($orderedObservations.Count -eq 0) { 'No observations are available for the requested period.' } else { $null }
    if ($FetchedAtUtc -eq [DateTimeOffset]::MinValue -and $orderedObservations.Count -gt 0) {
        $retrievedAtValues = @($orderedObservations | Where-Object {
                $null -ne $_.PSObject.Properties['retrievedAtUtc']
            } | ForEach-Object {
                [DateTimeOffset]::Parse(
                    [string]$_.retrievedAtUtc,
                    [System.Globalization.CultureInfo]::InvariantCulture
                ).ToUniversalTime()
            })
        if ($retrievedAtValues.Count -gt 0) {
            $FetchedAtUtc = ($retrievedAtValues | Sort-Object -Descending | Select-Object -First 1)
        }
    }
    $effectiveFetchedAtUtc = if ($FetchedAtUtc -eq [DateTimeOffset]::MinValue) {
        $NowUtc.ToUniversalTime()
    }
    else {
        $FetchedAtUtc.ToUniversalTime()
    }

    [pscustomobject][ordered]@{
        instrumentId = $Instrument.instrumentId
        symbol = $Instrument.symbol
        displayName = $Instrument.displayName
        quoteCurrency = $Instrument.quoteCurrency
        unit = $Instrument.unit
        isProxy = $Instrument.isProxy
        proxyFor = $Instrument.proxyFor
        sourceId = $Source.sourceId
        sourceName = $Source.name
        upstreamSourceIds = @($upstreamSources | ForEach-Object { [string]$_.sourceId })
        upstreamSourceNames = $upstreamSourceNames
        attribution = $seriesAttribution
        range = $Request.range
        startUtc = $Request.startUtc
        endUtc = $Request.endUtc
        interval = $Request.interval
        observations = $orderedObservations
        gaps = @($gaps)
        status = if ($emptyReason) { 'unavailable' } else { $status }
        freshness = if ($emptyReason) { 'unavailable' } else { $freshness }
        reason = if ($emptyReason) { $emptyReason } else { $StatusMessage }
        retrievedAtUtc = $NowUtc.ToUniversalTime()
        fetchedAtUtc = $effectiveFetchedAtUtc
    }
}

function New-HistoricalCachedFallback {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Instrument,

        [Parameter(Mandatory)]
        [pscustomobject]$Source,

        [Parameter(Mandatory)]
        [pscustomobject]$SourceRegister,

        [Parameter(Mandatory)]
        [pscustomobject]$Request,

        [Parameter(Mandatory)]
        [pscustomobject]$Cache,

        [Parameter(Mandatory)]
        [DateTimeOffset]$NowUtc,

        [Parameter(Mandatory)]
        [ValidateSet('unavailable', 'failed')]
        [string]$RefreshOutcome
    )

    $refreshMessage = if ($RefreshOutcome -eq 'failed') { 'Refresh failed' } else { 'Refresh unavailable' }
    New-HistoricalSeries -Instrument $Instrument -Source $Source `
        -SourceRegister $SourceRegister -Request $Request `
        -Observations @($Cache.payload.observations) -NowUtc $NowUtc -IsCached `
        -FetchedAtUtc $Cache.fetchedAtUtc `
        -StatusMessage ("{0}; showing cached history last updated {1}." -f `
            $refreshMessage, $Cache.fetchedAtUtc.ToUniversalTime().ToString('yyyy-MM-dd HH:mm UTC'))
}

function Get-HistoricalSeries {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Store,

        [Parameter(Mandatory)]
        [pscustomobject]$Instrument,

        [Parameter(Mandatory)]
        [pscustomobject]$Capability,

        [Parameter(Mandatory)]
        [pscustomobject]$SourceRegister,

        [Parameter(Mandatory)]
        [pscustomobject]$Request,

        [Parameter()]
        [scriptblock]$Fetch,

        [Parameter(Mandatory)]
        [DateTimeOffset]$NowUtc,

        [Parameter()]
        [ValidateScript({ $_ -gt [TimeSpan]::Zero })]
        [TimeSpan]$CacheTtl = [TimeSpan]::FromMinutes(15)
    )

    $requiredSourceIds = @([string]$Capability.SourceId) + @($Capability.UpstreamSourceIds)
    $requiredSources = [System.Collections.Generic.List[object]]::new()
    foreach ($requiredSourceId in @($requiredSourceIds | Select-Object -Unique)) {
        $matches = @($SourceRegister.sources | Where-Object { $_.sourceId -eq $requiredSourceId })
        if ($matches.Count -ne 1) {
            $source = [pscustomobject]@{
                sourceId = [string]$Capability.SourceId
                name = [string]$Capability.SourceId
                attribution = ''
            }
            return New-HistoricalSeries -Instrument $Instrument -Source $source `
                -SourceRegister $SourceRegister -Request $Request -NowUtc $NowUtc
        }
        $requiredSources.Add($matches[0])
    }
    $sourceMatches = @($requiredSources | Where-Object sourceId -eq $Capability.SourceId)
    if ($sourceMatches.Count -ne 1) {
        $source = [pscustomobject]@{
            sourceId = [string]$Capability.SourceId
            name = [string]$Capability.SourceId
            attribution = ''
        }
        return New-HistoricalSeries -Instrument $Instrument -Source $source `
            -SourceRegister $SourceRegister -Request $Request -NowUtc $NowUtc
    }
    $source = $sourceMatches[0]

    $sourceRightsAllowed = $true
    foreach ($requiredSource in $requiredSources) {
        $displayDecision = Get-SourcePolicyDecision -Sources @($requiredSource) `
            -SourceId $requiredSource.sourceId -Use display
        $persistenceDecision = Get-SourcePolicyDecision -Sources @($requiredSource) `
            -SourceId $requiredSource.sourceId -Use persistence
        if (-not $displayDecision.allowed -or -not $persistenceDecision.allowed) {
            $sourceRightsAllowed = $false
            break
        }
    }
    if (-not $Request.isSupported -or -not $sourceRightsAllowed -or
        $source.sourceId -notin @($Instrument.sourceIds)) {
        $blockedRequest = $Request
        if ($Request.isSupported -and -not $sourceRightsAllowed) {
            $blockedRequest = $Request.PSObject.Copy()
            $blockedRequest.isSupported = $false
            $blockedRequest.reason = 'Source or upstream source rights do not permit historical display and persistence.'
        }
        return New-HistoricalSeries -Instrument $Instrument -Source $source `
            -SourceRegister $SourceRegister -Request $blockedRequest -NowUtc $NowUtc
    }

    $cacheKey = Get-HistoricalSeriesCacheKey -SourceId $source.sourceId `
        -InstrumentId $Instrument.instrumentId -Interval $Request.interval `
        -RangeStartUtc $Request.startUtc -RangeEndUtc $Request.endUtc
    $cache = Get-CacheRecord -Store $Store -CacheKey $cacheKey -Source $source -NowUtc $NowUtc
    $staleCache = if ($cache.status -eq 'expired' -and $cache.payload.observations) { $cache } else { $null }
    if ($cache.status -eq 'cached' -and $cache.payload.observations) {
        return New-HistoricalSeries -Instrument $Instrument -Source $source `
            -SourceRegister $SourceRegister -Request $Request `
            -Observations @($cache.payload.observations) -NowUtc $NowUtc -IsCached `
            -FetchedAtUtc $cache.fetchedAtUtc `
            -StatusMessage ("Using cached history; last updated {0}." -f $cache.fetchedAtUtc.ToUniversalTime().ToString('yyyy-MM-dd HH:mm UTC'))
    }

    if (-not $Fetch) {
        if ($null -ne $staleCache) {
            return New-HistoricalCachedFallback -Instrument $Instrument -Source $source `
                -SourceRegister $SourceRegister -Request $Request -Cache $staleCache `
                -NowUtc $NowUtc -RefreshOutcome unavailable
        }
        return New-HistoricalSeries -Instrument $Instrument -Source $source `
            -SourceRegister $SourceRegister -Request $Request -NowUtc $NowUtc
    }

    try {
        $observations = @(& $Fetch $Request)
    }
    catch {
        if ($null -ne $staleCache) {
            return New-HistoricalCachedFallback -Instrument $Instrument -Source $source `
                -SourceRegister $SourceRegister -Request $Request -Cache $staleCache `
                -NowUtc $NowUtc -RefreshOutcome failed
        }
        throw
    }
    $series = New-HistoricalSeries -Instrument $Instrument -Source $source `
        -SourceRegister $SourceRegister -Request $Request -Observations $observations -NowUtc $NowUtc
    if ($series.status -notin @('live', 'delayed', 'partial') -or $observations.Count -eq 0) {
        if ($null -ne $staleCache) {
            return New-HistoricalCachedFallback -Instrument $Instrument -Source $source `
                -SourceRegister $SourceRegister -Request $Request -Cache $staleCache `
                -NowUtc $NowUtc -RefreshOutcome unavailable
        }
        return $series
    }

    $sourceTimestampUtc = ($observations | Sort-Object {
            [DateTimeOffset]::Parse(
                [string]$_.observedAtUtc,
                [System.Globalization.CultureInfo]::InvariantCulture
            )
        } -Descending | Select-Object -First 1).observedAtUtc
    Set-CacheRecord -Store $Store -CacheKey $cacheKey -Source $source `
        -Payload @{ observations = $observations } -FetchedAtUtc $NowUtc `
        -SourceTimestampUtc ([DateTimeOffset]$sourceTimestampUtc) `
        -ExpiresAtUtc $NowUtc.Add($CacheTtl) -PayloadVersion '1' `
        -Freshness $series.freshness
    $series
}