Private/Application/RefreshCoordinator.ps1

function Test-RefreshPlainData {
    [CmdletBinding()]
    param(
        [Parameter()]
        [AllowNull()]
        [object]$Value,

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

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

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

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

    if ($Value -is [System.Collections.IDictionary]) {
        foreach ($entry in $Value.GetEnumerator()) {
            if (-not (Test-RefreshPlainData -Value $entry.Key -Depth ($Depth + 1)) -or
                -not (Test-RefreshPlainData -Value $entry.Value -Depth ($Depth + 1))) {
                return $false
            }
        }

        return $true
    }

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

        return $true
    }

    if ($Value -is [pscustomobject]) {
        foreach ($property in $Value.PSObject.Properties) {
            if ($property.MemberType -notin @('NoteProperty', 'AliasProperty') -or
                -not (Test-RefreshPlainData -Value $property.Value -Depth ($Depth + 1))) {
                return $false
            }
        }

        return $true
    }

    return $false
}

function New-RefreshCoordinator {
    [CmdletBinding()]
    param(
        [Parameter()]
        [ValidateRange(1, 64)]
        [int]$MaxConcurrency = 5,

        [Parameter()]
        [ValidateRange(0, 600000)]
        [int]$MinimumSourceIntervalMilliseconds = 0
    )

    $runspacePool = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspacePool(
        1,
        $MaxConcurrency
    )
    $runspacePool.Open()

    [pscustomobject]@{
        RunspacePool = $runspacePool
        MaxConcurrency = $MaxConcurrency
        MinimumSourceIntervalMilliseconds = $MinimumSourceIntervalMilliseconds
        InFlight = @{}
        LastStartedBySource = @{}
        SyncRoot = [object]::new()
        IsDisposed = $false
    }
}

function Start-RefreshRequest {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Coordinator,

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

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

        [Parameter(Mandatory)]
        [scriptblock]$WorkerScript,

        [Parameter()]
        [AllowEmptyCollection()]
        [object[]]$ArgumentList = @()
    )

    if ($Coordinator.IsDisposed) {
        throw 'Refresh coordinator has been disposed.'
    }

    if (-not (Test-RefreshPlainData -Value $ArgumentList)) {
        throw 'Refresh arguments must contain plain data only; WPF controls and dispatcher objects are not allowed.'
    }

    [System.Threading.Monitor]::Enter($Coordinator.SyncRoot)
    try {
        if ($Coordinator.IsDisposed) {
            throw 'Refresh coordinator has been disposed.'
        }

        $existing = $Coordinator.InFlight[$Key]
        if ($null -ne $existing) {
            if (-not $existing.AsyncResult.IsCompleted) {
                return $existing
            }

            $Coordinator.InFlight.Remove($Key)
        }

        $nowUtc = [DateTimeOffset]::UtcNow
        $lastStartedUtc = $Coordinator.LastStartedBySource[$SourceId]
        if ($Coordinator.MinimumSourceIntervalMilliseconds -gt 0 -and
            $null -ne $lastStartedUtc -and
            ($nowUtc - $lastStartedUtc).TotalMilliseconds -lt $Coordinator.MinimumSourceIntervalMilliseconds) {
            throw "Refresh for source '$SourceId' is throttled."
        }

        $powerShell = [System.Management.Automation.PowerShell]::Create()
        $powerShell.RunspacePool = $Coordinator.RunspacePool
        [void]$powerShell.AddScript($WorkerScript.ToString())
        foreach ($argument in $ArgumentList) {
            [void]$powerShell.AddArgument($argument)
        }

        $started = $false
        try {
            $asyncResult = $powerShell.BeginInvoke()
            $started = $true
        }
        finally {
            if (-not $started) {
                $powerShell.Dispose()
            }
        }

        $request = [pscustomobject]@{
            Coordinator = $Coordinator
            Key = $Key
            SourceId = $SourceId
            PowerShell = $powerShell
            AsyncResult = $asyncResult
            StartedAtUtc = $nowUtc
            StopReason = $null
            IsDisposed = $false
        }
        $Coordinator.InFlight[$Key] = $request
        $Coordinator.LastStartedBySource[$SourceId] = $nowUtc
        return $request
    }
    finally {
        [System.Threading.Monitor]::Exit($Coordinator.SyncRoot)
    }
}

