| | | 1 | | using Microsoft.AspNetCore.Server.Kestrel.Core; |
| | | 2 | | using System.Net; |
| | | 3 | | using System.Management.Automation; |
| | | 4 | | using System.Management.Automation.Runspaces; |
| | | 5 | | using Kestrun.Utilities; |
| | | 6 | | using Microsoft.CodeAnalysis; |
| | | 7 | | using System.Reflection; |
| | | 8 | | using System.Security.Cryptography.X509Certificates; |
| | | 9 | | using Serilog; |
| | | 10 | | using Serilog.Events; |
| | | 11 | | using Microsoft.AspNetCore.SignalR; |
| | | 12 | | using Kestrun.Scheduling; |
| | | 13 | | using Kestrun.SharedState; |
| | | 14 | | using Kestrun.Middleware; |
| | | 15 | | using Kestrun.Scripting; |
| | | 16 | | using Kestrun.Hosting.Options; |
| | | 17 | | using System.Runtime.InteropServices; |
| | | 18 | | using Microsoft.PowerShell; |
| | | 19 | | using System.Net.Sockets; |
| | | 20 | | using Microsoft.Net.Http.Headers; |
| | | 21 | | using Kestrun.Authentication; |
| | | 22 | | using Kestrun.Health; |
| | | 23 | | using Kestrun.Tasks; |
| | | 24 | | using Kestrun.Runtime; |
| | | 25 | | |
| | | 26 | | namespace Kestrun.Hosting; |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Provides hosting and configuration for the Kestrun application, including service registration, middleware setup, an |
| | | 30 | | /// </summary> |
| | | 31 | | public class KestrunHost : IDisposable |
| | | 32 | | { |
| | | 33 | | #region Fields |
| | 1290 | 34 | | internal WebApplicationBuilder Builder { get; } |
| | | 35 | | |
| | | 36 | | private WebApplication? _app; |
| | | 37 | | |
| | 108 | 38 | | internal WebApplication App => _app ?? throw new InvalidOperationException("WebApplication is not built yet. Call Bu |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Gets the application name for the Kestrun host. |
| | | 42 | | /// </summary> |
| | 2 | 43 | | public string ApplicationName => Options.ApplicationName ?? "KestrunApp"; |
| | | 44 | | |
| | | 45 | | /// <summary> |
| | | 46 | | /// Gets the configuration options for the Kestrun host. |
| | | 47 | | /// </summary> |
| | 1161 | 48 | | public KestrunOptions Options { get; private set; } = new(); |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// List of PowerShell module paths to be loaded. |
| | | 52 | | /// </summary> |
| | 323 | 53 | | private readonly List<string> _modulePaths = []; |
| | | 54 | | |
| | | 55 | | /// <summary> |
| | | 56 | | /// Indicates whether the Kestrun host is stopping. |
| | | 57 | | /// </summary> |
| | | 58 | | private int _stopping; // 0 = running, 1 = stopping |
| | | 59 | | |
| | | 60 | | /// <summary> |
| | | 61 | | /// Indicates whether the Kestrun host configuration has been applied. |
| | | 62 | | /// </summary> |
| | 250 | 63 | | public bool IsConfigured { get; private set; } |
| | | 64 | | |
| | | 65 | | /// <summary> |
| | | 66 | | /// Gets the timestamp when the Kestrun host was started. |
| | | 67 | | /// </summary> |
| | 17 | 68 | | public DateTime? StartTime { get; private set; } |
| | | 69 | | |
| | | 70 | | /// <summary> |
| | | 71 | | /// Gets the timestamp when the Kestrun host was stopped. |
| | | 72 | | /// </summary> |
| | 18 | 73 | | public DateTime? StopTime { get; private set; } |
| | | 74 | | |
| | | 75 | | /// <summary> |
| | | 76 | | /// Gets the uptime duration of the Kestrun host. |
| | | 77 | | /// While running (no StopTime yet), this returns DateTime.UtcNow - StartTime. |
| | | 78 | | /// After stopping, it returns StopTime - StartTime. |
| | | 79 | | /// If StartTime is not set, returns null. |
| | | 80 | | /// </summary> |
| | | 81 | | public TimeSpan? Uptime => |
| | 0 | 82 | | !StartTime.HasValue |
| | 0 | 83 | | ? null |
| | 0 | 84 | | : StopTime.HasValue |
| | 0 | 85 | | ? StopTime - StartTime |
| | 0 | 86 | | : DateTime.UtcNow - StartTime.Value; |
| | | 87 | | /// <summary> |
| | | 88 | | /// The runspace pool manager for PowerShell execution. |
| | | 89 | | /// </summary> |
| | | 90 | | private KestrunRunspacePoolManager? _runspacePool; |
| | | 91 | | |
| | | 92 | | /// <summary> |
| | | 93 | | /// Status code options for configuring status code pages. |
| | | 94 | | /// </summary> |
| | | 95 | | private StatusCodeOptions? _statusCodeOptions; |
| | | 96 | | /// <summary> |
| | | 97 | | /// Exception options for configuring exception handling. |
| | | 98 | | /// </summary> |
| | | 99 | | private ExceptionOptions? _exceptionOptions; |
| | | 100 | | /// <summary> |
| | | 101 | | /// Forwarded headers options for configuring forwarded headers handling. |
| | | 102 | | /// </summary> |
| | | 103 | | private ForwardedHeadersOptions? _forwardedHeaderOptions; |
| | | 104 | | |
| | 4 | 105 | | internal KestrunRunspacePoolManager RunspacePool => _runspacePool ?? throw new InvalidOperationException("Runspace p |
| | | 106 | | |
| | | 107 | | // ── ✦ QUEUE #1 : SERVICE REGISTRATION ✦ ───────────────────────────── |
| | 323 | 108 | | private readonly List<Action<IServiceCollection>> _serviceQueue = []; |
| | | 109 | | |
| | | 110 | | // ── ✦ QUEUE #2 : MIDDLEWARE STAGES ✦ ──────────────────────────────── |
| | 323 | 111 | | private readonly List<Action<IApplicationBuilder>> _middlewareQueue = []; |
| | | 112 | | |
| | 406 | 113 | | internal List<Action<KestrunHost>> FeatureQueue { get; } = []; |
| | | 114 | | |
| | 485 | 115 | | internal List<IProbe> HealthProbes { get; } = []; |
| | | 116 | | #if NET9_0_OR_GREATER |
| | 323 | 117 | | private readonly Lock _healthProbeLock = new(); |
| | | 118 | | #else |
| | | 119 | | private readonly object _healthProbeLock = new(); |
| | | 120 | | #endif |
| | | 121 | | |
| | 323 | 122 | | internal readonly Dictionary<(string Pattern, string Method), MapRouteOptions> _registeredRoutes = |
| | 323 | 123 | | new(new RouteKeyComparer()); |
| | | 124 | | |
| | | 125 | | //internal readonly Dictionary<(string Scheme, string Type), AuthenticationSchemeOptions> _registeredAuthentications |
| | | 126 | | // new(new AuthKeyComparer()); |
| | | 127 | | |
| | | 128 | | /// <summary> |
| | | 129 | | /// Gets the root directory path for the Kestrun application. |
| | | 130 | | /// </summary> |
| | 134 | 131 | | public string? KestrunRoot { get; private set; } |
| | | 132 | | |
| | | 133 | | /// <summary> |
| | | 134 | | /// Gets the Serilog logger instance used by the Kestrun host. |
| | | 135 | | /// </summary> |
| | 5957 | 136 | | public Serilog.ILogger Logger { get; private set; } |
| | | 137 | | |
| | | 138 | | /// <summary> |
| | | 139 | | /// Gets the scheduler service used for managing scheduled tasks in the Kestrun host. |
| | | 140 | | /// </summary> |
| | 84 | 141 | | public SchedulerService Scheduler { get; internal set; } = null!; // Initialized in ConfigureServices |
| | | 142 | | |
| | | 143 | | /// <summary> |
| | | 144 | | /// Gets the ad-hoc task service used for running one-off tasks (PowerShell, C#, VB.NET). |
| | | 145 | | /// </summary> |
| | 0 | 146 | | public KestrunTaskService Tasks { get; internal set; } = null!; // Initialized via AddTasks() |
| | | 147 | | |
| | | 148 | | /// <summary> |
| | | 149 | | /// Gets the stack used for managing route groups in the Kestrun host. |
| | | 150 | | /// </summary> |
| | 323 | 151 | | public System.Collections.Stack RouteGroupStack { get; } = new(); |
| | | 152 | | |
| | | 153 | | |
| | | 154 | | /// <summary> |
| | | 155 | | /// Gets the registered routes in the Kestrun host. |
| | | 156 | | /// </summary> |
| | 0 | 157 | | public Dictionary<(string, string), MapRouteOptions> RegisteredRoutes => _registeredRoutes; |
| | | 158 | | |
| | | 159 | | /// <summary> |
| | | 160 | | /// Gets the registered authentication schemes in the Kestrun host. |
| | | 161 | | /// </summary> |
| | 343 | 162 | | public AuthenticationRegistry RegisteredAuthentications { get; } = new(); |
| | | 163 | | |
| | | 164 | | /// <summary> |
| | | 165 | | /// Gets or sets the default cache control settings for HTTP responses. |
| | | 166 | | /// </summary> |
| | 4 | 167 | | public CacheControlHeaderValue? DefaultCacheControl { get; internal set; } |
| | | 168 | | |
| | | 169 | | /// <summary> |
| | | 170 | | /// Gets the shared state manager for managing shared data across requests and sessions. |
| | | 171 | | /// </summary> |
| | 100 | 172 | | public bool PowershellMiddlewareEnabled { get; set; } = false; |
| | | 173 | | |
| | | 174 | | /// <summary> |
| | | 175 | | /// Gets or sets a value indicating whether this instance is the default Kestrun host. |
| | | 176 | | /// </summary> |
| | 1 | 177 | | public bool DefaultHost { get; internal set; } |
| | | 178 | | |
| | | 179 | | /// <summary> |
| | | 180 | | /// Gets or sets the status code options for configuring status code pages. |
| | | 181 | | /// </summary> |
| | | 182 | | public StatusCodeOptions? StatusCodeOptions |
| | | 183 | | { |
| | 80 | 184 | | get => _statusCodeOptions; |
| | | 185 | | set |
| | | 186 | | { |
| | 0 | 187 | | if (IsConfigured) |
| | | 188 | | { |
| | 0 | 189 | | throw new InvalidOperationException("Cannot modify StatusCodeOptions after configuration is applied."); |
| | | 190 | | } |
| | 0 | 191 | | _statusCodeOptions = value; |
| | 0 | 192 | | } |
| | | 193 | | } |
| | | 194 | | |
| | | 195 | | /// <summary> |
| | | 196 | | /// Gets or sets the exception options for configuring exception handling. |
| | | 197 | | /// </summary> |
| | | 198 | | public ExceptionOptions? ExceptionOptions |
| | | 199 | | { |
| | 91 | 200 | | get => _exceptionOptions; |
| | | 201 | | set |
| | | 202 | | { |
| | 5 | 203 | | if (IsConfigured) |
| | | 204 | | { |
| | 0 | 205 | | throw new InvalidOperationException("Cannot modify ExceptionOptions after configuration is applied."); |
| | | 206 | | } |
| | 5 | 207 | | _exceptionOptions = value; |
| | 5 | 208 | | } |
| | | 209 | | } |
| | | 210 | | |
| | | 211 | | /// <summary> |
| | | 212 | | /// Gets or sets the forwarded headers options for configuring forwarded headers handling. |
| | | 213 | | /// </summary> |
| | | 214 | | public ForwardedHeadersOptions? ForwardedHeaderOptions |
| | | 215 | | { |
| | 83 | 216 | | get => _forwardedHeaderOptions; |
| | | 217 | | set |
| | | 218 | | { |
| | 4 | 219 | | if (IsConfigured) |
| | | 220 | | { |
| | 1 | 221 | | throw new InvalidOperationException("Cannot modify ForwardedHeaderOptions after configuration is applied |
| | | 222 | | } |
| | 3 | 223 | | _forwardedHeaderOptions = value; |
| | 3 | 224 | | } |
| | | 225 | | } |
| | | 226 | | |
| | | 227 | | #endregion |
| | | 228 | | |
| | | 229 | | // Accepts optional module paths (from PowerShell) |
| | | 230 | | #region Constructor |
| | | 231 | | |
| | | 232 | | /// <summary> |
| | | 233 | | /// Initializes a new instance of the <see cref="KestrunHost"/> class with the specified application name, root dire |
| | | 234 | | /// </summary> |
| | | 235 | | /// <param name="appName">The name of the application.</param> |
| | | 236 | | /// <param name="kestrunRoot">The root directory for the Kestrun application.</param> |
| | | 237 | | /// <param name="modulePathsObj">An array of module paths to be loaded.</param> |
| | | 238 | | public KestrunHost(string? appName, string? kestrunRoot = null, string[]? modulePathsObj = null) : |
| | 96 | 239 | | this(appName, Log.Logger, kestrunRoot, modulePathsObj) |
| | 96 | 240 | | { } |
| | | 241 | | |
| | | 242 | | /// <summary> |
| | | 243 | | /// Initializes a new instance of the <see cref="KestrunHost"/> class with the specified application name, logger, r |
| | | 244 | | /// </summary> |
| | | 245 | | /// <param name="appName">The name of the application.</param> |
| | | 246 | | /// <param name="logger">The Serilog logger instance to use.</param> |
| | | 247 | | /// <param name="kestrunRoot">The root directory for the Kestrun application.</param> |
| | | 248 | | /// <param name="modulePathsObj">An array of module paths to be loaded.</param> |
| | | 249 | | /// <param name="args">Command line arguments to pass to the application.</param> |
| | 323 | 250 | | public KestrunHost(string? appName, Serilog.ILogger logger, |
| | 323 | 251 | | string? kestrunRoot = null, string[]? modulePathsObj = null, string[]? args = null) |
| | | 252 | | { |
| | | 253 | | // ① Logger |
| | 323 | 254 | | Logger = logger ?? Log.Logger; |
| | 323 | 255 | | LogConstructorArgs(appName, logger == null, kestrunRoot, modulePathsObj?.Length ?? 0); |
| | | 256 | | |
| | | 257 | | // ② Working directory/root |
| | 323 | 258 | | SetWorkingDirectoryIfNeeded(kestrunRoot); |
| | | 259 | | |
| | | 260 | | // ③ Ensure Kestrun module path is available |
| | 323 | 261 | | AddKestrunModulePathIfMissing(modulePathsObj); |
| | | 262 | | |
| | | 263 | | // ④ WebApplicationBuilder |
| | 323 | 264 | | Builder = WebApplication.CreateBuilder(new WebApplicationOptions() |
| | 323 | 265 | | { |
| | 323 | 266 | | ContentRootPath = string.IsNullOrWhiteSpace(kestrunRoot) ? Directory.GetCurrentDirectory() : kestrunRoot, |
| | 323 | 267 | | Args = args ?? [], |
| | 323 | 268 | | EnvironmentName = EnvironmentHelper.Name |
| | 323 | 269 | | }); |
| | | 270 | | // Enable Serilog for the host |
| | 323 | 271 | | _ = Builder.Host.UseSerilog(); |
| | | 272 | | |
| | | 273 | | // Make this KestrunHost available via DI so framework-created components (e.g., auth handlers) |
| | | 274 | | // can resolve it. We register the current instance as a singleton. |
| | 323 | 275 | | _ = Builder.Services.AddSingleton(this); |
| | | 276 | | |
| | | 277 | | // Expose Serilog.ILogger via DI for components (e.g., SignalR hubs) that depend on Serilog's logger |
| | | 278 | | // ASP.NET Core registers Microsoft.Extensions.Logging.ILogger by default; we also bind Serilog.ILogger |
| | | 279 | | // to the same instance so constructors like `KestrunHub(Serilog.ILogger logger)` resolve properly. |
| | 323 | 280 | | _ = Builder.Services.AddSingleton(Logger); |
| | | 281 | | |
| | | 282 | | // ⑤ Options |
| | 323 | 283 | | InitializeOptions(appName); |
| | | 284 | | |
| | | 285 | | // ⑥ Add user-provided module paths |
| | 323 | 286 | | AddUserModulePaths(modulePathsObj); |
| | | 287 | | |
| | 323 | 288 | | Logger.Information("Current working directory: {CurrentDirectory}", Directory.GetCurrentDirectory()); |
| | 323 | 289 | | } |
| | | 290 | | #endregion |
| | | 291 | | |
| | | 292 | | #region Helpers |
| | | 293 | | |
| | | 294 | | |
| | | 295 | | /// <summary> |
| | | 296 | | /// Logs constructor arguments at Debug level for diagnostics. |
| | | 297 | | /// </summary> |
| | | 298 | | private void LogConstructorArgs(string? appName, bool defaultLogger, string? kestrunRoot, int modulePathsLength) |
| | | 299 | | { |
| | 323 | 300 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 301 | | { |
| | 202 | 302 | | Logger.Debug( |
| | 202 | 303 | | "KestrunHost ctor: AppName={AppName}, DefaultLogger={DefaultLogger}, KestrunRoot={KestrunRoot}, ModulePa |
| | 202 | 304 | | appName, defaultLogger, kestrunRoot, modulePathsLength); |
| | | 305 | | } |
| | 323 | 306 | | } |
| | | 307 | | |
| | | 308 | | /// <summary> |
| | | 309 | | /// Sets the current working directory to the provided Kestrun root if needed and stores it. |
| | | 310 | | /// </summary> |
| | | 311 | | /// <param name="kestrunRoot">The Kestrun root directory path.</param> |
| | | 312 | | private void SetWorkingDirectoryIfNeeded(string? kestrunRoot) |
| | | 313 | | { |
| | 323 | 314 | | if (string.IsNullOrWhiteSpace(kestrunRoot)) |
| | | 315 | | { |
| | 190 | 316 | | return; |
| | | 317 | | } |
| | | 318 | | |
| | 133 | 319 | | if (!string.Equals(Directory.GetCurrentDirectory(), kestrunRoot, StringComparison.Ordinal)) |
| | | 320 | | { |
| | 96 | 321 | | Directory.SetCurrentDirectory(kestrunRoot); |
| | 96 | 322 | | Logger.Information("Changed current directory to Kestrun root: {KestrunRoot}", kestrunRoot); |
| | | 323 | | } |
| | | 324 | | else |
| | | 325 | | { |
| | 37 | 326 | | Logger.Verbose("Current directory is already set to Kestrun root: {KestrunRoot}", kestrunRoot); |
| | | 327 | | } |
| | | 328 | | |
| | 133 | 329 | | KestrunRoot = kestrunRoot; |
| | 133 | 330 | | } |
| | | 331 | | |
| | | 332 | | /// <summary> |
| | | 333 | | /// Ensures the core Kestrun module path is present; if missing, locates and adds it. |
| | | 334 | | /// </summary> |
| | | 335 | | /// <param name="modulePathsObj">The array of module paths to check.</param> |
| | | 336 | | private void AddKestrunModulePathIfMissing(string[]? modulePathsObj) |
| | | 337 | | { |
| | 323 | 338 | | var needsLocate = modulePathsObj is null || |
| | 360 | 339 | | (modulePathsObj?.Any(p => p.Contains("Kestrun.psm1", StringComparison.Ordinal)) == false); |
| | 323 | 340 | | if (!needsLocate) |
| | | 341 | | { |
| | 37 | 342 | | return; |
| | | 343 | | } |
| | | 344 | | |
| | 286 | 345 | | var kestrunModulePath = PowerShellModuleLocator.LocateKestrunModule(); |
| | 286 | 346 | | if (string.IsNullOrWhiteSpace(kestrunModulePath)) |
| | | 347 | | { |
| | 0 | 348 | | Logger.Fatal("Kestrun module not found. Ensure the Kestrun module is installed."); |
| | 0 | 349 | | throw new FileNotFoundException("Kestrun module not found."); |
| | | 350 | | } |
| | | 351 | | |
| | 286 | 352 | | Logger.Information("Found Kestrun module at: {KestrunModulePath}", kestrunModulePath); |
| | 286 | 353 | | Logger.Verbose("Adding Kestrun module path: {KestrunModulePath}", kestrunModulePath); |
| | 286 | 354 | | _modulePaths.Add(kestrunModulePath); |
| | 286 | 355 | | } |
| | | 356 | | |
| | | 357 | | /// <summary> |
| | | 358 | | /// Initializes Kestrun options and sets the application name when provided. |
| | | 359 | | /// </summary> |
| | | 360 | | /// <param name="appName">The name of the application.</param> |
| | | 361 | | private void InitializeOptions(string? appName) |
| | | 362 | | { |
| | 323 | 363 | | if (string.IsNullOrEmpty(appName)) |
| | | 364 | | { |
| | 1 | 365 | | Logger.Information("No application name provided, using default."); |
| | 1 | 366 | | Options = new KestrunOptions(); |
| | | 367 | | } |
| | | 368 | | else |
| | | 369 | | { |
| | 322 | 370 | | Logger.Information("Setting application name: {AppName}", appName); |
| | 322 | 371 | | Options = new KestrunOptions { ApplicationName = appName }; |
| | | 372 | | } |
| | 322 | 373 | | } |
| | | 374 | | |
| | | 375 | | /// <summary> |
| | | 376 | | /// Adds user-provided module paths if they exist, logging warnings for invalid entries. |
| | | 377 | | /// </summary> |
| | | 378 | | /// <param name="modulePathsObj">The array of module paths to check.</param> |
| | | 379 | | private void AddUserModulePaths(string[]? modulePathsObj) |
| | | 380 | | { |
| | 323 | 381 | | if (modulePathsObj is IEnumerable<object> modulePathsEnum) |
| | | 382 | | { |
| | 148 | 383 | | foreach (var modPathObj in modulePathsEnum) |
| | | 384 | | { |
| | 37 | 385 | | if (modPathObj is string modPath && !string.IsNullOrWhiteSpace(modPath)) |
| | | 386 | | { |
| | 37 | 387 | | if (File.Exists(modPath)) |
| | | 388 | | { |
| | 37 | 389 | | Logger.Information("[KestrunHost] Adding module path: {ModPath}", modPath); |
| | 37 | 390 | | _modulePaths.Add(modPath); |
| | | 391 | | } |
| | | 392 | | else |
| | | 393 | | { |
| | 0 | 394 | | Logger.Warning("[KestrunHost] Module path does not exist: {ModPath}", modPath); |
| | | 395 | | } |
| | | 396 | | } |
| | | 397 | | else |
| | | 398 | | { |
| | 0 | 399 | | Logger.Warning("[KestrunHost] Invalid module path provided."); |
| | | 400 | | } |
| | | 401 | | } |
| | | 402 | | } |
| | 323 | 403 | | } |
| | | 404 | | #endregion |
| | | 405 | | |
| | | 406 | | |
| | | 407 | | #region Health Probes |
| | | 408 | | |
| | | 409 | | /// <summary> |
| | | 410 | | /// Registers the provided <see cref="IProbe"/> instance with the host. |
| | | 411 | | /// </summary> |
| | | 412 | | /// <param name="probe">The probe to register.</param> |
| | | 413 | | /// <returns>The current <see cref="KestrunHost"/> instance.</returns> |
| | | 414 | | public KestrunHost AddProbe(IProbe probe) |
| | | 415 | | { |
| | 0 | 416 | | ArgumentNullException.ThrowIfNull(probe); |
| | 0 | 417 | | RegisterProbeInternal(probe); |
| | 0 | 418 | | return this; |
| | | 419 | | } |
| | | 420 | | |
| | | 421 | | /// <summary> |
| | | 422 | | /// Registers a delegate-based probe. |
| | | 423 | | /// </summary> |
| | | 424 | | /// <param name="name">Probe name.</param> |
| | | 425 | | /// <param name="tags">Optional tag list used for filtering.</param> |
| | | 426 | | /// <param name="callback">Delegate executed when the probe runs.</param> |
| | | 427 | | /// <returns>The current <see cref="KestrunHost"/> instance.</returns> |
| | | 428 | | public KestrunHost AddProbe(string name, string[]? tags, Func<CancellationToken, Task<ProbeResult>> callback) |
| | | 429 | | { |
| | 0 | 430 | | ArgumentException.ThrowIfNullOrEmpty(name); |
| | 0 | 431 | | ArgumentNullException.ThrowIfNull(callback); |
| | | 432 | | |
| | 0 | 433 | | var probe = new DelegateProbe(name, tags, callback); |
| | 0 | 434 | | RegisterProbeInternal(probe); |
| | 0 | 435 | | return this; |
| | | 436 | | } |
| | | 437 | | |
| | | 438 | | /// <summary> |
| | | 439 | | /// Registers a script-based probe written in any supported language. |
| | | 440 | | /// </summary> |
| | | 441 | | /// <param name="name">Probe name.</param> |
| | | 442 | | /// <param name="tags">Optional tag list used for filtering.</param> |
| | | 443 | | /// <param name="code">Script contents.</param> |
| | | 444 | | /// <param name="language">Optional language override. When null, <see cref="KestrunOptions.Health"/> defaults are u |
| | | 445 | | /// <param name="arguments">Optional argument dictionary exposed to the script.</param> |
| | | 446 | | /// <param name="extraImports">Optional language-specific imports.</param> |
| | | 447 | | /// <param name="extraRefs">Optional additional assembly references.</param> |
| | | 448 | | /// <returns>The current <see cref="KestrunHost"/> instance.</returns> |
| | | 449 | | public KestrunHost AddProbe( |
| | | 450 | | string name, |
| | | 451 | | string[]? tags, |
| | | 452 | | string code, |
| | | 453 | | ScriptLanguage? language = null, |
| | | 454 | | IReadOnlyDictionary<string, object?>? arguments = null, |
| | | 455 | | string[]? extraImports = null, |
| | | 456 | | Assembly[]? extraRefs = null) |
| | | 457 | | { |
| | 0 | 458 | | ArgumentException.ThrowIfNullOrEmpty(name); |
| | 0 | 459 | | ArgumentException.ThrowIfNullOrEmpty(code); |
| | | 460 | | |
| | 0 | 461 | | var effectiveLanguage = language ?? Options.Health.DefaultScriptLanguage; |
| | 0 | 462 | | var logger = Logger.ForContext("HealthProbe", name); |
| | 0 | 463 | | var probe = ScriptProbeFactory.Create( |
| | 0 | 464 | | name, |
| | 0 | 465 | | tags, |
| | 0 | 466 | | effectiveLanguage, |
| | 0 | 467 | | code, |
| | 0 | 468 | | logger, |
| | 0 | 469 | | effectiveLanguage == ScriptLanguage.PowerShell ? () => RunspacePool : null, |
| | 0 | 470 | | arguments, |
| | 0 | 471 | | extraImports, |
| | 0 | 472 | | extraRefs); |
| | | 473 | | |
| | 0 | 474 | | RegisterProbeInternal(probe); |
| | 0 | 475 | | return this; |
| | | 476 | | } |
| | | 477 | | |
| | | 478 | | /// <summary> |
| | | 479 | | /// Returns a snapshot of the currently registered probes. |
| | | 480 | | /// </summary> |
| | | 481 | | internal IReadOnlyList<IProbe> GetHealthProbesSnapshot() |
| | 0 | 482 | | { |
| | | 483 | | lock (_healthProbeLock) |
| | | 484 | | { |
| | 0 | 485 | | return [.. HealthProbes]; |
| | | 486 | | } |
| | 0 | 487 | | } |
| | | 488 | | |
| | | 489 | | private void RegisterProbeInternal(IProbe probe) |
| | 54 | 490 | | { |
| | | 491 | | lock (_healthProbeLock) |
| | | 492 | | { |
| | 54 | 493 | | var index = HealthProbes.FindIndex(p => string.Equals(p.Name, probe.Name, StringComparison.OrdinalIgnoreCase |
| | 54 | 494 | | if (index >= 0) |
| | | 495 | | { |
| | 0 | 496 | | HealthProbes[index] = probe; |
| | 0 | 497 | | Logger.Information("Replaced health probe {ProbeName}.", probe.Name); |
| | | 498 | | } |
| | | 499 | | else |
| | | 500 | | { |
| | 54 | 501 | | HealthProbes.Add(probe); |
| | 54 | 502 | | Logger.Information("Registered health probe {ProbeName}.", probe.Name); |
| | | 503 | | } |
| | 54 | 504 | | } |
| | 54 | 505 | | } |
| | | 506 | | |
| | | 507 | | #endregion |
| | | 508 | | |
| | | 509 | | |
| | | 510 | | #region ListenerOptions |
| | | 511 | | |
| | | 512 | | /// <summary> |
| | | 513 | | /// Configures a listener for the Kestrun host with the specified port, optional IP address, certificate, protocols, |
| | | 514 | | /// </summary> |
| | | 515 | | /// <param name="port">The port number to listen on.</param> |
| | | 516 | | /// <param name="ipAddress">The IP address to bind to. If null, binds to any address.</param> |
| | | 517 | | /// <param name="x509Certificate">The X509 certificate for HTTPS. If null, HTTPS is not used.</param> |
| | | 518 | | /// <param name="protocols">The HTTP protocols to use.</param> |
| | | 519 | | /// <param name="useConnectionLogging">Specifies whether to enable connection logging.</param> |
| | | 520 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 521 | | public KestrunHost ConfigureListener( |
| | | 522 | | int port, |
| | | 523 | | IPAddress? ipAddress = null, |
| | | 524 | | X509Certificate2? x509Certificate = null, |
| | | 525 | | HttpProtocols protocols = HttpProtocols.Http1, |
| | | 526 | | bool useConnectionLogging = false) |
| | | 527 | | { |
| | 37 | 528 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 529 | | { |
| | 18 | 530 | | Logger.Debug("ConfigureListener port={Port}, ipAddress={IPAddress}, protocols={Protocols}, useConnectionLogg |
| | | 531 | | } |
| | | 532 | | |
| | 37 | 533 | | if (protocols == HttpProtocols.Http1AndHttp2AndHttp3 && !CcUtilities.PreviewFeaturesEnabled()) |
| | | 534 | | { |
| | 2 | 535 | | Logger.Warning("Http3 is not supported in this version of Kestrun. Using Http1 and Http2 only."); |
| | 2 | 536 | | protocols = HttpProtocols.Http1AndHttp2; |
| | | 537 | | } |
| | | 538 | | |
| | 37 | 539 | | Options.Listeners.Add(new ListenerOptions |
| | 37 | 540 | | { |
| | 37 | 541 | | IPAddress = ipAddress ?? IPAddress.Any, |
| | 37 | 542 | | Port = port, |
| | 37 | 543 | | UseHttps = x509Certificate != null, |
| | 37 | 544 | | X509Certificate = x509Certificate, |
| | 37 | 545 | | Protocols = protocols, |
| | 37 | 546 | | UseConnectionLogging = useConnectionLogging |
| | 37 | 547 | | }); |
| | 37 | 548 | | return this; |
| | | 549 | | } |
| | | 550 | | |
| | | 551 | | /// <summary> |
| | | 552 | | /// Configures a listener for the Kestrun host with the specified port, optional IP address, and connection logging. |
| | | 553 | | /// </summary> |
| | | 554 | | /// <param name="port">The port number to listen on.</param> |
| | | 555 | | /// <param name="ipAddress">The IP address to bind to. If null, binds to any address.</param> |
| | | 556 | | /// <param name="useConnectionLogging">Specifies whether to enable connection logging.</param> |
| | | 557 | | public void ConfigureListener( |
| | | 558 | | int port, |
| | | 559 | | IPAddress? ipAddress = null, |
| | 20 | 560 | | bool useConnectionLogging = false) => _ = ConfigureListener(port: port, ipAddress: ipAddress, x509Certificate: null, |
| | | 561 | | |
| | | 562 | | /// <summary> |
| | | 563 | | /// Configures a listener for the Kestrun host with the specified port and connection logging option. |
| | | 564 | | /// </summary> |
| | | 565 | | /// <param name="port">The port number to listen on.</param> |
| | | 566 | | /// <param name="useConnectionLogging">Specifies whether to enable connection logging.</param> |
| | | 567 | | public void ConfigureListener( |
| | | 568 | | int port, |
| | 1 | 569 | | bool useConnectionLogging = false) => _ = ConfigureListener(port: port, ipAddress: null, x509Certificate: null, prot |
| | | 570 | | |
| | | 571 | | |
| | | 572 | | /// <summary> |
| | | 573 | | /// Configures listeners for the Kestrun host by resolving the specified host name to IP addresses and binding to ea |
| | | 574 | | /// </summary> |
| | | 575 | | /// <param name="hostName">The host name to resolve and bind to.</param> |
| | | 576 | | /// <param name="port">The port number to listen on.</param> |
| | | 577 | | /// <param name="x509Certificate">The X509 certificate for HTTPS. If null, HTTPS is not used.</param> |
| | | 578 | | /// <param name="protocols">The HTTP protocols to use.</param> |
| | | 579 | | /// <param name="useConnectionLogging">Specifies whether to enable connection logging.</param> |
| | | 580 | | /// <param name="families">Optional array of address families to filter resolved addresses (e.g., IPv4-only).</param |
| | | 581 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 582 | | /// <exception cref="ArgumentException">Thrown when the host name is null or whitespace.</exception> |
| | | 583 | | /// <exception cref="InvalidOperationException">Thrown when no valid IP addresses are resolved.</exception> |
| | | 584 | | public KestrunHost ConfigureListener( |
| | | 585 | | string hostName, |
| | | 586 | | int port, |
| | | 587 | | X509Certificate2? x509Certificate = null, |
| | | 588 | | HttpProtocols protocols = HttpProtocols.Http1, |
| | | 589 | | bool useConnectionLogging = false, |
| | | 590 | | AddressFamily[]? families = null) // e.g. new[] { AddressFamily.InterNetwork } for IPv4-only |
| | | 591 | | { |
| | 0 | 592 | | if (string.IsNullOrWhiteSpace(hostName)) |
| | | 593 | | { |
| | 0 | 594 | | throw new ArgumentException("Host name must be provided.", nameof(hostName)); |
| | | 595 | | } |
| | | 596 | | |
| | | 597 | | // If caller passed an IP literal, just bind once. |
| | 0 | 598 | | if (IPAddress.TryParse(hostName, out var parsedIp)) |
| | | 599 | | { |
| | 0 | 600 | | _ = ConfigureListener(port, parsedIp, x509Certificate, protocols, useConnectionLogging); |
| | 0 | 601 | | return this; |
| | | 602 | | } |
| | | 603 | | |
| | | 604 | | // Resolve and bind to ALL matching addresses (IPv4/IPv6) |
| | 0 | 605 | | var addrs = Dns.GetHostAddresses(hostName) |
| | 0 | 606 | | .Where(a => families is null || families.Length == 0 || families.Contains(a.AddressFamily)) |
| | 0 | 607 | | .Where(a => a.AddressFamily is AddressFamily.InterNetwork or AddressFamily.InterNetworkV6) |
| | 0 | 608 | | .ToArray(); |
| | | 609 | | |
| | 0 | 610 | | if (addrs.Length == 0) |
| | | 611 | | { |
| | 0 | 612 | | throw new InvalidOperationException($"No IPv4/IPv6 addresses resolved for host '{hostName}'."); |
| | | 613 | | } |
| | | 614 | | |
| | 0 | 615 | | foreach (var addr in addrs) |
| | | 616 | | { |
| | 0 | 617 | | _ = ConfigureListener(port, addr, x509Certificate, protocols, useConnectionLogging); |
| | | 618 | | } |
| | | 619 | | |
| | 0 | 620 | | return this; |
| | | 621 | | } |
| | | 622 | | |
| | | 623 | | /// <summary> |
| | | 624 | | /// Configures listeners for the Kestrun host based on the provided absolute URI, resolving the host to IP addresses |
| | | 625 | | /// </summary> |
| | | 626 | | /// <param name="uri">The absolute URI to configure the listener for.</param> |
| | | 627 | | /// <param name="x509Certificate">The X509 certificate for HTTPS. If null, HTTPS is not used.</param> |
| | | 628 | | /// <param name="protocols">The HTTP protocols to use.</param> |
| | | 629 | | /// <param name="useConnectionLogging">Specifies whether to enable connection logging.</param> |
| | | 630 | | /// <param name="families">Optional array of address families to filter resolved addresses (e.g., IPv4-only).</param |
| | | 631 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 632 | | /// <exception cref="ArgumentException">Thrown when the provided URI is not absolute.</exception> |
| | | 633 | | /// <exception cref="InvalidOperationException">Thrown when no valid IP addresses are resolved.</exception> |
| | | 634 | | public KestrunHost ConfigureListener( |
| | | 635 | | Uri uri, |
| | | 636 | | X509Certificate2? x509Certificate = null, |
| | | 637 | | HttpProtocols? protocols = null, |
| | | 638 | | bool useConnectionLogging = false, |
| | | 639 | | AddressFamily[]? families = null) |
| | | 640 | | { |
| | 0 | 641 | | ArgumentNullException.ThrowIfNull(uri); |
| | | 642 | | |
| | 0 | 643 | | if (!uri.IsAbsoluteUri) |
| | | 644 | | { |
| | 0 | 645 | | throw new ArgumentException("URL must be absolute.", nameof(uri)); |
| | | 646 | | } |
| | | 647 | | |
| | 0 | 648 | | var isHttps = uri.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase); |
| | 0 | 649 | | var port = uri.IsDefaultPort ? (isHttps ? 443 : 80) : uri.Port; |
| | | 650 | | |
| | | 651 | | // Default: HTTPS → H1+H2, HTTP → H1 |
| | 0 | 652 | | var chosenProtocols = protocols ?? (isHttps ? HttpProtocols.Http1AndHttp2 : HttpProtocols.Http1); |
| | | 653 | | |
| | | 654 | | // Delegate to hostname overload (which will resolve or handle IP literal) |
| | 0 | 655 | | return ConfigureListener( |
| | 0 | 656 | | hostName: uri.Host, |
| | 0 | 657 | | port: port, |
| | 0 | 658 | | x509Certificate: x509Certificate, |
| | 0 | 659 | | protocols: chosenProtocols, |
| | 0 | 660 | | useConnectionLogging: useConnectionLogging, |
| | 0 | 661 | | families: families |
| | 0 | 662 | | ); |
| | | 663 | | } |
| | | 664 | | |
| | | 665 | | #endregion |
| | | 666 | | |
| | | 667 | | #region Configuration |
| | | 668 | | |
| | | 669 | | |
| | | 670 | | /// <summary> |
| | | 671 | | /// Validates if configuration can be applied and returns early if already configured. |
| | | 672 | | /// </summary> |
| | | 673 | | /// <returns>True if configuration should proceed, false if it should be skipped.</returns> |
| | | 674 | | internal bool ValidateConfiguration() |
| | | 675 | | { |
| | 74 | 676 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 677 | | { |
| | 41 | 678 | | Logger.Debug("EnableConfiguration(options) called"); |
| | | 679 | | } |
| | | 680 | | |
| | 74 | 681 | | if (IsConfigured) |
| | | 682 | | { |
| | 18 | 683 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 684 | | { |
| | 2 | 685 | | Logger.Debug("Configuration already applied, skipping"); |
| | | 686 | | } |
| | 18 | 687 | | return false; // Already configured |
| | | 688 | | } |
| | | 689 | | |
| | 56 | 690 | | return true; |
| | | 691 | | } |
| | | 692 | | |
| | | 693 | | /// <summary> |
| | | 694 | | /// Creates and initializes the runspace pool for PowerShell execution. |
| | | 695 | | /// </summary> |
| | | 696 | | /// <param name="userVariables">User-defined variables to inject into the runspace pool.</param> |
| | | 697 | | /// <param name="userFunctions">User-defined functions to inject into the runspace pool.</param> |
| | | 698 | | /// <exception cref="InvalidOperationException">Thrown when runspace pool creation fails.</exception> |
| | | 699 | | internal void InitializeRunspacePool(Dictionary<string, object>? userVariables, Dictionary<string, string>? userFunc |
| | | 700 | | { |
| | 57 | 701 | | _runspacePool = CreateRunspacePool(Options.MaxRunspaces, userVariables, userFunctions); |
| | 57 | 702 | | if (_runspacePool == null) |
| | | 703 | | { |
| | 0 | 704 | | throw new InvalidOperationException("Failed to create runspace pool."); |
| | | 705 | | } |
| | | 706 | | |
| | 57 | 707 | | if (Logger.IsEnabled(LogEventLevel.Verbose)) |
| | | 708 | | { |
| | 0 | 709 | | Logger.Verbose("Runspace pool created with max runspaces: {MaxRunspaces}", Options.MaxRunspaces); |
| | | 710 | | } |
| | 57 | 711 | | } |
| | | 712 | | |
| | | 713 | | /// <summary> |
| | | 714 | | /// Configures the Kestrel web server with basic options. |
| | | 715 | | /// </summary> |
| | | 716 | | internal void ConfigureKestrelBase() |
| | | 717 | | { |
| | 55 | 718 | | _ = Builder.WebHost.UseKestrel(opts => |
| | 55 | 719 | | { |
| | 54 | 720 | | opts.CopyFromTemplate(Options.ServerOptions); |
| | 109 | 721 | | }); |
| | 55 | 722 | | } |
| | | 723 | | |
| | | 724 | | /// <summary> |
| | | 725 | | /// Configures named pipe listeners if supported on the current platform. |
| | | 726 | | /// </summary> |
| | | 727 | | internal void ConfigureNamedPipes() |
| | | 728 | | { |
| | 56 | 729 | | if (Options.NamedPipeOptions is not null) |
| | | 730 | | { |
| | 1 | 731 | | if (OperatingSystem.IsWindows()) |
| | | 732 | | { |
| | 0 | 733 | | _ = Builder.WebHost.UseNamedPipes(opts => |
| | 0 | 734 | | { |
| | 0 | 735 | | opts.ListenerQueueCount = Options.NamedPipeOptions.ListenerQueueCount; |
| | 0 | 736 | | opts.MaxReadBufferSize = Options.NamedPipeOptions.MaxReadBufferSize; |
| | 0 | 737 | | opts.MaxWriteBufferSize = Options.NamedPipeOptions.MaxWriteBufferSize; |
| | 0 | 738 | | opts.CurrentUserOnly = Options.NamedPipeOptions.CurrentUserOnly; |
| | 0 | 739 | | opts.PipeSecurity = Options.NamedPipeOptions.PipeSecurity; |
| | 0 | 740 | | }); |
| | | 741 | | } |
| | | 742 | | else |
| | | 743 | | { |
| | 1 | 744 | | Logger.Verbose("Named pipe listeners configuration is supported only on Windows; skipping UseNamedPipes |
| | | 745 | | } |
| | | 746 | | } |
| | 56 | 747 | | } |
| | | 748 | | |
| | | 749 | | /// <summary> |
| | | 750 | | /// Configures HTTPS connection adapter defaults. |
| | | 751 | | /// </summary> |
| | | 752 | | /// <param name="serverOptions">The Kestrel server options to configure.</param> |
| | | 753 | | internal void ConfigureHttpsAdapter(KestrelServerOptions serverOptions) |
| | | 754 | | { |
| | 55 | 755 | | if (Options.HttpsConnectionAdapter is not null) |
| | | 756 | | { |
| | 0 | 757 | | Logger.Verbose("Applying HTTPS connection adapter options from KestrunOptions."); |
| | | 758 | | |
| | | 759 | | // Apply HTTPS defaults if needed |
| | 0 | 760 | | serverOptions.ConfigureHttpsDefaults(httpsOptions => |
| | 0 | 761 | | { |
| | 0 | 762 | | httpsOptions.SslProtocols = Options.HttpsConnectionAdapter.SslProtocols; |
| | 0 | 763 | | httpsOptions.ClientCertificateMode = Options.HttpsConnectionAdapter.ClientCertificateMode; |
| | 0 | 764 | | httpsOptions.ClientCertificateValidation = Options.HttpsConnectionAdapter.ClientCertificateValidation; |
| | 0 | 765 | | httpsOptions.CheckCertificateRevocation = Options.HttpsConnectionAdapter.CheckCertificateRevocation; |
| | 0 | 766 | | httpsOptions.ServerCertificate = Options.HttpsConnectionAdapter.ServerCertificate; |
| | 0 | 767 | | httpsOptions.ServerCertificateChain = Options.HttpsConnectionAdapter.ServerCertificateChain; |
| | 0 | 768 | | httpsOptions.ServerCertificateSelector = Options.HttpsConnectionAdapter.ServerCertificateSelector; |
| | 0 | 769 | | httpsOptions.HandshakeTimeout = Options.HttpsConnectionAdapter.HandshakeTimeout; |
| | 0 | 770 | | httpsOptions.OnAuthenticate = Options.HttpsConnectionAdapter.OnAuthenticate; |
| | 0 | 771 | | }); |
| | | 772 | | } |
| | 55 | 773 | | } |
| | | 774 | | |
| | | 775 | | /// <summary> |
| | | 776 | | /// Binds all configured listeners (Unix sockets, named pipes, TCP) to the server. |
| | | 777 | | /// </summary> |
| | | 778 | | /// <param name="serverOptions">The Kestrel server options to configure.</param> |
| | | 779 | | internal void BindListeners(KestrelServerOptions serverOptions) |
| | | 780 | | { |
| | | 781 | | // Unix domain socket listeners |
| | 112 | 782 | | foreach (var unixSocket in Options.ListenUnixSockets) |
| | | 783 | | { |
| | 0 | 784 | | if (!string.IsNullOrWhiteSpace(unixSocket)) |
| | | 785 | | { |
| | 0 | 786 | | Logger.Verbose("Binding Unix socket: {Sock}", unixSocket); |
| | 0 | 787 | | serverOptions.ListenUnixSocket(unixSocket); |
| | | 788 | | // NOTE: control access via directory perms/umask; UDS file perms are inherited from process umask |
| | | 789 | | // Prefer placing the socket under a group-owned dir (e.g., /var/run/kestrun) with 0770. |
| | | 790 | | } |
| | | 791 | | } |
| | | 792 | | |
| | | 793 | | // Named pipe listeners |
| | 112 | 794 | | foreach (var namedPipeName in Options.NamedPipeNames) |
| | | 795 | | { |
| | 0 | 796 | | if (!string.IsNullOrWhiteSpace(namedPipeName)) |
| | | 797 | | { |
| | 0 | 798 | | Logger.Verbose("Binding Named Pipe: {Pipe}", namedPipeName); |
| | 0 | 799 | | serverOptions.ListenNamedPipe(namedPipeName); |
| | | 800 | | } |
| | | 801 | | } |
| | | 802 | | |
| | | 803 | | // TCP listeners |
| | 172 | 804 | | foreach (var opt in Options.Listeners) |
| | | 805 | | { |
| | 30 | 806 | | serverOptions.Listen(opt.IPAddress, opt.Port, listenOptions => |
| | 30 | 807 | | { |
| | 30 | 808 | | listenOptions.Protocols = opt.Protocols; |
| | 30 | 809 | | listenOptions.DisableAltSvcHeader = opt.DisableAltSvcHeader; |
| | 30 | 810 | | if (opt.UseHttps && opt.X509Certificate is not null) |
| | 30 | 811 | | { |
| | 2 | 812 | | _ = listenOptions.UseHttps(opt.X509Certificate); |
| | 30 | 813 | | } |
| | 30 | 814 | | if (opt.UseConnectionLogging) |
| | 30 | 815 | | { |
| | 0 | 816 | | _ = listenOptions.UseConnectionLogging(); |
| | 30 | 817 | | } |
| | 60 | 818 | | }); |
| | | 819 | | } |
| | 56 | 820 | | } |
| | | 821 | | |
| | | 822 | | /// <summary> |
| | | 823 | | /// Logs the configured endpoints after building the application. |
| | | 824 | | /// </summary> |
| | | 825 | | internal void LogConfiguredEndpoints() |
| | | 826 | | { |
| | | 827 | | // build the app to validate configuration |
| | 55 | 828 | | _app = Build(); |
| | | 829 | | // Log configured endpoints |
| | 55 | 830 | | var dataSource = _app.Services.GetRequiredService<EndpointDataSource>(); |
| | | 831 | | |
| | 55 | 832 | | if (dataSource.Endpoints.Count == 0) |
| | | 833 | | { |
| | 55 | 834 | | Logger.Warning("EndpointDataSource is empty. No endpoints configured."); |
| | | 835 | | } |
| | | 836 | | else |
| | | 837 | | { |
| | 0 | 838 | | foreach (var ep in dataSource.Endpoints) |
| | | 839 | | { |
| | 0 | 840 | | Logger.Information("➡️ Endpoint: {DisplayName}", ep.DisplayName); |
| | | 841 | | } |
| | | 842 | | } |
| | 0 | 843 | | } |
| | | 844 | | |
| | | 845 | | /// <summary> |
| | | 846 | | /// Handles configuration errors and wraps them with meaningful messages. |
| | | 847 | | /// </summary> |
| | | 848 | | /// <param name="ex">The exception that occurred during configuration.</param> |
| | | 849 | | /// <exception cref="InvalidOperationException">Always thrown with wrapped exception.</exception> |
| | | 850 | | internal void HandleConfigurationError(Exception ex) |
| | | 851 | | { |
| | 1 | 852 | | Logger.Error(ex, "Error applying configuration: {Message}", ex.Message); |
| | 1 | 853 | | throw new InvalidOperationException("Failed to apply configuration.", ex); |
| | | 854 | | } |
| | | 855 | | |
| | | 856 | | /// <summary> |
| | | 857 | | /// Applies the configured options to the Kestrel server and initializes the runspace pool. |
| | | 858 | | /// </summary> |
| | | 859 | | public void EnableConfiguration(Dictionary<string, object>? userVariables = null, Dictionary<string, string>? userFu |
| | | 860 | | { |
| | 71 | 861 | | if (!ValidateConfiguration()) |
| | | 862 | | { |
| | 17 | 863 | | return; |
| | | 864 | | } |
| | | 865 | | |
| | | 866 | | try |
| | | 867 | | { |
| | 54 | 868 | | InitializeRunspacePool(userVariables, userFunctions); |
| | 54 | 869 | | ConfigureKestrelBase(); |
| | 54 | 870 | | ConfigureNamedPipes(); |
| | | 871 | | |
| | | 872 | | // Apply Kestrel listeners and HTTPS settings |
| | 54 | 873 | | _ = Builder.WebHost.ConfigureKestrel(serverOptions => |
| | 54 | 874 | | { |
| | 54 | 875 | | ConfigureHttpsAdapter(serverOptions); |
| | 54 | 876 | | BindListeners(serverOptions); |
| | 108 | 877 | | }); |
| | | 878 | | |
| | 54 | 879 | | LogConfiguredEndpoints(); |
| | | 880 | | |
| | | 881 | | // Register default probes after endpoints are logged but before marking configured |
| | 54 | 882 | | RegisterDefaultHealthProbes(); |
| | 54 | 883 | | IsConfigured = true; |
| | 54 | 884 | | Logger.Information("Configuration applied successfully."); |
| | 54 | 885 | | } |
| | 0 | 886 | | catch (Exception ex) |
| | | 887 | | { |
| | 0 | 888 | | HandleConfigurationError(ex); |
| | 0 | 889 | | } |
| | 54 | 890 | | } |
| | | 891 | | |
| | | 892 | | /// <summary> |
| | | 893 | | /// Registers built-in default health probes (idempotent). Currently includes disk space probe. |
| | | 894 | | /// </summary> |
| | | 895 | | private void RegisterDefaultHealthProbes() |
| | | 896 | | { |
| | | 897 | | try |
| | 54 | 898 | | { |
| | | 899 | | // Avoid duplicate registration if user already added a probe named "disk". |
| | | 900 | | lock (_healthProbeLock) |
| | | 901 | | { |
| | 54 | 902 | | if (HealthProbes.Any(p => string.Equals(p.Name, "disk", StringComparison.OrdinalIgnoreCase))) |
| | | 903 | | { |
| | 0 | 904 | | return; // already present |
| | | 905 | | } |
| | 54 | 906 | | } |
| | | 907 | | |
| | 54 | 908 | | var tags = new[] { IProbe.TAG_SELF }; // neutral tag; user can filter by name if needed |
| | 54 | 909 | | var diskProbe = new DiskSpaceProbe("disk", tags); |
| | 54 | 910 | | RegisterProbeInternal(diskProbe); |
| | 54 | 911 | | } |
| | 0 | 912 | | catch (Exception ex) |
| | | 913 | | { |
| | 0 | 914 | | Logger.Warning(ex, "Failed to register default disk space probe."); |
| | 0 | 915 | | } |
| | 54 | 916 | | } |
| | | 917 | | |
| | | 918 | | #endregion |
| | | 919 | | #region Builder |
| | | 920 | | /* More information about the KestrunHost class |
| | | 921 | | https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.webapplication?view=aspnetcore-8.0 |
| | | 922 | | |
| | | 923 | | */ |
| | | 924 | | |
| | | 925 | | /// <summary> |
| | | 926 | | /// Builds the WebApplication. |
| | | 927 | | /// This method applies all queued services and middleware stages, |
| | | 928 | | /// and returns the built WebApplication instance. |
| | | 929 | | /// </summary> |
| | | 930 | | /// <returns>The built WebApplication.</returns> |
| | | 931 | | /// <exception cref="InvalidOperationException"></exception> |
| | | 932 | | public WebApplication Build() |
| | | 933 | | { |
| | 80 | 934 | | ValidateBuilderState(); |
| | 80 | 935 | | ApplyQueuedServices(); |
| | 80 | 936 | | BuildWebApplication(); |
| | 80 | 937 | | ConfigureBuiltInMiddleware(); |
| | 80 | 938 | | LogApplicationInfo(); |
| | 80 | 939 | | ApplyQueuedMiddleware(); |
| | 80 | 940 | | ApplyFeatures(); |
| | | 941 | | |
| | 80 | 942 | | return _app!; |
| | | 943 | | } |
| | | 944 | | |
| | | 945 | | /// <summary> |
| | | 946 | | /// Validates that the builder is properly initialized before building. |
| | | 947 | | /// </summary> |
| | | 948 | | /// <exception cref="InvalidOperationException">Thrown when the builder is not initialized.</exception> |
| | | 949 | | private void ValidateBuilderState() |
| | | 950 | | { |
| | 80 | 951 | | if (Builder == null) |
| | | 952 | | { |
| | 0 | 953 | | throw new InvalidOperationException("Call CreateBuilder() first."); |
| | | 954 | | } |
| | 80 | 955 | | } |
| | | 956 | | |
| | | 957 | | /// <summary> |
| | | 958 | | /// Applies all queued service configurations to the service collection. |
| | | 959 | | /// </summary> |
| | | 960 | | private void ApplyQueuedServices() |
| | | 961 | | { |
| | 250 | 962 | | foreach (var configure in _serviceQueue) |
| | | 963 | | { |
| | 45 | 964 | | configure(Builder.Services); |
| | | 965 | | } |
| | 80 | 966 | | } |
| | | 967 | | |
| | | 968 | | /// <summary> |
| | | 969 | | /// Builds the WebApplication instance from the configured builder. |
| | | 970 | | /// </summary> |
| | | 971 | | private void BuildWebApplication() |
| | | 972 | | { |
| | 80 | 973 | | _app = Builder.Build(); |
| | 80 | 974 | | Logger.Information("Application built successfully."); |
| | 80 | 975 | | } |
| | | 976 | | |
| | | 977 | | /// <summary> |
| | | 978 | | /// Configures built-in middleware components in the correct order. |
| | | 979 | | /// </summary> |
| | | 980 | | private void ConfigureBuiltInMiddleware() |
| | | 981 | | { |
| | 80 | 982 | | ConfigureExceptionHandling(); |
| | 80 | 983 | | ConfigureForwardedHeaders(); |
| | 80 | 984 | | ConfigureStatusCodePages(); |
| | 80 | 985 | | ConfigurePowerShellRuntime(); |
| | 80 | 986 | | } |
| | | 987 | | |
| | | 988 | | /// <summary> |
| | | 989 | | /// Configures exception handling middleware if enabled. |
| | | 990 | | /// </summary> |
| | | 991 | | private void ConfigureExceptionHandling() |
| | | 992 | | { |
| | 80 | 993 | | if (ExceptionOptions is not null) |
| | | 994 | | { |
| | 5 | 995 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 996 | | { |
| | 0 | 997 | | Logger.Debug("Exception handling middleware is enabled."); |
| | | 998 | | } |
| | 5 | 999 | | _ = ExceptionOptions.DeveloperExceptionPageOptions is not null |
| | 5 | 1000 | | ? _app!.UseDeveloperExceptionPage(ExceptionOptions.DeveloperExceptionPageOptions) |
| | 5 | 1001 | | : _app!.UseExceptionHandler(ExceptionOptions); |
| | | 1002 | | } |
| | 76 | 1003 | | } |
| | | 1004 | | |
| | | 1005 | | /// <summary> |
| | | 1006 | | /// Configures forwarded headers middleware if enabled. |
| | | 1007 | | /// </summary> |
| | | 1008 | | private void ConfigureForwardedHeaders() |
| | | 1009 | | { |
| | 80 | 1010 | | if (ForwardedHeaderOptions is not null) |
| | | 1011 | | { |
| | 3 | 1012 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1013 | | { |
| | 0 | 1014 | | Logger.Debug("Forwarded headers middleware is enabled."); |
| | | 1015 | | } |
| | 3 | 1016 | | _ = _app!.UseForwardedHeaders(ForwardedHeaderOptions); |
| | | 1017 | | } |
| | 80 | 1018 | | } |
| | | 1019 | | |
| | | 1020 | | /// <summary> |
| | | 1021 | | /// Configures status code pages middleware if enabled. |
| | | 1022 | | /// </summary> |
| | | 1023 | | private void ConfigureStatusCodePages() |
| | | 1024 | | { |
| | | 1025 | | // Register StatusCodePages BEFORE language runtimes so that re-executed requests |
| | | 1026 | | // pass through language middleware again (and get fresh RouteValues/context). |
| | 80 | 1027 | | if (StatusCodeOptions is not null) |
| | | 1028 | | { |
| | 0 | 1029 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1030 | | { |
| | 0 | 1031 | | Logger.Debug("Status code pages middleware is enabled."); |
| | | 1032 | | } |
| | 0 | 1033 | | _ = _app!.UseStatusCodePages(StatusCodeOptions); |
| | | 1034 | | } |
| | 80 | 1035 | | } |
| | | 1036 | | |
| | | 1037 | | /// <summary> |
| | | 1038 | | /// Configures PowerShell runtime middleware if enabled. |
| | | 1039 | | /// </summary> |
| | | 1040 | | /// <exception cref="InvalidOperationException">Thrown when PowerShell is enabled but runspace pool is not initializ |
| | | 1041 | | private void ConfigurePowerShellRuntime() |
| | | 1042 | | { |
| | 80 | 1043 | | if (PowershellMiddlewareEnabled) |
| | | 1044 | | { |
| | 0 | 1045 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1046 | | { |
| | 0 | 1047 | | Logger.Debug("PowerShell middleware is enabled."); |
| | | 1048 | | } |
| | | 1049 | | |
| | 0 | 1050 | | if (_runspacePool is null) |
| | | 1051 | | { |
| | 0 | 1052 | | throw new InvalidOperationException("Runspace pool is not initialized. Call EnableConfiguration first.") |
| | | 1053 | | } |
| | 0 | 1054 | | Logger.Information("Adding PowerShell runtime"); |
| | 0 | 1055 | | _ = _app!.UseLanguageRuntime( |
| | 0 | 1056 | | ScriptLanguage.PowerShell, |
| | 0 | 1057 | | b => b.UsePowerShellRunspace(_runspacePool)); |
| | | 1058 | | } |
| | 80 | 1059 | | } |
| | | 1060 | | |
| | | 1061 | | /// <summary> |
| | | 1062 | | /// Logs application information including working directory and Pages directory contents. |
| | | 1063 | | /// </summary> |
| | | 1064 | | private void LogApplicationInfo() |
| | | 1065 | | { |
| | 80 | 1066 | | Logger.Information("CWD: {CWD}", Directory.GetCurrentDirectory()); |
| | 80 | 1067 | | Logger.Information("ContentRoot: {Root}", _app!.Environment.ContentRootPath); |
| | 80 | 1068 | | LogPagesDirectory(); |
| | 80 | 1069 | | } |
| | | 1070 | | |
| | | 1071 | | /// <summary> |
| | | 1072 | | /// Logs information about the Pages directory and its contents. |
| | | 1073 | | /// </summary> |
| | | 1074 | | private void LogPagesDirectory() |
| | | 1075 | | { |
| | 80 | 1076 | | var pagesDir = Path.Combine(_app!.Environment.ContentRootPath, "Pages"); |
| | 80 | 1077 | | Logger.Information("Pages Dir: {PagesDir}", pagesDir); |
| | | 1078 | | |
| | 80 | 1079 | | if (Directory.Exists(pagesDir)) |
| | | 1080 | | { |
| | 0 | 1081 | | foreach (var file in Directory.GetFiles(pagesDir, "*.*", SearchOption.AllDirectories)) |
| | | 1082 | | { |
| | 0 | 1083 | | Logger.Information("Pages file: {File}", file); |
| | | 1084 | | } |
| | | 1085 | | } |
| | | 1086 | | else |
| | | 1087 | | { |
| | 80 | 1088 | | Logger.Warning("Pages directory does not exist: {PagesDir}", pagesDir); |
| | | 1089 | | } |
| | 80 | 1090 | | } |
| | | 1091 | | |
| | | 1092 | | /// <summary> |
| | | 1093 | | /// Applies all queued middleware stages to the application pipeline. |
| | | 1094 | | /// </summary> |
| | | 1095 | | private void ApplyQueuedMiddleware() |
| | | 1096 | | { |
| | 240 | 1097 | | foreach (var stage in _middlewareQueue) |
| | | 1098 | | { |
| | 40 | 1099 | | stage(_app!); |
| | | 1100 | | } |
| | 80 | 1101 | | } |
| | | 1102 | | |
| | | 1103 | | /// <summary> |
| | | 1104 | | /// Applies all queued features to the host. |
| | | 1105 | | /// </summary> |
| | | 1106 | | private void ApplyFeatures() |
| | | 1107 | | { |
| | 164 | 1108 | | foreach (var feature in FeatureQueue) |
| | | 1109 | | { |
| | 2 | 1110 | | feature(this); |
| | | 1111 | | } |
| | 80 | 1112 | | } |
| | | 1113 | | |
| | | 1114 | | /// <summary> |
| | | 1115 | | /// Returns true if the specified service type has already been registered in the IServiceCollection. |
| | | 1116 | | /// </summary> |
| | | 1117 | | public bool IsServiceRegistered(Type serviceType) |
| | 777 | 1118 | | => Builder?.Services?.Any(sd => sd.ServiceType == serviceType) ?? false; |
| | | 1119 | | |
| | | 1120 | | /// <summary> |
| | | 1121 | | /// Generic convenience overload. |
| | | 1122 | | /// </summary> |
| | 0 | 1123 | | public bool IsServiceRegistered<TService>() => IsServiceRegistered(typeof(TService)); |
| | | 1124 | | |
| | | 1125 | | /// <summary> |
| | | 1126 | | /// Adds a service configuration action to the service queue. |
| | | 1127 | | /// This action will be executed when the services are built. |
| | | 1128 | | /// </summary> |
| | | 1129 | | /// <param name="configure">The service configuration action.</param> |
| | | 1130 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 1131 | | public KestrunHost AddService(Action<IServiceCollection> configure) |
| | | 1132 | | { |
| | 81 | 1133 | | _serviceQueue.Add(configure); |
| | 81 | 1134 | | return this; |
| | | 1135 | | } |
| | | 1136 | | |
| | | 1137 | | /// <summary> |
| | | 1138 | | /// Adds a middleware stage to the application pipeline. |
| | | 1139 | | /// </summary> |
| | | 1140 | | /// <param name="stage">The middleware stage to add.</param> |
| | | 1141 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 1142 | | public KestrunHost Use(Action<IApplicationBuilder> stage) |
| | | 1143 | | { |
| | 87 | 1144 | | _middlewareQueue.Add(stage); |
| | 87 | 1145 | | return this; |
| | | 1146 | | } |
| | | 1147 | | |
| | | 1148 | | /// <summary> |
| | | 1149 | | /// Adds a feature configuration action to the feature queue. |
| | | 1150 | | /// This action will be executed when the features are applied. |
| | | 1151 | | /// </summary> |
| | | 1152 | | /// <param name="feature">The feature configuration action.</param> |
| | | 1153 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 1154 | | public KestrunHost AddFeature(Action<KestrunHost> feature) |
| | | 1155 | | { |
| | 2 | 1156 | | FeatureQueue.Add(feature); |
| | 2 | 1157 | | return this; |
| | | 1158 | | } |
| | | 1159 | | |
| | | 1160 | | /// <summary> |
| | | 1161 | | /// Adds a scheduling feature to the Kestrun host, optionally specifying the maximum number of runspaces for the sch |
| | | 1162 | | /// </summary> |
| | | 1163 | | /// <param name="MaxRunspaces">The maximum number of runspaces for the scheduler. If null, uses the default value.</ |
| | | 1164 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 1165 | | public KestrunHost AddScheduling(int? MaxRunspaces = null) |
| | | 1166 | | { |
| | 4 | 1167 | | return MaxRunspaces is not null and <= 0 |
| | 4 | 1168 | | ? throw new ArgumentOutOfRangeException(nameof(MaxRunspaces), "MaxRunspaces must be greater than zero.") |
| | 4 | 1169 | | : AddFeature(host => |
| | 4 | 1170 | | { |
| | 2 | 1171 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | 4 | 1172 | | { |
| | 2 | 1173 | | Logger.Debug("AddScheduling (deferred)"); |
| | 4 | 1174 | | } |
| | 4 | 1175 | | |
| | 2 | 1176 | | if (host.Scheduler is null) |
| | 4 | 1177 | | { |
| | 1 | 1178 | | if (MaxRunspaces is not null and > 0) |
| | 4 | 1179 | | { |
| | 1 | 1180 | | Logger.Information("Setting MaxSchedulerRunspaces to {MaxRunspaces}", MaxRunspaces); |
| | 1 | 1181 | | host.Options.MaxSchedulerRunspaces = MaxRunspaces.Value; |
| | 4 | 1182 | | } |
| | 1 | 1183 | | Logger.Verbose("Creating SchedulerService with MaxSchedulerRunspaces={MaxRunspaces}", |
| | 1 | 1184 | | host.Options.MaxSchedulerRunspaces); |
| | 1 | 1185 | | var pool = host.CreateRunspacePool(host.Options.MaxSchedulerRunspaces); |
| | 1 | 1186 | | var logger = Logger.ForContext<KestrunHost>(); |
| | 1 | 1187 | | host.Scheduler = new SchedulerService(pool, logger); |
| | 4 | 1188 | | } |
| | 4 | 1189 | | else |
| | 4 | 1190 | | { |
| | 1 | 1191 | | Logger.Warning("SchedulerService already configured; skipping."); |
| | 4 | 1192 | | } |
| | 5 | 1193 | | }); |
| | | 1194 | | } |
| | | 1195 | | |
| | | 1196 | | /// <summary> |
| | | 1197 | | /// Adds the Tasks feature to run ad-hoc scripts with status/result/cancellation. |
| | | 1198 | | /// </summary> |
| | | 1199 | | /// <param name="MaxRunspaces">Optional max runspaces for the task PowerShell pool; when null uses scheduler default |
| | | 1200 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 1201 | | public KestrunHost AddTasks(int? MaxRunspaces = null) |
| | | 1202 | | { |
| | 0 | 1203 | | return MaxRunspaces is not null and <= 0 |
| | 0 | 1204 | | ? throw new ArgumentOutOfRangeException(nameof(MaxRunspaces), "MaxRunspaces must be greater than zero.") |
| | 0 | 1205 | | : AddFeature(host => |
| | 0 | 1206 | | { |
| | 0 | 1207 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | 0 | 1208 | | { |
| | 0 | 1209 | | Logger.Debug("AddTasks (deferred)"); |
| | 0 | 1210 | | } |
| | 0 | 1211 | | |
| | 0 | 1212 | | if (host.Tasks is null) |
| | 0 | 1213 | | { |
| | 0 | 1214 | | // Reuse scheduler pool sizing unless explicitly overridden |
| | 0 | 1215 | | if (MaxRunspaces is not null and > 0) |
| | 0 | 1216 | | { |
| | 0 | 1217 | | Logger.Information("Setting MaxTaskRunspaces to {MaxRunspaces}", MaxRunspaces); |
| | 0 | 1218 | | } |
| | 0 | 1219 | | var pool = host.CreateRunspacePool(MaxRunspaces ?? host.Options.MaxSchedulerRunspaces); |
| | 0 | 1220 | | var logger = Logger.ForContext<KestrunHost>(); |
| | 0 | 1221 | | host.Tasks = new KestrunTaskService(pool, logger); |
| | 0 | 1222 | | } |
| | 0 | 1223 | | else |
| | 0 | 1224 | | { |
| | 0 | 1225 | | Logger.Warning("KestrunTaskService already configured; skipping."); |
| | 0 | 1226 | | } |
| | 0 | 1227 | | }); |
| | | 1228 | | } |
| | | 1229 | | |
| | | 1230 | | /// <summary> |
| | | 1231 | | /// Adds MVC / API controllers to the application. |
| | | 1232 | | /// </summary> |
| | | 1233 | | /// <param name="cfg">The configuration options for MVC / API controllers.</param> |
| | | 1234 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 1235 | | public KestrunHost AddControllers(Action<Microsoft.AspNetCore.Mvc.MvcOptions>? cfg = null) |
| | | 1236 | | { |
| | 0 | 1237 | | return AddService(services => |
| | 0 | 1238 | | { |
| | 0 | 1239 | | var builder = services.AddControllers(); |
| | 0 | 1240 | | if (cfg != null) |
| | 0 | 1241 | | { |
| | 0 | 1242 | | _ = builder.ConfigureApplicationPartManager(pm => { }); // customise if you wish |
| | 0 | 1243 | | } |
| | 0 | 1244 | | }); |
| | | 1245 | | } |
| | | 1246 | | |
| | | 1247 | | |
| | | 1248 | | |
| | | 1249 | | |
| | | 1250 | | /// <summary> |
| | | 1251 | | /// Adds a PowerShell runtime to the application. |
| | | 1252 | | /// This middleware allows you to execute PowerShell scripts in response to HTTP requests. |
| | | 1253 | | /// </summary> |
| | | 1254 | | /// <param name="routePrefix">The route prefix to use for the PowerShell runtime.</param> |
| | | 1255 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 1256 | | public KestrunHost AddPowerShellRuntime(PathString? routePrefix = null) |
| | | 1257 | | { |
| | 1 | 1258 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1259 | | { |
| | 1 | 1260 | | Logger.Debug("Adding PowerShell runtime with route prefix: {RoutePrefix}", routePrefix); |
| | | 1261 | | } |
| | | 1262 | | |
| | 1 | 1263 | | return Use(app => |
| | 1 | 1264 | | { |
| | 1 | 1265 | | ArgumentNullException.ThrowIfNull(_runspacePool); |
| | 1 | 1266 | | // ── mount PowerShell at the root ── |
| | 1 | 1267 | | _ = app.UseLanguageRuntime( |
| | 1 | 1268 | | ScriptLanguage.PowerShell, |
| | 2 | 1269 | | b => b.UsePowerShellRunspace(_runspacePool)); |
| | 2 | 1270 | | }); |
| | | 1271 | | } |
| | | 1272 | | |
| | | 1273 | | /// <summary> |
| | | 1274 | | /// Adds a SignalR hub to the application at the specified path. |
| | | 1275 | | /// </summary> |
| | | 1276 | | /// <typeparam name="T">The type of the SignalR hub.</typeparam> |
| | | 1277 | | /// <param name="path">The path at which to map the SignalR hub.</param> |
| | | 1278 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 1279 | | public KestrunHost AddSignalR<T>(string path) where T : Hub |
| | | 1280 | | { |
| | 0 | 1281 | | return AddService(s => |
| | 0 | 1282 | | { |
| | 0 | 1283 | | _ = s.AddSignalR().AddJsonProtocol(opts => |
| | 0 | 1284 | | { |
| | 0 | 1285 | | // Avoid failures when payloads contain cycles; our sanitizer should prevent most, this is a safety net. |
| | 0 | 1286 | | opts.PayloadSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreC |
| | 0 | 1287 | | }); |
| | 0 | 1288 | | // Register IRealtimeBroadcaster as singleton if it's the KestrunHub |
| | 0 | 1289 | | if (typeof(T) == typeof(SignalR.KestrunHub)) |
| | 0 | 1290 | | { |
| | 0 | 1291 | | _ = s.AddSingleton<SignalR.IRealtimeBroadcaster, SignalR.RealtimeBroadcaster>(); |
| | 0 | 1292 | | _ = s.AddSingleton<SignalR.IConnectionTracker, SignalR.InMemoryConnectionTracker>(); |
| | 0 | 1293 | | } |
| | 0 | 1294 | | }) |
| | 0 | 1295 | | .Use(app => ((IEndpointRouteBuilder)app).MapHub<T>(path)); |
| | | 1296 | | } |
| | | 1297 | | |
| | | 1298 | | /// <summary> |
| | | 1299 | | /// Adds the default SignalR hub (KestrunHub) to the application at the specified path. |
| | | 1300 | | /// </summary> |
| | | 1301 | | /// <param name="path">The path at which to map the SignalR hub.</param> |
| | | 1302 | | /// <returns></returns> |
| | 0 | 1303 | | public KestrunHost AddSignalR(string path) => AddSignalR<SignalR.KestrunHub>(path); |
| | | 1304 | | |
| | | 1305 | | /* |
| | | 1306 | | // ④ gRPC |
| | | 1307 | | public KestrunHost AddGrpc<TService>() where TService : class |
| | | 1308 | | { |
| | | 1309 | | return AddService(s => s.AddGrpc()) |
| | | 1310 | | .Use(app => app.MapGrpcService<TService>()); |
| | | 1311 | | } |
| | | 1312 | | */ |
| | | 1313 | | |
| | | 1314 | | /* public KestrunHost AddSwagger() |
| | | 1315 | | { |
| | | 1316 | | AddService(s => |
| | | 1317 | | { |
| | | 1318 | | s.AddEndpointsApiExplorer(); |
| | | 1319 | | s.AddSwaggerGen(); |
| | | 1320 | | }); |
| | | 1321 | | // ⚠️ Swagger’s middleware normally goes first in the pipeline |
| | | 1322 | | return Use(app => |
| | | 1323 | | { |
| | | 1324 | | app.UseSwagger(); |
| | | 1325 | | app.UseSwaggerUI(); |
| | | 1326 | | }); |
| | | 1327 | | }*/ |
| | | 1328 | | |
| | | 1329 | | // Add as many tiny helpers as you wish: |
| | | 1330 | | // • AddAuthentication(jwt => { … }) |
| | | 1331 | | // • AddSignalR() |
| | | 1332 | | // • AddHealthChecks() |
| | | 1333 | | // • AddGrpc() |
| | | 1334 | | // etc. |
| | | 1335 | | |
| | | 1336 | | #endregion |
| | | 1337 | | #region Run/Start/Stop |
| | | 1338 | | |
| | | 1339 | | /// <summary> |
| | | 1340 | | /// Runs the Kestrun web application, applying configuration and starting the server. |
| | | 1341 | | /// </summary> |
| | | 1342 | | public void Run() |
| | | 1343 | | { |
| | 0 | 1344 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1345 | | { |
| | 0 | 1346 | | Logger.Debug("Run() called"); |
| | | 1347 | | } |
| | | 1348 | | |
| | 0 | 1349 | | EnableConfiguration(); |
| | 0 | 1350 | | StartTime = DateTime.UtcNow; |
| | 0 | 1351 | | _app?.Run(); |
| | 0 | 1352 | | } |
| | | 1353 | | |
| | | 1354 | | /// <summary> |
| | | 1355 | | /// Starts the Kestrun web application asynchronously. |
| | | 1356 | | /// </summary> |
| | | 1357 | | /// <param name="cancellationToken">A cancellation token to observe while waiting for the task to complete.</param> |
| | | 1358 | | /// <returns>A task that represents the asynchronous start operation.</returns> |
| | | 1359 | | public async Task StartAsync(CancellationToken cancellationToken = default) |
| | | 1360 | | { |
| | 17 | 1361 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1362 | | { |
| | 1 | 1363 | | Logger.Debug("StartAsync() called"); |
| | | 1364 | | } |
| | | 1365 | | |
| | 17 | 1366 | | EnableConfiguration(); |
| | 17 | 1367 | | if (_app != null) |
| | | 1368 | | { |
| | 17 | 1369 | | StartTime = DateTime.UtcNow; |
| | 17 | 1370 | | await _app.StartAsync(cancellationToken); |
| | | 1371 | | } |
| | 17 | 1372 | | } |
| | | 1373 | | |
| | | 1374 | | /// <summary> |
| | | 1375 | | /// Stops the Kestrun web application asynchronously. |
| | | 1376 | | /// </summary> |
| | | 1377 | | /// <param name="cancellationToken">A cancellation token to observe while waiting for the task to complete.</param> |
| | | 1378 | | /// <returns>A task that represents the asynchronous stop operation.</returns> |
| | | 1379 | | public async Task StopAsync(CancellationToken cancellationToken = default) |
| | | 1380 | | { |
| | 22 | 1381 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1382 | | { |
| | 6 | 1383 | | Logger.Debug("StopAsync() called"); |
| | | 1384 | | } |
| | | 1385 | | |
| | 22 | 1386 | | if (_app != null) |
| | | 1387 | | { |
| | | 1388 | | try |
| | | 1389 | | { |
| | | 1390 | | // Initiate graceful shutdown |
| | 17 | 1391 | | await _app.StopAsync(cancellationToken); |
| | 17 | 1392 | | StopTime = DateTime.UtcNow; |
| | 17 | 1393 | | } |
| | 0 | 1394 | | catch (Exception ex) when (ex.GetType().FullName == "System.Net.Quic.QuicException") |
| | | 1395 | | { |
| | | 1396 | | // QUIC exceptions can occur during shutdown, especially if the server is not using QUIC. |
| | | 1397 | | // We log this as a debug message to avoid cluttering the logs with expected exceptions. |
| | | 1398 | | // This is a workaround for |
| | | 1399 | | |
| | 0 | 1400 | | Logger.Debug("Ignored QUIC exception during shutdown: {Message}", ex.Message); |
| | 0 | 1401 | | } |
| | | 1402 | | } |
| | 22 | 1403 | | } |
| | | 1404 | | |
| | | 1405 | | /// <summary> |
| | | 1406 | | /// Initiates a graceful shutdown of the Kestrun web application. |
| | | 1407 | | /// </summary> |
| | | 1408 | | public void Stop() |
| | | 1409 | | { |
| | 1 | 1410 | | if (Interlocked.Exchange(ref _stopping, 1) == 1) |
| | | 1411 | | { |
| | 0 | 1412 | | return; // already stopping |
| | | 1413 | | } |
| | 1 | 1414 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1415 | | { |
| | 1 | 1416 | | Logger.Debug("Stop() called"); |
| | | 1417 | | } |
| | | 1418 | | // This initiates a graceful shutdown. |
| | 1 | 1419 | | _app?.Lifetime.StopApplication(); |
| | 1 | 1420 | | StopTime = DateTime.UtcNow; |
| | 1 | 1421 | | } |
| | | 1422 | | |
| | | 1423 | | /// <summary> |
| | | 1424 | | /// Determines whether the Kestrun web application is currently running. |
| | | 1425 | | /// </summary> |
| | | 1426 | | /// <returns>True if the application is running; otherwise, false.</returns> |
| | | 1427 | | public bool IsRunning |
| | | 1428 | | { |
| | | 1429 | | get |
| | | 1430 | | { |
| | 8 | 1431 | | var appField = typeof(KestrunHost) |
| | 8 | 1432 | | .GetField("_app", BindingFlags.NonPublic | BindingFlags.Instance); |
| | | 1433 | | |
| | 8 | 1434 | | return appField?.GetValue(this) is WebApplication app && !app.Lifetime.ApplicationStopping.IsCancellationReq |
| | | 1435 | | } |
| | | 1436 | | } |
| | | 1437 | | |
| | | 1438 | | #endregion |
| | | 1439 | | |
| | | 1440 | | |
| | | 1441 | | |
| | | 1442 | | #region Runspace Pool Management |
| | | 1443 | | |
| | | 1444 | | /// <summary> |
| | | 1445 | | /// Creates and returns a new <see cref="KestrunRunspacePoolManager"/> instance with the specified maximum number of |
| | | 1446 | | /// </summary> |
| | | 1447 | | /// <param name="maxRunspaces">The maximum number of runspaces to create. If not specified or zero, defaults to twic |
| | | 1448 | | /// <param name="userVariables">A dictionary of user-defined variables to inject into the runspace pool.</param> |
| | | 1449 | | /// <param name="userFunctions">A dictionary of user-defined functions to inject into the runspace pool.</param> |
| | | 1450 | | /// <returns>A configured <see cref="KestrunRunspacePoolManager"/> instance.</returns> |
| | | 1451 | | public KestrunRunspacePoolManager CreateRunspacePool(int? maxRunspaces = 0, Dictionary<string, object>? userVariable |
| | | 1452 | | { |
| | 58 | 1453 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1454 | | { |
| | 41 | 1455 | | Logger.Debug("CreateRunspacePool() called: {@MaxRunspaces}", maxRunspaces); |
| | | 1456 | | } |
| | | 1457 | | |
| | | 1458 | | // Create a default InitialSessionState with an unrestricted policy: |
| | 58 | 1459 | | var iss = InitialSessionState.CreateDefault(); |
| | | 1460 | | |
| | 58 | 1461 | | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
| | | 1462 | | { |
| | | 1463 | | // On Windows, we can use the full .NET Framework modules |
| | 0 | 1464 | | iss.ExecutionPolicy = ExecutionPolicy.Unrestricted; |
| | | 1465 | | } |
| | 232 | 1466 | | foreach (var p in _modulePaths) |
| | | 1467 | | { |
| | 58 | 1468 | | iss.ImportPSModule([p]); |
| | | 1469 | | } |
| | | 1470 | | |
| | | 1471 | | // Inject 'KrServer' variable to provide access to the host instance |
| | 58 | 1472 | | iss.Variables.Add( |
| | 58 | 1473 | | new SessionStateVariableEntry( |
| | 58 | 1474 | | "KrServer", |
| | 58 | 1475 | | this, |
| | 58 | 1476 | | "The Kestrun Server Host (KestrunHost) instance" |
| | 58 | 1477 | | ) |
| | 58 | 1478 | | ); |
| | | 1479 | | // Inject global variables into all runspaces |
| | 636 | 1480 | | foreach (var kvp in SharedStateStore.Snapshot()) |
| | | 1481 | | { |
| | | 1482 | | // kvp.Key = "Visits", kvp.Value = 0 |
| | 260 | 1483 | | iss.Variables.Add( |
| | 260 | 1484 | | new SessionStateVariableEntry( |
| | 260 | 1485 | | kvp.Key, |
| | 260 | 1486 | | kvp.Value, |
| | 260 | 1487 | | "Global variable" |
| | 260 | 1488 | | ) |
| | 260 | 1489 | | ); |
| | | 1490 | | } |
| | | 1491 | | |
| | 120 | 1492 | | foreach (var kvp in userVariables ?? []) |
| | | 1493 | | { |
| | 2 | 1494 | | if (kvp.Value is PSVariable psVar) |
| | | 1495 | | { |
| | 0 | 1496 | | iss.Variables.Add( |
| | 0 | 1497 | | new SessionStateVariableEntry( |
| | 0 | 1498 | | kvp.Key, |
| | 0 | 1499 | | psVar.Value, |
| | 0 | 1500 | | psVar.Description ?? "User-defined variable" |
| | 0 | 1501 | | ) |
| | 0 | 1502 | | ); |
| | | 1503 | | } |
| | | 1504 | | else |
| | | 1505 | | { |
| | 2 | 1506 | | iss.Variables.Add( |
| | 2 | 1507 | | new SessionStateVariableEntry( |
| | 2 | 1508 | | kvp.Key, |
| | 2 | 1509 | | kvp.Value, |
| | 2 | 1510 | | "User-defined variable" |
| | 2 | 1511 | | ) |
| | 2 | 1512 | | ); |
| | | 1513 | | } |
| | | 1514 | | } |
| | | 1515 | | |
| | 120 | 1516 | | foreach (var r in userFunctions ?? []) |
| | | 1517 | | { |
| | 2 | 1518 | | var name = r.Key; |
| | 2 | 1519 | | var def = r.Value; |
| | | 1520 | | |
| | | 1521 | | // Use the string-based ctor available in 7.4 ref/net8.0 |
| | 2 | 1522 | | var entry = new SessionStateFunctionEntry( |
| | 2 | 1523 | | name, |
| | 2 | 1524 | | def, |
| | 2 | 1525 | | ScopedItemOptions.ReadOnly, // or ScopedItemOptions.None if you want them mutable |
| | 2 | 1526 | | helpFile: null |
| | 2 | 1527 | | ); |
| | | 1528 | | |
| | 2 | 1529 | | iss.Commands.Add(entry); |
| | | 1530 | | } |
| | | 1531 | | |
| | | 1532 | | // Determine max runspaces |
| | 58 | 1533 | | var maxRs = (maxRunspaces.HasValue && maxRunspaces.Value > 0) ? maxRunspaces.Value : Environment.ProcessorCount |
| | | 1534 | | |
| | 58 | 1535 | | Logger.Information($"Creating runspace pool with max runspaces: {maxRs}"); |
| | 58 | 1536 | | var runspacePool = new KestrunRunspacePoolManager(this, Options?.MinRunspaces ?? 1, maxRunspaces: maxRs, initial |
| | | 1537 | | // Return the created runspace pool |
| | 58 | 1538 | | return runspacePool; |
| | | 1539 | | } |
| | | 1540 | | |
| | | 1541 | | |
| | | 1542 | | #endregion |
| | | 1543 | | |
| | | 1544 | | |
| | | 1545 | | #region Disposable |
| | | 1546 | | |
| | | 1547 | | /// <summary> |
| | | 1548 | | /// Releases all resources used by the <see cref="KestrunHost"/> instance. |
| | | 1549 | | /// </summary> |
| | | 1550 | | public void Dispose() |
| | | 1551 | | { |
| | 80 | 1552 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1553 | | { |
| | 60 | 1554 | | Logger.Debug("Dispose() called"); |
| | | 1555 | | } |
| | | 1556 | | |
| | 80 | 1557 | | _runspacePool?.Dispose(); |
| | 80 | 1558 | | _runspacePool = null; // Clear the runspace pool reference |
| | 80 | 1559 | | IsConfigured = false; // Reset configuration state |
| | 80 | 1560 | | _app = null; |
| | 80 | 1561 | | Scheduler?.Dispose(); |
| | 80 | 1562 | | (Logger as IDisposable)?.Dispose(); |
| | 80 | 1563 | | GC.SuppressFinalize(this); |
| | 80 | 1564 | | } |
| | | 1565 | | #endregion |
| | | 1566 | | |
| | | 1567 | | #region Script Validation |
| | | 1568 | | |
| | | 1569 | | |
| | | 1570 | | #endregion |
| | | 1571 | | } |