Private/Invoke-PrismRequest.ps1

function Invoke-PrismRequest {
    <#
    .SYNOPSIS
        Internal helper that issues an authenticated request against the Nutanix
        Prism Central v4 REST API.
 
    .DESCRIPTION
        Resolves the named PrismSession, builds the fully-qualified request URI from
        the relative API path and an optional query hashtable, honors the session's
        SSL settings, attaches the session's WebSession (Basic Authorization header +
        IGW session cookie), serializes the body to JSON when needed and invokes the
        request.
 
        All public Prism wrapper functions funnel their HTTP calls through this helper
        so the session/SSL/serialization boilerplate lives in exactly one place.
        Public wrappers include the session's ApiVersion in their request paths.
 
        HTTP 429 responses are retried up to five times using the server's timing
        headers and bounded exponential backoff. All retries reuse the same request,
        including its NTNX-Request-Id and If-Match headers. HTTP 401 refreshes the
        session and retries once within the same budget. Other errors propagate.
        Session resolution, HTTP attempts and retry waits share a 100-second total
        budget by default. A shorter caller deadline takes precedence. This is a
        cooperative deadline: whole-second HTTP timeout rounding and transport/DNS
        overhead can cause a small overrun. A response that arrives after the deadline
        is still returned, because a mutating request has already taken effect.
 
    .PARAMETER PrismSession
        The server/FQDN of the PrismSession to use. May be omitted when only one session exists.
 
    .PARAMETER Path
        The API path relative to the '/api/' base, for example
        'vmm/v4.2/ahv/config/vms' or 'vmm/v4.2/content/ovas/{extId}'.
 
    .PARAMETER Method
        The HTTP method to use. Defaults to 'GET'.
 
    .PARAMETER Query
        A hashtable of query string parameters. Null/empty values are skipped and
        values are URL-encoded. Useful for OData parameters such as $page, $limit,
        $filter, $orderby and $select.
 
    .PARAMETER Body
        The request body. A string is sent as-is; any other object is converted to
        JSON before sending.
 
    .PARAMETER Header
        Additional request headers to merge in (for example If-Match or
        NTNX-Request-Id).
 
    .PARAMETER PassThruResponse
        Returns the full Invoke-WebRequest response object (so callers can read
        response headers such as ETag) instead of the deserialized body.
 
    .PARAMETER TimeoutSeconds
        Total time budget for this request, including session validation and retries.
        Defaults to 100 seconds, rather than 100 seconds for each of six attempts.
 
    .PARAMETER Deadline
        An optional earlier deadline shared with a caller such as Wait-PrismTask.
 
    .OUTPUTS
        The deserialized API response, or the full web response when -PassThruResponse
        is supplied.
    #>


    [CmdletBinding()]
    param(
        [Parameter()][string]$PrismSession,
        [Parameter(Mandatory)][string]$Path,
        [Parameter()][string]$Method = 'GET',
        [Parameter()][hashtable]$Query,
        [Parameter()]$Body,
        [Parameter()][hashtable]$Header,
        [Parameter()][switch]$PassThruResponse,
        [Parameter()][ValidateRange(1, 2147483647)][int]$TimeoutSeconds = 100,
        [Parameter(DontShow)][Nullable[DateTimeOffset]]$Deadline
    )

    $requestDeadline = [DateTimeOffset]::UtcNow.AddSeconds($TimeoutSeconds)
    if ($null -ne $Deadline -and $Deadline -lt $requestDeadline) { $requestDeadline = $Deadline }
    $null = Get-PrismRequestTimeout -Deadline $requestDeadline
    ## Resolve the session (this validates / refreshes it as needed)
    $PrismSessionConfig = Get-PrismSession $PrismSession -Deadline $requestDeadline
    if (-not $PrismSessionConfig) {
        Write-Host 'PrismSession: [' -NoNewline
        Write-Host $PrismSession -ForegroundColor Cyan
        Write-Host '] was not Found. Please use the New-PrismSession command.'
        Throw 'Prism Session Not Found. Use New-PrismSession command before using features.'
    }

    ## Ensure the session has a version; wrappers include it in their request paths.
    if ([string]::IsNullOrEmpty($PrismSessionConfig.ApiVersion)) {
        throw 'Prism session has no ApiVersion. Recreate it with New-PrismSession.'
    }
    $requestPath = $Path.TrimStart('/')

    ## Build the base URI. Prism Central APIs are served beneath '/api'.
    $uri = 'https://{0}:{1}/api/{2}' -f $PrismSessionConfig.PrismServer, $PrismSessionConfig.PrismPort, $requestPath

    ## Append any query string parameters
    if ($Query -and $Query.Count) {
        $pairs = foreach ($key in $Query.Keys) {
            $value = $Query[$key]
            if ($null -eq $value -or $value -eq '') { continue }
            '{0}={1}' -f [uri]::EscapeDataString($key), [uri]::EscapeDataString([string]$value)
        }
        if ($pairs) {
            $uri += '?' + ($pairs -join '&')
        }
    }

    $RestMethodSplat = @{
        Uri                  = $uri
        Method               = $Method
        WebSession           = $PrismSessionConfig.PrismWebSession
        TimeoutSec           = 100
        ErrorAction          = 'Stop'
        ProgressAction       = 'SilentlyContinue'
        SkipCertificateCheck = $PrismSessionConfig.AllowInsecureSSL
        # Prism Central v4 returns a non-standard, unquoted ETag. PowerShell otherwise
        # validates the If-Match header and rejects it ("not a valid quoted string"),
        # so skipping header validation lets the raw ETag pass through. Do not remove.
        SkipHeaderValidation = $true
    }

    $RequestHeaders = @{
        'Accept'       = 'application/json'
        'Content-Type' = 'application/json'
    }
    if ($Header) {
        foreach ($key in $Header.Keys) { $RequestHeaders[$key] = $Header[$key] }
    }
    $RestMethodSplat.Headers = $RequestHeaders

    if ($PSBoundParameters.ContainsKey('Body') -and $null -ne $Body) {
        $RestMethodSplat.Body = ($Body -is [string]) ? $Body : ($Body | ConvertTo-Json -Depth 25 -Compress)
    }

    # Rate-limit retries and one authentication refresh share the original deadline.
    $retryAttempt = 0
    $authenticationRetried = $false
    while ($true) {
        $RestMethodSplat.TimeoutSec = Get-PrismRequestTimeout -Deadline $requestDeadline
        try {
            # A response that arrives after the deadline is still returned: for
            # mutating requests the change has already been applied server-side.
            if ($PassThruResponse.IsPresent) {
                return Invoke-WebRequest @RestMethodSplat
            }
            return Invoke-RestMethod @RestMethodSplat
        } catch {
            $failure = $_
            $response = $failure.Exception.Response
            $status = if ($response -and $response.StatusCode) { [int]$response.StatusCode } else { 0 }
            if ($status -in 401, 403) {
                Unregister-PrismSessionValidation -PrismSession $PrismSessionConfig
            }
            if ($status -eq 401 -and -not $authenticationRetried) {
                if ([DateTimeOffset]::UtcNow -ge $requestDeadline) { throw $failure }
                # The IAM gateway rejected the request before it reached the service.
                # Refresh once, preserving the request headers and original deadline.
                $authenticationRetried = $true
                Write-Verbose "Prism rejected session [$($PrismSessionConfig.Name)] (HTTP 401); refreshing it and retrying once."
                $PrismSessionConfig = Get-PrismSession -Name $PrismSessionConfig.Name -Deadline $requestDeadline
                $RestMethodSplat.WebSession = $PrismSessionConfig.PrismWebSession
                continue
            }
            # A real HTTP answer other than 429 (401, 412, 503, ...) is never masked by
            # the deadline, and neither is the final 429 once retries are exhausted.
            if ($null -ne $response -and ([int]$response.StatusCode -ne 429 -or $retryAttempt -ge 5)) {
                throw $failure
            }
            # Transport failures and retryable 429s: an expired deadline becomes a
            # TimeoutException that carries the original error as its inner exception.
            $null = Get-PrismRequestTimeout -Deadline $requestDeadline -InnerException $failure.Exception
            if ($null -eq $response) {
                throw $failure
            }
            $retryAttempt++
            $waitSplat = @{
                Headers        = $response.Headers
                RetryAttempt   = $retryAttempt
                Deadline       = $requestDeadline
                InnerException = $failure.Exception
            }
            if (-not (Wait-PrismRateLimit @waitSplat)) {
                throw $failure
            }
        }
    }
}