function Stop-RefreshRequest {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Request
    )

    if (-not $Request.IsDisposed -and -not $Request.AsyncResult.IsCompleted) {
        if ([string]::IsNullOrWhiteSpace($Request.StopReason)) {
            $Request.StopReason = 'cancelled'
        }

        $Request.PowerShell.Stop()
    }
}

function Receive-RefreshRequest {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Request,

        [Parameter()]
        [ValidateRange(1, 86400)]
        [int]$TimeoutSeconds = 30
    )

    $completed = $Request.AsyncResult.AsyncWaitHandle.WaitOne(
        [TimeSpan]::FromSeconds($TimeoutSeconds)
    )
    if (-not $completed -and [string]::IsNullOrWhiteSpace($Request.StopReason)) {
        $Request.StopReason = 'timeout'
        Stop-RefreshRequest -Request $Request
        [void]$Request.AsyncResult.AsyncWaitHandle.WaitOne([TimeSpan]::FromSeconds(5))
    }

    try {
        if (-not [string]::IsNullOrWhiteSpace($Request.StopReason)) {
            try {
                [void]$Request.PowerShell.EndInvoke($Request.AsyncResult)
            }
            catch [System.Management.Automation.PipelineStoppedException] {
                Write-Verbose 'Refresh request was stopped before completion.'
            }

            return [pscustomobject]@{
                status = $Request.StopReason
                result = $null
                failureType = $Request.StopReason
            }
        }

        $records = @($Request.PowerShell.EndInvoke($Request.AsyncResult))
        if ($Request.PowerShell.Streams.Error.Count -gt 0) {
            $errorType = $Request.PowerShell.Streams.Error[0].Exception.GetType().Name
            throw [System.InvalidOperationException]::new(
                "Refresh worker reported an error ($errorType)."
            )
        }

        if (-not (Test-RefreshPlainData -Value $records)) {
            throw 'Refresh worker returned a non-data object.'
        }

        $result = if ($records.Count -eq 0) {
            $null
        }
        elseif ($records.Count -eq 1) {
            $records[0]
        }
        else {
            $records
        }

        [pscustomobject]@{
            status = 'completed'
            result = $result
            failureType = $null
        }
    }
    catch [System.Management.Automation.PipelineStoppedException] {
        [pscustomobject]@{
            status = 'cancelled'
            result = $null
            failureType = 'cancelled'
        }
    }
    finally {
        $Request.PowerShell.Dispose()
        $Request.IsDisposed = $true
        $coordinator = $Request.Coordinator
        [System.Threading.Monitor]::Enter($coordinator.SyncRoot)
        try {
            if ([object]::ReferenceEquals($coordinator.InFlight[$Request.Key], $Request)) {
                $coordinator.InFlight.Remove($Request.Key)
            }
        }
        finally {
            [System.Threading.Monitor]::Exit($coordinator.SyncRoot)
        }
    }
}

function Close-RefreshCoordinator {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [pscustomobject]$Coordinator
    )

    if ($Coordinator.IsDisposed) {
        return
    }

    $failures = [System.Collections.Generic.List[System.Exception]]::new()
    try {
        foreach ($request in @($Coordinator.InFlight.Values)) {
            try {
                Stop-RefreshRequest -Request $request
                [void](Receive-RefreshRequest -Request $request -TimeoutSeconds 5)
            }
            catch [System.Management.Automation.RuntimeException], [System.InvalidOperationException] {
                $failures.Add($_.Exception)
            }
        }
    }
    finally {
        try {
            $Coordinator.RunspacePool.Close()
        }
        finally {
            $Coordinator.RunspacePool.Dispose()
            $Coordinator.IsDisposed = $true
        }
    }
    if ($failures.Count) {
        throw [System.AggregateException]::new('Refresh coordinator cleanup encountered worker failures.', $failures.ToArray())
    }
}