< Summary - Kestrun — Combined Coverage

Information
Class: Public.Server.Start-KrServer
Assembly: Kestrun.PowerShell.Public
File(s): /home/runner/work/Kestrun/Kestrun/src/PowerShell/Kestrun/Public/Server/Start-KrServer.ps1
Tag: Kestrun/Kestrun@5f1d2b981c9d7292c11fd448428c6ab6c811c5de
Line coverage
0%
Covered lines: 0
Uncovered lines: 85
Coverable lines: 85
Total lines: 205
Line coverage: 0%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 11/19/2025 - 17:40:50 Line coverage: 0% (0/47) Total lines: 130 Tag: Kestrun/Kestrun@fcf33342333cef0516fe0d0912a86709874fd02612/12/2025 - 17:27:19 Line coverage: 0% (0/50) Total lines: 136 Tag: Kestrun/Kestrun@826bf9dcf9db118c5de4c78a3259bce9549f0dcd03/26/2026 - 03:54:59 Line coverage: 0% (0/85) Total lines: 205 Tag: Kestrun/Kestrun@844b5179fb0492dc6b1182bae3ff65fa7365521d

Coverage delta

Coverage delta 1 -1

Metrics

File(s)

/home/runner/work/Kestrun/Kestrun/src/PowerShell/Kestrun/Public/Server/Start-KrServer.ps1

