Private/Persistence/CacheStore.ps1

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

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

        [Parameter()]
        [string]$InstrumentId,

        [Parameter()]
        [string]$Interval,

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

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

    if (($null -eq $RangeStartUtc) -ne ($null -eq $RangeEndUtc)) {
        throw 'Cache range start and end must be specified together.'
    }

    if ($null -ne $RangeStartUtc -and $RangeStartUtc -gt $RangeEndUtc) {
        throw 'Cache range start must not be later than its end.'
    }

    $startTicks = if ($null -eq $RangeStartUtc) { '' } else { $RangeStartUtc.ToUniversalTime().Ticks }
    $endTicks = if ($null -eq $RangeEndUtc) { '' } else { $RangeEndUtc.ToUniversalTime().Ticks }
    $normalizedInstrumentId = if ([string]::IsNullOrWhiteSpace($InstrumentId)) { '' } else { $InstrumentId.ToLowerInvariant() }
    $normalizedInterval = if ([string]::IsNullOrWhiteSpace($Interval)) { '' } else { $Interval.ToLowerInvariant() }
    $identity = '{0}|{1}|{2}|{3}|{4}|{5}' -f `
        $SourceId.ToLowerInvariant(), $DataKind.ToLowerInvariant(),
        $normalizedInstrumentId, $normalizedInterval, $startTicks, $endTicks
    $hasher = [System.Security.Cryptography.SHA256]::Create()
    try {
        $digest = $hasher.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($identity))
    }
    finally {
        $hasher.Dispose()
    }

    [System.BitConverter]::ToString($digest).Replace('-', '').ToLowerInvariant()
}

function New-CacheStore {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Directory,

        [Parameter()]
        [ValidateRange(1, 100000)]
        [int]$MaximumEntries = 1000,

        [Parameter()]
        [ValidateRange(1024, 1073741824)]
        [long]$MaximumBytes = 104857600
    )

    $resolvedDirectory = [System.IO.Path]::GetFullPath($Directory)
    [void][System.IO.Directory]::CreateDirectory($resolvedDirectory)

    [pscustomobject]@{
        Directory = $resolvedDirectory
        MaximumEntries = $MaximumEntries
        MaximumBytes = $MaximumBytes
        SyncRoot = [object]::new()
    }
}

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

        [Parameter(Mandatory)]
        [ValidatePattern('^[a-fA-F0-9]{64}$')]
        [string]$CacheKey
    )

    Join-Path $Store.Directory "$($CacheKey.ToLowerInvariant()).json"
}

function Test-CachePayloadSafe {
    [CmdletBinding()]
    param(
        [Parameter()]
        [AllowNull()]
        [object]$Payload,

        [Parameter()]
        [ValidateRange(0, 32)]
        [int]$Depth = 0
    )

    if ($Depth -gt 16) {
        return $false
    }

    if ($null -eq $Payload) {
        return $true
    }

    $payloadType = $Payload.GetType()
    if ($Payload -is [string] -or $payloadType.IsPrimitive -or
        $Payload -is [decimal] -or $Payload -is [DateTime] -or
        $Payload -is [DateTimeOffset] -or $Payload -is [Guid] -or
        $Payload -is [enum]) {
        return $true
    }

    if ($Payload -is [System.Collections.IDictionary]) {
        foreach ($entry in $Payload.GetEnumerator()) {
            if ($entry.Key -match '(?i)(credential|api.?key|password|token|secret|portfolio.?transaction)' -or
                -not (Test-CachePayloadSafe -Payload $entry.Value -Depth ($Depth + 1))) {
                return $false
            }
        }

        return $true
    }

    if ($Payload -is [System.Collections.IEnumerable]) {
        foreach ($item in $Payload) {
            if (-not (Test-CachePayloadSafe -Payload $item -Depth ($Depth + 1))) {
                return $false
            }
        }

        return $true
    }

    if ($Payload -is [pscustomobject]) {
        foreach ($property in $Payload.PSObject.Properties) {
            if ($property.Name -match '(?i)(credential|api.?key|password|token|secret|portfolio.?transaction)' -or
                $property.MemberType -notin @('NoteProperty', 'AliasProperty') -or
                -not (Test-CachePayloadSafe -Payload $property.Value -Depth ($Depth + 1))) {
                return $false
            }
        }

        return $true
    }

    return $false
}

function Test-CachePermission {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Source
    )

    $decision = Get-SourcePolicyDecision -Sources @($Source) `
        -SourceId $Source.sourceId -Use persistence
    return [bool]$decision.allowed
}

