# ============================================================================== # Performance.psm1 - Metrics Sampling, GDI/Handle Tracking & Memory Leak Evaluator # ============================================================================== Add-Type -TypeDefinition @" using System; using System.Runtime.InteropServices; public static class User32 { [DllImport("user32.dll")] public static extern uint GetGuiResources(IntPtr hProcess, uint uiFlags); } "@ -ErrorAction SilentlyContinue function Get-GuiResourceCounts([IntPtr]$processHandle) { try { $gdi = [User32]::GetGuiResources($processHandle, 0) $user = [User32]::GetGuiResources($processHandle, 1) return @{ Gdi = $gdi; User = $user } } catch { return @{ Gdi = 0; User = 0 } } } function Sample-ClientPerformanceMetrics { [CmdletBinding()] param( [string]$Stage = "Load" ) $samples = [System.Collections.Generic.List[PSCustomObject]]::new() $timestamp = (Get-Date).ToUniversalTime().ToString("o") $targetNames = @("ClassNotify.Service", "ClassNotify.Client") foreach ($name in $targetNames) { $procs = Get-Process -Name $name -ErrorAction SilentlyContinue foreach ($p in $procs) { $gui = Get-GuiResourceCounts $p.Handle $sample = [PSCustomObject]@{ TimestampUtc = $timestamp Stage = $Stage ProcessName = $p.ProcessName Pid = $p.Id WorkingSetMb = [math]::Round($p.WorkingSet64 / 1MB, 2) PrivateBytesMb = [math]::Round($p.PrivateMemorySize64 / 1MB, 2) Handles = $p.HandleCount Threads = $p.Threads.Count GdiObjects = $gui.Gdi UserObjects = $gui.User } $samples.Add($sample) } } return $samples } function Calculate-LinearRegressionSlope { [CmdletBinding()] param( [double[]]$TimeSeconds, [double[]]$Values ) $n = $TimeSeconds.Length if ($n -lt 2) { return 0.0 } $sumX = 0.0 $sumY = 0.0 $sumXY = 0.0 $sumX2 = 0.0 for ($i = 0; $i -lt $n; $i++) { $x = $TimeSeconds[$i] $y = $Values[$i] $sumX += $x $sumY += $y $sumXY += ($x * $y) $sumX2 += ($x * $x) } $denominator = ($n * $sumX2) - ($sumX * $sumX) if ([math]::Abs($denominator) -lt 0.000001) { return 0.0 } # Slope in units per second -> convert to units per hour (* 3600) $slopePerSec = (($n * $sumXY) - ($sumX * $sumY)) / $denominator return [math]::Round($slopePerSec * 3600.0, 4) } function Analyze-MemoryLeakRisk { [CmdletBinding()] param( [PSCustomObject[]]$MetricHistory, [string]$ProcessName = "ClassNotify.Service", [string]$StageFilter = "Soak" ) $samplesToUse = if (-not [string]::IsNullOrWhiteSpace($StageFilter)) { $MetricHistory | Where-Object { $_.Stage -eq $StageFilter -and $_.ProcessName -eq $ProcessName } } else { $MetricHistory | Where-Object { $_.ProcessName -eq $ProcessName } } $procSamples = $samplesToUse | Sort-Object TimestampUtc if ($procSamples.Count -lt 5) { return [PSCustomObject]@{ ProcessName = $ProcessName SampleCount = $procSamples.Count SlopeMbPerHour = 0.0 BaselineMb = 0.0 FinalMb = 0.0 PeakMb = 0.0 IsLeaking = $false Verdict = if (-not [string]::IsNullOrWhiteSpace($StageFilter)) { "INSUFFICIENT_SOAK_DATA" } else { "INSUFFICIENT_SAMPLES" } } } $firstTime = [DateTimeOffset]::Parse($procSamples[0].TimestampUtc).ToUnixTimeSeconds() $timeSecs = @() $memMbs = @() foreach ($s in $procSamples) { $t = [DateTimeOffset]::Parse($s.TimestampUtc).ToUnixTimeSeconds() - $firstTime $timeSecs += [double]$t $memMbs += [double]$s.PrivateBytesMb } $slope = Calculate-LinearRegressionSlope -TimeSeconds $timeSecs -Values $memMbs $baseline = $memMbs[0] $final = $memMbs[-1] $peak = ($memMbs | Measure-Object -Maximum).Maximum $threshold = if ($ProcessName -like "*Service*") { 2.0 } else { 5.0 } $isLeaking = ($slope -gt $threshold -and $final -gt ($baseline * 1.3)) $verdict = if ($isLeaking) { "LEAK_DETECTED" } elseif ($slope -gt ($threshold * 0.75)) { "WARN" } else { "PASS" } return [PSCustomObject]@{ ProcessName = $ProcessName SampleCount = $procSamples.Count SlopeMbPerHour = $slope BaselineMb = $baseline FinalMb = $final PeakMb = $peak IsLeaking = $isLeaking Verdict = $verdict } } Export-ModuleMember -Function Sample-ClientPerformanceMetrics, Calculate-LinearRegressionSlope, Analyze-MemoryLeakRisk