Private/System/Initialize-MemoryManager.ps1

#Requires -Version 5.1

# Memory management constants, defined once for the module: Invoke-Cleanup and
# Invoke-ResourceCleanup read them and must not reassign the table, or a key one of them needs can
# disappear after the other runs. Only keys something reads belong here.
$script:MemoryManagementConfig = @{
    MemoryPressureAmountMB = 50
    GCRetryAttempts = 3
    GCRetryDelayMilliseconds = 100
    LogComponent = 'MemoryManagement'
}


function Initialize-MemoryManager {
    <#
    .SYNOPSIS
        Creates and initializes a new MemoryManager instance

    .DESCRIPTION
        Initializes a memory management system with specified thresholds
        and monitoring intervals. Provides memory monitoring
        with correlation tracking for troubleshooting and performance analysis.

    .PARAMETER MaxMemoryMB
        Maximum memory threshold in megabytes before triggering cleanup

    .PARAMETER CheckInterval
        Number of operations between memory usage checks

    .PARAMETER CorrelationId
        Unique correlation identifier for tracking operations

    .EXAMPLE
        PS> Initialize-MemoryManager -MaxMemoryMB 2048 -CheckInterval 25

        Creates memory manager with 2GB threshold, checking every 25 operations

    .EXAMPLE
        PS> Initialize-MemoryManager -MaxMemoryMB 1024 -CheckInterval 50 -CorrelationId $correlationId

        Creates memory manager with custom correlation ID for tracking

    .OUTPUTS
        [MemoryManager] Configured memory management instance

    .NOTES
        PERFORMANCE CONSIDERATIONS:
        - Lower thresholds: More frequent cleanup, better memory control
        - Higher thresholds: Less cleanup overhead, faster processing
        - Optimal range: 1024-4096 MB for most enterprise environments

        WHATIF BEHAVIOR:
        - Memory manager creation ALWAYS executes regardless of -WhatIf
        - Only logging and reporting operations respect -WhatIf
        - This ensures system stability is maintained during simulations

        TROUBLESHOOTING:
        - For memory issues: .\Troubleshooting\Performance\Memory-Management.md
        - For configuration: .\Troubleshooting\Performance\Memory-Management-Issues.md
    #>


    [CmdletBinding(SupportsShouldProcess)]
    [OutputType('MemoryManager')]
    param(
        [Parameter(Mandatory)]
        # The same ranges the commands and the configuration file accept. This function once took
        # 256-16384 and 5-100, so -MaxMemoryUsageMB 100-255 and a configured interval outside 5-100
        # passed every earlier check and then failed initialization.
        [ValidateRange(100, 16384)]
        [int]$MaxMemoryMB,

        [Parameter(Mandatory)]
        [ValidateRange(1, 1000)]
        [int]$CheckInterval,

        [Parameter()]
        [string]$CorrelationId = [System.Guid]::NewGuid().ToString()
    )

    begin {
        # Ensure correlation ID is not empty
        if (-not $CorrelationId.Trim()) {
            $CorrelationId = [System.Guid]::NewGuid().ToString()
        }
    }

    process {
        try {
            # Memory manager creation always executes - critical for system health
            # Only the reporting respects ShouldProcess
            if ($PSCmdlet.ShouldProcess("MemoryManager", "Initialize with threshold $MaxMemoryMB MB")) {
                Write-StructuredLog "Initializing memory manager with threshold $MaxMemoryMB MB" -Level Information -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId
            } else {
                Write-Verbose "WhatIf: Would initialize memory manager with threshold $MaxMemoryMB MB"
            }

            # ALWAYS create memory manager - essential for system stability
            $memoryManager = [MemoryManager]::new($MaxMemoryMB, $CheckInterval, $CorrelationId)

            if ($PSCmdlet.ShouldProcess("MemoryManager", "Log initialization completion")) {
                Write-StructuredLog "Memory manager initialized successfully" -Level Information -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId
                Write-StructuredLog "Configuration: Threshold=$MaxMemoryMB MB, CheckInterval=$CheckInterval operations" -Level Debug -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId
            } else {
                Write-StructuredLog "Memory manager created for WhatIf simulation" -Level Debug -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId
            }

            return $memoryManager
        }
        catch {
            Write-StructuredLog "Failed to initialize memory manager: $($_.Exception.Message)" -Level Error -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId
            $message = "Memory manager initialization failed: $($_.Exception.Message)"
            $exception = [System.InvalidOperationException]::new($message, $_.Exception)
            $category = [System.Management.Automation.ErrorCategory]::InvalidOperation
            $errorRecord = [System.Management.Automation.ErrorRecord]::new(
                $exception, 'MemoryManagerNotInitialized', $category, $MaxMemoryMB)
            $PSCmdlet.ThrowTerminatingError($errorRecord)
        }
    }

    end {
        Write-StructuredLog "Memory manager initialization completed" -Level Debug -Component $script:MemoryManagementConfig.LogComponent -CorrelationId $CorrelationId
    }
}

# Functions are automatically available when dot-sourced
# Note: Export-ModuleMember is only valid in .psm1 module files