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