function Set-CacheRecord {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Store,

        [Parameter(Mandatory)]
        [ValidatePattern('^[a-fA-F0-9]{64}$')]
        [string]$CacheKey,

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

        [Parameter(Mandatory)]
        [AllowNull()]
        [object]$Payload,

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

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

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

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

        [Parameter()]
        [ValidateSet('live', 'delayed', 'partial')]
        [string]$Freshness = 'live'
    )

    if (-not (Test-CachePermission -Source $Source)) {
        throw "Source '$($Source.sourceId)' is not approved for caching."
    }

    if (-not (Test-CachePayloadSafe -Payload $Payload)) {
        throw 'Cache payload contains a prohibited field or unsupported object.'
    }

    if ($ExpiresAtUtc -le $FetchedAtUtc) {
        throw 'Cache expiry must be later than the fetch time.'
    }

    $envelope = [ordered]@{
        cacheKey = $CacheKey.ToLowerInvariant()
        sourceId = $Source.sourceId
        fetchedAtUtc = $FetchedAtUtc.ToUniversalTime().ToString('o', [System.Globalization.CultureInfo]::InvariantCulture)
        sourceTimestampUtc = $SourceTimestampUtc.ToUniversalTime().ToString('o', [System.Globalization.CultureInfo]::InvariantCulture)
        expiresAtUtc = $ExpiresAtUtc.ToUniversalTime().ToString('o', [System.Globalization.CultureInfo]::InvariantCulture)
        rightsDecision = 'approved:cache'
        payloadVersion = $PayloadVersion
        freshness = $Freshness
        payload = $Payload
    }
    $json = ConvertTo-Json -InputObject $envelope -Depth 32 -Compress
    $encoding = [System.Text.UTF8Encoding]::new($false)
    $byteCount = $encoding.GetByteCount($json)
    if ($byteCount -gt $Store.MaximumBytes) {
        throw "Cache record exceeds the configured maximum of $($Store.MaximumBytes) bytes."
    }

    $destination = Get-CacheRecordPath -Store $Store -CacheKey $CacheKey
    $temporaryPath = "$destination.$([guid]::NewGuid().ToString('N')).tmp"
    [System.Threading.Monitor]::Enter($Store.SyncRoot)
    try {
        try {
            [System.IO.File]::WriteAllText($temporaryPath, $json, $encoding)
            Move-Item -LiteralPath $temporaryPath -Destination $destination -Force
        }
        finally {
            if (Test-Path -LiteralPath $temporaryPath) {
                Remove-Item -LiteralPath $temporaryPath -Force
            }
        }

        $files = @(Get-ChildItem -LiteralPath $Store.Directory -File -Filter '*.json' |
            Sort-Object LastWriteTimeUtc)
        $totalBytes = ($files | Measure-Object -Property Length -Sum).Sum
        while ($files.Count -gt $Store.MaximumEntries -or $totalBytes -gt $Store.MaximumBytes) {
            $victim = $files | Where-Object { $_.FullName -ne $destination } | Select-Object -First 1
            if ($null -eq $victim) {
                throw 'Cache bounds cannot be satisfied without evicting the newly written record.'
            }

            Remove-Item -LiteralPath $victim.FullName -Force
            $files = @(Get-ChildItem -LiteralPath $Store.Directory -File -Filter '*.json' |
                Sort-Object LastWriteTimeUtc)
            $totalBytes = ($files | Measure-Object -Property Length -Sum).Sum
        }
    }
    finally {
        [System.Threading.Monitor]::Exit($Store.SyncRoot)
    }
}

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

        [Parameter(Mandatory)]
        [ValidatePattern('^[a-fA-F0-9]{64}$')]
        [string]$CacheKey,

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

        [Parameter()]
        [DateTimeOffset]$NowUtc = [DateTimeOffset]::UtcNow
    )

    if (-not (Test-CachePermission -Source $Source)) {
        return [pscustomobject]@{ status = 'denied'; payload = $null }
    }

    $path = Get-CacheRecordPath -Store $Store -CacheKey $CacheKey
    if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
        return [pscustomobject]@{ status = 'miss'; payload = $null }
    }

    [System.Threading.Monitor]::Enter($Store.SyncRoot)
    try {
        $envelope = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json -AsHashtable -Depth 32
    }
    finally {
        [System.Threading.Monitor]::Exit($Store.SyncRoot)
    }

    foreach ($requiredField in @('cacheKey', 'sourceId', 'fetchedAtUtc', 'sourceTimestampUtc', 'expiresAtUtc', 'rightsDecision', 'payloadVersion', 'freshness', 'payload')) {
        if (-not $envelope.ContainsKey($requiredField)) {
            throw "Cache record is missing required field '$requiredField'."
        }
    }

    if ($envelope.cacheKey -ne $CacheKey.ToLowerInvariant() -or
        $envelope.sourceId -ne $Source.sourceId -or
        $envelope.rightsDecision -ne 'approved:cache') {
        throw 'Cache record identity or rights metadata does not match the request.'
    }

    if (-not (Test-CachePayloadSafe -Payload $envelope.payload)) {
        throw 'Cache record contains a prohibited field or unsupported object.'
    }

    $expiresAtUtc = [DateTimeOffset]::Parse(
        [string]$envelope.expiresAtUtc,
        [System.Globalization.CultureInfo]::InvariantCulture,
        [System.Globalization.DateTimeStyles]::RoundtripKind
    )
    $isExpired = $NowUtc.ToUniversalTime() -ge $expiresAtUtc

    [pscustomobject][ordered]@{
        status = if ($isExpired) { 'expired' } else { 'cached' }
        freshness = 'cached'
        isExpired = $isExpired
        cacheKey = $envelope.cacheKey
        sourceId = $envelope.sourceId
        fetchedAtUtc = [DateTimeOffset]::Parse(
            [string]$envelope.fetchedAtUtc,
            [System.Globalization.CultureInfo]::InvariantCulture,
            [System.Globalization.DateTimeStyles]::RoundtripKind
        )
        sourceTimestampUtc = [DateTimeOffset]::Parse(
            [string]$envelope.sourceTimestampUtc,
            [System.Globalization.CultureInfo]::InvariantCulture,
            [System.Globalization.DateTimeStyles]::RoundtripKind
        )
        expiresAtUtc = $expiresAtUtc
        rightsDecision = $envelope.rightsDecision
        payloadVersion = $envelope.payloadVersion
        originalFreshness = $envelope.freshness
        payload = $envelope.payload
    }
}