#LineLine coverage
 1<#
 2    .SYNOPSIS
 3        Starts the Kestrun server and listens for incoming requests.
 4    .DESCRIPTION
 5        This function starts the Kestrun server, allowing it to accept incoming HTTP requests.
 6    .PARAMETER Server
 7        The Kestrun server instance to start. This parameter is mandatory.
 8    .PARAMETER NoWait
 9        If specified, the function will not wait for the server to start and will return immediately.
 10    .PARAMETER Quiet
 11        If specified, suppresses output messages during the startup process.
 12    .PARAMETER CloseLogsOnExit
 13        If specified, closes all loggers when the server stops.
 14    .PARAMETER PassThru
 15        If specified, the cmdlet will return the modified server instance after starting it.
 16    .EXAMPLE
 17        Start-KrServer -Server $server
 18        Starts the specified Kestrun server instance and listens for incoming requests.
 19    .NOTES
 20        This function is designed to be used after the server has been configured and routes have been added.
 21        It will block the console until the server is stopped or Ctrl+C is pressed.
 22#>
 23function Start-KrServer {
 24    [KestrunRuntimeApi('Definition')]
 25    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
 26    [CmdletBinding()]
 27    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '')]
 28    param(
 29        [Parameter(Mandatory = $false, ValueFromPipeline = $true)]
 30        [Kestrun.Hosting.KestrunHost]$Server,
 31        [Parameter()]
 32        [switch]$NoWait,
 33        [Parameter()]
 34        [switch]$Quiet,
 35        [Parameter()]
 36        [switch]$PassThru,
 37        [Parameter()]
 38        [switch]$CloseLogsOnExit
 39    )
 40    begin {
 041        $effectiveQuiet = $Quiet.IsPresent
 042        if (-not $PSBoundParameters.ContainsKey('Quiet')) {
 043            $effectiveQuiet = [bool]$ExecutionContext.SessionState.PSVariable.GetValue('__krRunnerQuiet', $false)
 44        }
 045        $managedConsole = [bool]$ExecutionContext.SessionState.PSVariable.GetValue('__krRunnerManagedConsole', $false)
 46
 47        # Ensure the server instance is resolved
 048        $Server = Resolve-KestrunServer -Server $Server
 049        $hasConsole = $false
 050        $writeConsole = $false
 51        try {
 052            if (-not $managedConsole) {
 053                $null = [Console]::KeyAvailable
 054                $hasConsole = $true
 55            }
 056            $writeConsole = -not $effectiveQuiet
 57        } catch {
 058            Write-KrLog -Level Information -Message 'No console available; running in non-interactive mode.'
 59        }
 60
 061        $writeStartupFailureBanner = {
 62            param([Exception]$Exception)
 63
 064            if (-not $effectiveQuiet) {
 065                $errorMessage = "Failed to start Kestrun server '$($Server.ApplicationName)'."
 066                if ($Exception -and -not [string]::IsNullOrWhiteSpace($Exception.Message)) {
 067                    $errorMessage = "$errorMessage $($Exception.Message)"
 68                }
 69
 070                Write-KrLog -Level Error -Message $errorMessage
 71            }
 72        }
 73    }
 74    process {
 75        # Generate OpenAPI documents if not already generated
 076        foreach ( $doc in $Server.OpenApiDocumentDescriptor.Keys ) {
 077            if ( -not $Server.OpenApiDocumentDescriptor[$doc].HasBeenGenerated ) {
 078                Build-KrOpenApiDocument -Server $Server -DocId $doc
 79            }
 80        }
 81        # Start the Kestrel server
 082        if ( -not $effectiveQuiet ) {
 083            Write-Host "Starting Kestrun server '$($Server.ApplicationName)' ..."
 084            Write-KrLog -Level Information -Message "Starting Kestrun server '{ApplicationName}' ..." -Values $Server.Ap
 85        }
 86
 087        $startupTask = $null
 88        try {
 089            $startupTask = $Server.StartAsync()
 90        } catch {
 091            $originalException = $_.Exception
 092            $displayException = if ($originalException -and $originalException.InnerException) {
 093                $originalException.InnerException
 94            } else {
 095                $originalException
 96            }
 097            & $writeStartupFailureBanner $displayException
 98            throw
 99        }
 100
 0101        if ($NoWait.IsPresent) {
 102            # Preserve the -NoWait contract: return immediately after startup is initiated.
 0103            if ($startupTask.IsFaulted) {
 0104                $startupException = if ($startupTask.Exception -and $startupTask.Exception.InnerException) {
 0105                    $startupTask.Exception.InnerException
 106                } else {
 0107                    $startupTask.Exception
 108                }
 0109                & $writeStartupFailureBanner $startupException
 0110                if ($startupTask.Exception -and $startupTask.Exception.InnerException) {
 0111                    throw $startupTask.Exception.InnerException
 112                }
 0113                throw $startupTask.Exception
 114            }
 115
 0116            if ($writeConsole) {
 0117                Write-Host 'Kestrun server startup initiated (NoWait).'
 118            }
 119        } else {
 120            try {
 121                # Block until startup completes so bind/config errors surface immediately.
 0122                $null = $startupTask.GetAwaiter().GetResult()
 123            } catch {
 0124                $originalException = $_.Exception
 0125                $displayException = if ($originalException -and $originalException.InnerException) {
 0126                    $originalException.InnerException
 127                } else {
 0128                    $originalException
 129                }
 0130                & $writeStartupFailureBanner $displayException
 131                throw
 132            }
 133
 0134            if ($writeConsole) {
 0135                Write-Host 'Kestrun server started successfully.'
 0136                foreach ($listener in $Server.Options.Listeners) {
 0137                    if ($listener.X509Certificate) {
 0138                        Write-Host "Listening on https://$($listener.IPAddress):$($listener.Port) with protocols: $($lis
 139                    } else {
 0140                        Write-Host "Listening on http://$($listener.IPAddress):$($listener.Port) with protocols: $($list
 141                    }
 0142                    if ($listener.X509Certificate) {
 0143                        Write-Host "Using certificate: $($listener.X509Certificate.Subject)"
 144                    } else {
 0145                        Write-Host 'No certificate configured. Running in HTTP mode.'
 146                    }
 0147                    if ($listener.UseConnectionLogging) {
 0148                        Write-Host 'Connection logging is enabled.'
 149                    } else {
 0150                        Write-Host 'Connection logging is disabled.'
 151                    }
 152                }
 0153                Write-Host 'Press Ctrl+C to stop the server.'
 154            }
 155        }
 0156        if (-not $NoWait.IsPresent) {
 157            # Intercept Ctrl+C and gracefully stop the Kestrun server
 158            try {
 0159                if ($hasConsole) {
 0160                    [Console]::TreatControlCAsInput = $true
 0161                    while ($Server.IsRunning) {
 0162                        if ([Console]::KeyAvailable) {
 0163                            $key = [Console]::ReadKey($true)
 0164                            if (($key.Modifiers -eq 'Control') -and ($key.Key -eq 'C')) {
 0165                                if ($writeConsole) {
 0166                                    Write-Host 'Ctrl+C detected. Stopping Kestrun server...'
 167                                }
 0168                                $null = $Server.StopAsync().Wait()
 169                                break
 170                            }
 171                        }
 0172                        Start-Sleep -Milliseconds 100
 173                    }
 174                } else {
 175                    # Just wait for the server to stop (block until externally stopped)
 0176                    while ($Server.IsRunning) {
 0177                        Start-Sleep -Seconds 1
 178                    }
 179                }
 180            } finally {
 181                # Ensure the server is stopped on exit
 0182                if ($writeConsole) {
 0183                    Write-Host 'Stopping Kestrun server...'
 184                }
 0185                if ($Server.IsRunning) {
 0186                    $null = [Kestrun.KestrunHostManager]::StopAsync($Server.ApplicationName).Wait()
 187                }
 188                #$Server.StopAsync().Wait()
 0189                [Kestrun.KestrunHostManager]::Destroy($Server.ApplicationName)
 190
 0191                if ($CloseLogsOnExit.IsPresent) {
 192                    # Close the Kestrel loggers
 0193                    Close-KrLogger
 194                }
 195
 0196                if ($writeConsole) {
 0197                    Write-Host 'Kestrun server stopped.'
 198                }
 199            }
 0200        } elseif ($PassThru.IsPresent) {
 201            # if the PassThru switch is specified, return the server instance
 0202            return $Server
 203        }
 204    }
 205}

Methods/Properties

Start-KrServer()