VirtualMetric.psm1

# The VirtualMetric module. The runtime is hand-written (Private, Public); the resource cmdlets are generated
# from the API catalog (Generated/Cmdlets.ps1, written by go run ./cmd/pwshgen) as thin stubs over
# Invoke-VMetricCatalogCmdlet, which reads VirtualMetric.Catalog.json.

$script:ModuleRoot = $PSScriptRoot
# While the root module loads, the module object does not carry the manifest's version yet: read it from the
# manifest itself.
$script:ModuleVersion = '0.0.0'
$manifestPath = Join-Path -Path $PSScriptRoot -ChildPath 'VirtualMetric.psd1'
if (Test-Path -LiteralPath $manifestPath) {
    $script:ModuleVersion = [string](Import-PowerShellDataFile -LiteralPath $manifestPath).ModuleVersion
}

# The current session (a synchronized hashtable, see Private/Session.ps1), every session this PowerShell
# session holds keyed by origin and tenant, and the catalog once read.
$script:VMetricSession = $null
$script:VMetricSessions = [ordered]@{}
$script:VMetricCatalog = $null
$script:VMetricCatalogPath = $null
$script:VMetricUserAgent = $null
# The transport's HttpClients, one per certificate policy (see Private/Http.ps1).
$script:VMetricHttpClients = @{}

foreach ($folder in @('Private', 'Public')) {
    $folderPath = Join-Path -Path $PSScriptRoot -ChildPath $folder
    if (-not (Test-Path -LiteralPath $folderPath)) {
        continue
    }
    foreach ($file in (Get-ChildItem -LiteralPath $folderPath -Filter '*.ps1' -File | Sort-Object -Property Name)) {
        . $file.FullName
    }
}

$generatedPath = Join-Path -Path $PSScriptRoot -ChildPath 'Generated/Cmdlets.ps1'
if (Test-Path -LiteralPath $generatedPath) {
    . $generatedPath
}

# Removing the module forgets every session and zeroes the tokens it held, and closes the transport's
# connections. Nothing is revoked on the server: Disconnect-VMetric does that.
$ExecutionContext.SessionState.Module.OnRemove = {
    Clear-VMetricSessionState
    foreach ($client in @($script:VMetricHttpClients.Values)) {
        $client.Dispose()
    }
    $script:VMetricHttpClients.Clear()
}